micro/build/golang/golang.go

76 lines
1.3 KiB
Go
Raw Normal View History

2019-05-31 02:26:34 +03:00
// Package golang is a go package manager
package golang
import (
"os"
"os/exec"
"path/filepath"
"github.com/micro/go-micro/v3/build"
2019-05-31 02:26:34 +03:00
)
type goBuild struct {
2019-11-19 19:09:43 +03:00
Options build.Options
2019-05-31 02:26:34 +03:00
Cmd string
Path string
}
// whichGo locates the go command
func whichGo() string {
// check GOROOT
if gr := os.Getenv("GOROOT"); len(gr) > 0 {
return filepath.Join(gr, "bin", "go")
}
// check path
for _, p := range filepath.SplitList(os.Getenv("PATH")) {
bin := filepath.Join(p, "go")
if _, err := os.Stat(bin); err == nil {
return bin
}
}
// best effort
return "go"
}
func (g *goBuild) Package(name string, src *build.Source) (*build.Package, error) {
binary := filepath.Join(g.Path, name)
source := src.Path
2019-05-31 02:26:34 +03:00
cmd := exec.Command(g.Cmd, "build", "-o", binary, source)
if err := cmd.Run(); err != nil {
return nil, err
}
2019-11-19 19:09:43 +03:00
return &build.Package{
Name: name,
2019-05-31 02:26:34 +03:00
Path: binary,
Type: g.String(),
Source: src,
2019-05-31 02:26:34 +03:00
}, nil
}
func (g *goBuild) Remove(b *build.Package) error {
2019-05-31 02:26:34 +03:00
binary := filepath.Join(b.Path, b.Name)
return os.Remove(binary)
}
func (g *goBuild) String() string {
return "golang"
}
func NewBuild(opts ...build.Option) build.Build {
2019-11-19 19:09:43 +03:00
options := build.Options{
2019-05-31 02:26:34 +03:00
Path: os.TempDir(),
}
for _, o := range opts {
o(&options)
}
return &goBuild{
2019-05-31 02:26:34 +03:00
Options: options,
Cmd: whichGo(),
Path: options.Path,
}
}