Skip to content

Commit

Permalink
Merge branch 'main' into nushell
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack Wright committed Nov 12, 2024
2 parents 99c3692 + 02326d5 commit 49445b9
Show file tree
Hide file tree
Showing 16 changed files with 173 additions and 114 deletions.
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ jobs:
- 20
- 21
- 22
- 23
name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
runs-on: ${{ matrix.platform }}-latest
steps:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ go install github.com/spf13/cobra-cli@latest

For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)

For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md).
For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md).

# License

Expand Down
33 changes: 18 additions & 15 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ func (c *Command) SetArgs(a []string) {

// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
//
// Deprecated: Use SetOut and/or SetErr instead
func (c *Command) SetOutput(output io.Writer) {
c.outWriter = output
Expand Down Expand Up @@ -606,7 +607,7 @@ func (c *Command) VersionTemplate() string {
if c.HasParent() {
return c.parent.VersionTemplate()
}
return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
return `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
`
}

Expand Down Expand Up @@ -1189,7 +1190,7 @@ func (c *Command) InitDefaultHelpFlag() {
c.mergePersistentFlags()
if c.Flags().Lookup("help") == nil {
usage := "help for "
name := c.displayName()
name := c.DisplayName()
if name == "" {
usage += "this command"
} else {
Expand All @@ -1215,7 +1216,7 @@ func (c *Command) InitDefaultVersionFlag() {
if c.Name() == "" {
usage += "this command"
} else {
usage += c.Name()
usage += c.DisplayName()
}
if c.Flags().ShorthandLookup("v") == nil {
c.Flags().BoolP("version", "v", false, usage)
Expand All @@ -1239,7 +1240,7 @@ func (c *Command) InitDefaultHelpCmd() {
Use: "help [command]",
Short: "Help about any command",
Long: `Help provides help for any command in the application.
Simply type ` + c.displayName() + ` help [path to command] for full details.`,
Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
var completions []string
cmd, _, e := c.Root().Find(args)
Expand Down Expand Up @@ -1430,10 +1431,12 @@ func (c *Command) CommandPath() string {
if c.HasParent() {
return c.Parent().CommandPath() + " " + c.Name()
}
return c.displayName()
return c.DisplayName()
}

func (c *Command) displayName() string {
// DisplayName returns the name to display in help text. Returns command Name()
// If CommandDisplayNameAnnoation is not set
func (c *Command) DisplayName() string {
if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
return displayName
}
Expand All @@ -1443,7 +1446,7 @@ func (c *Command) displayName() string {
// UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string {
var useline string
use := strings.Replace(c.Use, c.Name(), c.displayName(), 1)
use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
if c.HasParent() {
useline = c.parent.CommandPath() + " " + use
} else {
Expand Down Expand Up @@ -1649,7 +1652,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f
// to this command (local and persistent declared here and by all parents).
func (c *Command) Flags() *flag.FlagSet {
if c.flags == nil {
c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
Expand All @@ -1664,7 +1667,7 @@ func (c *Command) Flags() *flag.FlagSet {
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
persistentFlags := c.PersistentFlags()

out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
c.LocalFlags().VisitAll(func(f *flag.Flag) {
if persistentFlags.Lookup(f.Name) == nil {
out.AddFlag(f)
Expand All @@ -1679,7 +1682,7 @@ func (c *Command) LocalFlags() *flag.FlagSet {
c.mergePersistentFlags()

if c.lflags == nil {
c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
Expand Down Expand Up @@ -1707,7 +1710,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
c.mergePersistentFlags()

if c.iflags == nil {
c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
Expand Down Expand Up @@ -1736,7 +1739,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet {
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
func (c *Command) PersistentFlags() *flag.FlagSet {
if c.pflags == nil {
c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
Expand All @@ -1749,9 +1752,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
func (c *Command) ResetFlags() {
c.flagErrorBuf = new(bytes.Buffer)
c.flagErrorBuf.Reset()
c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
c.flags.SetOutput(c.flagErrorBuf)
c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
c.pflags.SetOutput(c.flagErrorBuf)

c.lflags = nil
Expand Down Expand Up @@ -1868,7 +1871,7 @@ func (c *Command) mergePersistentFlags() {
// If c.parentsPflags == nil, it makes new.
func (c *Command) updateParentsPflags() {
if c.parentsPflags == nil {
c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
c.parentsPflags.SetOutput(c.flagErrorBuf)
c.parentsPflags.SortFlags = false
}
Expand Down
30 changes: 26 additions & 4 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,9 @@ func TestAliasPrefixMatching(t *testing.T) {
// text should reflect the way we run the command.
func TestPlugin(t *testing.T) {
cmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,
Use: "kubectl-plugin",
Version: "1.0.0",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Expand All @@ -386,13 +387,15 @@ func TestPlugin(t *testing.T) {

checkStringContains(t, cmdHelp, "kubectl plugin [flags]")
checkStringContains(t, cmdHelp, "help for kubectl plugin")
checkStringContains(t, cmdHelp, "version for kubectl plugin")
}

// TestPlugin checks usage as plugin with sub commands.
func TestPluginWithSubCommands(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Args: NoArgs,
Use: "kubectl-plugin",
Version: "1.0.0",
Args: NoArgs,
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Expand All @@ -408,6 +411,7 @@ func TestPluginWithSubCommands(t *testing.T) {

checkStringContains(t, rootHelp, "kubectl plugin [command]")
checkStringContains(t, rootHelp, "help for kubectl plugin")
checkStringContains(t, rootHelp, "version for kubectl plugin")
checkStringContains(t, rootHelp, "kubectl plugin [command] --help")

childHelp, err := executeCommand(rootCmd, "sub", "-h")
Expand Down Expand Up @@ -1090,6 +1094,24 @@ func TestVersionFlagExecuted(t *testing.T) {
checkStringContains(t, output, "root version 1.0.0")
}

func TestVersionFlagExecutedDiplayName(t *testing.T) {
rootCmd := &Command{
Use: "kubectl-plugin",
Version: "1.0.0",
Annotations: map[string]string{
CommandDisplayNameAnnotation: "kubectl plugin",
},
Run: emptyRun,
}

output, err := executeCommand(rootCmd, "--version", "arg1")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

checkStringContains(t, output, "kubectl plugin version 1.0.0")
}

func TestVersionFlagExecutedWithNoName(t *testing.T) {
rootCmd := &Command{Version: "1.0.0", Run: emptyRun}

Expand Down
5 changes: 3 additions & 2 deletions completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,9 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi
doCompleteFlags := func(flag *pflag.Flag) {
if !flag.Changed ||
strings.Contains(flag.Value.Type(), "Slice") ||
strings.Contains(flag.Value.Type(), "Array") {
// If the flag is not already present, or if it can be specified multiple times (Array or Slice)
strings.Contains(flag.Value.Type(), "Array") ||
strings.HasPrefix(flag.Value.Type(), "stringTo") {
// If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)
// we suggest it as a completion
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
}
Expand Down
5 changes: 2 additions & 3 deletions doc/man_docs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -168,7 +167,7 @@ func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
func TestGenManTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
header := &GenManHeader{Section: "2"}
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
tmpdir, err := os.MkdirTemp("", "test-gen-man-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error())
}
Expand Down Expand Up @@ -219,7 +218,7 @@ func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
}

func BenchmarkGenManToFile(b *testing.B) {
file, err := ioutil.TempFile("", "")
file, err := os.CreateTemp("", "")
if err != nil {
b.Fatal(err)
}
Expand Down
5 changes: 2 additions & 3 deletions doc/md_docs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package doc

import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -94,7 +93,7 @@ func TestGenMdNoTag(t *testing.T) {

func TestGenMdTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
tmpdir, err := os.MkdirTemp("", "test-gen-md-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %v", err)
}
Expand All @@ -110,7 +109,7 @@ func TestGenMdTree(t *testing.T) {
}

func BenchmarkGenMarkdownToFile(b *testing.B) {
file, err := ioutil.TempFile("", "")
file, err := os.CreateTemp("", "")
if err != nil {
b.Fatal(err)
}
Expand Down
5 changes: 2 additions & 3 deletions doc/rest_docs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package doc

import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -81,7 +80,7 @@ func TestGenRSTNoTag(t *testing.T) {
func TestGenRSTTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}

tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
tmpdir, err := os.MkdirTemp("", "test-gen-rst-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error())
}
Expand All @@ -97,7 +96,7 @@ func TestGenRSTTree(t *testing.T) {
}

func BenchmarkGenReSTToFile(b *testing.B) {
file, err := ioutil.TempFile("", "")
file, err := os.CreateTemp("", "")
if err != nil {
b.Fatal(err)
}
Expand Down
5 changes: 2 additions & 3 deletions doc/yaml_docs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package doc
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -58,7 +57,7 @@ func TestGenYamlNoTag(t *testing.T) {
func TestGenYamlTree(t *testing.T) {
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}

tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
tmpdir, err := os.MkdirTemp("", "test-gen-yaml-tree")
if err != nil {
t.Fatalf("Failed to create tmpdir: %s", err.Error())
}
Expand All @@ -85,7 +84,7 @@ func TestGenYamlDocRunnable(t *testing.T) {
}

func BenchmarkGenYamlToFile(b *testing.B) {
file, err := ioutil.TempFile("", "")
file, err := os.CreateTemp("", "")
if err != nil {
b.Fatal(err)
}
Expand Down
35 changes: 30 additions & 5 deletions powershell_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ filter __%[1]s_escapeStringWithSpecialChars {
if (-Not $Description) {
$Description = " "
}
@{Name="$Name";Description="$Description"}
New-Object -TypeName PSCustomObject -Property @{
Name = "$Name"
Description = "$Description"
}
}
Expand Down Expand Up @@ -240,7 +243,12 @@ filter __%[1]s_escapeStringWithSpecialChars {
__%[1]s_debug "Only one completion left"
# insert space after value
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
} else {
# Add the proper number of spaces to align the descriptions
Expand All @@ -255,7 +263,12 @@ filter __%[1]s_escapeStringWithSpecialChars {
$Description = " ($($comp.Description))"
}
[System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
$CompletionText = "$($comp.Name)$Description"
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
}
}
Expand All @@ -264,15 +277,27 @@ filter __%[1]s_escapeStringWithSpecialChars {
# insert space after value
# MenuComplete will automatically show the ToolTip of
# the highlighted value at the bottom of the suggestions.
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
}
# TabCompleteNext and in case we get something unknown
Default {
# Like MenuComplete but we don't want to add a space here because
# the user need to press space anyway to get the completion.
# Description will not be shown because that's not possible with TabCompleteNext
[System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
$CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars)
if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
[System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
} else {
$CompletionText
}
}
}
Expand Down
Loading

0 comments on commit 49445b9

Please sign in to comment.