Skip to content

Commit ac394dc

Browse files
committed
Go: Better check for path prefixes
1 parent b1e0bc0 commit ac394dc

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

go/extractor/project/project.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ func getBuildRoots(emitDiagnostics bool) (goWorkspaces []GoWorkspace, totalModul
481481
// Determines whether `str` starts with any of `prefixes`.
482482
func startsWithAnyOf(str string, prefixes []string) bool {
483483
for _, prefix := range prefixes {
484-
if strings.HasPrefix(str, prefix) {
484+
if relPath, err := filepath.Rel(str, prefix); err == nil && !strings.HasPrefix(relPath, "..") {
485485
return true
486486
}
487487
}

go/extractor/project/project_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package project
2+
3+
import (
4+
"path/filepath"
5+
"testing"
6+
)
7+
8+
func testStartsWithAnyOf(t *testing.T, path string, prefix string, expectation bool) {
9+
result := startsWithAnyOf(path, []string{prefix})
10+
if result != expectation {
11+
t.Errorf("Expected startsWithAnyOf(%s, %s) to be %t, but it is %t.", path, prefix, expectation, result)
12+
}
13+
}
14+
15+
func TestStartsWithAnyOf(t *testing.T) {
16+
testStartsWithAnyOf(t, ".", ".", true)
17+
testStartsWithAnyOf(t, ".", "dir", true)
18+
testStartsWithAnyOf(t, ".", filepath.Join("foo", "bar"), true)
19+
testStartsWithAnyOf(t, "dir", "dir", true)
20+
testStartsWithAnyOf(t, "foo", filepath.Join("foo", "bar"), true)
21+
testStartsWithAnyOf(t, filepath.Join("foo", "bar"), filepath.Join("foo", "bar"), true)
22+
testStartsWithAnyOf(t, filepath.Join("foo", "bar"), filepath.Join("foo", "bar", "baz"), true)
23+
24+
testStartsWithAnyOf(t, filepath.Join("foo", "bar"), "foo", false)
25+
testStartsWithAnyOf(t, filepath.Join("foo", "bar"), "bar", false)
26+
testStartsWithAnyOf(t, filepath.Join("foo", "bar"), filepath.Join("foo", "baz"), false)
27+
}

0 commit comments

Comments
 (0)