docker.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package docker
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "text/template"
  9. "time"
  10. "github.com/logrusorgru/aurora"
  11. "github.com/tal-tech/go-zero/tools/goctl/util"
  12. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  13. "github.com/urfave/cli"
  14. )
  15. const (
  16. dockerfileName = "Dockerfile"
  17. etcDir = "etc"
  18. yamlEtx = ".yaml"
  19. cstOffset = 60 * 60 * 8 // 8 hours offset for Chinese Standard Time
  20. )
  21. type Docker struct {
  22. Chinese bool
  23. GoRelPath string
  24. GoFile string
  25. ExeFile string
  26. HasPort bool
  27. Port int
  28. HasArgs bool
  29. Argument string
  30. }
  31. func DockerCommand(c *cli.Context) error {
  32. goFile := c.String("go")
  33. if len(goFile) == 0 {
  34. return errors.New("-go can't be empty")
  35. }
  36. if !util.FileExists(goFile) {
  37. return fmt.Errorf("file %q not found", goFile)
  38. }
  39. port := c.Int("port")
  40. if _, err := os.Stat(etcDir); os.IsNotExist(err) {
  41. return generateDockerfile(goFile, port)
  42. }
  43. cfg, err := findConfig(goFile, etcDir)
  44. if err != nil {
  45. return err
  46. }
  47. if err := generateDockerfile(goFile, port, "-f", "etc/"+cfg); err != nil {
  48. return err
  49. }
  50. projDir, ok := util.FindProjectPath(goFile)
  51. if ok {
  52. fmt.Printf("Hint: run \"docker build ...\" command in dir %q\n", projDir)
  53. fmt.Println(aurora.Green("Done."))
  54. }
  55. return nil
  56. }
  57. func findConfig(file, dir string) (string, error) {
  58. var files []string
  59. err := filepath.Walk(dir, func(path string, f os.FileInfo, _ error) error {
  60. if !f.IsDir() {
  61. if filepath.Ext(f.Name()) == yamlEtx {
  62. files = append(files, f.Name())
  63. }
  64. }
  65. return nil
  66. })
  67. if err != nil {
  68. return "", err
  69. }
  70. if len(files) == 0 {
  71. return "", errors.New("no yaml file")
  72. }
  73. name := strings.TrimSuffix(filepath.Base(file), ".go")
  74. for _, f := range files {
  75. if strings.Index(f, name) == 0 {
  76. return f, nil
  77. }
  78. }
  79. return files[0], nil
  80. }
  81. func generateDockerfile(goFile string, port int, args ...string) error {
  82. projPath, err := getFilePath(filepath.Dir(goFile))
  83. if err != nil {
  84. return err
  85. }
  86. if len(projPath) == 0 {
  87. projPath = "."
  88. } else {
  89. pos := strings.IndexByte(projPath, os.PathSeparator)
  90. if pos >= 0 {
  91. projPath = projPath[pos+1:]
  92. }
  93. }
  94. out, err := util.CreateIfNotExist(dockerfileName)
  95. if err != nil {
  96. return err
  97. }
  98. defer out.Close()
  99. text, err := ctlutil.LoadTemplate(category, dockerTemplateFile, dockerTemplate)
  100. if err != nil {
  101. return err
  102. }
  103. var builder strings.Builder
  104. for _, arg := range args {
  105. builder.WriteString(`, "` + arg + `"`)
  106. }
  107. _, offset := time.Now().Zone()
  108. t := template.Must(template.New("dockerfile").Parse(text))
  109. return t.Execute(out, Docker{
  110. Chinese: offset == cstOffset,
  111. GoRelPath: projPath,
  112. GoFile: goFile,
  113. ExeFile: util.FileNameWithoutExt(filepath.Base(goFile)),
  114. HasPort: port > 0,
  115. Port: port,
  116. HasArgs: builder.Len() > 0,
  117. Argument: builder.String(),
  118. })
  119. }
  120. func getFilePath(file string) (string, error) {
  121. wd, err := os.Getwd()
  122. if err != nil {
  123. return "", err
  124. }
  125. projPath, ok := util.FindGoModPath(filepath.Join(wd, file))
  126. if !ok {
  127. projPath, err = util.PathFromGoSrc()
  128. if err != nil {
  129. return "", errors.New("no go.mod found, or not in GOPATH")
  130. }
  131. }
  132. return projPath, nil
  133. }