Skip to content

Commit

Permalink
File manager (#183)
Browse files Browse the repository at this point in the history
* Add OpenReaderIfExists to FileManager

* Add ReadDirEntryNames to FileManager
  • Loading branch information
godrei authored May 30, 2023
1 parent 2c8004d commit 06a0eeb
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions fileutil/fileutil.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package fileutil

import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
)

// 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
Expand All @@ -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)
Expand Down

0 comments on commit 06a0eeb

Please sign in to comment.