Skip to content

Commit

Permalink
feat: add mgtool.GoInstallWithModfile
Browse files Browse the repository at this point in the history
  • Loading branch information
odsod committed Jan 17, 2022
1 parent a041c70 commit c7d525a
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions mgtool/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,52 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/go-logr/logr"
"github.com/magefile/mage/sh"
"go.einride.tech/mage-tools/mgpath"
)

func GoInstall(ctx context.Context, goPkg, version string) (string, error) {
executable := filepath.Join(mgpath.Tools(), "go", goPkg, version, "bin", filepath.Base(goPkg))
func GoInstall(ctx context.Context, pkg, version string) (string, error) {
executable := filepath.Join(mgpath.Tools(), "go", pkg, version, filepath.Base(pkg))
// Check if executable already exist
if _, err := os.Stat(executable); err == nil {
symlink, err := CreateSymlink(executable)
if err != nil {
return "", err
}
return symlink, nil
}
pkgVersion := fmt.Sprintf("%s@%s", pkg, version)
logr.FromContextOrDiscard(ctx).Info("building...", "pkg", pkgVersion)
if err := sh.RunWithV(
map[string]string{"GOBIN": filepath.Dir(executable)},
"go",
"install",
pkgVersion,
); err != nil {
return "", err
}
symlink, err := CreateSymlink(executable)
if err != nil {
return "", err
}
return symlink, nil
}

func GoInstallWithModfile(ctx context.Context, pkg, file string) (string, error) {
cleanup := mgpath.ChangeWorkDir(filepath.Dir(file))
defer cleanup()
version, err := sh.Output("go", "list", "-f", "{{.Module.Version}}", pkg)
if err != nil {
return "", err
}
version = strings.TrimSpace(version)
if version == "" {
return "", fmt.Errorf("failed to determine version of package %s", pkg)
}
executable := filepath.Join(mgpath.Tools(), "go", pkg, version, filepath.Base(pkg))
// Check if executable already exist
if _, err := os.Stat(executable); err == nil {
symlink, err := CreateSymlink(executable)
Expand All @@ -22,10 +59,13 @@ func GoInstall(ctx context.Context, goPkg, version string) (string, error) {
}
return symlink, nil
}
goPkgVer := fmt.Sprintf("%s@%s", goPkg, version)
os.Setenv("GOBIN", filepath.Dir(executable))
logr.FromContextOrDiscard(ctx).Info(fmt.Sprintf("Building %s...", goPkgVer))
if err := sh.RunV("go", "install", goPkgVer); err != nil {
logr.FromContextOrDiscard(ctx).Info("building", "pkg", pkg)
if err := sh.RunWithV(
map[string]string{"GOBIN": filepath.Dir(executable)},
"go",
"install",
pkg,
); err != nil {
return "", err
}
symlink, err := CreateSymlink(executable)
Expand Down

0 comments on commit c7d525a

Please sign in to comment.