From e55466ce70363418309d465a0f2aa6c7ada1e51d Mon Sep 17 00:00:00 2001 From: Brad Date: Tue, 5 Oct 2021 10:15:10 -0400 Subject: [PATCH] tpl/path: Add path.Clean Fixes #8885 --- tpl/path/path.go | 12 ++++++++++++ tpl/path/path_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/tpl/path/path.go b/tpl/path/path.go index 64105522..ec50cff7 100644 --- a/tpl/path/path.go +++ b/tpl/path/path.go @@ -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 +} diff --git a/tpl/path/path_test.go b/tpl/path/path_test.go index dc0761f2..d4a438b5 100644 --- a/tpl/path/path_test.go +++ b/tpl/path/path_test.go @@ -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) + } +}