Repository navigation
Expand file tree
/
Copy pathextension.go
More file actions
4238 lines (3832 loc) · 133 KB
/
Copy pathextension.go
File metadata and controls
4238 lines (3832 loc) · 133 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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"maps"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"text/tabwriter"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Masterminds/semver/v3"
"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/events"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/extensions"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"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/rzip"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel/codes"
)
// Register extension commands
func extensionActions(root *actions.ActionDescriptor) *actions.ActionDescriptor {
group := root.Add("extension", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "extension",
Aliases: []string{"ext"},
Short: "Manage azd extensions.",
},
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupBeta,
},
})
// azd extension list [--installed]
group.Add("list", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "list [--installed]",
Short: "List available extensions.",
Long: `List available extensions from registered extension sources.
The --source flag accepts a registered source name or registry location (URL or
file path). Locations are queried read-only and are not registered. Extensions
from an unregistered location show the location itself in the SOURCE column.`,
},
OutputFormats: []output.Format{output.JsonFormat, output.TableFormat},
DefaultFormat: output.TableFormat,
ActionResolver: newExtensionListAction,
FlagsResolver: newExtensionListFlags,
})
// azd extension show
group.Add("show", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "show <extension-id>",
Short: "Show details for a specific extension.",
Long: `Includes version compatibility, dependencies, and installed dependents.
Uses installed metadata when no registry lists the extension, or a registry lookup fails without --source.`,
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newExtensionShowAction,
FlagsResolver: newExtensionShowFlags,
})
// azd extension install <extension-id>
group.Add("install", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "install <extension-id|bundle-path-or-url>",
Short: "Installs specified extensions.",
Long: `Installs one or more extensions by id from a registered extension source.
The --source flag also accepts a registry location (URL or file path). When a
location is given, azd registers it as a source (prompting for a name, and
confirming first for a URL) and then installs from it. If the location is already
registered, azd reuses that source.
You can also pass a self-contained extension bundle as a local .zip path or an
https URL. Remote URLs may be shortened or opaque. azd follows redirects
automatically and warns when a download redirects from HTTPS to HTTP. Bundle
installs aren't tracked for updates; install a newer bundle to update.`,
},
ActionResolver: newExtensionInstallAction,
FlagsResolver: newExtensionInstallFlags,
})
// azd extension uninstall <extension-id>
group.Add("uninstall", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "uninstall [extension-id...]",
Short: "Uninstall specified extensions.",
Long: `Also removes unused dependency installs after confirmation.
Use --no-dependencies to keep them; --no-prompt accepts their removal.
Required extensions cannot be removed unless their dependents are also removed
or --force is set.`,
},
ActionResolver: newExtensionUninstallAction,
FlagsResolver: newExtensionUninstallFlags,
})
// azd extension update <extension-id>
group.Add("update", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "update [extension-id]",
Aliases: []string{"upgrade"},
Short: "Update installed extensions to the latest version.",
Long: `Also updates installed dependencies to compatible versions unless
--no-dependency-updates is set.
Failures return a nonzero exit code. Other extensions continue updating;
completed updates are kept.`,
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newExtensionUpgradeAction,
FlagsResolver: newExtensionUpgradeFlags,
})
sourceGroup := group.Add("source", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "source",
Short: "View and manage extension sources",
},
})
sourceGroup.Add("list", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "list",
Short: "List extension sources",
},
OutputFormats: []output.Format{output.JsonFormat, output.TableFormat},
DefaultFormat: output.TableFormat,
ActionResolver: newExtensionSourceListAction,
})
sourceGroup.Add("add", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "add",
Short: "Add an extension source with the specified name",
Long: "Add an extension source with the specified name.\n\n" +
"Names must contain 1-64 lowercase ASCII letters, digits, hyphens, or underscores, " +
"and must begin and end with a letter or digit. The name 'bundle' is reserved.\n\n" +
"`azd extension install --source` and `azd extension update --source` also accept " +
"a registry URL or file path directly.",
},
ActionResolver: newExtensionSourceAddAction,
FlagsResolver: newExtensionSourceAddFlags,
OutputFormats: []output.Format{output.NoneFormat},
DefaultFormat: output.NoneFormat,
})
sourceGroup.Add("remove", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "remove <name>",
Short: "Remove an extension source with the specified name",
},
ActionResolver: newExtensionSourceRemoveAction,
OutputFormats: []output.Format{output.NoneFormat},
DefaultFormat: output.NoneFormat,
})
// azd extension source validate <name-or-path-or-url>
sourceGroup.Add("validate", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "validate <name-or-path-or-url>",
Short: "Validate an extension source's registry.json file.",
Long: "Validate an extension source's registry.json file.\n\n" +
"Accepts a source name (from 'azd extension source list'), a local file path,\n" +
"or a URL. Checks required fields, valid capabilities, semver version format,\n" +
"platform artifact structure, and extension ID format.",
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newExtensionSourceValidateAction,
FlagsResolver: newExtensionSourceValidateFlags,
})
return group
}
type extensionListFlags struct {
installed bool
source string
tags []string
}
func newExtensionListFlags(cmd *cobra.Command) *extensionListFlags {
flags := &extensionListFlags{}
cmd.Flags().BoolVar(&flags.installed, "installed", false, "List installed extensions")
cmd.Flags().StringVarP(&flags.source, "source", "s", "",
"Filter extensions by registered source name or registry location (URL or file path).")
cmd.Flags().StringSliceVar(&flags.tags, "tags", nil, "Filter extensions by tags")
return flags
}
// azd extension list [--installed]
type extensionListAction struct {
flags *extensionListFlags
formatter output.Formatter
console input.Console
writer io.Writer
sourceManager *extensions.SourceManager
extensionManager *extensions.Manager
}
func newExtensionListAction(
flags *extensionListFlags,
formatter output.Formatter,
console input.Console,
writer io.Writer,
sourceManager *extensions.SourceManager,
extensionManager *extensions.Manager,
) actions.Action {
return &extensionListAction{
flags: flags,
formatter: formatter,
console: console,
writer: writer,
sourceManager: sourceManager,
extensionManager: extensionManager,
}
}
type extensionListItem struct {
Id string `json:"id"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Version string `json:"version"`
InstalledVersion string `json:"installedVersion"`
UpdateAvailable bool `json:"updateAvailable"`
Incompatible bool `json:"-"`
Source string `json:"source"`
// Status is a human-readable installation/update status indicator.
// Populated only for pretty-table rendering; omitted from JSON.
Status string `json:"-"`
}
func (a *extensionListAction) Run(ctx context.Context) (*actions.ActionResult, error) {
tracing.SetUsageAttributes(fields.ExtensionSourceKind.String(sourceArgKind(a.flags.source)))
options := &extensions.FilterOptions{
Source: a.flags.source,
Tags: a.flags.tags,
}
sourceFilter, err := resolveSourceFilter(ctx, a.sourceManager, a.flags.source)
if err != nil {
return nil, err
}
options.Source = sourceFilter.source
if sourceFilter.config != nil {
options.SourceConfig = sourceFilter.config
options.Source = ""
} else if options.Source != "" && !sourceFilter.registered {
return nil, fmt.Errorf("extension source '%s' not found: %w", a.flags.source, extensions.ErrSourceNotFound)
}
registryExtensions, err := a.extensionManager.FindExtensions(ctx, options)
if err != nil {
return nil, fmt.Errorf("failed listing extensions from registry: %w", err)
}
installedExtensions, err := a.extensionManager.ListInstalled()
if err != nil {
return nil, fmt.Errorf("failed listing installed extensions: %w", err)
}
extensionRows := []extensionListItem{}
azdVersion := a.extensionManager.AzdVersion()
// Track installed extensions that are represented by a matching registry row
// so the local pass below can surface the rest (e.g. bundle-installed
// extensions, or extensions whose source was removed).
coveredInstalled := map[string]bool{}
for _, extension := range registryExtensions {
if len(extension.Versions) == 0 {
continue
}
installedExtension, has := installedExtensions[extension.Id]
installed := has && installedExtension.Source == extension.Source
if installed {
coveredInstalled[extension.Id] = true
}
if a.flags.installed && !installed {
continue
}
// Always show the true latest version
latestVersion := extensions.LatestVersion(extension.Versions).Version
var installedVersion string
var updateAvailable bool
var updateIncompatible bool
if installed {
installedVersion = installedExtension.Version
// Compare versions to determine if an update is available.
// If either version string fails semver parsing (e.g., non-standard build tags),
// we silently fall back to showing "✓ Up to date" rather than erroring,
// since the list command should remain best-effort.
installedSemver, installedErr := semver.NewVersion(installedExtension.Version)
latestSemver, latestErr := semver.NewVersion(latestVersion)
if installedErr == nil && latestErr == nil {
updateAvailable = latestSemver.GreaterThan(installedSemver)
}
// Check if the update is incompatible with the current azd version
if updateAvailable && azdVersion != nil {
compatResult := extensions.FilterCompatibleVersions(extension.Versions, azdVersion)
updateIncompatible = compatResult.HasNewerIncompatible
}
}
status := extensionStatus(installed, updateAvailable && !updateIncompatible, updateIncompatible)
extensionRows = append(extensionRows, extensionListItem{
Id: extension.Id,
Name: extension.DisplayName,
Namespace: extension.Namespace,
Version: latestVersion,
InstalledVersion: installedVersion,
UpdateAvailable: updateAvailable && !updateIncompatible,
Incompatible: updateIncompatible,
Source: extension.Source,
Status: status,
})
}
// Surface installed extensions that are not represented by any configured
// registry (e.g. installed from a self-contained bundle, or whose source was
// removed). These have no live source to track updates against, so they are
// shown as up to date; the SOURCE column distinguishes them (e.g. "bundle").
for _, ext := range slices.SortedFunc(maps.Values(installedExtensions),
func(a, b *extensions.Extension) int { return strings.Compare(a.Id, b.Id) }) {
if coveredInstalled[ext.Id] {
continue
}
// Respect an explicit --source filter.
if a.flags.source != "" && !strings.EqualFold(a.flags.source, ext.Source) {
continue
}
// Installed records carry no tag metadata, so they cannot satisfy a tag filter.
if len(a.flags.tags) > 0 {
continue
}
extensionRows = append(extensionRows, extensionListItem{
Id: ext.Id,
Name: ext.DisplayName,
Namespace: ext.Namespace,
Version: ext.Version,
InstalledVersion: ext.Version,
Source: ext.Source,
Status: statusUpToDate,
})
}
if len(extensionRows) == 0 {
// NOTE: When no extensions found, we display a formatted message even for JSON output.
// This is existing azd behavior.
if a.flags.installed {
a.console.Message(ctx, output.WithWarningFormat("WARNING: No extensions installed.\n"))
a.console.Message(ctx, fmt.Sprintf(
"Run %s to install extensions.",
output.WithHighLightFormat("azd extension install <extension-id>"),
))
} else {
a.console.Message(ctx, output.WithWarningFormat("WARNING: No extensions found in configured sources.\n"))
a.console.Message(ctx, fmt.Sprintf(
"Run %s to add a new extension source.",
output.WithHighLightFormat("azd extension source add [flags]"),
))
}
return nil, nil
}
var formatErr error
if a.formatter.Kind() == output.TableFormat {
prettyFormatter := &output.PrettyTableFormatter{}
columns := []output.PrettyColumn{
{
Column: output.Column{
Heading: "ID",
ValueTemplate: "{{.Id}}",
},
Priority: 1,
},
{
Column: output.Column{
Heading: "NAME",
ValueTemplate: "{{.Name}}",
},
Priority: 3,
CardTitle: true,
Truncatable: true,
},
{
Column: output.Column{
Heading: "STATUS",
ValueTemplate: "{{.Status}}",
},
Priority: 1,
Truncatable: true,
ColorFunc: extensionStatusColor,
},
{
Column: output.Column{
Heading: "INSTALLED",
ValueTemplate: `{{if .InstalledVersion}}{{.InstalledVersion}}{{else}}-{{end}}`,
},
CardValueTemplate: `{{if .InstalledVersion}}{{.InstalledVersion}}{{end}}`,
Priority: 1,
},
{
Column: output.Column{
Heading: "LATEST",
ValueTemplate: "{{.Version}}",
},
CardValueTemplate: `{{if or .UpdateAvailable (not .InstalledVersion)}}{{.Version}}{{end}}`,
Priority: 3,
Truncatable: true,
},
{
Column: output.Column{
Heading: "SOURCE",
ValueTemplate: "{{.Source}}",
},
Priority: 1,
},
}
formatErr = prettyFormatter.Format(extensionRows, a.writer, output.PrettyTableFormatterOptions{
Columns: columns,
CardGroupColumn: "SOURCE",
ResponsiveColumnHint: true,
})
if formatErr == nil {
hasCompatibleUpdates := slices.ContainsFunc(extensionRows, func(row extensionListItem) bool {
return row.UpdateAvailable
})
hasIncompatibleUpdates := slices.ContainsFunc(extensionRows, func(row extensionListItem) bool {
return row.Incompatible
})
if hasCompatibleUpdates || hasIncompatibleUpdates {
a.console.Message(ctx, "")
}
if hasCompatibleUpdates {
a.console.Message(ctx, fmt.Sprintf(
"To update: %s", output.WithHighLightFormat("azd extension update <extension-id>")))
a.console.Message(ctx, fmt.Sprintf(
"To update all: %s", output.WithHighLightFormat("azd extension update --all")))
}
if hasIncompatibleUpdates {
if hasCompatibleUpdates {
a.console.Message(ctx, "")
}
a.console.Message(ctx, output.WithWarningFormat(
"WARNING: Some updates are incompatible with your current azd version"))
}
}
} else {
formatErr = a.formatter.Format(extensionRows, a.writer, nil)
}
return nil, formatErr
}
// Status indicator constants for extension list display.
const (
statusUpToDate = "Up to date"
statusUpgrade = "Update available"
statusIncompat = "Incompatible"
statusNotInstall = "Not installed"
)
// extensionStatus returns a human-readable status string for the extension list table.
func extensionStatus(installed, updateAvailable, incompatible bool) string {
switch {
case incompatible:
return statusIncompat
case updateAvailable:
return statusUpgrade
case installed:
return statusUpToDate
default:
return statusNotInstall
}
}
// extensionStatusColor applies color formatting based on the status indicator text.
func extensionStatusColor(s string) string {
switch s {
case statusUpToDate:
return output.WithSuccessFormat(s)
case statusUpgrade:
return output.WithWarningFormat(s)
case statusIncompat:
return output.WithErrorFormat(s)
default:
return output.WithGrayFormat(s)
}
}
// azd extension show
type extensionShowFlags struct {
source string
global *internal.GlobalCommandOptions
}
func newExtensionShowFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *extensionShowFlags {
flags := &extensionShowFlags{
global: global,
}
cmd.Flags().StringVarP(&flags.source, "source", "s", "",
"The registered source name or registry location (URL or file path) to use.")
return flags
}
type extensionShowAction struct {
args []string
flags *extensionShowFlags
console input.Console
formatter output.Formatter
writer io.Writer
sourceManager *extensions.SourceManager
extensionManager *extensions.Manager
}
func newExtensionShowAction(
args []string,
flags *extensionShowFlags,
console input.Console,
formatter output.Formatter,
writer io.Writer,
sourceManager *extensions.SourceManager,
extensionManager *extensions.Manager,
) actions.Action {
return &extensionShowAction{
args: args,
flags: flags,
console: console,
formatter: formatter,
writer: writer,
sourceManager: sourceManager,
extensionManager: extensionManager,
}
}
// extensionShowItem is the `azd extension show` view model. Field names are the
// `--output json` contract and follow the camelCase convention of other azd commands.
type extensionShowItem struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Website string `json:"website,omitempty"`
Source string `json:"source"`
Namespace string `json:"namespace,omitempty"`
Tags []string `json:"tags,omitempty"`
// LatestVersion is the highest published version regardless of azd compatibility.
// Empty when the extension is only known from its installed record.
LatestVersion string `json:"latestVersion,omitempty"`
// LatestCompatibleVersion is the highest published version the running azd can install.
LatestCompatibleVersion string `json:"latestCompatibleVersion,omitempty"`
// RequiresAzd is the azd version constraint declared by the latest version.
RequiresAzd string `json:"requiresAzd,omitempty"`
// OtherVersions lists the remaining published versions, newest first.
OtherVersions []string `json:"otherVersions,omitempty"`
InstalledVersion string `json:"installedVersion,omitempty"`
// InstalledSource is set when the extension is installed from a source other than the
// one being described, in which case update state is not reported.
InstalledSource string `json:"installedSource,omitempty"`
InstalledAsDependency bool `json:"installedAsDependency,omitempty"`
// UpdateAvailable is true when a newer version compatible with the running azd exists.
UpdateAvailable bool `json:"updateAvailable,omitempty"`
Dependencies []extensionShowDependency `json:"dependencies,omitempty"`
RequiredBy []extensionShowDependent `json:"requiredBy,omitempty"`
Capabilities []extensions.CapabilityType `json:"capabilities,omitempty"`
Providers []extensions.Provider `json:"providers,omitempty"`
Usage string `json:"usage,omitempty"`
Examples []extensions.ExtensionExample `json:"examples,omitempty"`
// azdVersion, latestIncompatible, and newerIncompatible drive the compatibility
// annotations in Display. latestIncompatible means the latest release cannot run on this
// azd (Requires azd row); newerIncompatible additionally means it is newer than what is
// installed (Installed row).
azdVersion string
latestIncompatible bool
newerIncompatible bool
}
// extensionShowDependency is one declared dependency together with its installed state.
type extensionShowDependency struct {
Id string `json:"id"`
// Version is the declared constraint. Empty means any version.
Version string `json:"version,omitempty"`
InstalledVersion string `json:"installedVersion,omitempty"`
// Satisfied is true when the dependency is installed at a version matching the constraint.
Satisfied bool `json:"satisfied"`
}
// extensionShowDependent is an installed extension that declares a dependency on the shown one.
type extensionShowDependent struct {
Id string `json:"id"`
Version string `json:"version"`
}
// installedSummary describes the installed state with at most one annotation, in priority
// order: foreign source, compatible update, newer incompatible release.
func (t *extensionShowItem) installedSummary() string {
if t.InstalledVersion == "" {
return "Not installed"
}
summary := t.InstalledVersion
switch {
case t.InstalledSource != "":
summary += fmt.Sprintf(" (from %s)", t.InstalledSource)
case t.UpdateAvailable:
summary += fmt.Sprintf(" (update available: %s)", t.LatestCompatibleVersion)
case t.newerIncompatible:
summary += fmt.Sprintf(" (%s requires a newer azd)", t.LatestVersion)
}
return summary
}
// requiresAzdSummary annotates the latest version's azd constraint when the running azd
// cannot use it.
func (t *extensionShowItem) requiresAzdSummary() string {
if !t.latestIncompatible || t.azdVersion == "" {
return t.RequiresAzd
}
if t.LatestCompatibleVersion != "" {
return fmt.Sprintf(
"%s (not compatible with azd %s; latest compatible is %s)",
t.RequiresAzd, t.azdVersion, t.LatestCompatibleVersion,
)
}
return fmt.Sprintf("%s (not compatible with azd %s)", t.RequiresAzd, t.azdVersion)
}
// summary renders the constraint and installed state of a dependency row.
func (d extensionShowDependency) summary() string {
constraint := d.Version
if constraint == "" {
constraint = "any version"
}
switch {
case d.InstalledVersion == "":
return constraint + " (not installed)"
case d.Satisfied:
return fmt.Sprintf("%s (installed %s)", constraint, d.InstalledVersion)
default:
return fmt.Sprintf("%s (installed %s, outside constraint)", constraint, d.InstalledVersion)
}
}
func (t *extensionShowItem) Display(writer io.Writer) error {
// Helper function to write a section with its own tabwriter
writeSection := func(header string, rows [][]string) error {
if len(rows) == 0 {
return nil
}
// Write bold and underlined header
underlinedHeader := output.WithUnderline("%s", header)
boldUnderlinedHeader := output.WithBold("%s", underlinedHeader)
_, err := fmt.Fprintf(writer, "%s\n", boldUnderlinedHeader)
if err != nil {
return err
} // Create tabwriter for this section
tabs := tabwriter.NewWriter(
writer,
0,
output.TableTabSize,
1,
output.TablePadCharacter,
output.TableFlags)
// Write rows
for _, row := range rows {
_, err := tabs.Write([]byte(strings.Join(row, "\t") + "\n"))
if err != nil {
return err
}
}
// Flush and add spacing
if err := tabs.Flush(); err != nil {
return err
}
_, err = fmt.Fprintln(writer)
return err
}
// Extension Information section. Rows without a value are omitted rather than shown blank.
extensionInfo := [][]string{
{"Id", ":", t.Id},
{"Name", ":", t.Name},
{"Description", ":", t.Description},
{"Source", ":", t.Source},
}
if t.Namespace != "" {
extensionInfo = append(extensionInfo, []string{"Namespace", ":", t.Namespace})
}
if t.Website != "" {
extensionInfo = append(extensionInfo, []string{"Website", ":", t.Website})
}
if len(t.Tags) > 0 {
extensionInfo = append(extensionInfo, []string{"Tags", ":", strings.Join(t.Tags, ", ")})
}
if err := writeSection("Extension Information", extensionInfo); err != nil {
return err
}
// Version Information section
versionInfo := [][]string{
{"Installed", ":", t.installedSummary()},
}
if t.InstalledAsDependency {
versionInfo = append(versionInfo, []string{"Installed as", ":", "Dependency"})
}
if t.LatestVersion != "" {
versionInfo = append(versionInfo, []string{"Latest", ":", t.LatestVersion})
}
if t.RequiresAzd != "" {
versionInfo = append(versionInfo, []string{"Requires azd", ":", t.requiresAzdSummary()})
}
if len(t.OtherVersions) > 0 {
versionInfo = append(versionInfo, []string{"Other Versions", ":", strings.Join(t.OtherVersions, ", ")})
}
if err := writeSection("Version Information", versionInfo); err != nil {
return err
}
// Dependencies section - only if the shown version declares any
if len(t.Dependencies) > 0 {
dependencyRows := [][]string{}
for _, dependency := range t.Dependencies {
dependencyRows = append(dependencyRows, []string{dependency.Id, ":", dependency.summary()})
}
if err := writeSection("Dependencies", dependencyRows); err != nil {
return err
}
}
// Required By section - only if installed extensions depend on this one
if len(t.RequiredBy) > 0 {
dependentRows := [][]string{}
for _, dependent := range t.RequiredBy {
dependentRows = append(dependentRows, []string{dependent.Id, ":", dependent.Version})
}
if err := writeSection("Required By", dependentRows); err != nil {
return err
}
}
// Capabilities section - only if there are capabilities
if len(t.Capabilities) > 0 {
capabilityRows := [][]string{}
for _, capability := range t.Capabilities {
capabilityRows = append(capabilityRows, []string{"-", string(capability)})
}
if err := writeSection("Capabilities", capabilityRows); err != nil {
return err
}
}
// Providers section - only if there are providers
if len(t.Providers) > 0 {
providerRows := [][]string{}
for _, provider := range t.Providers {
providerInfo := fmt.Sprintf("%s (%s) - %s", provider.Name, provider.Type, provider.Description)
providerRows = append(providerRows, []string{"", "", providerInfo})
}
if err := writeSection("Providers", providerRows); err != nil {
return err
}
}
// Usage section - only if the extension has one (packs typically do not)
if strings.TrimSpace(t.Usage) != "" {
usageRows := [][]string{
{"", "", t.Usage},
}
if err := writeSection("Usage", usageRows); err != nil {
return err
}
}
// Examples section - only if there are examples
if len(t.Examples) > 0 {
exampleRows := [][]string{}
for _, example := range t.Examples {
exampleRows = append(exampleRows, []string{"", "", example.Usage})
}
if err := writeSection("Examples", exampleRows); err != nil {
return err
}
}
return nil
}
func (a *extensionShowAction) Run(ctx context.Context) (*actions.ActionResult, error) {
tracing.SetUsageAttributes(fields.ExtensionSourceKind.String(sourceArgKind(a.flags.source)))
if len(a.args) == 0 {
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrNoArgsProvided,
Suggestion: "Run 'azd extension show <extension-id>' specifying the extension.",
}
}
if len(a.args) > 1 {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf("cannot specify multiple extensions: %w", internal.ErrInvalidFlagCombination),
Suggestion: "Specify a single extension ID.",
}
}
extensionId := a.args[0]
installedExtension, err := a.extensionManager.GetInstalled(extensions.FilterOptions{Id: extensionId})
if err != nil && !errors.Is(err, extensions.ErrInstalledExtensionNotFound) {
return nil, fmt.Errorf("failed to get installed extension: %w", err)
}
filterOptions := &extensions.FilterOptions{
Source: a.flags.source,
Id: extensionId,
}
sourceFilter, err := resolveSourceFilter(ctx, a.sourceManager, a.flags.source)
if err != nil {
return nil, err
}
filterOptions.Source = sourceFilter.source
if sourceFilter.config != nil {
filterOptions.SourceConfig = sourceFilter.config
filterOptions.Source = ""
} else if filterOptions.Source != "" && !sourceFilter.registered {
return nil, fmt.Errorf(
"extension source '%s' not found: %w", a.flags.source, extensions.ErrSourceNotFound)
}
extensionMatches, err := a.extensionManager.FindExtensions(ctx, filterOptions)
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
if err != nil {
if installedExtension == nil || a.flags.source != "" ||
errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, fmt.Errorf("failed to find extension: %w", err)
}
a.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: "Could not load extension registry information. Showing installed metadata only.",
})
extensionMatches = nil
}
// Without registry metadata, describe the installed record unless --source requested a different source.
var registryExtension *extensions.ExtensionMetadata
installedOnly := len(extensionMatches) == 0 && installedExtension != nil &&
(a.flags.source == "" || strings.EqualFold(a.flags.source, installedExtension.Source))
if !installedOnly {
registryExtension, err = a.selectRegistryExtension(ctx, extensionId, extensionMatches, installedExtension)
if err != nil {
return nil, err
}
}
extensionDetails, err := a.buildShowItem(extensionId, registryExtension, installedExtension)
if err != nil {
return nil, err
}
var formatErr error
if a.formatter.Kind() == output.NoneFormat {
formatErr = extensionDetails.Display(a.writer)
} else {
formatErr = a.formatter.Format(extensionDetails, a.writer, nil)
}
return nil, formatErr
}
// selectRegistryExtension picks the registry entry to describe. The source the extension is
// installed from wins when it is among the matches, so an installed extension listed by several
// sources is described without prompting. Otherwise the user chooses, as for install.
func (a *extensionShowAction) selectRegistryExtension(
ctx context.Context,
extensionId string,
matches []*extensions.ExtensionMetadata,
installed *extensions.Extension,
) (*extensions.ExtensionMetadata, error) {
if installed != nil {
for _, match := range matches {
if strings.EqualFold(match.Source, installed.Source) {
return match, nil
}
}
}
return selectDistinctExtension(ctx, a.console, extensionId, matches, a.flags.global)
}
// buildShowItem assembles the view model from the registry entry (when there is one) and the
// installed record (when the extension is installed). Either may be nil, but not both.
func (a *extensionShowAction) buildShowItem(
extensionId string,
registryExtension *extensions.ExtensionMetadata,
installed *extensions.Extension,
) (*extensionShowItem, error) {
item := &extensionShowItem{Id: extensionId}
var dependencies []extensions.ExtensionDependency
if registryExtension != nil {
item.Id = registryExtension.Id
item.Name = registryExtension.DisplayName
item.Description = registryExtension.Description
item.Website = registryExtension.Website
item.Source = registryExtension.Source
item.Namespace = registryExtension.Namespace
item.Tags = registryExtension.Tags
if latest := extensions.LatestVersion(registryExtension.Versions); latest != nil {
item.LatestVersion = latest.Version
item.RequiresAzd = latest.RequiredAzdVersion
item.OtherVersions = otherVersionsNewestFirst(registryExtension.Versions, latest.Version)
item.Usage = latest.Usage
item.Examples = latest.Examples
item.Providers = latest.Providers
item.Capabilities = latest.Capabilities
dependencies = latest.Dependencies
if azdVersion := a.extensionManager.AzdVersion(); azdVersion != nil {
compat := extensions.FilterCompatibleVersions(registryExtension.Versions, azdVersion)
item.azdVersion = azdVersion.String()
item.latestIncompatible = compat.HasNewerIncompatible
item.newerIncompatible = compat.HasNewerIncompatible
if compat.LatestCompatible != nil {
item.LatestCompatibleVersion = compat.LatestCompatible.Version
}
} else {
// Without a compatibility policy (dev builds, IgnoreAzdCompatibility) every
// published version is installable.
item.LatestCompatibleVersion = latest.Version
}
}
}
if installed != nil {
item.InstalledVersion = installed.Version
item.InstalledAsDependency = installed.InstalledAsDependency
switch {
case registryExtension == nil:
item.Id = installed.Id
item.Name = installed.DisplayName
item.Description = installed.Description
item.Source = installed.Source
item.Namespace = installed.Namespace
item.Usage = installed.Usage
item.Capabilities = installed.Capabilities
item.Providers = installed.Providers
case !strings.EqualFold(installed.Source, registryExtension.Source):
item.InstalledSource = installed.Source