gaper/builder.go

67 lines
1.4 KiB
Go
Raw Normal View History

package gaper
2018-06-16 19:22:21 -05:00
import (
"fmt"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
2018-06-20 21:04:16 -05:00
// Builder is a interface for the build process
2018-06-16 19:22:21 -05:00
type Builder interface {
Build() error
Binary() string
}
type builder struct {
dir string
binary string
wd string
buildArgs []string
}
2018-06-20 21:04:16 -05:00
// NewBuilder creates a new builder
2018-06-16 19:22:21 -05:00
func NewBuilder(dir string, bin string, wd string, buildArgs []string) Builder {
2018-06-20 20:40:09 -05:00
// resolve bin name by current folder name
if bin == "" {
bin = filepath.Base(wd)
2018-06-16 19:22:21 -05:00
}
// does not work on Windows without the ".exe" extension
if runtime.GOOS == OSWindows {
// check if it already has the .exe extension
if !strings.HasSuffix(bin, ".exe") {
bin += ".exe"
}
}
return &builder{dir: dir, binary: bin, wd: wd, buildArgs: buildArgs}
}
2018-06-20 21:04:16 -05:00
// Binary returns its build binary's path
2018-06-16 19:22:21 -05:00
func (b *builder) Binary() string {
return b.binary
}
2018-06-20 21:04:16 -05:00
// Build the Golang project set for this builder
2018-06-16 19:22:21 -05:00
func (b *builder) Build() error {
logger.Info("Building program")
args := append([]string{"go", "build", "-o", filepath.Join(b.wd, b.binary)}, b.buildArgs...)
logger.Debug("Build command", args)
command := exec.Command(args[0], args[1:]...) // nolint gas
command.Dir = b.dir
output, err := command.CombinedOutput()
if err != nil {
return fmt.Errorf("build failed with %v\n%s", err, output)
2018-06-16 19:22:21 -05:00
}
2018-06-20 20:40:09 -05:00
if !command.ProcessState.Success() {
return fmt.Errorf("error building: %s", output)
2018-06-16 19:22:21 -05:00
}
return nil
}