feat: [CODE-2943]: Add 'Depth' method in 'paths' package (#3211)

BT-10437
Johannes Batzill 2024-12-30 19:55:10 +00:00 committed by Harness
parent 3d5feb0315
commit 819597fa76
2 changed files with 49 additions and 1 deletions

View File

@ -105,12 +105,23 @@ func Concatenate(paths ...string) string {
}
// Segments returns all segments of the path
// e.g. /space1/space2/space3 -> [space1, space2, space3].
// e.g. space1/space2/space3 -> [space1, space2, space3].
func Segments(path string) []string {
path = strings.Trim(path, types.PathSeparatorAsString)
return strings.Split(path, types.PathSeparatorAsString)
}
// Depth returns the depth of the path.
// e.g. space1/space2 -> 2.
func Depth(path string) int {
path = strings.Trim(path, types.PathSeparatorAsString)
if len(path) == 0 {
return 0
}
return strings.Count(path, types.PathSeparatorAsString) + 1
}
// IsAncesterOf returns true iff 'path' is an ancestor of 'other' or they are the same.
// e.g. other = path(/.*).
func IsAncesterOf(path string, other string) bool {

View File

@ -139,3 +139,40 @@ func Test_Concatenate(t *testing.T) {
assert.Equal(t, tt.want, got, "path isn't matching for %v", tt.in)
}
}
func Test_Depth(t *testing.T) {
type testCase struct {
in string
want int
}
tests := []testCase{
{
in: "",
want: 0,
},
{
in: "/",
want: 0,
},
{
in: "a",
want: 1,
},
{
in: "/a/",
want: 1,
},
{
in: "a/b",
want: 2,
},
{
in: "/a/b/c/d/e/f/",
want: 6,
},
}
for _, tt := range tests {
got := Depth(tt.in)
assert.Equal(t, tt.want, got, "depth isn't matching for %q", tt.in)
}
}