diff --git a/pkg/cli/commands.go b/pkg/cli/commands.go index ad6366e..68e71b2 100644 --- a/pkg/cli/commands.go +++ b/pkg/cli/commands.go @@ -66,9 +66,7 @@ func CommandFactory(raw string, macro *Macro) (Executer, error) { return NewCommandWaitForResp(timeout), nil default: if macro != nil { - if command, ok := (*macro)[cmd]; ok { - return command, nil - } + return macro.Get(cmd) } return nil, fmt.Errorf("unknown command: %s", cmd) @@ -221,3 +219,24 @@ func (c *CommandCmdEdit) Execute(exCtx *ExecutionContext) (Executer, error) { return cmd, nil } + +type CommandSequence struct { + subCommands []Executer +} + +func NewCommandSequence(subCommands []Executer) *CommandSequence { + return &CommandSequence{subCommands} +} + +func (c *CommandSequence) Execute(exCtx *ExecutionContext) (Executer, error) { + for _, cmd := range c.subCommands { + for cmd != nil { + var err error + if cmd, err = cmd.Execute(exCtx); err != nil { + return nil, err + } + } + } + + return nil, nil +} diff --git a/pkg/cli/macro.go b/pkg/cli/macro.go index 354d2b9..32ccdb5 100644 --- a/pkg/cli/macro.go +++ b/pkg/cli/macro.go @@ -13,7 +13,53 @@ type Config struct { Domains []string `yaml:"domains"` } -type Macro map[string]Executer +type Macro struct { + macro map[string]Executer + domains []string +} + +func NewMacro(domains []string) *Macro { + return &Macro{ + macro: make(map[string]Executer), + domains: domains, + } +} + +func (m *Macro) AddCommands(name string, rawCommands []string) error { + if _, ok := m.macro[name]; ok { + return fmt.Errorf("macro already exists: %s", name) + } + + commands := []Executer{} + + for _, rawCommand := range rawCommands { + cmd, err := CommandFactory(rawCommand, nil) + if err != nil { + return err + } + + commands = append(commands, cmd) + } + + switch len(commands) { + case 0: + return fmt.Errorf("empty macro: %s", name) + case 1: + m.macro[name] = commands[0] + default: + m.macro[name] = NewCommandSequence(commands) + } + + return nil +} + +func (m *Macro) Get(name string) (Executer, error) { + if cmd, ok := m.macro[name]; ok { + return cmd, nil + } + + return nil, fmt.Errorf("unknown command: %s", name) +} func LoadMacro(path string) (*Macro, error) { data, err := os.ReadFile(path) @@ -30,26 +76,13 @@ func LoadMacro(path string) (*Macro, error) { return nil, fmt.Errorf("unsupported macro version: %s", cfg.Version) } - macro := make(Macro) + macroCfg := NewMacro(cfg.Domains) for name, rawCommands := range cfg.Macro { - var commands []Executer - - for _, rawCommand := range rawCommands { - cmd, err := CommandFactory(rawCommand, nil) - if err != nil { - return nil, err - } - - commands = append(commands, cmd) + if err := macroCfg.AddCommands(name, rawCommands); err != nil { + return nil, err } - - if len(commands) == 0 { - return nil, fmt.Errorf("empty macro: %s", name) - } - - macro[name] = commands[0] } - return ¯o, nil + return macroCfg, nil }