]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/archive/zip/writer.go
archive/zip: add AddFS method to zip Writer
[gostls13.git] / src / archive / zip / writer.go
index 3b23cc3391d9e676a6735266fa8bb76a73ace755..0e81c6a5d7c71396d1744fa2c95f6c4f511ce3f8 100644 (file)
@@ -11,6 +11,7 @@ import (
        "hash"
        "hash/crc32"
        "io"
+       "io/fs"
        "strings"
        "unicode/utf8"
 )
@@ -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 {