chinampa/pkg/command/help.go

68 lines
1.5 KiB
Go
Raw Normal View History

2022-12-19 03:04:34 +00:00
// Copyright © 2022 Roberto Hidalgo <chinampa@un.rob.mx>
2022-12-31 05:53:24 +00:00
// SPDX-License-Identifier: Apache-2.0
2022-12-19 03:04:34 +00:00
package command
import (
"bytes"
2022-12-31 05:53:24 +00:00
"git.rob.mx/nidito/chinampa/pkg/render"
2022-12-19 03:04:34 +00:00
"git.rob.mx/nidito/chinampa/pkg/runtime"
"github.com/spf13/cobra"
)
type combinedCommand struct {
Spec *Command
Command *cobra.Command
GlobalOptions Options
HTMLOutput bool
}
func (cmd *Command) HasAdditionalHelp() bool {
return cmd.HelpFunc != nil
}
func (cmd *Command) AdditionalHelp(printLinks bool) *string {
if cmd.HelpFunc != nil {
str := cmd.HelpFunc(printLinks)
return &str
}
return nil
}
func (cmd *Command) HelpRenderer(globalOptions Options) func(cc *cobra.Command, args []string) {
return func(cc *cobra.Command, args []string) {
// some commands don't have a binding until help is rendered
// like virtual ones (sub command groups)
cmd.SetCobra(cc)
content, err := cmd.ShowHelp(globalOptions, args)
if err != nil {
panic(err)
}
_, err = cc.OutOrStderr().Write(content)
if err != nil {
panic(err)
}
}
}
func (cmd *Command) ShowHelp(globalOptions Options, args []string) ([]byte, error) {
var buf bytes.Buffer
2023-03-24 01:51:36 +00:00
colorEnabled := runtime.ColorEnabled()
2022-12-19 03:04:34 +00:00
c := &combinedCommand{
Spec: cmd,
Command: cmd.Cobra,
GlobalOptions: globalOptions,
2023-03-24 01:51:36 +00:00
HTMLOutput: runtime.HelpStyle() == "markdown",
2022-12-19 03:04:34 +00:00
}
2022-12-31 05:53:24 +00:00
err := render.HelpTemplate(runtime.Executable).Execute(&buf, c)
2022-12-19 03:04:34 +00:00
if err != nil {
return nil, err
}
content, err := render.Markdown(buf.Bytes(), colorEnabled)
if err != nil {
return nil, err
}
return content, nil
}