-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathupdate.go
More file actions
329 lines (283 loc) · 10.1 KB
/
update.go
File metadata and controls
329 lines (283 loc) · 10.1 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"errors"
"fmt"
"io"
"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/internal/tracing/resource"
"github.com/azure/azure-dev/cli/azd/pkg/alpha"
"github.com/azure/azure-dev/cli/azd/pkg/config"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/installer"
"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/update"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type updateFlags struct {
channel string
checkIntervalHours int
global *internal.GlobalCommandOptions
}
func newUpdateFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *updateFlags {
flags := &updateFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
func (f *updateFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
f.global = global
local.StringVar(
&f.channel,
"channel",
"",
"Update channel: stable or daily.",
)
local.IntVar(
&f.checkIntervalHours,
"check-interval-hours",
0,
"Override the update check interval in hours.",
)
}
func newUpdateCmd() *cobra.Command {
return &cobra.Command{
Use: "update",
Short: "Updates azd to the latest version.",
Hidden: true,
}
}
type updateAction struct {
flags *updateFlags
console input.Console
formatter output.Formatter
writer io.Writer
configManager config.UserConfigManager
commandRunner exec.CommandRunner
alphaFeatureManager *alpha.FeatureManager
}
func newUpdateAction(
flags *updateFlags,
console input.Console,
formatter output.Formatter,
writer io.Writer,
configManager config.UserConfigManager,
commandRunner exec.CommandRunner,
alphaFeatureManager *alpha.FeatureManager,
) actions.Action {
return &updateAction{
flags: flags,
console: console,
formatter: formatter,
writer: writer,
configManager: configManager,
commandRunner: commandRunner,
alphaFeatureManager: alphaFeatureManager,
}
}
func (a *updateAction) Run(ctx context.Context) (*actions.ActionResult, error) {
// Non-production builds (dev and PR) should not self-update.
if internal.IsNonProdVersion() {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf("not supported for dev or PR builds: %w", internal.ErrUnsupportedOperation),
Suggestion: "Build from source or install a release build to use 'azd update'.",
}
}
// Auto-enable the alpha feature if not already enabled.
// The user's intent is clear by running `azd update` directly.
if !a.alphaFeatureManager.IsEnabled(update.FeatureUpdate) {
userCfg, err := a.configManager.Load()
if err != nil {
userCfg = config.NewEmptyConfig()
}
if err := userCfg.Set(fmt.Sprintf("alpha.%s", update.FeatureUpdate), "on"); err != nil {
return nil, fmt.Errorf("failed to enable update feature: %w", err)
}
if err := a.configManager.Save(userCfg); err != nil {
return nil, fmt.Errorf("failed to save config: %w", err)
}
a.console.MessageUxItem(ctx, &ux.MessageTitle{
Title: "azd update is in alpha. Channel-aware version checks are now enabled.\n",
})
}
// Track install method for telemetry
installedBy := installer.InstalledBy()
tracing.SetUsageAttributes(
fields.UpdateInstallMethod.String(string(installedBy)),
)
userConfig, err := a.configManager.Load()
if err != nil {
userConfig = config.NewEmptyConfig()
}
// Determine current channel BEFORE persisting any flags
currentCfg := update.LoadUpdateConfig(userConfig)
switchingChannels := a.flags.channel != "" && update.Channel(a.flags.channel) != currentCfg.Channel
// Persist non-channel config flags immediately (auto-update, check-interval)
configChanged, err := a.persistNonChannelFlags(userConfig)
if err != nil {
return nil, err
}
// If switching channels, persist channel to a temporary config for the version check
// but don't save to disk until after confirmation
if switchingChannels {
newChannel, err := update.ParseChannel(a.flags.channel)
if err != nil {
return nil, err
}
_ = update.SaveChannel(userConfig, newChannel)
configChanged = true
} else if a.flags.channel != "" {
// Same channel explicitly set — just persist it
if err := update.SaveChannel(userConfig, update.Channel(a.flags.channel)); err != nil {
return nil, err
}
configChanged = true
}
cfg := update.LoadUpdateConfig(userConfig)
// Track channel for telemetry
tracing.SetUsageAttributes(
fields.UpdateChannel.String(string(cfg.Channel)),
fields.UpdateFromVersion.String(internal.VersionInfo().Version.String()),
)
mgr := update.NewManager(a.commandRunner, nil)
// Block update in CI/CD environments
if resource.IsRunningOnCI() {
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeSkippedCI))
return nil, &update.UpdateError{
Code: update.CodeSkippedCI,
Err: &internal.ErrorWithSuggestion{
Err: fmt.Errorf("azd update is not supported in CI/CD environments"),
Suggestion: "Use your pipeline to install the desired version directly.",
},
}
}
// Check if the user is trying to switch to daily via a package manager
if a.flags.channel == string(update.ChannelDaily) && update.IsPackageManagerInstall() {
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodePackageManagerFailed))
uninstallCmd := update.PackageManagerUninstallCmd(installedBy)
return nil, &update.UpdateError{
Code: update.CodePackageManagerFailed,
Err: &internal.ErrorWithSuggestion{
Err: fmt.Errorf("daily builds aren't available via %s", installedBy),
Suggestion: fmt.Sprintf(
"Uninstall first with: %s\nThen install daily with: "+
"powershell -ex AllSigned -c \"Invoke-RestMethod 'https://aka.ms/install-azd.ps1'"+
" -OutFile 'install-azd.ps1'; ./install-azd.ps1 -Version 'daily'\"",
uninstallCmd),
},
}
}
// If only config flags were set (no channel change, no update needed), just confirm
if a.onlyConfigFlagsSet() {
if configChanged {
if err := a.configManager.Save(userConfig); err != nil {
return nil, fmt.Errorf("failed to save config: %w", err)
}
}
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeSuccess))
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: "Update preferences saved.",
},
}, nil
}
// Check for updates (always fresh for manual invocation)
a.console.ShowSpinner(ctx, "Checking for updates...", input.Step)
versionInfo, err := mgr.CheckForUpdate(ctx, cfg, true)
a.console.StopSpinner(ctx, "", input.StepDone)
if err != nil {
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeVersionCheckFailed))
return nil, &update.UpdateError{
Code: update.CodeVersionCheckFailed, Err: err,
}
}
// Track target version
tracing.SetUsageAttributes(
fields.UpdateToVersion.String(versionInfo.Version),
)
if !versionInfo.HasUpdate && !switchingChannels {
currentVersion := internal.VersionInfo().Version.String()
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeAlreadyUpToDate))
header := fmt.Sprintf("azd is up to date (version %s) on the %s channel.", currentVersion, cfg.Channel)
if cfg.Channel == update.ChannelDaily {
header += " To check for stable updates, run: azd update --channel stable"
}
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: header,
},
}, nil
}
// Confirm channel switch with version details
if switchingChannels {
currentVersion := internal.VersionInfo().Version.String()
confirmMsg := fmt.Sprintf(
"Switch from %s channel (%s) to %s channel (%s)?",
currentCfg.Channel, currentVersion,
cfg.Channel, versionInfo.Version,
)
confirm, err := a.console.Confirm(ctx, input.ConsoleOptions{
Message: confirmMsg,
DefaultValue: true,
})
if err != nil || !confirm {
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeChannelSwitchDecline))
a.console.Message(ctx, "Channel switch cancelled.")
return nil, nil
}
}
// Now persist all config changes (including channel) after confirmation
if configChanged {
if err := a.configManager.Save(userConfig); err != nil {
return nil, fmt.Errorf("failed to save config: %w", err)
}
}
// Perform the update
a.console.MessageUxItem(ctx, &ux.MessageTitle{
Title: fmt.Sprintf("Updating azd to %s (%s)", versionInfo.Version, cfg.Channel),
})
stdout := a.console.Handles().Stdout
if err := mgr.Update(ctx, cfg, stdout); err != nil {
// UpdateError already has the right code, just track it
if updateErr, ok := errors.AsType[*update.UpdateError](err); ok {
tracing.SetUsageAttributes(fields.UpdateResult.String(updateErr.Code))
} else {
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeReplaceFailed))
}
return nil, err
}
tracing.SetUsageAttributes(fields.UpdateResult.String(update.CodeSuccess))
// Clean up any staged binary now that a manual update succeeded
update.CleanStagedUpdate()
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: fmt.Sprintf(
"Updated azd to version %s. Changes take effect on next invocation.",
versionInfo.Version,
),
},
}, nil
}
// persistNonChannelFlags saves check-interval flags to config.
// Channel is handled separately to allow confirmation before persisting.
func (a *updateAction) persistNonChannelFlags(cfg config.Config) (bool, error) {
changed := false
if a.flags.checkIntervalHours > 0 {
if err := update.SaveCheckIntervalHours(cfg, a.flags.checkIntervalHours); err != nil {
return false, err
}
changed = true
}
return changed, nil
}
// onlyConfigFlagsSet returns true if only config flags were provided (no channel that requires an update).
func (a *updateAction) onlyConfigFlagsSet() bool {
return a.flags.channel == "" && a.flags.checkIntervalHours > 0
}