Skip to content

Commit 053dbd0

Browse files
authored
Merge pull request #48 from keybase/strib/gh-truncate
fs: add `Truncate` method to `File` interface
2 parents 8067977 + 0aa8204 commit 053dbd0

File tree

4 files changed

+35
-0
lines changed

4 files changed

+35
-0
lines changed

fs.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,6 @@ type File interface {
140140
Lock() error
141141
// Unlock unlocks the file.
142142
Unlock() error
143+
// Truncate the file.
144+
Truncate(size int64) error
143145
}

memfs/memory.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,16 @@ func (f *file) Close() error {
270270
return nil
271271
}
272272

273+
func (f *file) Truncate(size int64) error {
274+
if size < int64(len(f.content.bytes)) {
275+
f.content.bytes = f.content.bytes[:size]
276+
} else if more := int(size)-len(f.content.bytes); more > 0 {
277+
f.content.bytes = append(f.content.bytes, make([]byte, more)...)
278+
}
279+
280+
return nil
281+
}
282+
273283
func (f *file) Duplicate(filename string, mode os.FileMode, flag int) billy.File {
274284
new := &file{
275285
name: filename,

test/basic.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,3 +562,22 @@ func (s *BasicSuite) TestWriteFile(c *C) {
562562

563563
c.Assert(f.Close(), IsNil)
564564
}
565+
566+
func (s *BasicSuite) TestTruncate(c *C) {
567+
f, err := s.FS.Create("foo")
568+
c.Assert(err, IsNil)
569+
570+
for _, sz := range []int64{4, 7, 2, 30, 0, 1} {
571+
err = f.Truncate(sz)
572+
c.Assert(err, IsNil)
573+
574+
bs, err := ioutil.ReadAll(f)
575+
c.Assert(err, IsNil)
576+
c.Assert(len(bs), Equals, int(sz))
577+
578+
_, err = f.Seek(0, io.SeekStart)
579+
c.Assert(err, IsNil)
580+
}
581+
582+
c.Assert(f.Close(), IsNil)
583+
}

test/mock.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,7 @@ func (*FileMock) Lock() error {
130130
func (*FileMock) Unlock() error {
131131
return nil
132132
}
133+
134+
func (*FileMock) Truncate(size int64) error {
135+
return nil
136+
}

0 commit comments

Comments
 (0)