github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/utils/utils.go (about) 1 package utils 2 3 import ( 4 "os" 5 "path/filepath" 6 "regexp" 7 "runtime" 8 "strconv" 9 "strings" 10 ) 11 12 // GetGOPATHs returns all paths in GOPATH variable. 13 func GetGOPATHs() []string { 14 gopath := os.Getenv("GOPATH") 15 if gopath == "" && compareGoVersion(runtime.Version(), "go1.8") >= 0 { 16 gopath = defaultGOPATH() 17 } 18 return filepath.SplitList(gopath) 19 } 20 21 func compareGoVersion(a, b string) int { 22 reg := regexp.MustCompile("^\\d*") 23 24 a = strings.TrimPrefix(a, "go") 25 b = strings.TrimPrefix(b, "go") 26 27 versionsA := strings.Split(a, ".") 28 versionsB := strings.Split(b, ".") 29 30 for i := 0; i < len(versionsA) && i < len(versionsB); i++ { 31 versionA := versionsA[i] 32 versionB := versionsB[i] 33 34 vA, err := strconv.Atoi(versionA) 35 if err != nil { 36 str := reg.FindString(versionA) 37 if str != "" { 38 vA, _ = strconv.Atoi(str) 39 } else { 40 vA = -1 41 } 42 } 43 44 vB, err := strconv.Atoi(versionB) 45 if err != nil { 46 str := reg.FindString(versionB) 47 if str != "" { 48 vB, _ = strconv.Atoi(str) 49 } else { 50 vB = -1 51 } 52 } 53 54 if vA > vB { 55 // vA = 12, vB = 8 56 return 1 57 } else if vA < vB { 58 // vA = 6, vB = 8 59 return -1 60 } else if vA == -1 { 61 // vA = rc1, vB = rc3 62 return strings.Compare(versionA, versionB) 63 } 64 65 // vA = vB = 8 66 continue 67 } 68 69 if len(versionsA) > len(versionsB) { 70 return 1 71 } else if len(versionsA) == len(versionsB) { 72 return 0 73 } 74 75 return -1 76 } 77 78 func defaultGOPATH() string { 79 env := "HOME" 80 if runtime.GOOS == "windows" { 81 env = "USERPROFILE" 82 } else if runtime.GOOS == "plan9" { 83 env = "home" 84 } 85 if home := os.Getenv(env); home != "" { 86 return filepath.Join(home, "go") 87 } 88 return "" 89 }