Skip to content

Commit

Permalink
fix(file): accept absolute paths (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
favonia committed Jun 18, 2022
1 parent 2fa8268 commit 79bcd9b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 11 additions & 0 deletions internal/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@ import (
"bytes"
"io/fs"
"os"
"path/filepath"

"github.com/favonia/cloudflare-ddns/internal/pp"
)

var FS = os.DirFS("/") //nolint:gochecknoglobals

func ReadString(ppfmt pp.PP, path string) (string, bool) {
// os.DirFS(...).Open() does not accept absolute paths
if filepath.IsAbs(path) {
newpath, err := filepath.Rel("/", path)
if err != nil {
ppfmt.Errorf(pp.EmojiImpossible, `%q is an absolute path but does not start with "/": %v`, err)
return "", false
}
path = newpath
}

body, err := fs.ReadFile(FS, path)
if err != nil {
ppfmt.Errorf(pp.EmojiUserError, "Failed to read %q: %v", path, err)
Expand Down
25 changes: 24 additions & 1 deletion internal/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func TestReadStringWrongPath(t *testing.T) {
mockCtrl := gomock.NewController(t)
useMemFS(t, fstest.MapFS{})

path := "/wrong/path.txt"
path := "wrong/path.txt"
mockPP := mocks.NewMockPP(mockCtrl)
mockPP.EXPECT().Errorf(pp.EmojiUserError, "Failed to read %q: %v", path, gomock.Any())
content, ok := file.ReadString(mockPP, path)
Expand All @@ -75,3 +75,26 @@ func TestReadStringNoAccess(t *testing.T) {
require.False(t, ok)
require.Empty(t, content)
}

//nolint:paralleltest // reading global var file.FS
func TestReadStringOkayAbsolutePath(t *testing.T) {
mockCtrl := gomock.NewController(t)

path := "test/file.txt"
written := " hello world " // space is intentionally added to test trimming
expected := strings.TrimSpace(written)

useMemFS(t, fstest.MapFS{
path: &fstest.MapFile{
Data: []byte(written),
Mode: 0o644,
ModTime: time.Unix(1234, 5678),
Sys: nil,
},
})

mockPP := mocks.NewMockPP(mockCtrl)
content, ok := file.ReadString(mockPP, "/"+path)
require.True(t, ok)
require.Equal(t, expected, content)
}

0 comments on commit 79bcd9b

Please sign in to comment.