Support to read go.mod recursively to get module path

pull/2757/head
loyalsoldier 2020-10-04 12:38:25 +08:00
parent d30b5fb501
commit 4130b54579
No known key found for this signature in database
GPG Key ID: 23829BBC1ACF2C90
1 changed files with 26 additions and 18 deletions

View File

@ -126,16 +126,21 @@ 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(pathToProjectRoot string) (string, error) { func GetModuleName(pathToProjectRoot string) (string, error) {
gomodPath := filepath.Join(pathToProjectRoot, "go.mod") var moduleName string
loopPath := pathToProjectRoot
for {
if idx := strings.LastIndex(loopPath, string(filepath.Separator)); idx >= 0 {
gomodPath := filepath.Join(loopPath, "go.mod")
gomodBytes, err := ioutil.ReadFile(gomodPath) gomodBytes, err := ioutil.ReadFile(gomodPath)
if err != nil { if err != nil {
return "", err loopPath = loopPath[:idx]
continue
} }
gomodContent := string(gomodBytes) gomodContent := string(gomodBytes)
moduleIdx := strings.Index(gomodContent, "module ") moduleIdx := strings.Index(gomodContent, "module ")
newLineIdx := strings.Index(gomodContent, "\n") newLineIdx := strings.Index(gomodContent, "\n")
var moduleName string
if moduleIdx >= 0 { if moduleIdx >= 0 {
if newLineIdx >= 0 { if newLineIdx >= 0 {
moduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx]) moduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx])
@ -143,8 +148,11 @@ func GetModuleName(pathToProjectRoot string) (string, error) {
} else { } else {
moduleName = strings.TrimSpace(gomodContent[moduleIdx+6:]) moduleName = strings.TrimSpace(gomodContent[moduleIdx+6:])
} }
} else {
return "", fmt.Errorf("can not get module path in `%s`", gomodPath)
}
return moduleName, nil return moduleName, nil
} }
return "", fmt.Errorf("can not get module path in `%s`", gomodPath)
}
break
}
return moduleName, fmt.Errorf("no `go.mod` file in every parent directory of `%s`", pathToProjectRoot)
}