From 15e8c75e0b21dcbc26057dc71196ab13150d4295 Mon Sep 17 00:00:00 2001 From: Elliot Morrison-Reed Date: Thu, 25 Aug 2016 23:06:56 +0200 Subject: [PATCH] Changed string comparison for child path to use filepath.Rel --- cobra/cmd/helpers.go | 15 ++++++++++++++- cobra/cmd/helpers_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/cobra/cmd/helpers.go b/cobra/cmd/helpers.go index 7cd3be18..2c08dc1b 100644 --- a/cobra/cmd/helpers.go +++ b/cobra/cmd/helpers.go @@ -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) } diff --git a/cobra/cmd/helpers_test.go b/cobra/cmd/helpers_test.go index bd0f7595..668850f1 100644 --- a/cobra/cmd/helpers_test.go +++ b/cobra/cmd/helpers_test.go @@ -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) + } + } + } +}