forked from dizzyd/mcdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ziphelper.go
83 lines (67 loc) · 1.87 KB
/
ziphelper.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
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"github.com/Jeffail/gabs"
)
type ZipHelper struct {
data []byte
dataSz int64
files map[string]int
}
func NewZipHelper(data []byte) (*ZipHelper, error) {
var zh ZipHelper
zh.data = data
zh.dataSz = int64(len(data))
// Open the zip data and cache all the filenames and offsets; also allows
// reduced error checking later on, since we've validated the file works
r, err := zip.NewReader(bytes.NewReader(zh.data), zh.dataSz)
if err != nil {
return nil, fmt.Errorf("failed to open ZIP data: %+v", err)
}
// Cache filenames and offsets into list of files
zh.files = make(map[string]int)
for i, f := range r.File {
zh.files[f.Name] = i
}
return &zh, nil
}
func (zh *ZipHelper) getFile(name string) (io.ReadCloser, error) {
index, ok := zh.files[name]
if !ok {
return nil, fmt.Errorf("file not found in ZIP: %s", name)
}
r, _ := zip.NewReader(bytes.NewReader(zh.data), zh.dataSz)
file := r.File[index]
return file.Open()
}
func (zh *ZipHelper) getJsonFile(name string) (*gabs.Container, error) {
r, err := zh.getFile(name)
if err != nil {
return nil, err
}
json, err := gabs.ParseJSONBuffer(r)
if err != nil {
return nil, fmt.Errorf("failed to parse %s JSON: %+v", name, err)
}
return json, nil
}
func (zh *ZipHelper) writeFileToDir(zipFilename string, targetDir string) (string, error) {
return zh.writeFile(zipFilename, filepath.Join(targetDir, zipFilename))
}
func (zh *ZipHelper) writeFile(zipFilename string, filename string) (string, error) {
r, err := zh.getFile(zipFilename)
if err != nil {
return "", err
}
// Make sure all the directories in the filename actually exist
err = os.MkdirAll(filepath.Dir(filename), 0700)
if err != nil {
return "", fmt.Errorf("failed to create directores for %s: %+v", filename, err)
}
return filename, writeStream(filename, r)
}