From 3d00c2e38924ae28f54e5ad4b2e326a320d11697 Mon Sep 17 00:00:00 2001 From: Felix Svensson Date: Thu, 30 Dec 2021 09:09:13 +0100 Subject: [PATCH] feat(commands): add a list func to export registered commands --- command.go | 13 +++++++++++++ command_test.go | 12 ++++++++++++ 2 files changed, 25 insertions(+) diff --git a/command.go b/command.go index fcbae4a4..edcea144 100644 --- a/command.go +++ b/command.go @@ -120,5 +120,18 @@ func CreateCommand(commandType CommandType) (Command, error) { return nil, ErrCommandNotRegistered } +// ListCommands returns a list of all registered command types. +func RegisteredCommands() map[CommandType]func() Command { + commandsMu.Lock() + defer commandsMu.Unlock() + + mapCopy := make(map[CommandType]func() Command) + for key, val := range commands { + mapCopy[key] = val + } + + return mapCopy +} + var commands = make(map[CommandType]func() Command) var commandsMu sync.RWMutex diff --git a/command_test.go b/command_test.go index 56fcf68e..818f49bd 100644 --- a/command_test.go +++ b/command_test.go @@ -28,6 +28,7 @@ func TestCreateCommand(t *testing.T) { } RegisterCommand(func() Command { return &TestCommandRegister{} }) + defer UnregisterCommand(TestCommandRegisterType) cmd, err := CreateCommand(TestCommandRegisterType) if err != nil { @@ -87,6 +88,17 @@ func TestUnregisterCommandTwice(t *testing.T) { UnregisterCommand(TestCommandUnregisterTwiceType) } +func TestRegisteredCommands(t *testing.T) { + commands = make(map[CommandType]func() Command) + RegisterCommand(func() Command { return &TestCommandRegister{} }) + defer UnregisterCommand(TestCommandRegisterType) + + commands := RegisteredCommands() + if len(commands) != 1 { + t.Error("there should be one command:", commands) + } +} + const ( TestCommandRegisterType CommandType = "TestCommandRegister" TestCommandRegisterEmptyType CommandType = ""