Skip to content

Commit 6d89cf3

Browse files
committed
common: add functions for misc. filesystem operations
Add interfaced 'FileSystem' type for handling basic filesystem operations (existence checks, read/write, etc.). For now, just implement 'FileExists()' and 'WriteFile()'. Note that 'WriteFile()' differs from 'os.WriteFile()' - it creates the parent directories of the file (if necessary), and sets directory and file permissions based on hardcoded defaults (755 and 644, respectively). Signed-off-by: Victoria Dye <[email protected]>
1 parent a442b65 commit 6d89cf3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

internal/common/filesystem.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package common
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
"path"
8+
)
9+
10+
type FileSystem interface {
11+
FileExists(filename string) (bool, error)
12+
WriteFile(filename string, content []byte) error
13+
}
14+
15+
type fileSystem struct{}
16+
17+
func NewFileSystem() *fileSystem {
18+
return &fileSystem{}
19+
}
20+
21+
func (f *fileSystem) FileExists(filename string) (bool, error) {
22+
_, err := os.Stat(filename)
23+
if err == nil {
24+
return true, nil
25+
} else if errors.Is(err, os.ErrNotExist) {
26+
return false, nil
27+
} else {
28+
return false, fmt.Errorf("error checking for file existence with 'stat': %w", err)
29+
}
30+
}
31+
32+
func (f *fileSystem) WriteFile(filename string, content []byte) error {
33+
// Get filename parent path
34+
parentDir := path.Dir(filename)
35+
err := os.MkdirAll(parentDir, 0755)
36+
if err != nil {
37+
return fmt.Errorf("error creating parent directories: %w", err)
38+
}
39+
40+
err = os.WriteFile(filename, content, 0644)
41+
if err != nil {
42+
return fmt.Errorf("could not write file: %w", err)
43+
}
44+
return nil
45+
}

0 commit comments

Comments
 (0)