Skip to content

Commit

Permalink
#32: fix bug by setting GOPATH as command level
Browse files Browse the repository at this point in the history
  • Loading branch information
kcmvp committed Dec 29, 2023
1 parent 0f97b82 commit 8592894
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 46 deletions.
4 changes: 4 additions & 0 deletions cmd/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import (
"os"
)

//func persistentPreRun(_ *cobra.Command, _ []string) {
// internal.CurProject().Setup(false)
//}

// builderCmd represents the base command when called without any subcommands
var builderCmd = &cobra.Command{
Use: "gob",
Expand Down
14 changes: 6 additions & 8 deletions cmd/builder_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
//go:build ignore

package cmd

import (
"fmt"
"github.com/kcmvp/gob/internal"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
Expand All @@ -23,10 +20,14 @@ type BuilderTestSuit struct {
func TestBuilderTestSuit(t *testing.T) {
suite.Run(t, &BuilderTestSuit{
start: time.Now().UnixNano(),
gopath: os.Getenv("GOPATH"),
gopath: internal.GoPath(),
})
}

func (suite *BuilderTestSuit) SetupTest() {
os.RemoveAll(suite.gopath)
}

func (suite *BuilderTestSuit) TestPersistentPreRun() {
builderCmd.PersistentPreRun(nil, nil)
hooks := lo.MapToSlice(internal.HookScripts, func(key string, _ string) string {
Expand All @@ -38,12 +39,9 @@ func (suite *BuilderTestSuit) TestPersistentPreRun() {
assert.True(suite.T(), info.ModTime().UnixNano() > suite.start)
}
}
//fmt.Println(internal.CurProject().Configuration())
fmt.Println(internal.CurProject().Plugins())
// test the missing plugins installation
lo.ForEach(internal.CurProject().Plugins(), func(plugin lo.Tuple4[string, string, string, string], index int) {
_, name := internal.NormalizePlugin(plugin.D)
_, err := os.Stat(filepath.Join(suite.gopath, "bin", name))
_, err := os.Stat(filepath.Join(suite.gopath, name))
assert.NoErrorf(suite.T(), err, "plugin should be insalled")
})
}
8 changes: 6 additions & 2 deletions cmd/initializer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ type InitializationTestSuite struct {

func TestInitializationTestSuit(t *testing.T) {
suite.Run(t, &InitializationTestSuite{
gopath: os.Getenv("GOPATH"),
gopath: internal.GoPath(),
})
}

func (suite *InitializationTestSuite) SetupTest() {
os.RemoveAll(suite.gopath)
}

func (suite *InitializationTestSuite) TestInitializeHook() {
initializerFunc(nil, nil)
file, err := os.Open(internal.CurProject().Configuration())
Expand All @@ -48,7 +52,7 @@ func (suite *InitializationTestSuite) TestInitializeHook() {
assert.True(suite.T(), hasAlias)
// verify plugin
var installed bool
filepath.WalkDir(filepath.Join(suite.gopath, "bin"), func(path string, d fs.DirEntry, err error) error {
filepath.WalkDir(suite.gopath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
Expand Down
7 changes: 4 additions & 3 deletions internal/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"github.com/fatih/color"
"github.com/samber/lo"
lop "github.com/samber/lo/parallel"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -114,8 +113,10 @@ func (project *Project) Setup(init bool) {
os.Remove(filepath.Join(CurProject().HookDir(), name))
}
}
// install missing plugins
lop.ForEach(CurProject().Plugins(), func(plugin lo.Tuple4[string, string, string, string], index int) {
if !init {
color.Cyan("checking plugins ......")
}
lo.ForEach(CurProject().Plugins(), func(plugin lo.Tuple4[string, string, string, string], index int) {
if !CurProject().PluginInstalled(plugin.D) {
CurProject().InstallPlugin(plugin.D, plugin.B, plugin.C)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (suite *GitHookTestSuite) TearDownSuite() {

func TestGitHookSuite(t *testing.T) {
suite.Run(t, &GitHookTestSuite{
gopath: os.Getenv("GOPATH"),
gopath: GoPath(),
start: time.Now().UnixNano(),
})
}
Expand Down
47 changes: 35 additions & 12 deletions internal/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,25 @@ type Project struct {

func TestCallee() (bool, string) {
var test bool
var method string
var file string
callers := make([]uintptr, 20)
n := runtime.Callers(0, callers)
frames := runtime.CallersFrames(callers[:n])
for {
frame, more := frames.Next()
//fmt.Printf("file name %s:%d\n", frame.File, frame.Line)
test = strings.HasSuffix(frame.File, "_test.go") && strings.HasPrefix(frame.Function, module)
// fmt.Printf("%s - %s \n", frame.File, frame.Function)
if test || !more {
method, _ = lo.Last(strings.Split(frame.Function, "."))
items := strings.Split(frame.File, "/")
items = lo.Map(items[len(items)-2:], func(item string, _ int) string {
return strings.ReplaceAll(item, ".go", "")
})
file = strings.Join(items, "-")
break
}
}
return test, method
// fmt.Println("****************")
return test, file
}

func (project *Project) HookDir() string {
Expand Down Expand Up @@ -207,7 +212,8 @@ func NormalizePlugin(url string) (base string, name string) {
// PluginInstalled return true if the plugin is installed
func (project *Project) PluginInstalled(url string) bool {
_, name := NormalizePlugin(url)
_, err := os.Stat(filepath.Join(os.Getenv("GOPATH"), "bin", name))
gopath := GoPath()
_, err := os.Stat(filepath.Join(gopath, name))
return err == nil
}

Expand Down Expand Up @@ -236,32 +242,35 @@ func (project *Project) PluginCommands() []lo.Tuple3[string, string, string] {
// InstallPlugin install the tool as gob plugin save it in gob.yml
func (project *Project) InstallPlugin(url string, aliasAndCommand ...string) error {
base, name := NormalizePlugin(url)
gopath := os.Getenv("GOPATH")
installed := project.PluginInstalled(url)
configured := project.PluginConfigured(url)
if installed && configured {
return PluginExists
} else {
var err error
if !installed {
// install only
tempGoPath, _ := os.MkdirTemp("", base)
os.Setenv("GOPATH", tempGoPath)
tempGoPath := TemporaryGoPath()
fmt.Printf("Installing %s ...... \n", url)
_, err = exec.Command("go", "install", url).CombinedOutput()
cmd := exec.Command("go", "install", url)
cmd.Env = lo.Map(os.Environ(), func(pair string, _ int) string {
if strings.HasPrefix(pair, "GOPATH=") {
return fmt.Sprintf("%s=%s", "GOPATH", tempGoPath)
}
return pair
})
_, err = cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to install %s: %v", url, err)
}
defer func() {
os.Setenv("GOPATH", gopath)
os.RemoveAll(tempGoPath)
}()
if err = filepath.WalkDir(tempGoPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && strings.HasPrefix(d.Name(), base) {
err = os.Rename(path, filepath.Join(gopath, "bin", name))
err = os.Rename(path, filepath.Join(GoPath(), name))
if err != nil {
return err
}
Expand Down Expand Up @@ -325,6 +334,20 @@ func Version() string {
return unknownVersion
}

func TemporaryGoPath() string {
dir, _ := os.MkdirTemp("", "test")
return dir
}

func GoPath() string {
if ok, method := TestCallee(); ok {
dir := filepath.Join(os.TempDir(), method, "bin")
os.MkdirAll(dir, 0o700) //nolint
return dir
}
return filepath.Join(os.Getenv("GOPATH"), "bin")
}

// Windows return true when current os is Windows
func Windows() bool {
return runtime.GOOS == "windows"
Expand Down
57 changes: 37 additions & 20 deletions internal/project_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package internal
import (
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"os"
"path/filepath"
"testing"
Expand All @@ -11,44 +12,60 @@ import (
var v6 = "golang.org/x/tools/cmd/digraph@v0.16.0"
var v7 = "golang.org/x/tools/cmd/digraph@v0.16.1"

func TestInstallPlugin(t *testing.T) {
type ProjectTestSuit struct {
suite.Suite
goPath string
}

func TestProjectTestSuit(t *testing.T) {
suite.Run(t, &ProjectTestSuit{
goPath: GoPath(),
})
}

func (suite *ProjectTestSuit) SetupTest() {
os.RemoveAll(suite.goPath)
println(suite.goPath)
}

func (suite *ProjectTestSuit) TestInstallPlugin() {
CurProject().LoadSettings()
cfg := CurProject().Configuration()
defer func() {
os.Remove(cfg)
}()
err := CurProject().InstallPlugin(v6, "callvis")
assert.NoError(t, err)
gopath := os.Getenv("GOPATH")
assert.NoError(suite.T(), err)
_, name := NormalizePlugin(v6)
_, err = os.Stat(filepath.Join(gopath, "bin", name))
assert.NoError(t, err)
info, err := os.Stat(filepath.Join(suite.goPath, name))
assert.NoError(suite.T(), err)
println(info.Name())
plugin, ok := lo.Find(CurProject().Plugins(), func(item lo.Tuple4[string, string, string, string]) bool {
return item.D == v6
})
assert.True(t, ok)
assert.Equal(t, "digraph", plugin.A)
assert.Equal(t, "callvis", plugin.B)
assert.Empty(t, plugin.C)
assert.Equal(t, v6, plugin.D)
assert.True(suite.T(), ok)
assert.Equal(suite.T(), "digraph", plugin.A)
assert.Equal(suite.T(), "callvis", plugin.B)
assert.Empty(suite.T(), plugin.C)
assert.Equal(suite.T(), v6, plugin.D)

// install same plugin again
err = CurProject().InstallPlugin(v6, "callvis")
assert.Error(t, err)
assert.Error(suite.T(), err)

// update the plugin
err = CurProject().InstallPlugin(v7, "callvisv7", "run")
assert.NoError(t, err)
assert.NoError(suite.T(), err)
plugin, ok = lo.Find(CurProject().Plugins(), func(item lo.Tuple4[string, string, string, string]) bool {
return item.D == v7
})
assert.True(t, ok)
assert.Equal(t, 1, len(CurProject().Plugins()))
assert.Equal(t, plugin.B, "callvisv7")
assert.Equal(t, plugin.C, "run")
assert.True(suite.T(), ok)
assert.Equal(suite.T(), 1, len(CurProject().Plugins()))
assert.Equal(suite.T(), plugin.B, "callvisv7")
assert.Equal(suite.T(), plugin.C, "run")
}

func TestVersion(t *testing.T) {
//assert.True(t, strings.HasPrefix(Version(), "v0.0.2"))
//assert.True(t, strings.Contains(Version(), "@"))
}
//func TestVersion(t *testing.T) {
// assert.True(t, strings.HasPrefix(Version(), "v0.0.2"))
// assert.True(t, strings.Contains(Version(), "@"))
//}

0 comments on commit 8592894

Please sign in to comment.