在Java测试中获取当前的Git分支

7

我需要在Java测试中获取当前Git分支的名称。可能可以解析git status的结果。是否有其他方法或现成的代码片段可用?

1个回答

9

对我来说很好用。

public static String getCurrentGitBranch() throws IOException, InterruptedException {
    Process process = Runtime.getRuntime().exec( "git rev-parse --abbrev-ref HEAD" );
    process.waitFor();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader( process.getInputStream() ) );

    return reader.readLine();
}

3
在这种情况下,git rev-parse --abbrev-ref HEAD可能会更好。 - 1615903
好的,那应该会更好。谢谢! - Alex T
这可能是一个常识性的评论,但不要忘记将“Git”添加到您的系统路径中。对于Windows机器,您需要在C:\ Users \ [YOUR_USER_NAME] \ AppData \ Local文件夹内找到它。 - hfontanez
顺带一提,分支信息在 .git/HEAD 文件中。 - MarkHu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接