docker.go 3.4 KB

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