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
|
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
)
var Version = "develop"
func main() {
fs := flag.NewFlagSet("gomodinit", flag.ExitOnError)
versionFlag := fs.Bool("version", false, "Print version and exit")
if err := fs.Parse(os.Args[1:]); err != nil {
fmt.Println(err)
return
}
if *versionFlag {
fmt.Printf("gomodinit %s\n", Version)
return
}
var name string
if fs.NArg() > 0 {
name = fs.Arg(0)
} else {
n, err := module()
if err != nil {
fmt.Println(err)
return
}
name = n
}
cmd := exec.Command("go", "mod", "init", name)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
}
func module() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
root := dir
list := strings.Split(dir, string(filepath.Separator))
name := list[len(list)-1]
for idx := len(list) - 2; idx >= 0; idx-- {
part := list[idx]
name = fmt.Sprintf("%s/%s", part, name)
root = filepath.Dir(root)
if strings.Contains(part, ".") {
break
}
}
override, err := os.ReadFile(filepath.Join(root, ".gomodinit"))
if errors.Is(err, fs.ErrNotExist) {
return name, nil
}
if err != nil {
return name, err
}
parts := strings.SplitN(name, "/", 2)
return fmt.Sprintf("%s/%s", bytes.TrimSpace(override), parts[1]), nil
}
|