Skip to content

Commit

Permalink
Add prompt type: menuFromCommand
Browse files Browse the repository at this point in the history
  • Loading branch information
FoamScience committed Jul 18, 2021
1 parent 1573a44 commit d18c8c8
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
4 changes: 4 additions & 0 deletions pkg/config/user_config.go
Expand Up @@ -280,6 +280,10 @@ type CustomCommandPrompt struct {

// this only applies to menus
Options []CustomCommandMenuOption

// this only applies to menuFromCommand
Command string `yaml:"command"`
Filter string `yaml:"filter"`
}

type CustomCommandMenuOption struct {
Expand Down
59 changes: 58 additions & 1 deletion pkg/gui/custom_commands.go
@@ -1,8 +1,10 @@
package gui

import (
"fmt"
"log"
"strings"
"regexp"

"github.com/fatih/color"
"github.com/jesseduffield/gocui"
Expand Down Expand Up @@ -151,10 +153,65 @@ func (gui *Gui) handleCustomCommandKeybinding(customCommand config.CustomCommand
return gui.surfaceError(err)
}

return gui.createMenu(title, menuItems, createMenuOptions{showCancel: true})
}
case "menuFromCommand":
f = func() error {
// Collect cmd to run from config
cmdStr, err := gui.resolveTemplate(prompt.Command, promptResponses)
if err != nil {
return gui.surfaceError(err)
}

// Collect Filter regexp
filter, err := gui.resolveTemplate(prompt.Filter, promptResponses)
if err != nil {
return gui.surfaceError(err)
}

// Run and save output
message,err := gui.GitCommand.RunCommandWithOutput(cmdStr)
if err != nil {
return gui.surfaceError(err)
}

// Need to make a menu out of what the cmd has displayed
var candidates []string
reg := regexp.MustCompile(filter)
for _,str := range strings.Split(string(message), "\n"){
cand := str
if str != "" {
for i := 1; i < (reg.NumSubexp()+1); i++ {
trim := reg.ReplaceAllString(str, "${"+fmt.Sprint(i)+"}")
cand = strings.Trim(cand, trim)
}
candidates = append(candidates, cand)
}
}

menuItems := make([]*menuItem, len(candidates))
for i, option := range candidates {
option := option

menuItems[i] = &menuItem{
displayStrings: []string{option},
onPress: func() error {
promptResponses[idx] = option

return wrappedF()
},
}
}

title, err := gui.resolveTemplate(prompt.Title, promptResponses)
if err != nil {
return gui.surfaceError(err)
}

return gui.createMenu(title, menuItems, createMenuOptions{showCancel: true})
}
default:
return gui.createErrorPanel("custom command prompt must have a type of 'input' or 'menu'")
return gui.createErrorPanel("custom command prompt must have a type of 'input', 'menu' or 'menuFromCommand'")
}

}
Expand Down

0 comments on commit d18c8c8

Please sign in to comment.