-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
124 lines (112 loc) · 2.49 KB
/
image.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
120
121
122
123
124
package whaler
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
//Image is a basic representation of a docker image
type Image struct {
ID string
Name string
Labels map[string]string
Tags []string
}
type ImageConfig struct {
}
//BuildImageConfig is a basic configuration to build an image
type BuildImageConfig struct {
PathContext string
Dockerfile string
Tag string
}
//BuildImageWithDockerfile builds an image using a specific dockerfile
func BuildImageWithDockerfile(config BuildImageConfig) (string, error) {
buf := bytes.NewBuffer(nil)
if config.PathContext == "" {
if wd, err := os.Getwd(); err != nil {
return "", err
} else {
config.PathContext = wd
}
}
err := compress(config.PathContext, buf)
if err != nil {
return "", err
}
if config.Dockerfile == "" {
config.Dockerfile = "Dockerfile"
}
return buildDockerImage(config.Dockerfile, config.Tag, buf)
}
func buildDockerImage(dockerfile, tag string, ctx io.Reader) (string, error) {
cli, err := client.NewEnvClient()
if err != nil {
return "", err
}
resp, err := cli.ImageBuild(context.Background(), ctx, types.ImageBuildOptions{
Dockerfile: dockerfile,
Tags: []string{tag},
NetworkMode: "bridge",
NoCache: true,
})
if err != nil {
return "", err
}
b, _ := ioutil.ReadAll(resp.Body)
return string(b), nil
}
//Publish image to registry
func Publish(image, username, password string) (string, error) {
auth := types.AuthConfig{
Username: username,
Password: password,
}
encodedJSON, err := json.Marshal(auth)
if err != nil {
return "", err
}
encoded := base64.StdEncoding.EncodeToString(encodedJSON)
cli, err := client.NewEnvClient()
if err != nil {
return "", err
}
out, err := cli.ImagePush(context.Background(), image, types.ImagePushOptions{
All: true,
RegistryAuth: encoded,
})
if err != nil {
return "", err
}
if b, err := ioutil.ReadAll(out); err != nil {
return "", err
} else {
return string(b), nil
}
}
func ListImages() ([]Image, error) {
cli, err := client.NewEnvClient()
if err != nil {
return nil, err
}
list, err := cli.ImageList(context.Background(), types.ImageListOptions{
All: true,
})
if err != nil {
return nil, err
}
result := make([]Image, len(list))
for i, image := range list {
result[i] = Image{
ID: image.ID,
Labels: image.Labels,
Tags: image.RepoTags,
}
}
return result, nil
}