Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completion support for Nushell #1857

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions nushell_completions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
"bytes"
"io"
"os"
)

func (c *Command) GenNushellCompletion(w io.Writer) error {
ayax79 marked this conversation as resolved.
Show resolved Hide resolved
buf := new(bytes.Buffer)
WriteStringAndCheck(buf, `
# An external configurator that works with any cobra based
# command line application (e.g. kubectl, minikube)
let cobra_configurator = {|spans|
ayax79 marked this conversation as resolved.
Show resolved Hide resolved

let cmd = $spans.0

# skip the first entry in the span (the command) and join the rest of the span to create __complete args
let cmd_args = ($spans | skip 1 | str join ' ')

# If the last span entry was empty add "" to the end of the command args
let cmd_args = if ($spans | last | str trim | is-empty) {
$'($cmd_args) ""'
} else {
$cmd_args
}

# The full command to be executed
let full_cmd = $'($cmd) __complete ($cmd_args)'
ayax79 marked this conversation as resolved.
Show resolved Hide resolved

# Since nushell doesn't have anything like eval, execute in a subshell
let result = (do -i { nu -c $"'($full_cmd)'" } | complete)

# Create a record with all completion related info.
# directive and directive_str are for posterity
let stdout_lines = ($result.stdout | lines)
let $completions = ($stdout_lines | drop | parse -r '([\w\-\.:\+]*)\t?(.*)' | rename value description)

let result = ({
completions: $completions
directive_str: ($result.stderr)
directive: ($stdout_lines | last)
})

ayax79 marked this conversation as resolved.
Show resolved Hide resolved
$result.completions
}`)

_, err := buf.WriteTo(w)
return err
}

func (c *Command) GenNushellCompletionFile(filename string) error {
outFile, err := os.Create(filename)
if err != nil {
return err
}
defer outFile.Close()

return c.GenNushellCompletion(outFile)
}
4 changes: 4 additions & 0 deletions nushell_completions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Generating Nushell Completions For Your cobra.Command

Please refer to [Shell Completions](shell_completions.md) for details.

96 changes: 96 additions & 0 deletions nushell_completions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
"bytes"
"log"
"os"
"testing"
)

func TestGenNushellCompletion(t *testing.T) {
rootCmd := &Command{Use: "kubectl", Run: emptyRun}
rootCmd.PersistentFlags().String("server", "s", "The address and port of the Kubernetes API server")
rootCmd.PersistentFlags().BoolP("skip-headers", "", false, "The address and port of the Kubernetes API serverIf true, avoid header prefixes in the log messages")
getCmd := &Command{
Use: "get",
Short: "Display one or many resources",
ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"},
ValidArgs: []string{"pod", "node", "service", "replicationcontroller"},
Run: emptyRun,
}
rootCmd.AddCommand(getCmd)

buf := new(bytes.Buffer)
assertNoErr(t, rootCmd.GenNushellCompletion(buf))
output := buf.String()

check(t, output, "let full_cmd = $'($cmd) __complete ($cmd_args)'")
}

func TestGenNushellCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0o755)
if err != nil {
log.Fatal(err.Error())
}

defer os.RemoveAll("./tmp")

rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{
Use: "child",
ValidArgsFunction: validArgsFunc,
Run: emptyRun,
}
rootCmd.AddCommand(child)

assertNoErr(t, rootCmd.GenNushellCompletionFile("./tmp/test"))
}

func TestFailGenNushellCompletionFile(t *testing.T) {
err := os.Mkdir("./tmp", 0o755)
if err != nil {
log.Fatal(err.Error())
}

defer os.RemoveAll("./tmp")

f, _ := os.OpenFile("./tmp/test", os.O_CREATE, 0o400)
defer f.Close()

rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
child := &Command{
Use: "child",
ValidArgsFunction: validArgsFunc,
Run: emptyRun,
}
rootCmd.AddCommand(child)

got := rootCmd.GenNushellCompletionFile("./tmp/test")
if got == nil {
t.Error("should raise permission denied error")
}

if os.Getenv("MSYSTEM") == "MINGW64" {
if got.Error() != "open ./tmp/test: Access is denied." {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: Access is denied.")
}
} else {
if got.Error() != "open ./tmp/test: permission denied" {
t.Errorf("got: %s, want: %s", got.Error(), "open ./tmp/test: permission denied")
}
}
}
21 changes: 20 additions & 1 deletion shell_completions.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The currently supported shells are:
- Zsh
- fish
- PowerShell
- Nushell
ayax79 marked this conversation as resolved.
Show resolved Hide resolved

Cobra will automatically provide your program with a fully functional `completion` command,
similarly to how it provides the `help` command.
Expand Down Expand Up @@ -68,9 +69,25 @@ PowerShell:
# To load completions for every new session, run:
PS> %[1]s completion powershell > %[1]s.ps1
# and source this file from your PowerShell profile.

Nushell:

# 1. Copy the output of the command below:
> %[1]s completion nushell

# 2. Edit the nushell config file:
> config nu

# 3. Paste above the "let-env config" line.

# 4. Change the config block's external_completer line to be
external_completer: $cobra_completer

# 5. You will need to start a new shell for this setup to take effect.

`,cmd.Root().Name()),
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
ValidArgs: []string{"bash", "zsh", "fish", "powershell", "nushell"},
marckhouzam marked this conversation as resolved.
Show resolved Hide resolved
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
Expand All @@ -82,6 +99,8 @@ PowerShell:
cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
case "nushell":
cmd.Root().GenNushellCompletion(os.Stdout, true)
ayax79 marked this conversation as resolved.
Show resolved Hide resolved
}
},
}
Expand Down