Skip to content

Commit

Permalink
chore: cleanup pkg/util/tar package
Browse files Browse the repository at this point in the history
  • Loading branch information
lburgazzoli committed May 8, 2024
1 parent 317338c commit 1711a50
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
2 changes: 1 addition & 1 deletion pkg/cmd/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (o *dumpCmdOptions) dump(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
tar.CreateTarFile([]string{file.Name()}, "dump."+file.Name()+"."+time.Now().Format(time.RFC3339)+".tar.gz", cmd)
tar.CreateTarFile([]string{file.Name()}, "dump."+file.Name()+"."+time.Now().Format(time.RFC3339)+".tar.gz", cmd.OutOrStdout())
return nil
})
} else {
Expand Down
24 changes: 15 additions & 9 deletions pkg/util/tar/util_compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,27 @@ import (
"io"
"os"

"github.com/spf13/cobra"
"github.com/apache/camel-k/v2/pkg/util"
)

func CreateTarFile(fileNames []string, archiveName string, cmd *cobra.Command) {
func CreateTarFile(fileNames []string, archiveName string, buf io.Writer) {
out, err := os.Create(archiveName)
if err != nil {
fmt.Fprintln(cmd.ErrOrStderr(), "Error writing archive:", err.Error())
_, _ = fmt.Fprintln(buf, "Error writing archive:", err.Error())
}
defer out.Close()
defer util.CloseQuietly(out)

err = createArchiveFile(fileNames, out)
if err != nil {
fmt.Fprintln(cmd.ErrOrStderr(), "Error writing archive:", err.Error())
_, _ = fmt.Fprintln(buf, "Error writing archive:", err.Error())
}
}

func createArchiveFile(files []string, buf io.Writer) error {
gw := gzip.NewWriter(buf)
defer gw.Close()
defer util.CloseQuietly(gw)
tw := tar.NewWriter(gw)
defer tw.Close()
defer util.CloseQuietly(tw)

// Iterate over files and add them to the tar archive
for _, file := range files {
Expand All @@ -61,7 +61,8 @@ func addEntryToArchive(tw *tar.Writer, filename string) error {
if err != nil {
return err
}
defer file.Close()
defer util.CloseQuietly(file)

info, err := file.Stat()
if err != nil {
return err
Expand All @@ -79,6 +80,11 @@ func addEntryToArchive(tw *tar.Writer, filename string) error {
if err != nil {
return err
}
defer os.Remove(filename)

err = os.Remove(filename)
if err != nil {
return err
}

return nil
}

0 comments on commit 1711a50

Please sign in to comment.