sailorhq/sailor

CLI: Validations using Cobra's Helpers

Open

#7 opened on Aug 11, 2025

View on GitHub
 (2 comments) (0 reactions) (1 assignee)Go (2 forks)auto 404
good first issuehelp wanted

Repository metrics

Stars
 (2 stars)
PR merge metrics
 (PR metrics pending)

Description

In CLI commands validations are handled in a custom way, and most of them are just copy-pasta's of code which are used in other command. We have the following nice API from Cobra for flag validations:

What you want to express Cobra helper Typical usage
Single flag is mandatory cmd.MarkFlagRequired(name) cmd.MarkFlagRequired("config")
Two or more flags are all required together cmd.MarkFlagsRequiredTogether(names…) cmd.MarkFlagsRequiredTogether("input", "output")
A set of flags are mutually exclusive cmd.MarkFlagsMutuallyExclusive(names…) cmd.MarkFlagsMutuallyExclusive("json", "yaml")
All flags in a set are required together or at least one of them must be present cmd.MarkFlagsOneRequired(names…) cmd.MarkFlagsOneRequired("id", "name")

For flag values like kind where we need to only allow certain values, use Annotations.

// Register the flag
rootCmd.Flags().StringVar(&kind, "kind", "", "resource kind (config, secret, misc)")
// Tell Cobra what values are acceptable
rootCmd.Flags().SetAnnotation("kind", cobra.ValidArgsAnnotation, []string{"config", "secret", "misc"})

Once we move all code to these helpers, we will have nice looking less messy code 😉

Contributor guide