-
Notifications
You must be signed in to change notification settings - Fork 1
/
docker.go
83 lines (73 loc) · 2.15 KB
/
docker.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 docker
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/client"
"github.com/liamg/tml"
)
type Client interface {
RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error)
ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error)
ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error)
}
var _ Client = &client.Client{}
func Tag(registry, image, tag string, eout io.Writer) string {
slug := SlugifyTag(tag)
if slug != tag {
_, _ = fmt.Fprint(eout, tml.Sprintf("<yellow>Warning: tag was changed from '%s' to '%s' due to Dockers rules.</yellow>", tag, slug))
}
return fmt.Sprintf("%s/%s:%s", registry, image, slug)
}
func SlugifyTag(tag string) string {
validChars := regexp.MustCompile(`(?i)[^a-zA-Z0-9.\-_]`)
temp := validChars.ReplaceAllString(tag, "")
leading := regexp.MustCompile(`^([.-]*)([a-zA-Z0-9.\-_]*)$`)
result := leading.FindStringSubmatch(temp)[2]
if len(result) > 128 {
return result[:128]
}
return result
}
func ParseDockerignore(dir, dockerfile string) ([]string, error) {
var defaultIgnore = []string{"k8s"}
filePath := filepath.Join(dir, ".dockerignore")
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return defaultIgnore, nil
}
if file, err := ioutil.ReadFile(filePath); err != nil {
return defaultIgnore, err
} else {
var result = defaultIgnore
scanner := bufio.NewScanner(bytes.NewReader(file))
for scanner.Scan() {
text := scanner.Text()
if len(text) > 0 && text != dockerfile {
result = append(result, text)
}
}
return result, nil
}
}
func FindStages(content string) []string {
var stages []string
re := regexp.MustCompile(`(?i)^FROM .* AS (.*)$`)
scanner := bufio.NewScanner(strings.NewReader(content))
for scanner.Scan() {
text := scanner.Text()
matches := re.FindStringSubmatch(text)
if len(matches) != 0 {
stages = append(stages, matches[1])
}
}
return stages
}