Preserve alias context in usage errors

This commit is contained in:
2026-10-19 19:46:22 +00:00
parent a504efbad7
commit 1fa026e5bd
5 changed files with 239 additions and 13 deletions

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"strings"
internalcobra "gitea.maximumdirect.net/eric/CommandKit/internal/cobra"
commandmeta "gitea.maximumdirect.net/eric/CommandKit/internal/commandmeta"
@@ -40,12 +41,12 @@ func (a *App) Execute(ctx context.Context, args []string, streams Streams) Outco
return current.present(current.renderHelp(parsed.Path), parsed.Path)
}
if parsed.HelpRequested || !payload.hasRun() {
if _, err := payload.prepare(parsed.FlagValues, parsed.Operands, false); err != nil {
if _, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.Operands, false); err != nil {
return current.present(Usage(err), parsed.Path)
}
return current.present(current.renderHelp(parsed.Path), parsed.Path)
}
run, err := payload.prepare(parsed.FlagValues, parsed.Operands, true)
run, err := payload.prepare(parsed.FlagValues, parsed.FlagSpellings, parsed.Operands, true)
if err != nil {
return current.present(Usage(err), parsed.Path)
}
@@ -190,7 +191,20 @@ func (current *execution) usageLine(path []string) string {
}
func (current *execution) present(outcome Outcome, path []string) Outcome {
return current.app.presentWithUsageLine(outcome, path, current.streams, current.usageLine)
usageLine := func(path []string) string { return current.usageLine(path) }
if current.route.kind == routeCanonical && !current.route.enteredPath.Equal(current.route.canonicalPath) {
path = clonePath(current.route.enteredPath)
usageLine = func([]string) string { return current.routeUsageLine() }
}
return current.app.presentWithUsageLine(outcome, path, current.streams, usageLine)
}
func (current *execution) routeUsageLine() string {
line := current.usageLine(clonePath(current.route.canonicalPath))
canonical := strings.TrimSpace(current.app.identity.Name + " " + current.route.canonicalPath.String())
entered := strings.TrimSpace(current.app.identity.Name + " " + current.route.enteredPath.String())
line = strings.Replace(line, "Usage: "+canonical, "Usage: "+entered, 1)
return line + "\nAlias for: " + canonical
}
func normalizeStreams(streams Streams) Streams {