Created
December 1, 2016 03:14
-
-
Save unakatsuo/4adb2d4a5ec26e54003b05f5c02b680b to your computer and use it in GitHub Desktop.
Guess current Git branch name even on Detached HEAD.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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