mirror of
https://github.com/spf13/cobra
synced 2024-11-24 22:57:12 +00:00
Changed string comparison for child path to use filepath.Rel
This commit is contained in:
parent
37c3f80603
commit
15e8c75e0b
2 changed files with 39 additions and 1 deletions
|
@ -100,13 +100,26 @@ func guessCmdDir() string {
|
|||
func guessImportPath() string {
|
||||
guessProjectPath()
|
||||
|
||||
if !strings.HasPrefix(projectPath, getSrcPath()) {
|
||||
if !inPath(getSrcPath(), projectPath) {
|
||||
er("Cobra only supports project within $GOPATH")
|
||||
}
|
||||
|
||||
return filepath.ToSlash(filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath())))
|
||||
}
|
||||
|
||||
func inPath(srcPath, projectPath string) bool {
|
||||
relPath, err := filepath.Rel(srcPath, projectPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, d := range filepath.SplitList(relPath) {
|
||||
if d == ".." || d == "." {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getSrcPath() string {
|
||||
return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator)
|
||||
}
|
||||
|
|
|
@ -38,3 +38,28 @@ func TestProjectPath(t *testing.T) {
|
|||
checkGuess(t, "/bar/foo/commands", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "github.com/spf13/hugo/../hugo", "", filepath.Join("github.com", "spf13", "hugo"))
|
||||
}
|
||||
|
||||
func TestInPath(t *testing.T) {
|
||||
cases := []struct {
|
||||
Src string
|
||||
Prj string
|
||||
InPath bool
|
||||
}{
|
||||
{"/bar/foo", "/bar/foo", false},
|
||||
{"/bar/foo", "/bar/foo/baz", true},
|
||||
{"/bar/foo/baz", "/bar/foo", false},
|
||||
{"C:/bar/foo", "c:/bar/foo/baz", true},
|
||||
{"c:\\bar\\foo", "C:\\bar\\foo", false},
|
||||
{"c:\\bar\\..\\bar\\foo", "C:\\bar\\foo\\baz", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
ip := inPath(tc.Src, tc.Prj)
|
||||
if tc.InPath != ip {
|
||||
if tc.InPath {
|
||||
t.Errorf("Unexpected %s determined as inside %s", tc.Prj, tc.Src)
|
||||
} else {
|
||||
t.Errorf("Unexpected %s not determined as inside %s", tc.Prj, tc.Src)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue