docker.go 3.0 KB

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