当前位置: 首页 > 工具软件 > SVNKit > 使用案例 >

SVNKit - Subversion for java

毛博
2023-12-01

一、什么是SVNKit 

             Subversion是一个领先且快速增长的开源版本控制系统。SVNKit让Subversion更接近Java世界!SVNKit是一个纯Java工具包 - 它实现了所有Subversion功能,并提供了API来处理Subversion工作副本,访问和操作Subversion存储库 - Java应用程序中的所有内容。官网:https://svnkit.com/

二、工具类

     pom.xml中添加以下依赖

        <dependency>
            <groupId>org.tmatesoft.svnkit</groupId>
            <artifactId>svnkit</artifactId>
            <version>1.9.3</version>
        </dependency>

   工具类代码如下:

import org.jboss.logging.Logger;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.*;

import java.io.File;
import java.util.*;

/**
 * Author:xyl
 * Date:2019/3/19 9:17
 * Description:SVN工具类
 */
public class SVNUtil {
    private static Logger logger = Logger.getLogger(SVNUtil.class);
    private static final String SVN_URL = "svn://192.168.30.132/";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "123123";

    /**
     * 通过不同的协议初始化版本库
     */
    private static void setupLibrary() {
        DAVRepositoryFactory.setup();
        SVNRepositoryFactoryImpl.setup();
    }

    /**
     * 获取客户端
     *
     * @return svn客户端
     */
    public static SVNClientManager authSvn() {
        // 初始化版本库
        setupLibrary();
        // 创建库连接
        SVNRepository repository;
        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(SVN_URL));
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
            return null;
        }
        // 身份验证
        ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(USER_NAME, PASSWORD.toCharArray());
        // 创建身份验证管理器
        repository.setAuthenticationManager(authManager);
        DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(true);
        return SVNClientManager.newInstance(options, authManager);
    }

    /**
     * 创建文件夹
     *
     * @param commitMessage 提交信息
     * @param url           svn路径
     */
    public static SVNCommitInfo makeDirectory(String url, String commitMessage) {
        try {
            return authSvn().getCommitClient().doMkDir(new SVNURL[]{SVNURL.parseURIEncoded(url)}, commitMessage);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return null;
    }

    /**
     * 导入文件夹
     *
     * @param localPath     本地路径
     * @param dstURL        目标地址
     * @param commitMessage 提交信息
     * @param isRecursive   是否包含子目录
     */
    public static SVNCommitInfo importDirectory(String localPath, String dstURL, String commitMessage, boolean isRecursive) {
        try {
            return authSvn().getCommitClient().doImport(new File(localPath), SVNURL.parseURIEncoded(dstURL), commitMessage, null, true, true, SVNDepth.fromRecurse(isRecursive));
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return null;
    }

    /**
     * 添加入口
     */
    public static void addEntry(String wcPath) {
        try {
            authSvn().getWCClient().doAdd(new File[]{new File(wcPath)}, true, false, false, SVNDepth.INFINITY, false, false, true);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
    }

    /**
     * 显示状态
     */
    public static SVNStatus showStatus(File wcPath, boolean remote) {
        SVNStatus status = null;
        try {
            status = authSvn().getStatusClient().doStatus(wcPath, remote);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return status;
    }

    /**
     * 提交
     *
     * @param keepLocks     是否保持锁定
     * @param wcPath        本地文件路径
     * @param commitMessage 提交信息
     */
    public static SVNCommitInfo commit(String wcPath, boolean keepLocks, String commitMessage) {
        try {
            return authSvn().getCommitClient().doCommit(new File[]{new File(wcPath)}, keepLocks, commitMessage, null, null, false, false, SVNDepth.INFINITY);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return null;
    }

    /**
     * 更新
     *
     * @param wcPath           本地文件路径
     * @param updateToRevision 版本
     * @param depth            更新方式
     */
    public static long update(String wcPath, SVNRevision updateToRevision, SVNDepth depth) {
        SVNUpdateClient updateClient = Objects.requireNonNull(authSvn()).getUpdateClient();
        updateClient.setIgnoreExternals(false);
        try {
            return updateClient.doUpdate(new File(wcPath), updateToRevision, depth, false, false);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return 0;
    }

    /**
     * 从SVN导出项目到本地
     *
     * @param url      SVN的url
     * @param revision 版本
     * @param destPath 目标路径
     */
    public static long checkout(SVNURL url, SVNRevision revision, File destPath, SVNDepth depth) {
        SVNUpdateClient updateClient = authSvn().getUpdateClient();
        updateClient.setIgnoreExternals(false);
        try {
            return updateClient.doCheckout(url, destPath, revision, revision, depth, false);
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return 0;
    }

    /**
     * 确定path是否是一个工作空间
     */
    public static boolean isWorkingCopy(File path) {
        if (!path.exists()) {
            logger.warn("'" + path + "' not exist!");
            return false;
        }
        try {
            if (null == SVNWCUtil.getWorkingCopyRoot(path, false)) {
                return false;
            }
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return true;
    }

    /**
     * 确定一个URL在SVN上是否存在
     */
    public static boolean isURLExist(String url) {
        try {
            SVNRepository svnRepository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
            ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(USER_NAME, PASSWORD.toCharArray());
            svnRepository.setAuthenticationManager(authManager);
            //遍历SVN,获取结点。
            SVNNodeKind nodeKind = svnRepository.checkPath("", -1);
            return nodeKind != SVNNodeKind.NONE;
        } catch (SVNException e) {
            logger.error(e.getErrorMessage(), e);
        }
        return false;
    }

    /**
     * 获取提交日志
     *
     * @param url 路径
     */
    public static void getLog(String url) throws SVNException {
        setupLibrary();
        SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
        ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(USER_NAME, PASSWORD.toCharArray());
        repository.setAuthenticationManager(authManager);
        long startRevision = 0;
        //表示最后一个版本
        long endRevision = -1;
        Collection logEntries = repository.log(new String[]{""}, null, startRevision, endRevision, true, true);
        for (Iterator entries = logEntries.iterator(); entries.hasNext(); ) {
            SVNLogEntry logEntry = (SVNLogEntry) entries.next();
            logger.info("---------------------------------------------");
            logger.info("revision: " + logEntry.getRevision());
            logger.info("author: " + logEntry.getAuthor());
            logger.info("date: " + logEntry.getDate());
            logger.info("log message: " + logEntry.getMessage());
            if (logEntry.getChangedPaths().size() > 0) {
                logger.info("\n");
                logger.info("changed paths:");
                Set changedPathsSet = logEntry.getChangedPaths().keySet();
                for (Iterator changedPaths = changedPathsSet.iterator(); changedPaths.hasNext(); ) {
                    SVNLogEntryPath entryPath = logEntry.getChangedPaths().get(changedPaths.next());
                    logger.info(" "
                            + entryPath.getType()
                            + " "
                            + entryPath.getPath()
                            + ((entryPath.getCopyPath() != null) ? " (from "
                            + entryPath.getCopyPath() + " revision "
                            + entryPath.getCopyRevision() + ")" : ""));
                }
            }
        }
    }
}

注:为图方便,本文中svn的用户名和密码直接写死了,在实际开发中可根据具体情况配置。

 类似资料:

相关阅读

相关文章

相关问答