Skip to content

Commit 1f8d783

Browse files
committed
filesystem: gracefully handle missing files in 'ReadFileLines()'
If the file argument to 'ReadFileLines()' does not exist on disk, return an empty string list (corresponding to an empty file) with no error rather than pass the error on to the caller. This removes a pre-existing side-effect behavior of 'ReadFileLines()', where the 'os.O_CREATE' flag would create the file if it was missing when read. It would not create leading directories, though, leading to unhandled error cases (e.g. in 'git-bundle-server init' without '~/git-bundle-server'). By instead returning an empty result for any missing file, these errors are avoided. Signed-off-by: Victoria Dye <[email protected]>
1 parent c0a1cc4 commit 1f8d783

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

internal/common/filesystem.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,16 @@ func (f *fileSystem) DeleteFile(filename string) (bool, error) {
6363
}
6464

6565
func (f *fileSystem) ReadFileLines(filename string) ([]string, error) {
66-
file, err := os.OpenFile(filename, os.O_RDONLY|os.O_CREATE, 0o600)
66+
file, err := os.Open(filename)
6767
if err != nil {
68-
return nil, err
68+
pathErr, ok := err.(*os.PathError)
69+
if ok && pathErr.Err == syscall.ENOENT {
70+
// If the file doesn't exist, return empty result rather than an
71+
// error
72+
return []string{}, nil
73+
} else {
74+
return nil, err
75+
}
6976
}
7077

7178
var l []string

0 commit comments

Comments
 (0)