Skip to content

Commit 2f9054f

Browse files
authored
Merge pull request #44 from sttts/sttts-has-prefix-colon
🐛 HasPrefix: properly separate by :
2 parents 72747f7 + c31a2f0 commit 2f9054f

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

path.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,14 @@ func (p *Path) UnmarshalJSON(data []byte) error {
159159

160160
// HasPrefix tests whether the path begins with the other path.
161161
func (p Path) HasPrefix(other Path) bool {
162-
return strings.HasPrefix(p.value, other.value)
162+
if p == other || other.Empty() {
163+
return true
164+
}
165+
if strings.HasSuffix(other.String(), separator) {
166+
// this is not a valid path, but we should have a defined behaviour
167+
return strings.HasPrefix(p.value, other.value)
168+
}
169+
return strings.HasPrefix(p.value, other.value+separator)
163170
}
164171

165172
// Equal checks if the path is the same as the other path.

path_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,28 @@ func TestPath_Name(t *testing.T) {
137137
})
138138
}
139139
}
140+
141+
func TestPathHasPrefix(t *testing.T) {
142+
tests := []struct {
143+
name string
144+
path Path
145+
other Path
146+
want bool
147+
}{
148+
{"empty both", NewPath(""), NewPath(""), true},
149+
{"empty other", NewPath("foo"), NewPath(""), true},
150+
{"empty path", NewPath(""), NewPath("foo"), false},
151+
{"equal", NewPath("foo"), NewPath("foo"), true},
152+
{"prefix", NewPath("foo:bar"), NewPath("foo"), true},
153+
{"string prefix only", NewPath("foooo:bar"), NewPath("foo"), false},
154+
{"not prefix", NewPath("foo"), NewPath("foo:bar"), false},
155+
{"other ending in :", NewPath("foo:bar"), NewPath("foo:"), true}, // "foo:" is not a valid path, but we should have a defined behaviour
156+
}
157+
for _, tt := range tests {
158+
t.Run(tt.name, func(t *testing.T) {
159+
if got := tt.path.HasPrefix(tt.other); got != tt.want {
160+
t.Errorf("HasPrefix() = %v, want %v", got, tt.want)
161+
}
162+
})
163+
}
164+
}

0 commit comments

Comments
 (0)