From be50d7f462b820e3c19fe45d132a6cb3c5a11341 Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Fri, 20 Dec 2019 16:52:45 -0500 Subject: [PATCH 1/2] Add WithReaderContent PathOp --- fs/ops.go | 16 ++++++++++++++++ fs/ops_test.go | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/fs/ops.go b/fs/ops.go index 476647af..998a36fd 100644 --- a/fs/ops.go +++ b/fs/ops.go @@ -61,6 +61,22 @@ 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) + 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)) +} From 36a3c7b22dfbe2cbe3d5a58c3ef54bf777811bea Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Sat, 21 Dec 2019 13:48:51 -0500 Subject: [PATCH 2/2] Close the file in WithReaderContent --- fs/ops.go | 1 + 1 file changed, 1 insertion(+) diff --git a/fs/ops.go b/fs/ops.go index 998a36fd..b43c2e92 100644 --- a/fs/ops.go +++ b/fs/ops.go @@ -73,6 +73,7 @@ func WithReaderContent(r io.Reader) PathOp { return err } _, err = io.Copy(f, r) + f.Close() return err } }