feat: add function for listing files within a directory by prefix

This commit is contained in:
Jose Diaz-Gonzalez committed 2020-11-21 20:57:33 -05:00
1 parent 82f13af166
commit 36dc98452d
1 file changed
+22
+22
View File
@@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/user" "os/user"
"strconv" "strconv"
@@ -130,6 +131,27 @@ func IsAbsPath(path string) bool {
return strings.HasPrefix(path, "/") return strings.HasPrefix(path, "/")
} }
// ListFiles lists files within a given path that have a given prefix
func ListFilesWithPrefix(path string, prefix string) []string {
names, err := ioutil.ReadDir(path)
if err != nil {
return []string{}
}
files := []string{}
for _, f := range names {
if prefix != "" && !strings.HasPrefix(f.Name(), prefix) {
continue
}
if f.Mode().IsRegular() {
files = append(files, fmt.Sprintf("%s/%s", path, f.Name()))
}
}
return files
}
// ReadFirstLine gets the first line of a file that has contents and returns it // ReadFirstLine gets the first line of a file that has contents and returns it
// if there are no contents, an empty string is returned // if there are no contents, an empty string is returned
// will also return an empty string if the file does not exist // will also return an empty string if the file does not exist