Say we have two paths:
c:\foo\bar\baz
and c:\foo\bar
Is there any package/method that will help me determine if one is a subdirectory of another? I am looking at a cross-platform option.
You could try and use path.filepath.Rel():
func Rel(basepath, targpath string) (string, error)
Rel
returns a relative path that is lexically equivalent totargpath
when joined tobasepath
with an intervening separator.
That is,Join(basepath, Rel(basepath, targpath))
is equivalent totargpath
itself
That means Rel("c:\foo\bar", "c:\foo\bar\baz")
should be baz
, meaning a subpath completely included in c:\foo\bar\baz
, and without any '../
'.
The same would apply for unix paths.
That would make c:\foo\bar\baz
a subdirectory of c:\foo\bar
.
You can use the function path.filepath.Match()
Match reports whether name matches the shell file name pattern.
For example:
pattern := "C:\foo\bar" + string(filepath.Separator) + "*"
matched, err := filepath.Match(pattern, "C:\foo\bar\baz")
Where matched
should be true
.