docker.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package docker
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "text/template"
  8. "github.com/tal-tech/go-zero/tools/goctl/util"
  9. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/urfave/cli"
  11. )
  12. const (
  13. etcDir = "etc"
  14. yamlEtx = ".yaml"
  15. )
  16. func DockerCommand(c *cli.Context) error {
  17. goFile := c.String("go")
  18. if len(goFile) == 0 {
  19. return errors.New("-go can't be empty")
  20. }
  21. cfg, err := findConfig(goFile, etcDir)
  22. if err != nil {
  23. return err
  24. }
  25. return generateDockerfile(goFile, "-f", "etc/"+cfg)
  26. }
  27. func findConfig(file, dir string) (string, error) {
  28. var files []string
  29. err := filepath.Walk(dir, func(path string, f os.FileInfo, _ error) error {
  30. if !f.IsDir() {
  31. if filepath.Ext(f.Name()) == yamlEtx {
  32. files = append(files, f.Name())
  33. }
  34. }
  35. return nil
  36. })
  37. if err != nil {
  38. return "", err
  39. }
  40. if len(files) == 0 {
  41. return "", errors.New("no yaml file")
  42. }
  43. name := strings.TrimSuffix(filepath.Base(file), ".go")
  44. for _, f := range files {
  45. if strings.Index(f, name) == 0 {
  46. return f, nil
  47. }
  48. }
  49. return files[0], nil
  50. }
  51. func generateDockerfile(goFile string, args ...string) error {
  52. projPath, err := getFilePath(filepath.Dir(goFile))
  53. if err != nil {
  54. return err
  55. }
  56. pos := strings.IndexByte(projPath, '/')
  57. if pos >= 0 {
  58. projPath = projPath[pos+1:]
  59. }
  60. out, err := util.CreateIfNotExist("Dockerfile")
  61. if err != nil {
  62. return err
  63. }
  64. defer out.Close()
  65. text, err := ctlutil.LoadTemplate(category, dockerTemplateFile, dockerTemplate)
  66. if err != nil {
  67. return err
  68. }
  69. var builder strings.Builder
  70. for _, arg := range args {
  71. builder.WriteString(`, "` + arg + `"`)
  72. }
  73. t := template.Must(template.New("dockerfile").Parse(text))
  74. return t.Execute(out, map[string]string{
  75. "goRelPath": projPath,
  76. "goFile": goFile,
  77. "exeFile": util.FileNameWithoutExt(filepath.Base(goFile)),
  78. "argument": builder.String(),
  79. })
  80. }
  81. func getFilePath(file string) (string, error) {
  82. wd, err := os.Getwd()
  83. if err != nil {
  84. return "", err
  85. }
  86. projPath, ok := util.FindGoModPath(filepath.Join(wd, file))
  87. if !ok {
  88. projPath, err = util.PathFromGoSrc()
  89. if err != nil {
  90. return "", errors.New("no go.mod found, or not in GOPATH")
  91. }
  92. }
  93. return projPath, nil
  94. }