docker.go 2.8 KB

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