docker.go 3.6 KB

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