docker.go 3.8 KB

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