repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/file_node.go
pkg/gui/filetree/file_node.go
package filetree import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/mergeconflicts" ) // FileNode wraps a node and provides some file-specific methods for it. type FileNode struct { *Node[models.File] } var _ models.IFile = &FileNode{} func NewFileNode(node *Node[models.File]) *FileNode { if node == nil { return nil } return &FileNode{Node: node} } // returns the underlying node, without any file-specific methods attached func (self *FileNode) Raw() *Node[models.File] { if self == nil { return nil } return self.Node } func (self *FileNode) GetHasUnstagedChanges() bool { return self.SomeFile(func(file *models.File) bool { return file.HasUnstagedChanges }) } func (self *FileNode) GetHasStagedOrTrackedChanges() bool { if !self.GetHasStagedChanges() { return self.SomeFile(func(t *models.File) bool { return t.Tracked }) } return true } func (self *FileNode) GetHasStagedChanges() bool { return self.SomeFile(func(file *models.File) bool { return file.HasStagedChanges }) } func (self *FileNode) GetHasInlineMergeConflicts() bool { return self.SomeFile(func(file *models.File) bool { if !file.HasInlineMergeConflicts { return false } hasConflicts, _ := mergeconflicts.FileHasConflictMarkers(file.Path) return hasConflicts }) } func (self *FileNode) GetIsTracked() bool { return self.SomeFile(func(file *models.File) bool { return file.Tracked }) } func (self *FileNode) GetIsFile() bool { return self.IsFile() } func (self *FileNode) GetPreviousPath() string { if self.File == nil { return "" } return self.File.PreviousPath }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/file_tree.go
pkg/gui/filetree/file_tree.go
package filetree import ( "fmt" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type FileTreeDisplayFilter int const ( DisplayAll FileTreeDisplayFilter = iota DisplayStaged DisplayUnstaged DisplayTracked DisplayUntracked // this shows files with merge conflicts DisplayConflicted ) type ITree[T any] interface { InTreeMode() bool ExpandToPath(path string) ToggleShowTree() GetIndexForPath(path string) (int, bool) Len() int GetItem(index int) types.HasUrn SetTree() IsCollapsed(path string) bool ToggleCollapsed(path string) CollapsedPaths() *CollapsedPaths CollapseAll() ExpandAll() } type IFileTree interface { ITree[models.File] FilterFiles(test func(*models.File) bool) []*models.File SetStatusFilter(filter FileTreeDisplayFilter) ForceShowUntracked() bool Get(index int) *FileNode GetFile(path string) *models.File GetAllItems() []*FileNode GetAllFiles() []*models.File GetFilter() FileTreeDisplayFilter GetRoot() *FileNode } type FileTree struct { getFiles func() []*models.File tree *Node[models.File] showTree bool common *common.Common filter FileTreeDisplayFilter collapsedPaths *CollapsedPaths } var _ IFileTree = &FileTree{} func NewFileTree(getFiles func() []*models.File, common *common.Common, showTree bool) *FileTree { return &FileTree{ getFiles: getFiles, common: common, showTree: showTree, filter: DisplayAll, collapsedPaths: NewCollapsedPaths(), } } func (self *FileTree) InTreeMode() bool { return self.showTree } func (self *FileTree) ExpandToPath(path string) { self.collapsedPaths.ExpandToPath(path) } func (self *FileTree) getFilesForDisplay() []*models.File { switch self.filter { case DisplayAll: return self.getFiles() case DisplayStaged: return self.FilterFiles(func(file *models.File) bool { return file.HasStagedChanges }) case DisplayUnstaged: return self.FilterFiles(func(file *models.File) bool { return file.HasUnstagedChanges }) case DisplayTracked: // untracked but staged files are technically not tracked by git // but including such files in the filtered mode helps see what files are getting committed return self.FilterFiles(func(file *models.File) bool { return file.Tracked || file.HasStagedChanges }) case DisplayUntracked: return self.FilterFiles(func(file *models.File) bool { return !(file.Tracked || file.HasStagedChanges) }) case DisplayConflicted: return self.FilterFiles(func(file *models.File) bool { return file.HasMergeConflicts }) default: panic(fmt.Sprintf("Unexpected files display filter: %d", self.filter)) } } func (self *FileTree) ForceShowUntracked() bool { return self.filter == DisplayUntracked } func (self *FileTree) FilterFiles(test func(*models.File) bool) []*models.File { return lo.Filter(self.getFiles(), func(file *models.File, _ int) bool { return test(file) }) } func (self *FileTree) SetStatusFilter(filter FileTreeDisplayFilter) { self.filter = filter self.SetTree() } func (self *FileTree) ToggleShowTree() { self.showTree = !self.showTree self.SetTree() } func (self *FileTree) Get(index int) *FileNode { // need to traverse the tree depth first until we get to the index. return NewFileNode(self.tree.GetNodeAtIndex(index+1, self.collapsedPaths)) // ignoring root } func (self *FileTree) GetFile(path string) *models.File { for _, file := range self.getFiles() { if file.Path == path { return file } } return nil } func (self *FileTree) GetIndexForPath(path string) (int, bool) { index, found := self.tree.GetIndexForPath(path, self.collapsedPaths) return index - 1, found } // note: this gets all items when the filter is taken into consideration. There may // be hidden files that aren't included here. Files off the screen however will // be included func (self *FileTree) GetAllItems() []*FileNode { if self.tree == nil { return nil } // ignoring root return lo.Map(self.tree.Flatten(self.collapsedPaths)[1:], func(node *Node[models.File], _ int) *FileNode { return NewFileNode(node) }) } func (self *FileTree) Len() int { // -1 because we're ignoring the root return max(self.tree.Size(self.collapsedPaths)-1, 0) } func (self *FileTree) GetItem(index int) types.HasUrn { // Unimplemented because we don't yet need to show inlines statuses in commit file views return nil } func (self *FileTree) GetAllFiles() []*models.File { return self.getFiles() } func (self *FileTree) SetTree() { filesForDisplay := self.getFilesForDisplay() showRootItem := self.common.UserConfig().Gui.ShowRootItemInFileTree if self.showTree { self.tree = BuildTreeFromFiles(filesForDisplay, showRootItem) } else { self.tree = BuildFlatTreeFromFiles(filesForDisplay, showRootItem) } } func (self *FileTree) IsCollapsed(path string) bool { return self.collapsedPaths.IsCollapsed(path) } func (self *FileTree) ToggleCollapsed(path string) { self.collapsedPaths.ToggleCollapsed(path) } func (self *FileTree) CollapseAll() { dirPaths := lo.FilterMap(self.GetAllItems(), func(file *FileNode, index int) (string, bool) { return file.path, !file.IsFile() }) for _, path := range dirPaths { self.collapsedPaths.Collapse(path) } } func (self *FileTree) ExpandAll() { self.collapsedPaths.ExpandAll() } func (self *FileTree) Tree() *FileNode { return NewFileNode(self.tree) } func (self *FileTree) GetRoot() *FileNode { return NewFileNode(self.tree) } func (self *FileTree) CollapsedPaths() *CollapsedPaths { return self.collapsedPaths } func (self *FileTree) GetFilter() FileTreeDisplayFilter { return self.filter }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/file_tree_view_model.go
pkg/gui/filetree/file_tree_view_model.go
package filetree import ( "strings" "sync" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/context/traits" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type IFileTreeViewModel interface { IFileTree types.IListCursor } // This combines our FileTree struct with a cursor that retains information about // which item is selected. It also contains logic for repositioning that cursor // after the files are refreshed type FileTreeViewModel struct { sync.RWMutex types.IListCursor IFileTree } var _ IFileTreeViewModel = &FileTreeViewModel{} func NewFileTreeViewModel(getFiles func() []*models.File, common *common.Common, showTree bool) *FileTreeViewModel { fileTree := NewFileTree(getFiles, common, showTree) listCursor := traits.NewListCursor(fileTree.Len) return &FileTreeViewModel{ IFileTree: fileTree, IListCursor: listCursor, } } func (self *FileTreeViewModel) GetSelected() *FileNode { if self.Len() == 0 { return nil } return self.Get(self.GetSelectedLineIdx()) } func (self *FileTreeViewModel) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.ID() } func (self *FileTreeViewModel) GetSelectedItems() ([]*FileNode, int, int) { if self.Len() == 0 { return nil, 0, 0 } startIdx, endIdx := self.GetSelectionRange() nodes := []*FileNode{} for i := startIdx; i <= endIdx; i++ { nodes = append(nodes, self.Get(i)) } return nodes, startIdx, endIdx } func (self *FileTreeViewModel) GetSelectedItemIds() ([]string, int, int) { selectedItems, startIdx, endIdx := self.GetSelectedItems() ids := lo.Map(selectedItems, func(item *FileNode, _ int) string { return item.ID() }) return ids, startIdx, endIdx } func (self *FileTreeViewModel) GetSelectedFile() *models.File { node := self.GetSelected() if node == nil { return nil } return node.File } func (self *FileTreeViewModel) GetSelectedPath() string { node := self.GetSelected() if node == nil { return "" } return node.GetPath() } func (self *FileTreeViewModel) SetTree() { newFiles := self.GetAllFiles() selectedNode := self.GetSelected() // for when you stage the old file of a rename and the new file is in a collapsed dir for _, file := range newFiles { if selectedNode != nil && selectedNode.path != "" && file.PreviousPath == selectedNode.path { self.ExpandToPath(file.Path) } } prevNodes := self.GetAllItems() prevSelectedLineIdx := self.GetSelectedLineIdx() self.IFileTree.SetTree() if selectedNode != nil { newNodes := self.GetAllItems() newIdx := self.findNewSelectedIdx(prevNodes[prevSelectedLineIdx:], newNodes) if newIdx != -1 && newIdx != prevSelectedLineIdx { self.SetSelection(newIdx) } } self.ClampSelection() } // Let's try to find our file again and move the cursor to that. // If we can't find our file, it was probably just removed by the user. In that // case, we go looking for where the next file has been moved to. Given that the // user could have removed a whole directory, we continue iterating through the old // nodes until we find one that exists in the new set of nodes, then move the cursor // to that. // prevNodes starts from our previously selected node because we don't need to consider anything above that func (self *FileTreeViewModel) findNewSelectedIdx(prevNodes []*FileNode, currNodes []*FileNode) int { getPaths := func(node *FileNode) []string { if node == nil { return nil } if node.File != nil && node.File.IsRename() { return node.File.Names() } return []string{node.path} } for _, prevNode := range prevNodes { selectedPaths := getPaths(prevNode) for idx, node := range currNodes { paths := getPaths(node) // If you started off with a rename selected, and now it's broken in two, we want you to jump to the new file, not the old file. // This is because the new should be in the same position as the rename was meaning less cursor jumping foundOldFileInRename := prevNode.File != nil && prevNode.File.IsRename() && node.path == prevNode.File.PreviousPath foundNode := utils.StringArraysOverlap(paths, selectedPaths) && !foundOldFileInRename if foundNode { return idx } } } return -1 } func (self *FileTreeViewModel) SetStatusFilter(filter FileTreeDisplayFilter) { self.IFileTree.SetStatusFilter(filter) self.IListCursor.SetSelection(0) } // If we're going from flat to tree we want to select the same file. // If we're going from tree to flat and we have a file selected we want to select that. // If instead we've selected a directory we need to select the first file in that directory. func (self *FileTreeViewModel) ToggleShowTree() { selectedNode := self.GetSelected() self.IFileTree.ToggleShowTree() if selectedNode == nil { return } path := selectedNode.path if self.InTreeMode() { self.ExpandToPath(path) } else if len(selectedNode.Children) > 0 { path = selectedNode.GetLeaves()[0].path } index, found := self.GetIndexForPath(path) if found { self.SetSelectedLineIdx(index) } } func (self *FileTreeViewModel) CollapseAll() { selectedNode := self.GetSelected() self.IFileTree.CollapseAll() if selectedNode == nil { return } topLevelPath := strings.Split(selectedNode.path, "/")[0] index, found := self.GetIndexForPath(topLevelPath) if found { self.SetSelectedLineIdx(index) } } func (self *FileTreeViewModel) ExpandAll() { selectedNode := self.GetSelected() self.IFileTree.ExpandAll() if selectedNode == nil { return } index, found := self.GetIndexForPath(selectedNode.path) if found { self.SetSelectedLineIdx(index) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/commit_file_node.go
pkg/gui/filetree/commit_file_node.go
package filetree import "github.com/jesseduffield/lazygit/pkg/commands/models" // CommitFileNode wraps a node and provides some commit-file-specific methods for it. type CommitFileNode struct { *Node[models.CommitFile] } func NewCommitFileNode(node *Node[models.CommitFile]) *CommitFileNode { if node == nil { return nil } return &CommitFileNode{Node: node} } // returns the underlying node, without any commit-file-specific methods attached func (self *CommitFileNode) Raw() *Node[models.CommitFile] { if self == nil { return nil } return self.Node }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/build_tree_test.go
pkg/gui/filetree/build_tree_test.go
package filetree import ( "testing" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/stretchr/testify/assert" ) func TestBuildTreeFromFiles(t *testing.T) { scenarios := []struct { name string files []*models.File showRootItem bool expected *Node[models.File] }{ { name: "no files", files: []*models.File{}, expected: &Node[models.File]{ path: "", Children: nil, }, }, { name: "files in same directory", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: "./dir1", CompressionLevel: 1, Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "./dir1/a", }, { File: &models.File{Path: "dir1/b"}, path: "./dir1/b", }, }, }, }, }, }, { name: "files in same directory, not root item", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: false, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: "dir1", CompressionLevel: 0, Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "dir1/a", }, { File: &models.File{Path: "dir1/b"}, path: "dir1/b", }, }, }, }, }, }, { name: "paths that can be compressed", files: []*models.File{ { Path: "dir1/dir3/a", }, { Path: "dir2/dir4/b", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: ".", Children: []*Node[models.File]{ { path: "./dir1/dir3", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/dir3/a"}, path: "./dir1/dir3/a", }, }, CompressionLevel: 1, }, { path: "./dir2/dir4", Children: []*Node[models.File]{ { File: &models.File{Path: "dir2/dir4/b"}, path: "./dir2/dir4/b", }, }, CompressionLevel: 1, }, }, }, }, }, }, { name: "paths that can be compressed, no root item", files: []*models.File{ { Path: "dir1/dir3/a", }, { Path: "dir2/dir4/b", }, }, showRootItem: false, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: "dir1/dir3", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/dir3/a"}, path: "dir1/dir3/a", }, }, CompressionLevel: 1, }, { path: "dir2/dir4", Children: []*Node[models.File]{ { File: &models.File{Path: "dir2/dir4/b"}, path: "dir2/dir4/b", }, }, CompressionLevel: 1, }, }, }, }, { name: "paths that can be sorted", files: []*models.File{ { Path: "b", }, { Path: "a", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: ".", Children: []*Node[models.File]{ { File: &models.File{Path: "a"}, path: "./a", }, { File: &models.File{Path: "b"}, path: "./b", }, }, }, }, }, }, { name: "paths that can be sorted including a merge conflict file", files: []*models.File{ { Path: "b", }, { Path: "z", HasMergeConflicts: true, }, { Path: "a", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: ".", // it is a little strange that we're not bubbling up our merge conflict // here but we are technically still in tree mode and that's the rule Children: []*Node[models.File]{ { File: &models.File{Path: "a"}, path: "./a", }, { File: &models.File{Path: "b"}, path: "./b", }, { File: &models.File{Path: "z", HasMergeConflicts: true}, path: "./z", }, }, }, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { result := BuildTreeFromFiles(s.files, s.showRootItem) assert.EqualValues(t, s.expected, result) }) } } func TestBuildFlatTreeFromFiles(t *testing.T) { scenarios := []struct { name string files []*models.File showRootItem bool expected *Node[models.File] }{ { name: "no files", files: []*models.File{}, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{}, }, }, { name: "files in same directory", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "./dir1/a", CompressionLevel: 0, }, { File: &models.File{Path: "dir1/b"}, path: "./dir1/b", CompressionLevel: 0, }, }, }, }, { name: "files in same directory, not root item", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: false, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "dir1/a", CompressionLevel: 0, }, { File: &models.File{Path: "dir1/b"}, path: "dir1/b", CompressionLevel: 0, }, }, }, }, { name: "paths that can be compressed", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir2/b", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "./dir1/a", CompressionLevel: 0, }, { File: &models.File{Path: "dir2/b"}, path: "./dir2/b", CompressionLevel: 0, }, }, }, }, { name: "paths that can be compressed, no root item", files: []*models.File{ { Path: "dir1/a", }, { Path: "dir2/b", }, }, showRootItem: false, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "dir1/a"}, path: "dir1/a", CompressionLevel: 0, }, { File: &models.File{Path: "dir2/b"}, path: "dir2/b", CompressionLevel: 0, }, }, }, }, { name: "paths that can be sorted", files: []*models.File{ { Path: "b", }, { Path: "a", }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "a"}, path: "./a", }, { File: &models.File{Path: "b"}, path: "./b", }, }, }, }, { name: "tracked, untracked, and conflicted files", files: []*models.File{ { Path: "a2", Tracked: false, }, { Path: "a1", Tracked: false, }, { Path: "c2", HasMergeConflicts: true, }, { Path: "c1", HasMergeConflicts: true, }, { Path: "b2", Tracked: true, }, { Path: "b1", Tracked: true, }, }, showRootItem: true, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { File: &models.File{Path: "c1", HasMergeConflicts: true}, path: "./c1", }, { File: &models.File{Path: "c2", HasMergeConflicts: true}, path: "./c2", }, { File: &models.File{Path: "b1", Tracked: true}, path: "./b1", }, { File: &models.File{Path: "b2", Tracked: true}, path: "./b2", }, { File: &models.File{Path: "a1", Tracked: false}, path: "./a1", }, { File: &models.File{Path: "a2", Tracked: false}, path: "./a2", }, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { result := BuildFlatTreeFromFiles(s.files, s.showRootItem) assert.EqualValues(t, s.expected, result) }) } } func TestBuildTreeFromCommitFiles(t *testing.T) { scenarios := []struct { name string files []*models.CommitFile showRootItem bool expected *Node[models.CommitFile] }{ { name: "no files", files: []*models.CommitFile{}, expected: &Node[models.CommitFile]{ path: "", Children: nil, }, }, { name: "files in same directory", files: []*models.CommitFile{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { path: "./dir1", CompressionLevel: 1, Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/a"}, path: "./dir1/a", }, { File: &models.CommitFile{Path: "dir1/b"}, path: "./dir1/b", }, }, }, }, }, }, { name: "files in same directory, not root item", files: []*models.CommitFile{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: false, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { path: "dir1", CompressionLevel: 0, Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/a"}, path: "dir1/a", }, { File: &models.CommitFile{Path: "dir1/b"}, path: "dir1/b", }, }, }, }, }, }, { name: "paths that can be compressed", files: []*models.CommitFile{ { Path: "dir1/dir3/a", }, { Path: "dir2/dir4/b", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { path: ".", Children: []*Node[models.CommitFile]{ { path: "./dir1/dir3", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/dir3/a"}, path: "./dir1/dir3/a", }, }, CompressionLevel: 1, }, { path: "./dir2/dir4", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir2/dir4/b"}, path: "./dir2/dir4/b", }, }, CompressionLevel: 1, }, }, }, }, }, }, { name: "paths that can be compressed, no root item", files: []*models.CommitFile{ { Path: "dir1/dir3/a", }, { Path: "dir2/dir4/b", }, }, showRootItem: false, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { path: "dir1/dir3", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/dir3/a"}, path: "dir1/dir3/a", }, }, CompressionLevel: 1, }, { path: "dir2/dir4", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir2/dir4/b"}, path: "dir2/dir4/b", }, }, CompressionLevel: 1, }, }, }, }, { name: "paths that can be sorted", files: []*models.CommitFile{ { Path: "b", }, { Path: "a", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { path: ".", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "a"}, path: "./a", }, { File: &models.CommitFile{Path: "b"}, path: "./b", }, }, }, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { result := BuildTreeFromCommitFiles(s.files, s.showRootItem) assert.EqualValues(t, s.expected, result) }) } } func TestBuildFlatTreeFromCommitFiles(t *testing.T) { scenarios := []struct { name string files []*models.CommitFile showRootItem bool expected *Node[models.CommitFile] }{ { name: "no files", files: []*models.CommitFile{}, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{}, }, }, { name: "files in same directory", files: []*models.CommitFile{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/a"}, path: "./dir1/a", CompressionLevel: 0, }, { File: &models.CommitFile{Path: "dir1/b"}, path: "./dir1/b", CompressionLevel: 0, }, }, }, }, { name: "files in same directory, not root item", files: []*models.CommitFile{ { Path: "dir1/a", }, { Path: "dir1/b", }, }, showRootItem: false, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/a"}, path: "dir1/a", CompressionLevel: 0, }, { File: &models.CommitFile{Path: "dir1/b"}, path: "dir1/b", CompressionLevel: 0, }, }, }, }, { name: "paths that can be compressed", files: []*models.CommitFile{ { Path: "dir1/a", }, { Path: "dir2/b", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "dir1/a"}, path: "./dir1/a", CompressionLevel: 0, }, { File: &models.CommitFile{Path: "dir2/b"}, path: "./dir2/b", CompressionLevel: 0, }, }, }, }, { name: "paths that can be sorted", files: []*models.CommitFile{ { Path: "b", }, { Path: "a", }, }, showRootItem: true, expected: &Node[models.CommitFile]{ path: "", Children: []*Node[models.CommitFile]{ { File: &models.CommitFile{Path: "a"}, path: "./a", }, { File: &models.CommitFile{Path: "b"}, path: "./b", }, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { result := BuildFlatTreeFromCommitFiles(s.files, s.showRootItem) assert.EqualValues(t, s.expected, result) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/file_node_test.go
pkg/gui/filetree/file_node_test.go
package filetree import ( "testing" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/stretchr/testify/assert" ) func TestCompress(t *testing.T) { scenarios := []struct { name string root *Node[models.File] expected *Node[models.File] }{ { name: "nil node", root: nil, expected: nil, }, { name: "leaf node", root: &Node[models.File]{ path: "", Children: []*Node[models.File]{ {File: &models.File{Path: "test", ShortStatus: " M", HasStagedChanges: true}, path: "test"}, }, }, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ {File: &models.File{Path: "test", ShortStatus: " M", HasStagedChanges: true}, path: "test"}, }, }, }, { name: "big example", root: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: "dir1", Children: []*Node[models.File]{ { File: &models.File{Path: "file2", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir1/file2", }, }, }, { path: "dir2", Children: []*Node[models.File]{ { File: &models.File{Path: "file3", ShortStatus: " M", HasStagedChanges: true}, path: "dir2/file3", }, { File: &models.File{Path: "file4", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir2/file4", }, }, }, { path: "dir3", Children: []*Node[models.File]{ { path: "dir3/dir3-1", Children: []*Node[models.File]{ { File: &models.File{Path: "file5", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir3/dir3-1/file5", }, }, }, }, }, { File: &models.File{Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, path: "file1", }, }, }, expected: &Node[models.File]{ path: "", Children: []*Node[models.File]{ { path: "dir1", Children: []*Node[models.File]{ { File: &models.File{Path: "file2", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir1/file2", }, }, }, { path: "dir2", Children: []*Node[models.File]{ { File: &models.File{Path: "file3", ShortStatus: " M", HasStagedChanges: true}, path: "dir2/file3", }, { File: &models.File{Path: "file4", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir2/file4", }, }, }, { path: "dir3/dir3-1", CompressionLevel: 1, Children: []*Node[models.File]{ { File: &models.File{Path: "file5", ShortStatus: "M ", HasUnstagedChanges: true}, path: "dir3/dir3-1/file5", }, }, }, { File: &models.File{Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, path: "file1", }, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { s.root.Compress() assert.EqualValues(t, s.expected, s.root) }) } } func TestGetFile(t *testing.T) { scenarios := []struct { name string viewModel *FileTree path string expected *models.File }{ { name: "valid case", viewModel: NewFileTree(func() []*models.File { return []*models.File{{Path: "blah/one"}, {Path: "blah/two"}} }, nil, false), path: "blah/two", expected: &models.File{Path: "blah/two"}, }, { name: "not found", viewModel: NewFileTree(func() []*models.File { return []*models.File{{Path: "blah/one"}, {Path: "blah/two"}} }, nil, false), path: "blah/three", expected: nil, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { assert.EqualValues(t, s.expected, s.viewModel.GetFile(s.path)) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/style_test.go
pkg/gui/style/style_test.go
package style import ( "bytes" "testing" "text/template" "github.com/gookit/color" "github.com/stretchr/testify/assert" "github.com/xo/terminfo" ) func TestMerge(t *testing.T) { type scenario struct { name string toMerge []TextStyle expectedStyle TextStyle expectedStr string } fgRed := color.FgRed bgRed := color.BgRed fgBlue := color.FgBlue rgbPinkLib := color.Rgb(0xFF, 0x00, 0xFF) rgbPink := NewRGBColor(rgbPinkLib) rgbYellowLib := color.Rgb(0xFF, 0xFF, 0x00) rgbYellow := NewRGBColor(rgbYellowLib) strToPrint := "foo" scenarios := []scenario{ { "no color", nil, TextStyle{Style: color.Style{}}, "foo", }, { "only fg color", []TextStyle{FgRed}, TextStyle{fg: &Color{basic: &fgRed}, Style: color.Style{fgRed}}, "\x1b[31mfoo\x1b[0m", }, { "only bg color", []TextStyle{BgRed}, TextStyle{bg: &Color{basic: &bgRed}, Style: color.Style{bgRed}}, "\x1b[41mfoo\x1b[0m", }, { "fg and bg color", []TextStyle{FgBlue, BgRed}, TextStyle{ fg: &Color{basic: &fgBlue}, bg: &Color{basic: &bgRed}, Style: color.Style{fgBlue, bgRed}, }, "\x1b[34;41mfoo\x1b[0m", }, { "single attribute", []TextStyle{AttrBold}, TextStyle{ decoration: Decoration{bold: true}, Style: color.Style{color.OpBold}, }, "\x1b[1mfoo\x1b[0m", }, { "multiple attributes", []TextStyle{AttrBold, AttrUnderline}, TextStyle{ decoration: Decoration{ bold: true, underline: true, }, Style: color.Style{color.OpBold, color.OpUnderscore}, }, "\x1b[1;4mfoo\x1b[0m", }, { "multiple attributes and colors", []TextStyle{AttrBold, FgBlue, AttrUnderline, BgRed}, TextStyle{ fg: &Color{basic: &fgBlue}, bg: &Color{basic: &bgRed}, decoration: Decoration{ bold: true, underline: true, }, Style: color.Style{fgBlue, bgRed, color.OpBold, color.OpUnderscore}, }, "\x1b[34;41;1;4mfoo\x1b[0m", }, { "rgb fg color", []TextStyle{New().SetFg(rgbPink)}, TextStyle{ fg: &rgbPink, Style: color.NewRGBStyle(rgbPinkLib).SetOpts(color.Opts{}), }, // '38;2' qualifies an RGB foreground color "\x1b[38;2;255;0;255mfoo\x1b[0m", }, { "rgb fg and bg color", []TextStyle{New().SetFg(rgbPink).SetBg(rgbYellow)}, TextStyle{ fg: &rgbPink, bg: &rgbYellow, Style: color.NewRGBStyle(rgbPinkLib, rgbYellowLib).SetOpts(color.Opts{}), }, // '48;2' qualifies an RGB background color "\x1b[38;2;255;0;255;48;2;255;255;0mfoo\x1b[0m", }, { "rgb fg and bg color with opts", []TextStyle{AttrBold, New().SetFg(rgbPink).SetBg(rgbYellow), AttrUnderline}, TextStyle{ fg: &rgbPink, bg: &rgbYellow, decoration: Decoration{ bold: true, underline: true, }, Style: color.NewRGBStyle(rgbPinkLib, rgbYellowLib).SetOpts(color.Opts{color.OpBold, color.OpUnderscore}), }, "\x1b[38;2;255;0;255;48;2;255;255;0;1;4mfoo\x1b[0m", }, { "mix color-16 (background) with rgb (foreground)", []TextStyle{New().SetFg(rgbYellow), BgRed}, TextStyle{ fg: &rgbYellow, bg: &Color{basic: &bgRed}, Style: color.NewRGBStyle( rgbYellowLib, fgRed.RGB(), // We need to use FG here, https://github.com/gookit/color/issues/39 ).SetOpts(color.Opts{}), }, "\x1b[38;2;255;255;0;48;2;197;30;20mfoo\x1b[0m", }, { "mix color-16 (foreground) with rgb (background)", []TextStyle{FgRed, New().SetBg(rgbYellow)}, TextStyle{ fg: &Color{basic: &fgRed}, bg: &rgbYellow, Style: color.NewRGBStyle( fgRed.RGB(), rgbYellowLib, ).SetOpts(color.Opts{}), }, "\x1b[38;2;197;30;20;48;2;255;255;0mfoo\x1b[0m", }, } oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions) defer color.ForceSetColorLevel(oldColorLevel) for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { style := New() for _, other := range s.toMerge { style = style.MergeStyle(other) } assert.Equal(t, s.expectedStyle, style) assert.Equal(t, s.expectedStr, style.Sprint(strToPrint)) }) } } func TestTemplateFuncMapAddColors(t *testing.T) { type scenario struct { name string tmpl string expect string } scenarios := []scenario{ { "normal template", "{{ .Foo }}", "bar", }, { "colored string", "{{ .Foo | red }}", "\x1b[31mbar\x1b[0m", }, { "string with decorator", "{{ .Foo | bold }}", "\x1b[1mbar\x1b[0m", }, { "string with color and decorator", "{{ .Foo | bold | red }}", "\x1b[31m\x1b[1mbar\x1b[0m\x1b[0m", }, { "multiple string with different colors", "{{ .Foo | red }} - {{ .Foo | blue }}", "\x1b[31mbar\x1b[0m - \x1b[34mbar\x1b[0m", }, } oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions) defer color.ForceSetColorLevel(oldColorLevel) for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { tmpl, err := template.New("test template").Funcs(TemplateFuncMapAddColors(template.FuncMap{})).Parse(s.tmpl) assert.NoError(t, err) buff := bytes.NewBuffer(nil) err = tmpl.Execute(buff, struct{ Foo string }{"bar"}) assert.NoError(t, err) assert.Equal(t, s.expect, buff.String()) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/hyperlink.go
pkg/gui/style/hyperlink.go
package style import "fmt" // Render the given text as an OSC 8 hyperlink func PrintHyperlink(text string, link string) string { return fmt.Sprintf("\033]8;;%s\033\\%s\033]8;;\033\\", link, text) } // Render a link where the text is the same as a link func PrintSimpleHyperlink(link string) string { return fmt.Sprintf("\033]8;;%s\033\\%s\033]8;;\033\\", link, link) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/decoration.go
pkg/gui/style/decoration.go
package style import "github.com/gookit/color" type Decoration struct { bold bool underline bool reverse bool strikethrough bool } func (d *Decoration) SetBold() { d.bold = true } func (d *Decoration) SetUnderline() { d.underline = true } func (d *Decoration) SetReverse() { d.reverse = true } func (d *Decoration) SetStrikethrough() { d.strikethrough = true } func (d Decoration) ToOpts() color.Opts { opts := make([]color.Color, 0, 3) if d.bold { opts = append(opts, color.OpBold) } if d.underline { opts = append(opts, color.OpUnderscore) } if d.reverse { opts = append(opts, color.OpReverse) } if d.strikethrough { opts = append(opts, color.OpStrikethrough) } return opts } func (d Decoration) Merge(other Decoration) Decoration { if other.bold { d.bold = true } if other.underline { d.underline = true } if other.reverse { d.reverse = true } if other.strikethrough { d.strikethrough = true } return d }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/color.go
pkg/gui/style/color.go
package style import "github.com/gookit/color" type Color struct { rgb *color.RGBColor basic *color.Color } func NewRGBColor(cl color.RGBColor) Color { c := Color{} c.rgb = &cl return c } func NewBasicColor(cl color.Color) Color { c := Color{} c.basic = &cl return c } func (c Color) IsRGB() bool { return c.rgb != nil } func (c Color) ToRGB(isBg bool) Color { if c.IsRGB() { return c } if isBg { // We need to convert bg color to fg color // This is a gookit/color bug, // https://github.com/gookit/color/issues/39 return NewRGBColor((*c.basic - 10).RGB()) } return NewRGBColor(c.basic.RGB()) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/text_style.go
pkg/gui/style/text_style.go
package style import ( "github.com/gookit/color" ) // A TextStyle contains a foreground color, background color, and // decorations (bold/underline/reverse). // // Colors may each be either 16-bit or 24-bit RGB colors. When // we need to produce a string with a TextStyle, if either foreground or // background color is RGB, we'll promote the other color component to RGB as well. // We could simplify this code by forcing everything to be RGB, but we're not // sure how compatible or efficient that would be with various terminals. // Lazygit will typically stick to 16-bit colors, but users may configure RGB colors. // // TextStyles are value objects, not entities, so for example if you want to // add the bold decoration to a TextStyle, we'll create a new TextStyle with // that decoration applied. // // Decorations are additive, so when we merge two TextStyles, if either is bold // then the resulting style will also be bold. // // So that we aren't rederiving the underlying style each time we want to print // a string, we derive it when a new TextStyle is created and store it in the // `style` field. type TextStyle struct { fg *Color bg *Color decoration Decoration // making this public so that we can use a type switch to get to the underlying // value so we can cache styles. This is very much a hack. Style Sprinter } type Sprinter interface { Sprint(a ...any) string Sprintf(format string, a ...any) string } func New() TextStyle { s := TextStyle{} s.Style = s.deriveStyle() return s } func (b TextStyle) Sprint(a ...any) string { return b.Style.Sprint(a...) } func (b TextStyle) Sprintf(format string, a ...any) string { return b.Style.Sprintf(format, a...) } // note that our receiver here is not a pointer which means we're receiving a // copy of the original TextStyle. This allows us to mutate and return that // TextStyle receiver without actually modifying the original. func (b TextStyle) SetBold() TextStyle { b.decoration.SetBold() b.Style = b.deriveStyle() return b } func (b TextStyle) SetUnderline() TextStyle { b.decoration.SetUnderline() b.Style = b.deriveStyle() return b } func (b TextStyle) SetReverse() TextStyle { b.decoration.SetReverse() b.Style = b.deriveStyle() return b } func (b TextStyle) SetStrikethrough() TextStyle { b.decoration.SetStrikethrough() b.Style = b.deriveStyle() return b } func (b TextStyle) SetBg(color Color) TextStyle { b.bg = &color b.Style = b.deriveStyle() return b } func (b TextStyle) SetFg(color Color) TextStyle { b.fg = &color b.Style = b.deriveStyle() return b } func (b TextStyle) MergeStyle(other TextStyle) TextStyle { b.decoration = b.decoration.Merge(other.decoration) if other.fg != nil { b.fg = other.fg } if other.bg != nil { b.bg = other.bg } b.Style = b.deriveStyle() return b } func (b TextStyle) deriveStyle() Sprinter { if b.fg == nil && b.bg == nil { return color.Style(b.decoration.ToOpts()) } isRgb := (b.fg != nil && b.fg.IsRGB()) || (b.bg != nil && b.bg.IsRGB()) if isRgb { return b.deriveRGBStyle() } return b.deriveBasicStyle() } func (b TextStyle) deriveBasicStyle() color.Style { style := make([]color.Color, 0, 5) if b.fg != nil { style = append(style, *b.fg.basic) } if b.bg != nil { style = append(style, *b.bg.basic) } style = append(style, b.decoration.ToOpts()...) return color.Style(style) } func (b TextStyle) deriveRGBStyle() *color.RGBStyle { style := &color.RGBStyle{} if b.fg != nil { style.SetFg(*b.fg.ToRGB(false).rgb) } if b.bg != nil { // We need to convert the bg firstly to a foreground color, // For more info see style.SetBg(*b.bg.ToRGB(true).rgb) } style.SetOpts(b.decoration.ToOpts()) return style }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/style/basic_styles.go
pkg/gui/style/basic_styles.go
package style import ( "text/template" "github.com/gookit/color" ) var ( FgWhite = FromBasicFg(color.FgWhite) FgLightWhite = FromBasicFg(color.FgLightWhite) FgBlack = FromBasicFg(color.FgBlack) FgBlackLighter = FromBasicFg(color.FgBlack.Light()) FgCyan = FromBasicFg(color.FgCyan) FgRed = FromBasicFg(color.FgRed) FgGreen = FromBasicFg(color.FgGreen) FgBlue = FromBasicFg(color.FgBlue) FgYellow = FromBasicFg(color.FgYellow) FgMagenta = FromBasicFg(color.FgMagenta) FgDefault = FromBasicFg(color.FgDefault) BgWhite = FromBasicBg(color.BgWhite) BgBlack = FromBasicBg(color.BgBlack) BgRed = FromBasicBg(color.BgRed) BgGreen = FromBasicBg(color.BgGreen) BgYellow = FromBasicBg(color.BgYellow) BgBlue = FromBasicBg(color.BgBlue) BgMagenta = FromBasicBg(color.BgMagenta) BgCyan = FromBasicBg(color.BgCyan) BgDefault = FromBasicBg(color.BgDefault) // will not print any colour escape codes, including the reset escape code Nothing = New() AttrUnderline = New().SetUnderline() AttrBold = New().SetBold() ColorMap = map[string]struct { Foreground TextStyle Background TextStyle }{ "default": {FgDefault, BgDefault}, "black": {FgBlack, BgBlack}, "red": {FgRed, BgRed}, "green": {FgGreen, BgGreen}, "yellow": {FgYellow, BgYellow}, "blue": {FgBlue, BgBlue}, "magenta": {FgMagenta, BgMagenta}, "cyan": {FgCyan, BgCyan}, "white": {FgWhite, BgWhite}, } ) func FromBasicFg(fg color.Color) TextStyle { return New().SetFg(NewBasicColor(fg)) } func FromBasicBg(bg color.Color) TextStyle { return New().SetBg(NewBasicColor(bg)) } func TemplateFuncMapAddColors(m template.FuncMap) template.FuncMap { for k, v := range ColorMap { m[k] = v.Foreground.Sprint } m["underline"] = color.OpUnderscore.Sprint m["bold"] = color.OpBold.Sprint return m }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/merge_conflict.go
pkg/gui/mergeconflicts/merge_conflict.go
package mergeconflicts // mergeConflict : A git conflict with a start, ancestor (if exists), target, and end corresponding to line // numbers in the file where the conflict markers appear. // If no ancestor is present (i.e. we're not using the diff3 algorithm), then // the `ancestor` field's value will be -1 type mergeConflict struct { start int ancestor int target int end int } func (c *mergeConflict) hasAncestor() bool { return c.ancestor >= 0 } func (c *mergeConflict) isMarkerLine(i int) bool { return i == c.start || i == c.ancestor || i == c.target || i == c.end } type Selection int const ( TOP Selection = iota MIDDLE BOTTOM ALL ) func (s Selection) isIndexToKeep(conflict *mergeConflict, i int) bool { // we're only handling one conflict at a time so any lines outside this // conflict we'll keep if i < conflict.start || conflict.end < i { return true } if conflict.isMarkerLine(i) { return false } return s.selected(conflict, i) } func (s Selection) bounds(c *mergeConflict) (int, int) { switch s { case TOP: if c.hasAncestor() { return c.start, c.ancestor } return c.start, c.target case MIDDLE: return c.ancestor, c.target case BOTTOM: return c.target, c.end case ALL: return c.start, c.end } panic("unexpected selection for merge conflict") } func (s Selection) selected(c *mergeConflict, idx int) bool { start, end := s.bounds(c) return start < idx && idx < end } func availableSelections(c *mergeConflict) []Selection { if c.hasAncestor() { return []Selection{TOP, MIDDLE, BOTTOM} } return []Selection{TOP, BOTTOM} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/find_conflicts_test.go
pkg/gui/mergeconflicts/find_conflicts_test.go
package mergeconflicts import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestDetermineLineType(t *testing.T) { type scenario struct { line string expected LineType } scenarios := []scenario{ { line: "", expected: NOT_A_MARKER, }, { line: "blah", expected: NOT_A_MARKER, }, { line: "<<<<<<< HEAD", expected: START, }, { line: "<<<<<<< HEAD:my_branch", expected: START, }, { line: "<<<<<<< MERGE_HEAD:my_branch", expected: START, }, { line: "<<<<<<< Updated upstream:my_branch", expected: START, }, { line: "<<<<<<< ours:my_branch", expected: START, }, { line: "=======", expected: TARGET, }, { line: ">>>>>>> blah", expected: END, }, { line: "||||||| adf33b9", expected: ANCESTOR, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, determineLineType(s.line)) } } func TestFindConflictsAux(t *testing.T) { type scenario struct { content string expected bool } scenarios := []scenario{ { content: "", expected: false, }, { content: "blah", expected: false, }, { content: ">>>>>>> ", expected: true, }, { content: "<<<<<<< ", expected: true, }, { content: " <<<<<<< ", expected: false, }, { content: "a\nb\nc\n<<<<<<< ", expected: true, }, } for _, s := range scenarios { reader := strings.NewReader(s.content) assert.EqualValues(t, s.expected, fileHasConflictMarkersAux(reader)) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/state.go
pkg/gui/mergeconflicts/state.go
package mergeconflicts import ( "strings" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) // State represents the selection state of the merge conflict context. type State struct { // path of the file with the conflicts path string // This is a stack of the file content. It is used to undo changes. // The last item is the current file content. contents []string conflicts []*mergeConflict // this is the index of the above `conflicts` field which is currently selected conflictIndex int // this is the index of the selected conflict's available selections slice e.g. [TOP, MIDDLE, BOTTOM] // We use this to know which hunk of the conflict is selected. selectionIndex int } func NewState() *State { return &State{ conflictIndex: 0, selectionIndex: 0, conflicts: []*mergeConflict{}, contents: []string{}, } } func (s *State) setConflictIndex(index int) { if len(s.conflicts) == 0 { s.conflictIndex = 0 } else { s.conflictIndex = lo.Clamp(index, 0, len(s.conflicts)-1) } s.setSelectionIndex(s.selectionIndex) } func (s *State) setSelectionIndex(index int) { if selections := s.availableSelections(); len(selections) != 0 { s.selectionIndex = lo.Clamp(index, 0, len(selections)-1) } } func (s *State) SelectNextConflictHunk() { s.setSelectionIndex(s.selectionIndex + 1) } func (s *State) SelectPrevConflictHunk() { s.setSelectionIndex(s.selectionIndex - 1) } func (s *State) SelectNextConflict() { s.setConflictIndex(s.conflictIndex + 1) } func (s *State) SelectPrevConflict() { s.setConflictIndex(s.conflictIndex - 1) } func (s *State) currentConflict() *mergeConflict { if len(s.conflicts) == 0 { return nil } return s.conflicts[s.conflictIndex] } // this is for starting a new merge conflict session func (s *State) SetContent(content string, path string) { if content == s.GetContent() && path == s.path { return } s.path = path s.contents = []string{} s.PushContent(content) } // this is for when you've resolved a conflict. This allows you to undo to a previous // state func (s *State) PushContent(content string) { s.contents = append(s.contents, content) s.setConflicts(findConflicts(content)) } func (s *State) GetContent() string { if len(s.contents) == 0 { return "" } return s.contents[len(s.contents)-1] } func (s *State) GetPath() string { return s.path } func (s *State) Undo() bool { if len(s.contents) <= 1 { return false } s.contents = s.contents[:len(s.contents)-1] newContent := s.GetContent() // We could be storing the old conflicts and selected index on a stack too. s.setConflicts(findConflicts(newContent)) return true } func (s *State) setConflicts(conflicts []*mergeConflict) { s.conflicts = conflicts s.setConflictIndex(s.conflictIndex) } func (s *State) NoConflicts() bool { return len(s.conflicts) == 0 } func (s *State) Selection() Selection { if selections := s.availableSelections(); len(selections) > 0 { return selections[s.selectionIndex] } return TOP } func (s *State) availableSelections() []Selection { if conflict := s.currentConflict(); conflict != nil { return availableSelections(conflict) } return nil } func (s *State) AllConflictsResolved() bool { return len(s.conflicts) == 0 } func (s *State) Reset() { s.contents = []string{} s.path = "" } // we're not resetting selectedIndex here because the user typically would want // to pick either all top hunks or all bottom hunks so we retain that selection func (s *State) ResetConflictSelection() { s.conflictIndex = 0 } func (s *State) Active() bool { return s.path != "" } func (s *State) GetConflictMiddle() int { currentConflict := s.currentConflict() if currentConflict == nil { return 0 } return currentConflict.target } func (s *State) ContentAfterConflictResolve(selection Selection) (bool, string, error) { conflict := s.currentConflict() if conflict == nil { return false, "", nil } content := "" err := utils.ForEachLineInFile(s.path, func(line string, i int) { if selection.isIndexToKeep(conflict, i) { content += line } }) if err != nil { return false, "", err } return true, content, nil } func (s *State) GetSelectedLine() int { conflict := s.currentConflict() if conflict == nil { // TODO: see why this is 1 and not 0 return 1 } selection := s.Selection() startIndex, _ := selection.bounds(conflict) return startIndex + 1 } func (s *State) GetSelectedRange() (int, int) { conflict := s.currentConflict() if conflict == nil { return 0, 0 } selection := s.Selection() startIndex, endIndex := selection.bounds(conflict) return startIndex, endIndex } func (s *State) PlainRenderSelected() string { startIndex, endIndex := s.GetSelectedRange() content := s.GetContent() contentLines := utils.SplitLines(content) return strings.Join(contentLines[startIndex:endIndex+1], "\n") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/state_test.go
pkg/gui/mergeconflicts/state_test.go
package mergeconflicts import ( "testing" "github.com/stretchr/testify/assert" ) func TestFindConflicts(t *testing.T) { type scenario struct { name string content string expected []*mergeConflict } scenarios := []scenario{ { name: "empty", content: "", expected: []*mergeConflict{}, }, { name: "various conflicts", content: `++<<<<<<< HEAD foo ++======= bar ++>>>>>>> branch <<<<<<< HEAD: foo/bar/baz.go foo bar ======= baz >>>>>>> branch ++<<<<<<< MERGE_HEAD foo ++======= bar ++>>>>>>> branch ++<<<<<<< Updated upstream foo ++======= bar ++>>>>>>> branch ++<<<<<<< ours foo ++======= bar ++>>>>>>> branch <<<<<<< Updated upstream: foo/bar/baz.go foo bar ======= baz >>>>>>> branch <<<<<<< HEAD foo ||||||| fffffff bar ======= baz >>>>>>> branch `, expected: []*mergeConflict{ { start: 0, ancestor: -1, target: 2, end: 4, }, { start: 6, ancestor: -1, target: 9, end: 11, }, { start: 13, ancestor: -1, target: 15, end: 17, }, { start: 19, ancestor: -1, target: 21, end: 23, }, { start: 25, ancestor: -1, target: 27, end: 29, }, { start: 31, ancestor: -1, target: 34, end: 36, }, { start: 38, ancestor: 40, target: 42, end: 44, }, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { assert.EqualValues(t, s.expected, findConflicts(s.content)) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/find_conflicts.go
pkg/gui/mergeconflicts/find_conflicts.go
package mergeconflicts import ( "bufio" "bytes" "io" "os" "strings" "github.com/jesseduffield/lazygit/pkg/utils" ) // LineType tells us whether a given line is a start/middle/end marker of a conflict, // or if it's not a marker at all type LineType int const ( START LineType = iota ANCESTOR TARGET END NOT_A_MARKER ) func findConflicts(content string) []*mergeConflict { conflicts := make([]*mergeConflict, 0) if content == "" { return conflicts } var newConflict *mergeConflict for i, line := range utils.SplitLines(content) { switch determineLineType(line) { case START: newConflict = &mergeConflict{start: i, ancestor: -1} case ANCESTOR: if newConflict != nil { newConflict.ancestor = i } case TARGET: if newConflict != nil { newConflict.target = i } case END: if newConflict != nil { newConflict.end = i conflicts = append(conflicts, newConflict) } // reset value to avoid any possible silent mutations in further iterations newConflict = nil default: // line isn't a merge conflict marker so we just continue } } return conflicts } var ( CONFLICT_START = "<<<<<<< " CONFLICT_END = ">>>>>>> " CONFLICT_START_BYTES = []byte(CONFLICT_START) CONFLICT_END_BYTES = []byte(CONFLICT_END) ) func determineLineType(line string) LineType { // TODO: find out whether we ever actually get this prefix trimmedLine := strings.TrimPrefix(line, "++") switch { case strings.HasPrefix(trimmedLine, CONFLICT_START): return START case strings.HasPrefix(trimmedLine, "||||||| "): return ANCESTOR case trimmedLine == "=======": return TARGET case strings.HasPrefix(trimmedLine, CONFLICT_END): return END default: return NOT_A_MARKER } } // tells us whether a file actually has inline merge conflicts. We need to run this // because git will continue showing a status of 'UU' even after the conflicts have // been resolved in the user's editor func FileHasConflictMarkers(path string) (bool, error) { file, err := os.Open(path) if err != nil { return false, err } defer file.Close() return fileHasConflictMarkersAux(file), nil } // Efficiently scans through a file looking for merge conflict markers. Returns true if it does func fileHasConflictMarkersAux(file io.Reader) bool { scanner := bufio.NewScanner(file) scanner.Split(utils.ScanLinesAndTruncateWhenLongerThanBuffer(bufio.MaxScanTokenSize)) for scanner.Scan() { line := scanner.Bytes() // only searching for start/end markers because the others are more ambiguous if bytes.HasPrefix(line, CONFLICT_START_BYTES) { return true } if bytes.HasPrefix(line, CONFLICT_END_BYTES) { return true } } return false }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/mergeconflicts/rendering.go
pkg/gui/mergeconflicts/rendering.go
package mergeconflicts import ( "bytes" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/utils" ) func ColoredConflictFile(state *State) string { content := state.GetContent() if len(state.conflicts) == 0 { return content } conflict, remainingConflicts := shiftConflict(state.conflicts) var outputBuffer bytes.Buffer for i, line := range utils.SplitLines(content) { textStyle := theme.DefaultTextColor if conflict.isMarkerLine(i) { textStyle = style.FgRed } if i == conflict.end && len(remainingConflicts) > 0 { conflict, remainingConflicts = shiftConflict(remainingConflicts) } outputBuffer.WriteString(textStyle.Sprint(line) + "\n") } return outputBuffer.String() } func shiftConflict(conflicts []*mergeConflict) (*mergeConflict, []*mergeConflict) { return conflicts[0], conflicts[1:] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/global_controller.go
pkg/gui/controllers/global_controller.go
package controllers import ( "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type GlobalController struct { baseController c *ControllerCommon } func NewGlobalController( c *ControllerCommon, ) *GlobalController { return &GlobalController{ baseController: baseController{}, c: c, } } func (self *GlobalController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.ExecuteShellCommand), Handler: self.shellCommand, Description: self.c.Tr.ExecuteShellCommand, Tooltip: self.c.Tr.ExecuteShellCommandTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.CreatePatchOptionsMenu), Handler: self.createCustomPatchOptionsMenu, Description: self.c.Tr.ViewPatchOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.CreateRebaseOptionsMenu), Handler: opts.Guards.NoPopupPanel(self.c.Helpers().MergeAndRebase.CreateRebaseOptionsMenu), Description: self.c.Tr.ViewMergeRebaseOptions, Tooltip: self.c.Tr.ViewMergeRebaseOptionsTooltip, OpensMenu: true, GetDisabledReason: self.canShowRebaseOptions, }, { Key: opts.GetKey(opts.Config.Universal.Refresh), Handler: opts.Guards.NoPopupPanel(self.refresh), Description: self.c.Tr.Refresh, Tooltip: self.c.Tr.RefreshTooltip, }, { Key: opts.GetKey(opts.Config.Universal.NextScreenMode), Handler: opts.Guards.NoPopupPanel(self.nextScreenMode), Description: self.c.Tr.NextScreenMode, }, { Key: opts.GetKey(opts.Config.Universal.PrevScreenMode), Handler: opts.Guards.NoPopupPanel(self.prevScreenMode), Description: self.c.Tr.PrevScreenMode, }, { Key: opts.GetKey(opts.Config.Universal.CyclePagers), Handler: opts.Guards.NoPopupPanel(self.cyclePagers), GetDisabledReason: self.canCyclePagers, Description: self.c.Tr.CyclePagers, Tooltip: self.c.Tr.CyclePagersTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Return), Modifier: gocui.ModNone, Handler: self.escape, Description: self.c.Tr.Cancel, DescriptionFunc: self.escapeDescription, GetDisabledReason: self.escapeEnabled, DisplayOnScreen: true, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.OptionMenu), Handler: self.createOptionsMenu, OpensMenu: true, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.OptionMenuAlt1), Modifier: gocui.ModNone, // we have the description on the alt key and not the main key for legacy reasons // (the original main key was 'x' but we've reassigned that to other purposes) Description: self.c.Tr.OpenKeybindingsMenu, Handler: self.createOptionsMenu, ShortDescription: self.c.Tr.Keybindings, DisplayOnScreen: true, GetDisabledReason: self.optionsMenuDisabledReason, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.FilteringMenu), Handler: opts.Guards.NoPopupPanel(self.createFilteringMenu), Description: self.c.Tr.OpenFilteringMenu, Tooltip: self.c.Tr.OpenFilteringMenuTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.DiffingMenu), Handler: opts.Guards.NoPopupPanel(self.createDiffingMenu), Description: self.c.Tr.ViewDiffingOptions, Tooltip: self.c.Tr.ViewDiffingOptionsTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.DiffingMenuAlt), Handler: opts.Guards.NoPopupPanel(self.createDiffingMenu), Description: self.c.Tr.ViewDiffingOptions, Tooltip: self.c.Tr.ViewDiffingOptionsTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.Quit), Modifier: gocui.ModNone, Description: self.c.Tr.Quit, Handler: self.quit, }, { Key: opts.GetKey(opts.Config.Universal.QuitAlt1), Modifier: gocui.ModNone, Handler: self.quit, }, { Key: opts.GetKey(opts.Config.Universal.QuitWithoutChangingDirectory), Modifier: gocui.ModNone, Handler: self.quitWithoutChangingDirectory, }, { Key: opts.GetKey(opts.Config.Universal.SuspendApp), Modifier: gocui.ModNone, Handler: self.c.Helpers().SuspendResume.SuspendApp, Description: self.c.Tr.SuspendApp, GetDisabledReason: func() *types.DisabledReason { if !self.c.Helpers().SuspendResume.CanSuspendApp() { return &types.DisabledReason{ Text: self.c.Tr.CannotSuspendApp, } } return nil }, }, { Key: opts.GetKey(opts.Config.Universal.ToggleWhitespaceInDiffView), Handler: self.toggleWhitespace, Description: self.c.Tr.ToggleWhitespaceInDiffView, Tooltip: self.c.Tr.ToggleWhitespaceInDiffViewTooltip, }, } } func (self *GlobalController) Context() types.Context { return nil } func (self *GlobalController) shellCommand() error { return (&ShellCommandAction{c: self.c}).Call() } func (self *GlobalController) createCustomPatchOptionsMenu() error { return (&CustomPatchOptionsMenuAction{c: self.c}).Call() } func (self *GlobalController) refresh() error { self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil } func (self *GlobalController) nextScreenMode() error { return (&ScreenModeActions{c: self.c}).Next() } func (self *GlobalController) prevScreenMode() error { return (&ScreenModeActions{c: self.c}).Prev() } func (self *GlobalController) cyclePagers() error { self.c.State().GetPagerConfig().CyclePagers() if self.c.Context().CurrentSide().GetKey() == self.c.Context().Current().GetKey() { self.c.Context().CurrentSide().HandleFocus(types.OnFocusOpts{}) } current, total := self.c.State().GetPagerConfig().CurrentPagerIndex() self.c.Toast(fmt.Sprintf("Selected pager %d of %d", current+1, total)) return nil } func (self *GlobalController) canCyclePagers() *types.DisabledReason { _, total := self.c.State().GetPagerConfig().CurrentPagerIndex() if total <= 1 { return &types.DisabledReason{ Text: self.c.Tr.CyclePagersDisabledReason, } } return nil } func (self *GlobalController) createOptionsMenu() error { return (&OptionsMenuAction{c: self.c}).Call() } func (self *GlobalController) optionsMenuDisabledReason() *types.DisabledReason { ctx := self.c.Context().Current() // Don't show options menu while displaying popup. if ctx.GetKind() == types.PERSISTENT_POPUP || ctx.GetKind() == types.TEMPORARY_POPUP { // The empty error text is intentional. We don't want to show an error // toast for this, but only hide it from the options map. return &types.DisabledReason{Text: ""} } return nil } func (self *GlobalController) createFilteringMenu() error { return (&FilteringMenuAction{c: self.c}).Call() } func (self *GlobalController) createDiffingMenu() error { return (&DiffingMenuAction{c: self.c}).Call() } func (self *GlobalController) quit() error { return (&QuitActions{c: self.c}).Quit() } func (self *GlobalController) quitWithoutChangingDirectory() error { return (&QuitActions{c: self.c}).QuitWithoutChangingDirectory() } func (self *GlobalController) escape() error { return (&QuitActions{c: self.c}).Escape() } func (self *GlobalController) escapeDescription() string { return (&QuitActions{c: self.c}).EscapeDescription() } func (self *GlobalController) escapeEnabled() *types.DisabledReason { if (&QuitActions{c: self.c}).EscapeEnabled() { return nil } // The empty error text is intentional. We don't want to show an error // toast for this, but only hide it from the options map. return &types.DisabledReason{Text: ""} } func (self *GlobalController) toggleWhitespace() error { return (&ToggleWhitespaceAction{c: self.c}).Call() } func (self *GlobalController) canShowRebaseOptions() *types.DisabledReason { if self.c.Model().WorkingTreeStateAtLastCommitRefresh.None() { return &types.DisabledReason{ Text: self.c.Tr.NotMergingOrRebasing, } } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/search_prompt_controller.go
pkg/gui/controllers/search_prompt_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type SearchPromptController struct { baseController c *ControllerCommon } var _ types.IController = &SearchPromptController{} func NewSearchPromptController( c *ControllerCommon, ) *SearchPromptController { return &SearchPromptController{ baseController: baseController{}, c: c, } } func (self *SearchPromptController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: gocui.KeyEnter, Modifier: gocui.ModNone, Handler: self.confirm, }, { Key: opts.GetKey(opts.Config.Universal.Return), Modifier: gocui.ModNone, Handler: self.cancel, }, { Key: opts.GetKey(opts.Config.Universal.PrevItem), Modifier: gocui.ModNone, Handler: self.prevHistory, }, { Key: opts.GetKey(opts.Config.Universal.NextItem), Modifier: gocui.ModNone, Handler: self.nextHistory, }, } } func (self *SearchPromptController) Context() types.Context { return self.context() } func (self *SearchPromptController) context() types.Context { return self.c.Contexts().Search } func (self *SearchPromptController) confirm() error { return self.c.Helpers().Search.Confirm() } func (self *SearchPromptController) cancel() error { return self.c.Helpers().Search.CancelPrompt() } func (self *SearchPromptController) prevHistory() error { self.c.Helpers().Search.ScrollHistory(1) return nil } func (self *SearchPromptController) nextHistory() error { self.c.Helpers().Search.ScrollHistory(-1) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/merge_conflicts_controller.go
pkg/gui/controllers/merge_conflicts_controller.go
package controllers import ( "os" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/mergeconflicts" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type MergeConflictsController struct { baseController c *ControllerCommon } var _ types.IController = &MergeConflictsController{} func NewMergeConflictsController( c *ControllerCommon, ) *MergeConflictsController { return &MergeConflictsController{ baseController: baseController{}, c: c, } } func (self *MergeConflictsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withRenderAndFocus(self.HandlePickHunk), Description: self.c.Tr.PickHunk, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Main.PickBothHunks), Handler: self.withRenderAndFocus(self.HandlePickAllHunks), Description: self.c.Tr.PickAllHunks, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.withRenderAndFocus(self.PrevConflictHunk), Description: self.c.Tr.SelectPrevHunk, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.withRenderAndFocus(self.NextConflictHunk), Description: self.c.Tr.SelectNextHunk, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.PrevBlock), Handler: self.withRenderAndFocus(self.PrevConflict), Description: self.c.Tr.PrevConflict, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.NextBlock), Handler: self.withRenderAndFocus(self.NextConflict), Description: self.c.Tr.NextConflict, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Undo), Handler: self.withRenderAndFocus(self.HandleUndo), Description: self.c.Tr.Undo, Tooltip: self.c.Tr.UndoMergeResolveTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.HandleEditFile, Description: self.c.Tr.EditFile, Tooltip: self.c.Tr.EditFileTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.HandleOpenFile, Description: self.c.Tr.OpenFile, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.PrevBlockAlt), Handler: self.withRenderAndFocus(self.PrevConflict), }, { Key: opts.GetKey(opts.Config.Universal.NextBlockAlt), Handler: self.withRenderAndFocus(self.NextConflict), }, { Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Handler: self.withRenderAndFocus(self.PrevConflictHunk), }, { Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Handler: self.withRenderAndFocus(self.NextConflictHunk), }, { Key: opts.GetKey(opts.Config.Universal.ScrollLeft), Handler: self.withRenderAndFocus(self.HandleScrollLeft), Description: self.c.Tr.ScrollLeft, Tag: "navigation", }, { Key: opts.GetKey(opts.Config.Universal.ScrollRight), Handler: self.withRenderAndFocus(self.HandleScrollRight), Description: self.c.Tr.ScrollRight, Tag: "navigation", }, { Key: opts.GetKey(opts.Config.Files.OpenMergeOptions), Handler: self.openMergeConflictMenu, Description: self.c.Tr.ViewMergeConflictOptions, Tooltip: self.c.Tr.ViewMergeConflictOptionsTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.Escape, Description: self.c.Tr.ReturnToFilesPanel, }, } return bindings } func (self *MergeConflictsController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.context().GetViewName(), Key: gocui.MouseWheelUp, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollUp() }, }, { ViewName: self.context().GetViewName(), Key: gocui.MouseWheelDown, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollDown() }, }, } } func (self *MergeConflictsController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { self.c.Views().MergeConflicts.Wrap = false self.c.Helpers().MergeConflicts.Render() self.context().SetSelectedLineRange() } } func (self *MergeConflictsController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.context().SetUserScrolling(false) self.context().GetState().ResetConflictSelection() self.c.Views().MergeConflicts.Wrap = true } } func (self *MergeConflictsController) HandleScrollUp() error { self.context().SetUserScrolling(true) self.context().GetViewTrait().ScrollUp(self.c.UserConfig().Gui.ScrollHeight) return nil } func (self *MergeConflictsController) HandleScrollDown() error { self.context().SetUserScrolling(true) self.context().GetViewTrait().ScrollDown(self.c.UserConfig().Gui.ScrollHeight) return nil } func (self *MergeConflictsController) Context() types.Context { return self.context() } func (self *MergeConflictsController) context() *context.MergeConflictsContext { return self.c.Contexts().MergeConflicts } func (self *MergeConflictsController) Escape() error { self.c.Context().Pop() return nil } func (self *MergeConflictsController) HandleEditFile() error { lineNumber := self.context().GetState().GetSelectedLine() return self.c.Helpers().Files.EditFileAtLine(self.context().GetState().GetPath(), lineNumber) } func (self *MergeConflictsController) HandleOpenFile() error { return self.c.Helpers().Files.OpenFile(self.context().GetState().GetPath()) } func (self *MergeConflictsController) HandleScrollLeft() error { self.context().GetViewTrait().ScrollLeft() return nil } func (self *MergeConflictsController) HandleScrollRight() error { self.context().GetViewTrait().ScrollRight() return nil } func (self *MergeConflictsController) HandleUndo() error { state := self.context().GetState() ok := state.Undo() if !ok { return nil } self.c.LogAction("Restoring file to previous state") self.c.LogCommand(self.c.Tr.Log.HandleUndo, false) if err := os.WriteFile(state.GetPath(), []byte(state.GetContent()), 0o644); err != nil { return err } return nil } func (self *MergeConflictsController) PrevConflictHunk() error { self.context().SetUserScrolling(false) self.context().GetState().SelectPrevConflictHunk() return nil } func (self *MergeConflictsController) NextConflictHunk() error { self.context().SetUserScrolling(false) self.context().GetState().SelectNextConflictHunk() return nil } func (self *MergeConflictsController) NextConflict() error { self.context().SetUserScrolling(false) self.context().GetState().SelectNextConflict() return nil } func (self *MergeConflictsController) PrevConflict() error { self.context().SetUserScrolling(false) self.context().GetState().SelectPrevConflict() return nil } func (self *MergeConflictsController) HandlePickHunk() error { return self.pickSelection(self.context().GetState().Selection()) } func (self *MergeConflictsController) HandlePickAllHunks() error { return self.pickSelection(mergeconflicts.ALL) } func (self *MergeConflictsController) pickSelection(selection mergeconflicts.Selection) error { ok, err := self.resolveConflict(selection) if err != nil { return err } if !ok { return nil } if self.context().GetState().AllConflictsResolved() { self.onLastConflictResolved() } return nil } func (self *MergeConflictsController) resolveConflict(selection mergeconflicts.Selection) (bool, error) { self.context().SetUserScrolling(false) state := self.context().GetState() ok, content, err := state.ContentAfterConflictResolve(selection) if err != nil { return false, err } if !ok { return false, nil } var logStr string switch selection { case mergeconflicts.TOP: logStr = "Picking top hunk" case mergeconflicts.MIDDLE: logStr = "Picking middle hunk" case mergeconflicts.BOTTOM: logStr = "Picking bottom hunk" case mergeconflicts.ALL: logStr = "Picking all hunks" } self.c.LogAction("Resolve merge conflict") self.c.LogCommand(logStr, false) state.PushContent(content) return true, os.WriteFile(state.GetPath(), []byte(content), 0o644) } func (self *MergeConflictsController) onLastConflictResolved() { // as part of refreshing files, we handle the situation where a file has had // its merge conflicts resolved. self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}) } func (self *MergeConflictsController) openMergeConflictMenu() error { filepath := self.context().GetState().GetPath() return self.c.Helpers().WorkingTree.CreateMergeConflictMenu([]string{filepath}) } func (self *MergeConflictsController) withRenderAndFocus(f func() error) func() error { return self.withLock(func() error { if err := f(); err != nil { return err } self.context().RenderAndFocus() return nil }) } func (self *MergeConflictsController) withLock(f func() error) func() error { return func() error { self.context().GetMutex().Lock() defer self.context().GetMutex().Unlock() if self.context().GetState() == nil { return nil } return f() } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/suggestions_controller.go
pkg/gui/controllers/suggestions_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type SuggestionsController struct { baseController *ListControllerTrait[*types.Suggestion] c *ControllerCommon } var _ types.IController = &SuggestionsController{} func NewSuggestionsController( c *ControllerCommon, ) *SuggestionsController { return &SuggestionsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Suggestions, c.Contexts().Suggestions.GetSelected, c.Contexts().Suggestions.GetSelectedItems, ), c: c, } } func (self *SuggestionsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.ConfirmSuggestion), Handler: func() error { return self.context().State.OnConfirm() }, GetDisabledReason: self.require(self.singleItemSelected()), }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: func() error { return self.context().State.OnClose() }, }, { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: self.switchToPrompt, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: func() error { return self.context().State.OnDeleteSuggestion() }, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: func() error { if self.context().State.AllowEditSuggestion { if selectedItem := self.c.Contexts().Suggestions.GetSelected(); selectedItem != nil { self.c.Contexts().Prompt.GetView().TextArea.Clear() self.c.Contexts().Prompt.GetView().TextArea.TypeString(selectedItem.Value) self.c.Contexts().Prompt.GetView().RenderTextArea() self.c.Contexts().Suggestions.RefreshSuggestions() return self.switchToPrompt() } } return nil }, }, } return bindings } func (self *SuggestionsController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.c.Contexts().Prompt.GetViewName(), FocusedView: self.c.Contexts().Suggestions.GetViewName(), Key: gocui.MouseLeft, Handler: func(gocui.ViewMouseBindingOpts) error { return self.switchToPrompt() }, }, } } func (self *SuggestionsController) switchToPrompt() error { self.c.Views().Suggestions.Subtitle = "" self.c.Views().Suggestions.Highlight = false self.c.Context().Replace(self.c.Contexts().Prompt) return nil } func (self *SuggestionsController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.c.Helpers().Confirmation.DeactivatePrompt() } } func (self *SuggestionsController) context() *context.SuggestionsContext { return self.c.Contexts().Suggestions }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/scroll_off_margin.go
pkg/gui/controllers/scroll_off_margin.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // To be called after pressing up-arrow; checks whether the cursor entered the // top scroll-off margin, and so the view needs to be scrolled up one line func checkScrollUp(view types.IViewTrait, userConfig *config.UserConfig, lineIdxBefore int, lineIdxAfter int) { if userConfig.Gui.ScrollOffBehavior != "jump" { viewPortStart, viewPortHeight := view.ViewPortYBounds() linesToScroll := calculateLinesToScrollUp( viewPortStart, viewPortHeight, userConfig.Gui.ScrollOffMargin, lineIdxBefore, lineIdxAfter) if linesToScroll != 0 { view.ScrollUp(linesToScroll) } } } // To be called after pressing down-arrow; checks whether the cursor entered the // bottom scroll-off margin, and so the view needs to be scrolled down one line func checkScrollDown(view types.IViewTrait, userConfig *config.UserConfig, lineIdxBefore int, lineIdxAfter int) { if userConfig.Gui.ScrollOffBehavior != "jump" { viewPortStart, viewPortHeight := view.ViewPortYBounds() linesToScroll := calculateLinesToScrollDown( viewPortStart, viewPortHeight, userConfig.Gui.ScrollOffMargin, lineIdxBefore, lineIdxAfter) if linesToScroll != 0 { view.ScrollDown(linesToScroll) } } } func calculateLinesToScrollUp(viewPortStart int, viewPortHeight int, scrollOffMargin int, lineIdxBefore int, lineIdxAfter int) int { // Cap the margin to half the view height. This allows setting the config to // a very large value to keep the cursor always in the middle of the screen. // Use +.5 so that if the height is even, the top margin is one line higher // than the bottom margin. scrollOffMargin = min(scrollOffMargin, int((float64(viewPortHeight)+.5)/2)) // Scroll only if the "before" position was visible (this could be false if // the scroll wheel was used to scroll the selected line out of view) ... if lineIdxBefore >= viewPortStart && lineIdxBefore < viewPortStart+viewPortHeight { marginEnd := viewPortStart + scrollOffMargin // ... and the "after" position is within the top margin (or before it) if lineIdxAfter < marginEnd { return marginEnd - lineIdxAfter } } return 0 } func calculateLinesToScrollDown(viewPortStart int, viewPortHeight int, scrollOffMargin int, lineIdxBefore int, lineIdxAfter int) int { // Cap the margin to half the view height. This allows setting the config to // a very large value to keep the cursor always in the middle of the screen. // Use -.5 so that if the height is even, the bottom margin is one line lower // than the top margin. scrollOffMargin = min(scrollOffMargin, int((float64(viewPortHeight)-.5)/2)) // Scroll only if the "before" position was visible (this could be false if // the scroll wheel was used to scroll the selected line out of view) ... if lineIdxBefore >= viewPortStart && lineIdxBefore < viewPortStart+viewPortHeight { marginStart := viewPortStart + viewPortHeight - scrollOffMargin - 1 // ... and the "after" position is within the bottom margin (or after it) if lineIdxAfter > marginStart { return lineIdxAfter - marginStart } } return 0 }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/patch_building_controller.go
pkg/gui/controllers/patch_building_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type PatchBuildingController struct { baseController c *ControllerCommon } var _ types.IController = &PatchBuildingController{} func NewPatchBuildingController( c *ControllerCommon, ) *PatchBuildingController { return &PatchBuildingController{ baseController: baseController{}, c: c, } } func (self *PatchBuildingController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.OpenFile, Description: self.c.Tr.OpenFile, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.EditFile, Description: self.c.Tr.EditFile, Tooltip: self.c.Tr.EditFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.ToggleSelectionAndRefresh, Description: self.c.Tr.ToggleSelectionForPatch, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.Escape, Description: self.c.Tr.ExitCustomPatchBuilder, DescriptionFunc: self.EscapeDescription, DisplayOnScreen: true, }, } } func (self *PatchBuildingController) Context() types.Context { return self.c.Contexts().CustomPatchBuilder } func (self *PatchBuildingController) context() types.IPatchExplorerContext { return self.c.Contexts().CustomPatchBuilder } func (self *PatchBuildingController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{} } func (self *PatchBuildingController) GetOnFocus() func(types.OnFocusOpts) { return func(opts types.OnFocusOpts) { // no need to change wrap on the secondary view because it can't be interacted with self.c.Views().PatchBuilding.Wrap = self.c.UserConfig().Gui.WrapLinesInStagingView self.c.Helpers().PatchBuilding.RefreshPatchBuildingPanel(opts) } } func (self *PatchBuildingController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(opts types.OnFocusLostOpts) { self.context().SetState(nil) self.c.Views().PatchBuilding.Wrap = true if self.c.Git().Patch.PatchBuilder.IsEmpty() { self.c.Git().Patch.PatchBuilder.Reset() } } } func (self *PatchBuildingController) OpenFile() error { self.context().GetMutex().Lock() defer self.context().GetMutex().Unlock() path := self.c.Contexts().CommitFiles.GetSelectedPath() if path == "" { return nil } return self.c.Helpers().Files.OpenFile(path) } func (self *PatchBuildingController) EditFile() error { self.context().GetMutex().Lock() defer self.context().GetMutex().Unlock() path := self.c.Contexts().CommitFiles.GetSelectedPath() if path == "" { return nil } lineNumber := self.context().GetState().CurrentLineNumber() lineNumber = self.c.Helpers().Diff.AdjustLineNumber(path, lineNumber, self.context().GetViewName()) return self.c.Helpers().Files.EditFileAtLine(path, lineNumber) } func (self *PatchBuildingController) ToggleSelectionAndRefresh() error { if err := self.toggleSelection(); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.PATCH_BUILDING, types.COMMIT_FILES}, }) return nil } func (self *PatchBuildingController) toggleSelection() error { self.context().GetMutex().Lock() defer self.context().GetMutex().Unlock() filename := self.c.Contexts().CommitFiles.GetSelectedPath() if filename == "" { return nil } state := self.context().GetState() // Get added/deleted lines in the selected patch range lineIndicesToToggle := state.LineIndicesOfAddedOrDeletedLinesInSelectedPatchRange() if len(lineIndicesToToggle) == 0 { // Only context lines or header lines selected, so nothing to do return nil } includedLineIndices, err := self.c.Git().Patch.PatchBuilder.GetFileIncLineIndices(filename) if err != nil { return err } toggleFunc := self.c.Git().Patch.PatchBuilder.AddFileLineRange firstSelectedChangeLineIsStaged := lo.Contains(includedLineIndices, lineIndicesToToggle[0]) if firstSelectedChangeLineIsStaged { toggleFunc = self.c.Git().Patch.PatchBuilder.RemoveFileLineRange } // add range of lines to those set for the file if err := toggleFunc(filename, lineIndicesToToggle); err != nil { // might actually want to return an error here self.c.Log.Error(err) } if state.SelectingRange() { state.SetLineSelectMode() } state.SelectNextStageableLineOfSameIncludedState(self.context().GetIncludedLineIndices(), firstSelectedChangeLineIsStaged) return nil } func (self *PatchBuildingController) Escape() error { context := self.c.Contexts().CustomPatchBuilder state := context.GetState() if state.SelectingRange() || state.SelectingHunkEnabledByUser() { state.SetLineSelectMode() self.c.PostRefreshUpdate(context) return nil } self.c.Helpers().PatchBuilding.Escape() return nil } func (self *PatchBuildingController) EscapeDescription() string { context := self.c.Contexts().CustomPatchBuilder if state := context.GetState(); state != nil { if state.SelectingRange() { return self.c.Tr.DismissRangeSelect } if state.SelectingHunkEnabledByUser() { return self.c.Tr.SelectLineByLine } } return self.c.Tr.ExitCustomPatchBuilder }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/view_selection_controller.go
pkg/gui/controllers/view_selection_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type ViewSelectionControllerFactory struct { c *ControllerCommon } func NewViewSelectionControllerFactory(c *ControllerCommon) *ViewSelectionControllerFactory { return &ViewSelectionControllerFactory{ c: c, } } func (self *ViewSelectionControllerFactory) Create(context types.Context) types.IController { return &ViewSelectionController{ baseController: baseController{}, c: self.c, context: context, } } type ViewSelectionController struct { baseController c *ControllerCommon context types.Context } func (self *ViewSelectionController) Context() types.Context { return self.context } func (self *ViewSelectionController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.handlePrevLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Handler: self.handlePrevLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.handleNextLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Handler: self.handleNextLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevPage), Handler: self.handlePrevPage, Description: self.c.Tr.PrevPage}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextPage), Handler: self.handleNextPage, Description: self.c.Tr.NextPage}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTop), Handler: self.handleGotoTop, Description: self.c.Tr.GotoTop, Alternative: "<home>"}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottom), Handler: self.handleGotoBottom, Description: self.c.Tr.GotoBottom, Alternative: "<end>"}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTopAlt), Handler: self.handleGotoTop}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottomAlt), Handler: self.handleGotoBottom}, } } func (self *ViewSelectionController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{} } func (self *ViewSelectionController) handleLineChange(delta int) { if delta > 0 { if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { manager.ReadLines(delta) } } v := self.Context().GetView() if delta < 0 { v.ScrollUp(-delta) } else { v.ScrollDown(delta) } } func (self *ViewSelectionController) handlePrevLine() error { self.handleLineChange(-1) return nil } func (self *ViewSelectionController) handleNextLine() error { self.handleLineChange(1) return nil } func (self *ViewSelectionController) handlePrevPage() error { self.handleLineChange(-self.context.GetViewTrait().PageDelta()) return nil } func (self *ViewSelectionController) handleNextPage() error { self.handleLineChange(self.context.GetViewTrait().PageDelta()) return nil } func (self *ViewSelectionController) handleGotoTop() error { v := self.Context().GetView() self.handleLineChange(-v.ViewLinesHeight()) return nil } func (self *ViewSelectionController) handleGotoBottom() error { if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { manager.ReadToEnd(func() { self.c.OnUIThread(func() error { v := self.Context().GetView() self.handleLineChange(v.ViewLinesHeight()) return nil }) }) } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/list_controller.go
pkg/gui/controllers/list_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type ListControllerFactory struct { c *ControllerCommon } func NewListControllerFactory(c *ControllerCommon) *ListControllerFactory { return &ListControllerFactory{ c: c, } } func (self *ListControllerFactory) Create(context types.IListContext) *ListController { return &ListController{ baseController: baseController{}, c: self.c, context: context, } } type ListController struct { baseController c *ControllerCommon context types.IListContext } func (self *ListController) Context() types.Context { return self.context } func (self *ListController) HandlePrevLine() error { return self.handleLineChange(-1) } func (self *ListController) HandleNextLine() error { return self.handleLineChange(1) } func (self *ListController) HandleScrollLeft() error { return self.scrollHorizontal(self.context.GetViewTrait().ScrollLeft) } func (self *ListController) HandleScrollRight() error { return self.scrollHorizontal(self.context.GetViewTrait().ScrollRight) } func (self *ListController) HandleScrollUp() error { scrollHeight := self.c.UserConfig().Gui.ScrollHeight self.context.GetViewTrait().ScrollUp(scrollHeight) if self.context.RenderOnlyVisibleLines() { self.context.HandleRender() } return nil } func (self *ListController) HandleScrollDown() error { scrollHeight := self.c.UserConfig().Gui.ScrollHeight self.context.GetViewTrait().ScrollDown(scrollHeight) if self.context.RenderOnlyVisibleLines() { self.context.HandleRender() } return nil } func (self *ListController) scrollHorizontal(scrollFunc func()) error { scrollFunc() self.context.HandleFocus(types.OnFocusOpts{}) if self.context.NeedsRerenderOnWidthChange() == types.NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_WIDTH_CHANGES { self.context.HandleRender() } return nil } func (self *ListController) handleLineChange(change int) error { return self.handleLineChangeAux( self.context.GetList().MoveSelectedLine, change, ) } func (self *ListController) HandleRangeSelectChange(change int) error { return self.handleLineChangeAux( self.context.GetList().ExpandNonStickyRange, change, ) } func (self *ListController) handleLineChangeAux(f func(int), change int) error { list := self.context.GetList() rangeBefore := list.IsSelectingRange() before := list.GetSelectedLineIdx() f(change) rangeAfter := list.IsSelectingRange() after := list.GetSelectedLineIdx() // doing this check so that if we're holding the up key at the start of the list // we're not constantly re-rendering the main view. cursorMoved := before != after if cursorMoved { switch change { case -1: checkScrollUp(self.context.GetViewTrait(), self.c.UserConfig(), self.context.ModelIndexToViewIndex(before), self.context.ModelIndexToViewIndex(after)) case 1: checkScrollDown(self.context.GetViewTrait(), self.c.UserConfig(), self.context.ModelIndexToViewIndex(before), self.context.ModelIndexToViewIndex(after)) } } if cursorMoved || rangeBefore != rangeAfter { self.context.HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) } else { // If the selection did not change (because, for example, we are at the top of the list and // press up), we still want to ensure that the selection is visible. This is useful after // scrolling the selection out of view with the mouse. self.context.FocusLine(true) } return nil } func (self *ListController) HandlePrevPage() error { return self.handlePageChange(-self.context.GetViewTrait().PageDelta()) } func (self *ListController) HandleNextPage() error { return self.handlePageChange(self.context.GetViewTrait().PageDelta()) } func (self *ListController) handlePageChange(delta int) error { list := self.context.GetList() view := self.context.GetViewTrait() before := list.GetSelectedLineIdx() viewPortStart, viewPortHeight := view.ViewPortYBounds() beforeViewIdx := self.context.ModelIndexToViewIndex(before) afterViewIdx := beforeViewIdx + delta newModelIndex := self.context.ViewIndexToModelIndex(afterViewIdx) if delta < 0 { // Previous page: keep selection at top of viewport indexAtTopOfPage := self.context.ViewIndexToModelIndex(viewPortStart) if before != indexAtTopOfPage { // If the selection isn't already at the top of the page, move it there without scrolling list.MoveSelectedLine(indexAtTopOfPage - before) } else { // Otherwise, move the selection by one page and scroll list.MoveSelectedLine(newModelIndex - before) linesToScroll := afterViewIdx - viewPortStart if linesToScroll < 0 { view.ScrollUp(-linesToScroll) } } } else { // Next page: keep selection at bottom of viewport indexAtBottomOfPage := self.context.ViewIndexToModelIndex(viewPortStart + viewPortHeight - 1) if before != indexAtBottomOfPage { // If the selection isn't already at the bottom of the page, move it there without scrolling list.MoveSelectedLine(indexAtBottomOfPage - before) } else { // Otherwise, move the selection by one page and scroll list.MoveSelectedLine(newModelIndex - before) linesToScroll := afterViewIdx - (viewPortStart + viewPortHeight - 1) if linesToScroll > 0 { view.ScrollDown(linesToScroll) } } } // Since we already scrolled the view above, the normal mechanism that // ListContextTrait.FocusLine uses for deciding whether rerendering is needed won't work. It is // based on checking whether the origin was changed by the call to FocusPoint in that function, // but since we scrolled the view directly above, the origin has already been updated. So we // must tell it explicitly to rerender. self.context.SetNeedRerenderVisibleLines() // Since we are maintaining the scroll position ourselves above, there's no point in passing // ScrollSelectionIntoView=true here. self.context.HandleFocus(types.OnFocusOpts{}) return nil } func (self *ListController) HandleGotoTop() error { return self.handleLineChange(-self.context.GetList().Len()) } func (self *ListController) HandleGotoBottom() error { bottomIdx := self.context.IndexForGotoBottom() change := bottomIdx - self.context.GetList().GetSelectedLineIdx() return self.handleLineChange(change) } func (self *ListController) HandleToggleRangeSelect() error { list := self.context.GetList() list.ToggleStickyRange() self.context.HandleFocus(types.OnFocusOpts{}) return nil } func (self *ListController) HandleRangeSelectDown() error { return self.HandleRangeSelectChange(1) } func (self *ListController) HandleRangeSelectUp() error { return self.HandleRangeSelectChange(-1) } func (self *ListController) HandleClick(opts gocui.ViewMouseBindingOpts) error { newSelectedLineIdx := self.context.ViewIndexToModelIndex(opts.Y) alreadyFocused := self.isFocused() if err := self.pushContextIfNotFocused(); err != nil { return err } if newSelectedLineIdx > self.context.GetList().Len()-1 { return nil } self.context.GetList().SetSelection(newSelectedLineIdx) if opts.IsDoubleClick && alreadyFocused && self.context.GetOnClick() != nil { return self.context.GetOnClick()() } self.context.HandleFocus(types.OnFocusOpts{}) return nil } func (self *ListController) pushContextIfNotFocused() error { if !self.isFocused() { self.c.Context().Push(self.context, types.OnFocusOpts{}) } return nil } func (self *ListController) isFocused() bool { return self.c.Context().Current().GetKey() == self.context.GetKey() } func (self *ListController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Handler: self.HandlePrevLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.HandlePrevLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Handler: self.HandleNextLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.HandleNextLine}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevPage), Handler: self.HandlePrevPage, Description: self.c.Tr.PrevPage}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextPage), Handler: self.HandleNextPage, Description: self.c.Tr.NextPage}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTop), Handler: self.HandleGotoTop, Description: self.c.Tr.GotoTop, Alternative: "<home>"}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottom), Handler: self.HandleGotoBottom, Description: self.c.Tr.GotoBottom, Alternative: "<end>"}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTopAlt), Handler: self.HandleGotoTop}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottomAlt), Handler: self.HandleGotoBottom}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.ScrollLeft), Handler: self.HandleScrollLeft}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.ScrollRight), Handler: self.HandleScrollRight}, } if self.context.RangeSelectEnabled() { bindings = append(bindings, []*types.Binding{ {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.ToggleRangeSelect), Handler: self.HandleToggleRangeSelect, Description: self.c.Tr.ToggleRangeSelect}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.RangeSelectDown), Handler: self.HandleRangeSelectDown, Description: self.c.Tr.RangeSelectDown}, {Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.RangeSelectUp), Handler: self.HandleRangeSelectUp, Description: self.c.Tr.RangeSelectUp}, }..., ) } return bindings } func (self *ListController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.context.GetViewName(), Key: gocui.MouseWheelUp, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollUp() }, }, { ViewName: self.context.GetViewName(), Key: gocui.MouseLeft, Handler: func(opts gocui.ViewMouseBindingOpts) error { return self.HandleClick(opts) }, }, { ViewName: self.context.GetViewName(), Key: gocui.MouseWheelDown, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollDown() }, }, } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/patch_explorer_controller_test.go
pkg/gui/controllers/patch_explorer_controller_test.go
package controllers import ( "testing" "github.com/stretchr/testify/assert" ) func Test_dropDiffPrefix(t *testing.T) { scenarios := []struct { name string diff string expectedResult string }{ { name: "empty string", diff: "", expectedResult: "", }, { name: "only added lines", diff: `+line1 +line2 `, expectedResult: `line1 line2 `, }, { name: "added lines with context", diff: ` line1 +line2 `, expectedResult: `line1 line2 `, }, { name: "only deleted lines", diff: `-line1 -line2 `, expectedResult: `line1 line2 `, }, { name: "deleted lines with context", diff: `-line1 line2 `, expectedResult: `line1 line2 `, }, { name: "only context", diff: ` line1 line2 `, expectedResult: `line1 line2 `, }, { name: "added and deleted lines", diff: `+line1 -line2 `, expectedResult: `+line1 -line2 `, }, { name: "hunk header lines", diff: `@@ -1,8 +1,11 @@ line1 `, expectedResult: `@@ -1,8 +1,11 @@ line1 `, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { assert.Equal(t, s.expectedResult, dropDiffPrefix(s.diff)) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/submodules_controller.go
pkg/gui/controllers/submodules_controller.go
package controllers import ( "fmt" "path/filepath" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type SubmodulesController struct { baseController *ListControllerTrait[*models.SubmoduleConfig] c *ControllerCommon } var _ types.IController = &SubmodulesController{} func NewSubmodulesController( c *ControllerCommon, ) *SubmodulesController { return &SubmodulesController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Submodules, c.Contexts().Submodules.GetSelected, c.Contexts().Submodules.GetSelectedItems, ), c: c, } } func (self *SubmodulesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Enter, Tooltip: utils.ResolvePlaceholderString(self.c.Tr.EnterSubmoduleTooltip, map[string]string{"escape": keybindings.Label(opts.Config.Universal.Return)}), DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItem(self.remove), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Remove, Tooltip: self.c.Tr.RemoveSubmoduleTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Submodules.Update), Handler: self.withItem(self.update), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Update, Tooltip: self.c.Tr.SubmoduleUpdateTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.add, Description: self.c.Tr.NewSubmodule, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.withItem(self.editURL), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.EditSubmoduleUrl, }, { Key: opts.GetKey(opts.Config.Submodules.Init), Handler: self.withItem(self.init), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Initialize, Tooltip: self.c.Tr.InitSubmoduleTooltip, }, { Key: opts.GetKey(opts.Config.Submodules.BulkMenu), Handler: self.openBulkActionsMenu, Description: self.c.Tr.ViewBulkSubmoduleOptions, OpensMenu: true, }, { Key: nil, Handler: self.easterEgg, Description: self.c.Tr.EasterEgg, }, } } func (self *SubmodulesController) GetOnClick() func() error { return self.withItemGraceful(self.enter) } func (self *SubmodulesController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask submodule := self.context().GetSelected() if submodule == nil { task = types.NewRenderStringTask("No submodules") } else { prefix := fmt.Sprintf( "Name: %s\nPath: %s\nUrl: %s\n\n", style.FgGreen.Sprint(submodule.FullName()), style.FgYellow.Sprint(submodule.FullPath()), style.FgCyan.Sprint(submodule.Url), ) file := self.c.Helpers().WorkingTree.FileForSubmodule(submodule) if file == nil { task = types.NewRenderStringTask(prefix) } else { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(file, false, !file.HasUnstagedChanges && file.HasStagedChanges) task = types.NewRunCommandTaskWithPrefix(cmdObj.GetCmd(), prefix) } } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Submodule", Task: task, }, }) }) } } func (self *SubmodulesController) enter(submodule *models.SubmoduleConfig) error { return self.c.Helpers().Repos.EnterSubmodule(submodule) } func (self *SubmodulesController) add() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewSubmoduleUrl, HandleConfirm: func(submoduleUrl string) error { nameSuggestion := filepath.Base(strings.TrimSuffix(submoduleUrl, filepath.Ext(submoduleUrl))) self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewSubmoduleName, InitialContent: nameSuggestion, HandleConfirm: func(submoduleName string) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewSubmodulePath, InitialContent: submoduleName, HandleConfirm: func(submodulePath string) error { return self.c.WithWaitingStatus(self.c.Tr.AddingSubmoduleStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddSubmodule) err := self.c.Git().Submodule.Add(submoduleName, submodulePath, submoduleUrl) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, }) return nil }, }) return nil }, }) return nil } func (self *SubmodulesController) editURL(submodule *models.SubmoduleConfig) error { self.c.Prompt(types.PromptOpts{ Title: fmt.Sprintf(self.c.Tr.UpdateSubmoduleUrl, submodule.FullName()), InitialContent: submodule.Url, HandleConfirm: func(newUrl string) error { return self.c.WithWaitingStatus(self.c.Tr.UpdatingSubmoduleUrlStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.UpdateSubmoduleUrl) err := self.c.Git().Submodule.UpdateUrl(submodule, newUrl) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, }) return nil } func (self *SubmodulesController) init(submodule *models.SubmoduleConfig) error { return self.c.WithWaitingStatus(self.c.Tr.InitializingSubmoduleStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.InitialiseSubmodule) err := self.c.Git().Submodule.Init(submodule.Path) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) } func (self *SubmodulesController) openBulkActionsMenu() error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.BulkSubmoduleOptions, Items: []*types.MenuItem{ { LabelColumns: []string{self.c.Tr.BulkInitSubmodules, style.FgGreen.Sprint(self.c.Git().Submodule.BulkInitCmdObj().ToString())}, OnPress: func() error { return self.c.WithWaitingStatus(self.c.Tr.RunningCommand, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.BulkInitialiseSubmodules) err := self.c.Git().Submodule.BulkInitCmdObj().Run() if err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, Key: 'i', }, { LabelColumns: []string{self.c.Tr.BulkUpdateSubmodules, style.FgYellow.Sprint(self.c.Git().Submodule.BulkUpdateCmdObj().ToString())}, OnPress: func() error { return self.c.WithWaitingStatus(self.c.Tr.RunningCommand, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.BulkUpdateSubmodules) if err := self.c.Git().Submodule.BulkUpdateCmdObj().Run(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, Key: 'u', }, { LabelColumns: []string{self.c.Tr.BulkUpdateRecursiveSubmodules, style.FgYellow.Sprint(self.c.Git().Submodule.BulkUpdateRecursivelyCmdObj().ToString())}, OnPress: func() error { return self.c.WithWaitingStatus(self.c.Tr.RunningCommand, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.BulkUpdateRecursiveSubmodules) if err := self.c.Git().Submodule.BulkUpdateRecursivelyCmdObj().Run(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, Key: 'r', }, { LabelColumns: []string{self.c.Tr.BulkDeinitSubmodules, style.FgRed.Sprint(self.c.Git().Submodule.BulkDeinitCmdObj().ToString())}, OnPress: func() error { return self.c.WithWaitingStatus(self.c.Tr.RunningCommand, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.BulkDeinitialiseSubmodules) if err := self.c.Git().Submodule.BulkDeinitCmdObj().Run(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, Key: 'd', }, }, }) } func (self *SubmodulesController) update(submodule *models.SubmoduleConfig) error { return self.c.WithWaitingStatus(self.c.Tr.UpdatingSubmoduleStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.UpdateSubmodule) err := self.c.Git().Submodule.Update(submodule.Path) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) } func (self *SubmodulesController) remove(submodule *models.SubmoduleConfig) error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.RemoveSubmodule, Prompt: fmt.Sprintf(self.c.Tr.RemoveSubmodulePrompt, submodule.FullName()), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.RemoveSubmodule) if err := self.c.Git().Submodule.Delete(submodule); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES, types.FILES}}) return nil }, }) return nil } func (self *SubmodulesController) easterEgg() error { self.c.Context().Push(self.c.Contexts().Snake, types.OnFocusOpts{}) return nil } func (self *SubmodulesController) context() *context.SubmodulesContext { return self.c.Contexts().Submodules }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/patch_explorer_controller.go
pkg/gui/controllers/patch_explorer_controller.go
package controllers import ( "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type PatchExplorerControllerFactory struct { c *ControllerCommon } func NewPatchExplorerControllerFactory(c *ControllerCommon) *PatchExplorerControllerFactory { return &PatchExplorerControllerFactory{ c: c, } } func (self *PatchExplorerControllerFactory) Create(context types.IPatchExplorerContext) *PatchExplorerController { return &PatchExplorerController{ baseController: baseController{}, c: self.c, context: context, } } type PatchExplorerController struct { baseController c *ControllerCommon context types.IPatchExplorerContext } func (self *PatchExplorerController) Context() types.Context { return self.context } func (self *PatchExplorerController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Handler: self.withRenderAndFocus(self.HandlePrevLine), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.withRenderAndFocus(self.HandlePrevLine), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Handler: self.withRenderAndFocus(self.HandleNextLine), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.withRenderAndFocus(self.HandleNextLine), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.RangeSelectUp), Handler: self.withRenderAndFocus(self.HandlePrevLineRange), Description: self.c.Tr.RangeSelectUp, }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.RangeSelectDown), Handler: self.withRenderAndFocus(self.HandleNextLineRange), Description: self.c.Tr.RangeSelectDown, }, { Key: opts.GetKey(opts.Config.Universal.PrevBlock), Handler: self.withRenderAndFocus(self.HandlePrevHunk), Description: self.c.Tr.PrevHunk, }, { Key: opts.GetKey(opts.Config.Universal.PrevBlockAlt), Handler: self.withRenderAndFocus(self.HandlePrevHunk), }, { Key: opts.GetKey(opts.Config.Universal.NextBlock), Handler: self.withRenderAndFocus(self.HandleNextHunk), Description: self.c.Tr.NextHunk, }, { Key: opts.GetKey(opts.Config.Universal.NextBlockAlt), Handler: self.withRenderAndFocus(self.HandleNextHunk), }, { Key: opts.GetKey(opts.Config.Universal.ToggleRangeSelect), Handler: self.withRenderAndFocus(self.HandleToggleSelectRange), Description: self.c.Tr.ToggleRangeSelect, }, { Key: opts.GetKey(opts.Config.Main.ToggleSelectHunk), Handler: self.withRenderAndFocus(self.HandleToggleSelectHunk), Description: self.c.Tr.ToggleSelectHunk, DescriptionFunc: func() string { if state := self.context.GetState(); state != nil && state.SelectingHunk() { return self.c.Tr.SelectLineByLine } return self.c.Tr.SelectHunk }, Tooltip: self.c.Tr.ToggleSelectHunkTooltip, DisplayOnScreen: true, }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevPage), Handler: self.withRenderAndFocus(self.HandlePrevPage), Description: self.c.Tr.PrevPage, }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextPage), Handler: self.withRenderAndFocus(self.HandleNextPage), Description: self.c.Tr.NextPage, }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTop), Handler: self.withRenderAndFocus(self.HandleGotoTop), Description: self.c.Tr.GotoTop, }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottom), Description: self.c.Tr.GotoBottom, Handler: self.withRenderAndFocus(self.HandleGotoBottom), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoTopAlt), Handler: self.withRenderAndFocus(self.HandleGotoTop), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.GotoBottomAlt), Handler: self.withRenderAndFocus(self.HandleGotoBottom), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.ScrollLeft), Handler: self.withRenderAndFocus(self.HandleScrollLeft), }, { Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.ScrollRight), Handler: self.withRenderAndFocus(self.HandleScrollRight), }, { Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: self.withLock(self.CopySelectedToClipboard), Description: self.c.Tr.CopySelectedTextToClipboard, }, } } func (self *PatchExplorerController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.context.GetViewName(), Key: gocui.MouseLeft, Handler: func(opts gocui.ViewMouseBindingOpts) error { if self.isFocused() { return self.withRenderAndFocus(self.HandleMouseDown)() } self.c.Context().Push(self.context, types.OnFocusOpts{ ClickedWindowName: self.context.GetWindowName(), ClickedViewLineIdx: opts.Y, }) return nil }, }, { ViewName: self.context.GetViewName(), Key: gocui.MouseLeft, Modifier: gocui.ModMotion, Handler: func(gocui.ViewMouseBindingOpts) error { return self.withRenderAndFocus(self.HandleMouseDrag)() }, }, } } func (self *PatchExplorerController) HandlePrevLine() error { before := self.context.GetState().GetSelectedViewLineIdx() self.context.GetState().CycleSelection(false) after := self.context.GetState().GetSelectedViewLineIdx() if self.context.GetState().SelectingLine() { checkScrollUp(self.context.GetViewTrait(), self.c.UserConfig(), before, after) } return nil } func (self *PatchExplorerController) HandleNextLine() error { before := self.context.GetState().GetSelectedViewLineIdx() self.context.GetState().CycleSelection(true) after := self.context.GetState().GetSelectedViewLineIdx() if self.context.GetState().SelectingLine() { checkScrollDown(self.context.GetViewTrait(), self.c.UserConfig(), before, after) } return nil } func (self *PatchExplorerController) HandlePrevLineRange() error { s := self.context.GetState() s.CycleRange(false) return nil } func (self *PatchExplorerController) HandleNextLineRange() error { s := self.context.GetState() s.CycleRange(true) return nil } func (self *PatchExplorerController) HandlePrevHunk() error { self.context.GetState().SelectPreviousHunk() return nil } func (self *PatchExplorerController) HandleNextHunk() error { self.context.GetState().SelectNextHunk() return nil } func (self *PatchExplorerController) HandleToggleSelectRange() error { self.context.GetState().ToggleStickySelectRange() return nil } func (self *PatchExplorerController) HandleToggleSelectHunk() error { self.context.GetState().ToggleSelectHunk() return nil } func (self *PatchExplorerController) HandleScrollLeft() error { self.context.GetViewTrait().ScrollLeft() return nil } func (self *PatchExplorerController) HandleScrollRight() error { self.context.GetViewTrait().ScrollRight() return nil } func (self *PatchExplorerController) HandlePrevPage() error { self.context.GetState().AdjustSelectedLineIdx(-self.context.GetViewTrait().PageDelta()) return nil } func (self *PatchExplorerController) HandleNextPage() error { self.context.GetState().AdjustSelectedLineIdx(self.context.GetViewTrait().PageDelta()) return nil } func (self *PatchExplorerController) HandleGotoTop() error { self.context.GetState().SelectTop() return nil } func (self *PatchExplorerController) HandleGotoBottom() error { self.context.GetState().SelectBottom() return nil } func (self *PatchExplorerController) HandleMouseDown() error { self.context.GetState().SelectNewLineForRange(self.context.GetViewTrait().SelectedLineIdx()) return nil } func (self *PatchExplorerController) HandleMouseDrag() error { self.context.GetState().DragSelectLine(self.context.GetViewTrait().SelectedLineIdx()) return nil } func (self *PatchExplorerController) CopySelectedToClipboard() error { selected := self.context.GetState().PlainRenderSelected() self.c.LogAction(self.c.Tr.Actions.CopySelectedTextToClipboard) if err := self.c.OS().CopyToClipboard(dropDiffPrefix(selected)); err != nil { return err } return nil } // Removes '+' or '-' from the beginning of each line in the diff string, except // when both '+' and '-' lines are present, or diff header lines, in which case // the diff is returned unchanged. This is useful for copying parts of diffs to // the clipboard in order to paste them into code. func dropDiffPrefix(diff string) string { lines := strings.Split(strings.TrimRight(diff, "\n"), "\n") const ( PLUS int = iota MINUS CONTEXT OTHER ) linesByType := lo.GroupBy(lines, func(line string) int { switch { case strings.HasPrefix(line, "+"): return PLUS case strings.HasPrefix(line, "-"): return MINUS case strings.HasPrefix(line, " "): return CONTEXT } return OTHER }) hasLinesOfType := func(lineType int) bool { return len(linesByType[lineType]) > 0 } keepPrefix := hasLinesOfType(OTHER) || (hasLinesOfType(PLUS) && hasLinesOfType(MINUS)) if keepPrefix { return diff } return strings.Join(lo.Map(lines, func(line string, _ int) string { return line[1:] + "\n" }), "") } func (self *PatchExplorerController) isFocused() bool { return self.c.Context().Current().GetKey() == self.context.GetKey() } func (self *PatchExplorerController) withRenderAndFocus(f func() error) func() error { return self.withLock(func() error { if err := f(); err != nil { return err } self.context.RenderAndFocus() return nil }) } func (self *PatchExplorerController) withLock(f func() error) func() error { return func() error { self.context.GetMutex().Lock() defer self.context.GetMutex().Unlock() if self.context.GetState() == nil { return nil } return f() } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/sync_controller.go
pkg/gui/controllers/sync_controller.go
package controllers import ( "errors" "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type SyncController struct { baseController c *ControllerCommon } var _ types.IController = &SyncController{} func NewSyncController( common *ControllerCommon, ) *SyncController { return &SyncController{ baseController: baseController{}, c: common, } } func (self *SyncController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Push), Handler: opts.Guards.NoPopupPanel(self.HandlePush), GetDisabledReason: self.getDisabledReasonForPushOrPull, Description: self.c.Tr.Push, Tooltip: self.c.Tr.PushTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Pull), Handler: opts.Guards.NoPopupPanel(self.HandlePull), GetDisabledReason: self.getDisabledReasonForPushOrPull, Description: self.c.Tr.Pull, Tooltip: self.c.Tr.PullTooltip, }, } return bindings } func (self *SyncController) Context() types.Context { return nil } func (self *SyncController) HandlePush() error { return self.branchCheckedOut(self.push)() } func (self *SyncController) HandlePull() error { return self.branchCheckedOut(self.pull)() } func (self *SyncController) getDisabledReasonForPushOrPull() *types.DisabledReason { currentBranch := self.c.Helpers().Refs.GetCheckedOutRef() if currentBranch != nil { op := self.c.State().GetItemOperation(currentBranch) if op != types.ItemOperationNone { return &types.DisabledReason{Text: self.c.Tr.CantPullOrPushSameBranchTwice} } } return nil } func (self *SyncController) branchCheckedOut(f func(*models.Branch) error) func() error { return func() error { currentBranch := self.c.Helpers().Refs.GetCheckedOutRef() if currentBranch == nil { // need to wait for branches to refresh return nil } return f(currentBranch) } } func (self *SyncController) push(currentBranch *models.Branch) error { // if we are behind our upstream branch we'll ask if the user wants to force push if currentBranch.IsTrackingRemote() { opts := pushOpts{remoteBranchStoredLocally: currentBranch.RemoteBranchStoredLocally()} if currentBranch.IsBehindForPush() { return self.requestToForcePush(currentBranch, opts) } return self.pushAux(currentBranch, opts) } if self.c.Git().Config.GetPushToCurrent() { return self.pushAux(currentBranch, pushOpts{setUpstream: true}) } return self.c.Helpers().Upstream.PromptForUpstreamWithInitialContent(currentBranch, func(upstream string) error { upstreamRemote, upstreamBranch, err := self.c.Helpers().Upstream.ParseUpstream(upstream) if err != nil { return err } return self.pushAux(currentBranch, pushOpts{ setUpstream: true, upstreamRemote: upstreamRemote, upstreamBranch: upstreamBranch, }) }) } func (self *SyncController) pull(currentBranch *models.Branch) error { action := self.c.Tr.Actions.Pull // if we have no upstream branch we need to set that first if !currentBranch.IsTrackingRemote() { return self.c.Helpers().Upstream.PromptForUpstreamWithInitialContent(currentBranch, func(upstream string) error { if err := self.setCurrentBranchUpstream(upstream); err != nil { return err } return self.PullAux(currentBranch, PullFilesOptions{Action: action}) }) } return self.PullAux(currentBranch, PullFilesOptions{Action: action}) } func (self *SyncController) setCurrentBranchUpstream(upstream string) error { upstreamRemote, upstreamBranch, err := self.c.Helpers().Upstream.ParseUpstream(upstream) if err != nil { return err } if err := self.c.Git().Branch.SetCurrentBranchUpstream(upstreamRemote, upstreamBranch); err != nil { if strings.Contains(err.Error(), "does not exist") { return fmt.Errorf( "upstream branch %s/%s not found.\nIf you expect it to exist, you should fetch (with 'f').\nOtherwise, you should push (with 'shift+P')", upstreamRemote, upstreamBranch, ) } return err } return nil } type PullFilesOptions struct { UpstreamRemote string UpstreamBranch string FastForwardOnly bool Action string } func (self *SyncController) PullAux(currentBranch *models.Branch, opts PullFilesOptions) error { return self.c.WithInlineStatus(currentBranch, types.ItemOperationPulling, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error { return self.pullWithLock(task, opts) }) } func (self *SyncController) pullWithLock(task gocui.Task, opts PullFilesOptions) error { self.c.LogAction(opts.Action) err := self.c.Git().Sync.Pull( task, git_commands.PullOptions{ RemoteName: opts.UpstreamRemote, BranchName: opts.UpstreamBranch, FastForwardOnly: opts.FastForwardOnly, }, ) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) } type pushOpts struct { force bool forceWithLease bool upstreamRemote string upstreamBranch string setUpstream bool // If this is false, we can't tell ahead of time whether a force-push will // be necessary, so we start with a normal push and offer to force-push if // the server rejected. If this is true, we don't offer to force-push if the // server rejected, but rather ask the user to fetch. remoteBranchStoredLocally bool } func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts) error { return self.c.WithInlineStatus(currentBranch, types.ItemOperationPushing, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.Push) err := self.c.Git().Sync.Push( task, git_commands.PushOpts{ Force: opts.force, ForceWithLease: opts.forceWithLease, CurrentBranch: currentBranch.Name, UpstreamRemote: opts.upstreamRemote, UpstreamBranch: opts.upstreamBranch, SetUpstream: opts.setUpstream, }) if err != nil { if !opts.force && !opts.forceWithLease && strings.Contains(err.Error(), "Updates were rejected") { if opts.remoteBranchStoredLocally { return errors.New(self.c.Tr.UpdatesRejected) } forcePushDisabled := self.c.UserConfig().Git.DisableForcePushing if forcePushDisabled { return errors.New(self.c.Tr.UpdatesRejectedAndForcePushDisabled) } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.ForcePush, Prompt: self.forcePushPrompt(), HandleConfirm: func() error { newOpts := opts newOpts.force = true return self.pushAux(currentBranch, newOpts) }, }) return nil } return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } func (self *SyncController) requestToForcePush(currentBranch *models.Branch, opts pushOpts) error { forcePushDisabled := self.c.UserConfig().Git.DisableForcePushing if forcePushDisabled { return errors.New(self.c.Tr.ForcePushDisabled) } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.ForcePush, Prompt: self.forcePushPrompt(), HandleConfirm: func() error { opts.forceWithLease = true return self.pushAux(currentBranch, opts) }, }) return nil } func (self *SyncController) forcePushPrompt() string { return utils.ResolvePlaceholderString( self.c.Tr.ForcePushPrompt, map[string]string{ "cancelKey": self.c.UserConfig().Keybinding.Universal.Return, "confirmKey": self.c.UserConfig().Keybinding.Universal.Confirm, }, ) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/snake_controller.go
pkg/gui/controllers/snake_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/snake" ) type SnakeController struct { baseController c *ControllerCommon } var _ types.IController = &SnakeController{} func NewSnakeController( c *ControllerCommon, ) *SnakeController { return &SnakeController{ baseController: baseController{}, c: c, } } func (self *SnakeController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.SetDirection(snake.Down), }, { Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.SetDirection(snake.Up), }, { Key: opts.GetKey(opts.Config.Universal.PrevBlock), Handler: self.SetDirection(snake.Left), }, { Key: opts.GetKey(opts.Config.Universal.NextBlock), Handler: self.SetDirection(snake.Right), }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.Escape, }, } return bindings } func (self *SnakeController) Context() types.Context { return self.c.Contexts().Snake } func (self *SnakeController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { self.c.Helpers().Snake.StartGame() } } func (self *SnakeController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.c.Helpers().Snake.ExitGame() self.c.Helpers().Window.MoveToTopOfWindow(self.c.Contexts().Submodules) } } func (self *SnakeController) SetDirection(direction snake.Direction) func() error { return func() error { self.c.Helpers().Snake.SetDirection(direction) return nil } } func (self *SnakeController) Escape() error { self.c.Context().Push(self.c.Contexts().Submodules, types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/filter_controller.go
pkg/gui/controllers/filter_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" ) type FilterControllerFactory struct { c *ControllerCommon } func NewFilterControllerFactory(c *ControllerCommon) *FilterControllerFactory { return &FilterControllerFactory{ c: c, } } func (self *FilterControllerFactory) Create(context types.IFilterableContext) *FilterController { return &FilterController{ baseController: baseController{}, c: self.c, context: context, } } type FilterController struct { baseController c *ControllerCommon context types.IFilterableContext } func (self *FilterController) Context() types.Context { return self.context } func (self *FilterController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.StartSearch), Handler: self.OpenFilterPrompt, Description: self.c.Tr.StartFilter, }, } } func (self *FilterController) OpenFilterPrompt() error { return self.c.Helpers().Search.OpenFilterPrompt(self.context) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/sub_commits_controller.go
pkg/gui/controllers/sub_commits_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type SubCommitsController struct { baseController *ListControllerTrait[*models.Commit] c *ControllerCommon } var _ types.IController = &SubCommitsController{} func NewSubCommitsController( c *ControllerCommon, ) *SubCommitsController { return &SubCommitsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().SubCommits, c.Contexts().SubCommits.GetSelected, c.Contexts().SubCommits.GetSelectedItems, ), c: c, } } func (self *SubCommitsController) Context() types.Context { return self.context() } func (self *SubCommitsController) context() *context.SubCommitsContext { return self.c.Contexts().SubCommits } func (self *SubCommitsController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { commit := self.context().GetSelected() var task types.UpdateTask if commit == nil { task = types.NewRenderStringTask("No commits") } else { refRange := self.context().GetSelectedRefRangeForDiffFiles() task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff(commit, refRange) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Commit", SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: task, }, }) }) } } func (self *SubCommitsController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { context := self.context() if context.GetSelectedLineIdx() > COMMIT_THRESHOLD && context.GetLimitCommits() { context.SetLimitCommits(false) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.SUB_COMMITS}}) } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/menu_controller.go
pkg/gui/controllers/menu_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type MenuController struct { baseController *ListControllerTrait[*types.MenuItem] c *ControllerCommon } var _ types.IController = &MenuController{} func NewMenuController( c *ControllerCommon, ) *MenuController { return &MenuController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Menu, c.Contexts().Menu.GetSelected, c.Contexts().Menu.GetSelectedItems, ), c: c, } } // NOTE: if you add a new keybinding here, you'll also need to add it to // `reservedKeys` in `pkg/gui/context/menu_context.go` func (self *MenuController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.press), GetDisabledReason: self.require(self.singleItemSelected()), }, { Key: opts.GetKey(opts.Config.Universal.ConfirmMenu), Handler: self.withItem(self.press), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Execute, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.close, Description: self.c.Tr.CloseCancel, DisplayOnScreen: true, }, } return bindings } func (self *MenuController) GetOnClick() func() error { return self.withItemGraceful(self.press) } func (self *MenuController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { selectedMenuItem := self.context().GetSelected() if selectedMenuItem != nil { self.c.Views().Tooltip.SetContent(self.c.Helpers().Confirmation.TooltipForMenuItem(selectedMenuItem)) } } } func (self *MenuController) press(selectedItem *types.MenuItem) error { return self.context().OnMenuPress(selectedItem) } func (self *MenuController) close() error { if self.context().IsFiltering() { self.c.Helpers().Search.Cancel() return nil } self.c.Context().Pop() return nil } func (self *MenuController) context() *context.MenuContext { return self.c.Contexts().Menu }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/custom_patch_options_menu_action.go
pkg/gui/controllers/custom_patch_options_menu_action.go
package controllers import ( "errors" "fmt" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type CustomPatchOptionsMenuAction struct { c *ControllerCommon } func (self *CustomPatchOptionsMenuAction) Call() error { if !self.c.Git().Patch.PatchBuilder.Active() { return errors.New(self.c.Tr.NoPatchError) } if self.c.Git().Patch.PatchBuilder.IsEmpty() { return errors.New(self.c.Tr.EmptyPatchError) } menuItems := []*types.MenuItem{ { Label: self.c.Tr.ResetPatch, Tooltip: self.c.Tr.ResetPatchTooltip, OnPress: self.c.Helpers().PatchBuilding.Reset, Key: 'c', }, { Label: self.c.Tr.ApplyPatch, Tooltip: self.c.Tr.ApplyPatchTooltip, OnPress: func() error { return self.handleApplyPatch(false) }, Key: 'a', }, { Label: self.c.Tr.ApplyPatchInReverse, Tooltip: self.c.Tr.ApplyPatchInReverseTooltip, OnPress: func() error { return self.handleApplyPatch(true) }, Key: 'r', }, } if self.c.Git().Patch.PatchBuilder.CanRebase && self.c.Git().Status.WorkingTreeState().None() { menuItems = append(menuItems, []*types.MenuItem{ { Label: fmt.Sprintf(self.c.Tr.RemovePatchFromOriginalCommit, utils.ShortHash(self.c.Git().Patch.PatchBuilder.To)), Tooltip: self.c.Tr.RemovePatchFromOriginalCommitTooltip, OnPress: self.handleDeletePatchFromCommit, Key: 'd', }, { Label: self.c.Tr.MovePatchOutIntoIndex, Tooltip: self.c.Tr.MovePatchOutIntoIndexTooltip, OnPress: self.handleMovePatchIntoWorkingTree, Key: 'i', }, { Label: self.c.Tr.MovePatchIntoNewCommit, Tooltip: self.c.Tr.MovePatchIntoNewCommitTooltip, OnPress: self.handlePullPatchIntoNewCommit, Key: 'n', }, { Label: self.c.Tr.MovePatchIntoNewCommitBefore, Tooltip: self.c.Tr.MovePatchIntoNewCommitBeforeTooltip, OnPress: self.handlePullPatchIntoNewCommitBefore, Key: 'N', }, }...) if self.c.Context().Current().GetKey() == self.c.Contexts().LocalCommits.GetKey() { selectedCommit := self.c.Contexts().LocalCommits.GetSelected() if selectedCommit != nil && self.c.Git().Patch.PatchBuilder.To != selectedCommit.Hash() { var disabledReason *types.DisabledReason if self.c.Contexts().LocalCommits.AreMultipleItemsSelected() { disabledReason = &types.DisabledReason{Text: self.c.Tr.RangeSelectNotSupported} } // adding this option to index 1 menuItems = append( menuItems[:1], append( []*types.MenuItem{ { Label: fmt.Sprintf(self.c.Tr.MovePatchToSelectedCommit, selectedCommit.Hash()), Tooltip: self.c.Tr.MovePatchToSelectedCommitTooltip, OnPress: self.handleMovePatchToSelectedCommit, Key: 'm', DisabledReason: disabledReason, }, }, menuItems[1:]..., )..., ) } } } menuItems = append(menuItems, []*types.MenuItem{ { Label: self.c.Tr.CopyPatchToClipboard, OnPress: func() error { return self.copyPatchToClipboard() }, Key: 'y', }, }...) return self.c.Menu(types.CreateMenuOptions{Title: self.c.Tr.PatchOptionsTitle, Items: menuItems}) } func (self *CustomPatchOptionsMenuAction) getPatchCommitIndex() int { for index, commit := range self.c.Model().Commits { if commit.Hash() == self.c.Git().Patch.PatchBuilder.To { return index } } return -1 } func (self *CustomPatchOptionsMenuAction) validateNormalWorkingTreeState() (bool, error) { if self.c.Git().Status.WorkingTreeState().Any() { return false, errors.New(self.c.Tr.CantPatchWhileRebasingError) } return true, nil } func (self *CustomPatchOptionsMenuAction) returnFocusFromPatchExplorerIfNecessary() { if self.c.Context().Current().GetKey() == self.c.Contexts().CustomPatchBuilder.GetKey() { self.c.Helpers().PatchBuilding.Escape() } } func (self *CustomPatchOptionsMenuAction) handleDeletePatchFromCommit() error { if ok, err := self.validateNormalWorkingTreeState(); !ok { return err } self.returnFocusFromPatchExplorerIfNecessary() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.RemovePatchFromCommit) err := self.c.Git().Patch.DeletePatchesFromCommit(self.c.Model().Commits, commitIndex) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) } func (self *CustomPatchOptionsMenuAction) handleMovePatchToSelectedCommit() error { if ok, err := self.validateNormalWorkingTreeState(); !ok { return err } self.returnFocusFromPatchExplorerIfNecessary() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.MovePatchToSelectedCommit) err := self.c.Git().Patch.MovePatchToSelectedCommit(self.c.Model().Commits, commitIndex, self.c.Contexts().LocalCommits.GetSelectedLineIdx()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) } func (self *CustomPatchOptionsMenuAction) handleMovePatchIntoWorkingTree() error { if ok, err := self.validateNormalWorkingTreeState(); !ok { return err } self.returnFocusFromPatchExplorerIfNecessary() mustStash := self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() return self.c.ConfirmIf(mustStash, types.ConfirmOpts{ Title: self.c.Tr.MustStashTitle, Prompt: self.c.Tr.MustStashWarning, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoIndex) err := self.c.Git().Patch.MovePatchIntoIndex(self.c.Model().Commits, commitIndex, mustStash) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) }, }) } func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error { if ok, err := self.validateNormalWorkingTreeState(); !ok { return err } self.returnFocusFromPatchExplorerIfNecessary() commitIndex := self.getPatchCommitIndex() self.c.Helpers().Commits.OpenCommitMessagePanel( &helpers.OpenCommitMessagePanelOpts{ // Pass a commit index of one less than the moved-from commit, so that // you can press up arrow once to recall the original commit message: CommitIndex: commitIndex - 1, InitialMessage: "", SummaryTitle: self.c.Tr.CommitSummaryTitle, DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: false, OnConfirm: func(summary string, description string) error { return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) err := self.c.Git().Patch.PullPatchIntoNewCommit(self.c.Model().Commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) return nil }) }, }, ) return nil } func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommitBefore() error { if ok, err := self.validateNormalWorkingTreeState(); !ok { return err } self.returnFocusFromPatchExplorerIfNecessary() commitIndex := self.getPatchCommitIndex() self.c.Helpers().Commits.OpenCommitMessagePanel( &helpers.OpenCommitMessagePanelOpts{ // Pass a commit index of one less than the moved-from commit, so that // you can press up arrow once to recall the original commit message: CommitIndex: commitIndex - 1, InitialMessage: "", SummaryTitle: self.c.Tr.CommitSummaryTitle, DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: false, OnConfirm: func(summary string, description string) error { return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) err := self.c.Git().Patch.PullPatchIntoNewCommitBefore(self.c.Model().Commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) return nil }) }, }, ) return nil } func (self *CustomPatchOptionsMenuAction) handleApplyPatch(reverse bool) error { self.returnFocusFromPatchExplorerIfNecessary() affectedUnstagedFiles := self.getAffectedUnstagedFiles() mustStageFiles := len(affectedUnstagedFiles) > 0 return self.c.ConfirmIf(mustStageFiles, types.ConfirmOpts{ Title: self.c.Tr.MustStageFilesAffectedByPatchTitle, Prompt: self.c.Tr.MustStageFilesAffectedByPatchWarning, HandleConfirm: func() error { action := self.c.Tr.Actions.ApplyPatch if reverse { action = "Apply patch in reverse" } self.c.LogAction(action) if mustStageFiles { if err := self.c.Git().WorkingTree.StageFiles(affectedUnstagedFiles, nil); err != nil { return err } } if err := self.c.Git().Patch.ApplyCustomPatch(reverse, true); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }) } func (self *CustomPatchOptionsMenuAction) copyPatchToClipboard() error { patch := self.c.Git().Patch.PatchBuilder.RenderAggregatedPatch(true) self.c.LogAction(self.c.Tr.Actions.CopyPatchToClipboard) if err := self.c.OS().CopyToClipboard(patch); err != nil { return err } self.c.Toast(self.c.Tr.PatchCopiedToClipboard) return nil } // Returns a list of files that have unstaged changes and are contained in the patch. func (self *CustomPatchOptionsMenuAction) getAffectedUnstagedFiles() []string { unstagedFiles := set.NewFromSlice(lo.FilterMap(self.c.Model().Files, func(f *models.File, _ int) (string, bool) { if f.GetHasUnstagedChanges() { return f.GetPath(), true } return "", false })) return lo.Filter(self.c.Git().Patch.PatchBuilder.AllFilesInPatch(), func(patchFile string, _ int) bool { return unstagedFiles.Includes(patchFile) }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/reflog_commits_controller.go
pkg/gui/controllers/reflog_commits_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type ReflogCommitsController struct { baseController *ListControllerTrait[*models.Commit] c *ControllerCommon } var _ types.IController = &ReflogCommitsController{} func NewReflogCommitsController( c *ControllerCommon, ) *ReflogCommitsController { return &ReflogCommitsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().ReflogCommits, c.Contexts().ReflogCommits.GetSelected, c.Contexts().ReflogCommits.GetSelectedItems, ), c: c, } } func (self *ReflogCommitsController) Context() types.Context { return self.context() } func (self *ReflogCommitsController) context() *context.ReflogCommitsContext { return self.c.Contexts().ReflogCommits } func (self *ReflogCommitsController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { commit := self.context().GetSelected() var task types.UpdateTask if commit == nil { task = types.NewRenderStringTask("No reflog history") } else { cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit)) task = types.NewRunPtyTask(cmdObj.GetCmd()) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Reflog Entry", Task: task, }, }) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/commit_description_controller.go
pkg/gui/controllers/commit_description_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type CommitDescriptionController struct { baseController c *ControllerCommon } var _ types.IController = &CommitMessageController{} func NewCommitDescriptionController( c *ControllerCommon, ) *CommitDescriptionController { return &CommitDescriptionController{ baseController: baseController{}, c: c, } } func (self *CommitDescriptionController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: self.handleTogglePanel, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.close, }, { Key: opts.GetKey(opts.Config.Universal.ConfirmInEditor), Handler: self.confirm, }, { Key: opts.GetKey(opts.Config.Universal.ConfirmInEditorAlt), Handler: self.confirm, }, { Key: opts.GetKey(opts.Config.CommitMessage.CommitMenu), Handler: self.openCommitMenu, }, } return bindings } func (self *CommitDescriptionController) Context() types.Context { return self.c.Contexts().CommitDescription } func (self *CommitDescriptionController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.Context().GetViewName(), FocusedView: self.c.Contexts().CommitMessage.GetViewName(), Key: gocui.MouseLeft, Handler: self.onClick, }, } } func (self *CommitDescriptionController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { footer := "" if self.c.UserConfig().Keybinding.Universal.ConfirmInEditor != "<disabled>" || self.c.UserConfig().Keybinding.Universal.ConfirmInEditorAlt != "<disabled>" { if self.c.UserConfig().Keybinding.Universal.ConfirmInEditor == "<disabled>" { footer = utils.ResolvePlaceholderString(self.c.Tr.CommitDescriptionFooter, map[string]string{ "confirmInEditorKeybinding": keybindings.Label(self.c.UserConfig().Keybinding.Universal.ConfirmInEditorAlt), }) } else if self.c.UserConfig().Keybinding.Universal.ConfirmInEditorAlt == "<disabled>" { footer = utils.ResolvePlaceholderString(self.c.Tr.CommitDescriptionFooter, map[string]string{ "confirmInEditorKeybinding": keybindings.Label(self.c.UserConfig().Keybinding.Universal.ConfirmInEditor), }) } else { footer = utils.ResolvePlaceholderString(self.c.Tr.CommitDescriptionFooterTwoBindings, map[string]string{ "confirmInEditorKeybinding1": keybindings.Label(self.c.UserConfig().Keybinding.Universal.ConfirmInEditor), "confirmInEditorKeybinding2": keybindings.Label(self.c.UserConfig().Keybinding.Universal.ConfirmInEditorAlt), }) } } self.c.Views().CommitDescription.Footer = footer } } func (self *CommitDescriptionController) switchToCommitMessage() error { self.c.Context().Replace(self.c.Contexts().CommitMessage) return nil } func (self *CommitDescriptionController) handleTogglePanel() error { // The default keybinding for this action is "<tab>", which means that we // also get here when pasting multi-line text that contains tabs. In that // case we don't want to toggle the panel, but insert the tab as a character // (somehow, see below). // // Only do this if the TogglePanel command is actually mapped to "<tab>" // (the default). If it's not, we can only hope that it's mapped to some // ctrl key or fn key, which is unlikely to occur in pasted text. And if // they mapped some *other* command to "<tab>", then we're totally out of // luck. if self.c.GocuiGui().IsPasting && self.c.UserConfig().Keybinding.Universal.TogglePanel == "<tab>" { // Handling tabs in pasted commit messages is not optimal, but hopefully // good enough for now. We simply insert 4 spaces without worrying about // column alignment. This works well enough for leading indentation, // which is common in pasted code snippets. view := self.Context().GetView() for range 4 { view.Editor.Edit(view, gocui.KeySpace, ' ', 0) } return nil } return self.switchToCommitMessage() } func (self *CommitDescriptionController) close() error { self.c.Helpers().Commits.CloseCommitMessagePanel() return nil } func (self *CommitDescriptionController) confirm() error { return self.c.Helpers().Commits.HandleCommitConfirm() } func (self *CommitDescriptionController) openCommitMenu() error { authorSuggestion := self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc() return self.c.Helpers().Commits.OpenCommitMenu(authorSuggestion) } func (self *CommitDescriptionController) onClick(opts gocui.ViewMouseBindingOpts) error { self.c.Context().Replace(self.c.Contexts().CommitDescription) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/switch_to_sub_commits_controller.go
pkg/gui/controllers/switch_to_sub_commits_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" ) var _ types.IController = &SwitchToSubCommitsController{} type CanSwitchToSubCommits interface { types.IListContext GetSelectedRef() models.Ref ShowBranchHeadsInSubCommits() bool } // Not using our ListControllerTrait because our 'selected' item is not a list item // but an attribute on it i.e. the ref of an item. type SwitchToSubCommitsController struct { baseController *ListControllerTrait[models.Ref] c *ControllerCommon context CanSwitchToSubCommits } func NewSwitchToSubCommitsController( c *ControllerCommon, context CanSwitchToSubCommits, ) *SwitchToSubCommitsController { return &SwitchToSubCommitsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, context, context.GetSelectedRef, func() ([]models.Ref, int, int) { panic("Not implemented") }, ), c: c, context: context, } } func (self *SwitchToSubCommitsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Handler: self.viewCommits, GetDisabledReason: self.require(self.singleItemSelected()), Key: opts.GetKey(opts.Config.Universal.GoInto), Description: self.c.Tr.ViewCommits, }, } return bindings } func (self *SwitchToSubCommitsController) GetOnClick() func() error { return self.viewCommits } func (self *SwitchToSubCommitsController) viewCommits() error { ref := self.context.GetSelectedRef() if ref == nil { return nil } return self.c.Helpers().SubCommits.ViewSubCommits(helpers.ViewSubCommitsOpts{ Ref: ref, TitleRef: ref.RefName(), Context: self.context, ShowBranchHeads: self.context.ShowBranchHeadsInSubCommits(), }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/options_menu_action.go
pkg/gui/controllers/options_menu_action.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type OptionsMenuAction struct { c *ControllerCommon } func (self *OptionsMenuAction) Call() error { ctx := self.c.Context().Current() local, global, navigation := self.getBindings(ctx) menuItems := []*types.MenuItem{} appendBindings := func(bindings []*types.Binding, section *types.MenuSection) { menuItems = append(menuItems, lo.Map(bindings, func(binding *types.Binding, _ int) *types.MenuItem { var disabledReason *types.DisabledReason if binding.GetDisabledReason != nil { disabledReason = binding.GetDisabledReason() } return &types.MenuItem{ OpensMenu: binding.OpensMenu, Label: binding.GetDescription(), OnPress: func() error { if binding.Handler == nil { return nil } return self.c.IGuiCommon.CallKeybindingHandler(binding) }, Key: binding.Key, Tooltip: binding.Tooltip, DisabledReason: disabledReason, Section: section, } })...) } appendBindings(local, &types.MenuSection{Title: self.c.Tr.KeybindingsMenuSectionLocal, Column: 1}) appendBindings(global, &types.MenuSection{Title: self.c.Tr.KeybindingsMenuSectionGlobal, Column: 1}) appendBindings(navigation, &types.MenuSection{Title: self.c.Tr.KeybindingsMenuSectionNavigation, Column: 1}) return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Keybindings, Items: menuItems, HideCancel: true, ColumnAlignment: []utils.Alignment{utils.AlignRight, utils.AlignLeft}, AllowFilteringKeybindings: true, KeepConflictingKeybindings: true, }) } // Returns three slices of bindings: local, global, and navigation func (self *OptionsMenuAction) getBindings(context types.Context) ([]*types.Binding, []*types.Binding, []*types.Binding) { var bindingsGlobal, bindingsPanel, bindingsNavigation []*types.Binding bindings, _ := self.c.GetInitialKeybindingsWithCustomCommands() for _, binding := range bindings { if binding.GetDescription() != "" { if binding.ViewName == "" || binding.Tag == "global" { bindingsGlobal = append(bindingsGlobal, binding) } else if binding.ViewName == context.GetViewName() { if binding.Tag == "navigation" { bindingsNavigation = append(bindingsNavigation, binding) } else { bindingsPanel = append(bindingsPanel, binding) } } } } return uniqueBindings(bindingsPanel), uniqueBindings(bindingsGlobal), uniqueBindings(bindingsNavigation) } // We shouldn't really need to do this. We should define alternative keys for the same // handler in the keybinding struct. func uniqueBindings(bindings []*types.Binding) []*types.Binding { return lo.UniqBy(bindings, func(binding *types.Binding) string { return binding.GetDescription() }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/git_flow_controller.go
pkg/gui/controllers/git_flow_controller.go
package controllers import ( "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type GitFlowController struct { baseController *ListControllerTrait[*models.Branch] c *ControllerCommon } var _ types.IController = &GitFlowController{} func NewGitFlowController( c *ControllerCommon, ) *GitFlowController { return &GitFlowController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Branches, c.Contexts().Branches.GetSelected, c.Contexts().Branches.GetSelectedItems, ), c: c, } } func (self *GitFlowController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Branches.ViewGitFlowOptions), Handler: self.withItem(self.handleCreateGitFlowMenu), Description: self.c.Tr.GitFlowOptions, OpensMenu: true, }, } return bindings } func (self *GitFlowController) handleCreateGitFlowMenu(branch *models.Branch) error { if !self.c.Git().Flow.GitFlowEnabled() { return errors.New("You need to install git-flow and enable it in this repo to use git-flow features") } startHandler := func(branchType string) func() error { return func() error { title := utils.ResolvePlaceholderString(self.c.Tr.NewGitFlowBranchPrompt, map[string]string{"branchType": branchType}) self.c.Prompt(types.PromptOpts{ Title: title, HandleConfirm: func(name string) error { self.c.LogAction(self.c.Tr.Actions.GitFlowStart) return self.c.RunSubprocessAndRefresh( self.c.Git().Flow.StartCmdObj(branchType, name), ) }, }) return nil } } return self.c.Menu(types.CreateMenuOptions{ Title: "git flow", Items: []*types.MenuItem{ { // not localising here because it's one to one with the actual git flow commands Label: fmt.Sprintf("finish branch '%s'", branch.Name), OnPress: func() error { return self.gitFlowFinishBranch(branch.Name) }, DisabledReason: self.require(self.singleItemSelected())(), }, { Label: "start feature", OnPress: startHandler("feature"), Key: 'f', }, { Label: "start hotfix", OnPress: startHandler("hotfix"), Key: 'h', }, { Label: "start bugfix", OnPress: startHandler("bugfix"), Key: 'b', }, { Label: "start release", OnPress: startHandler("release"), Key: 'r', }, }, }) } func (self *GitFlowController) gitFlowFinishBranch(branchName string) error { cmdObj, err := self.c.Git().Flow.FinishCmdObj(branchName) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.GitFlowFinish) return self.c.RunSubprocessAndRefresh(cmdObj) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/main_view_controller.go
pkg/gui/controllers/main_view_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type MainViewController struct { baseController c *ControllerCommon context *context.MainContext otherContext *context.MainContext } var _ types.IController = &MainViewController{} func NewMainViewController( c *ControllerCommon, context *context.MainContext, otherContext *context.MainContext, ) *MainViewController { return &MainViewController{ baseController: baseController{}, c: c, context: context, otherContext: otherContext, } } func (self *MainViewController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: self.togglePanel, Description: self.c.Tr.ToggleStagingView, Tooltip: self.c.Tr.ToggleStagingViewTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.escape, Description: self.c.Tr.ExitFocusedMainView, DisplayOnScreen: true, }, { // overriding this because we want to read all of the task's output before we start searching Key: opts.GetKey(opts.Config.Universal.StartSearch), Handler: self.openSearch, Description: self.c.Tr.StartSearch, Tag: "navigation", }, } } func (self *MainViewController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.context.GetViewName(), Key: gocui.MouseLeft, Handler: self.onClickInAlreadyFocusedView, FocusedView: self.context.GetViewName(), }, { ViewName: self.context.GetViewName(), Key: gocui.MouseLeft, Handler: self.onClickInOtherViewOfMainViewPair, FocusedView: self.otherContext.GetViewName(), }, } } func (self *MainViewController) Context() types.Context { return self.context } func (self *MainViewController) togglePanel() error { if self.otherContext.GetView().Visible { self.c.Context().Push(self.otherContext, types.OnFocusOpts{}) } return nil } func (self *MainViewController) escape() error { self.c.Context().Pop() return nil } func (self *MainViewController) onClickInAlreadyFocusedView(opts gocui.ViewMouseBindingOpts) error { sidePanelContext := self.c.Context().NextInStack(self.context) if sidePanelContext != nil && sidePanelContext.GetOnClickFocusedMainView() != nil { return sidePanelContext.GetOnClickFocusedMainView()(self.context.GetViewName(), opts.Y) } return nil } func (self *MainViewController) onClickInOtherViewOfMainViewPair(opts gocui.ViewMouseBindingOpts) error { self.c.Context().Push(self.context, types.OnFocusOpts{ ClickedWindowName: self.context.GetWindowName(), ClickedViewLineIdx: opts.Y, }) return nil } func (self *MainViewController) openSearch() error { if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { manager.ReadToEnd(func() { self.c.OnUIThread(func() error { return self.c.Helpers().Search.OpenSearchPrompt(self.context) }) }) } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/scroll_off_margin_test.go
pkg/gui/controllers/scroll_off_margin_test.go
package controllers import ( "testing" "github.com/stretchr/testify/assert" ) func Test_calculateLinesToScrollUp(t *testing.T) { scenarios := []struct { name string viewPortStart int viewPortHeight int scrollOffMargin int lineIdxBefore int lineIdxAfter int expectedLinesToScroll int }{ { name: "before position is above viewport - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 9, lineIdxAfter: 8, expectedLinesToScroll: 0, }, { name: "before position is below viewport - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 20, lineIdxAfter: 19, expectedLinesToScroll: 0, }, { name: "before and after positions are outside scroll-off margin - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 14, lineIdxAfter: 13, expectedLinesToScroll: 0, }, { name: "before outside, after inside scroll-off margin - scroll by 1", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 13, lineIdxAfter: 12, expectedLinesToScroll: 1, }, { name: "scroll-off margin is zero - scroll by 1 at end of view", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 0, lineIdxBefore: 10, lineIdxAfter: 9, expectedLinesToScroll: 1, }, { name: "before inside scroll-off margin - scroll by more than 1", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 11, lineIdxAfter: 10, expectedLinesToScroll: 3, }, { name: "very large scroll-off margin - keep view centered (even viewport height)", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 999, lineIdxBefore: 15, lineIdxAfter: 14, expectedLinesToScroll: 1, }, { name: "very large scroll-off margin - keep view centered (odd viewport height)", viewPortStart: 10, viewPortHeight: 9, scrollOffMargin: 999, lineIdxBefore: 14, lineIdxAfter: 13, expectedLinesToScroll: 1, }, } for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { linesToScroll := calculateLinesToScrollUp(scenario.viewPortStart, scenario.viewPortHeight, scenario.scrollOffMargin, scenario.lineIdxBefore, scenario.lineIdxAfter) assert.Equal(t, scenario.expectedLinesToScroll, linesToScroll) }) } } func Test_calculateLinesToScrollDown(t *testing.T) { scenarios := []struct { name string viewPortStart int viewPortHeight int scrollOffMargin int lineIdxBefore int lineIdxAfter int expectedLinesToScroll int }{ { name: "before position is above viewport - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 9, lineIdxAfter: 10, expectedLinesToScroll: 0, }, { name: "before position is below viewport - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 20, lineIdxAfter: 21, expectedLinesToScroll: 0, }, { name: "before and after positions are outside scroll-off margin - don't scroll", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 15, lineIdxAfter: 16, expectedLinesToScroll: 0, }, { name: "before outside, after inside scroll-off margin - scroll by 1", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 16, lineIdxAfter: 17, expectedLinesToScroll: 1, }, { name: "scroll-off margin is zero - scroll by 1 at end of view", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 0, lineIdxBefore: 19, lineIdxAfter: 20, expectedLinesToScroll: 1, }, { name: "before inside scroll-off margin - scroll by more than 1", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 3, lineIdxBefore: 18, lineIdxAfter: 19, expectedLinesToScroll: 3, }, { name: "very large scroll-off margin - keep view centered (even viewport height)", viewPortStart: 10, viewPortHeight: 10, scrollOffMargin: 999, lineIdxBefore: 15, lineIdxAfter: 16, expectedLinesToScroll: 1, }, { name: "very large scroll-off margin - keep view centered (odd viewport height)", viewPortStart: 10, viewPortHeight: 9, scrollOffMargin: 999, lineIdxBefore: 14, lineIdxAfter: 15, expectedLinesToScroll: 1, }, } for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { linesToScroll := calculateLinesToScrollDown(scenario.viewPortStart, scenario.viewPortHeight, scenario.scrollOffMargin, scenario.lineIdxBefore, scenario.lineIdxAfter) assert.Equal(t, scenario.expectedLinesToScroll, linesToScroll) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/attach.go
pkg/gui/controllers/attach.go
package controllers import "github.com/jesseduffield/lazygit/pkg/gui/types" func AttachControllers(context types.Context, controllers ...types.IController) { for _, controller := range controllers { context.AddKeybindingsFn(controller.GetKeybindings) context.AddMouseKeybindingsFn(controller.GetMouseKeybindings) context.AddOnClickFn(controller.GetOnClick()) context.AddOnClickFocusedMainViewFn(controller.GetOnClickFocusedMainView()) context.AddOnRenderToMainFn(controller.GetOnRenderToMain()) context.AddOnFocusFn(controller.GetOnFocus()) context.AddOnFocusLostFn(controller.GetOnFocusLost()) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/workspace_reset_controller.go
pkg/gui/controllers/workspace_reset_controller.go
package controllers import ( "bytes" "errors" "fmt" "math" "math/rand" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // this is in its own file given that the workspace controller file is already quite long func (self *FilesController) createResetMenu() error { red := style.FgRed nukeStr := "git reset --hard HEAD && git clean -fd" if len(self.c.Model().Submodules) > 0 { nukeStr = fmt.Sprintf("%s (%s)", nukeStr, self.c.Tr.AndResetSubmodules) } menuItems := []*types.MenuItem{ { LabelColumns: []string{ self.c.Tr.DiscardAllChangesToAllFiles, red.Sprint(nukeStr), }, OnPress: func() error { self.c.Confirm( types.ConfirmOpts{ Title: self.c.Tr.Actions.NukeWorkingTree, Prompt: self.c.Tr.NukeTreeConfirmation, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.NukeWorkingTree) if err := self.c.Git().WorkingTree.ResetAndClean(); err != nil { return err } if self.c.UserConfig().Gui.AnimateExplosion { self.animateExplosion() } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, }) return nil }, Key: 'x', Tooltip: self.c.Tr.NukeDescription, }, { LabelColumns: []string{ self.c.Tr.DiscardAnyUnstagedChanges, red.Sprint("git checkout -- ."), }, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.DiscardUnstagedFileChanges) if err := self.c.Git().WorkingTree.DiscardAnyUnstagedFileChanges(); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, Key: 'u', }, { LabelColumns: []string{ self.c.Tr.DiscardUntrackedFiles, red.Sprint("git clean -fd"), }, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RemoveUntrackedFiles) if err := self.c.Git().WorkingTree.RemoveUntrackedFiles(); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, Key: 'c', }, { LabelColumns: []string{ self.c.Tr.DiscardStagedChanges, red.Sprint("stash staged and drop stash"), }, Tooltip: self.c.Tr.DiscardStagedChangesDescription, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RemoveStagedFiles) if !self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() { return errors.New(self.c.Tr.NoTrackedStagedFilesStash) } if err := self.c.Git().Stash.SaveStagedChanges("[lazygit] tmp stash"); err != nil { return err } if err := self.c.Git().Stash.DropNewest(); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, Key: 'S', }, { LabelColumns: []string{ self.c.Tr.SoftReset, red.Sprint("git reset --soft HEAD"), }, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.SoftReset) if err := self.c.Git().WorkingTree.ResetSoft("HEAD"); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, Key: 's', }, { LabelColumns: []string{ "mixed reset", red.Sprint("git reset --mixed HEAD"), }, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.MixedReset) if err := self.c.Git().WorkingTree.ResetMixed("HEAD"); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, Key: 'm', }, { LabelColumns: []string{ self.c.Tr.HardReset, red.Sprint("git reset --hard HEAD"), }, OnPress: func() error { return self.c.ConfirmIf(helpers.IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules), types.ConfirmOpts{ Title: self.c.Tr.Actions.HardReset, Prompt: self.c.Tr.ResetHardConfirmation, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.HardReset) if err := self.c.Git().WorkingTree.ResetHard("HEAD"); err != nil { return err } self.c.Refresh( types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, ) return nil }, }) }, Key: 'h', }, } return self.c.Menu(types.CreateMenuOptions{Title: "", Items: menuItems}) } func (self *FilesController) animateExplosion() { self.Explode(self.c.Views().Files, func() { self.c.PostRefreshUpdate(self.c.Contexts().Files) }) } // Animates an explosion within the view by drawing a bunch of flamey characters func (self *FilesController) Explode(v *gocui.View, onDone func()) { width := v.InnerWidth() height := v.InnerHeight() styles := []style.TextStyle{ style.FgLightWhite.SetBold(), style.FgYellow.SetBold(), style.FgRed.SetBold(), style.FgBlue.SetBold(), style.FgBlack.SetBold(), } self.c.OnWorker(func(_ gocui.Task) error { max := 25 for i := range max { image := getExplodeImage(width, height, i, max) style := styles[(i*len(styles)/max)%len(styles)] coloredImage := style.Sprint(image) self.c.OnUIThread(func() error { v.SetOrigin(0, 0) v.SetContent(coloredImage) return nil }) time.Sleep(time.Millisecond * 20) } self.c.OnUIThread(func() error { v.Clear() onDone() return nil }) return nil }) } // Render an explosion in the given bounds. func getExplodeImage(width int, height int, frame int, max int) string { // Predefine the explosion symbols explosionChars := []rune{'*', '.', '@', '#', '&', '+', '%'} // Initialize a buffer to build our string var buf bytes.Buffer // Initialize RNG seed random := rand.New(rand.NewSource(time.Now().UnixNano())) // calculate the center of explosion centerX, centerY := width/2, height/2 // calculate the max radius (hypotenuse of the view) maxRadius := math.Hypot(float64(centerX), float64(centerY)) // calculate frame as a proportion of max, apply square root to create the non-linear effect progress := math.Sqrt(float64(frame) / float64(max)) // calculate radius of explosion according to frame and max radius := progress * maxRadius * 2 // introduce a new radius for the inner boundary of the explosion (the shockwave effect) var innerRadius float64 if progress > 0.5 { innerRadius = (progress - 0.5) * 2 * maxRadius } for y := range height { for x := range width { // calculate distance from center, scale x by 2 to compensate for character aspect ratio distance := math.Hypot(float64(x-centerX), float64(y-centerY)*2) // if distance is less than radius and greater than innerRadius, draw explosion char if distance <= radius && distance >= innerRadius { // Make placement random and less likely as explosion progresses if random.Float64() > progress { // Pick a random explosion char char := explosionChars[random.Intn(len(explosionChars))] buf.WriteRune(char) } else { buf.WriteRune(' ') } } else { // If not explosion, then it's empty space buf.WriteRune(' ') } } // End of line if y < height-1 { buf.WriteRune('\n') } } return buf.String() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/basic_commits_controller.go
pkg/gui/controllers/basic_commits_controller.go
package controllers import ( "errors" "fmt" "strings" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context/traits" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) // This controller is for all contexts that contain a list of commits. var _ types.IController = &BasicCommitsController{} type ContainsCommits interface { types.Context types.IListContext GetSelected() *models.Commit GetSelectedItems() ([]*models.Commit, int, int) GetCommits() []*models.Commit GetSelectedLineIdx() int GetSelectionRangeAndMode() (int, int, traits.RangeSelectMode) SetSelectionRangeAndMode(int, int, traits.RangeSelectMode) } type BasicCommitsController struct { baseController *ListControllerTrait[*models.Commit] c *ControllerCommon context ContainsCommits } func NewBasicCommitsController(c *ControllerCommon, context ContainsCommits) *BasicCommitsController { return &BasicCommitsController{ baseController: baseController{}, c: c, context: context, ListControllerTrait: NewListControllerTrait( c, context, context.GetSelected, context.GetSelectedItems, ), } } func (self *BasicCommitsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Commits.CheckoutCommit), Handler: self.withItem(self.checkout), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Checkout, Tooltip: self.c.Tr.CheckoutCommitTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.CopyCommitAttributeToClipboard), Handler: self.withItem(self.copyCommitAttribute), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CopyCommitAttributeToClipboard, Tooltip: self.c.Tr.CopyCommitAttributeToClipboardTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.OpenInBrowser), Handler: self.withItem(self.openInBrowser), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenCommitInBrowser, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.withItem(self.newBranch), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CreateNewBranchFromCommit, }, { // Putting this in BasicCommitsController even though we really only want it in the commits // panel. But I find it important that this ends up next to "New Branch", and I couldn't // find another way to achieve this. It's not such a big deal to have it in subcommits and // reflog too, I'd say. Key: opts.GetKey(opts.Config.Branches.MoveCommitsToNewBranch), Handler: self.c.Helpers().Refs.MoveCommitsToNewBranch, GetDisabledReason: self.c.Helpers().Refs.CanMoveCommitsToNewBranch, Description: self.c.Tr.MoveCommitsToNewBranch, Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.withItem(self.createResetMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ViewResetOptions, Tooltip: self.c.Tr.ResetTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.CherryPickCopy), Handler: self.withItem(self.copyRange), GetDisabledReason: self.require(self.itemRangeSelected(self.canCopyCommits)), Description: self.c.Tr.CherryPickCopy, Tooltip: utils.ResolvePlaceholderString(self.c.Tr.CherryPickCopyTooltip, map[string]string{ "paste": keybindings.Label(opts.Config.Commits.PasteCommits), "escape": keybindings.Label(opts.Config.Universal.Return), }, ), DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.ResetCherryPick), Handler: self.c.Helpers().CherryPick.Reset, Description: self.c.Tr.ResetCherryPick, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(self.openDiffTool), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, { Key: opts.GetKey(opts.Config.Commits.SelectCommitsOfCurrentBranch), Handler: self.selectCommitsOfCurrentBranch, GetDisabledReason: self.require(self.canSelectCommitsOfCurrentBranch), Description: self.c.Tr.SelectCommitsOfCurrentBranch, }, // Putting this at the bottom of the list so that it has the lowest priority, // meaning that if the user has configured another keybinding to the same key // then that will take precedence. { // Hardcoding this key because it's not configurable Key: opts.GetKey("c"), Handler: self.handleOldCherryPickKey, }, } return bindings } func (self *BasicCommitsController) getCommitMessageBody(hash string) string { commitMessageBody, err := self.c.Git().Commit.GetCommitMessage(hash) if err != nil { return "" } _, body := self.c.Helpers().Commits.SplitCommitMessageAndDescription(commitMessageBody) return body } func (self *BasicCommitsController) copyCommitAttribute(commit *models.Commit) error { commitMessageBody := self.getCommitMessageBody(commit.Hash()) var commitMessageBodyDisabled *types.DisabledReason if commitMessageBody == "" { commitMessageBodyDisabled = &types.DisabledReason{ Text: self.c.Tr.CommitHasNoMessageBody, } } items := []*types.MenuItem{ { Label: self.c.Tr.CommitHash, OnPress: func() error { return self.copyCommitHashToClipboard(commit) }, }, { Label: self.c.Tr.CommitSubject, OnPress: func() error { return self.copyCommitSubjectToClipboard(commit) }, Key: 's', }, { Label: self.c.Tr.CommitMessage, OnPress: func() error { return self.copyCommitMessageToClipboard(commit) }, Key: 'm', }, { Label: self.c.Tr.CommitMessageBody, DisabledReason: commitMessageBodyDisabled, OnPress: func() error { return self.copyCommitMessageBodyToClipboard(commitMessageBody) }, Key: 'b', }, { Label: self.c.Tr.CommitURL, OnPress: func() error { return self.copyCommitURLToClipboard(commit) }, Key: 'u', }, { Label: self.c.Tr.CommitDiff, OnPress: func() error { return self.copyCommitDiffToClipboard(commit) }, Key: 'd', }, { Label: self.c.Tr.CommitAuthor, OnPress: func() error { return self.copyAuthorToClipboard(commit) }, Key: 'a', }, } commitTagsItem := types.MenuItem{ Label: self.c.Tr.CommitTags, OnPress: func() error { return self.copyCommitTagsToClipboard(commit) }, Key: 't', } if len(commit.Tags) == 0 { commitTagsItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.CommitHasNoTags} } items = append(items, &commitTagsItem) return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Actions.CopyCommitAttributeToClipboard, Items: items, }) } func (self *BasicCommitsController) copyCommitHashToClipboard(commit *models.Commit) error { self.c.LogAction(self.c.Tr.Actions.CopyCommitHashToClipboard) if err := self.c.OS().CopyToClipboard(commit.Hash()); err != nil { return err } self.c.Toast(fmt.Sprintf("'%s' %s", commit.Hash(), self.c.Tr.CopiedToClipboard)) return nil } func (self *BasicCommitsController) copyCommitURLToClipboard(commit *models.Commit) error { url, err := self.c.Helpers().Host.GetCommitURL(commit.Hash()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.CopyCommitURLToClipboard) if err := self.c.OS().CopyToClipboard(url); err != nil { return err } self.c.Toast(self.c.Tr.CommitURLCopiedToClipboard) return nil } func (self *BasicCommitsController) copyCommitDiffToClipboard(commit *models.Commit) error { diff, err := self.c.Git().Commit.GetCommitDiff(commit.Hash()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.CopyCommitDiffToClipboard) if err := self.c.OS().CopyToClipboard(diff); err != nil { return err } self.c.Toast(self.c.Tr.CommitDiffCopiedToClipboard) return nil } func (self *BasicCommitsController) copyAuthorToClipboard(commit *models.Commit) error { author, err := self.c.Git().Commit.GetCommitAuthor(commit.Hash()) if err != nil { return err } formattedAuthor := fmt.Sprintf("%s <%s>", author.Name, author.Email) self.c.LogAction(self.c.Tr.Actions.CopyCommitAuthorToClipboard) if err := self.c.OS().CopyToClipboard(formattedAuthor); err != nil { return err } self.c.Toast(self.c.Tr.CommitAuthorCopiedToClipboard) return nil } func (self *BasicCommitsController) copyCommitMessageToClipboard(commit *models.Commit) error { message, err := self.c.Git().Commit.GetCommitMessage(commit.Hash()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.CopyCommitMessageToClipboard) if err := self.c.OS().CopyToClipboard(message); err != nil { return err } self.c.Toast(self.c.Tr.CommitMessageCopiedToClipboard) return nil } func (self *BasicCommitsController) copyCommitMessageBodyToClipboard(commitMessageBody string) error { self.c.LogAction(self.c.Tr.Actions.CopyCommitMessageBodyToClipboard) if err := self.c.OS().CopyToClipboard(commitMessageBody); err != nil { return err } self.c.Toast(self.c.Tr.CommitMessageBodyCopiedToClipboard) return nil } func (self *BasicCommitsController) copyCommitSubjectToClipboard(commit *models.Commit) error { message, err := self.c.Git().Commit.GetCommitSubject(commit.Hash()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.CopyCommitSubjectToClipboard) if err := self.c.OS().CopyToClipboard(message); err != nil { return err } self.c.Toast(self.c.Tr.CommitSubjectCopiedToClipboard) return nil } func (self *BasicCommitsController) copyCommitTagsToClipboard(commit *models.Commit) error { message := strings.Join(commit.Tags, "\n") self.c.LogAction(self.c.Tr.Actions.CopyCommitTagsToClipboard) if err := self.c.OS().CopyToClipboard(message); err != nil { return err } self.c.Toast(self.c.Tr.CommitTagsCopiedToClipboard) return nil } func (self *BasicCommitsController) openInBrowser(commit *models.Commit) error { url, err := self.c.Helpers().Host.GetCommitURL(commit.Hash()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.OpenCommitInBrowser) if err := self.c.OS().OpenLink(url); err != nil { return err } return nil } func (self *BasicCommitsController) newBranch(commit *models.Commit) error { return self.c.Helpers().Refs.NewBranch(commit.RefName(), commit.Description(), "") } func (self *BasicCommitsController) createResetMenu(commit *models.Commit) error { return self.c.Helpers().Refs.CreateGitResetMenu(commit.Hash(), commit.Hash()) } func (self *BasicCommitsController) checkout(commit *models.Commit) error { return self.c.Helpers().Refs.CreateCheckoutMenu(commit) } func (self *BasicCommitsController) copyRange(*models.Commit) error { return self.c.Helpers().CherryPick.CopyRange(self.context.GetCommits(), self.context) } func (self *BasicCommitsController) canCopyCommits(selectedCommits []*models.Commit, startIdx int, endIdx int) *types.DisabledReason { for _, commit := range selectedCommits { if commit.Hash() == "" { return &types.DisabledReason{Text: self.c.Tr.CannotCherryPickNonCommit, ShowErrorInPanel: true} } } return nil } func (self *BasicCommitsController) handleOldCherryPickKey() error { msg := utils.ResolvePlaceholderString(self.c.Tr.OldCherryPickKeyWarning, map[string]string{ "copy": keybindings.Label(self.c.UserConfig().Keybinding.Commits.CherryPickCopy), "paste": keybindings.Label(self.c.UserConfig().Keybinding.Commits.PasteCommits), }) return errors.New(msg) } func (self *BasicCommitsController) openDiffTool(commit *models.Commit) error { to := commit.RefName() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(commit.ParentRefName()) _, err := self.c.RunSubprocess(self.c.Git().Diff.OpenDiffToolCmdObj( git_commands.DiffToolCmdOptions{ Filepath: ".", FromCommit: from, ToCommit: to, Reverse: reverse, IsDirectory: true, Staged: false, })) return err } func (self *BasicCommitsController) canSelectCommitsOfCurrentBranch() *types.DisabledReason { if index := self.findFirstCommitAfterCurrentBranch(); index <= 0 { return &types.DisabledReason{Text: self.c.Tr.NoCommitsThisBranch} } return nil } func (self *BasicCommitsController) findFirstCommitAfterCurrentBranch() int { _, index, ok := lo.FindIndexOf(self.context.GetCommits(), func(c *models.Commit) bool { return c.IsMerge() || c.Status == models.StatusMerged }) if !ok { return 0 } return index } func (self *BasicCommitsController) selectCommitsOfCurrentBranch() error { index := self.findFirstCommitAfterCurrentBranch() if index <= 0 { return nil } _, _, mode := self.context.GetSelectionRangeAndMode() if mode != traits.RangeSelectModeSticky { // If we are in sticky range mode already, keep that; otherwise, open a non-sticky range mode = traits.RangeSelectModeNonSticky } // Create the range from bottom to top, so that when you cancel the range, // the head commit is selected self.context.SetSelectionRangeAndMode(0, index-1, mode) self.context.HandleFocus(types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/search_controller.go
pkg/gui/controllers/search_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" ) type SearchControllerFactory struct { c *ControllerCommon } func NewSearchControllerFactory(c *ControllerCommon) *SearchControllerFactory { return &SearchControllerFactory{ c: c, } } func (self *SearchControllerFactory) Create(context types.ISearchableContext) *SearchController { return &SearchController{ baseController: baseController{}, c: self.c, context: context, } } type SearchController struct { baseController c *ControllerCommon context types.ISearchableContext } func (self *SearchController) Context() types.Context { return self.context } func (self *SearchController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.StartSearch), Handler: self.OpenSearchPrompt, Description: self.c.Tr.StartSearch, }, } } func (self *SearchController) OpenSearchPrompt() error { return self.c.Helpers().Search.OpenSearchPrompt(self.context) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/bisect_controller.go
pkg/gui/controllers/bisect_controller.go
package controllers import ( "fmt" "strings" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type BisectController struct { baseController *ListControllerTrait[*models.Commit] c *ControllerCommon } var _ types.IController = &BisectController{} func NewBisectController( c *ControllerCommon, ) *BisectController { return &BisectController{ baseController: baseController{}, c: c, ListControllerTrait: NewListControllerTrait( c, c.Contexts().LocalCommits, c.Contexts().LocalCommits.GetSelected, c.Contexts().LocalCommits.GetSelectedItems, ), } } func (self *BisectController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Commits.ViewBisectOptions), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.openMenu)), Description: self.c.Tr.ViewBisectOptions, OpensMenu: true, }, } return bindings } func (self *BisectController) openMenu(commit *models.Commit) error { // no shame in getting this directly rather than using the cached value // given how cheap it is to obtain info := self.c.Git().Bisect.GetInfo() if info.Started() { return self.openMidBisectMenu(info, commit) } return self.openStartBisectMenu(info, commit) } func (self *BisectController) openMidBisectMenu(info *git_commands.BisectInfo, commit *models.Commit) error { // if there is not yet a 'current' bisect commit, or if we have // selected the current commit, we need to jump to the next 'current' commit // after we perform a bisect action. The reason we don't unconditionally jump // is that sometimes the user will want to go and mark a few commits as skipped // in a row and they wouldn't want to be jumped back to the current bisect // commit each time. // Originally we were allowing the user to, from the bisect menu, select whether // they were talking about the selected commit or the current bisect commit, // and that was a bit confusing (and required extra keypresses). selectCurrentAfter := info.GetCurrentHash() == "" || info.GetCurrentHash() == commit.Hash() // we need to wait to reselect if our bisect commits aren't ancestors of our 'start' // ref, because we'll be reloading our commits in that case. waitToReselect := selectCurrentAfter && !self.c.Git().Bisect.ReachableFromStart(info) // If we have a current hash already, then we always want to use that one. If // not, we're still picking the initial commits before we really start, so // use the selected commit in that case. bisecting := info.GetCurrentHash() != "" hashToMark := lo.Ternary(bisecting, info.GetCurrentHash(), commit.Hash()) shortHashToMark := utils.ShortHash(hashToMark) // For marking a commit as bad, when we're not already bisecting, we require // a single item selected, but once we are bisecting, it doesn't matter because // the action applies to the HEAD commit rather than the selected commit. var singleItemIfNotBisecting *types.DisabledReason if !bisecting { singleItemIfNotBisecting = self.require(self.singleItemSelected())() } menuItems := []*types.MenuItem{ { Label: fmt.Sprintf(self.c.Tr.Bisect.Mark, shortHashToMark, info.NewTerm()), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.BisectMark) if err := self.c.Git().Bisect.Mark(hashToMark, info.NewTerm()); err != nil { return err } return self.afterMark(selectCurrentAfter, waitToReselect) }, DisabledReason: singleItemIfNotBisecting, Key: 'b', }, { Label: fmt.Sprintf(self.c.Tr.Bisect.Mark, shortHashToMark, info.OldTerm()), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.BisectMark) if err := self.c.Git().Bisect.Mark(hashToMark, info.OldTerm()); err != nil { return err } return self.afterMark(selectCurrentAfter, waitToReselect) }, DisabledReason: singleItemIfNotBisecting, Key: 'g', }, { Label: fmt.Sprintf(self.c.Tr.Bisect.SkipCurrent, shortHashToMark), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.BisectSkip) if err := self.c.Git().Bisect.Skip(hashToMark); err != nil { return err } return self.afterMark(selectCurrentAfter, waitToReselect) }, DisabledReason: singleItemIfNotBisecting, Key: 's', }, } if info.GetCurrentHash() != "" && info.GetCurrentHash() != commit.Hash() { menuItems = append(menuItems, lo.ToPtr(types.MenuItem{ Label: fmt.Sprintf(self.c.Tr.Bisect.SkipSelected, commit.ShortHash()), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.BisectSkip) if err := self.c.Git().Bisect.Skip(commit.Hash()); err != nil { return err } return self.afterMark(selectCurrentAfter, waitToReselect) }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'S', })) } menuItems = append(menuItems, lo.ToPtr(types.MenuItem{ Label: self.c.Tr.Bisect.ResetOption, OnPress: func() error { return self.c.Helpers().Bisect.Reset() }, Key: 'r', })) return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Bisect.BisectMenuTitle, Items: menuItems, }) } func (self *BisectController) openStartBisectMenu(info *git_commands.BisectInfo, commit *models.Commit) error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Bisect.BisectMenuTitle, Items: []*types.MenuItem{ { Label: fmt.Sprintf(self.c.Tr.Bisect.MarkStart, commit.ShortHash(), info.NewTerm()), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.StartBisect) if err := self.c.Git().Bisect.Start(); err != nil { return err } if err := self.c.Git().Bisect.Mark(commit.Hash(), info.NewTerm()); err != nil { return err } self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'b', }, { Label: fmt.Sprintf(self.c.Tr.Bisect.MarkStart, commit.ShortHash(), info.OldTerm()), OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.StartBisect) if err := self.c.Git().Bisect.Start(); err != nil { return err } if err := self.c.Git().Bisect.Mark(commit.Hash(), info.OldTerm()); err != nil { return err } self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'g', }, { Label: self.c.Tr.Bisect.ChooseTerms, OnPress: func() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.Bisect.OldTermPrompt, HandleConfirm: func(oldTerm string) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.Bisect.NewTermPrompt, HandleConfirm: func(newTerm string) error { self.c.LogAction(self.c.Tr.Actions.StartBisect) if err := self.c.Git().Bisect.StartWithTerms(oldTerm, newTerm); err != nil { return err } self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil }, }) return nil }, }) return nil }, Key: 't', }, }, }) } func (self *BisectController) showBisectCompleteMessage(candidateHashes []string) error { prompt := self.c.Tr.Bisect.CompletePrompt if len(candidateHashes) > 1 { prompt = self.c.Tr.Bisect.CompletePromptIndeterminate } formattedCommits, err := self.c.Git().Commit.GetCommitsOneline(candidateHashes) if err != nil { return err } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Bisect.CompleteTitle, Prompt: fmt.Sprintf(prompt, strings.TrimSpace(formattedCommits)), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.ResetBisect) if err := self.c.Git().Bisect.Reset(); err != nil { return err } self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil }, }) return nil } func (self *BisectController) afterMark(selectCurrent bool, waitToReselect bool) error { done, candidateHashes, err := self.c.Git().Bisect.IsDone() if err != nil { return err } if err := self.afterBisectMarkRefresh(selectCurrent, waitToReselect); err != nil { return err } if done { return self.showBisectCompleteMessage(candidateHashes) } return nil } func (self *BisectController) afterBisectMarkRefresh(selectCurrent bool, waitToReselect bool) error { selectFn := func() { if selectCurrent { self.selectCurrentBisectCommit() } } if waitToReselect { self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{}, Then: selectFn}) return nil } selectFn() self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil } func (self *BisectController) selectCurrentBisectCommit() { info := self.c.Git().Bisect.GetInfo() if info.GetCurrentHash() != "" { // find index of commit with that hash, move cursor to that. for i, commit := range self.c.Model().Commits { if commit.Hash() == info.GetCurrentHash() { self.context().SetSelection(i) self.context().HandleFocus(types.OnFocusOpts{}) break } } } } func (self *BisectController) context() *context.LocalCommitsContext { return self.c.Contexts().LocalCommits }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/stash_controller.go
pkg/gui/controllers/stash_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type StashController struct { baseController *ListControllerTrait[*models.StashEntry] c *ControllerCommon } var _ types.IController = &StashController{} func NewStashController( c *ControllerCommon, ) *StashController { return &StashController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Stash, c.Contexts().Stash.GetSelected, c.Contexts().Stash.GetSelectedItems, ), c: c, } } func (self *StashController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.handleStashApply), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Apply, Tooltip: self.c.Tr.StashApplyTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Stash.PopStash), Handler: self.withItem(self.handleStashPop), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Pop, Tooltip: self.c.Tr.StashPopTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItems(self.handleStashDrop), GetDisabledReason: self.require(self.itemRangeSelected()), Description: self.c.Tr.Drop, Tooltip: self.c.Tr.StashDropTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.withItem(self.handleNewBranchOffStashEntry), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.NewBranch, Tooltip: self.c.Tr.NewBranchFromStashTooltip, }, { Key: opts.GetKey(opts.Config.Stash.RenameStash), Handler: self.withItem(self.handleRenameStashEntry), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.RenameStash, }, } return bindings } func (self *StashController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask stashEntry := self.context().GetSelected() if stashEntry == nil { task = types.NewRenderStringTask(self.c.Tr.NoStashEntries) } else { prefix := style.FgYellow.Sprintf("%s\n\n", stashEntry.Description()) task = types.NewRunPtyTaskWithPrefix( self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index).GetCmd(), prefix, ) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Stash", SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: task, }, }) }) } } func (self *StashController) context() *context.StashContext { return self.c.Contexts().Stash } func (self *StashController) handleStashApply(stashEntry *models.StashEntry) error { return self.c.ConfirmIf(!self.c.UserConfig().Gui.SkipStashWarning, types.ConfirmOpts{ Title: self.c.Tr.StashApply, Prompt: self.c.Tr.SureApplyStashEntry, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.ApplyStash) err := self.c.Git().Stash.Apply(stashEntry.Index) self.postStashRefresh() if err != nil { return err } if self.c.UserConfig().Gui.SwitchToFilesAfterStashApply { self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) } return nil }, }) } func (self *StashController) handleStashPop(stashEntry *models.StashEntry) error { pop := func() error { self.c.LogAction(self.c.Tr.Actions.PopStash) self.c.LogCommand("Popping stash "+stashEntry.Hash, false) err := self.c.Git().Stash.Pop(stashEntry.Index) self.postStashRefresh() if err != nil { return err } if self.c.UserConfig().Gui.SwitchToFilesAfterStashPop { self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) } return nil } if self.c.UserConfig().Gui.SkipStashWarning { return pop() } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.StashPop, Prompt: self.c.Tr.SurePopStashEntry, HandleConfirm: func() error { return pop() }, }) return nil } func (self *StashController) handleStashDrop(stashEntries []*models.StashEntry) error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.StashDrop, Prompt: self.c.Tr.SureDropStashEntry, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.DropStash) for i := len(stashEntries) - 1; i >= 0; i-- { self.c.LogCommand("Dropping stash "+stashEntries[i].Hash, false) err := self.c.Git().Stash.Drop(stashEntries[i].Index) self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) if err != nil { return err } } self.context().CollapseRangeSelectionToTop() return nil }, }) return nil } func (self *StashController) postStashRefresh() { self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH, types.FILES}}) } func (self *StashController) handleNewBranchOffStashEntry(stashEntry *models.StashEntry) error { return self.c.Helpers().Refs.NewBranch(stashEntry.FullRefName(), stashEntry.Description(), "") } func (self *StashController) handleRenameStashEntry(stashEntry *models.StashEntry) error { message := utils.ResolvePlaceholderString( self.c.Tr.RenameStashPrompt, map[string]string{ "stashName": stashEntry.RefName(), }, ) self.c.Prompt(types.PromptOpts{ Title: message, InitialContent: stashEntry.Name, HandleConfirm: func(response string) error { self.c.LogAction(self.c.Tr.Actions.RenameStash) err := self.c.Git().Stash.Rename(stashEntry.Index, response) if err != nil { self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) return err } self.context().SetSelection(0) // Select the renamed stash self.context().FocusLine(true) self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) return nil }, AllowEmptyInput: true, }) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/switch_to_focused_main_view_controller.go
pkg/gui/controllers/switch_to_focused_main_view_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // This controller is for all contexts that can focus their main view. var _ types.IController = &SwitchToFocusedMainViewController{} type SwitchToFocusedMainViewController struct { baseController c *ControllerCommon context types.Context } func NewSwitchToFocusedMainViewController( c *ControllerCommon, context types.Context, ) *SwitchToFocusedMainViewController { return &SwitchToFocusedMainViewController{ baseController: baseController{}, c: c, context: context, } } func (self *SwitchToFocusedMainViewController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.FocusMainView), Handler: self.handleFocusMainView, Description: self.c.Tr.FocusMainView, Tag: "global", }, } return bindings } func (self *SwitchToFocusedMainViewController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: "main", Key: gocui.MouseLeft, Handler: self.onClickMain, FocusedView: self.context.GetViewName(), }, { ViewName: "secondary", Key: gocui.MouseLeft, Handler: self.onClickSecondary, FocusedView: self.context.GetViewName(), }, } } func (self *SwitchToFocusedMainViewController) Context() types.Context { return self.context } func (self *SwitchToFocusedMainViewController) onClickMain(opts gocui.ViewMouseBindingOpts) error { return self.focusMainView(self.c.Contexts().Normal) } func (self *SwitchToFocusedMainViewController) onClickSecondary(opts gocui.ViewMouseBindingOpts) error { return self.focusMainView(self.c.Contexts().NormalSecondary) } func (self *SwitchToFocusedMainViewController) handleFocusMainView() error { return self.focusMainView(self.c.Contexts().Normal) } func (self *SwitchToFocusedMainViewController) focusMainView(mainViewContext types.Context) error { if context, ok := mainViewContext.(types.ISearchableContext); ok { context.ClearSearchString() } self.c.Context().Push(mainViewContext, types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/switch_to_diff_files_controller.go
pkg/gui/controllers/switch_to_diff_files_controller.go
package controllers import ( "path/filepath" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // This controller is for all contexts that contain commit files. var _ types.IController = &SwitchToDiffFilesController{} type CanSwitchToDiffFiles interface { types.IListContext CanRebase() bool GetSelectedRef() models.Ref GetSelectedRefRangeForDiffFiles() *types.RefRange } // Not using our ListControllerTrait because we have our own way of working with // range selections that's different from ListControllerTrait's type SwitchToDiffFilesController struct { baseController c *ControllerCommon context CanSwitchToDiffFiles } func NewSwitchToDiffFilesController( c *ControllerCommon, context CanSwitchToDiffFiles, ) *SwitchToDiffFilesController { return &SwitchToDiffFilesController{ baseController: baseController{}, c: c, context: context, } } func (self *SwitchToDiffFilesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.enter, GetDisabledReason: self.canEnter, Description: self.c.Tr.ViewItemFiles, }, } return bindings } func (self *SwitchToDiffFilesController) Context() types.Context { return self.context } func (self *SwitchToDiffFilesController) GetOnClick() func() error { return func() error { if self.canEnter() == nil { return self.enter() } return nil } } func (self *SwitchToDiffFilesController) enter() error { ref := self.context.GetSelectedRef() refsRange := self.context.GetSelectedRefRangeForDiffFiles() commitFilesContext := self.c.Contexts().CommitFiles canRebase := self.context.CanRebase() if canRebase { if self.c.Modes().Diffing.Active() { if self.c.Modes().Diffing.Ref != ref.RefName() { canRebase = false } } else if refsRange != nil { canRebase = false } } commitFilesContext.ReInit(ref, refsRange) commitFilesContext.SetSelection(0) commitFilesContext.SetCanRebase(canRebase) commitFilesContext.SetParentContext(self.context) commitFilesContext.SetWindowName(self.context.GetWindowName()) commitFilesContext.ClearSearchString() commitFilesContext.GetView().TitlePrefix = self.context.GetView().TitlePrefix self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.COMMIT_FILES}, }) if filterPath := self.c.Modes().Filtering.GetPath(); filterPath != "" { path, err := filepath.Rel(self.c.Git().RepoPaths.RepoPath(), filterPath) if err != nil { path = filterPath } commitFilesContext.CommitFileTreeViewModel.SelectPath( filepath.ToSlash(path), self.c.UserConfig().Gui.ShowRootItemInFileTree) } self.c.Context().Push(commitFilesContext, types.OnFocusOpts{}) return nil } func (self *SwitchToDiffFilesController) canEnter() *types.DisabledReason { refRange := self.context.GetSelectedRefRangeForDiffFiles() if refRange != nil { return nil } ref := self.context.GetSelectedRef() if ref == nil { return &types.DisabledReason{Text: self.c.Tr.NoItemSelected} } if ref.RefName() == "" { return &types.DisabledReason{Text: self.c.Tr.SelectedItemDoesNotHaveFiles} } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/remotes_controller.go
pkg/gui/controllers/remotes_controller.go
package controllers import ( "errors" "fmt" "regexp" "slices" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type RemotesController struct { baseController *ListControllerTrait[*models.Remote] c *ControllerCommon setRemoteBranches func([]*models.RemoteBranch) } var _ types.IController = &RemotesController{} func NewRemotesController( c *ControllerCommon, setRemoteBranches func([]*models.RemoteBranch), ) *RemotesController { return &RemotesController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Remotes, c.Contexts().Remotes.GetSelected, c.Contexts().Remotes.GetSelectedItems, ), c: c, setRemoteBranches: setRemoteBranches, } } func (self *RemotesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ViewBranches, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.add, Description: self.c.Tr.NewRemote, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItem(self.remove), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Remove, Tooltip: self.c.Tr.RemoveRemoteTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.withItem(self.edit), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Edit, Tooltip: self.c.Tr.EditRemoteTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.FetchRemote), Handler: self.withItem(self.fetch), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Fetch, Tooltip: self.c.Tr.FetchRemoteTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.AddForkRemote), Handler: self.addFork, GetDisabledReason: self.hasOriginRemote(), Description: self.c.Tr.AddForkRemote, Tooltip: self.c.Tr.AddForkRemoteTooltip, DisplayOnScreen: true, }, } return bindings } func (self *RemotesController) context() *context.RemotesContext { return self.c.Contexts().Remotes } func (self *RemotesController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask remote := self.context().GetSelected() if remote == nil { task = types.NewRenderStringTask("No remotes") } else { task = types.NewRenderStringTask(fmt.Sprintf("%s\nUrls:\n%s", style.FgGreen.Sprint(remote.Name), strings.Join(remote.Urls, "\n"))) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Remote", Task: task, }, }) }) } } func (self *RemotesController) GetOnClick() func() error { return self.withItemGraceful(self.enter) } func (self *RemotesController) enter(remote *models.Remote) error { // naive implementation: get the branches from the remote and render them to the list, change the context self.setRemoteBranches(remote.Branches) newSelectedLine := 0 if len(remote.Branches) == 0 { newSelectedLine = -1 } remoteBranchesContext := self.c.Contexts().RemoteBranches remoteBranchesContext.SetSelection(newSelectedLine) remoteBranchesContext.SetTitleRef(remote.Name) remoteBranchesContext.SetParentContext(self.Context()) remoteBranchesContext.GetView().TitlePrefix = self.Context().GetView().TitlePrefix self.c.PostRefreshUpdate(remoteBranchesContext) self.c.Context().Push(remoteBranchesContext, types.OnFocusOpts{}) return nil } // Adds a new remote, refreshes and selects it, then fetches and checks out the specified branch if provided. func (self *RemotesController) addAndCheckoutRemote(remoteName string, remoteUrl string, branchToCheckout string) error { err := self.c.Git().Remote.AddRemote(remoteName, remoteUrl) if err != nil { return err } // Do a sync refresh of the remotes so that we can select // the new one. Loading remotes is not expensive, so we can // afford it. self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.REMOTES}, Mode: types.SYNC, }) // Select the remote for idx, remote := range self.c.Model().Remotes { if remote.Name == remoteName { self.c.Contexts().Remotes.SetSelection(idx) break } } // Fetch the remote return self.fetchAndCheckout(self.c.Contexts().Remotes.GetSelected(), branchToCheckout) } // Ensures the fork remote exists (matching the given URL). // If it exists and matches, itโ€™s selected and fetched; otherwise, itโ€™s created and then fetched and checked out. // If it does exist but with a different URL, an error is returned. func (self *RemotesController) ensureForkRemoteAndCheckout(remoteName string, remoteUrl string, branchToCheckout string) error { for idx, remote := range self.c.Model().Remotes { if remote.Name == remoteName { hasTheSameUrl := slices.Contains(remote.Urls, remoteUrl) if !hasTheSameUrl { return errors.New(utils.ResolvePlaceholderString( self.c.Tr.IncompatibleForkAlreadyExistsError, map[string]string{ "remoteName": remoteName, }, )) } self.c.Contexts().Remotes.SetSelection(idx) return self.fetchAndCheckout(remote, branchToCheckout) } } return self.addAndCheckoutRemote(remoteName, remoteUrl, branchToCheckout) } func (self *RemotesController) add() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewRemoteName, HandleConfirm: func(remoteName string) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewRemoteUrl, HandleConfirm: func(remoteUrl string) error { self.c.LogAction(self.c.Tr.Actions.AddRemote) return self.addAndCheckoutRemote(remoteName, remoteUrl, "") }, }) return nil }, }) return nil } // Regex to match and capture parts of a Git remote URL. Supports the following formats: // 1. SCP-like SSH: git@host:owner[/subgroups]/repo(.git) // 2. SSH URL style: ssh://user@host[:port]/owner[/subgroups]/repo(.git) // 3. HTTPS: https://host/owner[/subgroups]/repo(.git) // 4. Only for integration tests: ../repo_name var ( urlRegex = regexp.MustCompile(`^(git@[^:]+:|ssh://[^/]+/|https?://[^/]+/)([^/]+(?:/[^/]+)*)/([^/]+?)(\.git)?$`) integrationTestUrlRegex = regexp.MustCompile(`^\.\./.+$`) ) // Rewrites a Git remote URL to use the given fork username, // keeping the repo name and host intact. Supports SCP-like SSH, SSH URL style, and HTTPS. func replaceForkUsername(originUrl, forkUsername string, isIntegrationTest bool) (string, error) { if urlRegex.MatchString(originUrl) { return urlRegex.ReplaceAllString(originUrl, "${1}"+forkUsername+"/$3$4"), nil } else if isIntegrationTest && integrationTestUrlRegex.MatchString(originUrl) { return "../" + forkUsername, nil } return "", fmt.Errorf("unsupported or invalid remote URL: %s", originUrl) } func (self *RemotesController) getOrigin() *models.Remote { for _, remote := range self.c.Model().Remotes { if remote.Name == "origin" { return remote } } return nil } func (self *RemotesController) hasOriginRemote() func() *types.DisabledReason { return func() *types.DisabledReason { if self.getOrigin() == nil { return &types.DisabledReason{Text: self.c.Tr.NoOriginRemote} } return nil } } func (self *RemotesController) addFork() error { origin := self.getOrigin() self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.AddForkRemoteUsername, HandleConfirm: func(forkUsername string) error { branchToCheckout := "" parts := strings.SplitN(forkUsername, ":", 2) if len(parts) == 2 { forkUsername = parts[0] branchToCheckout = parts[1] } originUrl := origin.Urls[0] remoteUrl, err := replaceForkUsername(originUrl, forkUsername, self.c.RunningIntegrationTest()) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.AddForkRemote) return self.ensureForkRemoteAndCheckout(forkUsername, remoteUrl, branchToCheckout) }, }) return nil } func (self *RemotesController) remove(remote *models.Remote) error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.RemoveRemote, Prompt: self.c.Tr.RemoveRemotePrompt + " '" + remote.Name + "'?", HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.RemoveRemote) if err := self.c.Git().Remote.RemoveRemote(remote.Name); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }, }) return nil } func (self *RemotesController) edit(remote *models.Remote) error { editNameMessage := utils.ResolvePlaceholderString( self.c.Tr.EditRemoteName, map[string]string{ "remoteName": remote.Name, }, ) self.c.Prompt(types.PromptOpts{ Title: editNameMessage, InitialContent: remote.Name, HandleConfirm: func(updatedRemoteName string) error { if updatedRemoteName != remote.Name { self.c.LogAction(self.c.Tr.Actions.UpdateRemote) if err := self.c.Git().Remote.RenameRemote(remote.Name, updatedRemoteName); err != nil { return err } } editUrlMessage := utils.ResolvePlaceholderString( self.c.Tr.EditRemoteUrl, map[string]string{ "remoteName": updatedRemoteName, }, ) urls := remote.Urls url := "" if len(urls) > 0 { url = urls[0] } self.c.Prompt(types.PromptOpts{ Title: editUrlMessage, InitialContent: url, HandleConfirm: func(updatedRemoteUrl string) error { self.c.LogAction(self.c.Tr.Actions.UpdateRemote) if err := self.c.Git().Remote.UpdateRemoteUrl(updatedRemoteName, updatedRemoteUrl); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }, }) return nil }, }) return nil } func (self *RemotesController) fetch(remote *models.Remote) error { return self.fetchAndCheckout(remote, "") } func (self *RemotesController) fetchAndCheckout(remote *models.Remote, branchName string) error { return self.c.WithInlineStatus(remote, types.ItemOperationFetching, context.REMOTES_CONTEXT_KEY, func(task gocui.Task) error { err := self.c.Git().Sync.FetchRemote(task, remote.Name) if err != nil { return err } refreshOptions := types.RefreshOptions{ Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}, Mode: types.ASYNC, } if branchName != "" { err = self.c.Git().Branch.New(branchName, remote.Name+"/"+branchName) if err == nil { self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) self.c.Helpers().Refs.SelectFirstBranchAndFirstCommit() refreshOptions.KeepBranchSelectionIndex = true } } self.c.Refresh(refreshOptions) return err }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/base_controller.go
pkg/gui/controllers/base_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type baseController struct{} func (self *baseController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return nil } func (self *baseController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return nil } func (self *baseController) GetOnClick() func() error { return nil } func (self *baseController) GetOnClickFocusedMainView() func(mainViewName string, clickedLineIdx int) error { return nil } func (self *baseController) GetOnRenderToMain() func() { return nil } func (self *baseController) GetOnFocus() func(types.OnFocusOpts) { return nil } func (self *baseController) GetOnFocusLost() func(types.OnFocusLostOpts) { return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/remotes_controller_test.go
pkg/gui/controllers/remotes_controller_test.go
package controllers import ( "testing" "github.com/stretchr/testify/assert" ) func TestReplaceForkUsername_SSH_OK(t *testing.T) { cases := []struct { name string in string forkUser string expected string }{ { name: "github ssh scp-like basic", in: "git@github.com:old/repo.git", forkUser: "new", expected: "git@github.com:new/repo.git", }, { name: "ssh scp-like no .git", in: "git@github.com:old/repo", forkUser: "new", expected: "git@github.com:new/repo", }, { name: "gitlab subgroup ssh scp-like", in: "git@gitlab.com:group/sub/repo.git", forkUser: "alice", expected: "git@gitlab.com:alice/repo.git", }, { name: "ssh url style basic", in: "ssh://git@github.com/old/repo.git", forkUser: "new", expected: "ssh://git@github.com/new/repo.git", }, { name: "ssh url style with port", in: "ssh://git@github.com:2222/old/repo.git", forkUser: "bob", expected: "ssh://git@github.com:2222/bob/repo.git", }, { name: "ssh url style multi subgroup", in: "ssh://git@gitlab.com/group/sub/repo.git", forkUser: "alice", expected: "ssh://git@gitlab.com/alice/repo.git", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { got, err := replaceForkUsername(c.in, c.forkUser, false) assert.NoError(t, err) assert.Equal(t, c.expected, got) }) } } func TestReplaceForkUsername_HTTPS_OK(t *testing.T) { cases := []struct { name string in string forkUser string expected string }{ { name: "github https basic", in: "https://github.com/old/repo.git", forkUser: "new", expected: "https://github.com/new/repo.git", }, { name: "https no .git", in: "https://github.com/old/repo", forkUser: "new", expected: "https://github.com/new/repo", }, { name: "https with port", in: "https://git.example.com:8443/group/repo", forkUser: "me", expected: "https://git.example.com:8443/me/repo", }, { name: "gitlab multi subgroup https", in: "https://gitlab.com/group/sub/sub2/repo", forkUser: "bob", expected: "https://gitlab.com/bob/repo", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { got, err := replaceForkUsername(c.in, c.forkUser, false) assert.NoError(t, err) assert.Equal(t, c.expected, got) }) } } func TestReplaceForkUsername_IntegrationTest_OK(t *testing.T) { got, err := replaceForkUsername("../origin", "bob", true) assert.NoError(t, err) assert.Equal(t, "../bob", got) } func TestReplaceForkUsername_Errors(t *testing.T) { cases := []struct { name string in string forkUser string }{ { name: "https host only", in: "https://github.com", forkUser: "x", }, { name: "https host slash only", in: "https://github.com/", forkUser: "x", }, { name: "https only repo (no owner)", in: "https://github.com/repo.git", forkUser: "x", }, { name: "ssh missing path", in: "git@github.com", forkUser: "x", }, { name: "ssh one segment only", in: "git@github.com:repo.git", forkUser: "x", }, { name: "unsupported scheme", in: "ftp://github.com/old/repo.git", forkUser: "x", }, { name: "empty url", in: "", forkUser: "x", }, { name: "integration test URL outside of integration test", in: "../origin", forkUser: "x", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { _, err := replaceForkUsername(c.in, c.forkUser, false) assert.EqualError(t, err, "unsupported or invalid remote URL: "+c.in) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/command_log_controller.go
pkg/gui/controllers/command_log_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" ) type CommandLogController struct { baseController c *ControllerCommon } var _ types.IController = &CommandLogController{} func NewCommandLogController( c *ControllerCommon, ) *CommandLogController { return &CommandLogController{ baseController: baseController{}, c: c, } } func (self *CommandLogController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{} return bindings } func (self *CommandLogController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.c.Views().Extras.Autoscroll = true } } func (self *CommandLogController) Context() types.Context { return self.context() } func (self *CommandLogController) context() types.Context { return self.c.Contexts().CommandLog }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/filtering_menu_action.go
pkg/gui/controllers/filtering_menu_action.go
package controllers import ( "fmt" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type FilteringMenuAction struct { c *ControllerCommon } func (self *FilteringMenuAction) Call() error { fileName := "" author := "" switch self.c.Context().CurrentSide() { case self.c.Contexts().Files: node := self.c.Contexts().Files.GetSelected() if node != nil { fileName = node.GetPath() } case self.c.Contexts().CommitFiles: node := self.c.Contexts().CommitFiles.GetSelected() if node != nil { fileName = node.GetPath() } case self.c.Contexts().LocalCommits: commit := self.c.Contexts().LocalCommits.GetSelected() if commit != nil { author = fmt.Sprintf("%s <%s>", commit.AuthorName, commit.AuthorEmail) } } menuItems := []*types.MenuItem{} tooltip := "" if self.c.Modes().Filtering.Active() { tooltip = self.c.Tr.WillCancelExistingFilterTooltip } if fileName != "" { menuItems = append(menuItems, &types.MenuItem{ Label: fmt.Sprintf("%s '%s'", self.c.Tr.FilterBy, fileName), OnPress: func() error { return self.setFilteringPath(fileName) }, Tooltip: tooltip, }) } if author != "" { menuItems = append(menuItems, &types.MenuItem{ Label: fmt.Sprintf("%s '%s'", self.c.Tr.FilterBy, author), OnPress: func() error { return self.setFilteringAuthor(author) }, Tooltip: tooltip, }) } menuItems = append(menuItems, &types.MenuItem{ Label: self.c.Tr.FilterPathOption, OnPress: func() error { self.c.Prompt(types.PromptOpts{ FindSuggestionsFunc: self.c.Helpers().Suggestions.GetFilePathSuggestionsFunc(), Title: self.c.Tr.EnterFileName, HandleConfirm: func(response string) error { return self.setFilteringPath(response) }, }) return nil }, Tooltip: tooltip, }) menuItems = append(menuItems, &types.MenuItem{ Label: self.c.Tr.FilterAuthorOption, OnPress: func() error { self.c.Prompt(types.PromptOpts{ FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), Title: self.c.Tr.EnterAuthor, HandleConfirm: func(response string) error { return self.setFilteringAuthor(response) }, }) return nil }, Tooltip: tooltip, }) if self.c.Modes().Filtering.Active() { menuItems = append(menuItems, &types.MenuItem{ Label: self.c.Tr.ExitFilterMode, OnPress: self.c.Helpers().Mode.ClearFiltering, }) } return self.c.Menu(types.CreateMenuOptions{Title: self.c.Tr.FilteringMenuTitle, Items: menuItems}) } func (self *FilteringMenuAction) setFilteringPath(path string) error { self.c.Modes().Filtering.Reset() self.c.Modes().Filtering.SetPath(path) return self.setFiltering() } func (self *FilteringMenuAction) setFilteringAuthor(author string) error { self.c.Modes().Filtering.Reset() self.c.Modes().Filtering.SetAuthor(author) return self.setFiltering() } func (self *FilteringMenuAction) setFiltering() error { self.c.Modes().Filtering.SetSelectedCommitHash(self.c.Contexts().LocalCommits.GetSelectedCommitHash()) repoState := self.c.State().GetRepoState() if repoState.GetScreenMode() == types.SCREEN_NORMAL { repoState.SetScreenMode(types.SCREEN_HALF) } self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) self.c.Refresh(types.RefreshOptions{Scope: helpers.ScopesToRefreshWhenFilteringModeChanges(), Then: func() { self.c.Contexts().LocalCommits.SetSelection(0) self.c.Contexts().LocalCommits.HandleFocus(types.OnFocusOpts{}) }}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/toggle_whitespace_action.go
pkg/gui/controllers/toggle_whitespace_action.go
package controllers import ( "errors" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type ToggleWhitespaceAction struct { c *ControllerCommon } func (self *ToggleWhitespaceAction) Call() error { contextsThatDontSupportIgnoringWhitespace := []types.ContextKey{ context.STAGING_MAIN_CONTEXT_KEY, context.STAGING_SECONDARY_CONTEXT_KEY, context.PATCH_BUILDING_MAIN_CONTEXT_KEY, } if lo.Contains(contextsThatDontSupportIgnoringWhitespace, self.c.Context().Current().GetKey()) { // Ignoring whitespace is not supported in these views. Let the user // know that it's not going to work in case they try to turn it on. return errors.New(self.c.Tr.IgnoreWhitespaceNotSupportedHere) } self.c.UserConfig().Git.IgnoreWhitespaceInDiffView = !self.c.UserConfig().Git.IgnoreWhitespaceInDiffView self.c.Context().CurrentSide().HandleFocus(types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/remote_branches_controller.go
pkg/gui/controllers/remote_branches_controller.go
package controllers import ( "strings" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type RemoteBranchesController struct { baseController *ListControllerTrait[*models.RemoteBranch] c *ControllerCommon } var _ types.IController = &RemoteBranchesController{} func NewRemoteBranchesController( c *ControllerCommon, ) *RemoteBranchesController { return &RemoteBranchesController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().RemoteBranches, c.Contexts().RemoteBranches.GetSelected, c.Contexts().RemoteBranches.GetSelectedItems, ), c: c, } } func (self *RemoteBranchesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.checkoutBranch), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Checkout, Tooltip: self.c.Tr.RemoteBranchCheckoutTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.withItem(self.newLocalBranch), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.NewBranch, }, { Key: opts.GetKey(opts.Config.Branches.MergeIntoCurrentBranch), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.merge)), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Merge, Tooltip: self.c.Tr.MergeBranchTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.RebaseBranch), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.rebase)), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.RebaseBranch, Tooltip: self.c.Tr.RebaseBranchTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItems(self.delete), GetDisabledReason: self.require(self.itemRangeSelected()), Description: self.c.Tr.Delete, Tooltip: self.c.Tr.DeleteRemoteBranchTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.SetUpstream), Handler: self.withItem(self.setAsUpstream), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.SetAsUpstream, Tooltip: self.c.Tr.SetAsUpstreamTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.SortOrder), Handler: self.createSortMenu, Description: self.c.Tr.SortOrder, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.withItem(self.createResetMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ViewResetOptions, Tooltip: self.c.Tr.ResetTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(func(selectedBranch *models.RemoteBranch) error { return self.c.Helpers().Diff.OpenDiffToolForRef(selectedBranch) }), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, } } func (self *RemoteBranchesController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask remoteBranch := self.context().GetSelected() if remoteBranch == nil { task = types.NewRenderStringTask("No branches for this remote") } else { cmdObj := self.c.Git().Branch.GetGraphCmdObj(remoteBranch.FullRefName()) task = types.NewRunCommandTask(cmdObj.GetCmd()) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Remote Branch", Task: task, }, }) }) } } func (self *RemoteBranchesController) context() *context.RemoteBranchesContext { return self.c.Contexts().RemoteBranches } func (self *RemoteBranchesController) delete(selectedBranches []*models.RemoteBranch) error { return self.c.Helpers().BranchesHelper.ConfirmDeleteRemote(selectedBranches, true) } func (self *RemoteBranchesController) merge(selectedBranch *models.RemoteBranch) error { return self.c.Helpers().MergeAndRebase.MergeRefIntoCheckedOutBranch(selectedBranch.FullName()) } func (self *RemoteBranchesController) rebase(selectedBranch *models.RemoteBranch) error { return self.c.Helpers().MergeAndRebase.RebaseOntoRef(selectedBranch.FullName()) } func (self *RemoteBranchesController) createSortMenu() error { return self.c.Helpers().Refs.CreateSortOrderMenu( []string{"alphabetical", "date"}, self.c.Tr.SortOrderPromptRemoteBranches, func(sortOrder string) error { if self.c.UserConfig().Git.RemoteBranchSortOrder != sortOrder { self.c.UserConfig().Git.RemoteBranchSortOrder = sortOrder self.c.Contexts().RemoteBranches.SetSelection(0) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.REMOTES}}) } return nil }, self.c.UserConfig().Git.RemoteBranchSortOrder) } func (self *RemoteBranchesController) createResetMenu(selectedBranch *models.RemoteBranch) error { return self.c.Helpers().Refs.CreateGitResetMenu(selectedBranch.FullName(), selectedBranch.FullRefName()) } func (self *RemoteBranchesController) setAsUpstream(selectedBranch *models.RemoteBranch) error { checkedOutBranch := self.c.Helpers().Refs.GetCheckedOutRef() message := utils.ResolvePlaceholderString( self.c.Tr.SetUpstreamMessage, map[string]string{ "checkedOut": checkedOutBranch.Name, "selected": selectedBranch.FullName(), }, ) self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.SetUpstreamTitle, Prompt: message, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.SetBranchUpstream) if err := self.c.Git().Branch.SetUpstream(selectedBranch.RemoteName, selectedBranch.Name, checkedOutBranch.Name); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }, }) return nil } func (self *RemoteBranchesController) newLocalBranch(selectedBranch *models.RemoteBranch) error { // will set to the remote's branch name without the remote name nameSuggestion := strings.SplitAfterN(selectedBranch.RefName(), "/", 2)[1] return self.c.Helpers().Refs.NewBranch(selectedBranch.RefName(), selectedBranch.RefName(), nameSuggestion) } func (self *RemoteBranchesController) checkoutBranch(selectedBranch *models.RemoteBranch) error { return self.c.Helpers().Refs.CheckoutRemoteBranch(selectedBranch.FullName(), selectedBranch.Name) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/screen_mode_actions.go
pkg/gui/controllers/screen_mode_actions.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type ScreenModeActions struct { c *ControllerCommon } func (self *ScreenModeActions) Next() error { self.c.State().GetRepoState().SetScreenMode( nextIntInCycle( []types.ScreenMode{types.SCREEN_NORMAL, types.SCREEN_HALF, types.SCREEN_FULL}, self.c.State().GetRepoState().GetScreenMode(), ), ) self.rerenderViewsWithScreenModeDependentContent() return nil } func (self *ScreenModeActions) Prev() error { self.c.State().GetRepoState().SetScreenMode( prevIntInCycle( []types.ScreenMode{types.SCREEN_NORMAL, types.SCREEN_HALF, types.SCREEN_FULL}, self.c.State().GetRepoState().GetScreenMode(), ), ) self.rerenderViewsWithScreenModeDependentContent() return nil } // these views need to be re-rendered when the screen mode changes. The commits view, // for example, will show authorship information in half and full screen mode. func (self *ScreenModeActions) rerenderViewsWithScreenModeDependentContent() { for _, context := range self.c.Context().AllList() { if context.NeedsRerenderOnWidthChange() == types.NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_SCREEN_MODE_CHANGES { self.rerenderView(context.GetView()) } } } func (self *ScreenModeActions) rerenderView(view *gocui.View) { context, ok := self.c.Helpers().View.ContextForView(view.Name()) if !ok { self.c.Log.Errorf("no context found for view %s", view.Name()) return } context.HandleRender() } func nextIntInCycle(sl []types.ScreenMode, current types.ScreenMode) types.ScreenMode { for i, val := range sl { if val == current { if i == len(sl)-1 { return sl[0] } return sl[i+1] } } return sl[0] } func prevIntInCycle(sl []types.ScreenMode, current types.ScreenMode) types.ScreenMode { for i, val := range sl { if val == current { if i > 0 { return sl[i-1] } return sl[len(sl)-1] } } return sl[len(sl)-1] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/commits_files_controller.go
pkg/gui/controllers/commits_files_controller.go
package controllers import ( "errors" "fmt" "path/filepath" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/filetree" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type CommitFilesController struct { baseController *ListControllerTrait[*filetree.CommitFileNode] c *ControllerCommon } var _ types.IController = &CommitFilesController{} func NewCommitFilesController( c *ControllerCommon, ) *CommitFilesController { return &CommitFilesController{ baseController: baseController{}, c: c, ListControllerTrait: NewListControllerTrait( c, c.Contexts().CommitFiles, c.Contexts().CommitFiles.GetSelected, c.Contexts().CommitFiles.GetSelectedItems, ), } } func (self *CommitFilesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Files.CopyFileInfoToClipboard), Handler: self.openCopyMenu, Description: self.c.Tr.CopyToClipboardMenu, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.CommitFiles.CheckoutCommitFile), Handler: self.withItem(self.checkout), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Checkout, Tooltip: self.c.Tr.CheckoutCommitFileTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItems(self.discard), GetDisabledReason: self.require(self.itemsSelected()), Description: self.c.Tr.Remove, Tooltip: self.c.Tr.DiscardOldFileChangeTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.withItem(self.open), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenFile, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.withItems(self.edit), GetDisabledReason: self.require(self.itemsSelected(self.canEditFiles)), Description: self.c.Tr.Edit, Tooltip: self.c.Tr.EditFileTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(self.openDiffTool), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItems(self.toggleForPatch), GetDisabledReason: self.require(self.itemsSelected()), Description: self.c.Tr.ToggleAddToPatch, Tooltip: utils.ResolvePlaceholderString(self.c.Tr.ToggleAddToPatchTooltip, map[string]string{"doc": constants.Links.Docs.CustomPatchDemo}, ), DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.ToggleStagedAll), Handler: self.withItem(self.toggleAllForPatch), Description: self.c.Tr.ToggleAllInPatch, Tooltip: utils.ResolvePlaceholderString(self.c.Tr.ToggleAllInPatchTooltip, map[string]string{"doc": constants.Links.Docs.CustomPatchDemo}, ), }, { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.EnterCommitFile, Tooltip: self.c.Tr.EnterCommitFileTooltip, }, { Key: opts.GetKey(opts.Config.Files.ToggleTreeView), Handler: self.toggleTreeView, Description: self.c.Tr.ToggleTreeView, Tooltip: self.c.Tr.ToggleTreeViewTooltip, }, { Key: opts.GetKey(opts.Config.Files.CollapseAll), Handler: self.collapseAll, Description: self.c.Tr.CollapseAll, Tooltip: self.c.Tr.CollapseAllTooltip, GetDisabledReason: self.require(self.isInTreeMode), }, { Key: opts.GetKey(opts.Config.Files.ExpandAll), Handler: self.expandAll, Description: self.c.Tr.ExpandAll, Tooltip: self.c.Tr.ExpandAllTooltip, GetDisabledReason: self.require(self.isInTreeMode), }, } return bindings } func (self *CommitFilesController) context() *context.CommitFilesContext { return self.c.Contexts().CommitFiles } func (self *CommitFilesController) GetOnRenderToMain() func() { return func() { node := self.context().GetSelected() if node == nil { return } from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, node.GetPath(), false) task := types.NewRunPtyTask(cmdObj.GetCmd()) self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.Patch, SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: task, }, Secondary: secondaryPatchPanelUpdateOpts(self.c), }) } } func (self *CommitFilesController) copyDiffToClipboard(path string, toastMessage string) error { from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, path, true) diff, err := cmdObj.RunWithOutput() if err != nil { return err } if err := self.c.OS().CopyToClipboard(diff); err != nil { return err } self.c.Toast(toastMessage) return nil } func (self *CommitFilesController) copyFileContentToClipboard(path string) error { _, to := self.context().GetFromAndToForDiff() cmdObj := self.c.Git().Commit.ShowFileContentCmdObj(to, path) diff, err := cmdObj.RunWithOutput() if err != nil { return err } return self.c.OS().CopyToClipboard(diff) } func (self *CommitFilesController) openCopyMenu() error { node := self.context().GetSelected() copyNameItem := &types.MenuItem{ Label: self.c.Tr.CopyFileName, OnPress: func() error { if err := self.c.OS().CopyToClipboard(node.Name()); err != nil { return err } self.c.Toast(self.c.Tr.FileNameCopiedToast) return nil }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'n', } copyRelativePathItem := &types.MenuItem{ Label: self.c.Tr.CopyRelativeFilePath, OnPress: func() error { if err := self.c.OS().CopyToClipboard(node.GetPath()); err != nil { return err } self.c.Toast(self.c.Tr.FilePathCopiedToast) return nil }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'p', } copyAbsolutePathItem := &types.MenuItem{ Label: self.c.Tr.CopyAbsoluteFilePath, OnPress: func() error { if err := self.c.OS().CopyToClipboard(filepath.Join(self.c.Git().RepoPaths.RepoPath(), node.GetPath())); err != nil { return err } self.c.Toast(self.c.Tr.FilePathCopiedToast) return nil }, DisabledReason: self.require(self.singleItemSelected())(), Key: 'P', } copyFileDiffItem := &types.MenuItem{ Label: self.c.Tr.CopySelectedDiff, OnPress: func() error { return self.copyDiffToClipboard(node.GetPath(), self.c.Tr.FileDiffCopiedToast) }, DisabledReason: self.require(self.singleItemSelected())(), Key: 's', } copyAllDiff := &types.MenuItem{ Label: self.c.Tr.CopyAllFilesDiff, OnPress: func() error { return self.copyDiffToClipboard(".", self.c.Tr.AllFilesDiffCopiedToast) }, DisabledReason: self.require(self.itemsSelected())(), Key: 'a', } copyFileContentItem := &types.MenuItem{ Label: self.c.Tr.CopyFileContent, OnPress: func() error { if err := self.copyFileContentToClipboard(node.GetPath()); err != nil { return err } self.c.Toast(self.c.Tr.FileContentCopiedToast) return nil }, DisabledReason: self.require(self.singleItemSelected( func(node *filetree.CommitFileNode) *types.DisabledReason { if !node.IsFile() { return &types.DisabledReason{ Text: self.c.Tr.ErrCannotCopyContentOfDirectory, ShowErrorInPanel: true, } } return nil }))(), Key: 'c', } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.CopyToClipboardMenu, Items: []*types.MenuItem{ copyNameItem, copyRelativePathItem, copyAbsolutePathItem, copyFileDiffItem, copyAllDiff, copyFileContentItem, }, }) } func (self *CommitFilesController) checkout(node *filetree.CommitFileNode) error { hasModifiedFiles := helpers.AnyTrackedFilesInPathExceptSubmodules(node.GetPath(), self.c.Model().Files, self.c.Model().Submodules) if hasModifiedFiles { return errors.New(self.c.Tr.CannotCheckoutWithModifiedFilesErr) } self.c.LogAction(self.c.Tr.Actions.CheckoutFile) _, to := self.context().GetFromAndToForDiff() if err := self.c.Git().WorkingTree.CheckoutFile(to, node.GetPath()); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil } func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileNode) error { parentContext := self.c.Context().Current().GetParentContext() if parentContext == nil || parentContext.GetKey() != context.LOCAL_COMMITS_CONTEXT_KEY { return errors.New(self.c.Tr.CanOnlyDiscardFromLocalCommits) } if ok, err := self.c.Helpers().PatchBuilding.ValidateNormalWorkingTreeState(); !ok { return err } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.DiscardFileChangesTitle, Prompt: self.c.Tr.DiscardFileChangesPrompt, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { var filePaths []string selectedNodes = normalisedSelectedCommitFileNodes(selectedNodes) // Reset the current patch if there is one. if self.c.Git().Patch.PatchBuilder.Active() { self.c.Git().Patch.PatchBuilder.Reset() } for _, node := range selectedNodes { _ = node.ForEachFile(func(file *models.CommitFile) error { filePaths = append(filePaths, file.GetPath()) return nil }) } err := self.c.Git().Rebase.DiscardOldFileChanges(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx(), filePaths) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } if self.context().RangeSelectEnabled() { self.context().GetList().CancelRangeSelect() } return nil }) }, }) return nil } func (self *CommitFilesController) open(node *filetree.CommitFileNode) error { return self.c.Helpers().Files.OpenFile(node.GetPath()) } func (self *CommitFilesController) edit(nodes []*filetree.CommitFileNode) error { return self.c.Helpers().Files.EditFiles(lo.FilterMap(nodes, func(node *filetree.CommitFileNode, _ int) (string, bool) { return node.GetPath(), node.IsFile() })) } func (self *CommitFilesController) canEditFiles(nodes []*filetree.CommitFileNode) *types.DisabledReason { if lo.NoneBy(nodes, func(node *filetree.CommitFileNode) bool { return node.IsFile() }) { return &types.DisabledReason{ Text: self.c.Tr.ErrCannotEditDirectory, ShowErrorInPanel: true, } } return nil } func (self *CommitFilesController) openDiffTool(node *filetree.CommitFileNode) error { from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) _, err := self.c.RunSubprocess(self.c.Git().Diff.OpenDiffToolCmdObj( git_commands.DiffToolCmdOptions{ Filepath: node.GetPath(), FromCommit: from, ToCommit: to, Reverse: reverse, IsDirectory: !node.IsFile(), Staged: false, })) return err } func (self *CommitFilesController) toggleForPatch(selectedNodes []*filetree.CommitFileNode) error { if self.c.UserConfig().Git.DiffContextSize == 0 { return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextForCustomPatch, keybindings.Label(self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView)) } toggle := func() error { return self.c.WithWaitingStatus(self.c.Tr.UpdatingPatch, func(gocui.Task) error { if !self.c.Git().Patch.PatchBuilder.Active() { if err := self.startPatchBuilder(); err != nil { return err } } selectedNodes = normalisedSelectedCommitFileNodes(selectedNodes) // Find if any file in the selection is unselected or partially added adding := lo.SomeBy(selectedNodes, func(node *filetree.CommitFileNode) bool { return node.SomeFile(func(file *models.CommitFile) bool { fileStatus := self.c.Git().Patch.PatchBuilder.GetFileStatus(file.Path, self.context().GetRef().RefName()) return fileStatus == patch.PART || fileStatus == patch.UNSELECTED }) }) patchOperationFunction := self.c.Git().Patch.PatchBuilder.RemoveFile if adding { patchOperationFunction = self.c.Git().Patch.PatchBuilder.AddFileWhole } for _, node := range selectedNodes { err := node.ForEachFile(func(file *models.CommitFile) error { return patchOperationFunction(file.Path) }) if err != nil { return err } } if self.c.Git().Patch.PatchBuilder.IsEmpty() { self.c.Git().Patch.PatchBuilder.Reset() } self.c.PostRefreshUpdate(self.context()) return nil }) } from, to, reverse := self.currentFromToReverseForPatchBuilding() mustDiscardPatch := self.c.Git().Patch.PatchBuilder.Active() && self.c.Git().Patch.PatchBuilder.NewPatchRequired(from, to, reverse) return self.c.ConfirmIf(mustDiscardPatch, types.ConfirmOpts{ Title: self.c.Tr.DiscardPatch, Prompt: self.c.Tr.DiscardPatchConfirm, HandleConfirm: func() error { if mustDiscardPatch { self.c.Git().Patch.PatchBuilder.Reset() } return toggle() }, }) } func (self *CommitFilesController) toggleAllForPatch(_ *filetree.CommitFileNode) error { root := self.context().CommitFileTreeViewModel.GetRoot() return self.toggleForPatch([]*filetree.CommitFileNode{root}) } func (self *CommitFilesController) startPatchBuilder() error { commitFilesContext := self.context() canRebase := commitFilesContext.GetCanRebase() from, to, reverse := self.currentFromToReverseForPatchBuilding() self.c.Git().Patch.PatchBuilder.Start(from, to, reverse, canRebase) return nil } func (self *CommitFilesController) currentFromToReverseForPatchBuilding() (string, string, bool) { commitFilesContext := self.context() from, to := commitFilesContext.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) return from, to, reverse } func (self *CommitFilesController) enter(node *filetree.CommitFileNode) error { return self.enterCommitFile(node, types.OnFocusOpts{ClickedWindowName: "", ClickedViewLineIdx: -1}) } func (self *CommitFilesController) enterCommitFile(node *filetree.CommitFileNode, opts types.OnFocusOpts) error { if node.File == nil { return self.handleToggleCommitFileDirCollapsed(node) } if self.c.UserConfig().Git.DiffContextSize == 0 { return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextForCustomPatch, keybindings.Label(self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView)) } from, to, reverse := self.currentFromToReverseForPatchBuilding() mustDiscardPatch := self.c.Git().Patch.PatchBuilder.Active() && self.c.Git().Patch.PatchBuilder.NewPatchRequired(from, to, reverse) return self.c.ConfirmIf(mustDiscardPatch, types.ConfirmOpts{ Title: self.c.Tr.DiscardPatch, Prompt: self.c.Tr.DiscardPatchConfirm, HandleConfirm: func() error { if mustDiscardPatch { self.c.Git().Patch.PatchBuilder.Reset() } if !self.c.Git().Patch.PatchBuilder.Active() { if err := self.startPatchBuilder(); err != nil { return err } } self.c.Context().Push(self.c.Contexts().CustomPatchBuilder, opts) self.c.Helpers().PatchBuilding.ShowHunkStagingHint() return nil }, }) } func (self *CommitFilesController) handleToggleCommitFileDirCollapsed(node *filetree.CommitFileNode) error { self.context().CommitFileTreeViewModel.ToggleCollapsed(node.GetInternalPath()) self.c.PostRefreshUpdate(self.context()) return nil } // NOTE: this is very similar to handleToggleFileTreeView, could be DRY'd with generics func (self *CommitFilesController) toggleTreeView() error { self.context().CommitFileTreeViewModel.ToggleShowTree() self.c.PostRefreshUpdate(self.context()) return nil } func (self *CommitFilesController) collapseAll() error { self.context().CommitFileTreeViewModel.CollapseAll() self.c.PostRefreshUpdate(self.context()) return nil } func (self *CommitFilesController) expandAll() error { self.context().CommitFileTreeViewModel.ExpandAll() self.c.PostRefreshUpdate(self.context()) return nil } func (self *CommitFilesController) GetOnClickFocusedMainView() func(mainViewName string, clickedLineIdx int) error { return func(mainViewName string, clickedLineIdx int) error { node := self.getSelectedItem() if node != nil && node.File != nil { return self.enterCommitFile(node, types.OnFocusOpts{ClickedWindowName: mainViewName, ClickedViewLineIdx: clickedLineIdx}) } return nil } } // NOTE: these functions are identical to those in files_controller.go (except for types) and // could also be cleaned up with some generics func normalisedSelectedCommitFileNodes(selectedNodes []*filetree.CommitFileNode) []*filetree.CommitFileNode { return lo.Filter(selectedNodes, func(node *filetree.CommitFileNode, _ int) bool { return !isDescendentOfSelectedCommitFileNodes(node, selectedNodes) }) } func isDescendentOfSelectedCommitFileNodes(node *filetree.CommitFileNode, selectedNodes []*filetree.CommitFileNode) bool { for _, selectedNode := range selectedNodes { selectedNodePath := selectedNode.GetPath() nodePath := node.GetPath() if strings.HasPrefix(nodePath, selectedNodePath) && nodePath != selectedNodePath { return true } } return false } func (self *CommitFilesController) isInTreeMode() *types.DisabledReason { if !self.context().CommitFileTreeViewModel.InTreeMode() { return &types.DisabledReason{Text: self.c.Tr.DisabledInFlatView} } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/tags_controller.go
pkg/gui/controllers/tags_controller.go
package controllers import ( "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type TagsController struct { baseController *ListControllerTrait[*models.Tag] c *ControllerCommon } var _ types.IController = &TagsController{} func NewTagsController( c *ControllerCommon, ) *TagsController { return &TagsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Tags, c.Contexts().Tags.GetSelected, c.Contexts().Tags.GetSelectedItems, ), c: c, } } func (self *TagsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.checkout), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Checkout, Tooltip: self.c.Tr.TagCheckoutTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.create, Description: self.c.Tr.NewTag, Tooltip: self.c.Tr.NewTagTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItem(self.delete), Description: self.c.Tr.Delete, GetDisabledReason: self.require(self.singleItemSelected()), Tooltip: self.c.Tr.TagDeleteTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.PushTag), Handler: self.withItem(self.push), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.PushTag, Tooltip: self.c.Tr.PushTagTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.withItem(self.createResetMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Reset, Tooltip: self.c.Tr.ResetTooltip, DisplayOnScreen: true, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(func(selectedTag *models.Tag) error { return self.c.Helpers().Diff.OpenDiffToolForRef(selectedTag) }), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, } return bindings } func (self *TagsController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask tag := self.context().GetSelected() if tag == nil { task = types.NewRenderStringTask("No tags") } else { cmdObj := self.c.Git().Branch.GetGraphCmdObj(tag.FullRefName()) prefix := self.getTagInfo(tag) + "\n\n---\n\n" task = types.NewRunCommandTaskWithPrefix(cmdObj.GetCmd(), prefix) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Tag", Task: task, }, }) }) } } func (self *TagsController) getTagInfo(tag *models.Tag) string { tagIsAnnotated, err := self.c.Git().Tag.IsTagAnnotated(tag.Name) if err != nil { self.c.Log.Warnf("Error checking if tag is annotated: %v", err) } if tagIsAnnotated { info := fmt.Sprintf("%s: %s", self.c.Tr.AnnotatedTag, style.AttrBold.Sprint(style.FgYellow.Sprint(tag.Name))) output, err := self.c.Git().Tag.ShowAnnotationInfo(tag.Name) if err == nil { info += "\n\n" + strings.TrimRight(filterOutPgpSignature(output), "\n") } return info } return fmt.Sprintf("%s: %s", self.c.Tr.LightweightTag, style.AttrBold.Sprint(style.FgYellow.Sprint(tag.Name))) } func filterOutPgpSignature(output string) string { lines := strings.Split(output, "\n") inPgpSignature := false filteredLines := lo.Filter(lines, func(line string, _ int) bool { if line == "-----END PGP SIGNATURE-----" { inPgpSignature = false return false } if line == "-----BEGIN PGP SIGNATURE-----" { inPgpSignature = true } return !inPgpSignature }) return strings.Join(filteredLines, "\n") } func (self *TagsController) checkout(tag *models.Tag) error { self.c.LogAction(self.c.Tr.Actions.CheckoutTag) if err := self.c.Helpers().Refs.CheckoutRef(tag.FullRefName(), types.CheckoutRefOptions{}); err != nil { return err } return nil } func (self *TagsController) localDelete(tag *models.Tag) error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag) err := self.c.Git().Tag.LocalDelete(tag.Name) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return err }) } func (self *TagsController) remoteDelete(tag *models.Tag) error { title := utils.ResolvePlaceholderString( self.c.Tr.SelectRemoteTagUpstream, map[string]string{ "tagName": tag.Name, }, ) self.c.Prompt(types.PromptOpts{ Title: title, InitialContent: "origin", FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(), HandleConfirm: func(upstream string) error { confirmTitle := utils.ResolvePlaceholderString( self.c.Tr.DeleteTagTitle, map[string]string{ "tagName": tag.Name, }, ) confirmPrompt := utils.ResolvePlaceholderString( self.c.Tr.DeleteRemoteTagPrompt, map[string]string{ "tagName": tag.Name, "upstream": upstream, }, ) self.c.Confirm(types.ConfirmOpts{ Title: confirmTitle, Prompt: confirmPrompt, HandleConfirm: func() error { return self.c.WithInlineStatus(tag, types.ItemOperationDeleting, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag) if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tag.Name); err != nil { return err } self.c.Toast(self.c.Tr.RemoteTagDeletedMessage) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, }) return nil }, }) return nil } func (self *TagsController) localAndRemoteDelete(tag *models.Tag) error { title := utils.ResolvePlaceholderString( self.c.Tr.SelectRemoteTagUpstream, map[string]string{ "tagName": tag.Name, }, ) self.c.Prompt(types.PromptOpts{ Title: title, InitialContent: "origin", FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(), HandleConfirm: func(upstream string) error { confirmTitle := utils.ResolvePlaceholderString( self.c.Tr.DeleteTagTitle, map[string]string{ "tagName": tag.Name, }, ) confirmPrompt := utils.ResolvePlaceholderString( self.c.Tr.DeleteLocalAndRemoteTagPrompt, map[string]string{ "tagName": tag.Name, "upstream": upstream, }, ) self.c.Confirm(types.ConfirmOpts{ Title: confirmTitle, Prompt: confirmPrompt, HandleConfirm: func() error { return self.c.WithInlineStatus(tag, types.ItemOperationDeleting, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag) if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tag.Name); err != nil { return err } self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag) if err := self.c.Git().Tag.LocalDelete(tag.Name); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, }) return nil }, }) return nil } func (self *TagsController) delete(tag *models.Tag) error { menuTitle := utils.ResolvePlaceholderString( self.c.Tr.DeleteTagTitle, map[string]string{ "tagName": tag.Name, }, ) menuItems := []*types.MenuItem{ { Label: self.c.Tr.DeleteLocalTag, Key: 'c', OnPress: func() error { return self.localDelete(tag) }, }, { Label: self.c.Tr.DeleteRemoteTag, Key: 'r', OpensMenu: true, OnPress: func() error { return self.remoteDelete(tag) }, }, { Label: self.c.Tr.DeleteLocalAndRemoteTag, Key: 'b', OpensMenu: true, OnPress: func() error { return self.localAndRemoteDelete(tag) }, }, } return self.c.Menu(types.CreateMenuOptions{ Title: menuTitle, Items: menuItems, }) } func (self *TagsController) push(tag *models.Tag) error { title := utils.ResolvePlaceholderString( self.c.Tr.PushTagTitle, map[string]string{ "tagName": tag.Name, }, ) self.c.Prompt(types.PromptOpts{ Title: title, InitialContent: "origin", FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(), HandleConfirm: func(response string) error { return self.c.WithInlineStatus(tag, types.ItemOperationPushing, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.PushTag) err := self.c.Git().Tag.Push(task, response, tag.Name) // Render again to remove the inline status: self.c.OnUIThread(func() error { self.c.Contexts().Tags.HandleRender() return nil }) return err }) }, }) return nil } func (self *TagsController) createResetMenu(tag *models.Tag) error { return self.c.Helpers().Refs.CreateGitResetMenu(tag.Name, tag.FullRefName()) } func (self *TagsController) create() error { // leaving commit hash blank so that we're just creating the tag for the current commit return self.c.Helpers().Tags.OpenCreateTagPrompt("", func() { self.context().SetSelection(0) }) } func (self *TagsController) context() *context.TagsContext { return self.c.Contexts().Tags }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/shell_command_action.go
pkg/gui/controllers/shell_command_action.go
package controllers import ( "slices" "strings" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type ShellCommandAction struct { c *ControllerCommon } func (self *ShellCommandAction) Call() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.ShellCommand, FindSuggestionsFunc: self.GetShellCommandsHistorySuggestionsFunc(), AllowEditSuggestion: true, PreserveWhitespace: true, HandleConfirm: func(command string) error { if self.shouldSaveCommand(command) { self.c.GetAppState().ShellCommandsHistory = utils.Limit( lo.Uniq(append([]string{command}, self.c.GetAppState().ShellCommandsHistory...)), 1000, ) } self.c.SaveAppStateAndLogError() self.c.LogAction(self.c.Tr.Actions.CustomCommand) return self.c.RunSubprocessAndRefresh( self.c.OS().Cmd.NewShell(command, self.c.UserConfig().OS.ShellFunctionsFile), ) }, HandleDeleteSuggestion: func(index int) error { // index is the index in the _filtered_ list of suggestions, so we // need to map it back to the full list. There's no really good way // to do this, but fortunately we keep the items in the // ShellCommandsHistory unique, which allows us to simply search // for it by string. item := self.c.Contexts().Suggestions.GetItems()[index].Value fullIndex := lo.IndexOf(self.c.GetAppState().ShellCommandsHistory, item) if fullIndex == -1 { // Should never happen, but better be safe return nil } self.c.GetAppState().ShellCommandsHistory = slices.Delete( self.c.GetAppState().ShellCommandsHistory, fullIndex, fullIndex+1) self.c.SaveAppStateAndLogError() self.c.Contexts().Suggestions.RefreshSuggestions() return nil }, }) return nil } func (self *ShellCommandAction) GetShellCommandsHistorySuggestionsFunc() func(string) []*types.Suggestion { return func(input string) []*types.Suggestion { history := self.c.GetAppState().ShellCommandsHistory return helpers.FilterFunc(history, self.c.UserConfig().Gui.UseFuzzySearch())(input) } } // this mimics the shell functionality `ignorespace` // which doesn't save a command to history if it starts with a space func (self *ShellCommandAction) shouldSaveCommand(command string) bool { return !strings.HasPrefix(command, " ") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/worktrees_controller.go
pkg/gui/controllers/worktrees_controller.go
package controllers import ( "errors" "fmt" "strings" "text/tabwriter" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type WorktreesController struct { baseController *ListControllerTrait[*models.Worktree] c *ControllerCommon } var _ types.IController = &WorktreesController{} func NewWorktreesController( c *ControllerCommon, ) *WorktreesController { return &WorktreesController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Worktrees, c.Contexts().Worktrees.GetSelected, c.Contexts().Worktrees.GetSelectedItems, ), c: c, } } func (self *WorktreesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.add, Description: self.c.Tr.NewWorktree, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Switch, Tooltip: self.c.Tr.SwitchToWorktreeTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.withItem(self.enter), GetDisabledReason: self.require(self.singleItemSelected()), }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.withItem(self.open), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenInEditor, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItem(self.remove), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Remove, Tooltip: self.c.Tr.RemoveWorktreeTooltip, DisplayOnScreen: true, }, } return bindings } func (self *WorktreesController) GetOnRenderToMain() func() { return func() { var task types.UpdateTask worktree := self.context().GetSelected() if worktree == nil { task = types.NewRenderStringTask(self.c.Tr.NoWorktreesThisRepo) } else { main := "" if worktree.IsMain { main = style.FgDefault.Sprintf(" %s", self.c.Tr.MainWorktree) } missing := "" if worktree.IsPathMissing { missing = style.FgRed.Sprintf(" %s", self.c.Tr.MissingWorktree) } var builder strings.Builder w := tabwriter.NewWriter(&builder, 0, 0, 2, ' ', 0) _, _ = fmt.Fprintf(w, "%s:\t%s%s\n", self.c.Tr.Name, style.FgGreen.Sprint(worktree.Name), main) _, _ = fmt.Fprintf(w, "%s:\t%s\n", self.c.Tr.Branch, style.FgYellow.Sprint(worktree.Branch)) _, _ = fmt.Fprintf(w, "%s:\t%s%s\n", self.c.Tr.Path, style.FgCyan.Sprint(worktree.Path), missing) _ = w.Flush() task = types.NewRenderStringTask(builder.String()) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.WorktreeTitle, Task: task, }, }) } } func (self *WorktreesController) add() error { return self.c.Helpers().Worktree.NewWorktree() } func (self *WorktreesController) remove(worktree *models.Worktree) error { if worktree.IsMain { return errors.New(self.c.Tr.CantDeleteMainWorktree) } if worktree.IsCurrent { return errors.New(self.c.Tr.CantDeleteCurrentWorktree) } return self.c.Helpers().Worktree.Remove(worktree, false) } func (self *WorktreesController) GetOnClick() func() error { return self.withItemGraceful(self.enter) } func (self *WorktreesController) enter(worktree *models.Worktree) error { return self.c.Helpers().Worktree.Switch(worktree, context.WORKTREES_CONTEXT_KEY) } func (self *WorktreesController) open(worktree *models.Worktree) error { return self.c.Helpers().Files.OpenDirInEditor(worktree.Path) } func (self *WorktreesController) context() *context.WorktreesContext { return self.c.Contexts().Worktrees }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/files_controller.go
pkg/gui/controllers/files_controller.go
package controllers import ( "errors" "fmt" "path/filepath" "strings" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/filetree" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type FilesController struct { baseController *ListControllerTrait[*filetree.FileNode] c *ControllerCommon } var _ types.IController = &FilesController{} func NewFilesController( c *ControllerCommon, ) *FilesController { return &FilesController{ c: c, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Files, c.Contexts().Files.GetSelected, c.Contexts().Files.GetSelectedItems, ), } } func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItems(self.press), GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected())), Description: self.c.Tr.Stage, Tooltip: self.c.Tr.StageTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.OpenStatusFilter), Handler: self.handleStatusFilterPressed, Description: self.c.Tr.FileFilter, }, { Key: opts.GetKey(opts.Config.Files.CopyFileInfoToClipboard), Handler: self.openCopyMenu, Description: self.c.Tr.CopyToClipboardMenu, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.CommitChanges), Handler: self.c.Helpers().WorkingTree.HandleCommitPress, Description: self.c.Tr.Commit, Tooltip: self.c.Tr.CommitTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithoutHook), Handler: self.c.Helpers().WorkingTree.HandleWIPCommitPress, Description: self.c.Tr.CommitChangesWithoutHook, }, { Key: opts.GetKey(opts.Config.Files.AmendLastCommit), Handler: self.handleAmendCommitPress, Description: self.c.Tr.AmendLastCommit, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithEditor), Handler: self.c.Helpers().WorkingTree.HandleCommitEditorPress, Description: self.c.Tr.CommitChangesWithEditor, }, { Key: opts.GetKey(opts.Config.Files.FindBaseCommitForFixup), Handler: self.c.Helpers().FixupHelper.HandleFindBaseCommitForFixupPress, Description: self.c.Tr.FindBaseCommitForFixup, Tooltip: self.c.Tr.FindBaseCommitForFixupTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.withItems(self.edit), GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected(self.canEditFiles))), Description: self.c.Tr.Edit, Tooltip: self.c.Tr.EditFileTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.Open, GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenFile, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Files.IgnoreFile), Handler: self.withItem(self.ignoreOrExcludeMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.Actions.IgnoreExcludeFile, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.RefreshFiles), Handler: self.refresh, Description: self.c.Tr.RefreshFiles, }, { Key: opts.GetKey(opts.Config.Files.StashAllChanges), Handler: self.stash, Description: self.c.Tr.Stash, Tooltip: self.c.Tr.StashTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.ViewStashOptions), Handler: self.createStashMenu, Description: self.c.Tr.ViewStashOptions, Tooltip: self.c.Tr.ViewStashOptionsTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.ToggleStagedAll), Handler: self.toggleStagedAll, Description: self.c.Tr.ToggleStagedAll, Tooltip: self.c.Tr.ToggleStagedAllTooltip, }, { Key: opts.GetKey(opts.Config.Universal.GoInto), Handler: self.enter, GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.FileEnter, Tooltip: self.c.Tr.FileEnterTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItems(self.remove), GetDisabledReason: self.withFileTreeViewModelMutex(self.require(self.itemsSelected(self.canRemove))), Description: self.c.Tr.Discard, Tooltip: self.c.Tr.DiscardFileChangesTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.createResetToUpstreamMenu, Description: self.c.Tr.ViewResetToUpstreamOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Files.ViewResetOptions), Handler: self.createResetMenu, Description: self.c.Tr.Reset, Tooltip: self.c.Tr.FileResetOptionsTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.ToggleTreeView), Handler: self.toggleTreeView, Description: self.c.Tr.ToggleTreeView, Tooltip: self.c.Tr.ToggleTreeViewTooltip, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(self.openDiffTool), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, { Key: opts.GetKey(opts.Config.Files.OpenMergeOptions), Handler: self.withItems(self.openMergeConflictMenu), Description: self.c.Tr.ViewMergeConflictOptions, Tooltip: self.c.Tr.ViewMergeConflictOptionsTooltip, GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected(self.canOpenMergeConflictMenu))), OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Files.Fetch), Handler: self.fetch, Description: self.c.Tr.Fetch, Tooltip: self.c.Tr.FetchTooltip, }, { Key: opts.GetKey(opts.Config.Files.CollapseAll), Handler: self.collapseAll, Description: self.c.Tr.CollapseAll, Tooltip: self.c.Tr.CollapseAllTooltip, GetDisabledReason: self.require(self.isInTreeMode), }, { Key: opts.GetKey(opts.Config.Files.ExpandAll), Handler: self.expandAll, Description: self.c.Tr.ExpandAll, Tooltip: self.c.Tr.ExpandAllTooltip, GetDisabledReason: self.require(self.isInTreeMode), }, } } func (self *FilesController) withFileTreeViewModelMutex(callback func() *types.DisabledReason) func() *types.DisabledReason { return func() *types.DisabledReason { self.c.Contexts().Files.FileTreeViewModel.RWMutex.RLock() defer self.c.Contexts().Files.FileTreeViewModel.RWMutex.RUnlock() return callback() } } func (self *FilesController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: "mergeConflicts", Key: gocui.MouseLeft, Handler: self.onClickMain, FocusedView: self.context().GetViewName(), }, } } func (self *FilesController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { node := self.context().GetSelected() if node == nil { self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.DiffTitle, SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: types.NewRenderStringTask(self.c.Tr.NoChangedFiles), }, }) return } if node.File != nil && node.File.HasInlineMergeConflicts { hasConflicts, err := self.c.Helpers().MergeConflicts.SetMergeState(node.GetPath()) if err != nil { return } if hasConflicts { self.c.Helpers().MergeConflicts.Render() return } } else if node.File != nil && node.File.HasMergeConflicts { opts := types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.DiffTitle, SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), }, } message := node.File.GetMergeStateDescription(self.c.Tr) message += "\n\n" + fmt.Sprintf(self.c.Tr.MergeConflictPressEnterToResolve, self.c.UserConfig().Keybinding.Universal.GoInto) if self.c.Views().Main.InnerWidth() > 70 { // If the main view is very wide, wrap the message to increase readability lines, _, _ := utils.WrapViewLinesToWidth(true, false, message, 70, 4) message = strings.Join(lines, "\n") } if node.File.ShortStatus == "DU" || node.File.ShortStatus == "UD" { cmdObj := self.c.Git().Diff.DiffCmdObj([]string{"--base", "--", node.GetPath()}) prefix := message + "\n\n" if node.File.ShortStatus == "DU" { prefix += self.c.Tr.MergeConflictIncomingDiff } else { prefix += self.c.Tr.MergeConflictCurrentDiff } prefix += "\n\n" opts.Main.Task = types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix) } else { opts.Main.Task = types.NewRenderStringTask(message) } self.c.RenderToMainViews(opts) return } self.c.Helpers().MergeConflicts.ResetMergeState() split := self.c.UserConfig().Gui.SplitDiff == "always" || (node.GetHasUnstagedChanges() && node.GetHasStagedChanges()) mainShowsStaged := !split && node.GetHasStagedChanges() cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, mainShowsStaged) title := self.c.Tr.UnstagedChanges if mainShowsStaged { title = self.c.Tr.StagedChanges } refreshOpts := types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Task: types.NewRunPtyTask(cmdObj.GetCmd()), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Title: title, }, } if split { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, true) title := self.c.Tr.StagedChanges if mainShowsStaged { title = self.c.Tr.UnstagedChanges } refreshOpts.Secondary = &types.ViewUpdateOpts{ Title: title, SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: types.NewRunPtyTask(cmdObj.GetCmd()), } } self.c.RenderToMainViews(refreshOpts) }) } } func (self *FilesController) GetOnClick() func() error { return self.withItemGraceful(func(node *filetree.FileNode) error { return self.press([]*filetree.FileNode{node}) }) } func (self *FilesController) GetOnClickFocusedMainView() func(mainViewName string, clickedLineIdx int) error { return func(mainViewName string, clickedLineIdx int) error { node := self.getSelectedItem() if node != nil && node.File != nil { return self.EnterFile(types.OnFocusOpts{ClickedWindowName: mainViewName, ClickedViewLineIdx: clickedLineIdx}) } return nil } } // if we are dealing with a status for which there is no key in this map, // then we won't optimistically render: we'll just let `git status` tell // us what the new status is. // There are no doubt more entries that could be added to these two maps. var stageStatusMap = map[string]string{ "??": "A ", " M": "M ", "MM": "M ", " D": "D ", " A": "A ", "AM": "A ", "MD": "D ", } var unstageStatusMap = map[string]string{ "A ": "??", "M ": " M", "D ": " D", } func (self *FilesController) optimisticStage(file *models.File) bool { newShortStatus, ok := stageStatusMap[file.ShortStatus] if !ok { return false } models.SetStatusFields(file, newShortStatus) return true } func (self *FilesController) optimisticUnstage(file *models.File) bool { newShortStatus, ok := unstageStatusMap[file.ShortStatus] if !ok { return false } models.SetStatusFields(file, newShortStatus) return true } // Running a git add command followed by a git status command can take some time (e.g. 200ms). // Given how often users stage/unstage files in Lazygit, we're adding some // optimistic rendering to make things feel faster. When we go to stage // a file, we'll first update that file's status in-memory, then re-render // the files panel. Then we'll immediately do a proper git status call // so that if the optimistic rendering got something wrong, it's quickly // corrected. func (self *FilesController) optimisticChange(nodes []*filetree.FileNode, optimisticChangeFn func(*models.File) bool) error { rerender := false for _, node := range nodes { err := node.ForEachFile(func(f *models.File) error { // can't act on the file itself: we need to update the original model file for _, modelFile := range self.c.Model().Files { if modelFile.Path == f.Path { if optimisticChangeFn(modelFile) { rerender = true } break } } return nil }) if err != nil { return err } } if rerender { self.c.PostRefreshUpdate(self.c.Contexts().Files) } return nil } func (self *FilesController) pressWithLock(selectedNodes []*filetree.FileNode) error { // Obtaining this lock because optimistic rendering requires us to mutate // the files in our model. self.c.Mutexes().RefreshingFilesMutex.Lock() defer self.c.Mutexes().RefreshingFilesMutex.Unlock() for _, node := range selectedNodes { // if any files within have inline merge conflicts we can't stage or unstage, // or it'll end up with those >>>>>> lines actually staged if node.GetHasInlineMergeConflicts() { return errors.New(self.c.Tr.ErrStageDirWithInlineMergeConflicts) } } toPaths := func(nodes []*filetree.FileNode) []string { return lo.Map(nodes, func(node *filetree.FileNode, _ int) string { return node.GetPath() }) } selectedNodes = normalisedSelectedNodes(selectedNodes) // If any node has unstaged changes, we'll stage all the selected unstaged nodes (staging already staged deleted files/folders would fail). // Otherwise, we unstage all the selected nodes. unstagedSelectedNodes := filterNodesHaveUnstagedChanges(selectedNodes) if len(unstagedSelectedNodes) > 0 { var extraArgs []string if self.context().GetFilter() == filetree.DisplayTracked { extraArgs = []string{"-u"} } self.c.LogAction(self.c.Tr.Actions.StageFile) if err := self.optimisticChange(unstagedSelectedNodes, self.optimisticStage); err != nil { return err } if err := self.c.Git().WorkingTree.StageFiles(toPaths(unstagedSelectedNodes), extraArgs); err != nil { return err } } else { self.c.LogAction(self.c.Tr.Actions.UnstageFile) if err := self.optimisticChange(selectedNodes, self.optimisticUnstage); err != nil { return err } // need to partition the paths into tracked and untracked (where we assume directories are tracked). Then we'll run the commands separately. trackedNodes, untrackedNodes := utils.Partition(selectedNodes, func(node *filetree.FileNode) bool { // We treat all directories as tracked. I'm not actually sure why we do this but // it's been the existing behaviour for a while and nobody has complained return !node.IsFile() || node.GetIsTracked() }) if len(untrackedNodes) > 0 { if err := self.c.Git().WorkingTree.UnstageUntrackedFiles(toPaths(untrackedNodes)); err != nil { return err } } if len(trackedNodes) > 0 { if err := self.c.Git().WorkingTree.UnstageTrackedFiles(toPaths(trackedNodes)); err != nil { return err } } } return nil } func (self *FilesController) press(nodes []*filetree.FileNode) error { if err := self.pressWithLock(nodes); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) self.context().HandleFocus(types.OnFocusOpts{}) return nil } func (self *FilesController) Context() types.Context { return self.context() } func (self *FilesController) context() *context.WorkingTreeContext { return self.c.Contexts().Files } func (self *FilesController) getSelectedFile() *models.File { node := self.context().GetSelected() if node == nil { return nil } return node.File } func (self *FilesController) enter() error { return self.EnterFile(types.OnFocusOpts{ClickedWindowName: "", ClickedViewLineIdx: -1}) } func (self *FilesController) collapseAll() error { self.context().FileTreeViewModel.CollapseAll() self.c.PostRefreshUpdate(self.context()) return nil } func (self *FilesController) expandAll() error { self.context().FileTreeViewModel.ExpandAll() self.c.PostRefreshUpdate(self.context()) return nil } func (self *FilesController) EnterFile(opts types.OnFocusOpts) error { node := self.context().GetSelected() if node == nil { return nil } if node.File == nil { return self.handleToggleDirCollapsed() } file := node.File submoduleConfigs := self.c.Model().Submodules if file.IsSubmodule(submoduleConfigs) { submoduleConfig := file.SubmoduleConfig(submoduleConfigs) return self.c.Helpers().Repos.EnterSubmodule(submoduleConfig) } if file.HasInlineMergeConflicts { return self.switchToMerge() } if file.HasMergeConflicts { return self.handleNonInlineConflict(file) } context := lo.Ternary(opts.ClickedWindowName == "secondary", self.c.Contexts().StagingSecondary, self.c.Contexts().Staging) self.c.Context().Push(context, opts) self.c.Helpers().PatchBuilding.ShowHunkStagingHint() return nil } func (self *FilesController) handleNonInlineConflict(file *models.File) error { handle := func(command func(command string) error, logText string) error { self.c.LogAction(logText) if err := command(file.GetPath()); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return nil } keepItem := &types.MenuItem{ Label: self.c.Tr.MergeConflictKeepFile, OnPress: func() error { return handle(self.c.Git().WorkingTree.StageFile, self.c.Tr.Actions.ResolveConflictByKeepingFile) }, Key: 'k', } deleteItem := &types.MenuItem{ Label: self.c.Tr.MergeConflictDeleteFile, OnPress: func() error { return handle(self.c.Git().WorkingTree.RemoveConflictedFile, self.c.Tr.Actions.ResolveConflictByDeletingFile) }, Key: 'd', } items := []*types.MenuItem{} switch file.ShortStatus { case "DD": // For "both deleted" conflicts, deleting the file is the only reasonable thing you can do. // Restoring to the state before deletion is not the responsibility of a conflict resolution tool. items = append(items, deleteItem) case "DU", "UD": // For these, we put the delete option first because it's the most common one, // even if it's more destructive. items = append(items, deleteItem, keepItem) case "AU", "UA": // For these, we put the keep option first because it's less destructive, // and the chances between keep and delete are 50/50. items = append(items, keepItem, deleteItem) default: panic("should only be called if there's a merge conflict") } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.MergeConflictsTitle, Prompt: file.GetMergeStateDescription(self.c.Tr), Items: items, }) } func (self *FilesController) toggleStagedAll() error { if err := self.toggleStagedAllWithLock(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) self.context().HandleFocus(types.OnFocusOpts{}) return nil } func (self *FilesController) toggleStagedAllWithLock() error { self.c.Mutexes().RefreshingFilesMutex.Lock() defer self.c.Mutexes().RefreshingFilesMutex.Unlock() root := self.context().FileTreeViewModel.GetRoot() // if any files within have inline merge conflicts we can't stage or unstage, // or it'll end up with those >>>>>> lines actually staged if root.GetHasInlineMergeConflicts() { return errors.New(self.c.Tr.ErrStageDirWithInlineMergeConflicts) } if root.GetHasUnstagedChanges() { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) if err := self.optimisticChange([]*filetree.FileNode{root}, self.optimisticStage); err != nil { return err } onlyTrackedFiles := self.context().GetFilter() == filetree.DisplayTracked if err := self.c.Git().WorkingTree.StageAll(onlyTrackedFiles); err != nil { return err } } else { self.c.LogAction(self.c.Tr.Actions.UnstageAllFiles) if err := self.optimisticChange([]*filetree.FileNode{root}, self.optimisticUnstage); err != nil { return err } if err := self.c.Git().WorkingTree.UnstageAll(); err != nil { return err } } return nil } func (self *FilesController) unstageFiles(node *filetree.FileNode) error { return node.ForEachFile(func(file *models.File) error { if file.HasStagedChanges { if err := self.c.Git().WorkingTree.UnStageFile(file.Names(), file.Tracked); err != nil { return err } } return nil }) } func (self *FilesController) ignoreOrExcludeTracked(node *filetree.FileNode, trAction string, f func(string) error) error { self.c.LogAction(trAction) // not 100% sure if this is necessary but I'll assume it is if err := self.unstageFiles(node); err != nil { return err } if err := self.c.Git().WorkingTree.RemoveTrackedFiles(node.GetPath()); err != nil { return err } if err := f(node.GetPath()); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return nil } func (self *FilesController) ignoreOrExcludeUntracked(node *filetree.FileNode, trAction string, f func(string) error) error { self.c.LogAction(trAction) if err := f(node.GetPath()); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return nil } func (self *FilesController) ignoreOrExcludeFile(node *filetree.FileNode, trText string, trPrompt string, trAction string, f func(string) error) error { if node.GetIsTracked() { self.c.Confirm(types.ConfirmOpts{ Title: trText, Prompt: trPrompt, HandleConfirm: func() error { return self.ignoreOrExcludeTracked(node, trAction, f) }, }) return nil } return self.ignoreOrExcludeUntracked(node, trAction, f) } func (self *FilesController) ignore(node *filetree.FileNode) error { if node.GetPath() == ".gitignore" { return errors.New(self.c.Tr.Actions.IgnoreFileErr) } return self.ignoreOrExcludeFile(node, self.c.Tr.IgnoreTracked, self.c.Tr.IgnoreTrackedPrompt, self.c.Tr.Actions.IgnoreExcludeFile, self.c.Git().WorkingTree.Ignore) } func (self *FilesController) exclude(node *filetree.FileNode) error { if node.GetPath() == ".gitignore" { return errors.New(self.c.Tr.Actions.ExcludeGitIgnoreErr) } return self.ignoreOrExcludeFile(node, self.c.Tr.ExcludeTracked, self.c.Tr.ExcludeTrackedPrompt, self.c.Tr.Actions.ExcludeFile, self.c.Git().WorkingTree.Exclude) } func (self *FilesController) ignoreOrExcludeMenu(node *filetree.FileNode) error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Actions.IgnoreExcludeFile, Items: []*types.MenuItem{ { LabelColumns: []string{self.c.Tr.IgnoreFile}, OnPress: func() error { if err := self.ignore(node); err != nil { return err } return nil }, Key: 'i', }, { LabelColumns: []string{self.c.Tr.ExcludeFile}, OnPress: func() error { if err := self.exclude(node); err != nil { return err } return nil }, Key: 'e', }, }, }) } func (self *FilesController) refresh() error { self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return nil } func (self *FilesController) handleAmendCommitPress() error { doAmend := func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { if len(self.c.Model().Commits) == 0 { return errors.New(self.c.Tr.NoCommitToAmend) } return self.c.Helpers().AmendHelper.AmendHead() }) } if self.isResolvingConflicts() { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.AmendCommitTitle, Prompt: self.c.Tr.AmendCommitWithConflictsMenuPrompt, HideCancel: true, // We want the cancel item first, so we add one manually Items: []*types.MenuItem{ { Label: self.c.Tr.Cancel, OnPress: func() error { return nil }, }, { Label: self.c.Tr.AmendCommitWithConflictsContinue, OnPress: func() error { return self.c.Helpers().MergeAndRebase.ContinueRebase() }, }, { Label: self.c.Tr.AmendCommitWithConflictsAmend, OnPress: func() error { return doAmend() }, }, }, }) } return self.c.ConfirmIf(!self.c.UserConfig().Gui.SkipAmendWarning, types.ConfirmOpts{ Title: self.c.Tr.AmendLastCommitTitle, Prompt: self.c.Tr.SureToAmend, HandleConfirm: func() error { return doAmend() }, }, ) } func (self *FilesController) isResolvingConflicts() bool { commits := self.c.Model().Commits for _, c := range commits { if c.Status == models.StatusConflicted { return true } if !c.IsTODO() { break } } return false } func (self *FilesController) handleStatusFilterPressed() error { currentFilter := self.context().GetFilter() return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.FilteringMenuTitle, Items: []*types.MenuItem{ { Label: self.c.Tr.FilterStagedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayStaged) }, Key: 's', Widget: types.MakeMenuRadioButton(currentFilter == filetree.DisplayStaged), }, { Label: self.c.Tr.FilterUnstagedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayUnstaged) }, Key: 'u', Widget: types.MakeMenuRadioButton(currentFilter == filetree.DisplayUnstaged), }, { Label: self.c.Tr.FilterTrackedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayTracked) }, Key: 't', Widget: types.MakeMenuRadioButton(currentFilter == filetree.DisplayTracked), }, { Label: self.c.Tr.FilterUntrackedFiles, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayUntracked) }, Key: 'T', Widget: types.MakeMenuRadioButton(currentFilter == filetree.DisplayUntracked), }, { Label: self.c.Tr.NoFilter, OnPress: func() error { return self.setStatusFiltering(filetree.DisplayAll) }, Key: 'r', Widget: types.MakeMenuRadioButton(currentFilter == filetree.DisplayAll), }, }, }) } func (self *FilesController) filteringLabel(filter filetree.FileTreeDisplayFilter) string { switch filter { case filetree.DisplayAll: return "" case filetree.DisplayStaged: return self.c.Tr.FilterLabelStagedFiles case filetree.DisplayUnstaged: return self.c.Tr.FilterLabelUnstagedFiles case filetree.DisplayTracked: return self.c.Tr.FilterLabelTrackedFiles case filetree.DisplayUntracked: return self.c.Tr.FilterLabelUntrackedFiles case filetree.DisplayConflicted: return self.c.Tr.FilterLabelConflictingFiles } panic(fmt.Sprintf("Unexpected files display filter: %d", filter)) } func (self *FilesController) setStatusFiltering(filter filetree.FileTreeDisplayFilter) error { previousFilter := self.context().GetFilter() self.context().FileTreeViewModel.SetStatusFilter(filter) self.c.Contexts().Files.GetView().Subtitle = self.filteringLabel(filter) // Whenever we switch between untracked and other filters, we need to refresh the files view // because the untracked files filter applies when running `git status`. if previousFilter != filter && (previousFilter == filetree.DisplayUntracked || filter == filetree.DisplayUntracked) { self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) } else { self.c.PostRefreshUpdate(self.context()) } return nil } func (self *FilesController) edit(nodes []*filetree.FileNode) error { return self.c.Helpers().Files.EditFiles(lo.FilterMap(nodes, func(node *filetree.FileNode, _ int) (string, bool) { return node.GetPath(), node.IsFile() })) } func (self *FilesController) canEditFiles(nodes []*filetree.FileNode) *types.DisabledReason { if lo.NoneBy(nodes, func(node *filetree.FileNode) bool { return node.IsFile() }) { return &types.DisabledReason{ Text: self.c.Tr.ErrCannotEditDirectory, ShowErrorInPanel: true, } } return nil } func (self *FilesController) Open() error { node := self.context().GetSelected() if node == nil { return nil } return self.c.Helpers().Files.OpenFile(node.GetPath()) } func (self *FilesController) openDiffTool(node *filetree.FileNode) error { fromCommit := "" reverse := false if self.c.Modes().Diffing.Active() { fromCommit = self.c.Modes().Diffing.Ref reverse = self.c.Modes().Diffing.Reverse } return self.c.RunSubprocessAndRefresh( self.c.Git().Diff.OpenDiffToolCmdObj( git_commands.DiffToolCmdOptions{ Filepath: node.GetPath(), FromCommit: fromCommit, ToCommit: "", Reverse: reverse, IsDirectory: !node.IsFile(), Staged: !node.GetHasUnstagedChanges(), }), ) } func (self *FilesController) switchToMerge() error { file := self.getSelectedFile() if file == nil { return nil } return self.c.Helpers().MergeConflicts.SwitchToMerge(file.Path) } func (self *FilesController) createStashMenu() error { return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.StashOptions, Items: []*types.MenuItem{ { Label: self.c.Tr.StashAllChanges, OnPress: func() error { if !self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() { return errors.New(self.c.Tr.NoFilesToStash) } return self.handleStashSave(self.c.Git().Stash.Push, self.c.Tr.Actions.StashAllChanges) }, Key: 'a', }, { Label: self.c.Tr.StashAllChangesKeepIndex, OnPress: func() error { if !self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() { return errors.New(self.c.Tr.NoFilesToStash) } // if there are no staged files it behaves the same as Stash.Save return self.handleStashSave(self.c.Git().Stash.StashAndKeepIndex, self.c.Tr.Actions.StashAllChangesKeepIndex) }, Key: 'i', }, { Label: self.c.Tr.StashIncludeUntrackedChanges, OnPress: func() error { return self.handleStashSave(self.c.Git().Stash.StashIncludeUntrackedChanges, self.c.Tr.Actions.StashIncludeUntrackedChanges) }, Key: 'U', }, { Label: self.c.Tr.StashStagedChanges, OnPress: func() error { // there must be something in staging otherwise the current implementation mucks the stash up if !self.c.Helpers().WorkingTree.AnyStagedFilesExceptSubmodules() { return errors.New(self.c.Tr.NoTrackedStagedFilesStash) } return self.handleStashSave(self.c.Git().Stash.SaveStagedChanges, self.c.Tr.Actions.StashStagedChanges) }, Key: 's', }, { Label: self.c.Tr.StashUnstagedChanges, OnPress: func() error { if !self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() { return errors.New(self.c.Tr.NoFilesToStash) } if self.c.Helpers().WorkingTree.AnyStagedFilesExceptSubmodules() { return self.handleStashSave(self.c.Git().Stash.StashUnstagedChanges, self.c.Tr.Actions.StashUnstagedChanges) } // ordinary stash return self.handleStashSave(self.c.Git().Stash.Push, self.c.Tr.Actions.StashUnstagedChanges) }, Key: 'u', }, }, }) } func (self *FilesController) openMergeConflictMenu(nodes []*filetree.FileNode) error { normalizedNodes := flattenSelectedNodesToFiles(nodes) fileNodesWithConflicts := lo.Filter(normalizedNodes, func(node *filetree.FileNode, _ int) bool { return node.File != nil && node.File.HasInlineMergeConflicts }) filepaths := lo.Map(fileNodesWithConflicts, func(node *filetree.FileNode, _ int) string { return node.GetPath() }) return self.c.Helpers().WorkingTree.CreateMergeConflictMenu(filepaths) } func (self *FilesController) canOpenMergeConflictMenu(nodes []*filetree.FileNode) *types.DisabledReason { normalizedNodes := flattenSelectedNodesToFiles(nodes)
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/undo_controller.go
pkg/gui/controllers/undo_controller.go
package controllers import ( "errors" "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) // Quick summary of how this all works: // when you want to undo or redo, we start from the top of the reflog and work // down until we've reached the last user-initiated reflog entry that hasn't already been undone // we then do the reverse of what that reflog describes. // When we do this, we create a new reflog entry, and tag it as either an undo or redo // Then, next time we want to undo, we'll use those entries to know which user-initiated // actions we can skip. E.g. if I do three things, A, B, and C, and hit undo twice, // the reflog will read UUCBA, and when I read the first two undos, I know to skip the following // two user actions, meaning we end up undoing reflog entry C. Redoing works in a similar way. type UndoController struct { baseController c *ControllerCommon } var _ types.IController = &UndoController{} func NewUndoController( c *ControllerCommon, ) *UndoController { return &UndoController{ baseController: baseController{}, c: c, } } type ReflogActionKind int const ( CHECKOUT ReflogActionKind = iota COMMIT REBASE CURRENT_REBASE ) type reflogAction struct { kind ReflogActionKind from string to string } func (self *UndoController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Undo), Handler: self.reflogUndo, Description: self.c.Tr.UndoReflog, Tooltip: self.c.Tr.UndoTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Redo), Handler: self.reflogRedo, Description: self.c.Tr.RedoReflog, Tooltip: self.c.Tr.RedoTooltip, }, } return bindings } func (self *UndoController) Context() types.Context { return nil } func (self *UndoController) reflogUndo() error { undoEnvVars := []string{"GIT_REFLOG_ACTION=[lazygit undo]"} undoingStatus := self.c.Tr.UndoingStatus if self.c.Git().Status.WorkingTreeState().Any() { return errors.New(self.c.Tr.CantUndoWhileRebasing) } return self.parseReflogForActions(func(counter int, action reflogAction) (bool, error) { if counter != 0 { return false, nil } switch action.kind { case COMMIT: self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.Undo, Prompt: fmt.Sprintf(self.c.Tr.SoftResetPrompt, utils.ShortHash(action.from)), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.Undo) return self.c.WithWaitingStatus(undoingStatus, func(gocui.Task) error { return self.c.Helpers().Refs.ResetToRef(action.from, "soft", undoEnvVars) }) }, }) return true, nil case REBASE: self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.Undo, Prompt: fmt.Sprintf(self.c.Tr.HardResetAutostashPrompt, utils.ShortHash(action.from)), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.Undo) return self.hardResetWithAutoStash(action.from, hardResetOptions{ EnvVars: undoEnvVars, WaitingStatus: undoingStatus, }) }, }) return true, nil case CHECKOUT: self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.Undo, Prompt: fmt.Sprintf(self.c.Tr.CheckoutAutostashPrompt, action.from), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.Undo) return self.c.Helpers().Refs.CheckoutRef(action.from, types.CheckoutRefOptions{ EnvVars: undoEnvVars, WaitingStatus: undoingStatus, }) }, }) return true, nil case CURRENT_REBASE: // do nothing } self.c.Log.Error("didn't match on the user action when trying to undo") return true, nil }) } func (self *UndoController) reflogRedo() error { redoEnvVars := []string{"GIT_REFLOG_ACTION=[lazygit redo]"} redoingStatus := self.c.Tr.RedoingStatus if self.c.Git().Status.WorkingTreeState().Any() { return errors.New(self.c.Tr.CantRedoWhileRebasing) } return self.parseReflogForActions(func(counter int, action reflogAction) (bool, error) { // if we're redoing and the counter is zero, we just return if counter == 0 { return true, nil } else if counter > 1 { return false, nil } switch action.kind { case COMMIT, REBASE: self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.Redo, Prompt: fmt.Sprintf(self.c.Tr.HardResetAutostashPrompt, utils.ShortHash(action.to)), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.Redo) return self.hardResetWithAutoStash(action.to, hardResetOptions{ EnvVars: redoEnvVars, WaitingStatus: redoingStatus, }) }, }) return true, nil case CHECKOUT: self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.Redo, Prompt: fmt.Sprintf(self.c.Tr.CheckoutAutostashPrompt, action.to), HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.Redo) return self.c.Helpers().Refs.CheckoutRef(action.to, types.CheckoutRefOptions{ EnvVars: redoEnvVars, WaitingStatus: redoingStatus, }) }, }) return true, nil case CURRENT_REBASE: // do nothing } self.c.Log.Error("didn't match on the user action when trying to redo") return true, nil }) } // Here we're going through the reflog and maintaining a counter that represents how many // undos/redos/user actions we've seen. when we hit a user action we call the callback specifying // what the counter is up to and the nature of the action. // If we find ourselves mid-rebase, we just return because undo/redo mid rebase // requires knowledge of previous TODO file states, which you can't just get from the reflog. // Though we might support this later, hence the use of the CURRENT_REBASE action kind. func (self *UndoController) parseReflogForActions(onUserAction func(counter int, action reflogAction) (bool, error)) error { counter := 0 reflogCommits := self.c.Model().ReflogCommits rebaseFinishCommitHash := "" var action *reflogAction for reflogCommitIdx, reflogCommit := range reflogCommits { action = nil prevCommitHash := "" if len(reflogCommits)-1 >= reflogCommitIdx+1 { prevCommitHash = reflogCommits[reflogCommitIdx+1].Hash() } if rebaseFinishCommitHash == "" { if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^\[lazygit undo\]`); ok { counter++ } else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^\[lazygit redo\]`); ok { counter-- } else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(abort\)|^rebase (-i )?\(finish\)`); ok { rebaseFinishCommitHash = reflogCommit.Hash() } else if ok, match := utils.FindStringSubmatch(reflogCommit.Name, `^checkout: moving from ([\S]+) to ([\S]+)`); ok { action = &reflogAction{kind: CHECKOUT, from: match[1], to: match[2]} } else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^commit|^reset: moving to|^pull`); ok { action = &reflogAction{kind: COMMIT, from: prevCommitHash, to: reflogCommit.Hash()} } else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok { // if we're here then we must be currently inside an interactive rebase action = &reflogAction{kind: CURRENT_REBASE, from: prevCommitHash} } } else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok { action = &reflogAction{kind: REBASE, from: prevCommitHash, to: rebaseFinishCommitHash} rebaseFinishCommitHash = "" } if action != nil { if action.kind != CURRENT_REBASE && action.from == action.to { // if we're going from one place to the same place we'll ignore the action. continue } ok, err := onUserAction(counter, *action) if ok { return err } counter-- } } return nil } type hardResetOptions struct { WaitingStatus string EnvVars []string } // only to be used in the undo flow for now (does an autostash) func (self *UndoController) hardResetWithAutoStash(commitHash string, options hardResetOptions) error { reset := func() error { return self.c.Helpers().Refs.ResetToRef(commitHash, "hard", options.EnvVars) } // if we have any modified tracked files we need to auto-stash dirtyWorkingTree := self.c.Helpers().WorkingTree.IsWorkingTreeDirtyExceptSubmodules() if dirtyWorkingTree { return self.c.WithWaitingStatus(options.WaitingStatus, func(gocui.Task) error { if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForUndo, utils.ShortHash(commitHash))); err != nil { return err } if err := reset(); err != nil { return err } err := self.c.Git().Stash.Pop(0) if err != nil { return err } self.c.Refresh(types.RefreshOptions{}) return nil }) } return self.c.WithWaitingStatus(options.WaitingStatus, func(gocui.Task) error { return reset() }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/jump_to_side_window_controller.go
pkg/gui/controllers/jump_to_side_window_controller.go
package controllers import ( "log" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type JumpToSideWindowController struct { baseController c *ControllerCommon nextTabFunc func() error } func NewJumpToSideWindowController( c *ControllerCommon, nextTabFunc func() error, ) *JumpToSideWindowController { return &JumpToSideWindowController{ baseController: baseController{}, c: c, nextTabFunc: nextTabFunc, } } func (self *JumpToSideWindowController) Context() types.Context { return nil } func (self *JumpToSideWindowController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { windows := self.c.Helpers().Window.SideWindows() if len(opts.Config.Universal.JumpToBlock) != len(windows) { log.Fatal("Jump to block keybindings cannot be set. Exactly 5 keybindings must be supplied.") } return lo.Map(windows, func(window string, index int) *types.Binding { return &types.Binding{ ViewName: "", // by default the keys are 1, 2, 3, etc Key: opts.GetKey(opts.Config.Universal.JumpToBlock[index]), Modifier: gocui.ModNone, Handler: opts.Guards.NoPopupPanel(self.goToSideWindow(window)), } }) } func (self *JumpToSideWindowController) goToSideWindow(window string) func() error { return func() error { sideWindowAlreadyActive := self.c.Helpers().Window.CurrentWindow() == window if sideWindowAlreadyActive && self.c.UserConfig().Gui.SwitchTabsWithPanelJumpKeys { return self.nextTabFunc() } context := self.c.Helpers().Window.GetContextForWindow(window) self.c.Context().Push(context, types.OnFocusOpts{}) return nil } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/rename_similarity_threshold_controller.go
pkg/gui/controllers/rename_similarity_threshold_controller.go
package controllers import ( "fmt" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // This controller lets you change the similarity threshold for detecting renames. var CONTEXT_KEYS_SHOWING_RENAMES = []types.ContextKey{ context.FILES_CONTEXT_KEY, context.SUB_COMMITS_CONTEXT_KEY, context.LOCAL_COMMITS_CONTEXT_KEY, context.STASH_CONTEXT_KEY, context.NORMAL_MAIN_CONTEXT_KEY, context.NORMAL_SECONDARY_CONTEXT_KEY, } type RenameSimilarityThresholdController struct { baseController c *ControllerCommon } var _ types.IController = &RenameSimilarityThresholdController{} func NewRenameSimilarityThresholdController( common *ControllerCommon, ) *RenameSimilarityThresholdController { return &RenameSimilarityThresholdController{ baseController: baseController{}, c: common, } } func (self *RenameSimilarityThresholdController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.IncreaseRenameSimilarityThreshold), Handler: self.Increase, Description: self.c.Tr.IncreaseRenameSimilarityThreshold, Tooltip: self.c.Tr.IncreaseRenameSimilarityThresholdTooltip, }, { Key: opts.GetKey(opts.Config.Universal.DecreaseRenameSimilarityThreshold), Handler: self.Decrease, Description: self.c.Tr.DecreaseRenameSimilarityThreshold, Tooltip: self.c.Tr.DecreaseRenameSimilarityThresholdTooltip, }, } return bindings } func (self *RenameSimilarityThresholdController) Context() types.Context { return nil } func (self *RenameSimilarityThresholdController) Increase() error { old_size := self.c.UserConfig().Git.RenameSimilarityThreshold if self.isShowingRenames() && old_size < 100 { self.c.UserConfig().Git.RenameSimilarityThreshold = min(100, old_size+5) return self.applyChange() } return nil } func (self *RenameSimilarityThresholdController) Decrease() error { old_size := self.c.UserConfig().Git.RenameSimilarityThreshold if self.isShowingRenames() && old_size > 5 { self.c.UserConfig().Git.RenameSimilarityThreshold = max(5, old_size-5) return self.applyChange() } return nil } func (self *RenameSimilarityThresholdController) applyChange() error { self.c.Toast(fmt.Sprintf(self.c.Tr.RenameSimilarityThresholdChanged, self.c.UserConfig().Git.RenameSimilarityThreshold)) currentContext := self.currentSidePanel() switch currentContext.GetKey() { // we make an exception for our files context, because it actually need to refresh its state afterwards. case context.FILES_CONTEXT_KEY: self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) default: currentContext.HandleRenderToMain() } return nil } func (self *RenameSimilarityThresholdController) isShowingRenames() bool { return lo.Contains( CONTEXT_KEYS_SHOWING_RENAMES, self.currentSidePanel().GetKey(), ) } func (self *RenameSimilarityThresholdController) currentSidePanel() types.Context { currentContext := self.c.Context().CurrentStatic() if currentContext.GetKey() == context.NORMAL_MAIN_CONTEXT_KEY || currentContext.GetKey() == context.NORMAL_SECONDARY_CONTEXT_KEY { if sidePanelContext := self.c.Context().NextInStack(currentContext); sidePanelContext != nil { return sidePanelContext } } return currentContext }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/staging_controller.go
pkg/gui/controllers/staging_controller.go
package controllers import ( "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type StagingController struct { baseController c *ControllerCommon context types.IPatchExplorerContext otherContext types.IPatchExplorerContext // if true, we're dealing with the secondary context i.e. dealing with staged file changes staged bool } var _ types.IController = &StagingController{} func NewStagingController( c *ControllerCommon, context types.IPatchExplorerContext, otherContext types.IPatchExplorerContext, staged bool, ) *StagingController { return &StagingController{ baseController: baseController{}, c: c, context: context, otherContext: otherContext, staged: staged, } } func (self *StagingController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.ToggleStaged, Description: self.c.Tr.Stage, Tooltip: self.c.Tr.StageSelectionTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.DiscardSelection, Description: self.c.Tr.DiscardSelection, Tooltip: self.c.Tr.DiscardSelectionTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.OpenFile, Description: self.c.Tr.OpenFile, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.EditFile, Description: self.c.Tr.EditFile, Tooltip: self.c.Tr.EditFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.Escape, Description: self.c.Tr.ReturnToFilesPanel, DescriptionFunc: self.EscapeDescription, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: self.TogglePanel, Description: self.c.Tr.ToggleStagingView, Tooltip: self.c.Tr.ToggleStagingViewTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Main.EditSelectHunk), Handler: self.EditHunkAndRefresh, Description: self.c.Tr.EditHunk, Tooltip: self.c.Tr.EditHunkTooltip, }, { Key: opts.GetKey(opts.Config.Files.CommitChanges), Handler: self.c.Helpers().WorkingTree.HandleCommitPress, Description: self.c.Tr.Commit, Tooltip: self.c.Tr.CommitTooltip, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithoutHook), Handler: self.c.Helpers().WorkingTree.HandleWIPCommitPress, Description: self.c.Tr.CommitChangesWithoutHook, }, { Key: opts.GetKey(opts.Config.Files.CommitChangesWithEditor), Handler: self.c.Helpers().WorkingTree.HandleCommitEditorPress, Description: self.c.Tr.CommitChangesWithEditor, }, { Key: opts.GetKey(opts.Config.Files.FindBaseCommitForFixup), Handler: self.c.Helpers().FixupHelper.HandleFindBaseCommitForFixupPress, Description: self.c.Tr.FindBaseCommitForFixup, Tooltip: self.c.Tr.FindBaseCommitForFixupTooltip, }, } } func (self *StagingController) Context() types.Context { return self.context } func (self *StagingController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{} } func (self *StagingController) GetOnFocus() func(types.OnFocusOpts) { return func(opts types.OnFocusOpts) { wrap := self.c.UserConfig().Gui.WrapLinesInStagingView self.c.Views().Staging.Wrap = wrap self.c.Views().StagingSecondary.Wrap = wrap self.c.Helpers().Staging.RefreshStagingPanel(opts) } } func (self *StagingController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(opts types.OnFocusLostOpts) { self.context.SetState(nil) if opts.NewContextKey != self.otherContext.GetKey() { self.c.Views().Staging.Wrap = true self.c.Views().StagingSecondary.Wrap = true } } } func (self *StagingController) OpenFile() error { self.context.GetMutex().Lock() defer self.context.GetMutex().Unlock() path := self.FilePath() if path == "" { return nil } return self.c.Helpers().Files.OpenFile(path) } func (self *StagingController) EditFile() error { self.context.GetMutex().Lock() defer self.context.GetMutex().Unlock() path := self.FilePath() if path == "" { return nil } lineNumber := self.context.GetState().CurrentLineNumber() lineNumber = self.c.Helpers().Diff.AdjustLineNumber(path, lineNumber, self.context.GetViewName()) return self.c.Helpers().Files.EditFileAtLine(path, lineNumber) } func (self *StagingController) Escape() error { if self.context.GetState().SelectingRange() || self.context.GetState().SelectingHunkEnabledByUser() { self.context.GetState().SetLineSelectMode() self.c.PostRefreshUpdate(self.context) return nil } self.c.Context().Pop() return nil } func (self *StagingController) EscapeDescription() string { if state := self.context.GetState(); state != nil { if state.SelectingRange() { return self.c.Tr.DismissRangeSelect } if state.SelectingHunkEnabledByUser() { return self.c.Tr.SelectLineByLine } } return self.c.Tr.ReturnToFilesPanel } func (self *StagingController) TogglePanel() error { if self.otherContext.GetState() != nil { self.c.Context().Push(self.otherContext, types.OnFocusOpts{}) } return nil } func (self *StagingController) ToggleStaged() error { if self.c.UserConfig().Git.DiffContextSize == 0 { return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextToStage, keybindings.Label(self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView)) } return self.applySelectionAndRefresh(self.staged) } func (self *StagingController) DiscardSelection() error { if self.c.UserConfig().Git.DiffContextSize == 0 { return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextToDiscard, keybindings.Label(self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView)) } return self.c.ConfirmIf(!self.staged && !self.c.UserConfig().Gui.SkipDiscardChangeWarning, types.ConfirmOpts{ Title: self.c.Tr.DiscardChangeTitle, Prompt: self.c.Tr.DiscardChangePrompt, HandleConfirm: func() error { return self.applySelectionAndRefresh(true) }, }) } func (self *StagingController) applySelectionAndRefresh(reverse bool) error { if err := self.applySelection(reverse); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) return nil } func (self *StagingController) applySelection(reverse bool) error { self.context.GetMutex().Lock() defer self.context.GetMutex().Unlock() state := self.context.GetState() path := self.FilePath() if path == "" { return nil } firstLineIdx, lastLineIdx := state.SelectedPatchRange() patchToApply := patch. Parse(state.GetDiff()). Transform(patch.TransformOpts{ Reverse: reverse, IncludedLineIndices: patch.ExpandRange(firstLineIdx, lastLineIdx), FileNameOverride: path, }). FormatPlain() if patchToApply == "" { return nil } // apply the patch then refresh this panel // create a new temp file with the patch, then call git apply with that patch self.c.LogAction(self.c.Tr.Actions.ApplyPatch) err := self.c.Git().Patch.ApplyPatch( patchToApply, git_commands.ApplyPatchOpts{ Reverse: reverse, Cached: !reverse || self.staged, }, ) if err != nil { return err } if state.SelectingRange() { firstLine, _ := state.SelectedViewRange() state.SelectLine(firstLine) } return nil } func (self *StagingController) EditHunkAndRefresh() error { if err := self.editHunk(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) return nil } func (self *StagingController) editHunk() error { self.context.GetMutex().Lock() defer self.context.GetMutex().Unlock() state := self.context.GetState() path := self.FilePath() if path == "" { return nil } hunkStartIdx, hunkEndIdx := state.CurrentHunkBounds() patchText := patch. Parse(state.GetDiff()). Transform(patch.TransformOpts{ Reverse: self.staged, IncludedLineIndices: patch.ExpandRange(hunkStartIdx, hunkEndIdx), FileNameOverride: path, }). FormatPlain() patchFilepath, err := self.c.Git().Patch.SaveTemporaryPatch(patchText) if err != nil { return err } lineOffset := 3 lineIdxInHunk := state.GetSelectedPatchLineIdx() - hunkStartIdx if err := self.c.Helpers().Files.EditFileAtLineAndWait(patchFilepath, lineIdxInHunk+lineOffset); err != nil { return err } editedPatchText, err := self.c.Git().File.Cat(patchFilepath) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.ApplyPatch) lineCount := strings.Count(editedPatchText, "\n") + 1 newPatchText := patch. Parse(editedPatchText). Transform(patch.TransformOpts{ IncludedLineIndices: patch.ExpandRange(0, lineCount), FileNameOverride: path, }). FormatPlain() if err := self.c.Git().Patch.ApplyPatch( newPatchText, git_commands.ApplyPatchOpts{ Reverse: self.staged, Cached: true, }, ); err != nil { return err } return nil } func (self *StagingController) FilePath() string { return self.c.Contexts().Files.GetSelectedPath() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/local_commits_controller_test.go
pkg/gui/controllers/local_commits_controller_test.go
package controllers import ( "testing" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/stretchr/testify/assert" ) func Test_countSquashableCommitsAbove(t *testing.T) { scenarios := []struct { name string commits []*models.Commit selectedIdx int rebaseStartIdx int expectedResult int }{ { name: "no squashable commits", commits: []*models.Commit{ {Name: "abc"}, {Name: "def"}, {Name: "ghi"}, }, selectedIdx: 2, rebaseStartIdx: 2, expectedResult: 0, }, { name: "some squashable commits, including for the selected commit", commits: []*models.Commit{ {Name: "fixup! def"}, {Name: "fixup! ghi"}, {Name: "abc"}, {Name: "def"}, {Name: "ghi"}, }, selectedIdx: 4, rebaseStartIdx: 4, expectedResult: 2, }, { name: "base commit is below rebase start", commits: []*models.Commit{ {Name: "fixup! def"}, {Name: "abc"}, {Name: "def"}, }, selectedIdx: 1, rebaseStartIdx: 1, expectedResult: 0, }, { name: "base commit does not exist at all", commits: []*models.Commit{ {Name: "fixup! xyz"}, {Name: "abc"}, {Name: "def"}, }, selectedIdx: 2, rebaseStartIdx: 2, expectedResult: 0, }, { name: "selected commit is in the middle of fixups", commits: []*models.Commit{ {Name: "fixup! def"}, {Name: "abc"}, {Name: "fixup! ghi"}, {Name: "def"}, {Name: "ghi"}, }, selectedIdx: 1, rebaseStartIdx: 4, expectedResult: 1, }, { name: "selected commit is after rebase start", commits: []*models.Commit{ {Name: "fixup! def"}, {Name: "abc"}, {Name: "def"}, {Name: "ghi"}, }, selectedIdx: 3, rebaseStartIdx: 2, expectedResult: 1, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { assert.Equal(t, s.expectedResult, countSquashableCommitsAbove(s.commits, s.selectedIdx, s.rebaseStartIdx)) }) } } func Test_isFixupCommit(t *testing.T) { scenarios := []struct { subject string expectedTrimmedSubject string expectedIsFixup bool }{ { subject: "Bla", expectedTrimmedSubject: "Bla", expectedIsFixup: false, }, { subject: "fixup Bla", expectedTrimmedSubject: "fixup Bla", expectedIsFixup: false, }, { subject: "fixup! Bla", expectedTrimmedSubject: "Bla", expectedIsFixup: true, }, { subject: "fixup! fixup! Bla", expectedTrimmedSubject: "Bla", expectedIsFixup: true, }, { subject: "amend! squash! Bla", expectedTrimmedSubject: "Bla", expectedIsFixup: true, }, { subject: "fixup!", expectedTrimmedSubject: "fixup!", expectedIsFixup: false, }, } for _, s := range scenarios { t.Run(s.subject, func(t *testing.T) { trimmedSubject, isFixupCommit := isFixupCommit(s.subject) assert.Equal(t, s.expectedTrimmedSubject, trimmedSubject) assert.Equal(t, s.expectedIsFixup, isFixupCommit) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/commit_message_controller.go
pkg/gui/controllers/commit_message_controller.go
package controllers import ( "errors" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type CommitMessageController struct { baseController c *ControllerCommon } var _ types.IController = &CommitMessageController{} func NewCommitMessageController( c *ControllerCommon, ) *CommitMessageController { return &CommitMessageController{ baseController: baseController{}, c: c, } } func (self *CommitMessageController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.SubmitEditorText), Handler: self.confirm, Description: self.c.Tr.Confirm, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: self.close, Description: self.c.Tr.Close, }, { Key: opts.GetKey(opts.Config.Universal.PrevItem), Handler: self.handlePreviousCommit, }, { Key: opts.GetKey(opts.Config.Universal.NextItem), Handler: self.handleNextCommit, }, { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: self.handleTogglePanel, }, { Key: opts.GetKey(opts.Config.CommitMessage.CommitMenu), Handler: self.openCommitMenu, }, } return bindings } func (self *CommitMessageController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.Context().GetViewName(), FocusedView: self.c.Contexts().CommitDescription.GetViewName(), Key: gocui.MouseLeft, Handler: self.onClick, }, } } func (self *CommitMessageController) GetOnFocus() func(types.OnFocusOpts) { return func(types.OnFocusOpts) { self.c.Views().CommitDescription.Footer = "" } } func (self *CommitMessageController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.context().RenderSubtitle() } } func (self *CommitMessageController) Context() types.Context { return self.context() } func (self *CommitMessageController) context() *context.CommitMessageContext { return self.c.Contexts().CommitMessage } func (self *CommitMessageController) handlePreviousCommit() error { return self.handleCommitIndexChange(1) } func (self *CommitMessageController) handleNextCommit() error { if self.context().GetSelectedIndex() == context.NoCommitIndex { return nil } return self.handleCommitIndexChange(-1) } func (self *CommitMessageController) switchToCommitDescription() error { self.c.Context().Replace(self.c.Contexts().CommitDescription) return nil } func (self *CommitMessageController) handleTogglePanel() error { // The default keybinding for this action is "<tab>", which means that we // also get here when pasting multi-line text that contains tabs. In that // case we don't want to toggle the panel, but insert the tab as a character // (somehow, see below). // // Only do this if the TogglePanel command is actually mapped to "<tab>" // (the default). If it's not, we can only hope that it's mapped to some // ctrl key or fn key, which is unlikely to occur in pasted text. And if // they mapped some *other* command to "<tab>", then we're totally out of // luck. if self.c.GocuiGui().IsPasting && self.c.UserConfig().Keybinding.Universal.TogglePanel == "<tab>" { // It is unlikely that a pasted commit message contains a tab in the // subject line, so it shouldn't matter too much how we handle it. // Simply insert 4 spaces instead; all that matters is that we don't // switch to the description panel. view := self.context().GetView() for range 4 { view.Editor.Edit(view, gocui.KeySpace, ' ', 0) } return nil } return self.switchToCommitDescription() } func (self *CommitMessageController) handleCommitIndexChange(value int) error { currentIndex := self.context().GetSelectedIndex() newIndex := currentIndex + value if newIndex == context.NoCommitIndex { self.context().SetSelectedIndex(newIndex) self.c.Helpers().Commits.SetMessageAndDescriptionInView(self.context().GetHistoryMessage()) return nil } else if currentIndex == context.NoCommitIndex { self.context().SetHistoryMessage(self.c.Helpers().Commits.JoinCommitMessageAndUnwrappedDescription()) } validCommit, err := self.setCommitMessageAtIndex(newIndex) if validCommit { self.context().SetSelectedIndex(newIndex) } return err } // returns true if the given index is for a valid commit func (self *CommitMessageController) setCommitMessageAtIndex(index int) (bool, error) { commitMessage, err := self.c.Git().Commit.GetCommitMessageFromHistory(index) if err != nil { if errors.Is(err, git_commands.ErrInvalidCommitIndex) { return false, nil } return false, errors.New(self.c.Tr.CommitWithoutMessageErr) } if self.c.UserConfig().Git.Commit.AutoWrapCommitMessage { commitMessage = helpers.TryRemoveHardLineBreaks(commitMessage, self.c.UserConfig().Git.Commit.AutoWrapWidth) } self.c.Helpers().Commits.UpdateCommitPanelView(commitMessage) return true, nil } func (self *CommitMessageController) confirm() error { // The default keybinding for this action is "<enter>", which means that we // also get here when pasting multi-line text that contains newlines. In // that case we don't want to confirm the commit, but switch to the // description panel instead so that the rest of the pasted text goes there. // // Only do this if the SubmitEditorText command is actually mapped to // "<enter>" (the default). If it's not, we can only hope that it's mapped // to some ctrl key or fn key, which is unlikely to occur in pasted text. // And if they mapped some *other* command to "<enter>", then we're totally // out of luck. if self.c.GocuiGui().IsPasting && self.c.UserConfig().Keybinding.Universal.SubmitEditorText == "<enter>" { return self.switchToCommitDescription() } return self.c.Helpers().Commits.HandleCommitConfirm() } func (self *CommitMessageController) close() error { self.c.Helpers().Commits.CloseCommitMessagePanel() return nil } func (self *CommitMessageController) openCommitMenu() error { authorSuggestion := self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc() return self.c.Helpers().Commits.OpenCommitMenu(authorSuggestion) } func (self *CommitMessageController) onClick(opts gocui.ViewMouseBindingOpts) error { self.c.Context().Replace(self.c.Contexts().CommitMessage) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/prompt_controller.go
pkg/gui/controllers/prompt_controller.go
package controllers import ( "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type PromptController struct { baseController c *ControllerCommon } var _ types.IController = &PromptController{} func NewPromptController( c *ControllerCommon, ) *PromptController { return &PromptController{ baseController: baseController{}, c: c, } } func (self *PromptController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: gocui.KeyEnter, Handler: func() error { return self.context().State.OnConfirm() }, Description: self.c.Tr.Confirm, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: func() error { return self.context().State.OnClose() }, Description: self.c.Tr.CloseCancel, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.TogglePanel), Handler: func() error { if len(self.c.Contexts().Suggestions.State.Suggestions) > 0 { self.switchToSuggestions() } return nil }, }, } return bindings } func (self *PromptController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.c.Contexts().Suggestions.GetViewName(), FocusedView: self.c.Contexts().Prompt.GetViewName(), Key: gocui.MouseLeft, Handler: func(gocui.ViewMouseBindingOpts) error { self.switchToSuggestions() // Let it fall through to the ListController's click handler so that // the clicked line gets selected: return gocui.ErrKeybindingNotHandled }, }, } } func (self *PromptController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.c.Helpers().Confirmation.DeactivatePrompt() } } func (self *PromptController) Context() types.Context { return self.context() } func (self *PromptController) context() *context.PromptContext { return self.c.Contexts().Prompt } func (self *PromptController) switchToSuggestions() { subtitle := "" if self.c.State().GetRepoState().GetCurrentPopupOpts().HandleDeleteSuggestion != nil { // We assume that whenever things are deletable, they // are also editable, so we show both keybindings subtitle = fmt.Sprintf(self.c.Tr.SuggestionsSubtitle, self.c.UserConfig().Keybinding.Universal.Remove, self.c.UserConfig().Keybinding.Universal.Edit) } self.c.Views().Suggestions.Subtitle = subtitle self.c.Context().Replace(self.c.Contexts().Suggestions) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/status_controller.go
pkg/gui/controllers/status_controller.go
package controllers import ( "errors" "fmt" "strings" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type StatusController struct { baseController c *ControllerCommon } var _ types.IController = &StatusController{} func NewStatusController( c *ControllerCommon, ) *StatusController { return &StatusController{ baseController: baseController{}, c: c, } } func (self *StatusController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.OpenFile), Handler: self.openConfig, Description: self.c.Tr.OpenConfig, Tooltip: self.c.Tr.OpenFileTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Edit), Handler: self.editConfig, Description: self.c.Tr.EditConfig, Tooltip: self.c.Tr.EditFileTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Status.CheckForUpdate), Handler: self.handleCheckForUpdate, Description: self.c.Tr.CheckForUpdate, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Status.RecentRepos), Handler: self.c.Helpers().Repos.CreateRecentReposMenu, Description: self.c.Tr.SwitchRepo, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Status.AllBranchesLogGraph), Handler: func() error { self.switchToOrRotateAllBranchesLogs(); return nil }, Description: self.c.Tr.AllBranchesLogGraph, }, } return bindings } func (self *StatusController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.Context().GetViewName(), Key: gocui.MouseLeft, Handler: self.onClick, }, } } func (self *StatusController) GetOnRenderToMain() func() { return func() { switch self.c.UserConfig().Gui.StatusPanelView { case "dashboard": self.showDashboard() case "allBranchesLog": self.showAllBranchLogs() default: self.showDashboard() } } } func (self *StatusController) Context() types.Context { return self.c.Contexts().Status } func (self *StatusController) onClick(opts gocui.ViewMouseBindingOpts) error { // TODO: move into some abstraction (status is currently not a listViewContext where a lot of this code lives) currentBranch := self.c.Helpers().Refs.GetCheckedOutRef() if currentBranch == nil { // need to wait for branches to refresh return nil } self.c.Context().Push(self.Context(), types.OnFocusOpts{}) upstreamStatus := utils.Decolorise(presentation.BranchStatus(currentBranch, types.ItemOperationNone, self.c.Tr, time.Now(), self.c.UserConfig())) repoName := self.c.Git().RepoPaths.RepoName() workingTreeState := self.c.Git().Status.WorkingTreeState() if workingTreeState.Any() { workingTreeStatus := fmt.Sprintf("(%s)", workingTreeState.LowerCaseTitle(self.c.Tr)) if cursorInSubstring(opts.X, upstreamStatus+" ", workingTreeStatus) { return self.c.Helpers().MergeAndRebase.CreateRebaseOptionsMenu() } if cursorInSubstring(opts.X, upstreamStatus+" "+workingTreeStatus+" ", repoName) { return self.c.Helpers().Repos.CreateRecentReposMenu() } } else if cursorInSubstring(opts.X, upstreamStatus+" ", repoName) { return self.c.Helpers().Repos.CreateRecentReposMenu() } return nil } func runeCount(str string) int { return len([]rune(str)) } func cursorInSubstring(cx int, prefix string, substring string) bool { return cx >= runeCount(prefix) && cx < runeCount(prefix+substring) } func lazygitTitle() string { return ` _ _ _ | | (_) | | | __ _ _____ _ __ _ _| |_ | |/ _` + "`" + ` |_ / | | |/ _` + "`" + ` | | __| | | (_| |/ /| |_| | (_| | | |_ |_|\__,_/___|\__, |\__, |_|\__| __/ | __/ | |___/ |___/ ` } func (self *StatusController) askForConfigFile(action func(file string) error) error { confPaths := self.c.GetConfig().GetUserConfigPaths() switch len(confPaths) { case 0: return errors.New(self.c.Tr.NoConfigFileFoundErr) case 1: return action(confPaths[0]) default: menuItems := lo.Map(confPaths, func(path string, _ int) *types.MenuItem { return &types.MenuItem{ Label: path, OnPress: func() error { return action(path) }, } }) return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.SelectConfigFile, Items: menuItems, }) } } func (self *StatusController) openConfig() error { return self.askForConfigFile(self.c.Helpers().Files.OpenFile) } func (self *StatusController) editConfig() error { return self.askForConfigFile(func(file string) error { return self.c.Helpers().Files.EditFiles([]string{file}) }) } func (self *StatusController) showAllBranchLogs() { cmdObj := self.c.Git().Branch.AllBranchesLogCmdObj() task := types.NewRunPtyTask(cmdObj.GetCmd()) title := self.c.Tr.LogTitle if i, n := self.c.Git().Branch.GetAllBranchesLogIdxAndCount(); n > 1 { title = fmt.Sprintf(self.c.Tr.LogXOfYTitle, i+1, n) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: title, Task: task, }, }) } // Switches to the all branches view, or, if already on that view, // rotates to the next command in the list, and then renders it. func (self *StatusController) switchToOrRotateAllBranchesLogs() { // A bit of a hack to ensure we only rotate to the next branch log command // if we currently are looking at a branch log. Otherwise, we should just show // the current index (if we are coming from the dashboard). if self.c.Views().Main.Title != self.c.Tr.StatusTitle { self.c.Git().Branch.RotateAllBranchesLogIdx() } self.showAllBranchLogs() } func (self *StatusController) showDashboard() { versionStr := "master" version, err := types.ParseVersionNumber(self.c.GetConfig().GetVersion()) if err == nil { // Don't just take the version string as is, but format it again. This // way it will be correct even if a distribution omits the "v", or the // ".0" at the end. versionStr = fmt.Sprintf("v%d.%d.%d", version.Major, version.Minor, version.Patch) } dashboardString := strings.Join( []string{ lazygitTitle(), fmt.Sprintf("Copyright %d Jesse Duffield", time.Now().Year()), fmt.Sprintf("Keybindings: %s", fmt.Sprintf(constants.Links.Docs.Keybindings, versionStr)), fmt.Sprintf("Config Options: %s", fmt.Sprintf(constants.Links.Docs.Config, versionStr)), fmt.Sprintf("Tutorial: %s", constants.Links.Docs.Tutorial), fmt.Sprintf("Raise an Issue: %s", constants.Links.Issues), fmt.Sprintf("Release Notes: %s", constants.Links.Releases), style.FgMagenta.Sprintf("Become a sponsor: %s", constants.Links.Donate), // caffeine ain't free }, "\n\n") + "\n" self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.StatusTitle, Task: types.NewRenderStringTask(dashboardString), }, }) } func (self *StatusController) handleCheckForUpdate() error { return self.c.Helpers().Update.CheckForUpdateInForeground() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/worktree_options_controller.go
pkg/gui/controllers/worktree_options_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" ) // This controller is for all contexts that have items you can create a worktree from var _ types.IController = &WorktreeOptionsController{} type CanViewWorktreeOptions interface { types.IListContext } type WorktreeOptionsController struct { baseController *ListControllerTrait[string] c *ControllerCommon context CanViewWorktreeOptions } func NewWorktreeOptionsController(c *ControllerCommon, context CanViewWorktreeOptions) *WorktreeOptionsController { return &WorktreeOptionsController{ baseController: baseController{}, ListControllerTrait: NewListControllerTrait( c, context, context.GetSelectedItemId, context.GetSelectedItemIds, ), c: c, context: context, } } func (self *WorktreeOptionsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Worktrees.ViewWorktreeOptions), Handler: self.withItem(self.viewWorktreeOptions), Description: self.c.Tr.ViewWorktreeOptions, OpensMenu: true, }, } return bindings } func (self *WorktreeOptionsController) viewWorktreeOptions(ref string) error { return self.c.Helpers().Worktree.ViewWorktreeOptions(self.context, ref) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/quit_actions.go
pkg/gui/controllers/quit_actions.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type QuitActions struct { c *ControllerCommon } func (self *QuitActions) Quit() error { self.c.State().SetRetainOriginalDir(false) return self.quitAux() } func (self *QuitActions) QuitWithoutChangingDirectory() error { self.c.State().SetRetainOriginalDir(true) return self.quitAux() } func (self *QuitActions) quitAux() error { if self.c.State().GetUpdating() { return self.confirmQuitDuringUpdate() } return self.c.ConfirmIf(self.c.UserConfig().ConfirmOnQuit, types.ConfirmOpts{ Title: "", Prompt: self.c.Tr.ConfirmQuit, HandleConfirm: func() error { return gocui.ErrQuit }, }) } func (self *QuitActions) confirmQuitDuringUpdate() error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.ConfirmQuitDuringUpdateTitle, Prompt: self.c.Tr.ConfirmQuitDuringUpdate, HandleConfirm: func() error { return gocui.ErrQuit }, }) return nil } func (self *QuitActions) Escape() error { // If you make changes to this function, be sure to update EscapeEnabled and EscapeDescription accordingly. currentContext := self.c.Context().Current() if listContext, ok := currentContext.(types.IListContext); ok { if listContext.GetList().IsSelectingRange() { listContext.GetList().CancelRangeSelect() self.c.PostRefreshUpdate(listContext) return nil } } // Cancelling searching (as opposed to filtering) is handled by gocui if ctx, ok := currentContext.(types.IFilterableContext); ok { if ctx.IsFiltering() { self.c.Helpers().Search.Cancel() return nil } } parentContext := currentContext.GetParentContext() if parentContext != nil { // TODO: think about whether this should be marked as a return rather than adding to the stack self.c.Context().Push(parentContext, types.OnFocusOpts{}) return nil } for _, mode := range self.c.Helpers().Mode.Statuses() { if mode.IsActive() { return mode.Reset() } } repoPathStack := self.c.State().GetRepoPathStack() if !repoPathStack.IsEmpty() { return self.c.Helpers().Repos.DispatchSwitchToRepo(repoPathStack.Pop(), context.NO_CONTEXT) } if self.c.UserConfig().QuitOnTopLevelReturn { return self.Quit() } return nil } func (self *QuitActions) EscapeEnabled() bool { currentContext := self.c.Context().Current() if listContext, ok := currentContext.(types.IListContext); ok { if listContext.GetList().IsSelectingRange() { return true } } if ctx, ok := currentContext.(types.IFilterableContext); ok { if ctx.IsFiltering() { return true } } parentContext := currentContext.GetParentContext() if parentContext != nil { return true } for _, mode := range self.c.Helpers().Mode.Statuses() { if mode.IsActive() { return true } } repoPathStack := self.c.State().GetRepoPathStack() if !repoPathStack.IsEmpty() { return true } if self.c.UserConfig().QuitOnTopLevelReturn { return true } return false } func (self *QuitActions) EscapeDescription() string { currentContext := self.c.Context().Current() if listContext, ok := currentContext.(types.IListContext); ok { if listContext.GetList().IsSelectingRange() { return self.c.Tr.DismissRangeSelect } } if ctx, ok := currentContext.(types.IFilterableContext); ok { if ctx.IsFiltering() { return self.c.Tr.ExitFilterMode } } parentContext := currentContext.GetParentContext() if parentContext != nil { return self.c.Tr.ExitSubview } for _, mode := range self.c.Helpers().Mode.Statuses() { if mode.IsActive() { return mode.CancelLabel() } } repoPathStack := self.c.State().GetRepoPathStack() if !repoPathStack.IsEmpty() { return self.c.Tr.BackToParentRepo } if self.c.UserConfig().QuitOnTopLevelReturn { return self.c.Tr.Quit } return self.c.Tr.Cancel }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/local_commits_controller.go
pkg/gui/controllers/local_commits_controller.go
package controllers import ( "strings" "github.com/go-errors/errors" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/context/traits" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" "github.com/stefanhaller/git-todo-parser/todo" ) // after selecting the 200th commit, we'll load in all the rest const COMMIT_THRESHOLD = 200 type ( PullFilesFn func() error ) type LocalCommitsController struct { baseController *ListControllerTrait[*models.Commit] c *ControllerCommon pullFiles PullFilesFn } var _ types.IController = &LocalCommitsController{} func NewLocalCommitsController( c *ControllerCommon, pullFiles PullFilesFn, ) *LocalCommitsController { return &LocalCommitsController{ baseController: baseController{}, c: c, pullFiles: pullFiles, ListControllerTrait: NewListControllerTrait( c, c.Contexts().LocalCommits, c.Contexts().LocalCommits.GetSelected, c.Contexts().LocalCommits.GetSelectedItems, ), } } func (self *LocalCommitsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { editCommitKey := opts.Config.Universal.Edit bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Commits.SquashDown), Handler: opts.Guards.OutsideFilterMode(self.withItemsRange(self.squashDown)), GetDisabledReason: self.require( self.itemRangeSelected( self.midRebaseCommandEnabled, self.canSquashOrFixup, ), ), Description: self.c.Tr.Squash, Tooltip: self.c.Tr.SquashTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.MarkCommitAsFixup), Handler: opts.Guards.OutsideFilterMode(self.withItemsRange(self.fixup)), GetDisabledReason: self.require( self.itemRangeSelected( self.midRebaseCommandEnabled, self.canSquashOrFixup, ), ), Description: self.c.Tr.Fixup, Tooltip: self.c.Tr.FixupTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.RenameCommit), Handler: self.withItem(self.reword), GetDisabledReason: self.require( self.singleItemSelected(self.rewordEnabled), ), Description: self.c.Tr.Reword, Tooltip: self.c.Tr.CommitRewordTooltip, DisplayOnScreen: true, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.RenameCommitWithEditor), Handler: self.withItem(self.rewordEditor), GetDisabledReason: self.require( self.singleItemSelected(self.rewordEnabled), ), Description: self.c.Tr.RewordCommitEditor, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItemsRange(self.drop), GetDisabledReason: self.require( self.itemRangeSelected( self.canDropCommits, ), ), Description: self.c.Tr.DropCommit, Tooltip: self.c.Tr.DropCommitTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(editCommitKey), Handler: opts.Guards.OutsideFilterMode(self.withItemsRange(self.edit)), GetDisabledReason: self.require( self.itemRangeSelected(self.midRebaseCommandEnabled), ), Description: self.c.Tr.EditCommit, ShortDescription: self.c.Tr.Edit, Tooltip: self.c.Tr.EditCommitTooltip, DisplayOnScreen: true, }, { // The user-facing description here is 'Start interactive rebase' but internally // we're calling it 'quick-start interactive rebase' to differentiate it from // when you manually select the base commit. Key: opts.GetKey(opts.Config.Commits.StartInteractiveRebase), Handler: opts.Guards.OutsideFilterMode(self.quickStartInteractiveRebase), GetDisabledReason: self.require(self.notMidRebase(self.c.Tr.AlreadyRebasing), self.canFindCommitForQuickStart), Description: self.c.Tr.QuickStartInteractiveRebase, Tooltip: utils.ResolvePlaceholderString(self.c.Tr.QuickStartInteractiveRebaseTooltip, map[string]string{ "editKey": keybindings.Label(editCommitKey), }), }, { Key: opts.GetKey(opts.Config.Commits.PickCommit), Handler: opts.Guards.OutsideFilterMode(self.withItems(self.pick)), GetDisabledReason: self.require( self.itemRangeSelected(self.pickEnabled), ), Description: self.c.Tr.Pick, Tooltip: self.c.Tr.PickCommitTooltip, }, { Key: opts.GetKey(opts.Config.Commits.CreateFixupCommit), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.createFixupCommit)), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CreateFixupCommit, Tooltip: utils.ResolvePlaceholderString( self.c.Tr.CreateFixupCommitTooltip, map[string]string{ "squashAbove": keybindings.Label(opts.Config.Commits.SquashAboveCommits), }, ), }, { Key: opts.GetKey(opts.Config.Commits.SquashAboveCommits), Handler: opts.Guards.OutsideFilterMode(self.squashFixupCommits), GetDisabledReason: self.require( self.notMidRebase(self.c.Tr.AlreadyRebasing), ), Description: self.c.Tr.SquashAboveCommits, Tooltip: self.c.Tr.SquashAboveCommitsTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.MoveDownCommit), Handler: opts.Guards.OutsideFilterMode(self.withItemsRange(self.moveDown)), GetDisabledReason: self.require(self.itemRangeSelected( self.midRebaseMoveCommandEnabled, self.canMoveDown, )), Description: self.c.Tr.MoveDownCommit, }, { Key: opts.GetKey(opts.Config.Commits.MoveUpCommit), Handler: opts.Guards.OutsideFilterMode(self.withItemsRange(self.moveUp)), GetDisabledReason: self.require(self.itemRangeSelected( self.midRebaseMoveCommandEnabled, self.canMoveUp, )), Description: self.c.Tr.MoveUpCommit, }, { Key: opts.GetKey(opts.Config.Commits.PasteCommits), Handler: opts.Guards.OutsideFilterMode(self.paste), GetDisabledReason: self.require(self.canPaste), Description: self.c.Tr.PasteCommits, DisplayStyle: &style.FgCyan, }, { Key: opts.GetKey(opts.Config.Commits.MarkCommitAsBaseForRebase), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.markAsBaseCommit)), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.MarkAsBaseCommit, Tooltip: self.c.Tr.MarkAsBaseCommitTooltip, }, // overriding this navigation keybinding because we might need to load // more commits on demand { Key: opts.GetKey(opts.Config.Universal.StartSearch), Handler: self.openSearch, Description: self.c.Tr.StartSearch, Tag: "navigation", }, { Key: opts.GetKey(opts.Config.Commits.AmendToCommit), Handler: self.withItem(self.amendTo), GetDisabledReason: self.require(self.singleItemSelected(self.canAmend)), Description: self.c.Tr.Amend, Tooltip: self.c.Tr.AmendCommitTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Commits.ResetCommitAuthor), Handler: self.withItemsRange(self.amendAttribute), GetDisabledReason: self.require(self.itemRangeSelected(self.canAmendRange)), Description: self.c.Tr.AmendCommitAttribute, Tooltip: self.c.Tr.AmendCommitAttributeTooltip, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.RevertCommit), Handler: self.withItemsRange(self.revert), GetDisabledReason: self.require(self.itemRangeSelected()), Description: self.c.Tr.Revert, Tooltip: self.c.Tr.RevertCommitTooltip, }, { Key: opts.GetKey(opts.Config.Commits.CreateTag), Handler: self.withItem(self.createTag), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.TagCommit, Tooltip: self.c.Tr.TagCommitTooltip, }, { Key: opts.GetKey(opts.Config.Commits.OpenLogMenu), Handler: self.handleOpenLogMenu, Description: self.c.Tr.OpenLogMenu, Tooltip: self.c.Tr.OpenLogMenuTooltip, OpensMenu: true, }, } return bindings } func (self *LocalCommitsController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask commit := self.context().GetSelected() if commit == nil { task = types.NewRenderStringTask(self.c.Tr.NoCommitsThisBranch) } else if commit.Action == todo.UpdateRef { task = types.NewRenderStringTask( utils.ResolvePlaceholderString( self.c.Tr.UpdateRefHere, map[string]string{ "ref": strings.TrimPrefix(commit.Name, "refs/heads/"), })) } else if commit.Action == todo.Exec { task = types.NewRenderStringTask( self.c.Tr.ExecCommandHere + "\n\n" + commit.Name) } else { refRange := self.context().GetSelectedRefRangeForDiffFiles() task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff(commit, refRange) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: "Patch", SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Task: task, }, Secondary: secondaryPatchPanelUpdateOpts(self.c), }) }) } } func secondaryPatchPanelUpdateOpts(c *ControllerCommon) *types.ViewUpdateOpts { if c.Git().Patch.PatchBuilder.Active() { patch := c.Git().Patch.PatchBuilder.RenderAggregatedPatch(false) return &types.ViewUpdateOpts{ Task: types.NewRenderStringWithoutScrollTask(patch), Title: c.Tr.CustomPatch, } } return nil } func (self *LocalCommitsController) squashDown(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { return self.updateTodos(todo.Squash, selectedCommits) } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Squash, Prompt: self.c.Tr.SureSquashThisCommit, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.SquashingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SquashCommitDown) return self.interactiveRebase(todo.Squash, startIdx, endIdx) }) }, }) return nil } func (self *LocalCommitsController) fixup(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { return self.updateTodos(todo.Fixup, selectedCommits) } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Fixup, Prompt: self.c.Tr.SureFixupThisCommit, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.FixingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.FixupCommit) return self.interactiveRebase(todo.Fixup, startIdx, endIdx) }) }, }) return nil } func (self *LocalCommitsController) reword(commit *models.Commit) error { commitIdx := self.context().GetSelectedLineIdx() if self.c.Git().Config.NeedsGpgSubprocessForCommit() && !self.isHeadCommit(commitIdx) { return errors.New(self.c.Tr.DisabledForGPG) } commitMessage, err := self.c.Git().Commit.GetCommitMessage(commit.Hash()) if err != nil { return err } if self.c.UserConfig().Git.Commit.AutoWrapCommitMessage { commitMessage = helpers.TryRemoveHardLineBreaks(commitMessage, self.c.UserConfig().Git.Commit.AutoWrapWidth) } self.c.Helpers().Commits.OpenCommitMessagePanel( &helpers.OpenCommitMessagePanelOpts{ CommitIndex: commitIdx, InitialMessage: commitMessage, SummaryTitle: self.c.Tr.Actions.RewordCommit, DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: false, OnConfirm: self.handleReword, OnSwitchToEditor: self.switchFromCommitMessagePanelToEditor, }, ) return nil } func (self *LocalCommitsController) switchFromCommitMessagePanelToEditor(filepath string) error { if self.isSelectedHeadCommit() { return self.c.RunSubprocessAndRefresh( self.c.Git().Commit.RewordLastCommitInEditorWithMessageFileCmdObj(filepath)) } err := self.c.Git().Rebase.BeginInteractiveRebaseForCommit(self.c.Model().Commits, self.context().GetSelectedLineIdx(), false) if err != nil { return err } // now the selected commit should be our head so we'll amend it with the new message err = self.c.RunSubprocessAndRefresh( self.c.Git().Commit.RewordLastCommitInEditorWithMessageFileCmdObj(filepath)) if err != nil { return err } err = self.c.Git().Rebase.ContinueRebase() if err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil } func (self *LocalCommitsController) handleReword(summary string, description string) error { if models.IsHeadCommit(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx()) { // we've selected the top commit so no rebase is required return self.c.Helpers().GPG.WithGpgHandling(self.c.Git().Commit.RewordLastCommit(summary, description), git_commands.CommitGpgSign, self.c.Tr.RewordingStatus, nil, nil) } return self.c.WithWaitingStatus(self.c.Tr.RewordingStatus, func(gocui.Task) error { err := self.c.Git().Rebase.RewordCommit(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx(), summary, description) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } func (self *LocalCommitsController) doRewordEditor() error { self.c.LogAction(self.c.Tr.Actions.RewordCommit) if self.isSelectedHeadCommit() { return self.c.RunSubprocessAndRefresh(self.c.Git().Commit.RewordLastCommitInEditorCmdObj()) } subProcess, err := self.c.Git().Rebase.RewordCommitInEditor( self.c.Model().Commits, self.context().GetSelectedLineIdx(), ) if err != nil { return err } if subProcess != nil { return self.c.RunSubprocessAndRefresh(subProcess) } return nil } func (self *LocalCommitsController) rewordEditor(commit *models.Commit) error { return self.c.ConfirmIf(!self.c.UserConfig().Gui.SkipRewordInEditorWarning, types.ConfirmOpts{ Title: self.c.Tr.RewordInEditorTitle, Prompt: self.c.Tr.RewordInEditorPrompt, HandleConfirm: self.doRewordEditor, }) } func (self *LocalCommitsController) drop(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { groupedTodos := lo.GroupBy(selectedCommits, func(c *models.Commit) bool { return c.Action == todo.UpdateRef }) updateRefTodos := groupedTodos[true] nonUpdateRefTodos := groupedTodos[false] if len(updateRefTodos) > 0 { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.DropCommitTitle, Prompt: self.c.Tr.DropUpdateRefPrompt, HandleConfirm: func() error { selectedIdx, rangeStartIdx, rangeSelectMode := self.context().GetSelectionRangeAndMode() if err := self.c.Git().Rebase.DeleteUpdateRefTodos(updateRefTodos); err != nil { return err } if selectedIdx > rangeStartIdx { selectedIdx = max(selectedIdx-len(updateRefTodos), rangeStartIdx) } else { rangeStartIdx = max(rangeStartIdx-len(updateRefTodos), selectedIdx) } self.context().SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, rangeSelectMode) return self.updateTodos(todo.Drop, nonUpdateRefTodos) }, }) return nil } return self.updateTodos(todo.Drop, selectedCommits) } isMerge := selectedCommits[0].IsMerge() self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.DropCommitTitle, Prompt: lo.Ternary(isMerge, self.c.Tr.DropMergeCommitPrompt, self.c.Tr.DropCommitPrompt), HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.DroppingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DropCommit) if isMerge { return self.dropMergeCommit(startIdx) } return self.interactiveRebase(todo.Drop, startIdx, endIdx) }) }, }) return nil } func (self *LocalCommitsController) dropMergeCommit(commitIdx int) error { err := self.c.Git().Rebase.DropMergeCommit(self.c.Model().Commits, commitIdx) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) } func (self *LocalCommitsController) edit(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { return self.updateTodos(todo.Edit, selectedCommits) } commits := self.c.Model().Commits if !commits[endIdx].IsMerge() { selectionRangeAndMode := self.getSelectionRangeAndMode() err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, todo.Edit) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{ Mode: types.BLOCK_UI, Then: func() { self.restoreSelectionRangeAndMode(selectionRangeAndMode) }, }) } return self.startInteractiveRebaseWithEdit(selectedCommits) } func (self *LocalCommitsController) quickStartInteractiveRebase() error { commitToEdit, err := self.findCommitForQuickStartInteractiveRebase() if err != nil { return err } return self.startInteractiveRebaseWithEdit([]*models.Commit{commitToEdit}) } func (self *LocalCommitsController) startInteractiveRebaseWithEdit( commitsToEdit []*models.Commit, ) error { return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.EditCommit) selectionRangeAndMode := self.getSelectionRangeAndMode() err := self.c.Git().Rebase.EditRebase(commitsToEdit[len(commitsToEdit)-1].Hash()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{Mode: types.BLOCK_UI, Then: func() { todos := make([]*models.Commit, 0, len(commitsToEdit)-1) for _, c := range commitsToEdit[:len(commitsToEdit)-1] { // Merge commits can't be set to "edit", so just skip them if !c.IsMerge() { todos = append(todos, models.NewCommit(self.c.Model().HashPool, models.NewCommitOpts{Hash: c.Hash(), Action: todo.Pick})) } } if len(todos) > 0 { err := self.updateTodos(todo.Edit, todos) if err != nil { self.c.Log.Errorf("error when updating todos: %v", err) } } self.restoreSelectionRangeAndMode(selectionRangeAndMode) }}) }) } type SelectionRangeAndMode struct { selectedHash string rangeStartHash string mode traits.RangeSelectMode } func (self *LocalCommitsController) getSelectionRangeAndMode() SelectionRangeAndMode { selectedIdx, rangeStartIdx, rangeSelectMode := self.context().GetSelectionRangeAndMode() commits := self.c.Model().Commits selectedHash := commits[selectedIdx].Hash() rangeStartHash := commits[rangeStartIdx].Hash() return SelectionRangeAndMode{selectedHash, rangeStartHash, rangeSelectMode} } func (self *LocalCommitsController) restoreSelectionRangeAndMode(selectionRangeAndMode SelectionRangeAndMode) { // We need to select the same commit range again because after starting a rebase, // new lines can be added for update-ref commands in the TODO file, due to // stacked branches. So the selected commits may be in different positions in the list. _, newSelectedIdx, ok1 := lo.FindIndexOf(self.c.Model().Commits, func(c *models.Commit) bool { return c.Hash() == selectionRangeAndMode.selectedHash }) _, newRangeStartIdx, ok2 := lo.FindIndexOf(self.c.Model().Commits, func(c *models.Commit) bool { return c.Hash() == selectionRangeAndMode.rangeStartHash }) if ok1 && ok2 { self.context().SetSelectionRangeAndMode(newSelectedIdx, newRangeStartIdx, selectionRangeAndMode.mode) self.context().HandleFocus(types.OnFocusOpts{}) } } func (self *LocalCommitsController) findCommitForQuickStartInteractiveRebase() (*models.Commit, error) { commit, index, ok := lo.FindIndexOf(self.c.Model().Commits, func(c *models.Commit) bool { return c.IsMerge() || c.Status == models.StatusMerged }) if !ok || index == 0 { errorMsg := utils.ResolvePlaceholderString(self.c.Tr.CannotQuickStartInteractiveRebase, map[string]string{ "editKey": keybindings.Label(self.c.UserConfig().Keybinding.Universal.Edit), }) return nil, errors.New(errorMsg) } return commit, nil } func (self *LocalCommitsController) pick(selectedCommits []*models.Commit) error { if self.isRebasing() { return self.updateTodos(todo.Pick, selectedCommits) } panic("should be disabled when not rebasing") } func (self *LocalCommitsController) interactiveRebase(action todo.TodoCommand, startIdx int, endIdx int) error { // When performing an action that will remove the selected commits, we need to select the // next commit down (which will end up at the start index after the action is performed) if action == todo.Drop || action == todo.Fixup || action == todo.Squash { self.context().SetSelection(startIdx) } err := self.c.Git().Rebase.InteractiveRebase(self.c.Model().Commits, startIdx, endIdx, action) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) } // updateTodos sees if the selected commit is in fact a rebasing // commit meaning you are trying to edit the todo file rather than actually // begin a rebase. It then updates the todo file with that action func (self *LocalCommitsController) updateTodos(action todo.TodoCommand, selectedCommits []*models.Commit) error { if err := self.c.Git().Rebase.EditRebaseTodo(selectedCommits, action); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, }) return nil } func (self *LocalCommitsController) rewordEnabled(commit *models.Commit) *types.DisabledReason { // for now we do not support setting 'reword' on TODO commits because it requires an editor // and that means we either unconditionally wait around for the subprocess to ask for // our input or we set a lazygit client as the EDITOR env variable and have it // request us to edit the commit message when prompted. if commit.IsTODO() { return &types.DisabledReason{Text: self.c.Tr.RewordNotSupported} } // If we are in a rebase, the only action that is allowed for // non-todo commits is rewording the current head commit if self.isRebasing() && !self.isSelectedHeadCommit() { return &types.DisabledReason{Text: self.c.Tr.AlreadyRebasing} } return nil } func (self *LocalCommitsController) isRebasing() bool { return self.c.Model().WorkingTreeStateAtLastCommitRefresh.Any() } func (self *LocalCommitsController) isCherryPickingOrReverting() bool { return self.c.Model().WorkingTreeStateAtLastCommitRefresh.CherryPicking || self.c.Model().WorkingTreeStateAtLastCommitRefresh.Reverting } func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { if err := self.c.Git().Rebase.MoveTodosDown(selectedCommits); err != nil { return err } self.context().MoveSelection(1) self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, }) return nil } return self.c.WithWaitingStatusSync(self.c.Tr.MovingStatus, func() error { self.c.LogAction(self.c.Tr.Actions.MoveCommitDown) err := self.c.Git().Rebase.MoveCommitsDown(self.c.Model().Commits, startIdx, endIdx) if err == nil { self.context().MoveSelection(1) } return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{Mode: types.SYNC}) }) } func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, startIdx int, endIdx int) error { if self.isRebasing() { if err := self.c.Git().Rebase.MoveTodosUp(selectedCommits); err != nil { return err } self.context().MoveSelection(-1) self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, }) return nil } return self.c.WithWaitingStatusSync(self.c.Tr.MovingStatus, func() error { self.c.LogAction(self.c.Tr.Actions.MoveCommitUp) err := self.c.Git().Rebase.MoveCommitsUp(self.c.Model().Commits, startIdx, endIdx) if err == nil { self.context().MoveSelection(-1) } return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{Mode: types.SYNC}) }) } func (self *LocalCommitsController) amendTo(commit *models.Commit) error { var handleCommit func() error if self.isSelectedHeadCommit() { handleCommit = func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { if err := self.c.Helpers().AmendHelper.AmendHead(); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } } else { handleCommit = func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AmendCommit) err := self.c.Git().Rebase.AmendTo(self.c.Model().Commits, self.context().GetView().SelectedLineIdx()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) }) } } return self.c.ConfirmIf(!self.c.UserConfig().Gui.SkipAmendWarning, types.ConfirmOpts{ Title: self.c.Tr.AmendCommitTitle, Prompt: self.c.Tr.AmendCommitPrompt, HandleConfirm: handleCommit, }) } func (self *LocalCommitsController) canAmendRange(commits []*models.Commit, start, end int) *types.DisabledReason { if (start != end || !self.isHeadCommit(start)) && self.isRebasing() { return &types.DisabledReason{Text: self.c.Tr.AlreadyRebasing} } return nil } func (self *LocalCommitsController) canAmend(_ *models.Commit) *types.DisabledReason { idx := self.context().GetSelectedLineIdx() return self.canAmendRange(self.c.Model().Commits, idx, idx) } func (self *LocalCommitsController) amendAttribute(commits []*models.Commit, start, end int) error { opts := self.c.KeybindingsOpts() return self.c.Menu(types.CreateMenuOptions{ Title: "Amend commit attribute", Items: []*types.MenuItem{ { Label: self.c.Tr.ResetAuthor, OnPress: func() error { return self.resetAuthor(start, end) }, Key: opts.GetKey(opts.Config.AmendAttribute.ResetAuthor), Tooltip: self.c.Tr.ResetAuthorTooltip, }, { Label: self.c.Tr.SetAuthor, OnPress: func() error { return self.setAuthor(start, end) }, Key: opts.GetKey(opts.Config.AmendAttribute.SetAuthor), Tooltip: self.c.Tr.SetAuthorTooltip, }, { Label: self.c.Tr.AddCoAuthor, OnPress: func() error { return self.addCoAuthor(start, end) }, Key: opts.GetKey(opts.Config.AmendAttribute.AddCoAuthor), Tooltip: self.c.Tr.AddCoAuthorTooltip, }, }, }) } func (self *LocalCommitsController) resetAuthor(start, end int) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.ResetCommitAuthor) if err := self.c.Git().Rebase.ResetCommitAuthor(self.c.Model().Commits, start, end); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } func (self *LocalCommitsController) setAuthor(start, end int) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.SetAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SetCommitAuthor) if err := self.c.Git().Rebase.SetCommitAuthor(self.c.Model().Commits, start, end, value); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) }, }) return nil } func (self *LocalCommitsController) addCoAuthor(start, end int) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.AddCoAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddCommitCoAuthor) if err := self.c.Git().Rebase.AddCommitCoAuthor(self.c.Model().Commits, start, end, value); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }) }, }) return nil } func (self *LocalCommitsController) revert(commits []*models.Commit, start, end int) error { var promptText string if len(commits) == 1 { promptText = utils.ResolvePlaceholderString( self.c.Tr.ConfirmRevertCommit, map[string]string{ "selectedCommit": commits[0].ShortHash(), }) } else { promptText = self.c.Tr.ConfirmRevertCommitRange } hashes := lo.Map(commits, func(c *models.Commit, _ int) string { return c.Hash() }) isMerge := lo.SomeBy(commits, func(c *models.Commit) bool { return c.IsMerge() }) self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Actions.RevertCommit, Prompt: promptText, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.RevertCommit) return self.c.WithWaitingStatusSync(self.c.Tr.RevertingStatus, func() error { mustStash := helpers.IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) if mustStash { if err := self.c.Git().Stash.Push(self.c.Tr.AutoStashForReverting); err != nil { return err } } result := self.c.Git().Commit.Revert(hashes, isMerge) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.SYNC}); err != nil { return err } self.context().MoveSelection(len(commits)) self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) if mustStash { if err := self.c.Git().Stash.Pop(0); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.STASH, types.FILES}, }) } return nil }) }, }) return nil } func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) error { var disabledReasonWhenFilesAreNeeded *types.DisabledReason if len(self.c.Model().Files) == 0 { disabledReasonWhenFilesAreNeeded = &types.DisabledReason{ Text: self.c.Tr.NoFilesStagedTitle, ShowErrorInPanel: true, } } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.CreateFixupCommit, Items: []*types.MenuItem{ { Label: self.c.Tr.FixupMenu_Fixup, Key: 'f', OnPress: func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { self.c.LogAction(self.c.Tr.Actions.CreateFixupCommit) return self.c.WithWaitingStatusSync(self.c.Tr.CreatingFixupCommitStatus, func() error { if err := self.c.Git().Commit.CreateFixupCommit(commit.Hash()); err != nil { return err } if err := self.moveFixupCommitToOwnerStackedBranch(commit); err != nil { return err } self.context().MoveSelectedLine(1) self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) return nil }) }) }, DisabledReason: disabledReasonWhenFilesAreNeeded, Tooltip: self.c.Tr.FixupMenu_FixupTooltip, }, { Label: self.c.Tr.FixupMenu_AmendWithChanges, Key: 'a', OnPress: func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { return self.createAmendCommit(commit, true) }) }, DisabledReason: disabledReasonWhenFilesAreNeeded, Tooltip: self.c.Tr.FixupMenu_AmendWithChangesTooltip, }, { Label: self.c.Tr.FixupMenu_AmendWithoutChanges, Key: 'r', OnPress: func() error { return self.createAmendCommit(commit, false) }, Tooltip: self.c.Tr.FixupMenu_AmendWithoutChangesTooltip, }, }, }) } func (self *LocalCommitsController) moveFixupCommitToOwnerStackedBranch(targetCommit *models.Commit) error { if self.c.Git().Version.IsOlderThan(2, 38, 0) { // Git 2.38.0 introduced the `rebase.updateRefs` config option. Don't // move the commit down with older versions, as it would break the stack. return nil } if self.c.Git().Status.WorkingTreeState().Any() { // Can't move commits while rebasing return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/side_window_controller.go
pkg/gui/controllers/side_window_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type SideWindowControllerFactory struct { c *ControllerCommon } func NewSideWindowControllerFactory(c *ControllerCommon) *SideWindowControllerFactory { return &SideWindowControllerFactory{c: c} } func (self *SideWindowControllerFactory) Create(context types.Context) types.IController { return NewSideWindowController(self.c, context) } type SideWindowController struct { baseController c *ControllerCommon context types.Context } func NewSideWindowController( c *ControllerCommon, context types.Context, ) *SideWindowController { return &SideWindowController{ baseController: baseController{}, c: c, context: context, } } func (self *SideWindowController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ {Key: opts.GetKey(opts.Config.Universal.PrevBlock), Modifier: gocui.ModNone, Handler: self.previousSideWindow}, {Key: opts.GetKey(opts.Config.Universal.NextBlock), Modifier: gocui.ModNone, Handler: self.nextSideWindow}, {Key: opts.GetKey(opts.Config.Universal.PrevBlockAlt), Modifier: gocui.ModNone, Handler: self.previousSideWindow}, {Key: opts.GetKey(opts.Config.Universal.NextBlockAlt), Modifier: gocui.ModNone, Handler: self.nextSideWindow}, {Key: opts.GetKey(opts.Config.Universal.PrevBlockAlt2), Modifier: gocui.ModNone, Handler: self.previousSideWindow}, {Key: opts.GetKey(opts.Config.Universal.NextBlockAlt2), Modifier: gocui.ModNone, Handler: self.nextSideWindow}, } } func (self *SideWindowController) Context() types.Context { return nil } func (self *SideWindowController) previousSideWindow() error { windows := self.c.Helpers().Window.SideWindows() currentWindow := self.c.Helpers().Window.CurrentWindow() var newWindow string if currentWindow == "" || currentWindow == windows[0] { newWindow = windows[len(windows)-1] } else { for i := range windows { if currentWindow == windows[i] { newWindow = windows[i-1] break } if i == len(windows)-1 { return nil } } } context := self.c.Helpers().Window.GetContextForWindow(newWindow) self.c.Context().Push(context, types.OnFocusOpts{}) return nil } func (self *SideWindowController) nextSideWindow() error { windows := self.c.Helpers().Window.SideWindows() currentWindow := self.c.Helpers().Window.CurrentWindow() var newWindow string if currentWindow == "" || currentWindow == windows[len(windows)-1] { newWindow = windows[0] } else { for i := range windows { if currentWindow == windows[i] { newWindow = windows[i+1] break } if i == len(windows)-1 { return nil } } } context := self.c.Helpers().Window.GetContextForWindow(newWindow) self.c.Context().Push(context, types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/vertical_scroll_controller.go
pkg/gui/controllers/vertical_scroll_controller.go
package controllers import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // given we have no fields here, arguably we shouldn't even need this factory // struct, but we're maintaining consistency with the other files. type VerticalScrollControllerFactory struct { c *ControllerCommon } func NewVerticalScrollControllerFactory(c *ControllerCommon) *VerticalScrollControllerFactory { return &VerticalScrollControllerFactory{ c: c, } } func (self *VerticalScrollControllerFactory) Create(context types.Context) types.IController { return &VerticalScrollController{ baseController: baseController{}, c: self.c, context: context, } } type VerticalScrollController struct { baseController c *ControllerCommon context types.Context } func (self *VerticalScrollController) Context() types.Context { return self.context } func (self *VerticalScrollController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{} } func (self *VerticalScrollController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { ViewName: self.context.GetViewName(), Key: gocui.MouseWheelUp, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollUp() }, }, { ViewName: self.context.GetViewName(), Key: gocui.MouseWheelDown, Handler: func(gocui.ViewMouseBindingOpts) error { return self.HandleScrollDown() }, }, } } func (self *VerticalScrollController) HandleScrollUp() error { self.context.GetViewTrait().ScrollUp(self.c.UserConfig().Gui.ScrollHeight) return nil } func (self *VerticalScrollController) HandleScrollDown() error { scrollHeight := self.c.UserConfig().Gui.ScrollHeight self.context.GetViewTrait().ScrollDown(scrollHeight) if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { manager.ReadLines(scrollHeight) } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/confirmation_controller.go
pkg/gui/controllers/confirmation_controller.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type ConfirmationController struct { baseController c *ControllerCommon } var _ types.IController = &ConfirmationController{} func NewConfirmationController( c *ControllerCommon, ) *ConfirmationController { return &ConfirmationController{ baseController: baseController{}, c: c, } } func (self *ConfirmationController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Confirm), Handler: func() error { return self.context().State.OnConfirm() }, Description: self.c.Tr.Confirm, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.Return), Handler: func() error { return self.context().State.OnClose() }, Description: self.c.Tr.CloseCancel, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: self.handleCopyToClipboard, Description: self.c.Tr.CopyToClipboardMenu, DisplayOnScreen: true, }, } return bindings } func (self *ConfirmationController) GetOnFocusLost() func(types.OnFocusLostOpts) { return func(types.OnFocusLostOpts) { self.c.Helpers().Confirmation.DeactivateConfirmation() } } func (self *ConfirmationController) Context() types.Context { return self.context() } func (self *ConfirmationController) context() *context.ConfirmationContext { return self.c.Contexts().Confirmation } func (self *ConfirmationController) handleCopyToClipboard() error { confirmationView := self.c.Views().Confirmation text := confirmationView.Buffer() if err := self.c.OS().CopyToClipboard(text); err != nil { return err } self.c.Toast(self.c.Tr.MessageCopiedToClipboard) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/diffing_menu_action.go
pkg/gui/controllers/diffing_menu_action.go
package controllers import ( "fmt" "github.com/jesseduffield/lazygit/pkg/gui/modes/diffing" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type DiffingMenuAction struct { c *ControllerCommon } func (self *DiffingMenuAction) Call() error { names := self.c.Helpers().Diff.CurrentDiffTerminals() menuItems := []*types.MenuItem{} for _, name := range names { menuItems = append(menuItems, []*types.MenuItem{ { Label: fmt.Sprintf("%s %s", self.c.Tr.Diff, name), OnPress: func() error { self.c.Modes().Diffing.Ref = name // can scope this down based on current view but too lazy right now self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }, }...) } menuItems = append(menuItems, []*types.MenuItem{ { Label: self.c.Tr.EnterRefToDiff, OnPress: func() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.EnterRefName, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRefsSuggestionsFunc(), HandleConfirm: func(response string) error { self.c.Modes().Diffing.Ref = response self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }) return nil }, }, }...) if self.c.Modes().Diffing.Active() { menuItems = append(menuItems, []*types.MenuItem{ { Label: self.c.Tr.SwapDiff, OnPress: func() error { self.c.Modes().Diffing.Reverse = !self.c.Modes().Diffing.Reverse self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }, { Label: self.c.Tr.ExitDiffMode, OnPress: func() error { self.c.Modes().Diffing = diffing.New() self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }, }...) } return self.c.Menu(types.CreateMenuOptions{Title: self.c.Tr.DiffingMenuTitle, Items: menuItems}) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/common.go
pkg/gui/controllers/common.go
package controllers import ( "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" ) type ControllerCommon struct { *helpers.HelperCommon IGetHelpers } type IGetHelpers interface { Helpers() *helpers.Helpers } func NewControllerCommon( c *helpers.HelperCommon, IGetHelpers IGetHelpers, ) *ControllerCommon { return &ControllerCommon{ HelperCommon: c, IGetHelpers: IGetHelpers, } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/branches_controller.go
pkg/gui/controllers/branches_controller.go
package controllers import ( "errors" "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type BranchesController struct { baseController *ListControllerTrait[*models.Branch] c *ControllerCommon } var _ types.IController = &BranchesController{} func NewBranchesController( c *ControllerCommon, ) *BranchesController { return &BranchesController{ baseController: baseController{}, c: c, ListControllerTrait: NewListControllerTrait( c, c.Contexts().Branches, c.Contexts().Branches.GetSelected, c.Contexts().Branches.GetSelectedItems, ), } } func (self *BranchesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { return []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.Select), Handler: self.withItem(self.press), GetDisabledReason: self.require( self.singleItemSelected(), self.notPulling, ), Description: self.c.Tr.Checkout, Tooltip: self.c.Tr.CheckoutTooltip, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.New), Handler: self.withItem(self.newBranch), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.NewBranch, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.MoveCommitsToNewBranch), Handler: self.c.Helpers().Refs.MoveCommitsToNewBranch, GetDisabledReason: self.c.Helpers().Refs.CanMoveCommitsToNewBranch, Description: self.c.Tr.MoveCommitsToNewBranch, Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, { Key: opts.GetKey(opts.Config.Branches.CreatePullRequest), Handler: self.withItem(self.handleCreatePullRequest), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CreatePullRequest, }, { Key: opts.GetKey(opts.Config.Branches.ViewPullRequestOptions), Handler: self.withItem(self.handleCreatePullRequestMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CreatePullRequestOptions, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Branches.CopyPullRequestURL), Handler: self.copyPullRequestURL, GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.CopyPullRequestURL, }, { Key: opts.GetKey(opts.Config.Branches.CheckoutBranchByName), Handler: self.checkoutByName, Description: self.c.Tr.CheckoutByName, Tooltip: self.c.Tr.CheckoutByNameTooltip, }, { Key: opts.GetKey(opts.Config.Branches.CheckoutPreviousBranch), Handler: self.checkoutPreviousBranch, Description: self.c.Tr.CheckoutPreviousBranch, }, { Key: opts.GetKey(opts.Config.Branches.ForceCheckoutBranch), Handler: self.forceCheckout, GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ForceCheckout, Tooltip: self.c.Tr.ForceCheckoutTooltip, }, { Key: opts.GetKey(opts.Config.Universal.Remove), Handler: self.withItems(self.delete), GetDisabledReason: self.require(self.itemRangeSelected(self.branchesAreReal)), Description: self.c.Tr.Delete, Tooltip: self.c.Tr.BranchDeleteTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.RebaseBranch), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.rebase)), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.RebaseBranch, Tooltip: self.c.Tr.RebaseBranchTooltip, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.MergeIntoCurrentBranch), Handler: opts.Guards.OutsideFilterMode(self.merge), GetDisabledReason: self.require(self.singleItemSelected(self.notMergingIntoYourself)), Description: self.c.Tr.Merge, Tooltip: self.c.Tr.MergeBranchTooltip, DisplayOnScreen: true, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Branches.FastForward), Handler: self.withItem(self.fastForward), GetDisabledReason: self.require(self.singleItemSelected(self.branchIsReal)), Description: self.c.Tr.FastForward, Tooltip: self.c.Tr.FastForwardTooltip, }, { Key: opts.GetKey(opts.Config.Branches.CreateTag), Handler: self.withItem(self.createTag), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.NewTag, }, { Key: opts.GetKey(opts.Config.Branches.SortOrder), Handler: self.createSortMenu, Description: self.c.Tr.SortOrder, OpensMenu: true, }, { Key: opts.GetKey(opts.Config.Commits.ViewResetOptions), Handler: self.withItem(self.createResetMenu), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ViewResetOptions, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Branches.RenameBranch), Handler: self.withItem(self.rename), GetDisabledReason: self.require(self.singleItemSelected(self.branchIsReal)), Description: self.c.Tr.RenameBranch, }, { Key: opts.GetKey(opts.Config.Branches.SetUpstream), Handler: self.withItem(self.viewUpstreamOptions), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.ViewBranchUpstreamOptions, Tooltip: self.c.Tr.ViewBranchUpstreamOptionsTooltip, ShortDescription: self.c.Tr.Upstream, OpensMenu: true, DisplayOnScreen: true, }, { Key: opts.GetKey(opts.Config.Universal.OpenDiffTool), Handler: self.withItem(func(selectedBranch *models.Branch) error { return self.c.Helpers().Diff.OpenDiffToolForRef(selectedBranch) }), GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.OpenDiffTool, }, } } func (self *BranchesController) GetOnRenderToMain() func() { return func() { self.c.Helpers().Diff.WithDiffModeCheck(func() { var task types.UpdateTask branch := self.context().GetSelected() if branch == nil { task = types.NewRenderStringTask(self.c.Tr.NoBranchesThisRepo) } else { cmdObj := self.c.Git().Branch.GetGraphCmdObj(branch.FullRefName()) task = types.NewRunPtyTask(cmdObj.GetCmd()) } self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, Main: &types.ViewUpdateOpts{ Title: self.c.Tr.LogTitle, Task: task, }, }) }) } } func (self *BranchesController) viewUpstreamOptions(selectedBranch *models.Branch) error { upstream := lo.Ternary(selectedBranch.RemoteBranchStoredLocally(), selectedBranch.ShortUpstreamRefName(), self.c.Tr.UpstreamGenericName) viewDivergenceItem := &types.MenuItem{ LabelColumns: []string{self.c.Tr.ViewDivergenceFromUpstream}, OnPress: func() error { branch := self.context().GetSelected() if branch == nil { return nil } return self.c.Helpers().SubCommits.ViewSubCommits(helpers.ViewSubCommitsOpts{ Ref: branch, TitleRef: fmt.Sprintf("%s <-> %s", branch.RefName(), upstream), RefToShowDivergenceFrom: branch.FullUpstreamRefName(), Context: self.context(), ShowBranchHeads: false, }) }, } var disabledReason *types.DisabledReason baseBranch, err := self.c.Git().Loaders.BranchLoader.GetBaseBranch(selectedBranch, self.c.Model().MainBranches) if err != nil { return err } if baseBranch == "" { baseBranch = self.c.Tr.CouldNotDetermineBaseBranch disabledReason = &types.DisabledReason{Text: self.c.Tr.CouldNotDetermineBaseBranch} } shortBaseBranchName := helpers.ShortBranchName(baseBranch) label := utils.ResolvePlaceholderString( self.c.Tr.ViewDivergenceFromBaseBranch, map[string]string{"baseBranch": shortBaseBranchName}, ) viewDivergenceFromBaseBranchItem := &types.MenuItem{ LabelColumns: []string{label}, Key: 'b', OnPress: func() error { branch := self.context().GetSelected() if branch == nil { return nil } return self.c.Helpers().SubCommits.ViewSubCommits(helpers.ViewSubCommitsOpts{ Ref: branch, TitleRef: fmt.Sprintf("%s <-> %s", branch.RefName(), shortBaseBranchName), RefToShowDivergenceFrom: baseBranch, Context: self.context(), ShowBranchHeads: false, }) }, DisabledReason: disabledReason, } unsetUpstreamItem := &types.MenuItem{ LabelColumns: []string{self.c.Tr.UnsetUpstream}, OnPress: func() error { if err := self.c.Git().Branch.UnsetUpstream(selectedBranch.Name); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{ types.BRANCHES, types.COMMITS, }, }) return nil }, Key: 'u', } setUpstreamItem := &types.MenuItem{ LabelColumns: []string{self.c.Tr.SetUpstream}, OnPress: func() error { return self.c.Helpers().Upstream.PromptForUpstreamWithoutInitialContent(selectedBranch, func(upstream string) error { upstreamRemote, upstreamBranch, err := self.c.Helpers().Upstream.ParseUpstream(upstream) if err != nil { return err } if err := self.c.Git().Branch.SetUpstream(upstreamRemote, upstreamBranch, selectedBranch.Name); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{ types.BRANCHES, types.COMMITS, }, }) return nil }) }, Key: 's', } upstreamResetOptions := utils.ResolvePlaceholderString( self.c.Tr.ViewUpstreamResetOptions, map[string]string{"upstream": upstream}, ) upstreamResetTooltip := utils.ResolvePlaceholderString( self.c.Tr.ViewUpstreamResetOptionsTooltip, map[string]string{"upstream": upstream}, ) upstreamRebaseOptions := utils.ResolvePlaceholderString( self.c.Tr.ViewUpstreamRebaseOptions, map[string]string{"upstream": upstream}, ) upstreamRebaseTooltip := utils.ResolvePlaceholderString( self.c.Tr.ViewUpstreamRebaseOptionsTooltip, map[string]string{"upstream": upstream}, ) upstreamResetItem := &types.MenuItem{ LabelColumns: []string{upstreamResetOptions}, OpensMenu: true, OnPress: func() error { // We only can invoke this when the remote branch is stored locally, so using the selectedBranch here is fine. err := self.c.Helpers().Refs.CreateGitResetMenu(upstream, selectedBranch.FullUpstreamRefName()) if err != nil { return err } return nil }, Tooltip: upstreamResetTooltip, Key: 'g', } upstreamRebaseItem := &types.MenuItem{ LabelColumns: []string{upstreamRebaseOptions}, OpensMenu: true, OnPress: func() error { if err := self.c.Helpers().MergeAndRebase.RebaseOntoRef(upstream); err != nil { return err } return nil }, Tooltip: upstreamRebaseTooltip, Key: 'r', } if !selectedBranch.IsTrackingRemote() { unsetUpstreamItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.UpstreamNotSetError} } if !selectedBranch.RemoteBranchStoredLocally() { viewDivergenceItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.UpstreamNotSetError} upstreamResetItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.UpstreamNotSetError} upstreamRebaseItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.UpstreamNotSetError} } options := []*types.MenuItem{ viewDivergenceItem, viewDivergenceFromBaseBranchItem, unsetUpstreamItem, setUpstreamItem, upstreamResetItem, upstreamRebaseItem, } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.BranchUpstreamOptionsTitle, Items: options, }) } func (self *BranchesController) Context() types.Context { return self.context() } func (self *BranchesController) context() *context.BranchesContext { return self.c.Contexts().Branches } func (self *BranchesController) press(selectedBranch *models.Branch) error { if selectedBranch == self.c.Helpers().Refs.GetCheckedOutRef() { return errors.New(self.c.Tr.AlreadyCheckedOutBranch) } worktreeForRef, ok := self.worktreeForBranch(selectedBranch) if ok && !worktreeForRef.IsCurrent { return self.promptToCheckoutWorktree(worktreeForRef) } self.c.LogAction(self.c.Tr.Actions.CheckoutBranch) return self.c.Helpers().Refs.CheckoutRef(selectedBranch.Name, types.CheckoutRefOptions{}) } func (self *BranchesController) notPulling() *types.DisabledReason { currentBranch := self.c.Helpers().Refs.GetCheckedOutRef() if currentBranch != nil { op := self.c.State().GetItemOperation(currentBranch) if op == types.ItemOperationFastForwarding || op == types.ItemOperationPulling { return &types.DisabledReason{Text: self.c.Tr.CantCheckoutBranchWhilePulling} } } return nil } func (self *BranchesController) worktreeForBranch(branch *models.Branch) (*models.Worktree, bool) { return git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees) } func (self *BranchesController) promptToCheckoutWorktree(worktree *models.Worktree) error { prompt := utils.ResolvePlaceholderString(self.c.Tr.AlreadyCheckedOutByWorktree, map[string]string{ "worktreeName": worktree.Name, }) return self.c.ConfirmIf(!self.c.UserConfig().Gui.SkipSwitchWorktreeOnCheckoutWarning, types.ConfirmOpts{ Title: self.c.Tr.SwitchToWorktree, Prompt: prompt, HandleConfirm: func() error { return self.c.Helpers().Worktree.Switch(worktree, context.LOCAL_BRANCHES_CONTEXT_KEY) }, }) } func (self *BranchesController) handleCreatePullRequest(selectedBranch *models.Branch) error { if !selectedBranch.IsTrackingRemote() { return errors.New(self.c.Tr.PullRequestNoUpstream) } return self.createPullRequest(selectedBranch.UpstreamBranch, "") } func (self *BranchesController) handleCreatePullRequestMenu(selectedBranch *models.Branch) error { checkedOutBranch := self.c.Helpers().Refs.GetCheckedOutRef() return self.createPullRequestMenu(selectedBranch, checkedOutBranch) } func (self *BranchesController) copyPullRequestURL() error { branch := self.context().GetSelected() branchExistsOnRemote := self.c.Git().Remote.CheckRemoteBranchExists(branch.Name) if !branchExistsOnRemote { return errors.New(self.c.Tr.NoBranchOnRemote) } url, err := self.c.Helpers().Host.GetPullRequestURL(branch.Name, "") if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.CopyPullRequestURL) if err := self.c.OS().CopyToClipboard(url); err != nil { return err } self.c.Toast(self.c.Tr.PullRequestURLCopiedToClipboard) return nil } func (self *BranchesController) forceCheckout() error { branch := self.context().GetSelected() message := self.c.Tr.SureForceCheckout title := self.c.Tr.ForceCheckoutBranch self.c.Confirm(types.ConfirmOpts{ Title: title, Prompt: message, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.ForceCheckoutBranch) if err := self.c.Git().Branch.Checkout(branch.Name, git_commands.CheckoutOptions{Force: true}); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil }, }) return nil } func (self *BranchesController) checkoutPreviousBranch() error { self.c.LogAction(self.c.Tr.Actions.CheckoutBranch) return self.c.Helpers().Refs.CheckoutPreviousRef() } func (self *BranchesController) checkoutByName() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.BranchName + ":", FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRefsSuggestionsFunc(), HandleConfirm: func(response string) error { self.c.LogAction("Checkout branch") _, branchName, found := self.c.Helpers().Refs.ParseRemoteBranchName(response) if found { return self.c.Helpers().Refs.CheckoutRemoteBranch(response, branchName) } return self.c.Helpers().Refs.CheckoutRef(response, types.CheckoutRefOptions{ OnRefNotFound: func(ref string) error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.BranchNotFoundTitle, Prompt: fmt.Sprintf("%s %s%s", self.c.Tr.BranchNotFoundPrompt, ref, "?"), HandleConfirm: func() error { return self.createNewBranchWithName(ref) }, }) return nil }, }) }, }, ) return nil } func (self *BranchesController) createNewBranchWithName(newBranchName string) error { branch := self.context().GetSelected() if branch == nil { return nil } if err := self.c.Git().Branch.New(newBranchName, branch.FullRefName()); err != nil { return err } self.c.Helpers().Refs.SelectFirstBranchAndFirstCommit() self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, KeepBranchSelectionIndex: true}) return nil } func (self *BranchesController) localDelete(branches []*models.Branch) error { return self.c.Helpers().BranchesHelper.ConfirmLocalDelete(branches) } func (self *BranchesController) remoteDelete(branches []*models.Branch) error { remoteBranches := lo.Map(branches, func(branch *models.Branch, _ int) *models.RemoteBranch { return &models.RemoteBranch{Name: branch.UpstreamBranch, RemoteName: branch.UpstreamRemote} }) return self.c.Helpers().BranchesHelper.ConfirmDeleteRemote(remoteBranches, false) } func (self *BranchesController) localAndRemoteDelete(branches []*models.Branch) error { return self.c.Helpers().BranchesHelper.ConfirmLocalAndRemoteDelete(branches) } func (self *BranchesController) delete(branches []*models.Branch) error { checkedOutBranch := self.c.Helpers().Refs.GetCheckedOutRef() isBranchCheckedOut := lo.SomeBy(branches, func(branch *models.Branch) bool { return checkedOutBranch.Name == branch.Name }) hasUpstream := lo.EveryBy(branches, func(branch *models.Branch) bool { return branch.IsTrackingRemote() && !branch.UpstreamGone }) localDeleteItem := &types.MenuItem{ Label: lo.Ternary(len(branches) > 1, self.c.Tr.DeleteLocalBranches, self.c.Tr.DeleteLocalBranch), Key: 'c', OnPress: func() error { return self.localDelete(branches) }, } if isBranchCheckedOut { localDeleteItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.CantDeleteCheckOutBranch} } remoteDeleteItem := &types.MenuItem{ Label: lo.Ternary(len(branches) > 1, self.c.Tr.DeleteRemoteBranches, self.c.Tr.DeleteRemoteBranch), Key: 'r', OnPress: func() error { return self.remoteDelete(branches) }, } if !hasUpstream { remoteDeleteItem.DisabledReason = &types.DisabledReason{ Text: lo.Ternary(len(branches) > 1, self.c.Tr.UpstreamsNotSetError, self.c.Tr.UpstreamNotSetError), } } deleteBothItem := &types.MenuItem{ Label: lo.Ternary(len(branches) > 1, self.c.Tr.DeleteLocalAndRemoteBranches, self.c.Tr.DeleteLocalAndRemoteBranch), Key: 'b', OnPress: func() error { return self.localAndRemoteDelete(branches) }, } if isBranchCheckedOut { deleteBothItem.DisabledReason = &types.DisabledReason{Text: self.c.Tr.CantDeleteCheckOutBranch} } else if !hasUpstream { deleteBothItem.DisabledReason = &types.DisabledReason{ Text: lo.Ternary(len(branches) > 1, self.c.Tr.UpstreamsNotSetError, self.c.Tr.UpstreamNotSetError), } } var menuTitle string if len(branches) == 1 { menuTitle = utils.ResolvePlaceholderString( self.c.Tr.DeleteBranchTitle, map[string]string{ "selectedBranchName": branches[0].Name, }, ) } else { menuTitle = self.c.Tr.DeleteBranchesTitle } return self.c.Menu(types.CreateMenuOptions{ Title: menuTitle, Items: []*types.MenuItem{localDeleteItem, remoteDeleteItem, deleteBothItem}, }) } func (self *BranchesController) merge() error { selectedBranchName := self.context().GetSelected().Name return self.c.Helpers().MergeAndRebase.MergeRefIntoCheckedOutBranch(selectedBranchName) } func (self *BranchesController) rebase(branch *models.Branch) error { return self.c.Helpers().MergeAndRebase.RebaseOntoRef(branch.Name) } func (self *BranchesController) fastForward(branch *models.Branch) error { if !branch.IsTrackingRemote() { return errors.New(self.c.Tr.FwdNoUpstream) } if !branch.RemoteBranchStoredLocally() { return errors.New(self.c.Tr.FwdNoLocalUpstream) } if branch.IsAheadForPull() { return errors.New(self.c.Tr.FwdCommitsToPush) } action := self.c.Tr.Actions.FastForwardBranch return self.c.WithInlineStatus(branch, types.ItemOperationFastForwarding, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error { worktree, ok := self.worktreeForBranch(branch) if ok { self.c.LogAction(action) worktreeGitDir := "" worktreePath := "" // if it is the current worktree path, no need to specify the path if !worktree.IsCurrent { worktreeGitDir = worktree.GitDir worktreePath = worktree.Path } err := self.c.Git().Sync.Pull( task, git_commands.PullOptions{ RemoteName: branch.UpstreamRemote, BranchName: branch.UpstreamBranch, FastForwardOnly: true, WorktreeGitDir: worktreeGitDir, WorktreePath: worktreePath, }, ) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return err } self.c.LogAction(action) err := self.c.Git().Sync.FastForward( task, branch.Name, branch.UpstreamRemote, branch.UpstreamBranch, ) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return err }) } func (self *BranchesController) createTag(branch *models.Branch) error { return self.c.Helpers().Tags.OpenCreateTagPrompt(branch.FullRefName(), func() {}) } func (self *BranchesController) createSortMenu() error { return self.c.Helpers().Refs.CreateSortOrderMenu( []string{"recency", "alphabetical", "date"}, self.c.Tr.SortOrderPromptLocalBranches, func(sortOrder string) error { if self.c.UserConfig().Git.LocalBranchSortOrder != sortOrder { self.c.UserConfig().Git.LocalBranchSortOrder = sortOrder self.c.Contexts().Branches.SetSelection(0) self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return nil } return nil }, self.c.UserConfig().Git.LocalBranchSortOrder) } func (self *BranchesController) createResetMenu(selectedBranch *models.Branch) error { return self.c.Helpers().Refs.CreateGitResetMenu(selectedBranch.Name, selectedBranch.FullRefName()) } func (self *BranchesController) rename(branch *models.Branch) error { promptForNewName := func() error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewBranchNamePrompt + " " + branch.Name + ":", InitialContent: branch.Name, HandleConfirm: func(newBranchName string) error { self.c.LogAction(self.c.Tr.Actions.RenameBranch) if err := self.c.Git().Branch.Rename(branch.Name, helpers.SanitizedBranchName(newBranchName)); err != nil { return err } // need to find where the branch is now so that we can re-select it. That means we need to refetch the branches synchronously and then find our branch self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES, types.WORKTREES}, }) // now that we've got our stuff again we need to find that branch and reselect it. for i, newBranch := range self.c.Model().Branches { if newBranch.Name == newBranchName { self.context().SetSelection(i) self.context().HandleRender() } } return nil }, }) return nil } // I could do an explicit check here for whether the branch is tracking a remote branch // but if we've selected it we'll already know that via Pullables and Pullables. // Bit of a hack but I'm lazy. return self.c.ConfirmIf(branch.IsTrackingRemote(), types.ConfirmOpts{ Title: self.c.Tr.RenameBranch, Prompt: self.c.Tr.RenameBranchWarning, HandleConfirm: promptForNewName, }) } func (self *BranchesController) newBranch(selectedBranch *models.Branch) error { return self.c.Helpers().Refs.NewBranch(selectedBranch.FullRefName(), selectedBranch.RefName(), "") } func (self *BranchesController) createPullRequestMenu(selectedBranch *models.Branch, checkedOutBranch *models.Branch) error { menuItems := make([]*types.MenuItem, 0, 4) fromToLabelColumns := func(from string, to string) []string { return []string{fmt.Sprintf("%s โ†’ %s", from, to)} } menuItemsForBranch := func(branch *models.Branch) []*types.MenuItem { return []*types.MenuItem{ { LabelColumns: fromToLabelColumns(branch.Name, self.c.Tr.DefaultBranch), OnPress: func() error { return self.handleCreatePullRequest(branch) }, }, { LabelColumns: fromToLabelColumns(branch.Name, self.c.Tr.SelectBranch), OnPress: func() error { if !branch.IsTrackingRemote() { return errors.New(self.c.Tr.PullRequestNoUpstream) } if len(self.c.Model().Remotes) == 1 { toRemote := self.c.Model().Remotes[0].Name self.c.Log.Debugf("PR will target the only existing remote '%s'", toRemote) return self.promptForTargetBranchNameAndCreatePullRequest(branch, toRemote) } self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.SelectTargetRemote, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(), HandleConfirm: func(toRemote string) error { self.c.Log.Debugf("PR will target remote '%s'", toRemote) return self.promptForTargetBranchNameAndCreatePullRequest(branch, toRemote) }, }) return nil }, }, } } if selectedBranch != checkedOutBranch { menuItems = append(menuItems, &types.MenuItem{ LabelColumns: fromToLabelColumns(checkedOutBranch.Name, selectedBranch.Name), OnPress: func() error { if !checkedOutBranch.IsTrackingRemote() || !selectedBranch.IsTrackingRemote() { return errors.New(self.c.Tr.PullRequestNoUpstream) } return self.createPullRequest(checkedOutBranch.UpstreamBranch, selectedBranch.UpstreamBranch) }, }, ) menuItems = append(menuItems, menuItemsForBranch(checkedOutBranch)...) } menuItems = append(menuItems, menuItemsForBranch(selectedBranch)...) return self.c.Menu(types.CreateMenuOptions{Title: fmt.Sprint(self.c.Tr.CreatePullRequestOptions), Items: menuItems}) } func (self *BranchesController) promptForTargetBranchNameAndCreatePullRequest(fromBranch *models.Branch, toRemote string) error { remoteDoesNotExist := lo.NoneBy(self.c.Model().Remotes, func(remote *models.Remote) bool { return remote.Name == toRemote }) if remoteDoesNotExist { return fmt.Errorf(self.c.Tr.NoValidRemoteName, toRemote) } self.c.Prompt(types.PromptOpts{ Title: fmt.Sprintf("%s โ†’ %s/", fromBranch.UpstreamBranch, toRemote), FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteBranchesForRemoteSuggestionsFunc(toRemote), HandleConfirm: func(toBranch string) error { self.c.Log.Debugf("PR will target branch '%s' on remote '%s'", toBranch, toRemote) return self.createPullRequest(fromBranch.UpstreamBranch, toBranch) }, }) return nil } func (self *BranchesController) createPullRequest(from string, to string) error { url, err := self.c.Helpers().Host.GetPullRequestURL(from, to) if err != nil { return err } self.c.LogAction(self.c.Tr.Actions.OpenPullRequest) if err := self.c.OS().OpenLink(url); err != nil { return err } return nil } func (self *BranchesController) branchIsReal(branch *models.Branch) *types.DisabledReason { if !branch.IsRealBranch() { return &types.DisabledReason{Text: self.c.Tr.SelectedItemIsNotABranch} } return nil } func (self *BranchesController) branchesAreReal(selectedBranches []*models.Branch, startIdx int, endIdx int) *types.DisabledReason { if !lo.EveryBy(selectedBranches, func(branch *models.Branch) bool { return branch.IsRealBranch() }) { return &types.DisabledReason{Text: self.c.Tr.SelectedItemIsNotABranch} } return nil } func (self *BranchesController) notMergingIntoYourself(branch *models.Branch) *types.DisabledReason { selectedBranchName := branch.Name checkedOutBranch := self.c.Helpers().Refs.GetCheckedOutRef().Name if checkedOutBranch == selectedBranchName { return &types.DisabledReason{Text: self.c.Tr.CantMergeBranchIntoItself} } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/list_controller_trait.go
pkg/gui/controllers/list_controller_trait.go
package controllers import ( "errors" "github.com/jesseduffield/lazygit/pkg/gui/types" ) // Embed this into your list controller to get some convenience methods for // ensuring a single item is selected, etc. type ListControllerTrait[T comparable] struct { c *ControllerCommon context types.IListContext getSelectedItem func() T getSelectedItems func() ([]T, int, int) } func NewListControllerTrait[T comparable]( c *ControllerCommon, context types.IListContext, getSelected func() T, getSelectedItems func() ([]T, int, int), ) *ListControllerTrait[T] { return &ListControllerTrait[T]{ c: c, context: context, getSelectedItem: getSelected, getSelectedItems: getSelectedItems, } } // Convenience function for combining multiple disabledReason callbacks. // The first callback to return a disabled reason will be the one returned. func (self *ListControllerTrait[T]) require(callbacks ...func() *types.DisabledReason) func() *types.DisabledReason { return func() *types.DisabledReason { for _, callback := range callbacks { if disabledReason := callback(); disabledReason != nil { return disabledReason } } return nil } } // Convenience function for enforcing that a single item is selected. // Also takes callbacks for additional disabled reasons, and passes the selected // item into each one. func (self *ListControllerTrait[T]) singleItemSelected(callbacks ...func(T) *types.DisabledReason) func() *types.DisabledReason { return func() *types.DisabledReason { if self.context.GetList().AreMultipleItemsSelected() { return &types.DisabledReason{Text: self.c.Tr.RangeSelectNotSupported} } var zeroValue T item := self.getSelectedItem() if item == zeroValue { return &types.DisabledReason{Text: self.c.Tr.NoItemSelected} } for _, callback := range callbacks { if reason := callback(item); reason != nil { return reason } } return nil } } // Ensures that at least one item is selected. func (self *ListControllerTrait[T]) itemRangeSelected(callbacks ...func([]T, int, int) *types.DisabledReason) func() *types.DisabledReason { return func() *types.DisabledReason { items, startIdx, endIdx := self.getSelectedItems() if len(items) == 0 { return &types.DisabledReason{Text: self.c.Tr.NoItemSelected} } for _, callback := range callbacks { if reason := callback(items, startIdx, endIdx); reason != nil { return reason } } return nil } } func (self *ListControllerTrait[T]) itemsSelected(callbacks ...func([]T) *types.DisabledReason) func() *types.DisabledReason { return func() *types.DisabledReason { items, _, _ := self.getSelectedItems() if len(items) == 0 { return &types.DisabledReason{Text: self.c.Tr.NoItemSelected} } for _, callback := range callbacks { if reason := callback(items); reason != nil { return reason } } return nil } } // Passes the selected item to the callback. Used for handler functions. func (self *ListControllerTrait[T]) withItem(callback func(T) error) func() error { return func() error { var zeroValue T commit := self.getSelectedItem() if commit == zeroValue { return errors.New(self.c.Tr.NoItemSelected) } return callback(commit) } } func (self *ListControllerTrait[T]) withItems(callback func([]T) error) func() error { return func() error { items, _, _ := self.getSelectedItems() if len(items) == 0 { return errors.New(self.c.Tr.NoItemSelected) } return callback(items) } } // like withItems but also passes the start and end index of the selection func (self *ListControllerTrait[T]) withItemsRange(callback func([]T, int, int) error) func() error { return func() error { items, startIdx, endIdx := self.getSelectedItems() if len(items) == 0 { return errors.New(self.c.Tr.NoItemSelected) } return callback(items, startIdx, endIdx) } } // Like withItem, but doesn't show an error message if no item is selected. // Use this for click actions (it's a no-op to click empty space) func (self *ListControllerTrait[T]) withItemGraceful(callback func(T) error) func() error { return func() error { var zeroValue T commit := self.getSelectedItem() if commit == zeroValue { return nil } return callback(commit) } } // All controllers must implement this method so we're defining it here for convenience func (self *ListControllerTrait[T]) Context() types.Context { return self.context }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/context_lines_controller.go
pkg/gui/controllers/context_lines_controller.go
package controllers import ( "errors" "fmt" "math" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // This controller lets you change the context size for diffs. The 'context' in 'context size' refers to the conventional meaning of the word 'context' in a diff, as opposed to lazygit's own idea of a 'context'. var CONTEXT_KEYS_SHOWING_DIFFS = []types.ContextKey{ context.FILES_CONTEXT_KEY, context.COMMIT_FILES_CONTEXT_KEY, context.STASH_CONTEXT_KEY, context.LOCAL_COMMITS_CONTEXT_KEY, context.SUB_COMMITS_CONTEXT_KEY, context.STAGING_MAIN_CONTEXT_KEY, context.STAGING_SECONDARY_CONTEXT_KEY, context.PATCH_BUILDING_MAIN_CONTEXT_KEY, context.PATCH_BUILDING_SECONDARY_CONTEXT_KEY, context.NORMAL_MAIN_CONTEXT_KEY, context.NORMAL_SECONDARY_CONTEXT_KEY, } type ContextLinesController struct { baseController c *ControllerCommon } var _ types.IController = &ContextLinesController{} func NewContextLinesController( c *ControllerCommon, ) *ContextLinesController { return &ContextLinesController{ baseController: baseController{}, c: c, } } func (self *ContextLinesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { bindings := []*types.Binding{ { Key: opts.GetKey(opts.Config.Universal.IncreaseContextInDiffView), Handler: self.Increase, Description: self.c.Tr.IncreaseContextInDiffView, Tooltip: self.c.Tr.IncreaseContextInDiffViewTooltip, }, { Key: opts.GetKey(opts.Config.Universal.DecreaseContextInDiffView), Handler: self.Decrease, Description: self.c.Tr.DecreaseContextInDiffView, Tooltip: self.c.Tr.DecreaseContextInDiffViewTooltip, }, } return bindings } func (self *ContextLinesController) Context() types.Context { return nil } func (self *ContextLinesController) Increase() error { if self.isShowingDiff() { if err := self.checkCanChangeContext(); err != nil { return err } if self.c.UserConfig().Git.DiffContextSize < math.MaxUint64 { self.c.UserConfig().Git.DiffContextSize++ } return self.applyChange() } return nil } func (self *ContextLinesController) Decrease() error { if self.isShowingDiff() { if err := self.checkCanChangeContext(); err != nil { return err } if self.c.UserConfig().Git.DiffContextSize > 0 { self.c.UserConfig().Git.DiffContextSize-- } return self.applyChange() } return nil } func (self *ContextLinesController) applyChange() error { self.c.Toast(fmt.Sprintf(self.c.Tr.DiffContextSizeChanged, self.c.UserConfig().Git.DiffContextSize)) currentContext := self.currentSidePanel() switch currentContext.GetKey() { // we make an exception for our staging and patch building contexts because they actually need to refresh their state afterwards. case context.PATCH_BUILDING_MAIN_CONTEXT_KEY: self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.PATCH_BUILDING}}) case context.STAGING_MAIN_CONTEXT_KEY, context.STAGING_SECONDARY_CONTEXT_KEY: self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STAGING}}) default: currentContext.HandleRenderToMain() } return nil } func (self *ContextLinesController) checkCanChangeContext() error { if self.c.Git().Patch.PatchBuilder.Active() { return errors.New(self.c.Tr.CantChangeContextSizeError) } return nil } func (self *ContextLinesController) isShowingDiff() bool { return lo.Contains( CONTEXT_KEYS_SHOWING_DIFFS, self.currentSidePanel().GetKey(), ) } func (self *ContextLinesController) currentSidePanel() types.Context { currentContext := self.c.Context().CurrentStatic() if currentContext.GetKey() == context.NORMAL_MAIN_CONTEXT_KEY || currentContext.GetKey() == context.NORMAL_SECONDARY_CONTEXT_KEY { if sidePanelContext := self.c.Context().NextInStack(currentContext); sidePanelContext != nil { return sidePanelContext } } return currentContext }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/refresh_helper.go
pkg/gui/controllers/helpers/refresh_helper.go
package helpers import ( "strings" "sync" "time" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/filetree" "github.com/jesseduffield/lazygit/pkg/gui/mergeconflicts" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type RefreshHelper struct { c *HelperCommon refsHelper *RefsHelper mergeAndRebaseHelper *MergeAndRebaseHelper patchBuildingHelper *PatchBuildingHelper stagingHelper *StagingHelper mergeConflictsHelper *MergeConflictsHelper worktreeHelper *WorktreeHelper searchHelper *SearchHelper } func NewRefreshHelper( c *HelperCommon, refsHelper *RefsHelper, mergeAndRebaseHelper *MergeAndRebaseHelper, patchBuildingHelper *PatchBuildingHelper, stagingHelper *StagingHelper, mergeConflictsHelper *MergeConflictsHelper, worktreeHelper *WorktreeHelper, searchHelper *SearchHelper, ) *RefreshHelper { return &RefreshHelper{ c: c, refsHelper: refsHelper, mergeAndRebaseHelper: mergeAndRebaseHelper, patchBuildingHelper: patchBuildingHelper, stagingHelper: stagingHelper, mergeConflictsHelper: mergeConflictsHelper, worktreeHelper: worktreeHelper, searchHelper: searchHelper, } } func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if options.Mode == types.ASYNC && options.Then != nil { panic("RefreshOptions.Then doesn't work with mode ASYNC") } t := time.Now() defer func() { self.c.Log.Infof("Refresh took %s", time.Since(t)) }() if options.Scope == nil { self.c.Log.Infof( "refreshing all scopes in %s mode", getModeName(options.Mode), ) } else { self.c.Log.Infof( "refreshing the following scopes in %s mode: %s", getModeName(options.Mode), strings.Join(getScopeNames(options.Scope), ","), ) } f := func() { var scopeSet *set.Set[types.RefreshableView] if len(options.Scope) == 0 { // not refreshing staging/patch-building unless explicitly requested because we only need // to refresh those while focused. scopeSet = set.NewFromSlice([]types.RefreshableView{ types.COMMITS, types.BRANCHES, types.FILES, types.STASH, types.REFLOG, types.TAGS, types.REMOTES, types.WORKTREES, types.STATUS, types.BISECT_INFO, types.STAGING, }) } else { scopeSet = set.NewFromSlice(options.Scope) } wg := sync.WaitGroup{} refresh := func(name string, f func()) { // if we're in a demo we don't want any async refreshes because // everything happens fast and it's better to have everything update // in the one frame if !self.c.InDemo() && options.Mode == types.ASYNC { self.c.OnWorker(func(t gocui.Task) error { f() return nil }) } else { wg.Add(1) go utils.Safe(func() { t := time.Now() defer wg.Done() f() self.c.Log.Infof("refreshed %s in %s", name, time.Since(t)) }) } } includeWorktreesWithBranches := false if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) || scopeSet.Includes(types.REFLOG) || scopeSet.Includes(types.BISECT_INFO) { // whenever we change commits, we should update branches because the upstream/downstream // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. refresh("commits and commit files", self.refreshCommitsAndCommitFiles) includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { refresh("reflog and branches", func() { self.refreshReflogAndBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex) }) } else { refresh("branches", func() { self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true) }) refresh("reflog", func() { _ = self.refreshReflogCommits() }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one // if we've asked specifically for rebase commits and not those other things refresh("rebase commits", func() { _ = self.refreshRebaseCommits() }) } if scopeSet.Includes(types.SUB_COMMITS) { refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit() }) } // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { refresh("commit files", func() { _ = self.refreshCommitFilesContext() }) } fileWg := sync.WaitGroup{} if scopeSet.Includes(types.FILES) || scopeSet.Includes(types.SUBMODULES) { fileWg.Add(1) refresh("files", func() { _ = self.refreshFilesAndSubmodules() fileWg.Done() }) } if scopeSet.Includes(types.STASH) { refresh("stash", func() { self.refreshStashEntries() }) } if scopeSet.Includes(types.TAGS) { refresh("tags", func() { _ = self.refreshTags() }) } if scopeSet.Includes(types.REMOTES) { refresh("remotes", func() { _ = self.refreshRemotes() }) } if scopeSet.Includes(types.WORKTREES) && !includeWorktreesWithBranches { refresh("worktrees", func() { self.refreshWorktrees() }) } if scopeSet.Includes(types.STAGING) { refresh("staging", func() { fileWg.Wait() self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) }) } if scopeSet.Includes(types.PATCH_BUILDING) { refresh("patch building", func() { self.patchBuildingHelper.RefreshPatchBuildingPanel(types.OnFocusOpts{}) }) } if scopeSet.Includes(types.MERGE_CONFLICTS) || scopeSet.Includes(types.FILES) { refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState() }) } self.refreshStatus() wg.Wait() if options.Then != nil { options.Then() } } if options.Mode == types.BLOCK_UI { self.c.OnUIThread(func() error { f() return nil }) return } f() } func getScopeNames(scopes []types.RefreshableView) []string { scopeNameMap := map[types.RefreshableView]string{ types.COMMITS: "commits", types.BRANCHES: "branches", types.FILES: "files", types.SUBMODULES: "submodules", types.SUB_COMMITS: "subCommits", types.STASH: "stash", types.REFLOG: "reflog", types.TAGS: "tags", types.REMOTES: "remotes", types.WORKTREES: "worktrees", types.STATUS: "status", types.BISECT_INFO: "bisect", types.STAGING: "staging", types.MERGE_CONFLICTS: "mergeConflicts", } return lo.Map(scopes, func(scope types.RefreshableView, _ int) string { return scopeNameMap[scope] }) } func getModeName(mode types.RefreshMode) string { switch mode { case types.SYNC: return "sync" case types.ASYNC: return "async" case types.BLOCK_UI: return "block-ui" default: return "unknown mode" } } // during startup, the bottleneck is fetching the reflog entries. We need these // on startup to sort the branches by recency. So we have two phases: INITIAL, and COMPLETE. // In the initial phase we don't get any reflog commits, but we asynchronously get them // and refresh the branches after that func (self *RefreshHelper) refreshReflogCommitsConsideringStartup() { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: self.c.OnWorker(func(_ gocui.Task) error { _ = self.refreshReflogCommits() self.refreshBranches(false, true, true) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) case types.COMPLETE: _ = self.refreshReflogCommits() } } func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { loadBehindCounts := self.c.State().GetRepoState().GetStartupStage() == types.COMPLETE self.refreshReflogCommitsConsideringStartup() self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, loadBehindCounts) } func (self *RefreshHelper) refreshCommitsAndCommitFiles() { _ = self.refreshCommitsWithLimit() ctx := self.c.Contexts().CommitFiles.GetParentContext() if ctx != nil && ctx.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY { // This makes sense when we've e.g. just amended a commit, meaning we get a new commit hash at the same position. // However if we've just added a brand new commit, it pushes the list down by one and so we would end up // showing the contents of a different commit than the one we initially entered. // Ideally we would know when to refresh the commit files context and when not to, // or perhaps we could just pop that context off the stack whenever cycling windows. // For now the awkwardness remains. commit := self.c.Contexts().LocalCommits.GetSelected() if commit != nil && commit.RefName() != "" { refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() self.c.Contexts().CommitFiles.ReInit(commit, refRange) _ = self.refreshCommitFilesContext() } } } func (self *RefreshHelper) determineCheckedOutRef() models.Ref { if rebasedBranch := self.c.Git().Status.BranchBeingRebased(); rebasedBranch != "" { // During a rebase we're on a detached head, so cannot determine the // branch name in the usual way. We need to read it from the // ".git/rebase-merge/head-name" file instead. return &models.Branch{Name: strings.TrimPrefix(rebasedBranch, "refs/heads/")} } if bisectInfo := self.c.Git().Bisect.GetInfo(); bisectInfo.Bisecting() && bisectInfo.GetStartHash() != "" { // Likewise, when we're bisecting we're on a detached head as well. In // this case we read the branch name from the ".git/BISECT_START" file. return &models.Branch{Name: bisectInfo.GetStartHash()} } // In all other cases, get the branch name by asking git what branch is // checked out. Note that if we're on a detached head (for reasons other // than rebasing or bisecting, i.e. it was explicitly checked out), then // this will return an empty string. if branchName, err := self.c.Git().Branch.CurrentBranchName(); err == nil && branchName != "" { return &models.Branch{Name: branchName} } // Should never get here unless the working copy is corrupt return nil } func (self *RefreshHelper) refreshCommitsWithLimit() error { self.c.Mutexes().LocalCommitsMutex.Lock() defer self.c.Mutexes().LocalCommitsMutex.Unlock() checkedOutRef := self.determineCheckedOutRef() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: self.c.Contexts().LocalCommits.GetLimitCommits(), FilterPath: self.c.Modes().Filtering.GetPath(), FilterAuthor: self.c.Modes().Filtering.GetAuthor(), IncludeRebaseCommits: true, RefName: self.refForLog(), RefForPushedStatus: checkedOutRef, All: self.c.Contexts().LocalCommits.GetShowWholeGitGraph(), MainBranches: self.c.Model().MainBranches, HashPool: self.c.Model().HashPool, }, ) if err != nil { return err } self.c.Model().Commits = commits self.RefreshAuthors(commits) self.c.Model().WorkingTreeStateAtLastCommitRefresh = self.c.Git().Status.WorkingTreeState() if checkedOutRef != nil { self.c.Model().CheckedOutBranch = checkedOutRef.RefName() } else { self.c.Model().CheckedOutBranch = "" } self.refreshView(self.c.Contexts().LocalCommits) return nil } func (self *RefreshHelper) refreshSubCommitsWithLimit() error { if self.c.Contexts().SubCommits.GetRef() == nil { return nil } self.c.Mutexes().SubCommitsMutex.Lock() defer self.c.Mutexes().SubCommitsMutex.Unlock() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: self.c.Contexts().SubCommits.GetLimitCommits(), FilterPath: self.c.Modes().Filtering.GetPath(), FilterAuthor: self.c.Modes().Filtering.GetAuthor(), IncludeRebaseCommits: false, RefName: self.c.Contexts().SubCommits.GetRef().FullRefName(), RefToShowDivergenceFrom: self.c.Contexts().SubCommits.GetRefToShowDivergenceFrom(), RefForPushedStatus: self.c.Contexts().SubCommits.GetRef(), MainBranches: self.c.Model().MainBranches, HashPool: self.c.Model().HashPool, }, ) if err != nil { return err } self.c.Model().SubCommits = commits self.RefreshAuthors(commits) self.refreshView(self.c.Contexts().SubCommits) return nil } func (self *RefreshHelper) RefreshAuthors(commits []*models.Commit) { self.c.Mutexes().AuthorsMutex.Lock() defer self.c.Mutexes().AuthorsMutex.Unlock() authors := self.c.Model().Authors for _, commit := range commits { if _, ok := authors[commit.AuthorEmail]; !ok { authors[commit.AuthorEmail] = &models.Author{ Email: commit.AuthorEmail, Name: commit.AuthorName, } } } } func (self *RefreshHelper) refreshCommitFilesContext() error { from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(from, to, reverse) if err != nil { return err } self.c.Model().CommitFiles = files self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() self.refreshView(self.c.Contexts().CommitFiles) return nil } func (self *RefreshHelper) refreshRebaseCommits() error { self.c.Mutexes().LocalCommitsMutex.Lock() defer self.c.Mutexes().LocalCommitsMutex.Unlock() updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(self.c.Model().HashPool, self.c.Model().Commits) if err != nil { return err } self.c.Model().Commits = updatedCommits self.c.Model().WorkingTreeStateAtLastCommitRefresh = self.c.Git().Status.WorkingTreeState() self.refreshView(self.c.Contexts().LocalCommits) return nil } func (self *RefreshHelper) refreshTags() error { tags, err := self.c.Git().Loaders.TagLoader.GetTags() if err != nil { return err } self.c.Model().Tags = tags self.refreshView(self.c.Contexts().Tags) return nil } func (self *RefreshHelper) refreshStateSubmoduleConfigs() error { configs, err := self.c.Git().Submodule.GetConfigs(nil) if err != nil { return err } self.c.Model().Submodules = configs return nil } // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool) { self.c.Mutexes().RefreshingBranchesMutex.Lock() defer self.c.Mutexes().RefreshingBranchesMutex.Unlock() branches, err := self.c.Git().Loaders.BranchLoader.Load( self.c.Model().ReflogCommits, self.c.Model().MainBranches, self.c.Model().Branches, loadBehindCounts, func(f func() error) { self.c.OnWorker(func(_ gocui.Task) error { return f() }) }, func() { self.c.OnUIThread(func() error { self.c.Contexts().Branches.HandleRender() self.refreshStatus() return nil }) }) if err != nil { self.c.Log.Error(err) } prevSelectedBranch := self.c.Contexts().Branches.GetSelected() self.c.Model().Branches = branches if refreshWorktrees { self.loadWorktrees() self.refreshView(self.c.Contexts().Worktrees) } if !keepBranchSelectionIndex && prevSelectedBranch != nil { self.searchHelper.ReApplyFilter(self.c.Contexts().Branches) _, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(), func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name }) if found { self.c.Contexts().Branches.SetSelectedLineIdx(idx) } } self.refreshView(self.c.Contexts().Branches) // Need to re-render the commits view because the visualization of local // branch heads might have changed self.c.Mutexes().LocalCommitsMutex.Lock() self.c.Contexts().LocalCommits.HandleRender() self.c.Mutexes().LocalCommitsMutex.Unlock() self.refreshStatus() } func (self *RefreshHelper) refreshFilesAndSubmodules() error { self.c.Mutexes().RefreshingFilesMutex.Lock() self.c.State().SetIsRefreshingFiles(true) defer func() { self.c.State().SetIsRefreshingFiles(false) self.c.Mutexes().RefreshingFilesMutex.Unlock() }() if err := self.refreshStateSubmoduleConfigs(); err != nil { return err } if err := self.refreshStateFiles(); err != nil { return err } self.c.OnUIThread(func() error { self.refreshView(self.c.Contexts().Submodules) self.refreshView(self.c.Contexts().Files) return nil }) return nil } func (self *RefreshHelper) refreshStateFiles() error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel prevConflictFileCount := 0 if self.c.UserConfig().Git.AutoStageResolvedConflicts { // If git thinks any of our files have inline merge conflicts, but they actually don't, // we stage them. // Note that if files with merge conflicts have both arisen and have been resolved // between refreshes, we won't stage them here. This is super unlikely though, // and this approach spares us from having to call `git status` twice in a row. // Although this also means that at startup we won't be staging anything until // we call git status again. pathsToStage := []string{} for _, file := range self.c.Model().Files { if file.HasMergeConflicts { prevConflictFileCount++ } if file.HasInlineMergeConflicts { hasConflicts, err := mergeconflicts.FileHasConflictMarkers(file.Path) if err != nil { self.c.Log.Error(err) } else if !hasConflicts { pathsToStage = append(pathsToStage, file.Path) } } } if len(pathsToStage) > 0 { self.c.LogAction(self.c.Tr.Actions.StageResolvedFiles) if err := self.c.Git().WorkingTree.StageFiles(pathsToStage, nil); err != nil { return err } } } files := self.c.Git().Loaders.FileLoader. GetStatusFiles(git_commands.GetStatusFileOptions{ ForceShowUntracked: self.c.Contexts().Files.ForceShowUntracked(), }) conflictFileCount := 0 for _, file := range files { if file.HasMergeConflicts { conflictFileCount++ } } if self.c.Git().Status.WorkingTreeState().Any() && conflictFileCount == 0 && prevConflictFileCount > 0 { self.c.OnUIThread(func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) } fileTreeViewModel.RWMutex.Lock() // only taking over the filter if it hasn't already been set by the user. if conflictFileCount > 0 && prevConflictFileCount == 0 { if fileTreeViewModel.GetFilter() == filetree.DisplayAll { fileTreeViewModel.SetStatusFilter(filetree.DisplayConflicted) self.c.Contexts().Files.GetView().Subtitle = self.c.Tr.FilterLabelConflictingFiles } } else if conflictFileCount == 0 && fileTreeViewModel.GetFilter() == filetree.DisplayConflicted { fileTreeViewModel.SetStatusFilter(filetree.DisplayAll) self.c.Contexts().Files.GetView().Subtitle = "" } self.c.Model().Files = files fileTreeViewModel.SetTree() fileTreeViewModel.RWMutex.Unlock() return nil } // the reflogs panel is the only panel where we cache data, in that we only // load entries that have been created since we last ran the call. This means // we need to be more careful with how we use this, and to ensure we're emptying // the reflogs array when changing contexts. // This method also manages two things: ReflogCommits and FilteredReflogCommits. // FilteredReflogCommits are rendered in the reflogs panel, and ReflogCommits // are used by the branches panel to obtain recency values for sorting. func (self *RefreshHelper) refreshReflogCommits() error { // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception model := self.c.Model() refresh := func(stateCommits *[]*models.Commit, filterPath string, filterAuthor string) error { var lastReflogCommit *models.Commit if filterPath == "" && filterAuthor == "" && len(*stateCommits) > 0 { lastReflogCommit = (*stateCommits)[0] } commits, onlyObtainedNewReflogCommits, err := self.c.Git().Loaders.ReflogCommitLoader. GetReflogCommits(self.c.Model().HashPool, lastReflogCommit, filterPath, filterAuthor) if err != nil { return err } if onlyObtainedNewReflogCommits { *stateCommits = append(commits, *stateCommits...) } else { *stateCommits = commits } return nil } if err := refresh(&model.ReflogCommits, "", ""); err != nil { return err } if self.c.Modes().Filtering.Active() { if err := refresh(&model.FilteredReflogCommits, self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()); err != nil { return err } } else { model.FilteredReflogCommits = model.ReflogCommits } self.refreshView(self.c.Contexts().ReflogCommits) return nil } func (self *RefreshHelper) refreshRemotes() error { prevSelectedRemote := self.c.Contexts().Remotes.GetSelected() remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() if err != nil { return err } self.c.Model().Remotes = remotes // we need to ensure our selected remote branches aren't now outdated if prevSelectedRemote != nil && self.c.Model().RemoteBranches != nil { // find remote now for _, remote := range remotes { if remote.Name == prevSelectedRemote.Name { self.c.Model().RemoteBranches = remote.Branches break } } } self.refreshView(self.c.Contexts().Remotes) self.refreshView(self.c.Contexts().RemoteBranches) return nil } func (self *RefreshHelper) loadWorktrees() { worktrees, err := self.c.Git().Loaders.Worktrees.GetWorktrees() if err != nil { self.c.Log.Error(err) self.c.Model().Worktrees = []*models.Worktree{} } self.c.Model().Worktrees = worktrees } func (self *RefreshHelper) refreshWorktrees() { self.loadWorktrees() // need to refresh branches because the branches view shows worktrees against // branches self.refreshView(self.c.Contexts().Branches) self.refreshView(self.c.Contexts().Worktrees) } func (self *RefreshHelper) refreshStashEntries() { self.c.Model().StashEntries = self.c.Git().Loaders.StashLoader. GetStashEntries(self.c.Modes().Filtering.GetPath()) self.refreshView(self.c.Contexts().Stash) } // never call this on its own, it should only be called from within refreshCommits() func (self *RefreshHelper) refreshStatus() { self.c.Mutexes().RefreshingStatusMutex.Lock() defer self.c.Mutexes().RefreshingStatusMutex.Unlock() currentBranch := self.refsHelper.GetCheckedOutRef() if currentBranch == nil { // need to wait for branches to refresh return } workingTreeState := self.c.Git().Status.WorkingTreeState() linkedWorktreeName := self.worktreeHelper.GetLinkedWorktreeName() repoName := self.c.Git().RepoPaths.RepoName() status := presentation.FormatStatus(repoName, currentBranch, types.ItemOperationNone, linkedWorktreeName, workingTreeState, self.c.Tr, self.c.UserConfig()) self.c.SetViewContent(self.c.Views().Status, status) } func (self *RefreshHelper) refForLog() string { bisectInfo := self.c.Git().Bisect.GetInfo() self.c.Model().BisectInfo = bisectInfo if !bisectInfo.Started() { return "HEAD" } // need to see if our bisect's current commit is reachable from our 'new' ref. if bisectInfo.Bisecting() && !self.c.Git().Bisect.ReachableFromStart(bisectInfo) { return bisectInfo.GetNewHash() } return bisectInfo.GetStartHash() } func (self *RefreshHelper) refreshView(context types.Context) { // Re-applying the filter must be done before re-rendering the view, so that // the filtered list model is up to date for rendering. self.searchHelper.ReApplyFilter(context) self.c.PostRefreshUpdate(context) self.c.AfterLayout(func() error { // Re-applying the search must be done after re-rendering the view though, // so that the "x of y" status is shown correctly. // // Also, it must be done after layout, because otherwise FocusPoint // hasn't been called yet (see ListContextTrait.FocusLine), which means // that the scroll position might be such that the entire visible // content is outside the viewport. And this would cause problems in // searchModelCommits. self.searchHelper.ReApplySearch(context) return nil }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/sub_commits_helper.go
pkg/gui/controllers/helpers/sub_commits_helper.go
package helpers import ( "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type SubCommitsHelper struct { c *HelperCommon refreshHelper *RefreshHelper } func NewSubCommitsHelper( c *HelperCommon, refreshHelper *RefreshHelper, ) *SubCommitsHelper { return &SubCommitsHelper{ c: c, refreshHelper: refreshHelper, } } type ViewSubCommitsOpts struct { Ref models.Ref RefToShowDivergenceFrom string TitleRef string Context types.Context ShowBranchHeads bool } func (self *SubCommitsHelper) ViewSubCommits(opts ViewSubCommitsOpts) error { commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: true, FilterPath: self.c.Modes().Filtering.GetPath(), FilterAuthor: self.c.Modes().Filtering.GetAuthor(), IncludeRebaseCommits: false, RefName: opts.Ref.FullRefName(), RefForPushedStatus: opts.Ref, RefToShowDivergenceFrom: opts.RefToShowDivergenceFrom, MainBranches: self.c.Model().MainBranches, HashPool: self.c.Model().HashPool, }, ) if err != nil { return err } self.setSubCommits(commits) self.refreshHelper.RefreshAuthors(commits) subCommitsContext := self.c.Contexts().SubCommits subCommitsContext.SetSelection(0) subCommitsContext.SetParentContext(opts.Context) subCommitsContext.SetWindowName(opts.Context.GetWindowName()) subCommitsContext.SetTitleRef(utils.TruncateWithEllipsis(opts.TitleRef, 50)) subCommitsContext.SetRef(opts.Ref) subCommitsContext.SetRefToShowDivergenceFrom(opts.RefToShowDivergenceFrom) subCommitsContext.SetLimitCommits(true) subCommitsContext.SetShowBranchHeads(opts.ShowBranchHeads) subCommitsContext.ClearSearchString() subCommitsContext.GetView().ClearSearch() subCommitsContext.GetView().TitlePrefix = opts.Context.GetView().TitlePrefix self.c.PostRefreshUpdate(self.c.Contexts().SubCommits) self.c.Context().Push(self.c.Contexts().SubCommits, types.OnFocusOpts{}) return nil } func (self *SubCommitsHelper) setSubCommits(commits []*models.Commit) { self.c.Mutexes().SubCommitsMutex.Lock() defer self.c.Mutexes().SubCommitsMutex.Unlock() self.c.Model().SubCommits = commits }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/window_helper.go
pkg/gui/controllers/helpers/window_helper.go
package helpers import ( "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type WindowHelper struct { c *HelperCommon viewHelper *ViewHelper } func NewWindowHelper(c *HelperCommon, viewHelper *ViewHelper) *WindowHelper { return &WindowHelper{ c: c, viewHelper: viewHelper, } } // A window refers to a place on the screen which can hold one or more views. // A view is a box that renders content, and within a window only one view will // appear at a time. When a view appears within a window, it occupies the whole // space. Right now most windows are 1:1 with views, except for commitFiles which // is a view that moves between windows func (self *WindowHelper) GetViewNameForWindow(window string) string { viewName, ok := self.windowViewNameMap().Get(window) if !ok { panic(fmt.Sprintf("Viewname not found for window: %s", window)) } return viewName } func (self *WindowHelper) GetContextForWindow(window string) types.Context { viewName := self.GetViewNameForWindow(window) context, ok := self.viewHelper.ContextForView(viewName) if !ok { panic("TODO: fix this") } return context } // for now all we actually care about is the context's view so we're storing that func (self *WindowHelper) SetWindowContext(c types.Context) { if c.IsTransient() { self.resetWindowContext(c) } self.windowViewNameMap().Set(c.GetWindowName(), c.GetViewName()) } func (self *WindowHelper) windowViewNameMap() *utils.ThreadSafeMap[string, string] { return self.c.State().GetRepoState().GetWindowViewNameMap() } func (self *WindowHelper) CurrentWindow() string { return self.c.Context().Current().GetWindowName() } // assumes the context's windowName has been set to the new window if necessary func (self *WindowHelper) resetWindowContext(c types.Context) { for _, windowName := range self.windowViewNameMap().Keys() { viewName, ok := self.windowViewNameMap().Get(windowName) if !ok { continue } if viewName == c.GetViewName() && windowName != c.GetWindowName() { for _, context := range self.c.Contexts().Flatten() { if context.GetKey() != c.GetKey() && context.GetWindowName() == windowName { self.windowViewNameMap().Set(windowName, context.GetViewName()) } } } } } // moves given context's view to the top of the window func (self *WindowHelper) MoveToTopOfWindow(context types.Context) { view := context.GetView() if view == nil { return } window := context.GetWindowName() topView := self.TopViewInWindow(window, true) if topView != nil && view.Name() != topView.Name() { if err := self.c.GocuiGui().SetViewOnTopOf(view.Name(), topView.Name()); err != nil { self.c.Log.Error(err) } } } func (self *WindowHelper) TopViewInWindow(windowName string, includeInvisibleViews bool) *gocui.View { // now I need to find all views in that same window, via contexts. And I guess then I need to find the index of the highest view in that list. viewNamesInWindow := self.viewNamesInWindow(windowName) // The views list is ordered highest-last, so we're grabbing the last view of the window var topView *gocui.View for _, currentView := range self.c.GocuiGui().Views() { if lo.Contains(viewNamesInWindow, currentView.Name()) && (currentView.Visible || includeInvisibleViews) { topView = currentView } } return topView } func (self *WindowHelper) viewNamesInWindow(windowName string) []string { result := []string{} for _, context := range self.c.Contexts().Flatten() { if context.GetWindowName() == windowName { result = append(result, context.GetViewName()) } } return result } func (self *WindowHelper) WindowForView(viewName string) string { context, ok := self.viewHelper.ContextForView(viewName) if !ok { panic("todo: deal with this") } return context.GetWindowName() } func (self *WindowHelper) SideWindows() []string { return []string{"status", "files", "branches", "commits", "stash"} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/fixup_helper.go
pkg/gui/controllers/helpers/fixup_helper.go
package helpers import ( "errors" "fmt" "regexp" "strings" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" "golang.org/x/sync/errgroup" ) type FixupHelper struct { c *HelperCommon } func NewFixupHelper( c *HelperCommon, ) *FixupHelper { return &FixupHelper{ c: c, } } // hunk describes the lines in a diff hunk. Used for two distinct cases: // // - when the hunk contains some deleted lines. Because we're diffing with a // context of 0, all deleted lines always come first, and then the added lines // (if any). In this case, numLines is only the number of deleted lines, we // ignore whether there are also some added lines in the hunk, as this is not // relevant for our algorithm. // // - when the hunk contains only added lines, in which case (obviously) numLines // is the number of added lines. type hunk struct { filename string startLineIdx int numLines int } func (self *FixupHelper) HandleFindBaseCommitForFixupPress() error { diff, hasStagedChanges, err := self.getDiff() if err != nil { return err } deletedLineHunks, addedLineHunks := parseDiff(diff) commits := self.c.Model().Commits var hashes []string warnAboutAddedLines := false if len(deletedLineHunks) > 0 { hashes, err = self.blameDeletedLines(deletedLineHunks) warnAboutAddedLines = len(addedLineHunks) > 0 } else if len(addedLineHunks) > 0 { hashes, err = self.blameAddedLines(commits, addedLineHunks) } else { return errors.New(self.c.Tr.NoChangedFiles) } if err != nil { return err } if len(hashes) == 0 { // This should never happen return errors.New(self.c.Tr.NoBaseCommitsFound) } // If a commit can't be found, and the last known commit is already merged, // we know that the commit we're looking for is also merged. Otherwise we // can't tell. notFoundMeansMerged := len(commits) > 0 && commits[len(commits)-1].Status == models.StatusMerged const ( MERGED int = iota NOT_MERGED CANNOT_TELL ) // Group the hashes into buckets by merged status hashGroups := lo.GroupBy(hashes, func(hash string) int { commit, _, ok := self.findCommit(commits, hash) if ok { return lo.Ternary(commit.Status == models.StatusMerged, MERGED, NOT_MERGED) } return lo.Ternary(notFoundMeansMerged, MERGED, CANNOT_TELL) }) if len(hashGroups[CANNOT_TELL]) > 0 { // If we have any commits that we can't tell if they're merged, just // show the generic "not in current view" error. This can only happen if // a feature branch has more than 300 commits, or there is no main // branch. Both are so unlikely that we don't bother returning a more // detailed error message (e.g. we could say something about the commits // that *are* in the current branch, but it's not worth it). return errors.New(self.c.Tr.BaseCommitIsNotInCurrentView) } if len(hashGroups[NOT_MERGED]) == 0 { // If all the commits are merged, show the "already on main branch" // error. It isn't worth doing a detailed report of which commits we // found. return errors.New(self.c.Tr.BaseCommitIsAlreadyOnMainBranch) } if len(hashGroups[NOT_MERGED]) > 1 { // If there are multiple commits that could be the base commit, list // them in the error message. But only the candidates from the current // branch, not including any that are already merged. subjects := self.getHashesAndSubjects(commits, hashGroups[NOT_MERGED]) message := lo.Ternary(hasStagedChanges, self.c.Tr.MultipleBaseCommitsFoundStaged, self.c.Tr.MultipleBaseCommitsFoundUnstaged) return fmt.Errorf("%s\n\n%s", message, subjects) } // At this point we know that the NOT_MERGED bucket has exactly one commit, // and that's the one we want to select. _, index, _ := self.findCommit(commits, hashGroups[NOT_MERGED][0]) return self.c.ConfirmIf(warnAboutAddedLines, types.ConfirmOpts{ Title: self.c.Tr.FindBaseCommitForFixup, Prompt: self.c.Tr.HunksWithOnlyAddedLinesWarning, HandleConfirm: func() error { if !hasStagedChanges { if err := self.c.Git().WorkingTree.StageAll(true); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) } self.c.Contexts().LocalCommits.SetSelection(index) self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) return nil }, }) } func (self *FixupHelper) getHashesAndSubjects(commits []*models.Commit, hashes []string) string { // This is called only for the NOT_MERGED commits, and we know that all of them are contained in // the commits slice. commitsSet := set.NewFromSlice(hashes) subjects := make([]string, 0, len(hashes)) for _, c := range commits { if commitsSet.Includes(c.Hash()) { subjects = append(subjects, fmt.Sprintf("%s %s", c.ShortRefName(), c.Name)) commitsSet.Remove(c.Hash()) if commitsSet.Len() == 0 { break } } } return strings.Join(subjects, "\n") } func (self *FixupHelper) getDiff() (string, bool, error) { args := []string{"-U0", "--ignore-submodules=all", "HEAD", "--"} // Try staged changes first hasStagedChanges := true diff, err := self.c.Git().Diff.DiffIndexCmdObj(append([]string{"--cached"}, args...)...).RunWithOutput() if err == nil && diff == "" { hasStagedChanges = false // If there are no staged changes, try unstaged changes diff, err = self.c.Git().Diff.DiffIndexCmdObj(args...).RunWithOutput() } return diff, hasStagedChanges, err } // Parse the diff output into hunks, and return two lists of hunks: the first // are ones that contain deleted lines, the second are ones that contain only // added lines. func parseDiff(diff string) ([]*hunk, []*hunk) { lines := strings.Split(strings.TrimSuffix(diff, "\n"), "\n") deletedLineHunks := []*hunk{} addedLineHunks := []*hunk{} hunkHeaderRegexp := regexp.MustCompile(`@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@`) var filename string var currentHunk *hunk numDeletedLines := 0 numAddedLines := 0 finishHunk := func() { if currentHunk != nil { if numDeletedLines > 0 { currentHunk.numLines = numDeletedLines deletedLineHunks = append(deletedLineHunks, currentHunk) } else if numAddedLines > 0 { currentHunk.numLines = numAddedLines addedLineHunks = append(addedLineHunks, currentHunk) } } numDeletedLines = 0 numAddedLines = 0 } for _, line := range lines { if strings.HasPrefix(line, "diff --git") { finishHunk() currentHunk = nil } else if currentHunk == nil && strings.HasPrefix(line, "--- ") { // For some reason, the line ends with a tab character if the file // name contains spaces filename = strings.TrimRight(line[6:], "\t") } else if strings.HasPrefix(line, "@@ ") { finishHunk() match := hunkHeaderRegexp.FindStringSubmatch(line) startIdx := utils.MustConvertToInt(match[1]) currentHunk = &hunk{filename, startIdx, 0} } else if currentHunk != nil && line[0] == '-' { numDeletedLines++ } else if currentHunk != nil && line[0] == '+' { numAddedLines++ } } finishHunk() return deletedLineHunks, addedLineHunks } // returns the list of commit hashes that introduced the lines which have now been deleted func (self *FixupHelper) blameDeletedLines(deletedLineHunks []*hunk) ([]string, error) { errg := errgroup.Group{} hashChan := make(chan string) for _, h := range deletedLineHunks { errg.Go(func() error { blameOutput, err := self.c.Git().Blame.BlameLineRange(h.filename, "HEAD", h.startLineIdx, h.numLines) if err != nil { return err } blameLines := strings.SplitSeq(strings.TrimSuffix(blameOutput, "\n"), "\n") for line := range blameLines { hashChan <- strings.Split(line, " ")[0] } return nil }) } go func() { // We don't care about the error here, we'll check it later (in the // return statement below). Here we only wait for all the goroutines to // finish so that we can close the channel. _ = errg.Wait() close(hashChan) }() result := set.New[string]() for hash := range hashChan { result.Add(hash) } return result.ToSlice(), errg.Wait() } func (self *FixupHelper) blameAddedLines(commits []*models.Commit, addedLineHunks []*hunk) ([]string, error) { errg := errgroup.Group{} hashesChan := make(chan []string) for _, h := range addedLineHunks { errg.Go(func() error { result := make([]string, 0, 2) appendBlamedLine := func(blameOutput string) { blameLines := strings.Split(strings.TrimSuffix(blameOutput, "\n"), "\n") if len(blameLines) == 1 { result = append(result, strings.Split(blameLines[0], " ")[0]) } } // Blame the line before this hunk, if there is one if h.startLineIdx > 0 { blameOutput, err := self.c.Git().Blame.BlameLineRange(h.filename, "HEAD", h.startLineIdx, 1) if err != nil { return err } appendBlamedLine(blameOutput) } // Blame the line after this hunk. We don't know how many lines the // file has, so we can't check if there is a line after the hunk; // let the error tell us. blameOutput, err := self.c.Git().Blame.BlameLineRange(h.filename, "HEAD", h.startLineIdx+1, 1) if err != nil { // If this fails, we're probably at the end of the file (we // could have checked this beforehand, but it's expensive). If // there was a line before this hunk, this is fine, we'll just // return that one; if not, the hunk encompasses the entire // file, and we can't blame the lines before and after the hunk. // This is an error. if h.startLineIdx == 0 { return errors.New("Entire file") // TODO i18n } } else { appendBlamedLine(blameOutput) } hashesChan <- result return nil }) } go func() { // We don't care about the error here, we'll check it later (in the // return statement below). Here we only wait for all the goroutines to // finish so that we can close the channel. _ = errg.Wait() close(hashesChan) }() result := set.New[string]() for hashes := range hashesChan { if len(hashes) == 1 { result.Add(hashes[0]) } else if len(hashes) > 1 { if hashes[0] == hashes[1] { result.Add(hashes[0]) } else { _, index1, ok1 := self.findCommit(commits, hashes[0]) _, index2, ok2 := self.findCommit(commits, hashes[1]) if ok1 && ok2 { result.Add(lo.Ternary(index1 < index2, hashes[0], hashes[1])) } else if ok1 { result.Add(hashes[0]) } else if ok2 { result.Add(hashes[1]) } else { return nil, errors.New(self.c.Tr.NoBaseCommitsFound) } } } } return result.ToSlice(), errg.Wait() } func (self *FixupHelper) findCommit(commits []*models.Commit, hash string) (*models.Commit, int, bool) { return lo.FindIndexOf(commits, func(commit *models.Commit) bool { return commit.Hash() == hash }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/worktree_helper.go
pkg/gui/controllers/helpers/worktree_helper.go
package helpers import ( "errors" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type WorktreeHelper struct { c *HelperCommon reposHelper *ReposHelper refsHelper *RefsHelper suggestionsHelper *SuggestionsHelper } func NewWorktreeHelper(c *HelperCommon, reposHelper *ReposHelper, refsHelper *RefsHelper, suggestionsHelper *SuggestionsHelper) *WorktreeHelper { return &WorktreeHelper{ c: c, reposHelper: reposHelper, refsHelper: refsHelper, suggestionsHelper: suggestionsHelper, } } func (self *WorktreeHelper) GetMainWorktreeName() string { for _, worktree := range self.c.Model().Worktrees { if worktree.IsMain { return worktree.Name } } return "" } // If we're on the main worktree, we return an empty string func (self *WorktreeHelper) GetLinkedWorktreeName() string { worktrees := self.c.Model().Worktrees if len(worktrees) == 0 { return "" } // worktrees always have the current worktree on top currentWorktree := worktrees[0] if currentWorktree.IsMain { return "" } return currentWorktree.Name } func (self *WorktreeHelper) NewWorktree() error { branch := self.refsHelper.GetCheckedOutRef() currentBranchName := branch.RefName() f := func(detached bool) { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewWorktreeBase, InitialContent: currentBranchName, FindSuggestionsFunc: self.suggestionsHelper.GetRefsSuggestionsFunc(), HandleConfirm: func(base string) error { // we assume that the base can be checked out canCheckoutBase := true return self.NewWorktreeCheckout(base, canCheckoutBase, detached, context.WORKTREES_CONTEXT_KEY) }, }) } placeholders := map[string]string{"ref": "ref"} return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.WorktreeTitle, Items: []*types.MenuItem{ { LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFrom, placeholders)}, OnPress: func() error { f(false) return nil }, }, { LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFromDetached, placeholders)}, OnPress: func() error { f(true) return nil }, }, }, }) } func (self *WorktreeHelper) NewWorktreeCheckout(base string, canCheckoutBase bool, detached bool, contextKey types.ContextKey) error { opts := git_commands.NewWorktreeOpts{ Base: base, Detach: detached, } f := func() error { return self.c.WithWaitingStatus(self.c.Tr.AddingWorktree, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddWorktree) if err := self.c.Git().Worktree.New(opts); err != nil { return err } return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) }) } self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewWorktreePath, HandleConfirm: func(path string) error { opts.Path = path if detached { return f() } if canCheckoutBase { title := utils.ResolvePlaceholderString(self.c.Tr.NewBranchNameLeaveBlank, map[string]string{"default": base}) // prompt for the new branch name where a blank means we just check out the branch self.c.Prompt(types.PromptOpts{ Title: title, HandleConfirm: func(branchName string) error { opts.Branch = branchName return f() }, AllowEmptyInput: true, }) return nil } // prompt for the new branch name self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewBranchName, HandleConfirm: func(branchName string) error { opts.Branch = branchName return f() }, AllowEmptyInput: false, }) return nil }, }) return nil } func (self *WorktreeHelper) Switch(worktree *models.Worktree, contextKey types.ContextKey) error { if worktree.IsCurrent { return errors.New(self.c.Tr.AlreadyInWorktree) } self.c.LogAction(self.c.Tr.SwitchToWorktree) return self.reposHelper.DispatchSwitchTo(worktree.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) } func (self *WorktreeHelper) Remove(worktree *models.Worktree, force bool) error { title := self.c.Tr.RemoveWorktreeTitle var templateStr string if force { templateStr = self.c.Tr.ForceRemoveWorktreePrompt } else { templateStr = self.c.Tr.RemoveWorktreePrompt } message := utils.ResolvePlaceholderString( templateStr, map[string]string{ "worktreeName": worktree.Name, }, ) self.c.Confirm(types.ConfirmOpts{ Title: title, Prompt: message, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.RemovingWorktree, func(gocui.Task) error { self.c.LogAction(self.c.Tr.RemoveWorktree) if err := self.c.Git().Worktree.Delete(worktree.Path, force); err != nil { errMessage := err.Error() if !strings.Contains(errMessage, "--force") && !strings.Contains(errMessage, "fatal: working trees containing submodules cannot be moved or removed") { return err } if !force { return self.Remove(worktree, true) } return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) }, }) return nil } func (self *WorktreeHelper) Detach(worktree *models.Worktree) error { return self.c.WithWaitingStatus(self.c.Tr.DetachingWorktree, func(gocui.Task) error { self.c.LogAction(self.c.Tr.RemovingWorktree) err := self.c.Git().Worktree.Detach(worktree.Path) if err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) } func (self *WorktreeHelper) ViewWorktreeOptions(context types.IListContext, ref string) error { currentBranch := self.refsHelper.GetCheckedOutRef() canCheckoutBase := context == self.c.Contexts().Branches && ref != currentBranch.RefName() return self.ViewBranchWorktreeOptions(ref, canCheckoutBase) } func (self *WorktreeHelper) ViewBranchWorktreeOptions(branchName string, canCheckoutBase bool) error { placeholders := map[string]string{"ref": branchName} return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.WorktreeTitle, Items: []*types.MenuItem{ { LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFrom, placeholders)}, OnPress: func() error { return self.NewWorktreeCheckout(branchName, canCheckoutBase, false, context.LOCAL_BRANCHES_CONTEXT_KEY) }, }, { LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFromDetached, placeholders)}, OnPress: func() error { return self.NewWorktreeCheckout(branchName, canCheckoutBase, true, context.LOCAL_BRANCHES_CONTEXT_KEY) }, }, }, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/working_tree_helper.go
pkg/gui/controllers/helpers/working_tree_helper.go
package helpers import ( "errors" "fmt" "os" "regexp" "strings" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type WorkingTreeHelper struct { c *HelperCommon refHelper *RefsHelper commitsHelper *CommitsHelper gpgHelper *GpgHelper mergeAndRebaseHelper *MergeAndRebaseHelper } func NewWorkingTreeHelper( c *HelperCommon, refHelper *RefsHelper, commitsHelper *CommitsHelper, gpgHelper *GpgHelper, mergeAndRebaseHelper *MergeAndRebaseHelper, ) *WorkingTreeHelper { return &WorkingTreeHelper{ c: c, refHelper: refHelper, commitsHelper: commitsHelper, gpgHelper: gpgHelper, mergeAndRebaseHelper: mergeAndRebaseHelper, } } func (self *WorkingTreeHelper) AnyStagedFiles() bool { return AnyStagedFiles(self.c.Model().Files) } func AnyStagedFiles(files []*models.File) bool { return lo.SomeBy(files, func(f *models.File) bool { return f.HasStagedChanges }) } func (self *WorkingTreeHelper) AnyStagedFilesExceptSubmodules() bool { return AnyStagedFilesExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) } func AnyStagedFilesExceptSubmodules(files []*models.File, submoduleConfigs []*models.SubmoduleConfig) bool { return lo.SomeBy(files, func(f *models.File) bool { return f.HasStagedChanges && !f.IsSubmodule(submoduleConfigs) }) } func (self *WorkingTreeHelper) AnyTrackedFiles() bool { return AnyTrackedFiles(self.c.Model().Files) } func AnyTrackedFiles(files []*models.File) bool { return lo.SomeBy(files, func(f *models.File) bool { return f.Tracked }) } func (self *WorkingTreeHelper) AnyTrackedFilesExceptSubmodules() bool { return AnyTrackedFilesExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) } func AnyTrackedFilesExceptSubmodules(files []*models.File, submoduleConfigs []*models.SubmoduleConfig) bool { return lo.SomeBy(files, func(f *models.File) bool { return f.Tracked && !f.IsSubmodule(submoduleConfigs) }) } func isContainedInPath(candidate string, path string) bool { return ( // If the path is the repo root (appears as "/" in the UI), then all candidates are contained in it path == "." || // Exact match; will only be true for files candidate == path || // Match for files within a directory. We need to match the trailing slash to avoid // matching files with longer names. strings.HasPrefix(candidate, path+"/")) } func AnyTrackedFilesInPathExceptSubmodules(path string, files []*models.File, submoduleConfigs []*models.SubmoduleConfig) bool { return lo.SomeBy(files, func(f *models.File) bool { return f.Tracked && isContainedInPath(f.GetPath(), path) && !f.IsSubmodule(submoduleConfigs) }) } func (self *WorkingTreeHelper) IsWorkingTreeDirtyExceptSubmodules() bool { return IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) } func IsWorkingTreeDirtyExceptSubmodules(files []*models.File, submoduleConfigs []*models.SubmoduleConfig) bool { return AnyStagedFilesExceptSubmodules(files, submoduleConfigs) || AnyTrackedFilesExceptSubmodules(files, submoduleConfigs) } func (self *WorkingTreeHelper) FileForSubmodule(submodule *models.SubmoduleConfig) *models.File { for _, file := range self.c.Model().Files { if file.IsSubmodule([]*models.SubmoduleConfig{submodule}) { return file } } return nil } func (self *WorkingTreeHelper) OpenMergeTool() error { self.c.LogAction(self.c.Tr.Actions.OpenMergeTool) return self.c.RunSubprocessAndRefresh( self.c.Git().WorkingTree.OpenMergeToolCmdObj(), ) } func (self *WorkingTreeHelper) HandleCommitPressWithMessage(initialMessage string, forceSkipHooks bool) error { return self.WithEnsureCommittableFiles(func() error { self.commitsHelper.OpenCommitMessagePanel( &OpenCommitMessagePanelOpts{ CommitIndex: context.NoCommitIndex, InitialMessage: initialMessage, SummaryTitle: self.c.Tr.CommitSummaryTitle, DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: true, OnConfirm: func(summary string, description string) error { return self.handleCommit(summary, description, forceSkipHooks) }, OnSwitchToEditor: func(filepath string) error { return self.switchFromCommitMessagePanelToEditor(filepath, forceSkipHooks) }, ForceSkipHooks: forceSkipHooks, SkipHooksPrefix: self.c.UserConfig().Git.SkipHookPrefix, }, ) return nil }) } func (self *WorkingTreeHelper) handleCommit(summary string, description string, forceSkipHooks bool) error { cmdObj := self.c.Git().Commit.CommitCmdObj(summary, description, forceSkipHooks) self.c.LogAction(self.c.Tr.Actions.Commit) return self.gpgHelper.WithGpgHandling(cmdObj, git_commands.CommitGpgSign, self.c.Tr.CommittingStatus, func() error { self.commitsHelper.ClearPreservedCommitMessage() return nil }, nil) } func (self *WorkingTreeHelper) switchFromCommitMessagePanelToEditor(filepath string, forceSkipHooks bool) error { // We won't be able to tell whether the commit was successful, because // RunSubprocessAndRefresh doesn't return the error (it opens an error alert // itself and returns nil on error). But even if we could, we wouldn't have // access to the last message that the user typed, and it might be very // different from what was last in the commit panel. So the best we can do // here is to always clear the remembered commit message. self.commitsHelper.ClearPreservedCommitMessage() self.c.LogAction(self.c.Tr.Actions.Commit) return self.c.RunSubprocessAndRefresh( self.c.Git().Commit.CommitInEditorWithMessageFileCmdObj(filepath, forceSkipHooks), ) } // HandleCommitEditorPress - handle when the user wants to commit changes via // their editor rather than via the popup panel func (self *WorkingTreeHelper) HandleCommitEditorPress() error { return self.WithEnsureCommittableFiles(func() error { // See reasoning in switchFromCommitMessagePanelToEditor for why it makes sense // to clear this message before calling into the editor self.commitsHelper.ClearPreservedCommitMessage() self.c.LogAction(self.c.Tr.Actions.Commit) return self.c.RunSubprocessAndRefresh( self.c.Git().Commit.CommitEditorCmdObj(), ) }) } func (self *WorkingTreeHelper) HandleWIPCommitPress() error { var initialMessage string preservedMessage := self.c.Contexts().CommitMessage.GetPreservedMessageAndLogError() if preservedMessage == "" { // Use the skipHook prefix only if we don't have a preserved message initialMessage = self.c.UserConfig().Git.SkipHookPrefix } return self.HandleCommitPressWithMessage(initialMessage, true) } func (self *WorkingTreeHelper) HandleCommitPress() error { message := self.c.Contexts().CommitMessage.GetPreservedMessageAndLogError() if message == "" { commitPrefixConfigs := self.commitPrefixConfigsForRepo() for _, commitPrefixConfig := range commitPrefixConfigs { prefixPattern := commitPrefixConfig.Pattern if prefixPattern == "" { continue } prefixReplace := commitPrefixConfig.Replace branchName := self.refHelper.GetCheckedOutRef().Name rgx, err := regexp.Compile(prefixPattern) if err != nil { return fmt.Errorf("%s: %s", self.c.Tr.CommitPrefixPatternError, err.Error()) } if rgx.MatchString(branchName) { prefix := rgx.ReplaceAllString(branchName, prefixReplace) message = prefix break } } } return self.HandleCommitPressWithMessage(message, false) } func (self *WorkingTreeHelper) WithEnsureCommittableFiles(handler func() error) error { if err := self.prepareFilesForCommit(); err != nil { return err } if len(self.c.Model().Files) == 0 { return errors.New(self.c.Tr.NoFilesStagedTitle) } if !self.AnyStagedFiles() { return self.promptToStageAllAndRetry(handler) } return handler() } func (self *WorkingTreeHelper) promptToStageAllAndRetry(retry func() error) error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.NoFilesStagedTitle, Prompt: self.c.Tr.NoFilesStagedPrompt, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) if err := self.c.Git().WorkingTree.StageAll(false); err != nil { return err } self.syncRefresh() return retry() }, }) return nil } // for when you need to refetch files before continuing an action. Runs synchronously. func (self *WorkingTreeHelper) syncRefresh() { self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) } func (self *WorkingTreeHelper) prepareFilesForCommit() error { noStagedFiles := !self.AnyStagedFiles() if noStagedFiles && self.c.UserConfig().Gui.SkipNoStagedFilesWarning { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) err := self.c.Git().WorkingTree.StageAll(false) if err != nil { return err } self.syncRefresh() } return nil } func (self *WorkingTreeHelper) commitPrefixConfigsForRepo() []config.CommitPrefixConfig { cfg, ok := self.c.UserConfig().Git.CommitPrefixes[self.c.Git().RepoPaths.RepoName()] if ok { return append(cfg, self.c.UserConfig().Git.CommitPrefix...) } return self.c.UserConfig().Git.CommitPrefix } func (self *WorkingTreeHelper) mergeFile(filepath string, strategy string) (string, error) { if self.c.Git().Version.IsOlderThan(2, 43, 0) { return self.mergeFileWithTempFiles(filepath, strategy) } return self.mergeFileWithObjectIDs(filepath, strategy) } func (self *WorkingTreeHelper) mergeFileWithTempFiles(filepath string, strategy string) (string, error) { showToTempFile := func(stage int, label string) (string, error) { output, err := self.c.Git().WorkingTree.ShowFileAtStage(filepath, stage) if err != nil { return "", err } f, err := os.CreateTemp(self.c.GetConfig().GetTempDir(), "mergefile-"+label+"-*") if err != nil { return "", err } defer f.Close() if _, err := f.Write([]byte(output)); err != nil { return "", err } return f.Name(), nil } baseFilepath, err := showToTempFile(1, "base") if err != nil { return "", err } defer os.Remove(baseFilepath) oursFilepath, err := showToTempFile(2, "ours") if err != nil { return "", err } defer os.Remove(oursFilepath) theirsFilepath, err := showToTempFile(3, "theirs") if err != nil { return "", err } defer os.Remove(theirsFilepath) return self.c.Git().WorkingTree.MergeFileForFiles(strategy, oursFilepath, baseFilepath, theirsFilepath) } func (self *WorkingTreeHelper) mergeFileWithObjectIDs(filepath, strategy string) (string, error) { baseID, err := self.c.Git().WorkingTree.ObjectIDAtStage(filepath, 1) if err != nil { return "", err } oursID, err := self.c.Git().WorkingTree.ObjectIDAtStage(filepath, 2) if err != nil { return "", err } theirsID, err := self.c.Git().WorkingTree.ObjectIDAtStage(filepath, 3) if err != nil { return "", err } return self.c.Git().WorkingTree.MergeFileForObjectIDs(strategy, oursID, baseID, theirsID) } func (self *WorkingTreeHelper) CreateMergeConflictMenu(selectedFilepaths []string) error { onMergeStrategySelected := func(strategy string) error { for _, filepath := range selectedFilepaths { output, err := self.mergeFile(filepath, strategy) if err != nil { return err } if err = os.WriteFile(filepath, []byte(output), 0o644); err != nil { return err } } err := self.c.Git().WorkingTree.StageFiles(selectedFilepaths, nil) self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) return err } cmdColor := style.FgBlue return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.MergeConflictOptionsTitle, Items: []*types.MenuItem{ { LabelColumns: []string{ self.c.Tr.UseCurrentChanges, cmdColor.Sprint("git merge-file --ours"), }, OnPress: func() error { return onMergeStrategySelected("--ours") }, Key: 'c', }, { LabelColumns: []string{ self.c.Tr.UseIncomingChanges, cmdColor.Sprint("git merge-file --theirs"), }, OnPress: func() error { return onMergeStrategySelected("--theirs") }, Key: 'i', }, { LabelColumns: []string{ self.c.Tr.UseBothChanges, cmdColor.Sprint("git merge-file --union"), }, OnPress: func() error { return onMergeStrategySelected("--union") }, Key: 'b', }, { LabelColumns: []string{ self.c.Tr.OpenMergeTool, cmdColor.Sprint("git mergetool"), }, OnPress: self.OpenMergeTool, Key: 'm', }, }, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/suggestions_helper.go
pkg/gui/controllers/helpers/suggestions_helper.go
package helpers import ( "fmt" "strings" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" "golang.org/x/exp/slices" "gopkg.in/ozeidan/fuzzy-patricia.v3/patricia" ) // Thinking out loud: I'm typically a staunch advocate of organising code by feature rather than type, // because colocating code that relates to the same feature means far less effort // to get all the context you need to work on any particular feature. But the one // major benefit of grouping by type is that it makes it makes it less likely that // somebody will re-implement the same logic twice, because they can quickly see // if a certain method has been used for some use case, given that as a starting point // they know about the type. In that vein, I'm including all our functions for // finding suggestions in this file, so that it's easy to see if a function already // exists for fetching a particular model. type SuggestionsHelper struct { c *HelperCommon } func NewSuggestionsHelper( c *HelperCommon, ) *SuggestionsHelper { return &SuggestionsHelper{ c: c, } } func (self *SuggestionsHelper) getRemoteNames() []string { return lo.Map(self.c.Model().Remotes, func(remote *models.Remote, _ int) string { return remote.Name }) } func matchesToSuggestions(matches []string) []*types.Suggestion { return lo.Map(matches, func(match string, _ int) *types.Suggestion { return &types.Suggestion{ Value: match, Label: match, } }) } func (self *SuggestionsHelper) GetRemoteSuggestionsFunc() func(string) []*types.Suggestion { remoteNames := self.getRemoteNames() return FilterFunc(remoteNames, self.c.UserConfig().Gui.UseFuzzySearch()) } func (self *SuggestionsHelper) getBranchNames() []string { return lo.Map(self.c.Model().Branches, func(branch *models.Branch, _ int) string { return branch.Name }) } func (self *SuggestionsHelper) GetBranchNameSuggestionsFunc() func(string) []*types.Suggestion { branchNames := self.getBranchNames() return func(input string) []*types.Suggestion { var matchingBranchNames []string if input == "" { matchingBranchNames = branchNames } else { matchingBranchNames = utils.FilterStrings(input, branchNames, self.c.UserConfig().Gui.UseFuzzySearch()) } return lo.Map(matchingBranchNames, func(branchName string, _ int) *types.Suggestion { return &types.Suggestion{ Value: branchName, Label: presentation.GetBranchTextStyle(branchName).Sprint(branchName), } }) } } // here we asynchronously fetch the latest set of paths in the repo and store in // self.c.Model().FilesTrie. On the main thread we'll be doing a fuzzy search via // self.c.Model().FilesTrie. So if we've looked for a file previously, we'll start with // the old trie and eventually it'll be swapped out for the new one. func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*types.Suggestion { _ = self.c.WithWaitingStatus(self.c.Tr.LoadingFileSuggestions, func(gocui.Task) error { trie := patricia.NewTrie() // load every file in the repo files, err := self.c.Git().WorkingTree.AllRepoFiles() if err != nil { return err } seen := set.New[string]() for _, file := range files { // For every file we also want to add its parent directories, but only once. for i := range len(file) { if file[i] == '/' { dir := file[:i] if !seen.Includes(dir) { trie.Insert(patricia.Prefix(dir), dir) seen.Add(dir) } } } trie.Insert(patricia.Prefix(file), file) } // cache the trie for future use self.c.Model().FilesTrie = trie self.c.Contexts().Suggestions.RefreshSuggestions() return err }) return func(input string) []*types.Suggestion { matchingNames := []string{} if self.c.UserConfig().Gui.UseFuzzySearch() { _ = self.c.Model().FilesTrie.VisitFuzzy(patricia.Prefix(input), true, func(prefix patricia.Prefix, item patricia.Item, skipped int) error { matchingNames = append(matchingNames, item.(string)) return nil }) // doing another fuzzy search for good measure matchingNames = utils.FilterStrings(input, matchingNames, true) } else { substrings := strings.Fields(input) _ = self.c.Model().FilesTrie.Visit(func(prefix patricia.Prefix, item patricia.Item) error { for _, sub := range substrings { if !utils.CaseAwareContains(item.(string), sub) { return nil } } matchingNames = append(matchingNames, item.(string)) return nil }) } return matchesToSuggestions(matchingNames) } } func (self *SuggestionsHelper) getRemoteBranchNames(separator string) []string { return lo.FlatMap(self.c.Model().Remotes, func(remote *models.Remote, _ int) []string { return lo.Map(remote.Branches, func(branch *models.RemoteBranch, _ int) string { return fmt.Sprintf("%s%s%s", remote.Name, separator, branch.Name) }) }) } func (self *SuggestionsHelper) getRemoteBranchNamesForRemote(remoteName string) []string { remote, ok := lo.Find(self.c.Model().Remotes, func(remote *models.Remote) bool { return remote.Name == remoteName }) if ok { return lo.Map(remote.Branches, func(branch *models.RemoteBranch, _ int) string { return branch.Name }) } return nil } func (self *SuggestionsHelper) GetRemoteBranchesSuggestionsFunc(separator string) func(string) []*types.Suggestion { return FilterFunc(self.getRemoteBranchNames(separator), self.c.UserConfig().Gui.UseFuzzySearch()) } func (self *SuggestionsHelper) GetRemoteBranchesForRemoteSuggestionsFunc(remoteName string) func(string) []*types.Suggestion { return FilterFunc(self.getRemoteBranchNamesForRemote(remoteName), self.c.UserConfig().Gui.UseFuzzySearch()) } func (self *SuggestionsHelper) getTagNames() []string { return lo.Map(self.c.Model().Tags, func(tag *models.Tag, _ int) string { return tag.Name }) } func (self *SuggestionsHelper) GetTagsSuggestionsFunc() func(string) []*types.Suggestion { tagNames := self.getTagNames() return FilterFunc(tagNames, self.c.UserConfig().Gui.UseFuzzySearch()) } func (self *SuggestionsHelper) GetRefsSuggestionsFunc() func(string) []*types.Suggestion { remoteBranchNames := self.getRemoteBranchNames("/") localBranchNames := self.getBranchNames() tagNames := self.getTagNames() additionalRefNames := []string{"HEAD", "FETCH_HEAD", "MERGE_HEAD", "ORIG_HEAD"} refNames := append(append(append(remoteBranchNames, localBranchNames...), tagNames...), additionalRefNames...) return FilterFunc(refNames, self.c.UserConfig().Gui.UseFuzzySearch()) } func (self *SuggestionsHelper) GetAuthorsSuggestionsFunc() func(string) []*types.Suggestion { authors := lo.Map(lo.Values(self.c.Model().Authors), func(author *models.Author, _ int) string { return author.Combined() }) slices.Sort(authors) return FilterFunc(authors, self.c.UserConfig().Gui.UseFuzzySearch()) } func FilterFunc(options []string, useFuzzySearch bool) func(string) []*types.Suggestion { return func(input string) []*types.Suggestion { var matches []string if input == "" { matches = options } else { matches = utils.FilterStrings(input, options, useFuzzySearch) } return matchesToSuggestions(matches) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/repos_helper.go
pkg/gui/controllers/helpers/repos_helper.go
package helpers import ( "errors" "fmt" "os" "path/filepath" "strings" "sync" "github.com/jesseduffield/gocui" appTypes "github.com/jesseduffield/lazygit/pkg/app/types" "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/env" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/presentation/icons" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type onNewRepoFn func(startArgs appTypes.StartArgs, contextKey types.ContextKey) error // helps switch back and forth between repos type ReposHelper struct { c *HelperCommon recordDirectoryHelper *RecordDirectoryHelper onNewRepo onNewRepoFn } func NewRecentReposHelper( c *HelperCommon, recordDirectoryHelper *RecordDirectoryHelper, onNewRepo onNewRepoFn, ) *ReposHelper { return &ReposHelper{ c: c, recordDirectoryHelper: recordDirectoryHelper, onNewRepo: onNewRepo, } } func (self *ReposHelper) EnterSubmodule(submodule *models.SubmoduleConfig) error { wd, err := os.Getwd() if err != nil { return err } self.c.State().GetRepoPathStack().Push(wd) return self.DispatchSwitchToRepo(submodule.FullPath(), context.NO_CONTEXT) } func (self *ReposHelper) getCurrentBranch(path string) string { readHeadFile := func(path string) (string, error) { headFile, err := os.ReadFile(filepath.Join(path, "HEAD")) if err == nil { content := strings.TrimSpace(string(headFile)) refsPrefix := "ref: refs/heads/" var branchDisplay string if bareName, ok := strings.CutPrefix(content, refsPrefix); ok { // is a branch branchDisplay = bareName } else { // detached HEAD state, displaying short hash branchDisplay = utils.ShortHash(content) } return branchDisplay, nil } return "", err } gitDirPath := filepath.Join(path, ".git") if gitDir, err := os.Stat(gitDirPath); err == nil { if gitDir.IsDir() { // ordinary repo if branch, err := readHeadFile(gitDirPath); err == nil { return branch } } else { // worktree if worktreeGitDir, err := os.ReadFile(gitDirPath); err == nil { content := strings.TrimSpace(string(worktreeGitDir)) worktreePath := strings.TrimPrefix(content, "gitdir: ") if branch, err := readHeadFile(worktreePath); err == nil { return branch } } } } return self.c.Tr.BranchUnknown } func (self *ReposHelper) CreateRecentReposMenu() error { // we'll show an empty panel if there are no recent repos recentRepoPaths := []string{} if len(self.c.GetAppState().RecentRepos) > 0 { // we skip the first one because we're currently in it recentRepoPaths = self.c.GetAppState().RecentRepos[1:] } currentBranches := sync.Map{} wg := sync.WaitGroup{} wg.Add(len(recentRepoPaths)) for _, path := range recentRepoPaths { go func(path string) { defer wg.Done() currentBranches.Store(path, self.getCurrentBranch(path)) }(path) } wg.Wait() menuItems := lo.Map(recentRepoPaths, func(path string, _ int) *types.MenuItem { branchName, _ := currentBranches.Load(path) if icons.IsIconEnabled() { branchName = icons.BRANCH_ICON + " " + fmt.Sprintf("%v", branchName) } return &types.MenuItem{ LabelColumns: []string{ filepath.Base(path), style.FgCyan.Sprint(branchName), style.FgMagenta.Sprint(path), }, OnPress: func() error { // if we were in a submodule, we want to forget about that stack of repos // so that hitting escape in the new repo does nothing self.c.State().GetRepoPathStack().Clear() return self.DispatchSwitchToRepo(path, context.NO_CONTEXT) }, } }) return self.c.Menu(types.CreateMenuOptions{Title: self.c.Tr.RecentRepos, Items: menuItems}) } func (self *ReposHelper) DispatchSwitchToRepo(path string, contextKey types.ContextKey) error { return self.DispatchSwitchTo(path, self.c.Tr.ErrRepositoryMovedOrDeleted, contextKey) } func (self *ReposHelper) DispatchSwitchTo(path string, errMsg string, contextKey types.ContextKey) error { return self.c.WithWaitingStatus(self.c.Tr.Switching, func(gocui.Task) error { env.UnsetGitLocationEnvVars() originalPath, err := os.Getwd() if err != nil { return nil } msg := utils.ResolvePlaceholderString(self.c.Tr.ChangingDirectoryTo, map[string]string{"path": path}) self.c.LogCommand(msg, false) if err := os.Chdir(path); err != nil { if os.IsNotExist(err) { return errors.New(errMsg) } return err } if err := commands.VerifyInGitRepo(self.c.OS()); err != nil { if err := os.Chdir(originalPath); err != nil { return err } return err } if err := self.recordDirectoryHelper.RecordCurrentDirectory(); err != nil { return err } self.c.Mutexes().RefreshingFilesMutex.Lock() defer self.c.Mutexes().RefreshingFilesMutex.Unlock() return self.onNewRepo(appTypes.StartArgs{}, contextKey) }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/merge_and_rebase_helper.go
pkg/gui/controllers/helpers/merge_and_rebase_helper.go
package helpers import ( "errors" "fmt" "os" "path/filepath" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" "github.com/stefanhaller/git-todo-parser/todo" ) type MergeAndRebaseHelper struct { c *HelperCommon } func NewMergeAndRebaseHelper( c *HelperCommon, ) *MergeAndRebaseHelper { return &MergeAndRebaseHelper{ c: c, } } type RebaseOption string const ( REBASE_OPTION_CONTINUE string = "continue" REBASE_OPTION_ABORT string = "abort" REBASE_OPTION_SKIP string = "skip" ) func (self *MergeAndRebaseHelper) CreateRebaseOptionsMenu() error { type optionAndKey struct { option string key types.Key } options := []optionAndKey{ {option: REBASE_OPTION_CONTINUE, key: 'c'}, {option: REBASE_OPTION_ABORT, key: 'a'}, } if self.c.Git().Status.WorkingTreeState().CanSkip() { options = append(options, optionAndKey{ option: REBASE_OPTION_SKIP, key: 's', }) } menuItems := lo.Map(options, func(row optionAndKey, _ int) *types.MenuItem { return &types.MenuItem{ Label: row.option, OnPress: func() error { return self.genericMergeCommand(row.option) }, Key: row.key, } }) title := self.c.Git().Status.WorkingTreeState().OptionsMenuTitle(self.c.Tr) return self.c.Menu(types.CreateMenuOptions{Title: title, Items: menuItems}) } func (self *MergeAndRebaseHelper) ContinueRebase() error { return self.genericMergeCommand(REBASE_OPTION_CONTINUE) } func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { status := self.c.Git().Status.WorkingTreeState() if status.None() { return errors.New(self.c.Tr.NotMergingOrRebasing) } self.c.LogAction(fmt.Sprintf("Merge/Rebase: %s", command)) effectiveStatus := status.Effective() if effectiveStatus == models.WORKING_TREE_STATE_REBASING { todoFile, err := os.ReadFile( filepath.Join(self.c.Git().RepoPaths.WorktreeGitDirPath(), "rebase-merge/git-rebase-todo"), ) if err != nil { if !os.IsNotExist(err) { return err } } else { self.c.LogCommand(string(todoFile), false) } } commandType := status.CommandName() // we should end up with a command like 'git merge --continue' // it's impossible for a rebase to require a commit so we'll use a subprocess only if it's a merge needsSubprocess := (effectiveStatus == models.WORKING_TREE_STATE_MERGING && command != REBASE_OPTION_ABORT && self.c.UserConfig().Git.Merging.ManualCommit) || // but we'll also use a subprocess if we have exec todos; those are likely to be lengthy build // tasks whose output the user will want to see in the terminal (effectiveStatus == models.WORKING_TREE_STATE_REBASING && command != REBASE_OPTION_ABORT && self.hasExecTodos()) if needsSubprocess { // TODO: see if we should be calling more of the code from self.Git.Rebase.GenericMergeOrRebaseAction return self.c.RunSubprocessAndRefresh( self.c.Git().Rebase.GenericMergeOrRebaseActionCmdObj(commandType, command), ) } result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) if err := self.CheckMergeOrRebase(result); err != nil { return err } return nil } func (self *MergeAndRebaseHelper) hasExecTodos() bool { for _, commit := range self.c.Model().Commits { if !commit.IsTODO() { break } if commit.Action == todo.Exec { return true } } return false } var conflictStrings = []string{ "Failed to merge in the changes", "When you have resolved this problem", "fix conflicts", "Resolve all conflicts manually", "Merge conflict in file", "hint: after resolving the conflicts", "CONFLICT (content):", } func isMergeConflictErr(errStr string) bool { for _, str := range conflictStrings { if strings.Contains(errStr, str) { return true } } return false } func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result error, refreshOptions types.RefreshOptions) error { self.c.Refresh(refreshOptions) if result == nil { return nil } else if strings.Contains(result.Error(), "No changes - did you forget to use") { return self.genericMergeCommand(REBASE_OPTION_SKIP) } else if strings.Contains(result.Error(), "The previous cherry-pick is now empty") { return self.genericMergeCommand(REBASE_OPTION_SKIP) } else if strings.Contains(result.Error(), "No rebase in progress?") { // assume in this case that we're already done return nil } return self.CheckForConflicts(result) } func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { return self.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.ASYNC}) } func (self *MergeAndRebaseHelper) CheckForConflicts(result error) error { if result == nil { return nil } if isMergeConflictErr(result.Error()) { return self.PromptForConflictHandling() } return result } func (self *MergeAndRebaseHelper) PromptForConflictHandling() error { mode := self.c.Git().Status.WorkingTreeState().CommandName() return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.FoundConflictsTitle, Items: []*types.MenuItem{ { Label: self.c.Tr.ViewConflictsMenuItem, OnPress: func() error { self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) return nil }, }, { Label: fmt.Sprintf(self.c.Tr.AbortMenuItem, mode), OnPress: func() error { return self.genericMergeCommand(REBASE_OPTION_ABORT) }, Key: 'a', }, }, HideCancel: true, }) } func (self *MergeAndRebaseHelper) AbortMergeOrRebaseWithConfirm() error { // prompt user to confirm that they want to abort, then do it mode := self.c.Git().Status.WorkingTreeState().CommandName() self.c.Confirm(types.ConfirmOpts{ Title: fmt.Sprintf(self.c.Tr.AbortTitle, mode), Prompt: fmt.Sprintf(self.c.Tr.AbortPrompt, mode), HandleConfirm: func() error { return self.genericMergeCommand(REBASE_OPTION_ABORT) }, }) return nil } // PromptToContinueRebase asks the user if they want to continue the rebase/merge that's in progress func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Continue, Prompt: fmt.Sprintf(self.c.Tr.ConflictsResolved, self.c.Git().Status.WorkingTreeState().CommandName()), HandleConfirm: func() error { // By the time we get here, we might have unstaged changes again, // e.g. if the user had to fix build errors after resolving the // conflicts, but after lazygit opened the prompt already. Ask again // to auto-stage these. // Need to refresh the files to be really sure if this is the case. // We would otherwise be relying on lazygit's auto-refresh on focus, // but this is not supported by all terminals or on all platforms. self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}, }) root := self.c.Contexts().Files.FileTreeViewModel.GetRoot() if root.GetHasUnstagedChanges() { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Continue, Prompt: self.c.Tr.UnstagedFilesAfterConflictsResolved, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.StageAllFiles) if err := self.c.Git().WorkingTree.StageAll(true); err != nil { return err } return self.genericMergeCommand(REBASE_OPTION_CONTINUE) }, }) return nil } return self.genericMergeCommand(REBASE_OPTION_CONTINUE) }, }) return nil } func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { checkedOutBranch := self.c.Model().Branches[0] checkedOutBranchName := checkedOutBranch.Name var disabledReason, baseBranchDisabledReason *types.DisabledReason if checkedOutBranchName == ref { disabledReason = &types.DisabledReason{Text: self.c.Tr.CantRebaseOntoSelf} } baseBranch, err := self.c.Git().Loaders.BranchLoader.GetBaseBranch(checkedOutBranch, self.c.Model().MainBranches) if err != nil { return err } if baseBranch == "" { baseBranch = self.c.Tr.CouldNotDetermineBaseBranch baseBranchDisabledReason = &types.DisabledReason{Text: self.c.Tr.CouldNotDetermineBaseBranch} } menuItems := []*types.MenuItem{ { Label: utils.ResolvePlaceholderString(self.c.Tr.SimpleRebase, map[string]string{"ref": ref}, ), Key: 's', DisabledReason: disabledReason, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.RebaseBranchFromBaseCommit(ref, baseCommit) } else { err = self.c.Git().Rebase.RebaseBranch(ref) } err = self.CheckMergeOrRebase(err) if err == nil { return self.ResetMarkedBaseCommit() } return err }) }, }, { Label: utils.ResolvePlaceholderString(self.c.Tr.InteractiveRebase, map[string]string{"ref": ref}, ), Key: 'i', DisabledReason: disabledReason, Tooltip: self.c.Tr.InteractiveRebaseTooltip, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.EditRebaseFromBaseCommit(ref, baseCommit) } else { err = self.c.Git().Rebase.EditRebase(ref) } if err = self.CheckMergeOrRebase(err); err != nil { return err } if err = self.ResetMarkedBaseCommit(); err != nil { return err } self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) return nil }, }, { Label: utils.ResolvePlaceholderString(self.c.Tr.RebaseOntoBaseBranch, map[string]string{"baseBranch": ShortBranchName(baseBranch)}, ), Key: 'b', DisabledReason: baseBranchDisabledReason, Tooltip: self.c.Tr.RebaseOntoBaseBranchTooltip, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.RebaseBranchFromBaseCommit(baseBranch, baseCommit) } else { err = self.c.Git().Rebase.RebaseBranch(baseBranch) } err = self.CheckMergeOrRebase(err) if err == nil { return self.ResetMarkedBaseCommit() } return err }) }, }, } title := utils.ResolvePlaceholderString( lo.Ternary(self.c.Modes().MarkedBaseCommit.GetHash() != "", self.c.Tr.RebasingFromBaseCommitTitle, self.c.Tr.RebasingTitle), map[string]string{ "checkedOutBranch": checkedOutBranchName, }, ) return self.c.Menu(types.CreateMenuOptions{ Title: title, Items: menuItems, }) } func (self *MergeAndRebaseHelper) MergeRefIntoCheckedOutBranch(refName string) error { if self.c.Git().Branch.IsHeadDetached() { return errors.New("Cannot merge branch in detached head state. You might have checked out a commit directly or a remote branch, in which case you should checkout the local branch you want to be on") } checkedOutBranchName := self.c.Model().Branches[0].Name if checkedOutBranchName == refName { return errors.New(self.c.Tr.CantMergeBranchIntoItself) } wantFastForward, wantNonFastForward := self.fastForwardMergeUserPreference() canFastForward := self.c.Git().Branch.CanDoFastForwardMerge(refName) var firstRegularMergeItem *types.MenuItem var secondRegularMergeItem *types.MenuItem var fastForwardMergeItem *types.MenuItem if !wantNonFastForward && (wantFastForward || canFastForward) { firstRegularMergeItem = &types.MenuItem{ Label: self.c.Tr.RegularMergeFastForward, OnPress: self.RegularMerge(refName, git_commands.MERGE_VARIANT_REGULAR), Key: 'm', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.RegularMergeFastForwardTooltip, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), } fastForwardMergeItem = firstRegularMergeItem secondRegularMergeItem = &types.MenuItem{ Label: self.c.Tr.RegularMergeNonFastForward, OnPress: self.RegularMerge(refName, git_commands.MERGE_VARIANT_NON_FAST_FORWARD), Key: 'n', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.RegularMergeNonFastForwardTooltip, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), } } else { firstRegularMergeItem = &types.MenuItem{ Label: self.c.Tr.RegularMergeNonFastForward, OnPress: self.RegularMerge(refName, git_commands.MERGE_VARIANT_REGULAR), Key: 'm', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.RegularMergeNonFastForwardTooltip, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), } secondRegularMergeItem = &types.MenuItem{ Label: self.c.Tr.RegularMergeFastForward, OnPress: self.RegularMerge(refName, git_commands.MERGE_VARIANT_FAST_FORWARD), Key: 'f', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.RegularMergeFastForwardTooltip, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), } fastForwardMergeItem = secondRegularMergeItem } if !canFastForward { fastForwardMergeItem.DisabledReason = &types.DisabledReason{ Text: utils.ResolvePlaceholderString( self.c.Tr.CannotFastForwardMerge, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), } } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.Merge, Items: []*types.MenuItem{ firstRegularMergeItem, secondRegularMergeItem, { Label: self.c.Tr.SquashMergeUncommitted, OnPress: self.SquashMergeUncommitted(refName), Key: 's', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.SquashMergeUncommittedTooltip, map[string]string{ "selectedBranch": refName, }, ), }, { Label: self.c.Tr.SquashMergeCommitted, OnPress: self.SquashMergeCommitted(refName, checkedOutBranchName), Key: 'S', Tooltip: utils.ResolvePlaceholderString( self.c.Tr.SquashMergeCommittedTooltip, map[string]string{ "checkedOutBranch": checkedOutBranchName, "selectedBranch": refName, }, ), }, }, }) } func (self *MergeAndRebaseHelper) RegularMerge(refName string, variant git_commands.MergeVariant) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.Merge) err := self.c.Git().Branch.Merge(refName, variant) return self.CheckMergeOrRebase(err) } } func (self *MergeAndRebaseHelper) SquashMergeUncommitted(refName string) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.SquashMerge) err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) return self.CheckMergeOrRebase(err) } } func (self *MergeAndRebaseHelper) SquashMergeCommitted(refName, checkedOutBranchName string) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.SquashMerge) err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) if err = self.CheckMergeOrRebase(err); err != nil { return err } message := utils.ResolvePlaceholderString(self.c.UserConfig().Git.Merging.SquashMergeMessage, map[string]string{ "selectedRef": refName, "currentBranch": checkedOutBranchName, }) err = self.c.Git().Commit.CommitCmdObj(message, "", false).Run() if err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil } } // Returns wantsFastForward, wantsNonFastForward. These will never both be true, but they can both be false. func (self *MergeAndRebaseHelper) fastForwardMergeUserPreference() (bool, bool) { // Check user config first, because it takes precedence over git config mergingArgs := self.c.UserConfig().Git.Merging.Args if strings.Contains(mergingArgs, "--ff") { // also covers "--ff-only" return true, false } if strings.Contains(mergingArgs, "--no-ff") { return false, true } // Then check git config mergeFfConfig := self.c.Git().Config.GetMergeFF() if mergeFfConfig == "true" || mergeFfConfig == "only" { return true, false } if mergeFfConfig == "false" { return false, true } return false, false } func (self *MergeAndRebaseHelper) ResetMarkedBaseCommit() error { self.c.Modes().MarkedBaseCommit.Reset() self.c.PostRefreshUpdate(self.c.Contexts().LocalCommits) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/cherry_pick_helper.go
pkg/gui/controllers/helpers/cherry_pick_helper.go
package helpers import ( "strconv" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type CherryPickHelper struct { c *HelperCommon rebaseHelper *MergeAndRebaseHelper } // I'm using the analogy of copy+paste in the terminology here because it's intuitively what's going on, // even if in truth we're running git cherry-pick func NewCherryPickHelper( c *HelperCommon, rebaseHelper *MergeAndRebaseHelper, ) *CherryPickHelper { return &CherryPickHelper{ c: c, rebaseHelper: rebaseHelper, } } func (self *CherryPickHelper) getData() *cherrypicking.CherryPicking { return self.c.Modes().CherryPicking } func (self *CherryPickHelper) CopyRange(commitsList []*models.Commit, context types.IListContext) error { startIdx, endIdx := context.GetList().GetSelectionRange() if err := self.resetIfNecessary(context); err != nil { return err } commitSet := self.getData().SelectedHashSet() allCommitsCopied := lo.EveryBy(commitsList[startIdx:endIdx+1], func(commit *models.Commit) bool { return commitSet.Includes(commit.Hash()) }) // if all selected commits are already copied, we'll uncopy them if allCommitsCopied { for index := startIdx; index <= endIdx; index++ { commit := commitsList[index] self.getData().Remove(commit, commitsList) } } else { for index := startIdx; index <= endIdx; index++ { commit := commitsList[index] self.getData().Add(commit, commitsList) } } self.getData().DidPaste = false self.rerender() return nil } // HandlePasteCommits begins a cherry-pick rebase with the commits the user has copied. // Only to be called from the branch commits controller func (self *CherryPickHelper) Paste() error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.CherryPick, Prompt: utils.ResolvePlaceholderString( self.c.Tr.SureCherryPick, map[string]string{ "numCommits": strconv.Itoa(len(self.getData().CherryPickedCommits)), }), HandleConfirm: func() error { return self.c.WithWaitingStatusSync(self.c.Tr.CherryPickingStatus, func() error { mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) self.c.LogAction(self.c.Tr.Actions.CherryPick) if mustStash { if err := self.c.Git().Stash.Push(self.c.Tr.AutoStashForCherryPicking); err != nil { return err } } cherryPickedCommits := self.getData().CherryPickedCommits result := self.c.Git().Rebase.CherryPickCommits(cherryPickedCommits) err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.SYNC}) if err != nil { return result } // Move the selection down by the number of commits we just // cherry-picked, to keep the same commit selected as before. // Don't do this if a rebase todo is selected, because in this // case we are in a rebase and the cherry-picked commits end up // below the selection. if commit := self.c.Contexts().LocalCommits.GetSelected(); commit != nil && !commit.IsTODO() { self.c.Contexts().LocalCommits.MoveSelection(len(cherryPickedCommits)) self.c.Contexts().LocalCommits.FocusLine(true) } // If we're in the cherry-picking state at this point, it must // be because there were conflicts. Don't clear the copied // commits in this case, since we might want to abort and try // pasting them again. isInCherryPick, result := self.c.Git().Status.IsInCherryPick() if result != nil { return result } if !isInCherryPick { self.getData().DidPaste = true self.rerender() if mustStash { if err := self.c.Git().Stash.Pop(0); err != nil { return err } self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.STASH, types.FILES}, }) } } return nil }) }, }) return nil } func (self *CherryPickHelper) CanPaste() bool { return self.getData().CanPaste() } func (self *CherryPickHelper) Reset() error { self.getData().ContextKey = "" self.getData().CherryPickedCommits = nil self.rerender() return nil } // you can only copy from one context at a time, because the order and position of commits matter func (self *CherryPickHelper) resetIfNecessary(context types.Context) error { oldContextKey := types.ContextKey(self.getData().ContextKey) if oldContextKey != context.GetKey() { // need to reset the cherry picking mode self.getData().ContextKey = string(context.GetKey()) self.getData().CherryPickedCommits = make([]*models.Commit, 0) } return nil } func (self *CherryPickHelper) rerender() { for _, context := range []types.Context{ self.c.Contexts().LocalCommits, self.c.Contexts().ReflogCommits, self.c.Contexts().SubCommits, } { self.c.PostRefreshUpdate(context) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/branches_helper.go
pkg/gui/controllers/helpers/branches_helper.go
package helpers import ( "errors" "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type BranchesHelper struct { c *HelperCommon worktreeHelper *WorktreeHelper } func NewBranchesHelper(c *HelperCommon, worktreeHelper *WorktreeHelper) *BranchesHelper { return &BranchesHelper{ c: c, worktreeHelper: worktreeHelper, } } func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error { if len(branches) > 1 { if lo.SomeBy(branches, func(branch *models.Branch) bool { return self.checkedOutByOtherWorktree(branch) }) { return errors.New(self.c.Tr.SomeBranchesCheckedOutByWorktreeError) } } else if self.checkedOutByOtherWorktree(branches[0]) { return self.promptWorktreeBranchDelete(branches[0]) } allBranchesMerged, err := self.allBranchesMerged(branches) if err != nil { return err } doDelete := func() error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(_ gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteLocalBranch) branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.Name }) if err := self.c.Git().Branch.LocalDelete(branchNames, true); err != nil { return err } self.c.Contexts().Branches.CollapseRangeSelectionToTop() self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return nil }) } if allBranchesMerged { return doDelete() } title := self.c.Tr.ForceDeleteBranchTitle var message string if len(branches) == 1 { message = utils.ResolvePlaceholderString( self.c.Tr.ForceDeleteBranchMessage, map[string]string{ "selectedBranchName": branches[0].Name, }, ) } else { message = self.c.Tr.ForceDeleteBranchesMessage } self.c.Confirm(types.ConfirmOpts{ Title: title, Prompt: message, HandleConfirm: func() error { return doDelete() }, }) return nil } func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteBranch, resetRemoteBranchesSelection bool) error { var title string if len(remoteBranches) == 1 { title = utils.ResolvePlaceholderString( self.c.Tr.DeleteBranchTitle, map[string]string{ "selectedBranchName": remoteBranches[0].Name, }, ) } else { title = self.c.Tr.DeleteBranchesTitle } var prompt string if len(remoteBranches) == 1 { prompt = utils.ResolvePlaceholderString( self.c.Tr.DeleteRemoteBranchPrompt, map[string]string{ "selectedBranchName": remoteBranches[0].Name, "upstream": remoteBranches[0].RemoteName, }, ) } else { prompt = self.c.Tr.DeleteRemoteBranchesPrompt } self.c.Confirm(types.ConfirmOpts{ Title: title, Prompt: prompt, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(task gocui.Task) error { if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { return err } self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) if resetRemoteBranchesSelection { self.c.Contexts().RemoteBranches.CollapseRangeSelectionToTop() } return nil }) }, }) return nil } func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branch) error { if lo.SomeBy(branches, func(branch *models.Branch) bool { return self.checkedOutByOtherWorktree(branch) }) { return errors.New(self.c.Tr.SomeBranchesCheckedOutByWorktreeError) } allBranchesMerged, err := self.allBranchesMerged(branches) if err != nil { return err } var prompt string if len(branches) == 1 { prompt = utils.ResolvePlaceholderString( self.c.Tr.DeleteLocalAndRemoteBranchPrompt, map[string]string{ "localBranchName": branches[0].Name, "remoteBranchName": branches[0].UpstreamBranch, "remoteName": branches[0].UpstreamRemote, }, ) } else { prompt = self.c.Tr.DeleteLocalAndRemoteBranchesPrompt } if !allBranchesMerged { if len(branches) == 1 { prompt += "\n\n" + utils.ResolvePlaceholderString( self.c.Tr.ForceDeleteBranchMessage, map[string]string{ "selectedBranchName": branches[0].Name, }, ) } else { prompt += "\n\n" + self.c.Tr.ForceDeleteBranchesMessage } } self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.DeleteLocalAndRemoteBranch, Prompt: prompt, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(task gocui.Task) error { // Delete the remote branches first so that we keep the local ones // in case of failure remoteBranches := lo.Map(branches, func(branch *models.Branch, _ int) *models.RemoteBranch { return &models.RemoteBranch{Name: branch.UpstreamBranch, RemoteName: branch.UpstreamRemote} }) if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { return err } self.c.LogAction(self.c.Tr.Actions.DeleteLocalBranch) branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.Name }) if err := self.c.Git().Branch.LocalDelete(branchNames, true); err != nil { return err } self.c.Contexts().Branches.CollapseRangeSelectionToTop() self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }) }, }) return nil } func ShortBranchName(fullBranchName string) string { return strings.TrimPrefix(strings.TrimPrefix(fullBranchName, "refs/heads/"), "refs/remotes/") } func (self *BranchesHelper) checkedOutByOtherWorktree(branch *models.Branch) bool { return git_commands.CheckedOutByOtherWorktree(branch, self.c.Model().Worktrees) } func (self *BranchesHelper) worktreeForBranch(branch *models.Branch) (*models.Worktree, bool) { return git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees) } func (self *BranchesHelper) promptWorktreeBranchDelete(selectedBranch *models.Branch) error { worktree, ok := self.worktreeForBranch(selectedBranch) if !ok { self.c.Log.Error("promptWorktreeBranchDelete out of sync with list of worktrees") return nil } title := utils.ResolvePlaceholderString(self.c.Tr.BranchCheckedOutByWorktree, map[string]string{ "worktreeName": worktree.Name, "branchName": selectedBranch.Name, }) return self.c.Menu(types.CreateMenuOptions{ Title: title, Items: []*types.MenuItem{ { Label: self.c.Tr.SwitchToWorktree, OnPress: func() error { return self.worktreeHelper.Switch(worktree, context.LOCAL_BRANCHES_CONTEXT_KEY) }, }, { Label: self.c.Tr.DetachWorktree, Tooltip: self.c.Tr.DetachWorktreeTooltip, OnPress: func() error { return self.worktreeHelper.Detach(worktree) }, }, { Label: self.c.Tr.RemoveWorktree, OnPress: func() error { return self.worktreeHelper.Remove(worktree, false) }, }, }, }) } func (self *BranchesHelper) allBranchesMerged(branches []*models.Branch) (bool, error) { allBranchesMerged := true for _, branch := range branches { isMerged, err := self.c.Git().Branch.IsBranchMerged(branch, self.c.Model().MainBranches) if err != nil { return false, err } if !isMerged { allBranchesMerged = false break } } return allBranchesMerged, nil } func (self *BranchesHelper) deleteRemoteBranches(remoteBranches []*models.RemoteBranch, task gocui.Task) error { remotes := lo.GroupBy(remoteBranches, func(branch *models.RemoteBranch) string { return branch.RemoteName }) for remote, branches := range remotes { self.c.LogAction(self.c.Tr.Actions.DeleteRemoteBranch) branchNames := lo.Map(branches, func(branch *models.RemoteBranch, _ int) string { return branch.Name }) if err := self.c.Git().Remote.DeleteRemoteBranch(task, remote, branchNames); err != nil { return err } } return nil } func (self *BranchesHelper) AutoForwardBranches() error { if self.c.UserConfig().Git.AutoForwardBranches == "none" { return nil } branches := self.c.Model().Branches if len(branches) == 0 { return nil } allBranches := self.c.UserConfig().Git.AutoForwardBranches == "allBranches" updateCommands := "" // The first branch is the currently checked out branch; skip it for _, branch := range branches[1:] { if branch.RemoteBranchStoredLocally() && !self.checkedOutByOtherWorktree(branch) && (allBranches || lo.Contains(self.c.UserConfig().Git.MainBranches, branch.Name)) { isStrictlyBehind := branch.IsBehindForPull() && !branch.IsAheadForPull() if isStrictlyBehind { updateCommands += fmt.Sprintf("update %s %s %s\n", branch.FullRefName(), branch.FullUpstreamRefName(), branch.CommitHash) } } } if updateCommands == "" { return nil } self.c.LogAction(self.c.Tr.Actions.AutoForwardBranches) self.c.LogCommand(strings.TrimRight(updateCommands, "\n"), false) err := self.c.Git().Branch.UpdateBranchRefs(updateCommands) self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Mode: types.SYNC}) return err }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/inline_status_helper.go
pkg/gui/controllers/helpers/inline_status_helper.go
package helpers import ( "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/sasha-s/go-deadlock" ) type InlineStatusHelper struct { c *HelperCommon windowHelper *WindowHelper contextsWithInlineStatus map[types.ContextKey]*inlineStatusInfo mutex deadlock.Mutex } func NewInlineStatusHelper(c *HelperCommon, windowHelper *WindowHelper) *InlineStatusHelper { return &InlineStatusHelper{ c: c, windowHelper: windowHelper, contextsWithInlineStatus: make(map[types.ContextKey]*inlineStatusInfo), } } type InlineStatusOpts struct { Item types.HasUrn Operation types.ItemOperation ContextKey types.ContextKey } type inlineStatusInfo struct { refCount int stop chan struct{} } // A custom task for WithInlineStatus calls; it wraps the original one and // hides the status whenever the task is paused, and shows it again when // continued. type inlineStatusHelperTask struct { gocui.Task inlineStatusHelper *InlineStatusHelper opts InlineStatusOpts } // poor man's version of explicitly saying that struct X implements interface Y var _ gocui.Task = inlineStatusHelperTask{} func (self inlineStatusHelperTask) Pause() { self.inlineStatusHelper.stop(self.opts) self.Task.Pause() self.inlineStatusHelper.renderContext(self.opts.ContextKey) } func (self inlineStatusHelperTask) Continue() { self.Task.Continue() self.inlineStatusHelper.start(self.opts) } func (self *InlineStatusHelper) WithInlineStatus(opts InlineStatusOpts, f func(gocui.Task) error) { context := self.c.ContextForKey(opts.ContextKey).(types.IListContext) view := context.GetView() visible := view.Visible && self.windowHelper.TopViewInWindow(context.GetWindowName(), false) == view if visible && context.IsItemVisible(opts.Item) { self.c.OnWorker(func(task gocui.Task) error { self.start(opts) defer self.stop(opts) return f(inlineStatusHelperTask{task, self, opts}) }) } else { message := presentation.ItemOperationToString(opts.Operation, self.c.Tr) _ = self.c.WithWaitingStatus(message, func(t gocui.Task) error { // We still need to set the item operation, because it might be used // for other (non-presentation) purposes self.c.State().SetItemOperation(opts.Item, opts.Operation) defer self.c.State().ClearItemOperation(opts.Item) return f(t) }) } } func (self *InlineStatusHelper) start(opts InlineStatusOpts) { self.c.State().SetItemOperation(opts.Item, opts.Operation) self.mutex.Lock() defer self.mutex.Unlock() info := self.contextsWithInlineStatus[opts.ContextKey] if info == nil { info = &inlineStatusInfo{refCount: 0, stop: make(chan struct{})} self.contextsWithInlineStatus[opts.ContextKey] = info go utils.Safe(func() { ticker := time.NewTicker(time.Millisecond * time.Duration(self.c.UserConfig().Gui.Spinner.Rate)) defer ticker.Stop() outer: for { select { case <-ticker.C: self.renderContext(opts.ContextKey) case <-info.stop: break outer } } }) } info.refCount++ } func (self *InlineStatusHelper) stop(opts InlineStatusOpts) { self.mutex.Lock() if info := self.contextsWithInlineStatus[opts.ContextKey]; info != nil { info.refCount-- if info.refCount <= 0 { info.stop <- struct{}{} delete(self.contextsWithInlineStatus, opts.ContextKey) } } self.mutex.Unlock() self.c.State().ClearItemOperation(opts.Item) // When recording a demo we need to re-render the context again here to // remove the inline status. In normal usage we don't want to do this // because in the case of pushing a branch this would first reveal the โ†‘3โ†“7 // status from before the push for a brief moment, to be replaced by a green // checkmark a moment later when the async refresh is done. This looks // jarring, so normally we rely on the async refresh to redraw with the // status removed. (In some rare cases, where there's no refresh at all, we // need to redraw manually in the controller; see TagsController.push() for // an example.) // // In demos, however, we turn all async refreshes into sync ones, because // this looks better in demos. In this case the refresh happens while the // status is still set, so we need to render again after removing it. if self.c.InDemo() { self.renderContext(opts.ContextKey) } } func (self *InlineStatusHelper) renderContext(contextKey types.ContextKey) { self.c.OnUIThread(func() error { self.c.ContextForKey(contextKey).HandleRender() return nil }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/host_helper.go
pkg/gui/controllers/helpers/host_helper.go
package helpers import ( "github.com/jesseduffield/lazygit/pkg/commands/hosting_service" ) // this helper just wraps our hosting_service package type HostHelper struct { c *HelperCommon } func NewHostHelper( c *HelperCommon, ) *HostHelper { return &HostHelper{ c: c, } } func (self *HostHelper) GetPullRequestURL(from string, to string) (string, error) { mgr, err := self.getHostingServiceMgr() if err != nil { return "", err } return mgr.GetPullRequestURL(from, to) } func (self *HostHelper) GetCommitURL(commitHash string) (string, error) { mgr, err := self.getHostingServiceMgr() if err != nil { return "", err } return mgr.GetCommitURL(commitHash) } // getting this on every request rather than storing it in state in case our remoteURL changes // from one invocation to the next. func (self *HostHelper) getHostingServiceMgr() (*hosting_service.HostingServiceMgr, error) { remoteUrl, err := self.c.Git().Remote.GetRemoteURL("origin") if err != nil { return nil, err } configServices := self.c.UserConfig().Services return hosting_service.NewHostingServiceMgr(self.c.Log, self.c.Tr, remoteUrl, configServices), nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/commits_helper.go
pkg/gui/controllers/helpers/commits_helper.go
package helpers import ( "errors" "path/filepath" "strings" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type CommitsHelper struct { c *HelperCommon getCommitSummary func() string setCommitSummary func(string) getCommitDescription func() string getUnwrappedCommitDescription func() string setCommitDescription func(string) } func NewCommitsHelper( c *HelperCommon, getCommitSummary func() string, setCommitSummary func(string), getCommitDescription func() string, getUnwrappedCommitDescription func() string, setCommitDescription func(string), ) *CommitsHelper { return &CommitsHelper{ c: c, getCommitSummary: getCommitSummary, setCommitSummary: setCommitSummary, getCommitDescription: getCommitDescription, getUnwrappedCommitDescription: getUnwrappedCommitDescription, setCommitDescription: setCommitDescription, } } func (self *CommitsHelper) SplitCommitMessageAndDescription(message string) (string, string) { msg, description, _ := strings.Cut(message, "\n") return msg, strings.TrimSpace(description) } func (self *CommitsHelper) SetMessageAndDescriptionInView(message string) { summary, description := self.SplitCommitMessageAndDescription(message) self.setCommitSummary(summary) self.setCommitDescription(description) self.c.Contexts().CommitMessage.RenderSubtitle() } func (self *CommitsHelper) JoinCommitMessageAndUnwrappedDescription() string { if len(self.getUnwrappedCommitDescription()) == 0 { return self.getCommitSummary() } return self.getCommitSummary() + "\n" + self.getUnwrappedCommitDescription() } func TryRemoveHardLineBreaks(message string, autoWrapWidth int) string { lastHardLineStart := 0 result := message for i, b := range message { if b == '\n' { // Try to make this a soft linebreak by turning it into a space, and // checking whether it still wraps to the same result then. str := message[lastHardLineStart:i] + " " + message[i+1:] softLineBreakIndices := gocui.AutoWrapContent(str, autoWrapWidth) // See if auto-wrapping inserted a soft line break: if len(softLineBreakIndices) > 0 && softLineBreakIndices[0] == i-lastHardLineStart+1 { // It did, so change it to a space in the result. result = result[:i] + " " + result[i+1:] } lastHardLineStart = i + 1 } } return result } func (self *CommitsHelper) SwitchToEditor() error { message := lo.Ternary(len(self.getCommitDescription()) == 0, self.getCommitSummary(), self.getCommitSummary()+"\n\n"+self.getCommitDescription()) filepath := filepath.Join(self.c.OS().GetTempDir(), self.c.Git().RepoPaths.RepoName(), time.Now().Format("Jan _2 15.04.05.000000000")+".msg") err := self.c.OS().CreateFileWithContent(filepath, message) if err != nil { return err } self.CloseCommitMessagePanel() return self.c.Contexts().CommitMessage.SwitchToEditor(filepath) } func (self *CommitsHelper) UpdateCommitPanelView(message string) { if message != "" { self.SetMessageAndDescriptionInView(message) return } if self.c.Contexts().CommitMessage.GetPreserveMessage() { preservedMessage := self.c.Contexts().CommitMessage.GetPreservedMessageAndLogError() self.SetMessageAndDescriptionInView(preservedMessage) return } self.SetMessageAndDescriptionInView("") } type OpenCommitMessagePanelOpts struct { CommitIndex int SummaryTitle string DescriptionTitle string PreserveMessage bool OnConfirm func(summary string, description string) error OnSwitchToEditor func(string) error InitialMessage string // The following two fields are only for the display of the "(hooks // disabled)" display in the commit message panel. They have no effect on // the actual behavior; make sure what you are passing in matches that. // Leave unassigned if the concept of skipping hooks doesn't make sense for // what you are doing, e.g. when creating a tag. ForceSkipHooks bool SkipHooksPrefix string } func (self *CommitsHelper) OpenCommitMessagePanel(opts *OpenCommitMessagePanelOpts) { onConfirm := func(summary string, description string) error { self.CloseCommitMessagePanel() return opts.OnConfirm(summary, description) } self.c.Contexts().CommitMessage.SetPanelState( opts.CommitIndex, opts.SummaryTitle, opts.DescriptionTitle, opts.PreserveMessage, opts.InitialMessage, onConfirm, opts.OnSwitchToEditor, opts.ForceSkipHooks, opts.SkipHooksPrefix, ) self.UpdateCommitPanelView(opts.InitialMessage) self.c.Context().Push(self.c.Contexts().CommitMessage, types.OnFocusOpts{}) } func (self *CommitsHelper) ClearPreservedCommitMessage() { self.c.Contexts().CommitMessage.SetPreservedMessageAndLogError("") } func (self *CommitsHelper) HandleCommitConfirm() error { summary, description := self.getCommitSummary(), self.getCommitDescription() if summary == "" { return errors.New(self.c.Tr.CommitWithoutMessageErr) } err := self.c.Contexts().CommitMessage.OnConfirm(summary, description) if err != nil { return err } return nil } func (self *CommitsHelper) CloseCommitMessagePanel() { if self.c.Contexts().CommitMessage.GetPreserveMessage() { message := self.JoinCommitMessageAndUnwrappedDescription() if message != self.c.Contexts().CommitMessage.GetInitialMessage() { self.c.Contexts().CommitMessage.SetPreservedMessageAndLogError(message) } } else { self.SetMessageAndDescriptionInView("") } self.c.Contexts().CommitMessage.SetHistoryMessage("") self.c.Views().CommitMessage.Visible = false self.c.Views().CommitDescription.Visible = false self.c.Context().Pop() } func (self *CommitsHelper) OpenCommitMenu(suggestionFunc func(string) []*types.Suggestion) error { var disabledReasonForOpenInEditor *types.DisabledReason if !self.c.Contexts().CommitMessage.CanSwitchToEditor() { disabledReasonForOpenInEditor = &types.DisabledReason{ Text: self.c.Tr.CommandDoesNotSupportOpeningInEditor, } } menuItems := []*types.MenuItem{ { Label: self.c.Tr.OpenInEditor, OnPress: func() error { return self.SwitchToEditor() }, Key: 'e', DisabledReason: disabledReasonForOpenInEditor, }, { Label: self.c.Tr.AddCoAuthor, OnPress: func() error { return self.addCoAuthor(suggestionFunc) }, Key: 'c', }, { Label: self.c.Tr.PasteCommitMessageFromClipboard, OnPress: func() error { return self.pasteCommitMessageFromClipboard() }, Key: 'p', }, } return self.c.Menu(types.CreateMenuOptions{ Title: self.c.Tr.CommitMenuTitle, Items: menuItems, }) } func (self *CommitsHelper) addCoAuthor(suggestionFunc func(string) []*types.Suggestion) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.AddCoAuthorPromptTitle, FindSuggestionsFunc: suggestionFunc, HandleConfirm: func(value string) error { commitDescription := self.getCommitDescription() commitDescription = git_commands.AddCoAuthorToDescription(commitDescription, value) self.setCommitDescription(commitDescription) return nil }, }) return nil } func (self *CommitsHelper) pasteCommitMessageFromClipboard() error { message, err := self.c.OS().PasteFromClipboard() if err != nil { return err } if message == "" { return nil } currentMessage := self.JoinCommitMessageAndUnwrappedDescription() return self.c.ConfirmIf(currentMessage != "", types.ConfirmOpts{ Title: self.c.Tr.PasteCommitMessageFromClipboard, Prompt: self.c.Tr.SurePasteCommitMessage, HandleConfirm: func() error { self.SetMessageAndDescriptionInView(message) return nil }, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/update_helper.go
pkg/gui/controllers/helpers/update_helper.go
package helpers import ( "errors" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/updates" "github.com/jesseduffield/lazygit/pkg/utils" ) type UpdateHelper struct { c *HelperCommon updater *updates.Updater } func NewUpdateHelper(c *HelperCommon, updater *updates.Updater) *UpdateHelper { return &UpdateHelper{ c: c, updater: updater, } } func (self *UpdateHelper) CheckForUpdateInBackground() { self.updater.CheckForNewUpdate(func(newVersion string, err error) error { if err != nil { // ignoring the error for now so that I'm not annoying users self.c.Log.Error(err.Error()) return nil } if newVersion == "" { return nil } if self.c.UserConfig().Update.Method == "background" { self.startUpdating(newVersion) return nil } return self.showUpdatePrompt(newVersion) }, false) } func (self *UpdateHelper) CheckForUpdateInForeground() error { return self.c.WithWaitingStatus(self.c.Tr.CheckingForUpdates, func(gocui.Task) error { self.updater.CheckForNewUpdate(func(newVersion string, err error) error { if err != nil { return err } if newVersion == "" { return errors.New(self.c.Tr.FailedToRetrieveLatestVersionErr) } return self.showUpdatePrompt(newVersion) }, true) return nil }) } func (self *UpdateHelper) startUpdating(newVersion string) { _ = self.c.WithWaitingStatus(self.c.Tr.UpdateInProgressWaitingStatus, func(gocui.Task) error { self.c.State().SetUpdating(true) err := self.updater.Update(newVersion) return self.onUpdateFinish(err) }) } func (self *UpdateHelper) onUpdateFinish(err error) error { self.c.State().SetUpdating(false) self.c.OnUIThread(func() error { self.c.SetViewContent(self.c.Views().AppStatus, "") if err != nil { errMessage := utils.ResolvePlaceholderString( self.c.Tr.UpdateFailedErr, map[string]string{ "errMessage": err.Error(), }, ) return errors.New(errMessage) } self.c.Alert(self.c.Tr.UpdateCompletedTitle, self.c.Tr.UpdateCompleted) return nil }) return nil } func (self *UpdateHelper) showUpdatePrompt(newVersion string) error { message := utils.ResolvePlaceholderString( self.c.Tr.UpdateAvailable, map[string]string{ "newVersion": newVersion, }, ) self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.UpdateAvailableTitle, Prompt: message, HandleConfirm: func() error { self.startUpdating(newVersion) return nil }, }) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/mode_helper.go
pkg/gui/controllers/helpers/mode_helper.go
package helpers import ( "fmt" "strings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type ModeHelper struct { c *HelperCommon diffHelper *DiffHelper patchBuildingHelper *PatchBuildingHelper cherryPickHelper *CherryPickHelper mergeAndRebaseHelper *MergeAndRebaseHelper bisectHelper *BisectHelper suppressRebasingMode bool } func NewModeHelper( c *HelperCommon, diffHelper *DiffHelper, patchBuildingHelper *PatchBuildingHelper, cherryPickHelper *CherryPickHelper, mergeAndRebaseHelper *MergeAndRebaseHelper, bisectHelper *BisectHelper, ) *ModeHelper { return &ModeHelper{ c: c, diffHelper: diffHelper, patchBuildingHelper: patchBuildingHelper, cherryPickHelper: cherryPickHelper, mergeAndRebaseHelper: mergeAndRebaseHelper, bisectHelper: bisectHelper, } } type ModeStatus struct { IsActive func() bool InfoLabel func() string CancelLabel func() string Reset func() error } func (self *ModeHelper) Statuses() []ModeStatus { return []ModeStatus{ { IsActive: self.c.Modes().Diffing.Active, InfoLabel: func() string { return self.withResetButton( fmt.Sprintf( "%s %s", self.c.Tr.ShowingGitDiff, "git diff "+strings.Join(self.diffHelper.DiffArgs(), " "), ), style.FgMagenta, ) }, CancelLabel: func() string { return self.c.Tr.CancelDiffingMode }, Reset: self.diffHelper.ExitDiffMode, }, { IsActive: self.c.Git().Patch.PatchBuilder.Active, InfoLabel: func() string { return self.withResetButton(self.c.Tr.BuildingPatch, style.FgYellow.SetBold()) }, CancelLabel: func() string { return self.c.Tr.ExitCustomPatchBuilder }, Reset: self.patchBuildingHelper.Reset, }, { IsActive: self.c.Modes().Filtering.Active, InfoLabel: func() string { filterContent := lo.Ternary(self.c.Modes().Filtering.GetPath() != "", self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()) return self.withResetButton( fmt.Sprintf( "%s '%s'", self.c.Tr.FilteringBy, filterContent, ), style.FgRed, ) }, CancelLabel: func() string { return self.c.Tr.ExitFilterMode }, Reset: self.ExitFilterMode, }, { IsActive: self.c.Modes().MarkedBaseCommit.Active, InfoLabel: func() string { return self.withResetButton( self.c.Tr.MarkedBaseCommitStatus, style.FgCyan, ) }, CancelLabel: func() string { return self.c.Tr.CancelMarkedBaseCommit }, Reset: self.mergeAndRebaseHelper.ResetMarkedBaseCommit, }, { IsActive: self.c.Modes().CherryPicking.Active, InfoLabel: func() string { copiedCount := len(self.c.Modes().CherryPicking.CherryPickedCommits) text := self.c.Tr.CommitsCopied if copiedCount == 1 { text = self.c.Tr.CommitCopied } return self.withResetButton( fmt.Sprintf( "%d %s", copiedCount, text, ), style.FgCyan, ) }, CancelLabel: func() string { return self.c.Tr.ResetCherryPickShort }, Reset: self.cherryPickHelper.Reset, }, { IsActive: func() bool { return !self.suppressRebasingMode && self.c.Git().Status.WorkingTreeState().Any() }, InfoLabel: func() string { workingTreeState := self.c.Git().Status.WorkingTreeState() return self.withResetButton( workingTreeState.Title(self.c.Tr), style.FgYellow, ) }, CancelLabel: func() string { return fmt.Sprintf(self.c.Tr.AbortTitle, self.c.Git().Status.WorkingTreeState().CommandName()) }, Reset: self.mergeAndRebaseHelper.AbortMergeOrRebaseWithConfirm, }, { IsActive: func() bool { return self.c.Model().BisectInfo.Started() }, InfoLabel: func() string { return self.withResetButton(self.c.Tr.Bisect.Bisecting, style.FgGreen) }, CancelLabel: func() string { return self.c.Tr.Actions.ResetBisect }, Reset: self.bisectHelper.Reset, }, } } func (self *ModeHelper) withResetButton(content string, textStyle style.TextStyle) string { return textStyle.Sprintf( "%s %s", content, style.AttrUnderline.Sprint(self.c.Tr.ResetInParentheses), ) } func (self *ModeHelper) GetActiveMode() (ModeStatus, bool) { return lo.Find(self.Statuses(), func(mode ModeStatus) bool { return mode.IsActive() }) } func (self *ModeHelper) IsAnyModeActive() bool { return lo.SomeBy(self.Statuses(), func(mode ModeStatus) bool { return mode.IsActive() }) } func (self *ModeHelper) ExitFilterMode() error { return self.ClearFiltering() } func (self *ModeHelper) ClearFiltering() error { selectedCommitHash := self.c.Contexts().LocalCommits.GetSelectedCommitHash() self.c.Modes().Filtering.Reset() if self.c.State().GetRepoState().GetScreenMode() == types.SCREEN_HALF { self.c.State().GetRepoState().SetScreenMode(types.SCREEN_NORMAL) } self.c.Refresh(types.RefreshOptions{ Scope: ScopesToRefreshWhenFilteringModeChanges(), Then: func() { // Find the commit that was last selected in filtering mode, and select it again after refreshing if !self.c.Contexts().LocalCommits.SelectCommitByHash(selectedCommitHash) { // If we couldn't find it (either because no commit was selected // in filtering mode, or because the commit is outside the // initial 300 range), go back to the commit that was selected // before we entered filtering self.c.Contexts().LocalCommits.SelectCommitByHash(self.c.Modes().Filtering.GetSelectedCommitHash()) } self.c.PostRefreshUpdate(self.c.Contexts().LocalCommits) }, }) return nil } // Stashes really only need to be refreshed when filtering by path, not by author, but it's too much // work to distinguish this, and refreshing stashes is fast, so we don't bother func ScopesToRefreshWhenFilteringModeChanges() []types.RefreshableView { return []types.RefreshableView{ types.COMMITS, types.SUB_COMMITS, types.REFLOG, types.STASH, } } func (self *ModeHelper) SetSuppressRebasingMode(value bool) { self.suppressRebasingMode = value }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/window_arrangement_helper_test.go
pkg/gui/controllers/helpers/window_arrangement_helper_test.go
package helpers import ( "cmp" "fmt" "slices" "strings" "testing" "github.com/jesseduffield/lazycore/pkg/boxlayout" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // The best way to add test cases here is to set your args and then get the // test to fail and copy+paste the output into the test case's expected string. // TODO: add more test cases func TestGetWindowDimensions(t *testing.T) { getDefaultArgs := func() WindowArrangementArgs { return WindowArrangementArgs{ Width: 75, Height: 30, UserConfig: config.GetDefaultConfig(), CurrentWindow: "files", CurrentSideWindow: "files", SplitMainPanel: false, ScreenMode: types.SCREEN_NORMAL, AppStatus: "", InformationStr: "information", ShowExtrasWindow: false, InDemo: false, IsAnyModeActive: false, InSearchPrompt: false, SearchPrefix: "", } } type Test struct { name string mutateArgs func(*WindowArrangementArgs) expected string } tests := []Test{ { name: "default", mutateArgs: func(args *WindowArrangementArgs) {}, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "stash focused", mutateArgs: func(args *WindowArrangementArgs) { args.CurrentSideWindow = "stash" }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "expandFocusedSidePanel", mutateArgs: func(args *WindowArrangementArgs) { args.UserConfig.Gui.ExpandFocusedSidePanel = true }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "expandSidePanelWeight", mutateArgs: func(args *WindowArrangementArgs) { args.UserConfig.Gui.ExpandFocusedSidePanel = true args.UserConfig.Gui.ExpandedSidePanelWeight = 4 }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "0.5 SidePanelWidth", mutateArgs: func(args *WindowArrangementArgs) { args.UserConfig.Gui.SidePanelWidth = 0.5 }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "0.8 SidePanelWidth", mutateArgs: func(args *WindowArrangementArgs) { args.UserConfig.Gui.SidePanelWidth = 0.8 }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญfilesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญbranchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญcommitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ”‚ โ”‚ โ•ญstashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "half screen mode, enlargedSideViewLocation left", mutateArgs: func(args *WindowArrangementArgs) { args.Height = 20 // smaller height because we don't more here args.ScreenMode = types.SCREEN_HALF args.UserConfig.Gui.EnlargedSideViewLocation = "left" }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎโ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ”‚ โ”‚โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏโ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "half screen mode, enlargedSideViewLocation top", mutateArgs: func(args *WindowArrangementArgs) { args.Height = 20 // smaller height because we don't more here args.ScreenMode = types.SCREEN_HALF args.UserConfig.Gui.EnlargedSideViewLocation = "top" }, expected: ` โ•ญstatusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer1 B: information `, }, { name: "search mode", mutateArgs: func(args *WindowArrangementArgs) { args.InSearchPrompt = true args.SearchPrefix = "Search: " args.Height = 6 // small height cos we only care about the bottom line }, expected: ` <statusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ <filesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <branchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <commitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <stashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <Aโ”€โ”€โ”€โ”€โ”€><searchโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: searchPrefix `, }, { name: "app status present", mutateArgs: func(args *WindowArrangementArgs) { args.AppStatus = "Rebasing /" args.Height = 6 // small height cos we only care about the bottom line }, // We expect single-character spacers between the windows of the bottom line expected: ` <statusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ <filesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <branchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <commitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <stashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <Aโ”€โ”€โ”€โ”€โ”€โ”€โ”€>B<optionsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>C<Dโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: appStatus B: statusSpacer2 C: statusSpacer1 D: information `, }, { name: "information present without options", mutateArgs: func(args *WindowArrangementArgs) { args.Height = 6 // small height cos we only care about the bottom line args.UserConfig.Gui.ShowBottomLine = false // this hides the options window args.IsAnyModeActive = true // this means we show the bottom line despite the user config }, // We expect a spacer on the left of the bottom line so that the information // window is right-aligned expected: ` <statusโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ญmainโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ <filesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <branchesโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <commitsโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ”‚ โ”‚ <stashโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ <statusSpacer1โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€>A<Bโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> A: statusSpacer2 B: information `, }, { name: "app status present without information or options", mutateArgs: func(args *WindowArrangementArgs) { args.Height = 6 // small height cos we only care about the bottom line args.UserConfig.Gui.ShowBottomLine = false // this hides the options window args.IsAnyModeActive = false args.AppStatus = "Rebasing /" }, // We expect the app status window to take up all the available space expected: `
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/bisect_helper.go
pkg/gui/controllers/helpers/bisect_helper.go
package helpers import ( "github.com/jesseduffield/lazygit/pkg/gui/types" ) type BisectHelper struct { c *HelperCommon } func NewBisectHelper(c *HelperCommon) *BisectHelper { return &BisectHelper{c: c} } func (self *BisectHelper) Reset() error { self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Bisect.ResetTitle, Prompt: self.c.Tr.Bisect.ResetPrompt, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.ResetBisect) if err := self.c.Git().Bisect.Reset(); err != nil { return err } self.PostBisectCommandRefresh() return nil }, }) return nil } func (self *BisectHelper) PostBisectCommandRefresh() { self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{}}) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false