forked from docker/app
/
init.go
291 lines (271 loc) · 7.72 KB
/
init.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package packager
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
"text/template"
"github.com/docker/app/internal"
"github.com/docker/app/internal/types"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
func prependToFile(filename, text string) {
content, _ := ioutil.ReadFile(filename)
content = append([]byte(text), content...)
ioutil.WriteFile(filename, content, 0644)
}
// Init is the entrypoint initialization function.
// It generates a new application package based on the provided parameters.
func Init(name string, composeFile string, description string, maintainers []string, singleFile bool) error {
if err := internal.ValidateAppName(name); err != nil {
return err
}
dirName := internal.DirNameFromAppName(name)
if err := os.Mkdir(dirName, 0755); err != nil {
return errors.Wrap(err, "failed to create application directory")
}
var err error
defer func() {
if err != nil {
os.RemoveAll(dirName)
}
}()
if err = writeMetadataFile(name, dirName, description, maintainers); err != nil {
return err
}
if composeFile == "" {
if _, err := os.Stat("docker-compose.yml"); err == nil {
composeFile = "docker-compose.yml"
}
}
if composeFile == "" {
err = initFromScratch(name)
} else {
err = initFromComposeFile(name, composeFile)
}
if err != nil {
return err
}
if !singleFile {
return nil
}
// Merge as a single file
// Add some helfpful comments to distinguish the sections
prependToFile(filepath.Join(dirName, "docker-compose.yml"), "# This section contains the Compose file that describes your application services.\n")
prependToFile(filepath.Join(dirName, "settings.yml"), "# This section contains the default values for your application settings.\n")
prependToFile(filepath.Join(dirName, "metadata.yml"), "# This section contains your application metadata.\n")
temp := "_temp_dockerapp__.dockerapp"
err = os.Rename(dirName, temp)
if err != nil {
return err
}
defer os.RemoveAll(temp)
return Merge(temp, dirName)
}
func initFromScratch(name string) error {
log.Debug("init from scratch")
composeData, err := composeFileFromScratch()
if err != nil {
return err
}
dirName := internal.DirNameFromAppName(name)
if err := ioutil.WriteFile(filepath.Join(dirName, "docker-compose.yml"), composeData, 0644); err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(dirName, "settings.yml"), []byte{'\n'}, 0644)
}
func parseEnv(env string, target map[string]string) {
envlines := strings.Split(env, "\n")
for _, l := range envlines {
l = strings.Trim(l, "\r ")
if l == "" || l[0] == '#' {
continue
}
kv := strings.SplitN(l, "=", 2)
if len(kv) != 2 {
continue
}
target[kv[0]] = kv[1]
}
}
func isAlNum(b byte) bool {
return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '_' || b == '.'
}
func extractString(data string, res *[]string) {
for {
dollar := strings.Index(data, "$")
if dollar == -1 || len(data) == dollar+1 {
break
}
if data[dollar+1] == '$' {
data = data[dollar+2:]
continue
}
dollar++
if data[dollar] == '{' {
dollar++
}
start := dollar
for dollar < len(data) && isAlNum(data[dollar]) {
dollar++
}
*res = append(*res, data[start:dollar])
data = data[dollar:]
}
}
func extractRecurseList(node []interface{}, res *[]string) error {
for _, v := range node {
switch vv := v.(type) {
case string:
extractString(vv, res)
case []interface{}:
if err := extractRecurseList(vv, res); err != nil {
return err
}
case map[interface{}]interface{}:
if err := extractRecurse(vv, res); err != nil {
return err
}
}
}
return nil
}
func extractRecurse(node map[interface{}]interface{}, res *[]string) error {
for _, v := range node {
switch vv := v.(type) {
case string:
extractString(vv, res)
case []interface{}:
if err := extractRecurseList(vv, res); err != nil {
return err
}
case map[interface{}]interface{}:
if err := extractRecurse(vv, res); err != nil {
return err
}
}
}
return nil
}
// ExtractVariables returns the list of variables used by given compose raw data
func ExtractVariables(composeRaw string) ([]string, error) {
compose := make(map[interface{}]interface{})
err := yaml.Unmarshal([]byte(composeRaw), compose)
if err != nil {
return nil, err
}
var res []string
err = extractRecurse(compose, &res)
return res, err
}
func initFromComposeFile(name string, composeFile string) error {
log.Debug("init from compose")
dirName := internal.DirNameFromAppName(name)
composeRaw, err := ioutil.ReadFile(composeFile)
if err != nil {
return errors.Wrap(err, "failed to read compose file")
}
settings := make(map[string]string)
envRaw, err := ioutil.ReadFile(filepath.Join(filepath.Dir(composeFile), ".env"))
if err == nil {
parseEnv(string(envRaw), settings)
}
keys, err := ExtractVariables(string(composeRaw))
if err != nil {
return errors.Wrap(err, "failed to parse compose file")
}
needsFilling := false
for _, k := range keys {
if _, ok := settings[k]; !ok {
settings[k] = "FILL ME"
needsFilling = true
}
}
settingsYAML, err := yaml.Marshal(settings)
if err != nil {
return errors.Wrap(err, "failed to marshal settings")
}
err = ioutil.WriteFile(filepath.Join(dirName, "docker-compose.yml"), composeRaw, 0644)
if err != nil {
return errors.Wrap(err, "failed to write docker-compose.yml")
}
err = ioutil.WriteFile(filepath.Join(dirName, "settings.yml"), settingsYAML, 0644)
if err != nil {
return errors.Wrap(err, "failed to write settings.yml")
}
if needsFilling {
fmt.Println("You will need to edit settings.yml to fill in default values.")
}
return nil
}
func composeFileFromScratch() ([]byte, error) {
fileStruct := types.NewInitialComposeFile()
return yaml.Marshal(fileStruct)
}
const metaTemplate = `# Version of the application
version: {{ .Version }}
# Name of the application
name: {{ .Name }}
# A short description of the application
description: {{ .Description }}
# Namespace to use when pushing to a registry. This is typically your Hub username.
{{ if len .Namespace}}namespace: {{ .Namespace }} {{ else }}#namespace: myHubUsername{{ end }}
# List of application maitainers with name and email for each
{{ if len .Maintainers }}maintainers:
{{ range .Maintainers }} - name: {{ .Name }}
email: {{ .Email }}
{{ end }}{{ else }}#maintainers:
# - name: John Doe
# email: john@doe.com
{{ end }}# Specify false here if your application doesn't support Swarm or Kubernetes
targets:
swarm: true
kubernetes: true
`
func writeMetadataFile(name, dirName string, description string, maintainers []string) error {
meta := newMetadata(name, description, maintainers)
tmpl, err := template.New("metadata").Parse(metaTemplate)
if err != nil {
return errors.Wrap(err, "internal error parsing metadata template")
}
resBuf := &bytes.Buffer{}
if err := tmpl.Execute(resBuf, meta); err != nil {
return errors.Wrap(err, "error generating metadata")
}
return ioutil.WriteFile(filepath.Join(dirName, "metadata.yml"), resBuf.Bytes(), 0644)
}
func newMetadata(name string, description string, maintainers []string) types.AppMetadata {
target := types.ApplicationTarget{
Swarm: true,
Kubernetes: true,
}
res := types.AppMetadata{
Version: "0.1.0",
Targets: target,
Name: name,
Description: description,
}
if len(maintainers) == 0 {
var userName string
userData, _ := user.Current()
if userData != nil {
userName = userData.Username
}
res.Maintainers = []types.Maintainer{{Name: userName}}
} else {
for _, m := range maintainers {
ne := strings.Split(m, ":")
email := ""
if len(ne) > 1 {
email = ne[1]
}
res.Maintainers = append(res.Maintainers, types.Maintainer{Name: ne[0], Email: email})
}
}
return res
}