From 1dce090192092391187d4f1de18a20bae03095a6 Mon Sep 17 00:00:00 2001 From: rsteube Date: Mon, 10 Jul 2023 18:32:37 +0200 Subject: [PATCH] spec: support hidden --- internal/pflagfork/flag.go | 16 ++++++++++++++++ internal/shell/spec/command.go | 2 ++ internal/shell/spec/snippet.go | 12 ++++-------- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/internal/pflagfork/flag.go b/internal/pflagfork/flag.go index 1fb3ff5f..ae4676ca 100644 --- a/internal/pflagfork/flag.go +++ b/internal/pflagfork/flag.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/rsteube/carapace/pkg/style" + "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -125,6 +126,13 @@ func (f Flag) Style() string { } } +func (f Flag) Required() bool { + if annotation := f.Annotations[cobra.BashCompOneRequiredFlag]; len(annotation) == 1 && annotation[0] == "true" { + return true + } + return false +} + func (f Flag) Definition() string { var definition string switch f.Mode() { @@ -141,6 +149,14 @@ func (f Flag) Definition() string { } } + if f.Hidden { + definition += "&" + } + + if f.Required() { + definition += "!" + } + if f.IsRepeatable() { definition += "*" } diff --git a/internal/shell/spec/command.go b/internal/shell/spec/command.go index 49eb17db..f3db47b3 100644 --- a/internal/shell/spec/command.go +++ b/internal/shell/spec/command.go @@ -5,6 +5,8 @@ type Command struct { Aliases []string `yaml:"aliases,omitempty"` Description string `yaml:"description,omitempty"` Group string `yaml:"group,omitempty"` + Hidden bool `yaml:"hidden,omitempty"` + ExclusiveFlags [][]string `yaml:"exclusiveflags,omitempty"` Flags map[string]string `yaml:"flags,omitempty"` PersistentFlags map[string]string `yaml:"persistentflags,omitempty"` Completion struct { diff --git a/internal/shell/spec/snippet.go b/internal/shell/spec/snippet.go index 4d484e70..7a7ee399 100644 --- a/internal/shell/spec/snippet.go +++ b/internal/shell/spec/snippet.go @@ -20,16 +20,15 @@ func command(cmd *cobra.Command) Command { Description: cmd.Short, Aliases: cmd.Aliases, Group: cmd.GroupID, + Hidden: cmd.Hidden, Flags: make(map[string]string), PersistentFlags: make(map[string]string), Commands: make([]Command, 0), } - cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) { - if flag.Hidden { - return - } + // TODO mutually exclusive flags + cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) { if cmd.PersistentFlags().Lookup(flag.Name) != nil { return } @@ -40,16 +39,13 @@ func command(cmd *cobra.Command) Command { }) cmd.PersistentFlags().VisitAll(func(flag *pflag.Flag) { - if flag.Hidden { - return - } f := pflagfork.Flag{Flag: flag} c.PersistentFlags[f.Definition()] = f.Usage }) for _, subcmd := range cmd.Commands() { - if !subcmd.Hidden { + if subcmd.Name() != "_carapace" { c.Commands = append(c.Commands, command(subcmd)) } }