diff --git a/app/paths/paths.go b/app/paths/paths.go index d6c58ebe2..0fabd9f7b 100644 --- a/app/paths/paths.go +++ b/app/paths/paths.go @@ -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 { diff --git a/app/paths/paths_test.go b/app/paths/paths_test.go index ba9a46db1..d02ab0698 100644 --- a/app/paths/paths_test.go +++ b/app/paths/paths_test.go @@ -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) + } +}