收集整理了网上的一些jgit操作代码,自己尝试了一下写了一些常用的jgit操作代码

package com.romanenco.gitt;
import java.io.File;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.storage.file.FileRepository;
import org.eclipse.jgit.api.CheckoutCommand;
import org.eclipse.jgit.api.PullCommand;
import java.util.List;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import java.util.ArrayList;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
//ResetCommand.ResetType;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.lib.ObjectId;
import java.io.IOException;
import org.eclipse.jgit.lib.Constants;
import java.util.Iterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.diff.RenameDetector;
import org.eclipse.jgit.util.StringUtils;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.PushResult;

public class GitUtil
{
    /*
    获取git的状态
    */
    public static String gitShowStatus(File repoDir) {
        File RepoGitDir = new File(repoDir.getAbsolutePath() + "/.git");
        StringBuffer logger = new StringBuffer();
        if (!RepoGitDir.exists()) {
            logger.append("Error! Not Exists : " + RepoGitDir.getAbsolutePath());
        } else {
            Repository repo = null;
            try {
                repo = new FileRepository(RepoGitDir.getAbsolutePath());
                Git    git    = new Git(repo);
                Status status = git.status().call();
                logger.append("Git Change: " + status.getChanged());
                logger.append("Git Modified: " + status.getModified());
                //logger.append("Git UncommittedChanges: " + status.getUntracked() /* status.getUncommittedChanges()*/);
                logger.append("Git Untracked: " + status.getUntracked());
            } catch (Exception e) {
                logger.append(e.getMessage() + " : " + repoDir.getAbsolutePath());
            } finally {
                if (repo != null) {
                    repo.close();
                }
            }
        }
        return logger.toString();
    }

    //获取git待提交的文件列表
    public static List<String> getStatusList(File repoDir){
    ArrayList<String> list_file = new ArrayList<String>();

File RepoGitDir = new File(repoDir.getAbsolutePath() + "/.git");
        StringBuffer logger = new StringBuffer();
        if (!RepoGitDir.exists()) {
            logger.append("Error! Not Exists : " + RepoGitDir.getAbsolutePath());
        } else {
            Repository repo = null;
            try {
                repo = new FileRepository(RepoGitDir.getAbsolutePath());
                Git    git    = new Git(repo);
                Status status = git.status().call();
                logger.append("Git Change: " + status.getChanged());
                list_file.addAll(status.getChanged());

                logger.append("Git Modified: " + status.getModified());
                list_file.addAll(status.getModified());
                //logger.append("Git UncommittedChanges: " + status.getUntracked() /* status.getUncommittedChanges()*/);
                logger.append("Git Untracked: " + status.getUntracked());
                list_file.addAll(status.getUntracked());
            } catch (Exception e) {
                logger.append(e.getMessage() + " : " + repoDir.getAbsolutePath());
            } finally {
                if (repo != null) {
                    repo.close();
                }
            }
        }
        //return logger.toString();
        return list_file;
    }

    public static String gitClone(String remoteUrl, File repoDir) {
        StringBuffer logger = new StringBuffer();
        try {
            Git git = Git.cloneRepository()
                .setURI(remoteUrl)
                .setDirectory(repoDir)
                .call();

            logger.append("Cloning from " + remoteUrl + " to " + git.getRepository());
        } catch (Exception e) {
            logger.append(e.getMessage());
        }
        return logger.toString();
    }

    public static String gitCheckout(File repoDir, String version) {
        File RepoGitDir = new File(repoDir.getAbsolutePath() + "/.git");
        StringBuffer logger = new StringBuffer();
        if (!RepoGitDir.exists()) {
            logger.append("Error! Not Exists : " + RepoGitDir.getAbsolutePath());
        } else {
            Repository repo = null;
            try {
                repo = new FileRepository(RepoGitDir.getAbsolutePath());
                Git git = new Git(repo);
                CheckoutCommand checkout = git.checkout();
                checkout.setName(version);
                checkout.call();
                logger.append("Checkout to " + version);

                PullCommand pullCmd = git.pull();
                pullCmd.call();

                logger.append("Pulled from remote repository to local repository at " + repo.getDirectory());
            } catch (Exception e) {
                logger.append(e.getMessage() + " : " + RepoGitDir.getAbsolutePath());
            } finally {
                if (repo != null) {
                    repo.close();
                }
            }
        }
        return logger.toString();
    }

    public static  String gitPull(File repoDir) {
        File RepoGitDir = new File(repoDir.getAbsolutePath() + "/.git");
        StringBuffer logger = new StringBuffer();
        if (!RepoGitDir.exists()) {
            logger.append("Error! Not Exists : " + RepoGitDir.getAbsolutePath());
        } else {
            Repository repo = null;
            try {
                repo = new FileRepository(RepoGitDir.getAbsolutePath());
                Git git = new Git(repo);
                PullCommand pullCmd = git.pull();
                pullCmd.call();

                logger.append("Pulled from remote repository to local repository at " + repo.getDirectory());
            } catch (Exception e) {
                logger.append(e.getMessage() + " : " + RepoGitDir.getAbsolutePath());
            } finally {
                if (repo != null) {
                    repo.close();
                }
            }
        }
        return logger.toString();
    }

