Skip to content

Commit

Permalink
Merge pull request #22 from rsteube/custom-macros
Browse files Browse the repository at this point in the history
custom macros
  • Loading branch information
rsteube authored May 3, 2022
2 parents 89d593a + b865e23 commit fc93c4a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
9 changes: 9 additions & 0 deletions macro.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package spec

import "github.com/rsteube/carapace"

var macros = make(map[string]func(string) carapace.Action)

func AddMacro(s string, f func(string) carapace.Action) {
macros[s] = f
}
19 changes: 13 additions & 6 deletions spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (f flag) addTo(flagSet *pflag.FlagSet) {

func parseAction(cmd *cobra.Command, arr []string) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
rMacro := regexp.MustCompile(`^(?P<macro>\$[^(]*)(\((?P<arg>.*)\))?$`)
rMacro := regexp.MustCompile(`^\$(?P<macro>[^(]*)(\((?P<arg>.*)\))?$`)
listDelimiter := ""
nospace := false

Expand All @@ -166,19 +166,26 @@ func parseAction(cmd *cobra.Command, arr []string) carapace.Action {
macro := match["macro"]
arg := match["arg"]

if strings.HasPrefix(macro, "_") { // custom macro
if f := macros[strings.TrimPrefix(macro, "_")]; f != nil {
return f(arg)
}
return carapace.ActionMessage(fmt.Sprintf("unknown custom macro: '%v'", elem))
}

switch macro {
case "$nospace":
case "nospace":
nospace = true
case "$list":
case "list":
listDelimiter = arg
case "$directories":
case "directories":
return carapace.ActionDirectories()
case "$files":
case "files":
if arg != "" {
batch = append(batch, carapace.ActionFiles(strings.Fields(arg)...))
}
batch = append(batch, carapace.ActionFiles())
case "$":
case "":
batch = append(batch, carapace.ActionCallback(func(c carapace.Context) carapace.Action {
for index, arg := range c.Args {
c.Setenv(fmt.Sprintf("CARAPACE_ARG%v", index), arg)
Expand Down

0 comments on commit fc93c4a

Please sign in to comment.