Permalink
Browse files

Support loading git branch from CI specific environment variables

Closes #79.
  • Loading branch information...
1 parent edf7508 commit 7d0f7db063322be584b29f8ad1ceb0bef15e9e93 @fsouza fsouza committed Nov 8, 2016
Showing with 81 additions and 1 deletion.
  1. +11 −1 gitinfo.go
  2. +70 −0 gitinfo_test.go
View
@@ -53,7 +53,7 @@ func collectGitInfo() *Git {
}
for key, args := range gitCmds {
if key == "branch" {
- if envBranch := os.Getenv("GIT_BRANCH"); envBranch != "" {
+ if envBranch := loadBranchFromEnv(); envBranch != "" {
results[key] = envBranch
continue
}
@@ -104,3 +104,13 @@ func collectGitInfo() *Git {
}
return g
}
+
+func loadBranchFromEnv() string {
+ varNames := []string{"GIT_BRANCH", "CIRCLE_BRANCH", "TRAVIS_BRANCH", "CI_BRANCH"}
+ for _, varName := range varNames {
+ if branch := os.Getenv(varName); branch != "" {
+ return branch
+ }
+ }
+ return ""
+}
View
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "os"
+ "testing"
+)
+
+func TestLoadBranchFromEnv(t *testing.T) {
+ var tests = []struct {
+ testCase string
+ envs map[string]string
+ expectedBranch string
+ }{
+ {
+ "all vars defined",
+ map[string]string{
+ "GIT_BRANCH": "master",
+ "CIRCLE_BRANCH": "circle-master",
+ "TRAVIS_BRANCH": "travis-master",
+ "CI_BRANCH": "ci-master",
+ },
+ "master",
+ },
+ {
+ "all except GIT_BRANCH",
+ map[string]string{
+ "CIRCLE_BRANCH": "circle-master",
+ "TRAVIS_BRANCH": "travis-master",
+ "CI_BRANCH": "ci-master",
+ },
+ "circle-master",
+ },
+ {
+ "all except GIT_BRANCH and CIRCLE_BRANCH",
+ map[string]string{
+ "TRAVIS_BRANCH": "travis-master",
+ "CI_BRANCH": "ci-master",
+ },
+ "travis-master",
+ },
+ {
+ "only CI_BRANCH defined",
+ map[string]string{
+ "CI_BRANCH": "ci-master",
+ },
+ "ci-master",
+ },
+ {
+ "no branch var defined",
+ map[string]string{},
+ "",
+ },
+ }
+ for _, test := range tests {
+ resetBranchEnvs(test.envs)
+ envBranch := loadBranchFromEnv()
+ if envBranch != test.expectedBranch {
+ t.Errorf("%s: wrong branch returned. Expected %q, but got %q", test.testCase, test.expectedBranch, envBranch)
+ }
+ }
+}
+
+func resetBranchEnvs(values map[string]string) {
+ for _, envVar := range []string{"CI_BRANCH", "CIRCLE_BRANCH", "GIT_BRANCH", "TRAVIS_BRANCH"} {
+ os.Unsetenv(envVar)
+ }
+ for k, v := range values {
+ os.Setenv(k, v)
+ }
+}

0 comments on commit 7d0f7db

Please sign in to comment.