mirror of
https://gitea.com/gitea/tea.git
synced 2026-10-26 11:01:25 +01:00
refactor(flags): accept plural flag names through one normalize function
Every command accepts a flag's plural, such as --add-labels for --add-label (D8), instead of per-command alias maps. Signed-off-by: bircni <bircni@icloud.com>
This commit is contained in:
3 files changed
+19
-8
No files matched your search
+18
-3
@@ -214,19 +214,34 @@ var rootGroups = map[string]string{
|
||||
// Commands add other gh verbs, such as new, co, add and get, to their own Aliases.
|
||||
var verbAliases = map[string]string{"list": "ls", "delete": "rm"}
|
||||
|
||||
// addVerbAliases gives every list and delete command its short name.
|
||||
// addVerbAliases gives every list and delete command its short name, and lets its flags be named
|
||||
// in the plural.
|
||||
func addVerbAliases(cmd *cobra.Command) {
|
||||
if alias, ok := verbAliases[cmd.Name()]; ok && cmd.HasParent() && !slices.Contains(cmd.Aliases, alias) {
|
||||
cmd.Aliases = append(cmd.Aliases, alias)
|
||||
}
|
||||
acceptPlurals(cmd)
|
||||
for _, child := range cmd.Commands() {
|
||||
addVerbAliases(child)
|
||||
}
|
||||
}
|
||||
|
||||
// acceptPlurals lets the flags of cmd be named in the plural, such as --add-labels for the gh name
|
||||
// --add-label (D8), without showing the plural in help.
|
||||
func acceptPlurals(cmd *cobra.Command) {
|
||||
names := map[string]bool{}
|
||||
cmd.Flags().VisitAll(func(flag *pflag.Flag) { names[flag.Name] = true })
|
||||
normalize := cmd.Flags().GetNormalizeFunc()
|
||||
cmd.Flags().SetNormalizeFunc(func(flags *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
if singular, ok := strings.CutSuffix(name, "s"); ok && !names[name] && names[singular] {
|
||||
name = singular
|
||||
}
|
||||
return normalize(flags, name)
|
||||
})
|
||||
}
|
||||
|
||||
// flagAliases makes the flags of cmd accept each key of aliases as another name of the flag it maps
|
||||
// to, without showing it in help. Renamed flags keep their old names working this way, such as the
|
||||
// plural --add-labels after the singular gh name --add-label became primary (D8).
|
||||
// to, without showing it in help. Renamed flags keep their old names working this way.
|
||||
func flagAliases(cmd *cobra.Command, aliases map[string]string) {
|
||||
normalize := cmd.Flags().GetNormalizeFunc()
|
||||
cmd.Flags().SetNormalizeFunc(func(flags *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
|
||||
Reference in new issue
Block a user