-
Notifications
You must be signed in to change notification settings - Fork 221
/
archive.go
102 lines (83 loc) · 2.26 KB
/
archive.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
package imgsrc
import (
"archive/tar"
"io"
"os"
"path/filepath"
"strings"
"github.com/docker/docker/builder/dockerignore"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/fileutils"
)
type archiveOptions struct {
sourcePath string
exclusions []string
compressed bool
additions map[string][]byte
}
func archiveDirectory(options archiveOptions) (io.ReadCloser, error) {
opts := &archive.TarOptions{
ExcludePatterns: options.exclusions,
}
if options.compressed && len(options.additions) == 0 {
opts.Compression = archive.Gzip
}
r, err := archive.TarWithOptions(options.sourcePath, opts)
if err != nil {
return nil, err
}
if options.additions != nil {
mods := map[string]archive.TarModifierFunc{}
for name, contents := range options.additions {
mods[name] = func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
newHeader := &tar.Header{
Name: name,
Size: int64(len(contents)),
}
return newHeader, contents, nil
}
}
r = archive.ReplaceFileTarWrapper(r, mods)
}
return r, nil
}
func readDockerignore(workingDir string) ([]string, error) {
file, err := os.Open(filepath.Join(workingDir, ".dockerignore"))
if os.IsNotExist(err) {
return []string{}, nil
} else if err != nil {
return nil, err
}
defer file.Close()
return parseDockerignore(file)
}
func parseDockerignore(r io.Reader) ([]string, error) {
excludes, err := dockerignore.ReadAll(r)
if err != nil {
return nil, err
}
if match, _ := fileutils.Matches("fly.toml", excludes); !match {
excludes = append(excludes, "fly.toml")
}
if match, _ := fileutils.Matches(".dockerignore", excludes); match {
excludes = append(excludes, "!.dockerignore")
}
if match, _ := fileutils.Matches("Dockerfile", excludes); match {
excludes = append(excludes, "![Dd]ockerfile")
}
if match, _ := fileutils.Matches("dockerfile", excludes); match {
excludes = append(excludes, "![Dd]ockerfile")
}
return excludes, nil
}
func isPathInRoot(target, rootDir string) bool {
rootDir, _ = filepath.Abs(rootDir)
if !filepath.IsAbs(target) {
target = filepath.Join(rootDir, target)
}
rel, err := filepath.Rel(rootDir, target)
if err != nil {
return false
}
return !strings.HasPrefix(filepath.ToSlash(rel), "../")
}