polygon-cli
polygon-cli copied to clipboard
chore: refactor flag_loader
Description
- Remove
flag_loaderpackage to the root directory - Combine some logic to improve flag parsing
Jira / Linear Tickets
- DVT-000
Testing
- [ ] Test A
- [ ] Test B
Cobra Best Practices Research
I've done some research on Cobra best practices to improve our CLI development. Here are the key findings:
Flag Sharing Patterns
- Struct with
AddFlags()method is the most common pattern in popular projects (kubectl, Docker CLI, Helm) - Allows sharing flags horizontally across unrelated commands
- Better than PersistentFlags for non-parent-child relationships
Viper + Cobra Integration
- Configuration precedence: Flags > Environment Variables > Config File > Defaults
- Critical timing: Bind flags in
PersistentPreRunE(after parsing, before execution), NOT ininit() - Always read from Viper after binding, never from flag variables
- Use
mapstructuretags to map dash-containing flag names (e.g.,--write-to-tx) to Go struct fields (e.g.,WriteToTx)
Key Pattern for Viper
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return viper.BindPFlags(cmd.Flags()) // Magic happens here
}
Resources
- Real-world examples from kubernetes/kubectl, docker/cli, helm/helm
- Flag sharing: Struct +
AddFlags()method pattern is industry standard - Viper unmarshalling: Use
mapstructuretags for any flag name → struct field mapping