Skip to content

Commit

Permalink
Merge pull request #786 from gruntwork-io/rho/branch-issue
Browse files Browse the repository at this point in the history
Use git branch --show-current because it works when there are no commits
  • Loading branch information
rhoboat authored Mar 19, 2021
2 parents a53c621 + d2a5f73 commit 393f87d
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions modules/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 393f87d

Please sign in to comment.