Skip to content

Commit

Permalink
archive/zip: add AddFS method to zip 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 zip archive.
This method walks the directory tree starting at the root of the filesystem
and adds each file to the archive.

Fixes: golang#54898
  • Loading branch information
mauri870 committed Jul 26, 2023
1 parent 3afa5da commit 070a6c8
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/archive/zip/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"hash"
"hash/crc32"
"io"
"io/fs"
"strings"
"unicode/utf8"
)
Expand Down Expand Up @@ -495,6 +496,41 @@ func (w *Writer) RegisterCompressor(method uint16, comp Compressor) {
w.compressors[method] = comp
}

// AddFS adds the files from fs.FS to the archive.
// It walks the directory tree starting at the root of the filesystem
// adding each file to the zip using deflate while maintaining the directory structure.
func (w *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
h.Method = Deflate
fw, err := w.CreateHeader(h)
if err != nil {
return err
}
f, err := fsys.Open(name)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(fw, f)
return err
})
}

func (w *Writer) compressor(method uint16) Compressor {
comp := w.compressors[method]
if comp == nil {
Expand Down
40 changes: 40 additions & 0 deletions src/archive/zip/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import (
"io/fs"
"math/rand"
"os"
"reflect"
"strings"
"testing"
"testing/fstest"
"time"
)

Expand Down Expand Up @@ -602,3 +604,41 @@ func BenchmarkCompressedZipGarbage(b *testing.B) {
}
})
}

func TestWriterAddFs(t *testing.T) {
expectedFiles := []string{
"file.go",
"subfolder/another.go",
}
fsys := fstest.MapFS{
"file.go": {Data: []byte("hello")},
"subfolder/another.go": {Data: []byte("world")},
}
println(fsys)

buf := new(bytes.Buffer)
zw := NewWriter(buf)
if err := zw.AddFS(fsys); err != nil {
zw.Close()
t.Fatal(err)
}

if err := zw.Close(); err != nil {
t.Fatal(err)
}

// Test that we can get the files back from the archive
zr, err := NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatal(err)
}
var foundFiles []string
for _, file := range zr.File {
foundFiles = append(foundFiles, file.FileHeader.Name)
}

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

0 comments on commit 070a6c8

Please sign in to comment.