github.com/annwntech/go-micro/v2@v2.9.5/runtime/local/build/go/golang.go (about)

     1  // Package golang is a go package manager
     2  package golang
     3  
     4  import (
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  
     9  	"github.com/annwntech/go-micro/v2/runtime/local/build"
    10  )
    11  
    12  type Builder struct {
    13  	Options build.Options
    14  	Cmd     string
    15  	Path    string
    16  }
    17  
    18  // whichGo locates the go command
    19  func whichGo() string {
    20  	// check GOROOT
    21  	if gr := os.Getenv("GOROOT"); len(gr) > 0 {
    22  		return filepath.Join(gr, "bin", "go")
    23  	}
    24  
    25  	// check path
    26  	for _, p := range filepath.SplitList(os.Getenv("PATH")) {
    27  		bin := filepath.Join(p, "go")
    28  		if _, err := os.Stat(bin); err == nil {
    29  			return bin
    30  		}
    31  	}
    32  
    33  	// best effort
    34  	return "go"
    35  }
    36  
    37  func (g *Builder) Build(s *build.Source) (*build.Package, error) {
    38  	binary := filepath.Join(g.Path, s.Repository.Name)
    39  	source := filepath.Join(s.Repository.Path, s.Repository.Name)
    40  
    41  	cmd := exec.Command(g.Cmd, "build", "-o", binary, source)
    42  	if err := cmd.Run(); err != nil {
    43  		return nil, err
    44  	}
    45  	return &build.Package{
    46  		Name:   s.Repository.Name,
    47  		Path:   binary,
    48  		Type:   "go",
    49  		Source: s,
    50  	}, nil
    51  }
    52  
    53  func (g *Builder) Clean(b *build.Package) error {
    54  	binary := filepath.Join(b.Path, b.Name)
    55  	return os.Remove(binary)
    56  }
    57  
    58  func NewBuild(opts ...build.Option) build.Builder {
    59  	options := build.Options{
    60  		Path: os.TempDir(),
    61  	}
    62  	for _, o := range opts {
    63  		o(&options)
    64  	}
    65  	return &Builder{
    66  		Options: options,
    67  		Cmd:     whichGo(),
    68  		Path:    options.Path,
    69  	}
    70  }