added osutils.IsProbablyGoRun
This commit is contained in:
@@ -63,3 +63,17 @@ func YesNoPrompt(message string, fallback bool) bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IsProbablyGoRun loosely checks if the current executable is running
|
||||
// as a result of "go run".
|
||||
func IsProbablyGoRun() bool {
|
||||
runDirs := []string{os.TempDir(), os.Getenv("GOCACHE")}
|
||||
|
||||
for _, dir := range runDirs {
|
||||
if dir != "" && strings.HasPrefix(os.Args[0], dir) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -64,3 +64,40 @@ func TestYesNoPrompt(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsProbablyGoRun(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
arg string
|
||||
envs map[string]string
|
||||
expected bool
|
||||
}{
|
||||
{"", nil, false},
|
||||
{"a/b/c", nil, false},
|
||||
{"/a/b/c", nil, false},
|
||||
{"/a/b/c", map[string]string{"GOCACHE": "/b/"}, false},
|
||||
{"/a/b/c", map[string]string{"GOCACHE": "/a/"}, true},
|
||||
{os.TempDir() + "/a/b/c", nil, true},
|
||||
}
|
||||
|
||||
originalArgs := os.Args
|
||||
defer func() {
|
||||
os.Args = originalArgs
|
||||
}()
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.arg, func(t *testing.T) {
|
||||
os.Args = []string{s.arg}
|
||||
|
||||
for k, v := range s.envs {
|
||||
defer os.Setenv(k, os.Getenv(k))
|
||||
os.Setenv(k, v)
|
||||
}
|
||||
|
||||
result := osutils.IsProbablyGoRun()
|
||||
|
||||
if result != s.expected {
|
||||
t.Fatalf("Expected %v, got %v", s.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user