github.com/argoproj/argo-cd/v3@v3.2.1/util/tgzstream/stream.go (about) 1 package tgzstream 2 3 import ( 4 "crypto/sha256" 5 "encoding/hex" 6 "fmt" 7 "io" 8 "os" 9 "path/filepath" 10 11 log "github.com/sirupsen/logrus" 12 13 "github.com/argoproj/argo-cd/v3/util/io/files" 14 ) 15 16 func CloseAndDelete(f *os.File) { 17 if f == nil { 18 return 19 } 20 if err := f.Close(); err != nil { 21 log.Warnf("error closing file %q: %s", f.Name(), err) 22 } 23 if err := os.Remove(f.Name()); err != nil { 24 log.Warnf("error removing file %q: %s", f.Name(), err) 25 } 26 } 27 28 // CompressFiles will create a tgz file with all contents of appPath 29 // directory excluding globs in the excluded array. Returns the file 30 // alongside its sha256 hash to be used as checksum. It is the 31 // responsibility of the caller to close the file. 32 func CompressFiles(appPath string, included []string, excluded []string) (*os.File, int, string, error) { 33 appName := filepath.Base(appPath) 34 tempDir, err := files.CreateTempDir(os.TempDir()) 35 if err != nil { 36 return nil, 0, "", fmt.Errorf("error creating tempDir for compressing files: %w", err) 37 } 38 tgzFile, err := os.CreateTemp(tempDir, appName) 39 if err != nil { 40 return nil, 0, "", fmt.Errorf("error creating app temp tgz file: %w", err) 41 } 42 hasher := sha256.New() 43 filesWritten, err := files.Tgz(appPath, included, excluded, tgzFile, hasher) 44 if err != nil { 45 CloseAndDelete(tgzFile) 46 return nil, 0, "", fmt.Errorf("error creating app tgz file: %w", err) 47 } 48 checksum := hex.EncodeToString(hasher.Sum(nil)) 49 hasher.Reset() 50 51 // reposition the offset to the beginning of the file for proper reads 52 _, err = tgzFile.Seek(0, io.SeekStart) 53 if err != nil { 54 CloseAndDelete(tgzFile) 55 return nil, 0, "", fmt.Errorf("error processing tgz file: %w", err) 56 } 57 return tgzFile, filesWritten, checksum, nil 58 }