docker.go 3.2 KB

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