github.com/r2d2-ai/cli@v1.20.0/util/version.go (about) 1 package util 2 3 import ( 4 "log" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "regexp" 9 "strings" 10 "text/template" 11 "time" 12 ) 13 14 const ( 15 cliPackage = "github.com/r2d2-ai/cli" 16 ) 17 18 func GetCLIInfo() (string, string, error) { 19 20 path, ver, err := FindOldPackageSrc(cliPackage) 21 22 if IsPkgNotFoundError(err) { 23 //must be using the new go mod layout 24 path, ver, err = FindGoModPackageSrc(cliPackage, "", true) 25 if err != nil { 26 workingDir, _ := os.Getwd() 27 ver = GetPackageVersionFromGit(workingDir) 28 } 29 } 30 31 return path, ver, err 32 } 33 34 // retrieve the package version from source in GOPATH using "git describe" command 35 func GetPackageVersionFromSource(pkg string) string { 36 gopath := GetGoPath() 37 38 pkgParts := strings.Split(pkg, "/") 39 40 return GetPackageVersionFromGit(filepath.Join(gopath, "src", filepath.Join(pkgParts...))) 41 } 42 43 // retrieve the package version from source in a directory using "git describe" command 44 func GetPackageVersionFromGit(dir string) string { 45 re := regexp.MustCompile("\\n") 46 47 cmd := exec.Command("git", "describe", "--tags", "--dirty", "--always") 48 cmd.Env = append(os.Environ()) 49 50 cmd.Dir = dir 51 52 out, err := cmd.Output() // execute "git describe" 53 if err != nil { 54 log.Fatal(err) 55 } 56 fc := re.ReplaceAllString(string(out), "") 57 58 if len(fc) > 1 { 59 return fc[1:] 60 } 61 62 return fc 63 } 64 65 func CreateVersionFile(cmdPath, currentVersion string) error { 66 67 f, err := os.Create(filepath.Join(cmdPath, "currentversion.go")) 68 if err != nil { 69 log.Fatal(err) 70 return nil 71 } 72 defer f.Close() 73 74 _ = packageTemplate.Execute(f, struct { 75 Timestamp time.Time 76 Version string 77 }{ 78 Timestamp: time.Now(), 79 Version: currentVersion, 80 }) 81 82 return nil 83 } 84 85 var packageTemplate = template.Must(template.New("").Parse(`// Generated Code; DO NOT EDIT. 86 // {{ .Timestamp }} 87 package main 88 89 func init() { 90 Version = "{{ .Version }}" 91 } 92 `))