github.com/terraform-modules-krish/terratest@v0.29.0/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/terraform-modules-krish/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 func GetCurrentBranchNameE(t testing.TestingT) (string, error) { 24 cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") 25 bytes, err := cmd.Output() 26 if err != nil { 27 return "", err 28 } 29 30 name := strings.TrimSpace(string(bytes)) 31 if name == "HEAD" { 32 return "", nil 33 } 34 35 return name, nil 36 } 37 38 // GetCurrentGitRef retrieves current branch name, lightweight (non-annotated) tag or 39 // if tag points to the commit exact tag value. 40 func GetCurrentGitRef(t testing.TestingT) string { 41 out, err := GetCurrentGitRefE(t) 42 if err != nil { 43 t.Fatal(err) 44 } 45 return out 46 } 47 48 // GetCurrentGitRefE retrieves current branch name, lightweight (non-annotated) tag or 49 // if tag points to the commit exact tag value. 50 func GetCurrentGitRefE(t testing.TestingT) (string, error) { 51 out, err := GetCurrentBranchNameE(t) 52 53 if err != nil { 54 return "", err 55 } 56 57 if out != "" { 58 return out, nil 59 } 60 61 out, err = GetTagE(t) 62 if err != nil { 63 return "", err 64 } 65 return out, nil 66 } 67 68 // GetTagE retrieves lightweight (non-annotated) tag or if tag points 69 // to the commit exact tag value. 70 func GetTagE(t testing.TestingT) (string, error) { 71 cmd := exec.Command("git", "describe", "--tags") 72 bytes, err := cmd.Output() 73 if err != nil { 74 return "", err 75 } 76 return strings.TrimSpace(string(bytes)), nil 77 }