Fix determining the current executable under Homebrew for Linux
We need to use `os.Lstat` instead of `os.Stat` if we are going to manually inspect files for whether they are a symlink. On macOS, it looks like `os.Stat` returns information about the symlink itself.
This commit is contained in:
parent
2e6f202031
commit
7387346196
2 changed files with 60 additions and 1 deletions
|
|
@ -68,7 +68,7 @@ func executable(fallbackName string) string {
|
|||
if err != nil {
|
||||
continue
|
||||
}
|
||||
f, err := os.Stat(p)
|
||||
f, err := os.Lstat(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
|
|
|||
59
pkg/cmdutil/factory_test.go
Normal file
59
pkg/cmdutil/factory_test.go
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
package cmdutil
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_executable(t *testing.T) {
|
||||
testExe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
testExeName := filepath.Base(testExe)
|
||||
|
||||
// Create 3 extra PATH entries that each contain an executable with the same name as the running test
|
||||
// process. The first is a symlink, but to an unrelated executable, the second is a symlink to our test
|
||||
// process and thus represents the result we want, and the third one is an unrelated executable.
|
||||
dir := t.TempDir()
|
||||
bin1 := filepath.Join(dir, "bin1")
|
||||
bin1Exe := filepath.Join(bin1, testExeName)
|
||||
bin2 := filepath.Join(dir, "bin2")
|
||||
bin2Exe := filepath.Join(bin2, testExeName)
|
||||
bin3 := filepath.Join(dir, "bin3")
|
||||
bin3Exe := filepath.Join(bin3, testExeName)
|
||||
|
||||
if err := os.MkdirAll(bin1, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(bin2, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(bin3, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, err := os.OpenFile(bin3Exe, os.O_CREATE, 0755); err == nil {
|
||||
f.Close()
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(testExe, bin2Exe); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(bin3Exe, bin1Exe); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
oldPath := os.Getenv("PATH")
|
||||
t.Cleanup(func() {
|
||||
os.Setenv("PATH", oldPath)
|
||||
})
|
||||
os.Setenv("PATH", strings.Join([]string{bin1, bin2, bin3, oldPath}, string(os.PathListSeparator)))
|
||||
|
||||
if got := executable(""); got != bin2Exe {
|
||||
t.Errorf("executable() = %q, want %q", got, bin2Exe)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue