util: add path functions

add IsParentPath and IsSameOrParent path functions and related tests
This commit is contained in:
Simone Gotti 2019-04-30 16:24:04 +02:00
parent 27f84738d6
commit da2ac0ab38
2 changed files with 90 additions and 0 deletions

View File

@ -16,6 +16,7 @@ package util
import (
"path"
"strings"
)
// PathHierarchy return a slice of paths from the base path (root included as . or / ).
@ -51,3 +52,24 @@ func PathList(p string) []string {
}
return paths
}
// IsParentPath returns if the provided parent is parent of p
// parent and p paths must use slash "/" separators and must be absolute paths
func IsParentPath(parent, p string) bool {
// add ending / to avoid names with common prefix, like:
// /path/to
// /path/t
if !strings.HasSuffix(parent, "/") {
parent = parent + "/"
}
return strings.Contains(p, parent)
}
// IsParentPath returns if the provided parent the same path as p or a parent of p
// parent and p paths must use slash "/" separators
func IsSameOrParentPath(parent, p string) bool {
if parent == p {
return true
}
return IsParentPath(parent, p)
}

View File

@ -0,0 +1,68 @@
// Copyright 2019 Sorint.lab
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import "testing"
func TestIsParentPath(t *testing.T) {
tests := []struct {
parent string
p string
ok bool
}{
{"/", "/a", true},
{"/a", "/a", false},
{"/path/to", "/path/to/file", true},
{"/path/to/", "/path/to/file", true},
{"/path/to/f", "/path/to/file", false},
{"/path/t", "/path/to/file", false},
}
for _, tt := range tests {
t.Run("test is parent path", func(t *testing.T) {
ok := IsParentPath(tt.parent, tt.p)
if ok != tt.ok {
t.Errorf("got %t but wanted: %t a: %v, b: %v", ok, tt.ok, tt.parent, tt.p)
}
})
}
}
func TestIsSameOrParentPath(t *testing.T) {
tests := []struct {
parent string
p string
ok bool
}{
{"/", "/a", true},
{"/a", "/a", true},
{"/path/to", "/path/to/file", true},
{"/path/to/", "/path/to/file", true},
{"/path/to/f", "/path/to/file", false},
{"/path/t", "/path/to/file", false},
{"/path/to/file", "/path/to/file", true},
{"/path/to/file", "/path/to/file2", false},
{"/path/to/file", "/path/to/fil", false},
}
for _, tt := range tests {
t.Run("test is parent path", func(t *testing.T) {
ok := IsSameOrParentPath(tt.parent, tt.p)
if ok != tt.ok {
t.Errorf("got %t but wanted: %t a: %v, b: %v", ok, tt.ok, tt.parent, tt.p)
}
})
}
}