Skip to content

Commit c06074b

Browse files
authored
Merge pull request #6283 from Benehiko/command/registration
Add command registration helpers
2 parents 877a6ef + 4ead878 commit c06074b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

internal/commands/commands.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package commands
2+
3+
import (
4+
"os"
5+
"slices"
6+
"sync"
7+
8+
"github.com/docker/cli/cli/command"
9+
"github.com/spf13/cobra"
10+
)
11+
12+
var (
13+
commands []func(command.Cli) *cobra.Command
14+
l sync.RWMutex
15+
)
16+
17+
// Register pushes the passed in command into an internal queue which can
18+
// be retrieved using the [Commands] function.
19+
func Register(f func(command.Cli) *cobra.Command) {
20+
l.Lock()
21+
defer l.Unlock()
22+
commands = append(commands, f)
23+
}
24+
25+
// RegisterLegacy functions similarly to [Register], but it checks the
26+
// `DOCKER_HIDE_LEGACY_COMMANDS` environment variable and if
27+
// it has been set and is non-empty, the command will be hidden.
28+
func RegisterLegacy(f func(command.Cli) *cobra.Command) {
29+
l.Lock()
30+
defer l.Unlock()
31+
commands = append(commands, func(c command.Cli) *cobra.Command {
32+
cmd := f(c)
33+
if os.Getenv("DOCKER_HIDE_LEGACY_COMMANDS") == "" {
34+
return cmd
35+
}
36+
cmdCopy := *cmd
37+
cmdCopy.Hidden = true
38+
cmdCopy.Aliases = []string{}
39+
return &cmdCopy
40+
})
41+
}
42+
43+
// Commands returns a copy of the internal queue holding registered commands
44+
// added via [Register] or [RegisterLegacy].
45+
func Commands() []func(command.Cli) *cobra.Command {
46+
l.RLock()
47+
defer l.RUnlock()
48+
return slices.Clone(commands)
49+
}

0 commit comments

Comments
 (0)