add dockerfile into template

This commit is contained in:
kevin
2020-11-09 18:02:16 +08:00
parent 3f389a55c2
commit cb9075b737
5 changed files with 78 additions and 70 deletions

View File

@@ -5,8 +5,10 @@ import (
"os"
"path/filepath"
"strings"
"text/template"
"github.com/tal-tech/go-zero/tools/goctl/gen"
"github.com/tal-tech/go-zero/tools/goctl/util"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli"
)
@@ -26,7 +28,7 @@ func DockerCommand(c *cli.Context) error {
return err
}
return gen.GenerateDockerfile(goFile, "-f", "etc/"+cfg)
return generateDockerfile(goFile, "-f", "etc/"+cfg)
}
func findConfig(file, dir string) (string, error) {
@@ -57,3 +59,56 @@ func findConfig(file, dir string) (string, error) {
return files[0], nil
}
func generateDockerfile(goFile string, args ...string) error {
projPath, err := getFilePath(filepath.Dir(goFile))
if err != nil {
return err
}
pos := strings.IndexByte(projPath, '/')
if pos >= 0 {
projPath = projPath[pos+1:]
}
out, err := util.CreateIfNotExist("Dockerfile")
if err != nil {
return err
}
defer out.Close()
text, err := ctlutil.LoadTemplate(category, dockerTemplateFile, dockerTemplate)
if err != nil {
return err
}
var builder strings.Builder
for _, arg := range args {
builder.WriteString(`, "` + arg + `"`)
}
t := template.Must(template.New("dockerfile").Parse(text))
return t.Execute(out, map[string]string{
"goRelPath": projPath,
"goFile": goFile,
"exeFile": util.FileNameWithoutExt(filepath.Base(goFile)),
"argument": builder.String(),
})
}
func getFilePath(file string) (string, error) {
wd, err := os.Getwd()
if err != nil {
return "", err
}
projPath, ok := util.FindGoModPath(filepath.Join(wd, file))
if !ok {
projPath, err = util.PathFromGoSrc()
if err != nil {
return "", errors.New("no go.mod found, or not in GOPATH")
}
}
return projPath, nil
}

View File

@@ -0,0 +1,44 @@
package docker
import (
"github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli"
)
const (
category = "docker"
dockerTemplateFile = "docker.tpl"
dockerTemplate = `FROM golang:alpine AS builder
LABEL stage=gobuilder
ENV CGO_ENABLED 0
ENV GOOS linux
ENV GOPROXY https://goproxy.cn,direct
WORKDIR /build/zero
COPY . .
COPY {{.goRelPath}}/etc /app/etc
RUN go build -ldflags="-s -w" -o /app/{{.exeFile}} {{.goRelPath}}/{{.goFile}}
FROM alpine
RUN apk update --no-cache
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
WORKDIR /app
COPY --from=builder /app/{{.exeFile}} /app/{{.exeFile}}
COPY --from=builder /app/etc /app/etc
CMD ["./{{.exeFile}}"{{.argument}}]
`
)
func GenTemplates(_ *cli.Context) error {
return util.InitTemplates(category, map[string]string{
dockerTemplateFile: dockerTemplate,
})
}