Files
lazygit/pkg/gui/context/local_commits_context.go

692 lines
23 KiB
Go

package context
import (
"fmt"
"log"
"slices"
"strings"
"sync/atomic"
"time"
"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/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/branchstack"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/graph"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type LocalCommitsContext struct {
*LocalCommitsViewModel
*ListContextTrait
*SearchTrait
dropIndicator *commitDropIndicator
// Whether to show a row for each of the branches that UpdateRefBranches
// returns, while commits are dragged, so that they can be dropped between
// them.
showUpdateRefRows bool
}
type commitDropIndicator struct {
insertionIndex int
// How many of the update-ref rows above the commit at insertionIndex are
// above the indicator.
updateRefsAbove int
moving bool
}
var (
_ types.IListContext = (*LocalCommitsContext)(nil)
_ types.DiffableContext = (*LocalCommitsContext)(nil)
_ types.ISearchableContext = (*LocalCommitsContext)(nil)
_ types.DiffMainViewContext = (*LocalCommitsContext)(nil)
_ types.PullRequestDiffContext = (*LocalCommitsContext)(nil)
)
func (self *LocalCommitsContext) GetDiffMainViewType() types.DiffMainViewType {
return types.DiffMainViewTypePatchBuilding
}
// This panel shows the commits of the checked-out branch, and of the branches below it
// in a stack. PullRequestDiff looks for their pull request among those branches.
func (self *LocalCommitsContext) PullRequestDiff() types.PullRequestDiff {
_, selectionStart, selectionEnd := self.GetSelectedItems()
startIdx, endIdx := commitRangeShownInDiff(
selectionStart, selectionEnd, self.GetSelectedLineIdx(), self.GetSelectedRefRangeForDiffFiles())
model := self.ListContextTrait.c.Model()
return pullRequestDiff(
self.GetCommits(), startIdx, endIdx, model.CheckedOutBranch, model.Branches, model.PullRequestsMap)
}
// commitRangeShownInDiff returns the indices of the newest and the oldest of the commits
// whose combined diff a panel listing a branch's commits renders into the main view: the
// selected range where it has a range to diff, and the commit at the cursor otherwise.
// The panel hands the same selection to DiffHelper.GetUpdateTaskForRenderingCommitsDiff,
// so anything acting on the diff on screen acts on the commits that diff is of.
func commitRangeShownInDiff(
selectionStart int, selectionEnd int, cursor int, refRange *types.RefRange,
) (int, int) {
if refRange != nil {
return selectionStart, selectionEnd
}
return cursor, cursor
}
// pullRequestDiff works out which branch's pull request would show the diff of the
// commits from startIdx to endIdx of a panel listing the commits of listedBranch, and
// which commit that diff starts after.
//
// That commit is the parent of the oldest of the commits. A pull request holds only the
// commits of its branch that are pushed, so a parent that isn't pushed is none of its
// own. A parent on the branch below in a stack isn't either, because the pull request
// was opened against that branch. The diff then starts where the pull request itself
// does, and an empty BaseHash says so.
func pullRequestDiff(
allCommits []*models.Commit,
startIdx int,
endIdx int,
listedBranch string,
branches []*models.Branch,
pullRequests map[string]*models.GithubPullRequest,
) types.PullRequestDiff {
if listedBranch == "" || startIdx < 0 || endIdx >= len(allCommits) {
return types.PullRequestDiff{}
}
heads := pullRequestBranchHeads(branches, pullRequests)
branchAt := func(idx int) string {
return pullRequestBranchAt(allCommits, idx, heads, listedBranch)
}
branch := branchAt(startIdx)
diff := types.PullRequestDiff{
Branch: branch,
SpansBranches: branchAt(endIdx) != branch,
Commits: allCommits[startIdx : endIdx+1],
}
oldest := allCommits[endIdx]
if oldest.IsFirstCommit() {
return diff
}
parentHash := oldest.Parents()[0]
_, parentIdx, found := lo.FindIndexOf(allCommits, func(commit *models.Commit) bool {
return commit.Hash() == parentHash
})
if found && allCommits[parentIdx].Status == models.StatusPushed && branchAt(parentIdx) == branch {
diff.BaseHash = parentHash
}
return diff
}
// pullRequestBranchHeads maps the head commit of each branch that has a pull request to
// that branch. Where several share a head, the first of them in the list wins. The
// checked-out branch comes first in the list, so it wins over the others.
func pullRequestBranchHeads(
branches []*models.Branch, pullRequests map[string]*models.GithubPullRequest,
) map[string]string {
heads := map[string]string{}
for _, branch := range branches {
if _, hasPullRequest := pullRequests[branch.Name]; !hasPullRequest || branch.CommitHash == "" {
continue
}
if _, taken := heads[branch.CommitHash]; !taken {
heads[branch.CommitHash] = branch.Name
}
}
return heads
}
// pullRequestBranchAt returns the branch whose pull request holds the commit at the given
// index: the nearest branch with a pull request whose head is that commit or one listed
// above it. A stack of branches lists the commits of each branch above those of the
// branch it is based on, so this is the branch of the stack that the commit is on.
// Commits that are in a main branch already are skipped, because a branch whose head is
// one of them has been merged and doesn't belong to the stack. If no branch with a pull
// request is found, it is the branch the panel lists, whether or not that one has a pull
// request.
func pullRequestBranchAt(
commits []*models.Commit, idx int, pullRequestBranchHeads map[string]string, listedBranch string,
) string {
for i := idx; i >= 0; i-- {
if commits[i].Status == models.StatusMerged {
continue
}
if branch, ok := pullRequestBranchHeads[commits[i].Hash()]; ok {
return branch
}
}
return listedBranch
}
// UpdateRefBranches returns, for each commit, the branches of a stack that
// point at it and that git updates when rebasing it. Their update-ref todos
// are the boundaries between the branches of the stack when we move commits.
// Returns nil if the rebase.updateRefs config is off, or if a rebase is in
// progress; moving commits then edits the rebase todo, where update-ref todos
// are rows of their own.
func (self *LocalCommitsContext) UpdateRefBranches() [][]string {
c := self.ListContextTrait.c
if !c.Git().Config.GetRebaseUpdateRefs() || c.Model().WorkingTreeStateAtLastCommitRefresh.Any() {
return nil
}
return updateRefBranches(
c.Model().Commits,
c.Model().Branches,
c.Model().CheckedOutBranch,
c.UserConfig().Git.MainBranches,
c.Model().Worktrees,
)
}
func updateRefBranches(
commits []*models.Commit,
branches []*models.Branch,
currentBranchName string,
mainBranches []string,
worktrees []*models.Worktree,
) [][]string {
if len(commits) == 0 {
return nil
}
branchesByHash := map[string][]string{}
for _, branch := range branches {
if presentation.IsStackBranch(branch, currentBranchName, mainBranches) &&
// Our rebase daemon deletes the update-ref todos of the branches
// that point at the head commit
branch.CommitHash != commits[0].Hash() &&
// git creates no update-ref todos for branches that are checked out
// in another worktree
!git_commands.CheckedOutByOtherWorktree(branch, worktrees) {
branchesByHash[branch.CommitHash] = append(branchesByHash[branch.CommitHash], branch.Name)
}
}
return lo.Map(commits, func(commit *models.Commit, _ int) []string {
// The commits list doesn't mark the branches at merged commits
if commit.Status == models.StatusMerged {
return nil
}
return branchesByHash[commit.Hash()]
})
}
func NewLocalCommitsContext(c *ContextCommon) *LocalCommitsContext {
var ctx *LocalCommitsContext
dropIndicator := &commitDropIndicator{insertionIndex: -1}
viewModel := NewLocalCommitsViewModel(
func() []*models.Commit { return c.Model().Commits },
c,
)
getDisplayStrings := func(startIdx int, endIdx int) [][]string {
var selectedCommitHashPtr *string
if c.Context().Current().GetKey() == LOCAL_COMMITS_CONTEXT_KEY {
selectedCommit := viewModel.GetSelected()
if selectedCommit != nil {
selectedCommitHashPtr = selectedCommit.HashPtr()
}
}
hasRebaseUpdateRefsConfig := c.Git().Config.GetRebaseUpdateRefs()
return presentation.GetCommitListDisplayStrings(
c.Common,
c.Model().Commits,
c.Model().Branches,
c.Model().CheckedOutBranch,
hasRebaseUpdateRefsConfig,
c.State().GetRepoState().GetScreenMode() != types.SCREEN_NORMAL,
c.Modes().CherryPicking.SelectedHashSet(),
c.Modes().Diffing.Ref,
c.Modes().MarkedBaseCommit.GetHash(),
c.UserConfig().Gui.TimeFormat,
c.UserConfig().Gui.ShortTimeFormat,
time.Now(),
c.UserConfig().Git.ParseEmoji,
selectedCommitHashPtr,
startIdx,
endIdx,
shouldShowGraph(c),
commitGraphSymbolSet(c),
c.Model().BisectInfo,
)
}
getNonModelItems := func() []*NonModelItem {
result := []*NonModelItem{}
if c.Model().WorkingTreeStateAtLastCommitRefresh.CanShowTodos() {
if c.Model().WorkingTreeStateAtLastCommitRefresh.Rebasing {
result = append(result, &NonModelItem{
Index: 0,
Content: formatListSectionHeader(c.Tr.PendingRebaseTodosSectionHeader),
})
}
if c.Model().WorkingTreeStateAtLastCommitRefresh.CherryPicking ||
c.Model().WorkingTreeStateAtLastCommitRefresh.Reverting {
_, firstCherryPickOrRevertTodo, found := lo.FindIndexOf(
c.Model().Commits, func(c *models.Commit) bool {
return c.Status == models.StatusCherryPickingOrReverting ||
c.Status == models.StatusConflicted
})
if !found {
firstCherryPickOrRevertTodo = 0
}
label := lo.Ternary(c.Model().WorkingTreeStateAtLastCommitRefresh.CherryPicking,
c.Tr.PendingCherryPicksSectionHeader,
c.Tr.PendingRevertsSectionHeader)
result = append(result, &NonModelItem{
Index: firstCherryPickOrRevertTodo,
Content: formatListSectionHeader(label),
})
}
if c.Model().WorkingTreeStateAtLastCommitRefresh.ApplyingPatches {
_, firstPatch, found := lo.FindIndexOf(
c.Model().Commits, func(c *models.Commit) bool {
return c.PatchFile != ""
})
if !found {
firstPatch = 0
}
result = append(result, &NonModelItem{
Index: firstPatch,
Content: formatListSectionHeader(c.Tr.PendingPatchesSectionHeader),
})
}
result = addCommitDropIndicator(
result,
dropIndicator,
0,
c.Tr.MoveCommitsHere,
c.Tr.MovingCommitsHere,
c.UserConfig().Gui.Spinner,
time.Now(),
)
_, firstRealCommit, found := lo.FindIndexOf(
c.Model().Commits, func(c *models.Commit) bool {
return !c.IsTODO()
})
if !found {
firstRealCommit = 0
}
result = append(result, &NonModelItem{
Index: firstRealCommit,
Content: formatListSectionHeader(c.Tr.CommitsSectionHeader),
})
} else {
updateRefRowsBelowIndicator := 0
if ctx.showUpdateRefRows {
updateRefBranches := ctx.UpdateRefBranches()
result = updateRefRows(updateRefBranches, c.UserConfig().Gui.CommitHashLength)
if idx := dropIndicator.insertionIndex; idx >= 0 && idx < len(updateRefBranches) {
updateRefRowsBelowIndicator = len(updateRefBranches[idx]) - dropIndicator.updateRefsAbove
}
}
result = addCommitDropIndicator(
result,
dropIndicator,
updateRefRowsBelowIndicator,
c.Tr.MoveCommitsHere,
c.Tr.MovingCommitsHere,
c.UserConfig().Gui.Spinner,
time.Now(),
)
}
return result
}
ctx = &LocalCommitsContext{
LocalCommitsViewModel: viewModel,
SearchTrait: NewSearchTrait(c),
dropIndicator: dropIndicator,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Commits,
WindowName: "commits",
Key: LOCAL_COMMITS_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
NeedsRerenderOnWidthChange: types.NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_SCREEN_MODE_CHANGES,
NeedsRerenderOnHeightChange: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
getNonModelItems: getNonModelItems,
},
c: c,
refreshViewportOnChange: true,
renderOnlyVisibleLines: true,
},
}
return ctx
}
// updateRefRows returns a row for each of the given update-ref branches, above
// its commit. The row is a horizontal line across the hash column, followed by
// the name of the branch.
func updateRefRows(updateRefBranches [][]string, hashLength int) []*NonModelItem {
lineWidth := hashLength
if lineWidth == 0 {
// There is no hash column; show a short line anyway
lineWidth = 4
}
line := strings.Repeat("─", lineWidth)
branchIcon := ""
if icons.IsIconEnabled() {
branchIcon = icons.BRANCH_ICON + " "
}
result := []*NonModelItem{}
for idx, branches := range updateRefBranches {
for _, branch := range branches {
result = append(result, &NonModelItem{
Index: idx,
Content: line + " " + style.FgYellow.Sprint(branchIcon+branch),
Column: 1, // the hash column
})
}
}
return result
}
// addCommitDropIndicator inserts the drop indicator into the given items,
// which must be ordered by index. Of the items at the indicator's insertion
// index, the last itemsBelow ones go below it, all others above it.
func addCommitDropIndicator(
items []*NonModelItem,
indicator *commitDropIndicator,
itemsBelow int,
dropLabel string,
movingLabel string,
spinnerConfig config.SpinnerConfig,
now time.Time,
) []*NonModelItem {
if indicator.insertionIndex < 0 {
return items
}
label := dropLabel
if indicator.moving {
label = fmt.Sprintf("%s %s", movingLabel, presentation.Loader(now, spinnerConfig))
}
insertAt := len(items)
for i, item := range items {
if item.Index > indicator.insertionIndex {
insertAt = i
break
}
}
insertAt -= itemsBelow
return slices.Insert(items, insertAt, &NonModelItem{
Index: indicator.insertionIndex,
Content: style.FgCyan.SetBold().Sprintf("━━━━━━ %s ━━━━━━", label),
Column: 6, // align with the commit subject
})
}
// SetDropInsertionIndex shows the drop indicator directly above the commit at
// index, below the first updateRefsAbove of its update-ref rows.
func (self *LocalCommitsContext) SetDropInsertionIndex(index int, updateRefsAbove int) {
self.dropIndicator.insertionIndex = index
self.dropIndicator.updateRefsAbove = updateRefsAbove
self.dropIndicator.moving = false
}
func (self *LocalCommitsContext) SetMovingCommitsInsertionIndex(index int, updateRefsAbove int) {
self.dropIndicator.insertionIndex = index
self.dropIndicator.updateRefsAbove = updateRefsAbove
self.dropIndicator.moving = true
}
func (self *LocalCommitsContext) ClearDropInsertionIndex() {
self.dropIndicator.insertionIndex = -1
self.dropIndicator.updateRefsAbove = 0
self.dropIndicator.moving = false
}
func (self *LocalCommitsContext) SetShowUpdateRefRows(value bool) {
self.showUpdateRefRows = value
}
// DragRowAt tells what the view shows at the given view index while commits
// are dragged: the commit at the returned model index if the returned
// update-ref row is -1, or otherwise the update-ref row with that index among
// the ones above that commit. A section header or the drop indicator counts as
// the row below it.
func (self *LocalCommitsContext) DragRowAt(viewIndex int) (int, int) {
modelIndex := self.ViewIndexToModelIndex(viewIndex)
rowsAboveCommit := self.ModelIndexToViewIndex(modelIndex) - viewIndex
if !self.showUpdateRefRows || rowsAboveCommit <= 0 {
return modelIndex, -1
}
updateRefBranches := self.UpdateRefBranches()
if modelIndex >= len(updateRefBranches) {
return modelIndex, -1
}
updateRefRowCount := len(updateRefBranches[modelIndex])
if self.dropIndicator.insertionIndex != modelIndex {
return modelIndex, updateRefRowCount - rowsAboveCommit
}
// The drop indicator is among the rows above the commit
row := updateRefRowCount + 1 - rowsAboveCommit
if row > self.dropIndicator.updateRefsAbove {
row--
}
if row == updateRefRowCount {
return modelIndex, -1
}
return modelIndex, row
}
type LocalCommitsViewModel struct {
*ListViewModel[*models.Commit]
// If this is true we limit the amount of commits we load, for the sake of keeping things fast.
// If the user attempts to scroll past the end of the list, we will load more commits.
// Atomic because a checkout or reset sets it from a worker goroutine while the
// commits refresh reads it on the UI thread to decide how many commits to load.
limitCommits atomic.Bool
// The limit that the commits in the model were loaded with, or 0 if they
// were loaded without one.
loadedCommitLimit int
// If this is true we'll use git log --all when fetching the commits.
showWholeGitGraph bool
}
func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *ContextCommon) *LocalCommitsViewModel {
self := &LocalCommitsViewModel{
ListViewModel: NewListViewModel(getModel),
showWholeGitGraph: c.UserConfig().Git.Log.ShowWholeGraph,
}
self.limitCommits.Store(true)
return self
}
func (self *LocalCommitsContext) CanRebase() bool {
return true
}
func (self *LocalCommitsContext) GetSelectedRef() models.Ref {
commit := self.GetSelected()
if commit == nil {
return nil
}
return commit
}
func (self *LocalCommitsContext) GetSelectedRefRangeForDiffFiles() *types.RefRange {
commits, startIdx, endIdx := self.GetSelectedItems()
if commits == nil || startIdx == endIdx {
return nil
}
from := commits[len(commits)-1]
to := commits[0]
if from.IsTODO() || to.IsTODO() {
return nil
}
return &types.RefRange{From: from, To: to}
}
// Returns the commit hash of the selected commit, or an empty string if no
// commit is selected
func (self *LocalCommitsContext) GetSelectedCommitHash() string {
commit := self.GetSelected()
if commit == nil {
return ""
}
return commit.Hash()
}
func (self *LocalCommitsContext) SelectCommitByHash(hash string) bool {
if hash == "" {
return false
}
if _, idx, found := lo.FindIndexOf(self.GetItems(), func(c *models.Commit) bool { return c.Hash() == hash }); found {
self.SetSelection(idx)
return true
}
return false
}
func (self *LocalCommitsContext) GetDiffTerminals() []string {
itemId := self.GetSelectedItemId()
return []string{itemId}
}
func (self *LocalCommitsContext) RefForAdjustingLineNumberInDiff() string {
commits, _, _ := self.GetSelectedItems()
if commits == nil {
return ""
}
return commits[0].Hash()
}
func (self *LocalCommitsContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition {
return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.modelToViewIndexConverter(), searchStr)
}
func (self *LocalCommitsViewModel) SetLimitCommits(value bool) {
self.limitCommits.Store(value)
}
func (self *LocalCommitsViewModel) GetLimitCommits() bool {
return self.limitCommits.Load()
}
func (self *LocalCommitsViewModel) SetLoadedCommitLimit(value int) {
self.loadedCommitLimit = value
}
func (self *LocalCommitsViewModel) GetLoadedCommitLimit() int {
return self.loadedCommitLimit
}
func (self *LocalCommitsViewModel) SetShowWholeGitGraph(value bool) {
self.showWholeGitGraph = value
}
func (self *LocalCommitsViewModel) GetShowWholeGitGraph() bool {
return self.showWholeGitGraph
}
func (self *LocalCommitsViewModel) GetCommits() []*models.Commit {
return self.getModel()
}
func shouldShowGraph(c *ContextCommon) bool {
// Whether we can draw a graph is a property of the commit list we have
// loaded, not of the filtering mode: turning filtering on or off only
// reaches the screen when the reloaded list does, and until then the graph
// has to keep matching the list that is still on display. Drawing one for a
// filtered list is also ruinously slow, because none of the commits in it
// are connected to each other, so no pipe ever terminates.
if c.Model().CommitsWereFilteredAtLastRefresh {
return false
}
value := c.UserConfig().Git.Log.ShowGraph
switch value {
case "always":
return true
case "never":
return false
case "when-maximised":
return c.State().GetRepoState().GetScreenMode() != types.SCREEN_NORMAL
}
log.Fatalf("Unknown value for git.log.showGraph: %s. Expected one of: 'always', 'never', 'when-maximised'", value)
return false
}
func commitGraphSymbolSet(c *ContextCommon) graph.SymbolSet {
switch c.UserConfig().Gui.CommitGraphStyle {
case "detailed":
return graph.BranchDrawingSymbols
case "auto":
if graph.TerminalDrawsBranchDrawingSymbols(c.GocuiGui().Terminal()) {
return graph.BranchDrawingSymbols
}
}
return graph.BoxDrawingSymbols
}
func searchModelCommits(caseSensitive bool, commits []*models.Commit, columnPositions []int,
modelToViewIndex func(int) int, searchStr string,
) []gocui.SearchPosition {
if columnPositions == nil {
// This should never happen. We are being called at a time where our
// entire view content is scrolled out of view, so that we didn't draw
// anything the last time we rendered. If we run into a scenario where
// this happens, we should fix it, but until we found them all, at least
// make sure we don't crash.
return []gocui.SearchPosition{}
}
normalize := lo.Ternary(caseSensitive, func(s string) string { return s }, strings.ToLower)
return lo.FilterMap(commits, func(commit *models.Commit, idx int) (gocui.SearchPosition, bool) {
// The XStart and XEnd values are only used if the search string can't
// be found in the view. This can really only happen if the user is
// searching for a commit hash that is longer than the truncated hash
// that we render. So we just set the XStart and XEnd values to the
// start and end of the commit hash column, which is the second one.
result := gocui.SearchPosition{XStart: columnPositions[1], XEnd: columnPositions[2] - 1, Y: modelToViewIndex(idx)}
return result, strings.Contains(normalize(commit.Hash()), searchStr) ||
strings.Contains(normalize(commit.Name), searchStr) ||
strings.Contains(normalize(commit.ExtraInfo), searchStr) // allow searching for tags
})
}
func (self *LocalCommitsContext) IndexForGotoBottom() int {
c := self.ListContextTrait.c
commits := self.GetCommits()
branchesBelow := branchstack.BranchesBelow(
commits, c.Model().Branches, c.Model().CheckedOutBranch, c.UserConfig().Git.MainBranches)
return indexForGotoBottomInCommits(commits, self.GetSelectedLineIdx(), branchesBelow, c.Model().BisectInfo)
}