generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
zip.go
135 lines (117 loc) · 2.56 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package internal
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// UnzipDir unzips a ZIP archive into the specified directory.
func UnzipDir(zipReader *zip.Reader, destDir string) error {
err := os.MkdirAll(destDir, 0700)
if err != nil {
return err
}
for _, file := range zipReader.File {
destPath := filepath.Clean(filepath.Join(destDir, file.Name)) //nolint:gosec
if destDir != "." && !strings.HasPrefix(destPath, destDir) {
return fmt.Errorf("invalid file path: %q", destPath)
}
// Create directory if it doesn't exist
if file.FileInfo().IsDir() {
err := os.MkdirAll(destPath, file.Mode())
if err != nil {
return err
}
continue
}
// Handle symlinks
if file.Mode()&os.ModeSymlink != 0 {
reader, err := file.Open()
if err != nil {
return err
}
buf := &bytes.Buffer{}
_, err = io.Copy(buf, reader) //nolint:gosec
if err != nil {
return err
}
err = os.Symlink(buf.String(), destPath)
if err != nil {
return err
}
continue
}
// Handle regular files
fileReader, err := file.Open()
if err != nil {
return err
}
defer fileReader.Close()
destFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, fileReader) //nolint:gosec
if err != nil {
return err
}
}
return nil
}
func ZipDir(srcDir, destZipFile string) error {
zipFile, err := os.Create(destZipFile)
if err != nil {
return err
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
return filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
headerPath := strings.TrimPrefix(path, srcDir)
if strings.HasPrefix(headerPath, string(filepath.Separator)) {
headerPath = headerPath[1:]
}
if info.IsDir() {
headerPath += "/"
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = headerPath
if info.Mode()&os.ModeSymlink != 0 {
dest, err := os.Readlink(path)
if err != nil {
return err
}
header.Method = zip.Store
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
_, err = writer.Write([]byte(dest))
return err
}
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
}
return nil
})
}