-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathinit_templating.go
388 lines (334 loc) · 11.4 KB
/
init_templating.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
* Copyright (c) 2021-present Fabien Potencier <fabien@symfony.com>
*
* This file is part of Symfony CLI project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package commands
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"github.com/hashicorp/go-version"
"github.com/pkg/errors"
"github.com/symfony-cli/symfony-cli/git"
"github.com/symfony-cli/symfony-cli/local/platformsh"
"github.com/symfony-cli/symfony-cli/util"
"github.com/symfony-cli/terminal"
"gopkg.in/yaml.v2"
)
const templatesGitRepository = "https://github.com/symfonycorp/cloud-templates.git"
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error { return nil }
func createRequiredFilesProject(brand platformsh.CloudBrand, rootDirectory, projectSlug, templateName string, minorPHPVersion string, cloudServices []*CloudService, dump, force bool) ([]string, error) {
createdFiles := []string{}
templates, err := getTemplates(brand, rootDirectory, templateName, minorPHPVersion)
if err != nil {
return nil, errors.Wrap(err, "could not determine template to use")
}
publicDirectory := "public"
if fi, err := os.Stat(filepath.Join(rootDirectory, "web")); err == nil && fi.IsDir() {
publicDirectory = "web"
}
frontController := "index.php"
// Symfony installations can also have a front controller named app.php!
if _, err := os.Stat(filepath.Join(rootDirectory, publicDirectory, "app.php")); err == nil {
frontController = "app.php"
}
availablePHPExtensions := map[string][]string{
"postgresql": {"pdo_pgsql"},
"redis": {"redis"},
"rabbitmq": {"amqp"},
}
phpExts := append(phpExtensions(rootDirectory), "apcu", "mbstring", "sodium", "xsl", "blackfire")
for _, service := range cloudServices {
if v, ok := availablePHPExtensions[service.Type]; ok {
phpExts = append(phpExts, v...)
}
}
sort.Strings(phpExts)
serviceDiskSizes := map[string]string{
"postgresql": "1024",
}
data := &struct {
Slug string
FrontController string
PublicDirectory string
PhpVersion string
PHPExtensions []string
Services []*CloudService
ServiceDiskSizes map[string]string
}{
Slug: projectSlug,
FrontController: frontController,
PublicDirectory: publicDirectory,
PhpVersion: minorPHPVersion,
PHPExtensions: phpExts,
Services: cloudServices,
ServiceDiskSizes: serviceDiskSizes,
}
for file, templateText := range templates {
file = filepath.Join(rootDirectory, file)
var f io.WriteCloser
if dump {
f = nopCloser{terminal.Stdout}
fmt.Fprintf(f, "\n<info># %s:</>\n", file)
} else if _, err := os.Stat(file); !force && (err == nil || !os.IsNotExist(err)) {
terminal.Logger.Warn().Msgf("%s already exists, template generation skipped\n", file)
continue
} else {
createdFiles = append(createdFiles, file)
if dir := filepath.Dir(file); dir != "" {
if err := os.MkdirAll(dir, 0755); err != nil {
return createdFiles, errors.WithStack(errors.Wrapf(err, "unable to create directory %s", dir))
}
}
f, err = os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return createdFiles, errors.WithStack(errors.Wrapf(err, "unable to create %s", file))
}
}
if err = templateText.Execute(f, data); err != nil {
return createdFiles, errors.WithStack(errors.Wrapf(err, "unable to write to %s", file))
}
if err = f.Close(); err != nil {
return createdFiles, errors.WithStack(errors.Wrapf(err, "unable to close %s", file))
}
}
return createdFiles, nil
}
func isValidURL(toTest string) bool {
u, err := url.Parse(toTest)
if err != nil {
return false
}
if u.Host == "" {
return false
}
return true
}
func isValidFilePath(toTest string) bool {
f, err := os.Stat(toTest)
if err != nil {
return false
}
if f.IsDir() {
return false
}
return true
}
func getTemplates(brand platformsh.CloudBrand, rootDirectory, chosenTemplateName string, minorPHPVersion string) (map[string]*template.Template, error) {
var foundTemplate *configTemplate
s := terminal.NewSpinner(terminal.Stderr)
s.Start()
defer func() {
s.Stop()
}()
terminal.Println("Updating configuration templates")
directory := filepath.Join(util.GetHomeDir(), "cache", "templates")
if f, err := os.Stat(directory); err == nil && f.IsDir() {
terminal.Logger.Info().Msg("Updating configuration templates cache")
if err := git.Fetch(directory, templatesGitRepository, "master"); err != nil {
return nil, errors.Wrap(err, "could not update configuration templates")
}
if err := git.ResetHard(directory, "FETCH_HEAD"); err != nil {
return nil, errors.Wrap(err, "could not update configuration templates")
}
} else {
if err := os.MkdirAll(filepath.Dir(directory), 0755); err != nil {
return nil, errors.Wrapf(err, "unable to create directory for %s", directory)
}
terminal.Logger.Info().Msg("Initial configuration templates fetch")
if err := git.Clone(templatesGitRepository, directory); err != nil {
return nil, errors.Wrap(err, "could not fetch configuration templates")
}
}
if brand == platformsh.UpsunBrand {
directory = filepath.Join(directory, "upsun")
}
if isURL, isFile := isValidURL(chosenTemplateName), isValidFilePath(chosenTemplateName); isURL || isFile {
var (
templateConfigBytes []byte
err error
)
if isFile {
templateConfigBytes, err = os.ReadFile(chosenTemplateName)
} else {
var resp *http.Response
resp, err = http.Get(chosenTemplateName)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, errors.Errorf("Got HTTP status code >= 400: %s", resp.Status)
}
defer resp.Body.Close()
templateConfigBytes, err = io.ReadAll(resp.Body)
}
if err != nil {
return nil, errors.Wrap(err, "could not apply project template")
}
if err := yaml.Unmarshal(templateConfigBytes, &foundTemplate); err != nil {
return nil, errors.Wrap(err, "could not apply project template")
}
terminal.Logger.Info().Msg("Using template " + chosenTemplateName)
} else {
files, err := os.ReadDir(directory)
if err != nil {
return nil, errors.Wrap(err, "could not read configuration templates")
}
for _, file := range files {
if file.Name() == ".git" {
continue
}
if file.IsDir() {
terminal.Logger.Warn().Msg(file.Name() + " is not a regular file")
continue
}
if !strings.HasSuffix(file.Name(), ".yaml") {
continue
}
templateName := strings.TrimSuffix(file.Name(), ".yaml")[strings.Index(file.Name(), "-")+1:]
isTemplateChosen := chosenTemplateName == templateName
if chosenTemplateName != "" && !isTemplateChosen {
continue
}
templateConfigBytes, err := os.ReadFile(filepath.Join(directory, file.Name()))
if err != nil {
if isTemplateChosen {
return nil, errors.Wrap(err, "could not apply configuration template")
}
terminal.Logger.Warn().Msg(err.Error())
continue
}
var templateConfig configTemplate
if err := yaml.Unmarshal(templateConfigBytes, &templateConfig); err != nil {
if isTemplateChosen {
return nil, errors.Wrap(err, "could not apply configuration template")
}
terminal.Logger.Warn().Msg(err.Error())
continue
}
if chosenTemplateName == "" && !templateConfig.Match(rootDirectory, minorPHPVersion) {
continue
}
terminal.Printf("Using configuration template <info>%s</>\n", templateName)
foundTemplate = &templateConfig
break
}
}
if foundTemplate == nil {
return nil, errors.New("no matching template found")
}
phpini, err := os.ReadFile(filepath.Join(directory, "php.ini"))
if err != nil {
return nil, errors.New("unable to find the php.ini template")
}
servicesyaml := `
{{ range $service := $.Services -}}
{{ $service.Name }}:
type: {{ $service.Type }}{{ if $service.Version }}:{{ $service.Version }}{{ end }}
{{- if index $.ServiceDiskSizes $service.Type }}
disk: {{ index $.ServiceDiskSizes $service.Type }}
{{ end }}
{{ end -}}
`
templateFuncs := getTemplateFuncs(rootDirectory, minorPHPVersion)
var templates map[string]*template.Template
if brand == platformsh.UpsunBrand {
templates = map[string]*template.Template{
".upsun/config.yaml": template.Must(template.New("output").Funcs(templateFuncs).Parse(foundTemplate.Template)),
"php.ini": template.Must(template.New("output").Funcs(templateFuncs).Parse(string(phpini))),
}
} else {
templates = map[string]*template.Template{
".platform.app.yaml": template.Must(template.New("output").Funcs(templateFuncs).Parse(foundTemplate.Template)),
".platform/services.yaml": template.Must(template.New("output").Funcs(templateFuncs).Parse(servicesyaml)),
".platform/routes.yaml": template.Must(template.New("output").Funcs(templateFuncs).Parse(`"https://{all}/": { type: upstream, upstream: "{{.Slug}}:http" }
"http://{all}/": { type: redirect, to: "https://{all}/" }
`)),
"php.ini": template.Must(template.New("output").Funcs(templateFuncs).Parse(string(phpini))),
}
}
for path, tpl := range foundTemplate.ExtraFiles {
if _, alreadyExists := templates[path]; alreadyExists {
terminal.Logger.Info().Msgf("Skipping extra file<info>%s</>\n", path)
continue
}
templates[path] = template.Must(template.New("output").Funcs(templateFuncs).Parse(tpl))
}
return templates, nil
}
type configTemplate struct {
Requirements []configRequirement
ExtraFiles map[string]string `yaml:"extra_files"`
Template string
}
func (c *configTemplate) Match(directory, minorPHPVersion string) bool {
for _, req := range c.Requirements {
if !req.Check(directory, minorPHPVersion) {
return false
}
}
return true
}
type configRequirement struct {
Type, Value string
}
func (req configRequirement) Check(directory, minorPHPVersion string) bool {
if f, ok := getTemplateFuncs(directory, minorPHPVersion)[req.Type].(func(string) bool); ok {
return f(req.Value)
}
terminal.Logger.Error().Msg("unsupported check " + req.Type)
return false
}
func getTemplateFuncs(rootDirectory, minorPHPVersion string) template.FuncMap {
return template.FuncMap{
"file_exists": func(file string) bool {
_, err := os.Stat(filepath.Join(rootDirectory, file))
return err == nil
},
"has_composer_package": func(pkg string) bool {
return hasComposerPackage(rootDirectory, pkg)
},
"has_php_extension": func(ext string) bool {
return hasPHPExtension(rootDirectory, ext)
},
"php_extensions": func() []string {
// FIXME: obsolete, replaced by PHPExtensions, should be removed
return phpExtensions(rootDirectory)
},
"php_extension_available": platformsh.IsPhpExtensionAvailable,
"php_at_least": func(v string) bool {
minVersion, err := version.NewVersion(v)
if err != nil {
panic(err)
}
minorPHP, err := version.NewVersion(minorPHPVersion)
if err != nil {
panic(err)
}
return minorPHP.GreaterThanOrEqual(minVersion)
},
}
}