Skip to content

Commit b6ab205

Browse files
committed
Add command registration helpers
This patch adds helper methods to the CLI to register cobra commands. Signed-off-by: Alano Terblanche <[email protected]>
1 parent 877a6ef commit b6ab205

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

internal/commands/commands.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
func RegisterCommand(f func(command.Cli) *cobra.Command) {
18+
l.Lock()
19+
defer l.Unlock()
20+
commands = append(commands, f)
21+
}
22+
23+
// MaybeHideLegacy checks the `DOCKER_HIDE_LEGACY_COMMANDS` environment variable and if
24+
// it has been set and is non-empty, the legacy command will be hidden.
25+
// Legacy commands are `docker ps`, `docker exec`, etc.
26+
func MaybeHideLegacy(f func(command.Cli) *cobra.Command) func(command.Cli) *cobra.Command {
27+
return func(c command.Cli) *cobra.Command {
28+
cmd := f(c)
29+
// If the environment variable with name "DOCKER_HIDE_LEGACY_COMMANDS" is not empty,
30+
// these legacy commands (such as `docker ps`, `docker exec`, etc)
31+
// will not be shown in output console.
32+
if os.Getenv("DOCKER_HIDE_LEGACY_COMMANDS") == "" {
33+
return cmd
34+
}
35+
cmdCopy := *cmd
36+
cmdCopy.Hidden = true
37+
cmdCopy.Aliases = []string{}
38+
return &cmdCopy
39+
}
40+
}
41+
42+
func Commands() []func(command.Cli) *cobra.Command {
43+
l.RLock()
44+
defer l.RUnlock()
45+
return slices.Clone(commands)
46+
}

0 commit comments

Comments
 (0)