forked from incu6us/goimports-reviser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
75 lines (57 loc) · 1.31 KB
/
module.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package module
import (
"io/ioutil"
"os"
"path/filepath"
"golang.org/x/mod/modfile"
)
const goModFilename = "go.mod"
// Name reads module value from ./go.mod
func Name(goModRootPath string) (string, error) {
goModFile := filepath.Join(goModRootPath, goModFilename)
data, err := ioutil.ReadFile(goModFile)
if err != nil {
return "", err
}
f, err := modfile.Parse(goModFile, data, nil)
if err != nil {
return "", err
}
if f.Module != nil {
return f.Module.Mod.Path, nil
}
return "", &UndefinedModuleError{}
}
// GoModRootPath in case of any directory or file of the project will return root dir of the project where go.mod file
// is exist
func GoModRootPath(path string) (string, error) {
if path == "" {
return "", &PathIsNotSetError{}
}
path = filepath.Clean(path)
for {
if fi, err := os.Stat(filepath.Join(path, goModFilename)); err == nil && !fi.IsDir() {
return path, nil
}
d := filepath.Dir(path)
if d == path {
break
}
path = d
}
return "", nil
}
func DetermineProjectName(projectName, filePath string) (string, error) {
if projectName == "" {
projectRootPath, err := GoModRootPath(filePath)
if err != nil {
return "", err
}
moduleName, err := Name(projectRootPath)
if err != nil {
return "", err
}
return moduleName, nil
}
return projectName, nil
}