Skip to content

Commit 5369545

Browse files
yfodilquantumsheep
andauthored
feat(config): add output default format (#3003)
Co-authored-by: Nathanael Demacon <nathanael.dmc@outlook.fr> Co-authored-by: Nathanael DEMACON <ndemacon@scaleway.com>
1 parent 1f5c070 commit 5369545

File tree

2 files changed

+70
-14
lines changed

2 files changed

+70
-14
lines changed

internal/config/config.go

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package config
22

33
import (
4+
"bytes"
45
"fmt"
56
"os"
67
"path/filepath"
8+
"text/template"
79

810
"gopkg.in/yaml.v3"
911

@@ -16,10 +18,37 @@ const (
1618

1719
DefaultConfigFileName = "cli.yaml"
1820
defaultConfigPermission = 0644
21+
22+
DefaultOutput = "human"
23+
configFileTemplate = `# Scaleway CLI config file
24+
# This config file can be used only with Scaleway CLI (>2.0.0) (https://github.com/scaleway/scaleway-cli)
25+
# Output sets the output format for all commands you run
26+
{{ if .Output }}output: {{ .Output }}{{ else }}# output: human{{ end }}
27+
28+
# Alias creates custom aliases for your Scaleway CLI commands
29+
{{- if .Alias }}
30+
alias:
31+
aliases:
32+
{{- range $alias, $commands := .Alias.Aliases }}
33+
{{ $alias }}:
34+
{{- range $index, $command := $commands }}
35+
- {{ $command }}
36+
{{- end }}
37+
{{- end }}
38+
{{- else }}
39+
# alias:
40+
# aliases:
41+
# isl:
42+
# - instance
43+
# - server
44+
# - list
45+
{{- end }}
46+
`
1947
)
2048

2149
type Config struct {
22-
Alias *alias.Config `json:"alias"`
50+
Alias *alias.Config `json:"alias"`
51+
Output string `json:"output"`
2352

2453
path string
2554
}
@@ -32,15 +61,17 @@ func LoadConfig(configPath string) (*Config, error) {
3261
if err != nil {
3362
if os.IsNotExist(err) {
3463
return &Config{
35-
Alias: alias.EmptyConfig(),
36-
path: configPath,
64+
Alias: alias.EmptyConfig(),
65+
Output: DefaultOutput,
66+
path: configPath,
3767
}, nil
3868
}
3969
return nil, fmt.Errorf("failed to read cli config file: %w", err)
4070
}
4171
config := &Config{
42-
Alias: alias.EmptyConfig(),
43-
path: configPath,
72+
Alias: alias.EmptyConfig(),
73+
Output: DefaultOutput,
74+
path: configPath,
4475
}
4576
err = yaml.Unmarshal(file, &config)
4677
if err != nil {
@@ -52,15 +83,32 @@ func LoadConfig(configPath string) (*Config, error) {
5283

5384
// Save marshal config to config file
5485
func (c *Config) Save() error {
55-
config, err := yaml.Marshal(c)
86+
file, err := c.HumanConfig()
5687
if err != nil {
5788
return err
5889
}
90+
5991
err = os.MkdirAll(filepath.Dir(c.path), 0700)
6092
if err != nil {
6193
return err
6294
}
63-
return os.WriteFile(c.path, config, defaultConfigPermission)
95+
return os.WriteFile(c.path, []byte(file), defaultConfigPermission)
96+
}
97+
98+
// HumanConfig will generate a config file with documented arguments
99+
func (c *Config) HumanConfig() (string, error) {
100+
tmpl, err := template.New("configuration").Parse(configFileTemplate)
101+
if err != nil {
102+
return "", err
103+
}
104+
105+
var buf bytes.Buffer
106+
err = tmpl.Execute(&buf, c)
107+
if err != nil {
108+
return "", err
109+
}
110+
111+
return buf.String(), nil
64112
}
65113

66114
func FilePath() (string, error) {

internal/core/bootstrap.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,6 @@ type BootstrapConfig struct {
7070
BetaMode bool
7171
}
7272

73-
const (
74-
defaultOutput = "human"
75-
)
76-
7773
// Bootstrap is the main entry point. It is directly called from main.
7874
// BootstrapConfig.Args is usually os.Args
7975
// BootstrapConfig.Commands is a list of command available in CLI.
@@ -87,7 +83,7 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e
8783
flags := pflag.NewFlagSet(config.Args[0], pflag.ContinueOnError)
8884
flags.StringVarP(&profileFlag, "profile", "p", "", "The config profile to use")
8985
flags.StringVarP(&configPathFlag, "config", "c", "", "The path to the config file")
90-
flags.StringVarP(&outputFlag, "output", "o", defaultOutput, "Output format: json or human")
86+
flags.StringVarP(&outputFlag, "output", "o", cliConfig.DefaultOutput, "Output format: json or human")
9187
flags.BoolVarP(&debug, "debug", "D", os.Getenv("SCW_DEBUG") == "true", "Enable debug mode")
9288
// Ignore unknown flag
9389
flags.ParseErrorsWhitelist.UnknownFlags = true
@@ -104,7 +100,7 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e
104100

105101
// If debug flag is set enable debug mode in SDK logger
106102
logLevel := logger.LogLevelWarning
107-
if outputFlag != defaultOutput {
103+
if outputFlag != cliConfig.DefaultOutput {
108104
logLevel = logger.LogLevelError
109105
}
110106

@@ -207,6 +203,18 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e
207203
return 1, nil, err
208204
}
209205
meta.CliConfig = cliCfg
206+
if cliCfg.Output != cliConfig.DefaultOutput {
207+
outputFlag = cliCfg.Output
208+
printer, err = NewPrinter(&PrinterConfig{
209+
OutputFlag: outputFlag,
210+
Stdout: config.Stdout,
211+
Stderr: config.Stderr,
212+
})
213+
if err != nil {
214+
_, _ = fmt.Fprintln(config.Stderr, err)
215+
return 1, nil, err
216+
}
217+
}
210218

211219
// Check CLI new version when exiting the bootstrap
212220
defer func() { // if we plan to remove defer, do not forget logger is not set until cobra pre init func
@@ -242,7 +250,7 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e
242250
// declaration in order for them to be shown in the cobra usage documentation.
243251
rootCmd.PersistentFlags().StringVarP(&profileFlag, "profile", "p", "", "The config profile to use")
244252
rootCmd.PersistentFlags().StringVarP(&configPathFlag, "config", "c", "", "The path to the config file")
245-
rootCmd.PersistentFlags().StringVarP(&outputFlag, "output", "o", "human", "Output format: json or human, see 'scw help output' for more info")
253+
rootCmd.PersistentFlags().StringVarP(&outputFlag, "output", "o", cliConfig.DefaultOutput, "Output format: json or human, see 'scw help output' for more info")
246254
rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, "Enable debug mode")
247255
rootCmd.SetArgs(args)
248256
rootCmd.SetHelpCommand(&cobra.Command{Hidden: true})

0 commit comments

Comments
 (0)