From 112b994638c3dfcddfaf6ee1041bc6169d880d1d Mon Sep 17 00:00:00 2001 From: Felipe Cotti Date: Mon, 27 Jan 2025 02:41:45 -0300 Subject: [PATCH] We must needs traverse everything file by file. --- .../internal/compactor/compactor.go | 49 +++++++++++++++---- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/src/Guestbooky-backup/internal/compactor/compactor.go b/src/Guestbooky-backup/internal/compactor/compactor.go index 8eb471f..e8a5a26 100644 --- a/src/Guestbooky-backup/internal/compactor/compactor.go +++ b/src/Guestbooky-backup/internal/compactor/compactor.go @@ -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