-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
templates.go
467 lines (402 loc) 路 12.6 KB
/
templates.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package workspace
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"gopkg.in/yaml.v2"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/resource/config"
"github.com/pulumi/pulumi/pkg/tokens"
"github.com/pulumi/pulumi/pkg/util/contract"
)
const (
defaultProjectName = "project"
// This file will be ignored when copying from the template cache to
// a project directory.
pulumiTemplateManifestFile = ".pulumi.template.yaml"
)
// Template represents a project template.
type Template struct {
// The name of the template.
Name string `json:"name" yaml:"name"`
// Optional description of the template, also used as a default project description.
Description string `json:"description" yaml:"description"`
// Optional bool which determines whether dependencies should be installed after project creation.
InstallDependencies bool `json:"installdependencies" yaml:"installdependencies"`
// Optional default config values.
Config map[config.Key]string `json:"config" yaml:"config"`
}
// LoadLocalTemplate returns a local template.
func LoadLocalTemplate(name string) (Template, error) {
templateDir, err := GetTemplateDir(name)
if err != nil {
return Template{}, err
}
info, err := os.Stat(templateDir)
if err != nil {
return Template{}, err
}
if !info.IsDir() {
return Template{}, errors.Errorf("template '%s' in %s is not a directory", name, templateDir)
}
// Read the description from the manifest (if it exists).
template, err := readTemplateManifest(filepath.Join(templateDir, pulumiTemplateManifestFile))
if err != nil && !os.IsNotExist(err) {
return Template{}, err
}
template.Name = name
return template, nil
}
// ListLocalTemplates returns a list of local templates.
func ListLocalTemplates() ([]Template, error) {
templateDir, err := GetTemplateDir("")
if err != nil {
return nil, err
}
infos, err := ioutil.ReadDir(templateDir)
if err != nil {
return nil, err
}
var templates []Template
for _, info := range infos {
if info.IsDir() {
template, err := LoadLocalTemplate(info.Name())
if err != nil {
return nil, err
}
templates = append(templates, template)
}
}
return templates, nil
}
// InstallTemplate installs a template tarball into the local cache.
func InstallTemplate(name string, tarball io.ReadCloser) error {
contract.Require(name != "", "name")
contract.Require(tarball != nil, "tarball")
var templateDir string
var err error
// Get the template directory.
if templateDir, err = GetTemplateDir(name); err != nil {
return err
}
// Delete the directory if it exists.
if err = os.RemoveAll(templateDir); err != nil {
return errors.Wrapf(err, "removing existing template directory %s", templateDir)
}
// Ensure it exists since we may have just deleted it.
if err = os.MkdirAll(templateDir, 0700); err != nil {
return errors.Wrapf(err, "creating template directory %s", templateDir)
}
// Extract the tarball to its directory.
if err = extractTarball(tarball, templateDir); err != nil {
return errors.Wrapf(err, "extracting template to %s", templateDir)
}
// On Windows, we need to replace \n with \r\n. We'll just do this as a separate step.
if runtime.GOOS == "windows" {
if err = fixWindowsLineEndings(templateDir); err != nil {
return errors.Wrapf(err, "fixing line endings in %s", templateDir)
}
}
return nil
}
// CopyTemplateFilesDryRun does a dry run of copying a template to a destination directory,
// to ensure it won't overwrite any files.
func (template Template) CopyTemplateFilesDryRun(destDir string) error {
var err error
var sourceDir string
if sourceDir, err = GetTemplateDir(template.Name); err != nil {
return err
}
var existing []string
err = walkFiles(sourceDir, destDir, func(info os.FileInfo, source string, dest string) error {
if destInfo, statErr := os.Stat(dest); statErr == nil && !destInfo.IsDir() {
existing = append(existing, filepath.Base(dest))
}
return nil
})
if err != nil {
return err
}
if len(existing) > 0 {
return newExistingFilesError(existing)
}
return nil
}
// CopyTemplateFiles does the actual copy operation to a destination directory.
func (template Template) CopyTemplateFiles(
destDir string, force bool, projectName string, projectDescription string) error {
sourceDir, err := GetTemplateDir(template.Name)
if err != nil {
return err
}
return walkFiles(sourceDir, destDir, func(info os.FileInfo, source string, dest string) error {
if info.IsDir() {
// Create the destination directory.
return os.Mkdir(dest, 0700)
}
// Read the source file.
b, err := ioutil.ReadFile(source)
if err != nil {
return err
}
// Transform only if it isn't a binary file.
result := b
if !isBinary(b) {
transformed := transform(string(b), projectName, projectDescription)
result = []byte(transformed)
}
// Write to the destination file.
err = writeAllBytes(dest, result, force)
if err != nil {
// An existing file has shown up in between the dry run and the actual copy operation.
if os.IsExist(err) {
return newExistingFilesError([]string{filepath.Base(dest)})
}
}
return err
})
}
// GetTemplateDir returns the directory in which templates on the current machine are stored.
func GetTemplateDir(name string) (string, error) {
u, err := user.Current()
if u == nil || err != nil {
return "", errors.Wrap(err, "getting user home directory")
}
dir := filepath.Join(u.HomeDir, BookkeepingDir, TemplateDir)
if name != "" {
dir = filepath.Join(dir, name)
}
return dir, nil
}
// IsValidProjectName returns true if the project name is a valid name.
func IsValidProjectName(name string) bool {
return tokens.IsPackageName(name)
}
// ValueOrSanitizedDefaultProjectName returns the value or a sanitized valid project name
// based on defaultNameToSanitize.
func ValueOrSanitizedDefaultProjectName(name string, defaultNameToSanitize string) string {
if name != "" {
return name
}
return getValidProjectName(defaultNameToSanitize)
}
// ValueOrDefaultProjectDescription returns the value or defaultDescription.
func ValueOrDefaultProjectDescription(description string, defaultDescription string) string {
if description != "" {
return description
}
if defaultDescription != "" {
return defaultDescription
}
return ""
}
// getValidProjectName returns a valid project name based on the passed-in name.
func getValidProjectName(name string) string {
// If the name is valid, return it.
if IsValidProjectName(name) {
return name
}
// Otherwise, try building-up the name, removing any invalid chars.
var result string
for i := 0; i < len(name); i++ {
temp := result + string(name[i])
if IsValidProjectName(temp) {
result = temp
}
}
// If we couldn't come up with a valid project name, fallback to a default.
if result == "" {
result = defaultProjectName
}
return result
}
// extractTarball extracts the tarball to the specified destination directory.
func extractTarball(tarball io.ReadCloser, destDir string) error {
// Unzip and untar the file as we go.
defer contract.IgnoreClose(tarball)
gzr, err := gzip.NewReader(tarball)
if err != nil {
return errors.Wrapf(err, "unzipping")
}
r := tar.NewReader(gzr)
for {
header, err := r.Next()
if err == io.EOF {
break
} else if err != nil {
return errors.Wrapf(err, "untarring")
}
path := filepath.Join(destDir, header.Name)
switch header.Typeflag {
case tar.TypeDir:
// Create any directories as needed.
if _, err := os.Stat(path); err != nil {
if err = os.MkdirAll(path, 0700); err != nil {
return errors.Wrapf(err, "untarring dir %s", path)
}
}
case tar.TypeReg:
// Expand files into the target directory.
dst, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return errors.Wrapf(err, "opening file %s for untar", path)
}
defer contract.IgnoreClose(dst)
if _, err = io.Copy(dst, r); err != nil {
return errors.Wrapf(err, "untarring file %s", path)
}
default:
return errors.Errorf("unexpected plugin file type %s (%v)", header.Name, header.Typeflag)
}
}
return nil
}
// walkFiles is a helper that walks the directories/files in a source directory
// and performs an action for each item.
func walkFiles(sourceDir string, destDir string,
actionFn func(info os.FileInfo, source string, dest string) error) error {
contract.Require(sourceDir != "", "sourceDir")
contract.Require(destDir != "", "destDir")
contract.Require(actionFn != nil, "actionFn")
infos, err := ioutil.ReadDir(sourceDir)
if err != nil {
return err
}
for _, info := range infos {
name := info.Name()
source := filepath.Join(sourceDir, name)
dest := filepath.Join(destDir, name)
if info.IsDir() {
if err := actionFn(info, source, dest); err != nil {
return err
}
if err := walkFiles(source, dest, actionFn); err != nil {
return err
}
} else {
// Ignore template manifest file.
if name == pulumiTemplateManifestFile {
continue
}
if err := actionFn(info, source, dest); err != nil {
return err
}
}
}
return nil
}
// readTemplateManifest reads a template manifest file.
func readTemplateManifest(filename string) (Template, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return Template{}, err
}
var manifest Template
err = yaml.Unmarshal(b, &manifest)
if err != nil {
return Template{}, err
}
return manifest, nil
}
// newExistingFilesError returns a new error from a list of existing file names
// that would be overwritten.
func newExistingFilesError(existing []string) error {
contract.Assert(len(existing) > 0)
message := "creating this template will make changes to existing files:\n"
for _, file := range existing {
message = message + fmt.Sprintf(" overwrite %s\n", file)
}
message = message + "\nrerun the command and pass --force to accept and create"
return errors.New(message)
}
// transform returns a new string with ${PROJECT} and ${DESCRIPTION} replaced by
// the value of projectName and projectDescription.
func transform(content string, projectName string, projectDescription string) string {
content = strings.Replace(content, "${PROJECT}", projectName, -1)
content = strings.Replace(content, "${DESCRIPTION}", projectDescription, -1)
return content
}
// writeAllBytes writes the bytes to the specified file, with an option to overwrite.
func writeAllBytes(filename string, bytes []byte, overwrite bool) error {
flag := os.O_WRONLY | os.O_CREATE
if overwrite {
flag = flag | os.O_TRUNC
} else {
flag = flag | os.O_EXCL
}
f, err := os.OpenFile(filename, flag, 0600)
if err != nil {
return err
}
defer contract.IgnoreClose(f)
_, err = f.Write(bytes)
return err
}
// isBinary returns true if a zero byte occurs within the first
// 8000 bytes (or the entire length if shorter). This is the
// same approach that git uses to determine if a file is binary.
func isBinary(bytes []byte) bool {
const firstFewBytes = 8000
length := len(bytes)
if firstFewBytes < length {
length = firstFewBytes
}
for i := 0; i < length; i++ {
if bytes[i] == 0 {
return true
}
}
return false
}
// fixWindowsLineEndings will go through the sourceDir, read each file, replace \n with \r\n,
// and save the changes.
// It'd be more efficient to do this during tarball extraction, but this is sufficient for now.
func fixWindowsLineEndings(sourceDir string) error {
return walkFiles(sourceDir, sourceDir, func(info os.FileInfo, source string, dest string) error {
// Skip directories.
if info.IsDir() {
return nil
}
// Read the source file.
b, err := ioutil.ReadFile(source)
if err != nil {
return err
}
// Transform only if it isn't a binary file.
result := b
if !isBinary(b) {
content := string(b)
content = strings.Replace(content, "\n", "\r\n", -1)
result = []byte(content)
}
// Write to the destination file.
err = writeAllBytes(dest, result, true /*overwrite*/)
if err != nil {
// An existing file has shown up in between the dry run and the actual copy operation.
if os.IsExist(err) {
return newExistingFilesError([]string{filepath.Base(dest)})
}
}
return err
})
}