forked from zeromicro/go-zero
/
path.go
82 lines (68 loc) · 1.42 KB
/
path.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
76
77
78
79
80
81
82
package util
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/yilefreedom/go-zero/tools/goctl/vars"
)
const (
pkgSep = "/"
goModeIdentifier = "go.mod"
)
func JoinPackages(pkgs ...string) string {
return strings.Join(pkgs, pkgSep)
}
func MkdirIfNotExist(dir string) error {
if len(dir) == 0 {
return nil
}
if _, err := os.Stat(dir); os.IsNotExist(err) {
return os.MkdirAll(dir, os.ModePerm)
}
return nil
}
func PathFromGoSrc() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
gopath := os.Getenv("GOPATH")
parent := path.Join(gopath, "src", vars.ProjectName)
pos := strings.Index(dir, parent)
if pos < 0 {
return "", fmt.Errorf("%s is not in GOPATH", dir)
}
// skip slash
return dir[len(parent)+1:], nil
}
func FindGoModPath(dir string) (string, bool) {
absDir, err := filepath.Abs(dir)
if err != nil {
return "", false
}
absDir = strings.ReplaceAll(absDir, `\`, `/`)
var rootPath string
var tempPath = absDir
var hasGoMod = false
for {
if FileExists(filepath.Join(tempPath, goModeIdentifier)) {
tempPath = filepath.Dir(tempPath)
rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")
hasGoMod = true
break
}
if tempPath == filepath.Dir(tempPath) {
break
}
tempPath = filepath.Dir(tempPath)
if tempPath == string(filepath.Separator) {
break
}
}
if hasGoMod {
return rootPath, true
}
return "", false
}