|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package config |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + |
| 9 | + "github.com/microsoft/azldev/internal/app/azldev" |
| 10 | + "github.com/pelletier/go-toml/v2" |
| 11 | + "github.com/spf13/cobra" |
| 12 | + "github.com/spf13/pflag" |
| 13 | +) |
| 14 | + |
| 15 | +type configDumpFormat string |
| 16 | + |
| 17 | +const ( |
| 18 | + ConfigDumpFormatTOML configDumpFormat = "toml" |
| 19 | +) |
| 20 | + |
| 21 | +// Assert that ConfigDumpFormat implements the [pflag.Value] interface. |
| 22 | +var _ pflag.Value = (*configDumpFormat)(nil) |
| 23 | + |
| 24 | +func (f *configDumpFormat) String() string { |
| 25 | + return string(*f) |
| 26 | +} |
| 27 | + |
| 28 | +// Parses the format from a string; used by command-line parser. |
| 29 | +func (f *configDumpFormat) Set(value string) error { |
| 30 | + switch value { |
| 31 | + case "toml": |
| 32 | + *f = ConfigDumpFormatTOML |
| 33 | + default: |
| 34 | + return fmt.Errorf("unsupported format: %#q", value) |
| 35 | + } |
| 36 | + |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +// Returns a descriptive string used in command-line help. |
| 41 | +func (f *configDumpFormat) Type() string { |
| 42 | + return "fmt" |
| 43 | +} |
| 44 | + |
| 45 | +// Called once when the app is initialized; registers any commands or callbacks with the app. |
| 46 | +func dumpConfigOnAppInit(_ *azldev.App, parentCmd *cobra.Command) { |
| 47 | + parentCmd.AddCommand(newDumpCmd()) |
| 48 | +} |
| 49 | + |
| 50 | +func newDumpCmd() *cobra.Command { |
| 51 | + configDumpFormat := ConfigDumpFormatTOML |
| 52 | + |
| 53 | + cmd := &cobra.Command{ |
| 54 | + Use: "dump", |
| 55 | + Short: "Dump the current configuration", |
| 56 | + RunE: azldev.RunFunc(func(env *azldev.Env) (interface{}, error) { |
| 57 | + configText, err := DumpConfig(env, configDumpFormat) |
| 58 | + if err != nil { |
| 59 | + return nil, err |
| 60 | + } |
| 61 | + |
| 62 | + fmt.Println(configText) |
| 63 | + |
| 64 | + return "", nil |
| 65 | + }), |
| 66 | + } |
| 67 | + |
| 68 | + cmd.Flags().VarP(&configDumpFormat, "format", "f", "Output format") |
| 69 | + |
| 70 | + azldev.ExportAsMCPTool(cmd) |
| 71 | + |
| 72 | + return cmd |
| 73 | +} |
| 74 | + |
| 75 | +func DumpConfig(env *azldev.Env, format configDumpFormat) (string, error) { |
| 76 | + switch format { |
| 77 | + case ConfigDumpFormatTOML: |
| 78 | + tomlBytes, err := toml.Marshal(env.Config()) |
| 79 | + if err != nil { |
| 80 | + return "", fmt.Errorf("failed to serialize config to TOML:\n%w", err) |
| 81 | + } |
| 82 | + |
| 83 | + return string(tomlBytes), nil |
| 84 | + default: |
| 85 | + return "", fmt.Errorf("unsupported format: %#q", format) |
| 86 | + } |
| 87 | +} |
0 commit comments