diff options
Diffstat (limited to 'crawl')
| -rw-r--r-- | crawl/crawl.go | 54 | ||||
| -rw-r--r-- | crawl/crawl_test.go | 58 |
2 files changed, 112 insertions, 0 deletions
diff --git a/crawl/crawl.go b/crawl/crawl.go new file mode 100644 index 0000000..dac6b19 --- /dev/null +++ b/crawl/crawl.go @@ -0,0 +1,54 @@ +package crawl + +import ( + "path" + "path/filepath" + "slices" + "strings" +) + +func Evaluated(loc string) (string, error) { + return filepath.EvalSymlinks(loc) +} + +func RichLocations(origin string) []string { + locs := Locations(origin) + + eval, err := Evaluated(origin) + if err == nil && eval != origin { + i := 0 + evaledLocations := Locations(eval) + var result []string + for i < len(locs) && i < len(evaledLocations) { + result = append(result, evaledLocations[i], locs[i]) + } + result = slices.Compact(result) + return result + } + return locs +} + +func Locations(origin string) []string { + origin = path.Clean(origin) + var locs = []string{ + origin, + } + for { + previous := locs[len(locs)-1] + parent := ParentDir(previous) + if previous == parent { + break + } + locs = append(locs, parent) + } + return locs +} + +func ParentDir(origin string) string { + trimmedOrigin := strings.TrimSuffix(origin, "/") + dir, _ := path.Split(trimmedOrigin) + if dir == "" { + return origin + } + return dir +} diff --git a/crawl/crawl_test.go b/crawl/crawl_test.go new file mode 100644 index 0000000..88b70f1 --- /dev/null +++ b/crawl/crawl_test.go @@ -0,0 +1,58 @@ +package crawl + +import ( + "github.com/stretchr/testify/assert" + "io/fs" + "testing" +) + +func TestParentDir(t *testing.T) { + input := "/var/lib" + parent := ParentDir(input) + assert.Equal(t, parent, "/var/") +} + +func TestParentDir_TrailingSlash(t *testing.T) { + input := "/var/lib/" + parent := ParentDir(input) + assert.Equal(t, parent, "/var/") +} + +func TestParentDir_ToRoot(t *testing.T) { + input := "/var/" + parent := ParentDir(input) + assert.Equal(t, parent, "/") +} +func TestParentDir_ToRoot_NoTrailingSlash(t *testing.T) { + input := "/var" + parent := ParentDir(input) + assert.Equal(t, parent, "/") +} + +func TestParentDir_WithoutParent(t *testing.T) { + input := "/" + parent := ParentDir(input) + assert.Equal(t, parent, "/") +} + +func TestLocations(t *testing.T) { + input := "/var/lib/uwu/asdf" + locs := Locations(input) + assert.Equal(t, locs, []string{"/var/lib/uwu/asdf", "/var/lib/uwu/", "/var/lib/", "/var/", "/"}) +} + +func TestLocations_WithDotPath(t *testing.T) { + input := "/root/./second/asdf/../third" + locs := Locations(input) + assert.Equal(t, locs, []string{"/root/second/third", "/root/second/", "/root/", "/"}) +} + +func TestLocations_HighestFirst(t *testing.T) { + input := "/one/two/three" + locs := Locations(input) + assert.Equal(t, locs[0], "/one/two/three") +} + +func Test(t *testing.T) { + assert.True(t, fs.ValidPath("asdf/hjkl")) +} |
