1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-04-19 12:12:42 +02:00

many more generics

This commit is contained in:
Jesse Duffield 2022-03-19 19:12:58 +11:00
parent bf4f06ab4e
commit 1b75ed3740
31 changed files with 278 additions and 320 deletions

2
go.mod
View File

@ -14,7 +14,7 @@ require (
github.com/gookit/color v1.4.2 github.com/gookit/color v1.4.2
github.com/imdario/mergo v0.3.11 github.com/imdario/mergo v0.3.11
github.com/integrii/flaggy v1.4.0 github.com/integrii/flaggy v1.4.0
github.com/jesseduffield/generics v0.0.0-20220319062156-fa5cb8bde518 github.com/jesseduffield/generics v0.0.0-20220319080325-a60171f800d5
github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4 github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4
github.com/jesseduffield/gocui v0.3.1-0.20220227022729-69f0c798eec8 github.com/jesseduffield/gocui v0.3.1-0.20220227022729-69f0c798eec8
github.com/jesseduffield/minimal/gitignore v0.3.3-0.20211018110810-9cde264e6b1e github.com/jesseduffield/minimal/gitignore v0.3.3-0.20211018110810-9cde264e6b1e

4
go.sum
View File

@ -66,8 +66,8 @@ github.com/integrii/flaggy v1.4.0 h1:A1x7SYx4jqu5NSrY14z8Z+0UyX2S5ygfJJrfolWR3zM
github.com/integrii/flaggy v1.4.0/go.mod h1:tnTxHeTJbah0gQ6/K0RW0J7fMUBk9MCF5blhm43LNpI= github.com/integrii/flaggy v1.4.0/go.mod h1:tnTxHeTJbah0gQ6/K0RW0J7fMUBk9MCF5blhm43LNpI=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jesseduffield/generics v0.0.0-20220319062156-fa5cb8bde518 h1:scclO0fuRMsIdYr6Gg+9LS1S1ZO93tHKQSbErWQWQ4s= github.com/jesseduffield/generics v0.0.0-20220319080325-a60171f800d5 h1:mZf9Ezkd4Thuw2tj5naFeoUbHkbNiD38LQFokUGSbtQ=
github.com/jesseduffield/generics v0.0.0-20220319062156-fa5cb8bde518/go.mod h1:+LLj9/WUPAP8LqCchs7P+7X0R98HiFujVFANdNaxhGk= github.com/jesseduffield/generics v0.0.0-20220319080325-a60171f800d5/go.mod h1:+LLj9/WUPAP8LqCchs7P+7X0R98HiFujVFANdNaxhGk=
github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4 h1:GOQrmaE8i+KEdB8NzAegKYd4tPn/inM0I1uo0NXFerg= github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4 h1:GOQrmaE8i+KEdB8NzAegKYd4tPn/inM0I1uo0NXFerg=
github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4/go.mod h1:nGNEErzf+NRznT+N2SWqmHnDnF9aLgANB1CUNEan09o= github.com/jesseduffield/go-git/v5 v5.1.2-0.20201006095850-341962be15a4/go.mod h1:nGNEErzf+NRznT+N2SWqmHnDnF9aLgANB1CUNEan09o=
github.com/jesseduffield/gocui v0.3.1-0.20220227022729-69f0c798eec8 h1:9N08i5kjvOfkzMj6THmIM110wPTQLdVYEOHMHT2DFiI= github.com/jesseduffield/gocui v0.3.1-0.20220227022729-69f0c798eec8 h1:9N08i5kjvOfkzMj6THmIM110wPTQLdVYEOHMHT2DFiI=

View File

@ -7,6 +7,7 @@ import (
"strings" "strings"
"github.com/jesseduffield/generics/maps" "github.com/jesseduffield/generics/maps"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/gocui" "github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
@ -413,16 +414,9 @@ func (gui *Gui) changeMainViewsContext(c types.Context) {
func (gui *Gui) viewTabNames(viewName string) []string { func (gui *Gui) viewTabNames(viewName string) []string {
tabContexts := gui.State.ViewTabContextMap[viewName] tabContexts := gui.State.ViewTabContextMap[viewName]
if len(tabContexts) == 0 { return slices.Map(tabContexts, func(tabContext context.TabContext) string {
return nil return tabContext.Tab
} })
result := make([]string, len(tabContexts))
for i, tabContext := range tabContexts {
result[i] = tabContext.Tab
}
return result
} }
func (gui *Gui) setViewTabForContext(c types.Context) { func (gui *Gui) setViewTabForContext(c types.Context) {

View File

@ -1,6 +1,7 @@
package context package context
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/gocui" "github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
@ -77,19 +78,16 @@ func (self *MenuViewModel) SetMenuItems(items []*types.MenuItem) {
} }
// TODO: move into presentation package // TODO: move into presentation package
func (self *MenuViewModel) GetDisplayStrings(startIdx int, length int) [][]string { func (self *MenuViewModel) GetDisplayStrings(_startIdx int, _length int) [][]string {
stringArrays := make([][]string, len(self.menuItems)) return slices.Map(self.menuItems, func(item *types.MenuItem) []string {
for i, item := range self.menuItems { if item.DisplayStrings != nil {
if item.DisplayStrings == nil { return item.DisplayStrings
}
styledStr := item.DisplayString styledStr := item.DisplayString
if item.OpensMenu { if item.OpensMenu {
styledStr = presentation.OpensMenuStyle(styledStr) styledStr = presentation.OpensMenuStyle(styledStr)
} }
stringArrays[i] = []string{styledStr} return []string{styledStr}
} else { })
stringArrays[i] = item.DisplayStrings
}
}
return stringArrays
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/types/enums" "github.com/jesseduffield/lazygit/pkg/commands/types/enums"
@ -51,17 +52,14 @@ func (self *MergeAndRebaseHelper) CreateRebaseOptionsMenu() error {
options = append(options, REBASE_OPTION_SKIP) options = append(options, REBASE_OPTION_SKIP)
} }
menuItems := make([]*types.MenuItem, len(options)) menuItems := slices.Map(options, func(option string) *types.MenuItem {
for i, option := range options { return &types.MenuItem{
// note to self. Never, EVER, close over loop variables in a function
option := option
menuItems[i] = &types.MenuItem{
DisplayString: option, DisplayString: option,
OnPress: func() error { OnPress: func() error {
return self.genericMergeCommand(option) return self.genericMergeCommand(option)
}, },
} }
} })
var title string var title string
if self.git.Status.WorkingTreeState() == enums.REBASE_MODE_MERGING { if self.git.Status.WorkingTreeState() == enums.REBASE_MODE_MERGING {

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
@ -134,10 +135,8 @@ func (self *RefsHelper) ResetToRef(ref string, strength string, envVars []string
func (self *RefsHelper) CreateGitResetMenu(ref string) error { func (self *RefsHelper) CreateGitResetMenu(ref string) error {
strengths := []string{"soft", "mixed", "hard"} strengths := []string{"soft", "mixed", "hard"}
menuItems := make([]*types.MenuItem, len(strengths)) menuItems := slices.Map(strengths, func(strength string) *types.MenuItem {
for i, strength := range strengths { return &types.MenuItem{
strength := strength
menuItems[i] = &types.MenuItem{
DisplayStrings: []string{ DisplayStrings: []string{
fmt.Sprintf("%s reset", strength), fmt.Sprintf("%s reset", strength),
style.FgRed.Sprintf("reset --%s %s", strength, ref), style.FgRed.Sprintf("reset --%s %s", strength, ref),
@ -147,7 +146,7 @@ func (self *RefsHelper) CreateGitResetMenu(ref string) error {
return self.ResetToRef(ref, strength, []string{}) return self.ResetToRef(ref, strength, []string{})
}, },
} }
} })
return self.c.Menu(types.CreateMenuOptions{ return self.c.Menu(types.CreateMenuOptions{
Title: fmt.Sprintf("%s %s", self.c.Tr.LcResetTo, ref), Title: fmt.Sprintf("%s %s", self.c.Tr.LcResetTo, ref),

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils" "github.com/jesseduffield/lazygit/pkg/utils"
@ -51,22 +53,18 @@ func NewSuggestionsHelper(
} }
func (self *SuggestionsHelper) getRemoteNames() []string { func (self *SuggestionsHelper) getRemoteNames() []string {
result := make([]string, len(self.model.Remotes)) return slices.Map(self.model.Remotes, func(remote *models.Remote) string {
for i, remote := range self.model.Remotes { return remote.Name
result[i] = remote.Name })
}
return result
} }
func matchesToSuggestions(matches []string) []*types.Suggestion { func matchesToSuggestions(matches []string) []*types.Suggestion {
suggestions := make([]*types.Suggestion, len(matches)) return slices.Map(matches, func(match string) *types.Suggestion {
for i, match := range matches { return &types.Suggestion{
suggestions[i] = &types.Suggestion{
Value: match, Value: match,
Label: match, Label: match,
} }
} })
return suggestions
} }
func (self *SuggestionsHelper) GetRemoteSuggestionsFunc() func(string) []*types.Suggestion { func (self *SuggestionsHelper) GetRemoteSuggestionsFunc() func(string) []*types.Suggestion {
@ -76,11 +74,9 @@ func (self *SuggestionsHelper) GetRemoteSuggestionsFunc() func(string) []*types.
} }
func (self *SuggestionsHelper) getBranchNames() []string { func (self *SuggestionsHelper) getBranchNames() []string {
result := make([]string, len(self.model.Branches)) return slices.Map(self.model.Branches, func(branch *models.Branch) string {
for i, branch := range self.model.Branches { return branch.Name
result[i] = branch.Name })
}
return result
} }
func (self *SuggestionsHelper) GetBranchNameSuggestionsFunc() func(string) []*types.Suggestion { func (self *SuggestionsHelper) GetBranchNameSuggestionsFunc() func(string) []*types.Suggestion {
@ -94,15 +90,12 @@ func (self *SuggestionsHelper) GetBranchNameSuggestionsFunc() func(string) []*ty
matchingBranchNames = utils.FuzzySearch(input, branchNames) matchingBranchNames = utils.FuzzySearch(input, branchNames)
} }
suggestions := make([]*types.Suggestion, len(matchingBranchNames)) return slices.Map(matchingBranchNames, func(branchName string) *types.Suggestion {
for i, branchName := range matchingBranchNames { return &types.Suggestion{
suggestions[i] = &types.Suggestion{
Value: branchName, Value: branchName,
Label: presentation.GetBranchTextStyle(branchName).Sprint(branchName), Label: presentation.GetBranchTextStyle(branchName).Sprint(branchName),
} }
} })
return suggestions
} }
} }
@ -148,26 +141,16 @@ func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*type
// doing another fuzzy search for good measure // doing another fuzzy search for good measure
matchingNames = utils.FuzzySearch(input, matchingNames) matchingNames = utils.FuzzySearch(input, matchingNames)
suggestions := make([]*types.Suggestion, len(matchingNames)) return matchesToSuggestions(matchingNames)
for i, name := range matchingNames {
suggestions[i] = &types.Suggestion{
Value: name,
Label: name,
}
}
return suggestions
} }
} }
func (self *SuggestionsHelper) getRemoteBranchNames(separator string) []string { func (self *SuggestionsHelper) getRemoteBranchNames(separator string) []string {
result := []string{} return slices.FlatMap(self.model.Remotes, func(remote *models.Remote) []string {
for _, remote := range self.model.Remotes { return slices.Map(remote.Branches, func(branch *models.RemoteBranch) string {
for _, branch := range remote.Branches { return fmt.Sprintf("%s%s%s", remote.Name, separator, branch.Name)
result = append(result, fmt.Sprintf("%s%s%s", remote.Name, separator, branch.Name)) })
} })
}
return result
} }
func (self *SuggestionsHelper) GetRemoteBranchesSuggestionsFunc(separator string) func(string) []*types.Suggestion { func (self *SuggestionsHelper) GetRemoteBranchesSuggestionsFunc(separator string) func(string) []*types.Suggestion {
@ -175,11 +158,9 @@ func (self *SuggestionsHelper) GetRemoteBranchesSuggestionsFunc(separator string
} }
func (self *SuggestionsHelper) getTagNames() []string { func (self *SuggestionsHelper) getTagNames() []string {
result := make([]string, len(self.model.Tags)) return slices.Map(self.model.Tags, func(tag *models.Tag) string {
for i, tag := range self.model.Tags { return tag.Name
result[i] = tag.Name })
}
return result
} }
func (self *SuggestionsHelper) GetRefsSuggestionsFunc() func(string) []*types.Suggestion { func (self *SuggestionsHelper) GetRefsSuggestionsFunc() func(string) []*types.Suggestion {

View File

@ -3,6 +3,7 @@ package gui
import ( import (
"testing" "testing"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -24,11 +25,7 @@ func TestGetSuggestedRemote(t *testing.T) {
} }
func mkRemoteList(names ...string) []*models.Remote { func mkRemoteList(names ...string) []*models.Remote {
result := make([]*models.Remote, 0, len(names)) return slices.Map(names, func(name string) *models.Remote {
return &models.Remote{Name: name}
for _, name := range names { })
result = append(result, &models.Remote{Name: name})
}
return result
} }

View File

@ -1,6 +1,7 @@
package filetree package filetree
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
) )
@ -40,19 +41,15 @@ func (s *CommitFileNode) GetPath() string {
} }
func (s *CommitFileNode) GetChildren() []INode { func (s *CommitFileNode) GetChildren() []INode {
result := make([]INode, len(s.Children)) return slices.Map(s.Children, func(child *CommitFileNode) INode {
for i, child := range s.Children { return child
result[i] = child })
}
return result
} }
func (s *CommitFileNode) SetChildren(children []INode) { func (s *CommitFileNode) SetChildren(children []INode) {
castChildren := make([]*CommitFileNode, len(children)) castChildren := slices.Map(children, func(child INode) *CommitFileNode {
for i, child := range children { return child.(*CommitFileNode)
castChildren[i] = child.(*CommitFileNode) })
}
s.Children = castChildren s.Children = castChildren
} }
@ -102,12 +99,10 @@ func (s *CommitFileNode) EveryFile(test func(file *models.CommitFile) bool) bool
func (n *CommitFileNode) Flatten(collapsedPaths *CollapsedPaths) []*CommitFileNode { func (n *CommitFileNode) Flatten(collapsedPaths *CollapsedPaths) []*CommitFileNode {
results := flatten(n, collapsedPaths) results := flatten(n, collapsedPaths)
nodes := make([]*CommitFileNode, len(results))
for i, result := range results {
nodes[i] = result.(*CommitFileNode)
}
return nodes return slices.Map(results, func(result INode) *CommitFileNode {
return result.(*CommitFileNode)
})
} }
func (node *CommitFileNode) GetNodeAtIndex(index int, collapsedPaths *CollapsedPaths) *CommitFileNode { func (node *CommitFileNode) GetNodeAtIndex(index int, collapsedPaths *CollapsedPaths) *CommitFileNode {
@ -149,12 +144,10 @@ func (s *CommitFileNode) Compress() {
func (s *CommitFileNode) GetLeaves() []*CommitFileNode { func (s *CommitFileNode) GetLeaves() []*CommitFileNode {
leaves := getLeaves(s) leaves := getLeaves(s)
castLeaves := make([]*CommitFileNode, len(leaves))
for i := range leaves {
castLeaves[i] = leaves[i].(*CommitFileNode)
}
return castLeaves return slices.Map(leaves, func(leaf INode) *CommitFileNode {
return leaf.(*CommitFileNode)
})
} }
// extra methods // extra methods

View File

@ -1,6 +1,7 @@
package filetree package filetree
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
) )
@ -42,19 +43,15 @@ func (s *FileNode) GetPath() string {
} }
func (s *FileNode) GetChildren() []INode { func (s *FileNode) GetChildren() []INode {
result := make([]INode, len(s.Children)) return slices.Map(s.Children, func(child *FileNode) INode {
for i, child := range s.Children { return child
result[i] = child })
}
return result
} }
func (s *FileNode) SetChildren(children []INode) { func (s *FileNode) SetChildren(children []INode) {
castChildren := make([]*FileNode, len(children)) castChildren := slices.Map(children, func(child INode) *FileNode {
for i, child := range children { return child.(*FileNode)
castChildren[i] = child.(*FileNode) })
}
s.Children = castChildren s.Children = castChildren
} }
@ -89,12 +86,9 @@ func (s *FileNode) Any(test func(node *FileNode) bool) bool {
func (n *FileNode) Flatten(collapsedPaths *CollapsedPaths) []*FileNode { func (n *FileNode) Flatten(collapsedPaths *CollapsedPaths) []*FileNode {
results := flatten(n, collapsedPaths) results := flatten(n, collapsedPaths)
nodes := make([]*FileNode, len(results)) return slices.Map(results, func(result INode) *FileNode {
for i, result := range results { return result.(*FileNode)
nodes[i] = result.(*FileNode) })
}
return nodes
} }
func (node *FileNode) GetNodeAtIndex(index int, collapsedPaths *CollapsedPaths) *FileNode { func (node *FileNode) GetNodeAtIndex(index int, collapsedPaths *CollapsedPaths) *FileNode {
@ -146,12 +140,10 @@ func (node *FileNode) GetFilePathsMatching(test func(*models.File) bool) []strin
func (s *FileNode) GetLeaves() []*FileNode { func (s *FileNode) GetLeaves() []*FileNode {
leaves := getLeaves(s) leaves := getLeaves(s)
castLeaves := make([]*FileNode, len(leaves))
for i := range leaves {
castLeaves[i] = leaves[i].(*FileNode)
}
return castLeaves return slices.Map(leaves, func(leaf INode) *FileNode {
return leaf.(*FileNode)
})
} }
// extra methods // extra methods

View File

@ -3,6 +3,7 @@ package filetree
import ( import (
"fmt" "fmt"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -85,13 +86,7 @@ func (self *FileTree) getFilesForDisplay() []*models.File {
} }
func (self *FileTree) FilterFiles(test func(*models.File) bool) []*models.File { func (self *FileTree) FilterFiles(test func(*models.File) bool) []*models.File {
result := make([]*models.File, 0) return slices.Filter(self.getFiles(), test)
for _, file := range self.getFiles() {
if test(file) {
result = append(result, file)
}
}
return result
} }
func (self *FileTree) SetFilter(filter FileTreeDisplayFilter) { func (self *FileTree) SetFilter(filter FileTreeDisplayFilter) {

View File

@ -3,6 +3,7 @@ package gui
import ( import (
"log" "log"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/context"
@ -28,12 +29,9 @@ func (gui *Gui) filesListContext() *context.WorkingTreeContext {
gui.Views.Files, gui.Views.Files,
func(startIdx int, length int) [][]string { func(startIdx int, length int) [][]string {
lines := presentation.RenderFileTree(gui.State.Contexts.Files.FileTreeViewModel, gui.State.Modes.Diffing.Ref, gui.State.Model.Submodules) lines := presentation.RenderFileTree(gui.State.Contexts.Files.FileTreeViewModel, gui.State.Modes.Diffing.Ref, gui.State.Model.Submodules)
mappedLines := make([][]string, len(lines)) return slices.Map(lines, func(line string) []string {
for i, line := range lines { return []string{line}
mappedLines[i] = []string{line} })
}
return mappedLines
}, },
OnFocusWrapper(gui.onFocusFile), OnFocusWrapper(gui.onFocusFile),
OnFocusWrapper(gui.withDiffModeCheck(gui.filesRenderToMain)), OnFocusWrapper(gui.withDiffModeCheck(gui.filesRenderToMain)),
@ -235,12 +233,9 @@ func (gui *Gui) commitFilesListContext() *context.CommitFilesContext {
} }
lines := presentation.RenderCommitFileTree(gui.State.Contexts.CommitFiles.CommitFileTreeViewModel, gui.State.Modes.Diffing.Ref, gui.git.Patch.PatchManager) lines := presentation.RenderCommitFileTree(gui.State.Contexts.CommitFiles.CommitFileTreeViewModel, gui.State.Modes.Diffing.Ref, gui.git.Patch.PatchManager)
mappedLines := make([][]string, len(lines)) return slices.Map(lines, func(line string) []string {
for i, line := range lines { return []string{line}
mappedLines[i] = []string{line} })
}
return mappedLines
}, },
OnFocusWrapper(gui.onCommitFileFocus), OnFocusWrapper(gui.onCommitFileFocus),
OnFocusWrapper(gui.withDiffModeCheck(gui.commitFilesRenderToMain)), OnFocusWrapper(gui.withDiffModeCheck(gui.commitFilesRenderToMain)),

View File

@ -4,6 +4,7 @@ import (
"log" "log"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
@ -62,11 +63,8 @@ func (gui *Gui) handleCreateOptionsMenu() error {
context := gui.currentContext() context := gui.currentContext()
bindings := gui.getBindings(context) bindings := gui.getBindings(context)
menuItems := make([]*types.MenuItem, len(bindings)) menuItems := slices.Map(bindings, func(binding *types.Binding) *types.MenuItem {
return &types.MenuItem{
for i, binding := range bindings {
binding := binding // note to self, never close over loop variables
menuItems[i] = &types.MenuItem{
DisplayStrings: []string{GetKeyDisplay(binding.Key), gui.displayDescription(binding)}, DisplayStrings: []string{GetKeyDisplay(binding.Key), gui.displayDescription(binding)},
OnPress: func() error { OnPress: func() error {
if binding.Key == nil { if binding.Key == nil {
@ -78,7 +76,7 @@ func (gui *Gui) handleCreateOptionsMenu() error {
return binding.Handler() return binding.Handler()
}, },
} }
} })
return gui.c.Menu(types.CreateMenuOptions{ return gui.c.Menu(types.CreateMenuOptions{
Title: strings.Title(gui.c.Tr.LcMenu), Title: strings.Title(gui.c.Tr.LcMenu),

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/i18n" "github.com/jesseduffield/lazygit/pkg/i18n"
@ -14,14 +15,10 @@ import (
var branchPrefixColorCache = make(map[string]style.TextStyle) var branchPrefixColorCache = make(map[string]style.TextStyle)
func GetBranchListDisplayStrings(branches []*models.Branch, fullDescription bool, diffName string, tr *i18n.TranslationSet) [][]string { func GetBranchListDisplayStrings(branches []*models.Branch, fullDescription bool, diffName string, tr *i18n.TranslationSet) [][]string {
lines := make([][]string, len(branches)) return slices.Map(branches, func(branch *models.Branch) []string {
diffed := branch.Name == diffName
for i := range branches { return getBranchDisplayStrings(branch, fullDescription, diffed, tr)
diffed := branches[i].Name == diffName })
lines[i] = getBranchDisplayStrings(branches[i], fullDescription, diffed, tr)
}
return lines
} }
// getBranchDisplayStrings returns the display string of branch // getBranchDisplayStrings returns the display string of branch

View File

@ -5,10 +5,12 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/generics/slices" "github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/utils" "github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
) )
type PipeKind uint8 type PipeKind uint8
@ -77,7 +79,6 @@ func GetPipeSets(commits []*models.Commit, getStyle func(c *models.Commit) style
func RenderAux(pipeSets [][]*Pipe, commits []*models.Commit, selectedCommitSha string) []string { func RenderAux(pipeSets [][]*Pipe, commits []*models.Commit, selectedCommitSha string) []string {
maxProcs := runtime.GOMAXPROCS(0) maxProcs := runtime.GOMAXPROCS(0)
lines := make([]string, 0, len(pipeSets))
// splitting up the rendering of the graph into multiple goroutines allows us to render the graph in parallel // splitting up the rendering of the graph into multiple goroutines allows us to render the graph in parallel
chunks := make([][]string, maxProcs) chunks := make([][]string, maxProcs)
perProc := len(pipeSets) / maxProcs perProc := len(pipeSets) / maxProcs
@ -110,24 +111,19 @@ func RenderAux(pipeSets [][]*Pipe, commits []*models.Commit, selectedCommitSha s
wg.Wait() wg.Wait()
for _, chunk := range chunks { return slices.Flatten(chunks)
lines = append(lines, chunk...)
}
return lines
} }
func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *models.Commit) style.TextStyle) []*Pipe { func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *models.Commit) style.TextStyle) []*Pipe {
currentPipes := make([]*Pipe, 0, len(prevPipes)) maxPos := lo.Max(
maxPos := 0 slices.Map(prevPipes, func(pipe *Pipe) int { return pipe.toPos }),
for _, pipe := range prevPipes { )
// a pipe that terminated in the previous line has no bearing on the current line // a pipe that terminated in the previous line has no bearing on the current line
// so we'll filter those out // so we'll filter those out
if pipe.kind != TERMINATES { currentPipes := slices.Filter(prevPipes, func(pipe *Pipe) bool {
currentPipes = append(currentPipes, pipe) return pipe.kind != TERMINATES
} })
maxPos = utils.Max(maxPos, pipe.toPos)
}
newPipes := make([]*Pipe, 0, len(currentPipes)+len(commit.Parents)) newPipes := make([]*Pipe, 0, len(currentPipes)+len(commit.Parents))
// start by assuming that we've got a brand new commit not related to any preceding commit. // start by assuming that we've got a brand new commit not related to any preceding commit.
@ -142,9 +138,9 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
} }
// a taken spot is one where a current pipe is ending on // a taken spot is one where a current pipe is ending on
takenSpots := make(map[int]bool) takenSpots := set.New[int]()
// a traversed spot is one where a current pipe is starting on, ending on, or passing through // a traversed spot is one where a current pipe is starting on, ending on, or passing through
traversedSpots := make(map[int]bool) traversedSpots := set.New[int]()
if len(commit.Parents) > 0 { if len(commit.Parents) > 0 {
newPipes = append(newPipes, &Pipe{ newPipes = append(newPipes, &Pipe{
@ -157,17 +153,17 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
}) })
} }
traversedSpotsForContinuingPipes := make(map[int]bool) traversedSpotsForContinuingPipes := set.New[int]()
for _, pipe := range currentPipes { for _, pipe := range currentPipes {
if !equalHashes(pipe.toSha, commit.Sha) { if !equalHashes(pipe.toSha, commit.Sha) {
traversedSpotsForContinuingPipes[pipe.toPos] = true traversedSpotsForContinuingPipes.Add(pipe.toPos)
} }
} }
getNextAvailablePosForContinuingPipe := func() int { getNextAvailablePosForContinuingPipe := func() int {
i := 0 i := 0
for { for {
if !traversedSpots[i] { if !traversedSpots.Includes(i) {
return i return i
} }
i++ i++
@ -179,7 +175,7 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
for { for {
// a newly created pipe is not allowed to end on a spot that's already taken, // a newly created pipe is not allowed to end on a spot that's already taken,
// nor on a spot that's been traversed by a continuing pipe. // nor on a spot that's been traversed by a continuing pipe.
if !takenSpots[i] && !traversedSpotsForContinuingPipes[i] { if !takenSpots.Includes(i) && !traversedSpotsForContinuingPipes.Includes(i) {
return i return i
} }
i++ i++
@ -192,9 +188,9 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
left, right = right, left left, right = right, left
} }
for i := left; i <= right; i++ { for i := left; i <= right; i++ {
traversedSpots[i] = true traversedSpots.Add(i)
} }
takenSpots[to] = true takenSpots.Add(to)
} }
for _, pipe := range currentPipes { for _, pipe := range currentPipes {
@ -237,7 +233,7 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
style: getStyle(commit), style: getStyle(commit),
}) })
takenSpots[availablePos] = true takenSpots.Add(availablePos)
} }
} }
@ -246,7 +242,7 @@ func getNextPipes(prevPipes []*Pipe, commit *models.Commit, getStyle func(c *mod
// continuing on, potentially moving left to fill in a blank spot // continuing on, potentially moving left to fill in a blank spot
last := pipe.toPos last := pipe.toPos
for i := pipe.toPos; i > pos; i-- { for i := pipe.toPos; i > pos; i-- {
if takenSpots[i] || traversedSpots[i] { if takenSpots.Includes(i) || traversedSpots.Includes(i) {
break break
} else { } else {
last = i last = i
@ -297,10 +293,9 @@ func renderPipeSet(
} }
isMerge := startCount > 1 isMerge := startCount > 1
cells := make([]*Cell, maxPos+1) cells := slices.Map(lo.Range(maxPos+1), func(i int) *Cell {
for i := range cells { return &Cell{cellType: CONNECTION, style: style.FgDefault}
cells[i] = &Cell{cellType: CONNECTION, style: style.FgDefault} })
}
renderPipe := func(pipe *Pipe, style style.TextStyle, overrideRightStyle bool) { renderPipe := func(pipe *Pipe, style style.TextStyle, overrideRightStyle bool) {
left := pipe.left() left := pipe.left()
@ -336,17 +331,9 @@ func renderPipeSet(
// so we have our commit pos again, now it's time to build the cells. // so we have our commit pos again, now it's time to build the cells.
// we'll handle the one that's sourced from our selected commit last so that it can override the other cells. // we'll handle the one that's sourced from our selected commit last so that it can override the other cells.
selectedPipes := []*Pipe{} selectedPipes, nonSelectedPipes := slices.Partition(pipes, func(pipe *Pipe) bool {
// pre-allocating this one because most of the time we'll only have non-selected pipes return highlight && equalHashes(pipe.fromSha, selectedCommitSha)
nonSelectedPipes := make([]*Pipe, 0, len(pipes)) })
for _, pipe := range pipes {
if highlight && equalHashes(pipe.fromSha, selectedCommitSha) {
selectedPipes = append(selectedPipes, pipe)
} else {
nonSelectedPipes = append(nonSelectedPipes, pipe)
}
}
for _, pipe := range nonSelectedPipes { for _, pipe := range nonSelectedPipes {
if pipe.kind == STARTS { if pipe.kind == STARTS {

View File

@ -2,6 +2,7 @@ package presentation
import ( import (
"github.com/jesseduffield/generics/set" "github.com/jesseduffield/generics/set"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
@ -10,8 +11,6 @@ import (
) )
func GetReflogCommitListDisplayStrings(commits []*models.Commit, fullDescription bool, cherryPickedCommitShaSet *set.Set[string], diffName string, parseEmoji bool) [][]string { func GetReflogCommitListDisplayStrings(commits []*models.Commit, fullDescription bool, cherryPickedCommitShaSet *set.Set[string], diffName string, parseEmoji bool) [][]string {
lines := make([][]string, len(commits))
var displayFunc func(*models.Commit, bool, bool, bool) []string var displayFunc func(*models.Commit, bool, bool, bool) []string
if fullDescription { if fullDescription {
displayFunc = getFullDescriptionDisplayStringsForReflogCommit displayFunc = getFullDescriptionDisplayStringsForReflogCommit
@ -19,13 +18,11 @@ func GetReflogCommitListDisplayStrings(commits []*models.Commit, fullDescription
displayFunc = getDisplayStringsForReflogCommit displayFunc = getDisplayStringsForReflogCommit
} }
for i := range commits { return slices.Map(commits, func(commit *models.Commit) []string {
diffed := commits[i].Sha == diffName diffed := commit.Sha == diffName
cherryPicked := cherryPickedCommitShaSet.Includes(commits[i].Sha) cherryPicked := cherryPickedCommitShaSet.Includes(commit.Sha)
lines[i] = displayFunc(commits[i], cherryPicked, diffed, parseEmoji) return displayFunc(commit, cherryPicked, diffed, parseEmoji)
} })
return lines
} }
func reflogShaColor(cherryPicked, diffed bool) style.TextStyle { func reflogShaColor(cherryPicked, diffed bool) style.TextStyle {

View File

@ -1,19 +1,16 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
) )
func GetRemoteBranchListDisplayStrings(branches []*models.RemoteBranch, diffName string) [][]string { func GetRemoteBranchListDisplayStrings(branches []*models.RemoteBranch, diffName string) [][]string {
lines := make([][]string, len(branches)) return slices.Map(branches, func(branch *models.RemoteBranch) []string {
diffed := branch.FullName() == diffName
for i := range branches { return getRemoteBranchDisplayStrings(branch, diffed)
diffed := branches[i].FullName() == diffName })
lines[i] = getRemoteBranchDisplayStrings(branches[i], diffed)
}
return lines
} }
// getRemoteBranchDisplayStrings returns the display string of branch // getRemoteBranchDisplayStrings returns the display string of branch

View File

@ -1,20 +1,17 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
) )
func GetRemoteListDisplayStrings(remotes []*models.Remote, diffName string) [][]string { func GetRemoteListDisplayStrings(remotes []*models.Remote, diffName string) [][]string {
lines := make([][]string, len(remotes)) return slices.Map(remotes, func(remote *models.Remote) []string {
diffed := remote.Name == diffName
for i := range remotes { return getRemoteDisplayStrings(remote, diffed)
diffed := remotes[i].Name == diffName })
lines[i] = getRemoteDisplayStrings(remotes[i], diffed)
}
return lines
} }
// getRemoteDisplayStrings returns the display string of branch // getRemoteDisplayStrings returns the display string of branch

View File

@ -1,19 +1,16 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
) )
func GetStashEntryListDisplayStrings(stashEntries []*models.StashEntry, diffName string) [][]string { func GetStashEntryListDisplayStrings(stashEntries []*models.StashEntry, diffName string) [][]string {
lines := make([][]string, len(stashEntries)) return slices.Map(stashEntries, func(stashEntry *models.StashEntry) []string {
diffed := stashEntry.RefName() == diffName
for i := range stashEntries { return getStashEntryDisplayStrings(stashEntry, diffed)
diffed := stashEntries[i].RefName() == diffName })
lines[i] = getStashEntryDisplayStrings(stashEntries[i], diffed)
}
return lines
} }
// getStashEntryDisplayStrings returns the display string of branch // getStashEntryDisplayStrings returns the display string of branch

View File

@ -1,18 +1,15 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
) )
func GetSubmoduleListDisplayStrings(submodules []*models.SubmoduleConfig) [][]string { func GetSubmoduleListDisplayStrings(submodules []*models.SubmoduleConfig) [][]string {
lines := make([][]string, len(submodules)) return slices.Map(submodules, func(submodule *models.SubmoduleConfig) []string {
return getSubmoduleDisplayStrings(submodule)
for i := range submodules { })
lines[i] = getSubmoduleDisplayStrings(submodules[i])
}
return lines
} }
func getSubmoduleDisplayStrings(s *models.SubmoduleConfig) []string { func getSubmoduleDisplayStrings(s *models.SubmoduleConfig) []string {

View File

@ -1,17 +1,14 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
) )
func GetSuggestionListDisplayStrings(suggestions []*types.Suggestion) [][]string { func GetSuggestionListDisplayStrings(suggestions []*types.Suggestion) [][]string {
lines := make([][]string, len(suggestions)) return slices.Map(suggestions, func(suggestion *types.Suggestion) []string {
return getSuggestionDisplayStrings(suggestion)
for i := range suggestions { })
lines[i] = getSuggestionDisplayStrings(suggestions[i])
}
return lines
} }
func getSuggestionDisplayStrings(suggestion *types.Suggestion) []string { func getSuggestionDisplayStrings(suggestion *types.Suggestion) []string {

View File

@ -1,19 +1,16 @@
package presentation package presentation
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/theme"
) )
func GetTagListDisplayStrings(tags []*models.Tag, diffName string) [][]string { func GetTagListDisplayStrings(tags []*models.Tag, diffName string) [][]string {
lines := make([][]string, len(tags)) return slices.Map(tags, func(tag *models.Tag) []string {
diffed := tag.Name == diffName
for i := range tags { return getTagDisplayStrings(tag, diffed)
diffed := tags[i].Name == diffName })
lines[i] = getTagDisplayStrings(tags[i], diffed)
}
return lines
} }
// getTagDisplayStrings returns the display string of branch // getTagDisplayStrings returns the display string of branch

View File

@ -4,22 +4,19 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/env" "github.com/jesseduffield/lazygit/pkg/env"
"github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
) )
func (gui *Gui) handleCreateRecentReposMenu() error { func (gui *Gui) handleCreateRecentReposMenu() error {
recentRepoPaths := gui.c.GetAppState().RecentRepos recentRepoPaths := gui.c.GetAppState().RecentRepos
reposCount := utils.Min(len(recentRepoPaths), 20)
// we won't show the current repo hence the -1 // we won't show the current repo hence the -1
menuItems := make([]*types.MenuItem, reposCount-1) menuItems := slices.Map(recentRepoPaths[1:], func(path string) *types.MenuItem {
for i, path := range recentRepoPaths[1:reposCount] { return &types.MenuItem{
path := path // cos we're closing over the loop variable
menuItems[i] = &types.MenuItem{
DisplayStrings: []string{ DisplayStrings: []string{
filepath.Base(path), filepath.Base(path),
style.FgMagenta.Sprint(path), style.FgMagenta.Sprint(path),
@ -31,7 +28,7 @@ func (gui *Gui) handleCreateRecentReposMenu() error {
return gui.dispatchSwitchToRepo(path, false) return gui.dispatchSwitchToRepo(path, false)
}, },
} }
} })
return gui.c.Menu(types.CreateMenuOptions{Title: gui.c.Tr.RecentRepos, Items: menuItems}) return gui.c.Menu(types.CreateMenuOptions{Title: gui.c.Tr.RecentRepos, Items: menuItems})
} }

View File

@ -6,6 +6,7 @@ import (
"sync" "sync"
"github.com/jesseduffield/generics/set" "github.com/jesseduffield/generics/set"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/loaders" "github.com/jesseduffield/lazygit/pkg/commands/loaders"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/types/enums" "github.com/jesseduffield/lazygit/pkg/commands/types/enums"
@ -32,12 +33,9 @@ func getScopeNames(scopes []types.RefreshableView) []string {
types.BISECT_INFO: "bisect", types.BISECT_INFO: "bisect",
} }
scopeNames := make([]string, len(scopes)) return slices.Map(scopes, func(scope types.RefreshableView) string {
for i, scope := range scopes { return scopeNameMap[scope]
scopeNames[i] = scopeNameMap[scope] })
}
return scopeNames
} }
func getModeName(mode types.RefreshMode) string { func getModeName(mode types.RefreshMode) string {

View File

@ -1,6 +1,7 @@
package custom_commands package custom_commands
import ( import (
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/config"
@ -99,16 +100,14 @@ func (self *HandlerCreator) inputPrompt(prompt *config.CustomCommandPrompt, wrap
} }
func (self *HandlerCreator) menuPrompt(prompt *config.CustomCommandPrompt, wrappedF func(string) error) error { func (self *HandlerCreator) menuPrompt(prompt *config.CustomCommandPrompt, wrappedF func(string) error) error {
menuItems := make([]*types.MenuItem, len(prompt.Options)) menuItems := slices.Map(prompt.Options, func(option config.CustomCommandMenuOption) *types.MenuItem {
for i, option := range prompt.Options { return &types.MenuItem{
option := option
menuItems[i] = &types.MenuItem{
DisplayStrings: []string{option.Name, style.FgYellow.Sprint(option.Description)}, DisplayStrings: []string{option.Name, style.FgYellow.Sprint(option.Description)},
OnPress: func() error { OnPress: func() error {
return wrappedF(option.Value) return wrappedF(option.Value)
}, },
} }
} })
return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems}) return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems})
} }
@ -126,16 +125,14 @@ func (self *HandlerCreator) menuPromptFromCommand(prompt *config.CustomCommandPr
return self.c.Error(err) return self.c.Error(err)
} }
menuItems := make([]*types.MenuItem, len(candidates)) menuItems := slices.Map(candidates, func(candidate *commandMenuEntry) *types.MenuItem {
for i := range candidates { return &types.MenuItem{
i := i DisplayStrings: []string{candidate.label},
menuItems[i] = &types.MenuItem{
DisplayStrings: []string{candidates[i].label},
OnPress: func() error { OnPress: func() error {
return wrappedF(candidates[i].value) return wrappedF(candidate.value)
}, },
} }
} })
return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems}) return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems})
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/gocui" "github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/context"
@ -77,11 +78,9 @@ func (self *KeybindingCreator) contextForContextKey(contextKey types.ContextKey)
} }
func formatUnknownContextError(customCommand config.CustomCommand) error { func formatUnknownContextError(customCommand config.CustomCommand) error {
// stupid golang making me build an array of strings for this. allContextKeyStrings := slices.Map(context.AllContextKeys, func(key types.ContextKey) string {
allContextKeyStrings := make([]string, len(context.AllContextKeys)) return string(key)
for i := range context.AllContextKeys { })
allContextKeyStrings[i] = string(context.AllContextKeys[i])
}
return fmt.Errorf("Error when setting custom command keybindings: unknown context: %s. Key: %s, Command: %s.\nPermitted contexts: %s", customCommand.Context, customCommand.Key, customCommand.Command, strings.Join(allContextKeyStrings, ", ")) return fmt.Errorf("Error when setting custom command keybindings: unknown context: %s. Key: %s, Command: %s.\nPermitted contexts: %s", customCommand.Context, customCommand.Key, customCommand.Command, strings.Join(allContextKeyStrings, ", "))
} }

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/jesseduffield/lazygit/pkg/commands/types/enums" "github.com/jesseduffield/lazygit/pkg/commands/types/enums"
"github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/constants"
"github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/presentation"
@ -102,16 +103,15 @@ func (gui *Gui) askForConfigFile(action func(file string) error) error {
case 1: case 1:
return action(confPaths[0]) return action(confPaths[0])
default: default:
menuItems := make([]*types.MenuItem, len(confPaths)) menuItems := slices.Map(confPaths, func(path string) *types.MenuItem {
for i, file := range confPaths { return &types.MenuItem{
i := i DisplayString: path,
menuItems[i] = &types.MenuItem{
DisplayString: file,
OnPress: func() error { OnPress: func() error {
return action(confPaths[i]) return action(path)
}, },
} }
} })
return gui.c.Menu(types.CreateMenuOptions{ return gui.c.Menu(types.CreateMenuOptions{
Title: gui.c.Tr.SelectConfigFile, Title: gui.c.Tr.SelectConfigFile,
Items: menuItems, Items: menuItems,

View File

@ -3,7 +3,9 @@ package utils
import ( import (
"strings" "strings"
"github.com/jesseduffield/generics/slices"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"github.com/samber/lo"
) )
// WithPadding pads a string as much as you want // WithPadding pads a string as much as you want
@ -83,27 +85,20 @@ func getPaddedDisplayStrings(stringArrays [][]string, padWidths []int) string {
} }
func getPadWidths(stringArrays [][]string) []int { func getPadWidths(stringArrays [][]string) []int {
maxWidth := 0 maxWidth := slices.MaxBy(stringArrays, func(stringArray []string) int {
for _, stringArray := range stringArrays { return len(stringArray)
if len(stringArray) > maxWidth { })
maxWidth = len(stringArray)
}
}
if maxWidth-1 < 0 { if maxWidth-1 < 0 {
return []int{} return []int{}
} }
padWidths := make([]int, maxWidth-1) return slices.Map(lo.Range(maxWidth-1), func(i int) int {
for i := range padWidths { return slices.MaxBy(stringArrays, func(stringArray []string) int {
for _, strings := range stringArrays { uncoloredStr := Decolorise(stringArray[i])
uncoloredStr := Decolorise(strings[i])
width := runewidth.StringWidth(uncoloredStr) return runewidth.StringWidth(uncoloredStr)
if width > padWidths[i] { })
padWidths[i] = width })
}
}
}
return padWidths
} }
// TruncateWithEllipsis returns a string, truncated to a certain length, with an ellipsis // TruncateWithEllipsis returns a string, truncated to a certain length, with an ellipsis

View File

@ -3,6 +3,7 @@ package utils
import ( import (
"sort" "sort"
"github.com/jesseduffield/generics/slices"
"github.com/sahilm/fuzzy" "github.com/sahilm/fuzzy"
) )
@ -14,10 +15,7 @@ func FuzzySearch(needle string, haystack []string) []string {
matches := fuzzy.Find(needle, haystack) matches := fuzzy.Find(needle, haystack)
sort.Sort(matches) sort.Sort(matches)
result := make([]string, len(matches)) return slices.Map(matches, func(match fuzzy.Match) string {
for i, match := range matches { return match.Str
result[i] = match.Str })
}
return result
} }

View File

@ -1,6 +1,7 @@
package slices package slices
import ( import (
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
) )
@ -28,14 +29,34 @@ func Every[T any](slice []T, test func(T) bool) bool {
// Produces a new slice, leaves the input slice untouched. // Produces a new slice, leaves the input slice untouched.
func Map[T any, V any](slice []T, f func(T) V) []V { func Map[T any, V any](slice []T, f func(T) V) []V {
result := make([]V, len(slice)) result := make([]V, 0, len(slice))
for i, value := range slice { for _, value := range slice {
result[i] = f(value) result = append(result, f(value))
} }
return result return result
} }
// Produces a new slice, leaves the input slice untouched.
func FlatMap[T any, V any](slice []T, f func(T) []V) []V {
// impossible to know how long this slice will be in the end but the length
// of the original slice is the lower bound
result := make([]V, 0, len(slice))
for _, value := range slice {
result = append(result, f(value)...)
}
return result
}
func Flatten[T any](slice [][]T) []T {
result := make([]T, 0, len(slice))
for _, subSlice := range slice {
result = append(result, subSlice...)
}
return result
}
func MapInPlace[T any](slice []T, f func(T) T) { func MapInPlace[T any](slice []T, f func(T) T) {
for i, value := range slice { for i, value := range slice {
slice[i] = f(value) slice[i] = f(value)
@ -152,3 +173,53 @@ func Shift[T any](slice []T) (T, []T) {
slice = slice[1:] slice = slice[1:]
return value, slice return value, slice
} }
func Partition[T any](slice []T, test func(T) bool) ([]T, []T) {
left := make([]T, 0, len(slice))
right := make([]T, 0, len(slice))
for _, value := range slice {
if test(value) {
left = append(left, value)
} else {
right = append(right, value)
}
}
return left, right
}
func MaxBy[T any, V constraints.Ordered](slice []T, f func(T) V) V {
if len(slice) == 0 {
return zero[V]()
}
max := f(slice[0])
for _, element := range slice[1:] {
value := f(element)
if value > max {
max = value
}
}
return max
}
func MinBy[T any, V constraints.Ordered](slice []T, f func(T) V) V {
if len(slice) == 0 {
return zero[V]()
}
min := f(slice[0])
for _, element := range slice[1:] {
value := f(element)
if value < min {
min = value
}
}
return min
}
func zero[T any]() T {
var value T
return value
}

2
vendor/modules.txt vendored
View File

@ -120,7 +120,7 @@ github.com/integrii/flaggy
# github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 # github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99
## explicit ## explicit
github.com/jbenet/go-context/io github.com/jbenet/go-context/io
# github.com/jesseduffield/generics v0.0.0-20220319062156-fa5cb8bde518 # github.com/jesseduffield/generics v0.0.0-20220319080325-a60171f800d5
## explicit; go 1.18 ## explicit; go 1.18
github.com/jesseduffield/generics/maps github.com/jesseduffield/generics/maps
github.com/jesseduffield/generics/set github.com/jesseduffield/generics/set