1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-02 09:21:40 +02:00

support prompts in custom commands

This commit is contained in:
Jesse Duffield 2020-09-26 19:48:13 +10:00
parent 266d8bf0d5
commit b5066f1d8e

View File

@ -21,10 +21,10 @@ type CustomCommandObjects struct {
SelectedStashEntry *commands.StashEntry
SelectedCommitFile *commands.CommitFile
CheckedOutBranch *commands.Branch
PromptResponses []string
}
func (gui *Gui) handleCustomCommandKeybinding(customCommand CustomCommand) func() error {
return func() error {
func (gui *Gui) resolveTemplate(templateStr string, promptResponses []string) (string, error) {
objects := CustomCommandObjects{
SelectedFile: gui.getSelectedFile(),
SelectedLocalCommit: gui.getSelectedLocalCommit(),
@ -37,20 +37,34 @@ func (gui *Gui) handleCustomCommandKeybinding(customCommand CustomCommand) func(
SelectedCommitFile: gui.getSelectedCommitFile(),
SelectedSubCommit: gui.getSelectedSubCommit(),
CheckedOutBranch: gui.currentBranch(),
PromptResponses: promptResponses,
}
tmpl, err := template.New("custom command template").Parse(customCommand.Command)
tmpl, err := template.New("template").Parse(templateStr)
if err != nil {
return gui.surfaceError(err)
return "", err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, objects); err != nil {
return gui.surfaceError(err)
return "", err
}
cmdStr := buf.String()
return cmdStr, nil
}
func (gui *Gui) handleCustomCommandKeybinding(customCommand CustomCommand) func() error {
return func() error {
promptResponses := make([]string, len(customCommand.Prompts))
f := func() error {
cmdStr, err := gui.resolveTemplate(customCommand.Command, promptResponses)
if err != nil {
return gui.surfaceError(err)
}
if customCommand.Subprocess {
gui.PrepareSubProcess(cmdStr)
return nil
@ -65,6 +79,38 @@ func (gui *Gui) handleCustomCommandKeybinding(customCommand CustomCommand) func(
return gui.refreshSidePanels(refreshOptions{})
})
}
// if we have prompts we'll recursively wrap our confirm handlers with more prompts
// until we reach the actual command
for reverseIdx := range customCommand.Prompts {
idx := len(customCommand.Prompts) - 1 - reverseIdx
// going backwards so the outermost prompt is the first one
prompt := customCommand.Prompts[idx]
gui.Log.Warn(prompt.Title)
wrappedF := f // need to do this because f's value will change with each iteration
f = func() error {
return gui.prompt(
prompt.Title,
prompt.InitialValue,
func(str string) error {
promptResponses[idx] = str
return wrappedF()
},
)
}
}
return f()
}
}
type CustomCommandPrompt struct {
Title string `yaml:"title"`
InitialValue string `yaml:"initialValue"`
}
type CustomCommand struct {
@ -72,6 +118,7 @@ type CustomCommand struct {
Context string `yaml:"context"`
Command string `yaml:"command"`
Subprocess bool `yaml:"subprocess"`
Prompts []CustomCommandPrompt `yaml:"prompts"`
}
func (gui *Gui) GetCustomCommandKeybindings() []*Binding {