github.com/Cloud-Foundations/Dominator@v0.3.4/lib/gitutil/getCommitId.go (about) 1 package gitutil 2 3 import ( 4 "fmt" 5 "os/exec" 6 "path/filepath" 7 "strings" 8 9 "github.com/Cloud-Foundations/Dominator/lib/fsutil" 10 ) 11 12 func getCommitIdOfRef(topdir, ref string) (string, error) { 13 // First try directly reading. 14 if commitId, err := getCommitIdOfRefDirect(topdir, ref); err == nil { 15 return commitId, nil 16 } 17 cmd := exec.Command("git", "log", "--format=format:%H", "-1", ref) 18 cmd.Dir = topdir 19 _output, err := cmd.CombinedOutput() 20 output := strings.TrimSpace(string(_output)) 21 if err != nil { 22 if len(output) < 1 { 23 return "", fmt.Errorf("error running: git log: %s", err) 24 } 25 return "", fmt.Errorf("error running: git log: %s: %s", err, output) 26 } 27 return output, nil 28 } 29 30 func getCommitIdOfRefDirect(topdir, ref string) (string, error) { 31 filename := filepath.Join(topdir, ".git", "refs", "heads", ref) 32 if lines, err := fsutil.LoadLines(filename); err != nil { 33 return "", err 34 } else if len(lines) != 1 { 35 return "", fmt.Errorf("%s does not have only one line", filename) 36 } else { 37 return strings.TrimSpace(lines[0]), nil 38 } 39 40 }