欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JGit 工具包、克隆、拉取、添加、提交、强制推送

最编程 2024-03-09 20:32:58
...
package net.xmeter.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.jmeter.util.JMeterUtils;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author :xifan
 * @date :Created in 2021/6/4 下午2:00
 * @description:git util
 */


public class GitUtil {
    private  String localPath, localGitPath, remotePath;
    private  Repository localRepository;
    private  String username,password;
    private  Git git;
    private  static GitUtil gitUtil;
    protected static Locale currentLocale = JMeterUtils.getLocale();

    private GitUtil(){

    }

    private GitUtil gitInit(String localPathStr, String remotePathStr,String usernameStr ,String passwordStr) throws IOException {
        username = usernameStr;
        password = passwordStr;
        localPath = localPathStr;
        remotePath = remotePathStr;
        localGitPath = localPath + "/.git";
        localRepository = new FileRepository(localGitPath);
        System.out.println("init git repository successfully~");
        return gitUtil;
    }
    public Git getGit() throws Exception {
        if(git==null) {
            if(isCompleteClone()) {
                git = Git.open(new File(localPath));
            }else {
                throw new Exception(I18NUtil.getMessage(currentLocale, "err.git_repository_not_existed"));
            }
        }
        return git;
    }

    /**
     * create local repository
     *
     * @throws IOException
     */
    public void create() throws IOException {
        Repository repository = new FileRepository(localGitPath);
        if(!repository.getDirectory().exists()){
            repository.create();
            System.out.println("create repository success");
        }
    }

    /**
     * Clone the remote branch to the local repository
     *
     * @param branchName
     * @throws GitAPIException
     */
    private  void cloneBranch(String branchName) throws GitAPIException {
        Git.cloneRepository()
                .setURI(remotePath)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username,password))
                .setBranch(branchName)
                .setDirectory(new File(localPath))
                .call();
        System.out.println("clone success for branch"+branchName);
    }

    public boolean isCompleteClone(){
        return new File(localGitPath).exists();
    }

    /**
     * pull remote code
     *
     * @param branchName Remote branch name
     * @throws Exception
     */
    private void pull(String branchName) throws Exception {
        getGit().pull().setRemote("origin")
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username,password))
                .setRemoteBranchName(branchName).call();
        System.out.println("pull success");
    }

    /**
     *Submit to remote warehouse
     * @param files
     * @param message
     * @return
     * @throws Exception
     */
    public  void commitToGitRepository(List<String> files,String message) throws Exception {
        if(null ==files &&files.size()<1){
            throw new Exception(I18NUtil.getMessage(currentLocale, "git.file_not_modified"));
        }
        showStatus();
        List<DiffEntry> diffEntries=getGit().diff().setPathFilter(PathFilterGroup.createFromStrings(files))
                .setShowNameAndStatusOnly(true).call();
        if (diffEntries == null || diffEntries.size() == 0) {
            throw new Exception(I18NUtil.getMessage(currentLocale, "git.file_not_modified"));
        }
        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;
            }
        }
        AddCommand addCmd = getGit().add();
        for (String file : updateFiles) {
            addCmd.addFilepattern(file);
        }
        addCmd.call();
        CommitCommand commitCmd = getGit().commit();
        for (String file : updateFiles) {
            commitCmd.setOnly(file);
        }
        RevCommit revCommit = commitCmd
                .setMessage(message).call();
        System.out.println("commit success");
        push();
        showStatus();
    }

    public void showStatus() throws Exception {
        System.out.println("============show current git status========");
        Status status = getGit().status().call();
        //返回的值都是相对工作区的路径,而不是绝对路径
        status.getAdded().forEach(it -> System.out.println("Add File :" + it));
        status.getRemoved().forEach(it -> System.out.println("Remove File :" + it));
        status.getModified().forEach(it -> System.out.println("Modified File :" + it));
        status.getUntracked().forEach(it -> System.out.println("Untracked File :" + it));
        status.getConflicting().forEach(it -> System.out.println("Conflicting File :" + it));
        status.getMissing().forEach(it -> System.out.println("Missing File :" + it));
        System.out.println("=============================================");
    }

    /**
     * Synchronize remote repository, push violently
     *
     * @throws Exception
     */
    public void push() throws Exception {
//        .setForce(true)
        getGit().push().setForce(true).setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).call();
        System.out.println("push success");
    }

    public static GitUtil getInstance() throws IOException {
//参数自定义填写git配置项  本地文件路径(空文件夹),仓库url,账户,密码
        return getInstance("git.localGitPath","git.url","git.username","git.password");
    }
    private static GitUtil getInstance(String localGitPath, String remotePath,String username,String password) throws IOException {
        if(gitUtil==null){
            gitUtil =new GitUtil();
            gitUtil.gitInit(localGitPath,remotePath,username,password);
     }
        return gitUtil;
    }

    public void pull() throws Exception {
//自定义分支
        pull("git.branch");
    }

    public void cloneBranch() throws Exception {
//自定义分支
        cloneBranch("git.branch");
    }

    public String getRelativeLocationForGitPath(String targetPath) throws Exception {
        String sourcePath=localPath;
        if(targetPath.indexOf(sourcePath)>=0) {
            return targetPath.replace(sourcePath+"/", "");
        }else {
            throw new Exception(I18NUtil.getMessage(currentLocale, "git.error.file_not_in_repository"));
        }
    }
    public List<String>  getRelativeLocationForGitPath(List<String> targetPaths) throws Exception {
        List<String> paths=new ArrayList<>();
        for(String path:targetPaths){
            paths.add(getRelativeLocationForGitPath(path));
        }
        System.out.println("RelativeLocations:"+JSONObject.toJSONString(paths));
        return paths;
    }



        public static void main(String[] args) throws IOException {
            GitUtil gitUtil = GitUtil.getInstance();
            String fileName = "HTTP请求.jmx";
//            File file=new File("/Users/workspace/idea/testgit1/nft-jbz-code/17xtest1.jmx");
            List<String> filePaths=new ArrayList<>();
            filePaths.add("17test1.jmx");
            filePaths.add("HTTP Request2.jmx");
            try {
//                gitUtil.commitToGitRepository(filePaths,"test 2021-6-25 第3次");
                gitUtil.pull("master");
            } catch (Exception exception) {
                exception.printStackTrace();
                System.out.println("error:"+exception.getMessage());
            }

        }
}