diff --git a/fs/ops.go b/fs/ops.go index 476647af..b43c2e92 100644 --- a/fs/ops.go +++ b/fs/ops.go @@ -61,6 +61,23 @@ func WithBytes(raw []byte) PathOp { } } +// WithReaderContent copies the reader contents to the file at Path +func WithReaderContent(r io.Reader) PathOp { + return func(path Path) error { + if m, ok := path.(manifestFile); ok { + m.SetContent(ioutil.NopCloser(r)) + return nil + } + f, err := os.OpenFile(path.Path(), os.O_WRONLY, defaultFileMode) + if err != nil { + return err + } + _, err = io.Copy(f, r) + f.Close() + return err + } +} + // AsUser changes ownership of the file system object at Path func AsUser(uid, gid int) PathOp { return func(path Path) error { diff --git a/fs/ops_test.go b/fs/ops_test.go index 90c01eeb..7185f2a5 100644 --- a/fs/ops_test.go +++ b/fs/ops_test.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" "time" @@ -86,3 +87,14 @@ func TestApply(t *testing.T) { assert.Assert(t, fs.Equal(tmpDir.Path(), expected)) }) } + +func TestWithReaderContent(t *testing.T) { + content := "this is a test" + dir := fs.NewDir(t, t.Name(), + fs.WithFile("1", "", + fs.WithReaderContent(strings.NewReader(content))), + ) + defer dir.Remove() + expected := fs.Expected(t, fs.WithFile("1", content)) + assert.Assert(t, fs.Equal(dir.Path(), expected)) +}