forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset.go
More file actions
90 lines (76 loc) · 2.09 KB
/
set.go
File metadata and controls
90 lines (76 loc) · 2.09 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
package set
import (
"errors"
"fmt"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type SetOptions struct {
IO *iostreams.IOStreams
Config config.Config
Key string
Value string
Hostname string
}
func NewCmdConfigSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command {
opts := &SetOptions{
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "set <key> <value>",
Short: "Update configuration with a value for the given key",
Example: heredoc.Doc(`
$ gh config set editor vim
$ gh config set editor "code --wait"
$ gh config set git_protocol ssh --host github.com
$ gh config set prompt disabled
`),
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
config, err := f.Config()
if err != nil {
return err
}
opts.Config = config
opts.Key = args[0]
opts.Value = args[1]
if runF != nil {
return runF(opts)
}
return setRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "host", "h", "", "Set per-host setting")
return cmd
}
func setRun(opts *SetOptions) error {
err := config.ValidateKey(opts.Key)
if err != nil {
warningIcon := opts.IO.ColorScheme().WarningIcon()
fmt.Fprintf(opts.IO.ErrOut, "%s warning: '%s' is not a known configuration key\n", warningIcon, opts.Key)
}
err = config.ValidateValue(opts.Key, opts.Value)
if err != nil {
var invalidValue *config.InvalidValueError
if errors.As(err, &invalidValue) {
var values []string
for _, v := range invalidValue.ValidValues {
values = append(values, fmt.Sprintf("'%s'", v))
}
return fmt.Errorf("failed to set %q to %q: valid values are %v", opts.Key, opts.Value, strings.Join(values, ", "))
}
}
err = opts.Config.Set(opts.Hostname, opts.Key, opts.Value)
if err != nil {
return fmt.Errorf("failed to set %q to %q: %w", opts.Key, opts.Value, err)
}
err = opts.Config.Write()
if err != nil {
return fmt.Errorf("failed to write config to disk: %w", err)
}
return nil
}