github.com/rohitsakala/goveralls@v0.0.4/gitinfo.go (about) 1 package main 2 3 import ( 4 "log" 5 "os" 6 "os/exec" 7 "strings" 8 ) 9 10 // A Head object encapsulates information about the HEAD revision of a git repo. 11 type Head struct { 12 Id string `json:"id"` 13 AuthorName string `json:"author_name,omitempty"` 14 AuthorEmail string `json:"author_email,omitempty"` 15 CommitterName string `json:"committer_name,omitempty"` 16 CommitterEmail string `json:"committer_email,omitempty"` 17 Message string `json:"message"` 18 } 19 20 // A Git object encapsulates information about a git repo. 21 type Git struct { 22 Head Head `json:"head"` 23 Branch string `json:"branch"` 24 } 25 26 // collectGitInfo runs several git commands to compose a Git object. 27 func collectGitInfo() *Git { 28 gitCmds := map[string][]string{ 29 "id": {"rev-parse", "HEAD"}, 30 "branch": {"rev-parse", "--abbrev-ref", "HEAD"}, 31 "aname": {"log", "-1", "--pretty=%aN"}, 32 "aemail": {"log", "-1", "--pretty=%aE"}, 33 "cname": {"log", "-1", "--pretty=%cN"}, 34 "cemail": {"log", "-1", "--pretty=%cE"}, 35 "message": {"log", "-1", "--pretty=%s"}, 36 } 37 results := map[string]string{} 38 gitPath, err := exec.LookPath("git") 39 if err != nil { 40 log.Fatal(err) 41 } 42 for key, args := range gitCmds { 43 if key == "branch" { 44 if envBranch := loadBranchFromEnv(); envBranch != "" { 45 results[key] = envBranch 46 continue 47 } 48 } 49 50 cmd := exec.Command(gitPath, args...) 51 ret, err := cmd.CombinedOutput() 52 if err != nil { 53 if strings.Contains(string(ret), `Not a git repository`) { 54 return nil 55 } 56 log.Fatalf("%v: %v", err, string(ret)) 57 } 58 s := string(ret) 59 s = strings.TrimRight(s, "\n") 60 results[key] = s 61 } 62 h := Head{ 63 Id: results["id"], 64 AuthorName: results["aname"], 65 AuthorEmail: results["aemail"], 66 CommitterName: results["cname"], 67 CommitterEmail: results["cemail"], 68 Message: results["message"], 69 } 70 g := &Git{ 71 Head: h, 72 Branch: results["branch"], 73 } 74 return g 75 } 76 77 func loadBranchFromEnv() string { 78 varNames := []string{"GIT_BRANCH", "CIRCLE_BRANCH", "TRAVIS_BRANCH", "CI_BRANCH", "APPVEYOR_REPO_BRANCH", "WERCKER_GIT_BRANCH", "DRONE_BRANCH", "BUILDKITE_BRANCH", "BRANCH_NAME"} 79 for _, varName := range varNames { 80 if branch := os.Getenv(varName); branch != "" { 81 return branch 82 } 83 } 84 return "" 85 }