I *really* hate reflect

This commit is contained in:
Neil Alexander 2019-02-17 23:14:28 +00:00
parent 965337b52b
commit 1735a1c63b
No known key found for this signature in database
GPG key ID: A02A2019A2BB0944

View file

@ -58,10 +58,7 @@ func main() {
} }
action := flags[0] action := flags[0]
switch strings.ToLower(flags[0]) { switch strings.ToLower(flags[0]) {
case "get": case "get", "set", "add", "del":
case "set":
case "add":
case "del":
action = strings.ToLower(flags[0]) action = strings.ToLower(flags[0])
default: default:
flag.Usage() flag.Usage()
@ -92,28 +89,40 @@ func main() {
panic(err) panic(err)
} }
json.Unmarshal(confJSON, &cfg) json.Unmarshal(confJSON, &cfg)
item := reflect.ValueOf(&cfg).Elem() item := reflect.ValueOf(cfg)
for index, arg := range flags { for index, arg := range flags {
switch index { switch index {
case 0: case 0:
continue continue
case len(flags) - 2:
fallthrough
case len(flags) - 1: case len(flags) - 1:
if action == "set" { if action != "get" {
continue break
} }
fallthrough fallthrough
default: default:
switch item.Kind() { switch item.Kind() {
case reflect.Map: case reflect.Map:
found := false
for _, key := range item.MapKeys() { for _, key := range item.MapKeys() {
if key.String() == arg { if key.String() == arg {
item = item.MapIndex(key) 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: case reflect.Struct:
item = item.FieldByName(arg) item = item.FieldByName(arg)
continue
} }
if !item.IsValid() { if !item.IsValid() {
os.Exit(1) os.Exit(1)
@ -160,8 +169,7 @@ func main() {
} }
} }
case reflect.Map: case reflect.Map:
intf := item.Interface().(map[string]interface{}) item.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(value))
intf[name] = value
} }
case "add": case "add":
value := flags[len(flags)-1:][0] value := flags[len(flags)-1:][0]
@ -169,15 +177,20 @@ func main() {
case reflect.Slice: case reflect.Slice:
fallthrough fallthrough
case reflect.Array: 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": case "del":
//value := flags[len(flags)-1:][0] /*value := flags[len(flags)-1:][0]
switch item.Kind() { switch item.Kind() {
case reflect.Slice: case reflect.Slice:
fallthrough fallthrough
case reflect.Array: case reflect.Array:
} }*/
} }
var bs []byte var bs []byte
if *usejson { if *usejson {