Files
commandkit/testdata/completion/main.go

51 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"context"
"encoding/json"
"fmt"
"os"
2026-11-04 03:49:38 +00:00
commandkit "go.maximumdirect.net/commandkit"
internalcobra "go.maximumdirect.net/commandkit/internal/cobra"
)
func main() {
args := os.Args[1:]
if logPath := os.Getenv("PROBE_LOG"); logPath != "" && (len(args) == 0 || args[0] != internalcobra.CompletionQueryToken) {
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
_ = json.NewEncoder(file).Encode(args)
_ = file.Close()
}
parse := func(value string) (string, error) { return value, nil }
flag := func(meta commandkit.FlagMeta) commandkit.Flag[struct{}] {
return commandkit.ValueFlag(meta, (*string)(nil), parse, func(*struct{}, commandkit.Supplied[string]) {})
}
run := commandkit.NewCommand(commandkit.CommandSpec[struct{}]{
Name: "run", Summary: "Run a fixture command.",
Flags: []commandkit.Flag[struct{}]{
commandkit.BoolFlag(commandkit.FlagMeta{Name: "switch", Short: "s"}, false, func(*struct{}, commandkit.Supplied[bool]) {}),
flag(commandkit.FlagMeta{Name: "format", Usage: "Report format.", Completion: commandkit.CompleteChoices(commandkit.CompletionChoice{Value: "text", Description: "Readable text"}, commandkit.CompletionChoice{Value: "yaml", Description: "YAML output"})}),
flag(commandkit.FlagMeta{Name: "config", Short: "c", Usage: "Configuration path.", Completion: commandkit.CompleteFiles()}),
flag(commandkit.FlagMeta{Name: "directory", Short: "d", Usage: "Directory path.", Completion: commandkit.CompleteDirectories()}),
},
Arguments: []commandkit.Argument[struct{}]{commandkit.ValueArgument(
commandkit.ArgumentMeta{Name: "item", Completion: commandkit.CompleteChoices(commandkit.CompletionChoice{Value: "alpha", Description: "Example item"})},
false, parse, func(*struct{}, commandkit.Supplied[string]) {})},
Run: func(commandkit.Invocation, struct{}) commandkit.Outcome { return commandkit.Success() },
})
app, err := commandkit.New(commandkit.Identity{Name: "Completion fixture"}, commandkit.Completion("probe"), run, commandkit.Alias("shortcut", "run"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
if outcome.Status != 0 {
os.Exit(outcome.Status)
}
}