Skip to content

Instantly share code, notes, and snippets.

@unakatsuo
Created December 1, 2016 03:14
Show Gist options
  • Save unakatsuo/4adb2d4a5ec26e54003b05f5c02b680b to your computer and use it in GitHub Desktop.
Save unakatsuo/4adb2d4a5ec26e54003b05f5c02b680b to your computer and use it in GitHub Desktop.
Guess current Git branch name even on Detached HEAD.
import (
"log"
"bufio"
"os"
"strings"
"os/exec"
"bytes"
)
func findCurrentBranch() string {
if v, exists := os.LookupEnv("GIT_BRANCH"); exists {
// Respect the value if Jenkins provides.
return v
}
cmd := exec.Command("git", "show", "-s", "-pretty=%d", "HEAD")
err := cmd.Run()
if err != nil {
log.Fatal("Failed to run git command: ", err)
}
out, err := cmd.Output()
if err != nil {
log.Fatal("Failed to get stdout from git: ", err)
}
scanner := bufio.NewScanner(bytes.NewReader(out))
if !scanner.Scan() {
log.Fatal("Invalid git show output: ", string(out))
}
l1 := scanner.Text()
// $ git show -s --pretty=%d HEAD
if strings.HasSuffix(l1, "(HEAD -> ") {
// Normal result:
// (HEAD -> generalize-template)
return l1[9 : len(l1)-1]
}
if strings.HasSuffix(l1, "(HEAD, ") {
// Detached HEAD:
// (HEAD, origin/pr/24, origin/attributed-offer)
refs := strings.Split(l1[1:len(l1)-1], ", ")
for _, ref := range refs {
return ref
}
}
return ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment