1
0
mirror of https://github.com/golang/go synced 2024-11-26 02:57:57 -07:00

add fix and test for non-regular files

This commit is contained in:
Mauri de Souza Meneguzzo 2023-08-09 21:00:10 -03:00
parent 21ed9e1e79
commit 11a62bfd7e
2 changed files with 37 additions and 8 deletions

View File

@ -5,6 +5,7 @@
package tar package tar
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
@ -419,6 +420,10 @@ func (tw *Writer) AddFS(fsys fs.FS) error {
if err != nil { if err != nil {
return err return err
} }
// TODO(#49580): Handle symlinks when fs.ReadLinkFS is available.
if !info.Mode().IsRegular() {
return errors.New("tar: cannot add non-regular file")
}
h, err := FileInfoHeader(info, "") h, err := FileInfoHeader(info, "")
if err != nil { if err != nil {
return err return err

View File

@ -9,6 +9,7 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"io" "io"
"io/fs"
"os" "os"
"path" "path"
"reflect" "reflect"
@ -1335,7 +1336,7 @@ func TestFileWriter(t *testing.T) {
} }
} }
func TestWriterAddFs(t *testing.T) { func TestWriterAddFS(t *testing.T) {
fsys := fstest.MapFS{ fsys := fstest.MapFS{
"file.go": {Data: []byte("hello")}, "file.go": {Data: []byte("hello")},
"subfolder/another.go": {Data: []byte("world")}, "subfolder/another.go": {Data: []byte("world")},
@ -1349,7 +1350,18 @@ func TestWriterAddFs(t *testing.T) {
// Test that we can get the files back from the archive // Test that we can get the files back from the archive
tr := NewReader(&buf) tr := NewReader(&buf)
for name, file := range fsys { entries, err := fsys.ReadDir(".")
if err != nil {
t.Fatal(err)
}
var curfname string
for _, entry := range entries {
curfname = entry.Name()
if entry.IsDir() {
curfname += "/"
continue
}
hdr, err := tr.Next() hdr, err := tr.Next()
if err == io.EOF { if err == io.EOF {
break // End of archive break // End of archive
@ -1358,20 +1370,32 @@ func TestWriterAddFs(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
data := make([]byte, hdr.Size) data, err := io.ReadAll(tr)
_, err = io.ReadFull(tr, data)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if name != hdr.Name { if hdr.Name != curfname {
t.Fatalf("got filename %v, want %v", t.Fatalf("got filename %v, want %v",
name, hdr.Name) curfname, hdr.Name)
} }
if string(data) != string(file.Data) { origdata := fsys[curfname].Data
if string(data) != string(origdata) {
t.Fatalf("got file content %v, want %v", t.Fatalf("got file content %v, want %v",
data, file.Data) data, origdata)
} }
} }
} }
func TestWriterAddFSNonRegularFiles(t *testing.T) {
fsys := fstest.MapFS{
"device": {Data: []byte("hello"), Mode: 0755 | fs.ModeDevice},
"symlink": {Data: []byte("world"), Mode: 0755 | fs.ModeSymlink},
}
var buf bytes.Buffer
tw := NewWriter(&buf)
if err := tw.AddFS(fsys); err == nil {
t.Fatal("expected error, got nil")
}
}