Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use git branch --show-current because it works when there are no commits #786

Merged
merged 3 commits into from
Mar 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
rhoboat marked this conversation as resolved.
Show resolved Hide resolved
bytes, err := cmd.Output()
if err != nil {
return GetCurrentBranchNameOldE(t)
}

name := strings.TrimSpace(string(bytes))
if name == "HEAD" {
return "", nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: DRY with the logic above by extracting the git subprocess call into its own function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course!


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