From da3b0bf7c8aa6202d5eb9c8178f6648bc695336a Mon Sep 17 00:00:00 2001 From: Jesse Duffield Date: Sat, 28 Nov 2020 13:14:48 +1100 Subject: [PATCH] Start on supporting auto-suggestions when checking out a branch switch to other fuzzy package with no dependencies --- go.mod | 2 + go.sum | 4 + pkg/gui/branches_panel.go | 7 +- pkg/gui/commit_files_panel.go | 6 +- pkg/gui/commit_message_panel.go | 40 --- pkg/gui/confirmation_panel.go | 104 ++++++-- pkg/gui/context.go | 32 ++- pkg/gui/credentials_panel.go | 2 +- pkg/gui/editors.go | 93 +++++++ pkg/gui/files_panel.go | 6 +- pkg/gui/gui.go | 8 + pkg/gui/layout.go | 4 +- pkg/gui/list_context.go | 20 +- pkg/gui/menu_panel.go | 2 +- pkg/gui/merge_panel.go | 6 +- pkg/gui/patch_building_panel.go | 2 +- pkg/gui/patch_options_panel.go | 2 +- pkg/gui/presentation/suggestions.go | 15 ++ pkg/gui/quitting.go | 2 +- pkg/gui/rebase_options_panel.go | 2 +- pkg/gui/remote_branches_panel.go | 2 +- pkg/gui/remotes_panel.go | 2 +- pkg/gui/reset_menu_panel.go | 2 +- pkg/gui/searching.go | 2 +- pkg/gui/side_window.go | 6 +- pkg/gui/staging_panel.go | 6 +- pkg/gui/status_panel.go | 2 +- pkg/gui/sub_commits_panel.go | 2 +- pkg/gui/suggestions_panel.go | 22 ++ pkg/gui/tags_panel.go | 2 +- pkg/gui/view_helpers.go | 7 +- pkg/utils/fuzzy_search.go | 28 +++ pkg/utils/fuzzy_search_test.go | 53 ++++ vendor/github.com/sahilm/fuzzy/.gitignore | 2 + .../github.com/sahilm/fuzzy/CONTRIBUTING.md | 1 + vendor/github.com/sahilm/fuzzy/Gopkg.lock | 20 ++ vendor/github.com/sahilm/fuzzy/Gopkg.toml | 4 + vendor/github.com/sahilm/fuzzy/LICENSE | 21 ++ vendor/github.com/sahilm/fuzzy/Makefile | 57 +++++ vendor/github.com/sahilm/fuzzy/README.md | 184 ++++++++++++++ vendor/github.com/sahilm/fuzzy/fuzzy.go | 235 ++++++++++++++++++ vendor/modules.txt | 5 + 42 files changed, 919 insertions(+), 105 deletions(-) create mode 100644 pkg/gui/editors.go create mode 100644 pkg/gui/presentation/suggestions.go create mode 100644 pkg/gui/suggestions_panel.go create mode 100644 pkg/utils/fuzzy_search.go create mode 100644 pkg/utils/fuzzy_search_test.go create mode 100644 vendor/github.com/sahilm/fuzzy/.gitignore create mode 100644 vendor/github.com/sahilm/fuzzy/CONTRIBUTING.md create mode 100644 vendor/github.com/sahilm/fuzzy/Gopkg.lock create mode 100644 vendor/github.com/sahilm/fuzzy/Gopkg.toml create mode 100644 vendor/github.com/sahilm/fuzzy/LICENSE create mode 100644 vendor/github.com/sahilm/fuzzy/Makefile create mode 100644 vendor/github.com/sahilm/fuzzy/README.md create mode 100644 vendor/github.com/sahilm/fuzzy/fuzzy.go diff --git a/go.mod b/go.mod index 633bcb6ed..23babf27e 100644 --- a/go.mod +++ b/go.mod @@ -23,11 +23,13 @@ require ( github.com/jesseduffield/yaml v2.1.0+incompatible github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/mattn/go-colorable v0.1.7 // indirect github.com/mattn/go-runewidth v0.0.9 github.com/mgutz/str v1.2.0 github.com/onsi/ginkgo v1.10.3 // indirect github.com/onsi/gomega v1.7.1 // indirect + github.com/sahilm/fuzzy v0.1.0 github.com/sirupsen/logrus v1.4.2 github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad github.com/stretchr/testify v1.4.0 diff --git a/go.sum b/go.sum index 63d20d766..01eb8e3fa 100644 --- a/go.sum +++ b/go.sum @@ -86,6 +86,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= @@ -114,6 +116,8 @@ github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI= +github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= diff --git a/pkg/gui/branches_panel.go b/pkg/gui/branches_panel.go index 48e322025..523ecd0c2 100644 --- a/pkg/gui/branches_panel.go +++ b/pkg/gui/branches_panel.go @@ -212,7 +212,6 @@ func (gui *Gui) handleCheckoutByName(g *gocui.Gui, v *gocui.View) error { onRefNotFound: func(ref string) error { return gui.ask(askOpts{ - title: gui.Tr.BranchNotFoundTitle, prompt: fmt.Sprintf("%s %s%s", gui.Tr.BranchNotFoundPrompt, ref, "?"), handleConfirm: func() error { @@ -278,7 +277,6 @@ func (gui *Gui) deleteNamedBranch(selectedBranch *models.Branch, force bool) err ) return gui.ask(askOpts{ - title: title, prompt: message, handleConfirm: func() error { @@ -315,7 +313,6 @@ func (gui *Gui) mergeBranchIntoCheckedOutBranch(branchName string) error { ) return gui.ask(askOpts{ - title: gui.Tr.MergingTitle, prompt: prompt, handleConfirm: func() error { @@ -357,7 +354,6 @@ func (gui *Gui) handleRebaseOntoBranch(selectedBranchName string) error { ) return gui.ask(askOpts{ - title: gui.Tr.RebasingTitle, prompt: prompt, handleConfirm: func() error { @@ -454,7 +450,6 @@ func (gui *Gui) handleRenameBranch(g *gocui.Gui, v *gocui.View) error { } return gui.ask(askOpts{ - title: gui.Tr.LcRenameBranch, prompt: gui.Tr.RenameBranchWarning, handleConfirm: promptForNewName, @@ -500,7 +495,7 @@ func (gui *Gui) handleNewBranchOffCurrentItem() error { } if context.GetKey() != gui.Contexts.Branches.Context.GetKey() { - if err := gui.switchContext(gui.Contexts.Branches.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Branches.Context); err != nil { return err } } diff --git a/pkg/gui/commit_files_panel.go b/pkg/gui/commit_files_panel.go index c560e667b..98a8d98a9 100644 --- a/pkg/gui/commit_files_panel.go +++ b/pkg/gui/commit_files_panel.go @@ -176,7 +176,7 @@ func (gui *Gui) enterCommitFile(selectedLineIdx int) error { } } - if err := gui.switchContext(gui.Contexts.PatchBuilding.Context); err != nil { + if err := gui.pushContext(gui.Contexts.PatchBuilding.Context); err != nil { return err } return gui.handleRefreshPatchBuildingPanel(selectedLineIdx) @@ -192,7 +192,7 @@ func (gui *Gui) enterCommitFile(selectedLineIdx int) error { return enterTheFile(selectedLineIdx) }, handleClose: func() error { - return gui.switchContext(gui.Contexts.CommitFiles.Context) + return gui.pushContext(gui.Contexts.CommitFiles.Context) }, }) } @@ -215,5 +215,5 @@ func (gui *Gui) switchToCommitFilesContext(refName string, canRebase bool, conte return err } - return gui.switchContext(gui.Contexts.CommitFiles.Context) + return gui.pushContext(gui.Contexts.CommitFiles.Context) } diff --git a/pkg/gui/commit_message_panel.go b/pkg/gui/commit_message_panel.go index 333882467..1cdd51770 100644 --- a/pkg/gui/commit_message_panel.go +++ b/pkg/gui/commit_message_panel.go @@ -79,43 +79,3 @@ func (gui *Gui) RenderCommitLength() { v := gui.getCommitMessageView() v.Subtitle = gui.getBufferLength(v) } - -// we've just copy+pasted the editor from gocui to here so that we can also re- -// render the commit message length on each keypress -func (gui *Gui) commitMessageEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { - newlineKey, ok := gui.getKey(gui.Config.GetUserConfig().Keybinding.Universal.AppendNewline).(gocui.Key) - if !ok { - newlineKey = gocui.KeyTab - } - - switch { - case key == gocui.KeyBackspace || key == gocui.KeyBackspace2: - v.EditDelete(true) - case key == gocui.KeyDelete: - v.EditDelete(false) - case key == gocui.KeyArrowDown: - v.MoveCursor(0, 1, false) - case key == gocui.KeyArrowUp: - v.MoveCursor(0, -1, false) - case key == gocui.KeyArrowLeft: - v.MoveCursor(-1, 0, false) - case key == gocui.KeyArrowRight: - v.MoveCursor(1, 0, false) - case key == newlineKey: - v.EditNewLine() - case key == gocui.KeySpace: - v.EditWrite(' ') - case key == gocui.KeyInsert: - v.Overwrite = !v.Overwrite - case key == gocui.KeyCtrlU: - v.EditDeleteToStartOfLine() - case key == gocui.KeyCtrlA: - v.EditGotoToStartOfLine() - case key == gocui.KeyCtrlE: - v.EditGotoToEndOfLine() - default: - v.EditWrite(ch) - } - - gui.RenderCommitLength() -} diff --git a/pkg/gui/confirmation_panel.go b/pkg/gui/confirmation_panel.go index fbea691ad..dfea11c05 100644 --- a/pkg/gui/confirmation_panel.go +++ b/pkg/gui/confirmation_panel.go @@ -27,14 +27,17 @@ type createPopupPanelOpts struct { // when handlersManageFocus is true, do not return from the confirmation context automatically. It's expected that the handlers will manage focus, whether that means switching to another context, or manually returning the context. handlersManageFocus bool + + showSuggestionsPanel bool } type askOpts struct { - title string - prompt string - handleConfirm func() error - handleClose func() error - handlersManageFocus bool + title string + prompt string + handleConfirm func() error + handleClose func() error + handlersManageFocus bool + showSuggestionsPanel bool } func (gui *Gui) createLoaderPanel(prompt string) error { @@ -46,20 +49,22 @@ func (gui *Gui) createLoaderPanel(prompt string) error { func (gui *Gui) ask(opts askOpts) error { return gui.createPopupPanel(createPopupPanelOpts{ - title: opts.title, - prompt: opts.prompt, - handleConfirm: opts.handleConfirm, - handleClose: opts.handleClose, - handlersManageFocus: opts.handlersManageFocus, + title: opts.title, + prompt: opts.prompt, + handleConfirm: opts.handleConfirm, + handleClose: opts.handleClose, + handlersManageFocus: opts.handlersManageFocus, + showSuggestionsPanel: opts.showSuggestionsPanel, }) } func (gui *Gui) prompt(title string, initialContent string, handleConfirm func(string) error) error { return gui.createPopupPanel(createPopupPanelOpts{ - title: title, - prompt: initialContent, - editable: true, - handleConfirmPrompt: handleConfirm, + title: title, + prompt: initialContent, + editable: true, + handleConfirmPrompt: handleConfirm, + showSuggestionsPanel: true, }) } @@ -79,10 +84,10 @@ func (gui *Gui) wrappedConfirmationFunction(handlersManageFocus bool, function f } } -func (gui *Gui) wrappedPromptConfirmationFunction(handlersManageFocus bool, function func(string) error) func(*gocui.Gui, *gocui.View) error { - return func(g *gocui.Gui, v *gocui.View) error { +func (gui *Gui) wrappedPromptConfirmationFunction(handlersManageFocus bool, function func(string) error, getResponse func() string) func(*gocui.Gui, *gocui.View) error { + return gui.wrappedHandler(func() error { if function != nil { - if err := function(v.Buffer()); err != nil { + if err := function(getResponse()); err != nil { return gui.surfaceError(err) } } @@ -92,7 +97,7 @@ func (gui *Gui) wrappedPromptConfirmationFunction(handlersManageFocus bool, func } return nil - } + }) } func (gui *Gui) deleteConfirmationView() { @@ -104,6 +109,15 @@ func (gui *Gui) deleteConfirmationView() { _ = gui.g.DeleteView("confirmation") } +func (gui *Gui) deleteSuggestionsView() { + keybindingConfig := gui.Config.GetUserConfig().Keybinding + _ = gui.g.DeleteKeybinding("suggestions", gui.getKey(keybindingConfig.Universal.Confirm), gocui.ModNone) + _ = gui.g.DeleteKeybinding("suggestions", gui.getKey(keybindingConfig.Universal.ConfirmAlt1), gocui.ModNone) + _ = gui.g.DeleteKeybinding("suggestions", gui.getKey(keybindingConfig.Universal.Return), gocui.ModNone) + + _ = gui.g.DeleteView("suggestions") +} + func (gui *Gui) closeConfirmationPrompt(handlersManageFocus bool) error { view := gui.getConfirmationView() if view == nil { @@ -117,6 +131,9 @@ func (gui *Gui) closeConfirmationPrompt(handlersManageFocus bool) error { } gui.deleteConfirmationView() + + _, _ = gui.g.SetViewOnBottom("suggestions") + return nil } @@ -156,7 +173,7 @@ func (gui *Gui) getConfirmationPanelDimensions(wrap bool, prompt string) (int, i height/2 + panelHeight/2 } -func (gui *Gui) prepareConfirmationPanel(title, prompt string, hasLoader bool) (*gocui.View, error) { +func (gui *Gui) prepareConfirmationPanel(title, prompt string, hasLoader bool, showSuggestionsPanel bool) (*gocui.View, error) { x0, y0, x1, y1 := gui.getConfirmationPanelDimensions(true, prompt) confirmationView, err := gui.g.SetView("confirmation", x0, y0, x1, y1, 0) if err != nil { @@ -171,8 +188,23 @@ func (gui *Gui) prepareConfirmationPanel(title, prompt string, hasLoader bool) ( confirmationView.Wrap = true confirmationView.FgColor = theme.GocuiDefaultTextColor } + + if showSuggestionsPanel { + suggestionsViewHeight := 11 + suggestionsView, err := gui.g.SetView("suggestions", x0, y1, x1, y1+suggestionsViewHeight, 0) + if err != nil { + if err.Error() != UNKNOWN_VIEW_ERROR_MSG { + return nil, err + } + suggestionsView.Wrap = true + suggestionsView.FgColor = theme.GocuiDefaultTextColor + } + gui.setSuggestions([]string{}) + _, _ = gui.g.SetViewOnTop("suggestions") + } + gui.g.Update(func(g *gocui.Gui) error { - return gui.switchContext(gui.Contexts.Confirmation.Context) + return gui.pushContext(gui.Contexts.Confirmation.Context) }) return confirmationView, nil } @@ -183,11 +215,12 @@ func (gui *Gui) createPopupPanel(opts createPopupPanelOpts) error { if view, _ := g.View("confirmation"); view != nil { gui.deleteConfirmationView() } - confirmationView, err := gui.prepareConfirmationPanel(opts.title, opts.prompt, opts.hasLoader) + confirmationView, err := gui.prepareConfirmationPanel(opts.title, opts.prompt, opts.hasLoader, opts.showSuggestionsPanel) if err != nil { return err } confirmationView.Editable = opts.editable + confirmationView.Editor = gocui.EditorFunc(gui.editorWithCallback) if opts.editable { go utils.Safe(func() { // TODO: remove this wait (right now if you remove it the EditGotoToEndOfLine method doesn't seem to work) @@ -200,6 +233,7 @@ func (gui *Gui) createPopupPanel(opts createPopupPanelOpts) error { } gui.renderString("confirmation", opts.prompt) + return gui.setKeyBindings(opts) }) return nil @@ -217,7 +251,7 @@ func (gui *Gui) setKeyBindings(opts createPopupPanelOpts) error { gui.renderString("options", actions) var onConfirm func(*gocui.Gui, *gocui.View) error if opts.handleConfirmPrompt != nil { - onConfirm = gui.wrappedPromptConfirmationFunction(opts.handlersManageFocus, opts.handleConfirmPrompt) + onConfirm = gui.wrappedPromptConfirmationFunction(opts.handlersManageFocus, opts.handleConfirmPrompt, func() string { return gui.getConfirmationView().Buffer() }) } else { onConfirm = gui.wrappedConfirmationFunction(opts.handlersManageFocus, opts.handleConfirm) } @@ -230,7 +264,31 @@ func (gui *Gui) setKeyBindings(opts createPopupPanelOpts) error { return err } - return gui.g.SetKeybinding("confirmation", nil, gui.getKey(keybindingConfig.Universal.Return), gocui.ModNone, gui.wrappedConfirmationFunction(opts.handlersManageFocus, opts.handleClose)) + if err := gui.g.SetKeybinding("confirmation", nil, gui.getKey(keybindingConfig.Universal.Return), gocui.ModNone, gui.wrappedConfirmationFunction(opts.handlersManageFocus, opts.handleClose)); err != nil { + return err + } + + if err := gui.g.SetKeybinding("confirmation", nil, gui.getKey(keybindingConfig.Universal.TogglePanel), gocui.ModNone, gui.wrappedHandler(func() error { return gui.replaceContext(gui.Contexts.Suggestions.Context) })); err != nil { + return err + } + + onSuggestionConfirm := gui.wrappedPromptConfirmationFunction(opts.handlersManageFocus, opts.handleConfirmPrompt, func() string { return gui.getSelectedSuggestion() }) + if err := gui.g.SetKeybinding("suggestions", nil, gui.getKey(keybindingConfig.Universal.Confirm), gocui.ModNone, onSuggestionConfirm); err != nil { + return err + } + if err := gui.g.SetKeybinding("suggestions", nil, gui.getKey(keybindingConfig.Universal.ConfirmAlt1), gocui.ModNone, onSuggestionConfirm); err != nil { + return err + } + + if err := gui.g.SetKeybinding("suggestions", nil, gui.getKey(keybindingConfig.Universal.Return), gocui.ModNone, gui.wrappedConfirmationFunction(opts.handlersManageFocus, opts.handleClose)); err != nil { + return err + } + + if err := gui.g.SetKeybinding("suggestions", nil, gui.getKey(keybindingConfig.Universal.TogglePanel), gocui.ModNone, gui.wrappedHandler(func() error { return gui.replaceContext(gui.Contexts.Confirmation.Context) })); err != nil { + return err + } + + return nil } func (gui *Gui) createErrorPanel(message string) error { diff --git a/pkg/gui/context.go b/pkg/gui/context.go index 3784bb1d5..c28fc9efc 100644 --- a/pkg/gui/context.go +++ b/pkg/gui/context.go @@ -35,6 +35,7 @@ const ( SEARCH_CONTEXT_KEY = "search" COMMIT_MESSAGE_CONTEXT_KEY = "commitMessage" SUBMODULES_CONTEXT_KEY = "submodules" + SUGGESTIONS_CONTEXT_KEY = "suggestions" ) var allContextKeys = []string{ @@ -59,6 +60,7 @@ var allContextKeys = []string{ SEARCH_CONTEXT_KEY, COMMIT_MESSAGE_CONTEXT_KEY, SUBMODULES_CONTEXT_KEY, + SUGGESTIONS_CONTEXT_KEY, } type SimpleContextNode struct { @@ -91,6 +93,7 @@ type ContextTree struct { Confirmation SimpleContextNode CommitMessage SimpleContextNode Search SimpleContextNode + Suggestions SimpleContextNode } func (gui *Gui) allContexts() []Context { @@ -115,6 +118,7 @@ func (gui *Gui) allContexts() []Context { gui.Contexts.Merging.Context, gui.Contexts.PatchBuilding.Context, gui.Contexts.SubCommits.Context, + gui.Contexts.Suggestions.Context, } } @@ -303,6 +307,9 @@ func (gui *Gui) contextTree() ContextTree { Key: CONFIRMATION_CONTEXT_KEY, }, }, + Suggestions: SimpleContextNode{ + Context: gui.suggestionsListContext(), + }, CommitMessage: SimpleContextNode{ Context: BasicContext{ OnFocus: gui.handleCommitMessageFocused, @@ -400,7 +407,24 @@ func (gui *Gui) currentContextKeyIgnoringPopups() string { return "" } -func (gui *Gui) switchContext(c Context) error { +// use replaceContext when you don't want to return to the original context upon +// hitting escape: you want to go that context's parent instead. +func (gui *Gui) replaceContext(c Context) error { + gui.g.Update(func(*gocui.Gui) error { + if len(gui.State.ContextStack) == 0 { + gui.State.ContextStack = []Context{c} + } else { + // replace the last item with the given item + gui.State.ContextStack = append(gui.State.ContextStack[0:len(gui.State.ContextStack)-1], c) + } + + return gui.activateContext(c) + }) + + return nil +} + +func (gui *Gui) pushContext(c Context) error { gui.g.Update(func(*gocui.Gui) error { // push onto stack // if we are switching to a side context, remove all other contexts in the stack @@ -424,11 +448,11 @@ func (gui *Gui) switchContext(c Context) error { return nil } -// switchContextToView is to be used when you don't know which context you +// pushContextWithView is to be used when you don't know which context you // want to switch to: you only know the view that you want to switch to. It will // look up the context currently active for that view and switch to that context -func (gui *Gui) switchContextToView(viewName string) error { - return gui.switchContext(gui.State.ViewContextMap[viewName]) +func (gui *Gui) pushContextWithView(viewName string) error { + return gui.pushContext(gui.State.ViewContextMap[viewName]) } func (gui *Gui) returnFromContext() error { diff --git a/pkg/gui/credentials_panel.go b/pkg/gui/credentials_panel.go index 53166aa76..fe97dc9aa 100644 --- a/pkg/gui/credentials_panel.go +++ b/pkg/gui/credentials_panel.go @@ -26,7 +26,7 @@ func (gui *Gui) promptUserForCredential(passOrUname string) string { credentialsView.Mask = '*' } - if err := gui.switchContext(gui.Contexts.Credentials.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Credentials.Context); err != nil { return err } diff --git a/pkg/gui/editors.go b/pkg/gui/editors.go new file mode 100644 index 000000000..baffd19a3 --- /dev/null +++ b/pkg/gui/editors.go @@ -0,0 +1,93 @@ +package gui + +import ( + "github.com/jesseduffield/gocui" + "github.com/jesseduffield/lazygit/pkg/utils" +) + +// we've just copy+pasted the editor from gocui to here so that we can also re- +// render the commit message length on each keypress +func (gui *Gui) commitMessageEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { + newlineKey, ok := gui.getKey(gui.Config.GetUserConfig().Keybinding.Universal.AppendNewline).(gocui.Key) + if !ok { + newlineKey = gocui.KeyTab + } + + switch { + case key == gocui.KeyBackspace || key == gocui.KeyBackspace2: + v.EditDelete(true) + case key == gocui.KeyDelete: + v.EditDelete(false) + case key == gocui.KeyArrowDown: + v.MoveCursor(0, 1, false) + case key == gocui.KeyArrowUp: + v.MoveCursor(0, -1, false) + case key == gocui.KeyArrowLeft: + v.MoveCursor(-1, 0, false) + case key == gocui.KeyArrowRight: + v.MoveCursor(1, 0, false) + case key == newlineKey: + v.EditNewLine() + case key == gocui.KeySpace: + v.EditWrite(' ') + case key == gocui.KeyInsert: + v.Overwrite = !v.Overwrite + case key == gocui.KeyCtrlU: + v.EditDeleteToStartOfLine() + case key == gocui.KeyCtrlA: + v.EditGotoToStartOfLine() + case key == gocui.KeyCtrlE: + v.EditGotoToEndOfLine() + default: + v.EditWrite(ch) + } + + gui.RenderCommitLength() +} + +// we've just copy+pasted the editor from gocui to here so that we can also re- +// render the commit message length on each keypress +func (gui *Gui) editorWithCallback(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { + switch { + case key == gocui.KeyBackspace || key == gocui.KeyBackspace2: + v.EditDelete(true) + case key == gocui.KeyDelete: + v.EditDelete(false) + case key == gocui.KeyArrowDown: + v.MoveCursor(0, 1, false) + case key == gocui.KeyArrowUp: + v.MoveCursor(0, -1, false) + case key == gocui.KeyArrowLeft: + v.MoveCursor(-1, 0, false) + case key == gocui.KeyArrowRight: + v.MoveCursor(1, 0, false) + case key == gocui.KeySpace: + v.EditWrite(' ') + case key == gocui.KeyInsert: + v.Overwrite = !v.Overwrite + case key == gocui.KeyCtrlU: + v.EditDeleteToStartOfLine() + case key == gocui.KeyCtrlA: + v.EditGotoToStartOfLine() + case key == gocui.KeyCtrlE: + v.EditGotoToEndOfLine() + default: + v.EditWrite(ch) + } + + input := v.Buffer() + branchNames := gui.getBranchNames() + + suggestions := utils.FuzzySearch(input, branchNames) + gui.setSuggestions(suggestions) +} + +func (gui *Gui) getBranchNames() []string { + result := make([]string, len(gui.State.Branches)) + + for i, branch := range gui.State.Branches { + result[i] = branch.Name + } + + return result +} diff --git a/pkg/gui/files_panel.go b/pkg/gui/files_panel.go index 1d17b7771..665a403cf 100644 --- a/pkg/gui/files_panel.go +++ b/pkg/gui/files_panel.go @@ -183,7 +183,7 @@ func (gui *Gui) enterFile(forceSecondaryFocused bool, selectedLineIdx int) error if file.HasMergeConflicts { return gui.createErrorPanel(gui.Tr.FileStagingRequirements) } - _ = gui.switchContext(gui.Contexts.Staging.Context) + _ = gui.pushContext(gui.Contexts.Staging.Context) return gui.handleRefreshStagingPanel(forceSecondaryFocused, selectedLineIdx) // TODO: check if this is broken, try moving into context code } @@ -341,7 +341,7 @@ func (gui *Gui) handleCommitPress() error { } gui.g.Update(func(g *gocui.Gui) error { - if err := gui.switchContext(gui.Contexts.CommitMessage.Context); err != nil { + if err := gui.pushContext(gui.Contexts.CommitMessage.Context); err != nil { return err } @@ -642,7 +642,7 @@ func (gui *Gui) handleSwitchToMerge() error { return gui.createErrorPanel(gui.Tr.FileNoMergeCons) } - return gui.switchContext(gui.Contexts.Merging.Context) + return gui.pushContext(gui.Contexts.Merging.Context) } func (gui *Gui) openFile(filename string) error { diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index a1dbd909c..a90770ca9 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -220,6 +220,10 @@ type submodulePanelState struct { listPanelState } +type suggestionsPanelState struct { + listPanelState +} + type panelStates struct { Files *filePanelState Branches *branchPanelState @@ -235,6 +239,7 @@ type panelStates struct { Merging *mergingPanelState CommitFiles *commitFilesPanelState Submodules *submodulePanelState + Suggestions *suggestionsPanelState } type searchingState struct { @@ -299,6 +304,8 @@ type guiState struct { Commits []*models.Commit StashEntries []*models.StashEntry CommitFiles []*models.CommitFile + // Suggestions will sometimes appear when typing into a prompt + Suggestions []string // FilteredReflogCommits are the ones that appear in the reflog panel. // when in filtering mode we only include the ones that match the given path FilteredReflogCommits []*models.Commit @@ -385,6 +392,7 @@ func (gui *Gui) resetState() { CommitFiles: &commitFilesPanelState{listPanelState: listPanelState{SelectedLineIdx: -1}, refName: ""}, Stash: &stashPanelState{listPanelState{SelectedLineIdx: -1}}, Menu: &menuPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}, OnPress: nil}, + Suggestions: &suggestionsPanelState{listPanelState: listPanelState{SelectedLineIdx: 0}}, Merging: &mergingPanelState{ ConflictIndex: 0, ConflictTop: true, diff --git a/pkg/gui/layout.go b/pkg/gui/layout.go index 7f2a04315..2594cb9ad 100644 --- a/pkg/gui/layout.go +++ b/pkg/gui/layout.go @@ -277,7 +277,7 @@ func (gui *Gui) layout(g *gocui.Gui) error { initialContext = gui.Contexts.BranchCommits.Context } - if err := gui.switchContext(initialContext); err != nil { + if err := gui.pushContext(initialContext); err != nil { return err } } @@ -351,7 +351,7 @@ func (gui *Gui) onInitialViewsCreation() error { } gui.g.Mutexes.ViewsMutex.Unlock() - if err := gui.switchContext(gui.defaultSideContext()); err != nil { + if err := gui.pushContext(gui.defaultSideContext()); err != nil { return err } diff --git a/pkg/gui/list_context.go b/pkg/gui/list_context.go index 86271b065..908f35f7b 100644 --- a/pkg/gui/list_context.go +++ b/pkg/gui/list_context.go @@ -219,7 +219,7 @@ func (lc *ListContext) handleClick(g *gocui.Gui, v *gocui.View) error { newSelectedLineIdx := v.SelectedLineIdx() // we need to focus the view - if err := lc.Gui.switchContext(lc); err != nil { + if err := lc.Gui.pushContext(lc); err != nil { return err } @@ -483,6 +483,23 @@ func (gui *Gui) submodulesListContext() *ListContext { } } +func (gui *Gui) suggestionsListContext() *ListContext { + return &ListContext{ + ViewName: "suggestions", + WindowName: "suggestions", + ContextKey: SUGGESTIONS_CONTEXT_KEY, + GetItemsLength: func() int { return len(gui.State.Suggestions) }, + GetPanelState: func() IListPanelState { return gui.State.Panels.Suggestions }, + OnFocus: func() error { return nil }, + Gui: gui, + ResetMainViewOriginOnFocus: false, + Kind: PERSISTENT_POPUP, + GetDisplayStrings: func() [][]string { + return presentation.GetSuggestionListDisplayStrings(gui.State.Suggestions) + }, + } +} + func (gui *Gui) getListContexts() []*ListContext { return []*ListContext{ gui.menuListContext(), @@ -497,6 +514,7 @@ func (gui *Gui) getListContexts() []*ListContext { gui.stashListContext(), gui.commitFilesListContext(), gui.submodulesListContext(), + gui.suggestionsListContext(), } } diff --git a/pkg/gui/menu_panel.go b/pkg/gui/menu_panel.go index 791529ba3..e7839b0a0 100644 --- a/pkg/gui/menu_panel.go +++ b/pkg/gui/menu_panel.go @@ -88,7 +88,7 @@ func (gui *Gui) createMenu(title string, items []*menuItem, createMenuOptions cr gui.State.Panels.Menu.SelectedLineIdx = 0 gui.g.Update(func(g *gocui.Gui) error { - return gui.switchContext(gui.Contexts.Menu.Context) + return gui.pushContext(gui.Contexts.Menu.Context) }) return nil } diff --git a/pkg/gui/merge_panel.go b/pkg/gui/merge_panel.go index 85e7198e5..60ce4d560 100644 --- a/pkg/gui/merge_panel.go +++ b/pkg/gui/merge_panel.go @@ -309,7 +309,7 @@ func (gui *Gui) handleEscapeMerge() error { // it's possible this method won't be called from the merging view so we need to // ensure we only 'return' focus if we already have it if gui.g.CurrentView() == gui.getMainView() { - return gui.switchContext(gui.Contexts.Files.Context) + return gui.pushContext(gui.Contexts.Files.Context) } return nil } @@ -342,14 +342,14 @@ func (gui *Gui) promptToContinue() error { prompt: gui.Tr.ConflictsResolved, handlersManageFocus: true, handleConfirm: func() error { - if err := gui.switchContext(gui.Contexts.Files.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Files.Context); err != nil { return err } return gui.genericMergeCommand("continue") }, handleClose: func() error { - return gui.switchContext(gui.Contexts.Files.Context) + return gui.pushContext(gui.Contexts.Files.Context) }, }) } diff --git a/pkg/gui/patch_building_panel.go b/pkg/gui/patch_building_panel.go index 6ae41de6e..28926ddb4 100644 --- a/pkg/gui/patch_building_panel.go +++ b/pkg/gui/patch_building_panel.go @@ -110,7 +110,7 @@ func (gui *Gui) handleEscapePatchBuildingPanel() error { } if gui.currentContext().GetKey() == gui.Contexts.PatchBuilding.Context.GetKey() { - return gui.switchContext(gui.Contexts.CommitFiles.Context) + return gui.pushContext(gui.Contexts.CommitFiles.Context) } else { // need to re-focus in case the secondary view should now be hidden return gui.currentContext().HandleFocus() diff --git a/pkg/gui/patch_options_panel.go b/pkg/gui/patch_options_panel.go index 69cf67cc3..186b40c06 100644 --- a/pkg/gui/patch_options_panel.go +++ b/pkg/gui/patch_options_panel.go @@ -180,7 +180,7 @@ func (gui *Gui) handleApplyPatch(reverse bool) error { func (gui *Gui) handleResetPatch() error { gui.GitCommand.PatchManager.Reset() if gui.currentContextKeyIgnoringPopups() == MAIN_PATCH_BUILDING_CONTEXT_KEY { - if err := gui.switchContext(gui.Contexts.CommitFiles.Context); err != nil { + if err := gui.pushContext(gui.Contexts.CommitFiles.Context); err != nil { return err } } diff --git a/pkg/gui/presentation/suggestions.go b/pkg/gui/presentation/suggestions.go new file mode 100644 index 000000000..2e408e675 --- /dev/null +++ b/pkg/gui/presentation/suggestions.go @@ -0,0 +1,15 @@ +package presentation + +func GetSuggestionListDisplayStrings(suggestions []string) [][]string { + lines := make([][]string, len(suggestions)) + + for i := range suggestions { + lines[i] = getSuggestionDisplayStrings(suggestions[i]) + } + + return lines +} + +func getSuggestionDisplayStrings(suggestion string) []string { + return []string{suggestion} +} diff --git a/pkg/gui/quitting.go b/pkg/gui/quitting.go index 6bcd49da9..36c3e34a6 100644 --- a/pkg/gui/quitting.go +++ b/pkg/gui/quitting.go @@ -40,7 +40,7 @@ func (gui *Gui) handleTopLevelReturn(g *gocui.Gui, v *gocui.View) error { parentContext, hasParent := currentContext.GetParentContext() if hasParent && currentContext != nil && parentContext != nil { // TODO: think about whether this should be marked as a return rather than adding to the stack - return gui.switchContext(parentContext) + return gui.pushContext(parentContext) } for _, mode := range gui.modeStatuses() { diff --git a/pkg/gui/rebase_options_panel.go b/pkg/gui/rebase_options_panel.go index e53a78fb0..5ffd7b3bd 100644 --- a/pkg/gui/rebase_options_panel.go +++ b/pkg/gui/rebase_options_panel.go @@ -83,7 +83,7 @@ func (gui *Gui) handleGenericMergeCommandResult(result error) error { prompt: gui.Tr.FoundConflicts, handlersManageFocus: true, handleConfirm: func() error { - return gui.switchContext(gui.Contexts.Files.Context) + return gui.pushContext(gui.Contexts.Files.Context) }, handleClose: func() error { if err := gui.returnFromContext(); err != nil { diff --git a/pkg/gui/remote_branches_panel.go b/pkg/gui/remote_branches_panel.go index 582ed749d..68d5b50ff 100644 --- a/pkg/gui/remote_branches_panel.go +++ b/pkg/gui/remote_branches_panel.go @@ -40,7 +40,7 @@ func (gui *Gui) handleRemoteBranchSelect() error { } func (gui *Gui) handleRemoteBranchesEscape(g *gocui.Gui, v *gocui.View) error { - return gui.switchContext(gui.Contexts.Remotes.Context) + return gui.pushContext(gui.Contexts.Remotes.Context) } func (gui *Gui) handleMergeRemoteBranch(g *gocui.Gui, v *gocui.View) error { diff --git a/pkg/gui/remotes_panel.go b/pkg/gui/remotes_panel.go index 20e0be86c..3987bea1b 100644 --- a/pkg/gui/remotes_panel.go +++ b/pkg/gui/remotes_panel.go @@ -81,7 +81,7 @@ func (gui *Gui) handleRemoteEnter() error { } gui.State.Panels.RemoteBranches.SelectedLineIdx = newSelectedLine - return gui.switchContext(gui.Contexts.Remotes.Branches.Context) + return gui.pushContext(gui.Contexts.Remotes.Branches.Context) } func (gui *Gui) handleAddRemote(g *gocui.Gui, v *gocui.View) error { diff --git a/pkg/gui/reset_menu_panel.go b/pkg/gui/reset_menu_panel.go index 547aa89d0..3175dbed7 100644 --- a/pkg/gui/reset_menu_panel.go +++ b/pkg/gui/reset_menu_panel.go @@ -17,7 +17,7 @@ func (gui *Gui) resetToRef(ref string, strength string, options oscommands.RunCo // loading a heap of commits is slow so we limit them whenever doing a reset gui.State.Panels.Commits.LimitCommits = true - if err := gui.switchContext(gui.Contexts.BranchCommits.Context); err != nil { + if err := gui.pushContext(gui.Contexts.BranchCommits.Context); err != nil { return err } diff --git a/pkg/gui/searching.go b/pkg/gui/searching.go index ec66a8b92..cc21acaf2 100644 --- a/pkg/gui/searching.go +++ b/pkg/gui/searching.go @@ -14,7 +14,7 @@ func (gui *Gui) handleOpenSearch(g *gocui.Gui, v *gocui.View) error { gui.renderString("search", "") - if err := gui.switchContext(gui.Contexts.Search.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Search.Context); err != nil { return err } diff --git a/pkg/gui/side_window.go b/pkg/gui/side_window.go index 938123492..fc5842dea 100644 --- a/pkg/gui/side_window.go +++ b/pkg/gui/side_window.go @@ -25,7 +25,7 @@ func (gui *Gui) nextSideWindow() error { viewName := gui.getViewNameForWindow(newWindow) - return gui.switchContextToView(viewName) + return gui.pushContextWithView(viewName) } func (gui *Gui) previousSideWindow() error { @@ -51,11 +51,11 @@ func (gui *Gui) previousSideWindow() error { viewName := gui.getViewNameForWindow(newWindow) - return gui.switchContextToView(viewName) + return gui.pushContextWithView(viewName) } func (gui *Gui) goToSideWindow(sideViewName string) func(g *gocui.Gui, v *gocui.View) error { return func(g *gocui.Gui, v *gocui.View) error { - return gui.switchContextToView(sideViewName) + return gui.pushContextWithView(sideViewName) } } diff --git a/pkg/gui/staging_panel.go b/pkg/gui/staging_panel.go index 44413442f..05c762ed9 100644 --- a/pkg/gui/staging_panel.go +++ b/pkg/gui/staging_panel.go @@ -85,7 +85,7 @@ func (gui *Gui) handleTogglePanel() error { func (gui *Gui) handleStagingEscape() error { gui.escapeLineByLinePanel() - return gui.switchContext(gui.Contexts.Files.Context) + return gui.pushContext(gui.Contexts.Files.Context) } func (gui *Gui) handleToggleStagedSelection() error { @@ -108,7 +108,7 @@ func (gui *Gui) handleResetSelection() error { handlersManageFocus: true, handleConfirm: func() error { return gui.withLBLActiveCheck(func(state *lBlPanelState) error { - if err := gui.switchContext(gui.Contexts.Staging.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Staging.Context); err != nil { return err } @@ -116,7 +116,7 @@ func (gui *Gui) handleResetSelection() error { }) }, handleClose: func() error { - return gui.switchContext(gui.Contexts.Staging.Context) + return gui.pushContext(gui.Contexts.Staging.Context) }, }) } else { diff --git a/pkg/gui/status_panel.go b/pkg/gui/status_panel.go index 65ea426d6..726db21cc 100644 --- a/pkg/gui/status_panel.go +++ b/pkg/gui/status_panel.go @@ -73,7 +73,7 @@ func (gui *Gui) handleStatusClick(g *gocui.Gui, v *gocui.View) error { return nil } - if err := gui.switchContext(gui.Contexts.Status.Context); err != nil { + if err := gui.pushContext(gui.Contexts.Status.Context); err != nil { return err } diff --git a/pkg/gui/sub_commits_panel.go b/pkg/gui/sub_commits_panel.go index 24e9a3a39..a86022d38 100644 --- a/pkg/gui/sub_commits_panel.go +++ b/pkg/gui/sub_commits_panel.go @@ -97,7 +97,7 @@ func (gui *Gui) switchToSubCommitsContext(refName string) error { gui.State.Panels.SubCommits.SelectedLineIdx = 0 gui.Contexts.SubCommits.Context.SetParentContext(gui.currentSideContext()) - return gui.switchContext(gui.Contexts.SubCommits.Context) + return gui.pushContext(gui.Contexts.SubCommits.Context) } func (gui *Gui) handleSwitchToSubCommits() error { diff --git a/pkg/gui/suggestions_panel.go b/pkg/gui/suggestions_panel.go new file mode 100644 index 000000000..eb3b7808a --- /dev/null +++ b/pkg/gui/suggestions_panel.go @@ -0,0 +1,22 @@ +package gui + +func (gui *Gui) getSelectedSuggestion() string { + selectedLine := gui.State.Panels.Suggestions.SelectedLineIdx + if selectedLine == -1 { + return "" + } + + return gui.State.Suggestions[selectedLine] +} + +func (gui *Gui) setSuggestions(suggestions []string) { + view := gui.getSuggestionsView() + if view == nil { + return + } + + gui.State.Suggestions = suggestions + gui.State.Panels.Suggestions.SelectedLineIdx = 0 + _ = gui.resetOrigin(view) + _ = gui.Contexts.Suggestions.Context.HandleRender() +} diff --git a/pkg/gui/tags_panel.go b/pkg/gui/tags_panel.go index 6f9004e4d..6a4ad3832 100644 --- a/pkg/gui/tags_panel.go +++ b/pkg/gui/tags_panel.go @@ -56,7 +56,7 @@ func (gui *Gui) handleCheckoutTag(g *gocui.Gui, v *gocui.View) error { if err := gui.handleCheckoutRef(tag.Name, handleCheckoutRefOptions{}); err != nil { return err } - return gui.switchContext(gui.Contexts.Branches.Context) + return gui.pushContext(gui.Contexts.Branches.Context) } func (gui *Gui) handleDeleteTag(g *gocui.Gui, v *gocui.View) error { diff --git a/pkg/gui/view_helpers.go b/pkg/gui/view_helpers.go index 32d1f0b73..51947837d 100644 --- a/pkg/gui/view_helpers.go +++ b/pkg/gui/view_helpers.go @@ -259,6 +259,11 @@ func (gui *Gui) getMainView() *gocui.View { return v } +func (gui *Gui) getSuggestionsView() *gocui.View { + v, _ := gui.g.View("suggestions") + return v +} + func (gui *Gui) getSecondaryView() *gocui.View { v, _ := gui.g.View("secondary") return v @@ -415,7 +420,7 @@ func (gui *Gui) clearEditorView(v *gocui.View) { func (gui *Gui) onViewTabClick(viewName string, tabIndex int) error { context := gui.ViewTabContextMap[viewName][tabIndex].contexts[0] - return gui.switchContext(context) + return gui.pushContext(context) } func (gui *Gui) handleNextTab(g *gocui.Gui, v *gocui.View) error { diff --git a/pkg/utils/fuzzy_search.go b/pkg/utils/fuzzy_search.go new file mode 100644 index 000000000..c4bc078a3 --- /dev/null +++ b/pkg/utils/fuzzy_search.go @@ -0,0 +1,28 @@ +package utils + +import ( + "sort" + + "github.com/sahilm/fuzzy" +) + +func FuzzySearch(needle string, haystack []string) []string { + if needle == "" { + return []string{} + } + + myHaystack := make([]string, len(haystack)) + for i := range haystack { + myHaystack[i] = haystack[i] + } + + matches := fuzzy.Find(needle, haystack) + sort.Sort(matches) + + result := make([]string, len(matches)) + for i, match := range matches { + result[i] = match.Str + } + + return result +} diff --git a/pkg/utils/fuzzy_search_test.go b/pkg/utils/fuzzy_search_test.go new file mode 100644 index 000000000..808d83772 --- /dev/null +++ b/pkg/utils/fuzzy_search_test.go @@ -0,0 +1,53 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestFuzzySearch is a function. +func TestFuzzySearch(t *testing.T) { + type scenario struct { + needle string + haystack []string + expected []string + } + + scenarios := []scenario{ + { + needle: "", + haystack: []string{"test"}, + expected: []string{}, + }, + { + needle: "test", + haystack: []string{"test"}, + expected: []string{"test"}, + }, + { + needle: "o", + haystack: []string{"a", "o", "e"}, + expected: []string{"o"}, + }, + { + needle: "mybranch", + haystack: []string{"my_branch", "mybranch", "branch", "this is my branch"}, + expected: []string{"mybranch", "my_branch", "this is my branch"}, + }, + { + needle: "test", + haystack: []string{"not a good match", "this 'test' is a good match", "test"}, + expected: []string{"test", "this 'test' is a good match"}, + }, + { + needle: "test", + haystack: []string{"Test"}, + expected: []string{"Test"}, + }, + } + + for _, s := range scenarios { + assert.EqualValues(t, s.expected, FuzzySearch(s.needle, s.haystack)) + } +} diff --git a/vendor/github.com/sahilm/fuzzy/.gitignore b/vendor/github.com/sahilm/fuzzy/.gitignore new file mode 100644 index 000000000..d6c59ee86 --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/.gitignore @@ -0,0 +1,2 @@ +vendor/ +coverage/ diff --git a/vendor/github.com/sahilm/fuzzy/CONTRIBUTING.md b/vendor/github.com/sahilm/fuzzy/CONTRIBUTING.md new file mode 100644 index 000000000..7068ce130 --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/CONTRIBUTING.md @@ -0,0 +1 @@ +Everyone is welcome to contribute. Please send me a pull request or file an issue. I promise to respond promptly. diff --git a/vendor/github.com/sahilm/fuzzy/Gopkg.lock b/vendor/github.com/sahilm/fuzzy/Gopkg.lock new file mode 100644 index 000000000..6e3a7fe54 --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/Gopkg.lock @@ -0,0 +1,20 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + branch = "master" + digest = "1:ee97ec8a00b2424570c1ce53d7b410e96fbd4c241b29df134276ff6aa3750335" + name = "github.com/kylelemons/godebug" + packages = [ + "diff", + "pretty", + ] + pruneopts = "" + revision = "d65d576e9348f5982d7f6d83682b694e731a45c6" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = ["github.com/kylelemons/godebug/pretty"] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/sahilm/fuzzy/Gopkg.toml b/vendor/github.com/sahilm/fuzzy/Gopkg.toml new file mode 100644 index 000000000..8f96b112e --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/Gopkg.toml @@ -0,0 +1,4 @@ +# Test dependency +[[constraint]] + branch = "master" + name = "github.com/kylelemons/godebug" diff --git a/vendor/github.com/sahilm/fuzzy/LICENSE b/vendor/github.com/sahilm/fuzzy/LICENSE new file mode 100644 index 000000000..f848719e6 --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Sahil Muthoo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/sahilm/fuzzy/Makefile b/vendor/github.com/sahilm/fuzzy/Makefile new file mode 100644 index 000000000..7fa2be4ec --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/Makefile @@ -0,0 +1,57 @@ +.PHONY: all +all: setup lint test + +.PHONY: test +test: setup + go test -bench ./... + +.PHONY: cover +cover: setup + mkdir -p coverage + gocov test ./... | gocov-html > coverage/coverage.html + +sources = $(shell find . -name '*.go' -not -path './vendor/*') +.PHONY: goimports +goimports: setup + goimports -w $(sources) + +.PHONY: lint +lint: setup + gometalinter ./... --enable=goimports --disable=gocyclo --vendor -t + +.PHONY: install +install: setup + go install + +BIN_DIR := $(GOPATH)/bin +GOIMPORTS := $(BIN_DIR)/goimports +GOMETALINTER := $(BIN_DIR)/gometalinter +DEP := $(BIN_DIR)/dep +GOCOV := $(BIN_DIR)/gocov +GOCOV_HTML := $(BIN_DIR)/gocov-html + +$(GOIMPORTS): + go get -u golang.org/x/tools/cmd/goimports + +$(GOMETALINTER): + go get -u github.com/alecthomas/gometalinter + gometalinter --install &> /dev/null + +$(GOCOV): + go get -u github.com/axw/gocov/gocov + +$(GOCOV_HTML): + go get -u gopkg.in/matm/v1/gocov-html + +$(DEP): + go get -u github.com/golang/dep/cmd/dep + +tools: $(GOIMPORTS) $(GOMETALINTER) $(GOCOV) $(GOCOV_HTML) $(DEP) + +vendor: $(DEP) + dep ensure + +setup: tools vendor + +updatedeps: + dep ensure -update diff --git a/vendor/github.com/sahilm/fuzzy/README.md b/vendor/github.com/sahilm/fuzzy/README.md new file mode 100644 index 000000000..c632da5d9 --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/README.md @@ -0,0 +1,184 @@ +gopher looking for stuff gopher found stuff + +# fuzzy +[![Build Status](https://travis-ci.org/sahilm/fuzzy.svg?branch=master)](https://travis-ci.org/sahilm/fuzzy) +[![Documentation](https://godoc.org/github.com/sahilm/fuzzy?status.svg)](https://godoc.org/github.com/sahilm/fuzzy) + +Go library that provides fuzzy string matching optimized for filenames and code symbols in the style of Sublime Text, +VSCode, IntelliJ IDEA et al. This library is external dependency-free. It only depends on the Go standard library. + +## Features + +- Intuitive matching. Results are returned in descending order of match quality. Quality is determined by: + - The first character in the pattern matches the first character in the match string. + - The matched character is camel cased. + - The matched character follows a separator such as an underscore character. + - The matched character is adjacent to a previous match. + +- Speed. Matches are returned in milliseconds. It's perfect for interactive search boxes. + +- The positions of matches is returned. Allows you to highlight matching characters. + +- Unicode aware. + +## Demo + +Here is a [demo](_example/main.go) of matching various patterns against ~16K files from the Unreal Engine 4 codebase. + +![demo](assets/demo.gif) + +You can run the demo yourself like so: + +``` +cd _example/ +go get github.com/jroimartin/gocui +go run main.go +``` + +## Usage + +The following example prints out matches with the matched chars in bold. + +```go +package main + +import ( + "fmt" + + "github.com/sahilm/fuzzy" +) + +func main() { + const bold = "\033[1m%s\033[0m" + pattern := "mnr" + data := []string{"game.cpp", "moduleNameResolver.ts", "my name is_Ramsey"} + + matches := fuzzy.Find(pattern, data) + + for _, match := range matches { + for i := 0; i < len(match.Str); i++ { + if contains(i, match.MatchedIndexes) { + fmt.Print(fmt.Sprintf(bold, string(match.Str[i]))) + } else { + fmt.Print(string(match.Str[i])) + } + } + fmt.Println() + } +} + +func contains(needle int, haystack []int) bool { + for _, i := range haystack { + if needle == i { + return true + } + } + return false +} +``` +If the data you want to match isn't a slice of strings, you can use `FindFromSource` by implementing +the provided `Source` interface. Here's an example: + +```go +package main + +import ( + "fmt" + + "github.com/sahilm/fuzzy" +) + +type employee struct { + name string + age int +} + +type employees []employee + +func (e employees) String(i int) string { + return e[i].name +} + +func (e employees) Len() int { + return len(e) +} + +func main() { + emps := employees{ + { + name: "Alice", + age: 45, + }, + { + name: "Bob", + age: 35, + }, + { + name: "Allie", + age: 35, + }, + } + results := fuzzy.FindFrom("al", emps) + fmt.Println(results) +} +``` + +Check out the [godoc](https://godoc.org/github.com/sahilm/fuzzy) for detailed documentation. + +## Installation + +`go get github.com/sahilm/fuzzy` or use your favorite dependency management tool. + +## Speed + +Here are a few benchmark results on a normal laptop. + +``` +BenchmarkFind/with_unreal_4_(~16K_files)-4 100 12915315 ns/op +BenchmarkFind/with_linux_kernel_(~60K_files)-4 50 30885038 ns/op +``` + +Matching a pattern against ~60K files from the Linux kernel takes about 30ms. + +## Contributing + +Everyone is welcome to contribute. Please send me a pull request or file an issue. I promise +to respond promptly. + +## Credits + +* [@ericpauley](https://github.com/ericpauley) & [@lunixbochs](https://github.com/lunixbochs) contributed Unicode awareness and various performance optimisations. + +* The algorithm is based of the awesome work of [forrestthewoods](https://github.com/forrestthewoods/lib_fts/blob/master/code/fts_fuzzy_match.js). +See [this](https://blog.forrestthewoods.com/reverse-engineering-sublime-text-s-fuzzy-match-4cffeed33fdb#.d05n81yjy) +blog post for details of the algorithm. + +* The artwork is by my lovely wife Sanah. It's based on the Go Gopher. + +* The Go gopher was designed by Renee French (http://reneefrench.blogspot.com/). +The design is licensed under the Creative Commons 3.0 Attributions license. + +## License + +The MIT License (MIT) + +Copyright (c) 2017 Sahil Muthoo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/github.com/sahilm/fuzzy/fuzzy.go b/vendor/github.com/sahilm/fuzzy/fuzzy.go new file mode 100644 index 000000000..bd66ee66c --- /dev/null +++ b/vendor/github.com/sahilm/fuzzy/fuzzy.go @@ -0,0 +1,235 @@ +/* +Package fuzzy provides fuzzy string matching optimized +for filenames and code symbols in the style of Sublime Text, +VSCode, IntelliJ IDEA et al. +*/ +package fuzzy + +import ( + "sort" + "unicode" + "unicode/utf8" +) + +// Match represents a matched string. +type Match struct { + // The matched string. + Str string + // The index of the matched string in the supplied slice. + Index int + // The indexes of matched characters. Useful for highlighting matches. + MatchedIndexes []int + // Score used to rank matches + Score int +} + +const ( + firstCharMatchBonus = 10 + matchFollowingSeparatorBonus = 20 + camelCaseMatchBonus = 20 + adjacentMatchBonus = 5 + unmatchedLeadingCharPenalty = -5 + maxUnmatchedLeadingCharPenalty = -15 +) + +var separators = []rune("/-_ .\\") + +// Matches is a slice of Match structs +type Matches []Match + +func (a Matches) Len() int { return len(a) } +func (a Matches) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a Matches) Less(i, j int) bool { return a[i].Score >= a[j].Score } + +// Source represents an abstract source of a list of strings. Source must be iterable type such as a slice. +// The source will be iterated over till Len() with String(i) being called for each element where i is the +// index of the element. You can find a working example in the README. +type Source interface { + // The string to be matched at position i. + String(i int) string + // The length of the source. Typically is the length of the slice of things that you want to match. + Len() int +} + +type stringSource []string + +func (ss stringSource) String(i int) string { + return ss[i] +} + +func (ss stringSource) Len() int { return len(ss) } + +/* +Find looks up pattern in data and returns matches +in descending order of match quality. Match quality +is determined by a set of bonus and penalty rules. + +The following types of matches apply a bonus: + +* The first character in the pattern matches the first character in the match string. + +* The matched character is camel cased. + +* The matched character follows a separator such as an underscore character. + +* The matched character is adjacent to a previous match. + +Penalties are applied for every character in the search string that wasn't matched and all leading +characters upto the first match. +*/ +func Find(pattern string, data []string) Matches { + return FindFrom(pattern, stringSource(data)) +} + +/* +FindFrom is an alternative implementation of Find using a Source +instead of a list of strings. +*/ +func FindFrom(pattern string, data Source) Matches { + if len(pattern) == 0 { + return nil + } + runes := []rune(pattern) + var matches Matches + var matchedIndexes []int + for i := 0; i < data.Len(); i++ { + var match Match + match.Str = data.String(i) + match.Index = i + if matchedIndexes != nil { + match.MatchedIndexes = matchedIndexes + } else { + match.MatchedIndexes = make([]int, 0, len(runes)) + } + var score int + patternIndex := 0 + bestScore := -1 + matchedIndex := -1 + currAdjacentMatchBonus := 0 + var last rune + var lastIndex int + nextc, nextSize := utf8.DecodeRuneInString(data.String(i)) + var candidate rune + var candidateSize int + for j := 0; j < len(data.String(i)); j += candidateSize { + candidate, candidateSize = nextc, nextSize + if equalFold(candidate, runes[patternIndex]) { + score = 0 + if j == 0 { + score += firstCharMatchBonus + } + if unicode.IsLower(last) && unicode.IsUpper(candidate) { + score += camelCaseMatchBonus + } + if j != 0 && isSeparator(last) { + score += matchFollowingSeparatorBonus + } + if len(match.MatchedIndexes) > 0 { + lastMatch := match.MatchedIndexes[len(match.MatchedIndexes)-1] + bonus := adjacentCharBonus(lastIndex, lastMatch, currAdjacentMatchBonus) + score += bonus + // adjacent matches are incremental and keep increasing based on previous adjacent matches + // thus we need to maintain the current match bonus + currAdjacentMatchBonus += bonus + } + if score > bestScore { + bestScore = score + matchedIndex = j + } + } + var nextp rune + if patternIndex < len(runes)-1 { + nextp = runes[patternIndex+1] + } + if j+candidateSize < len(data.String(i)) { + if data.String(i)[j+candidateSize] < utf8.RuneSelf { // Fast path for ASCII + nextc, nextSize = rune(data.String(i)[j+candidateSize]), 1 + } else { + nextc, nextSize = utf8.DecodeRuneInString(data.String(i)[j+candidateSize:]) + } + } else { + nextc, nextSize = 0, 0 + } + // We apply the best score when we have the next match coming up or when the search string has ended. + // Tracking when the next match is coming up allows us to exhaustively find the best match and not necessarily + // the first match. + // For example given the pattern "tk" and search string "The Black Knight", exhaustively matching allows us + // to match the second k thus giving this string a higher score. + if equalFold(nextp, nextc) || nextc == 0 { + if matchedIndex > -1 { + if len(match.MatchedIndexes) == 0 { + penalty := matchedIndex * unmatchedLeadingCharPenalty + bestScore += max(penalty, maxUnmatchedLeadingCharPenalty) + } + match.Score += bestScore + match.MatchedIndexes = append(match.MatchedIndexes, matchedIndex) + score = 0 + bestScore = -1 + patternIndex++ + } + } + lastIndex = j + last = candidate + } + // apply penalty for each unmatched character + penalty := len(match.MatchedIndexes) - len(data.String(i)) + match.Score += penalty + if len(match.MatchedIndexes) == len(runes) { + matches = append(matches, match) + matchedIndexes = nil + } else { + matchedIndexes = match.MatchedIndexes[:0] // Recycle match index slice + } + } + sort.Stable(matches) + return matches +} + +// Taken from strings.EqualFold +func equalFold(tr, sr rune) bool { + if tr == sr { + return true + } + if tr < sr { + tr, sr = sr, tr + } + // Fast check for ASCII. + if tr < utf8.RuneSelf { + // ASCII, and sr is upper case. tr must be lower case. + if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' { + return true + } + return false + } + + // General case. SimpleFold(x) returns the next equivalent rune > x + // or wraps around to smaller values. + r := unicode.SimpleFold(sr) + for r != sr && r < tr { + r = unicode.SimpleFold(r) + } + return r == tr +} + +func adjacentCharBonus(i int, lastMatch int, currentBonus int) int { + if lastMatch == i { + return currentBonus*2 + adjacentMatchBonus + } + return 0 +} + +func isSeparator(s rune) bool { + for _, sep := range separators { + if s == sep { + return true + } + } + return false +} + +func max(x int, y int) int { + if x > y { + return x + } + return y +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5ecef1386..141091a4e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -123,6 +123,8 @@ github.com/kevinburke/ssh_config github.com/konsorten/go-windows-terminal-sequences # github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 github.com/kr/logfmt +# github.com/kylelemons/godebug v1.1.0 +## explicit # github.com/mattn/go-colorable v0.1.7 ## explicit github.com/mattn/go-colorable @@ -142,6 +144,9 @@ github.com/mitchellh/go-homedir ## explicit # github.com/pmezard/go-difflib v1.0.0 github.com/pmezard/go-difflib/difflib +# github.com/sahilm/fuzzy v0.1.0 +## explicit +github.com/sahilm/fuzzy # github.com/sergi/go-diff v1.1.0 github.com/sergi/go-diff/diffmatchpatch # github.com/sirupsen/logrus v1.4.2