From 9f580863da1c9ae486a61d6952f4ec8adecd069b Mon Sep 17 00:00:00 2001 From: Simone Gotti Date: Mon, 9 Sep 2019 14:46:39 +0200 Subject: [PATCH] util: Fix PathList output when path ends with slashes Fix PathList when a path ends with one or more slashes and add related tests. --- internal/util/path.go | 1 + internal/util/path_test.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/internal/util/path.go b/internal/util/path.go index 47266ab..de5cd00 100644 --- a/internal/util/path.go +++ b/internal/util/path.go @@ -42,6 +42,7 @@ func PathHierarchy(p string) []string { // I.E. for a path like "path/to/file" or "/path/to/file" it'll return a slice of these elements: // "path", "to", "file" func PathList(p string) []string { + p = path.Clean(p) paths := []string{} for { paths = append([]string{path.Base(p)}, paths...) diff --git a/internal/util/path_test.go b/internal/util/path_test.go index 60a8825..945ead7 100644 --- a/internal/util/path_test.go +++ b/internal/util/path_test.go @@ -14,7 +14,39 @@ package util -import "testing" +import ( + "reflect" + "testing" +) + +func TestPathList(t *testing.T) { + tests := []struct { + in string + out []string + }{ + {"/path", []string{"path"}}, + {"path", []string{"path"}}, + {"/path/", []string{"path"}}, + {"path/", []string{"path"}}, + {"//path/", []string{"path"}}, + {"///path///", []string{"path"}}, + {"/path/to/file", []string{"path", "to", "file"}}, + {"path/to/file", []string{"path", "to", "file"}}, + {"/path/to/file/", []string{"path", "to", "file"}}, + {"path/to/file/", []string{"path", "to", "file"}}, + {"path/to/file///", []string{"path", "to", "file"}}, + {"///path///to///file///", []string{"path", "to", "file"}}, + } + + for _, tt := range tests { + t.Run("test is parent path", func(t *testing.T) { + out := PathList(tt.in) + if !reflect.DeepEqual(out, tt.out) { + t.Errorf("got %q but wanted: %q", out, tt.out) + } + }) + } +} func TestIsParentPath(t *testing.T) { tests := []struct {