auto generate go mod if need

master
kingxt 4 years ago
parent fcaebd73fb
commit cfa6644b0c

@ -1,6 +1,7 @@
package gogen package gogen
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"os" "os"
@ -55,6 +56,7 @@ func GoCommand(c *cli.Context) error {
lang.Must(genLogic(dir, api)) lang.Must(genLogic(dir, api))
// it does not work // it does not work
format(dir) format(dir)
createGoModFileIfNeed(dir)
if err := backupAndSweep(apiFile); err != nil { if err := backupAndSweep(apiFile); err != nil {
return err return err
@ -98,7 +100,7 @@ func format(dir string) {
cmd := exec.Command("go", "fmt", "./"+dir+"...") cmd := exec.Command("go", "fmt", "./"+dir+"...")
_, err := cmd.CombinedOutput() _, err := cmd.CombinedOutput()
if err != nil { if err != nil {
print(err.Error()) fmt.Println(err.Error())
} }
} }
@ -131,3 +133,43 @@ func sweep() error {
return nil return nil
}) })
} }
func createGoModFileIfNeed(dir string) {
absDir, err := filepath.Abs(dir)
if err != nil {
panic(err)
}
var tempPath = absDir
var hasGoMod = false
for {
if tempPath == filepath.Dir(tempPath) {
break
}
tempPath = filepath.Dir(tempPath)
if util.FileExists(filepath.Join(tempPath, goModeIdentifier)) {
tempPath = filepath.Dir(tempPath)
hasGoMod = true
break
}
}
if !hasGoMod {
gopath := os.Getenv("GOPATH")
parent := path.Join(gopath, "src")
pos := strings.Index(absDir, parent)
if pos < 0 {
moduleName := absDir[len(filepath.Dir(absDir))+1:]
cmd := exec.Command("go", "mod", "init", moduleName)
cmd.Dir = dir
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(err.Error())
}
outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
fmt.Printf(outStr + "\n" + errStr)
}
}
}

Loading…
Cancel
Save