polygon-cli icon indicating copy to clipboard operation
polygon-cli copied to clipboard

chore: refactor flag_loader

Open minhd-vu opened this issue 3 months ago • 1 comments

Description

  • Remove flag_loader package to the root directory
  • Combine some logic to improve flag parsing

Jira / Linear Tickets

  • DVT-000

Testing

  • [ ] Test A
  • [ ] Test B

minhd-vu avatar Oct 03 '25 16:10 minhd-vu

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 in init()
  • Always read from Viper after binding, never from flag variables
  • Use mapstructure tags 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 mapstructure tags for any flag name → struct field mapping

minhd-vu avatar Oct 08 '25 18:10 minhd-vu