github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/ociinstaller/zip.go (about) 1 package ociinstaller 2 3 import ( 4 "compress/gzip" 5 "fmt" 6 "io" 7 "os" 8 "path/filepath" 9 ) 10 11 func ungzip(sourceFile string, destDir string) (string, error) { 12 r, err := os.Open(sourceFile) 13 if err != nil { 14 return "", err 15 } 16 defer r.Close() 17 18 uncompressedStream, err := gzip.NewReader(r) 19 if err != nil { 20 return "", err 21 } 22 23 destFile := filepath.Join(destDir, uncompressedStream.Name) 24 outFile, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) 25 if err != nil { 26 return "", err 27 } 28 29 if _, err := io.Copy(outFile, uncompressedStream); err != nil { 30 return "", err 31 } 32 33 outFile.Close() 34 if err := uncompressedStream.Close(); err != nil { 35 return "", err 36 } 37 38 return destFile, nil 39 } 40 41 func fileExists(filePath string) bool { 42 if _, err := os.Stat(filePath); os.IsNotExist(err) { 43 return false 44 } 45 return true 46 } 47 48 // moves a file within an fs partition. panics if movement is attempted between partitions 49 // this is done separately to achieve performance benefits of os.Rename over reading and writing content 50 func moveFileWithinPartition(sourcePath, destPath string) error { 51 if err := os.Rename(sourcePath, destPath); err != nil { 52 return fmt.Errorf("error moving file: %s", err) 53 } 54 return nil 55 } 56 57 // moves a folder within an fs partition. panics if movement is attempted between partitions 58 // this is done separately to achieve performance benefits of os.Rename over reading and writing content 59 func moveFolderWithinPartition(sourcePath, destPath string) error { 60 sourceinfo, err := os.Stat(sourcePath) 61 if err != nil { 62 return err 63 } 64 65 if err = os.MkdirAll(destPath, sourceinfo.Mode()); err != nil { 66 return err 67 } 68 69 directory, err := os.Open(sourcePath) 70 if err != nil { 71 return fmt.Errorf("couldn't open source dir: %s", err) 72 } 73 directory.Close() 74 75 defer os.RemoveAll(sourcePath) 76 77 return filepath.Walk(sourcePath, func(path string, info os.FileInfo, err error) error { 78 relPath, _ := filepath.Rel(sourcePath, path) 79 if relPath == "" { 80 return nil 81 } 82 if info.IsDir() { 83 return os.MkdirAll(filepath.Join(destPath, relPath), info.Mode()) 84 } 85 return moveFileWithinPartition(filepath.Join(sourcePath, relPath), filepath.Join(destPath, relPath)) 86 }) 87 }