• 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检出代码,切换分支,切换版本。

    *简洁可运行版本*

    import java.io.File;
    import java.util.List;
    
    import org.eclipse.jgit.api.Git;
    import org.eclipse.jgit.api.ListBranchCommand;
    import org.eclipse.jgit.api.errors.GitAPIException;
    import org.eclipse.jgit.lib.Ref;
    import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
    
    
    
    public class GitFromXLY {
    
        public static void main(String[] args) {
            String baseUrl = "http://git/url";
            String module = args[0];
            String user = "username";
            String pass = "password";
            String branch = args[1];
            String revision = args[2];
            
            GitFromXLY gfxly = new GitFromXLY(module, user, pass, branch, revision);
            
            int getPullCode = gfxly.pull(baseUrl + module);
            if (getPullCode == 0) {
                System.out.println("检出代码成功===0");
            } else if (getPullCode == 1) {
                System.exit(1);
            } else if (getPullCode == 2) {
                System.exit(2);
            } else if (getPullCode == 3) {
                System.exit(3);
            } else if (getPullCode == 4) {
                System.exit(4);
            } else {
                System.out.println("检出代码未知异常===5");
                System.exit(5);
            }
            int getBranchCode = gfxly.checkoutBranch();
            if (getBranchCode == 0) {
                System.out.println("检出分支成功===0");
            } else if (getPullCode == 6) {
                System.exit(6);
            } else {
                System.out.println("检出分支未知异常===7");
                System.exit(7);
            }
            int getRevisionCode = gfxly.checkoutRevision();
            if (getRevisionCode == 0) {
                System.out.println("检出版本成功===0");
            } else if (getPullCode == 8) {
                System.exit(8);
            } else {
                System.out.println("检出版本未知异常===9");
                System.exit(9);
            }
        }
        
        private String module;
        private String user;
        private String pass;
        private String branch;
        private String revision;
        private String git_config;
        
        public GitFromXLY(String module, String user, String pass, String branch, String revision){
            this.module = module;
            this.user = user;
            this.pass = pass;
            this.branch = branch;
            this.revision = revision;
            this.git_config = "./basedir/" + module + "/.git";
        }
        
        /**
         * 通过url拉取代码 
         * @param gitUrl
         * @return
         */
        public int pull(String gitUrl){
            String pullMsg = "";
            // 标记拉取代码的标志
            int pullFlag = 0;
            // 提供用户名和密码的验证
            UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(
                    this.user, this.pass);
            // 指定要加载的代码路径
            File dir = new File("./basedir/" + this.module);
            // 判断代码路径下是否有内容,如果有就删除
            if(dir.exists()){
                deleteFolder(dir);
            }
            
            Git git = null;
            try {
                git = Git.cloneRepository().setURI(gitUrl)
                        .setDirectory(dir).setCredentialsProvider(provider).call();
                pullMsg = "检出代码成功 success";
            } catch (org.eclipse.jgit.api.errors.TransportException e){
                e.printStackTrace();
                pullMsg = "用户名NAME或密码PASSWORD错误或远程链接URL错误 failed";
                pullFlag = 1;
            } catch (org.eclipse.jgit.api.errors.JGitInternalException e) {
                e.printStackTrace();
                pullMsg = "已经存在了项目的下载目录,并且目录正在被操作 failed";
                pullFlag = 2;
            } catch (GitAPIException e) {
                e.printStackTrace();
                pullMsg = "调用GitAPI异常,failed";
                pullFlag = 3;
            } catch (NoClassDefFoundError e) {
                e.printStackTrace();
                pullMsg = "未找到相应的类文件异常,failed";
                pullFlag = 4;
            } finally {
                System.out.println(pullMsg +"--code--"+ pullFlag);
                if (git != null) {
                    git.close();
                }
            }
            
            return pullFlag;
        }
        /**
         * 检出分支
         * @param branchName
         * @return
         */
        public int checkoutBranch(){
            String checkoutMsg = "";
            int checkoutFlag = 0;
    
            if (this.branch.equals("master")) {
                checkoutMsg = "Check out code OK. ->" + this.branch;
                System.out.println(checkoutMsg +"--code--"+ checkoutFlag);
                return checkoutFlag;
            }
            Git git = null;
            try {
                git = Git.open( new File(this.git_config) );
                //列出所有的分支名称
                List<Ref> branchList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
                for (Ref ref : branchList){
                    if (this.branch.equals(ref.getName())) {
                        System.out.println("代码分支列表中存在给定分支");
                    }
                }
                git.checkout().setName("origin/" + this.branch).setForce(true).call();
                checkoutMsg = "检出分支代码 success! code OK ->" + this.branch;
            } catch (Exception e) {
                e.printStackTrace();
                checkoutMsg = "检出分支代码 failed ! ->" + this.branch;
                checkoutFlag = 6;
            } finally {
                System.out.println(checkoutMsg +"--code--"+ checkoutFlag);
                if (git != null) {
                    git.close();
                }
            }
            
            return checkoutFlag;
        }
        /**
         * 检出代码
         * @param revision
         * @return
         */
        public int checkoutRevision(){
            String checkoutMsg = "";
            int checkoutFlag = 0;
            if (this.revision == null || this.revision.length() == 0) {
                checkoutMsg = "Check out code OK. ->" + this.revision;
                System.out.println(checkoutMsg +"--code--"+ checkoutFlag);
                return checkoutFlag;
            }
            Git git = null;
            try {
                git = Git.open( new File(this.git_config) );
                git.checkout().setName( this.revision ).setForce(true).call();
                checkoutMsg = "检出代码版本 success! code OK. ->" + this.revision;
            } catch (Exception e) {
                e.printStackTrace();
                checkoutMsg = "检出代码版本 failed ! ->" + this.revision;
                checkoutFlag = 8;
            } finally {
                System.out.println(checkoutMsg +"--code--"+ checkoutFlag);
                if (git != null) {
                    git.close();
                }
            }
            return checkoutFlag;
        }
        /**
         * 删除目录
         * @param file
         */
        private 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();
            }
        }
    
    }

     依赖包如下:

     

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

  • 相关阅读:
    BZOJ 1452 Count(二维树状数组)
    BZOJ 1407 Savage(拓展欧几里得)
    BZOJ 1415 聪聪和可可(期望DP)
    BZOJ 1406 密码箱(数论)
    最大流小结
    UVA6531Go up the ultras
    二分图小结
    Codeforces Round #243 (Div. 1)
    图论模板集合
    zoj3416 Balanced Number
  • 原文地址:https://www.cnblogs.com/wozijisun/p/10396660.html
Copyright © 2020-2023  润新知