Skip to content

Commit 45c6558

Browse files
committed
add fsext bridge
Signed-off-by: Pablo Chacin <pablochacin@gmail.com>
1 parent ef48b4b commit 45c6558

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

lib/fsext/bridge.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package fsext
2+
3+
import (
4+
"fmt"
5+
"io/fs"
6+
)
7+
8+
// IOFSBridge allows an afero.Fs to implement the Go standard library io/fs.FS.
9+
type IOFSBridge struct {
10+
FSExt Fs
11+
}
12+
13+
// NewIOFSBridge returns an IOFSBridge from a Fs
14+
func NewIOFSBridge(fs Fs) fs.FS {
15+
return &IOFSBridge{
16+
FSExt: fs,
17+
}
18+
}
19+
20+
// Open implements fs.Fs Open
21+
func (b *IOFSBridge) Open(name string) (fs.File, error) {
22+
f, err := b.FSExt.Open(name)
23+
if err != nil {
24+
return nil, fmt.Errorf("opening file %w", err)
25+
}
26+
return f, nil
27+
}

lib/fsext/bridge_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package fsext
2+
3+
import (
4+
"io"
5+
"io/fs"
6+
"testing"
7+
8+
"github.com/spf13/afero"
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
)
12+
13+
func TestBridgeOpen(t *testing.T) {
14+
t.Parallel()
15+
16+
testfs := afero.NewMemMapFs()
17+
require.NoError(t, WriteFile(testfs, "abasicpath/onetwo.txt", []byte(`test123`), 0o644))
18+
19+
bridge := &IOFSBridge{FSExt: testfs}
20+
21+
// it asserts that bridge implements io/fs.FS
22+
goiofs := fs.FS(bridge)
23+
f, err := goiofs.Open("abasicpath/onetwo.txt")
24+
require.NoError(t, err)
25+
require.NotNil(t, f)
26+
27+
content, err := io.ReadAll(f)
28+
require.NoError(t, err)
29+
30+
assert.Equal(t, "test123", string(content))
31+
}

0 commit comments

Comments
 (0)