Skip to content

Commit

Permalink
fix: truncate file when untar (#39)
Browse files Browse the repository at this point in the history
* fix: truncate file when untar

* add more unit tests
  • Loading branch information
shipengqi authored Sep 7, 2023
1 parent a603fe4 commit 637038f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
22 changes: 14 additions & 8 deletions fsutil/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,23 @@ func untar(reader io.Reader, dst string) error {
return err
}
case tar.TypeReg: // file
file, err := os.OpenFile(dstPath, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
if err = createf(tr, dstPath, header.FileInfo().Mode()); err != nil {
return err
}
_, err = io.Copy(file, tr)
if err != nil {
_ = file.Close()
return err
}
_ = file.Close()
}
}
return nil
}

func createf(src io.Reader, dst string, mode os.FileMode) error {
file, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode)
if err != nil {
return err
}
defer func() { _ = file.Close() }()
_, err = io.Copy(file, src)
if err != nil {
return err
}
return nil
}
23 changes: 23 additions & 0 deletions fsutil/tar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ func TestTar(t *testing.T) {
defer func() { _ = os.RemoveAll(undst) }()
err = UnTar(unsrc, undst)
assert.NoError(t, err)

f, err := os.Stat("testdata/src2/testdata/src/subdir")
assert.NoError(t, err)
assert.True(t, f.IsDir())

f, err = os.Stat("testdata/src2/testdata/src/a.txt")
assert.NoError(t, err)
assert.False(t, f.IsDir())

f, err = os.Stat("testdata/src2/testdata/src/b.txt")
assert.NoError(t, err)
assert.False(t, f.IsDir())

f, err = os.Stat("testdata/src2/testdata/src/subdir/c.txt")
assert.NoError(t, err)
assert.False(t, f.IsDir())
}

func TestTarFile(t *testing.T) {
Expand All @@ -33,6 +49,13 @@ func TestTarFile(t *testing.T) {
defer func() { _ = os.RemoveAll(undst) }()
err = UnTar(unsrc, undst)
assert.NoError(t, err)
f, err := os.Stat("testdata/src2/testdata/src/subdir")
assert.NoError(t, err)
assert.True(t, f.IsDir())

f, err = os.Stat("testdata/src2/testdata/src/subdir/c.txt")
assert.NoError(t, err)
assert.False(t, f.IsDir())
}

func TestCompress(t *testing.T) {
Expand Down

0 comments on commit 637038f

Please sign in to comment.