gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/runtime/source/go/golang.go (about)

     1  // Package golang is a source for Go
     2  package golang
     3  
     4  import (
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"gitee.com/liuxuezhan/go-micro-v1.18.0/runtime/source"
    11  )
    12  
    13  type Source struct {
    14  	Options source.Options
    15  	// Go Command
    16  	Cmd  string
    17  	Path string
    18  }
    19  
    20  func (g *Source) Fetch(url string) (*source.Repository, error) {
    21  	purl := url
    22  
    23  	if parts := strings.Split(url, "://"); len(parts) > 1 {
    24  		purl = parts[len(parts)-1]
    25  	}
    26  
    27  	// name of repo
    28  	name := filepath.Base(url)
    29  	// local path of repo
    30  	path := filepath.Join(g.Path, purl)
    31  	args := []string{"get", "-d", url, path}
    32  
    33  	cmd := exec.Command(g.Cmd, args...)
    34  	if err := cmd.Run(); err != nil {
    35  		return nil, err
    36  	}
    37  	return &source.Repository{
    38  		Name: name,
    39  		Path: path,
    40  		URL:  url,
    41  	}, nil
    42  }
    43  
    44  // Commit is not yet supported
    45  func (g *Source) Commit(r *source.Repository) error {
    46  	return nil
    47  }
    48  
    49  func (g *Source) String() string {
    50  	return "golang"
    51  }
    52  
    53  // whichGo locates the go command
    54  func whichGo() string {
    55  	// check GOROOT
    56  	if gr := os.Getenv("GOROOT"); len(gr) > 0 {
    57  		return filepath.Join(gr, "bin", "go")
    58  	}
    59  
    60  	// check path
    61  	for _, p := range filepath.SplitList(os.Getenv("PATH")) {
    62  		bin := filepath.Join(p, "go")
    63  		if _, err := os.Stat(bin); err == nil {
    64  			return bin
    65  		}
    66  	}
    67  
    68  	// best effort
    69  	return "go"
    70  }
    71  
    72  func NewSource(opts ...source.Option) source.Source {
    73  	options := source.Options{
    74  		Path: os.TempDir(),
    75  	}
    76  	for _, o := range opts {
    77  		o(&options)
    78  	}
    79  
    80  	cmd := whichGo()
    81  	path := options.Path
    82  
    83  	// point of no return
    84  	if len(cmd) == 0 {
    85  		panic("Could not find Go executable")
    86  	}
    87  
    88  	return &Source{
    89  		Options: options,
    90  		Cmd:     cmd,
    91  		Path:    path,
    92  	}
    93  }