LastMUD/internal/command/command.go

71 lines
1.4 KiB
Go
Raw Normal View History

2025-06-19 16:22:55 +03:00
package command
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
type Command struct {
commandDefinition CommandDefinition
params []Parameter
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
func CreateCommand(cmdDef CommandDefinition, parameters []Parameter) Command {
return Command{
commandDefinition: cmdDef,
params: parameters,
}
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
func (cmd Command) Execute() (err error) {
return cmd.commandDefinition.work(cmd.params...)
}
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
type commandContextError struct {
err string
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
func createCommandContextError(err string) *commandContextError {
return &commandContextError{
err: err,
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
}
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
func (cce *commandContextError) Error() string {
return cce.err
}
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
type CommandContext struct {
commandString string
tokens []Token
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
command Command
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
func CreateCommandContext(commandRegistry *CommandRegistry, commandString string) (ctx *CommandContext, err error) {
tokenizer := CreateTokenizer()
tokens, tokenizerError := tokenizer.Tokenize(commandString)
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
if tokenizerError != nil {
err = tokenizerError
return
}
commandDef := commandRegistry.Match(tokens)
if commandDef == nil {
err = createCommandContextError("Unknown command")
return
}
2025-06-16 14:59:51 +03:00
2025-06-18 17:04:06 +03:00
params := commandDef.ParseParameters(tokens)
ctx = &CommandContext{
commandString: commandString,
tokens: tokens,
command: CreateCommand(*commandDef, params),
2025-06-16 14:59:51 +03:00
}
2025-06-18 17:04:06 +03:00
return
}
func (ctx *CommandContext) ExecuteCommand() (err error) {
return ctx.command.Execute()
2025-06-16 14:59:51 +03:00
}