cmd/completions.go

125 lines
2.6 KiB
Go

package cmd
import (
"io"
"os"
"go.fifitido.net/cmd/opt"
)
var outputFileOption = opt.String("output", "o", "", "The file to output the completions to")
func CompletionsSubcommand() *Command {
cmd := New(
"completions",
WithShortDescription("Generate shell completions"),
WithLongDescription("Generate shell completions"),
)
registerBashCompletions(cmd)
registerFishCompletions(cmd)
registerPowerShellCompletions(cmd)
registerZsgCompletions(cmd)
return cmd
}
func getCompletionsOut() io.Writer {
outputFile := outputFileOption.Value()
if outputFile != "" {
var err error
out, err := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
return out
}
return os.Stdout
}
func registerBashCompletions(parent *Command) *Command {
return New(
"bash",
WithShortDescription("Generate bash completions"),
WithLongDescription("Generate bash completions"),
WithOptions(outputFileOption),
WithParent(parent),
WithRunFunc(func(args []string) {
out := getCompletionsOut()
if fc, ok := out.(io.Closer); ok {
defer fc.Close()
}
if err := WriteBashCompletions(out, parent.Root()); err != nil {
panic(err)
}
}),
)
}
func registerFishCompletions(parent *Command) *Command {
return New(
"fish",
WithShortDescription("Generate fish completions"),
WithLongDescription("Generate fish completions"),
WithOptions(outputFileOption),
WithParent(parent),
WithRunFunc(func(args []string) {
out := getCompletionsOut()
if fc, ok := out.(io.Closer); ok {
defer fc.Close()
}
if err := WriteFishCompletions(out, parent.Root()); err != nil {
panic(err)
}
}),
)
}
func registerPowerShellCompletions(parent *Command) *Command {
return New(
"powershell",
WithShortDescription("Generate powershell completions"),
WithLongDescription("Generate powershell completions"),
WithOptions(outputFileOption),
WithParent(parent),
WithRunFunc(func(args []string) {
out := getCompletionsOut()
if fc, ok := out.(io.Closer); ok {
defer fc.Close()
}
if err := WritePowerShellCompletions(out, parent.Root()); err != nil {
panic(err)
}
}),
)
}
func registerZsgCompletions(parent *Command) *Command {
return New(
"zsh",
WithShortDescription("Generate zsh completions"),
WithLongDescription("Generate zsh completions"),
WithOptions(outputFileOption),
WithParent(parent),
WithRunFunc(func(args []string) {
out := getCompletionsOut()
if fc, ok := out.(io.Closer); ok {
defer fc.Close()
}
if err := WriteZshCompletions(out, parent.Root()); err != nil {
panic(err)
}
}),
)
}