genconfigjson.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/urfave/cli"
  12. "zero/tools/goctl/vars"
  13. )
  14. const configTemplate = `package main
  15. import (
  16. "encoding/json"
  17. "io/ioutil"
  18. "os"
  19. "{{.import}}"
  20. )
  21. func main() {
  22. var c config.Config
  23. template, err := json.MarshalIndent(c, "", " ")
  24. if err != nil {
  25. panic(err)
  26. }
  27. err = ioutil.WriteFile("config.json", 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. xi := strings.Index(path, vars.ProjectName)
  39. if xi <= 0 {
  40. return errors.New("path should the absolute path of config go file")
  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": path[xi:],
  58. }); err != nil {
  59. return err
  60. }
  61. cmd := exec.Command("go", "run", goPath)
  62. _, err = cmd.Output()
  63. if err != nil {
  64. return err
  65. }
  66. fmt.Println(aurora.Green("Done."))
  67. return nil
  68. }