当前位置 : 主页 > 编程语言 > c++ >

java通过shell/cmd执行git命令来完成打tag、merge代码等git操作

来源:互联网 收集:自由互联 发布时间:2021-06-30
执行git的fetch命令 Process process = Runtime.getRuntime().exec(new String[]{ "git", "fetch", "--all" }, new String[]{}, file); int code = process.waitFor(); if (code != 0) { StringBuilder stringBuilder = new StringBuilder().append("\ng
执行git的fetch命令
Process process = Runtime.getRuntime().exec(new String[]{
                            "git", "fetch", "--all"
                    }, new String[]{}, file);

                    int code = process.waitFor();
                    if (code != 0) {
                        StringBuilder stringBuilder = new StringBuilder().append("\ngit fetch fail: path=").append(file.getAbsolutePath())
                                .append(",command=git fetch -all\n");
                        Scanner scanner = new Scanner(process.getErrorStream(), SHELL_CHARSET);
                        while (scanner.hasNextLine()) {
                            stringBuilder.append(scanner.nextLine()).append("\n");
                        }
                        logger.error(stringBuilder.toString());
                        logger.error(String.format("git fetch fail: %s", file.getAbsolutePath()));
                    }
构造命令字符串
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
    private static final String GIT_CMD = "git";
    private static final String SHELL_CHARSET;
    static {
        if (IS_WINDOWS) {
            SHELL_CHARSET = "GBK";
        } else {
            String lang = System.getenv("LANG");
            if (StringUtils.isNotBlank(lang)) {
                if (lang.contains(".")) {
                    SHELL_CHARSET = lang.substring(lang.indexOf(".") + 1);
                } else {
                    SHELL_CHARSET = lang;
                }
            } else {
                SHELL_CHARSET = System.getProperty("file.encoding", "UTF-8");
            }
        }
    }

    private String buildCommand(String[] cmdArray) {
        StringBuilder builder = new StringBuilder();
        if (IS_WINDOWS) {
            builder.append("cmd /c \"");
        }
        for (int i = 0; i < cmdArray.length; i++) {
            if (i != 0) {
                builder.append(" && ");
            }
            builder.append(cmdArray[i]);
        }
        if (IS_WINDOWS) {
            builder.append(" \"");
        }
        return builder.toString();
    }
执行git的merge(将tag merge到branch)
String command = buildCommand(new String[] {
                    String.format("%s checkout %s", GIT_CMD, branchName),
                    String.format("%s pull", GIT_CMD),
                    String.format("%s merge -s recursive -X theirs %s", GIT_CMD, tagName),
                    String.format("%s push origin %s -q", GIT_CMD, branchName)
            });
            long time = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(command, null, dir);

            int code = process.waitFor();
            if (code != 0) {
                StringBuilder stringBuilder = new StringBuilder().append("\ngit merge fail: gitPath=").append(gitPath)
                        .append(",dir=").append(dir.getAbsolutePath())
                        .append(",command=").append(command).append("\n");
                Scanner scanner = new Scanner(process.getErrorStream(), SHELL_CHARSET);
                while (scanner.hasNextLine()) {
                    stringBuilder.append(scanner.nextLine()).append("\n");
                }
                logger.error(stringBuilder.toString());
                throw new RuntimeException("git merge fail");
            }
执行git的clone
String[] cmdArray = new String[]{
                    "git", "clone", gitPath, dir.getName(), "-q"};
            long time = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(cmdArray, new String[]{}, dir.getAbsoluteFile().getParentFile());
            int code = process.waitFor();
            if (code != 0) {
                StringBuilder stringBuilder = new StringBuilder().append("\ngit clone fail: gitPath=").append(gitPath)
                        .append(",dir=").append(dir.getParentFile().getAbsolutePath())
                        .append(",command=").append(StringUtils.join(cmdArray, " ")).append("\n");
                Scanner scanner = new Scanner(process.getErrorStream(), SHELL_CHARSET);
                while (scanner.hasNextLine()) {
                    stringBuilder.append(scanner.nextLine()).append("\n");
                }
                logger.error(stringBuilder.toString());
                throw new RuntimeException("git clone fail");
            }
按commit hash来打tag、按branch上的HEAD来打tag、按tag来打tag
@Value("${git.repository.dir}")
    private String gitDir;

    /**
     * 按commit hash来打tag
     */
    public void tagByCommitHash(String gitPath, String branchName, String commitHash, String tagNameNew) throws Exception {
        tagByRef(gitPath, branchName, commitHash, tagNameNew);
    }

    /**
     * 按branch上的HEAD来打tag
     */
    public void tagByBranchName(String gitPath, String branchName, String tagNameNew) throws Exception {
        tagByRef(gitPath, branchName, "remotes/origin/" + branchName, tagNameNew);
    }

    /**
     * 按tag来打tag
     */
    public void tagByTagName(String gitPath, String branchName, String tagNameOld, String tagNameNew) throws Exception {
        tagByRef(gitPath, branchName, tagNameOld, tagNameNew);
    }

    private void tagByRef(String gitPath, String branchName, String tagRef, String tagNameNew) throws Exception {
        File dir = new File(gitDir, DigestUtils.md5DigestAsHex(gitPath.getBytes(StandardCharsets.UTF_8)));
        ReentrantLock lock = getLock(dir.getAbsolutePath());
        try {
            lock.lock();
            ensureGitWorkDir(gitPath, dir);

            String command = buildCommand(new String[] {
                    String.format("%s tag %s %s", GIT_CMD, tagNameNew, tagRef),
                    String.format("%s push origin %s", GIT_CMD, tagNameNew)
            });
            long time = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(command, null, dir);

            int code = process.waitFor();
            if (code != 0) {
                StringBuilder stringBuilder = new StringBuilder().append("\ngit merge fail: gitPath=").append(gitPath)
                        .append(",dir=").append(dir.getAbsolutePath())
                        .append(",command=").append(command).append("\n");
                Scanner scanner = new Scanner(process.getErrorStream(), SHELL_CHARSET);
                while (scanner.hasNextLine()) {
                    stringBuilder.append(scanner.nextLine()).append("\n");
                }
                logger.error(stringBuilder.toString());
                throw new RuntimeException("git tag fail");
            }
            logger.info("================tagByRef time ms:" + (System.currentTimeMillis() - time));
        } finally {
            lock.unlock();
        }
    }
网友评论