Skip to content

Commit

Permalink
nushell: use lexer to patch arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Jul 31, 2023
1 parent 699888b commit 0be7a8a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
5 changes: 5 additions & 0 deletions complete.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package carapace

import (
"github.com/rsteube/carapace/internal/config"
"github.com/rsteube/carapace/internal/shell/nushell"
"github.com/rsteube/carapace/pkg/ps"
"github.com/spf13/cobra"
)
Expand All @@ -14,6 +15,10 @@ func complete(cmd *cobra.Command, args []string) (string, error) {
return Gen(cmd).Snippet(args[0])
default:
initHelpCompletion(cmd)

if shell := ps.DetermineShell(); shell == "nushell" {
args = nushell.Patch(args)
}
action, context := traverse(cmd, args[2:])
if err := config.Load(); err != nil {
action = ActionMessage("failed to load config: " + err.Error())
Expand Down
12 changes: 11 additions & 1 deletion internal/shell/nushell/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ var sanitizer = strings.NewReplacer(
"\r", ``,
)

var escaper = strings.NewReplacer(
`\`, `\\`,
`"`, `\"`,
)

func sanitize(values []common.RawValue) []common.RawValue {
for index, v := range values {
(&values[index]).Value = sanitizer.Replace(v.Value)
Expand All @@ -32,7 +37,12 @@ func ActionRawValues(currentWord string, meta common.Meta, values common.RawValu
vals := make([]record, len(values))
for index, val := range sanitize(values) {
if strings.ContainsAny(val.Value, ` {}()[]<>$&"|;#\`+"`") {
val.Value = fmt.Sprintf("'%v'", val.Value)
switch {
case strings.HasPrefix(val.Value, "~"):
val.Value = fmt.Sprintf(`~"%v"`, escaper.Replace(val.Value[1:]))
default:
val.Value = fmt.Sprintf(`"%v"`, escaper.Replace(val.Value))
}
}

if !meta.Nospace.Matches(val.Value) {
Expand Down
19 changes: 19 additions & 0 deletions internal/shell/nushell/patch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package nushell

import (
"strings"

"github.com/rsteube/carapace/internal/lexer"
)

// Patch uses the lexer to parse and patch given arguments.
func Patch(args []string) []string {
for index, arg := range args {
if strings.HasPrefix(arg, `"`) || strings.HasPrefix(arg, "'") {
if tokenset, err := lexer.Split(arg, false); err == nil {
args[index] = tokenset.Tokens[0]
}
}
}
return args
}

0 comments on commit 0be7a8a

Please sign in to comment.