java操作git简单实现

Posted wozijisun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java操作git简单实现相关的知识,希望对你有一定的参考价值。

     记录瞬间

 

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Git操作工具类
 */
public class JGitUtil {
    private static String MODULE_NAME;
    private static String BRANCH_NAME;
    private static String GIT_USERNAME;
    private static String GIT_PASSWORD;
    private static String CHECK_BRANCH;
    private static String REVISION;
    private static String LOCAL_REPOGIT_CONFIG;

    final static Logger LOG = LoggerFactory.getLogger(JGitUtil.class);

    public JGitUtil(GitInfo gitInfo){
        String[] gitPath = gitInfo.getGitUrl().split("/");
        this.MODULE_NAME = "/" + gitPath[gitPath.length - 3] + "/" + gitPath[gitPath.length - 2]
                + "/" + gitPath[gitPath.length - 1];
        this.BRANCH_NAME = gitInfo.getGitUrl();
        this.GIT_PASSWORD = gitInfo.getGitPass();
        this.GIT_USERNAME = gitInfo.getGitName();
        this.CHECK_BRANCH = gitInfo.getGitBranch();
        this.REVISION = gitInfo.getNewVersion();
        this.LOCAL_REPOGIT_CONFIG = "./" + this.GIT_USERNAME + "/" + this.MODULE_NAME + "/.git";
    }
    /**
     * 拉取远程代码
     *
     * @return 远程分支名
     */
    public static boolean pull() {
        return pull(BRANCH_NAME);
    }

    public static boolean pull(String remoteBranchName) {

        boolean pullFlag = true;
        UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(
                GIT_USERNAME, GIT_PASSWORD);
        LOG.info(BRANCH_NAME);
        String getCodeDir = BRANCH_NAME.split("/git/")[1];
        File dir = new File("./" + GIT_USERNAME + "/" + getCodeDir);
        if(dir.exists()){
            deleteFolder(dir);
        }

        try {
            @SuppressWarnings("unused")
            Git git = Git.cloneRepository().setURI(remoteBranchName)
                    .setDirectory(dir).setCredentialsProvider(provider).call();
            List<Ref> call = git.branchList().call();
            Repository repository = git.getRepository();
            for (Ref ref : call) {
                List<Integer> counts = getCounts(repository, ref.getName());
                System.out.println("For branch: " + ref.getName());
                System.out.println("Commits ahead : " + counts.get(0));
                System.out.println("Commits behind : " + counts.get(1));
                System.out.println();
            }
        } catch (org.eclipse.jgit.api.errors.TransportException e){
            e.printStackTrace();
            pullFlag = false;
        } catch (Exception e) {
            e.printStackTrace();
            pullFlag = false;
        }
        return pullFlag;
    }

    private static List<Integer> getCounts(Repository repository, String branchName) throws IOException {
        BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName);
        List<Integer> counts = new ArrayList<>();
        if (trackingStatus != null) {
            counts.add(trackingStatus.getAheadCount());
            counts.add(trackingStatus.getBehindCount());
        } else {
            System.out.println("Returned null, likely no remote tracking of branch " + branchName);
            counts.add(0);
            counts.add(0);
        }
        return counts;
    }
    
    private static void deleteFolder(File file){
        try {
            if (file.isFile() || file.list().length==0) {
                file.delete();
            } else {
                File[] files = file.listFiles();
                for (File getFile: files) {
                    deleteFolder(getFile);
                    getFile.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检出代码
     * @param branchName
     * @return
     */
    public static boolean checkoutBranch(String branchName){
        boolean checkoutFlag=true;

        if (branchName.equals("master")) {
            return checkoutFlag;
        }

        try ( Git git = Git.open( new File(LOCAL_REPOGIT_CONFIG) );) {
            git.checkout().setName("origin/" + branchName).setForce(true).call();
            //列出所有的分支名称
            List<Ref> ll = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
            for (Ref ref : ll){
                System.out.println(ref.getName());
            }
            System.out.println("检出分支代码 success! ->" + branchName);
        } catch (Exception e) {
            e.printStackTrace();
            checkoutFlag = false;
            System.out.println("检出分支代码 failed ! ->" + branchName);

        }
        return checkoutFlag;
    }
    /**
     * 检出代码
     * @param revision
     * @return
     */
    public static boolean checkoutRevision(String revision){
        boolean checkoutFlag=true;
        if (revision == null || revision.length() == 0) {
            return checkoutFlag;
        }
        try ( Git git = Git.open( new File(LOCAL_REPOGIT_CONFIG) );) {
            git.checkout().setName( revision ).setForce(true).call();
            System.out.println("检出代码版本 success! ->" + revision);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("检出代码版本 failed ! ->" + revision);
            checkoutFlag = false;
        }
        return checkoutFlag;
    }
}

 

代码主要记录了,操作git检出代码,切换分支,切换版本。

 

===========================================

 


以上是关于java操作git简单实现的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段15——git命令操作一个完整流程

java操作git简单实现

巧用vscode编辑器 ,利用vscode可视化git跟踪git历史记录,简单实现git日常操作

巧用vscode编辑器 ,利用vscode可视化git跟踪git历史记录,简单实现git日常操作

巧用vscode编辑器 ,利用vscode可视化git跟踪git历史记录,简单实现git日常操作

巧用vscode编辑器 ,利用vscode可视化git跟踪git历史记录,简单实现git日常操作