feat: support build Dockerfile from current dir (#2021)

master
Kevin Wan 2 years ago committed by GitHub
parent 86d70317bf
commit 9eea311a4d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -3,6 +3,7 @@ package docker
import "github.com/spf13/cobra"
var (
varExeName string
varStringGo string
varStringBase string
varIntPort int
@ -21,6 +22,7 @@ var (
)
func init() {
Cmd.Flags().StringVar(&varExeName, "exe", "", "The executable name in the built image")
Cmd.Flags().StringVar(&varStringGo, "go", "", "The file that contains main function")
Cmd.Flags().StringVar(&varStringBase, "base", "scratch", "The base image to build the docker image, default scratch")
Cmd.Flags().IntVar(&varIntPort, "port", 0, "The port to expose, default none")

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"text/template"
@ -24,6 +25,7 @@ const (
// Docker describes a dockerfile
type Docker struct {
Chinese bool
GoMainFrom string
GoRelPath string
GoFile string
ExeFile string
@ -65,11 +67,7 @@ func dockerCommand(_ *cobra.Command, _ []string) (err error) {
pathx.RegisterGoctlHome(home)
}
if len(goFile) == 0 {
return errors.New("-go can't be empty")
}
if !pathx.FileExists(goFile) {
if len(goFile) > 0 && !pathx.FileExists(goFile) {
return fmt.Errorf("file %q not found", goFile)
}
@ -126,10 +124,14 @@ func findConfig(file, dir string) (string, error) {
}
func generateDockerfile(goFile, base string, port int, version, timezone string, args ...string) error {
projPath, err := getFilePath(filepath.Dir(goFile))
var projPath string
var err error
if len(goFile) > 0 {
projPath, err = getFilePath(filepath.Dir(goFile))
if err != nil {
return err
}
}
if len(projPath) == 0 {
projPath = "."
@ -151,12 +153,27 @@ func generateDockerfile(goFile, base string, port int, version, timezone string,
builder.WriteString(`, "` + arg + `"`)
}
var exeName string
if len(varExeName) > 0 {
exeName = varExeName
} else if len(goFile) > 0 {
exeName = pathx.FileNameWithoutExt(filepath.Base(goFile))
} else {
absPath, err := filepath.Abs(projPath)
if err != nil {
return err
}
exeName = filepath.Base(absPath)
}
t := template.Must(template.New("dockerfile").Parse(text))
return t.Execute(out, Docker{
Chinese: env.InChina(),
GoMainFrom: path.Join(projPath, goFile),
GoRelPath: projPath,
GoFile: goFile,
ExeFile: pathx.FileNameWithoutExt(filepath.Base(goFile)),
ExeFile: exeName,
BaseImage: base,
HasPort: port > 0,
Port: port,

@ -15,7 +15,7 @@ ADD go.sum .
RUN go mod download
COPY . .
{{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc
{{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}}
{{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoMainFrom}}
FROM {{.BaseImage}}

Loading…
Cancel
Save