tpl/path: Add path.Clean
authorBrad <brad.cypert@gmail.com>
Tue, 5 Oct 2021 14:15:10 +0000 (10:15 -0400)
committerGitHub <noreply@github.com>
Tue, 5 Oct 2021 14:15:10 +0000 (16:15 +0200)
 Fixes #8885

tpl/path/path.go
tpl/path/path_test.go

index 6410552240a60ad022b2a89ad12b3dd49d6efa52..ec50cff79215b860c6d7178cc3ce49911724924a 100644 (file)
@@ -144,3 +144,15 @@ func (ns *Namespace) Join(elements ...interface{}) (string, error) {
        }
        return _path.Join(pathElements...), nil
 }
+
+// Clean replaces the separators used with standard slashes and then
+// extraneous slashes are removed.
+func (ns *Namespace) Clean(path interface{}) (string, error) {
+       spath, err := cast.ToStringE(path)
+
+       if err != nil {
+               return "", err
+       }
+       spath = filepath.ToSlash(spath)
+       return _path.Clean(spath), nil
+}
index dc0761f2f4eb4dbbcb222d581e735e131cebf436..d4a438b5caef1d78e9ecbe1c2e62647df4ae0094 100644 (file)
@@ -175,3 +175,32 @@ func TestSplit(t *testing.T) {
                c.Assert(result, qt.Equals, test.expect)
        }
 }
+
+func TestClean(t *testing.T) {
+       t.Parallel()
+       c := qt.New(t)
+
+       for _, test := range []struct {
+               path   interface{}
+               expect interface{}
+       }{
+               {filepath.FromSlash(`foo/bar.txt`), `foo/bar.txt`},
+               {filepath.FromSlash(`foo/bar/txt`), `foo/bar/txt`},
+               {filepath.FromSlash(`foo/bar`), `foo/bar`},
+               {filepath.FromSlash(`foo/bar.t`), `foo/bar.t`},
+               {``, `.`},
+               // errors
+               {tstNoStringer{}, false},
+       } {
+
+               result, err := ns.Clean(test.path)
+
+               if b, ok := test.expect.(bool); ok && !b {
+                       c.Assert(err, qt.Not(qt.IsNil))
+                       continue
+               }
+
+               c.Assert(err, qt.IsNil)
+               c.Assert(result, qt.Equals, test.expect)
+       }
+}