Modify util.Files to return relative paths

pull/53/head
rwxrob 2 years ago
parent 06bc522037
commit 01a3a765e3
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77

@ -2,29 +2,27 @@ package util
import (
"os"
"path/filepath"
"github.com/rwxrob/bonzai/filt"
"github.com/rwxrob/bonzai/maps"
)
// Files returns a slice of strings matching the names of the files
// within the given directory adding a slash to the end of any
// directories.
func Files(dir string) []string {
if dir == "" {
dir = "."
}
dir = filepath.Clean(dir)
files := []string{}
finfo, _ := os.ReadDir(dir)
for _, f := range finfo {
name := f.Name()
if f.IsDir() {
name += "/"
}
files = append(files, name)
entries, err := os.ReadDir(dir)
if err != nil {
return files
}
return files
return maps.Prefix(maps.MarkDirs(entries), dir+string(os.PathSeparator))
}
//FilesWith takes the path of a directory and returns the name of the
//files with the matching prefix.
func FilesWith(dir, pre string) []string {
return filt.HasPrefix(Files(dir), pre)
return filt.HasPrefix(Files(dir), filepath.Join(dir, pre))
}

@ -1,43 +1,50 @@
package util_test
import (
"fmt"
"os"
"github.com/rwxrob/bonzai/filter"
"github.com/rwxrob/bonzai/loop"
"github.com/rwxrob/bonzai/util"
)
func ExampleFiles() {
filter.Println(util.Files("testdata/files"))
loop.Println(util.Files("testdata/files"))
// Output:
// bar
// blah
// dir1/
// dir2/
// dir3/
// foo
// other
// some
// testdata/files/bar
// testdata/files/blah
// testdata/files/dir1/
// testdata/files/dir2/
// testdata/files/dir3/
// testdata/files/foo
// testdata/files/other
// testdata/files/some
}
func ExampleFiles_empty() {
os.Chdir("testdata/files")
defer os.Chdir("../..")
filter.Println(util.Files(""))
loop.Println(util.Files(""))
// Output:
// bar
// blah
// dir1/
// dir2/
// dir3/
// foo
// other
// some
// ./bar
// ./blah
// ./dir1/
// ./dir2/
// ./dir3/
// ./foo
// ./other
// ./some
}
func ExampleFilesWith() {
filter.Println(util.FilesWith("testdata/files", "b"))
loop.Println(util.FilesWith("testdata/files", "b"))
// Output:
// bar
// blah
// testdata/files/bar
// testdata/files/blah
}
func ExampleFiles_not_Directory() {
fmt.Println(util.Files("none"))
// Output:
// []
}

Loading…
Cancel
Save