Skip to content

Commit

Permalink
Merge pull request #48 from keybase/strib/gh-truncate
Browse files Browse the repository at this point in the history
fs: add `Truncate` method to `File` interface
  • Loading branch information
mcuadros authored Nov 27, 2017
2 parents 8067977 + 0aa8204 commit 053dbd0
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,6 @@ type File interface {
Lock() error
// Unlock unlocks the file.
Unlock() error
// Truncate the file.
Truncate(size int64) error
}
10 changes: 10 additions & 0 deletions memfs/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,16 @@ 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]
} else if more := int(size)-len(f.content.bytes); more > 0 {
f.content.bytes = append(f.content.bytes, make([]byte, more)...)
}

return nil
}

func (f *file) Duplicate(filename string, mode os.FileMode, flag int) billy.File {
new := &file{
name: filename,
Expand Down
19 changes: 19 additions & 0 deletions test/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
4 changes: 4 additions & 0 deletions test/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,7 @@ func (*FileMock) Lock() error {
func (*FileMock) Unlock() error {
return nil
}

func (*FileMock) Truncate(size int64) error {
return nil
}

0 comments on commit 053dbd0

Please sign in to comment.