We must needs traverse everything file by file.
This commit is contained in:
parent
c28dc06816
commit
112b994638
1 changed files with 40 additions and 9 deletions
|
@ -1,12 +1,14 @@
|
|||
package compactor
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func Compact(source, destination string) error {
|
||||
|
@ -15,15 +17,9 @@ func Compact(source, destination string) error {
|
|||
)
|
||||
|
||||
if _, err := os.Stat(source); errors.Is(err, fs.ErrNotExist) {
|
||||
return errors.New("source file does not exist")
|
||||
return errors.New("source does not exist")
|
||||
}
|
||||
|
||||
originFileHandle, err := os.Open(source)
|
||||
if err != nil {
|
||||
return errors.New("failed to open source file")
|
||||
}
|
||||
defer originFileHandle.Close()
|
||||
|
||||
destinationFileHandle, err := os.Create(destination)
|
||||
if err != nil {
|
||||
return errors.New("failed to create destination file")
|
||||
|
@ -33,8 +29,43 @@ func Compact(source, destination string) error {
|
|||
zipWriter := gzip.NewWriter(destinationFileHandle)
|
||||
defer zipWriter.Close()
|
||||
|
||||
if _, err := io.Copy(zipWriter, originFileHandle); err != nil {
|
||||
return errors.New("failed to copy zip to destination file: " + err.Error()) //nolint:wraperr
|
||||
err = filepath.Walk(source, func(path string, info fs.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
originFileHandle, err := os.Open(path)
|
||||
if err != nil {
|
||||
return errors.New("failed to open origin file: " + err.Error())
|
||||
}
|
||||
defer originFileHandle.Close()
|
||||
|
||||
header, err := tar.FileInfoHeader(info, "")
|
||||
if err != nil {
|
||||
return errors.New("failed to create gzip file info header: " + err.Error())
|
||||
}
|
||||
header.Name = path
|
||||
|
||||
tarWriter := tar.NewWriter(zipWriter)
|
||||
defer tarWriter.Close()
|
||||
|
||||
if err := tarWriter.WriteHeader(header); err != nil {
|
||||
return errors.New("failed to write gzip header: " + err.Error())
|
||||
}
|
||||
|
||||
if _, err := io.Copy(tarWriter, originFileHandle); err != nil {
|
||||
return errors.New("failed to copy zip to destination file: " + err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return errors.New("failed to walk source directory: " + err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
Loading…
Reference in a new issue