Home

gomodinit @main - refs - log -
https://git.jolheiser.com/gomodinit.git
go mod init
Raw - main.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
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
}