From 8a2434ab7c4f9846dd33506612702aacb28d7278 Mon Sep 17 00:00:00 2001 From: Taru Karttunen Date: Tue, 12 Sep 2017 19:47:57 +0300 Subject: [PATCH 1/3] Add support for Truncate on files --- fs.go | 2 ++ memfs/memory.go | 7 +++++++ test/mock.go | 4 ++++ 3 files changed, 13 insertions(+) diff --git a/fs.go b/fs.go index cd1a4e7..00bb7a1 100644 --- a/fs.go +++ b/fs.go @@ -140,4 +140,6 @@ type File interface { Lock() error // Unlock unlocks the file. Unlock() error + // Truncate the file. + Truncate(size int64) error } diff --git a/memfs/memory.go b/memfs/memory.go index 0bb278c..1d1a0e2 100644 --- a/memfs/memory.go +++ b/memfs/memory.go @@ -270,6 +270,13 @@ func (f *file) Close() error { return nil } +func (f *file) Truncate(size int64) error { + if size < int64(len(f.content.bytes)) { + f.content.bytes = f.content.bytes[:size] + } + return nil +} + func (f *file) Duplicate(filename string, mode os.FileMode, flag int) billy.File { new := &file{ name: filename, diff --git a/test/mock.go b/test/mock.go index 0f00a92..2cf7397 100644 --- a/test/mock.go +++ b/test/mock.go @@ -130,3 +130,7 @@ func (*FileMock) Lock() error { func (*FileMock) Unlock() error { return nil } + +func (*FileMock) Truncate(size int64) error { + return nil +} From 2db7bbcd0c9b0aa1195a417d29700f366d65a47b Mon Sep 17 00:00:00 2001 From: Taru Karttunen Date: Wed, 13 Sep 2017 22:37:21 +0300 Subject: [PATCH 2/3] Support extending files in memoryfs truncate --- memfs/memory.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/memfs/memory.go b/memfs/memory.go index 1d1a0e2..2f8dcae 100644 --- a/memfs/memory.go +++ b/memfs/memory.go @@ -273,7 +273,10 @@ func (f *file) Close() error { func (f *file) Truncate(size int64) error { if size < int64(len(f.content.bytes)) { f.content.bytes = f.content.bytes[:size] + } else if more := int(size)-len(f.content.bytes); more > 0 { + f.content.bytes = append(f.content.bytes, make([]byte, more)...) } + return nil } From 0aa82040a3fbb8e4e76847b33e122c5f4cad1837 Mon Sep 17 00:00:00 2001 From: Taru Karttunen Date: Wed, 13 Sep 2017 22:37:46 +0300 Subject: [PATCH 3/3] Add test for truncating files --- test/basic.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/basic.go b/test/basic.go index f714b1c..1d5428b 100644 --- a/test/basic.go +++ b/test/basic.go @@ -562,3 +562,22 @@ func (s *BasicSuite) TestWriteFile(c *C) { c.Assert(f.Close(), IsNil) } + +func (s *BasicSuite) TestTruncate(c *C) { + f, err := s.FS.Create("foo") + c.Assert(err, IsNil) + + for _, sz := range []int64{4, 7, 2, 30, 0, 1} { + err = f.Truncate(sz) + c.Assert(err, IsNil) + + bs, err := ioutil.ReadAll(f) + c.Assert(err, IsNil) + c.Assert(len(bs), Equals, int(sz)) + + _, err = f.Seek(0, io.SeekStart) + c.Assert(err, IsNil) + } + + c.Assert(f.Close(), IsNil) +}