-
Notifications
You must be signed in to change notification settings - Fork 251
/
set.go
75 lines (62 loc) · 1.6 KB
/
set.go
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
package configCmd
import (
"encoding/json"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"github.com/taskcluster/taskcluster/v49/clients/client-shell/config"
)
func init() {
cmd := &cobra.Command{
Use: "set <key> [<value>]",
Short: "Set configuration <key> to <value>",
RunE: cmdSet,
}
cmd.Flags().BoolP("dry-run", "d", false, "Validate option only, don't set it")
Command.AddCommand(cmd)
}
func cmdSet(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("set requires argument <key>")
}
command, option, definition, value, err := getOptionFromKey(args[0])
if err != nil {
return err
}
var data string
// read from command line, or from stdin
if len(args) == 2 {
data = args[1]
} else {
d, err := io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("failed to read value from stdin, error: %s", err)
}
data = string(d)
}
// parse value if necessary
if definition.Parse {
err := json.Unmarshal([]byte(data), &value)
if err != nil {
return fmt.Errorf("failed to parse JSON value, error: %s", err)
}
} else {
value = data
}
// Validate value
if definition.Validate != nil {
if err := definition.Validate(value); err != nil {
return fmt.Errorf("invalid value, error: %s", err)
}
}
// Save option
if dry, _ := cmd.Flags().GetBool("dry-run"); !dry {
config.Configuration[command][option] = value
if err := config.Save(config.Configuration); err != nil {
return fmt.Errorf("failed to save configuration file, error: %s", err)
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Set '%s.%s' = %s\n", command, option, data)
return nil
}