From 74139ed8bbb271534c871b4ab9c77fff511cfecc Mon Sep 17 00:00:00 2001 From: Luca Burgazzoli Date: Wed, 8 May 2024 16:07:46 +0200 Subject: [PATCH] chore: cleanup pkg/util/tar package --- pkg/cmd/dump.go | 2 +- pkg/util/tar/util_compress.go | 24 +++++++++++++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/pkg/cmd/dump.go b/pkg/cmd/dump.go index d9351d7f01..187b73f1a8 100644 --- a/pkg/cmd/dump.go +++ b/pkg/cmd/dump.go @@ -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 { diff --git a/pkg/util/tar/util_compress.go b/pkg/util/tar/util_compress.go index 3388d124a7..9d97e4e509 100644 --- a/pkg/util/tar/util_compress.go +++ b/pkg/util/tar/util_compress.go @@ -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 { @@ -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 @@ -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 }