JGit 切換分支


JGit切換分支的時候,有兩種情況,一種是在本地已修建過這個分支,一種是本地沒有這個分支,需要從遠程拉取。如下面代碼所示:

 /**
     * 
     * <p>
     * Description:判斷本地分支名是否存在
     * </p>
     * 
     * @param git
     * @param branchName
     * @return
     * @throws GitAPIException
     * @author wgs
     * @date 2019年7月20日 下午2:49:46
     *
     */
    public boolean branchNameExist(Git git, String branchName) throws GitAPIException {
        List<Ref> refs = git.branchList().call();
        for (Ref ref : refs) {
            if (ref.getName().contains(branchName)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 
     * <p>Description:切換分支,並拉取到最新 </p>
     * @param repoDir
     * @param branchName
     * @author wgs 
     * @date  2019年7月20日 下午4:11:45
     *
     */
    public void checkoutAndPull(String repoDir, String branchName) {
        try {
            Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(repoDir)).build();
            Git git = new Git(existingRepo);
            try {
                if (this.branchNameExist(git, branchName)) {//如果分支在本地已存在,直接checkout即可。
                    git.checkout().setCreateBranch(false).setName(branchName).call();
                } else {//如果分支在本地不存在,需要創建這個分支,並追蹤到遠程分支上面。
                    git.checkout().setCreateBranch(true).setName(branchName).setStartPoint("origin/" + branchName).call();
                }
                git.pull().call();//拉取最新的提交
            } finally {
                git.close();
            }
        } catch (IOException | GitAPIException e) {
            e.printStackTrace();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM