go mod init
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.1 KiB

package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/peterbourgon/ff/v3"
)
var Version = "develop"
func main() {
fs := flag.NewFlagSet("gomodinit", flag.ExitOnError)
versionFlag := fs.Bool("version", false, "Print version and exit")
if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix("GMI")); 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
}
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)
if strings.Contains(part, ".") {
break
}
}
return name, nil
}