From 65a7921445b18c4ae2f2ff91e6276380cf090063 Mon Sep 17 00:00:00 2001 From: Tiago Carreira Date: Mon, 31 Jul 2023 19:40:02 +0100 Subject: [PATCH] fix: autocomplete considers command flags chore: add ForceCallPreRun (for autocomplete) when using cobra.Command.ValidArgsFunction call wrappers.ForceCallPreRun() from inside it. This will force parsing the flags in order to consider flag overriding flags (eg: --targets) --- internal/wrappers/cobra.go | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 internal/wrappers/cobra.go diff --git a/internal/wrappers/cobra.go b/internal/wrappers/cobra.go new file mode 100644 index 000000000..60468acc3 --- /dev/null +++ b/internal/wrappers/cobra.go @@ -0,0 +1,39 @@ +// Copyright © 2023 tsuru-client authors +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package wrappers + +import "github.com/spf13/cobra" + +// ForceCallPreRun climbs the parent tree until it finds and runs one of: +// - PreRun() +// - PreRunE() +// - PersistentPreRun() +// - PersistentPreRunE() +func ForceCallPreRun(cmd *cobra.Command, args []string) { + curr := cmd + for curr != nil { + if curr.PreRun != nil { + curr.PreRun(cmd, args) + return + } + if curr.PreRunE != nil { + _ = curr.PreRunE(cmd, args) + return + } + if curr.PersistentPreRun != nil { + curr.PersistentPreRun(cmd, args) + return + } + if curr.PersistentPreRunE != nil { + _ = curr.PersistentPreRunE(cmd, args) + return + } + + if curr == curr.Parent() { + return + } + curr = curr.Parent() + } +}