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/controllers/helpers/search_helper.go | pkg/gui/controllers/helpers/search_helper.go | package helpers
import (
"fmt"
"strings"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/keybindings"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
)
// NOTE: this helper supports both filtering and searching. Filtering is when
// the contents of the list are filtered, whereas searching does not actually
// change the contents of the list but instead just highlights the search.
// The general term we use to capture both searching and filtering is...
// 'searching', which is unfortunate but I can't think of a better name.
type SearchHelper struct {
c *HelperCommon
}
func NewSearchHelper(
c *HelperCommon,
) *SearchHelper {
return &SearchHelper{
c: c,
}
}
func (self *SearchHelper) OpenFilterPrompt(context types.IFilterableContext) error {
state := self.searchState()
state.Context = context
self.searchPrefixView().SetContent(context.FilterPrefix(self.c.Tr))
promptView := self.promptView()
promptView.ClearTextArea()
self.OnPromptContentChanged("")
promptView.RenderTextArea()
self.c.Context().Push(self.c.Contexts().Search, types.OnFocusOpts{})
return self.c.ResetKeybindings()
}
func (self *SearchHelper) OpenSearchPrompt(context types.ISearchableContext) error {
state := self.searchState()
state.PrevSearchIndex = -1
state.Context = context
self.searchPrefixView().SetContent(self.c.Tr.SearchPrefix)
promptView := self.promptView()
promptView.ClearTextArea()
promptView.RenderTextArea()
self.c.Context().Push(self.c.Contexts().Search, types.OnFocusOpts{})
return self.c.ResetKeybindings()
}
func (self *SearchHelper) DisplayFilterStatus(context types.IFilterableContext) {
state := self.searchState()
state.Context = context
searchString := context.GetFilter()
self.searchPrefixView().SetContent(context.FilterPrefix(self.c.Tr))
promptView := self.promptView()
keybindingConfig := self.c.UserConfig().Keybinding
promptView.SetContent(fmt.Sprintf("matches for '%s' ", searchString) + theme.OptionsFgColor.Sprintf(self.c.Tr.ExitTextFilterMode, keybindings.Label(keybindingConfig.Universal.Return)))
}
func (self *SearchHelper) DisplaySearchStatus(context types.ISearchableContext) {
state := self.searchState()
state.Context = context
self.searchPrefixView().SetContent(self.c.Tr.SearchPrefix)
index, totalCount := context.GetView().GetSearchStatus()
context.RenderSearchStatus(index, totalCount)
}
func (self *SearchHelper) searchState() *types.SearchState {
return self.c.State().GetRepoState().GetSearchState()
}
func (self *SearchHelper) searchPrefixView() *gocui.View {
return self.c.Views().SearchPrefix
}
func (self *SearchHelper) promptView() *gocui.View {
return self.c.Contexts().Search.GetView()
}
func (self *SearchHelper) promptContent() string {
return self.c.Contexts().Search.GetView().TextArea.GetContent()
}
func (self *SearchHelper) Confirm() error {
state := self.searchState()
if self.promptContent() == "" {
return self.CancelPrompt()
}
switch state.SearchType() {
case types.SearchTypeFilter:
self.ConfirmFilter()
case types.SearchTypeSearch:
self.ConfirmSearch()
case types.SearchTypeNone:
self.c.Context().Pop()
}
return self.c.ResetKeybindings()
}
func (self *SearchHelper) ConfirmFilter() {
// We also do this on each keypress but we do it here again just in case
state := self.searchState()
context, ok := state.Context.(types.IFilterableContext)
if !ok {
self.c.Log.Warnf("Context %s is not filterable", state.Context.GetKey())
return
}
self.OnPromptContentChanged(self.promptContent())
filterString := self.promptContent()
if filterString != "" {
context.GetSearchHistory().Push(filterString)
}
self.c.Context().Pop()
}
func (self *SearchHelper) ConfirmSearch() {
state := self.searchState()
context, ok := state.Context.(types.ISearchableContext)
if !ok {
self.c.Log.Warnf("Context %s is searchable", state.Context.GetKey())
return
}
searchString := self.promptContent()
context.SetSearchString(searchString)
if searchString != "" {
context.GetSearchHistory().Push(searchString)
}
self.c.Context().Pop()
context.GetView().Search(searchString, modelSearchResults(context))
}
func modelSearchResults(context types.ISearchableContext) []gocui.SearchPosition {
searchString := context.GetSearchString()
var normalizedSearchStr string
// if we have any uppercase characters we'll do a case-sensitive search
caseSensitive := utils.ContainsUppercase(searchString)
if caseSensitive {
normalizedSearchStr = searchString
} else {
normalizedSearchStr = strings.ToLower(searchString)
}
return context.ModelSearchResults(normalizedSearchStr, caseSensitive)
}
func (self *SearchHelper) CancelPrompt() error {
self.Cancel()
self.c.Context().Pop()
return self.c.ResetKeybindings()
}
func (self *SearchHelper) ScrollHistory(scrollIncrement int) {
state := self.searchState()
context, ok := state.Context.(types.ISearchHistoryContext)
if !ok {
return
}
states := context.GetSearchHistory()
if val, err := states.PeekAt(state.PrevSearchIndex + scrollIncrement); err == nil {
state.PrevSearchIndex += scrollIncrement
promptView := self.promptView()
promptView.ClearTextArea()
promptView.TextArea.TypeString(val)
promptView.RenderTextArea()
self.OnPromptContentChanged(val)
}
}
func (self *SearchHelper) Cancel() {
state := self.searchState()
switch context := state.Context.(type) {
case types.IFilterableContext:
context.ClearFilter()
self.c.PostRefreshUpdate(context)
case types.ISearchableContext:
context.ClearSearchString()
context.GetView().ClearSearch()
default:
// do nothing
}
self.HidePrompt()
}
func (self *SearchHelper) OnPromptContentChanged(searchString string) {
state := self.searchState()
switch context := state.Context.(type) {
case types.IFilterableContext:
context.SetSelection(0)
context.GetView().SetOriginY(0)
context.SetFilter(searchString, self.c.UserConfig().Gui.UseFuzzySearch())
self.c.PostRefreshUpdate(context)
case types.ISearchableContext:
// do nothing
default:
// do nothing (shouldn't land here)
}
}
func (self *SearchHelper) ReApplyFilter(context types.Context) {
filterableContext, ok := context.(types.IFilterableContext)
if ok {
state := self.searchState()
if context == state.Context {
filterableContext.SetSelection(0)
filterableContext.GetView().SetOriginY(0)
}
filterableContext.ReApplyFilter(self.c.UserConfig().Gui.UseFuzzySearch())
}
}
func (self *SearchHelper) ReApplySearch(ctx types.Context) {
// Reapply the search if the model has changed. This is needed for contexts
// that use the model for searching, to pass the new model search positions
// to the view.
searchableContext, ok := ctx.(types.ISearchableContext)
if ok {
ctx.GetView().UpdateSearchResults(searchableContext.GetSearchString(), modelSearchResults(searchableContext))
state := self.searchState()
if ctx == state.Context {
// Re-render the "x of y" search status, unless the search prompt is
// open for typing.
if self.c.Context().Current().GetKey() != context.SEARCH_CONTEXT_KEY {
self.RenderSearchStatus(searchableContext)
}
}
}
}
func (self *SearchHelper) RenderSearchStatus(c types.Context) {
if c.GetKey() == context.SEARCH_CONTEXT_KEY {
return
}
if searchableContext, ok := c.(types.ISearchableContext); ok {
if searchableContext.IsSearching() {
self.setSearchingFrameColor()
self.DisplaySearchStatus(searchableContext)
return
}
}
if filterableContext, ok := c.(types.IFilterableContext); ok {
if filterableContext.IsFiltering() {
self.setSearchingFrameColor()
self.DisplayFilterStatus(filterableContext)
return
}
}
self.HidePrompt()
}
func (self *SearchHelper) CancelSearchIfSearching(c types.Context) {
if searchableContext, ok := c.(types.ISearchableContext); ok {
view := searchableContext.GetView()
if view != nil && view.IsSearching() {
view.ClearSearch()
searchableContext.ClearSearchString()
self.Cancel()
}
return
}
if filterableContext, ok := c.(types.IFilterableContext); ok {
if filterableContext.IsFiltering() {
filterableContext.ClearFilter()
self.Cancel()
}
return
}
}
func (self *SearchHelper) HidePrompt() {
self.setNonSearchingFrameColor()
state := self.searchState()
state.Context = nil
}
func (self *SearchHelper) setSearchingFrameColor() {
self.c.GocuiGui().SelFgColor = theme.SearchingActiveBorderColor
self.c.GocuiGui().SelFrameColor = theme.SearchingActiveBorderColor
}
func (self *SearchHelper) setNonSearchingFrameColor() {
self.c.GocuiGui().SelFgColor = theme.ActiveBorderColor
self.c.GocuiGui().SelFrameColor = theme.ActiveBorderColor
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/gpg_helper.go | pkg/gui/controllers/helpers/gpg_helper.go | package helpers
import (
"fmt"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type GpgHelper struct {
c *HelperCommon
}
func NewGpgHelper(c *HelperCommon) *GpgHelper {
return &GpgHelper{
c: c,
}
}
// Currently there is a bug where if we switch to a subprocess from within
// WithWaitingStatus we get stuck there and can't return to lazygit. We could
// fix this bug, or just stop running subprocesses from within there, given that
// we don't need to see a loading status if we're in a subprocess.
func (self *GpgHelper) WithGpgHandling(cmdObj *oscommands.CmdObj, configKey git_commands.GpgConfigKey, waitingStatus string, onSuccess func() error, refreshScope []types.RefreshableView) error {
useSubprocess := self.c.Git().Config.NeedsGpgSubprocess(configKey)
if useSubprocess {
success, err := self.c.RunSubprocess(cmdObj)
if success && onSuccess != nil {
if err := onSuccess(); err != nil {
return err
}
}
self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: refreshScope})
return err
}
return self.runAndStream(cmdObj, waitingStatus, onSuccess, refreshScope)
}
func (self *GpgHelper) runAndStream(cmdObj *oscommands.CmdObj, waitingStatus string, onSuccess func() error, refreshScope []types.RefreshableView) error {
return self.c.WithWaitingStatus(waitingStatus, func(gocui.Task) error {
if err := cmdObj.StreamOutput().Run(); err != nil {
self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: refreshScope})
return fmt.Errorf(
self.c.Tr.GitCommandFailed, self.c.UserConfig().Keybinding.Universal.ExtrasMenu,
)
}
if onSuccess != nil {
if err := onSuccess(); err != nil {
return err
}
}
self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: refreshScope})
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/merge_conflicts_helper.go | pkg/gui/controllers/helpers/merge_conflicts_helper.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type MergeConflictsHelper struct {
c *HelperCommon
}
func NewMergeConflictsHelper(
c *HelperCommon,
) *MergeConflictsHelper {
return &MergeConflictsHelper{
c: c,
}
}
func (self *MergeConflictsHelper) SetMergeState(path string) (bool, error) {
self.context().GetMutex().Lock()
defer self.context().GetMutex().Unlock()
return self.setMergeStateWithoutLock(path)
}
func (self *MergeConflictsHelper) setMergeStateWithoutLock(path string) (bool, error) {
content, err := self.c.Git().File.Cat(path)
if err != nil {
return false, err
}
if path != self.context().GetState().GetPath() {
self.context().SetUserScrolling(false)
}
self.context().GetState().SetContent(content, path)
return !self.context().GetState().NoConflicts(), nil
}
func (self *MergeConflictsHelper) ResetMergeState() {
self.context().GetMutex().Lock()
defer self.context().GetMutex().Unlock()
self.resetMergeState()
}
func (self *MergeConflictsHelper) resetMergeState() {
self.context().SetUserScrolling(false)
self.context().GetState().Reset()
}
func (self *MergeConflictsHelper) EscapeMerge() error {
self.resetMergeState()
// doing this in separate UI thread so that we're not still holding the lock by the time refresh the file
self.c.OnUIThread(func() error {
// There is a race condition here: refreshing the files scope can trigger the
// confirmation context to be pushed if all conflicts are resolved (prompting
// to continue the merge/rebase. In that case, we don't want to then push the
// files context over it.
// So long as both places call OnUIThread, we're fine.
if self.c.Context().IsCurrent(self.c.Contexts().MergeConflicts) {
self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{})
}
return nil
})
return nil
}
func (self *MergeConflictsHelper) SetConflictsAndRender(path string) (bool, error) {
hasConflicts, err := self.setMergeStateWithoutLock(path)
if err != nil {
return false, err
}
if hasConflicts {
return true, self.context().Render()
}
return false, nil
}
func (self *MergeConflictsHelper) SwitchToMerge(path string) error {
if self.context().GetState().GetPath() != path {
hasConflicts, err := self.SetMergeState(path)
if err != nil {
return err
}
if !hasConflicts {
return nil
}
}
self.c.Context().Push(self.c.Contexts().MergeConflicts, types.OnFocusOpts{})
return nil
}
func (self *MergeConflictsHelper) context() *context.MergeConflictsContext {
return self.c.Contexts().MergeConflicts
}
func (self *MergeConflictsHelper) Render() {
content := self.context().GetContentToRender()
var task types.UpdateTask
if self.context().IsUserScrolling() {
task = types.NewRenderStringWithoutScrollTask(content)
} else {
originY := self.context().GetOriginY()
task = types.NewRenderStringWithScrollTask(content, 0, originY)
}
self.c.RenderToMainViews(types.RefreshMainOpts{
Pair: self.c.MainViewPairs().MergeConflicts,
Main: &types.ViewUpdateOpts{
Task: task,
},
})
}
func (self *MergeConflictsHelper) RefreshMergeState() error {
self.c.Contexts().MergeConflicts.GetMutex().Lock()
defer self.c.Contexts().MergeConflicts.GetMutex().Unlock()
if self.c.Context().Current().GetKey() != context.MERGE_CONFLICTS_CONTEXT_KEY {
return nil
}
hasConflicts, err := self.SetConflictsAndRender(self.c.Contexts().MergeConflicts.GetState().GetPath())
if err != nil {
return err
}
if !hasConflicts {
return self.EscapeMerge()
}
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/upstream_helper.go | pkg/gui/controllers/helpers/upstream_helper.go | package helpers
import (
"errors"
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type UpstreamHelper struct {
c *HelperCommon
getRemoteBranchesSuggestionsFunc func(string) func(string) []*types.Suggestion
}
func NewUpstreamHelper(
c *HelperCommon,
getRemoteBranchesSuggestionsFunc func(string) func(string) []*types.Suggestion,
) *UpstreamHelper {
return &UpstreamHelper{
c: c,
getRemoteBranchesSuggestionsFunc: getRemoteBranchesSuggestionsFunc,
}
}
func (self *UpstreamHelper) ParseUpstream(upstream string) (string, string, error) {
var upstreamBranch, upstreamRemote string
split := strings.Split(upstream, " ")
if len(split) != 2 {
return "", "", errors.New(self.c.Tr.InvalidUpstream)
}
upstreamRemote = split[0]
upstreamBranch = split[1]
return upstreamRemote, upstreamBranch, nil
}
func (self *UpstreamHelper) promptForUpstream(initialContent string, onConfirm func(string) error) error {
self.c.Prompt(types.PromptOpts{
Title: self.c.Tr.EnterUpstream,
InitialContent: initialContent,
FindSuggestionsFunc: self.getRemoteBranchesSuggestionsFunc(" "),
HandleConfirm: onConfirm,
})
return nil
}
func (self *UpstreamHelper) PromptForUpstreamWithInitialContent(currentBranch *models.Branch, onConfirm func(string) error) error {
suggestedRemote := self.GetSuggestedRemote()
initialContent := suggestedRemote + " " + currentBranch.Name
return self.promptForUpstream(initialContent, onConfirm)
}
func (self *UpstreamHelper) PromptForUpstreamWithoutInitialContent(_ *models.Branch, onConfirm func(string) error) error {
return self.promptForUpstream("", onConfirm)
}
func (self *UpstreamHelper) GetSuggestedRemote() string {
return getSuggestedRemote(self.c.Model().Remotes)
}
func getSuggestedRemote(remotes []*models.Remote) string {
if len(remotes) == 0 {
return "origin"
}
for _, remote := range remotes {
if remote.Name == "origin" {
return remote.Name
}
}
return remotes[0].Name
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/signal_handling.go | pkg/gui/controllers/helpers/signal_handling.go | //go:build !windows
package helpers
import (
"os"
"os/signal"
"syscall"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
func canSuspendApp() bool {
return true
}
func sendStopSignal() error {
return syscall.Kill(0, syscall.SIGSTOP)
}
// setForegroundPgrp sets the current process group as the foreground process group
// for the terminal, allowing the program to read input after resuming from suspension.
func setForegroundPgrp() error {
fd, err := unix.Open("/dev/tty", unix.O_RDWR, 0)
if err != nil {
return err
}
defer unix.Close(fd)
pgid := syscall.Getpgrp()
return unix.IoctlSetPointerInt(fd, unix.TIOCSPGRP, pgid)
}
func handleResumeSignal(log *logrus.Entry, onResume func() error) {
if err := setForegroundPgrp(); err != nil {
log.Warning(err)
return
}
if err := onResume(); err != nil {
log.Warning(err)
}
}
func installResumeSignalHandler(log *logrus.Entry, onResume func() error) {
go func() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGCONT)
for sig := range sigs {
switch sig {
case syscall.SIGCONT:
handleResumeSignal(log, onResume)
}
}
}()
}
| 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_test.go | pkg/gui/controllers/helpers/commits_helper_test.go | package helpers
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTryRemoveHardLineBreaks(t *testing.T) {
scenarios := []struct {
name string
message string
autoWrapWidth int
expectedResult string
}{
{
name: "empty",
message: "",
autoWrapWidth: 7,
expectedResult: "",
},
{
name: "all line breaks are needed",
message: "abc\ndef\n\nxyz",
autoWrapWidth: 7,
expectedResult: "abc\ndef\n\nxyz",
},
{
name: "some can be unwrapped",
message: "123\nabc def\nghi jkl\nmno\n456\n",
autoWrapWidth: 7,
expectedResult: "123\nabc def ghi jkl mno\n456\n",
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
actualResult := TryRemoveHardLineBreaks(s.message, s.autoWrapWidth)
assert.Equal(t, s.expectedResult, actualResult)
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/diff_helper.go | pkg/gui/controllers/helpers/diff_helper.go | package helpers
import (
"strings"
"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/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/modes/diffing"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type DiffHelper struct {
c *HelperCommon
}
func NewDiffHelper(c *HelperCommon) *DiffHelper {
return &DiffHelper{
c: c,
}
}
func (self *DiffHelper) DiffArgs() []string {
output := []string{"--stat", "-p", self.c.Modes().Diffing.Ref}
right := self.currentDiffTerminal()
if right != "" {
output = append(output, right)
}
if self.c.Modes().Diffing.Reverse {
output = append(output, "-R")
}
output = append(output, "--")
file := self.currentlySelectedFilename()
if file != "" {
output = append(output, file)
} else if self.c.Modes().Filtering.Active() {
output = append(output, self.c.Modes().Filtering.GetPath())
}
return output
}
// Returns an update task that can be passed to RenderToMainViews to render a
// diff for the selected commit(s). We need to pass both the selected commit
// and the refRange for a range selection. If the refRange is nil (meaning that
// either there's no range, or it can't be diffed for some reason), then we want
// to fall back to rendering the diff for the single commit.
func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Commit, refRange *types.RefRange) types.UpdateTask {
if refRange != nil {
from, to := refRange.From, refRange.To
args := []string{from.ParentRefName(), to.RefName(), "--stat", "-p"}
args = append(args, "--")
if filterPath := self.c.Modes().Filtering.GetPath(); filterPath != "" {
// If both refs are commits, filter by the union of their paths. This is useful for
// example when diffing a range of commits in filter-by-path mode across a rename.
fromCommit, ok1 := from.(*models.Commit)
toCommit, ok2 := to.(*models.Commit)
if ok1 && ok2 {
paths := append(self.FilterPathsForCommit(fromCommit), self.FilterPathsForCommit(toCommit)...)
args = append(args, lo.Uniq(paths)...)
} else {
// If either ref is not a commit (which is possible in sticky diff mode, when
// diffing against a branch or tag), we just filter by the filter path; that's the
// best we can do in this case.
args = append(args, filterPath)
}
}
cmdObj := self.c.Git().Diff.DiffCmdObj(args)
prefix := style.FgYellow.Sprintf("%s %s-%s\n\n", self.c.Tr.ShowingDiffForRange, from.ShortRefName(), to.ShortRefName())
return types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix)
}
cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit))
return types.NewRunPtyTask(cmdObj.GetCmd())
}
func (self *DiffHelper) FilterPathsForCommit(commit *models.Commit) []string {
filterPath := self.c.Modes().Filtering.GetPath()
if filterPath != "" {
if len(commit.FilterPaths) > 0 {
return commit.FilterPaths
}
return []string{filterPath}
}
return nil
}
func (self *DiffHelper) ExitDiffMode() error {
self.c.Modes().Diffing = diffing.New()
self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC})
return nil
}
func (self *DiffHelper) RenderDiff() {
args := self.DiffArgs()
cmdObj := self.c.Git().Diff.DiffCmdObj(args)
prefix := style.FgMagenta.Sprintf(
"%s %s\n\n",
self.c.Tr.ShowingGitDiff,
"git diff "+strings.Join(args, " "),
)
task := types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix)
self.c.RenderToMainViews(types.RefreshMainOpts{
Pair: self.c.MainViewPairs().Normal,
Main: &types.ViewUpdateOpts{
Title: "Diff",
SubTitle: self.IgnoringWhitespaceSubTitle(),
Task: task,
},
})
}
// CurrentDiffTerminals returns the current diff terminals of the currently selected item.
// in the case of a branch it returns both the branch and it's upstream name,
// which becomes an option when you bring up the diff menu, but when you're just
// flicking through branches it will be using the local branch name.
func (self *DiffHelper) CurrentDiffTerminals() []string {
c := self.c.Context().CurrentSide()
if c.GetKey() == "" {
return nil
}
switch v := c.(type) {
case types.DiffableContext:
return v.GetDiffTerminals()
}
return nil
}
func (self *DiffHelper) currentDiffTerminal() string {
names := self.CurrentDiffTerminals()
if len(names) == 0 {
return ""
}
return names[0]
}
func (self *DiffHelper) currentlySelectedFilename() string {
currentContext := self.c.Context().Current()
switch currentContext := currentContext.(type) {
case types.IListContext:
if lo.Contains([]types.ContextKey{context.FILES_CONTEXT_KEY, context.COMMIT_FILES_CONTEXT_KEY}, currentContext.GetKey()) {
return currentContext.GetSelectedItemId()
}
}
return ""
}
func (self *DiffHelper) WithDiffModeCheck(f func()) {
if self.c.Modes().Diffing.Active() {
self.RenderDiff()
} else {
f()
}
}
func (self *DiffHelper) IgnoringWhitespaceSubTitle() string {
if self.c.UserConfig().Git.IgnoreWhitespaceInDiffView {
return self.c.Tr.IgnoreWhitespaceDiffViewSubTitle
}
return ""
}
func (self *DiffHelper) OpenDiffToolForRef(selectedRef models.Ref) error {
to := selectedRef.RefName()
from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff("")
_, 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
}
// AdjustLineNumber is used to adjust a line number in the diff that's currently
// being viewed, so that it corresponds to the line number in the actual working
// copy state of the file. It is used when clicking on a delta hyperlink in a
// diff, or when pressing `e` in the staging or patch building panels. It works
// by getting a diff of what's being viewed in the main view against the working
// copy, and then using that diff to adjust the line number.
// path is the file path of the file being viewed
// linenumber is the line number to adjust (one-based)
// viewname is the name of the view that shows the diff. We need to pass it
// because the diff adjustment is slightly different depending on which view is
// showing the diff.
func (self *DiffHelper) AdjustLineNumber(path string, linenumber int, viewname string) int {
switch viewname {
case "main", "patchBuilding":
if diffableContext, ok := self.c.Context().CurrentSide().(types.DiffableContext); ok {
ref := diffableContext.RefForAdjustingLineNumberInDiff()
if len(ref) != 0 {
return self.adjustLineNumber(linenumber, ref, "--", path)
}
}
// if the type cast to DiffableContext returns false, we are in the
// unstaged changes view of the Files panel; no need to adjust line
// numbers in this case
case "secondary", "stagingSecondary":
return self.adjustLineNumber(linenumber, "--", path)
}
return linenumber
}
func (self *DiffHelper) adjustLineNumber(linenumber int, diffArgs ...string) int {
args := append([]string{"--unified=0"}, diffArgs...)
diff, err := self.c.Git().Diff.GetDiff(false, args...)
if err != nil {
return linenumber
}
patch := patch.Parse(diff)
return patch.AdjustLineNumber(linenumber)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/upstream_helper_test.go | pkg/gui/controllers/helpers/upstream_helper_test.go | package helpers
import (
"testing"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
)
func TestGetSuggestedRemote(t *testing.T) {
cases := []struct {
remotes []*models.Remote
expected string
}{
{mkRemoteList(), "origin"},
{mkRemoteList("upstream", "origin", "foo"), "origin"},
{mkRemoteList("upstream", "foo", "bar"), "upstream"},
}
for _, c := range cases {
result := getSuggestedRemote(c.remotes)
assert.EqualValues(t, c.expected, result)
}
}
func mkRemoteList(names ...string) []*models.Remote {
return lo.Map(names, func(name string, _ int) *models.Remote {
return &models.Remote{Name: name}
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/tags_helper.go | pkg/gui/controllers/helpers/tags_helper.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
)
type TagsHelper struct {
c *HelperCommon
commitsHelper *CommitsHelper
gpg *GpgHelper
}
func NewTagsHelper(c *HelperCommon, commitsHelper *CommitsHelper, gpg *GpgHelper) *TagsHelper {
return &TagsHelper{
c: c,
commitsHelper: commitsHelper,
gpg: gpg,
}
}
func (self *TagsHelper) OpenCreateTagPrompt(ref string, onCreate func()) error {
onConfirm := func(tagName string, description string) error {
prompt := utils.ResolvePlaceholderString(
self.c.Tr.ForceTagPrompt,
map[string]string{
"tagName": tagName,
"cancelKey": self.c.UserConfig().Keybinding.Universal.Return,
"confirmKey": self.c.UserConfig().Keybinding.Universal.Confirm,
},
)
force := self.c.Git().Tag.HasTag(tagName)
return self.c.ConfirmIf(force, types.ConfirmOpts{
Title: self.c.Tr.ForceTag,
Prompt: prompt,
HandleConfirm: func() error {
var command *oscommands.CmdObj
if description != "" || self.c.Git().Config.GetGpgTagSign() {
self.c.LogAction(self.c.Tr.Actions.CreateAnnotatedTag)
command = self.c.Git().Tag.CreateAnnotatedObj(tagName, ref, description, force)
} else {
self.c.LogAction(self.c.Tr.Actions.CreateLightweightTag)
command = self.c.Git().Tag.CreateLightweightObj(tagName, ref, force)
}
return self.gpg.WithGpgHandling(command, git_commands.TagGpgSign, self.c.Tr.CreatingTag, func() error {
return nil
}, []types.RefreshableView{types.COMMITS, types.TAGS})
},
})
}
self.commitsHelper.OpenCommitMessagePanel(
&OpenCommitMessagePanelOpts{
CommitIndex: context.NoCommitIndex,
InitialMessage: "",
SummaryTitle: self.c.Tr.TagNameTitle,
DescriptionTitle: self.c.Tr.TagMessageTitle,
PreserveMessage: false,
OnConfirm: onConfirm,
},
)
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/signal_handling_windows.go | pkg/gui/controllers/helpers/signal_handling_windows.go | package helpers
import (
"github.com/sirupsen/logrus"
)
func canSuspendApp() bool {
return false
}
func sendStopSignal() error {
return nil
}
func installResumeSignalHandler(log *logrus.Entry, onResume func() error) {
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/app_status_helper.go | pkg/gui/controllers/helpers/app_status_helper.go | package helpers
import (
"time"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/status"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type AppStatusHelper struct {
c *HelperCommon
statusMgr func() *status.StatusManager
modeHelper *ModeHelper
}
func NewAppStatusHelper(c *HelperCommon, statusMgr func() *status.StatusManager, modeHelper *ModeHelper) *AppStatusHelper {
return &AppStatusHelper{
c: c,
statusMgr: statusMgr,
modeHelper: modeHelper,
}
}
func (self *AppStatusHelper) Toast(message string, kind types.ToastKind) {
if self.c.RunningIntegrationTest() {
// Don't bother showing toasts in integration tests. You can't check for
// them anyway, and they would only slow down the test unnecessarily by
// two seconds.
return
}
self.statusMgr().AddToastStatus(message, kind)
self.renderAppStatus()
}
// A custom task for WithWaitingStatus calls; it wraps the original one and
// hides the status whenever the task is paused, and shows it again when
// continued.
type appStatusHelperTask struct {
gocui.Task
waitingStatusHandle *status.WaitingStatusHandle
}
// poor man's version of explicitly saying that struct X implements interface Y
var _ gocui.Task = appStatusHelperTask{}
func (self appStatusHelperTask) Pause() {
self.waitingStatusHandle.Hide()
self.Task.Pause()
}
func (self appStatusHelperTask) Continue() {
self.Task.Continue()
self.waitingStatusHandle.Show()
}
// WithWaitingStatus wraps a function and shows a waiting status while the function is still executing
func (self *AppStatusHelper) WithWaitingStatus(message string, f func(gocui.Task) error) {
self.c.OnWorker(func(task gocui.Task) error {
return self.WithWaitingStatusImpl(message, f, task)
})
}
func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui.Task) error, task gocui.Task) error {
return self.statusMgr().WithWaitingStatus(message, self.renderAppStatus, func(waitingStatusHandle *status.WaitingStatusHandle) error {
return f(appStatusHelperTask{task, waitingStatusHandle})
})
}
func (self *AppStatusHelper) WithWaitingStatusSync(message string, f func() error) error {
return self.statusMgr().WithWaitingStatus(message, func() {}, func(*status.WaitingStatusHandle) error {
stop := make(chan struct{})
defer func() { close(stop) }()
self.renderAppStatusSync(stop)
return f()
})
}
func (self *AppStatusHelper) HasStatus() bool {
return self.statusMgr().HasStatus()
}
func (self *AppStatusHelper) GetStatusString() string {
appStatus, _ := self.statusMgr().GetStatusString(self.c.UserConfig())
return appStatus
}
func (self *AppStatusHelper) renderAppStatus() {
self.c.OnWorker(func(_ gocui.Task) error {
ticker := time.NewTicker(time.Millisecond * time.Duration(self.c.UserConfig().Gui.Spinner.Rate))
defer ticker.Stop()
for range ticker.C {
appStatus, color := self.statusMgr().GetStatusString(self.c.UserConfig())
self.c.Views().AppStatus.FgColor = color
self.c.OnUIThread(func() error {
self.c.SetViewContent(self.c.Views().AppStatus, appStatus)
return nil
})
if appStatus == "" {
break
}
}
return nil
})
}
func (self *AppStatusHelper) renderAppStatusSync(stop chan struct{}) {
go func() {
ticker := time.NewTicker(time.Millisecond * 50)
defer ticker.Stop()
// Forcing a re-layout and redraw after we added the waiting status;
// this is needed in case the gui.showBottomLine config is set to false,
// to make sure the bottom line appears. It's also useful for redrawing
// once after each of several consecutive keypresses, e.g. pressing
// ctrl-j to move a commit down several steps.
_ = self.c.GocuiGui().ForceLayoutAndRedraw()
self.modeHelper.SetSuppressRebasingMode(true)
defer func() { self.modeHelper.SetSuppressRebasingMode(false) }()
outer:
for {
select {
case <-ticker.C:
appStatus, color := self.statusMgr().GetStatusString(self.c.UserConfig())
self.c.Views().AppStatus.FgColor = color
self.c.SetViewContent(self.c.Views().AppStatus, appStatus)
// Redraw all views of the bottom line:
bottomLineViews := []*gocui.View{
self.c.Views().AppStatus, self.c.Views().Options, self.c.Views().Information,
self.c.Views().StatusSpacer1, self.c.Views().StatusSpacer2,
}
_ = self.c.GocuiGui().ForceRedrawViews(bottomLineViews...)
case <-stop:
break outer
}
}
}()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/confirmation_helper.go | pkg/gui/controllers/helpers/confirmation_helper.go | package helpers
import (
goContext "context"
"fmt"
"strings"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
)
type ConfirmationHelper struct {
c *HelperCommon
}
func NewConfirmationHelper(c *HelperCommon) *ConfirmationHelper {
return &ConfirmationHelper{
c: c,
}
}
// This file is for the rendering of confirmation panels along with setting and handling associated
// keybindings.
func (self *ConfirmationHelper) closeAndCallConfirmationFunction(cancel goContext.CancelFunc, function func() error) error {
cancel()
self.c.Context().Pop()
if function != nil {
if err := function(); err != nil {
return err
}
}
return nil
}
func (self *ConfirmationHelper) wrappedConfirmationFunction(cancel goContext.CancelFunc, function func() error) func() error {
return func() error {
return self.closeAndCallConfirmationFunction(cancel, function)
}
}
func (self *ConfirmationHelper) wrappedPromptConfirmationFunction(
cancel goContext.CancelFunc,
function func(string) error,
getResponse func() string,
allowEmptyInput bool,
preserveWhitespace bool,
) func() error {
return func() error {
if self.c.GocuiGui().IsPasting {
// The user is pasting multi-line text into a prompt; we don't want to handle the
// line feeds as "confirm" keybindings. Simply ignoring them is the best we can do; this
// will cause the entire pasted text to appear as a single line in the prompt. Hopefully
// the user knows that ctrl-u allows them to delete it again...
return nil
}
response := getResponse()
if !preserveWhitespace {
response = strings.TrimSpace(response)
}
if response == "" && !allowEmptyInput {
self.c.ErrorToast(self.c.Tr.PromptInputCannotBeEmptyToast)
return nil
}
return self.closeAndCallConfirmationFunction(cancel, func() error {
return function(response)
})
}
}
func (self *ConfirmationHelper) DeactivateConfirmation() {
self.c.Mutexes().PopupMutex.Lock()
self.c.State().GetRepoState().SetCurrentPopupOpts(nil)
self.c.Mutexes().PopupMutex.Unlock()
self.c.Views().Confirmation.Visible = false
self.clearConfirmationViewKeyBindings()
}
func (self *ConfirmationHelper) DeactivatePrompt() {
self.c.Mutexes().PopupMutex.Lock()
self.c.State().GetRepoState().SetCurrentPopupOpts(nil)
self.c.Mutexes().PopupMutex.Unlock()
self.c.Views().Prompt.Visible = false
self.c.Views().Suggestions.Visible = false
self.clearPromptViewKeyBindings()
}
func getMessageHeight(wrap bool, editable bool, message string, width int, tabWidth int) int {
wrappedLines, _, _ := utils.WrapViewLinesToWidth(wrap, editable, message, width, tabWidth)
return len(wrappedLines)
}
func (self *ConfirmationHelper) getPopupPanelDimensionsForContentHeight(panelWidth, contentHeight int, parentPopupContext types.Context) (int, int, int, int) {
return self.getPopupPanelDimensionsAux(panelWidth, contentHeight, parentPopupContext)
}
func (self *ConfirmationHelper) getPopupPanelDimensionsAux(panelWidth int, panelHeight int, parentPopupContext types.Context) (int, int, int, int) {
width, height := self.c.GocuiGui().Size()
if panelHeight > height*3/4 {
panelHeight = height * 3 / 4
}
if parentPopupContext != nil {
// If there's already a popup on the screen, offset the new one from its
// parent so that it's clearly distinguished from the parent
x0, y0, _, _ := parentPopupContext.GetView().Dimensions()
x0 += 2
y0 += 1
return x0, y0, x0 + panelWidth, y0 + panelHeight + 1
}
return width/2 - panelWidth/2,
height/2 - panelHeight/2 - panelHeight%2 - 1,
width/2 + panelWidth/2,
height/2 + panelHeight/2
}
func (self *ConfirmationHelper) getPopupPanelWidth() int {
width, _ := self.c.GocuiGui().Size()
// we want a minimum width up to a point, then we do it based on ratio.
panelWidth := 4 * width / 7
minWidth := 80
if panelWidth < minWidth {
panelWidth = min(width-2, minWidth)
}
return panelWidth
}
func (self *ConfirmationHelper) prepareConfirmationPanel(
opts types.ConfirmOpts,
) {
self.c.Views().Confirmation.Title = opts.Title
self.c.Views().Confirmation.FgColor = theme.GocuiDefaultTextColor
self.c.ResetViewOrigin(self.c.Views().Confirmation)
self.c.SetViewContent(self.c.Views().Confirmation, style.AttrBold.Sprint(strings.TrimSpace(opts.Prompt)))
}
func (self *ConfirmationHelper) preparePromptPanel(
opts types.ConfirmOpts,
) {
self.c.Views().Prompt.Title = opts.Title
self.c.Views().Prompt.FgColor = theme.GocuiDefaultTextColor
self.c.Views().Prompt.Mask = characterForMask(opts.Mask)
self.c.Views().Prompt.SetOrigin(0, 0)
textArea := self.c.Views().Prompt.TextArea
textArea.Clear()
textArea.TypeString(opts.Prompt)
self.c.Views().Prompt.RenderTextArea()
if opts.FindSuggestionsFunc != nil {
suggestionsContext := self.c.Contexts().Suggestions
suggestionsContext.State.FindSuggestions = opts.FindSuggestionsFunc
suggestionsView := self.c.Views().Suggestions
suggestionsView.Wrap = false
suggestionsView.FgColor = theme.GocuiDefaultTextColor
suggestionsContext.SetSuggestions(opts.FindSuggestionsFunc(""))
suggestionsView.Visible = true
suggestionsView.Title = fmt.Sprintf(self.c.Tr.SuggestionsTitle, self.c.UserConfig().Keybinding.Universal.TogglePanel)
suggestionsView.Subtitle = ""
}
}
func characterForMask(mask bool) string {
if mask {
return "*"
}
return ""
}
func (self *ConfirmationHelper) CreatePopupPanel(ctx goContext.Context, opts types.CreatePopupPanelOpts) {
self.c.Mutexes().PopupMutex.Lock()
defer self.c.Mutexes().PopupMutex.Unlock()
_, cancel := goContext.WithCancel(ctx)
// we don't allow interruptions of non-loader popups in case we get stuck somehow
// e.g. a credentials popup never gets its required user input so a process hangs
// forever.
// The proper solution is to have a queue of popup options
currentPopupOpts := self.c.State().GetRepoState().GetCurrentPopupOpts()
if currentPopupOpts != nil && !currentPopupOpts.HasLoader {
self.c.Log.Error("ignoring create popup panel because a popup panel is already open")
cancel()
return
}
// remove any previous keybindings
self.clearConfirmationViewKeyBindings()
self.clearPromptViewKeyBindings()
var context types.Context
if opts.Editable {
self.c.Contexts().Suggestions.State.FindSuggestions = opts.FindSuggestionsFunc
self.preparePromptPanel(
types.ConfirmOpts{
Title: opts.Title,
Prompt: opts.Prompt,
FindSuggestionsFunc: opts.FindSuggestionsFunc,
Mask: opts.Mask,
})
context = self.c.Contexts().Prompt
self.setPromptKeyBindings(cancel, opts)
} else {
if opts.FindSuggestionsFunc != nil {
panic("non-editable confirmation views do not support suggestions")
}
self.c.Contexts().Suggestions.State.FindSuggestions = nil
self.prepareConfirmationPanel(
types.ConfirmOpts{
Title: opts.Title,
Prompt: opts.Prompt,
})
context = self.c.Contexts().Confirmation
self.setConfirmationKeyBindings(cancel, opts)
}
self.c.Contexts().Suggestions.State.AllowEditSuggestion = opts.AllowEditSuggestion
self.c.State().GetRepoState().SetCurrentPopupOpts(&opts)
self.c.Context().Push(context, types.OnFocusOpts{})
}
func (self *ConfirmationHelper) setConfirmationKeyBindings(cancel goContext.CancelFunc, opts types.CreatePopupPanelOpts) {
onConfirm := self.wrappedConfirmationFunction(cancel, opts.HandleConfirm)
onClose := self.wrappedConfirmationFunction(cancel, opts.HandleClose)
self.c.Contexts().Confirmation.State.OnConfirm = onConfirm
self.c.Contexts().Confirmation.State.OnClose = onClose
}
func (self *ConfirmationHelper) setPromptKeyBindings(cancel goContext.CancelFunc, opts types.CreatePopupPanelOpts) {
onConfirm := self.wrappedPromptConfirmationFunction(cancel, opts.HandleConfirmPrompt,
func() string { return self.c.Views().Prompt.TextArea.GetContent() },
opts.AllowEmptyInput, opts.PreserveWhitespace)
onSuggestionConfirm := self.wrappedPromptConfirmationFunction(
cancel,
opts.HandleConfirmPrompt,
self.getSelectedSuggestionValue,
opts.AllowEmptyInput,
opts.PreserveWhitespace,
)
onClose := self.wrappedConfirmationFunction(cancel, opts.HandleClose)
onDeleteSuggestion := func() error {
if opts.HandleDeleteSuggestion == nil {
return nil
}
idx := self.c.Contexts().Suggestions.GetSelectedLineIdx()
return opts.HandleDeleteSuggestion(idx)
}
self.c.Contexts().Prompt.State.OnConfirm = onConfirm
self.c.Contexts().Prompt.State.OnClose = onClose
self.c.Contexts().Suggestions.State.OnConfirm = onSuggestionConfirm
self.c.Contexts().Suggestions.State.OnClose = onClose
self.c.Contexts().Suggestions.State.OnDeleteSuggestion = onDeleteSuggestion
}
func (self *ConfirmationHelper) clearConfirmationViewKeyBindings() {
noop := func() error { return nil }
self.c.Contexts().Confirmation.State.OnConfirm = noop
self.c.Contexts().Confirmation.State.OnClose = noop
}
func (self *ConfirmationHelper) clearPromptViewKeyBindings() {
noop := func() error { return nil }
self.c.Contexts().Prompt.State.OnConfirm = noop
self.c.Contexts().Prompt.State.OnClose = noop
self.c.Contexts().Suggestions.State.OnConfirm = noop
self.c.Contexts().Suggestions.State.OnClose = noop
self.c.Contexts().Suggestions.State.OnDeleteSuggestion = noop
}
func (self *ConfirmationHelper) getSelectedSuggestionValue() string {
selectedSuggestion := self.c.Contexts().Suggestions.GetSelected()
if selectedSuggestion != nil {
return selectedSuggestion.Value
}
return ""
}
func (self *ConfirmationHelper) ResizeCurrentPopupPanels() {
var parentPopupContext types.Context
for _, c := range self.c.Context().CurrentPopup() {
switch c {
case self.c.Contexts().Menu:
self.resizeMenu(parentPopupContext)
case self.c.Contexts().Confirmation:
self.resizeConfirmationPanel(parentPopupContext)
case self.c.Contexts().Prompt, self.c.Contexts().Suggestions:
self.resizePromptPanel(parentPopupContext)
case self.c.Contexts().CommitMessage, self.c.Contexts().CommitDescription:
self.ResizeCommitMessagePanels(parentPopupContext)
}
parentPopupContext = c
}
}
func (self *ConfirmationHelper) resizeMenu(parentPopupContext types.Context) {
// we want the unfiltered length here so that if we're filtering we don't
// resize the window
itemCount := self.c.Contexts().Menu.UnfilteredLen()
offset := 3
panelWidth := self.getPopupPanelWidth()
contentWidth := panelWidth - 2 // minus 2 for the frame
promptLinesCount := self.layoutMenuPrompt(contentWidth)
x0, y0, x1, y1 := self.getPopupPanelDimensionsForContentHeight(panelWidth, itemCount+offset+promptLinesCount, parentPopupContext)
menuBottom := y1 - offset
_, _ = self.c.GocuiGui().SetView(self.c.Views().Menu.Name(), x0, y0, x1, menuBottom, 0)
tooltipTop := menuBottom + 1
tooltip := ""
selectedItem := self.c.Contexts().Menu.GetSelected()
if selectedItem != nil {
tooltip = self.TooltipForMenuItem(selectedItem)
}
tooltipHeight := getMessageHeight(true, false, tooltip, contentWidth, self.c.Views().Menu.TabWidth) + 2 // plus 2 for the frame
_, _ = self.c.GocuiGui().SetView(self.c.Views().Tooltip.Name(), x0, tooltipTop, x1, tooltipTop+tooltipHeight-1, 0)
}
// Wraps the lines of the menu prompt to the available width and rerenders the
// menu if needed. Returns the number of lines the prompt takes up.
func (self *ConfirmationHelper) layoutMenuPrompt(contentWidth int) int {
oldPromptLines := self.c.Contexts().Menu.GetPromptLines()
var promptLines []string
prompt := self.c.Contexts().Menu.GetPrompt()
if len(prompt) > 0 {
promptLines, _, _ = utils.WrapViewLinesToWidth(true, false, prompt, contentWidth, self.c.Views().Menu.TabWidth)
promptLines = append(promptLines, "")
}
self.c.Contexts().Menu.SetPromptLines(promptLines)
if len(oldPromptLines) != len(promptLines) {
// The number of lines in the prompt has changed; this happens either
// because we're now showing a menu that has a prompt, and the previous
// menu didn't (or vice versa), or because the user is resizing the
// terminal window while a menu with a prompt is open.
// We need to rerender to give the menu context a chance to update its
// non-model items, and reinitialize the data it uses for converting
// between view index and model index.
self.c.Contexts().Menu.HandleRender()
// Then we need to refocus to ensure the cursor is in the right place in
// the view.
self.c.Contexts().Menu.HandleFocus(types.OnFocusOpts{})
}
return len(promptLines)
}
func (self *ConfirmationHelper) resizeConfirmationPanel(parentPopupContext types.Context) {
panelWidth := self.getPopupPanelWidth()
contentWidth := panelWidth - 2 // minus 2 for the frame
confirmationView := self.c.Views().Confirmation
prompt := confirmationView.Buffer()
panelHeight := getMessageHeight(true, false, prompt, contentWidth, confirmationView.TabWidth)
x0, y0, x1, y1 := self.getPopupPanelDimensionsAux(panelWidth, panelHeight, parentPopupContext)
_, _ = self.c.GocuiGui().SetView(confirmationView.Name(), x0, y0, x1, y1, 0)
}
func (self *ConfirmationHelper) resizePromptPanel(parentPopupContext types.Context) {
suggestionsViewHeight := 0
if self.c.Views().Suggestions.Visible {
suggestionsViewHeight = 11
}
panelWidth := self.getPopupPanelWidth()
contentWidth := panelWidth - 2 // minus 2 for the frame
promptView := self.c.Views().Prompt
prompt := promptView.TextArea.GetContent()
panelHeight := getMessageHeight(false, true, prompt, contentWidth, promptView.TabWidth) + suggestionsViewHeight
x0, y0, x1, y1 := self.getPopupPanelDimensionsAux(panelWidth, panelHeight, parentPopupContext)
promptViewBottom := y1 - suggestionsViewHeight
_, _ = self.c.GocuiGui().SetView(promptView.Name(), x0, y0, x1, promptViewBottom, 0)
suggestionsViewTop := promptViewBottom + 1
_, _ = self.c.GocuiGui().SetView(self.c.Views().Suggestions.Name(), x0, suggestionsViewTop, x1, suggestionsViewTop+suggestionsViewHeight, 0)
}
func (self *ConfirmationHelper) ResizeCommitMessagePanels(parentPopupContext types.Context) {
panelWidth := self.getPopupPanelWidth()
content := self.c.Views().CommitDescription.TextArea.GetContent()
summaryViewHeight := 3
panelHeight := getMessageHeight(false, true, content, panelWidth, self.c.Views().CommitDescription.TabWidth)
minHeight := 7
if panelHeight < minHeight {
panelHeight = minHeight
}
x0, y0, x1, y1 := self.getPopupPanelDimensionsAux(panelWidth, panelHeight, parentPopupContext)
_, _ = self.c.GocuiGui().SetView(self.c.Views().CommitMessage.Name(), x0, y0, x1, y0+summaryViewHeight-1, 0)
_, _ = self.c.GocuiGui().SetView(self.c.Views().CommitDescription.Name(), x0, y0+summaryViewHeight, x1, y1+summaryViewHeight, 0)
}
func (self *ConfirmationHelper) IsPopupPanel(context types.Context) bool {
return context.GetKind() == types.PERSISTENT_POPUP || context.GetKind() == types.TEMPORARY_POPUP
}
func (self *ConfirmationHelper) IsPopupPanelFocused() bool {
return self.IsPopupPanel(self.c.Context().Current())
}
func (self *ConfirmationHelper) TooltipForMenuItem(menuItem *types.MenuItem) string {
tooltip := menuItem.Tooltip
if menuItem.DisabledReason != nil && menuItem.DisabledReason.Text != "" {
if tooltip != "" {
tooltip += "\n\n"
}
tooltip += style.FgRed.Sprintf(self.c.Tr.DisabledMenuItemPrefix) + menuItem.DisabledReason.Text
}
return tooltip
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/files_helper.go | pkg/gui/controllers/helpers/files_helper.go | package helpers
import (
"path/filepath"
"github.com/samber/lo"
)
type FilesHelper struct {
c *HelperCommon
}
func NewFilesHelper(c *HelperCommon) *FilesHelper {
return &FilesHelper{
c: c,
}
}
func (self *FilesHelper) EditFiles(filenames []string) error {
absPaths := lo.Map(filenames, func(filename string, _ int) string {
absPath, err := filepath.Abs(filename)
if err != nil {
return filename
}
return absPath
})
cmdStr, suspend := self.c.Git().File.GetEditCmdStr(absPaths)
return self.callEditor(cmdStr, suspend)
}
func (self *FilesHelper) EditFileAtLine(filename string, lineNumber int) error {
absPath, err := filepath.Abs(filename)
if err != nil {
return err
}
cmdStr, suspend := self.c.Git().File.GetEditAtLineCmdStr(absPath, lineNumber)
return self.callEditor(cmdStr, suspend)
}
func (self *FilesHelper) EditFileAtLineAndWait(filename string, lineNumber int) error {
absPath, err := filepath.Abs(filename)
if err != nil {
return err
}
cmdStr := self.c.Git().File.GetEditAtLineAndWaitCmdStr(absPath, lineNumber)
// Always suspend, regardless of the value of the suspend config,
// since we want to prevent interacting with the UI until the editor
// returns, even if the editor doesn't use the terminal
return self.callEditor(cmdStr, true)
}
func (self *FilesHelper) OpenDirInEditor(path string) error {
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
cmdStr, suspend := self.c.Git().File.GetOpenDirInEditorCmdStr(absPath)
return self.callEditor(cmdStr, suspend)
}
func (self *FilesHelper) callEditor(cmdStr string, suspend bool) error {
if suspend {
return self.c.RunSubprocessAndRefresh(
self.c.OS().Cmd.NewShell(cmdStr, self.c.UserConfig().OS.ShellFunctionsFile),
)
}
return self.c.OS().Cmd.NewShell(cmdStr, self.c.UserConfig().OS.ShellFunctionsFile).Run()
}
func (self *FilesHelper) OpenFile(filename string) error {
absPath, err := filepath.Abs(filename)
if err != nil {
return err
}
self.c.LogAction(self.c.Tr.Actions.OpenFile)
if err := self.c.OS().OpenFile(absPath); err != nil {
return err
}
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/staging_helper.go | pkg/gui/controllers/helpers/staging_helper.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/patch_exploring"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type StagingHelper struct {
c *HelperCommon
}
func NewStagingHelper(
c *HelperCommon,
) *StagingHelper {
return &StagingHelper{
c: c,
}
}
// NOTE: used from outside this file
func (self *StagingHelper) RefreshStagingPanel(focusOpts types.OnFocusOpts) {
secondaryFocused := self.secondaryStagingFocused()
mainFocused := self.mainStagingFocused()
// this method could be called when the staging panel is not being used,
// in which case we don't want to do anything.
if !mainFocused && !secondaryFocused {
return
}
mainSelectedLineIdx := -1
secondarySelectedLineIdx := -1
if focusOpts.ClickedViewLineIdx > 0 {
if secondaryFocused {
secondarySelectedLineIdx = focusOpts.ClickedViewLineIdx
} else {
mainSelectedLineIdx = focusOpts.ClickedViewLineIdx
}
}
mainContext := self.c.Contexts().Staging
secondaryContext := self.c.Contexts().StagingSecondary
var file *models.File
node := self.c.Contexts().Files.GetSelected()
if node != nil {
file = node.File
}
if file == nil || (!file.HasUnstagedChanges && !file.HasStagedChanges) {
self.handleStagingEscape()
return
}
mainDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, true, false)
secondaryDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, true, true)
// grabbing locks here and releasing before we finish the function
// because pushing say the secondary context could mean entering this function
// again, and we don't want to have a deadlock
mainContext.GetMutex().Lock()
secondaryContext.GetMutex().Lock()
hunkMode := self.c.UserConfig().Gui.UseHunkModeInStagingView
mainContext.SetState(
patch_exploring.NewState(mainDiff, mainSelectedLineIdx, mainContext.GetView(), mainContext.GetState(), hunkMode),
)
secondaryContext.SetState(
patch_exploring.NewState(secondaryDiff, secondarySelectedLineIdx, secondaryContext.GetView(), secondaryContext.GetState(), hunkMode),
)
mainState := mainContext.GetState()
secondaryState := secondaryContext.GetState()
mainContent := mainContext.GetContentToRender()
secondaryContent := secondaryContext.GetContentToRender()
mainContext.GetMutex().Unlock()
secondaryContext.GetMutex().Unlock()
if mainState == nil && secondaryState == nil {
self.handleStagingEscape()
return
}
if mainState == nil && !secondaryFocused {
self.c.Context().Push(secondaryContext, focusOpts)
return
}
if secondaryState == nil && secondaryFocused {
self.c.Context().Push(mainContext, focusOpts)
return
}
if secondaryFocused {
self.c.Contexts().StagingSecondary.FocusSelection()
} else {
self.c.Contexts().Staging.FocusSelection()
}
self.c.RenderToMainViews(types.RefreshMainOpts{
Pair: self.c.MainViewPairs().Staging,
Main: &types.ViewUpdateOpts{
Task: types.NewRenderStringWithoutScrollTask(mainContent),
Title: self.c.Tr.UnstagedChanges,
},
Secondary: &types.ViewUpdateOpts{
Task: types.NewRenderStringWithoutScrollTask(secondaryContent),
Title: self.c.Tr.StagedChanges,
},
})
}
func (self *StagingHelper) handleStagingEscape() {
self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{})
}
func (self *StagingHelper) secondaryStagingFocused() bool {
return self.c.Context().CurrentStatic().GetKey() == self.c.Contexts().StagingSecondary.GetKey()
}
func (self *StagingHelper) mainStagingFocused() bool {
return self.c.Context().CurrentStatic().GetKey() == self.c.Contexts().Staging.GetKey()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/credentials_helper.go | pkg/gui/controllers/helpers/credentials_helper.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type CredentialsHelper struct {
c *HelperCommon
}
func NewCredentialsHelper(
c *HelperCommon,
) *CredentialsHelper {
return &CredentialsHelper{
c: c,
}
}
// PromptUserForCredential wait for a username, password or passphrase input from the credentials popup
// We return a channel rather than returning the string directly so that the calling function knows
// when the prompt has been created (before the user has entered anything) so that it can
// note that we're now waiting on user input and lazygit isn't processing anything.
func (self *CredentialsHelper) PromptUserForCredential(passOrUname oscommands.CredentialType) <-chan string {
ch := make(chan string)
self.c.OnUIThread(func() error {
title, mask := self.getTitleAndMask(passOrUname)
self.c.Prompt(types.PromptOpts{
Title: title,
Mask: mask,
HandleConfirm: func(input string) error {
ch <- input + "\n"
self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC})
return nil
},
HandleClose: func() error {
ch <- "\n"
return nil
},
AllowEmptyInput: true,
})
return nil
})
return ch
}
func (self *CredentialsHelper) getTitleAndMask(passOrUname oscommands.CredentialType) (string, bool) {
switch passOrUname {
case oscommands.Username:
return self.c.Tr.CredentialsUsername, false
case oscommands.Password:
return self.c.Tr.CredentialsPassword, true
case oscommands.Passphrase:
return self.c.Tr.CredentialsPassphrase, true
case oscommands.PIN:
return self.c.Tr.CredentialsPIN, true
case oscommands.Token:
return self.c.Tr.CredentialsToken, true
}
// should never land here
panic("unexpected credential request")
}
| 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.go | pkg/gui/controllers/helpers/window_arrangement_helper.go | package helpers
import (
"fmt"
mapsPkg "maps"
"math"
"strings"
"github.com/jesseduffield/lazycore/pkg/boxlayout"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"golang.org/x/exp/slices"
)
// In this file we use the boxlayout package, along with knowledge about the app's state,
// to arrange the windows (i.e. panels) on the screen.
type WindowArrangementHelper struct {
c *HelperCommon
windowHelper *WindowHelper
modeHelper *ModeHelper
appStatusHelper *AppStatusHelper
}
func NewWindowArrangementHelper(
c *HelperCommon,
windowHelper *WindowHelper,
modeHelper *ModeHelper,
appStatusHelper *AppStatusHelper,
) *WindowArrangementHelper {
return &WindowArrangementHelper{
c: c,
windowHelper: windowHelper,
modeHelper: modeHelper,
appStatusHelper: appStatusHelper,
}
}
type WindowArrangementArgs struct {
// Width of the screen (in characters)
Width int
// Height of the screen (in characters)
Height int
// User config
UserConfig *config.UserConfig
// Name of the currently focused window. (It's actually the current static window, meaning
// popups are ignored)
CurrentWindow string
// Name of the current side window (i.e. the current window in the left
// section of the UI)
CurrentSideWindow string
// Whether the main panel is split (as is the case e.g. when a file has both
// staged and unstaged changes)
SplitMainPanel bool
// The current screen mode (normal, half, full)
ScreenMode types.ScreenMode
// The content shown on the bottom left of the screen when showing a loader
// or toast e.g. 'Rebasing /'
AppStatus string
// The content shown on the bottom right of the screen (e.g. the 'donate',
// 'ask question' links or a message about the current mode e.g. rebase mode)
InformationStr string
// Whether to show the extras window which contains the command log context
ShowExtrasWindow bool
// Whether we are in a demo (which is used for generating demo gifs for the
// repo's readme)
InDemo bool
// Whether any mode is active (e.g. rebasing, cherry picking, etc)
IsAnyModeActive bool
// Whether the search prompt is shown in the bottom left
InSearchPrompt bool
// One of '' (not searching), 'Search: ', and 'Filter: '
SearchPrefix string
}
func (self *WindowArrangementHelper) GetWindowDimensions(informationStr string, appStatus string) map[string]boxlayout.Dimensions {
width, height := self.c.GocuiGui().Size()
repoState := self.c.State().GetRepoState()
var searchPrefix string
if filterableContext, ok := repoState.GetSearchState().Context.(types.IFilterableContext); ok {
searchPrefix = filterableContext.FilterPrefix(self.c.Tr)
} else {
searchPrefix = self.c.Tr.SearchPrefix
}
args := WindowArrangementArgs{
Width: width,
Height: height,
UserConfig: self.c.UserConfig(),
CurrentWindow: self.c.Context().CurrentStatic().GetWindowName(),
CurrentSideWindow: self.c.Context().CurrentSide().GetWindowName(),
SplitMainPanel: repoState.GetSplitMainPanel(),
ScreenMode: repoState.GetScreenMode(),
AppStatus: appStatus,
InformationStr: informationStr,
ShowExtrasWindow: self.c.State().GetShowExtrasWindow(),
InDemo: self.c.InDemo(),
IsAnyModeActive: self.modeHelper.IsAnyModeActive(),
InSearchPrompt: repoState.InSearchPrompt(),
SearchPrefix: searchPrefix,
}
return GetWindowDimensions(args)
}
func shouldUsePortraitMode(args WindowArrangementArgs) bool {
if args.ScreenMode == types.SCREEN_HALF {
return args.UserConfig.Gui.EnlargedSideViewLocation == "top"
}
switch args.UserConfig.Gui.PortraitMode {
case "never":
return false
case "always":
return true
default: // "auto" or any garbage values in PortraitMode value
return args.Width <= 84 && args.Height > 45
}
}
func GetWindowDimensions(args WindowArrangementArgs) map[string]boxlayout.Dimensions {
sideSectionWeight, mainSectionWeight := getMidSectionWeights(args)
sidePanelsDirection := boxlayout.COLUMN
if shouldUsePortraitMode(args) {
sidePanelsDirection = boxlayout.ROW
}
showInfoSection := args.UserConfig.Gui.ShowBottomLine ||
args.InSearchPrompt ||
args.IsAnyModeActive ||
args.AppStatus != ""
infoSectionSize := 0
if showInfoSection {
infoSectionSize = 1
}
root := &boxlayout.Box{
Direction: boxlayout.ROW,
Children: []*boxlayout.Box{
{
Direction: sidePanelsDirection,
Weight: 1,
Children: []*boxlayout.Box{
{
Direction: boxlayout.ROW,
Weight: sideSectionWeight,
ConditionalChildren: sidePanelChildren(args),
},
{
Direction: boxlayout.ROW,
Weight: mainSectionWeight,
Children: mainPanelChildren(args),
},
},
},
{
Direction: boxlayout.COLUMN,
Size: infoSectionSize,
Children: infoSectionChildren(args),
},
},
}
layerOneWindows := boxlayout.ArrangeWindows(root, 0, 0, args.Width, args.Height)
limitWindows := boxlayout.ArrangeWindows(&boxlayout.Box{Window: "limit"}, 0, 0, args.Width, args.Height)
return MergeMaps(layerOneWindows, limitWindows)
}
func mainPanelChildren(args WindowArrangementArgs) []*boxlayout.Box {
mainPanelsDirection := boxlayout.ROW
if splitMainPanelSideBySide(args) {
mainPanelsDirection = boxlayout.COLUMN
}
result := []*boxlayout.Box{
{
Direction: mainPanelsDirection,
Children: mainSectionChildren(args),
Weight: 1,
},
}
if args.ShowExtrasWindow {
result = append(result, &boxlayout.Box{
Window: "extras",
Size: getExtrasWindowSize(args),
})
}
return result
}
func MergeMaps[K comparable, V any](maps ...map[K]V) map[K]V {
result := map[K]V{}
for _, currMap := range maps {
mapsPkg.Copy(result, currMap)
}
return result
}
func mainSectionChildren(args WindowArrangementArgs) []*boxlayout.Box {
// if we're not in split mode we can just show the one main panel. Likewise if
// the main panel is focused and we're in full-screen mode
if !args.SplitMainPanel || (args.ScreenMode == types.SCREEN_FULL && args.CurrentWindow == "main") {
return []*boxlayout.Box{
{
Window: "main",
Weight: 1,
},
}
}
if args.CurrentWindow == "secondary" && args.ScreenMode == types.SCREEN_FULL {
return []*boxlayout.Box{
{
Window: "secondary",
Weight: 1,
},
}
}
return []*boxlayout.Box{
{
Window: "main",
Weight: 1,
},
{
Window: "secondary",
Weight: 1,
},
}
}
func getMidSectionWeights(args WindowArrangementArgs) (int, int) {
sidePanelWidthRatio := args.UserConfig.Gui.SidePanelWidth
// Using 120 so that the default of 0.3333 will remain consistent with previous behavior
const maxColumnCount = 120
mainSectionWeight := int(math.Round(maxColumnCount * (1 - sidePanelWidthRatio)))
sideSectionWeight := int(math.Round(maxColumnCount * sidePanelWidthRatio))
if splitMainPanelSideBySide(args) {
mainSectionWeight = sideSectionWeight * 5 // need to shrink side panel to make way for main panels if side-by-side
}
if args.CurrentWindow == "main" || args.CurrentWindow == "secondary" {
if args.ScreenMode == types.SCREEN_HALF || args.ScreenMode == types.SCREEN_FULL {
sideSectionWeight = 0
}
} else {
if args.ScreenMode == types.SCREEN_HALF {
if args.UserConfig.Gui.EnlargedSideViewLocation == "top" {
mainSectionWeight = sideSectionWeight * 2
} else {
mainSectionWeight = sideSectionWeight
}
} else if args.ScreenMode == types.SCREEN_FULL {
mainSectionWeight = 0
}
}
return sideSectionWeight, mainSectionWeight
}
func infoSectionChildren(args WindowArrangementArgs) []*boxlayout.Box {
if args.InSearchPrompt {
return []*boxlayout.Box{
{
Window: "searchPrefix",
Size: utils.StringWidth(args.SearchPrefix),
},
{
Window: "search",
Weight: 1,
},
}
}
statusSpacerPrefix := "statusSpacer"
spacerBoxIndex := 0
maxSpacerBoxIndex := 2 // See pkg/gui/types/views.go
// Returns a box with size 1 to be used as padding between views
spacerBox := func() *boxlayout.Box {
spacerBoxIndex++
if spacerBoxIndex > maxSpacerBoxIndex {
panic("Too many spacer boxes")
}
return &boxlayout.Box{Window: fmt.Sprintf("%s%d", statusSpacerPrefix, spacerBoxIndex), Size: 1}
}
// Returns a box with weight 1 to be used as flexible padding between views
flexibleSpacerBox := func() *boxlayout.Box {
spacerBoxIndex++
if spacerBoxIndex > maxSpacerBoxIndex {
panic("Too many spacer boxes")
}
return &boxlayout.Box{Window: fmt.Sprintf("%s%d", statusSpacerPrefix, spacerBoxIndex), Weight: 1}
}
// Adds spacer boxes inbetween given boxes
insertSpacerBoxes := func(boxes []*boxlayout.Box) []*boxlayout.Box {
for i := len(boxes) - 1; i >= 1; i-- {
// ignore existing spacer boxes
if !strings.HasPrefix(boxes[i].Window, statusSpacerPrefix) {
boxes = slices.Insert(boxes, i, spacerBox())
}
}
return boxes
}
// First collect the real views that we want to show, we'll add spacers in
// between at the end
var result []*boxlayout.Box
if !args.InDemo {
// app status appears very briefly in demos and dislodges the caption,
// so better not to show it at all
if args.AppStatus != "" {
result = append(result, &boxlayout.Box{Window: "appStatus", Size: utils.StringWidth(args.AppStatus)})
}
}
if args.UserConfig.Gui.ShowBottomLine {
result = append(result, &boxlayout.Box{Window: "options", Weight: 1})
}
if (!args.InDemo && args.UserConfig.Gui.ShowBottomLine) || args.IsAnyModeActive {
result = append(result,
&boxlayout.Box{
Window: "information",
// unlike appStatus, informationStr has various colors so we need to decolorise before taking the length
Size: utils.StringWidth(utils.Decolorise(args.InformationStr)),
})
}
if len(result) == 2 && result[0].Window == "appStatus" {
// Only status and information are showing; need to insert a flexible
// spacer between the two, so that information is right-aligned. Note
// that the call to insertSpacerBoxes below will still insert a 1-char
// spacer in addition (right after the flexible one); this is needed for
// the case that there's not enough room, to ensure there's always at
// least one space.
result = slices.Insert(result, 1, flexibleSpacerBox())
} else if len(result) == 1 {
if result[0].Window == "information" {
// Only information is showing; need to add a flexible spacer so
// that information is right-aligned
result = slices.Insert(result, 0, flexibleSpacerBox())
} else {
// Only status is showing; need to make it flexible so that it
// extends over the whole width
result[0].Size = 0
result[0].Weight = 1
}
}
if len(result) > 0 {
// If we have at least one view, insert 1-char wide spacer boxes between them.
result = insertSpacerBoxes(result)
}
return result
}
func splitMainPanelSideBySide(args WindowArrangementArgs) bool {
if !args.SplitMainPanel {
return false
}
mainPanelSplitMode := args.UserConfig.Gui.MainPanelSplitMode
switch mainPanelSplitMode {
case "vertical":
return false
case "horizontal":
return true
default:
if args.Width < 200 && args.Height > 30 { // 2 80 character width panels + 40 width for side panel
return false
}
return true
}
}
func getExtrasWindowSize(args WindowArrangementArgs) int {
var baseSize int
// The 'extras' window contains the command log context
if args.CurrentWindow == "extras" {
baseSize = 1000 // my way of saying 'fill the available space'
} else if args.Height < 40 {
baseSize = 1
} else {
baseSize = args.UserConfig.Gui.CommandLogSize
}
frameSize := 2
return baseSize + frameSize
}
// The stash window by default only contains one line so that it's not hogging
// too much space, but if you access it it should take up some space. This is
// the default behaviour when accordion mode is NOT in effect. If it is in effect
// then when it's accessed it will have weight 2, not 1.
func getDefaultStashWindowBox(args WindowArrangementArgs) *boxlayout.Box {
box := &boxlayout.Box{Window: "stash"}
// if the stash window is anywhere in our stack we should enlargen it
if args.CurrentSideWindow == "stash" {
box.Weight = 1
} else {
box.Size = 3
}
return box
}
func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) []*boxlayout.Box {
return func(width int, height int) []*boxlayout.Box {
if args.ScreenMode == types.SCREEN_FULL || args.ScreenMode == types.SCREEN_HALF {
fullHeightBox := func(window string) *boxlayout.Box {
if window == args.CurrentSideWindow {
return &boxlayout.Box{
Window: window,
Weight: 1,
}
}
return &boxlayout.Box{
Window: window,
Size: 0,
}
}
return []*boxlayout.Box{
fullHeightBox("status"),
fullHeightBox("files"),
fullHeightBox("branches"),
fullHeightBox("commits"),
fullHeightBox("stash"),
}
} else if height >= 28 {
accordionMode := args.UserConfig.Gui.ExpandFocusedSidePanel
accordionBox := func(defaultBox *boxlayout.Box) *boxlayout.Box {
if accordionMode && defaultBox.Window == args.CurrentSideWindow {
return &boxlayout.Box{
Window: defaultBox.Window,
Weight: args.UserConfig.Gui.ExpandedSidePanelWeight,
}
}
return defaultBox
}
return []*boxlayout.Box{
{
Window: "status",
Size: 3,
},
accordionBox(&boxlayout.Box{Window: "files", Weight: 1}),
accordionBox(&boxlayout.Box{Window: "branches", Weight: 1}),
accordionBox(&boxlayout.Box{Window: "commits", Weight: 1}),
accordionBox(getDefaultStashWindowBox(args)),
}
}
squashedHeight := 1
if height >= 21 {
squashedHeight = 3
}
squashedSidePanelBox := func(window string) *boxlayout.Box {
if window == args.CurrentSideWindow {
return &boxlayout.Box{
Window: window,
Weight: 1,
}
}
return &boxlayout.Box{
Window: window,
Size: squashedHeight,
}
}
return []*boxlayout.Box{
squashedSidePanelBox("status"),
squashedSidePanelBox("files"),
squashedSidePanelBox("branches"),
squashedSidePanelBox("commits"),
squashedSidePanelBox("stash"),
}
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/record_directory_helper.go | pkg/gui/controllers/helpers/record_directory_helper.go | package helpers
import (
"os"
)
type RecordDirectoryHelper struct {
c *HelperCommon
}
func NewRecordDirectoryHelper(c *HelperCommon) *RecordDirectoryHelper {
return &RecordDirectoryHelper{
c: c,
}
}
// when a user runs lazygit with the LAZYGIT_NEW_DIR_FILE env variable defined
// we will write the current directory to that file on exit so that their
// shell can then change to that directory. That means you don't get kicked
// back to the directory that you started with.
func (self *RecordDirectoryHelper) RecordCurrentDirectory() error {
// determine current directory, set it in LAZYGIT_NEW_DIR_FILE
dirName, err := os.Getwd()
if err != nil {
return err
}
return self.RecordDirectory(dirName)
}
func (self *RecordDirectoryHelper) RecordDirectory(dirName string) error {
newDirFilePath := os.Getenv("LAZYGIT_NEW_DIR_FILE")
if newDirFilePath == "" {
return nil
}
return self.c.OS().CreateFileWithContent(newDirFilePath, dirName)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/patch_building_helper.go | pkg/gui/controllers/helpers/patch_building_helper.go | package helpers
import (
"errors"
"fmt"
"github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/gui/keybindings"
"github.com/jesseduffield/lazygit/pkg/gui/patch_exploring"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type PatchBuildingHelper struct {
c *HelperCommon
}
func NewPatchBuildingHelper(
c *HelperCommon,
) *PatchBuildingHelper {
return &PatchBuildingHelper{
c: c,
}
}
func (self *PatchBuildingHelper) ValidateNormalWorkingTreeState() (bool, error) {
if self.c.Git().Status.WorkingTreeState().Any() {
return false, errors.New(self.c.Tr.CantPatchWhileRebasingError)
}
return true, nil
}
func (self *PatchBuildingHelper) ShowHunkStagingHint() {
if !self.c.AppState.DidShowHunkStagingHint && self.c.UserConfig().Gui.UseHunkModeInStagingView {
self.c.AppState.DidShowHunkStagingHint = true
self.c.SaveAppStateAndLogError()
message := fmt.Sprintf(self.c.Tr.HunkStagingHint,
keybindings.Label(self.c.UserConfig().Keybinding.Main.ToggleSelectHunk))
self.c.Confirm(types.ConfirmOpts{
Prompt: message,
})
}
}
// takes us from the patch building panel back to the commit files panel
func (self *PatchBuildingHelper) Escape() {
self.c.Context().Pop()
}
// kills the custom patch and returns us back to the commit files panel if needed
func (self *PatchBuildingHelper) Reset() error {
self.c.Git().Patch.PatchBuilder.Reset()
if self.c.Context().CurrentStatic().GetKind() != types.SIDE_CONTEXT {
self.Escape()
}
self.c.Refresh(types.RefreshOptions{
Scope: []types.RefreshableView{types.COMMIT_FILES},
})
// refreshing the current context so that the secondary panel is hidden if necessary.
self.c.PostRefreshUpdate(self.c.Context().Current())
return nil
}
func (self *PatchBuildingHelper) RefreshPatchBuildingPanel(opts types.OnFocusOpts) {
selectedLineIdx := -1
if opts.ClickedWindowName == "main" {
selectedLineIdx = opts.ClickedViewLineIdx
}
if !self.c.Git().Patch.PatchBuilder.Active() {
self.Escape()
return
}
// get diff from commit file that's currently selected
path := self.c.Contexts().CommitFiles.GetSelectedPath()
if path == "" {
return
}
from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff()
from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from)
diff, err := self.c.Git().WorkingTree.ShowFileDiff(from, to, reverse, path, true)
if err != nil {
return
}
secondaryDiff := self.c.Git().Patch.PatchBuilder.RenderPatchForFile(patch.RenderPatchForFileOpts{
Filename: path,
Plain: false,
Reverse: false,
TurnAddedFilesIntoDiffAgainstEmptyFile: true,
})
context := self.c.Contexts().CustomPatchBuilder
oldState := context.GetState()
state := patch_exploring.NewState(diff, selectedLineIdx, context.GetView(), oldState, self.c.UserConfig().Gui.UseHunkModeInStagingView)
context.SetState(state)
if state == nil {
self.Escape()
return
}
mainContent := context.GetContentToRender()
self.c.Contexts().CustomPatchBuilder.FocusSelection()
self.c.RenderToMainViews(types.RefreshMainOpts{
Pair: self.c.MainViewPairs().PatchBuilding,
Main: &types.ViewUpdateOpts{
Task: types.NewRenderStringWithoutScrollTask(mainContent),
Title: self.c.Tr.Patch,
},
Secondary: &types.ViewUpdateOpts{
Task: types.NewRenderStringWithoutScrollTask(secondaryDiff),
Title: self.c.Tr.CustomPatch,
},
})
}
| 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_test.go | pkg/gui/controllers/helpers/fixup_helper_test.go | package helpers
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFixupHelper_parseDiff(t *testing.T) {
scenarios := []struct {
name string
diff string
expectedDeletedLineHunks []*hunk
expectedAddedLineHunks []*hunk
}{
{
name: "no diff",
diff: "",
expectedDeletedLineHunks: []*hunk{},
expectedAddedLineHunks: []*hunk{},
},
{
name: "hunk with only deleted lines",
diff: `
diff --git a/file1.txt b/file1.txt
index 9ce8efb33..aaf2a4666 100644
--- a/file1.txt
+++ b/file1.txt
@@ -3 +2,0 @@ bbb
-xxx
`,
expectedDeletedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 3,
numLines: 1,
},
},
expectedAddedLineHunks: []*hunk{},
},
{
name: "hunk with deleted and added lines",
diff: `
diff --git a/file1.txt b/file1.txt
index 9ce8efb33..eb246cf98 100644
--- a/file1.txt
+++ b/file1.txt
@@ -3 +3 @@ bbb
-xxx
+yyy
`,
expectedDeletedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 3,
numLines: 1,
},
},
expectedAddedLineHunks: []*hunk{},
},
{
name: "hunk with only added lines",
diff: `
diff --git a/file1.txt b/file1.txt
index 9ce8efb33..fb5e469e7 100644
--- a/file1.txt
+++ b/file1.txt
@@ -4,0 +5,2 @@ ddd
+xxx
+yyy
`,
expectedDeletedLineHunks: []*hunk{},
expectedAddedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 4,
numLines: 2,
},
},
},
{
name: "hunk with dashed lines",
diff: `
diff --git a/file1.txt b/file1.txt
index 9ce8efb33..fb5e469e7 100644
--- a/file1.txt
+++ b/file1.txt
@@ -3,1 +3,1 @@
--- xxx
+-- yyy
`,
expectedDeletedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 3,
numLines: 1,
},
},
expectedAddedLineHunks: []*hunk{},
},
{
name: "several hunks in different files",
diff: `
diff --git a/file1.txt b/file1.txt
index 9ce8efb33..0632e41b0 100644
--- a/file1.txt
+++ b/file1.txt
@@ -2 +1,0 @@ aaa
-bbb
@@ -4 +3 @@ ccc
-ddd
+xxx
@@ -6,0 +6 @@ fff
+zzz
diff --git a/file2.txt b/file2.txt
index 9ce8efb33..0632e41b0 100644
--- a/file2.txt
+++ b/file2.txt
@@ -0,3 +1,0 @@ aaa
-aaa
-bbb
-ccc
`,
expectedDeletedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 2,
numLines: 1,
},
{
filename: "file1.txt",
startLineIdx: 4,
numLines: 1,
},
{
filename: "file2.txt",
startLineIdx: 0,
numLines: 3,
},
},
expectedAddedLineHunks: []*hunk{
{
filename: "file1.txt",
startLineIdx: 6,
numLines: 1,
},
},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
deletedLineHunks, addedLineHunks := parseDiff(s.diff)
assert.Equal(t, s.expectedDeletedLineHunks, deletedLineHunks)
assert.Equal(t, s.expectedAddedLineHunks, addedLineHunks)
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/amend_helper.go | pkg/gui/controllers/helpers/amend_helper.go | package helpers
import "github.com/jesseduffield/lazygit/pkg/commands/git_commands"
type AmendHelper struct {
c *HelperCommon
gpg *GpgHelper
}
func NewAmendHelper(
c *HelperCommon,
gpg *GpgHelper,
) *AmendHelper {
return &AmendHelper{
c: c,
gpg: gpg,
}
}
func (self *AmendHelper) AmendHead() error {
cmdObj := self.c.Git().Commit.AmendHeadCmdObj()
self.c.LogAction(self.c.Tr.Actions.AmendCommit)
return self.gpg.WithGpgHandling(cmdObj, git_commands.CommitGpgSign, self.c.Tr.AmendingStatus, nil, nil)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/refs_helper.go | pkg/gui/controllers/helpers/refs_helper.go | package helpers
import (
"fmt"
"strings"
"text/template"
"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/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
type RefsHelper struct {
c *HelperCommon
rebaseHelper *MergeAndRebaseHelper
}
func NewRefsHelper(
c *HelperCommon,
rebaseHelper *MergeAndRebaseHelper,
) *RefsHelper {
return &RefsHelper{
c: c,
rebaseHelper: rebaseHelper,
}
}
func (self *RefsHelper) SelectFirstBranchAndFirstCommit() {
self.c.Contexts().Branches.SetSelection(0)
self.c.Contexts().ReflogCommits.SetSelection(0)
self.c.Contexts().LocalCommits.SetSelection(0)
self.c.Contexts().Branches.GetView().SetOriginY(0)
self.c.Contexts().ReflogCommits.GetView().SetOriginY(0)
self.c.Contexts().LocalCommits.GetView().SetOriginY(0)
}
func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions) error {
waitingStatus := options.WaitingStatus
if waitingStatus == "" {
waitingStatus = self.c.Tr.CheckingOutStatus
}
cmdOptions := git_commands.CheckoutOptions{Force: false, EnvVars: options.EnvVars}
refresh := func() {
self.SelectFirstBranchAndFirstCommit()
// loading a heap of commits is slow so we limit them whenever doing a reset
self.c.Contexts().LocalCommits.SetLimitCommits(true)
self.c.Refresh(types.RefreshOptions{Mode: types.BLOCK_UI, KeepBranchSelectionIndex: true})
}
localBranch, found := lo.Find(self.c.Model().Branches, func(branch *models.Branch) bool {
return branch.Name == ref
})
withCheckoutStatus := func(f func(gocui.Task) error) error {
if found {
return self.c.WithInlineStatus(localBranch, types.ItemOperationCheckingOut, context.LOCAL_BRANCHES_CONTEXT_KEY, f)
}
return self.c.WithWaitingStatus(waitingStatus, f)
}
// Switch to the branches context _before_ starting to check out the branch, so that we see the
// inline status. This is a no-op if the branches panel is already focused.
self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{})
return withCheckoutStatus(func(gocui.Task) error {
if err := self.c.Git().Branch.Checkout(ref, cmdOptions); err != nil {
// note, this will only work for english-language git commands. If we force git to use english, and the error isn't this one, then the user will receive an english command they may not understand. I'm not sure what the best solution to this is. Running the command once in english and a second time in the native language is one option
if options.OnRefNotFound != nil && strings.Contains(err.Error(), "did not match any file(s) known to git") {
return options.OnRefNotFound(ref)
}
if IsSwitchBranchUncommittedChangesError(err) {
// offer to autostash changes
self.c.OnUIThread(func() error {
// (Before showing the prompt, render again to remove the inline status)
self.c.Contexts().Branches.HandleRender()
self.c.Confirm(types.ConfirmOpts{
Title: self.c.Tr.AutoStashTitle,
Prompt: self.c.Tr.AutoStashPrompt,
HandleConfirm: func() error {
return withCheckoutStatus(func(gocui.Task) error {
if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForCheckout, ref)); err != nil {
return err
}
if err := self.c.Git().Branch.Checkout(ref, cmdOptions); err != nil {
return err
}
err := self.c.Git().Stash.Pop(0)
// Branch switch successful so re-render the UI even if the pop operation failed (e.g. conflict).
refresh()
return err
})
},
})
return nil
})
return nil
}
return err
}
refresh()
return nil
})
}
// Shows a prompt to choose between creating a new branch or checking out a detached head
func (self *RefsHelper) CheckoutRemoteBranch(fullBranchName string, localBranchName string) error {
checkout := func(branchName string) error {
return self.CheckoutRef(branchName, types.CheckoutRefOptions{})
}
// If a branch with this name already exists locally, just check it out. We
// don't bother checking whether it actually tracks this remote branch, since
// it's very unlikely that it doesn't.
if lo.ContainsBy(self.c.Model().Branches, func(branch *models.Branch) bool {
return branch.Name == localBranchName
}) {
return checkout(localBranchName)
}
return self.c.Menu(types.CreateMenuOptions{
Title: utils.ResolvePlaceholderString(self.c.Tr.RemoteBranchCheckoutTitle, map[string]string{
"branchName": fullBranchName,
}),
Prompt: self.c.Tr.RemoteBranchCheckoutPrompt,
Items: []*types.MenuItem{
{
Label: self.c.Tr.CheckoutTypeNewBranch,
Tooltip: self.c.Tr.CheckoutTypeNewBranchTooltip,
OnPress: func() error {
// First create the local branch with the upstream set, and
// then check it out. We could do that in one step using
// "git checkout -b", but we want to benefit from all the
// nice features of the CheckoutRef function.
if err := self.c.Git().Branch.CreateWithUpstream(localBranchName, fullBranchName); err != nil {
return err
}
// Do a sync refresh to make sure the new branch is visible,
// so that we see an inline status when checking it out
self.c.Refresh(types.RefreshOptions{
Mode: types.SYNC,
Scope: []types.RefreshableView{types.BRANCHES},
})
return checkout(localBranchName)
},
},
{
Label: self.c.Tr.CheckoutTypeDetachedHead,
Tooltip: self.c.Tr.CheckoutTypeDetachedHeadTooltip,
OnPress: func() error {
return checkout(fullBranchName)
},
},
},
})
}
func (self *RefsHelper) CheckoutPreviousRef() error {
previousRef, err := self.c.Git().Branch.PreviousRef()
if err == nil && strings.HasPrefix(previousRef, "refs/heads/") {
return self.CheckoutRef(strings.TrimPrefix(previousRef, "refs/heads/"), types.CheckoutRefOptions{})
}
return self.CheckoutRef("-", types.CheckoutRefOptions{})
}
func (self *RefsHelper) GetCheckedOutRef() *models.Branch {
if len(self.c.Model().Branches) == 0 {
return nil
}
return self.c.Model().Branches[0]
}
func (self *RefsHelper) ResetToRef(ref string, strength string, envVars []string) error {
if err := self.c.Git().Commit.ResetToCommit(ref, strength, envVars); err != nil {
return err
}
self.c.Contexts().LocalCommits.SetSelection(0)
self.c.Contexts().ReflogCommits.SetSelection(0)
// loading a heap of commits is slow so we limit them whenever doing a reset
self.c.Contexts().LocalCommits.SetLimitCommits(true)
self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.BRANCHES, types.REFLOG, types.COMMITS}})
return nil
}
func (self *RefsHelper) CreateSortOrderMenu(sortOptionsOrder []string, menuPrompt string, onSelected func(sortOrder string) error, currentValue string) error {
type sortMenuOption struct {
key types.Key
label string
description string
sortOrder string
}
availableSortOptions := map[string]sortMenuOption{
"recency": {label: self.c.Tr.SortByRecency, description: self.c.Tr.SortBasedOnReflog, key: 'r'},
"alphabetical": {label: self.c.Tr.SortAlphabetical, description: "--sort=refname", key: 'a'},
"date": {label: self.c.Tr.SortByDate, description: "--sort=-committerdate", key: 'd'},
}
sortOptions := make([]sortMenuOption, 0, len(sortOptionsOrder))
for _, key := range sortOptionsOrder {
sortOption, ok := availableSortOptions[key]
if !ok {
panic(fmt.Sprintf("unexpected sort order: %s", key))
}
sortOption.sortOrder = key
sortOptions = append(sortOptions, sortOption)
}
menuItems := lo.Map(sortOptions, func(opt sortMenuOption, _ int) *types.MenuItem {
return &types.MenuItem{
LabelColumns: []string{
opt.label,
style.FgYellow.Sprint(opt.description),
},
OnPress: func() error {
return onSelected(opt.sortOrder)
},
Key: opt.key,
Widget: types.MakeMenuRadioButton(opt.sortOrder == currentValue),
}
})
return self.c.Menu(types.CreateMenuOptions{
Title: self.c.Tr.SortOrder,
Items: menuItems,
Prompt: menuPrompt,
})
}
func (self *RefsHelper) CreateGitResetMenu(name string, ref string) error {
type strengthWithKey struct {
strength string
label string
key types.Key
tooltip string
}
strengths := []strengthWithKey{
// not i18'ing because it's git terminology
{strength: "mixed", label: "Mixed reset", key: 'm', tooltip: self.c.Tr.ResetMixedTooltip},
{strength: "soft", label: "Soft reset", key: 's', tooltip: self.c.Tr.ResetSoftTooltip},
{strength: "hard", label: "Hard reset", key: 'h', tooltip: self.c.Tr.ResetHardTooltip},
}
menuItems := lo.Map(strengths, func(row strengthWithKey, _ int) *types.MenuItem {
return &types.MenuItem{
LabelColumns: []string{
row.label,
style.FgRed.Sprintf("reset --%s %s", row.strength, name),
},
OnPress: func() error {
return self.c.ConfirmIf(row.strength == "hard" && 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("Reset")
return self.ResetToRef(ref, row.strength, []string{})
},
})
},
Key: row.key,
Tooltip: row.tooltip,
}
})
return self.c.Menu(types.CreateMenuOptions{
Title: fmt.Sprintf("%s %s", self.c.Tr.ResetTo, name),
Items: menuItems,
})
}
func (self *RefsHelper) CreateCheckoutMenu(commit *models.Commit) error {
branches := lo.Filter(self.c.Model().Branches, func(branch *models.Branch, _ int) bool {
return commit.Hash() == branch.CommitHash && branch.Name != self.c.Model().CheckedOutBranch
})
hash := commit.Hash()
menuItems := []*types.MenuItem{
{
LabelColumns: []string{fmt.Sprintf(self.c.Tr.Actions.CheckoutCommitAsDetachedHead, utils.ShortHash(hash))},
OnPress: func() error {
self.c.LogAction(self.c.Tr.Actions.CheckoutCommit)
return self.CheckoutRef(hash, types.CheckoutRefOptions{})
},
Key: 'd',
},
}
if len(branches) > 0 {
menuItems = append(menuItems, lo.Map(branches, func(branch *models.Branch, index int) *types.MenuItem {
var key types.Key
if index < 9 {
key = rune(index + 1 + '0') // Convert 1-based index to key
}
return &types.MenuItem{
LabelColumns: []string{fmt.Sprintf(self.c.Tr.Actions.CheckoutBranchAtCommit, branch.Name)},
OnPress: func() error {
self.c.LogAction(self.c.Tr.Actions.CheckoutBranch)
return self.CheckoutRef(branch.RefName(), types.CheckoutRefOptions{})
},
Key: key,
}
})...)
} else {
menuItems = append(menuItems, &types.MenuItem{
LabelColumns: []string{self.c.Tr.Actions.CheckoutBranch},
OnPress: func() error { return nil },
DisabledReason: &types.DisabledReason{Text: self.c.Tr.NoBranchesFoundAtCommitTooltip},
Key: '1',
})
}
return self.c.Menu(types.CreateMenuOptions{
Title: self.c.Tr.Actions.CheckoutBranchOrCommit,
Items: menuItems,
})
}
func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggestedBranchName string) error {
message := utils.ResolvePlaceholderString(
self.c.Tr.NewBranchNameBranchOff,
map[string]string{
"branchName": fromFormattedName,
},
)
if suggestedBranchName == "" {
var err error
suggestedBranchName, err = self.getSuggestedBranchName()
if err != nil {
return err
}
}
refresh := func() {
if self.c.Context().Current() != self.c.Contexts().Branches {
self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{})
}
self.SelectFirstBranchAndFirstCommit()
self.c.Refresh(types.RefreshOptions{Mode: types.BLOCK_UI, KeepBranchSelectionIndex: true})
}
self.c.Prompt(types.PromptOpts{
Title: message,
InitialContent: suggestedBranchName,
HandleConfirm: func(response string) error {
self.c.LogAction(self.c.Tr.Actions.CreateBranch)
newBranchName := SanitizedBranchName(response)
newBranchFunc := self.c.Git().Branch.New
if newBranchName != suggestedBranchName {
newBranchFunc = self.c.Git().Branch.NewWithoutTracking
}
if err := newBranchFunc(newBranchName, from); err != nil {
if IsSwitchBranchUncommittedChangesError(err) {
// offer to autostash changes
self.c.Confirm(types.ConfirmOpts{
Title: self.c.Tr.AutoStashTitle,
Prompt: self.c.Tr.AutoStashPrompt,
HandleConfirm: func() error {
if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil {
return err
}
if err := newBranchFunc(newBranchName, from); err != nil {
return err
}
err := self.c.Git().Stash.Pop(0)
// Branch switch successful so re-render the UI even if the pop operation failed (e.g. conflict).
refresh()
return err
},
})
return nil
}
return err
}
refresh()
return nil
},
})
return nil
}
func (self *RefsHelper) MoveCommitsToNewBranch() error {
currentBranch := self.c.Model().Branches[0]
baseBranchRef, err := self.c.Git().Loaders.BranchLoader.GetBaseBranch(currentBranch, self.c.Model().MainBranches)
if err != nil {
return err
}
withNewBranchNamePrompt := func(baseBranchName string, f func(string) error) error {
prompt := utils.ResolvePlaceholderString(
self.c.Tr.NewBranchNameBranchOff,
map[string]string{
"branchName": baseBranchName,
},
)
suggestedBranchName, err := self.getSuggestedBranchName()
if err != nil {
return err
}
self.c.Prompt(types.PromptOpts{
Title: prompt,
InitialContent: suggestedBranchName,
HandleConfirm: func(response string) error {
self.c.LogAction(self.c.Tr.MoveCommitsToNewBranch)
newBranchName := SanitizedBranchName(response)
return self.c.WithWaitingStatus(self.c.Tr.MovingCommitsToNewBranchStatus, func(gocui.Task) error {
return f(newBranchName)
})
},
})
return nil
}
isMainBranch := lo.Contains(self.c.UserConfig().Git.MainBranches, currentBranch.Name)
if isMainBranch {
prompt := utils.ResolvePlaceholderString(
self.c.Tr.MoveCommitsToNewBranchFromMainPrompt,
map[string]string{
"baseBranchName": currentBranch.Name,
},
)
self.c.Confirm(types.ConfirmOpts{
Title: self.c.Tr.MoveCommitsToNewBranch,
Prompt: prompt,
HandleConfirm: func() error {
return withNewBranchNamePrompt(currentBranch.Name, self.moveCommitsToNewBranchStackedOnCurrentBranch)
},
})
return nil
}
shortBaseBranchName := ShortBranchName(baseBranchRef)
prompt := utils.ResolvePlaceholderString(
self.c.Tr.MoveCommitsToNewBranchMenuPrompt,
map[string]string{
"baseBranchName": shortBaseBranchName,
},
)
return self.c.Menu(types.CreateMenuOptions{
Title: self.c.Tr.MoveCommitsToNewBranch,
Prompt: prompt,
Items: []*types.MenuItem{
{
Label: fmt.Sprintf(self.c.Tr.MoveCommitsToNewBranchFromBaseItem, shortBaseBranchName),
OnPress: func() error {
return withNewBranchNamePrompt(shortBaseBranchName, func(newBranchName string) error {
return self.moveCommitsToNewBranchOffOfMainBranch(newBranchName, baseBranchRef)
})
},
},
{
Label: fmt.Sprintf(self.c.Tr.MoveCommitsToNewBranchStackedItem, currentBranch.Name),
OnPress: func() error {
return withNewBranchNamePrompt(currentBranch.Name, self.moveCommitsToNewBranchStackedOnCurrentBranch)
},
},
},
})
}
func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchName string) error {
if err := self.c.Git().Branch.NewWithoutCheckout(newBranchName, "HEAD"); err != nil {
return err
}
mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules)
if mustStash {
if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil {
return err
}
}
if err := self.c.Git().Commit.ResetToCommit("@{u}", "hard", []string{}); err != nil {
return err
}
if err := self.c.Git().Branch.Checkout(newBranchName, git_commands.CheckoutOptions{}); err != nil {
return err
}
if mustStash {
if err := self.c.Git().Stash.Pop(0); err != nil {
return err
}
}
self.SelectFirstBranchAndFirstCommit()
self.c.Refresh(types.RefreshOptions{Mode: types.BLOCK_UI, KeepBranchSelectionIndex: true})
return nil
}
func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName string, baseBranchRef string) error {
commitsToCherryPick := lo.Filter(self.c.Model().Commits, func(commit *models.Commit, _ int) bool {
return commit.Status == models.StatusUnpushed
})
mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules)
if mustStash {
if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil {
return err
}
}
if err := self.c.Git().Commit.ResetToCommit("@{u}", "hard", []string{}); err != nil {
return err
}
if err := self.c.Git().Branch.NewWithoutTracking(newBranchName, baseBranchRef); err != nil {
return err
}
err := self.c.Git().Rebase.CherryPickCommits(commitsToCherryPick)
err = self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(err, types.RefreshOptions{Mode: types.SYNC})
if err != nil {
return err
}
if mustStash {
if err := self.c.Git().Stash.Pop(0); err != nil {
return err
}
}
self.SelectFirstBranchAndFirstCommit()
self.c.Refresh(types.RefreshOptions{Mode: types.BLOCK_UI, KeepBranchSelectionIndex: true})
return nil
}
func (self *RefsHelper) CanMoveCommitsToNewBranch() *types.DisabledReason {
if len(self.c.Model().Branches) == 0 {
return &types.DisabledReason{Text: self.c.Tr.NoBranchesThisRepo}
}
currentBranch := self.GetCheckedOutRef()
if currentBranch.DetachedHead {
return &types.DisabledReason{Text: self.c.Tr.CannotMoveCommitsFromDetachedHead, ShowErrorInPanel: true}
}
if !currentBranch.RemoteBranchStoredLocally() {
return &types.DisabledReason{Text: self.c.Tr.CannotMoveCommitsNoUpstream, ShowErrorInPanel: true}
}
if currentBranch.IsBehindForPull() {
return &types.DisabledReason{Text: self.c.Tr.CannotMoveCommitsBehindUpstream, ShowErrorInPanel: true}
}
if !currentBranch.IsAheadForPull() {
return &types.DisabledReason{Text: self.c.Tr.CannotMoveCommitsNoUnpushedCommits, ShowErrorInPanel: true}
}
return nil
}
// SanitizedBranchName will remove all spaces in favor of a dash "-" to meet
// git's branch naming requirement.
func SanitizedBranchName(input string) string {
return strings.ReplaceAll(input, " ", "-")
}
// Checks if the given branch name is a remote branch, and returns the name of
// the remote and the bare branch name if it is.
func (self *RefsHelper) ParseRemoteBranchName(fullBranchName string) (string, string, bool) {
remoteName, branchName, found := strings.Cut(fullBranchName, "/")
if !found {
return "", "", false
}
// See if the part before the first slash is actually one of our remotes
if !lo.ContainsBy(self.c.Model().Remotes, func(remote *models.Remote) bool {
return remote.Name == remoteName
}) {
return "", "", false
}
return remoteName, branchName, true
}
func IsSwitchBranchUncommittedChangesError(err error) bool {
return strings.Contains(err.Error(), "Please commit your changes or stash them before you switch branch")
}
func (self *RefsHelper) getSuggestedBranchName() (string, error) {
suggestedBranchName, err := utils.ResolveTemplate(self.c.UserConfig().Git.BranchPrefix, nil, template.FuncMap{
"runCommand": self.c.Git().Custom.TemplateFunctionRunCommand,
})
if err != nil {
return suggestedBranchName, err
}
suggestedBranchName = strings.ReplaceAll(suggestedBranchName, "\t", " ")
return suggestedBranchName, nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/snake_helper.go | pkg/gui/controllers/helpers/snake_helper.go | package helpers
import (
"errors"
"fmt"
"strings"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/snake"
)
type SnakeHelper struct {
c *HelperCommon
game *snake.Game
}
func NewSnakeHelper(c *HelperCommon) *SnakeHelper {
return &SnakeHelper{
c: c,
}
}
func (self *SnakeHelper) StartGame() {
view := self.c.Views().Snake
game := snake.NewGame(view.InnerWidth(), view.InnerHeight(), self.renderSnakeGame, self.c.LogAction)
self.game = game
game.Start()
}
func (self *SnakeHelper) ExitGame() {
self.game.Exit()
}
func (self *SnakeHelper) SetDirection(direction snake.Direction) {
self.game.SetDirection(direction)
}
func (self *SnakeHelper) renderSnakeGame(cells [][]snake.CellType, alive bool) {
view := self.c.Views().Snake
if !alive {
self.c.OnUIThread(func() error { return errors.New(self.c.Tr.YouDied) })
return
}
output := self.drawSnakeGame(cells)
view.Clear()
fmt.Fprint(view, output)
self.c.Render()
}
func (self *SnakeHelper) drawSnakeGame(cells [][]snake.CellType) string {
writer := &strings.Builder{}
for i, row := range cells {
for _, cell := range row {
switch cell {
case snake.None:
writer.WriteString(" ")
case snake.Snake:
writer.WriteString("█")
case snake.Food:
writer.WriteString(style.FgMagenta.Sprint("█"))
}
}
if i < len(cells) {
writer.WriteString("\n")
}
}
output := writer.String()
return output
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/suspend_resume_helper.go | pkg/gui/controllers/helpers/suspend_resume_helper.go | package helpers
type SuspendResumeHelper struct {
c *HelperCommon
}
func NewSuspendResumeHelper(c *HelperCommon) *SuspendResumeHelper {
return &SuspendResumeHelper{
c: c,
}
}
func (s *SuspendResumeHelper) CanSuspendApp() bool {
return canSuspendApp()
}
func (s *SuspendResumeHelper) SuspendApp() error {
if !canSuspendApp() {
return nil
}
if err := s.c.Suspend(); err != nil {
return err
}
return sendStopSignal()
}
func (s *SuspendResumeHelper) InstallResumeSignalHandler() {
installResumeSignalHandler(s.c.Log, s.c.Resume)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/helpers.go | pkg/gui/controllers/helpers/helpers.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type HelperCommon struct {
*common.Common
types.IGuiCommon
IGetContexts
}
type IGetContexts interface {
Contexts() *context.ContextTree
}
type Helpers struct {
Refs *RefsHelper
Bisect *BisectHelper
Suggestions *SuggestionsHelper
Files *FilesHelper
WorkingTree *WorkingTreeHelper
BranchesHelper *BranchesHelper
Tags *TagsHelper
MergeAndRebase *MergeAndRebaseHelper
MergeConflicts *MergeConflictsHelper
CherryPick *CherryPickHelper
Host *HostHelper
PatchBuilding *PatchBuildingHelper
Staging *StagingHelper
GPG *GpgHelper
Upstream *UpstreamHelper
AmendHelper *AmendHelper
FixupHelper *FixupHelper
Commits *CommitsHelper
SuspendResume *SuspendResumeHelper
Snake *SnakeHelper
// lives in context package because our contexts need it to render to main
Diff *DiffHelper
Repos *ReposHelper
RecordDirectory *RecordDirectoryHelper
Update *UpdateHelper
Window *WindowHelper
View *ViewHelper
Refresh *RefreshHelper
Confirmation *ConfirmationHelper
Mode *ModeHelper
AppStatus *AppStatusHelper
InlineStatus *InlineStatusHelper
WindowArrangement *WindowArrangementHelper
Search *SearchHelper
Worktree *WorktreeHelper
SubCommits *SubCommitsHelper
}
func NewStubHelpers() *Helpers {
return &Helpers{
Refs: &RefsHelper{},
Bisect: &BisectHelper{},
Suggestions: &SuggestionsHelper{},
Files: &FilesHelper{},
WorkingTree: &WorkingTreeHelper{},
Tags: &TagsHelper{},
MergeAndRebase: &MergeAndRebaseHelper{},
MergeConflicts: &MergeConflictsHelper{},
CherryPick: &CherryPickHelper{},
Host: &HostHelper{},
PatchBuilding: &PatchBuildingHelper{},
Staging: &StagingHelper{},
GPG: &GpgHelper{},
Upstream: &UpstreamHelper{},
AmendHelper: &AmendHelper{},
FixupHelper: &FixupHelper{},
Commits: &CommitsHelper{},
Snake: &SnakeHelper{},
Diff: &DiffHelper{},
Repos: &ReposHelper{},
RecordDirectory: &RecordDirectoryHelper{},
Update: &UpdateHelper{},
Window: &WindowHelper{},
View: &ViewHelper{},
Refresh: &RefreshHelper{},
Confirmation: &ConfirmationHelper{},
Mode: &ModeHelper{},
AppStatus: &AppStatusHelper{},
InlineStatus: &InlineStatusHelper{},
WindowArrangement: &WindowArrangementHelper{},
Search: &SearchHelper{},
Worktree: &WorktreeHelper{},
SubCommits: &SubCommitsHelper{},
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers/helpers/view_helper.go | pkg/gui/controllers/helpers/view_helper.go | package helpers
import (
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type ViewHelper struct {
c *HelperCommon
}
func NewViewHelper(c *HelperCommon, contexts *context.ContextTree) *ViewHelper {
return &ViewHelper{
c: c,
}
}
func (self *ViewHelper) ContextForView(viewName string) (types.Context, bool) {
view, err := self.c.GocuiGui().View(viewName)
if err != nil {
return nil, false
}
for _, context := range self.c.Contexts().Flatten() {
if context.GetViewName() == view.Name() {
return context, true
}
}
return nil, false
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/item_operations.go | pkg/gui/presentation/item_operations.go | package presentation
import (
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/i18n"
)
func ItemOperationToString(itemOperation types.ItemOperation, tr *i18n.TranslationSet) string {
switch itemOperation {
case types.ItemOperationNone:
return ""
case types.ItemOperationPushing:
return tr.PushingStatus
case types.ItemOperationPulling:
return tr.PullingStatus
case types.ItemOperationFastForwarding:
return tr.FastForwarding
case types.ItemOperationDeleting:
return tr.DeletingStatus
case types.ItemOperationFetching:
return tr.FetchingStatus
case types.ItemOperationCheckingOut:
return tr.CheckingOutStatus
}
return ""
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/files_test.go | pkg/gui/presentation/files_test.go | package presentation
import (
"strings"
"testing"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/filetree"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/stretchr/testify/assert"
"github.com/xo/terminfo"
)
func toStringSlice(str string) []string {
return strings.Split(strings.TrimSpace(str), "\n")
}
func TestRenderFileTree(t *testing.T) {
scenarios := []struct {
name string
root *filetree.FileNode
files []*models.File
collapsedPaths []string
showLineChanges bool
showRootItem bool
expected []string
}{
{
name: "nil node",
files: nil,
expected: []string{},
},
{
name: "leaf node",
files: []*models.File{
{Path: "test", ShortStatus: " M", HasStagedChanges: true},
},
showRootItem: true,
expected: []string{" M test"},
},
{
name: "numstat",
files: []*models.File{
{Path: "test", ShortStatus: " M", HasStagedChanges: true, LinesAdded: 1, LinesDeleted: 1},
{Path: "test2", ShortStatus: " M", HasStagedChanges: true, LinesAdded: 1},
{Path: "test3", ShortStatus: " M", HasStagedChanges: true, LinesDeleted: 1},
{Path: "test4", ShortStatus: " M", HasStagedChanges: true, LinesAdded: 0, LinesDeleted: 0},
},
showLineChanges: true,
showRootItem: true,
expected: []string{
"▼ /",
" M test +1 -1",
" M test2 +1",
" M test3 -1",
" M test4",
},
},
{
name: "big example",
files: []*models.File{
{Path: "dir1/file2", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir1/file3", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir2/dir2/file3", ShortStatus: " M", HasStagedChanges: true},
{Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir2/file5", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true},
},
showRootItem: true,
expected: toStringSlice(
`
▼ /
▶ dir1
▼ dir2
▼ dir2
M file3
M file4
M file5
M file1
`,
),
collapsedPaths: []string{"./dir1"},
},
{
name: "big example without root item",
files: []*models.File{
{Path: "dir1/file2", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir1/file3", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir2/dir2/file3", ShortStatus: " M", HasStagedChanges: true},
{Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "dir2/file5", ShortStatus: "M ", HasUnstagedChanges: true},
{Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true},
},
showRootItem: false,
expected: toStringSlice(
`
▶ dir1
▼ dir2
▼ dir2
M file3
M file4
M file5
M file1
`,
),
collapsedPaths: []string{"dir1"},
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelNone)
defer color.ForceSetColorLevel(oldColorLevel)
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
common := common.NewDummyCommon()
common.UserConfig().Gui.ShowRootItemInFileTree = s.showRootItem
viewModel := filetree.NewFileTree(func() []*models.File { return s.files }, common, true)
viewModel.SetTree()
for _, path := range s.collapsedPaths {
viewModel.ToggleCollapsed(path)
}
result := RenderFileTree(viewModel, nil, false, s.showLineChanges, &config.CustomIconsConfig{}, s.showRootItem)
assert.EqualValues(t, s.expected, result)
})
}
}
func TestRenderCommitFileTree(t *testing.T) {
scenarios := []struct {
name string
root *filetree.FileNode
files []*models.CommitFile
collapsedPaths []string
showRootItem bool
expected []string
}{
{
name: "nil node",
files: nil,
expected: []string{},
},
{
name: "leaf node",
files: []*models.CommitFile{
{Path: "test", ChangeStatus: "A"},
},
showRootItem: true,
expected: []string{"A test"},
},
{
name: "big example",
files: []*models.CommitFile{
{Path: "dir1/file2", ChangeStatus: "M"},
{Path: "dir1/file3", ChangeStatus: "A"},
{Path: "dir2/dir2/file3", ChangeStatus: "D"},
{Path: "dir2/dir2/file4", ChangeStatus: "M"},
{Path: "dir2/file5", ChangeStatus: "M"},
{Path: "file1", ChangeStatus: "M"},
},
showRootItem: true,
expected: toStringSlice(
`
▼ /
▶ dir1
▼ dir2
▼ dir2
D file3
M file4
M file5
M file1
`,
),
collapsedPaths: []string{"./dir1"},
},
{
name: "big example without root item",
files: []*models.CommitFile{
{Path: "dir1/file2", ChangeStatus: "M"},
{Path: "dir1/file3", ChangeStatus: "A"},
{Path: "dir2/dir2/file3", ChangeStatus: "D"},
{Path: "dir2/dir2/file4", ChangeStatus: "M"},
{Path: "dir2/file5", ChangeStatus: "M"},
{Path: "file1", ChangeStatus: "M"},
},
showRootItem: false,
expected: toStringSlice(
`
▶ dir1
▼ dir2
▼ dir2
D file3
M file4
M file5
M file1
`,
),
collapsedPaths: []string{"dir1"},
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelNone)
defer color.ForceSetColorLevel(oldColorLevel)
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
hashPool := &utils.StringPool{}
common := common.NewDummyCommon()
common.UserConfig().Gui.ShowRootItemInFileTree = s.showRootItem
viewModel := filetree.NewCommitFileTreeViewModel(func() []*models.CommitFile { return s.files }, common, true)
viewModel.SetRef(models.NewCommit(hashPool, models.NewCommitOpts{Hash: "1234"}))
viewModel.SetTree()
for _, path := range s.collapsedPaths {
viewModel.ToggleCollapsed(path)
}
patchBuilder := patch.NewPatchBuilder(
utils.NewDummyLog(),
func(from string, to string, reverse bool, filename string, plain bool) (string, error) {
return "", nil
},
)
patchBuilder.Start("from", "to", false, false)
result := RenderCommitFileTree(viewModel, patchBuilder, false, &config.CustomIconsConfig{})
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/presentation/loader.go | pkg/gui/presentation/loader.go | package presentation
import (
"time"
"github.com/jesseduffield/lazygit/pkg/config"
)
// Loader dumps a string to be displayed as a loader
func Loader(now time.Time, config config.SpinnerConfig) string {
milliseconds := now.UnixMilli()
index := milliseconds / int64(config.Rate) % int64(len(config.Frames))
return config.Frames[index]
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/status.go | pkg/gui/presentation/status.go | package presentation
import (
"fmt"
"time"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/config"
"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/i18n"
)
func FormatStatus(
repoName string,
currentBranch *models.Branch,
itemOperation types.ItemOperation,
linkedWorktreeName string,
workingTreeState models.WorkingTreeState,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) string {
status := ""
if currentBranch.IsRealBranch() {
status += BranchStatus(currentBranch, itemOperation, tr, time.Now(), userConfig)
if status != "" {
status += " "
}
}
if workingTreeState.Any() {
status += style.FgYellow.Sprintf("(%s) ", workingTreeState.LowerCaseTitle(tr))
}
name := GetBranchTextStyle(currentBranch.Name).Sprint(currentBranch.Name)
// If the user is in a linked worktree (i.e. not the main worktree) we'll display that
if linkedWorktreeName != "" {
icon := ""
if icons.IsIconEnabled() {
icon = icons.LINKED_WORKTREE_ICON + " "
}
repoName = fmt.Sprintf("%s(%s%s)", repoName, icon, style.FgCyan.Sprint(linkedWorktreeName))
}
status += fmt.Sprintf("%s → %s", repoName, name)
return status
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/submodules.go | pkg/gui/presentation/submodules.go | package presentation
import (
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetSubmoduleListDisplayStrings(submodules []*models.SubmoduleConfig) [][]string {
return lo.Map(submodules, func(submodule *models.SubmoduleConfig, _ int) []string {
return getSubmoduleDisplayStrings(submodule)
})
}
func getSubmoduleDisplayStrings(s *models.SubmoduleConfig) []string {
name := s.Name
if s.ParentModule != nil {
count := 0
for p := s.ParentModule; p != nil; p = p.ParentModule {
count++
}
indentation := strings.Repeat(" ", count)
name = indentation + "- " + s.Name
}
return []string{theme.DefaultTextColor.Sprint(name)}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/tags.go | pkg/gui/presentation/tags.go | package presentation
import (
"time"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/config"
"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/i18n"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetTagListDisplayStrings(
tags []*models.Tag,
getItemOperation func(item types.HasUrn) types.ItemOperation,
diffName string,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) [][]string {
return lo.Map(tags, func(tag *models.Tag, _ int) []string {
diffed := tag.Name == diffName
return getTagDisplayStrings(tag, getItemOperation(tag), diffed, tr, userConfig)
})
}
// getTagDisplayStrings returns the display string of branch
func getTagDisplayStrings(
t *models.Tag,
itemOperation types.ItemOperation,
diffed bool,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) []string {
textStyle := theme.DefaultTextColor
if diffed {
textStyle = theme.DiffTerminalColor
}
res := make([]string, 0, 2)
if icons.IsIconEnabled() {
res = append(res, textStyle.Sprint(icons.IconForTag(t)))
}
descriptionColor := style.FgYellow
descriptionStr := descriptionColor.Sprint(t.Description())
itemOperationStr := ItemOperationToString(itemOperation, tr)
if itemOperationStr != "" {
descriptionStr = style.FgCyan.Sprint(itemOperationStr+" "+Loader(time.Now(), userConfig.Gui.Spinner)) + " " + descriptionStr
}
res = append(res, textStyle.Sprint(t.Name), descriptionStr)
return res
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/stash_entries.go | pkg/gui/presentation/stash_entries.go | package presentation
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetStashEntryListDisplayStrings(stashEntries []*models.StashEntry, diffName string) [][]string {
return lo.Map(stashEntries, func(stashEntry *models.StashEntry, _ int) []string {
diffed := stashEntry.RefName() == diffName
return getStashEntryDisplayStrings(stashEntry, diffed)
})
}
// getStashEntryDisplayStrings returns the display string of branch
func getStashEntryDisplayStrings(s *models.StashEntry, diffed bool) []string {
textStyle := theme.DefaultTextColor
if diffed {
textStyle = theme.DiffTerminalColor
}
res := make([]string, 0, 3)
res = append(res, style.FgCyan.Sprint(s.Recency))
if icons.IsIconEnabled() {
res = append(res, textStyle.Sprint(icons.IconForStash(s)))
}
res = append(res, textStyle.Sprint(s.Name))
return res
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/suggestions.go | pkg/gui/presentation/suggestions.go | package presentation
import (
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
func GetSuggestionListDisplayStrings(suggestions []*types.Suggestion) [][]string {
return lo.Map(suggestions, func(suggestion *types.Suggestion, _ int) []string {
return getSuggestionDisplayStrings(suggestion)
})
}
func getSuggestionDisplayStrings(suggestion *types.Suggestion) []string {
return []string{suggestion.Label}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/remote_branches.go | pkg/gui/presentation/remote_branches.go | package presentation
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetRemoteBranchListDisplayStrings(branches []*models.RemoteBranch, diffName string) [][]string {
return lo.Map(branches, func(branch *models.RemoteBranch, _ int) []string {
diffed := branch.FullName() == diffName
return getRemoteBranchDisplayStrings(branch, diffed)
})
}
// getRemoteBranchDisplayStrings returns the display string of branch
func getRemoteBranchDisplayStrings(b *models.RemoteBranch, diffed bool) []string {
textStyle := GetBranchTextStyle(b.Name)
if diffed {
textStyle = theme.DiffTerminalColor
}
res := make([]string, 0, 2)
if icons.IsIconEnabled() {
res = append(res, textStyle.Sprint(icons.IconForRemoteBranch(b)))
}
res = append(res, textStyle.Sprint(b.Name))
return res
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/files.go | pkg/gui/presentation/files.go | package presentation
import (
"strings"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/filetree"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
)
const (
EXPANDED_ARROW = "▼"
COLLAPSED_ARROW = "▶"
)
func RenderFileTree(
tree filetree.IFileTree,
submoduleConfigs []*models.SubmoduleConfig,
showFileIcons bool,
showNumstat bool,
customIconsConfig *config.CustomIconsConfig,
showRootItem bool,
) []string {
collapsedPaths := tree.CollapsedPaths()
return renderAux(tree.GetRoot().Raw(), collapsedPaths, -1, -1, func(node *filetree.Node[models.File], treeDepth int, visualDepth int, isCollapsed bool) string {
fileNode := filetree.NewFileNode(node)
return getFileLine(isCollapsed, fileNode.GetHasUnstagedChanges(), fileNode.GetHasStagedChanges(), treeDepth, visualDepth, showNumstat, showFileIcons, submoduleConfigs, node, customIconsConfig, showRootItem)
})
}
func RenderCommitFileTree(
tree *filetree.CommitFileTreeViewModel,
patchBuilder *patch.PatchBuilder,
showFileIcons bool,
customIconsConfig *config.CustomIconsConfig,
) []string {
collapsedPaths := tree.CollapsedPaths()
return renderAux(tree.GetRoot().Raw(), collapsedPaths, -1, -1, func(node *filetree.Node[models.CommitFile], treeDepth int, visualDepth int, isCollapsed bool) string {
status := commitFilePatchStatus(node, tree, patchBuilder)
return getCommitFileLine(isCollapsed, treeDepth, visualDepth, node, status, showFileIcons, customIconsConfig)
})
}
// Returns the status of a commit file in terms of its inclusion in the custom patch
func commitFilePatchStatus(node *filetree.Node[models.CommitFile], tree *filetree.CommitFileTreeViewModel, patchBuilder *patch.PatchBuilder) patch.PatchStatus {
// This is a little convoluted because we're dealing with either a leaf or a non-leaf.
// But this code actually applies to both. If it's a leaf, the status will just
// be whatever status it is, but if it's a non-leaf it will determine its status
// based on the leaves of that subtree
if node.EveryFile(func(file *models.CommitFile) bool {
return patchBuilder.GetFileStatus(file.Path, tree.GetRef().RefName()) == patch.WHOLE
}) {
return patch.WHOLE
} else if node.EveryFile(func(file *models.CommitFile) bool {
return patchBuilder.GetFileStatus(file.Path, tree.GetRef().RefName()) == patch.UNSELECTED
}) {
return patch.UNSELECTED
}
return patch.PART
}
func renderAux[T any](
node *filetree.Node[T],
collapsedPaths *filetree.CollapsedPaths,
// treeDepth is the depth of the node in the actual file tree. This is different to
// visualDepth because some directory nodes are compressed e.g. 'pkg/gui/blah' takes
// up two tree depths, but one visual depth. We need to track these separately,
// because indentation relies on visual depth, whereas file path truncation
// relies on tree depth.
treeDepth int,
visualDepth int,
renderLine func(*filetree.Node[T], int, int, bool) string,
) []string {
if node == nil {
return []string{}
}
isRoot := treeDepth == -1
if node.IsFile() {
if isRoot {
return []string{}
}
return []string{renderLine(node, treeDepth, visualDepth, false)}
}
arr := []string{}
if !isRoot {
isCollapsed := collapsedPaths.IsCollapsed(node.GetInternalPath())
arr = append(arr, renderLine(node, treeDepth, visualDepth, isCollapsed))
}
if collapsedPaths.IsCollapsed(node.GetInternalPath()) {
return arr
}
for _, child := range node.Children {
arr = append(arr, renderAux(child, collapsedPaths, treeDepth+1+node.CompressionLevel, visualDepth+1, renderLine)...)
}
return arr
}
func getFileLine(
isCollapsed bool,
hasUnstagedChanges bool,
hasStagedChanges bool,
treeDepth int,
visualDepth int,
showNumstat,
showFileIcons bool,
submoduleConfigs []*models.SubmoduleConfig,
node *filetree.Node[models.File],
customIconsConfig *config.CustomIconsConfig,
showRootItem bool,
) string {
name := fileNameAtDepth(node, treeDepth, showRootItem)
output := ""
var nameColor style.TextStyle
file := node.File
indentation := strings.Repeat(" ", visualDepth)
if hasStagedChanges && !hasUnstagedChanges {
nameColor = style.FgGreen
} else if hasStagedChanges {
nameColor = style.FgYellow
} else {
nameColor = theme.DefaultTextColor
}
if file == nil {
output += indentation + ""
arrow := EXPANDED_ARROW
if isCollapsed {
arrow = COLLAPSED_ARROW
}
arrowStyle := nameColor
output += arrowStyle.Sprint(arrow) + " "
} else {
// Sprinting the space at the end in the specific style is for the sake of
// when a reverse style is used in the theme, which looks ugly if you just
// use the default style
output += indentation + formatFileStatus(file, nameColor) + nameColor.Sprint(" ")
}
isSubmodule := file != nil && file.IsSubmodule(submoduleConfigs)
isLinkedWorktree := file != nil && file.IsWorktree
isDirectory := file == nil
if showFileIcons {
icon := icons.IconForFile(name, isSubmodule, isLinkedWorktree, isDirectory, customIconsConfig)
paint := color.HEX(icon.Color, false)
output += paint.Sprint(icon.Icon) + nameColor.Sprint(" ")
}
output += nameColor.Sprint(utils.EscapeSpecialChars(name))
if isSubmodule {
output += theme.DefaultTextColor.Sprint(" (submodule)")
}
if file != nil && showNumstat {
if lineChanges := formatLineChanges(file.LinesAdded, file.LinesDeleted); lineChanges != "" {
output += " " + lineChanges
}
}
return output
}
func formatFileStatus(file *models.File, restColor style.TextStyle) string {
firstChar := file.ShortStatus[0:1]
firstCharCl := style.FgGreen
switch firstChar {
case "?":
firstCharCl = theme.UnstagedChangesColor
case " ":
firstCharCl = restColor
}
secondChar := file.ShortStatus[1:2]
secondCharCl := theme.UnstagedChangesColor
if secondChar == " " {
secondCharCl = restColor
}
return firstCharCl.Sprint(firstChar) + secondCharCl.Sprint(secondChar)
}
func formatLineChanges(linesAdded, linesDeleted int) string {
output := ""
if linesAdded != 0 {
output += style.FgGreen.Sprintf("+%d", linesAdded)
}
if linesDeleted != 0 {
if output != "" {
output += " "
}
output += style.FgRed.Sprintf("-%d", linesDeleted)
}
return output
}
func getCommitFileLine(
isCollapsed bool,
treeDepth int,
visualDepth int,
node *filetree.Node[models.CommitFile],
status patch.PatchStatus,
showFileIcons bool,
customIconsConfig *config.CustomIconsConfig,
) string {
indentation := strings.Repeat(" ", visualDepth)
name := commitFileNameAtDepth(node, treeDepth)
commitFile := node.File
output := indentation
isDirectory := commitFile == nil
nameColor := theme.DefaultTextColor
switch status {
case patch.WHOLE:
nameColor = style.FgGreen
case patch.PART:
nameColor = style.FgYellow
case patch.UNSELECTED:
nameColor = theme.DefaultTextColor
}
if isDirectory {
arrow := EXPANDED_ARROW
if isCollapsed {
arrow = COLLAPSED_ARROW
}
output += nameColor.Sprint(arrow) + " "
} else {
var symbol string
symbolStyle := nameColor
switch status {
case patch.WHOLE:
symbol = "●"
case patch.PART:
symbol = "◐"
case patch.UNSELECTED:
symbol = commitFile.ChangeStatus
symbolStyle = getColorForChangeStatus(symbol)
}
output += symbolStyle.Sprint(symbol) + " "
}
name = utils.EscapeSpecialChars(name)
isSubmodule := false
isLinkedWorktree := false
if showFileIcons {
icon := icons.IconForFile(name, isSubmodule, isLinkedWorktree, isDirectory, customIconsConfig)
paint := color.HEX(icon.Color, false)
output += paint.Sprint(icon.Icon) + " "
}
output += nameColor.Sprint(name)
return output
}
func getColorForChangeStatus(changeStatus string) style.TextStyle {
switch changeStatus {
case "A":
return style.FgGreen
case "M", "R":
return style.FgYellow
case "D":
return theme.UnstagedChangesColor
case "C":
return style.FgCyan
case "T":
return style.FgMagenta
default:
return theme.DefaultTextColor
}
}
func fileNameAtDepth(node *filetree.Node[models.File], depth int, showRootItem bool) string {
splitName := split(node.GetInternalPath())
if depth == 0 && splitName[0] == "." {
if len(splitName) == 1 {
return "/"
}
depth = 1
}
name := join(splitName[depth:])
if node.File != nil && node.File.IsRename() {
splitPrevName := filetree.SplitFileTreePath(node.File.PreviousPath, showRootItem)
prevName := node.File.PreviousPath
// if the file has just been renamed inside the same directory, we can shave off
// the prefix for the previous path too. Otherwise we'll keep it unchanged
sameParentDir := len(splitName) == len(splitPrevName) && join(splitName[0:depth]) == join(splitPrevName[0:depth])
if sameParentDir {
prevName = join(splitPrevName[depth:])
}
return prevName + " → " + name
}
return name
}
func commitFileNameAtDepth(node *filetree.Node[models.CommitFile], depth int) string {
splitName := split(node.GetInternalPath())
if depth == 0 && splitName[0] == "." {
if len(splitName) == 1 {
return "/"
}
depth = 1
}
name := join(splitName[depth:])
return name
}
func split(str string) []string {
return strings.Split(str, "/")
}
func join(strs []string) string {
return strings.Join(strs, "/")
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/commits_test.go | pkg/gui/presentation/commits_test.go | package presentation
import (
"os"
"strings"
"testing"
"time"
"github.com/gookit/color"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
"github.com/stefanhaller/git-todo-parser/todo"
"github.com/stretchr/testify/assert"
"github.com/xo/terminfo"
)
func formatExpected(expected string) string {
return strings.TrimSpace(strings.ReplaceAll(expected, "\t", ""))
}
func TestGetCommitListDisplayStrings(t *testing.T) {
scenarios := []struct {
testName string
commitOpts []models.NewCommitOpts
branches []*models.Branch
currentBranchName string
hasUpdateRefConfig bool
fullDescription bool
cherryPickedCommitHashSet *set.Set[string]
markedBaseCommit string
diffName string
timeFormat string
shortTimeFormat string
now time.Time
parseEmoji bool
selectedCommitHashPtr *string
startIdx int
endIdx int
showGraph bool
bisectInfo *git_commands.BisectInfo
expected string
focus bool
}{
{
testName: "no commits",
commitOpts: []models.NewCommitOpts{},
startIdx: 0,
endIdx: 1,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: "",
},
{
testName: "some commits",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1"},
{Name: "commit2", Hash: "hash2"},
},
startIdx: 0,
endIdx: 2,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 commit1
hash2 commit2
`),
},
{
testName: "commit with tags",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Tags: []string{"tag1", "tag2"}},
{Name: "commit2", Hash: "hash2"},
},
startIdx: 0,
endIdx: 2,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 tag1 tag2 commit1
hash2 commit2
`),
},
{
testName: "show local branch head, except the current branch, main branches, or merged branches",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1"},
{Name: "commit2", Hash: "hash2"},
{Name: "commit3", Hash: "hash3"},
{Name: "commit4", Hash: "hash4", Status: models.StatusMerged},
},
branches: []*models.Branch{
{Name: "current-branch", CommitHash: "hash1", Head: true},
{Name: "other-branch", CommitHash: "hash2", Head: false},
{Name: "master", CommitHash: "hash3", Head: false},
{Name: "old-branch", CommitHash: "hash4", Head: false},
},
currentBranchName: "current-branch",
hasUpdateRefConfig: true,
startIdx: 0,
endIdx: 4,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 commit1
hash2 * commit2
hash3 commit3
hash4 commit4
`),
},
{
testName: "show local branch head for head commit if updateRefs is on",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1"},
{Name: "commit2", Hash: "hash2"},
},
branches: []*models.Branch{
{Name: "current-branch", CommitHash: "hash1", Head: true},
{Name: "other-branch", CommitHash: "hash1", Head: false},
},
currentBranchName: "current-branch",
hasUpdateRefConfig: true,
startIdx: 0,
endIdx: 2,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 * commit1
hash2 commit2
`),
},
{
testName: "don't show local branch head for head commit if updateRefs is off",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1"},
{Name: "commit2", Hash: "hash2"},
},
branches: []*models.Branch{
{Name: "current-branch", CommitHash: "hash1", Head: true},
{Name: "other-branch", CommitHash: "hash1", Head: false},
},
currentBranchName: "current-branch",
hasUpdateRefConfig: false,
startIdx: 0,
endIdx: 2,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 commit1
hash2 commit2
`),
},
{
testName: "show local branch head and tag if both exist",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1"},
{Name: "commit2", Hash: "hash2", Tags: []string{"some-tag"}},
{Name: "commit3", Hash: "hash3"},
},
branches: []*models.Branch{
{Name: "some-branch", CommitHash: "hash2"},
},
startIdx: 0,
endIdx: 3,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 commit1
hash2 * some-tag commit2
hash3 commit3
`),
},
{
testName: "showing graph",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 0,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 ⏣─╮ commit1
hash2 ◯ │ commit2
hash3 ◯─╯ commit3
hash4 ◯ commit4
hash5 ◯ commit5
`),
},
{
testName: "showing graph, including rebase commits",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}, Action: todo.Pick},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}, Action: todo.Pick},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 0,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 pick commit1
hash2 pick commit2
hash3 ◯ commit3
hash4 ◯ commit4
hash5 ◯ commit5
`),
},
{
testName: "showing graph, including rebase commits, with offset",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}, Action: todo.Pick},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}, Action: todo.Pick},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 1,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash2 pick commit2
hash3 ◯ commit3
hash4 ◯ commit4
hash5 ◯ commit5
`),
},
{
testName: "startIdx is past TODO commits",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}, Action: todo.Pick},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}, Action: todo.Pick},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 3,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash4 ◯ commit4
hash5 ◯ commit5
`),
},
{
testName: "only showing TODO commits",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}, Action: todo.Pick},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}, Action: todo.Pick},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 0,
endIdx: 2,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 pick commit1
hash2 pick commit2
`),
},
{
testName: "no TODO commits, towards bottom",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 4,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash5 ◯ commit5
`),
},
{
testName: "only TODO commits except last",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", Parents: []string{"hash2", "hash3"}, Action: todo.Pick},
{Name: "commit2", Hash: "hash2", Parents: []string{"hash3"}, Action: todo.Pick},
{Name: "commit3", Hash: "hash3", Parents: []string{"hash4"}, Action: todo.Pick},
{Name: "commit4", Hash: "hash4", Parents: []string{"hash5"}, Action: todo.Pick},
{Name: "commit5", Hash: "hash5", Parents: []string{"hash7"}},
},
startIdx: 0,
endIdx: 2,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
hash1 pick commit1
hash2 pick commit2
`),
},
{
testName: "graph in divergence view - all commits visible",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 0,
endIdx: 8,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↓ hash1r ◯ commit1
↓ hash2r ⏣─╮ commit2
↓ hash3r ◯ │ commit3
↑ hash1l ◯ commit1
↑ hash2l ⏣─╮ commit2
↑ hash3l ◯ │ commit3
↑ hash4l ◯─╯ commit4
↑ hash5l ◯ commit5
`),
},
{
testName: "graph in divergence view - not all remote commits visible",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 2,
endIdx: 8,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↓ hash3r ◯ │ commit3
↑ hash1l ◯ commit1
↑ hash2l ⏣─╮ commit2
↑ hash3l ◯ │ commit3
↑ hash4l ◯─╯ commit4
↑ hash5l ◯ commit5
`),
},
{
testName: "graph in divergence view - not all local commits",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 0,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↓ hash1r ◯ commit1
↓ hash2r ⏣─╮ commit2
↓ hash3r ◯ │ commit3
↑ hash1l ◯ commit1
↑ hash2l ⏣─╮ commit2
`),
},
{
testName: "graph in divergence view - no remote commits visible",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 4,
endIdx: 8,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↑ hash2l ⏣─╮ commit2
↑ hash3l ◯ │ commit3
↑ hash4l ◯─╯ commit4
↑ hash5l ◯ commit5
`),
},
{
testName: "graph in divergence view - no local commits visible",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 0,
endIdx: 2,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↓ hash1r ◯ commit1
↓ hash2r ⏣─╮ commit2
`),
},
{
testName: "graph in divergence view - no remote commits present",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1l", Parents: []string{"hash2l"}, Divergence: models.DivergenceLeft},
{Name: "commit2", Hash: "hash2l", Parents: []string{"hash3l", "hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit3", Hash: "hash3l", Parents: []string{"hash4l"}, Divergence: models.DivergenceLeft},
{Name: "commit4", Hash: "hash4l", Parents: []string{"hash5l"}, Divergence: models.DivergenceLeft},
{Name: "commit5", Hash: "hash5l", Parents: []string{"hash6l"}, Divergence: models.DivergenceLeft},
},
startIdx: 0,
endIdx: 5,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↑ hash1l ◯ commit1
↑ hash2l ⏣─╮ commit2
↑ hash3l ◯ │ commit3
↑ hash4l ◯─╯ commit4
↑ hash5l ◯ commit5
`),
},
{
testName: "graph in divergence view - no local commits present",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1r", Parents: []string{"hash2r"}, Divergence: models.DivergenceRight},
{Name: "commit2", Hash: "hash2r", Parents: []string{"hash3r", "hash5r"}, Divergence: models.DivergenceRight},
{Name: "commit3", Hash: "hash3r", Parents: []string{"hash4r"}, Divergence: models.DivergenceRight},
},
startIdx: 0,
endIdx: 3,
showGraph: true,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
expected: formatExpected(`
↓ hash1r ◯ commit1
↓ hash2r ⏣─╮ commit2
↓ hash3r ◯ │ commit3
`),
},
{
testName: "custom time format",
commitOpts: []models.NewCommitOpts{
{Name: "commit1", Hash: "hash1", UnixTimestamp: 1577844184, AuthorName: "Jesse Duffield"},
{Name: "commit2", Hash: "hash2", UnixTimestamp: 1576844184, AuthorName: "Jesse Duffield"},
},
fullDescription: true,
timeFormat: "2006-01-02",
shortTimeFormat: "3:04PM",
startIdx: 0,
endIdx: 2,
showGraph: false,
bisectInfo: git_commands.NewNullBisectInfo(),
cherryPickedCommitHashSet: set.New[string](),
now: time.Date(2020, 1, 1, 5, 3, 4, 0, time.UTC),
expected: formatExpected(`
hash1 2:03AM Jesse Duffield commit1
hash2 2019-12-20 Jesse Duffield commit2
`),
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelNone)
defer color.ForceSetColorLevel(oldColorLevel)
os.Setenv("TZ", "UTC")
focusing := false
for _, scenario := range scenarios {
if scenario.focus {
focusing = true
}
}
common := common.NewDummyCommon()
for _, s := range scenarios {
if !focusing || s.focus {
t.Run(s.testName, func(t *testing.T) {
hashPool := &utils.StringPool{}
commits := lo.Map(s.commitOpts,
func(opts models.NewCommitOpts, _ int) *models.Commit { return models.NewCommit(hashPool, opts) })
result := GetCommitListDisplayStrings(
common,
commits,
s.branches,
s.currentBranchName,
s.hasUpdateRefConfig,
s.fullDescription,
s.cherryPickedCommitHashSet,
s.diffName,
s.markedBaseCommit,
s.timeFormat,
s.shortTimeFormat,
s.now,
s.parseEmoji,
s.selectedCommitHashPtr,
s.startIdx,
s.endIdx,
s.showGraph,
s.bisectInfo,
)
renderedLines, _ := utils.RenderDisplayStrings(result, nil)
renderedResult := strings.Join(renderedLines, "\n")
t.Logf("\n%s", renderedResult)
assert.EqualValues(t, s.expected, renderedResult)
})
}
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/remotes.go | pkg/gui/presentation/remotes.go | package presentation
import (
"time"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/config"
"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/i18n"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetRemoteListDisplayStrings(
remotes []*models.Remote,
diffName string,
getItemOperation func(item types.HasUrn) types.ItemOperation,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) [][]string {
return lo.Map(remotes, func(remote *models.Remote, _ int) []string {
diffed := remote.Name == diffName
return getRemoteDisplayStrings(remote, diffed, getItemOperation(remote), tr, userConfig)
})
}
// getRemoteDisplayStrings returns the display string of branch
func getRemoteDisplayStrings(
r *models.Remote,
diffed bool,
itemOperation types.ItemOperation,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) []string {
branchCount := len(r.Branches)
textStyle := theme.DefaultTextColor
if diffed {
textStyle = theme.DiffTerminalColor
}
res := make([]string, 0, 3)
if icons.IsIconEnabled() {
res = append(res, textStyle.Sprint(icons.IconForRemote(r)))
}
descriptionStr := style.FgBlue.Sprintf("%d branches", branchCount)
itemOperationStr := ItemOperationToString(itemOperation, tr)
if itemOperationStr != "" {
descriptionStr += " " + style.FgCyan.Sprint(itemOperationStr+" "+Loader(time.Now(), userConfig.Gui.Spinner))
}
res = append(res, textStyle.Sprint(r.Name), descriptionStr)
return res
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/reflog_commits.go | pkg/gui/presentation/reflog_commits.go | package presentation
import (
"time"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/kyokomi/emoji/v2"
"github.com/samber/lo"
)
func GetReflogCommitListDisplayStrings(commits []*models.Commit, fullDescription bool, cherryPickedCommitHashSet *set.Set[string], diffName string, now time.Time, timeFormat string, shortTimeFormat string, parseEmoji bool) [][]string {
var displayFunc func(*models.Commit, reflogCommitDisplayAttributes) []string
if fullDescription {
displayFunc = getFullDescriptionDisplayStringsForReflogCommit
} else {
displayFunc = getDisplayStringsForReflogCommit
}
return lo.Map(commits, func(commit *models.Commit, _ int) []string {
diffed := commit.Hash() == diffName
cherryPicked := cherryPickedCommitHashSet.Includes(commit.Hash())
return displayFunc(commit,
reflogCommitDisplayAttributes{
cherryPicked: cherryPicked,
diffed: diffed,
parseEmoji: parseEmoji,
timeFormat: timeFormat,
shortTimeFormat: shortTimeFormat,
now: now,
})
})
}
func reflogHashColor(cherryPicked, diffed bool) style.TextStyle {
if diffed {
return theme.DiffTerminalColor
}
hashColor := style.FgBlue
if cherryPicked {
hashColor = theme.CherryPickedCommitTextStyle
}
return hashColor
}
type reflogCommitDisplayAttributes struct {
cherryPicked bool
diffed bool
parseEmoji bool
timeFormat string
shortTimeFormat string
now time.Time
}
func getFullDescriptionDisplayStringsForReflogCommit(c *models.Commit, attrs reflogCommitDisplayAttributes) []string {
name := c.Name
if attrs.parseEmoji {
name = emoji.Sprint(name)
}
return []string{
reflogHashColor(attrs.cherryPicked, attrs.diffed).Sprint(c.ShortHash()),
style.FgMagenta.Sprint(utils.UnixToDateSmart(attrs.now, c.UnixTimestamp, attrs.timeFormat, attrs.shortTimeFormat)),
theme.DefaultTextColor.Sprint(name),
}
}
func getDisplayStringsForReflogCommit(c *models.Commit, attrs reflogCommitDisplayAttributes) []string {
name := c.Name
if attrs.parseEmoji {
name = emoji.Sprint(name)
}
return []string{
reflogHashColor(attrs.cherryPicked, attrs.diffed).Sprint(c.ShortHash()),
theme.DefaultTextColor.Sprint(name),
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/branches_test.go | pkg/gui/presentation/branches_test.go | package presentation
import (
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/xo/terminfo"
)
func makeAtomic(v int32) *atomic.Int32 {
var result atomic.Int32
result.Store(v)
return &result
}
func Test_getBranchDisplayStrings(t *testing.T) {
scenarios := []struct {
branch *models.Branch
itemOperation types.ItemOperation
fullDescription bool
viewWidth int
useIcons bool
checkedOutByWorktree bool
showDivergenceCfg string
expected []string
}{
// First some tests for when the view is wide enough so that everything fits:
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_name"},
},
{
branch: &models.Branch{Name: "🍉_special_char", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 19,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "🍉_special_char"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_name (worktree)"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 100,
useIcons: true,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "", "branch_name "},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "0",
BehindForPull: "0",
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_name ✓"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "3",
BehindForPull: "5",
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_name (worktree) ↓5↑3"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
BehindBaseBranch: *makeAtomic(2),
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 20,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "onlyArrow",
expected: []string{"1m", "branch_name ↓"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "0",
BehindForPull: "0",
BehindBaseBranch: *makeAtomic(2),
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 22,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "arrowAndNumber",
expected: []string{"1m", "branch_name ✓ ↓2"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "3",
BehindForPull: "5",
BehindBaseBranch: *makeAtomic(2),
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 26,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "arrowAndNumber",
expected: []string{"1m", "branch_name ↓5↑3 ↓2"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationPushing,
fullDescription: false,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_name Pushing |"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
CommitHash: "1234567890",
UpstreamRemote: "origin",
UpstreamBranch: "branch_name",
AheadForPull: "0",
BehindForPull: "0",
Subject: "commit title",
},
itemOperation: types.ItemOperationNone,
fullDescription: true,
viewWidth: 100,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "12345678", "branch_name ✓", "origin branch_name", "commit title"},
},
// Now tests for how we truncate the branch name when there's not enough room:
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 14,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_na…"},
},
{
branch: &models.Branch{Name: "🍉_special_char", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 18,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "🍉_special_ch…"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 14,
useIcons: false,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "bra… (worktree)"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 14,
useIcons: true,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "", "branc… "},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "0",
BehindForPull: "0",
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 14,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_… ✓"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "3",
BehindForPull: "5",
BehindBaseBranch: *makeAtomic(4),
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 21,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "arrowAndNumber",
expected: []string{"1m", "branch_n… ↓5↑3 ↓4"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
UpstreamRemote: "origin",
AheadForPull: "3",
BehindForPull: "5",
},
itemOperation: types.ItemOperationNone,
fullDescription: false,
viewWidth: 30,
useIcons: false,
checkedOutByWorktree: true,
showDivergenceCfg: "none",
expected: []string{"1m", "branch_na… (worktree) ↓5↑3"},
},
{
branch: &models.Branch{Name: "branch_name", Recency: "1m"},
itemOperation: types.ItemOperationPushing,
fullDescription: false,
viewWidth: 20,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "branc… Pushing |"},
},
{
branch: &models.Branch{Name: "abc", Recency: "1m"},
itemOperation: types.ItemOperationPushing,
fullDescription: false,
viewWidth: -1,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "abc Pushing |"},
},
{
branch: &models.Branch{Name: "ab", Recency: "1m"},
itemOperation: types.ItemOperationPushing,
fullDescription: false,
viewWidth: -1,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "ab Pushing |"},
},
{
branch: &models.Branch{Name: "a", Recency: "1m"},
itemOperation: types.ItemOperationPushing,
fullDescription: false,
viewWidth: -1,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "a Pushing |"},
},
{
branch: &models.Branch{
Name: "branch_name",
Recency: "1m",
CommitHash: "1234567890",
UpstreamRemote: "origin",
UpstreamBranch: "branch_name",
AheadForPull: "0",
BehindForPull: "0",
Subject: "commit title",
},
itemOperation: types.ItemOperationNone,
fullDescription: true,
viewWidth: 20,
useIcons: false,
checkedOutByWorktree: false,
showDivergenceCfg: "none",
expected: []string{"1m", "12345678", "bran… ✓", "origin branch_name", "commit title"},
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelNone)
defer color.ForceSetColorLevel(oldColorLevel)
c := common.NewDummyCommon()
SetCustomBranches(c.UserConfig().Gui.BranchColorPatterns, true)
for i, s := range scenarios {
icons.SetNerdFontsVersion(lo.Ternary(s.useIcons, "3", ""))
c.UserConfig().Gui.ShowDivergenceFromBaseBranch = s.showDivergenceCfg
worktrees := []*models.Worktree{}
if s.checkedOutByWorktree {
worktrees = append(worktrees, &models.Worktree{Branch: s.branch.Name})
}
t.Run(fmt.Sprintf("getBranchDisplayStrings_%d", i), func(t *testing.T) {
strings := getBranchDisplayStrings(s.branch, s.itemOperation, s.fullDescription, false, s.viewWidth, c.Tr, c.UserConfig(), worktrees, time.Time{})
assert.Equal(t, s.expected, strings)
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/branches.go | pkg/gui/presentation/branches.go | package presentation
import (
"fmt"
"regexp"
"strings"
"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/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/i18n"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
type colorMatcher struct {
patterns map[string]*style.TextStyle
isRegex bool // NOTE: this value is needed only until the deprecated branchColors config is removed and only regex color patterns are used
}
var colorPatterns *colorMatcher
func GetBranchListDisplayStrings(
branches []*models.Branch,
getItemOperation func(item types.HasUrn) types.ItemOperation,
fullDescription bool,
diffName string,
viewWidth int,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
worktrees []*models.Worktree,
) [][]string {
return lo.Map(branches, func(branch *models.Branch, _ int) []string {
diffed := branch.Name == diffName
return getBranchDisplayStrings(branch, getItemOperation(branch), fullDescription, diffed, viewWidth, tr, userConfig, worktrees, time.Now())
})
}
// getBranchDisplayStrings returns the display string of branch
func getBranchDisplayStrings(
b *models.Branch,
itemOperation types.ItemOperation,
fullDescription bool,
diffed bool,
viewWidth int,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
worktrees []*models.Worktree,
now time.Time,
) []string {
checkedOutByWorkTree := git_commands.CheckedOutByOtherWorktree(b, worktrees)
showCommitHash := fullDescription || userConfig.Gui.ShowBranchCommitHash
branchStatus := BranchStatus(b, itemOperation, tr, now, userConfig)
divergence := divergenceStr(b, itemOperation, tr, userConfig)
worktreeIcon := lo.Ternary(icons.IsIconEnabled(), icons.LINKED_WORKTREE_ICON, fmt.Sprintf("(%s)", tr.LcWorktree))
// Recency is always three characters, plus one for the space
availableWidth := viewWidth - 4
if len(divergence) > 0 {
availableWidth -= utils.StringWidth(divergence) + 1
}
if icons.IsIconEnabled() {
availableWidth -= 2 // one for the icon, one for the space
}
if showCommitHash {
availableWidth -= utils.COMMIT_HASH_SHORT_SIZE + 1
}
paddingNeededForDivergence := availableWidth
if checkedOutByWorkTree {
availableWidth -= utils.StringWidth(worktreeIcon) + 1
}
if len(branchStatus) > 0 {
availableWidth -= utils.StringWidth(utils.Decolorise(branchStatus)) + 1
}
displayName := b.Name
if b.DisplayName != "" {
displayName = b.DisplayName
}
nameTextStyle := GetBranchTextStyle(b.Name)
if diffed {
nameTextStyle = theme.DiffTerminalColor
}
// Don't bother shortening branch names that are already 3 characters or less
if utils.StringWidth(displayName) > max(availableWidth, 3) {
// Never shorten the branch name to less then 3 characters
len := max(availableWidth, 4)
displayName = utils.TruncateWithEllipsis(displayName, len)
}
coloredName := nameTextStyle.Sprint(displayName)
if checkedOutByWorkTree {
coloredName = fmt.Sprintf("%s %s", coloredName, style.FgDefault.Sprint(worktreeIcon))
}
if len(branchStatus) > 0 {
coloredName = fmt.Sprintf("%s %s", coloredName, branchStatus)
}
recencyColor := style.FgCyan
if b.Recency == " *" {
recencyColor = style.FgGreen
}
res := make([]string, 0, 6)
res = append(res, recencyColor.Sprint(b.Recency))
if icons.IsIconEnabled() {
res = append(res, nameTextStyle.Sprint(icons.IconForBranch(b)))
}
if showCommitHash {
res = append(res, utils.ShortHash(b.CommitHash))
}
if divergence != "" {
paddingNeededForDivergence -= utils.StringWidth(utils.Decolorise(coloredName)) - 1
if paddingNeededForDivergence > 0 {
coloredName += strings.Repeat(" ", paddingNeededForDivergence)
coloredName += style.FgCyan.Sprint(divergence)
}
}
res = append(res, coloredName)
if fullDescription {
res = append(
res,
fmt.Sprintf("%s %s",
style.FgYellow.Sprint(b.UpstreamRemote),
style.FgYellow.Sprint(b.UpstreamBranch),
),
utils.TruncateWithEllipsis(b.Subject, 60),
)
}
return res
}
// GetBranchTextStyle branch color
func GetBranchTextStyle(name string) style.TextStyle {
if style, ok := colorPatterns.match(name); ok {
return *style
}
return theme.DefaultTextColor
}
func (m *colorMatcher) match(name string) (*style.TextStyle, bool) {
if m.isRegex {
for pattern, style := range m.patterns {
if matched, _ := regexp.MatchString(pattern, name); matched {
return style, true
}
}
} else {
// old behavior using the deprecated branchColors behavior matching on branch type
branchType := strings.Split(name, "/")[0]
if value, ok := m.patterns[branchType]; ok {
return value, true
}
}
return nil, false
}
func BranchStatus(
branch *models.Branch,
itemOperation types.ItemOperation,
tr *i18n.TranslationSet,
now time.Time,
userConfig *config.UserConfig,
) string {
itemOperationStr := ItemOperationToString(itemOperation, tr)
if itemOperationStr != "" {
return style.FgCyan.Sprintf("%s %s", itemOperationStr, Loader(now, userConfig.Gui.Spinner))
}
result := ""
if branch.IsTrackingRemote() {
if branch.UpstreamGone {
result = style.FgRed.Sprint(tr.UpstreamGone)
} else if branch.MatchesUpstream() {
result = style.FgGreen.Sprint("✓")
} else if branch.RemoteBranchNotStoredLocally() {
result = style.FgMagenta.Sprint("?")
} else if branch.IsBehindForPull() && branch.IsAheadForPull() {
result = style.FgYellow.Sprintf("↓%s↑%s", branch.BehindForPull, branch.AheadForPull)
} else if branch.IsBehindForPull() {
result = style.FgYellow.Sprintf("↓%s", branch.BehindForPull)
} else if branch.IsAheadForPull() {
result = style.FgYellow.Sprintf("↑%s", branch.AheadForPull)
}
}
return result
}
func divergenceStr(
branch *models.Branch,
itemOperation types.ItemOperation,
tr *i18n.TranslationSet,
userConfig *config.UserConfig,
) string {
result := ""
if ItemOperationToString(itemOperation, tr) == "" && userConfig.Gui.ShowDivergenceFromBaseBranch != "none" {
behind := branch.BehindBaseBranch.Load()
if behind != 0 {
if userConfig.Gui.ShowDivergenceFromBaseBranch == "arrowAndNumber" {
result += fmt.Sprintf("↓%d", behind)
} else {
result += "↓"
}
}
}
return result
}
func SetCustomBranches(customBranchColors map[string]string, isRegex bool) {
colorPatterns = &colorMatcher{
patterns: utils.SetCustomColors(customBranchColors),
isRegex: isRegex,
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/commits.go | pkg/gui/presentation/commits.go | package presentation
import (
"fmt"
"strings"
"time"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/authors"
"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/theme"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/kyokomi/emoji/v2"
"github.com/samber/lo"
"github.com/sasha-s/go-deadlock"
"github.com/stefanhaller/git-todo-parser/todo"
)
type pipeSetCacheKey struct {
commitHash string
commitCount int
divergence models.Divergence
}
var (
pipeSetCache = make(map[pipeSetCacheKey][][]graph.Pipe)
mutex deadlock.Mutex
)
type bisectBounds struct {
newIndex int
oldIndex int
}
func GetCommitListDisplayStrings(
common *common.Common,
commits []*models.Commit,
branches []*models.Branch,
currentBranchName string,
hasRebaseUpdateRefsConfig bool,
fullDescription bool,
cherryPickedCommitHashSet *set.Set[string],
diffName string,
markedBaseCommit string,
timeFormat string,
shortTimeFormat string,
now time.Time,
parseEmoji bool,
selectedCommitHashPtr *string,
startIdx int,
endIdx int,
showGraph bool,
bisectInfo *git_commands.BisectInfo,
) [][]string {
mutex.Lock()
defer mutex.Unlock()
if len(commits) == 0 {
return nil
}
if startIdx >= len(commits) {
return nil
}
// this is where my non-TODO commits begin
rebaseOffset := min(indexOfFirstNonTODOCommit(commits), endIdx)
filteredCommits := commits[startIdx:endIdx]
bisectBounds := getbisectBounds(commits, bisectInfo)
// function expects to be passed the index of the commit in terms of the `commits` slice
var getGraphLine func(int) string
if showGraph {
if len(commits) > 0 && commits[0].Divergence != models.DivergenceNone {
// Showing a divergence log; we know we don't have any rebasing
// commits in this case. But we need to render separate graphs for
// the Local and Remote sections.
allGraphLines := []string{}
_, localSectionStart, found := lo.FindIndexOf(
commits, func(c *models.Commit) bool { return c.Divergence == models.DivergenceLeft })
if !found {
localSectionStart = len(commits)
}
if localSectionStart > 0 {
// we have some remote commits
pipeSets := loadPipesets(commits[:localSectionStart])
if startIdx < localSectionStart {
// some of the remote commits are visible
start := startIdx
end := min(endIdx, localSectionStart)
graphPipeSets := pipeSets[start:end]
graphCommits := commits[start:end]
graphLines := graph.RenderAux(
graphPipeSets,
graphCommits,
selectedCommitHashPtr,
)
allGraphLines = append(allGraphLines, graphLines...)
}
}
if localSectionStart < len(commits) {
// we have some local commits
pipeSets := loadPipesets(commits[localSectionStart:])
if localSectionStart < endIdx {
// some of the local commits are visible
graphOffset := max(startIdx, localSectionStart)
pipeSetOffset := max(startIdx-localSectionStart, 0)
graphPipeSets := pipeSets[pipeSetOffset : endIdx-localSectionStart]
graphCommits := commits[graphOffset:endIdx]
graphLines := graph.RenderAux(
graphPipeSets,
graphCommits,
selectedCommitHashPtr,
)
allGraphLines = append(allGraphLines, graphLines...)
}
}
getGraphLine = func(idx int) string {
return allGraphLines[idx-startIdx]
}
} else {
// this is where the graph begins (may be beyond the TODO commits depending on startIdx,
// but we'll never include TODO commits as part of the graph because it'll be messy)
graphOffset := max(startIdx, rebaseOffset)
pipeSets := loadPipesets(commits[rebaseOffset:])
pipeSetOffset := max(startIdx-rebaseOffset, 0)
graphPipeSets := pipeSets[pipeSetOffset:max(endIdx-rebaseOffset, 0)]
graphCommits := commits[graphOffset:endIdx]
graphLines := graph.RenderAux(
graphPipeSets,
graphCommits,
selectedCommitHashPtr,
)
getGraphLine = func(idx int) string {
if idx >= graphOffset {
return graphLines[idx-graphOffset]
}
return ""
}
}
} else {
getGraphLine = func(int) string { return "" }
}
// Determine the hashes of the local branches for which we want to show a
// branch marker in the commits list. We only want to do this for branches
// that are not the current branch, and not any of the main branches. The
// goal is to visualize stacks of local branches, so anything that doesn't
// contribute to a branch stack shouldn't show a marker.
//
// If there are other branches pointing to the current head commit, we only
// want to show the marker if the rebase.updateRefs config is on.
branchHeadsToVisualize := set.NewFromSlice(lo.FilterMap(branches,
func(b *models.Branch, index int) (string, bool) {
return b.CommitHash,
// Don't consider branches that don't have a commit hash. As far
// as I can see, this happens for a detached head, so filter
// these out
b.CommitHash != "" &&
// Don't show a marker for the current branch
b.Name != currentBranchName &&
// Don't show a marker for main branches
!lo.Contains(common.UserConfig().Git.MainBranches, b.Name) &&
// Don't show a marker for the head commit unless the
// rebase.updateRefs config is on
(hasRebaseUpdateRefsConfig || b.CommitHash != commits[0].Hash())
}))
lines := make([][]string, 0, len(filteredCommits))
var bisectStatus BisectStatus
willBeRebased := markedBaseCommit == ""
for i, commit := range filteredCommits {
unfilteredIdx := i + startIdx
bisectStatus = getBisectStatus(unfilteredIdx, commit.Hash(), bisectInfo, bisectBounds)
isMarkedBaseCommit := commit.Hash() != "" && commit.Hash() == markedBaseCommit
if isMarkedBaseCommit {
willBeRebased = true
}
lines = append(lines, displayCommit(
common,
commit,
branchHeadsToVisualize,
hasRebaseUpdateRefsConfig,
cherryPickedCommitHashSet,
isMarkedBaseCommit,
willBeRebased,
diffName,
timeFormat,
shortTimeFormat,
now,
parseEmoji,
getGraphLine(unfilteredIdx),
fullDescription,
bisectStatus,
bisectInfo,
))
}
return lines
}
func getbisectBounds(commits []*models.Commit, bisectInfo *git_commands.BisectInfo) *bisectBounds {
if !bisectInfo.Bisecting() {
return nil
}
bisectBounds := &bisectBounds{}
for i, commit := range commits {
if commit.Hash() == bisectInfo.GetNewHash() {
bisectBounds.newIndex = i
}
status, ok := bisectInfo.Status(commit.Hash())
if ok && status == git_commands.BisectStatusOld {
bisectBounds.oldIndex = i
return bisectBounds
}
}
// shouldn't land here
return nil
}
// precondition: slice is not empty
func indexOfFirstNonTODOCommit(commits []*models.Commit) int {
for i, commit := range commits {
if !commit.IsTODO() {
return i
}
}
// shouldn't land here
return 0
}
func loadPipesets(commits []*models.Commit) [][]graph.Pipe {
// given that our cache key is a commit hash and a commit count, it's very important that we don't actually try to render pipes
// when dealing with things like filtered commits.
cacheKey := pipeSetCacheKey{
commitHash: commits[0].Hash(),
commitCount: len(commits),
divergence: commits[0].Divergence,
}
pipeSets, ok := pipeSetCache[cacheKey]
if !ok {
// pipe sets are unique to a commit head. and a commit count. Sometimes we haven't loaded everything for that.
// so let's just cache it based on that.
getStyle := func(commit *models.Commit) *style.TextStyle {
return authors.AuthorStyle(commit.AuthorName)
}
pipeSets = graph.GetPipeSets(commits, getStyle)
pipeSetCache[cacheKey] = pipeSets
}
return pipeSets
}
// similar to the git_commands.BisectStatus but more gui-focused
type BisectStatus int
const (
BisectStatusNone BisectStatus = iota
BisectStatusOld
BisectStatusNew
BisectStatusSkipped
// adding candidate here which isn't present in the commands package because
// we need to actually go through the commits to get this info
BisectStatusCandidate
// also adding this
BisectStatusCurrent
)
func getBisectStatus(index int, commitHash string, bisectInfo *git_commands.BisectInfo, bisectBounds *bisectBounds) BisectStatus {
if !bisectInfo.Started() {
return BisectStatusNone
}
if bisectInfo.GetCurrentHash() == commitHash {
return BisectStatusCurrent
}
status, ok := bisectInfo.Status(commitHash)
if ok {
switch status {
case git_commands.BisectStatusNew:
return BisectStatusNew
case git_commands.BisectStatusOld:
return BisectStatusOld
case git_commands.BisectStatusSkipped:
return BisectStatusSkipped
}
} else {
if bisectBounds != nil && index >= bisectBounds.newIndex && index <= bisectBounds.oldIndex {
return BisectStatusCandidate
}
return BisectStatusNone
}
// should never land here
return BisectStatusNone
}
func getBisectStatusText(bisectStatus BisectStatus, bisectInfo *git_commands.BisectInfo) string {
if bisectStatus == BisectStatusNone {
return ""
}
style := getBisectStatusColor(bisectStatus)
switch bisectStatus {
case BisectStatusNew:
return style.Sprintf("<-- " + bisectInfo.NewTerm())
case BisectStatusOld:
return style.Sprintf("<-- " + bisectInfo.OldTerm())
case BisectStatusCurrent:
// TODO: i18n
return style.Sprintf("<-- current")
case BisectStatusSkipped:
return style.Sprintf("<-- skipped")
case BisectStatusCandidate:
return style.Sprintf("?")
case BisectStatusNone:
return ""
}
return ""
}
func displayCommit(
common *common.Common,
commit *models.Commit,
branchHeadsToVisualize *set.Set[string],
hasRebaseUpdateRefsConfig bool,
cherryPickedCommitHashSet *set.Set[string],
isMarkedBaseCommit bool,
willBeRebased bool,
diffName string,
timeFormat string,
shortTimeFormat string,
now time.Time,
parseEmoji bool,
graphLine string,
fullDescription bool,
bisectStatus BisectStatus,
bisectInfo *git_commands.BisectInfo,
) []string {
bisectString := getBisectStatusText(bisectStatus, bisectInfo)
hashString := ""
hashColor := getHashColor(commit, diffName, cherryPickedCommitHashSet, bisectStatus, bisectInfo)
hashLength := common.UserConfig().Gui.CommitHashLength
if hashLength >= len(commit.Hash()) {
hashString = hashColor.Sprint(commit.Hash())
} else if hashLength > 0 {
hashString = hashColor.Sprint(commit.Hash()[:hashLength])
} else if !icons.IsIconEnabled() { // hashLength <= 0
hashString = hashColor.Sprint("*")
}
divergenceString := ""
if commit.Divergence != models.DivergenceNone {
divergenceString = hashColor.Sprint(lo.Ternary(commit.Divergence == models.DivergenceLeft, "↑", "↓"))
} else if icons.IsIconEnabled() {
divergenceString = hashColor.Sprint(icons.IconForCommit(commit))
}
descriptionString := ""
if fullDescription {
descriptionString = style.FgBlue.Sprint(
utils.UnixToDateSmart(now, commit.UnixTimestamp, timeFormat, shortTimeFormat),
)
}
actionString := ""
if commit.Action != models.ActionNone {
actionString = actionColorMap(commit.Action, commit.Status).Sprint(commit.Action.String())
}
tagString := ""
if fullDescription {
if commit.ExtraInfo != "" {
tagString = style.FgMagenta.SetBold().Sprint(commit.ExtraInfo) + " "
}
} else {
if len(commit.Tags) > 0 {
tagString = theme.DiffTerminalColor.SetBold().Sprint(strings.Join(commit.Tags, " ")) + " "
}
if branchHeadsToVisualize.Includes(commit.Hash()) &&
// Don't show branch head on commits that are already merged to a main branch
commit.Status != models.StatusMerged &&
// Don't show branch head on a "pick" todo if the rebase.updateRefs config is on
!(commit.IsTODO() && hasRebaseUpdateRefsConfig) {
tagString = style.FgCyan.SetBold().Sprint(
lo.Ternary(icons.IsIconEnabled(), icons.BRANCH_ICON, "*") + " " + tagString)
}
}
name := commit.Name
if commit.Action == todo.UpdateRef {
name = strings.TrimPrefix(name, "refs/heads/")
}
if parseEmoji {
name = emoji.Sprint(name)
}
mark := ""
if commit.Status == models.StatusConflicted {
youAreHere := style.FgRed.Sprintf("<-- %s ---", common.Tr.ConflictLabel)
mark = fmt.Sprintf("%s ", youAreHere)
} else if isMarkedBaseCommit {
rebaseFromHere := style.FgYellow.Sprint(common.Tr.MarkedCommitMarker)
mark = fmt.Sprintf("%s ", rebaseFromHere)
} else if !willBeRebased {
willBeRebased := style.FgYellow.Sprint("✓")
mark = fmt.Sprintf("%s ", willBeRebased)
}
authorLength := common.UserConfig().Gui.CommitAuthorShortLength
if fullDescription {
authorLength = common.UserConfig().Gui.CommitAuthorLongLength
}
author := authors.AuthorWithLength(commit.AuthorName, authorLength)
cols := make([]string, 0, 7)
cols = append(
cols,
divergenceString,
hashString,
bisectString,
descriptionString,
actionString,
author,
graphLine+mark+tagString+theme.DefaultTextColor.Sprint(name),
)
return cols
}
func getBisectStatusColor(status BisectStatus) style.TextStyle {
switch status {
case BisectStatusNone:
return style.FgBlack
case BisectStatusNew:
return style.FgRed
case BisectStatusOld:
return style.FgGreen
case BisectStatusSkipped:
return style.FgYellow
case BisectStatusCurrent:
return style.FgMagenta
case BisectStatusCandidate:
return style.FgBlue
}
// shouldn't land here
return style.FgWhite
}
func getHashColor(
commit *models.Commit,
diffName string,
cherryPickedCommitHashSet *set.Set[string],
bisectStatus BisectStatus,
bisectInfo *git_commands.BisectInfo,
) style.TextStyle {
if bisectInfo.Started() {
return getBisectStatusColor(bisectStatus)
}
diffed := commit.Hash() != "" && commit.Hash() == diffName
hashColor := theme.DefaultTextColor
switch commit.Status {
case models.StatusUnpushed:
hashColor = style.FgRed
case models.StatusPushed:
hashColor = style.FgYellow
case models.StatusMerged:
hashColor = style.FgGreen
case models.StatusRebasing, models.StatusCherryPickingOrReverting, models.StatusConflicted:
hashColor = style.FgBlue
case models.StatusReflog:
hashColor = style.FgBlue
default:
}
if diffed {
hashColor = theme.DiffTerminalColor
} else if cherryPickedCommitHashSet.Includes(commit.Hash()) {
hashColor = theme.CherryPickedCommitTextStyle
} else if commit.Divergence == models.DivergenceRight && commit.Status != models.StatusMerged {
hashColor = style.FgBlue
}
return hashColor
}
func actionColorMap(action todo.TodoCommand, status models.CommitStatus) style.TextStyle {
if status == models.StatusConflicted {
return style.FgRed
}
switch action {
case todo.Pick:
return style.FgCyan
case todo.Drop:
return style.FgRed
case todo.Edit:
return style.FgGreen
case todo.Fixup:
return style.FgMagenta
default:
return style.FgYellow
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/worktrees.go | pkg/gui/presentation/worktrees.go | package presentation
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/i18n"
"github.com/jesseduffield/lazygit/pkg/theme"
"github.com/samber/lo"
)
func GetWorktreeDisplayStrings(tr *i18n.TranslationSet, worktrees []*models.Worktree) [][]string {
return lo.Map(worktrees, func(worktree *models.Worktree, _ int) []string {
return GetWorktreeDisplayString(
tr,
worktree)
})
}
func GetWorktreeDisplayString(tr *i18n.TranslationSet, worktree *models.Worktree) []string {
textStyle := theme.DefaultTextColor
current := ""
currentColor := style.FgCyan
if worktree.IsCurrent {
current = " *"
currentColor = style.FgGreen
}
icon := icons.IconForWorktree(false)
if worktree.IsPathMissing {
textStyle = style.FgRed
icon = icons.IconForWorktree(true)
}
res := []string{}
res = append(res, currentColor.Sprint(current))
if icons.IsIconEnabled() {
res = append(res, textStyle.Sprint(icon))
}
name := worktree.Name
if worktree.IsMain {
name += " " + tr.MainWorktree
}
if worktree.IsPathMissing && !icons.IsIconEnabled() {
name += " " + tr.MissingWorktree
}
res = append(res, textStyle.Sprint(name))
return res
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/authors/authors_test.go | pkg/gui/presentation/authors/authors_test.go | package authors
import (
"testing"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/stretchr/testify/assert"
)
func TestGetInitials(t *testing.T) {
for input, expectedOutput := range map[string]string{
"Jesse Duffield": "JD",
"Jesse Duffield Man": "JD",
"JesseDuffield": "Je",
"J": "J",
"六书六書": "六",
"書": "書",
"": "",
} {
output := getInitials(input)
if output != expectedOutput {
t.Errorf("Expected %s to be %s", output, expectedOutput)
}
}
}
func TestAuthorWithLength(t *testing.T) {
scenarios := []struct {
authorName string
length int
expectedOutput string
}{
{"Jesse Duffield", 0, ""},
{"Jesse Duffield", 1, ""},
{"Jesse Duffield", 2, "JD"},
{"Jesse Duffield", 3, "Je…"},
{"Jesse Duffield", 10, "Jesse Duf…"},
{"Jesse Duffield", 14, "Jesse Duffield"},
}
for _, s := range scenarios {
assert.Equal(t, s.expectedOutput, utils.Decolorise(AuthorWithLength(s.authorName, s.length)))
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/authors/authors.go | pkg/gui/presentation/authors/authors.go | package authors
import (
"crypto/md5"
"strings"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/lucasb-eyer/go-colorful"
"github.com/rivo/uniseg"
)
type authorNameCacheKey struct {
authorName string
truncateTo int
}
// if these being global variables causes trouble we can wrap them in a struct
// attached to the gui state.
var (
authorInitialCache = make(map[string]string)
authorNameCache = make(map[authorNameCacheKey]string)
authorStyleCache = make(map[string]*style.TextStyle)
)
const authorNameWildcard = "*"
func ShortAuthor(authorName string) string {
if value, ok := authorInitialCache[authorName]; ok {
return value
}
initials := getInitials(authorName)
if initials == "" {
return ""
}
value := AuthorStyle(authorName).Sprint(initials)
authorInitialCache[authorName] = value
return value
}
func LongAuthor(authorName string, length int) string {
cacheKey := authorNameCacheKey{authorName: authorName, truncateTo: length}
if value, ok := authorNameCache[cacheKey]; ok {
return value
}
paddedAuthorName := utils.WithPadding(authorName, length, utils.AlignLeft)
truncatedName := utils.TruncateWithEllipsis(paddedAuthorName, length)
value := AuthorStyle(authorName).Sprint(truncatedName)
authorNameCache[cacheKey] = value
return value
}
// AuthorWithLength returns a representation of the author that fits into a
// given maximum length:
// - if the length is less than 2, it returns an empty string
// - if the length is 2, it returns the initials
// - otherwise, it returns the author name truncated to the maximum length
func AuthorWithLength(authorName string, length int) string {
if length < 2 {
return ""
}
if length == 2 {
return ShortAuthor(authorName)
}
return LongAuthor(authorName, length)
}
func AuthorStyle(authorName string) *style.TextStyle {
if value, ok := authorStyleCache[authorName]; ok {
return value
}
// use the unified style whatever the author name is
if value, ok := authorStyleCache[authorNameWildcard]; ok {
return value
}
value := trueColorStyle(authorName)
authorStyleCache[authorName] = &value
return &value
}
func trueColorStyle(str string) style.TextStyle {
hash := md5.Sum([]byte(str))
c := colorful.Hsl(randFloat(hash[0:4])*360.0, 0.6+0.4*randFloat(hash[4:8]), 0.4+randFloat(hash[8:12])*0.2)
return style.New().SetFg(style.NewRGBColor(color.RGB(uint8(c.R*255), uint8(c.G*255), uint8(c.B*255))))
}
func randFloat(hash []byte) float64 {
return float64(randInt(hash, 100)) / 100
}
func randInt(hash []byte, max int) int {
sum := 0
for _, b := range hash {
sum = (sum + int(b)) % max
}
return sum
}
func getInitials(authorName string) string {
if authorName == "" {
return authorName
}
firstChar, _, width, _ := uniseg.FirstGraphemeClusterInString(authorName, -1)
if width > 1 {
return firstChar
}
split := strings.Split(authorName, " ")
if len(split) == 1 {
return utils.LimitStr(authorName, 2)
}
return utils.LimitStr(split[0], 1) + utils.LimitStr(split[1], 1)
}
func SetCustomAuthors(customAuthorColors map[string]string) {
authorStyleCache = utils.SetCustomColors(customAuthorColors)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/icons/icons.go | pkg/gui/presentation/icons/icons.go | package icons
import (
"log"
"github.com/samber/lo"
)
type IconProperties struct {
Icon string
Color string
}
var isIconEnabled = false
func IsIconEnabled() bool {
return isIconEnabled
}
func SetNerdFontsVersion(version string) {
if version == "" {
isIconEnabled = false
} else {
if !lo.Contains([]string{"2", "3"}, version) {
log.Fatalf("Unsupported nerdFontVersion %s", version)
}
if version == "2" {
patchGitIconsForNerdFontsV2()
patchFileIconsForNerdFontsV2()
}
isIconEnabled = true
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/icons/file_icons_test.go | pkg/gui/presentation/icons/file_icons_test.go | package icons
import (
"testing"
)
func TestFileIcons(t *testing.T) {
t.Run("TestFileIcons", func(t *testing.T) {
for name, icon := range nameIconMap {
if len([]rune(icon.Icon)) != 1 {
t.Errorf("nameIconMap[\"%s\"] is not a single rune", name)
}
}
for ext, icon := range extIconMap {
if len([]rune(icon.Icon)) != 1 {
t.Errorf("extIconMap[\"%s\"] is not a single rune", ext)
}
}
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/icons/git_icons.go | pkg/gui/presentation/icons/git_icons.go | package icons
import (
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/models"
)
var (
BRANCH_ICON = "\U000f062c" //
DETACHED_HEAD_ICON = "\ue729" //
TAG_ICON = "\uf02b" //
COMMIT_ICON = "\U000f0718" //
MERGE_COMMIT_ICON = "\U000f062d" //
DEFAULT_REMOTE_ICON = "\U000f02a2" //
STASH_ICON = "\uf01c" //
LINKED_WORKTREE_ICON = "\U000f0339" //
MISSING_LINKED_WORKTREE_ICON = "\U000f033a" //
)
var remoteIcons = map[string]string{
"github.com": "\ue709", //
"bitbucket.org": "\ue703", //
"gitlab.com": "\uf296", //
"dev.azure.com": "\U000f0805", //
"codeberg.org": "\uf330", //
"git.FreeBSD.org": "\uf30c", //
"gitlab.archlinux.org": "\uf303", //
"gitlab.freedesktop.org": "\uf360", //
"gitlab.gnome.org": "\uf361", //
"gnu.org": "\ue779", //
"invent.kde.org": "\uf373", //
"kernel.org": "\uf31a", //
"salsa.debian.org": "\uf306", //
"sr.ht": "\uf1db", //
}
func patchGitIconsForNerdFontsV2() {
BRANCH_ICON = "\ufb2b" // שׂ
COMMIT_ICON = "\ufc16" // ﰖ
MERGE_COMMIT_ICON = "\ufb2c" // שּׁ
DEFAULT_REMOTE_ICON = "\uf7a1" //
LINKED_WORKTREE_ICON = "\uf838" //
MISSING_LINKED_WORKTREE_ICON = "\uf839" //
remoteIcons["dev.azure.com"] = "\ufd03" // ﴃ
}
func IconForBranch(branch *models.Branch) string {
if branch.DetachedHead {
return DETACHED_HEAD_ICON
}
return BRANCH_ICON
}
func IconForRemoteBranch(branch *models.RemoteBranch) string {
return BRANCH_ICON
}
func IconForTag(tag *models.Tag) string {
return TAG_ICON
}
func IconForCommit(commit *models.Commit) string {
if commit.IsMerge() {
return MERGE_COMMIT_ICON
}
return COMMIT_ICON
}
func IconForRemote(remote *models.Remote) string {
for domain, icon := range remoteIcons {
for _, url := range remote.Urls {
if strings.Contains(url, domain) {
return icon
}
}
}
return DEFAULT_REMOTE_ICON
}
func IconForStash(stash *models.StashEntry) string {
return STASH_ICON
}
func IconForWorktree(missing bool) string {
if missing {
return MISSING_LINKED_WORKTREE_ICON
}
return LINKED_WORKTREE_ICON
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/icons/file_icons.go | pkg/gui/presentation/icons/file_icons.go | package icons
import (
"path/filepath"
"strings"
"github.com/jesseduffield/lazygit/pkg/config"
)
// NOTE: Visit next links for inspiration:
// https://github.com/eza-community/eza/blob/main/src/output/icons.rs
// https://github.com/nvim-tree/nvim-web-devicons/tree/master/lua/nvim-web-devicons/default
var (
DEFAULT_FILE_ICON = IconProperties{Icon: "\uf15b", Color: "#878787"} //
DEFAULT_SUBMODULE_ICON = IconProperties{Icon: "\U000f02a2", Color: "#FF4F00"} //
DEFAULT_DIRECTORY_ICON = IconProperties{Icon: "\uf07b", Color: "#878787"} //
)
// NOTE: The filename map is case sensitive.
var nameIconMap = map[string]IconProperties{
".atom": {Icon: "\ue764", Color: "#EED9B7"}, //
".babelrc": {Icon: "\ue639", Color: "#FED836"}, //
".bash_profile": {Icon: "\ue615", Color: "#89E051"}, //
".bashprofile": {Icon: "\ue615", Color: "#89E051"}, //
".bashrc": {Icon: "\ue795", Color: "#89E051"}, //
".clang-format": {Icon: "\ue615", Color: "#86806D"}, //
".clang-tidy": {Icon: "\ue615", Color: "#86806D"}, //
".codespellrc": {Icon: "\U000f04c6", Color: "#35DA60"}, //
".condarc": {Icon: "\ue715", Color: "#43B02A"}, //
".dockerignore": {Icon: "\U000f0868", Color: "#458EE6"}, //
".ds_store": {Icon: "\uf302", Color: "#78919C"}, //
".editorconfig": {Icon: "\ue652", Color: "#FFFFFF"}, //
".env": {Icon: "\U000f066a", Color: "#FBC02D"}, //
".eslintignore": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
".eslintrc": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
".git": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".git-blame-ignore-revs": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".gitattributes": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".gitconfig": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".github": {Icon: "\uf408", Color: "#333333"}, //
".gitignore": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".gitlab-ci.yml": {Icon: "\uf296", Color: "#F54D27"}, //
".gitmodules": {Icon: "\U000f02a2", Color: "#E64A19"}, //
".gtkrc-2.0": {Icon: "\uf362", Color: "#FFFFFF"}, //
".gvimrc": {Icon: "\ue62b", Color: "#019833"}, //
".idea": {Icon: "\ue7b5", Color: "#626262"}, //
".justfile": {Icon: "\uf0ad", Color: "#6D8086"}, //
".luacheckrc": {Icon: "\ue615", Color: "#868F9D"}, //
".luaurc": {Icon: "\ue615", Color: "#00A2FF"}, //
".mailmap": {Icon: "\U000f01ee", Color: "#42A5F5"}, //
".nanorc": {Icon: "\ue838", Color: "#440077"}, //
".npmignore": {Icon: "\ued0e", Color: "#CC3837"}, //
".npmrc": {Icon: "\ued0e", Color: "#CC3837"}, //
".nuxtrc": {Icon: "\U000f1106", Color: "#00C58E"}, //
".nvmrc": {Icon: "\ued0d", Color: "#4CAF51"}, //
".pre-commit-config.yaml": {Icon: "\U000f06e2", Color: "#F8B424"}, //
".prettierignore": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc.json": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc.json5": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc.toml": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc.yaml": {Icon: "\ue6b4", Color: "#4285F4"}, //
".prettierrc.yml": {Icon: "\ue6b4", Color: "#4285F4"}, //
".pylintrc": {Icon: "\ue615", Color: "#968F6D"}, //
".rvm": {Icon: "\ue21e", Color: "#D70000"}, //
".settings.json": {Icon: "\ue70c", Color: "#854CC7"}, //
".SRCINFO": {Icon: "\uf129", Color: "#0F94D2"}, //
".tmux.conf": {Icon: "\uebc8", Color: "#14BA19"}, //
".tmux.conf.local": {Icon: "\uebc8", Color: "#14BA19"}, //
".Trash": {Icon: "\uf1f8", Color: "#ACBCEF"}, //
".vimrc": {Icon: "\ue62b", Color: "#019833"}, //
".vscode": {Icon: "\ue70c", Color: "#007ACC"}, //
".Xauthority": {Icon: "\uf369", Color: "#E54D18"}, //
".Xresources": {Icon: "\uf369", Color: "#E54D18"}, //
".xinitrc": {Icon: "\uf369", Color: "#E54D18"}, //
".xsession": {Icon: "\uf369", Color: "#E54D18"}, //
".zprofile": {Icon: "\ue615", Color: "#89E051"}, //
".zshenv": {Icon: "\ue615", Color: "#89E051"}, //
".zshrc": {Icon: "\ue795", Color: "#89E051"}, //
"_gvimrc": {Icon: "\ue62b", Color: "#019833"}, //
"_vimrc": {Icon: "\ue62b", Color: "#019833"}, //
"AUTHORS": {Icon: "\uedca", Color: "#A172FF"}, //
"AUTHORS.txt": {Icon: "\uedca", Color: "#A172FF"}, //
"bin": {Icon: "\U000f12a7", Color: "#25A79A"}, //
"brewfile": {Icon: "\ue791", Color: "#701516"}, //
"bspwmrc": {Icon: "\uf355", Color: "#2F2F2F"}, //
"BUILD": {Icon: "\ue63a", Color: "#89E051"}, //
"build.gradle": {Icon: "\ue660", Color: "#005F87"}, //
"build.zig.zon": {Icon: "\ue6a9", Color: "#F69A1B"}, //
"bun.lockb": {Icon: "\ue76f", Color: "#EADCD1"}, //
"cantorrc": {Icon: "\uf373", Color: "#1C99F3"}, //
"Cargo.lock": {Icon: "\ue7a8", Color: "#DEA584"}, //
"Cargo.toml": {Icon: "\ue7a8", Color: "#DEA584"}, //
"checkhealth": {Icon: "\U000f04d9", Color: "#75B4FB"}, //
"CMakeLists.txt": {Icon: "\ue794", Color: "#DCE3EB"}, //
"CODE_OF_CONDUCT": {Icon: "\uf4ae", Color: "#E41662"}, //
"CODE_OF_CONDUCT.md": {Icon: "\uf4ae", Color: "#E41662"}, //
"CODE-OF-CONDUCT.md": {Icon: "\uf4ae", Color: "#E41662"}, //
"commit_editmsg": {Icon: "\ue702", Color: "#F54D27"}, //
"COMMIT_EDITMSG": {Icon: "\ue702", Color: "#E54D18"}, //
"commitlint.config.js": {Icon: "\U000f0718", Color: "#039688"}, //
"commitlint.config.ts": {Icon: "\U000f0718", Color: "#039688"}, //
"compose.yaml": {Icon: "\uf21f", Color: "#0088C9"}, //
"compose.yml": {Icon: "\uf21f", Color: "#0088C9"}, //
"config": {Icon: "\uf013", Color: "#696969"}, //
"containerfile": {Icon: "\uf21f", Color: "#0088C9"}, //
"copying": {Icon: "\U000f0124", Color: "#FF5821"}, //
"copying.lesser": {Icon: "\ue60a", Color: "#CBCB41"}, //
"docker-compose.yaml": {Icon: "\uf21f", Color: "#0088C9"}, //
"docker-compose.yml": {Icon: "\uf21f", Color: "#0088C9"}, //
"dockerfile": {Icon: "\uf21f", Color: "#0088C9"}, //
"Dockerfile": {Icon: "\uf308", Color: "#458EE6"}, //
"ds_store": {Icon: "\uf179", Color: "#DDDDDD"}, //
"eslint.config.cjs": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
"eslint.config.js": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
"eslint.config.mjs": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
"eslint.config.ts": {Icon: "\U000f0c7a", Color: "#3F52B5"}, //
"ext_typoscript_setup.txt": {Icon: "\ue772", Color: "#FF8700"}, //
"favicon.ico": {Icon: "\ue623", Color: "#CBCB41"}, //
"fp-info-cache": {Icon: "\uf34c", Color: "#FFFFFF"}, //
"fp-lib-table": {Icon: "\uf34c", Color: "#FFFFFF"}, //
"FreeCAD.conf": {Icon: "\uf336", Color: "#CB333B"}, //
"gemfile$": {Icon: "\ue791", Color: "#701516"}, //
"gitignore_global": {Icon: "\U000f02a2", Color: "#E64A19"}, //
"gnumakefile": {Icon: "\ueba2", Color: "#EF5351"}, //
"GNUmakefile": {Icon: "\ue779", Color: "#6D8086"}, //
"go.mod": {Icon: "\ue627", Color: "#02ACC1"}, //
"go.sum": {Icon: "\ue627", Color: "#02ACC1"}, //
"go.work": {Icon: "\ue627", Color: "#02ACC1"}, //
"gradle": {Icon: "\ue660", Color: "#005F87"}, //
"gradle-wrapper.properties": {Icon: "\ue660", Color: "#005F87"}, //
"gradle.properties": {Icon: "\ue660", Color: "#005F87"}, //
"gradlew": {Icon: "\ue660", Color: "#005F87"}, //
"gruntfile.babel.js": {Icon: "\ue611", Color: "#E37933"}, //
"gruntfile.coffee": {Icon: "\ue611", Color: "#E37933"}, //
"gruntfile.js": {Icon: "\ue611", Color: "#E37933"}, //
"gruntfile.ls": {Icon: "\ue611", Color: "#E37933"}, //
"gruntfile.ts": {Icon: "\ue611", Color: "#E37933"}, //
"gtkrc": {Icon: "\uf362", Color: "#FFFFFF"}, //
"gulpfile.babel.js": {Icon: "\ue610", Color: "#CC3E44"}, //
"gulpfile.coffee": {Icon: "\ue610", Color: "#CC3E44"}, //
"gulpfile.js": {Icon: "\ue610", Color: "#CC3E44"}, //
"gulpfile.ls": {Icon: "\ue610", Color: "#CC3E44"}, //
"gulpfile.ts": {Icon: "\ue610", Color: "#CC3E44"}, //
"hidden": {Icon: "\uf023", Color: "#555555"}, //
"hypridle.conf": {Icon: "\uf359", Color: "#00AAAE"}, //
"hyprland.conf": {Icon: "\uf359", Color: "#00AAAE"}, //
"hyprlock.conf": {Icon: "\uf359", Color: "#00AAAE"}, //
"hyprpaper.conf": {Icon: "\uf359", Color: "#00AAAE"}, //
"i3blocks.conf": {Icon: "\uf35a", Color: "#E8EBEE"}, //
"i3status.conf": {Icon: "\uf35a", Color: "#E8EBEE"}, //
"include": {Icon: "\ue5fc", Color: "#EEEEEE"}, //
"index.theme": {Icon: "\uee72", Color: "#2DB96F"}, //
"ionic.config.json": {Icon: "\ue66b", Color: "#508FF7"}, //
"justfile": {Icon: "\uf0ad", Color: "#6D8086"}, //
"kalgebrarc": {Icon: "\uf373", Color: "#1C99F3"}, //
"kdeglobals": {Icon: "\uf373", Color: "#1C99F3"}, //
"kdenlive-layoutsrc": {Icon: "\uf33c", Color: "#83B8F2"}, //
"kdenliverc": {Icon: "\uf33c", Color: "#83B8F2"}, //
"kritadisplayrc": {Icon: "\uf33d", Color: "#F245FB"}, //
"kritarc": {Icon: "\uf33d", Color: "#F245FB"}, //
"lib": {Icon: "\U000f1517", Color: "#8BC34A"}, //
"LICENSE": {Icon: "\uf02d", Color: "#EDEDED"}, //
"LICENSE.md": {Icon: "\uf02d", Color: "#EDEDED"}, //
"localized": {Icon: "\uf179", Color: "#DDDDDD"}, //
"lxde-rc.xml": {Icon: "\uf363", Color: "#909090"}, //
"lxqt.conf": {Icon: "\uf364", Color: "#0192D3"}, //
"Makefile": {Icon: "\ue673", Color: "#FEFEFE"}, //
"mix.lock": {Icon: "\ue62d", Color: "#A074C4"}, //
"mpv.conf": {Icon: "\uf36e", Color: "#3B1342"}, //
"node_modules": {Icon: "\ue718", Color: "#E8274B"}, //
"npmignore": {Icon: "\ue71e", Color: "#E8274B"}, //
"nuxt.config.cjs": {Icon: "\U000f1106", Color: "#00C58E"}, //
"nuxt.config.js": {Icon: "\U000f1106", Color: "#00C58E"}, //
"nuxt.config.mjs": {Icon: "\U000f1106", Color: "#00C58E"}, //
"nuxt.config.ts": {Icon: "\U000f1106", Color: "#00C58E"}, //
"package-lock.json": {Icon: "\ued0d", Color: "#F54436"}, //
"package.json": {Icon: "\ued0d", Color: "#4CAF51"}, //
"PKGBUILD": {Icon: "\uf303", Color: "#0F94D2"}, //
"platformio.ini": {Icon: "\ue682", Color: "#F6822B"}, //
"pom.xml": {Icon: "\U000f06d3", Color: "#FF7043"}, //
"prettier.config.cjs": {Icon: "\ue6b4", Color: "#4285F4"}, //
"prettier.config.js": {Icon: "\ue6b4", Color: "#4285F4"}, //
"prettier.config.mjs": {Icon: "\ue6b4", Color: "#4285F4"}, //
"prettier.config.ts": {Icon: "\ue6b4", Color: "#4285F4"}, //
"PrusaSlicer.ini": {Icon: "\uf351", Color: "#EC6B23"}, //
"PrusaSlicerGcodeViewer.ini": {Icon: "\uf351", Color: "#EC6B23"}, //
"py.typed": {Icon: "\ue606", Color: "#ffbc03"}, //
"QtProject.conf": {Icon: "\uf375", Color: "#40CD52"}, //
"R": {Icon: "\U000f07d4", Color: "#2266BA"}, //
"README": {Icon: "\U000f00ba", Color: "#EDEDED"}, //
"README.md": {Icon: "\U000f00ba", Color: "#EDEDED"}, //
"robots.txt": {Icon: "\U000f06a9", Color: "#5D7096"}, //
"rubydoc": {Icon: "\ue73b", Color: "#F32C24"}, //
"SECURITY": {Icon: "\U000f0483", Color: "#BEC4C9"}, //
"SECURITY.md": {Icon: "\U000f0483", Color: "#BEC4C9"}, //
"settings.gradle": {Icon: "\ue660", Color: "#005F87"}, //
"svelte.config.js": {Icon: "\ue697", Color: "#FF5821"}, //
"sxhkdrc": {Icon: "\uf355", Color: "#2F2F2F"}, //
"sym-lib-table": {Icon: "\uf34c", Color: "#FFFFFF"}, //
"tailwind.config.js": {Icon: "\U000f13ff", Color: "#4DB6AC"}, //
"tailwind.config.mjs": {Icon: "\U000f13ff", Color: "#4DB6AC"}, //
"tailwind.config.ts": {Icon: "\U000f13ff", Color: "#4DB6AC"}, //
"tmux.conf": {Icon: "\uebc8", Color: "#14BA19"}, //
"tmux.conf.local": {Icon: "\uebc8", Color: "#14BA19"}, //
"tsconfig.json": {Icon: "\ue628", Color: "#0188D1"}, //
"unlicense": {Icon: "\ue60a", Color: "#D0BF41"}, //
"vagrantfile$": {Icon: "\uf2b8", Color: "#1868F2"}, //
"vlcrc": {Icon: "\U000f057c", Color: "#E85E00"}, //
"webpack": {Icon: "\U000f072b", Color: "#519ABA"}, //
"weston.ini": {Icon: "\uf367", Color: "#FFBB01"}, //
"WORKSPACE": {Icon: "\ue63a", Color: "#89E051"}, //
"WORKSPACE.bzlmod": {Icon: "\ue63a", Color: "#89E051"}, //
"xmobarrc": {Icon: "\uf35e", Color: "#FD4D5D"}, //
"xmobarrc.hs": {Icon: "\uf35e", Color: "#FD4D5D"}, //
"xmonad.hs": {Icon: "\uf35e", Color: "#FD4D5D"}, //
"xorg.conf": {Icon: "\uf369", Color: "#E54D18"}, //
"xsettingsd.conf": {Icon: "\uf369", Color: "#E54D18"}, //
"yarn.lock": {Icon: "\ue6a7", Color: "#0188D1"}, //
}
var extIconMap = map[string]IconProperties{
".3gp": {Icon: "\uf03d", Color: "#F6822B"}, //
".3mf": {Icon: "\U000f01a7", Color: "#888888"}, //
".7z": {Icon: "\uf410", Color: "#ECA517"}, //
".DS_store": {Icon: "\uf179", Color: "#A2AAAD"}, //
".a": {Icon: "\U000f1517", Color: "#8BC34A"}, //
".aac": {Icon: "\uf001", Color: "#20C2E3"}, //
".adb": {Icon: "\ue6b5", Color: "#22FFFF"}, //
".ads": {Icon: "\ue6b5", Color: "#22FFFF"}, //
".ai": {Icon: "\ue7b4", Color: "#D0BF41"}, //
".aif": {Icon: "\uf001", Color: "#00AFFF"}, //
".aiff": {Icon: "\U000f0386", Color: "#EE534F"}, //
".android": {Icon: "\ue70e", Color: "#66AF3D"}, //
".ape": {Icon: "\uf001", Color: "#00AFFF"}, //
".apk": {Icon: "\ue70e", Color: "#8BC34A"}, //
".app": {Icon: "\ueae8", Color: "#9F0500"}, //
".apple": {Icon: "\ue635", Color: "#A2AAAD"}, //
".applescript": {Icon: "\uf302", Color: "#78919C"}, //
".asc": {Icon: "\U000f0306", Color: "#25A79A"}, //
".asm": {Icon: "\ue637", Color: "#0091BD"}, //
".ass": {Icon: "\U000f0a16", Color: "#FFB713"}, //
".astro": {Icon: "\ue6b3", Color: "#FF6D00"}, //
".avi": {Icon: "\U000f0381", Color: "#FF9800"}, //
".avif": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".avro": {Icon: "\ue60b", Color: "#965824"}, //
".awk": {Icon: "\U000f018d", Color: "#FF7043"}, //
".azcli": {Icon: "\uebd8", Color: "#2088E5"}, //
".bak": {Icon: "\U000f006f", Color: "#6D8086"}, //
".bash": {Icon: "\uebca", Color: "#FF7043"}, //
".bash_history": {Icon: "\ue795", Color: "#8DC149"}, //
".bash_profile": {Icon: "\ue795", Color: "#8DC149"}, //
".bashrc": {Icon: "\ue795", Color: "#8DC149"}, //
".bat": {Icon: "\U000f018d", Color: "#FF7043"}, //
".bats": {Icon: "\U000f0b5f", Color: "#D2D2D2"}, //
".bazel": {Icon: "\ue63a", Color: "#44A047"}, //
".bib": {Icon: "\U000f1517", Color: "#8BC34A"}, //
".bicep": {Icon: "\U000f0fd7", Color: "#FBC02D"}, //
".bicepparam": {Icon: "\ue63b", Color: "#797DAC"}, //
".blade.php": {Icon: "\uf2f7", Color: "#FF5252"}, //
".blend": {Icon: "\U000f00ab", Color: "#ED8F30"}, //
".blp": {Icon: "\U000f0ebe", Color: "#458EE6"}, //
".bmp": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".brep": {Icon: "\U000f0eeb", Color: "#839463"}, //
".bz": {Icon: "\uf410", Color: "#ECA517"}, //
".bz2": {Icon: "\uf410", Color: "#ECA517"}, //
".bz3": {Icon: "\uf410", Color: "#ECA517"}, //
".bzl": {Icon: "\ue63a", Color: "#44A047"}, //
".c": {Icon: "\ue61e", Color: "#0188D1"}, //
".c++": {Icon: "\ue61d", Color: "#0188D1"}, //
".cab": {Icon: "\ue70f", Color: "#626262"}, //
".cache": {Icon: "\uf49b", Color: "#FFFFFF"}, //
".cast": {Icon: "\uf03d", Color: "#EA8220"}, //
".cbl": {Icon: "\u2699", Color: "#005CA5"}, // ⚙
".cc": {Icon: "\ue61d", Color: "#0188D1"}, //
".ccm": {Icon: "\ue61d", Color: "#F34B7D"}, //
".cfg": {Icon: "\uf013", Color: "#42A5F5"}, //
".cjs": {Icon: "\ue60c", Color: "#CBCB41"}, //
".class": {Icon: "\uf0f4", Color: "#2088E5"}, //
".clj": {Icon: "\ue642", Color: "#2AB6F6"}, //
".cljc": {Icon: "\ue642", Color: "#2AB6F6"}, //
".cljd": {Icon: "\ue76a", Color: "#519ABA"}, //
".cljs": {Icon: "\ue642", Color: "#2AB6F6"}, //
".cls": {Icon: "\ue69b", Color: "#4B5163"}, //
".cmake": {Icon: "\ue794", Color: "#DCE3EB"}, //
".cmd": {Icon: "\uebc4", Color: "#FF7043"}, //
".cob": {Icon: "\u2699", Color: "#005CA5"}, // ⚙
".cobol": {Icon: "\u2699", Color: "#005CA5"}, // ⚙
".coffee": {Icon: "\ue61b", Color: "#6F4E38"}, //
".conda": {Icon: "\ue715", Color: "#43B02A"}, //
".conf": {Icon: "\uf013", Color: "#696969"}, //
".config.ru": {Icon: "\ue791", Color: "#701516"}, //
".cp": {Icon: "\ue646", Color: "#0188D1"}, //
".cpio": {Icon: "\uf410", Color: "#ECA517"}, //
".cpp": {Icon: "\ue61d", Color: "#0188D1"}, //
".cppm": {Icon: "\ue61d", Color: "#519ABA"}, //
".cpy": {Icon: "\u2699", Color: "#005CA5"}, // ⚙
".cr": {Icon: "\ue62f", Color: "#CFD8DD"}, //
".crdownload": {Icon: "\uf019", Color: "#44CDA8"}, //
".cs": {Icon: "\U000f031b", Color: "#0188D1"}, //
".csh": {Icon: "\U000f018d", Color: "#FF7043"}, //
".cshtml": {Icon: "\uf486", Color: "#42A5F5"}, //
".cson": {Icon: "\ue61b", Color: "#6F4E38"}, //
".csproj": {Icon: "\U000f0610", Color: "#AB48BC"}, //
".css": {Icon: "\ue749", Color: "#42A5F5"}, //
".csv": {Icon: "\U000f021b", Color: "#8BC34A"}, //
".csx": {Icon: "\U000f031b", Color: "#0188D1"}, //
".cts": {Icon: "\ue628", Color: "#519ABA"}, //
".cu": {Icon: "\ue64b", Color: "#89E051"}, //
".cue": {Icon: "\U000f0cb9", Color: "#ED95AE"}, //
".cuh": {Icon: "\ue64b", Color: "#A074C4"}, //
".cxx": {Icon: "\ue646", Color: "#0188D1"}, //
".cxxm": {Icon: "\ue61d", Color: "#519ABA"}, //
".d": {Icon: "\ue7af", Color: "#B03931"}, //
".d.ts": {Icon: "\ue628", Color: "#0188D1"}, //
".dart": {Icon: "\ue64c", Color: "#59B6F0"}, //
".db": {Icon: "\uf1c0", Color: "#FFCA29"}, //
".dconf": {Icon: "\ue706", Color: "#DAD8D8"}, //
".deb": {Icon: "\uebc5", Color: "#D80651"}, //
".desktop": {Icon: "\uf108", Color: "#56347C"}, //
".diff": {Icon: "\uf4d2", Color: "#4262A2"}, //
".djvu": {Icon: "\uf02d", Color: "#624262"}, //
".dll": {Icon: "\U000f107c", Color: "#42A5F5"}, //
".doc": {Icon: "\U000f022c", Color: "#0188D1"}, //
".docx": {Icon: "\U000f022c", Color: "#0188D1"}, //
".dot": {Icon: "\U000f1049", Color: "#005F87"}, //
".download": {Icon: "\uf019", Color: "#44CDA8"}, //
".drl": {Icon: "\ue28c", Color: "#FFAFAF"}, //
".dropbox": {Icon: "\ue707", Color: "#2E63FF"}, //
".ds_store": {Icon: "\uf179", Color: "#A2AAAD"}, //
".dump": {Icon: "\uf1c0", Color: "#DAD8D8"}, //
".dwg": {Icon: "\U000f0eeb", Color: "#839463"}, //
".dxf": {Icon: "\U000f0eeb", Color: "#839463"}, //
".ebook": {Icon: "\ue28b", Color: "#EAB16D"}, //
".ebuild": {Icon: "\uf30d", Color: "#4C416E"}, //
".editorconfig": {Icon: "\ue615", Color: "#626262"}, //
".edn": {Icon: "\ue76a", Color: "#519ABA"}, //
".eex": {Icon: "\ue62d", Color: "#9575CE"}, //
".ejs": {Icon: "\ue618", Color: "#CBCB41"}, //
".el": {Icon: "\ue632", Color: "#805EB7"}, //
".elc": {Icon: "\ue632", Color: "#805EB7"}, //
".elf": {Icon: "\ueae8", Color: "#9F0500"}, //
".elm": {Icon: "\ue62c", Color: "#60B6CC"}, //
".eln": {Icon: "\ue632", Color: "#8172BE"}, //
".env": {Icon: "\uf462", Color: "#FAF743"}, //
".eot": {Icon: "\ue659", Color: "#F54436"}, //
".epp": {Icon: "\ue631", Color: "#FFA61A"}, //
".epub": {Icon: "\ue28b", Color: "#EAB16D"}, //
".erb": {Icon: "\U000f0d2d", Color: "#F54436"}, //
".erl": {Icon: "\uf23f", Color: "#F54436"}, //
".ex": {Icon: "\ue62d", Color: "#9575CE"}, //
".exe": {Icon: "\uf2d0", Color: "#E64A19"}, //
".exs": {Icon: "\ue62d", Color: "#9575CE"}, //
".f#": {Icon: "\ue7a7", Color: "#519ABA"}, //
".f3d": {Icon: "\U000f0eeb", Color: "#839463"}, //
".f90": {Icon: "\U000f121a", Color: "#FF7043"}, //
".fbx": {Icon: "\uea8c", Color: "#2AB6F6"}, //
".fcbak": {Icon: "\uf336", Color: "#6D8086"}, //
".fcmacro": {Icon: "\uf336", Color: "#CB333B"}, //
".fcmat": {Icon: "\uf336", Color: "#CB333B"}, //
".fcparam": {Icon: "\uf336", Color: "#CB333B"}, //
".fcscript": {Icon: "\uf336", Color: "#CB333B"}, //
".fcstd": {Icon: "\uf336", Color: "#CB333B"}, //
".fcstd1": {Icon: "\uf336", Color: "#CB333B"}, //
".fctb": {Icon: "\uf336", Color: "#CB333B"}, //
".fctl": {Icon: "\uf336", Color: "#CB333B"}, //
".fdmdownload": {Icon: "\uf019", Color: "#44CDA8"}, //
".fish": {Icon: "\U000f023a", Color: "#FF7043"}, //
".flac": {Icon: "\U000f0386", Color: "#EE534F"}, //
".flc": {Icon: "\uf031", Color: "#ECECEC"}, //
".flf": {Icon: "\uf031", Color: "#ECECEC"}, //
".flv": {Icon: "\U000f0381", Color: "#FF9800"}, //
".fnl": {Icon: "\ue6af", Color: "#FFF3D7"}, //
".fodg": {Icon: "\uf379", Color: "#FFFB57"}, //
".fodp": {Icon: "\uf37a", Color: "#FE9C45"}, //
".fods": {Icon: "\uf378", Color: "#78FC4E"}, //
".fodt": {Icon: "\uf37c", Color: "#2DCBFD"}, //
".font": {Icon: "\ue659", Color: "#F54436"}, //
".fs": {Icon: "\ue7a7", Color: "#31B9DB"}, //
".fsi": {Icon: "\ue7a7", Color: "#31B9DB"}, //
".fsscript": {Icon: "\ue7a7", Color: "#519ABA"}, //
".fsx": {Icon: "\ue7a7", Color: "#31B9DB"}, //
".gcode": {Icon: "\U000f0af4", Color: "#505075"}, //
".gd": {Icon: "\ue65f", Color: "#42A5F5"}, //
".gdoc": {Icon: "\uf1c2", Color: "#01D000"}, //
".gem": {Icon: "\ue21e", Color: "#C90F02"}, //
".gemfile": {Icon: "\ueb48", Color: "#E63936"}, //
".gemspec": {Icon: "\ue21e", Color: "#C90F02"}, //
".gform": {Icon: "\uf298", Color: "#01D000"}, //
".gif": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".git": {Icon: "\U000f02a2", Color: "#EC6B23"}, //
".glb": {Icon: "\uf1b2", Color: "#FFA61A"}, //
".gnumakefile": {Icon: "\ueba2", Color: "#EF5351"}, //
".go": {Icon: "\ue627", Color: "#02ACC1"}, //
".godot": {Icon: "\ue65f", Color: "#42A5F5"}, //
".gpr": {Icon: "\ue6b5", Color: "#22FFFF"}, //
".gql": {Icon: "\U000f0877", Color: "#EC417A"}, //
".gradle": {Icon: "\ue660", Color: "#0397A7"}, //
".graphql": {Icon: "\U000f0877", Color: "#EC417A"}, //
".gresource": {Icon: "\uf362", Color: "#FFFFFF"}, //
".groovy": {Icon: "\ue775", Color: "#005F87"}, //
".gsheet": {Icon: "\uf1c3", Color: "#97BA6A"}, //
".gslides": {Icon: "\uf1c4", Color: "#FFFF00"}, //
".guardfile": {Icon: "\ue21e", Color: "#626262"}, //
".gv": {Icon: "\U000f1049", Color: "#005F87"}, //
".gz": {Icon: "\uf410", Color: "#ECA517"}, //
".h": {Icon: "\uf0fd", Color: "#A074C4"}, //
".haml": {Icon: "\ue664", Color: "#F4521E"}, //
".hbs": {Icon: "\U000f15de", Color: "#FF7043"}, //
".hc": {Icon: "\U000f00a2", Color: "#FAF743"}, //
".heex": {Icon: "\ue62d", Color: "#9575CE"}, //
".hex": {Icon: "\U000f12a7", Color: "#25A79A"}, //
".hh": {Icon: "\uf0fd", Color: "#A074C4"}, //
".hpp": {Icon: "\uf0fd", Color: "#A074C4"}, //
".hrl": {Icon: "\ue7b1", Color: "#B83998"}, //
".hs": {Icon: "\ue61f", Color: "#FFA726"}, //
".htm": {Icon: "\uf13b", Color: "#E44E27"}, //
".html": {Icon: "\uf13b", Color: "#E44E27"}, //
".huff": {Icon: "\U000f0858", Color: "#CFD8DD"}, //
".hurl": {Icon: "\uf0ec", Color: "#FF0288"}, //
".hx": {Icon: "\ue666", Color: "#F68713"}, //
".hxx": {Icon: "\uf0fd", Color: "#A074C4"}, //
".ical": {Icon: "\uf073", Color: "#2B9EF3"}, //
".icalendar": {Icon: "\uf073", Color: "#2B9EF3"}, //
".ico": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".ics": {Icon: "\U000f01ee", Color: "#42A5F5"}, //
".ifb": {Icon: "\uf073", Color: "#2B9EF3"}, //
".ifc": {Icon: "\U000f0eeb", Color: "#839463"}, //
".ige": {Icon: "\U000f0eeb", Color: "#839463"}, //
".iges": {Icon: "\U000f0eeb", Color: "#839463"}, //
".igs": {Icon: "\U000f0eeb", Color: "#839463"}, //
".image": {Icon: "\uf1c5", Color: "#CBCB41"}, //
".img": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".iml": {Icon: "\U000f022e", Color: "#8BC34A"}, //
".import": {Icon: "\uf0c6", Color: "#ECECEC"}, //
".info": {Icon: "\uf129", Color: "#FFF3D7"}, //
".ini": {Icon: "\uf013", Color: "#42A5F5"}, //
".ino": {Icon: "\uf34b", Color: "#01979D"}, //
".ipynb": {Icon: "\ue80f", Color: "#F57D01"}, //
".iso": {Icon: "\uede9", Color: "#B1BEC5"}, //
".ixx": {Icon: "\ue61d", Color: "#519ABA"}, //
".j2c": {Icon: "\uf1c5", Color: "#4B5163"}, //
".j2k": {Icon: "\uf1c5", Color: "#4B5163"}, //
".jad": {Icon: "\ue256", Color: "#F19210"}, //
".jar": {Icon: "\U000f06ca", Color: "#F19210"}, //
".java": {Icon: "\uf0f4", Color: "#F19210"}, //
".jfi": {Icon: "\uf1c5", Color: "#626262"}, //
".jfif": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".jif": {Icon: "\uf1c5", Color: "#626262"}, //
".jl": {Icon: "\ue624", Color: "#338A23"}, //
".jmd": {Icon: "\uf48a", Color: "#519ABA"}, //
".jp2": {Icon: "\uf1c5", Color: "#626262"}, //
".jpe": {Icon: "\uf1c5", Color: "#626262"}, //
".jpeg": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".jpg": {Icon: "\U000f021f", Color: "#25A6A0"}, //
".jpx": {Icon: "\uf1c5", Color: "#626262"}, //
".js": {Icon: "\U000f031e", Color: "#FFCA29"}, //
".json": {Icon: "\ue60b", Color: "#FAA825"}, //
".json5": {Icon: "\ue60b", Color: "#FAA825"}, //
".jsonc": {Icon: "\ue60b", Color: "#FAA825"}, //
".jsx": {Icon: "\ued46", Color: "#FFCA29"}, //
".jwmrc": {Icon: "\uf35b", Color: "#007AC2"}, //
".jxl": {Icon: "\uf1c5", Color: "#727252"}, //
".kbx": {Icon: "\U000f0bc4", Color: "#537662"}, //
".kdb": {Icon: "\uf23e", Color: "#529B34"}, //
".kdbx": {Icon: "\uf23e", Color: "#529B34"}, //
".kdenlive": {Icon: "\uf33c", Color: "#83B8F2"}, //
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/graph/graph_test.go | pkg/gui/presentation/graph/graph_test.go | package graph
import (
"fmt"
"math/rand"
"strings"
"testing"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/authors"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/xo/terminfo"
)
func TestRenderCommitGraph(t *testing.T) {
tests := []struct {
name string
commitOpts []models.NewCommitOpts
expectedOutput string
}{
{
name: "with some merges",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3"}},
{Hash: "3", Parents: []string{"4"}},
{Hash: "4", Parents: []string{"5", "7"}},
{Hash: "7", Parents: []string{"5"}},
{Hash: "5", Parents: []string{"8"}},
{Hash: "8", Parents: []string{"9"}},
{Hash: "9", Parents: []string{"A", "B"}},
{Hash: "B", Parents: []string{"D"}},
{Hash: "D", Parents: []string{"D"}},
{Hash: "A", Parents: []string{"E"}},
{Hash: "E", Parents: []string{"F"}},
{Hash: "F", Parents: []string{"D"}},
{Hash: "D", Parents: []string{"G"}},
},
expectedOutput: `
1 ◯
2 ◯
3 ◯
4 ⏣─╮
7 │ ◯
5 ◯─╯
8 ◯
9 ⏣─╮
B │ ◯
D │ ◯
A ◯ │
E ◯ │
F ◯ │
D ◯─╯`,
},
{
name: "with a path that has room to move to the left",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "4", Parents: []string{"3", "5"}},
{Hash: "3", Parents: []string{"5"}},
{Hash: "5", Parents: []string{"6"}},
{Hash: "6", Parents: []string{"7"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
4 │ ⏣─╮
3 ◯─╯ │
5 ◯───╯
6 ◯`,
},
{
name: "with a new commit",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "4", Parents: []string{"3", "5"}},
{Hash: "Z", Parents: []string{"Z"}},
{Hash: "3", Parents: []string{"5"}},
{Hash: "5", Parents: []string{"6"}},
{Hash: "6", Parents: []string{"7"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
4 │ ⏣─╮
Z │ │ │ ◯
3 ◯─╯ │ │
5 ◯───╯ │
6 ◯ ╭───╯`,
},
{
name: "with a path that has room to move to the left and continues",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "3", Parents: []string{"5", "4"}},
{Hash: "5", Parents: []string{"7", "8"}},
{Hash: "4", Parents: []string{"7"}},
{Hash: "7", Parents: []string{"11"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
3 ⏣─│─╮
5 ⏣─│─│─╮
4 │ ◯─╯ │
7 ◯─╯ ╭─╯`,
},
{
name: "with a path that has room to move to the left and continues",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "3", Parents: []string{"5", "4"}},
{Hash: "5", Parents: []string{"7", "8"}},
{Hash: "7", Parents: []string{"4", "A"}},
{Hash: "4", Parents: []string{"B"}},
{Hash: "B", Parents: []string{"C"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
3 ⏣─│─╮
5 ⏣─│─│─╮
7 ⏣─│─│─│─╮
4 ◯─┴─╯ │ │
B ◯ ╭───╯ │`,
},
{
name: "with a path that has room to move to the left and continues",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2", "3"}},
{Hash: "3", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"4", "5"}},
{Hash: "4", Parents: []string{"6", "7"}},
{Hash: "6", Parents: []string{"8"}},
},
expectedOutput: `
1 ⏣─╮
3 │ ◯
2 ⏣─│
4 ⏣─│─╮
6 ◯ │ │`,
},
{
name: "new merge path fills gap before continuing path on right",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2", "3", "4", "5"}},
{Hash: "4", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"A"}},
{Hash: "A", Parents: []string{"6", "B"}},
{Hash: "B", Parents: []string{"C"}},
},
expectedOutput: `
1 ⏣─┬─┬─╮
4 │ │ ◯ │
2 ◯─│─╯ │
A ⏣─│─╮ │
B │ │ ◯ │`,
},
{
name: "with a path that has room to move to the left and continues",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "3", Parents: []string{"5", "4"}},
{Hash: "5", Parents: []string{"7", "8"}},
{Hash: "7", Parents: []string{"4", "A"}},
{Hash: "4", Parents: []string{"B"}},
{Hash: "B", Parents: []string{"C"}},
{Hash: "C", Parents: []string{"D"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
3 ⏣─│─╮
5 ⏣─│─│─╮
7 ⏣─│─│─│─╮
4 ◯─┴─╯ │ │
B ◯ ╭───╯ │
C ◯ │ ╭───╯`,
},
{
name: "with a path that has room to move to the left and continues",
commitOpts: []models.NewCommitOpts{
{Hash: "1", Parents: []string{"2"}},
{Hash: "2", Parents: []string{"3", "4"}},
{Hash: "3", Parents: []string{"5", "4"}},
{Hash: "5", Parents: []string{"7", "G"}},
{Hash: "7", Parents: []string{"8", "A"}},
{Hash: "8", Parents: []string{"4", "E"}},
{Hash: "4", Parents: []string{"B"}},
{Hash: "B", Parents: []string{"C"}},
{Hash: "C", Parents: []string{"D"}},
{Hash: "D", Parents: []string{"F"}},
},
expectedOutput: `
1 ◯
2 ⏣─╮
3 ⏣─│─╮
5 ⏣─│─│─╮
7 ⏣─│─│─│─╮
8 ⏣─│─│─│─│─╮
4 ◯─┴─╯ │ │ │
B ◯ ╭───╯ │ │
C ◯ │ ╭───╯ │
D ◯ │ │ ╭───╯`,
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions)
defer color.ForceSetColorLevel(oldColorLevel)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
hashPool := &utils.StringPool{}
getStyle := func(c *models.Commit) *style.TextStyle { return &style.FgDefault }
commits := lo.Map(test.commitOpts,
func(opts models.NewCommitOpts, _ int) *models.Commit { return models.NewCommit(hashPool, opts) })
lines := RenderCommitGraph(commits, hashPool.Add("blah"), getStyle)
trimmedExpectedOutput := ""
for line := range strings.SplitSeq(strings.TrimPrefix(test.expectedOutput, "\n"), "\n") {
trimmedExpectedOutput += strings.TrimSpace(line) + "\n"
}
t.Log("\nexpected: \n" + trimmedExpectedOutput)
output := ""
for i, line := range lines {
description := test.commitOpts[i].Hash
output += strings.TrimSpace(description+" "+utils.Decolorise(line)) + "\n"
}
t.Log("\nactual: \n" + output)
assert.Equal(t,
trimmedExpectedOutput,
output)
})
}
}
func TestRenderPipeSet(t *testing.T) {
cyan := style.FgCyan
red := style.FgRed
green := style.FgGreen
// blue := style.FgBlue
yellow := style.FgYellow
magenta := style.FgMagenta
nothing := style.Nothing
hashPool := &utils.StringPool{}
pool := func(s string) *string { return hashPool.Add(s) }
tests := []struct {
name string
pipes []Pipe
commit *models.Commit
prevCommit *models.Commit
expectedStr string
expectedStyles []style.TextStyle
}{
{
name: "single cell",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("b"), kind: TERMINATES, style: &cyan},
{fromPos: 0, toPos: 0, fromHash: pool("b"), toHash: pool("c"), kind: STARTS, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a"}),
expectedStr: "◯",
expectedStyles: []style.TextStyle{green},
},
{
name: "single cell, selected",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("selected"), kind: TERMINATES, style: &cyan},
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("c"), kind: STARTS, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a"}),
expectedStr: "◯",
expectedStyles: []style.TextStyle{highlightStyle},
},
{
name: "terminating hook and starting hook, selected",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("selected"), kind: TERMINATES, style: &cyan},
{fromPos: 1, toPos: 0, fromHash: pool("c"), toHash: pool("selected"), kind: TERMINATES, style: &yellow},
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("d"), kind: STARTS, style: &green},
{fromPos: 0, toPos: 1, fromHash: pool("selected"), toHash: pool("e"), kind: STARTS, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a"}),
expectedStr: "⏣─╮",
expectedStyles: []style.TextStyle{
highlightStyle, highlightStyle, highlightStyle,
},
},
{
name: "terminating hook and starting hook, prioritise the terminating one",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("b"), kind: TERMINATES, style: &red},
{fromPos: 1, toPos: 0, fromHash: pool("c"), toHash: pool("b"), kind: TERMINATES, style: &magenta},
{fromPos: 0, toPos: 0, fromHash: pool("b"), toHash: pool("d"), kind: STARTS, style: &green},
{fromPos: 0, toPos: 1, fromHash: pool("b"), toHash: pool("e"), kind: STARTS, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a"}),
expectedStr: "⏣─│",
expectedStyles: []style.TextStyle{
green, green, magenta,
},
},
{
name: "starting and terminating pipe sharing some space",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 1, toPos: 1, fromHash: pool("b1"), toHash: pool("b2"), kind: CONTINUES, style: &magenta},
{fromPos: 3, toPos: 0, fromHash: pool("e1"), toHash: pool("a2"), kind: TERMINATES, style: &green},
{fromPos: 0, toPos: 2, fromHash: pool("a2"), toHash: pool("c3"), kind: STARTS, style: &yellow},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "⏣─│─┬─╯",
expectedStyles: []style.TextStyle{
yellow, yellow, magenta, yellow, yellow, green, green,
},
},
{
name: "starting and terminating pipe sharing some space, with selection",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("selected"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 1, toPos: 1, fromHash: pool("b1"), toHash: pool("b2"), kind: CONTINUES, style: &magenta},
{fromPos: 3, toPos: 0, fromHash: pool("e1"), toHash: pool("selected"), kind: TERMINATES, style: &green},
{fromPos: 0, toPos: 2, fromHash: pool("selected"), toHash: pool("c3"), kind: STARTS, style: &yellow},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "⏣───╮ ╯",
expectedStyles: []style.TextStyle{
highlightStyle, highlightStyle, highlightStyle, highlightStyle, highlightStyle, nothing, green,
},
},
{
name: "many terminating pipes",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 1, toPos: 0, fromHash: pool("b1"), toHash: pool("a2"), kind: TERMINATES, style: &magenta},
{fromPos: 2, toPos: 0, fromHash: pool("c1"), toHash: pool("a2"), kind: TERMINATES, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "◯─┴─╯",
expectedStyles: []style.TextStyle{
yellow, magenta, magenta, green, green,
},
},
{
name: "starting pipe passing through",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 0, toPos: 3, fromHash: pool("a2"), toHash: pool("d3"), kind: STARTS, style: &yellow},
{fromPos: 1, toPos: 1, fromHash: pool("b1"), toHash: pool("b3"), kind: CONTINUES, style: &magenta},
{fromPos: 2, toPos: 2, fromHash: pool("c1"), toHash: pool("c3"), kind: CONTINUES, style: &green},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "⏣─│─│─╮",
expectedStyles: []style.TextStyle{
yellow, yellow, magenta, yellow, green, yellow, yellow,
},
},
{
name: "starting and terminating path crossing continuing path",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 0, toPos: 1, fromHash: pool("a2"), toHash: pool("b3"), kind: STARTS, style: &yellow},
{fromPos: 1, toPos: 1, fromHash: pool("b1"), toHash: pool("a2"), kind: CONTINUES, style: &green},
{fromPos: 2, toPos: 0, fromHash: pool("c1"), toHash: pool("a2"), kind: TERMINATES, style: &magenta},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "⏣─│─╯",
expectedStyles: []style.TextStyle{
yellow, yellow, green, magenta, magenta,
},
},
{
name: "another clash of starting and terminating paths",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
{fromPos: 0, toPos: 1, fromHash: pool("a2"), toHash: pool("b3"), kind: STARTS, style: &yellow},
{fromPos: 2, toPos: 2, fromHash: pool("c1"), toHash: pool("c3"), kind: CONTINUES, style: &green},
{fromPos: 3, toPos: 0, fromHash: pool("d1"), toHash: pool("a2"), kind: TERMINATES, style: &magenta},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a1"}),
expectedStr: "⏣─┬─│─╯",
expectedStyles: []style.TextStyle{
yellow, yellow, yellow, magenta, green, magenta, magenta,
},
},
{
name: "commit whose previous commit is selected",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &yellow},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "selected"}),
expectedStr: "◯",
expectedStyles: []style.TextStyle{
yellow,
},
},
{
name: "commit whose previous commit is selected and is a merge commit",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 1, toPos: 1, fromHash: pool("selected"), toHash: pool("b3"), kind: CONTINUES, style: &red},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "selected"}),
expectedStr: "◯ │",
expectedStyles: []style.TextStyle{
highlightStyle, nothing, highlightStyle,
},
},
{
name: "commit whose previous commit is selected and is a merge commit, with continuing pipe inbetween",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("selected"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 1, toPos: 1, fromHash: pool("z1"), toHash: pool("z3"), kind: CONTINUES, style: &green},
{fromPos: 2, toPos: 2, fromHash: pool("selected"), toHash: pool("b3"), kind: CONTINUES, style: &red},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "selected"}),
expectedStr: "◯ │ │",
expectedStyles: []style.TextStyle{
highlightStyle, nothing, green, nothing, highlightStyle,
},
},
{
name: "when previous commit is selected, not a merge commit, and spawns a continuing pipe",
pipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a1"), toHash: pool("a2"), kind: TERMINATES, style: &red},
{fromPos: 0, toPos: 0, fromHash: pool("a2"), toHash: pool("a3"), kind: STARTS, style: &green},
{fromPos: 0, toPos: 1, fromHash: pool("a2"), toHash: pool("b3"), kind: STARTS, style: &green},
{fromPos: 1, toPos: 0, fromHash: pool("selected"), toHash: pool("a2"), kind: TERMINATES, style: &yellow},
},
prevCommit: models.NewCommit(hashPool, models.NewCommitOpts{Hash: "selected"}),
expectedStr: "⏣─╯",
expectedStyles: []style.TextStyle{
highlightStyle, highlightStyle, highlightStyle,
},
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions)
defer color.ForceSetColorLevel(oldColorLevel)
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actualStr := renderPipeSet(test.pipes, pool("selected"), test.prevCommit)
t.Log("actual cells:")
t.Log(actualStr)
expectedStr := ""
if len([]rune(test.expectedStr)) != len(test.expectedStyles) {
t.Fatalf("Error in test setup: you have %d characters in the expected output (%s) but have specified %d styles", len([]rune(test.expectedStr)), test.expectedStr, len(test.expectedStyles))
}
for i, char := range []rune(test.expectedStr) {
expectedStr += test.expectedStyles[i].Sprint(string(char))
}
expectedStr += " "
t.Log("expected cells:")
t.Log(expectedStr)
assert.Equal(t, expectedStr, actualStr)
})
}
}
func TestGetNextPipes(t *testing.T) {
hashPool := &utils.StringPool{}
pool := func(s string) *string { return hashPool.Add(s) }
tests := []struct {
prevPipes []Pipe
commit *models.Commit
expected []Pipe
}{
{
prevPipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("b"), kind: STARTS, style: &style.FgDefault},
},
commit: models.NewCommit(hashPool, models.NewCommitOpts{
Hash: "b",
Parents: []string{"c"},
}),
expected: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("b"), kind: TERMINATES, style: &style.FgDefault},
{fromPos: 0, toPos: 0, fromHash: pool("b"), toHash: pool("c"), kind: STARTS, style: &style.FgDefault},
},
},
{
prevPipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("b"), kind: TERMINATES, style: &style.FgDefault},
{fromPos: 0, toPos: 0, fromHash: pool("b"), toHash: pool("c"), kind: STARTS, style: &style.FgDefault},
{fromPos: 0, toPos: 1, fromHash: pool("b"), toHash: pool("d"), kind: STARTS, style: &style.FgDefault},
},
commit: models.NewCommit(hashPool, models.NewCommitOpts{
Hash: "d",
Parents: []string{"e"},
}),
expected: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("b"), toHash: pool("c"), kind: CONTINUES, style: &style.FgDefault},
{fromPos: 1, toPos: 1, fromHash: pool("b"), toHash: pool("d"), kind: TERMINATES, style: &style.FgDefault},
{fromPos: 1, toPos: 1, fromHash: pool("d"), toHash: pool("e"), kind: STARTS, style: &style.FgDefault},
},
},
{
prevPipes: []Pipe{
{fromPos: 0, toPos: 0, fromHash: pool("a"), toHash: pool("root"), kind: TERMINATES, style: &style.FgDefault},
},
commit: models.NewCommit(hashPool, models.NewCommitOpts{
Hash: "root",
Parents: []string{},
}),
expected: []Pipe{
{fromPos: 1, toPos: 1, fromHash: pool("root"), toHash: pool(models.EmptyTreeCommitHash), kind: STARTS, style: &style.FgDefault},
},
},
}
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions)
defer color.ForceSetColorLevel(oldColorLevel)
for _, test := range tests {
getStyle := func(c *models.Commit) *style.TextStyle { return &style.FgDefault }
pipes := getNextPipes(test.prevPipes, test.commit, getStyle)
// rendering cells so that it's easier to see what went wrong
actualStr := renderPipeSet(pipes, pool("selected"), nil)
expectedStr := renderPipeSet(test.expected, pool("selected"), nil)
t.Log("expected cells:")
t.Log(expectedStr)
t.Log("actual cells:")
t.Log(actualStr)
assert.EqualValues(t, test.expected, pipes)
}
}
func BenchmarkRenderCommitGraph(b *testing.B) {
oldColorLevel := color.ForceSetColorLevel(terminfo.ColorLevelMillions)
defer color.ForceSetColorLevel(oldColorLevel)
hashPool := &utils.StringPool{}
commits := generateCommits(hashPool, 50)
getStyle := func(commit *models.Commit) *style.TextStyle {
return authors.AuthorStyle(commit.AuthorName)
}
b.ResetTimer()
for b.Loop() {
RenderCommitGraph(commits, hashPool.Add("selected"), getStyle)
}
}
func generateCommits(hashPool *utils.StringPool, count int) []*models.Commit {
rnd := rand.New(rand.NewSource(1234))
pool := []*models.Commit{models.NewCommit(hashPool, models.NewCommitOpts{Hash: "a", AuthorName: "A"})}
commits := make([]*models.Commit, 0, count)
authorPool := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
for len(commits) < count {
currentCommitIdx := rnd.Intn(len(pool))
currentCommit := pool[currentCommitIdx]
pool = append(pool[0:currentCommitIdx], pool[currentCommitIdx+1:]...)
// I need to pick a random number of parents to add
parentCount := rnd.Intn(2) + 1
parentHashes := currentCommit.Parents()
for j := range parentCount {
reuseParent := rnd.Intn(6) != 1 && j <= len(pool)-1 && j != 0
var newParent *models.Commit
if reuseParent {
newParent = pool[j]
} else {
newParent = models.NewCommit(hashPool, models.NewCommitOpts{
Hash: fmt.Sprintf("%s%d", currentCommit.Hash(), j),
AuthorName: authorPool[rnd.Intn(len(authorPool))],
})
pool = append(pool, newParent)
}
parentHashes = append(parentHashes, newParent.Hash())
}
changedCommit := models.NewCommit(hashPool, models.NewCommitOpts{
Hash: currentCommit.Hash(),
AuthorName: currentCommit.AuthorName,
Parents: parentHashes,
})
commits = append(commits, changedCommit)
}
return commits
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/graph/cell.go | pkg/gui/presentation/graph/cell.go | package graph
import (
"io"
"sync"
"github.com/gookit/color"
"github.com/jesseduffield/lazygit/pkg/gui/style"
)
const (
MergeSymbol = '⏣'
CommitSymbol = '◯'
)
type cellType int
const (
CONNECTION cellType = iota
COMMIT
MERGE
)
type Cell struct {
up, down, left, right bool
cellType cellType
rightStyle *style.TextStyle
style *style.TextStyle
}
func (cell *Cell) render(writer io.StringWriter) {
up, down, left, right := cell.up, cell.down, cell.left, cell.right
first, second := getBoxDrawingChars(up, down, left, right)
var adjustedFirst string
switch cell.cellType {
case CONNECTION:
adjustedFirst = first
case COMMIT:
adjustedFirst = string(CommitSymbol)
case MERGE:
adjustedFirst = string(MergeSymbol)
}
var rightStyle *style.TextStyle
if cell.rightStyle == nil {
rightStyle = cell.style
} else {
rightStyle = cell.rightStyle
}
// just doing this for the sake of easy testing, so that we don't need to
// assert on the style of a space given a space has no styling (assuming we
// stick to only using foreground styles)
var styledSecondChar string
if second == " " {
styledSecondChar = " "
} else {
styledSecondChar = cachedSprint(*rightStyle, second)
}
_, _ = writer.WriteString(cachedSprint(*cell.style, adjustedFirst))
_, _ = writer.WriteString(styledSecondChar)
}
type rgbCacheKey struct {
*color.RGBStyle
str string
}
var (
rgbCache = make(map[rgbCacheKey]string)
rgbCacheMutex sync.RWMutex
)
func cachedSprint(style style.TextStyle, str string) string {
switch v := style.Style.(type) {
case *color.RGBStyle:
rgbCacheMutex.RLock()
key := rgbCacheKey{v, str}
value, ok := rgbCache[key]
rgbCacheMutex.RUnlock()
if ok {
return value
}
value = style.Sprint(str)
rgbCacheMutex.Lock()
rgbCache[key] = value
rgbCacheMutex.Unlock()
return value
case color.Basic:
return style.Sprint(str)
case color.Style:
value := style.Sprint(str)
return value
}
return style.Sprint(str)
}
func (cell *Cell) reset() {
cell.up = false
cell.down = false
cell.left = false
cell.right = false
}
func (cell *Cell) setUp(style *style.TextStyle) *Cell {
cell.up = true
cell.style = style
return cell
}
func (cell *Cell) setDown(style *style.TextStyle) *Cell {
cell.down = true
cell.style = style
return cell
}
func (cell *Cell) setLeft(style *style.TextStyle) *Cell {
cell.left = true
if !cell.up && !cell.down {
// vertical trumps left
cell.style = style
}
return cell
}
//nolint:unparam
func (cell *Cell) setRight(style *style.TextStyle, override bool) *Cell {
cell.right = true
if cell.rightStyle == nil || override {
cell.rightStyle = style
}
return cell
}
func (cell *Cell) setStyle(style *style.TextStyle) *Cell {
cell.style = style
return cell
}
func (cell *Cell) setType(cellType cellType) *Cell {
cell.cellType = cellType
return cell
}
func getBoxDrawingChars(up, down, left, right bool) (string, string) {
if up && down && left && right {
return "│", "─"
} else if up && down && left && !right {
return "│", " "
} else if up && down && !left && right {
return "│", "─"
} else if up && down && !left && !right {
return "│", " "
} else if up && !down && left && right {
return "┴", "─"
} else if up && !down && left && !right {
return "╯", " "
} else if up && !down && !left && right {
return "╰", "─"
} else if up && !down && !left && !right {
return "╵", " "
} else if !up && down && left && right {
return "┬", "─"
} else if !up && down && left && !right {
return "╮", " "
} else if !up && down && !left && right {
return "╭", "─"
} else if !up && down && !left && !right {
return "╷", " "
} else if !up && !down && left && right {
return "─", "─"
} else if !up && !down && left && !right {
return "─", " "
} else if !up && !down && !left && right {
return "╶", "─"
} else if !up && !down && !left && !right {
return " ", " "
}
panic("should not be possible")
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/presentation/graph/graph.go | pkg/gui/presentation/graph/graph.go | package graph
import (
"cmp"
"runtime"
"slices"
"strings"
"sync"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
type PipeKind uint8
const (
TERMINATES PipeKind = iota
STARTS
CONTINUES
)
type Pipe struct {
fromHash *string
toHash *string
style *style.TextStyle
fromPos int16
toPos int16
kind PipeKind
}
var (
highlightStyle = style.FgLightWhite.SetBold()
EmptyTreeCommitHash = models.EmptyTreeCommitHash
StartCommitHash = "START"
)
func (self Pipe) left() int16 {
return min(self.fromPos, self.toPos)
}
func (self Pipe) right() int16 {
return max(self.fromPos, self.toPos)
}
func RenderCommitGraph(commits []*models.Commit, selectedCommitHashPtr *string, getStyle func(c *models.Commit) *style.TextStyle) []string {
pipeSets := GetPipeSets(commits, getStyle)
if len(pipeSets) == 0 {
return nil
}
lines := RenderAux(pipeSets, commits, selectedCommitHashPtr)
return lines
}
func GetPipeSets(commits []*models.Commit, getStyle func(c *models.Commit) *style.TextStyle) [][]Pipe {
if len(commits) == 0 {
return nil
}
pipes := []Pipe{{fromPos: 0, toPos: 0, fromHash: &StartCommitHash, toHash: commits[0].HashPtr(), kind: STARTS, style: &style.FgDefault}}
return lo.Map(commits, func(commit *models.Commit, _ int) []Pipe {
pipes = getNextPipes(pipes, commit, getStyle)
return pipes
})
}
func RenderAux(pipeSets [][]Pipe, commits []*models.Commit, selectedCommitHashPtr *string) []string {
maxProcs := runtime.GOMAXPROCS(0)
// splitting up the rendering of the graph into multiple goroutines allows us to render the graph in parallel
chunks := make([][]string, maxProcs)
perProc := len(pipeSets) / maxProcs
wg := sync.WaitGroup{}
wg.Add(maxProcs)
for i := range maxProcs {
go func() {
from := i * perProc
to := (i + 1) * perProc
if i == maxProcs-1 {
to = len(pipeSets)
}
innerLines := make([]string, 0, to-from)
for j, pipeSet := range pipeSets[from:to] {
k := from + j
var prevCommit *models.Commit
if k > 0 {
prevCommit = commits[k-1]
}
line := renderPipeSet(pipeSet, selectedCommitHashPtr, prevCommit)
innerLines = append(innerLines, line)
}
chunks[i] = innerLines
wg.Done()
}()
}
wg.Wait()
return lo.Flatten(chunks)
}
func getNextPipes(prevPipes []Pipe, commit *models.Commit, getStyle func(c *models.Commit) *style.TextStyle) []Pipe {
maxPos := int16(0)
for _, pipe := range prevPipes {
if pipe.toPos > maxPos {
maxPos = pipe.toPos
}
}
// a pipe that terminated in the previous line has no bearing on the current line
// so we'll filter those out
currentPipes := lo.Filter(prevPipes, func(pipe Pipe, _ int) bool {
return pipe.kind != TERMINATES
})
newPipes := make([]Pipe, 0, len(currentPipes)+len(commit.ParentPtrs()))
// start by assuming that we've got a brand new commit not related to any preceding commit.
// (this only happens when we're doing `git log --all`). These will be tacked onto the far end.
pos := maxPos + 1
for _, pipe := range currentPipes {
if equalHashes(pipe.toHash, commit.HashPtr()) {
// turns out this commit does have a descendant so we'll place it right under the first instance
pos = pipe.toPos
break
}
}
// a taken spot is one where a current pipe is ending on
// Note: this set and similar ones below use int instead of int16 because
// that's much more efficient. We cast the int16 values we store in these
// sets to int on every access.
takenSpots := set.New[int]()
// a traversed spot is one where a current pipe is starting on, ending on, or passing through
traversedSpots := set.New[int]()
var toHash *string
if commit.IsFirstCommit() {
toHash = &EmptyTreeCommitHash
} else {
toHash = commit.ParentPtrs()[0]
}
newPipes = append(newPipes, Pipe{
fromPos: pos,
toPos: pos,
fromHash: commit.HashPtr(),
toHash: toHash,
kind: STARTS,
style: getStyle(commit),
})
traversedSpotsForContinuingPipes := set.New[int]()
for _, pipe := range currentPipes {
if !equalHashes(pipe.toHash, commit.HashPtr()) {
traversedSpotsForContinuingPipes.Add(int(pipe.toPos))
}
}
getNextAvailablePosForContinuingPipe := func() int16 {
i := int16(0)
for {
if !traversedSpots.Includes(int(i)) {
return i
}
i++
}
}
getNextAvailablePosForNewPipe := func() int16 {
i := int16(0)
for {
// a newly created pipe is not allowed to end on a spot that's already taken,
// nor on a spot that's been traversed by a continuing pipe.
if !takenSpots.Includes(int(i)) && !traversedSpotsForContinuingPipes.Includes(int(i)) {
return i
}
i++
}
}
traverse := func(from, to int16) {
left, right := from, to
if left > right {
left, right = right, left
}
for i := left; i <= right; i++ {
traversedSpots.Add(int(i))
}
takenSpots.Add(int(to))
}
for _, pipe := range currentPipes {
if equalHashes(pipe.toHash, commit.HashPtr()) {
// terminating here
newPipes = append(newPipes, Pipe{
fromPos: pipe.toPos,
toPos: pos,
fromHash: pipe.fromHash,
toHash: pipe.toHash,
kind: TERMINATES,
style: pipe.style,
})
traverse(pipe.toPos, pos)
} else if pipe.toPos < pos {
// continuing here
availablePos := getNextAvailablePosForContinuingPipe()
newPipes = append(newPipes, Pipe{
fromPos: pipe.toPos,
toPos: availablePos,
fromHash: pipe.fromHash,
toHash: pipe.toHash,
kind: CONTINUES,
style: pipe.style,
})
traverse(pipe.toPos, availablePos)
}
}
if commit.IsMerge() {
for _, parent := range commit.ParentPtrs()[1:] {
availablePos := getNextAvailablePosForNewPipe()
// need to act as if continuing pipes are going to continue on the same line.
newPipes = append(newPipes, Pipe{
fromPos: pos,
toPos: availablePos,
fromHash: commit.HashPtr(),
toHash: parent,
kind: STARTS,
style: getStyle(commit),
})
takenSpots.Add(int(availablePos))
}
}
for _, pipe := range currentPipes {
if !equalHashes(pipe.toHash, commit.HashPtr()) && pipe.toPos > pos {
// continuing on, potentially moving left to fill in a blank spot
last := pipe.toPos
for i := pipe.toPos; i > pos; i-- {
if takenSpots.Includes(int(i)) || traversedSpots.Includes(int(i)) {
break
}
last = i
}
newPipes = append(newPipes, Pipe{
fromPos: pipe.toPos,
toPos: last,
fromHash: pipe.fromHash,
toHash: pipe.toHash,
kind: CONTINUES,
style: pipe.style,
})
traverse(pipe.toPos, last)
}
}
// not efficient but doing it for now: sorting my pipes by toPos, then by kind
slices.SortFunc(newPipes, func(a, b Pipe) int {
if a.toPos == b.toPos {
return cmp.Compare(a.kind, b.kind)
}
return cmp.Compare(a.toPos, b.toPos)
})
return newPipes
}
func renderPipeSet(
pipes []Pipe,
selectedCommitHashPtr *string,
prevCommit *models.Commit,
) string {
maxPos := int16(0)
commitPos := int16(0)
startCount := 0
for _, pipe := range pipes {
if pipe.kind == STARTS {
startCount++
commitPos = pipe.fromPos
} else if pipe.kind == TERMINATES {
commitPos = pipe.toPos
}
if pipe.right() > maxPos {
maxPos = pipe.right()
}
}
isMerge := startCount > 1
cells := lo.Map(lo.Range(int(maxPos)+1), func(i int, _ int) *Cell {
return &Cell{cellType: CONNECTION, style: &style.FgDefault}
})
renderPipe := func(pipe *Pipe, style *style.TextStyle, overrideRightStyle bool) {
left := pipe.left()
right := pipe.right()
if left != right {
for i := left + 1; i < right; i++ {
cells[i].setLeft(style).setRight(style, overrideRightStyle)
}
cells[left].setRight(style, overrideRightStyle)
cells[right].setLeft(style)
}
if pipe.kind == STARTS || pipe.kind == CONTINUES {
cells[pipe.toPos].setDown(style)
}
if pipe.kind == TERMINATES || pipe.kind == CONTINUES {
cells[pipe.fromPos].setUp(style)
}
}
// we don't want to highlight two commits if they're contiguous. We only want
// to highlight multiple things if there's an actual visible pipe involved.
highlight := true
if prevCommit != nil && equalHashes(prevCommit.HashPtr(), selectedCommitHashPtr) {
highlight = false
for _, pipe := range pipes {
if equalHashes(pipe.fromHash, selectedCommitHashPtr) && (pipe.kind != TERMINATES || pipe.fromPos != pipe.toPos) {
highlight = true
}
}
}
// so we have our commit pos again, now it's time to build the cells.
// we'll handle the one that's sourced from our selected commit last so that it can override the other cells.
selectedPipes, nonSelectedPipes := utils.Partition(pipes, func(pipe Pipe) bool {
return highlight && equalHashes(pipe.fromHash, selectedCommitHashPtr)
})
for _, pipe := range nonSelectedPipes {
if pipe.kind == STARTS {
renderPipe(&pipe, pipe.style, true)
}
}
for _, pipe := range nonSelectedPipes {
if pipe.kind != STARTS && !(pipe.kind == TERMINATES && pipe.fromPos == commitPos && pipe.toPos == commitPos) {
renderPipe(&pipe, pipe.style, false)
}
}
for _, pipe := range selectedPipes {
for i := pipe.left(); i <= pipe.right(); i++ {
cells[i].reset()
}
}
for _, pipe := range selectedPipes {
renderPipe(&pipe, &highlightStyle, true)
if pipe.toPos == commitPos {
cells[pipe.toPos].setStyle(&highlightStyle)
}
}
cType := COMMIT
if isMerge {
cType = MERGE
}
cells[commitPos].setType(cType)
// using a string builder here for the sake of performance
writer := &strings.Builder{}
writer.Grow(len(cells) * 2)
for _, cell := range cells {
cell.render(writer)
}
return writer.String()
}
func equalHashes(a, b *string) bool {
// if our selectedCommitHashPtr is nil, there is no selected commit
if a == nil || b == nil {
return false
}
// We know that all hashes are stored in the pool, so we can compare their addresses
return a == b
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/patch_exploring/state.go | pkg/gui/patch_exploring/state.go | package patch_exploring
import (
"strings"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
// State represents the current state of the patch explorer context i.e. when
// you're staging a file or you're building a patch from an existing commit
// this struct holds the info about the diff you're interacting with and what's currently selected.
type State struct {
// These are in terms of view lines (wrapped), not patch lines
selectedLineIdx int
rangeStartLineIdx int
// If a range is sticky, it means we expand the range when we move up or down.
// Otherwise, we cancel the range when we move up or down.
rangeIsSticky bool
diff string
patch *patch.Patch
selectMode selectMode
// Array of indices of the wrapped lines indexed by a patch line index
viewLineIndices []int
// Array of indices of the original patch lines indexed by a wrapped view line index
patchLineIndices []int
// whether the user has switched to hunk mode manually; if hunk mode is on
// but this is false, then hunk mode was enabled because the config makes it
// on by default.
// this makes a difference for whether we want to escape out of hunk mode
userEnabledHunkMode bool
}
// these represent what select mode we're in
type selectMode int
const (
LINE selectMode = iota
RANGE
HUNK
)
func NewState(diff string, selectedLineIdx int, view *gocui.View, oldState *State, useHunkModeByDefault bool) *State {
if oldState != nil && diff == oldState.diff && selectedLineIdx == -1 {
// if we're here then we can return the old state. If selectedLineIdx was not -1
// then that would mean we were trying to click and potentially drag a range, which
// is why in that case we continue below
return oldState
}
patch := patch.Parse(diff)
if !patch.ContainsChanges() {
return nil
}
viewLineIndices, patchLineIndices := wrapPatchLines(diff, view)
rangeStartLineIdx := 0
if oldState != nil {
rangeStartLineIdx = oldState.rangeStartLineIdx
}
selectMode := LINE
if useHunkModeByDefault && !patch.IsSingleHunkForWholeFile() {
selectMode = HUNK
}
userEnabledHunkMode := false
if oldState != nil {
userEnabledHunkMode = oldState.userEnabledHunkMode
}
// if we have clicked from the outside to focus the main view we'll pass in a non-negative line index so that we can instantly select that line
if selectedLineIdx >= 0 {
// Clamp to the number of wrapped view lines; index might be out of
// bounds if a custom pager is being used which produces more lines
selectedLineIdx = min(selectedLineIdx, len(viewLineIndices)-1)
selectMode = RANGE
rangeStartLineIdx = selectedLineIdx
} else if oldState != nil {
// if we previously had a selectMode of RANGE, we want that to now be line again (or hunk, if that's the default)
if oldState.selectMode != RANGE {
selectMode = oldState.selectMode
}
selectedLineIdx = viewLineIndices[patch.GetNextChangeIdx(oldState.patchLineIndices[oldState.selectedLineIdx])]
} else {
selectedLineIdx = viewLineIndices[patch.GetNextChangeIdx(0)]
}
return &State{
patch: patch,
selectedLineIdx: selectedLineIdx,
selectMode: selectMode,
rangeStartLineIdx: rangeStartLineIdx,
rangeIsSticky: false,
diff: diff,
viewLineIndices: viewLineIndices,
patchLineIndices: patchLineIndices,
userEnabledHunkMode: userEnabledHunkMode,
}
}
func (s *State) OnViewWidthChanged(view *gocui.View) {
if !view.Wrap {
return
}
selectedPatchLineIdx := s.patchLineIndices[s.selectedLineIdx]
var rangeStartPatchLineIdx int
if s.selectMode == RANGE {
rangeStartPatchLineIdx = s.patchLineIndices[s.rangeStartLineIdx]
}
s.viewLineIndices, s.patchLineIndices = wrapPatchLines(s.diff, view)
s.selectedLineIdx = s.viewLineIndices[selectedPatchLineIdx]
if s.selectMode == RANGE {
s.rangeStartLineIdx = s.viewLineIndices[rangeStartPatchLineIdx]
}
}
func (s *State) GetSelectedPatchLineIdx() int {
return s.patchLineIndices[s.selectedLineIdx]
}
func (s *State) GetSelectedViewLineIdx() int {
return s.selectedLineIdx
}
func (s *State) GetDiff() string {
return s.diff
}
func (s *State) ToggleSelectHunk() {
if s.selectMode == HUNK {
s.selectMode = LINE
} else {
s.selectMode = HUNK
s.userEnabledHunkMode = true
// If we are not currently on a change line, select the next one (or the
// previous one if there is no next one):
s.selectedLineIdx = s.viewLineIndices[s.patch.GetNextChangeIdx(
s.patchLineIndices[s.selectedLineIdx])]
}
}
func (s *State) ToggleStickySelectRange() {
s.ToggleSelectRange(true)
}
func (s *State) ToggleSelectRange(sticky bool) {
if s.SelectingRange() {
s.selectMode = LINE
} else {
s.selectMode = RANGE
s.rangeStartLineIdx = s.selectedLineIdx
s.rangeIsSticky = sticky
}
}
func (s *State) SetRangeIsSticky(value bool) {
s.rangeIsSticky = value
}
func (s *State) SelectingHunk() bool {
return s.selectMode == HUNK
}
func (s *State) SelectingHunkEnabledByUser() bool {
return s.selectMode == HUNK && s.userEnabledHunkMode
}
func (s *State) SelectingRange() bool {
return s.selectMode == RANGE && (s.rangeIsSticky || s.rangeStartLineIdx != s.selectedLineIdx)
}
func (s *State) SelectingLine() bool {
return s.selectMode == LINE
}
func (s *State) SetLineSelectMode() {
s.selectMode = LINE
}
func (s *State) DismissHunkSelectMode() {
if s.SelectingHunk() {
s.selectMode = LINE
}
}
// For when you move the cursor without holding shift (meaning if we're in
// a non-sticky range select, we'll cancel it)
func (s *State) SelectLine(newSelectedLineIdx int) {
if s.selectMode == RANGE && !s.rangeIsSticky {
s.selectMode = LINE
}
s.selectLineWithoutRangeCheck(newSelectedLineIdx)
}
func (s *State) clampLineIdx(lineIdx int) int {
return lo.Clamp(lineIdx, 0, len(s.patchLineIndices)-1)
}
// This just moves the cursor without caring about range select
func (s *State) selectLineWithoutRangeCheck(newSelectedLineIdx int) {
s.selectedLineIdx = s.clampLineIdx(newSelectedLineIdx)
}
func (s *State) SelectNewLineForRange(newSelectedLineIdx int) {
s.rangeStartLineIdx = s.clampLineIdx(newSelectedLineIdx)
s.selectMode = RANGE
s.selectLineWithoutRangeCheck(newSelectedLineIdx)
}
func (s *State) DragSelectLine(newSelectedLineIdx int) {
s.selectMode = RANGE
s.selectLineWithoutRangeCheck(newSelectedLineIdx)
}
func (s *State) CycleSelection(forward bool) {
if s.SelectingHunk() {
if forward {
s.SelectNextHunk()
} else {
s.SelectPreviousHunk()
}
} else {
s.CycleLine(forward)
}
}
func (s *State) SelectPreviousHunk() {
patchLines := s.patch.Lines()
patchLineIdx := s.patchLineIndices[s.selectedLineIdx]
nextNonChangeLine := patchLineIdx
for nextNonChangeLine >= 0 && patchLines[nextNonChangeLine].IsChange() {
nextNonChangeLine--
}
nextChangeLine := nextNonChangeLine
for nextChangeLine >= 0 && !patchLines[nextChangeLine].IsChange() {
nextChangeLine--
}
if nextChangeLine >= 0 {
// Now we found a previous hunk, but we're on its last line. Skip to the beginning.
for nextChangeLine > 0 && patchLines[nextChangeLine-1].IsChange() {
nextChangeLine--
}
s.selectedLineIdx = s.viewLineIndices[nextChangeLine]
}
}
func (s *State) SelectNextHunk() {
patchLines := s.patch.Lines()
patchLineIdx := s.patchLineIndices[s.selectedLineIdx]
nextNonChangeLine := patchLineIdx
for nextNonChangeLine < len(patchLines) && patchLines[nextNonChangeLine].IsChange() {
nextNonChangeLine++
}
nextChangeLine := nextNonChangeLine
for nextChangeLine < len(patchLines) && !patchLines[nextChangeLine].IsChange() {
nextChangeLine++
}
if nextChangeLine < len(patchLines) {
s.selectedLineIdx = s.viewLineIndices[nextChangeLine]
}
}
func (s *State) CycleLine(forward bool) {
change := 1
if !forward {
change = -1
}
s.SelectLine(s.selectedLineIdx + change)
}
// This is called when we use shift+arrow to expand the range (i.e. a non-sticky
// range)
func (s *State) CycleRange(forward bool) {
if !s.SelectingRange() {
s.ToggleSelectRange(false)
}
s.SetRangeIsSticky(false)
change := 1
if !forward {
change = -1
}
s.selectLineWithoutRangeCheck(s.selectedLineIdx + change)
}
// returns first and last patch line index of current hunk
func (s *State) CurrentHunkBounds() (int, int) {
hunkIdx := s.patch.HunkContainingLine(s.patchLineIndices[s.selectedLineIdx])
start := s.patch.HunkStartIdx(hunkIdx)
end := s.patch.HunkEndIdx(hunkIdx)
return start, end
}
func (s *State) selectionRangeForCurrentBlockOfChanges() (int, int) {
patchLines := s.patch.Lines()
patchLineIdx := s.patchLineIndices[s.selectedLineIdx]
patchStart := patchLineIdx
for patchStart > 0 && patchLines[patchStart-1].IsChange() {
patchStart--
}
patchEnd := patchLineIdx
for patchEnd < len(patchLines)-1 && patchLines[patchEnd+1].IsChange() {
patchEnd++
}
viewStart, viewEnd := s.viewLineIndices[patchStart], s.viewLineIndices[patchEnd]
// Increase viewEnd in case the last patch line is wrapped to more than one view line.
for viewEnd < len(s.patchLineIndices)-1 && s.patchLineIndices[viewEnd] == s.patchLineIndices[viewEnd+1] {
viewEnd++
}
return viewStart, viewEnd
}
func (s *State) SelectedViewRange() (int, int) {
switch s.selectMode {
case HUNK:
return s.selectionRangeForCurrentBlockOfChanges()
case RANGE:
if s.rangeStartLineIdx > s.selectedLineIdx {
return s.selectedLineIdx, s.rangeStartLineIdx
}
return s.rangeStartLineIdx, s.selectedLineIdx
case LINE:
return s.selectedLineIdx, s.selectedLineIdx
default:
// should never happen
return 0, 0
}
}
func (s *State) SelectedPatchRange() (int, int) {
start, end := s.SelectedViewRange()
return s.patchLineIndices[start], s.patchLineIndices[end]
}
// Returns the line indices of the selected patch range that are changes (i.e. additions or deletions)
func (s *State) LineIndicesOfAddedOrDeletedLinesInSelectedPatchRange() []int {
viewStart, viewEnd := s.SelectedViewRange()
patchStart, patchEnd := s.patchLineIndices[viewStart], s.patchLineIndices[viewEnd]
lines := s.patch.Lines()
indices := []int{}
for i := patchStart; i <= patchEnd; i++ {
if lines[i].IsChange() {
indices = append(indices, i)
}
}
return indices
}
func (s *State) CurrentLineNumber() int {
return s.patch.LineNumberOfLine(s.patchLineIndices[s.selectedLineIdx])
}
func (s *State) AdjustSelectedLineIdx(change int) {
s.DismissHunkSelectMode()
s.SelectLine(s.selectedLineIdx + change)
}
func (s *State) RenderForLineIndices(includedLineIndices []int) string {
includedLineIndicesSet := set.NewFromSlice(includedLineIndices)
return s.patch.FormatView(patch.FormatViewOpts{
IncLineIndices: includedLineIndicesSet,
})
}
func (s *State) PlainRenderSelected() string {
firstLineIdx, lastLineIdx := s.SelectedPatchRange()
return s.patch.FormatRangePlain(firstLineIdx, lastLineIdx)
}
func (s *State) SelectBottom() {
s.DismissHunkSelectMode()
s.SelectLine(len(s.patchLineIndices) - 1)
}
func (s *State) SelectTop() {
s.DismissHunkSelectMode()
s.SelectLine(0)
}
func (s *State) CalculateOrigin(currentOrigin int, bufferHeight int, numLines int) int {
firstLineIdx, lastLineIdx := s.SelectedViewRange()
return calculateOrigin(currentOrigin, bufferHeight, numLines, firstLineIdx, lastLineIdx, s.GetSelectedViewLineIdx(), s.selectMode)
}
func wrapPatchLines(diff string, view *gocui.View) ([]int, []int) {
_, viewLineIndices, patchLineIndices := utils.WrapViewLinesToWidth(
view.Wrap, view.Editable, strings.TrimSuffix(diff, "\n"), view.InnerWidth(), view.TabWidth)
return viewLineIndices, patchLineIndices
}
func (s *State) SelectNextStageableLineOfSameIncludedState(includedLines []int, included bool) {
_, lastLineIdx := s.SelectedPatchRange()
patchLineIdx, found := s.patch.GetNextChangeIdxOfSameIncludedState(lastLineIdx+1, includedLines, included)
if found {
s.SelectLine(s.viewLineIndices[patchLineIdx])
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/patch_exploring/focus.go | pkg/gui/patch_exploring/focus.go | package patch_exploring
func calculateOrigin(currentOrigin int, bufferHeight int, numLines int, firstLineIdx int, lastLineIdx int, selectedLineIdx int, mode selectMode) int {
needToSeeIdx, wantToSeeIdx := getNeedAndWantLineIdx(firstLineIdx, lastLineIdx, selectedLineIdx, mode)
return calculateNewOriginWithNeededAndWantedIdx(currentOrigin, bufferHeight, numLines, needToSeeIdx, wantToSeeIdx)
}
// we want to scroll our origin so that the index we need to see is in view
// and the other index we want to see (e.g. the other side of a line range)
// is as close to being in view as possible.
func calculateNewOriginWithNeededAndWantedIdx(currentOrigin int, bufferHeight int, numLines int, needToSeeIdx int, wantToSeeIdx int) int {
origin := currentOrigin
if needToSeeIdx < currentOrigin || needToSeeIdx >= currentOrigin+bufferHeight {
origin = max(min(needToSeeIdx-bufferHeight/2, numLines-bufferHeight), 0)
}
bottom := origin + bufferHeight
if wantToSeeIdx < origin {
requiredChange := origin - wantToSeeIdx
allowedChange := bottom - needToSeeIdx
return origin - min(requiredChange, allowedChange)
} else if wantToSeeIdx >= bottom {
requiredChange := wantToSeeIdx + 1 - bottom
allowedChange := needToSeeIdx - origin
return origin + min(requiredChange, allowedChange)
}
return origin
}
func getNeedAndWantLineIdx(firstLineIdx int, lastLineIdx int, selectedLineIdx int, mode selectMode) (int, int) {
switch mode {
case LINE:
return selectedLineIdx, selectedLineIdx
case RANGE:
if selectedLineIdx == firstLineIdx {
return firstLineIdx, lastLineIdx
}
return lastLineIdx, firstLineIdx
case HUNK:
return firstLineIdx, lastLineIdx
default:
// we should never land here
panic("unknown mode")
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/patch_exploring/focus_test.go | pkg/gui/patch_exploring/focus_test.go | package patch_exploring
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewOrigin(t *testing.T) {
type scenario struct {
name string
origin int
bufferHeight int
numLines int
firstLineIdx int
lastLineIdx int
selectedLineIdx int
selectMode selectMode
expected int
}
scenarios := []scenario{
{
name: "selection above scroll window, enough room to put it in the middle",
origin: 250,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 210,
lastLineIdx: 210,
selectedLineIdx: 210,
selectMode: LINE,
expected: 160,
},
{
name: "selection above scroll window, not enough room to put it in the middle",
origin: 50,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 10,
lastLineIdx: 10,
selectedLineIdx: 10,
selectMode: LINE,
expected: 0,
},
{
name: "selection below scroll window, enough room to put it in the middle",
origin: 0,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 150,
lastLineIdx: 150,
selectedLineIdx: 150,
selectMode: LINE,
expected: 100,
},
{
name: "selection below scroll window, not enough room to put it in the middle",
origin: 0,
bufferHeight: 100,
numLines: 200,
firstLineIdx: 199,
lastLineIdx: 199,
selectedLineIdx: 199,
selectMode: LINE,
expected: 100,
},
{
name: "selection within scroll window",
origin: 0,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 50,
lastLineIdx: 50,
selectedLineIdx: 50,
selectMode: LINE,
expected: 0,
},
{
name: "range ending below scroll window with selection at end of range",
origin: 0,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 40,
lastLineIdx: 150,
selectedLineIdx: 150,
selectMode: RANGE,
expected: 50,
},
{
name: "range ending below scroll window with selection at beginning of range",
origin: 0,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 40,
lastLineIdx: 150,
selectedLineIdx: 40,
selectMode: RANGE,
expected: 40,
},
{
name: "range starting above scroll window with selection at beginning of range",
origin: 50,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 40,
lastLineIdx: 150,
selectedLineIdx: 40,
selectMode: RANGE,
expected: 40,
},
{
name: "hunk extending beyond both bounds of scroll window",
origin: 50,
bufferHeight: 100,
numLines: 500,
firstLineIdx: 40,
lastLineIdx: 200,
selectedLineIdx: 70,
selectMode: HUNK,
expected: 40,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
assert.EqualValues(t, s.expected, calculateOrigin(s.origin, s.bufferHeight, s.numLines, s.firstLineIdx, s.lastLineIdx, s.selectedLineIdx, s.selectMode))
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/keybindings.go | pkg/gui/types/keybindings.go | package types
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/style"
)
type Key any // FIXME: find out how to get `gocui.Key | rune`
// Binding - a keybinding mapping a key and modifier to a handler. The keypress
// is only handled if the given view has focus, or handled globally if the view
// is ""
type Binding struct {
ViewName string
Handler func() error
Key Key
Modifier gocui.Modifier
Description string
// DescriptionFunc is used instead of Description if non-nil, and is useful for dynamic
// descriptions that change depending on context. Important: this must not be an expensive call.
// Note that you should still provide a generic, non-dynamic description in the Description field,
// as this is used in the cheatsheet.
DescriptionFunc func() string
// If defined, this is used in place of Description when showing the keybinding
// in the options view at the bottom left of the screen.
ShortDescription string
// ShortDescriptionFunc is used instead of ShortDescription if non-nil, and is useful for dynamic
// descriptions that change depending on context. Important: this must not be an expensive call.
ShortDescriptionFunc func() string
Alternative string
Tag string // e.g. 'navigation'. Used for grouping things in the cheatsheet
OpensMenu bool
// If true, the keybinding will appear at the bottom of the screen.
// Even if set to true, the keybinding will not be displayed if it is currently
// disabled. We could instead display it with a strikethrough, but there's
// limited realestate to show all the keybindings we want, so we're hiding it instead.
DisplayOnScreen bool
// if unset, the binding will be displayed in the default color. Only applies to the keybinding
// on-screen, not in the keybindings menu.
DisplayStyle *style.TextStyle
// to be displayed if the keybinding is highlighted from within a menu
Tooltip string
// Function to decide whether the command is enabled, and why. If this
// returns an empty string, it is; if it returns a non-empty string, it is
// disabled and we show the given text in an error message when trying to
// invoke it. When left nil, the command is always enabled. Note that this
// function must not do expensive calls.
GetDisabledReason func() *DisabledReason
}
func (b *Binding) IsDisabled() bool {
return b.GetDisabledReason != nil && b.GetDisabledReason() != nil
}
func (b *Binding) GetDescription() string {
if b.DescriptionFunc != nil {
return b.DescriptionFunc()
}
return b.Description
}
func (b *Binding) GetShortDescription() string {
if b.ShortDescriptionFunc != nil {
return b.ShortDescriptionFunc()
}
if b.ShortDescription != "" {
return b.ShortDescription
}
return b.GetDescription()
}
// A guard is a decorator which checks something before executing a handler
// and potentially early-exits if some precondition hasn't been met.
type Guard func(func() error) func() error
type KeybindingGuards struct {
OutsideFilterMode Guard
NoPopupPanel Guard
}
type ErrKeybindingNotHandled struct {
DisabledReason *DisabledReason
}
func (e ErrKeybindingNotHandled) Error() string {
return e.DisabledReason.Text
}
func (e ErrKeybindingNotHandled) Unwrap() error {
return gocui.ErrKeybindingNotHandled
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/modes.go | pkg/gui/types/modes.go | package types
import (
"github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking"
"github.com/jesseduffield/lazygit/pkg/gui/modes/diffing"
"github.com/jesseduffield/lazygit/pkg/gui/modes/filtering"
"github.com/jesseduffield/lazygit/pkg/gui/modes/marked_base_commit"
)
type Modes struct {
Filtering filtering.Filtering
CherryPicking *cherrypicking.CherryPicking
Diffing diffing.Diffing
MarkedBaseCommit marked_base_commit.MarkedBaseCommit
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/version_number_test.go | pkg/gui/types/version_number_test.go | package types
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseVersionNumber(t *testing.T) {
tests := []struct {
versionStr string
expected *VersionNumber
err error
}{
{
versionStr: "1.2.3",
expected: &VersionNumber{
Major: 1,
Minor: 2,
Patch: 3,
},
err: nil,
},
{
versionStr: "v1.2.3",
expected: &VersionNumber{
Major: 1,
Minor: 2,
Patch: 3,
},
err: nil,
},
{
versionStr: "12.34.56",
expected: &VersionNumber{
Major: 12,
Minor: 34,
Patch: 56,
},
err: nil,
},
{
versionStr: "1.2",
expected: &VersionNumber{
Major: 1,
Minor: 2,
Patch: 0,
},
err: nil,
},
{
versionStr: "1",
expected: nil,
err: errors.New("unexpected version format: 1"),
},
{
versionStr: "invalid",
expected: nil,
err: errors.New("unexpected version format: invalid"),
},
{
versionStr: "junk_before 1.2.3",
expected: nil,
err: errors.New("unexpected version format: junk_before 1.2.3"),
},
{
versionStr: "1.2.3 junk_after",
expected: nil,
err: errors.New("unexpected version format: 1.2.3 junk_after"),
},
}
for _, test := range tests {
t.Run(test.versionStr, func(t *testing.T) {
actual, err := ParseVersionNumber(test.versionStr)
assert.Equal(t, test.expected, actual)
assert.Equal(t, test.err, err)
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/common_commands.go | pkg/gui/types/common_commands.go | package types
type CheckoutRefOptions struct {
WaitingStatus string
EnvVars []string
OnRefNotFound func(ref string) error
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/refresh.go | pkg/gui/types/refresh.go | package types
// models/views that we can refresh
type RefreshableView int
const (
COMMITS RefreshableView = iota
REBASE_COMMITS
SUB_COMMITS
BRANCHES
FILES
STASH
REFLOG
TAGS
REMOTES
WORKTREES
STATUS
SUBMODULES
STAGING
PATCH_BUILDING
MERGE_CONFLICTS
COMMIT_FILES
// not actually a view. Will refactor this later
BISECT_INFO
)
type RefreshMode int
const (
SYNC RefreshMode = iota // wait until everything is done before returning
ASYNC // return immediately, allowing each independent thing to update itself
BLOCK_UI // wrap code in an update call to ensure UI updates all at once and keybindings aren't executed till complete
)
type RefreshOptions struct {
Then func()
Scope []RefreshableView // e.g. []RefreshableView{COMMITS, BRANCHES}. Leave empty to refresh everything
Mode RefreshMode // one of SYNC (default), ASYNC, and BLOCK_UI
// Normally a refresh of the branches tries to keep the same branch selected
// (by name); this is usually important in case the order of branches
// changes. Passing true for KeepBranchSelectionIndex suppresses this and
// keeps the selection index the same. Useful after checking out a detached
// head, and selecting index 0.
KeepBranchSelectionIndex bool
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/views.go | pkg/gui/types/views.go | package types
import "github.com/jesseduffield/gocui"
type Views struct {
Status *gocui.View
Submodules *gocui.View
Files *gocui.View
Branches *gocui.View
Remotes *gocui.View
Worktrees *gocui.View
Tags *gocui.View
RemoteBranches *gocui.View
ReflogCommits *gocui.View
Commits *gocui.View
Stash *gocui.View
Main *gocui.View
Secondary *gocui.View
Staging *gocui.View
StagingSecondary *gocui.View
PatchBuilding *gocui.View
PatchBuildingSecondary *gocui.View
MergeConflicts *gocui.View
Options *gocui.View
Confirmation *gocui.View
Prompt *gocui.View
Menu *gocui.View
CommitMessage *gocui.View
CommitDescription *gocui.View
CommitFiles *gocui.View
SubCommits *gocui.View
Information *gocui.View
AppStatus *gocui.View
Search *gocui.View
SearchPrefix *gocui.View
StatusSpacer1 *gocui.View
StatusSpacer2 *gocui.View
Limit *gocui.View
Suggestions *gocui.View
Tooltip *gocui.View
Extras *gocui.View
// for playing the easter egg snake game
Snake *gocui.View
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/suggestion.go | pkg/gui/types/suggestion.go | package types
type Suggestion struct {
// value is the thing that we're matching on and the thing that will be submitted if you select the suggestion
Value string
// label is what is actually displayed so it can e.g. contain color
Label string
}
// Conforming to the HasID interface, which is needed for list contexts
func (self *Suggestion) ID() string {
return self.Value
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/rendering.go | pkg/gui/types/rendering.go | package types
import (
"os/exec"
)
type MainContextPair struct {
Main Context
Secondary Context
}
func NewMainContextPair(main Context, secondary Context) MainContextPair {
return MainContextPair{Main: main, Secondary: secondary}
}
type MainViewPairs struct {
Normal MainContextPair
MergeConflicts MainContextPair
Staging MainContextPair
PatchBuilding MainContextPair
}
type ViewUpdateOpts struct {
Title string
SubTitle string
Task UpdateTask
}
type RefreshMainOpts struct {
Pair MainContextPair
Main *ViewUpdateOpts
Secondary *ViewUpdateOpts
}
type UpdateTask interface {
IsUpdateTask()
}
type RenderStringTask struct {
Str string
}
func (t *RenderStringTask) IsUpdateTask() {}
func NewRenderStringTask(str string) *RenderStringTask {
return &RenderStringTask{Str: str}
}
type RenderStringWithoutScrollTask struct {
Str string
}
func (t *RenderStringWithoutScrollTask) IsUpdateTask() {}
func NewRenderStringWithoutScrollTask(str string) *RenderStringWithoutScrollTask {
return &RenderStringWithoutScrollTask{Str: str}
}
type RenderStringWithScrollTask struct {
Str string
OriginX int
OriginY int
}
func (t *RenderStringWithScrollTask) IsUpdateTask() {}
func NewRenderStringWithScrollTask(str string, originX int, originY int) *RenderStringWithScrollTask {
return &RenderStringWithScrollTask{Str: str, OriginX: originX, OriginY: originY}
}
type RunCommandTask struct {
Cmd *exec.Cmd
Prefix string
}
func (t *RunCommandTask) IsUpdateTask() {}
func NewRunCommandTask(cmd *exec.Cmd) *RunCommandTask {
return &RunCommandTask{Cmd: cmd}
}
func NewRunCommandTaskWithPrefix(cmd *exec.Cmd, prefix string) *RunCommandTask {
return &RunCommandTask{Cmd: cmd, Prefix: prefix}
}
type RunPtyTask struct {
Cmd *exec.Cmd
Prefix string
}
func (t *RunPtyTask) IsUpdateTask() {}
func NewRunPtyTask(cmd *exec.Cmd) *RunPtyTask {
return &RunPtyTask{Cmd: cmd}
}
func NewRunPtyTaskWithPrefix(cmd *exec.Cmd, prefix string) *RunPtyTask {
return &RunPtyTask{Cmd: cmd, Prefix: prefix}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/context.go | pkg/gui/types/context.go | package types
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/patch_exploring"
"github.com/jesseduffield/lazygit/pkg/i18n"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sasha-s/go-deadlock"
)
type ContextKind int
const (
// this is your files, branches, commits, contexts etc. They're all on the left hand side
// and you can cycle through them.
SIDE_CONTEXT ContextKind = iota
// This is either the left or right 'main' contexts that appear to the right of the side contexts
MAIN_CONTEXT
// A persistent popup is one that has its own identity e.g. the commit message context.
// When you open a popup over it, we'll let you return to it upon pressing escape
PERSISTENT_POPUP
// A temporary popup is one that could be used for various things (e.g. a generic menu or confirmation popup).
// Because we reuse these contexts, they're temporary in that you can't return to them after you've switched from them
// to some other context, because the context you switched to might actually be the same context but rendering different content.
// We should really be able to spawn new contexts for menus/prompts so that we can actually return to old ones.
TEMPORARY_POPUP
// This contains the command log, underneath the main contexts.
EXTRAS_CONTEXT
// only used by the one global context, purely for the sake of defining keybindings globally
GLOBAL_CONTEXT
// a display context only renders a view. It has no keybindings associated and
// it cannot receive focus.
DISPLAY_CONTEXT
)
type ParentContexter interface {
SetParentContext(Context)
GetParentContext() Context
}
type NeedsRerenderOnWidthChangeLevel int
const (
// view doesn't render differently when its width changes
NEEDS_RERENDER_ON_WIDTH_CHANGE_NONE NeedsRerenderOnWidthChangeLevel = iota
// view renders differently when its width changes. An example is a view
// that truncates long lines to the view width, e.g. the branches view
NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_WIDTH_CHANGES
// view renders differently only when the screen mode changes
NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_SCREEN_MODE_CHANGES
)
type IBaseContext interface {
HasKeybindings
ParentContexter
GetKind() ContextKind
GetViewName() string
GetView() *gocui.View
GetViewTrait() IViewTrait
GetWindowName() string
SetWindowName(string)
GetKey() ContextKey
IsFocusable() bool
// if a context is transient, then it only appears via some keybinding on another
// context. Until we add support for having multiple of the same context, no two
// of the same transient context can appear at once meaning one might be 'stolen'
// from another window.
IsTransient() bool
// this tells us if the view's bounds are determined by its window or if they're
// determined independently.
HasControlledBounds() bool
// the total height of the content that the view is currently showing
TotalContentHeight() int
// to what extent the view needs to be rerendered when its width changes
NeedsRerenderOnWidthChange() NeedsRerenderOnWidthChangeLevel
// true if the view needs to be rerendered when its height changes
NeedsRerenderOnHeightChange() bool
// returns the desired title for the view upon activation. If there is no desired title (returns empty string), then
// no title will be set
Title() string
GetOptionsMap() map[string]string
AddKeybindingsFn(KeybindingsFn)
AddMouseKeybindingsFn(MouseKeybindingsFn)
ClearAllAttachedControllerFunctions()
// This is a bit of a hack at the moment: we currently only set an onclick function so that
// our list controller can come along and wrap it in a list-specific click handler.
// We'll need to think of a better way to do this.
AddOnClickFn(func() error)
// Likewise for the focused main view: we need this to communicate between a
// side panel controller and the focused main view controller.
AddOnClickFocusedMainViewFn(func(mainViewName string, clickedLineIdx int) error)
AddOnRenderToMainFn(func())
AddOnFocusFn(func(OnFocusOpts))
AddOnFocusLostFn(func(OnFocusLostOpts))
}
type Context interface {
IBaseContext
HandleFocus(opts OnFocusOpts)
HandleFocusLost(opts OnFocusLostOpts)
FocusLine(scrollIntoView bool)
HandleRender()
HandleRenderToMain()
}
type ISearchHistoryContext interface {
Context
GetSearchHistory() *utils.HistoryBuffer[string]
}
type IFilterableContext interface {
Context
IListPanelState
ISearchHistoryContext
SetFilter(string, bool)
GetFilter() string
ClearFilter()
ReApplyFilter(bool)
IsFiltering() bool
IsFilterableContext()
FilterPrefix(tr *i18n.TranslationSet) string
}
type ISearchableContext interface {
Context
ISearchHistoryContext
// These are all implemented by SearchTrait
SetSearchString(string)
GetSearchString() string
ClearSearchString()
IsSearching() bool
IsSearchableContext()
RenderSearchStatus(int, int)
// This must be implemented by each concrete context. Return nil if not searching the model.
ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition
}
type DiffableContext interface {
Context
// Returns the current diff terminals of the currently selected item.
// in the case of a branch it returns both the branch and it's upstream name,
// which becomes an option when you bring up the diff menu, but when you're just
// flicking through branches it will be using the local branch name.
GetDiffTerminals() []string
// Returns the ref that should be used for creating a diff of what's
// currently shown in the main view against the working directory, in order
// to adjust line numbers in the diff to match the current state of the
// shown file. For example, if the main view shows a range diff of commits,
// we need to pass the first commit of the range. This is used by
// DiffHelper.AdjustLineNumber.
RefForAdjustingLineNumberInDiff() string
}
type IListContext interface {
Context
GetSelectedItemId() string
GetSelectedItemIds() ([]string, int, int)
IsItemVisible(item HasUrn) bool
GetList() IList
ViewIndexToModelIndex(int) int
ModelIndexToViewIndex(int) int
IsListContext() // used for type switch
RangeSelectEnabled() bool
RenderOnlyVisibleLines() bool
SetNeedRerenderVisibleLines()
IndexForGotoBottom() int
}
type IPatchExplorerContext interface {
Context
GetState() *patch_exploring.State
SetState(*patch_exploring.State)
GetIncludedLineIndices() []int
RenderAndFocus()
Render()
GetContentToRender() string
NavigateTo(selectedLineIdx int)
GetMutex() *deadlock.Mutex
IsPatchExplorerContext() // used for type switch
}
type IViewTrait interface {
FocusPoint(yIdx int, scrollIntoView bool)
SetRangeSelectStart(yIdx int)
CancelRangeSelect()
SetViewPortContent(content string)
SetViewPortContentAndClearEverythingElse(lineCount int, content string)
SetContent(content string)
SetFooter(value string)
SetOriginX(value int)
ViewPortYBounds() (int, int)
ScrollLeft()
ScrollRight()
ScrollUp(value int)
ScrollDown(value int)
PageDelta() int
SelectedLineIdx() int
SetHighlight(bool)
}
type OnFocusOpts struct {
ClickedWindowName string
ClickedViewLineIdx int
ScrollSelectionIntoView bool
}
type OnFocusLostOpts struct {
NewContextKey ContextKey
}
type ContextKey string
type KeybindingsOpts struct {
GetKey func(key string) Key
Config config.KeybindingConfig
Guards KeybindingGuards
}
type (
KeybindingsFn func(opts KeybindingsOpts) []*Binding
MouseKeybindingsFn func(opts KeybindingsOpts) []*gocui.ViewMouseBinding
)
type HasKeybindings interface {
GetKeybindings(opts KeybindingsOpts) []*Binding
GetMouseKeybindings(opts KeybindingsOpts) []*gocui.ViewMouseBinding
GetOnClick() func() error
GetOnClickFocusedMainView() func(mainViewName string, clickedLineIdx int) error
}
type IController interface {
HasKeybindings
Context() Context
GetOnRenderToMain() func()
GetOnFocus() func(OnFocusOpts)
GetOnFocusLost() func(OnFocusLostOpts)
}
type IList interface {
IListCursor
Len() int
GetItem(index int) HasUrn
}
type IListCursor interface {
GetSelectedLineIdx() int
SetSelectedLineIdx(value int)
SetSelection(value int)
MoveSelectedLine(delta int)
ClampSelection()
CancelRangeSelect()
GetRangeStartIdx() (int, bool)
GetSelectionRange() (int, int)
IsSelectingRange() bool
AreMultipleItemsSelected() bool
ToggleStickyRange()
ExpandNonStickyRange(int)
}
type IListPanelState interface {
SetSelectedLineIdx(int)
SetSelection(int)
GetSelectedLineIdx() int
}
type ListItem interface {
// ID is a hash when the item is a commit, a filename when the item is a file, 'stash@{4}' when it's a stash entry, 'my_branch' when it's a branch
ID() string
// Description is something we would show in a message e.g. '123as14: push blah' for a commit
Description() string
}
type IContextMgr interface {
Push(context Context, opts OnFocusOpts)
Pop()
Replace(context Context)
Activate(context Context, opts OnFocusOpts)
Current() Context
CurrentStatic() Context
CurrentSide() Context
CurrentPopup() []Context
NextInStack(context Context) Context
IsCurrent(c Context) bool
IsCurrentOrParent(c Context) bool
ForEach(func(Context))
AllList() []IListContext
AllFilterable() []IFilterableContext
AllSearchable() []ISearchableContext
AllPatchExplorer() []IPatchExplorerContext
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/version_number.go | pkg/gui/types/version_number.go | package types
import (
"errors"
"regexp"
"strconv"
)
type VersionNumber struct {
Major, Minor, Patch int
}
func (v *VersionNumber) IsOlderThan(otherVersion *VersionNumber) bool {
this := v.Major*1000*1000 + v.Minor*1000 + v.Patch
other := otherVersion.Major*1000*1000 + otherVersion.Minor*1000 + otherVersion.Patch
return this < other
}
func ParseVersionNumber(versionStr string) (*VersionNumber, error) {
re := regexp.MustCompile(`^v?(\d+)\.(\d+)(?:\.(\d+))?$`)
matches := re.FindStringSubmatch(versionStr)
if matches == nil {
return nil, errors.New("unexpected version format: " + versionStr)
}
v := &VersionNumber{}
var err error
if v.Major, err = strconv.Atoi(matches[1]); err != nil {
return nil, err
}
if v.Minor, err = strconv.Atoi(matches[2]); err != nil {
return nil, err
}
if len(matches[3]) > 0 {
if v.Patch, err = strconv.Atoi(matches[3]); err != nil {
return nil, err
}
}
return v, nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/search_state.go | pkg/gui/types/search_state.go | package types
type SearchType int
const (
SearchTypeNone SearchType = iota
// searching is where matches are highlighted but the content is not filtered down
SearchTypeSearch
// filter is where the list is filtered down to only matches
SearchTypeFilter
)
// TODO: could we remove this entirely?
type SearchState struct {
Context Context
PrevSearchIndex int
}
func NewSearchState() *SearchState {
return &SearchState{PrevSearchIndex: -1}
}
func (self *SearchState) SearchType() SearchType {
switch self.Context.(type) {
case IFilterableContext:
return SearchTypeFilter
case ISearchableContext:
return SearchTypeSearch
default:
return SearchTypeNone
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/ref_range.go | pkg/gui/types/ref_range.go | package types
import "github.com/jesseduffield/lazygit/pkg/commands/models"
type RefRange struct {
From models.Ref
To models.Ref
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/types/common.go | pkg/gui/types/common.go | package types
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/tasks"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sasha-s/go-deadlock"
"gopkg.in/ozeidan/fuzzy-patricia.v3/patricia"
)
type HelperCommon struct {
*ContextCommon
}
type ContextCommon struct {
*common.Common
IGuiCommon
}
type IGuiCommon interface {
IPopupHandler
LogAction(action string)
LogCommand(cmdStr string, isCommandLine bool)
// we call this when we want to refetch some models and render the result. Internally calls PostRefreshUpdate
Refresh(RefreshOptions)
// we call this when we've changed something in the view model but not the actual model,
// e.g. expanding or collapsing a folder in a file view. Calling 'Refresh' in this
// case would be overkill, although refresh will internally call 'PostRefreshUpdate'
PostRefreshUpdate(Context)
// renders string to a view without resetting its origin
SetViewContent(view *gocui.View, content string)
// resets cursor and origin of view. Often used before calling SetViewContent
ResetViewOrigin(view *gocui.View)
// this just re-renders the screen
Render()
// allows rendering to main views (i.e. the ones to the right of the side panel)
// in such a way that avoids concurrency issues when there are slow commands
// to display the output of
RenderToMainViews(opts RefreshMainOpts)
// used purely for the sake of RenderToMainViews to provide the pair of main views we want to render to
MainViewPairs() MainViewPairs
// return the view buffer manager for the given view, or nil if it doesn't have one
GetViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager
// returns true if command completed successfully
RunSubprocess(cmdObj *oscommands.CmdObj) (bool, error)
RunSubprocessAndRefresh(*oscommands.CmdObj) error
Suspend() error
Resume() error
Context() IContextMgr
ContextForKey(key ContextKey) Context
GetConfig() config.AppConfigurer
GetAppState() *config.AppState
SaveAppState() error
SaveAppStateAndLogError()
// Runs the given function on the UI thread (this is for things like showing a popup asking a user for input).
// Only necessary to call if you're not already on the UI thread i.e. you're inside a goroutine.
// All controller handlers are executed on the UI thread.
OnUIThread(f func() error)
// Runs a function in a goroutine. Use this whenever you want to run a goroutine and keep track of the fact
// that lazygit is still busy. See docs/dev/Busy.md
OnWorker(f func(gocui.Task) error)
// Function to call at the end of our 'layout' function which renders views
// For example, you may want a view's line to be focused only after that view is
// resized, if in accordion mode.
AfterLayout(f func() error)
// Wraps a function, attaching the given operation to the given item while
// the function is executing, and also causes the given context to be
// redrawn periodically. This allows the operation to be visualized with a
// spinning loader animation (e.g. when a branch is being pushed).
WithInlineStatus(item HasUrn, operation ItemOperation, contextKey ContextKey, f func(gocui.Task) error) error
// returns the gocui Gui struct. There is a good chance you don't actually want to use
// this struct and instead want to use another method above
GocuiGui() *gocui.Gui
Views() Views
Git() *commands.GitCommand
OS() *oscommands.OSCommand
Model() *Model
Modes() *Modes
Mutexes() *Mutexes
State() IStateAccessor
KeybindingsOpts() KeybindingsOpts
CallKeybindingHandler(binding *Binding) error
ResetKeybindings() error
// hopefully we can remove this once we've moved all our keybinding stuff out of the gui god struct.
GetInitialKeybindingsWithCustomCommands() ([]*Binding, []*gocui.ViewMouseBinding)
// Returns true if we're running an integration test
RunningIntegrationTest() bool
// Returns true if we're in a demo recording/playback
InDemo() bool
}
type IModeMgr interface {
IsAnyModeActive() bool
}
type IPopupHandler interface {
// The global error handler for gocui. Not to be used by application code.
ErrorHandler(err error) error
// Shows a notification popup with the given title and message to the user.
//
// This is a convenience wrapper around Confirm(), thus the popup can be closed using both 'Enter' and 'ESC'.
Alert(title string, message string)
// Shows a popup asking the user for confirmation.
Confirm(opts ConfirmOpts)
// Shows a popup asking the user for confirmation if condition is true; otherwise, the HandleConfirm function is called directly.
ConfirmIf(condition bool, opts ConfirmOpts) error
// Shows a popup prompting the user for input.
Prompt(opts PromptOpts)
WithWaitingStatus(message string, f func(gocui.Task) error) error
WithWaitingStatusSync(message string, f func() error) error
Menu(opts CreateMenuOptions) error
Toast(message string)
ErrorToast(message string)
SetToastFunc(func(string, ToastKind))
GetPromptInput() string
}
type ToastKind int
const (
ToastKindStatus ToastKind = iota
ToastKindError
)
type CreateMenuOptions struct {
Title string
Prompt string // a message that will be displayed above the menu options
Items []*MenuItem
HideCancel bool
ColumnAlignment []utils.Alignment
AllowFilteringKeybindings bool
KeepConflictingKeybindings bool // if true, the keybindings that match essential bindings such as confirm or return will not be removed from menu items
}
type CreatePopupPanelOpts struct {
HasLoader bool
Editable bool
Title string
Prompt string
HandleConfirm func() error
HandleConfirmPrompt func(string) error
HandleClose func() error
HandleDeleteSuggestion func(int) error
FindSuggestionsFunc func(string) []*Suggestion
Mask bool
AllowEditSuggestion bool
AllowEmptyInput bool
PreserveWhitespace bool
}
type ConfirmOpts struct {
Title string
Prompt string
HandleConfirm func() error
HandleClose func() error
FindSuggestionsFunc func(string) []*Suggestion
Editable bool
Mask bool
}
type PromptOpts struct {
Title string
InitialContent string
FindSuggestionsFunc func(string) []*Suggestion
HandleConfirm func(string) error
AllowEditSuggestion bool
AllowEmptyInput bool
PreserveWhitespace bool
// CAPTURE THIS
HandleClose func() error
HandleDeleteSuggestion func(int) error
Mask bool
}
type MenuSection struct {
Title string
Column int // The column that this section title should be aligned with
}
type DisabledReason struct {
Text string
// When trying to invoke a disabled key binding or menu item, we normally
// show the disabled reason as a toast; setting this to true shows it as an
// error panel instead. This is useful if the text is very long, or if it is
// important enough to show it more prominently, or both.
ShowErrorInPanel bool
// If true, the keybinding dispatch mechanism will continue to look for
// other handlers for the keypress.
AllowFurtherDispatching bool
}
type MenuWidget int
const (
MenuWidgetNone MenuWidget = iota
MenuWidgetRadioButtonSelected
MenuWidgetRadioButtonUnselected
MenuWidgetCheckboxSelected
MenuWidgetCheckboxUnselected
)
func MakeMenuRadioButton(value bool) MenuWidget {
if value {
return MenuWidgetRadioButtonSelected
}
return MenuWidgetRadioButtonUnselected
}
func MakeMenuCheckBox(value bool) MenuWidget {
if value {
return MenuWidgetCheckboxSelected
}
return MenuWidgetCheckboxUnselected
}
type MenuItem struct {
Label string
// alternative to Label. Allows specifying columns which will be auto-aligned
LabelColumns []string
OnPress func() error
// Only applies when Label is used
OpensMenu bool
// If Key is defined it allows the user to press the key to invoke the menu
// item, as opposed to having to navigate to it
Key Key
// A widget to show in front of the menu item. Supported widget types are
// checkboxes and radio buttons,
// This only handles the rendering of the widget; the behavior needs to be
// provided by the client.
Widget MenuWidget
// The tooltip will be displayed upon highlighting the menu item
Tooltip string
// If non-nil, show this in a tooltip, style the menu item as disabled,
// and refuse to invoke the command
DisabledReason *DisabledReason
// Can be used to group menu items into sections with headers. MenuItems
// with the same Section should be contiguous, and will automatically get a
// section header. If nil, the item is not part of a section.
// Note that pointer comparison is used to determine whether two menu items
// belong to the same section, so make sure all your items in a given
// section point to the same MenuSection instance.
Section *MenuSection
}
// Defining this for the sake of conforming to the HasID interface, which is used
// in list contexts.
func (self *MenuItem) ID() string {
return self.Label
}
type Model struct {
CommitFiles []*models.CommitFile
Files []*models.File
Submodules []*models.SubmoduleConfig
Branches []*models.Branch
Commits []*models.Commit
StashEntries []*models.StashEntry
SubCommits []*models.Commit
Remotes []*models.Remote
Worktrees []*models.Worktree
// FilteredReflogCommits are the ones that appear in the reflog panel.
// When in filtering mode we only include the ones that match the given path
FilteredReflogCommits []*models.Commit
// ReflogCommits are the ones used by the branches panel to obtain recency values,
// and for the undo functionality.
// If we're not in filtering mode, CommitFiles and FilteredReflogCommits will be
// one and the same
ReflogCommits []*models.Commit
BisectInfo *git_commands.BisectInfo
WorkingTreeStateAtLastCommitRefresh models.WorkingTreeState
RemoteBranches []*models.RemoteBranch
Tags []*models.Tag
// Name of the currently checked out branch. This will be set even when
// we're on a detached head because we're rebasing or bisecting.
CheckedOutBranch string
MainBranches *git_commands.MainBranches
// for displaying suggestions while typing in a file name
FilesTrie *patricia.Trie
Authors map[string]*models.Author
HashPool *utils.StringPool
}
type Mutexes struct {
RefreshingFilesMutex deadlock.Mutex
RefreshingBranchesMutex deadlock.Mutex
RefreshingStatusMutex deadlock.Mutex
LocalCommitsMutex deadlock.Mutex
SubCommitsMutex deadlock.Mutex
AuthorsMutex deadlock.Mutex
SubprocessMutex deadlock.Mutex
PopupMutex deadlock.Mutex
PtyMutex deadlock.Mutex
}
// A long-running operation associated with an item. For example, we'll show
// that a branch is being pushed from so that there's visual feedback about
// what's happening and so that you can see multiple branches' concurrent
// operations
type ItemOperation int
const (
ItemOperationNone ItemOperation = iota
ItemOperationPushing
ItemOperationPulling
ItemOperationFastForwarding
ItemOperationDeleting
ItemOperationFetching
ItemOperationCheckingOut
)
type HasUrn interface {
URN() string
}
type IStateAccessor interface {
GetRepoPathStack() *utils.StringStack
GetRepoState() IRepoStateAccessor
GetPagerConfig() *config.PagerConfig
// tells us whether we're currently updating lazygit
GetUpdating() bool
SetUpdating(bool)
SetIsRefreshingFiles(bool)
GetIsRefreshingFiles() bool
GetShowExtrasWindow() bool
SetShowExtrasWindow(bool)
GetRetainOriginalDir() bool
SetRetainOriginalDir(bool)
GetItemOperation(item HasUrn) ItemOperation
SetItemOperation(item HasUrn, operation ItemOperation)
ClearItemOperation(item HasUrn)
}
type IRepoStateAccessor interface {
GetViewsSetup() bool
GetWindowViewNameMap() *utils.ThreadSafeMap[string, string]
GetStartupStage() StartupStage
SetStartupStage(stage StartupStage)
GetCurrentPopupOpts() *CreatePopupPanelOpts
SetCurrentPopupOpts(*CreatePopupPanelOpts)
GetScreenMode() ScreenMode
SetScreenMode(ScreenMode)
InSearchPrompt() bool
GetSearchState() *SearchState
SetSplitMainPanel(bool)
GetSplitMainPanel() bool
}
// startup stages so we don't need to load everything at once
type StartupStage int
const (
INITIAL StartupStage = iota
COMPLETE
)
// screen sizing determines how much space your selected window takes up (window
// as in panel, not your terminal's window). Sometimes you want a bit more space
// to see the contents of a panel, and this keeps track of how much maximisation
// you've set
type ScreenMode int
const (
SCREEN_NORMAL ScreenMode = iota
SCREEN_HALF
SCREEN_FULL
)
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/modes/filtering/filtering.go | pkg/gui/modes/filtering/filtering.go | package filtering
type Filtering struct {
path string // the filename that gets passed to git log
author string // the author that gets passed to git log
selectedCommitHash string // the commit that was selected before we entered filtering mode
}
func New(path string, author string) Filtering {
return Filtering{path: path, author: author}
}
func (m *Filtering) Active() bool {
return m.path != "" || m.author != ""
}
func (m *Filtering) Reset() {
m.path = ""
m.author = ""
}
func (m *Filtering) SetPath(path string) {
m.path = path
}
func (m *Filtering) GetPath() string {
return m.path
}
func (m *Filtering) SetAuthor(author string) {
m.author = author
}
func (m *Filtering) GetAuthor() string {
return m.author
}
func (m *Filtering) SetSelectedCommitHash(hash string) {
m.selectedCommitHash = hash
}
func (m *Filtering) GetSelectedCommitHash() string {
return m.selectedCommitHash
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/modes/diffing/diffing.go | pkg/gui/modes/diffing/diffing.go | package diffing
// if ref is blank we're not diffing anything
type Diffing struct {
Ref string
Reverse bool
}
func New() Diffing {
return Diffing{}
}
func (self *Diffing) Active() bool {
return self.Ref != ""
}
// GetFromAndReverseArgsForDiff tells us the from and reverse args to be used in a diff command.
// If we're not in diff mode we'll end up with the equivalent of a `git show` i.e `git diff blah^..blah`.
func (self *Diffing) GetFromAndReverseArgsForDiff(from string) (string, bool) {
reverse := false
if self.Active() {
reverse = self.Reverse
from = self.Ref
}
return from, reverse
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/modes/marked_base_commit/marked_base_commit.go | pkg/gui/modes/marked_base_commit/marked_base_commit.go | package marked_base_commit
type MarkedBaseCommit struct {
hash string // the hash of the commit used as a rebase base commit; empty string when unset
}
func New() MarkedBaseCommit {
return MarkedBaseCommit{}
}
func (m *MarkedBaseCommit) Active() bool {
return m.hash != ""
}
func (m *MarkedBaseCommit) Reset() {
m.hash = ""
}
func (m *MarkedBaseCommit) SetHash(hash string) {
m.hash = hash
}
func (m *MarkedBaseCommit) GetHash() string {
return m.hash
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/modes/cherrypicking/cherry_picking.go | pkg/gui/modes/cherrypicking/cherry_picking.go | package cherrypicking
import (
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/samber/lo"
)
type CherryPicking struct {
CherryPickedCommits []*models.Commit
// we only allow cherry picking from one context at a time, so you can't copy a commit from
// the local commits context and then also copy a commit in the reflog context
ContextKey string
// keep track of whether the currently copied commits have been pasted already. If so, we hide
// the mode and the blue display of the commits, but we still allow pasting them again.
DidPaste bool
}
func New() *CherryPicking {
return &CherryPicking{
CherryPickedCommits: make([]*models.Commit, 0),
ContextKey: "",
}
}
func (self *CherryPicking) Active() bool {
return self.CanPaste() && !self.DidPaste
}
func (self *CherryPicking) CanPaste() bool {
return len(self.CherryPickedCommits) > 0
}
func (self *CherryPicking) SelectedHashSet() *set.Set[string] {
if self.DidPaste {
return set.New[string]()
}
hashes := lo.Map(self.CherryPickedCommits, func(commit *models.Commit, _ int) string {
return commit.Hash()
})
return set.NewFromSlice(hashes)
}
func (self *CherryPicking) Add(selectedCommit *models.Commit, commitsList []*models.Commit) {
commitSet := self.SelectedHashSet()
commitSet.Add(selectedCommit.Hash())
self.update(commitSet, commitsList)
}
func (self *CherryPicking) Remove(selectedCommit *models.Commit, commitsList []*models.Commit) {
commitSet := self.SelectedHashSet()
commitSet.Remove(selectedCommit.Hash())
self.update(commitSet, commitsList)
}
func (self *CherryPicking) update(selectedHashSet *set.Set[string], commitsList []*models.Commit) {
self.CherryPickedCommits = lo.Filter(commitsList, func(commit *models.Commit, _ int) bool {
return selectedHashSet.Includes(commit.Hash())
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/keybindings/keybindings.go | pkg/gui/keybindings/keybindings.go | package keybindings
import (
"fmt"
"log"
"strings"
"unicode/utf8"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/constants"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
func Label(name string) string {
return LabelFromKey(GetKey(name))
}
func LabelFromKey(key types.Key) string {
if key == nil {
return ""
}
keyInt := 0
switch key := key.(type) {
case rune:
keyInt = int(key)
case gocui.Key:
value, ok := config.LabelByKey[key]
if ok {
return value
}
keyInt = int(key)
}
return fmt.Sprintf("%c", keyInt)
}
func GetKey(key string) types.Key {
runeCount := utf8.RuneCountInString(key)
if key == "<disabled>" {
return nil
} else if runeCount > 1 {
binding, ok := config.KeyByLabel[strings.ToLower(key)]
if !ok {
log.Fatalf("Unrecognized key %s for keybinding. For permitted values see %s", strings.ToLower(key), constants.Links.Docs.CustomKeybindings)
}
return binding
} else if runeCount == 1 {
return []rune(key)[0]
}
return nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/status/status_manager.go | pkg/gui/status/status_manager.go | package status
import (
"time"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
"github.com/sasha-s/go-deadlock"
)
// StatusManager's job is to handle queuing of loading states and toast notifications
// that you see at the bottom left of the screen.
type StatusManager struct {
statuses []appStatus
nextId int
mutex deadlock.Mutex
}
// Can be used to manipulate a waiting status while it is running (e.g. pause
// and resume it)
type WaitingStatusHandle struct {
statusManager *StatusManager
message string
renderFunc func()
id int
}
func (self *WaitingStatusHandle) Show() {
self.id = self.statusManager.addStatus(self.message, "waiting", types.ToastKindStatus)
self.renderFunc()
}
func (self *WaitingStatusHandle) Hide() {
self.statusManager.removeStatus(self.id)
}
type appStatus struct {
message string
statusType string
color gocui.Attribute
id int
}
func NewStatusManager() *StatusManager {
return &StatusManager{}
}
func (self *StatusManager) WithWaitingStatus(message string, renderFunc func(), f func(*WaitingStatusHandle) error) error {
handle := &WaitingStatusHandle{statusManager: self, message: message, renderFunc: renderFunc, id: -1}
handle.Show()
defer handle.Hide()
return f(handle)
}
func (self *StatusManager) AddToastStatus(message string, kind types.ToastKind) int {
id := self.addStatus(message, "toast", kind)
go func() {
delay := lo.Ternary(kind == types.ToastKindError, time.Second*4, time.Second*2)
time.Sleep(delay)
self.removeStatus(id)
}()
return id
}
func (self *StatusManager) GetStatusString(userConfig *config.UserConfig) (string, gocui.Attribute) {
if len(self.statuses) == 0 {
return "", gocui.ColorDefault
}
topStatus := self.statuses[0]
if topStatus.statusType == "waiting" {
return topStatus.message + " " + presentation.Loader(time.Now(), userConfig.Gui.Spinner), topStatus.color
}
return topStatus.message, topStatus.color
}
func (self *StatusManager) HasStatus() bool {
return len(self.statuses) > 0
}
func (self *StatusManager) addStatus(message string, statusType string, kind types.ToastKind) int {
self.mutex.Lock()
defer self.mutex.Unlock()
self.nextId++
id := self.nextId
color := gocui.ColorCyan
if kind == types.ToastKindError {
color = gocui.ColorRed
}
newStatus := appStatus{
message: message,
statusType: statusType,
color: color,
id: id,
}
self.statuses = append([]appStatus{newStatus}, self.statuses...)
return id
}
func (self *StatusManager) removeStatus(id int) {
self.mutex.Lock()
defer self.mutex.Unlock()
self.statuses = lo.Filter(self.statuses, func(status appStatus, _ int) bool {
return status.id != id
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/history_trait.go | pkg/gui/context/history_trait.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/utils"
)
// Maintains a list of strings that have previously been searched/filtered for
type SearchHistory struct {
history *utils.HistoryBuffer[string]
}
func NewSearchHistory() *SearchHistory {
return &SearchHistory{
history: utils.NewHistoryBuffer[string](1000),
}
}
func (self *SearchHistory) GetSearchHistory() *utils.HistoryBuffer[string] {
return self.history
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/main_context.go | pkg/gui/context/main_context.go | package context
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type MainContext struct {
*SimpleContext
*SearchTrait
}
var _ types.ISearchableContext = (*MainContext)(nil)
func NewMainContext(
view *gocui.View,
windowName string,
key types.ContextKey,
c *ContextCommon,
) *MainContext {
ctx := &MainContext{
SimpleContext: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.MAIN_CONTEXT,
View: view,
WindowName: windowName,
Key: key,
Focusable: true,
HighlightOnFocus: false,
})),
SearchTrait: NewSearchTrait(c),
}
ctx.GetView().SetRenderSearchStatus(ctx.SearchTrait.RenderSearchStatus)
ctx.GetView().SetOnSelectItem(func(int) {})
return ctx
}
func (self *MainContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition {
return nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/context_common.go | pkg/gui/context/context_common.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type ContextCommon struct {
*common.Common
types.IGuiCommon
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/search_trait.go | pkg/gui/context/search_trait.go | package context
import (
"fmt"
"github.com/jesseduffield/lazygit/pkg/gui/keybindings"
"github.com/jesseduffield/lazygit/pkg/theme"
)
type SearchTrait struct {
c *ContextCommon
*SearchHistory
searchString string
}
func NewSearchTrait(c *ContextCommon) *SearchTrait {
return &SearchTrait{
c: c,
SearchHistory: NewSearchHistory(),
}
}
func (self *SearchTrait) GetSearchString() string {
return self.searchString
}
func (self *SearchTrait) SetSearchString(searchString string) {
self.searchString = searchString
}
func (self *SearchTrait) ClearSearchString() {
self.SetSearchString("")
}
// used for type switch
func (self *SearchTrait) IsSearchableContext() {}
func (self *SearchTrait) RenderSearchStatus(index int, total int) {
keybindingConfig := self.c.UserConfig().Keybinding
if total == 0 {
self.c.SetViewContent(
self.c.Views().Search,
fmt.Sprintf(
self.c.Tr.NoMatchesFor,
self.searchString,
theme.OptionsFgColor.Sprintf(self.c.Tr.ExitSearchMode, keybindings.Label(keybindingConfig.Universal.Return)),
),
)
} else {
self.c.SetViewContent(
self.c.Views().Search,
fmt.Sprintf(
self.c.Tr.MatchesFor,
self.searchString,
index+1,
total,
theme.OptionsFgColor.Sprintf(
self.c.Tr.SearchKeybindings,
keybindings.Label(keybindingConfig.Universal.NextMatch),
keybindings.Label(keybindingConfig.Universal.PrevMatch),
keybindings.Label(keybindingConfig.Universal.Return),
),
),
)
}
}
func (self *SearchTrait) IsSearching() bool {
return self.searchString != ""
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/confirmation_context.go | pkg/gui/context/confirmation_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type ConfirmationContext struct {
*SimpleContext
c *ContextCommon
State ConfirmationContextState
}
type ConfirmationContextState struct {
OnConfirm func() error
OnClose func() error
}
var _ types.Context = (*ConfirmationContext)(nil)
func NewConfirmationContext(
c *ContextCommon,
) *ConfirmationContext {
return &ConfirmationContext{
c: c,
SimpleContext: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Confirmation,
WindowName: "confirmation",
Key: CONFIRMATION_CONTEXT_KEY,
Kind: types.TEMPORARY_POPUP,
Focusable: true,
HasUncontrolledBounds: true,
})),
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/dynamic_title_builder.go | pkg/gui/context/dynamic_title_builder.go | package context
import "fmt"
type DynamicTitleBuilder struct {
formatStr string // e.g. 'remote branches for %s'
titleRef string // e.g. 'origin'
}
func NewDynamicTitleBuilder(formatStr string) *DynamicTitleBuilder {
return &DynamicTitleBuilder{
formatStr: formatStr,
}
}
func (self *DynamicTitleBuilder) SetTitleRef(titleRef string) {
self.titleRef = titleRef
}
func (self *DynamicTitleBuilder) Title() string {
return fmt.Sprintf(self.formatStr, self.titleRef)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/list_renderer.go | pkg/gui/context/list_renderer.go | package context
import (
"strings"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
"golang.org/x/exp/slices"
)
type NonModelItem struct {
// Where in the model this should be inserted
Index int
// Content to render
Content string
// The column from which to render the item
Column int
}
type ListRenderer struct {
list types.IList
// Function to get the display strings for each model item in the given
// range. startIdx and endIdx are model indices. For each model item, return
// an array of strings, one for each column; the list renderer will take
// care of aligning the columns appropriately.
getDisplayStrings func(startIdx int, endIdx int) [][]string
// Alignment for each column. If nil, the default is left alignment
getColumnAlignments func() []utils.Alignment
// Function to insert non-model items (e.g. section headers). If nil, no
// such items are inserted
getNonModelItems func() []*NonModelItem
// The remaining fields are private and shouldn't be initialized by clients
numNonModelItems int
viewIndicesByModelIndex []int
modelIndicesByViewIndex []int
columnPositions []int
}
func (self *ListRenderer) GetList() types.IList {
return self.list
}
func (self *ListRenderer) ModelIndexToViewIndex(modelIndex int) int {
modelIndex = lo.Clamp(modelIndex, 0, self.list.Len())
if self.viewIndicesByModelIndex != nil {
return self.viewIndicesByModelIndex[modelIndex]
}
return modelIndex
}
func (self *ListRenderer) ViewIndexToModelIndex(viewIndex int) int {
viewIndex = lo.Clamp(viewIndex, 0, self.list.Len()+self.numNonModelItems)
if self.modelIndicesByViewIndex != nil {
return self.modelIndicesByViewIndex[viewIndex]
}
return viewIndex
}
func (self *ListRenderer) ColumnPositions() []int {
return self.columnPositions
}
// startIdx and endIdx are view indices, not model indices. If you want to
// render the whole list, pass -1 for both.
func (self *ListRenderer) renderLines(startIdx int, endIdx int) string {
var columnAlignments []utils.Alignment
if self.getColumnAlignments != nil {
columnAlignments = self.getColumnAlignments()
}
nonModelItems := []*NonModelItem{}
self.numNonModelItems = 0
if self.getNonModelItems != nil {
nonModelItems = self.getNonModelItems()
self.prepareConversionArrays(nonModelItems)
}
startModelIdx := 0
if startIdx == -1 {
startIdx = 0
} else {
startModelIdx = self.ViewIndexToModelIndex(startIdx)
}
endModelIdx := self.list.Len()
if endIdx == -1 {
endIdx = endModelIdx + len(nonModelItems)
} else {
endModelIdx = self.ViewIndexToModelIndex(endIdx)
}
lines, columnPositions := utils.RenderDisplayStrings(
self.getDisplayStrings(startModelIdx, endModelIdx),
columnAlignments)
self.columnPositions = columnPositions
lines = self.insertNonModelItems(nonModelItems, endIdx, startIdx, lines, columnPositions)
return strings.Join(lines, "\n")
}
func (self *ListRenderer) prepareConversionArrays(nonModelItems []*NonModelItem) {
self.numNonModelItems = len(nonModelItems)
viewIndicesByModelIndex := lo.Range(self.list.Len() + 1)
modelIndicesByViewIndex := lo.Range(self.list.Len() + 1)
offset := 0
for _, item := range nonModelItems {
for i := item.Index; i <= self.list.Len(); i++ {
viewIndicesByModelIndex[i]++
}
modelIndicesByViewIndex = slices.Insert(
modelIndicesByViewIndex, item.Index+offset, modelIndicesByViewIndex[item.Index+offset])
offset++
}
self.viewIndicesByModelIndex = viewIndicesByModelIndex
self.modelIndicesByViewIndex = modelIndicesByViewIndex
}
func (self *ListRenderer) insertNonModelItems(
nonModelItems []*NonModelItem, endIdx int, startIdx int, lines []string, columnPositions []int,
) []string {
offset := 0
for _, item := range nonModelItems {
if item.Index+offset >= endIdx {
break
}
if item.Index+offset >= startIdx {
padding := ""
if columnPositions != nil {
padding = strings.Repeat(" ", columnPositions[item.Column])
}
lines = slices.Insert(lines, item.Index+offset-startIdx, padding+item.Content)
}
offset++
}
return lines
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/list_renderer_test.go | pkg/gui/context/list_renderer_test.go | package context
import (
"fmt"
"strings"
"testing"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
)
// wrapping string in my own type to give it an ID method which is required for list items
type mystring string
func (self mystring) ID() string {
return string(self)
}
func TestListRenderer_renderLines(t *testing.T) {
scenarios := []struct {
name string
modelStrings []mystring
nonModelIndices []int
startIdx int
endIdx int
expectedOutput string
}{
{
name: "Render whole list",
modelStrings: []mystring{"a", "b", "c"},
startIdx: 0,
endIdx: 3,
expectedOutput: `
a
b
c`,
},
{
name: "Partial list, beginning",
modelStrings: []mystring{"a", "b", "c"},
startIdx: 0,
endIdx: 2,
expectedOutput: `
a
b`,
},
{
name: "Partial list, end",
modelStrings: []mystring{"a", "b", "c"},
startIdx: 1,
endIdx: 3,
expectedOutput: `
b
c`,
},
{
name: "Pass an endIdx greater than the model length",
modelStrings: []mystring{"a", "b", "c"},
startIdx: 2,
endIdx: 5,
expectedOutput: `
c`,
},
{
name: "Whole list with section headers",
modelStrings: []mystring{"a", "b", "c"},
nonModelIndices: []int{1, 3},
startIdx: 0,
endIdx: 5,
expectedOutput: `
a
--- 1 (0) ---
b
c
--- 3 (1) ---`,
},
{
name: "Multiple consecutive headers",
modelStrings: []mystring{"a", "b", "c"},
nonModelIndices: []int{0, 0, 2, 2, 2},
startIdx: 0,
endIdx: 8,
expectedOutput: `
--- 0 (0) ---
--- 0 (1) ---
a
b
--- 2 (2) ---
--- 2 (3) ---
--- 2 (4) ---
c`,
},
{
name: "Partial list with headers, beginning",
modelStrings: []mystring{"a", "b", "c"},
nonModelIndices: []int{1, 3},
startIdx: 0,
endIdx: 3,
expectedOutput: `
a
--- 1 (0) ---
b`,
},
{
name: "Partial list with headers, end (beyond end index)",
modelStrings: []mystring{"a", "b", "c"},
nonModelIndices: []int{1, 3},
startIdx: 2,
endIdx: 7,
expectedOutput: `
b
c
--- 3 (1) ---`,
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
viewModel := NewListViewModel(func() []mystring { return s.modelStrings })
var getNonModelItems func() []*NonModelItem
if s.nonModelIndices != nil {
getNonModelItems = func() []*NonModelItem {
return lo.Map(s.nonModelIndices, func(modelIndex int, nonModelIndex int) *NonModelItem {
return &NonModelItem{
Index: modelIndex,
Content: fmt.Sprintf("--- %d (%d) ---", modelIndex, nonModelIndex),
}
})
}
}
self := &ListRenderer{
list: viewModel,
getDisplayStrings: func(startIdx int, endIdx int) [][]string {
return lo.Map(s.modelStrings[startIdx:endIdx],
func(s mystring, _ int) []string { return []string{string(s)} })
},
getNonModelItems: getNonModelItems,
}
expectedOutput := strings.Join(lo.Map(
strings.Split(strings.TrimPrefix(s.expectedOutput, "\n"), "\n"),
func(line string, _ int) string { return strings.TrimSpace(line) }), "\n")
assert.Equal(t, expectedOutput, self.renderLines(s.startIdx, s.endIdx))
})
}
}
type myint int
func (self myint) ID() string {
return fmt.Sprint(int(self))
}
func TestListRenderer_ModelIndexToViewIndex_and_back(t *testing.T) {
scenarios := []struct {
name string
numModelItems int
nonModelIndices []int
modelIndices []int
expectedViewIndices []int
viewIndices []int
expectedModelIndices []int
}{
{
name: "no headers (no getNonModelItems provided)",
numModelItems: 3,
nonModelIndices: nil, // no get
modelIndices: []int{-1, 0, 1, 2, 3, 4},
expectedViewIndices: []int{0, 0, 1, 2, 3, 3},
viewIndices: []int{-1, 0, 1, 2, 3, 4},
expectedModelIndices: []int{0, 0, 1, 2, 3, 3},
},
{
name: "no headers (getNonModelItems returns zero items)",
numModelItems: 3,
nonModelIndices: []int{},
modelIndices: []int{-1, 0, 1, 2, 3, 4},
expectedViewIndices: []int{0, 0, 1, 2, 3, 3},
viewIndices: []int{-1, 0, 1, 2, 3, 4},
expectedModelIndices: []int{0, 0, 1, 2, 3, 3},
},
{
name: "basic",
numModelItems: 3,
nonModelIndices: []int{1, 2},
/*
0: model 0
1: --- header 0 ---
2: model 1
3: --- header 1 ---
4: model 2
*/
modelIndices: []int{-1, 0, 1, 2, 3, 4},
expectedViewIndices: []int{0, 0, 2, 4, 5, 5},
viewIndices: []int{-1, 0, 1, 2, 3, 4, 5, 6},
expectedModelIndices: []int{0, 0, 1, 1, 2, 2, 3, 3},
},
{
name: "consecutive section headers",
numModelItems: 3,
nonModelIndices: []int{0, 0, 2, 2, 2, 3, 3},
/*
0: --- header 0 ---
1: --- header 1 ---
2: model 0
3: model 1
4: --- header 2 ---
5: --- header 3 ---
6: --- header 4 ---
7: model 2
8: --- header 5 ---
9: --- header 6 ---
*/
modelIndices: []int{-1, 0, 1, 2, 3, 4},
expectedViewIndices: []int{2, 2, 3, 7, 10, 10},
viewIndices: []int{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
expectedModelIndices: []int{0, 0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3},
},
}
for _, s := range scenarios {
t.Run(s.name, func(t *testing.T) {
// Expect lists of equal length for each test:
assert.Equal(t, len(s.modelIndices), len(s.expectedViewIndices))
assert.Equal(t, len(s.viewIndices), len(s.expectedModelIndices))
modelInts := lo.Map(lo.Range(s.numModelItems), func(i int, _ int) myint { return myint(i) })
viewModel := NewListViewModel(func() []myint { return modelInts })
var getNonModelItems func() []*NonModelItem
if s.nonModelIndices != nil {
getNonModelItems = func() []*NonModelItem {
return lo.Map(s.nonModelIndices, func(modelIndex int, _ int) *NonModelItem {
return &NonModelItem{Index: modelIndex, Content: ""}
})
}
}
self := &ListRenderer{
list: viewModel,
getDisplayStrings: func(startIdx int, endIdx int) [][]string {
return lo.Map(modelInts[startIdx:endIdx],
func(i myint, _ int) []string { return []string{fmt.Sprint(i)} })
},
getNonModelItems: getNonModelItems,
}
// Need to render first so that it knows the non-model items
self.renderLines(-1, -1)
for i := range len(s.modelIndices) {
assert.Equal(t, s.expectedViewIndices[i], self.ModelIndexToViewIndex(s.modelIndices[i]))
}
for i := range len(s.viewIndices) {
assert.Equal(t, s.expectedModelIndices[i], self.ViewIndexToModelIndex(s.viewIndices[i]))
}
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/view_trait.go | pkg/gui/context/view_trait.go | package context
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
const HORIZONTAL_SCROLL_FACTOR = 3
type ViewTrait struct {
view *gocui.View
}
var _ types.IViewTrait = &ViewTrait{}
func NewViewTrait(view *gocui.View) *ViewTrait {
return &ViewTrait{view: view}
}
func (self *ViewTrait) FocusPoint(yIdx int, scrollIntoView bool) {
self.view.FocusPoint(self.view.OriginX(), yIdx, scrollIntoView)
}
func (self *ViewTrait) SetRangeSelectStart(yIdx int) {
self.view.SetRangeSelectStart(yIdx)
}
func (self *ViewTrait) CancelRangeSelect() {
self.view.CancelRangeSelect()
}
func (self *ViewTrait) SetViewPortContent(content string) {
_, y := self.view.Origin()
self.view.OverwriteLines(y, content)
}
func (self *ViewTrait) SetViewPortContentAndClearEverythingElse(lineCount int, content string) {
_, y := self.view.Origin()
self.view.OverwriteLinesAndClearEverythingElse(lineCount, y, content)
}
func (self *ViewTrait) SetContent(content string) {
self.view.SetContent(content)
}
func (self *ViewTrait) SetHighlight(highlight bool) {
self.view.Highlight = highlight
self.view.HighlightInactive = false
}
func (self *ViewTrait) SetFooter(value string) {
self.view.Footer = value
}
func (self *ViewTrait) SetOriginX(value int) {
self.view.SetOriginX(value)
}
// tells us the start of line indexes shown in the view currently as well as the capacity of lines shown in the viewport.
func (self *ViewTrait) ViewPortYBounds() (int, int) {
_, start := self.view.Origin()
length := self.view.InnerHeight()
return start, length
}
func (self *ViewTrait) ScrollLeft() {
self.view.ScrollLeft(self.horizontalScrollAmount())
}
func (self *ViewTrait) ScrollRight() {
self.view.ScrollRight(self.horizontalScrollAmount())
}
func (self *ViewTrait) horizontalScrollAmount() int {
return self.view.InnerWidth() / HORIZONTAL_SCROLL_FACTOR
}
func (self *ViewTrait) ScrollUp(value int) {
self.view.ScrollUp(value)
}
func (self *ViewTrait) ScrollDown(value int) {
self.view.ScrollDown(value)
}
// this returns the amount we'll scroll if we want to scroll by a page.
func (self *ViewTrait) PageDelta() int {
height := self.view.InnerHeight()
delta := height - 1
if delta == 0 {
return 1
}
return delta
}
func (self *ViewTrait) SelectedLineIdx() int {
return self.view.SelectedLineIdx()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/prompt_context.go | pkg/gui/context/prompt_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type PromptContext struct {
*SimpleContext
c *ContextCommon
State ConfirmationContextState
}
var _ types.Context = (*PromptContext)(nil)
func NewPromptContext(
c *ContextCommon,
) *PromptContext {
return &PromptContext{
c: c,
SimpleContext: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Prompt,
WindowName: "prompt",
Key: PROMPT_CONTEXT_KEY,
Kind: types.TEMPORARY_POPUP,
Focusable: true,
HasUncontrolledBounds: true,
})),
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/tags_context.go | pkg/gui/context/tags_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type TagsContext struct {
*FilteredListViewModel[*models.Tag]
*ListContextTrait
}
var (
_ types.IListContext = (*TagsContext)(nil)
_ types.DiffableContext = (*TagsContext)(nil)
)
func NewTagsContext(
c *ContextCommon,
) *TagsContext {
viewModel := NewFilteredListViewModel(
func() []*models.Tag { return c.Model().Tags },
func(tag *models.Tag) []string {
return []string{tag.Name, tag.Message}
},
)
getDisplayStrings := func(_ int, _ int) [][]string {
return presentation.GetTagListDisplayStrings(
viewModel.GetItems(),
c.State().GetItemOperation,
c.Modes().Diffing.Ref, c.Tr, c.UserConfig())
}
return &TagsContext{
FilteredListViewModel: viewModel,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Tags,
WindowName: "branches",
Key: TAGS_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
},
}
}
func (self *TagsContext) GetSelectedRef() models.Ref {
tag := self.GetSelected()
if tag == nil {
return nil
}
return tag
}
func (self *TagsContext) GetDiffTerminals() []string {
itemId := self.GetSelectedItemId()
return []string{itemId}
}
func (self *TagsContext) RefForAdjustingLineNumberInDiff() string {
return self.GetSelectedItemId()
}
func (self *TagsContext) ShowBranchHeadsInSubCommits() bool {
return true
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/working_tree_context.go | pkg/gui/context/working_tree_context.go | package context
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/filetree"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/presentation/icons"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type WorkingTreeContext struct {
*filetree.FileTreeViewModel
*ListContextTrait
*SearchTrait
}
var (
_ types.IListContext = (*WorkingTreeContext)(nil)
_ types.ISearchableContext = (*WorkingTreeContext)(nil)
)
func NewWorkingTreeContext(c *ContextCommon) *WorkingTreeContext {
viewModel := filetree.NewFileTreeViewModel(
func() []*models.File { return c.Model().Files },
c.Common,
c.UserConfig().Gui.ShowFileTree,
)
getDisplayStrings := func(_ int, _ int) [][]string {
showFileIcons := icons.IsIconEnabled() && c.UserConfig().Gui.ShowFileIcons
showNumstat := c.UserConfig().Gui.ShowNumstatInFilesView
lines := presentation.RenderFileTree(viewModel, c.Model().Submodules, showFileIcons, showNumstat, &c.UserConfig().Gui.CustomIcons, c.UserConfig().Gui.ShowRootItemInFileTree)
return lo.Map(lines, func(line string, _ int) []string {
return []string{line}
})
}
ctx := &WorkingTreeContext{
SearchTrait: NewSearchTrait(c),
FileTreeViewModel: viewModel,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Files,
WindowName: "files",
Key: FILES_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
},
}
ctx.GetView().SetRenderSearchStatus(ctx.SearchTrait.RenderSearchStatus)
ctx.GetView().SetOnSelectItem(ctx.OnSearchSelect)
return ctx
}
func (self *WorkingTreeContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition {
return nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/filtered_list.go | pkg/gui/context/filtered_list.go | package context
import (
"strings"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sahilm/fuzzy"
"github.com/samber/lo"
"github.com/sasha-s/go-deadlock"
)
type FilteredList[T any] struct {
filteredIndices []int // if nil, we are not filtering
getList func() []T
getFilterFields func(T) []string
preprocessFilter func(string) string
filter string
mutex deadlock.Mutex
}
func NewFilteredList[T any](getList func() []T, getFilterFields func(T) []string) *FilteredList[T] {
return &FilteredList[T]{
getList: getList,
getFilterFields: getFilterFields,
}
}
func (self *FilteredList[T]) SetPreprocessFilterFunc(preprocessFilter func(string) string) {
self.preprocessFilter = preprocessFilter
}
func (self *FilteredList[T]) GetFilter() string {
return self.filter
}
func (self *FilteredList[T]) SetFilter(filter string, useFuzzySearch bool) {
self.filter = filter
self.applyFilter(useFuzzySearch)
}
func (self *FilteredList[T]) ClearFilter() {
self.SetFilter("", false)
}
func (self *FilteredList[T]) ReApplyFilter(useFuzzySearch bool) {
self.applyFilter(useFuzzySearch)
}
func (self *FilteredList[T]) IsFiltering() bool {
return self.filter != ""
}
func (self *FilteredList[T]) GetFilteredList() []T {
if self.filteredIndices == nil {
return self.getList()
}
return utils.ValuesAtIndices(self.getList(), self.filteredIndices)
}
// TODO: update to just 'Len'
func (self *FilteredList[T]) UnfilteredLen() int {
return len(self.getList())
}
type fuzzySource[T any] struct {
list []T
getFilterFields func(T) []string
}
var _ fuzzy.Source = &fuzzySource[string]{}
func (self *fuzzySource[T]) String(i int) string {
return strings.Join(self.getFilterFields(self.list[i]), " ")
}
func (self *fuzzySource[T]) Len() int {
return len(self.list)
}
func (self *FilteredList[T]) applyFilter(useFuzzySearch bool) {
self.mutex.Lock()
defer self.mutex.Unlock()
filter := self.filter
if self.preprocessFilter != nil {
filter = self.preprocessFilter(filter)
}
if filter == "" {
self.filteredIndices = nil
} else {
source := &fuzzySource[T]{
list: self.getList(),
getFilterFields: self.getFilterFields,
}
matches := utils.FindFrom(filter, source, useFuzzySearch)
self.filteredIndices = lo.Map(matches, func(match fuzzy.Match, _ int) int {
return match.Index
})
}
}
func (self *FilteredList[T]) UnfilteredIndex(index int) int {
self.mutex.Lock()
defer self.mutex.Unlock()
if self.filteredIndices == nil {
return index
}
// we use -1 when there are no items
if index == -1 {
return -1
}
return self.filteredIndices[index]
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/remote_branches_context.go | pkg/gui/context/remote_branches_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type RemoteBranchesContext struct {
*FilteredListViewModel[*models.RemoteBranch]
*ListContextTrait
*DynamicTitleBuilder
}
var (
_ types.IListContext = (*RemoteBranchesContext)(nil)
_ types.DiffableContext = (*RemoteBranchesContext)(nil)
)
func NewRemoteBranchesContext(
c *ContextCommon,
) *RemoteBranchesContext {
viewModel := NewFilteredListViewModel(
func() []*models.RemoteBranch { return c.Model().RemoteBranches },
func(remoteBranch *models.RemoteBranch) []string {
return []string{remoteBranch.Name}
},
)
getDisplayStrings := func(_ int, _ int) [][]string {
return presentation.GetRemoteBranchListDisplayStrings(viewModel.GetItems(), c.Modes().Diffing.Ref)
}
return &RemoteBranchesContext{
FilteredListViewModel: viewModel,
DynamicTitleBuilder: NewDynamicTitleBuilder(c.Tr.RemoteBranchesDynamicTitle),
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().RemoteBranches,
WindowName: "branches",
Key: REMOTE_BRANCHES_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
Transient: true,
NeedsRerenderOnHeightChange: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
},
}
}
func (self *RemoteBranchesContext) GetSelectedRef() models.Ref {
remoteBranch := self.GetSelected()
if remoteBranch == nil {
return nil
}
return remoteBranch
}
func (self *RemoteBranchesContext) GetSelectedRefs() ([]models.Ref, int, int) {
items, startIdx, endIdx := self.GetSelectedItems()
refs := lo.Map(items, func(item *models.RemoteBranch, _ int) models.Ref {
return item
})
return refs, startIdx, endIdx
}
func (self *RemoteBranchesContext) GetDiffTerminals() []string {
itemId := self.GetSelectedItemId()
return []string{itemId}
}
func (self *RemoteBranchesContext) RefForAdjustingLineNumberInDiff() string {
return self.GetSelectedItemId()
}
func (self *RemoteBranchesContext) ShowBranchHeadsInSubCommits() bool {
return true
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/patch_explorer_context.go | pkg/gui/context/patch_explorer_context.go | package context
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/patch_exploring"
"github.com/jesseduffield/lazygit/pkg/gui/types"
deadlock "github.com/sasha-s/go-deadlock"
)
type PatchExplorerContext struct {
*SimpleContext
*SearchTrait
state *patch_exploring.State
viewTrait *ViewTrait
getIncludedLineIndices func() []int
c *ContextCommon
mutex deadlock.Mutex
// true if we're inside the OnSelectItem callback; in that case we don't want to update the
// search result index.
inOnSelectItemCallback bool
}
var (
_ types.IPatchExplorerContext = (*PatchExplorerContext)(nil)
_ types.ISearchableContext = (*PatchExplorerContext)(nil)
)
func NewPatchExplorerContext(
view *gocui.View,
windowName string,
key types.ContextKey,
getIncludedLineIndices func() []int,
c *ContextCommon,
) *PatchExplorerContext {
ctx := &PatchExplorerContext{
state: nil,
viewTrait: NewViewTrait(view),
c: c,
getIncludedLineIndices: getIncludedLineIndices,
SimpleContext: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: view,
WindowName: windowName,
Key: key,
Kind: types.MAIN_CONTEXT,
Focusable: true,
HighlightOnFocus: true,
NeedsRerenderOnWidthChange: types.NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_WIDTH_CHANGES,
})),
SearchTrait: NewSearchTrait(c),
}
ctx.GetView().SetRenderSearchStatus(ctx.SearchTrait.RenderSearchStatus)
ctx.GetView().SetOnSelectItem(func(selectedLineIdx int) {
ctx.GetMutex().Lock()
defer ctx.GetMutex().Unlock()
ctx.inOnSelectItemCallback = true
ctx.NavigateTo(selectedLineIdx)
ctx.inOnSelectItemCallback = false
})
ctx.SetHandleRenderFunc(ctx.OnViewWidthChanged)
return ctx
}
func (self *PatchExplorerContext) IsPatchExplorerContext() {}
func (self *PatchExplorerContext) GetState() *patch_exploring.State {
return self.state
}
func (self *PatchExplorerContext) SetState(state *patch_exploring.State) {
self.state = state
}
func (self *PatchExplorerContext) GetViewTrait() types.IViewTrait {
return self.viewTrait
}
func (self *PatchExplorerContext) GetIncludedLineIndices() []int {
return self.getIncludedLineIndices()
}
func (self *PatchExplorerContext) RenderAndFocus() {
self.setContent()
self.FocusSelection()
self.c.Render()
}
func (self *PatchExplorerContext) Render() {
self.setContent()
self.c.Render()
}
func (self *PatchExplorerContext) setContent() {
self.GetView().SetContent(self.GetContentToRender())
}
func (self *PatchExplorerContext) FocusSelection() {
view := self.GetView()
state := self.GetState()
bufferHeight := view.InnerHeight()
_, origin := view.Origin()
numLines := view.ViewLinesHeight()
newOriginY := state.CalculateOrigin(origin, bufferHeight, numLines)
view.SetOriginY(newOriginY)
startIdx, endIdx := state.SelectedViewRange()
// As far as the view is concerned, we are always selecting a range
view.SetRangeSelectStart(startIdx)
view.SetCursorY(endIdx - newOriginY)
if !self.inOnSelectItemCallback {
view.SetNearestSearchPosition()
}
}
func (self *PatchExplorerContext) GetContentToRender() string {
if self.GetState() == nil {
return ""
}
return self.GetState().RenderForLineIndices(self.GetIncludedLineIndices())
}
func (self *PatchExplorerContext) NavigateTo(selectedLineIdx int) {
self.GetState().SetLineSelectMode()
self.GetState().SelectLine(selectedLineIdx)
self.RenderAndFocus()
}
func (self *PatchExplorerContext) GetMutex() *deadlock.Mutex {
return &self.mutex
}
func (self *PatchExplorerContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition {
return nil
}
func (self *PatchExplorerContext) OnViewWidthChanged() {
if state := self.GetState(); state != nil {
state.OnViewWidthChanged(self.GetView())
self.setContent()
self.RenderAndFocus()
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/local_commits_context.go | pkg/gui/context/local_commits_context.go | package context
import (
"fmt"
"log"
"strings"
"time"
"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/samber/lo"
)
type LocalCommitsContext struct {
*LocalCommitsViewModel
*ListContextTrait
*SearchTrait
}
var (
_ types.IListContext = (*LocalCommitsContext)(nil)
_ types.DiffableContext = (*LocalCommitsContext)(nil)
_ types.ISearchableContext = (*LocalCommitsContext)(nil)
)
func NewLocalCommitsContext(c *ContextCommon) *LocalCommitsContext {
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),
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: fmt.Sprintf("--- %s ---", 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: fmt.Sprintf("--- %s ---", label),
})
}
_, 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: fmt.Sprintf("--- %s ---", c.Tr.CommitsSectionHeader),
})
}
return result
}
ctx := &LocalCommitsContext{
LocalCommitsViewModel: viewModel,
SearchTrait: NewSearchTrait(c),
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,
},
}
ctx.GetView().SetRenderSearchStatus(ctx.SearchTrait.RenderSearchStatus)
ctx.GetView().SetOnSelectItem(ctx.OnSearchSelect)
return ctx
}
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.
limitCommits bool
// 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),
limitCommits: true,
showWholeGitGraph: c.UserConfig().Git.Log.ShowWholeGraph,
}
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.ModelIndexToViewIndex, searchStr)
}
func (self *LocalCommitsViewModel) SetLimitCommits(value bool) {
self.limitCommits = value
}
func (self *LocalCommitsViewModel) GetLimitCommits() bool {
return self.limitCommits
}
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 {
if c.Modes().Filtering.Active() {
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 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 {
commits := self.GetCommits()
selectedIdx := self.GetSelectedLineIdx()
if selectedIdx >= 0 && selectedIdx < len(commits)-1 {
if commits[selectedIdx+1].Status != models.StatusMerged {
_, idx, found := lo.FindIndexOf(commits, func(c *models.Commit) bool {
return c.Status == models.StatusMerged
})
if found {
return idx - 1
}
}
}
return self.list.Len() - 1
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/list_view_model.go | pkg/gui/context/list_view_model.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/gui/context/traits"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type HasID interface {
ID() string
}
type ListViewModel[T HasID] struct {
*traits.ListCursor
getModel func() []T
}
func NewListViewModel[T HasID](getModel func() []T) *ListViewModel[T] {
self := &ListViewModel[T]{
getModel: getModel,
}
self.ListCursor = traits.NewListCursor(func() int { return len(getModel()) })
return self
}
func (self *ListViewModel[T]) GetSelected() T {
if self.Len() == 0 {
return Zero[T]()
}
return self.getModel()[self.GetSelectedLineIdx()]
}
func (self *ListViewModel[T]) GetSelectedItemId() string {
if self.Len() == 0 {
return ""
}
return self.GetSelected().ID()
}
func (self *ListViewModel[T]) GetSelectedItems() ([]T, int, int) {
if self.Len() == 0 {
return nil, -1, -1
}
startIdx, endIdx := self.GetSelectionRange()
return self.getModel()[startIdx : endIdx+1], startIdx, endIdx
}
func (self *ListViewModel[T]) GetSelectedItemIds() ([]string, int, int) {
selectedItems, startIdx, endIdx := self.GetSelectedItems()
ids := lo.Map(selectedItems, func(item T, _ int) string {
return item.ID()
})
return ids, startIdx, endIdx
}
func (self *ListViewModel[T]) GetItems() []T {
return self.getModel()
}
func Zero[T any]() T {
return *new(T)
}
func (self *ListViewModel[T]) GetItem(index int) types.HasUrn {
item := self.getModel()[index]
return any(item).(types.HasUrn)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/remotes_context.go | pkg/gui/context/remotes_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type RemotesContext struct {
*FilteredListViewModel[*models.Remote]
*ListContextTrait
}
var (
_ types.IListContext = (*RemotesContext)(nil)
_ types.DiffableContext = (*RemotesContext)(nil)
)
func NewRemotesContext(c *ContextCommon) *RemotesContext {
viewModel := NewFilteredListViewModel(
func() []*models.Remote { return c.Model().Remotes },
func(remote *models.Remote) []string {
return []string{remote.Name}
},
)
getDisplayStrings := func(_ int, _ int) [][]string {
return presentation.GetRemoteListDisplayStrings(
viewModel.GetItems(), c.Modes().Diffing.Ref, c.State().GetItemOperation, c.Tr, c.UserConfig())
}
return &RemotesContext{
FilteredListViewModel: viewModel,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Remotes,
WindowName: "branches",
Key: REMOTES_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
},
}
}
func (self *RemotesContext) GetDiffTerminals() []string {
itemId := self.GetSelectedItemId()
return []string{itemId}
}
func (self *RemotesContext) RefForAdjustingLineNumberInDiff() string {
return ""
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/sub_commits_context.go | pkg/gui/context/sub_commits_context.go | package context
import (
"fmt"
"time"
"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/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/samber/lo"
)
type SubCommitsContext struct {
c *ContextCommon
*SubCommitsViewModel
*ListContextTrait
*DynamicTitleBuilder
*SearchTrait
}
var (
_ types.IListContext = (*SubCommitsContext)(nil)
_ types.DiffableContext = (*SubCommitsContext)(nil)
_ types.ISearchableContext = (*SubCommitsContext)(nil)
)
func NewSubCommitsContext(
c *ContextCommon,
) *SubCommitsContext {
viewModel := &SubCommitsViewModel{
ListViewModel: NewListViewModel(
func() []*models.Commit { return c.Model().SubCommits },
),
ref: nil,
limitCommits: true,
}
getDisplayStrings := func(startIdx int, endIdx int) [][]string {
// This can happen if a sub-commits view is asked to be rerendered while
// it is invisible; for example when switching screen modes, which
// rerenders all views.
if viewModel.GetRef() == nil {
return [][]string{}
}
var selectedCommitHashPtr *string
if c.Context().Current().GetKey() == SUB_COMMITS_CONTEXT_KEY {
selectedCommit := viewModel.GetSelected()
if selectedCommit != nil {
selectedCommitHashPtr = selectedCommit.HashPtr()
}
}
branches := []*models.Branch{}
if viewModel.GetShowBranchHeads() {
branches = c.Model().Branches
}
hasRebaseUpdateRefsConfig := c.Git().Config.GetRebaseUpdateRefs()
return presentation.GetCommitListDisplayStrings(
c.Common,
c.Model().SubCommits,
branches,
viewModel.GetRef().RefName(),
hasRebaseUpdateRefsConfig,
c.State().GetRepoState().GetScreenMode() != types.SCREEN_NORMAL,
c.Modes().CherryPicking.SelectedHashSet(),
c.Modes().Diffing.Ref,
"",
c.UserConfig().Gui.TimeFormat,
c.UserConfig().Gui.ShortTimeFormat,
time.Now(),
c.UserConfig().Git.ParseEmoji,
selectedCommitHashPtr,
startIdx,
endIdx,
shouldShowGraph(c),
git_commands.NewNullBisectInfo(),
)
}
getNonModelItems := func() []*NonModelItem {
result := []*NonModelItem{}
if viewModel.GetRefToShowDivergenceFrom() != "" {
_, upstreamIdx, found := lo.FindIndexOf(
c.Model().SubCommits, func(c *models.Commit) bool { return c.Divergence == models.DivergenceRight })
if !found {
upstreamIdx = 0
}
result = append(result, &NonModelItem{
Index: upstreamIdx,
Content: fmt.Sprintf("--- %s ---", c.Tr.DivergenceSectionHeaderRemote),
})
_, localIdx, found := lo.FindIndexOf(
c.Model().SubCommits, func(c *models.Commit) bool { return c.Divergence == models.DivergenceLeft })
if !found {
localIdx = len(c.Model().SubCommits)
}
result = append(result, &NonModelItem{
Index: localIdx,
Content: fmt.Sprintf("--- %s ---", c.Tr.DivergenceSectionHeaderLocal),
})
}
return result
}
ctx := &SubCommitsContext{
c: c,
SubCommitsViewModel: viewModel,
SearchTrait: NewSearchTrait(c),
DynamicTitleBuilder: NewDynamicTitleBuilder(c.Tr.SubCommitsDynamicTitle),
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().SubCommits,
WindowName: "branches",
Key: SUB_COMMITS_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
Transient: 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,
},
}
ctx.GetView().SetRenderSearchStatus(ctx.SearchTrait.RenderSearchStatus)
ctx.GetView().SetOnSelectItem(ctx.OnSearchSelect)
return ctx
}
type SubCommitsViewModel struct {
// name of the ref that the sub-commits are shown for
ref models.Ref
refToShowDivergenceFrom string
*ListViewModel[*models.Commit]
limitCommits bool
showBranchHeads bool
}
func (self *SubCommitsViewModel) SetRef(ref models.Ref) {
self.ref = ref
}
func (self *SubCommitsViewModel) GetRef() models.Ref {
return self.ref
}
func (self *SubCommitsViewModel) SetRefToShowDivergenceFrom(ref string) {
self.refToShowDivergenceFrom = ref
}
func (self *SubCommitsViewModel) GetRefToShowDivergenceFrom() string {
return self.refToShowDivergenceFrom
}
func (self *SubCommitsViewModel) SetShowBranchHeads(value bool) {
self.showBranchHeads = value
}
func (self *SubCommitsViewModel) GetShowBranchHeads() bool {
return self.showBranchHeads
}
func (self *SubCommitsContext) CanRebase() bool {
return false
}
func (self *SubCommitsContext) GetSelectedRef() models.Ref {
commit := self.GetSelected()
if commit == nil {
return nil
}
return commit
}
func (self *SubCommitsContext) 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.Divergence != to.Divergence {
return nil
}
return &types.RefRange{From: from, To: to}
}
func (self *SubCommitsContext) GetCommits() []*models.Commit {
return self.getModel()
}
func (self *SubCommitsContext) SetLimitCommits(value bool) {
self.limitCommits = value
}
func (self *SubCommitsContext) GetLimitCommits() bool {
return self.limitCommits
}
func (self *SubCommitsContext) GetDiffTerminals() []string {
itemId := self.GetSelectedItemId()
return []string{itemId}
}
func (self *SubCommitsContext) RefForAdjustingLineNumberInDiff() string {
commits, _, _ := self.GetSelectedItems()
if commits == nil {
return ""
}
return commits[0].Hash()
}
func (self *SubCommitsContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition {
return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.ModelIndexToViewIndex, searchStr)
}
func (self *SubCommitsContext) IndexForGotoBottom() int {
commits := self.GetCommits()
selectedIdx := self.GetSelectedLineIdx()
if selectedIdx >= 0 && selectedIdx < len(commits)-1 {
if commits[selectedIdx+1].Status != models.StatusMerged {
_, idx, found := lo.FindIndexOf(commits, func(c *models.Commit) bool {
return c.Status == models.StatusMerged
})
if found {
return idx - 1
}
}
}
return self.list.Len() - 1
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/commit_message_context.go | pkg/gui/context/commit_message_context.go | package context
import (
"os"
"path/filepath"
"strconv"
"strings"
"github.com/jesseduffield/lazygit/pkg/gui/keybindings"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/spf13/afero"
)
const PreservedCommitMessageFileName = "LAZYGIT_PENDING_COMMIT"
type CommitMessageContext struct {
c *ContextCommon
types.Context
viewModel *CommitMessageViewModel
}
var _ types.Context = (*CommitMessageContext)(nil)
// when selectedIndex (see below) is set to this value, it means that we're not
// currently viewing a commit message of an existing commit: instead we're making our own
// new commit message
const NoCommitIndex = -1
type CommitMessageViewModel struct {
// index of the commit message, where -1 is 'no commit', 0 is the HEAD commit, 1
// is the prior commit, and so on
selectedindex int
// if true, then upon escaping from the commit message panel, we will preserve
// the message so that it's still shown next time we open the panel
preserveMessage bool
// we remember the initial message so that we can tell whether we should preserve
// the message; if it's still identical to the initial message, we don't
initialMessage string
// invoked when pressing enter in the commit message panel
onConfirm func(string, string) error
// invoked when pressing the switch-to-editor key binding
onSwitchToEditor func(string) error
// the following two fields are used for the display of the "hooks disabled" subtitle
forceSkipHooks bool
skipHooksPrefix string
// The message typed in before cycling through history
// We store this separately to 'preservedMessage' because 'preservedMessage'
// is specifically for committing staged files and we don't want this affected
// by cycling through history in the context of rewording an old commit.
historyMessage string
}
func NewCommitMessageContext(
c *ContextCommon,
) *CommitMessageContext {
viewModel := &CommitMessageViewModel{}
return &CommitMessageContext{
c: c,
viewModel: viewModel,
Context: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.PERSISTENT_POPUP,
View: c.Views().CommitMessage,
WindowName: "commitMessage",
Key: COMMIT_MESSAGE_CONTEXT_KEY,
Focusable: true,
HasUncontrolledBounds: true,
}),
),
}
}
func (self *CommitMessageContext) SetSelectedIndex(value int) {
self.viewModel.selectedindex = value
}
func (self *CommitMessageContext) GetSelectedIndex() int {
return self.viewModel.selectedindex
}
func (self *CommitMessageContext) GetPreservedMessagePath() string {
return filepath.Join(self.c.Git().RepoPaths.WorktreeGitDirPath(), PreservedCommitMessageFileName)
}
func (self *CommitMessageContext) GetPreserveMessage() bool {
return self.viewModel.preserveMessage
}
func (self *CommitMessageContext) getPreservedMessage() (string, error) {
buf, err := afero.ReadFile(self.c.Fs, self.GetPreservedMessagePath())
if os.IsNotExist(err) {
return "", nil
}
if err != nil {
return "", err
}
return string(buf), nil
}
func (self *CommitMessageContext) GetPreservedMessageAndLogError() string {
msg, err := self.getPreservedMessage()
if err != nil {
self.c.Log.Errorf("error when retrieving persisted commit message: %v", err)
}
return msg
}
func (self *CommitMessageContext) setPreservedMessage(message string) error {
preservedFilePath := self.GetPreservedMessagePath()
if len(message) == 0 {
err := self.c.Fs.Remove(preservedFilePath)
if os.IsNotExist(err) {
return nil
}
return err
}
return afero.WriteFile(self.c.Fs, preservedFilePath, []byte(message), 0o644)
}
func (self *CommitMessageContext) SetPreservedMessageAndLogError(message string) {
if err := self.setPreservedMessage(message); err != nil {
self.c.Log.Errorf("error when persisting commit message: %v", err)
}
}
func (self *CommitMessageContext) GetInitialMessage() string {
return strings.TrimSpace(self.viewModel.initialMessage)
}
func (self *CommitMessageContext) GetHistoryMessage() string {
return self.viewModel.historyMessage
}
func (self *CommitMessageContext) SetHistoryMessage(message string) {
self.viewModel.historyMessage = message
}
func (self *CommitMessageContext) OnConfirm(summary string, description string) error {
return self.viewModel.onConfirm(summary, description)
}
func (self *CommitMessageContext) SetPanelState(
index int,
summaryTitle string,
descriptionTitle string,
preserveMessage bool,
initialMessage string,
onConfirm func(string, string) error,
onSwitchToEditor func(string) error,
forceSkipHooks bool,
skipHooksPrefix string,
) {
self.viewModel.selectedindex = index
self.viewModel.preserveMessage = preserveMessage
self.viewModel.initialMessage = initialMessage
self.viewModel.onConfirm = onConfirm
self.viewModel.onSwitchToEditor = onSwitchToEditor
self.viewModel.forceSkipHooks = forceSkipHooks
self.viewModel.skipHooksPrefix = skipHooksPrefix
self.GetView().Title = summaryTitle
self.c.Views().CommitDescription.Title = descriptionTitle
self.c.Views().CommitDescription.Subtitle = utils.ResolvePlaceholderString(self.c.Tr.CommitDescriptionSubTitle,
map[string]string{
"togglePanelKeyBinding": keybindings.Label(self.c.UserConfig().Keybinding.Universal.TogglePanel),
"commitMenuKeybinding": keybindings.Label(self.c.UserConfig().Keybinding.CommitMessage.CommitMenu),
})
self.c.Views().CommitDescription.Visible = true
}
func (self *CommitMessageContext) RenderSubtitle() {
skipHookPrefix := self.viewModel.skipHooksPrefix
subject := self.c.Views().CommitMessage.TextArea.GetContent()
var subtitle string
if self.viewModel.forceSkipHooks || (skipHookPrefix != "" && strings.HasPrefix(subject, skipHookPrefix)) {
subtitle = self.c.Tr.CommitHooksDisabledSubTitle
}
if self.c.UserConfig().Gui.CommitLength.Show {
if subtitle != "" {
subtitle += "─"
}
subtitle += getBufferLength(subject)
}
self.c.Views().CommitMessage.Subtitle = subtitle
}
func getBufferLength(subject string) string {
return " " + strconv.Itoa(strings.Count(subject, "")-1) + " "
}
func (self *CommitMessageContext) SwitchToEditor(message string) error {
return self.viewModel.onSwitchToEditor(message)
}
func (self *CommitMessageContext) CanSwitchToEditor() bool {
return self.viewModel.onSwitchToEditor != nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/list_context_trait.go | pkg/gui/context/list_context_trait.go | package context
import (
"fmt"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type ListContextTrait struct {
types.Context
ListRenderer
c *ContextCommon
// Some contexts, like the commit context, will highlight the path from the selected commit
// to its parents, because it's ambiguous otherwise. For these, we need to refresh the viewport
// so that we show the highlighted path.
// TODO: now that we allow scrolling, we should be smarter about what gets refreshed:
// we should find out exactly which lines are now part of the path and refresh those.
// We should also keep track of the previous path and refresh those lines too.
refreshViewportOnChange bool
// If this is true, we only render the visible lines of the list. Useful for lists that can
// get very long, because it can save a lot of memory
renderOnlyVisibleLines bool
// If renderOnlyVisibleLines is true, needRerenderVisibleLines indicates whether we need to
// rerender the visible lines e.g. because the scroll position changed
needRerenderVisibleLines bool
// true if we're inside the OnSearchSelect call; in that case we don't want to update the search
// result index.
inOnSearchSelect bool
}
func (self *ListContextTrait) IsListContext() {}
func (self *ListContextTrait) FocusLine(scrollIntoView bool) {
self.Context.FocusLine(scrollIntoView)
// Need to capture this in a local variable because by the time the AfterLayout function runs,
// the field will have been reset to false already
inOnSearchSelect := self.inOnSearchSelect
// Doing this at the end of the layout function because we need the view to be
// resized before we focus the line, otherwise if we're in accordion mode
// the view could be squashed and won't know how to adjust the cursor/origin.
// Also, refreshing the viewport needs to happen after the view has been resized.
self.c.AfterLayout(func() error {
oldOrigin, _ := self.GetViewTrait().ViewPortYBounds()
self.GetViewTrait().FocusPoint(
self.ModelIndexToViewIndex(self.list.GetSelectedLineIdx()), scrollIntoView)
if !inOnSearchSelect {
self.GetView().SetNearestSearchPosition()
}
selectRangeIndex, isSelectingRange := self.list.GetRangeStartIdx()
if isSelectingRange {
selectRangeIndex = self.ModelIndexToViewIndex(selectRangeIndex)
self.GetViewTrait().SetRangeSelectStart(selectRangeIndex)
} else {
self.GetViewTrait().CancelRangeSelect()
}
if self.refreshViewportOnChange {
self.refreshViewport()
} else if self.renderOnlyVisibleLines {
newOrigin, _ := self.GetViewTrait().ViewPortYBounds()
if oldOrigin != newOrigin || self.needRerenderVisibleLines {
self.refreshViewport()
}
}
return nil
})
self.setFooter()
}
func (self *ListContextTrait) refreshViewport() {
startIdx, length := self.GetViewTrait().ViewPortYBounds()
content := self.renderLines(startIdx, startIdx+length)
self.GetViewTrait().SetViewPortContent(content)
}
func (self *ListContextTrait) setFooter() {
self.GetViewTrait().SetFooter(formatListFooter(self.list.GetSelectedLineIdx(), self.list.Len()))
}
func formatListFooter(selectedLineIdx int, length int) string {
return fmt.Sprintf("%d of %d", selectedLineIdx+1, length)
}
func (self *ListContextTrait) HandleFocus(opts types.OnFocusOpts) {
self.FocusLine(opts.ScrollSelectionIntoView)
self.GetViewTrait().SetHighlight(self.list.Len() > 0)
self.Context.HandleFocus(opts)
}
func (self *ListContextTrait) HandleFocusLost(opts types.OnFocusLostOpts) {
self.GetViewTrait().SetOriginX(0)
if self.refreshViewportOnChange {
self.refreshViewport()
}
self.Context.HandleFocusLost(opts)
}
// OnFocus assumes that the content of the context has already been rendered to the view. OnRender is the function which actually renders the content to the view
func (self *ListContextTrait) HandleRender() {
self.list.ClampSelection()
if self.renderOnlyVisibleLines {
// Rendering only the visible area can save a lot of cell memory for
// those views that support it.
totalLength := self.list.Len()
if self.getNonModelItems != nil {
totalLength += len(self.getNonModelItems())
}
startIdx, length := self.GetViewTrait().ViewPortYBounds()
content := self.renderLines(startIdx, startIdx+length)
self.GetViewTrait().SetViewPortContentAndClearEverythingElse(totalLength, content)
self.needRerenderVisibleLines = false
} else {
content := self.renderLines(-1, -1)
self.GetViewTrait().SetContent(content)
}
self.c.Render()
self.setFooter()
}
func (self *ListContextTrait) OnSearchSelect(selectedLineIdx int) {
self.GetList().SetSelection(self.ViewIndexToModelIndex(selectedLineIdx))
self.inOnSearchSelect = true
self.HandleFocus(types.OnFocusOpts{})
self.inOnSearchSelect = false
}
func (self *ListContextTrait) IsItemVisible(item types.HasUrn) bool {
startIdx, length := self.GetViewTrait().ViewPortYBounds()
selectionStart := self.ViewIndexToModelIndex(startIdx)
selectionEnd := self.ViewIndexToModelIndex(startIdx + length)
for i := selectionStart; i < selectionEnd; i++ {
iterItem := self.GetList().GetItem(i)
if iterItem != nil && iterItem.URN() == item.URN() {
return true
}
}
return false
}
// By default, list contexts supports range select
func (self *ListContextTrait) RangeSelectEnabled() bool {
return true
}
func (self *ListContextTrait) RenderOnlyVisibleLines() bool {
return self.renderOnlyVisibleLines
}
func (self *ListContextTrait) SetNeedRerenderVisibleLines() {
self.needRerenderVisibleLines = true
}
func (self *ListContextTrait) TotalContentHeight() int {
result := self.list.Len()
if self.getNonModelItems != nil {
result += len(self.getNonModelItems())
}
return result
}
func (self *ListContextTrait) IndexForGotoBottom() int {
return self.list.Len() - 1
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/menu_context.go | pkg/gui/context/menu_context.go | package context
import (
"errors"
"strings"
"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/i18n"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
type MenuContext struct {
c *ContextCommon
*MenuViewModel
*ListContextTrait
}
var _ types.IListContext = (*MenuContext)(nil)
func NewMenuContext(
c *ContextCommon,
) *MenuContext {
viewModel := NewMenuViewModel(c)
return &MenuContext{
c: c,
MenuViewModel: viewModel,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Menu,
WindowName: "menu",
Key: "menu",
Kind: types.TEMPORARY_POPUP,
Focusable: true,
HasUncontrolledBounds: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: viewModel.GetDisplayStrings,
getColumnAlignments: func() []utils.Alignment { return viewModel.columnAlignment },
getNonModelItems: viewModel.GetNonModelItems,
},
c: c,
},
}
}
type MenuViewModel struct {
c *ContextCommon
menuItems []*types.MenuItem
prompt string
promptLines []string
columnAlignment []utils.Alignment
allowFilteringKeybindings bool
keybindingsTakePrecedence bool
*FilteredListViewModel[*types.MenuItem]
}
func NewMenuViewModel(c *ContextCommon) *MenuViewModel {
self := &MenuViewModel{
menuItems: nil,
c: c,
}
filterKeybindings := false
self.FilteredListViewModel = NewFilteredListViewModel(
func() []*types.MenuItem { return self.menuItems },
func(item *types.MenuItem) []string {
if filterKeybindings {
return []string{keybindings.LabelFromKey(item.Key)}
}
return item.LabelColumns
},
)
self.FilteredListViewModel.SetPreprocessFilterFunc(func(filter string) string {
if self.allowFilteringKeybindings && strings.HasPrefix(filter, "@") {
filterKeybindings = true
return filter[1:]
}
filterKeybindings = false
return filter
})
return self
}
func (self *MenuViewModel) SetMenuItems(items []*types.MenuItem, columnAlignment []utils.Alignment) {
self.menuItems = items
self.columnAlignment = columnAlignment
}
func (self *MenuViewModel) GetPrompt() string {
return self.prompt
}
func (self *MenuViewModel) SetPrompt(prompt string) {
self.prompt = prompt
self.promptLines = nil
}
func (self *MenuViewModel) GetPromptLines() []string {
return self.promptLines
}
func (self *MenuViewModel) SetPromptLines(promptLines []string) {
self.promptLines = promptLines
}
func (self *MenuViewModel) SetAllowFilteringKeybindings(allow bool) {
self.allowFilteringKeybindings = allow
}
func (self *MenuViewModel) SetKeybindingsTakePrecedence(value bool) {
self.keybindingsTakePrecedence = value
}
// TODO: move into presentation package
func (self *MenuViewModel) GetDisplayStrings(_ int, _ int) [][]string {
menuItems := self.FilteredListViewModel.GetItems()
return lo.Map(menuItems, func(item *types.MenuItem, _ int) []string {
displayStrings := item.LabelColumns
if item.DisabledReason != nil {
displayStrings[0] = style.FgDefault.SetStrikethrough().Sprint(displayStrings[0])
}
keyLabel := ""
if item.Key != nil {
keyLabel = style.FgCyan.Sprint(keybindings.LabelFromKey(item.Key))
}
checkMark := ""
switch item.Widget {
case types.MenuWidgetNone:
// do nothing
case types.MenuWidgetRadioButtonSelected:
checkMark = "(•)"
case types.MenuWidgetRadioButtonUnselected:
checkMark = "( )"
case types.MenuWidgetCheckboxSelected:
checkMark = "[✓]"
case types.MenuWidgetCheckboxUnselected:
checkMark = "[ ]"
}
displayStrings = utils.Prepend(displayStrings, keyLabel, checkMark)
return displayStrings
})
}
func (self *MenuViewModel) GetNonModelItems() []*NonModelItem {
result := []*NonModelItem{}
result = append(result, lo.Map(self.promptLines, func(line string, _ int) *NonModelItem {
return &NonModelItem{
Index: 0,
Column: 0,
Content: line,
}
})...)
// Don't display section headers when we are filtering, and the filter mode
// is fuzzy. The reason is that filtering changes the order of the items
// (they are sorted by best match), so all the sections would be messed up.
if self.FilteredListViewModel.IsFiltering() && self.c.UserConfig().Gui.UseFuzzySearch() {
return result
}
menuItems := self.FilteredListViewModel.GetItems()
var prevSection *types.MenuSection
for i, menuItem := range menuItems {
if menuItem.Section != nil && menuItem.Section != prevSection {
if prevSection != nil {
result = append(result, &NonModelItem{
Index: i,
Column: 1,
Content: "",
})
}
result = append(result, &NonModelItem{
Index: i,
Column: 1,
Content: style.FgGreen.SetBold().Sprintf("--- %s ---", menuItem.Section.Title),
})
prevSection = menuItem.Section
}
}
return result
}
func (self *MenuContext) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {
basicBindings := self.ListContextTrait.GetKeybindings(opts)
menuItemsWithKeys := lo.Filter(self.menuItems, func(item *types.MenuItem, _ int) bool {
return item.Key != nil
})
menuItemBindings := lo.Map(menuItemsWithKeys, func(item *types.MenuItem, _ int) *types.Binding {
return &types.Binding{
Key: item.Key,
Handler: func() error { return self.OnMenuPress(item) },
}
})
if self.keybindingsTakePrecedence {
// This is used for all normal menus except the keybindings menu. In this case we want the
// bindings of the menu items to have higher precedence than the builtin bindings; this
// allows assigning a keybinding to a menu item that overrides a non-essential binding such
// as 'j', 'k', 'H', 'L', etc. This is safe to do because the essential bindings such as
// confirm and return have already been removed from the menu items in this case.
return append(menuItemBindings, basicBindings...)
}
// For the keybindings menu we didn't remove the essential bindings from the menu items, because
// it is important to see all bindings (as a cheat sheet for what the keys are when the menu is
// not open). Therefore we want the essential bindings to have higher precedence than the menu
// item bindings.
return append(basicBindings, menuItemBindings...)
}
func (self *MenuContext) OnMenuPress(selectedItem *types.MenuItem) error {
if selectedItem != nil && selectedItem.DisabledReason != nil {
if selectedItem.DisabledReason.ShowErrorInPanel {
return errors.New(selectedItem.DisabledReason.Text)
}
self.c.ErrorToast(self.c.Tr.DisabledMenuItemPrefix + selectedItem.DisabledReason.Text)
return nil
}
self.c.Context().Pop()
if selectedItem == nil {
return nil
}
if err := selectedItem.OnPress(); err != nil {
return err
}
return nil
}
// There is currently no need to use range-select in a menu so we're disabling it.
func (self *MenuContext) RangeSelectEnabled() bool {
return false
}
func (self *MenuContext) FilterPrefix(tr *i18n.TranslationSet) string {
if self.allowFilteringKeybindings {
return tr.FilterPrefixMenu
}
return self.FilteredListViewModel.FilterPrefix(tr)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/simple_context.go | pkg/gui/context/simple_context.go | package context
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type SimpleContext struct {
*BaseContext
handleRenderFunc func()
}
func NewSimpleContext(baseContext *BaseContext) *SimpleContext {
return &SimpleContext{
BaseContext: baseContext,
}
}
var _ types.Context = &SimpleContext{}
// A Display context only renders a view. It has no keybindings and is not focusable.
func NewDisplayContext(key types.ContextKey, view *gocui.View, windowName string) types.Context {
return NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.DISPLAY_CONTEXT,
Key: key,
View: view,
WindowName: windowName,
Focusable: false,
Transient: false,
}),
)
}
func (self *SimpleContext) HandleFocus(opts types.OnFocusOpts) {
if self.highlightOnFocus {
self.GetViewTrait().SetHighlight(true)
}
for _, fn := range self.onFocusFns {
fn(opts)
}
if self.onRenderToMainFn != nil {
self.onRenderToMainFn()
}
}
func (self *SimpleContext) HandleFocusLost(opts types.OnFocusLostOpts) {
self.GetViewTrait().SetHighlight(false)
self.view.SetOriginX(0)
for _, fn := range self.onFocusLostFns {
fn(opts)
}
}
func (self *SimpleContext) FocusLine(scrollIntoView bool) {
}
func (self *SimpleContext) HandleRender() {
if self.handleRenderFunc != nil {
self.handleRenderFunc()
}
}
func (self *SimpleContext) SetHandleRenderFunc(f func()) {
self.handleRenderFunc = f
}
func (self *SimpleContext) HandleRenderToMain() {
if self.onRenderToMainFn != nil {
self.onRenderToMainFn()
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/setup.go | pkg/gui/context/setup.go | package context
import "github.com/jesseduffield/lazygit/pkg/gui/types"
func NewContextTree(c *ContextCommon) *ContextTree {
commitFilesContext := NewCommitFilesContext(c)
return &ContextTree{
Global: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.GLOBAL_CONTEXT,
View: nil, // TODO: see if this breaks anything
WindowName: "",
Key: GLOBAL_CONTEXT_KEY,
Focusable: false,
HasUncontrolledBounds: true, // setting to true because the global context doesn't even have a view
}),
),
Status: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.SIDE_CONTEXT,
View: c.Views().Status,
WindowName: "status",
Key: STATUS_CONTEXT_KEY,
Focusable: true,
}),
),
Files: NewWorkingTreeContext(c),
Submodules: NewSubmodulesContext(c),
Menu: NewMenuContext(c),
Remotes: NewRemotesContext(c),
Worktrees: NewWorktreesContext(c),
RemoteBranches: NewRemoteBranchesContext(c),
LocalCommits: NewLocalCommitsContext(c),
CommitFiles: commitFilesContext,
ReflogCommits: NewReflogCommitsContext(c),
SubCommits: NewSubCommitsContext(c),
Branches: NewBranchesContext(c),
Tags: NewTagsContext(c),
Stash: NewStashContext(c),
Suggestions: NewSuggestionsContext(c),
Normal: NewMainContext(c.Views().Main, "main", NORMAL_MAIN_CONTEXT_KEY, c),
NormalSecondary: NewMainContext(c.Views().Secondary, "secondary", NORMAL_SECONDARY_CONTEXT_KEY, c),
Staging: NewPatchExplorerContext(
c.Views().Staging,
"main",
STAGING_MAIN_CONTEXT_KEY,
func() []int { return nil },
c,
),
StagingSecondary: NewPatchExplorerContext(
c.Views().StagingSecondary,
"secondary",
STAGING_SECONDARY_CONTEXT_KEY,
func() []int { return nil },
c,
),
CustomPatchBuilder: NewPatchExplorerContext(
c.Views().PatchBuilding,
"main",
PATCH_BUILDING_MAIN_CONTEXT_KEY,
func() []int {
filename := commitFilesContext.GetSelectedPath()
includedLineIndices, err := c.Git().Patch.PatchBuilder.GetFileIncLineIndices(filename)
if err != nil {
c.Log.Error(err)
return nil
}
return includedLineIndices
},
c,
),
CustomPatchBuilderSecondary: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.MAIN_CONTEXT,
View: c.Views().PatchBuildingSecondary,
WindowName: "secondary",
Key: PATCH_BUILDING_SECONDARY_CONTEXT_KEY,
Focusable: false,
}),
),
MergeConflicts: NewMergeConflictsContext(
c,
),
Confirmation: NewConfirmationContext(c),
Prompt: NewPromptContext(c),
CommitMessage: NewCommitMessageContext(c),
CommitDescription: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.PERSISTENT_POPUP,
View: c.Views().CommitDescription,
WindowName: "commitDescription",
Key: COMMIT_DESCRIPTION_CONTEXT_KEY,
Focusable: true,
HasUncontrolledBounds: true,
}),
),
Search: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.PERSISTENT_POPUP,
View: c.Views().Search,
WindowName: "search",
Key: SEARCH_CONTEXT_KEY,
Focusable: true,
}),
),
CommandLog: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.EXTRAS_CONTEXT,
View: c.Views().Extras,
WindowName: "extras",
Key: COMMAND_LOG_CONTEXT_KEY,
Focusable: true,
}),
),
Snake: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.SIDE_CONTEXT,
View: c.Views().Snake,
WindowName: "files",
Key: SNAKE_CONTEXT_KEY,
Focusable: true,
}),
),
Options: NewDisplayContext(OPTIONS_CONTEXT_KEY, c.Views().Options, "options"),
AppStatus: NewDisplayContext(APP_STATUS_CONTEXT_KEY, c.Views().AppStatus, "appStatus"),
SearchPrefix: NewDisplayContext(SEARCH_PREFIX_CONTEXT_KEY, c.Views().SearchPrefix, "searchPrefix"),
Information: NewDisplayContext(INFORMATION_CONTEXT_KEY, c.Views().Information, "information"),
Limit: NewDisplayContext(LIMIT_CONTEXT_KEY, c.Views().Limit, "limit"),
StatusSpacer1: NewDisplayContext(STATUS_SPACER1_CONTEXT_KEY, c.Views().StatusSpacer1, "statusSpacer1"),
StatusSpacer2: NewDisplayContext(STATUS_SPACER2_CONTEXT_KEY, c.Views().StatusSpacer2, "statusSpacer2"),
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/merge_conflicts_context.go | pkg/gui/context/merge_conflicts_context.go | package context
import (
"math"
"github.com/jesseduffield/lazygit/pkg/gui/mergeconflicts"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/sasha-s/go-deadlock"
)
type MergeConflictsContext struct {
types.Context
viewModel *ConflictsViewModel
c *ContextCommon
mutex deadlock.Mutex
}
type ConflictsViewModel struct {
state *mergeconflicts.State
// userVerticalScrolling tells us if the user has started scrolling through the file themselves
// in which case we won't auto-scroll to a conflict.
userVerticalScrolling bool
}
func NewMergeConflictsContext(
c *ContextCommon,
) *MergeConflictsContext {
viewModel := &ConflictsViewModel{
state: mergeconflicts.NewState(),
userVerticalScrolling: false,
}
return &MergeConflictsContext{
viewModel: viewModel,
Context: NewSimpleContext(
NewBaseContext(NewBaseContextOpts{
Kind: types.MAIN_CONTEXT,
View: c.Views().MergeConflicts,
WindowName: "main",
Key: MERGE_CONFLICTS_CONTEXT_KEY,
Focusable: true,
HighlightOnFocus: true,
}),
),
c: c,
}
}
func (self *MergeConflictsContext) GetState() *mergeconflicts.State {
return self.viewModel.state
}
func (self *MergeConflictsContext) SetState(state *mergeconflicts.State) {
self.viewModel.state = state
}
func (self *MergeConflictsContext) GetMutex() *deadlock.Mutex {
return &self.mutex
}
func (self *MergeConflictsContext) SetUserScrolling(isScrolling bool) {
self.viewModel.userVerticalScrolling = isScrolling
}
func (self *MergeConflictsContext) IsUserScrolling() bool {
return self.viewModel.userVerticalScrolling
}
func (self *MergeConflictsContext) RenderAndFocus() {
self.setContent()
self.FocusSelection()
self.c.Render()
}
func (self *MergeConflictsContext) Render() error {
self.setContent()
self.c.Render()
return nil
}
func (self *MergeConflictsContext) GetContentToRender() string {
if self.GetState() == nil {
return ""
}
return mergeconflicts.ColoredConflictFile(self.GetState())
}
func (self *MergeConflictsContext) setContent() {
self.GetView().SetContent(self.GetContentToRender())
}
func (self *MergeConflictsContext) FocusSelection() {
if !self.IsUserScrolling() {
self.GetView().SetOriginY(self.GetOriginY())
}
self.SetSelectedLineRange()
}
func (self *MergeConflictsContext) SetSelectedLineRange() {
startIdx, endIdx := self.GetState().GetSelectedRange()
view := self.GetView()
originY := view.OriginY()
// As far as the view is concerned, we are always selecting a range
view.SetRangeSelectStart(startIdx)
view.SetCursorY(endIdx - originY)
}
func (self *MergeConflictsContext) GetOriginY() int {
view := self.GetView()
conflictMiddle := self.GetState().GetConflictMiddle()
return int(math.Max(0, float64(conflictMiddle-(view.InnerHeight()/2))))
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/submodules_context.go | pkg/gui/context/submodules_context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
type SubmodulesContext struct {
*FilteredListViewModel[*models.SubmoduleConfig]
*ListContextTrait
}
var _ types.IListContext = (*SubmodulesContext)(nil)
func NewSubmodulesContext(c *ContextCommon) *SubmodulesContext {
viewModel := NewFilteredListViewModel(
func() []*models.SubmoduleConfig { return c.Model().Submodules },
func(submodule *models.SubmoduleConfig) []string {
return []string{submodule.FullName()}
},
)
getDisplayStrings := func(_ int, _ int) [][]string {
return presentation.GetSubmoduleListDisplayStrings(viewModel.GetItems())
}
return &SubmodulesContext{
FilteredListViewModel: viewModel,
ListContextTrait: &ListContextTrait{
Context: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
View: c.Views().Submodules,
WindowName: "files",
Key: SUBMODULES_CONTEXT_KEY,
Kind: types.SIDE_CONTEXT,
Focusable: true,
})),
ListRenderer: ListRenderer{
list: viewModel,
getDisplayStrings: getDisplayStrings,
},
c: c,
},
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context/context.go | pkg/gui/context/context.go | package context
import (
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
const (
// used as a nil value when passing a context key as an arg
NO_CONTEXT types.ContextKey = "none"
GLOBAL_CONTEXT_KEY types.ContextKey = "global"
STATUS_CONTEXT_KEY types.ContextKey = "status"
SNAKE_CONTEXT_KEY types.ContextKey = "snake"
FILES_CONTEXT_KEY types.ContextKey = "files"
LOCAL_BRANCHES_CONTEXT_KEY types.ContextKey = "localBranches"
REMOTES_CONTEXT_KEY types.ContextKey = "remotes"
WORKTREES_CONTEXT_KEY types.ContextKey = "worktrees"
REMOTE_BRANCHES_CONTEXT_KEY types.ContextKey = "remoteBranches"
TAGS_CONTEXT_KEY types.ContextKey = "tags"
LOCAL_COMMITS_CONTEXT_KEY types.ContextKey = "commits"
REFLOG_COMMITS_CONTEXT_KEY types.ContextKey = "reflogCommits"
SUB_COMMITS_CONTEXT_KEY types.ContextKey = "subCommits"
COMMIT_FILES_CONTEXT_KEY types.ContextKey = "commitFiles"
STASH_CONTEXT_KEY types.ContextKey = "stash"
NORMAL_MAIN_CONTEXT_KEY types.ContextKey = "normal"
NORMAL_SECONDARY_CONTEXT_KEY types.ContextKey = "normalSecondary"
STAGING_MAIN_CONTEXT_KEY types.ContextKey = "staging"
STAGING_SECONDARY_CONTEXT_KEY types.ContextKey = "stagingSecondary"
PATCH_BUILDING_MAIN_CONTEXT_KEY types.ContextKey = "patchBuilding"
PATCH_BUILDING_SECONDARY_CONTEXT_KEY types.ContextKey = "patchBuildingSecondary"
MERGE_CONFLICTS_CONTEXT_KEY types.ContextKey = "mergeConflicts"
// these shouldn't really be needed for anything but I'm giving them unique keys nonetheless
OPTIONS_CONTEXT_KEY types.ContextKey = "options"
APP_STATUS_CONTEXT_KEY types.ContextKey = "appStatus"
SEARCH_PREFIX_CONTEXT_KEY types.ContextKey = "searchPrefix"
INFORMATION_CONTEXT_KEY types.ContextKey = "information"
LIMIT_CONTEXT_KEY types.ContextKey = "limit"
STATUS_SPACER1_CONTEXT_KEY types.ContextKey = "statusSpacer1"
STATUS_SPACER2_CONTEXT_KEY types.ContextKey = "statusSpacer2"
MENU_CONTEXT_KEY types.ContextKey = "menu"
CONFIRMATION_CONTEXT_KEY types.ContextKey = "confirmation"
PROMPT_CONTEXT_KEY types.ContextKey = "prompt"
SEARCH_CONTEXT_KEY types.ContextKey = "search"
COMMIT_MESSAGE_CONTEXT_KEY types.ContextKey = "commitMessage"
COMMIT_DESCRIPTION_CONTEXT_KEY types.ContextKey = "commitDescription"
SUBMODULES_CONTEXT_KEY types.ContextKey = "submodules"
SUGGESTIONS_CONTEXT_KEY types.ContextKey = "suggestions"
COMMAND_LOG_CONTEXT_KEY types.ContextKey = "cmdLog"
)
var AllContextKeys = []types.ContextKey{
GLOBAL_CONTEXT_KEY,
STATUS_CONTEXT_KEY,
FILES_CONTEXT_KEY,
LOCAL_BRANCHES_CONTEXT_KEY,
REMOTES_CONTEXT_KEY,
WORKTREES_CONTEXT_KEY,
REMOTE_BRANCHES_CONTEXT_KEY,
TAGS_CONTEXT_KEY,
LOCAL_COMMITS_CONTEXT_KEY,
REFLOG_COMMITS_CONTEXT_KEY,
SUB_COMMITS_CONTEXT_KEY,
COMMIT_FILES_CONTEXT_KEY,
STASH_CONTEXT_KEY,
NORMAL_MAIN_CONTEXT_KEY,
NORMAL_SECONDARY_CONTEXT_KEY,
STAGING_MAIN_CONTEXT_KEY,
STAGING_SECONDARY_CONTEXT_KEY,
PATCH_BUILDING_MAIN_CONTEXT_KEY,
PATCH_BUILDING_SECONDARY_CONTEXT_KEY,
MERGE_CONFLICTS_CONTEXT_KEY,
MENU_CONTEXT_KEY,
CONFIRMATION_CONTEXT_KEY,
PROMPT_CONTEXT_KEY,
SEARCH_CONTEXT_KEY,
COMMIT_MESSAGE_CONTEXT_KEY,
SUBMODULES_CONTEXT_KEY,
SUGGESTIONS_CONTEXT_KEY,
COMMAND_LOG_CONTEXT_KEY,
}
type ContextTree struct {
Global types.Context
Status types.Context
Snake types.Context
Files *WorkingTreeContext
Menu *MenuContext
Branches *BranchesContext
Tags *TagsContext
LocalCommits *LocalCommitsContext
CommitFiles *CommitFilesContext
Remotes *RemotesContext
Worktrees *WorktreesContext
Submodules *SubmodulesContext
RemoteBranches *RemoteBranchesContext
ReflogCommits *ReflogCommitsContext
SubCommits *SubCommitsContext
Stash *StashContext
Suggestions *SuggestionsContext
Normal *MainContext
NormalSecondary *MainContext
Staging *PatchExplorerContext
StagingSecondary *PatchExplorerContext
CustomPatchBuilder *PatchExplorerContext
CustomPatchBuilderSecondary types.Context
MergeConflicts *MergeConflictsContext
Confirmation *ConfirmationContext
Prompt *PromptContext
CommitMessage *CommitMessageContext
CommitDescription types.Context
CommandLog types.Context
// display contexts
AppStatus types.Context
Options types.Context
SearchPrefix types.Context
Search types.Context
Information types.Context
Limit types.Context
StatusSpacer1 types.Context
StatusSpacer2 types.Context
}
// the order of this decides which context is initially at the top of its window
func (self *ContextTree) Flatten() []types.Context {
return []types.Context{
self.Global,
self.Status,
self.Snake,
self.Submodules,
self.Worktrees,
self.Files,
self.SubCommits,
self.Remotes,
self.RemoteBranches,
self.Tags,
self.Branches,
self.CommitFiles,
self.ReflogCommits,
self.LocalCommits,
self.Stash,
self.Menu,
self.Confirmation,
self.Prompt,
self.CommitMessage,
self.CommitDescription,
self.MergeConflicts,
self.StagingSecondary,
self.Staging,
self.CustomPatchBuilderSecondary,
self.CustomPatchBuilder,
self.NormalSecondary,
self.Normal,
self.Suggestions,
self.CommandLog,
self.AppStatus,
self.Options,
self.SearchPrefix,
self.Search,
self.Information,
self.Limit,
self.StatusSpacer1,
self.StatusSpacer2,
}
}
type TabView struct {
Tab string
ViewName string
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.