Skip to content

Commit

Permalink
Merge pull request #295 from carapace-sh/flagset-visit-workaround
Browse files Browse the repository at this point in the history
FlagSet: Visit()` workaround for persistent flags
  • Loading branch information
rsteube authored Sep 3, 2024
2 parents 1420ee3 + 6d202c4 commit 4a41b80
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
6 changes: 4 additions & 2 deletions action.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,10 @@ func (a action) Parse(cmd *cobra.Command) carapace.Action {
}
c.Setenv("C_VALUE", c.Value)

cmd.Flags().Visit(func(f *pflag.Flag) {
c.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
cmd.Flags().VisitAll(func(f *pflag.Flag) { // VisitAll as Visit() skips changed persistent flags of parent commands
if f.Changed {
c.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
}
})

batch := carapace.Batch()
Expand Down
12 changes: 7 additions & 5 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ type run string
func (r run) parse() func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
context := carapace.NewContext(args...)
cmd.Flags().Visit(func(f *pflag.Flag) {
if slice, ok := f.Value.(pflag.SliceValue); ok {
context.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), strings.Join(slice.GetSlice(), ","))
} else {
context.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
cmd.Flags().VisitAll(func(f *pflag.Flag) { // VisitAll as Visit() skips changed persistent flags of parent commands
if f.Changed {
if slice, ok := f.Value.(pflag.SliceValue); ok {
context.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), strings.Join(slice.GetSlice(), ","))
} else {
context.Setenv(fmt.Sprintf("C_FLAG_%v", strings.ToUpper(f.Name)), f.Value.String())
}
}
})

Expand Down

0 comments on commit 4a41b80

Please sign in to comment.