docker.go 3.6 KB

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