        private final static String GIT = ".git";

        /**
         * 将文件列表提交到git仓库中
         * @param gitRoot git仓库目录
         * @param files 需要提交的文件列表
         * @return 返回本次提交的版本号
         * @throws IOException 
         */
        public static String commitToGitRepository(String gitRoot, List<String> files,String message) throws Exception {
            if ((!StringUtils.isEmptyOrNull(gitRoot)) && files != null && files.size() > 0) {

                File rootDir = new File(gitRoot);

                //初始化git仓库
                if (new File(gitRoot + File.separator + GIT).exists() == false) {
                    Git.init().setDirectory(rootDir).call();
                }

                //打开git仓库
                Git git = Git.open(rootDir);
                //判断是否有被修改过的文件
                List<DiffEntry> diffEntries = git.diff()
                    .setPathFilter(PathFilterGroup.createFromStrings(files))
                    .setShowNameAndStatusOnly(true).call();
                if (diffEntries == null || diffEntries.size() == 0) {
                    throw new Exception("提交的文件内容都没有被修改,不能提交");
                }
                //被修改过的文件
                List<String> updateFiles=new ArrayList<String>();
                DiffEntry.ChangeType changeType;
                for(DiffEntry entry : diffEntries){
                    changeType = entry.getChangeType();
                    switch (changeType) {
                        case ADD:
                            updateFiles.add(entry.getNewPath());
                            break;
                        case COPY:
                            updateFiles.add(entry.getNewPath());
                            break;
                        case DELETE:
                            updateFiles.add(entry.getOldPath());
                            break;
                        case MODIFY:
                            updateFiles.add(entry.getOldPath());
                            break;
                        case RENAME:
                            updateFiles.add(entry.getNewPath());
                            break;
                    }
                }
                //将文件提交到git仓库中,并返回本次提交的版本号
                AddCommand addCmd = git.add();
                for (String file : updateFiles) {
                    addCmd.addFilepattern(file);
                }
                addCmd.call();

                CommitCommand commitCmd = git.commit();
                for (String file : updateFiles) {
                    commitCmd.setOnly(file);
                }
                RevCommit revCommit = commitCmd//.setCommitter(name,email)
                    .setMessage(message).call();
                return revCommit.getName();
            }
            return null;
        }

        /**
         * 将git仓库内容回滚到指定版本的上一个版本
         * @param gitRoot 仓库目录
         * @param revision 指定的版本号
         * @return true,回滚成功,否则flase
         * @throws IOException
         */
        public static boolean rollBackPreRevision(String gitRoot, String revision) throws IOException, GitAPIException {

            Git git = Git.open(new File(gitRoot));

            Repository repository = git.getRepository();

            RevWalk walk = new RevWalk(repository);
            ObjectId objId = repository.resolve(revision);
            RevCommit revCommit = walk.parseCommit(objId);
            String preVision = revCommit.getParent(0).getName();
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef(preVision).call();
            repository.close();
            return true;
        }

        /**
         * 查询本次提交的日志
         * @param gitRoot git仓库
         * @param revision  版本号
         * @return 
         * @throws Exception
         */
        public static List<DiffEntry> getLog(String gitRoot, String revision) throws Exception {
            Git git = Git.open(new File(gitRoot));
            Repository repository = git.getRepository();

            ObjectId objId = repository.resolve(revision);
            Iterable<RevCommit> allCommitsLater = git.log().add(objId).call();
            Iterator<RevCommit> iter = allCommitsLater.iterator();
            RevCommit commit = iter.next();
            TreeWalk tw = new TreeWalk(repository);
            tw.addTree(commit.getTree());

            commit = iter.next();
            if (commit != null)
                tw.addTree(commit.getTree());
            else
                return null;

            tw.setRecursive(true);
            RenameDetector rd = new RenameDetector(repository);
            rd.addAll(DiffEntry.scan(tw));

            return rd.compute();
        }

    /**
     * 同步远程仓库
     *
     * @throws Exception
     */
    public static String push(String gitRoot,String username,String password) throws Exception {
        StringBuffer logger=new StringBuffer();
        Git git = Git.open(new File(gitRoot));
        //git.fetch();
        Iterable<PushResult> result = git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).call();
        //logger.append("push success");
        //result.iterator()
        for(PushResult re:result){
            logger.append(re.getMessages()+"\n");
        }
        return logger.toString();
    }

    /**
     * 同步远程仓库
     *
     * @throws Exception
     */
    public String fetch(String gitRoot,String username,String password) throws Exception {
        StringBuffer logger=new StringBuffer();
        Git git = Git.open(new File(gitRoot));
         FetchCommand fetchcommand =  git.fetch();
        FetchResult result =fetchcommand.call();
        return result.toString();
        //git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).call();
        //logger.append("push success");
    }

}

发表评论

邮箱地址不会被公开。 必填项已用*标注