/
utils.go
119 lines (106 loc) · 2.5 KB
/
utils.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
package kuhnuri
import (
"archive/zip"
"fmt"
"io"
"log"
"net/url"
"os"
"path/filepath"
)
type Path = string
func getName(in *url.URL) string {
return filepath.Base(filepath.FromSlash(in.Path))
}
func WithExt(path Path, ext string) Path {
from := filepath.Ext(path)
return path[0:len(path)-len(from)] + ext
}
func Unzip(zipFile Path, tempDir Path) error {
log.Printf("INFO: Unzip %s to %s\n", zipFile, tempDir)
r, err := zip.OpenReader(zipFile)
if err != nil {
return fmt.Errorf("Failed to open ZIP file reader: %v", err)
}
defer r.Close()
for _, f := range r.File {
if f.FileInfo().IsDir() {
continue
}
file := filepath.Clean(filepath.ToSlash(filepath.Join(tempDir, f.Name)))
log.Printf("DEBUG: Copy %s to %s\n", f.Name, file)
rc, err := f.Open()
if err != nil {
return fmt.Errorf("Failed to open ZIP entry: %v", err)
} else {
wc, err := Create(file)
if err != nil {
return fmt.Errorf("Failed to open ZIP extract writer: %v", err)
} else {
_, err = io.Copy(wc, rc)
if err != nil {
return fmt.Errorf("Failed to copy ZIP entry to outputy: %v", err)
}
}
wc.Close()
}
rc.Close()
}
return nil
}
func MkDirs(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("Failed to create directory %s: %v", dir, err)
}
}
return nil
}
func Create(file string) (*os.File, error) {
dir := filepath.Dir(file)
if err := MkDirs(dir); err != nil {
return nil, err
}
return os.Create(file)
}
func Zip(zipFile Path, tempDir Path) error {
log.Printf("INFO: Zip %s to %s\n", tempDir, zipFile)
out, err := Create(zipFile)
if err != nil {
return err
}
defer out.Close()
w := zip.NewWriter(out)
defer w.Close()
filepath.Walk(tempDir, func(path string, info os.FileInfo, err error) error {
fi, err := os.Stat(path)
if err != nil {
return err
}
if fi.IsDir() {
return nil
}
rel, err := filepath.Rel(tempDir, path)
if err != nil {
log.Fatalf("ERROR: Failed to relativize %s\n", path)
}
log.Printf("DEBUG: Read %s\n", path)
src, err := os.Open(path)
if err != nil {
return fmt.Errorf("Failed to open file reader: %v", err)
} else {
dst, err := w.Create(filepath.ToSlash(rel))
if err != nil {
return fmt.Errorf("Failed to open ZIP entry writer: %v", err)
} else {
_, err = io.Copy(dst, src)
if err != nil {
return fmt.Errorf("Failed to copy file to ZIP entry: %v", err)
}
}
src.Close()
}
return nil
})
return nil
}