docker.go 3.3 KB

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