Skip to content

Commit

Permalink
tpl/path: Add path.Clean
Browse files Browse the repository at this point in the history
 Fixes #8885
  • Loading branch information
bradcypert authored Oct 5, 2021
1 parent ecf025f commit e55466c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions tpl/path/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
29 changes: 29 additions & 0 deletions tpl/path/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit e55466c

Please sign in to comment.