genconfig.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package configgen
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strings"
  9. "text/template"
  10. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  11. "github.com/logrusorgru/aurora"
  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. // GenConfigCommand provides the entry of goctl config
  34. func GenConfigCommand(c *cli.Context) error {
  35. path, err := filepath.Abs(c.String("path"))
  36. if err != nil {
  37. return errors.New("abs failed: " + c.String("path"))
  38. }
  39. goModPath, found := util.FindGoModPath(path)
  40. if !found {
  41. return errors.New("go mod not initial")
  42. }
  43. path = strings.TrimSuffix(path, "/config.go")
  44. location := filepath.Join(path, "tmp")
  45. err = os.MkdirAll(location, os.ModePerm)
  46. if err != nil {
  47. return err
  48. }
  49. goPath := filepath.Join(location, "config.go")
  50. fp, err := os.Create(goPath)
  51. if err != nil {
  52. return err
  53. }
  54. defer fp.Close()
  55. defer os.RemoveAll(location)
  56. t := template.Must(template.New("template").Parse(configTemplate))
  57. if err := t.Execute(fp, map[string]string{
  58. "import": filepath.Dir(goModPath),
  59. }); err != nil {
  60. return err
  61. }
  62. gen := exec.Command("go", "run", "config.go")
  63. gen.Dir = filepath.Dir(goPath)
  64. gen.Stderr = os.Stderr
  65. gen.Stdout = os.Stdout
  66. err = gen.Run()
  67. if err != nil {
  68. panic(err)
  69. }
  70. path, err = os.Getwd()
  71. if err != nil {
  72. panic(err)
  73. }
  74. err = os.Rename(filepath.Dir(goPath)+"/config.yaml", path+"/config.yaml")
  75. if err != nil {
  76. panic(err)
  77. }
  78. fmt.Println(aurora.Green("Done."))
  79. return nil
  80. }