docker.go 3.1 KB

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