forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip.go
More file actions
69 lines (60 loc) · 1.23 KB
/
zip.go
File metadata and controls
69 lines (60 loc) · 1.23 KB
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
package download
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const (
dirMode os.FileMode = 0755
fileMode os.FileMode = 0644
execMode os.FileMode = 0755
)
func extractZip(zr *zip.Reader, destDir string) error {
destDirAbs, err := filepath.Abs(destDir)
if err != nil {
return err
}
pathPrefix := destDirAbs + string(filepath.Separator)
for _, zf := range zr.File {
fpath := filepath.Join(destDirAbs, filepath.FromSlash(zf.Name))
if !strings.HasPrefix(fpath, pathPrefix) {
continue
}
if err := extractZipFile(zf, fpath); err != nil {
return fmt.Errorf("error extracting %q: %w", zf.Name, err)
}
}
return nil
}
func extractZipFile(zf *zip.File, dest string) error {
zm := zf.Mode()
if zm.IsDir() {
return os.MkdirAll(dest, dirMode)
}
f, err := zf.Open()
if err != nil {
return err
}
defer f.Close()
if dir := filepath.Dir(dest); dir != "." {
if err := os.MkdirAll(dir, dirMode); err != nil {
return err
}
}
df, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_EXCL, getPerm(zm))
if err != nil {
return err
}
defer df.Close()
_, err = io.Copy(df, f)
return err
}
func getPerm(m os.FileMode) os.FileMode {
if m&0111 == 0 {
return fileMode
}
return execMode
}