genconfig.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package configgen
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strings"
  9. "text/template"
  10. "github.com/logrusorgru/aurora"
  11. "github.com/tal-tech/go-zero/tools/goctl/util"
  12. "github.com/urfave/cli"
  13. )
  14. const configTemplate = `package main
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "{{.import}}"
  19. "github.com/ghodss/yaml"
  20. )
  21. func main() {
  22. var c config.Config
  23. template, err := yaml.Marshal(c)
  24. if err != nil {
  25. panic(err)
  26. }
  27. err = ioutil.WriteFile("config.yaml", template, os.ModePerm)
  28. if err != nil {
  29. panic(err)
  30. }
  31. }
  32. `
  33. func GenConfigCommand(c *cli.Context) error {
  34. path, err := filepath.Abs(c.String("path"))
  35. if err != nil {
  36. return errors.New("abs failed: " + c.String("path"))
  37. }
  38. goModPath, hasFound := util.FindGoModPath(path)
  39. if !hasFound {
  40. return errors.New("go mod not initial")
  41. }
  42. path = strings.TrimSuffix(path, "/config.go")
  43. location := path + "/tmp"
  44. err = os.MkdirAll(location, os.ModePerm)
  45. if err != nil {
  46. return err
  47. }
  48. goPath := filepath.Join(location, "config.go")
  49. fp, err := os.Create(goPath)
  50. if err != nil {
  51. return err
  52. }
  53. defer fp.Close()
  54. defer os.RemoveAll(location)
  55. t := template.Must(template.New("template").Parse(configTemplate))
  56. if err := t.Execute(fp, map[string]string{
  57. "import": filepath.Dir(goModPath),
  58. }); err != nil {
  59. return err
  60. }
  61. gen := exec.Command("go", "run", "config.go")
  62. gen.Dir = filepath.Dir(goPath)
  63. gen.Stderr = os.Stderr
  64. gen.Stdout = os.Stdout
  65. err = gen.Run()
  66. if err != nil {
  67. panic(err)
  68. }
  69. path, err = os.Getwd()
  70. if err != nil {
  71. panic(err)
  72. }
  73. err = os.Rename(filepath.Dir(goPath)+"/config.yaml", path+"/config.yaml")
  74. if err != nil {
  75. panic(err)
  76. }
  77. fmt.Println(aurora.Green("Done."))
  78. return nil
  79. }