util: safepath: Add a new Dir method and tests

This adds a new helper method. It should be considered for other types
as well.
This commit is contained in:
James Shubin
2022-05-10 23:44:48 -04:00
parent b26f842de1
commit 00f6045b12
2 changed files with 66 additions and 1 deletions

View File

@@ -176,7 +176,6 @@ func (obj AbsFile) Cmp(absFile AbsFile) error {
} }
// Base returns the last component of the AbsFile, in this case, the filename. // Base returns the last component of the AbsFile, in this case, the filename.
// TODO: add tests
func (obj AbsFile) Base() RelFile { func (obj AbsFile) Base() RelFile {
obj.PanicValidate() obj.PanicValidate()
ix := strings.LastIndex(obj.path, "/") 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. // HasDir returns true if the input relative dir is present in the path.
func (obj AbsFile) HasDir(relDir RelDir) bool { func (obj AbsFile) HasDir(relDir RelDir) bool {
obj.PanicValidate() obj.PanicValidate()

View File

@@ -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())
}
}
}