github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/modules/git/git.go (about) 1 // Package git allows to interact with Git. 2 package git 3 4 import ( 5 "os/exec" 6 "strings" 7 8 "github.com/gruntwork-io/terratest/modules/testing" 9 ) 10 11 // GetCurrentBranchName retrieves the current branch name or 12 // empty string in case of detached state. 13 func GetCurrentBranchName(t testing.TestingT) string { 14 out, err := GetCurrentBranchNameE(t) 15 if err != nil { 16 t.Fatal(err) 17 } 18 return out 19 } 20 21 // GetCurrentBranchNameE retrieves the current branch name or 22 // empty string in case of detached state. 23 // Uses branch --show-current, which was introduced in git v2.22. 24 // Falls back to rev-parse for users of the older version, like Ubuntu 18.04. 25 func GetCurrentBranchNameE(t testing.TestingT) (string, error) { 26 cmd := exec.Command("git", "branch", "--show-current") 27 bytes, err := cmd.Output() 28 if err != nil { 29 return GetCurrentBranchNameOldE(t) 30 } 31 32 name := strings.TrimSpace(string(bytes)) 33 if name == "HEAD" { 34 return "", nil 35 } 36 37 return name, nil 38 } 39 40 // GetCurrentBranchNameOldE retrieves the current branch name or 41 // empty string in case of detached state. This uses the older pattern 42 // of `git rev-parse` rather than `git branch --show-current`. 43 func GetCurrentBranchNameOldE(t testing.TestingT) (string, error) { 44 cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") 45 bytes, err := cmd.Output() 46 if err != nil { 47 return "", err 48 } 49 50 name := strings.TrimSpace(string(bytes)) 51 if name == "HEAD" { 52 return "", nil 53 } 54 55 return name, nil 56 } 57 58 // GetCurrentGitRef retrieves current branch name, lightweight (non-annotated) tag or 59 // if tag points to the commit exact tag value. 60 func GetCurrentGitRef(t testing.TestingT) string { 61 out, err := GetCurrentGitRefE(t) 62 if err != nil { 63 t.Fatal(err) 64 } 65 return out 66 } 67 68 // GetCurrentGitRefE retrieves current branch name, lightweight (non-annotated) tag or 69 // if tag points to the commit exact tag value. 70 func GetCurrentGitRefE(t testing.TestingT) (string, error) { 71 out, err := GetCurrentBranchNameE(t) 72 73 if err != nil { 74 return "", err 75 } 76 77 if out != "" { 78 return out, nil 79 } 80 81 out, err = GetTagE(t) 82 if err != nil { 83 return "", err 84 } 85 return out, nil 86 } 87 88 // GetTagE retrieves lightweight (non-annotated) tag or if tag points 89 // to the commit exact tag value. 90 func GetTagE(t testing.TestingT) (string, error) { 91 cmd := exec.Command("git", "describe", "--tags") 92 bytes, err := cmd.Output() 93 if err != nil { 94 return "", err 95 } 96 return strings.TrimSpace(string(bytes)), nil 97 }