-
Notifications
You must be signed in to change notification settings - Fork 3
/
zip.go
79 lines (66 loc) · 2.08 KB
/
zip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ociinstaller
import (
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
)
func Ungzip(sourceFile string, destDir string) (string, error) {
r, err := os.Open(sourceFile)
if err != nil {
return "", err
}
uncompressedStream, err := gzip.NewReader(r)
if err != nil {
return "", err
}
destFile := filepath.Join(destDir, uncompressedStream.Name)
outFile, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
return "", err
}
if _, err := io.Copy(outFile, uncompressedStream); err != nil { //nolint:gosec // TODO G110: Potential DoS vulnerability via decompression bomb
return "", err
}
outFile.Close()
if err := uncompressedStream.Close(); err != nil {
return "", err
}
return destFile, nil
}
// moves a file within an fs partition. panics if movement is attempted between partitions
// this is done separately to achieve performance benefits of os.Rename over reading and writing content
func MoveFileWithinPartition(sourcePath, destPath string) error {
if err := os.Rename(sourcePath, destPath); err != nil {
return fmt.Errorf("error moving file: %s", err)
}
return nil
}
// moves a folder within an fs partition. panics if movement is attempted between partitions
// this is done separately to achieve performance benefits of os.Rename over reading and writing content
func MoveFolderWithinPartition(sourcePath, destPath string) error {
sourceinfo, err := os.Stat(sourcePath)
if err != nil {
return err
}
if err = os.MkdirAll(destPath, sourceinfo.Mode()); err != nil {
return err
}
directory, err := os.Open(sourcePath)
if err != nil {
return fmt.Errorf("couldn't open source dir: %s", err)
}
directory.Close()
defer os.RemoveAll(sourcePath)
return filepath.Walk(sourcePath, func(path string, info os.FileInfo, err error) error {
relPath, _ := filepath.Rel(sourcePath, path)
if relPath == "" {
return nil
}
if info.IsDir() {
return os.MkdirAll(filepath.Join(destPath, relPath), info.Mode())
}
return MoveFileWithinPartition(filepath.Join(sourcePath, relPath), filepath.Join(destPath, relPath))
})
}