Skip to content

Commit

Permalink
refactor: refactor help command using template (#282)
Browse files Browse the repository at this point in the history
Co-authored-by: Mohammad Hasan Saeedkia <170322053+MHSaeedkia@users.noreply.github.com>
  • Loading branch information
b00f and MHSaeedkia authored Jan 19, 2025
1 parent 9d5ea2b commit b4e9864
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 32 deletions.
77 changes: 47 additions & 30 deletions internal/engine/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/pagu-project/pagu/internal/entity"
"github.com/pagu-project/pagu/internal/version"
"github.com/pagu-project/pagu/pkg/log"
"github.com/pagu-project/pagu/pkg/utils"
)

Expand All @@ -21,11 +22,6 @@ const errorTemplate = `
{{.err}}
`

const aboutTemplate = `
**About pagu**
version : {{.version}}
`

var (
TargetMaskMainnet = 1
TargetMaskTestnet = 2
Expand Down Expand Up @@ -126,7 +122,7 @@ func (cmd *Command) RenderFailedTemplateF(reason string, a ...any) CommandResult
}

func (cmd *Command) RenderFailedTemplate(reason string) CommandResult {
msg, _ := cmd.executeTemplate(failedTemplate, map[string]any{"reason": reason})
msg := cmd.executeTemplate(failedTemplate, map[string]any{"reason": reason})

return CommandResult{
Title: fmt.Sprintf("%v %v", cmd.Name, cmd.Emoji),
Expand All @@ -136,7 +132,7 @@ func (cmd *Command) RenderFailedTemplate(reason string) CommandResult {
}

func (cmd *Command) RenderErrorTemplate(err error) CommandResult {
msg, _ := cmd.executeTemplate(errorTemplate, map[string]any{"err": err})
msg := cmd.executeTemplate(errorTemplate, map[string]any{"err": err})

return CommandResult{
Title: fmt.Sprintf("%v %v", cmd.Name, cmd.Emoji),
Expand All @@ -158,10 +154,7 @@ func (cmd *Command) RenderResultTemplate(keyvals ...any) CommandResult {
data[key] = val
}

msg, err := cmd.executeTemplate(cmd.ResultTemplate, data)
if err != nil {
return cmd.RenderErrorTemplate(err)
}
msg := cmd.executeTemplate(cmd.ResultTemplate, data)

return CommandResult{
Title: fmt.Sprintf("%v %v", cmd.Name, cmd.Emoji),
Expand All @@ -170,16 +163,29 @@ func (cmd *Command) RenderResultTemplate(keyvals ...any) CommandResult {
}
}

func (*Command) executeTemplate(templateContent string, data map[string]any) (string, error) {
tmpl, _ := template.New("template").Parse(templateContent)
func (*Command) executeTemplate(templateContent string, data map[string]any) string {
funcMap := template.FuncMap{
"fixed": func(width int, s string) string {
if len(s) > width {
return s[:width]
}

return s + strings.Repeat(" ", width-len(s))
},
}

tmpl, err := template.New("template").Funcs(funcMap).Parse(templateContent)
if err != nil {
log.Error("unable to parse template", "error", err)
}

var bldr strings.Builder
err := tmpl.Execute(&bldr, data)
err = tmpl.Execute(&bldr, data)
if err != nil {
return "", err
log.Error("unable to parse template", "error", err)
}

return strings.TrimSpace(bldr.String()), nil
return strings.TrimSpace(bldr.String())
}

// Deprecated: Use RenderResultTemplate.
Expand Down Expand Up @@ -215,10 +221,25 @@ func (cmd *Command) ErrorResult(err error) CommandResult {
return cmd.FailedResultF("An error occurred: %v", err.Error())
}

func (cmd *Command) HelpResult() CommandResult {
func (cmd *Command) RenderHelpTemplate() CommandResult {
const helpCommandTemplate = `
{{.cmd.Help}}
**Usage:**
{{.cmd.Name}} [subcommand]
**Available subcommands:**
{{- range .cmd.SubCommands }}
<pre>{{.Name | fixed 15 }}</pre> {{.Emoji}} {{.Help}}
{{- end}}
Use "{{.cmd.Name}} help --subcommand=[subcommand]" for more information about a subcommand.
`
msg := cmd.executeTemplate(helpCommandTemplate, map[string]any{"cmd": cmd})

return CommandResult{
Title: fmt.Sprintf("%v %v", cmd.Help, cmd.Emoji),
Message: cmd.HelpMessage(),
Title: fmt.Sprintf("%v %v", cmd.Name, cmd.Emoji),
Message: msg,
Successful: false,
}
}
Expand All @@ -231,16 +252,6 @@ func (cmd *Command) HasSubCommand() bool {
return len(cmd.SubCommands) > 0 && cmd.SubCommands != nil
}

func (cmd *Command) HelpMessage() string {
help := cmd.Help
help += "\n\nAvailable commands:\n"
for _, sc := range cmd.SubCommands {
help += fmt.Sprintf("- **%-12s**: %s\n", sc.Name, sc.Help)
}

return help
}

func (cmd *Command) AddSubCommand(subCmd *Command) {
if subCmd == nil {
return
Expand All @@ -260,14 +271,20 @@ func (cmd *Command) AddHelpSubCommand() {
AppIDs: entity.AllAppIDs(),
TargetFlag: TargetMaskAll,
Handler: func(_ *entity.User, _ *Command, _ map[string]string) CommandResult {
return cmd.SuccessfulResult(cmd.HelpMessage())
return cmd.RenderHelpTemplate()
},
}

cmd.AddSubCommand(helpCmd)
}

func (cmd *Command) AddAboutSubCommand() {
const aboutTemplate = `
## About Pagu
Version : {{.version}}
`

cmd.ResultTemplate = aboutTemplate
aboutCmd := &Command{
Name: "about",
Expand Down
1 change: 1 addition & 0 deletions internal/engine/command/crowdfund/crowdfund.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions internal/engine/command/crowdfund/crowdfund.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
emoji: 🤝
name: crowdfund
help: Commands for managing crowdfunding campaigns
sub_commands:
Expand Down
1 change: 1 addition & 0 deletions internal/engine/command/market/market.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions internal/engine/command/market/market.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
emoji: 📈
name: market
help: Commands for managing market
sub_commands:
Expand Down
4 changes: 2 additions & 2 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func newBotEngine(ctx context.Context,
rootCmd := &command.Command{
Emoji: "🤖",
Name: "pagu",
Help: "Root Command",
Help: "",
AppIDs: entity.AllAppIDs(),
SubCommands: make([]*command.Command, 0),
}
Expand Down Expand Up @@ -281,7 +281,7 @@ func (be *BotEngine) executeCommand(
}

if cmd.Handler == nil {
return cmd.HelpResult()
return cmd.RenderHelpTemplate()
}

caller, err := be.GetUser(appID, callerID)
Expand Down
3 changes: 3 additions & 0 deletions internal/generator/command.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func (c *{{.Name | title}}Cmd) buildSubCmds() *{{.Name}}SubCmds {

func (c *{{.Name | title}}Cmd) build{{.Name | title}}Command() *command.Command {
{{.Name}}Cmd := &command.Command{
{{- if .Emoji }}
Emoji: "{{.Emoji}}",
{{- end }}
Name: "{{.Name}}",
Help: "{{.Help}}",
SubCommands: make([]*command.Command, 0),
Expand Down

0 comments on commit b4e9864

Please sign in to comment.