Skip to content

Commit

Permalink
Merge pull request #54 from rsteube/add-join
Browse files Browse the repository at this point in the history
added join
  • Loading branch information
rsteube authored Jan 13, 2024
2 parents 9b4e649 + 4401df6 commit e7a0608
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
29 changes: 22 additions & 7 deletions cmd/carapace-shlex/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

var rootCmd = &cobra.Command{
Use: "carapace-spec",
Use: "carapace-shlex",
Long: "simple shell lexer",
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
Expand All @@ -32,15 +32,24 @@ var rootCmd = &cobra.Command{
if cmd.Flag("words").Changed {
tokens = tokens.Words()
}
if cmd.Flag("prefix").Changed {

switch {
case cmd.Flag("prefix").Changed:
fmt.Fprintln(cmd.OutOrStdout(), tokens.WordbreakPrefix())
return nil
case cmd.Flag("join").Changed:
words := make([]string, 0)
for _, word := range tokens.Words() {
words = append(words, word.Value)
}
fmt.Fprintln(cmd.OutOrStdout(), shlex.Join(words))
return nil
default:
encoder := json.NewEncoder(cmd.OutOrStdout())
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
return encoder.Encode(tokens)
}

encoder := json.NewEncoder(cmd.OutOrStdout())
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
return encoder.Encode(tokens)
},
}

Expand All @@ -53,6 +62,12 @@ func init() {
rootCmd.Flags().Bool("current", false, "show current pipeline")
rootCmd.Flags().Bool("prefix", false, "show wordbreak prefix")
rootCmd.Flags().Bool("words", false, "show words")
rootCmd.Flags().Bool("join", false, "re-join words")

rootCmd.MarkFlagsMutuallyExclusive(
"join",
"prefix",
)

carapace.Gen(rootCmd).PositionalCompletion(
bridge.ActionCarapaceBin().SplitP(),
Expand Down
22 changes: 22 additions & 0 deletions shlex.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,25 @@ func Split(s string) (TokenSlice, error) {
tokens = append(tokens, *token)
}
}

// Join concatenates words to create a single string.
// It quotes and escapes where appropriate.
// TODO experimental
func Join(s []string) string {
replacer := strings.NewReplacer(
"$", "\\$",
"`", "\\`",
)

formatted := make([]string, 0, len(s))
for _, arg := range s {
switch {
case arg == "",
strings.ContainsAny(arg, `"' `+"\n\r\t"):
formatted = append(formatted, replacer.Replace(fmt.Sprintf("%#v", arg)))
default:
formatted = append(formatted, arg)
}
}
return strings.Join(formatted, " ")
}

0 comments on commit e7a0608

Please sign in to comment.