Refine func GetModuleName

pull/2757/head
loyalsoldier 2020-10-04 09:55:21 +08:00
parent 68dd2a0d85
commit 4ba4cad7ae
No known key found for this signature in database
GPG Key ID: 23829BBC1ACF2C90
1 changed files with 6 additions and 6 deletions

View File

@ -125,26 +125,26 @@ func GetGOPATH() string {
} }
// GetModuleName returns the value of module in `go.mod` file. // GetModuleName returns the value of module in `go.mod` file.
func GetModuleName(path string) (string, error) { func GetModuleName(pathToProjectRoot string) (string, error) {
gomodPath := filepath.Join(path, "go.mod") gomodPath := filepath.Join(pathToProjectRoot, "go.mod")
gomodBytes, err := ioutil.ReadFile(gomodPath) gomodBytes, err := ioutil.ReadFile(gomodPath)
if err != nil { if err != nil {
return "", err return "", err
} }
gomodContent := string(gomodBytes) gomodContent := string(gomodBytes)
moduleIdx := strings.Index(gomodContent, "module") + 6 moduleIdx := strings.Index(gomodContent, "module ")
newLineIdx := strings.Index(gomodContent, "\n") newLineIdx := strings.Index(gomodContent, "\n")
var moduleName string var moduleName string
if moduleIdx >= 0 { if moduleIdx >= 0 {
if newLineIdx >= 0 { if newLineIdx >= 0 {
moduleName = strings.TrimSpace(gomodContent[moduleIdx:newLineIdx]) moduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx])
moduleName = strings.TrimSuffix(moduleName, "\r") moduleName = strings.TrimSuffix(moduleName, "\r")
} else { } else {
moduleName = strings.TrimSpace(gomodContent[moduleIdx:]) moduleName = strings.TrimSpace(gomodContent[moduleIdx+6:])
} }
} else { } else {
return "", fmt.Errorf("can not get the value of `module` in path `%s`", gomodPath) return "", fmt.Errorf("can not get module path in `%s`", gomodPath)
} }
return moduleName, nil return moduleName, nil
} }