diff --git a/fileutil/fileutil.go b/fileutil/fileutil.go index e25f06b..b2b9ba8 100644 --- a/fileutil/fileutil.go +++ b/fileutil/fileutil.go @@ -1,6 +1,9 @@ package fileutil import ( + "errors" + "io" + "io/fs" "os" "path/filepath" ) @@ -8,6 +11,8 @@ import ( // FileManager ... type FileManager interface { Open(path string) (*os.File, error) + OpenReaderIfExists(path string) (io.Reader, error) + ReadDirEntryNames(path string) ([]string, error) Remove(path string) error RemoveAll(path string) error Write(path string, value string, perm os.FileMode) error @@ -22,11 +27,38 @@ func NewFileManager() FileManager { return fileManager{} } +// ReadDirEntryNames reads the named directory using os.ReadDir and returns the dir entries' names. +func (fileManager) ReadDirEntryNames(path string) ([]string, error) { + entries, err := os.ReadDir(path) + if err != nil { + return nil, err + } + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + return names, nil +} + // Open ... func (fileManager) Open(path string) (*os.File, error) { return os.Open(path) } +// OpenReaderIfExists opens the named file using os.Open and returns an io.Reader. +// An ErrNotExist error is absorbed and the returned io.Reader will be nil, +// other errors from os.Open are returned as is. +func (fileManager) OpenReaderIfExists(path string) (io.Reader, error) { + file, err := os.Open(path) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + return file, nil +} + // Remove ... func (fileManager) Remove(path string) error { return os.Remove(path)