-
Notifications
You must be signed in to change notification settings - Fork 167
/
initializer.go
597 lines (504 loc) · 16 KB
/
initializer.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Package repository provides handling of files in the user's code repository.
package repository
import (
"bufio"
"context"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/environment/azdcontext"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/lazy"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/output/ux"
"github.com/azure/azure-dev/cli/azd/pkg/project"
"github.com/azure/azure-dev/cli/azd/pkg/templates"
"github.com/azure/azure-dev/cli/azd/pkg/tools/dotnet"
"github.com/azure/azure-dev/cli/azd/pkg/tools/git"
"github.com/azure/azure-dev/cli/azd/resources"
"github.com/otiai10/copy"
)
// Initializer handles the initialization of a local repository.
type Initializer struct {
console input.Console
gitCli git.GitCli
dotnetCli dotnet.DotNetCli
lazyEnvManager *lazy.Lazy[environment.Manager]
}
func NewInitializer(
console input.Console,
gitCli git.GitCli,
dotnetCli dotnet.DotNetCli,
lazyEnvManager *lazy.Lazy[environment.Manager],
) *Initializer {
return &Initializer{
console: console,
gitCli: gitCli,
lazyEnvManager: lazyEnvManager,
dotnetCli: dotnetCli,
}
}
// Initializes a local repository in the project directory from a remote repository.
//
// A confirmation prompt is displayed for any existing files to be overwritten.
func (i *Initializer) Initialize(
ctx context.Context,
azdCtx *azdcontext.AzdContext,
template *templates.Template,
templateBranch string) error {
var err error
stepMessage := fmt.Sprintf("Downloading template code to: %s", output.WithLinkFormat("%s", azdCtx.ProjectDirectory()))
i.console.ShowSpinner(ctx, stepMessage, input.Step)
defer i.console.StopSpinner(ctx, stepMessage+"\n", input.GetStepResultFormat(err))
staging, err := os.MkdirTemp("", "az-dev-template")
if err != nil {
return fmt.Errorf("creating temp folder: %w", err)
}
// Attempt to remove the temporary directory we cloned the template into, but don't fail the
// overall operation if we can't.
defer func() {
_ = os.RemoveAll(staging)
}()
target := azdCtx.ProjectDirectory()
templateUrl, err := templates.Absolute(template.RepositoryPath)
if err != nil {
return err
}
filesWithExecPerms, err := i.fetchCode(ctx, templateUrl, templateBranch, staging)
if err != nil {
return err
}
skipStagingFiles, err := i.promptForDuplicates(ctx, staging, target)
if err != nil {
return err
}
isEmpty, err := isEmptyDir(target)
if err != nil {
return err
}
options := copy.Options{}
if skipStagingFiles != nil {
options.Skip = func(fileInfo os.FileInfo, src, dest string) (bool, error) {
if _, shouldSkip := skipStagingFiles[src]; shouldSkip {
return true, nil
}
return false, nil
}
}
if err := copy.Copy(staging, target, options); err != nil {
return fmt.Errorf("copying template contents from temp staging directory: %w", err)
}
err = i.writeCoreAssets(ctx, azdCtx)
if err != nil {
return err
}
if err := i.initializeProject(ctx, azdCtx, &template.Metadata); err != nil {
return fmt.Errorf("initializing project: %w", err)
}
err = i.gitInitialize(ctx, target, filesWithExecPerms, isEmpty)
if err != nil {
return err
}
i.console.StopSpinner(ctx, stepMessage+"\n", input.GetStepResultFormat(err))
return nil
}
func (i *Initializer) fetchCode(
ctx context.Context,
templateUrl string,
templateBranch string,
destination string) (executableFilePaths []string, err error) {
err = i.gitCli.ShallowClone(ctx, templateUrl, templateBranch, destination)
if err != nil {
return nil, fmt.Errorf("fetching template: %w", err)
}
stagedFilesOutput, err := i.gitCli.ListStagedFiles(ctx, destination)
if err != nil {
return nil, fmt.Errorf("listing files with permissions: %w", err)
}
executableFilePaths, err = parseExecutableFiles(stagedFilesOutput)
if err != nil {
return nil, fmt.Errorf("parsing file permissions output: %w", err)
}
if err := os.RemoveAll(filepath.Join(destination, ".git")); err != nil {
return nil, fmt.Errorf("removing .git folder after clone: %w", err)
}
return executableFilePaths, nil
}
// promptForDuplicates prompts the user for any duplicate files detected.
// The list of absolute source file paths to skip are returned.
func (i *Initializer) promptForDuplicates(
ctx context.Context, staging string, target string) (skipSourceFiles map[string]struct{}, err error) {
log.Printf(
"template init, checking for duplicates. source: %s target: %s",
staging,
target,
)
duplicateFiles, err := determineDuplicates(staging, target)
if err != nil {
return nil, fmt.Errorf("checking for overwrites: %w", err)
}
if len(duplicateFiles) > 0 {
i.console.StopSpinner(ctx, "", input.StepDone)
i.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: "The following files are present both locally and in the template:",
})
for _, file := range duplicateFiles {
i.console.Message(ctx, fmt.Sprintf(" * %s", file))
}
selection, err := i.console.Select(ctx, input.ConsoleOptions{
Message: "What would you like to do with these files?",
Options: []string{
"Overwrite with versions from template",
"Keep my existing files unchanged",
},
})
if err != nil {
return nil, fmt.Errorf("prompting to overwrite: %w", err)
}
switch selection {
case 0: // overwrite
return nil, nil
case 1: // keep
skipSourceFiles = make(map[string]struct{}, len(duplicateFiles))
for _, file := range duplicateFiles {
// this also cleans the result, which is important for matching
sourceFile := filepath.Join(staging, file)
skipSourceFiles[sourceFile] = struct{}{}
}
return skipSourceFiles, nil
}
}
return nil, nil
}
func (i *Initializer) gitInitialize(ctx context.Context,
target string,
executableFilesToRestore []string,
stageAllFiles bool) error {
err := i.ensureGitRepository(ctx, target)
if err != nil {
return err
}
// Set executable files
for _, executableFile := range executableFilesToRestore {
err = i.gitCli.AddFileExecPermission(ctx, target, executableFile)
if err != nil {
return fmt.Errorf("restoring file permissions: %w", err)
}
}
if stageAllFiles {
err = i.gitCli.AddFile(ctx, target, "*")
if err != nil {
return fmt.Errorf("staging newly fetched template files: %w", err)
}
}
return nil
}
func (i *Initializer) ensureGitRepository(ctx context.Context, repoPath string) error {
_, err := i.gitCli.GetCurrentBranch(ctx, repoPath)
if err != nil {
if !errors.Is(err, git.ErrNotRepository) {
return fmt.Errorf("determining current git repository state: %w", err)
}
err = i.gitCli.InitRepo(ctx, repoPath)
if err != nil {
return fmt.Errorf("initializing git repository: %w", err)
}
i.console.MessageUxItem(ctx, &ux.DoneMessage{Message: "Initialized git repository"})
}
return nil
}
// Initialize the project with any metadata values from the template
func (i *Initializer) initializeProject(
ctx context.Context,
azdCtx *azdcontext.AzdContext,
templateMetaData *templates.Metadata,
) error {
if templateMetaData == nil || len(templateMetaData.Project) == 0 {
return nil
}
projectPath := azdCtx.ProjectPath()
projectConfig, err := project.LoadConfig(ctx, projectPath)
if err != nil {
return fmt.Errorf("loading project config: %w", err)
}
for key, value := range templateMetaData.Project {
if err := projectConfig.Set(key, value); err != nil {
return fmt.Errorf("setting project config: %w", err)
}
}
return project.SaveConfig(ctx, projectConfig, projectPath)
}
func parseExecutableFiles(stagedFilesOutput string) ([]string, error) {
scanner := bufio.NewScanner(strings.NewReader(stagedFilesOutput))
executableFiles := []string{}
for scanner.Scan() {
// Format for git ls --stage:
// <mode> <object> <stage>\t<file>
// In other words, space delimited for first three properties, tab delimited before filepath is present4ed
// Scan first word to obtain <mode>
advance, word, err := bufio.ScanWords(scanner.Bytes(), false)
if err != nil {
return nil, err
}
// 100755 is the only possible mode for git-tracked executable files
if string(word) == "100755" {
// Advance to past '\t', taking the remainder which is <file>
_, filepath, found := strings.Cut(scanner.Text()[advance:], "\t")
if !found {
return nil, errors.New("invalid staged files output format, missing file path")
}
executableFiles = append(executableFiles, filepath)
}
}
return executableFiles, nil
}
// Initializes a minimal azd project.
func (i *Initializer) InitializeMinimal(ctx context.Context, azdCtx *azdcontext.AzdContext) error {
projectDir := azdCtx.ProjectDirectory()
var err error
projectFormatted := output.WithLinkFormat("%s", projectDir)
i.console.ShowSpinner(ctx,
fmt.Sprintf("Creating minimal project files at: %s", projectFormatted),
input.Step)
defer i.console.StopSpinner(ctx,
fmt.Sprintf("Created minimal project files at: %s", projectFormatted)+"\n",
input.GetStepResultFormat(err))
isEmpty, err := isEmptyDir(projectDir)
if err != nil {
return err
}
err = i.writeCoreAssets(ctx, azdCtx)
if err != nil {
return err
}
projectConfig, err := project.Load(ctx, azdCtx.ProjectPath())
if err != nil {
return err
}
// Default infra path if not specified
infraPath := projectConfig.Infra.Path
if infraPath == "" {
infraPath = project.DefaultPath
}
err = os.MkdirAll(infraPath, osutil.PermissionDirectory)
if err != nil {
return err
}
module := projectConfig.Infra.Module
if projectConfig.Infra.Module == "" {
module = project.DefaultModule
}
mainPath := filepath.Join(infraPath, module)
retryInfix := ".azd"
err = i.writeFileSafe(
ctx,
fmt.Sprintf("%s.bicep", mainPath),
retryInfix,
resources.MinimalBicep,
osutil.PermissionFile)
if err != nil {
return err
}
err = i.writeFileSafe(
ctx,
fmt.Sprintf("%s.parameters.json", mainPath),
retryInfix,
resources.MinimalBicepParameters,
osutil.PermissionFile)
if err != nil {
return err
}
err = i.gitInitialize(ctx, projectDir, []string{}, isEmpty)
if err != nil {
return err
}
return nil
}
// writeFileSafe writes a file to path but only if it doesn't already exist.
// If it does exist, an extra attempt is performed to write the file with the retryInfix appended to the filename,
// before the file extension.
// If both files exist, no action is taken.
func (i *Initializer) writeFileSafe(
ctx context.Context,
path string,
retryInfix string,
content []byte,
perm fs.FileMode) error {
_, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return os.WriteFile(path, content, perm)
}
if err != nil {
return err
}
if retryInfix == "" {
return nil
}
ext := filepath.Ext(path)
pathNoExt := strings.TrimSuffix(path, ext)
renamed := pathNoExt + retryInfix + ext
_, err = os.Stat(renamed)
if errors.Is(err, os.ErrNotExist) {
i.console.MessageUxItem(
ctx,
&ux.WarningMessage{
Description: fmt.Sprintf("A file already exists at %s, writing to %s instead", path, renamed),
})
return os.WriteFile(renamed, content, perm)
}
// If both files exist, do nothing. We don't want to accidentally overwrite a user's file.
return err
}
func (i *Initializer) writeCoreAssets(ctx context.Context, azdCtx *azdcontext.AzdContext) error {
// Check to see if `azure.yaml` exists, and if it doesn't, create it.
if _, err := os.Stat(azdCtx.ProjectPath()); errors.Is(err, os.ErrNotExist) {
_, err = project.New(ctx, azdCtx.ProjectPath(), azdCtx.GetDefaultProjectName())
if err != nil {
return fmt.Errorf("failed to create a project file: %w", err)
}
i.console.MessageUxItem(ctx,
&ux.DoneMessage{Message: fmt.Sprintf("Created a new %s file", azdcontext.ProjectFileName)})
}
//create .azure when running azd init
err := os.MkdirAll(
filepath.Join(azdCtx.ProjectDirectory(), azdcontext.EnvironmentDirectoryName),
osutil.PermissionDirectory,
)
if err != nil {
return fmt.Errorf("failed to create a directory: %w", err)
}
//create .gitignore or open existing .gitignore file, and contains .azure
gitignoreFile, err := os.OpenFile(
filepath.Join(azdCtx.ProjectDirectory(), ".gitignore"),
os.O_APPEND|os.O_RDWR|os.O_CREATE,
osutil.PermissionFile,
)
if err != nil {
return fmt.Errorf("fail to create or open .gitignore: %w", err)
}
defer gitignoreFile.Close()
writeGitignoreFile := true
// Determines newline based on the last line containing a newline
useCrlf := false
// default to true, since if the file is empty, no preceding newline is needed.
hasTrailingNewLine := true
//bufio scanner splits on new lines by default
reader := bufio.NewReader(gitignoreFile)
for {
text, err := reader.ReadString('\n')
if err == nil {
// reset unless we're on the last line
useCrlf = false
}
if err != nil && len(text) > 0 {
// err != nil means no delimiter (newline) was found
// if text is present, that must mean the last line doesn't contain newline
hasTrailingNewLine = false
}
if len(text) > 0 && text[len(text)-1] == '\n' {
text = text[0 : len(text)-1]
}
if len(text) > 0 && text[len(text)-1] == '\r' {
text = text[0 : len(text)-1]
useCrlf = true
}
// match on entire line
// gitignore files can't have comments inline
if azdcontext.EnvironmentDirectoryName == text {
writeGitignoreFile = false
break
}
// EOF
if err != nil {
break
}
}
if writeGitignoreFile {
newLine := "\n"
if useCrlf {
newLine = "\r\n"
}
appendContents := azdcontext.EnvironmentDirectoryName + newLine
if !hasTrailingNewLine {
appendContents = newLine + appendContents
}
_, err := gitignoreFile.WriteString(appendContents)
if err != nil {
return fmt.Errorf("fail to write '%s' in .gitignore: %w", azdcontext.EnvironmentDirectoryName, err)
}
}
return nil
}
// PromptIfNonEmpty prompts the user for confirmation if the project directory to initialize in is non-empty.
// Returns error if an error occurred while prompting, or if the user declines confirmation.
func (i *Initializer) PromptIfNonEmpty(ctx context.Context, azdCtx *azdcontext.AzdContext) error {
dir := azdCtx.ProjectDirectory()
isEmpty, err := isEmptyDir(dir)
if err != nil {
return err
}
if !isEmpty {
_, err := i.gitCli.GetCurrentBranch(ctx, dir)
if err != nil && !errors.Is(err, git.ErrNotRepository) {
return fmt.Errorf("determining current git repository state: %w", err)
}
warningMessage := output.WithWarningFormat("WARNING: The current directory is not empty.")
i.console.Message(ctx, warningMessage)
i.console.Message(ctx, "Initializing an app in this directory may overwrite existing files.\n")
message := fmt.Sprintf(
"Continue initializing an app in '%s'?",
dir)
if err != nil {
message = fmt.Sprintf(
"Continue initializing an app here? This will also initialize a new git repository in '%s'.",
dir)
}
confirm, err := i.console.Confirm(ctx, input.ConsoleOptions{
Message: message,
})
if err != nil {
return err
}
if !confirm {
return fmt.Errorf("confirmation declined")
}
}
return nil
}
// Returns files that are both present in source and target.
// The files returned are expressed in their relative paths to source/target.
func determineDuplicates(source string, target string) ([]string, error) {
var duplicateFiles []string
if err := filepath.WalkDir(source, func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() {
return nil
}
partial, err := filepath.Rel(source, path)
if err != nil {
return fmt.Errorf("computing relative path: %w", err)
}
if _, err := os.Stat(filepath.Join(target, partial)); err == nil {
duplicateFiles = append(duplicateFiles, partial)
}
return nil
}); err != nil {
return nil, fmt.Errorf("enumerating template files: %w", err)
}
return duplicateFiles, nil
}
func isEmptyDir(dir string) (bool, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return false, fmt.Errorf("determining empty directory: %w", err)
}
return len(entries) == 0, nil
}