diff --git a/util/safepath/safepath.go b/util/safepath/safepath.go index c3c1ab2b..704f3fd3 100644 --- a/util/safepath/safepath.go +++ b/util/safepath/safepath.go @@ -176,7 +176,6 @@ func (obj AbsFile) Cmp(absFile AbsFile) error { } // Base returns the last component of the AbsFile, in this case, the filename. -// TODO: add tests func (obj AbsFile) Base() RelFile { obj.PanicValidate() ix := strings.LastIndex(obj.path, "/") @@ -185,6 +184,20 @@ func (obj AbsFile) Base() RelFile { } } +// Dir returns the head component of the AbsFile, in this case, the directory. +func (obj AbsFile) Dir() AbsDir { + obj.PanicValidate() + ix := strings.LastIndex(obj.path, "/") + if ix == 0 { + return AbsDir{ + path: "/", + } + } + return AbsDir{ + path: obj.path[0:ix], + } +} + // HasDir returns true if the input relative dir is present in the path. func (obj AbsFile) HasDir(relDir RelDir) bool { obj.PanicValidate() diff --git a/util/safepath/safepath_test.go b/util/safepath/safepath_test.go index 38fb4266..e4fbea1d 100644 --- a/util/safepath/safepath_test.go +++ b/util/safepath/safepath_test.go @@ -643,3 +643,55 @@ func TestPathHasPrefix(t *testing.T) { } } } + +func TestAbsFile(t *testing.T) { + tests := []struct { + AbsFile string + Base string // relfile + Dir string // absdir + }{ + // not possible afaict + //{ + // AbsFile: "/", + // Base: "", + // Dir: "/", + //}, + //{ + // AbsFile: "", + // Base: "", + // Dir: "", + //}, + { + AbsFile: "/abc/def/ghi", + Base: "ghi", + Dir: "/abc/def/", + }, + { + AbsFile: "/x", + Base: "x", + Dir: "/", + }, + { + AbsFile: "/abc", + Base: "abc", + Dir: "/", + }, + { + AbsFile: "/abc/def", + Base: "def", + Dir: "/abc/", + }, + } + + for _, x := range tests { + absFile := UnsafeParseIntoAbsFile(x.AbsFile) + base := UnsafeParseIntoRelFile(x.Base) + dir := UnsafeParseIntoAbsDir(x.Dir) + if out := absFile.Base(); base.Path() != out.Path() { + t.Errorf("%s exp base: %+v, got: %+v", x.AbsFile, base.Path(), out.Path()) + } + if out := absFile.Dir(); dir.Path() != out.Path() { + t.Errorf("%s exp dir: %+v, got: %+v", x.AbsFile, dir.Path(), out.Path()) + } + } +}