11package fileutil
22
33import (
4+ "errors"
5+ "io"
6+ "io/fs"
47 "os"
58 "path/filepath"
69)
710
811// FileManager ...
912type FileManager interface {
1013 Open (path string ) (* os.File , error )
14+ OpenReaderIfExists (path string ) (io.Reader , error )
15+ ReadDirEntryNames (path string ) ([]string , error )
1116 Remove (path string ) error
1217 RemoveAll (path string ) error
1318 Write (path string , value string , perm os.FileMode ) error
@@ -22,11 +27,38 @@ func NewFileManager() FileManager {
2227 return fileManager {}
2328}
2429
30+ // ReadDirEntryNames reads the named directory using os.ReadDir and returns the dir entries' names.
31+ func (fileManager ) ReadDirEntryNames (path string ) ([]string , error ) {
32+ entries , err := os .ReadDir (path )
33+ if err != nil {
34+ return nil , err
35+ }
36+ var names []string
37+ for _ , entry := range entries {
38+ names = append (names , entry .Name ())
39+ }
40+ return names , nil
41+ }
42+
2543// Open ...
2644func (fileManager ) Open (path string ) (* os.File , error ) {
2745 return os .Open (path )
2846}
2947
48+ // OpenReaderIfExists opens the named file using os.Open and returns an io.Reader.
49+ // An ErrNotExist error is absorbed and the returned io.Reader will be nil,
50+ // other errors from os.Open are returned as is.
51+ func (fileManager ) OpenReaderIfExists (path string ) (io.Reader , error ) {
52+ file , err := os .Open (path )
53+ if errors .Is (err , fs .ErrNotExist ) {
54+ return nil , nil
55+ }
56+ if err != nil {
57+ return nil , err
58+ }
59+ return file , nil
60+ }
61+
3062// Remove ...
3163func (fileManager ) Remove (path string ) error {
3264 return os .Remove (path )
0 commit comments