cobrafy confused by JSON attributes
I haven't used base commandeer yet, but the wanted to try using cobrafy to reuse some structs we use for JSON parsing as arguments for a sub command we shell out to.
However, it seems like the generated Cobra.Command is confused by the omitempty on the json attribute.
See for example: https://go.dev/play/p/dTj_Fxo63sr
package main
import (
"fmt"
"github.com/jaffee/commandeer/cobrafy"
)
type Args struct {
Count int `json:"count,omitempty"`
Reticulate bool `json:"reticulate,omitempty"`
}
func main() {
args := Args{
Count: 1,
Reticulate: false,
}
cmd, err := cobrafy.Command(&args)
if err != nil {
panic(err)
}
fmt.Println("Trying --count ... ")
cmd.SetArgs([]string{"--count"})
if err := cmd.Execute(); err != nil {
fmt.Println(err)
}
fmt.Println("Trying --reticulate,omitempty ... ")
cmd.SetArgs([]string{"--reticulate,omitempty"})
if err := cmd.Execute(); err != nil {
fmt.Println(err)
} else {
fmt.Println("Accepted")
}
}
Tested a little more and discovered that Count int `json:"count,omitempty" flag:"count"` does work but ideally we wouldn't need to do that when the json and flag name match (to prevent accidental drift).
I believe the issue is here: https://github.com/jaffee/commandeer/blob/master/com.go#L388
The json tag needs to be "sanitized" to remove extra attributes like omitempty. If think the easiest solution is to split on , and use the first result as the name (or use the entire tag is , is not found). And check for -.