From 338e831a8474c442b2c5e75eefed7b602276faa8 Mon Sep 17 00:00:00 2001 From: Dylan Allbee Date: Thu, 23 Jan 2020 21:08:18 -0800 Subject: [PATCH] Print global options in help for subcommands fixes #101 --- example_test.go | 3 ++- usage.go | 26 +++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/example_test.go b/example_test.go index be3cd12..4e6372f 100644 --- a/example_test.go +++ b/example_test.go @@ -235,7 +235,8 @@ func Example_helpTextForSubcommand() { // Positional arguments: // ITEM item to fetch // - // Options: + // Global options: + // --verbose // --help, -h display this help and exit } diff --git a/usage.go b/usage.go index 7ee68da..816c4be 100644 --- a/usage.go +++ b/usage.go @@ -144,9 +144,29 @@ func (p *Parser) writeHelpForCommand(w io.Writer, cmd *command) { } // write the list of options - fmt.Fprint(w, "\nOptions:\n") - for _, spec := range options { - p.printOption(w, spec) + if len(options) > 0 || cmd.parent == nil { + fmt.Fprint(w, "\nOptions:\n") + for _, spec := range options { + p.printOption(w, spec) + } + } + + // obtain a flattened list of options from all ancestors + var globals []*spec + ancestor := cmd.parent + for ancestor != nil { + for _, spec := range ancestor.specs { + globals = append(globals, spec) + } + ancestor = ancestor.parent + } + + // write the list of global options + if len(globals) > 0 { + fmt.Fprint(w, "\nGlobal options:\n") + for _, spec := range globals { + p.printOption(w, spec) + } } // write the list of built in options