docker.go 3.7 KB

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