internal/commands: remove mutexes / synchronisation
The Register and RegisterLegacy functions are designed to be used in package init() functions, which are guaranteed to be run sequentially. From the documentation (https://go.dev/ref/mem#init); > Program initialization runs in a single goroutine, but that goroutine > may create other goroutines, which run concurrently. If a package `p` > imports package `q`, the completion of `q`'s `init` functions happens > before the start of any of `p`'s. > > The completion of all `init` functions is synchronized before the > start of the function `main.main`. This patch removes the synchonisation as no concurrency should happen if these functions are used as intended. As the internal queue is not expected to be mutated after use, we also don't have to return a copy. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
@ -2,32 +2,25 @@ package commands
|
||||
|
||||
import (
|
||||
"os"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/docker/cli/cli/command"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
commands []func(command.Cli) *cobra.Command
|
||||
l sync.RWMutex
|
||||
)
|
||||
var commands []func(command.Cli) *cobra.Command
|
||||
|
||||
// Register pushes the passed in command into an internal queue which can
|
||||
// be retrieved using the [Commands] function.
|
||||
// be retrieved using the [Commands] function. It is designed to be called
|
||||
// in an init function and is not safe for concurrent use.
|
||||
func Register(f func(command.Cli) *cobra.Command) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
commands = append(commands, f)
|
||||
}
|
||||
|
||||
// RegisterLegacy functions similarly to [Register], but it checks the
|
||||
// `DOCKER_HIDE_LEGACY_COMMANDS` environment variable and if
|
||||
// it has been set and is non-empty, the command will be hidden.
|
||||
// "DOCKER_HIDE_LEGACY_COMMANDS" environment variable and if it has been
|
||||
// set and is non-empty, the command will be hidden. It is designed to be called
|
||||
// in an init function and is not safe for concurrent use.
|
||||
func RegisterLegacy(f func(command.Cli) *cobra.Command) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
commands = append(commands, func(c command.Cli) *cobra.Command {
|
||||
cmd := f(c)
|
||||
if os.Getenv("DOCKER_HIDE_LEGACY_COMMANDS") == "" {
|
||||
@ -40,10 +33,8 @@ func RegisterLegacy(f func(command.Cli) *cobra.Command) {
|
||||
})
|
||||
}
|
||||
|
||||
// Commands returns a copy of the internal queue holding registered commands
|
||||
// added via [Register] or [RegisterLegacy].
|
||||
// Commands returns the internal queue holding registered commands added
|
||||
// via [Register] and [RegisterLegacy].
|
||||
func Commands() []func(command.Cli) *cobra.Command {
|
||||
l.RLock()
|
||||
defer l.RUnlock()
|
||||
return slices.Clone(commands)
|
||||
return commands
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user