Repository navigation
Expand file tree
/
Copy pathzip.go
More file actions
87 lines (69 loc) · 1.8 KB
/
Copy pathzip.go
File metadata and controls
87 lines (69 loc) · 1.8 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package zip
import (
"bytes"
"io"
"io/ioutil"
"os"
"strings"
"github.com/pkg/errors"
"github.com/tj/go-archive"
)
var transform = archive.TransformFunc(func(r io.Reader, i os.FileInfo) (io.Reader, os.FileInfo) {
name := strings.Replace(i.Name(), "\\", "/", -1)
i = archive.Info{
Name: name,
Size: i.Size(),
Mode: i.Mode() | 0555,
Modified: i.ModTime(),
Dir: i.IsDir(),
}.FileInfo()
return r, i
})
// Build the given `dir`.
func Build(dir string) (io.ReadCloser, *archive.Stats, error) {
gitignore, err := read(".gitignore")
if err != nil {
return nil, nil, errors.Wrap(err, "reading .gitignore")
}
defer gitignore.Close()
upignore, err := read(".upignore")
if err != nil {
return nil, nil, errors.Wrap(err, "reading .upignore")
}
defer upignore.Close()
r := io.MultiReader(
strings.NewReader(".*\n"),
gitignore,
strings.NewReader("\n!node_modules/**\n!.pypath/**\n"),
upignore,
strings.NewReader("\n!main\n!server\n!_proxy.js\n!byline.js\n!up.json\n!pom.xml\n!build.gradle\n!project.clj\n"))
filter, err := archive.FilterPatterns(r)
if err != nil {
return nil, nil, errors.Wrap(err, "parsing ignore patterns")
}
buf := new(bytes.Buffer)
zip := archive.NewZip(buf).
WithFilter(filter).
WithTransform(transform)
if err := zip.Open(); err != nil {
return nil, nil, errors.Wrap(err, "opening")
}
if err := zip.AddDir(dir); err != nil {
return nil, nil, errors.Wrap(err, "adding dir")
}
if err := zip.Close(); err != nil {
return nil, nil, errors.Wrap(err, "closing")
}
return ioutil.NopCloser(buf), zip.Stats(), nil
}
// read file.
func read(path string) (io.ReadCloser, error) {
f, err := os.Open(path)
if os.IsNotExist(err) {
return ioutil.NopCloser(bytes.NewReader(nil)), nil
}
if err != nil {
return nil, err
}
return f, nil
}