-
Notifications
You must be signed in to change notification settings - Fork 0
/
unpack_zip.go
133 lines (102 loc) · 2.58 KB
/
unpack_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
package onearchiver
import (
"fmt"
ignore "github.com/sabhiram/go-gitignore"
"github.com/yeka/zip"
"io"
"os"
"path/filepath"
)
func startUnpackingZip(arc zipArchive, ph *ProgressHandler) error {
_filename := arc.meta.Filename
_password := arc.meta.Password
_destination := arc.unpack.Destination
_gitIgnorePattern := arc.meta.GitIgnorePattern
_fileList := arc.unpack.FileList
allowFileFiltering := len(_fileList) > 0
reader, err := zip.OpenReader(_filename)
if err != nil {
return err
}
var ignoreList []string
ignoreList = append(ignoreList, GlobalPatternDenylist...)
ignoreList = append(ignoreList, _gitIgnorePattern...)
ignoreMatches := ignore.CompileIgnoreLines(ignoreList...)
zipFilePathListMap := make(map[string]extractZipFileInfo)
for _, file := range reader.File {
if file.IsEncrypted() {
file.SetPassword(_password)
}
fileName := filepath.ToSlash(file.Name)
_fileInfo := file.FileInfo()
if allowFileFiltering {
matched := StringFilter(_fileList, func(s string) bool {
_filterFName := fixDirSlash(_fileInfo.IsDir(), fileName)
return subpathExists(s, _filterFName)
})
if len(matched) < 1 {
continue
}
}
if ignoreMatches.MatchesPath(fileName) {
continue
}
_absPath := filepath.Join(_destination, fileName)
zipFilePathListMap[_absPath] = extractZipFileInfo{
absFilepath: _absPath,
name: fileName,
fileInfo: &_fileInfo,
zipFileInfo: file,
}
}
totalFiles := len(reader.File)
pInfo, ch := initProgress(totalFiles, ph)
count := 0
for absolutePath, file := range zipFilePathListMap {
count += 1
pInfo.progress(ch, totalFiles, absolutePath, count)
if err := addFileFromZipToDisk(file.zipFileInfo, absolutePath); err != nil {
return err
}
}
pInfo.endProgress(ch, totalFiles)
defer func() {
if err := reader.Close(); err != nil {
fmt.Printf("%v\n", err)
}
}()
if !exists(_destination) {
if err := os.Mkdir(_destination, 0755); err != nil {
return err
}
}
return nil
}
func addFileFromZipToDisk(file *zip.File, filename string) error {
fileToExtract, err := file.Open()
if err != nil {
return err
}
defer func() {
if err := fileToExtract.Close(); err != nil {
fmt.Printf("%v\n", err)
}
}()
if file.FileInfo().IsDir() {
if err := os.MkdirAll(filename, os.ModePerm); err != nil {
return err
}
return nil
} else {
_basename := filepath.Dir(filename)
if err := os.MkdirAll(_basename, os.ModePerm); err != nil {
return err
}
}
writer, err := os.Create(filename)
if err != nil {
return err
}
_, _ = io.Copy(writer, fileToExtract)
return err
}