docker.go 3.2 KB

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