config set: allow arbitrary json input
This commit allows arbitrary json input to set. It also tests this with sharness.
Juan Batiz-Benet committed
May 10, 2015 at 08:09 UTC
6dd8aeb00af88cb6bb4cdde0272f2851b2d1b7f9
2 files changed
+27
-2
core/commands/config.go
+13
-2
@@ -59,6 +59,7 @@ Set the value of the 'datastore.path' key:
59
},
60
Options: []cmds.Option{
61
cmds.BoolOption("bool", "Set a boolean value"),
62
+ cmds.BoolOption("json", "Parse stringified JSON"),
63
},
64
Run: func(req cmds.Request, res cmds.Response) {
65
args := req.Arguments()
@@ -74,7 +75,17 @@ Set the value of the 'datastore.path' key:
75
var output *ConfigField
76
if len(args) == 2 {
77
value := args[1]
77
- if isbool, _, _ := req.Option("bool").Bool(); isbool {
78
+
79
+ if parseJson, _, _ := req.Option("json").Bool(); parseJson {
80
+ var jsonVal interface{}
81
+ if err := json.Unmarshal([]byte(value), &jsonVal); err != nil {
82
+ err = fmt.Errorf("failed to unmarshal json. %s", err)
83
+ res.SetError(err, cmds.ErrNormal)
84
+ return
85
+ }
86
+
87
+ output, err = setConfig(r, key, jsonVal)
88
+ } else if isbool, _, _ := req.Option("bool").Bool(); isbool {
89
output, err = setConfig(r, key, value == "true")
90
} else {
91
output, err = setConfig(r, key, value)
@@ -217,7 +228,7 @@ func getConfig(r repo.Repo, key string) (*ConfigField, error) {
228
func setConfig(r repo.Repo, key string, value interface{}) (*ConfigField, error) {
229
err := r.SetConfigKey(key, value)
230
if err != nil {
220
- return nil, fmt.Errorf("Failed to set config value: %s", err)
231
+ return nil, fmt.Errorf("Failed to set config value: %s (maybe use --json?)", err)
232
}
233
return getConfig(r, key)
234
}
test/sharness/t0021-config.sh
+14
@@ -36,6 +36,17 @@ test_config_cmd_set() {
36
'
37
}
38
39
+# this is a bit brittle. the problem is we need to test
40
+# with something that will be forced to unmarshal as a struct.
41
+# (i.e. just setting 'ipfs config --json foo "[1, 2, 3]"') may
42
+# set it as astring instead of proper json. We leverage the
43
+# unmarshalling that has to happen.
44
+CONFIG_SET_JSON_TEST='{
45
+ "MDNS": {
46
+ "Enabled": true,
47
+ "Interval": 10
48
+ }
49
+}'
50
51
test_config_cmd() {
52
test_config_cmd_set "beep" "boop"
@@ -43,6 +54,9 @@ test_config_cmd() {
54
test_config_cmd_set "beep1" "boop2"
55
test_config_cmd_set "--bool" "beep2" "true"
56
test_config_cmd_set "--bool" "beep2" "false"
57
+ test_config_cmd_set "--json" "beep3" "true"
58
+ test_config_cmd_set "--json" "beep3" "false"
59
+ test_config_cmd_set "--json" "Discovery" "$CONFIG_SET_JSON_TEST"
60
61
}
62