From 1735a1c63bee2c8e43fcba782c18e173d459db88 Mon Sep 17 00:00:00 2001 From: Neil Alexander Date: Sun, 17 Feb 2019 23:14:28 +0000 Subject: [PATCH] I *really* hate reflect --- cmd/yggdrasilconf/main.go | 41 ++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/cmd/yggdrasilconf/main.go b/cmd/yggdrasilconf/main.go index c155f0a0..cdb4cfaa 100644 --- a/cmd/yggdrasilconf/main.go +++ b/cmd/yggdrasilconf/main.go @@ -58,10 +58,7 @@ func main() { } action := flags[0] switch strings.ToLower(flags[0]) { - case "get": - case "set": - case "add": - case "del": + case "get", "set", "add", "del": action = strings.ToLower(flags[0]) default: flag.Usage() @@ -92,28 +89,40 @@ func main() { panic(err) } json.Unmarshal(confJSON, &cfg) - item := reflect.ValueOf(&cfg).Elem() + item := reflect.ValueOf(cfg) for index, arg := range flags { switch index { case 0: continue - case len(flags) - 2: - fallthrough case len(flags) - 1: - if action == "set" { - continue + if action != "get" { + break } fallthrough default: switch item.Kind() { case reflect.Map: + found := false for _, key := range item.MapKeys() { if key.String() == arg { item = item.MapIndex(key) + found = true + break } } + if !found { + t := reflect.TypeOf(item.Interface()) + k := reflect.ValueOf(arg) + v := reflect.New(t) + item.SetMapIndex(k, v) + item = item.MapIndex(k) + } + continue + case reflect.Array: + continue case reflect.Struct: item = item.FieldByName(arg) + continue } if !item.IsValid() { os.Exit(1) @@ -160,8 +169,7 @@ func main() { } } case reflect.Map: - intf := item.Interface().(map[string]interface{}) - intf[name] = value + item.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(value)) } case "add": value := flags[len(flags)-1:][0] @@ -169,15 +177,20 @@ func main() { case reflect.Slice: fallthrough case reflect.Array: - item.Set(reflect.Append(item, reflect.ValueOf(value))) + if item.CanSet() { + fmt.Println("add", value, "to", item) + item.Set(reflect.Append(item, reflect.ValueOf(value))) + } else { + fmt.Println("can't add", value, "to", item) + } } case "del": - //value := flags[len(flags)-1:][0] + /*value := flags[len(flags)-1:][0] switch item.Kind() { case reflect.Slice: fallthrough case reflect.Array: - } + }*/ } var bs []byte if *usejson {