Skip to content

Commit

Permalink
archive/tar: add AddFS method to Writer
Browse files Browse the repository at this point in the history
The method AddFS can be used to add the contents of a fs.FS filesystem
to a tar archive. This method walks the directory tree starting at the
root of the filesystem and adds each file to the archive.

Fixes: golang#58000
  • Loading branch information
mauri870 committed Jul 26, 2023
1 parent 3afa5da commit f5e2dab
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/next/58000.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pkg archive/tar, method (*Writer) AddFS(fsys fs.FS) error #58000
32 changes: 32 additions & 0 deletions src/archive/tar/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package tar
import (
"fmt"
"io"
"io/fs"
"path"
"sort"
"strings"
Expand Down Expand Up @@ -403,6 +404,37 @@ func (tw *Writer) writeRawHeader(blk *block, size int64, flag byte) error {
return nil
}

// AddFS walks the directory tree provided by fs.FS adding each file to the tar archive.
func (tw *Writer) AddFS(fsys fs.FS) error {
return fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil {
return err
}
h, err := FileInfoHeader(info, "")
if err != nil {
return err
}
h.Name = name
if err := tw.WriteHeader(h); err != nil {
return err
}
f, err := fsys.Open(name)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(tw, f)
return err
})
}

// splitUSTARPath splits a path according to USTAR prefix and suffix rules.
// If the path is not splittable, then it will return ("", "", false).
func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
Expand Down
36 changes: 36 additions & 0 deletions src/archive/tar/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"sort"
"strings"
"testing"
"testing/fstest"
"testing/iotest"
"time"
)
Expand Down Expand Up @@ -1333,3 +1334,38 @@ func TestFileWriter(t *testing.T) {
}
}
}

func TestWriterAddFs(t *testing.T) {
expectedFiles := []string{
"file.go",
"subfolder/another.go",
}
fsys := fstest.MapFS{
"file.go": {},
"subfolder/another.go": {},
}
var buf bytes.Buffer
tw := NewWriter(&buf)
if err := tw.AddFS(fsys); err != nil {
t.Fatal(err)
}

// Test that we can get the files back from the archive
tr := NewReader(&buf)
var foundFiles []string
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
t.Fatal(err)
}
foundFiles = append(foundFiles, hdr.Name)
}

if !reflect.DeepEqual(expectedFiles, foundFiles) {
t.Fatalf("got %+v, want %+v",
foundFiles, expectedFiles)
}
}

0 comments on commit f5e2dab

Please sign in to comment.