diff --git a/modules/git/git.go b/modules/git/git.go index 6e0c1e5d4..d13594756 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -20,7 +20,27 @@ func GetCurrentBranchName(t testing.TestingT) string { // GetCurrentBranchNameE retrieves the current branch name or // empty string in case of detached state. +// Uses branch --show-current, which was introduced in git v2.22. +// Falls back to rev-parse for users of the older version, like Ubuntu 18.04. func GetCurrentBranchNameE(t testing.TestingT) (string, error) { + cmd := exec.Command("git", "branch", "--show-current") + bytes, err := cmd.Output() + if err != nil { + return GetCurrentBranchNameOldE(t) + } + + name := strings.TrimSpace(string(bytes)) + if name == "HEAD" { + return "", nil + } + + return name, nil +} + +// GetCurrentBranchNameOldE retrieves the current branch name or +// empty string in case of detached state. This uses the older pattern +// of `git rev-parse` rather than `git branch --show-current`. +func GetCurrentBranchNameOldE(t testing.TestingT) (string, error) { cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") bytes, err := cmd.Output() if err != nil {