You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/configgen/genconfig.go

96 lines
1.7 KiB
Go

4 years ago
package configgen
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
"github.com/logrusorgru/aurora"
"github.com/tal-tech/go-zero/tools/goctl/util"
4 years ago
"github.com/urfave/cli"
)
const configTemplate = `package main
import (
"io/ioutil"
"os"
"{{.import}}"
"github.com/ghodss/yaml"
4 years ago
)
func main() {
var c config.Config
template, err := yaml.Marshal(c)
4 years ago
if err != nil {
panic(err)
}
err = ioutil.WriteFile("config.yaml", template, os.ModePerm)
4 years ago
if err != nil {
panic(err)
}
}
`
// GenConfigCommand provides the entry of goctl config
4 years ago
func GenConfigCommand(c *cli.Context) error {
path, err := filepath.Abs(c.String("path"))
if err != nil {
return errors.New("abs failed: " + c.String("path"))
}
goModPath, found := util.FindGoModPath(path)
if !found {
return errors.New("go mod not initial")
4 years ago
}
4 years ago
path = strings.TrimSuffix(path, "/config.go")
location := filepath.Join(path, "tmp")
4 years ago
err = os.MkdirAll(location, os.ModePerm)
if err != nil {
return err
}
goPath := filepath.Join(location, "config.go")
fp, err := os.Create(goPath)
if err != nil {
return err
}
defer fp.Close()
defer os.RemoveAll(location)
t := template.Must(template.New("template").Parse(configTemplate))
if err := t.Execute(fp, map[string]string{
"import": filepath.Dir(goModPath),
4 years ago
}); err != nil {
return err
}
gen := exec.Command("go", "run", "config.go")
gen.Dir = filepath.Dir(goPath)
gen.Stderr = os.Stderr
gen.Stdout = os.Stdout
err = gen.Run()
4 years ago
if err != nil {
panic(err)
}
path, err = os.Getwd()
if err != nil {
panic(err)
4 years ago
}
err = os.Rename(filepath.Dir(goPath)+"/config.yaml", path+"/config.yaml")
if err != nil {
panic(err)
}
4 years ago
fmt.Println(aurora.Green("Done."))
return nil
}