searcherside/internal/archive/tar.go

48 lines
768 B
Go

package archive
import (
"archive/tar"
"errors"
"io"
"io/fs"
"path/filepath"
)
func TarDirectory(src fs.FS, root string, writer io.Writer) (err error) {
tw := tar.NewWriter(writer)
defer func() {
err = errors.Join(err, tw.Close())
}()
return fs.WalkDir(src, root, func(path string, d fs.DirEntry, err error) error {
fileInfo, err := d.Info()
if err != nil {
return err
}
header, err := tar.FileInfoHeader(fileInfo, path)
if err != nil {
return err
}
header.Name = filepath.ToSlash(path)
if err := tw.WriteHeader(header); err != nil {
return err
}
if !d.IsDir() {
f, err := src.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(tw, f); err != nil {
return err
}
}
return nil
})
}