/
new.go
61 lines (56 loc) · 1.35 KB
/
new.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
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
common "github.com/bilibili/kratos/tool/pkg"
"github.com/urfave/cli/v2"
)
func runNew(ctx *cli.Context) (err error) {
if p.onlyGRPC && p.onlyHTTP {
p.onlyGRPC = false
p.onlyHTTP = false
}
if p.path != "" {
if p.path, err = filepath.Abs(p.path); err != nil {
return
}
p.path = filepath.Join(p.path, p.Name)
} else {
pwd, _ := os.Getwd()
p.path = filepath.Join(pwd, p.Name)
}
p.ModPrefix = modPath(p.path)
// creata a project
if err := create(); err != nil {
return err
}
fmt.Printf("Project: %s\n", p.Name)
fmt.Printf("OnlyGRPC: %t\n", p.onlyGRPC)
fmt.Printf("OnlyHTTP: %t\n", p.onlyHTTP)
fmt.Printf("Directory: %s\n\n", p.path)
fmt.Println("项目创建成功.")
return nil
}
func modPath(p string) string {
dir := filepath.Dir(p)
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
content, _ := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
mod := common.RegexpReplace(`module\s+(?P<name>[\S]+)`, string(content), "$name")
name := strings.TrimPrefix(filepath.Dir(p), dir)
name = strings.TrimPrefix(name, string(os.PathSeparator))
if name == "" {
return fmt.Sprintf("%s/", mod)
}
return fmt.Sprintf("%s/%s/", mod, name)
}
parent := filepath.Dir(dir)
if dir == parent {
return ""
}
dir = parent
}
}