From 803a10d4fabbd30533721db2f5efaefbccd88cdd Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Sat, 28 Oct 2023 18:30:20 +0200 Subject: commands: expand templates before command resolution Move the template expansion before the command name is looked up. It saves a few void renderings and will be required for the next commits. Signed-off-by: Robin Jarry Tested-by: Inwit --- commands/commands.go | 29 +++++++++-------------------- main.go | 6 +++++- 2 files changed, 14 insertions(+), 21 deletions(-) diff --git a/commands/commands.go b/commands/commands.go index 0ca8dc36..1c303484 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -111,16 +111,7 @@ func templateData( return data.Data() } -func (cmds *Commands) ExecuteCommand( - cmdline string, - account *config.AccountConfig, - msg *models.MessageInfo, -) error { - data := templateData(account, msg) - cmdline, err := expand(data, cmdline) - if err != nil { - return err - } +func (cmds *Commands) ExecuteCommand(cmdline string) error { args := opt.LexArgs(cmdline) name, err := args.ArgSafe(0) if err != nil { @@ -133,14 +124,18 @@ func (cmds *Commands) ExecuteCommand( return NoSuchCommand(name) } -// expand expands template expressions -func expand(data models.TemplateData, s string) (string, error) { +// expand template expressions +func ExpandTemplates( + s string, cfg *config.AccountConfig, msg *models.MessageInfo, +) (string, error) { if strings.Contains(s, "{{") && strings.Contains(s, "}}") { t, err := templates.ParseTemplate("execute", s) if err != nil { return "", err } + data := templateData(cfg, msg) + var buf bytes.Buffer err = templates.Render(t, &buf, data) if err != nil { @@ -188,18 +183,12 @@ func GetTemplateCompletion( return options, prefix + padding, true case countLeft == countRight: // expand template - data := templateData(nil, nil) - t, err := templates.ParseTemplate("", cmd) + s, err := ExpandTemplates(cmd, nil, nil) if err != nil { - log.Warnf("template parsing failed: %v", err) - return nil, "", false - } - var sb strings.Builder - if err = templates.Render(t, &sb, data); err != nil { log.Warnf("template rendering failed: %v", err) return nil, "", false } - return []string{sb.String()}, "", true + return []string{s}, "", true } return nil, "", false diff --git a/main.go b/main.go index b72bf713..8ac70cf9 100644 --- a/main.go +++ b/main.go @@ -105,6 +105,10 @@ func execCommand( cmdline string, acct *config.AccountConfig, msg *models.MessageInfo, ) error { + cmdline, err := commands.ExpandTemplates(cmdline, acct, msg) + if err != nil { + return err + } name, rest, didCut := strings.Cut(cmdline, " ") cmds := getCommands(app.SelectedTabContent()) cmdline = expandAbbreviations(name, cmds) @@ -112,7 +116,7 @@ func execCommand( cmdline += " " + rest } for i, set := range cmds { - err := set.ExecuteCommand(cmdline, acct, msg) + err := set.ExecuteCommand(cmdline) if err != nil { if errors.As(err, new(commands.NoSuchCommand)) { if i == len(cmds)-1 { -- cgit v1.2.3-54-g00ecf