-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathhooks.go
More file actions
377 lines (323 loc) · 9.97 KB
/
hooks.go
File metadata and controls
377 lines (323 loc) · 9.97 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"fmt"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/ext"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/ioc"
"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/tools"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func hooksActions(root *actions.ActionDescriptor) *actions.ActionDescriptor {
group := root.Add("hooks", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "hooks",
Short: "Develop, test and run hooks for a project.",
},
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupBeta,
},
})
group.Add("run", &actions.ActionDescriptorOptions{
Command: newHooksRunCmd(),
FlagsResolver: newHooksRunFlags,
ActionResolver: newHooksRunAction,
})
return group
}
func newHooksRunFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *hooksRunFlags {
flags := &hooksRunFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
func newHooksRunCmd() *cobra.Command {
return &cobra.Command{
Use: "run <name>",
Short: "Runs the specified hook for the project and services",
Args: cobra.ExactArgs(1),
}
}
type hooksRunFlags struct {
internal.EnvFlag
global *internal.GlobalCommandOptions
platform string
service string
}
func (f *hooksRunFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
f.EnvFlag.Bind(local, global)
f.global = global
local.StringVar(&f.platform, "platform", "", "Forces hooks to run for the specified platform.")
local.StringVar(&f.service, "service", "", "Only runs hooks for the specified service.")
}
type hooksRunAction struct {
projectConfig *project.ProjectConfig
env *environment.Environment
envManager environment.Manager
importManager *project.ImportManager
commandRunner exec.CommandRunner
console input.Console
flags *hooksRunFlags
args []string
serviceLocator ioc.ServiceLocator
}
func newHooksRunAction(
projectConfig *project.ProjectConfig,
importManager *project.ImportManager,
env *environment.Environment,
envManager environment.Manager,
commandRunner exec.CommandRunner,
console input.Console,
flags *hooksRunFlags,
args []string,
serviceLocator ioc.ServiceLocator,
) actions.Action {
return &hooksRunAction{
projectConfig: projectConfig,
env: env,
envManager: envManager,
commandRunner: commandRunner,
console: console,
flags: flags,
args: args,
importManager: importManager,
serviceLocator: serviceLocator,
}
}
type hookContextType string
const (
hookContextProject hookContextType = "command"
hookContextService hookContextType = "service"
)
// knownHookNames is the set of built-in azd hook names.
// Extension-defined hooks are not included here; they are hashed in telemetry.
// See https://github.com/Azure/azure-dev/issues/7348 for tracking.
var knownHookNames = map[string]bool{
"prebuild": true,
"postbuild": true,
"predeploy": true,
"postdeploy": true,
"predown": true,
"postdown": true,
"prepackage": true,
"postpackage": true,
"preprovision": true,
"postprovision": true,
"prepublish": true,
"postpublish": true,
"prerestore": true,
"postrestore": true,
"preup": true,
"postup": true,
}
func (hra *hooksRunAction) Run(ctx context.Context) (*actions.ActionResult, error) {
hookName := hra.args[0]
hookType := "project"
if hra.flags.service != "" {
hookType = "service"
}
// Log known hook names raw; hash unknown names to avoid logging arbitrary user input.
hookNameAttr := fields.StringHashed(fields.HooksNameKey, hookName)
if knownHookNames[hookName] {
hookNameAttr = fields.HooksNameKey.String(hookName)
}
tracing.SetUsageAttributes(
hookNameAttr,
fields.HooksTypeKey.String(hookType),
)
// Command title
hra.console.MessageUxItem(ctx, &ux.MessageTitle{
Title: "Running hooks (azd hooks run)",
TitleNote: fmt.Sprintf(
"Finding and executing %s hooks for environment %s",
output.WithHighLightFormat(hookName),
output.WithHighLightFormat(hra.env.Name()),
),
})
// Validate hooks and display warnings
if err := hra.validateAndWarnHooks(ctx); err != nil {
return nil, fmt.Errorf("failed validating hooks: %w", err)
}
// Validate service name
if hra.flags.service != "" {
if has, err := hra.importManager.HasService(ctx, hra.projectConfig, hra.flags.service); err != nil {
return nil, err
} else if !has {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf("service '%s': %w", hra.flags.service, internal.ErrServiceNotFound),
Suggestion: "Check the service name in azure.yaml or run 'azd show' to list services.",
}
}
}
// Project level hooks
projectHooks := hra.projectConfig.Hooks[hookName]
hra.console.Message(ctx, output.WithHighLightFormat("Project"))
if err := hra.processHooks(
ctx,
hra.projectConfig.Path,
hookName,
projectHooks,
hookContextProject,
false,
); err != nil {
return nil, err
}
stableServices, err := hra.importManager.ServiceStable(ctx, hra.projectConfig)
if err != nil {
return nil, err
}
// Service level hooks
for _, service := range stableServices {
serviceHooks := service.Hooks[hookName]
skip := hra.flags.service != "" && service.Name != hra.flags.service
hra.console.Message(ctx, "\n"+output.WithHighLightFormat(service.Name))
if err := hra.processHooks(
ctx,
service.RelativePath,
hookName,
serviceHooks,
hookContextService,
skip,
); err != nil {
return nil, err
}
}
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: "Your hooks have been run successfully",
},
}, nil
}
func (hra *hooksRunAction) processHooks(
ctx context.Context,
cwd string,
hookName string,
hooks []*ext.HookConfig,
contextType hookContextType,
skip bool,
) error {
if len(hooks) == 0 {
hra.console.MessageUxItem(ctx, &ux.WarningAltMessage{Message: "No hooks found"})
return nil
}
if skip {
// When skipping, show individual skip messages for each hook that would have run
for i := range hooks {
hra.console.MessageUxItem(ctx, &ux.SkippedMessage{
Message: fmt.Sprintf("service hook %d/%d", i+1, len(hooks)),
})
}
return nil
}
hookType, commandName := ext.InferHookType(hookName)
for idx, hook := range hooks {
if err := hra.prepareHook(hookName, hook); err != nil {
return err
}
hra.console.Message(ctx, output.WithBold("%s hook %d/%d:", contextType, idx+1, len(hooks)))
err := hra.execHook(ctx, cwd, hookType, commandName, hook)
if err != nil {
return fmt.Errorf("failed running hook %s, %w", hookName, err)
}
hra.console.MessageUxItem(ctx, &ux.DoneMessage{
Message: "Successfully executed hook",
})
// Add blank line after each hook except the last one
if idx < len(hooks)-1 {
hra.console.Message(ctx, "")
}
}
return nil
}
func (hra *hooksRunAction) execHook(
ctx context.Context,
cwd string,
hookType ext.HookType,
commandName string,
hook *ext.HookConfig,
) error {
hookName := string(hookType) + commandName
hooksMap := map[string][]*ext.HookConfig{
hookName: {hook},
}
hooksManager := ext.NewHooksManager(cwd, hra.commandRunner)
hooksRunner := ext.NewHooksRunner(
hooksManager, hra.commandRunner, hra.envManager, hra.console, cwd, hooksMap, hra.env, hra.serviceLocator)
// Always run in interactive mode for 'azd hooks run', to help with testing/debugging
runOptions := &tools.ExecOptions{
Interactive: new(true),
}
err := hooksRunner.RunHooks(ctx, hookType, runOptions, commandName)
if err != nil {
return err
}
return nil
}
// Validates hooks and displays warnings for default shell usage and other issues
func (hra *hooksRunAction) validateAndWarnHooks(ctx context.Context) error {
// Collect all hooks from project and services
allHooks := make(map[string][]*ext.HookConfig)
// Add project hooks
for hookName, hookConfigs := range hra.projectConfig.Hooks {
allHooks[hookName] = append(allHooks[hookName], hookConfigs...)
}
// Add service hooks
stableServices, err := hra.importManager.ServiceStable(ctx, hra.projectConfig)
if err == nil {
for _, service := range stableServices {
for hookName, hookConfigs := range service.Hooks {
allHooks[hookName] = append(allHooks[hookName], hookConfigs...)
}
}
}
// Create hooks manager and validate
hooksManager := ext.NewHooksManager(hra.projectConfig.Path, hra.commandRunner)
validationResult := hooksManager.ValidateHooks(ctx, allHooks)
// Display any warnings
for _, warning := range validationResult.Warnings {
hra.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: warning.Message,
})
if warning.Suggestion != "" {
hra.console.Message(ctx, warning.Suggestion)
}
hra.console.Message(ctx, "")
}
return nil
}
// Overrides the configured hooks from command line flags
func (hra *hooksRunAction) prepareHook(name string, hook *ext.HookConfig) error {
// Enable testing cross platform
if hra.flags.platform != "" {
platformType := ext.HookPlatformType(hra.flags.platform)
switch platformType {
case ext.HookPlatformWindows:
if hook.Windows == nil {
return fmt.Errorf("hook is not configured for Windows")
} else {
*hook = *hook.Windows
}
case ext.HookPlatformPosix:
if hook.Posix == nil {
return fmt.Errorf("hook is not configured for Posix")
} else {
*hook = *hook.Posix
}
default:
return fmt.Errorf("platform %s is not valid. Supported values are windows & posix", hra.flags.platform)
}
}
hook.Name = name
return nil
}