Skip to content

Commit

Permalink
add Output configuration support for command gf build in cross-buil…
Browse files Browse the repository at this point in the history
…dling binary scenario (#3120)
  • Loading branch information
gqcn committed Nov 1, 2023
1 parent 9393072 commit 3bbc0fd
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions cmd/gf/internal/cmd/cmd_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e
if gfile.Exists("main.go") {
file = "main.go"
} else {
mlog.Fatal("build file path cannot be empty")
mlog.Fatal("build file path is empty or main.go not found in current working directory")
}
}
if in.Name == "" {
Expand Down Expand Up @@ -254,27 +254,43 @@ func (c cBuild) Index(ctx context.Context, in cBuildInput) (out *cBuildOutput, e
continue
}
if len(customSystems) == 0 && len(customArches) == 0 {
// Single binary building, output the binary to current working folder.
// For example:
// `gf build`
// `gf build -o main.exe`
if runtime.GOOS == "windows" {
ext = ".exe"
}
// Single binary building, output the binary to current working folder.
output := ""
var outputPath string
if len(in.Output) > 0 {
output = "-o " + in.Output + ext
outputPath = "-o " + in.Output
} else {
output = "-o " + in.Name + ext
outputPath = "-o " + in.Name + ext
}
cmd = fmt.Sprintf(`go build %s -ldflags "%s" %s %s`, output, ldFlags, in.Extra, file)
cmd = fmt.Sprintf(
`go build %s -ldflags "%s" %s %s`,
outputPath, ldFlags, in.Extra, file,
)
} else {
// Cross-building, output the compiled binary to specified path.
if system == "windows" {
ext = ".exe"
}
genv.MustSet("GOOS", system)
genv.MustSet("GOARCH", arch)

var outputPath string
if len(in.Output) > 0 {
outputPath = "-o " + in.Output
} else {
outputPath = fmt.Sprintf(
"-o %s/%s/%s%s",
in.Path, system+"_"+arch, in.Name, ext,
)
}
cmd = fmt.Sprintf(
`go build -o %s/%s/%s%s -ldflags "%s" %s%s`,
in.Path, system+"_"+arch, in.Name, ext, ldFlags, in.Extra, file,
`GOOS=%s GOARCH=%s go build %s -ldflags "%s" %s%s`,
system, arch, outputPath, ldFlags, in.Extra, file,
)
}
mlog.Debug(cmd)
Expand Down

0 comments on commit 3bbc0fd

Please sign in to comment.