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/i18n/english.go
pkg/i18n/english.go
/* Todo list when making a new translation - Copy this file and rename it to the language you want to translate to like someLanguage.go - Change the EnglishTranslationSet() name to the language you want to translate to like SomeLanguageTranslationSet() - Add an entry of someLanguage in GetTranslationSets() - Remove this todo and the about section */ package i18n type TranslationSet struct { NotEnoughSpace string DiffTitle string FilesTitle string BranchesTitle string CommitsTitle string StashTitle string SnakeTitle string EasterEgg string UnstagedChanges string StagedChanges string StagingTitle string MergingTitle string NormalTitle string LogTitle string LogXOfYTitle string CommitSummary string CredentialsUsername string CredentialsPassword string CredentialsPassphrase string CredentialsPIN string CredentialsToken string PassUnameWrong string Commit string CommitTooltip string AmendLastCommit string AmendLastCommitTitle string SureToAmend string NoCommitToAmend string CommitChangesWithEditor string FindBaseCommitForFixup string FindBaseCommitForFixupTooltip string NoBaseCommitsFound string MultipleBaseCommitsFoundStaged string MultipleBaseCommitsFoundUnstaged string BaseCommitIsAlreadyOnMainBranch string BaseCommitIsNotInCurrentView string HunksWithOnlyAddedLinesWarning string StatusTitle string GlobalTitle string Execute string Stage string StageTooltip string ToggleStagedAll string ToggleStagedAllTooltip string ToggleTreeView string ToggleTreeViewTooltip string OpenDiffTool string OpenMergeTool string Refresh string RefreshTooltip string Push string Pull string PushTooltip string PullTooltip string FileFilter string CopyToClipboardMenu string CopyFileName string CopyRelativeFilePath string CopyAbsoluteFilePath string CopyFileDiffTooltip string CopySelectedDiff string CopyAllFilesDiff string CopyFileContent string NoContentToCopyError string FileNameCopiedToast string FilePathCopiedToast string FileDiffCopiedToast string AllFilesDiffCopiedToast string FileContentCopiedToast string FilterStagedFiles string FilterUnstagedFiles string FilterTrackedFiles string FilterUntrackedFiles string NoFilter string FilterLabelStagedFiles string FilterLabelUnstagedFiles string FilterLabelTrackedFiles string FilterLabelUntrackedFiles string FilterLabelConflictingFiles string MergeConflictsTitle string MergeConflictDescription_DD string MergeConflictDescription_AU string MergeConflictDescription_UA string MergeConflictDescription_DU string MergeConflictDescription_UD string MergeConflictIncomingDiff string MergeConflictCurrentDiff string MergeConflictPressEnterToResolve string MergeConflictKeepFile string MergeConflictDeleteFile string Checkout string CheckoutTooltip string CantCheckoutBranchWhilePulling string TagCheckoutTooltip string RemoteBranchCheckoutTooltip string CantPullOrPushSameBranchTwice string NoChangedFiles string SoftReset string AlreadyCheckedOutBranch string SureForceCheckout string ForceCheckoutBranch string BranchName string NewBranchNameBranchOff string CantDeleteCheckOutBranch string DeleteBranchTitle string DeleteBranchesTitle string DeleteLocalBranch string DeleteLocalBranches string DeleteRemoteBranchPrompt string DeleteRemoteBranchesPrompt string DeleteLocalAndRemoteBranchPrompt string DeleteLocalAndRemoteBranchesPrompt string ForceDeleteBranchTitle string ForceDeleteBranchMessage string ForceDeleteBranchesMessage string RebaseBranch string RebaseBranchTooltip string CantRebaseOntoSelf string CantMergeBranchIntoItself string ForceCheckout string ForceCheckoutTooltip string CheckoutByName string CheckoutByNameTooltip string CheckoutPreviousBranch string RemoteBranchCheckoutTitle string RemoteBranchCheckoutPrompt string CheckoutTypeNewBranch string CheckoutTypeNewBranchTooltip string CheckoutTypeDetachedHead string CheckoutTypeDetachedHeadTooltip string NewBranch string NewBranchFromStashTooltip string MoveCommitsToNewBranch string MoveCommitsToNewBranchTooltip string MoveCommitsToNewBranchFromMainPrompt string MoveCommitsToNewBranchMenuPrompt string MoveCommitsToNewBranchFromBaseItem string MoveCommitsToNewBranchStackedItem string CannotMoveCommitsFromDetachedHead string CannotMoveCommitsNoUpstream string CannotMoveCommitsBehindUpstream string CannotMoveCommitsNoUnpushedCommits string NoBranchesThisRepo string CommitWithoutMessageErr string Close string CloseCancel string Confirm string Quit string SquashTooltip string CannotSquashOrFixupFirstCommit string CannotSquashOrFixupMergeCommit string Fixup string FixupTooltip string SureFixupThisCommit string SureSquashThisCommit string Squash string PickCommitTooltip string Pick string Edit string Revert string RevertCommitTooltip string Reword string CommitRewordTooltip string DropCommit string DropCommitTooltip string MoveDownCommit string MoveUpCommit string CannotMoveAnyFurther string CannotMoveMergeCommit string EditCommit string EditCommitTooltip string AmendCommitTooltip string Amend string ResetAuthor string ResetAuthorTooltip string SetAuthor string SetAuthorTooltip string AddCoAuthor string AmendCommitAttribute string AmendCommitAttributeTooltip string SetAuthorPromptTitle string AddCoAuthorPromptTitle string AddCoAuthorTooltip string RewordCommitEditor string NoCommitsThisBranch string UpdateRefHere string ExecCommandHere string Error string Undo string UndoReflog string RedoReflog string UndoTooltip string RedoTooltip string UndoMergeResolveTooltip string DiscardAllTooltip string DiscardUnstagedTooltip string DiscardUnstagedDisabled string Pop string StashPopTooltip string Drop string StashDropTooltip string Apply string StashApplyTooltip string NoStashEntries string StashDrop string SureDropStashEntry string StashPop string SurePopStashEntry string StashApply string SureApplyStashEntry string NoTrackedStagedFilesStash string NoFilesToStash string StashChanges string RenameStash string RenameStashPrompt string OpenConfig string EditConfig string ForcePush string ForcePushPrompt string ForcePushDisabled string UpdatesRejected string UpdatesRejectedAndForcePushDisabled string CheckForUpdate string CheckingForUpdates string UpdateAvailableTitle string UpdateAvailable string UpdateInProgressWaitingStatus string UpdateCompletedTitle string UpdateCompleted string FailedToRetrieveLatestVersionErr string OnLatestVersionErr string MajorVersionErr string CouldNotFindBinaryErr string UpdateFailedErr string ConfirmQuitDuringUpdateTitle string ConfirmQuitDuringUpdate string IntroPopupMessage string NonReloadableConfigWarningTitle string NonReloadableConfigWarning string GitconfigParseErr string EditFile string EditFileTooltip string OpenFile string OpenFileTooltip string OpenInEditor string IgnoreFile string ExcludeFile string RefreshFiles string FocusMainView string Merge string MergeBranchTooltip string RegularMergeFastForward string RegularMergeFastForwardTooltip string CannotFastForwardMerge string RegularMergeNonFastForward string RegularMergeNonFastForwardTooltip string SquashMergeUncommitted string SquashMergeUncommittedTooltip string SquashMergeCommitted string SquashMergeCommittedTooltip string ConfirmQuit string SwitchRepo string AllBranchesLogGraph string UnsupportedGitService string CopyPullRequestURL string NoBranchOnRemote string Fetch string FetchTooltip string CollapseAll string CollapseAllTooltip string ExpandAll string ExpandAllTooltip string DisabledInFlatView string FileEnter string FileEnterTooltip string StageSelectionTooltip string DiscardSelection string DiscardSelectionTooltip string ToggleSelectHunk string SelectHunk string SelectLineByLine string ToggleSelectHunkTooltip string HunkStagingHint string ToggleSelectionForPatch string EditHunk string EditHunkTooltip string ToggleStagingView string ToggleStagingViewTooltip string ReturnToFilesPanel string FastForward string FastForwardTooltip string FastForwarding string FoundConflictsTitle string ViewConflictsMenuItem string AbortMenuItem string PickHunk string PickAllHunks string ViewMergeRebaseOptions string ViewMergeRebaseOptionsTooltip string ViewMergeOptions string ViewRebaseOptions string ViewCherryPickOptions string ViewRevertOptions string NotMergingOrRebasing string AlreadyRebasing string RecentRepos string MergeOptionsTitle string RebaseOptionsTitle string CherryPickOptionsTitle string RevertOptionsTitle string CommitSummaryTitle string CommitDescriptionTitle string CommitDescriptionSubTitle string CommitDescriptionFooter string CommitDescriptionFooterTwoBindings string CommitHooksDisabledSubTitle string LocalBranchesTitle string SearchTitle string TagsTitle string MenuTitle string CommitMenuTitle string RemotesTitle string RemoteBranchesTitle string PatchBuildingTitle string InformationTitle string SecondaryTitle string ReflogCommitsTitle string ConflictsResolved string Continue string UnstagedFilesAfterConflictsResolved string RebasingTitle string RebasingFromBaseCommitTitle string SimpleRebase string InteractiveRebase string RebaseOntoBaseBranch string InteractiveRebaseTooltip string RebaseOntoBaseBranchTooltip string MustSelectTodoCommits string FwdNoUpstream string FwdNoLocalUpstream string FwdCommitsToPush string PullRequestNoUpstream string ErrorOccurred string ConflictLabel string PendingRebaseTodosSectionHeader string PendingCherryPicksSectionHeader string PendingRevertsSectionHeader string CommitsSectionHeader string YouDied string RewordNotSupported string ChangingThisActionIsNotAllowed string NotAllowedMidCherryPickOrRevert string PickIsOnlyAllowedDuringRebase string DroppingMergeRequiresSingleSelection string CherryPickCopy string CherryPickCopyTooltip string PasteCommits string SureCherryPick string CherryPick string CannotCherryPickNonCommit string Donate string AskQuestion string PrevHunk string NextHunk string PrevConflict string NextConflict string SelectPrevHunk string SelectNextHunk string ScrollDown string ScrollUp string ScrollUpMainWindow string ScrollDownMainWindow string SuspendApp string CannotSuspendApp string AmendCommitTitle string AmendCommitPrompt string AmendCommitWithConflictsMenuPrompt string AmendCommitWithConflictsContinue string AmendCommitWithConflictsAmend string DropCommitTitle string DropCommitPrompt string DropUpdateRefPrompt string DropMergeCommitPrompt string PullingStatus string PushingStatus string FetchingStatus string SquashingStatus string FixingStatus string DeletingStatus string DroppingStatus string MovingStatus string RebasingStatus string MergingStatus string LowercaseRebasingStatus string LowercaseMergingStatus string LowercaseCherryPickingStatus string LowercaseRevertingStatus string AmendingStatus string CherryPickingStatus string UndoingStatus string RedoingStatus string CheckingOutStatus string CommittingStatus string RewordingStatus string RevertingStatus string CreatingFixupCommitStatus string MovingCommitsToNewBranchStatus string CommitFiles string SubCommitsDynamicTitle string CommitFilesDynamicTitle string RemoteBranchesDynamicTitle string ViewItemFiles string CommitFilesTitle string CheckoutCommitFileTooltip string CannotCheckoutWithModifiedFilesErr string CanOnlyDiscardFromLocalCommits string Remove string DiscardOldFileChangeTooltip string DiscardFileChangesTitle string DiscardFileChangesPrompt string DisabledForGPG string CreateRepo string BareRepo string InitialBranch string NoRecentRepositories string IncorrectNotARepository string AutoStashTitle string AutoStashPrompt string AutoStashForUndo string AutoStashForCheckout string AutoStashForNewBranch string AutoStashForMovingPatchToIndex string AutoStashForCherryPicking string AutoStashForReverting string Discard string DiscardChangesTitle string DiscardFileChangesTooltip string Cancel string DiscardAllChanges string DiscardUnstagedChanges string DiscardAllChangesToAllFiles string DiscardAnyUnstagedChanges string DiscardUntrackedFiles string DiscardStagedChanges string HardReset string BranchDeleteTooltip string TagDeleteTooltip string Delete string Reset string ResetTooltip string ViewResetOptions string FileResetOptionsTooltip string CreateFixupCommit string CreateFixupCommitTooltip string CreateAmendCommit string FixupMenu_Fixup string FixupMenu_FixupTooltip string FixupMenu_AmendWithChanges string FixupMenu_AmendWithChangesTooltip string FixupMenu_AmendWithoutChanges string FixupMenu_AmendWithoutChangesTooltip string SquashAboveCommitsTooltip string SquashCommitsAboveSelectedTooltip string SquashCommitsInCurrentBranchTooltip string SquashAboveCommits string SquashCommitsInCurrentBranch string SquashCommitsAboveSelectedCommit string CannotSquashCommitsInCurrentBranch string ExecuteShellCommand string ExecuteShellCommandTooltip string ShellCommand string CommitChangesWithoutHook string ResetTo string ResetSoftTooltip string ResetMixedTooltip string ResetHardTooltip string ResetHardConfirmation string PressEnterToReturn string ViewStashOptions string ViewStashOptionsTooltip string Stash string StashTooltip string StashAllChanges string StashStagedChanges string StashAllChangesKeepIndex string StashUnstagedChanges string StashIncludeUntrackedChanges string StashOptions string NotARepository string WorkingDirectoryDoesNotExist string ScrollLeft string ScrollRight string DiscardPatch string DiscardPatchConfirm string CantPatchWhileRebasingError string ToggleAddToPatch string ToggleAddToPatchTooltip string ToggleAllInPatch string ToggleAllInPatchTooltip string UpdatingPatch string ViewPatchOptions string PatchOptionsTitle string NoPatchError string EmptyPatchError string EnterCommitFile string EnterCommitFileTooltip string ExitCustomPatchBuilder string ExitFocusedMainView string EnterUpstream string InvalidUpstream string NewRemote string NewRemoteName string NewRemoteUrl string AddForkRemote string AddForkRemoteUsername string AddForkRemoteTooltip string IncompatibleForkAlreadyExistsError string NoOriginRemote string ViewBranches string EditRemoteName string EditRemoteUrl string RemoveRemote string RemoveRemoteTooltip string RemoveRemotePrompt string DeleteRemoteBranch string DeleteRemoteBranches string DeleteRemoteBranchTooltip string DeleteLocalAndRemoteBranch string DeleteLocalAndRemoteBranches string SetAsUpstream string SetAsUpstreamTooltip string SetUpstream string UnsetUpstream string ViewDivergenceFromUpstream string ViewDivergenceFromBaseBranch string CouldNotDetermineBaseBranch string DivergenceSectionHeaderLocal string DivergenceSectionHeaderRemote string ViewUpstreamResetOptions string ViewUpstreamResetOptionsTooltip string ViewUpstreamRebaseOptions string ViewUpstreamRebaseOptionsTooltip string UpstreamGenericName string SetUpstreamTitle string SetUpstreamMessage string EditRemoteTooltip string TagCommit string TagCommitTooltip string TagNameTitle string TagMessageTitle string LightweightTag string AnnotatedTag string DeleteTagTitle string DeleteLocalTag string DeleteRemoteTag string DeleteLocalAndRemoteTag string SelectRemoteTagUpstream string DeleteRemoteTagPrompt string DeleteLocalAndRemoteTagPrompt string RemoteTagDeletedMessage string PushTagTitle string PushTag string PushTagTooltip string NewTag string NewTagTooltip string CreatingTag string ForceTag string ForceTagPrompt string FetchRemoteTooltip string CheckoutCommitTooltip string NoBranchesFoundAtCommitTooltip string GitFlowOptions string NotAGitFlowBranch string NewBranchNamePrompt string IgnoreTracked string ExcludeTracked string IgnoreTrackedPrompt string ExcludeTrackedPrompt string ViewResetToUpstreamOptions string NextScreenMode string PrevScreenMode string CyclePagers string CyclePagersTooltip string CyclePagersDisabledReason string StartSearch string StartFilter string Keybindings string KeybindingsLegend string KeybindingsMenuSectionLocal string KeybindingsMenuSectionGlobal string KeybindingsMenuSectionNavigation string RenameBranch string Upstream string BranchUpstreamOptionsTitle string ViewBranchUpstreamOptions string ViewBranchUpstreamOptionsTooltip string UpstreamNotSetError string UpstreamsNotSetError string NewGitFlowBranchPrompt string RenameBranchWarning string OpenKeybindingsMenu string ResetCherryPick string ResetCherryPickShort string NextTab string PrevTab string CantUndoWhileRebasing string CantRedoWhileRebasing string MustStashWarning string MustStashTitle string ConfirmationTitle string PromptTitle string PromptInputCannotBeEmptyToast string PrevPage string NextPage string GotoTop string GotoBottom string FilteringBy string ResetInParentheses string OpenFilteringMenu string OpenFilteringMenuTooltip string FilterBy string ExitFilterMode string FilterPathOption string FilterAuthorOption string EnterFileName string EnterAuthor string FilteringMenuTitle string WillCancelExistingFilterTooltip string MustExitFilterModeTitle string MustExitFilterModePrompt string Diff string EnterRefToDiff string EnterRefName string ExitDiffMode string DiffingMenuTitle string SwapDiff string ViewDiffingOptions string ViewDiffingOptionsTooltip string CancelDiffingMode string OpenCommandLogMenu string OpenCommandLogMenuTooltip string ShowingGitDiff string ShowingDiffForRange string CommitDiff string CopyCommitHashToClipboard string CommitHash string CommitURL string PasteCommitMessageFromClipboard string SurePasteCommitMessage string CommitMessage string CommitMessageBody string CommitSubject string CommitAuthor string CommitTags string CopyCommitAttributeToClipboard string CopyCommitAttributeToClipboardTooltip string CopyBranchNameToClipboard string CopyTagToClipboard string CopyPathToClipboard string CommitPrefixPatternError string CopySelectedTextToClipboard string NoFilesStagedTitle string NoFilesStagedPrompt string BranchNotFoundTitle string BranchNotFoundPrompt string BranchUnknown string DiscardChangeTitle string DiscardChangePrompt string CreateNewBranchFromCommit string BuildingPatch string ViewCommits string MinGitVersionError string RunningCustomCommandStatus string SubmoduleStashAndReset string AndResetSubmodules string EnterSubmoduleTooltip string BackToParentRepo string Enter string CopySubmoduleNameToClipboard string RemoveSubmodule string RemoveSubmoduleTooltip string RemoveSubmodulePrompt string ResettingSubmoduleStatus string NewSubmoduleName string NewSubmoduleUrl string NewSubmodulePath string NewSubmodule string AddingSubmoduleStatus string UpdateSubmoduleUrl string UpdatingSubmoduleUrlStatus string EditSubmoduleUrl string InitializingSubmoduleStatus string InitSubmoduleTooltip string Update string Initialize string SubmoduleUpdateTooltip string UpdatingSubmoduleStatus string BulkInitSubmodules string BulkUpdateSubmodules string BulkDeinitSubmodules string BulkUpdateRecursiveSubmodules string ViewBulkSubmoduleOptions string BulkSubmoduleOptions string
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/i18n/i18n_test.go
pkg/i18n/i18n_test.go
package i18n import ( "fmt" "io" "runtime" "testing" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) // TestDetectLanguage is a function. func TestDetectLanguage(t *testing.T) { type scenario struct { langDetector func() (string, error) expected string } scenarios := []scenario{ { func() (string, error) { return "", fmt.Errorf("An error occurred") }, "C", }, { func() (string, error) { return "en", nil }, "en", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, detectLanguage(s.langDetector)) } } // Can't use utils.NewDummyLog() because of a cyclic dependency func newDummyLog() *logrus.Entry { log := logrus.New() log.Out = io.Discard return log.WithField("test", "test") } func TestNewTranslationSetFromConfig(t *testing.T) { if runtime.GOOS == "windows" { // These tests are based on setting the LANG environment variable, which // isn't respected on Windows. t.Skip("Skipping test on Windows") } scenarios := []struct { name string configLanguage string envLanguage string expected string expectedErr bool }{ { name: "configLanguage is nl", configLanguage: "nl", envLanguage: "en_US", expected: "nl", expectedErr: false, }, { name: "configLanguage is an unsupported language", configLanguage: "xy", envLanguage: "en_US", expectedErr: true, }, { name: "auto-detection without LANG set", configLanguage: "auto", envLanguage: "", expected: "en", expectedErr: false, }, { name: "auto-detection with LANG set to nl_NL", configLanguage: "auto", envLanguage: "nl_NL", expected: "nl", expectedErr: false, }, { name: "auto-detection with LANG set to zh-CN", configLanguage: "auto", envLanguage: "zh-CN", expected: "zh-CN", expectedErr: false, }, { name: "auto-detection with LANG set to an unsupported language", configLanguage: "auto", envLanguage: "xy_XY", expected: "en", expectedErr: false, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { log := newDummyLog() t.Setenv("LANG", s.envLanguage) actualTranslationSet, err := NewTranslationSetFromConfig(log, s.configLanguage) if s.expectedErr { assert.Error(t, err) } else { assert.NoError(t, err) expectedTranslationSet, _ := newTranslationSet(log, s.expected) assert.Equal(t, expectedTranslationSet, actualTranslationSet) } }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/regexp_test.go
pkg/utils/regexp_test.go
package utils import ( "reflect" "regexp" "testing" ) func TestFindNamedMatches(t *testing.T) { scenarios := []struct { regex *regexp.Regexp input string expected map[string]string }{ { regexp.MustCompile(`^(?P<name>\w+)`), "hello world", map[string]string{ "name": "hello", }, }, { regexp.MustCompile(`^https?://.*/(?P<owner>.*)/(?P<repo>.*?)(\.git)?$`), "https://my_username@bitbucket.org/johndoe/social_network.git", map[string]string{ "owner": "johndoe", "repo": "social_network", "": ".git", // unnamed capture group }, }, { regexp.MustCompile(`(?P<owner>hello) world`), "yo world", nil, }, } for _, scenario := range scenarios { actual := FindNamedMatches(scenario.regex, scenario.input) if !reflect.DeepEqual(actual, scenario.expected) { t.Errorf("FindNamedMatches(%s, %s) == %s, expected %s", scenario.regex, scenario.input, actual, scenario.expected) } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/date_test.go
pkg/utils/date_test.go
package utils import ( "testing" ) func TestFormatSecondsAgo(t *testing.T) { tests := []struct { name string args int64 want string }{ { name: "zero", args: 0, want: "0s", }, { name: "one second", args: 1, want: "1s", }, { name: "almost a minute", args: 59, want: "59s", }, { name: "one minute", args: 60, want: "1m", }, { name: "one minute and one second", args: 61, want: "1m", }, { name: "almost one hour", args: 3599, want: "59m", }, { name: "one hour", args: 3600, want: "1h", }, { name: "almost one day", args: 86399, want: "23h", }, { name: "one day", args: 86400, want: "1d", }, { name: "almost a week", args: 604799, want: "6d", }, { name: "one week", args: 604800, want: "1w", }, { name: "six months", args: SECONDS_IN_YEAR / 2, want: "6M", }, { name: "almost one year", args: 31535999, want: "11M", }, { name: "one year", args: SECONDS_IN_YEAR, want: "1y", }, { name: "50 years", args: SECONDS_IN_YEAR * 50, want: "50y", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := formatSecondsAgo(tt.args); got != tt.want { t.Errorf("formatSecondsAgo(%d) = %v, want %v", tt.args, got, tt.want) } }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/formatting_test.go
pkg/utils/formatting_test.go
package utils import ( "strings" "testing" "github.com/rivo/uniseg" "github.com/stretchr/testify/assert" ) func TestWithPadding(t *testing.T) { type scenario struct { str string padding int alignment Alignment expected string } scenarios := []scenario{ { str: "hello world !", padding: 1, alignment: AlignLeft, expected: "hello world !", }, { str: "hello world !", padding: 14, alignment: AlignLeft, expected: "hello world ! ", }, { str: "hello world !", padding: 14, alignment: AlignRight, expected: " hello world !", }, { str: "Güçlü", padding: 7, alignment: AlignLeft, expected: "Güçlü ", }, { str: "Güçlü", padding: 7, alignment: AlignRight, expected: " Güçlü", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, WithPadding(s.str, s.padding, s.alignment)) } } func TestGetPadWidths(t *testing.T) { type scenario struct { input [][]string expected []int } tests := []scenario{ { [][]string{{""}, {""}}, []int{}, }, { [][]string{{"a"}, {""}}, []int{}, }, { [][]string{{"aa", "b", "ccc"}, {"c", "d", "e"}}, []int{2, 1}, }, { [][]string{{"AŁ", "b", "ccc"}, {"c", "d", "e"}}, []int{2, 1}, }, } for _, test := range tests { output := getPadWidths(test.input) assert.EqualValues(t, test.expected, output) } } func TestTruncateWithEllipsis(t *testing.T) { // will need to check chinese characters as well // important that we have a three dot ellipsis within the limit type scenario struct { str string limit int expected string } scenarios := []scenario{ { "hello world !", 1, ".", }, { "hello world !", 2, "..", }, { "hello world !", 3, "he…", }, { "hello world !", 4, "hel…", }, { "hello world !", 5, "hell…", }, { "hello world !", 12, "hello world…", }, { "hello world !", 13, "hello world !", }, { "hello world !", 14, "hello world !", }, { "大大大大", 5, "大大…", }, { "大大大大", 2, "..", }, { "大大大大", 1, ".", }, { "大大大大", 0, "", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, TruncateWithEllipsis(s.str, s.limit)) } } func TestRenderDisplayStrings(t *testing.T) { type scenario struct { input [][]string columnAlignments []Alignment expectedOutput string expectedColumnPositions []int } tests := []scenario{ { input: [][]string{{""}, {""}}, columnAlignments: nil, expectedOutput: "", expectedColumnPositions: []int{0, 0}, }, { input: [][]string{{"a"}, {""}}, columnAlignments: nil, expectedOutput: "a\n", expectedColumnPositions: []int{0}, }, { input: [][]string{{"a"}, {"b"}}, columnAlignments: nil, expectedOutput: "a\nb", expectedColumnPositions: []int{0}, }, { input: [][]string{{"a", "b"}, {"c", "d"}}, columnAlignments: nil, expectedOutput: "a b\nc d", expectedColumnPositions: []int{0, 2}, }, { input: [][]string{{"a", "", "c"}, {"d", "", "f"}}, columnAlignments: nil, expectedOutput: "a c\nd f", expectedColumnPositions: []int{0, 2, 2}, }, { input: [][]string{{"a", "", "c", ""}, {"d", "", "f", ""}}, columnAlignments: nil, expectedOutput: "a c\nd f", expectedColumnPositions: []int{0, 2, 2}, }, { input: [][]string{{"abc", "", "d", ""}, {"e", "", "f", ""}}, columnAlignments: nil, expectedOutput: "abc d\ne f", expectedColumnPositions: []int{0, 4, 4}, }, { input: [][]string{{"", "abc", "", "", "d", "e"}, {"", "f", "", "", "g", "h"}}, columnAlignments: nil, expectedOutput: "abc d e\nf g h", expectedColumnPositions: []int{0, 0, 4, 4, 4, 6}, }, { input: [][]string{{"abc", "", "d", ""}, {"e", "", "f", ""}}, columnAlignments: []Alignment{AlignLeft, AlignLeft}, // same as nil (default) expectedOutput: "abc d\ne f", expectedColumnPositions: []int{0, 4, 4}, }, { input: [][]string{{"abc", "", "d", ""}, {"e", "", "f", ""}}, columnAlignments: []Alignment{AlignRight, AlignLeft}, expectedOutput: "abc d\n e f", expectedColumnPositions: []int{0, 4, 4}, }, { input: [][]string{{"a", "", "bcd", "efg", "h"}, {"i", "", "j", "k", "l"}}, columnAlignments: []Alignment{AlignLeft, AlignLeft, AlignRight, AlignLeft}, expectedOutput: "a bcd efg h\ni j k l", expectedColumnPositions: []int{0, 2, 2, 6, 10}, }, { input: [][]string{{"abc", "", "d", ""}, {"e", "", "f", ""}}, columnAlignments: []Alignment{AlignRight}, // gracefully defaults unspecified columns to left-align expectedOutput: "abc d\n e f", expectedColumnPositions: []int{0, 4, 4}, }, } for _, test := range tests { output, columnPositions := RenderDisplayStrings(test.input, test.columnAlignments) assert.EqualValues(t, test.expectedOutput, strings.Join(output, "\n")) assert.EqualValues(t, test.expectedColumnPositions, columnPositions) } } func BenchmarkStringWidthAsciiOriginal(b *testing.B) { for b.Loop() { uniseg.StringWidth("some ASCII string") } } func BenchmarkStringWidthAsciiOptimized(b *testing.B) { for b.Loop() { StringWidth("some ASCII string") } } func BenchmarkStringWidthNonAsciiOriginal(b *testing.B) { for b.Loop() { uniseg.StringWidth("some non-ASCII string 🍉") } } func BenchmarkStringWidthNonAsciiOptimized(b *testing.B) { for b.Loop() { StringWidth("some non-ASCII string 🍉") } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/formatting.go
pkg/utils/formatting.go
package utils import ( "fmt" "strings" "unicode" "github.com/rivo/uniseg" "github.com/samber/lo" "golang.org/x/exp/slices" ) type Alignment int const ( AlignLeft Alignment = iota AlignRight ) type ColumnConfig struct { Width int Alignment Alignment } func StringWidth(s string) int { // We are intentionally not using a range loop here, because that would // convert the characters to runes, which is unnecessary work in this case. for i := range len(s) { if s[i] > unicode.MaxASCII { return uniseg.StringWidth(s) } } return len(s) } // WithPadding pads a string as much as you want func WithPadding(str string, padding int, alignment Alignment) string { uncoloredStr := Decolorise(str) width := StringWidth(uncoloredStr) if padding < width { return str } space := strings.Repeat(" ", padding-width) if alignment == AlignLeft { return str + space } return space + str } // defaults to left-aligning each column. If you want to set the alignment of // each column, pass in a slice of Alignment values. // returns a list of strings that should be joined with "\n", and an array of // the column positions func RenderDisplayStrings(displayStringsArr [][]string, columnAlignments []Alignment) ([]string, []int) { if len(displayStringsArr) == 0 { return []string{}, nil } displayStringsArr, columnAlignments, removedColumns := excludeBlankColumns(displayStringsArr, columnAlignments) padWidths := getPadWidths(displayStringsArr) columnConfigs := make([]ColumnConfig, len(padWidths)) columnPositions := make([]int, len(padWidths)+1) columnPositions[0] = 0 for i, padWidth := range padWidths { // gracefully handle when columnAlignments is shorter than padWidths alignment := AlignLeft if len(columnAlignments) > i { alignment = columnAlignments[i] } columnConfigs[i] = ColumnConfig{ Width: padWidth, Alignment: alignment, } columnPositions[i+1] = columnPositions[i] + padWidth + 1 } // Add the removed columns back into columnPositions (a removed column gets // the same position as the following column); clients should be able to rely // on them all to be there for _, removedColumn := range removedColumns { if removedColumn < len(columnPositions) { columnPositions = slices.Insert(columnPositions, removedColumn, columnPositions[removedColumn]) } } return getPaddedDisplayStrings(displayStringsArr, columnConfigs), columnPositions } // NOTE: this mutates the input slice for the sake of performance func excludeBlankColumns(displayStringsArr [][]string, columnAlignments []Alignment) ([][]string, []Alignment, []int) { if len(displayStringsArr) == 0 { return displayStringsArr, columnAlignments, []int{} } // if all rows share a blank column, we want to remove that column toRemove := []int{} outer: for i := range displayStringsArr[0] { for _, strings := range displayStringsArr { if strings[i] != "" { continue outer } } toRemove = append(toRemove, i) } if len(toRemove) == 0 { return displayStringsArr, columnAlignments, []int{} } // remove the columns for i, strings := range displayStringsArr { for j := len(toRemove) - 1; j >= 0; j-- { strings = slices.Delete(strings, toRemove[j], toRemove[j]+1) } displayStringsArr[i] = strings } for j := len(toRemove) - 1; j >= 0; j-- { if columnAlignments != nil && toRemove[j] < len(columnAlignments) { columnAlignments = slices.Delete(columnAlignments, toRemove[j], toRemove[j]+1) } } return displayStringsArr, columnAlignments, toRemove } func getPaddedDisplayStrings(stringArrays [][]string, columnConfigs []ColumnConfig) []string { result := make([]string, 0, len(stringArrays)) for _, stringArray := range stringArrays { if len(stringArray) == 0 { continue } builder := strings.Builder{} for j, columnConfig := range columnConfigs { if len(stringArray)-1 < j { continue } builder.WriteString(WithPadding(stringArray[j], columnConfig.Width, columnConfig.Alignment)) builder.WriteString(" ") } if len(stringArray)-1 < len(columnConfigs) { continue } builder.WriteString(stringArray[len(columnConfigs)]) result = append(result, builder.String()) } return result } func getPadWidths(stringArrays [][]string) []int { maxWidth := MaxFn(stringArrays, func(stringArray []string) int { return len(stringArray) }) if maxWidth-1 < 0 { return []int{} } return lo.Map(lo.Range(maxWidth-1), func(i int, _ int) int { return MaxFn(stringArrays, func(stringArray []string) int { uncoloredStr := Decolorise(stringArray[i]) return StringWidth(uncoloredStr) }) }) } func MaxFn[T any](items []T, fn func(T) int) int { max := 0 for _, item := range items { if fn(item) > max { max = fn(item) } } return max } // TruncateWithEllipsis returns a string, truncated to a certain length, with an ellipsis func TruncateWithEllipsis(str string, limit int) string { if StringWidth(str) <= limit { return str } if limit <= 2 { return strings.Repeat(".", limit) } state := -1 var grapheme string var width int truncatedStr := "" for str != "" { grapheme, str, width, state = uniseg.FirstGraphemeClusterInString(str, state) if uniseg.StringWidth(truncatedStr)+width > limit-1 { break } truncatedStr += grapheme } return truncatedStr + "…" } func SafeTruncate(str string, limit int) string { if len(str) > limit { return str[0:limit] } return str } const COMMIT_HASH_SHORT_SIZE = 8 func ShortHash(hash string) string { if len(hash) < COMMIT_HASH_SHORT_SIZE { return hash } return hash[:COMMIT_HASH_SHORT_SIZE] } // Returns comma-separated list of paths, with ellipsis if there are more than 3 // e.g. "foo, bar, baz, [...3 more]" func FormatPaths(paths []string) string { if len(paths) <= 3 { return strings.Join(paths, ", ") } return fmt.Sprintf("%s, %s, %s, [...%d more]", paths[0], paths[1], paths[2], len(paths)-3) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/regexp.go
pkg/utils/regexp.go
package utils import "regexp" func FindNamedMatches(regex *regexp.Regexp, str string) map[string]string { match := regex.FindStringSubmatch(str) if len(match) == 0 { return nil } results := map[string]string{} for i, value := range match[1:] { results[regex.SubexpNames()[i+1]] = value } return results }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/dummies.go
pkg/utils/dummies.go
package utils import ( "io" "github.com/sirupsen/logrus" ) // NewDummyLog creates a new dummy Log for testing func NewDummyLog() *logrus.Entry { log := logrus.New() log.Out = io.Discard return log.WithField("test", "test") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/rebase_todo.go
pkg/utils/rebase_todo.go
package utils import ( "bytes" "errors" "fmt" "os" "slices" "github.com/samber/lo" "github.com/stefanhaller/git-todo-parser/todo" ) type Todo struct { Hash string // for todos that have one, e.g. pick, drop, fixup, etc. Ref string // for update-ref todos } type TodoChange struct { Hash string NewAction todo.TodoCommand } // Read a git-rebase-todo file, change the actions for the given commits, // and write it back func EditRebaseTodo(filePath string, changes []TodoChange, commentChar byte) error { todos, err := ReadRebaseTodoFile(filePath, commentChar) if err != nil { return err } matchCount := 0 for i := range todos { t := &todos[i] // This is a nested loop, but it's ok because the number of todos should be small for _, change := range changes { if equalHash(t.Commit, change.Hash) { matchCount++ t.Command = change.NewAction } } } if matchCount < len(changes) { // Should never get here return errors.New("Some todos not found in git-rebase-todo") } return WriteRebaseTodoFile(filePath, todos, commentChar) } func equalHash(a, b string) bool { if len(a) == 0 && len(b) == 0 { return true } commonLength := min(len(a), len(b)) return commonLength > 0 && a[:commonLength] == b[:commonLength] } func findTodo(todos []todo.Todo, todoToFind Todo) (int, bool) { _, idx, ok := lo.FindIndexOf(todos, func(t todo.Todo) bool { // For update-ref todos we also must compare the Ref (they have an empty hash) return equalHash(t.Commit, todoToFind.Hash) && t.Ref == todoToFind.Ref }) return idx, ok } func ReadRebaseTodoFile(fileName string, commentChar byte) ([]todo.Todo, error) { f, err := os.Open(fileName) if err != nil { return nil, err } todos, err := todo.Parse(f, commentChar) err2 := f.Close() if err == nil { err = err2 } return todos, err } func WriteRebaseTodoFile(fileName string, todos []todo.Todo, commentChar byte) error { f, err := os.Create(fileName) if err != nil { return err } err = todo.Write(f, todos, commentChar) err2 := f.Close() if err == nil { err = err2 } return err } func todosToString(todos []todo.Todo, commentChar byte) ([]byte, error) { buffer := bytes.Buffer{} err := todo.Write(&buffer, todos, commentChar) return buffer.Bytes(), err } func PrependStrToTodoFile(filePath string, linesToPrepend []byte) error { existingContent, err := os.ReadFile(filePath) if err != nil { return err } linesToPrepend = append(linesToPrepend, existingContent...) return os.WriteFile(filePath, linesToPrepend, 0o644) } // Unlike the other functions in this file, which write the changed todos file // back to disk, this one returns the new content as a byte slice. This is // because when deleting update-ref todos, we must perform a "git rebase // --edit-todo" command to pass the changed todos to git so that it can do some // housekeeping around the deleted todos. This can only be done by our caller. func DeleteTodos(fileName string, todosToDelete []Todo, commentChar byte) ([]byte, error) { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return nil, err } rearrangedTodos, err := deleteTodos(todos, todosToDelete) if err != nil { return nil, err } return todosToString(rearrangedTodos, commentChar) } func deleteTodos(todos []todo.Todo, todosToDelete []Todo) ([]todo.Todo, error) { for _, todoToDelete := range todosToDelete { idx, ok := findTodo(todos, todoToDelete) if !ok { // Should never happen return []todo.Todo{}, fmt.Errorf("Todo %s not found in git-rebase-todo", todoToDelete.Hash) } todos = Remove(todos, idx) } return todos, nil } func MoveTodosDown(fileName string, todosToMove []Todo, isInRebase bool, commentChar byte) error { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return err } rearrangedTodos, err := moveTodosDown(todos, todosToMove, isInRebase) if err != nil { return err } return WriteRebaseTodoFile(fileName, rearrangedTodos, commentChar) } func MoveTodosUp(fileName string, todosToMove []Todo, isInRebase bool, commentChar byte) error { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return err } rearrangedTodos, err := moveTodosUp(todos, todosToMove, isInRebase) if err != nil { return err } return WriteRebaseTodoFile(fileName, rearrangedTodos, commentChar) } func moveTodoDown(todos []todo.Todo, todoToMove Todo, isInRebase bool) ([]todo.Todo, error) { rearrangedTodos, err := moveTodoUp(lo.Reverse(todos), todoToMove, isInRebase) return lo.Reverse(rearrangedTodos), err } func moveTodosDown(todos []todo.Todo, todosToMove []Todo, isInRebase bool) ([]todo.Todo, error) { rearrangedTodos, err := moveTodosUp(lo.Reverse(todos), lo.Reverse(todosToMove), isInRebase) return lo.Reverse(rearrangedTodos), err } func moveTodoUp(todos []todo.Todo, todoToMove Todo, isInRebase bool) ([]todo.Todo, error) { sourceIdx, ok := findTodo(todos, todoToMove) if !ok { // Should never happen return []todo.Todo{}, fmt.Errorf("Todo %s not found in git-rebase-todo", todoToMove.Hash) } // The todos are ordered backwards compared to our model commits, so // actually move the commit _down_ in the todos slice (i.e. towards // the end of the slice) // Find the next todo that we show in lazygit's commits view (skipping the rest) _, skip, ok := lo.FindIndexOf(todos[sourceIdx+1:], func(t todo.Todo) bool { return isRenderedTodo(t, isInRebase) }) if !ok { // We expect callers to guard against this return []todo.Todo{}, errors.New("Destination position for moving todo is out of range") } destinationIdx := sourceIdx + 1 + skip rearrangedTodos := MoveElement(todos, sourceIdx, destinationIdx) return rearrangedTodos, nil } func moveTodosUp(todos []todo.Todo, todosToMove []Todo, isInRebase bool) ([]todo.Todo, error) { for _, todoToMove := range todosToMove { var newTodos []todo.Todo newTodos, err := moveTodoUp(todos, todoToMove, isInRebase) if err != nil { return nil, err } todos = newTodos } return todos, nil } func MoveFixupCommitDown(fileName string, originalHash string, fixupHash string, changeToFixup bool, commentChar byte) error { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return err } newTodos, err := moveFixupCommitDown(todos, originalHash, fixupHash, changeToFixup) if err != nil { return err } return WriteRebaseTodoFile(fileName, newTodos, commentChar) } func moveFixupCommitDown(todos []todo.Todo, originalHash string, fixupHash string, changeToFixup bool) ([]todo.Todo, error) { isOriginal := func(t todo.Todo) bool { return (t.Command == todo.Pick || t.Command == todo.Merge) && equalHash(t.Commit, originalHash) } isFixup := func(t todo.Todo) bool { return t.Command == todo.Pick && equalHash(t.Commit, fixupHash) } originalHashCount := lo.CountBy(todos, isOriginal) if originalHashCount != 1 { return nil, fmt.Errorf("Expected exactly one original hash, found %d", originalHashCount) } fixupHashCount := lo.CountBy(todos, isFixup) if fixupHashCount != 1 { return nil, fmt.Errorf("Expected exactly one fixup hash, found %d", fixupHashCount) } _, fixupIndex, _ := lo.FindIndexOf(todos, isFixup) _, originalIndex, _ := lo.FindIndexOf(todos, isOriginal) newTodos := MoveElement(todos, fixupIndex, originalIndex+1) if changeToFixup { newTodos[originalIndex+1].Command = todo.Fixup } return newTodos, nil } func RemoveUpdateRefsForCopiedBranch(fileName string, commentChar byte) error { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return err } // Filter out comments todos = lo.Filter(todos, func(t todo.Todo, _ int) bool { return t.Command != todo.Comment }) // Delete any update-ref todos at the end of the todo list. These are not // part of a stack of branches, and so shouldn't be updated. This makes it // possible to create a copy of a branch and rebase the copy without // affecting the original branch. if _, i, found := lo.FindLastIndexOf(todos, func(t todo.Todo) bool { return t.Command != todo.UpdateRef }); found && i < len(todos)-1 { todos = slices.Delete(todos, i+1, len(todos)) return WriteRebaseTodoFile(fileName, todos, commentChar) } return nil } // We render a todo in the commits view if it's a commit or if it's an // update-ref or exec. We don't render label, reset, or comment lines. func isRenderedTodo(t todo.Todo, isInRebase bool) bool { return t.Commit != "" || (isInRebase && (t.Command == todo.UpdateRef || t.Command == todo.Exec)) } func DropMergeCommit(fileName string, hash string, commentChar byte) error { todos, err := ReadRebaseTodoFile(fileName, commentChar) if err != nil { return err } newTodos, err := dropMergeCommit(todos, hash) if err != nil { return err } return WriteRebaseTodoFile(fileName, newTodos, commentChar) } func dropMergeCommit(todos []todo.Todo, hash string) ([]todo.Todo, error) { isMerge := func(t todo.Todo) bool { return t.Command == todo.Merge && t.Flag == "-C" && equalHash(t.Commit, hash) } if lo.CountBy(todos, isMerge) != 1 { return nil, fmt.Errorf("Expected exactly one merge commit with hash %s", hash) } _, idx, _ := lo.FindIndexOf(todos, isMerge) return slices.Delete(todos, idx, idx+1), nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/string_stack.go
pkg/utils/string_stack.go
package utils type StringStack struct { stack []string } func (self *StringStack) Push(s string) { self.stack = append(self.stack, s) } func (self *StringStack) Pop() string { if len(self.stack) == 0 { return "" } n := len(self.stack) - 1 last := self.stack[n] self.stack = self.stack[:n] return last } func (self *StringStack) IsEmpty() bool { return len(self.stack) == 0 } func (self *StringStack) Clear() { self.stack = []string{} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/history_buffer.go
pkg/utils/history_buffer.go
package utils import ( "errors" ) type HistoryBuffer[T any] struct { maxSize int items []T } func NewHistoryBuffer[T any](maxSize int) *HistoryBuffer[T] { return &HistoryBuffer[T]{ maxSize: maxSize, items: make([]T, 0, maxSize), } } func (self *HistoryBuffer[T]) Push(item T) { if len(self.items) == self.maxSize { self.items = self.items[:len(self.items)-1] } self.items = append([]T{item}, self.items...) } func (self *HistoryBuffer[T]) PeekAt(index int) (T, error) { var item T if len(self.items) == 0 { return item, errors.New("Buffer is empty") } if len(self.items) <= index || index < -1 { return item, errors.New("Index out of range") } if index == -1 { return item, nil } return self.items[index], nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/errors.go
pkg/utils/errors.go
package utils import "github.com/go-errors/errors" // WrapError wraps an error for the sake of showing a stack trace at the top level // the go-errors package, for some reason, does not return nil when you try to wrap // a non-error, so we're just doing it here func WrapError(err error) error { if err == nil { return err } return errors.Wrap(err, 0) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/lines_test.go
pkg/utils/lines_test.go
package utils import ( "bufio" "strings" "testing" "github.com/jesseduffield/gocui" "github.com/stretchr/testify/assert" ) // TestSplitLines is a function. func TestSplitLines(t *testing.T) { type scenario struct { multilineString string expected []string } scenarios := []scenario{ { "", []string{}, }, { "\n", []string{}, }, { "hello world !\nhello universe !\n", []string{ "hello world !", "hello universe !", }, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, SplitLines(s.multilineString)) } } func TestSplitNul(t *testing.T) { type scenario struct { multilineString string expected []string } scenarios := []scenario{ { "", []string{}, }, { "\x00", []string{ "", }, }, { "hello world !\x00hello universe !\x00", []string{ "hello world !", "hello universe !", }, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, SplitNul(s.multilineString)) } } // TestNormalizeLinefeeds is a function. func TestNormalizeLinefeeds(t *testing.T) { type scenario struct { byteArray []byte expected []byte } scenarios := []scenario{ { // \r\n []byte{97, 115, 100, 102, 13, 10}, []byte{97, 115, 100, 102, 10}, }, { // bash\r\nblah []byte{97, 115, 100, 102, 13, 10, 97, 115, 100, 102}, []byte{97, 115, 100, 102, 10, 97, 115, 100, 102}, }, { // \r []byte{97, 115, 100, 102, 13}, []byte{97, 115, 100, 102}, }, { // \n []byte{97, 115, 100, 102, 10}, []byte{97, 115, 100, 102, 10}, }, } for _, s := range scenarios { assert.EqualValues(t, string(s.expected), NormalizeLinefeeds(string(s.byteArray))) } } func TestScanLinesAndTruncateWhenLongerThanBuffer(t *testing.T) { type scenario struct { input string expectedLines []string } scenarios := []scenario{ { "", []string{}, }, { "\n", []string{""}, }, { "abc", []string{"abc"}, }, { "abc\ndef", []string{"abc", "def"}, }, { "abc\n\ndef", []string{"abc", "", "def"}, }, { "abc\r\ndef\r", []string{"abc", "def"}, }, { "abcdef", []string{"abcde"}, }, { "abcdef\n", []string{"abcde"}, }, { "abcdef\nghijkl\nx", []string{"abcde", "ghijk", "x"}, }, { "abc\ndefghijklmnopqrstuvw\nx", []string{"abc", "defgh", "x"}, }, } for _, s := range scenarios { scanner := bufio.NewScanner(strings.NewReader(s.input)) scanner.Buffer(make([]byte, 5), 5) scanner.Split(ScanLinesAndTruncateWhenLongerThanBuffer(5)) result := []string{} for scanner.Scan() { result = append(result, scanner.Text()) } assert.NoError(t, scanner.Err()) assert.EqualValues(t, s.expectedLines, result) } } func TestWrapViewLinesToWidth(t *testing.T) { tests := []struct { name string wrap bool editable bool text string width int tabWidth int expectedWrappedLines []string expectedWrappedLinesIndices []int expectedOriginalLinesIndices []int }{ { name: "Wrap off", wrap: false, text: "1st line\n2nd line\n3rd line", width: 5, expectedWrappedLines: []string{ "1st line", "2nd line", "3rd line", }, expectedWrappedLinesIndices: []int{0, 1, 2}, expectedOriginalLinesIndices: []int{0, 1, 2}, }, { name: "Wrap on space", wrap: true, text: "Hello World", width: 5, expectedWrappedLines: []string{ "Hello", "World", }, expectedWrappedLinesIndices: []int{0}, expectedOriginalLinesIndices: []int{0, 0}, }, { name: "Wrap on hyphen", wrap: true, text: "Hello-World", width: 6, expectedWrappedLines: []string{ "Hello-", "World", }, }, { name: "Wrap on hyphen 2", wrap: true, text: "Blah Hello-World", width: 12, expectedWrappedLines: []string{ "Blah Hello-", "World", }, }, { name: "Wrap on hyphen 3", wrap: true, text: "Blah Hello-World", width: 11, expectedWrappedLines: []string{ "Blah Hello-", "World", }, }, { name: "Wrap on hyphen 4", wrap: true, text: "Blah Hello-World", width: 10, expectedWrappedLines: []string{ "Blah Hello", "-World", }, }, { name: "Wrap on space 2", wrap: true, text: "Blah Hello World", width: 10, expectedWrappedLines: []string{ "Blah Hello", "World", }, }, { name: "Wrap on space with more words", wrap: true, text: "Longer word here", width: 10, expectedWrappedLines: []string{ "Longer", "word here", }, }, { name: "Split word that's too long", wrap: true, text: "ThisWordIsWayTooLong", width: 10, expectedWrappedLines: []string{ "ThisWordIs", "WayTooLong", }, }, { name: "Split word that's too long over multiple lines", wrap: true, text: "ThisWordIsWayTooLong", width: 5, expectedWrappedLines: []string{ "ThisW", "ordIs", "WayTo", "oLong", }, }, { name: "Lots of hyphens", wrap: true, text: "one-two-three-four-five", width: 8, expectedWrappedLines: []string{ "one-two-", "three-", "four-", "five", }, }, { name: "Several lines using all the available width", wrap: true, text: "aaa bb cc ddd-ee ff", width: 5, expectedWrappedLines: []string{ "aaa", "bb cc", "ddd-", "ee ff", }, }, { name: "Several lines using all the available width, with multi-cell runes", wrap: true, text: "🐤🐤🐤 🐝🐝 🙉🙉 🦊🦊🦊-🐬🐬 🦢🦢", width: 9, expectedWrappedLines: []string{ "🐤🐤🐤", "🐝🐝 🙉🙉", "🦊🦊🦊-", "🐬🐬 🦢🦢", }, }, { name: "Space in last column", wrap: true, text: "hello world", width: 6, expectedWrappedLines: []string{ "hello", "world", }, }, { name: "Hyphen in last column", wrap: true, text: "hello-world", width: 6, expectedWrappedLines: []string{ "hello-", "world", }, }, { name: "English text", wrap: true, text: "+The sea reach of the Thames stretched before us like the bedinnind of an interminable waterway. In the offind the sea and the sky were welded todether without a joint, and in the luminous space the tanned sails of the bardes drifting blah blah", width: 81, expectedWrappedLines: []string{ "+The sea reach of the Thames stretched before us like the bedinnind of an", "interminable waterway. In the offind the sea and the sky were welded todether", "without a joint, and in the luminous space the tanned sails of the bardes", "drifting blah blah", }, }, { name: "Tabs, width 4", wrap: true, text: "\ta\tbb\tccc\tdddd\teeeee", width: 50, tabWidth: 4, expectedWrappedLines: []string{ " a bb ccc dddd eeeee", }, }, { name: "Tabs, width 8", wrap: true, text: "\ta\tbb\tccc\tdddddddd\teeeee", width: 100, tabWidth: 8, expectedWrappedLines: []string{ " a bb ccc dddddddd eeeee", }, }, { name: "Multiple lines", wrap: true, text: "First paragraph\nThe second paragraph is a bit longer.\nThird paragraph\n", width: 10, expectedWrappedLines: []string{ "First", "paragraph", "The second", "paragraph", "is a bit", "longer.", "Third", "paragraph", }, expectedWrappedLinesIndices: []int{0, 2, 6}, expectedOriginalLinesIndices: []int{0, 0, 1, 1, 1, 1, 2, 2}, }, { name: "Avoid blank line at end if not editable", wrap: true, editable: false, text: "First\nSecond\nThird\n", width: 10, expectedWrappedLines: []string{ "First", "Second", "Third", }, expectedWrappedLinesIndices: []int{0, 1, 2}, expectedOriginalLinesIndices: []int{0, 1, 2}, }, { name: "Keep blank line at end if editable", wrap: true, editable: true, text: "First\nSecond\nThird\n", width: 10, expectedWrappedLines: []string{ "First", "Second", "Third", "", }, expectedWrappedLinesIndices: []int{0, 1, 2, 3}, expectedOriginalLinesIndices: []int{0, 1, 2, 3}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tabWidth := tt.tabWidth if tabWidth == 0 { tabWidth = 4 } wrappedLines, wrappedLinesIndices, originalLinesIndices := WrapViewLinesToWidth(tt.wrap, tt.editable, tt.text, tt.width, tabWidth) assert.Equal(t, tt.expectedWrappedLines, wrappedLines) if tt.expectedWrappedLinesIndices != nil { assert.Equal(t, tt.expectedWrappedLinesIndices, wrappedLinesIndices) } if tt.expectedOriginalLinesIndices != nil { assert.Equal(t, tt.expectedOriginalLinesIndices, originalLinesIndices) } // As a sanity check, also test that gocui's line wrapping behaves the same way view := gocui.NewView("", 0, 0, tt.width+1, 1000, gocui.OutputNormal) view.TabWidth = tabWidth assert.Equal(t, tt.width, view.InnerWidth()) view.Wrap = tt.wrap view.Editable = tt.editable view.SetContent(tt.text) assert.Equal(t, wrappedLines, view.ViewBufferLines()) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/slice_test.go
pkg/utils/slice_test.go
package utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestNextIndex(t *testing.T) { type scenario struct { testName string list []int element int expected int } scenarios := []scenario{ { // I'm not really fussed about how it behaves here "no elements", []int{}, 1, -1, }, { "one element", []int{1}, 1, 0, }, { "two elements", []int{1, 2}, 1, 1, }, { "two elements, giving second one", []int{1, 2}, 2, 1, }, { "three elements, giving second one", []int{1, 2, 3}, 2, 2, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { assert.EqualValues(t, s.expected, NextIndex(s.list, s.element)) }) } } func TestPrevIndex(t *testing.T) { type scenario struct { testName string list []int element int expected int } scenarios := []scenario{ { // I'm not really fussed about how it behaves here "no elements", []int{}, 1, 0, }, { "one element", []int{1}, 1, 0, }, { "two elements", []int{1, 2}, 1, 0, }, { "three elements, giving second one", []int{1, 2, 3}, 2, 0, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { assert.EqualValues(t, s.expected, PrevIndex(s.list, s.element)) }) } } func TestEscapeSpecialChars(t *testing.T) { type scenario struct { testName string input string expected string } scenarios := []scenario{ { "normal string", "ab", "ab", }, { "string with a special char", "a\nb", "a\\nb", }, { "multiple special chars", "\n\r\t\b\f\v", "\\n\\r\\t\\b\\f\\v", }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { assert.EqualValues(t, s.expected, EscapeSpecialChars(s.input)) }) } } func TestLimit(t *testing.T) { for _, test := range []struct { values []string limit int want []string }{ { values: []string{"a", "b", "c"}, limit: 3, want: []string{"a", "b", "c"}, }, { values: []string{"a", "b", "c"}, limit: 4, want: []string{"a", "b", "c"}, }, { values: []string{"a", "b", "c"}, limit: 2, want: []string{"a", "b"}, }, { values: []string{"a", "b", "c"}, limit: 1, want: []string{"a"}, }, { values: []string{"a", "b", "c"}, limit: 0, want: []string{}, }, { values: []string{}, limit: 0, want: []string{}, }, } { if got := Limit(test.values, test.limit); !assert.EqualValues(t, got, test.want) { t.Errorf("Limit(%v, %d) = %v; want %v", test.values, test.limit, got, test.want) } } } func TestLimitStr(t *testing.T) { for _, test := range []struct { values string limit int want string }{ { values: "", limit: 10, want: "", }, { values: "", limit: 0, want: "", }, { values: "a", limit: 1, want: "a", }, { values: "ab", limit: 2, want: "ab", }, { values: "abc", limit: 3, want: "abc", }, { values: "abcd", limit: 3, want: "abc", }, { values: "abcde", limit: 3, want: "abc", }, { values: "あいう", limit: 1, want: "あ", }, { values: "あいう", limit: 2, want: "あい", }, } { if got := LimitStr(test.values, test.limit); !assert.EqualValues(t, got, test.want) { t.Errorf("LimitString(%v, %d) = %v; want %v", test.values, test.limit, got, test.want) } } } func TestMoveElement(t *testing.T) { type scenario struct { testName string list []int from int to int expected []int } scenarios := []scenario{ { "no elements", []int{}, 0, 0, []int{}, }, { "one element", []int{1}, 0, 0, []int{1}, }, { "two elements, moving first to second", []int{1, 2}, 0, 1, []int{2, 1}, }, { "two elements, moving second to first", []int{1, 2}, 1, 0, []int{2, 1}, }, { "three elements, moving first to second", []int{1, 2, 3}, 0, 1, []int{2, 1, 3}, }, { "three elements, moving second to first", []int{1, 2, 3}, 1, 0, []int{2, 1, 3}, }, { "three elements, moving second to third", []int{1, 2, 3}, 1, 2, []int{1, 3, 2}, }, { "three elements, moving third to second", []int{1, 2, 3}, 2, 1, []int{1, 3, 2}, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { assert.EqualValues(t, s.expected, MoveElement(s.list, s.from, s.to)) }) } t.Run("from out of bounds", func(t *testing.T) { assert.Panics(t, func() { MoveElement([]int{1, 2, 3}, 3, 0) }) }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/io_test.go
pkg/utils/io_test.go
package utils import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func Test_forEachLineInStream(t *testing.T) { scenarios := []struct { name string input string expectedLines []string }{ { name: "empty input", input: "", expectedLines: []string{}, }, { name: "single line", input: "abc\n", expectedLines: []string{"abc\n"}, }, { name: "single line without line feed", input: "abc", expectedLines: []string{"abc"}, }, { name: "multiple lines", input: "abc\ndef\n", expectedLines: []string{"abc\n", "def\n"}, }, { name: "multiple lines including empty lines", input: "abc\n\ndef\n", expectedLines: []string{"abc\n", "\n", "def\n"}, }, { name: "multiple lines without linefeed at end of file", input: "abc\ndef\nghi", expectedLines: []string{"abc\n", "def\n", "ghi"}, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { lines := []string{} forEachLineInStream(strings.NewReader(s.input), func(line string, i int) { lines = append(lines, line) }) assert.EqualValues(t, s.expectedLines, lines) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/utils.go
pkg/utils/utils.go
package utils import ( "encoding/json" "fmt" "os" "regexp" "runtime" "strconv" "strings" "github.com/jesseduffield/gocui" ) // GetProjectRoot returns the path to the root of the project. Only to be used // in testing contexts, as with binaries it's unlikely this path will exist on // the machine func GetProjectRoot() string { dir, err := os.Getwd() if err != nil { panic(err) } return strings.Split(dir, "lazygit")[0] + "lazygit" } func SortRange(x int, y int) (int, int) { if x < y { return x, y } return y, x } func AsJson(i any) string { bytes, _ := json.MarshalIndent(i, "", " ") return string(bytes) } // used to keep a number n between 0 and max, allowing for wraparounds func ModuloWithWrap(n, max int) int { if max == 0 { return 0 } if n >= max { return n % max } else if n < 0 { return max + n } return n } func FindStringSubmatch(str string, regexpStr string) (bool, []string) { re := regexp.MustCompile(regexpStr) match := re.FindStringSubmatch(str) return len(match) > 0, match } func MustConvertToInt(s string) int { i, err := strconv.Atoi(s) if err != nil { panic(err) } return i } // Safe will close tcell if a panic occurs so that we don't end up in a malformed // terminal state func Safe(f func()) { _ = SafeWithError(func() error { f(); return nil }) } func SafeWithError(f func() error) error { panicking := true defer func() { if panicking && gocui.Screen != nil { gocui.Screen.Fini() } }() err := f() panicking = false return err } func StackTrace() string { buf := make([]byte, 10000) n := runtime.Stack(buf, false) return fmt.Sprintf("%s\n", buf[:n]) } // returns the path of the file that calls the function. // 'skip' is the number of stack frames to skip. func FilePath(skip int) string { _, path, _, _ := runtime.Caller(skip) return path }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/thread_safe_map.go
pkg/utils/thread_safe_map.go
package utils import "sync" type ThreadSafeMap[K comparable, V any] struct { mutex sync.RWMutex innerMap map[K]V } func NewThreadSafeMap[K comparable, V any]() *ThreadSafeMap[K, V] { return &ThreadSafeMap[K, V]{ innerMap: make(map[K]V), } } func (m *ThreadSafeMap[K, V]) Get(key K) (V, bool) { m.mutex.RLock() defer m.mutex.RUnlock() value, ok := m.innerMap[key] return value, ok } func (m *ThreadSafeMap[K, V]) Set(key K, value V) { m.mutex.Lock() defer m.mutex.Unlock() m.innerMap[key] = value } func (m *ThreadSafeMap[K, V]) Delete(key K) { m.mutex.Lock() defer m.mutex.Unlock() delete(m.innerMap, key) } func (m *ThreadSafeMap[K, V]) Keys() []K { m.mutex.RLock() defer m.mutex.RUnlock() keys := make([]K, 0, len(m.innerMap)) for key := range m.innerMap { keys = append(keys, key) } return keys } func (m *ThreadSafeMap[K, V]) Values() []V { m.mutex.RLock() defer m.mutex.RUnlock() values := make([]V, 0, len(m.innerMap)) for _, value := range m.innerMap { values = append(values, value) } return values } func (m *ThreadSafeMap[K, V]) Len() int { m.mutex.RLock() defer m.mutex.RUnlock() return len(m.innerMap) } func (m *ThreadSafeMap[K, V]) Clear() { m.mutex.Lock() defer m.mutex.Unlock() m.innerMap = make(map[K]V) } func (m *ThreadSafeMap[K, V]) IsEmpty() bool { m.mutex.RLock() defer m.mutex.RUnlock() return len(m.innerMap) == 0 } func (m *ThreadSafeMap[K, V]) Has(key K) bool { m.mutex.RLock() defer m.mutex.RUnlock() _, ok := m.innerMap[key] return ok }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/color_test.go
pkg/utils/color_test.go
package utils import ( "testing" "github.com/jesseduffield/lazygit/pkg/gui/style" ) func TestDecolorise(t *testing.T) { tests := []struct { input string output string }{ { input: "", output: "", }, { input: "hello", output: "hello", }, { input: "hello\x1b[31m", output: "hello", }, { input: "hello\x1b[31mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33m\x1b[34mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33m\x1b[34m\x1b[35mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33m\x1b[34m\x1b[35m\x1b[36mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33m\x1b[34m\x1b[35m\x1b[36m\x1b[37mworld", output: "helloworld", }, { input: "hello\x1b[31m\x1b[32m\x1b[33m\x1b[34m\x1b[35m\x1b[36m\x1b[37mworld", output: "helloworld", }, { input: "\x1b[38;2;47;228;2mJD\x1b[0m", output: "JD", }, { input: "\x1b[38;2;160;47;213mRy\x1b[0m", output: "Ry", }, { input: "\x1b[38;2;179;217;72mSB\x1b[0m", output: "SB", }, { input: "\x1b[38;2;48;34;214mMK\x1b[0m", output: "MK", }, { input: "\x1b[38;2;28;152;222mAŁ\x1b[0m", output: "AŁ", }, { input: "\x1b[38;2;237;230;56mHH\x1b[0m", output: "HH", }, { input: "\x1b[38;2;63;232;69mmj\x1b[0m", output: "mj", }, { input: "\x1b[38;2;111;207;16mbl\x1b[0m", output: "bl", }, { input: "\x1b[38;2;250;31;163msa\x1b[0m", output: "sa", }, { input: "\x1b[38;2;195;10;54mbt\x1b[0m", output: "bt", }, { input: "\x1b[38;2;232;147;68mco\x1b[0m", output: "co", }, { input: "\x1b[38;2;116;180;35mDY\x1b[0m", output: "DY", }, { input: "\x1b[38;2;232;1;195mDB\x1b[0m", output: "DB", }, { input: "\x1b[38;2;245;101;55mLi\x1b[0m", output: "Li", }, { input: "\x1b[38;2;47;4;217mRy\x1b[0m", output: "Ry", }, { input: "\x1b[38;2;252;197;1mEl\x1b[0m", output: "El", }, { input: "\x1b[38;2;41;131;237mMG\x1b[0m", output: "MG", }, { input: "\x1b[38;2;65;240;62mDP\x1b[0m", output: "DP", }, { input: "\x1b[38;2;29;201;139mFM\x1b[0m", output: "FM", }, { input: "\x1b[38;2;141;20;198mEB\x1b[0m", output: "EB", }, { input: "\x1b[38;2;60;215;140mDM\x1b[0m", output: "DM", }, { input: "\x1b[38;2;247;63;38mDE\x1b[0m", output: "DE", }, { input: "\x1b[38;2;67;210;17mCB\x1b[0m", output: "CB", }, { input: "\x1b[38;2;220;190;84mST\x1b[0m", output: "ST", }, { input: "\x1b[38;2;137;239;6mER\x1b[0m", output: "ER", }, { input: "\x1b[38;2;47;249;225mAY\x1b[0m", output: "AY", }, { input: "\x1b[38;2;215;16;195mca\x1b[0m", output: "ca", }, { input: "\x1b[38;2;73;215;122mRV\x1b[0m", output: "RV", }, { input: "\x1b[38;2;118;15;221mJP\x1b[0m", output: "JP", }, { input: "\x1b[38;2;186;163;39mHJ\x1b[0m", output: "HJ", }, { input: "\x1b[38;2;54;222;111mDD\x1b[0m", output: "DD", }, { input: "\x1b[38;2;56;209;108mPZ\x1b[0m", output: "PZ", }, { input: "\x1b[38;2;9;179;216mPM\x1b[0m", output: "PM", }, { input: "\x1b[38;2;157;205;18mta\x1b[0m", output: "ta", }, { input: "a_" + style.PrintSimpleHyperlink("xyz") + "_b", output: "a_xyz_b", }, } for _, test := range tests { output := Decolorise(test.input) if output != test.output { t.Errorf("Decolorise(%s) = %s, want %s", test.input, output, test.output) } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/thread_safe_map_test.go
pkg/utils/thread_safe_map_test.go
package utils import ( "testing" ) func TestThreadSafeMap(t *testing.T) { m := NewThreadSafeMap[int, int]() m.Set(1, 1) m.Set(2, 2) m.Set(3, 3) if m.Len() != 3 { t.Errorf("Expected length to be 3, got %d", m.Len()) } if !m.Has(1) { t.Errorf("Expected to have key 1") } if m.Has(4) { t.Errorf("Expected to not have key 4") } if _, ok := m.Get(1); !ok { t.Errorf("Expected to have key 1") } if _, ok := m.Get(4); ok { t.Errorf("Expected to not have key 4") } m.Delete(1) if m.Has(1) { t.Errorf("Expected to not have key 1") } m.Clear() if m.Len() != 0 { t.Errorf("Expected length to be 0, got %d", m.Len()) } } func TestThreadSafeMapConcurrentReadWrite(t *testing.T) { m := NewThreadSafeMap[int, int]() go func() { for range 10000 { m.Set(0, 0) } }() for range 10000 { m.Get(0) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/io.go
pkg/utils/io.go
package utils import ( "bufio" "io" "os" ) func ForEachLineInFile(path string, f func(string, int)) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() forEachLineInStream(file, f) return nil } func forEachLineInStream(reader io.Reader, f func(string, int)) { bufferedReader := bufio.NewReader(reader) for i := 0; true; i++ { line, _ := bufferedReader.ReadString('\n') if len(line) == 0 { break } f(line, i) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/slice.go
pkg/utils/slice.go
package utils import "golang.org/x/exp/slices" // NextIndex returns the index of the element that comes after the given number func NextIndex(numbers []int, currentNumber int) int { for index, number := range numbers { if number > currentNumber { return index } } return len(numbers) - 1 } // PrevIndex returns the index that comes before the given number, cycling if we reach the end func PrevIndex(numbers []int, currentNumber int) int { end := len(numbers) - 1 for i := end; i >= 0; i-- { if numbers[i] < currentNumber { return i } } return 0 } // NextIntInCycle returns the next int in a slice, returning to the first index if we've reached the end func NextIntInCycle(sl []int, current int) int { for i, val := range sl { if val == current { if i == len(sl)-1 { return sl[0] } return sl[i+1] } } return sl[0] } // PrevIntInCycle returns the prev int in a slice, returning to the first index if we've reached the end func PrevIntInCycle(sl []int, current int) int { for i, val := range sl { if val == current { if i > 0 { return sl[i-1] } return sl[len(sl)-1] } } return sl[len(sl)-1] } func StringArraysOverlap(strArrA []string, strArrB []string) bool { for _, first := range strArrA { if slices.Contains(strArrB, first) { return true } } return false } func Limit(values []string, limit int) []string { if len(values) > limit { return values[:limit] } return values } func LimitStr(value string, limit int) string { n := 0 for i := range value { if n >= limit { return value[:i] } n++ } return value } // Similar to a regular GroupBy, except that each item can be grouped under multiple keys, // so the callback returns a slice of keys instead of just one key. func MuiltiGroupBy[T any, K comparable](slice []T, f func(T) []K) map[K][]T { result := map[K][]T{} for _, item := range slice { for _, key := range f(item) { if _, ok := result[key]; !ok { result[key] = []T{item} } else { result[key] = append(result[key], item) } } } return result } // Returns a new slice with the element at index 'from' moved to index 'to'. // Does not mutate original slice. func MoveElement[T any](slice []T, from int, to int) []T { newSlice := make([]T, len(slice)) copy(newSlice, slice) if from == to { return newSlice } if from < to { copy(newSlice[from:to+1], newSlice[from+1:to+1]) } else { copy(newSlice[to+1:from+1], newSlice[to:from]) } newSlice[to] = slice[from] return newSlice } func ValuesAtIndices[T any](slice []T, indices []int) []T { result := make([]T, len(indices)) for i, index := range indices { // gracefully handling the situation where the index is out of bounds if index < len(slice) { result[i] = slice[index] } } return result } // returns two slices: the first is for elements that pass the test, the second for those that don't. func Partition[T any](slice []T, test func(T) bool) ([]T, []T) { left := make([]T, 0, len(slice)) right := make([]T, 0, len(slice)) for _, value := range slice { if test(value) { left = append(left, value) } else { right = append(right, value) } } return left, right } // Prepends items to the beginning of a slice. // E.g. Prepend([]int{1,2}, 3, 4) = []int{3,4,1,2} // Mutates original slice. Intended usage is to reassign the slice result to the input slice. func Prepend[T any](slice []T, values ...T) []T { return append(values, slice...) } // Removes the element at the given index. Intended usage is to reassign the result to the input slice. func Remove[T any](slice []T, index int) []T { return slices.Delete(slice, index, index+1) } // Removes the element at the 'fromIndex' and then inserts it at 'toIndex'. // Operates on the input slice. Expected use is to reassign the result to the input slice. func Move[T any](slice []T, fromIndex int, toIndex int) []T { item := slice[fromIndex] slice = Remove(slice, fromIndex) return slices.Insert(slice, toIndex, item) } // Pops item from the end of the slice and returns it, along with the updated slice // Mutates original slice. Intended usage is to reassign the slice result to the input slice. func Pop[T any](slice []T) (T, []T) { index := len(slice) - 1 value := slice[index] slice = slice[0:index] return value, slice } // Shifts item from the beginning of the slice and returns it, along with the updated slice. // Mutates original slice. Intended usage is to reassign the slice result to the input slice. func Shift[T any](slice []T) (T, []T) { value := slice[0] slice = slice[1:] return value, slice }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/color.go
pkg/utils/color.go
package utils import ( "regexp" "sync" "github.com/gookit/color" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/samber/lo" ) var ( decoloriseCache = make(map[string]string) decoloriseMutex sync.RWMutex ) // Decolorise strips a string of color func Decolorise(str string) string { decoloriseMutex.RLock() val := decoloriseCache[str] decoloriseMutex.RUnlock() if val != "" { return val } re := regexp.MustCompile(`\x1B\[([0-9]{1,3}(;[0-9]{1,3})*)?[mGK]`) linkRe := regexp.MustCompile(`\x1B]8;[^;]*;(.*?)(\x1B.|\x07)`) ret := re.ReplaceAllString(str, "") ret = linkRe.ReplaceAllString(ret, "") decoloriseMutex.Lock() decoloriseCache[str] = ret decoloriseMutex.Unlock() return ret } func IsValidHexValue(v string) bool { if len(v) != 4 && len(v) != 7 { return false } if v[0] != '#' { return false } for _, char := range v[1:] { switch char { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F': continue default: return false } } return true } func SetCustomColors(customColors map[string]string) map[string]*style.TextStyle { return lo.MapValues(customColors, func(c string, key string) *style.TextStyle { if s, ok := style.ColorMap[c]; ok { return &s.Foreground } value := style.New().SetFg(style.NewRGBColor(color.HEX(c, false))) return &value }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/utils_test.go
pkg/utils/utils_test.go
package utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestAsJson(t *testing.T) { type myStruct struct { a string } output := AsJson(&myStruct{a: "foo"}) // no idea why this is returning empty hashes but it's works in the app ¯\_(ツ)_/¯ assert.EqualValues(t, "{}", output) } func TestSafeTruncate(t *testing.T) { type scenario struct { str string limit int expected string } scenarios := []scenario{ { str: "", limit: 0, expected: "", }, { str: "12345", limit: 3, expected: "123", }, { str: "12345", limit: 4, expected: "1234", }, { str: "12345", limit: 5, expected: "12345", }, { str: "12345", limit: 6, expected: "12345", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, SafeTruncate(s.str, s.limit)) } } func TestModuloWithWrap(t *testing.T) { type scenario struct { n int max int expected int } scenarios := []scenario{ { n: 0, max: 0, expected: 0, }, { n: 0, max: 1, expected: 0, }, { n: 1, max: 0, expected: 0, }, { n: 3, max: 2, expected: 1, }, { n: -1, max: 2, expected: 1, }, } for _, s := range scenarios { if s.expected != ModuloWithWrap(s.n, s.max) { t.Errorf("expected %d, got %d, for n: %d, max: %d", s.expected, ModuloWithWrap(s.n, s.max), s.n, s.max) } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/search.go
pkg/utils/search.go
package utils import ( "strings" "github.com/sahilm/fuzzy" "github.com/samber/lo" ) func FilterStrings(needle string, haystack []string, useFuzzySearch bool) []string { if needle == "" { return []string{} } matches := Find(needle, haystack, useFuzzySearch) return lo.Map(matches, func(match fuzzy.Match, _ int) string { return match.Str }) } // Duplicated from the fuzzy package because it's private there type stringSource []string func (ss stringSource) String(i int) string { return ss[i] } func (ss stringSource) Len() int { return len(ss) } // Drop-in replacement for fuzzy.Find (except that it doesn't fill out // MatchedIndexes or Score, but we are not using these) func FindSubstrings(pattern string, data []string) fuzzy.Matches { return FindSubstringsFrom(pattern, stringSource(data)) } // Drop-in replacement for fuzzy.FindFrom (except that it doesn't fill out // MatchedIndexes or Score, but we are not using these) func FindSubstringsFrom(pattern string, data fuzzy.Source) fuzzy.Matches { substrings := strings.Fields(pattern) result := fuzzy.Matches{} outer: for i := range data.Len() { s := data.String(i) for _, sub := range substrings { if !CaseAwareContains(s, sub) { continue outer } } result = append(result, fuzzy.Match{Str: s, Index: i}) } return result } func Find(pattern string, data []string, useFuzzySearch bool) fuzzy.Matches { if useFuzzySearch { return fuzzy.Find(pattern, data) } return FindSubstrings(pattern, data) } func FindFrom(pattern string, data fuzzy.Source, useFuzzySearch bool) fuzzy.Matches { if useFuzzySearch { return fuzzy.FindFrom(pattern, data) } return FindSubstringsFrom(pattern, data) } func CaseAwareContains(haystack, needle string) bool { // if needle contains an uppercase letter, we'll do a case sensitive search if ContainsUppercase(needle) { return strings.Contains(haystack, needle) } return CaseInsensitiveContains(haystack, needle) } func ContainsUppercase(s string) bool { for _, r := range s { if r >= 'A' && r <= 'Z' { return true } } return false } func CaseInsensitiveContains(haystack, needle string) bool { return strings.Contains( strings.ToLower(haystack), strings.ToLower(needle), ) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/date.go
pkg/utils/date.go
package utils import ( "fmt" "time" ) func UnixToTimeAgo(timestamp int64) string { now := time.Now().Unix() return formatSecondsAgo(now - timestamp) } const ( SECONDS_IN_SECOND = 1 SECONDS_IN_MINUTE = 60 SECONDS_IN_HOUR = 3600 SECONDS_IN_DAY = 86400 SECONDS_IN_WEEK = 604800 SECONDS_IN_YEAR = 31536000 SECONDS_IN_MONTH = SECONDS_IN_YEAR / 12 ) type period struct { label string secondsInPeriod int64 } var periods = []period{ {"s", SECONDS_IN_SECOND}, {"m", SECONDS_IN_MINUTE}, {"h", SECONDS_IN_HOUR}, {"d", SECONDS_IN_DAY}, {"w", SECONDS_IN_WEEK}, {"M", SECONDS_IN_MONTH}, {"y", SECONDS_IN_YEAR}, } func formatSecondsAgo(secondsAgo int64) string { for i, period := range periods { if i == 0 { continue } if secondsAgo < period.secondsInPeriod { return fmt.Sprintf("%d%s", secondsAgo/periods[i-1].secondsInPeriod, periods[i-1].label, ) } } return fmt.Sprintf("%d%s", secondsAgo/periods[len(periods)-1].secondsInPeriod, periods[len(periods)-1].label, ) } // formats the date in a smart way, if the date is today, it will show the time, otherwise it will show the date func UnixToDateSmart(now time.Time, timestamp int64, longTimeFormat string, shortTimeFormat string) string { date := time.Unix(timestamp, 0) if date.Day() == now.Day() && date.Month() == now.Month() && date.Year() == now.Year() { return date.Format(shortTimeFormat) } return date.Format(longTimeFormat) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/history_buffer_test.go
pkg/utils/history_buffer_test.go
package utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewHistoryBuffer(t *testing.T) { hb := NewHistoryBuffer[int](5) assert.NotNil(t, hb) assert.Equal(t, 5, hb.maxSize) assert.Equal(t, 0, len(hb.items)) } func TestPush(t *testing.T) { hb := NewHistoryBuffer[int](3) hb.Push(1) hb.Push(2) hb.Push(3) hb.Push(4) assert.Equal(t, 3, len(hb.items)) assert.Equal(t, []int{4, 3, 2}, hb.items) } func TestPeekAt(t *testing.T) { hb := NewHistoryBuffer[int](3) hb.Push(1) hb.Push(2) hb.Push(3) item, err := hb.PeekAt(0) assert.Nil(t, err) assert.Equal(t, 3, item) item, err = hb.PeekAt(1) assert.Nil(t, err) assert.Equal(t, 2, item) item, err = hb.PeekAt(2) assert.Nil(t, err) assert.Equal(t, 1, item) item, err = hb.PeekAt(-1) assert.Nil(t, err) assert.Equal(t, 0, item) _, err = hb.PeekAt(3) assert.NotNil(t, err) assert.Equal(t, "Index out of range", err.Error()) _, err = hb.PeekAt(-2) assert.NotNil(t, err) assert.Equal(t, "Index out of range", err.Error()) } func TestPeekAtEmptyBuffer(t *testing.T) { hb := NewHistoryBuffer[int](3) _, err := hb.PeekAt(0) assert.NotNil(t, err) assert.Equal(t, "Buffer is empty", err.Error()) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/rebase_todo_test.go
pkg/utils/rebase_todo_test.go
package utils import ( "errors" "fmt" "testing" "github.com/stefanhaller/git-todo-parser/todo" "github.com/stretchr/testify/assert" ) func TestRebaseCommands_moveTodoDown(t *testing.T) { type scenario struct { testName string todos []todo.Todo todoToMoveDown Todo isInRebase bool expectedErr string expectedTodos []todo.Todo } scenarios := []scenario{ { testName: "simple case 1 - move to beginning", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveDown: Todo{Hash: "5678"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, }, }, { testName: "simple case 2 - move from end", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveDown: Todo{Hash: "abcd"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Pick, Commit: "5678"}, }, }, { testName: "move update-ref todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, }, todoToMoveDown: Todo{Ref: "refs/heads/some_branch"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, }, { testName: "move across update-ref todo in rebase", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveDown: Todo{Hash: "5678"}, isInRebase: true, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, }, }, { testName: "move across update-ref todo outside of rebase", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveDown: Todo{Hash: "5678"}, isInRebase: false, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, }, }, { testName: "move across exec todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Exec, ExecCommand: "make test"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveDown: Todo{Hash: "5678"}, isInRebase: true, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Exec, ExecCommand: "make test"}, }, }, { testName: "skip an invisible todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Label, Label: "myLabel"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "def0"}, }, todoToMoveDown: Todo{Hash: "5678"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Label, Label: "myLabel"}, {Command: todo.Pick, Commit: "def0"}, }, }, // Error cases { testName: "commit not found", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveDown: Todo{Hash: "def0"}, expectedErr: "Todo def0 not found in git-rebase-todo", expectedTodos: []todo.Todo{}, }, { testName: "trying to move first commit down", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveDown: Todo{Hash: "1234"}, expectedErr: "Destination position for moving todo is out of range", expectedTodos: []todo.Todo{}, }, { testName: "trying to move commit down when all commits before are invisible", todos: []todo.Todo{ {Command: todo.Label, Label: "myLabel"}, {Command: todo.Reset, Label: "otherlabel"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveDown: Todo{Hash: "1234"}, expectedErr: "Destination position for moving todo is out of range", expectedTodos: []todo.Todo{}, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { rearrangedTodos, err := moveTodoDown(s.todos, s.todoToMoveDown, s.isInRebase) if s.expectedErr == "" { assert.NoError(t, err) } else { assert.ErrorContains(t, err, s.expectedErr) } assert.Equal(t, s.expectedTodos, rearrangedTodos) }, ) } } func TestRebaseCommands_moveTodoUp(t *testing.T) { type scenario struct { testName string todos []todo.Todo todoToMoveUp Todo isInRebase bool expectedErr string expectedTodos []todo.Todo } scenarios := []scenario{ { testName: "simple case 1 - move to end", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveUp: Todo{Hash: "5678"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Pick, Commit: "5678"}, }, }, { testName: "simple case 2 - move from beginning", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveUp: Todo{Hash: "1234"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, }, }, { testName: "move update-ref todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveUp: Todo{Ref: "refs/heads/some_branch"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, }, }, { testName: "move across update-ref todo in rebase", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveUp: Todo{Hash: "1234"}, isInRebase: true, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, }, }, { testName: "move across update-ref todo outside of rebase", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveUp: Todo{Hash: "1234"}, isInRebase: false, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "1234"}, }, }, { testName: "move across exec todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Exec, ExecCommand: "make test"}, {Command: todo.Pick, Commit: "5678"}, }, todoToMoveUp: Todo{Hash: "1234"}, isInRebase: true, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Exec, ExecCommand: "make test"}, {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, }, }, { testName: "skip an invisible todo", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Label, Label: "myLabel"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "def0"}, }, todoToMoveUp: Todo{Hash: "abcd"}, expectedErr: "", expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Label, Label: "myLabel"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, {Command: todo.Pick, Commit: "def0"}, }, }, // Error cases { testName: "commit not found", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveUp: Todo{Hash: "def0"}, expectedErr: "Todo def0 not found in git-rebase-todo", expectedTodos: []todo.Todo{}, }, { testName: "trying to move last commit up", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todoToMoveUp: Todo{Hash: "abcd"}, expectedErr: "Destination position for moving todo is out of range", expectedTodos: []todo.Todo{}, }, { testName: "trying to move commit up when all commits after it are invisible", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Label, Label: "myLabel"}, {Command: todo.Reset, Label: "otherlabel"}, }, todoToMoveUp: Todo{Hash: "5678"}, expectedErr: "Destination position for moving todo is out of range", expectedTodos: []todo.Todo{}, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { rearrangedTodos, err := moveTodoUp(s.todos, s.todoToMoveUp, s.isInRebase) if s.expectedErr == "" { assert.NoError(t, err) } else { assert.ErrorContains(t, err, s.expectedErr) } assert.Equal(t, s.expectedTodos, rearrangedTodos) }, ) } } func TestRebaseCommands_moveFixupCommitDown(t *testing.T) { scenarios := []struct { name string todos []todo.Todo originalHash string fixupHash string changeToFixup bool expectedTodos []todo.Todo expectedErr error }{ { name: "fixup commit is the last commit (change to fixup)", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Fixup, Commit: "fixup"}, }, expectedErr: nil, }, { name: "fixup commit is the last commit (don't change to fixup)", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: false, expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "fixup"}, }, expectedErr: nil, }, { name: "fixup commit is separated from original commit", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "other"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Fixup, Commit: "fixup"}, {Command: todo.Pick, Commit: "other"}, }, expectedErr: nil, }, { name: "fixup commit is separated from original merge commit", todos: []todo.Todo{ {Command: todo.Merge, Commit: "original"}, {Command: todo.Pick, Commit: "other"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: []todo.Todo{ {Command: todo.Merge, Commit: "original"}, {Command: todo.Fixup, Commit: "fixup"}, {Command: todo.Pick, Commit: "other"}, }, expectedErr: nil, }, { name: "More original hashes than expected", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: nil, expectedErr: errors.New("Expected exactly one original hash, found 2"), }, { name: "More fixup hashes than expected", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, {Command: todo.Pick, Commit: "fixup"}, {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: nil, expectedErr: errors.New("Expected exactly one fixup hash, found 2"), }, { name: "No fixup hashes found", todos: []todo.Todo{ {Command: todo.Pick, Commit: "original"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: nil, expectedErr: errors.New("Expected exactly one fixup hash, found 0"), }, { name: "No original hashes found", todos: []todo.Todo{ {Command: todo.Pick, Commit: "fixup"}, }, originalHash: "original", fixupHash: "fixup", changeToFixup: true, expectedTodos: nil, expectedErr: errors.New("Expected exactly one original hash, found 0"), }, } for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { actualTodos, actualErr := moveFixupCommitDown(scenario.todos, scenario.originalHash, scenario.fixupHash, scenario.changeToFixup) if scenario.expectedErr == nil { assert.NoError(t, actualErr) } else { assert.EqualError(t, actualErr, scenario.expectedErr.Error()) } assert.EqualValues(t, scenario.expectedTodos, actualTodos) }) } } func TestRebaseCommands_deleteTodos(t *testing.T) { scenarios := []struct { name string todos []todo.Todo todosToDelete []Todo expectedTodos []todo.Todo expectedErr error }{ { name: "success", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.UpdateRef, Ref: "refs/heads/some_branch"}, {Command: todo.Pick, Commit: "5678"}, {Command: todo.Pick, Commit: "abcd"}, }, todosToDelete: []Todo{ {Ref: "refs/heads/some_branch"}, {Hash: "abcd"}, }, expectedTodos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, }, expectedErr: nil, }, { name: "failure", todos: []todo.Todo{ {Command: todo.Pick, Commit: "1234"}, {Command: todo.Pick, Commit: "5678"}, }, todosToDelete: []Todo{ {Hash: "abcd"}, }, expectedTodos: []todo.Todo{}, expectedErr: errors.New("Todo abcd not found in git-rebase-todo"), }, } for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { actualTodos, actualErr := deleteTodos(scenario.todos, scenario.todosToDelete) if scenario.expectedErr == nil { assert.NoError(t, actualErr) } else { assert.EqualError(t, actualErr, scenario.expectedErr.Error()) } assert.EqualValues(t, scenario.expectedTodos, actualTodos) }) } } func Test_equalHash(t *testing.T) { scenarios := []struct { a string b string expected bool }{ {"", "", true}, {"", "123", false}, {"123", "", false}, {"123", "123", true}, {"123", "123abc", true}, {"123abc", "123", true}, {"123", "a", false}, {"1", "abc", false}, } for _, scenario := range scenarios { t.Run(fmt.Sprintf("'%s' vs. '%s'", scenario.a, scenario.b), func(t *testing.T) { assert.Equal(t, scenario.expected, equalHash(scenario.a, scenario.b)) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/search_test.go
pkg/utils/search_test.go
package utils import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestFilterStrings(t *testing.T) { type scenario struct { needle string haystack []string useFuzzySearch bool expected []string } scenarios := []scenario{ { needle: "", haystack: []string{"test"}, useFuzzySearch: true, expected: []string{}, }, { needle: "test", haystack: []string{"test"}, useFuzzySearch: true, expected: []string{"test"}, }, { needle: "o", haystack: []string{"a", "o", "e"}, useFuzzySearch: true, expected: []string{"o"}, }, { needle: "mybranch", haystack: []string{"my_branch", "mybranch", "branch", "this is my branch"}, useFuzzySearch: true, expected: []string{"mybranch", "my_branch", "this is my branch"}, }, { needle: "test", haystack: []string{"not a good match", "this 'test' is a good match", "test"}, useFuzzySearch: true, expected: []string{"test", "this 'test' is a good match"}, }, { needle: "test", haystack: []string{"Test"}, useFuzzySearch: true, expected: []string{"Test"}, }, { needle: "test", haystack: []string{"integration-testing", "t_e_s_t"}, useFuzzySearch: false, expected: []string{"integration-testing"}, }, { needle: "integr test", haystack: []string{"integration-testing", "testing-integration"}, useFuzzySearch: false, expected: []string{"integration-testing", "testing-integration"}, }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, FilterStrings(s.needle, s.haystack, s.useFuzzySearch)) } } func TestCaseInsensitiveContains(t *testing.T) { testCases := []struct { haystack string needle string expected bool }{ {"Hello, World!", "world", true}, // Case-insensitive match {"Hello, World!", "WORLD", true}, // Case-insensitive match {"Hello, World!", "orl", true}, // Case-insensitive match {"Hello, World!", "o, W", true}, // Case-insensitive match {"Hello, World!", "hello", true}, // Case-insensitive match {"Hello, World!", "Foo", false}, // No match {"Hello, World!", "Hello, World!!", false}, // No match {"Hello, World!", "", true}, // Empty needle matches {"", "Hello", false}, // Empty haystack doesn't match {"", "", true}, // Empty strings match {"", " ", false}, // Empty haystack, non-empty needle {" ", "", true}, // Non-empty haystack, empty needle } for i, testCase := range testCases { result := CaseInsensitiveContains(testCase.haystack, testCase.needle) assert.Equal(t, testCase.expected, result, fmt.Sprintf("Test case %d failed. Expected '%v', got '%v' for '%s' in '%s'", i, testCase.expected, result, testCase.needle, testCase.haystack)) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/lines.go
pkg/utils/lines.go
package utils import ( "bytes" "strings" "github.com/rivo/uniseg" ) // SplitLines takes a multiline string and splits it on newlines // currently we are also stripping \r's which may have adverse effects for // windows users (but no issues have been raised yet) func SplitLines(multilineString string) []string { multilineString = strings.ReplaceAll(multilineString, "\r", "") if multilineString == "" || multilineString == "\n" { return make([]string, 0) } lines := strings.Split(multilineString, "\n") if lines[len(lines)-1] == "" { return lines[:len(lines)-1] } return lines } func SplitNul(str string) []string { if str == "" { return make([]string, 0) } str = strings.TrimSuffix(str, "\x00") return strings.Split(str, "\x00") } // NormalizeLinefeeds - Removes all Windows and Mac style line feeds func NormalizeLinefeeds(str string) string { str = strings.ReplaceAll(str, "\r\n", "\n") str = strings.ReplaceAll(str, "\r", "") return str } // EscapeSpecialChars - Replaces all special chars like \n with \\n func EscapeSpecialChars(str string) string { return strings.NewReplacer( "\n", "\\n", "\r", "\\r", "\t", "\\t", "\b", "\\b", "\f", "\\f", "\v", "\\v", ).Replace(str) } func dropCR(data []byte) []byte { if len(data) > 0 && data[len(data)-1] == '\r' { return data[0 : len(data)-1] } return data } // ScanLinesAndTruncateWhenLongerThanBuffer returns a split function that can be // used with bufio.Scanner.Split(). It is very similar to bufio.ScanLines, // except that it will truncate lines that are longer than the scanner's read // buffer (whereas bufio.ScanLines will return an error in that case, which is // often difficult to handle). // // If you are using your own buffer for the scanner, you must set maxBufferSize // to the same value as the max parameter that you passed to scanner.Buffer(). // Otherwise, maxBufferSize must be set to bufio.MaxScanTokenSize. func ScanLinesAndTruncateWhenLongerThanBuffer(maxBufferSize int) func(data []byte, atEOF bool) (int, []byte, error) { skipOverRemainderOfLongLine := false return func(data []byte, atEOF bool) (int, []byte, error) { if atEOF && len(data) == 0 { // Done return 0, nil, nil } if i := bytes.IndexByte(data, '\n'); i >= 0 { if skipOverRemainderOfLongLine { skipOverRemainderOfLongLine = false return i + 1, nil, nil } return i + 1, dropCR(data[0:i]), nil } if atEOF { if skipOverRemainderOfLongLine { return len(data), nil, nil } return len(data), dropCR(data), nil } // Buffer is full, so we can't get more data if len(data) >= maxBufferSize { if skipOverRemainderOfLongLine { return len(data), nil, nil } skipOverRemainderOfLongLine = true return len(data), data, nil } // Request more data. return 0, nil, nil } } // Wrap lines to a given width, and return: // - the wrapped lines // - the line indices of the wrapped lines, indexed by the original line indices // - the line indices of the original lines, indexed by the wrapped line indices // If wrap is false, the text is returned as is. // This code needs to behave the same as `gocui.lineWrap` does. func WrapViewLinesToWidth(wrap bool, editable bool, text string, width int, tabWidth int) ([]string, []int, []int) { if !editable { text = strings.TrimSuffix(text, "\n") } lines := strings.Split(text, "\n") if !wrap { indices := make([]int, len(lines)) for i := range lines { indices[i] = i } return lines, indices, indices } wrappedLines := make([]string, 0, len(lines)) wrappedLineIndices := make([]int, 0, len(lines)) originalLineIndices := make([]int, 0, len(lines)) if tabWidth < 1 { tabWidth = 4 } for originalLineIdx, line := range lines { wrappedLineIndices = append(wrappedLineIndices, len(wrappedLines)) // convert tabs to spaces for i := 0; i < len(line); i++ { if line[i] == '\t' { numSpaces := tabWidth - (i % tabWidth) line = line[:i] + strings.Repeat(" ", numSpaces) + line[i+1:] i += numSpaces - 1 } } appendWrappedLine := func(str string) { wrappedLines = append(wrappedLines, str) originalLineIndices = append(originalLineIndices, originalLineIdx) } n := 0 offset := 0 lastWhitespaceIndex := -1 for i, currChr := range line { rw := uniseg.StringWidth(string(currChr)) n += rw if n > width { if currChr == ' ' { appendWrappedLine(line[offset:i]) offset = i + 1 n = 0 } else if currChr == '-' { appendWrappedLine(line[offset:i]) offset = i n = rw } else if lastWhitespaceIndex != -1 { if line[lastWhitespaceIndex] == '-' { appendWrappedLine(line[offset : lastWhitespaceIndex+1]) } else { appendWrappedLine(line[offset:lastWhitespaceIndex]) } offset = lastWhitespaceIndex + 1 n = uniseg.StringWidth(line[offset : i+1]) } else { appendWrappedLine(line[offset:i]) offset = i n = rw } lastWhitespaceIndex = -1 } else if currChr == ' ' || currChr == '-' { lastWhitespaceIndex = i } } appendWrappedLine(line[offset:]) } return wrappedLines, wrappedLineIndices, originalLineIndices }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/template_test.go
pkg/utils/template_test.go
package utils import ( "testing" "github.com/stretchr/testify/assert" ) // TestResolvePlaceholderString is a function. func TestResolvePlaceholderString(t *testing.T) { type scenario struct { templateString string arguments map[string]string expected string } scenarios := []scenario{ { "", map[string]string{}, "", }, { "hello", map[string]string{}, "hello", }, { "hello {{arg}}", map[string]string{}, "hello {{arg}}", }, { "hello {{arg}}", map[string]string{"arg": "there"}, "hello there", }, { "hello", map[string]string{"arg": "there"}, "hello", }, { "{{nothing}}", map[string]string{"nothing": ""}, "", }, { "{{}} {{ this }} { should not throw}} an {{{{}}}} error", map[string]string{ "blah": "blah", "this": "won't match", }, "{{}} {{ this }} { should not throw}} an {{{{}}}} error", }, { "{{a}}", map[string]string{ "a": "X{{.a}}X", }, "X{{.a}}X", }, } for _, s := range scenarios { assert.EqualValues(t, s.expected, ResolvePlaceholderString(s.templateString, s.arguments)) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/once_writer_test.go
pkg/utils/once_writer_test.go
package utils import ( "bytes" "testing" ) func TestOnceWriter(t *testing.T) { innerWriter := bytes.NewBuffer(nil) counter := 0 onceWriter := NewOnceWriter(innerWriter, func() { counter++ }) _, _ = onceWriter.Write([]byte("hello")) _, _ = onceWriter.Write([]byte("hello")) if counter != 1 { t.Errorf("expected counter to be 1, got %d", counter) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/template.go
pkg/utils/template.go
package utils import ( "bytes" "strings" "text/template" ) func ResolveTemplate(templateStr string, object any, funcs template.FuncMap) (string, error) { tmpl, err := template.New("template").Funcs(funcs).Option("missingkey=error").Parse(templateStr) if err != nil { return "", err } var buf bytes.Buffer if err := tmpl.Execute(&buf, object); err != nil { return "", err } return buf.String(), nil } // ResolvePlaceholderString populates a template with values func ResolvePlaceholderString(str string, arguments map[string]string) string { oldnews := make([]string, 0, len(arguments)*4) for key, value := range arguments { oldnews = append(oldnews, "{{"+key+"}}", value, "{{."+key+"}}", value, ) } return strings.NewReplacer(oldnews...).Replace(str) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/once_writer.go
pkg/utils/once_writer.go
package utils import ( "io" "sync" ) // This wraps a writer and ensures that before we actually write anything we call a given function first type OnceWriter struct { writer io.Writer once sync.Once f func() } var _ io.Writer = &OnceWriter{} func NewOnceWriter(writer io.Writer, f func()) *OnceWriter { return &OnceWriter{ writer: writer, f: f, } } func (self *OnceWriter) Write(p []byte) (n int, err error) { self.once.Do(func() { self.f() }) return self.writer.Write(p) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/string_pool.go
pkg/utils/string_pool.go
package utils import "sync" // A simple string pool implementation that can help reduce memory usage for // cases where the same string is used multiple times. type StringPool struct { sync.Map } func (self *StringPool) Add(s string) *string { poolEntry, _ := self.LoadOrStore(s, &s) return poolEntry.(*string) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/yaml_utils/yaml_utils.go
pkg/utils/yaml_utils/yaml_utils.go
package yaml_utils import ( "bytes" "errors" "fmt" "slices" "gopkg.in/yaml.v3" ) func LookupKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) { for i := 0; i < len(node.Content)-1; i += 2 { if node.Content[i].Value == key { return node.Content[i], node.Content[i+1] } } return nil, nil } // Returns the key and value if they were present func RemoveKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) { for i := 0; i < len(node.Content)-1; i += 2 { if node.Content[i].Value == key { key, value := node.Content[i], node.Content[i+1] node.Content = slices.Delete(node.Content, i, i+2) return key, value } } return nil, nil } // Walks a yaml document from the root node to the specified path, and then applies the transformation to that node. // If the requested path is not defined in the document, no changes are made to the document. func TransformNode(rootNode *yaml.Node, path []string, transform func(node *yaml.Node) error) error { // Empty document: nothing to do. if len(rootNode.Content) == 0 { return nil } body := rootNode.Content[0] if err := transformNode(body, path, transform); err != nil { return err } return nil } // A recursive function to walk down the tree. See TransformNode for more details. func transformNode(node *yaml.Node, path []string, transform func(node *yaml.Node) error) error { if len(path) == 0 { return transform(node) } keyNode, valueNode := LookupKey(node, path[0]) if keyNode == nil { return nil } return transformNode(valueNode, path[1:], transform) } // Takes the root node of a yaml document, a path to a key, and a new name for the key. // Will rename the key to the new name if it exists, and do nothing otherwise. func RenameYamlKey(rootNode *yaml.Node, path []string, newKey string) (error, bool) { // Empty document: nothing to do. if len(rootNode.Content) == 0 { return nil, false } body := rootNode.Content[0] return renameYamlKey(body, path, newKey) } // Recursive function to rename the YAML key. func renameYamlKey(node *yaml.Node, path []string, newKey string) (error, bool) { if node.Kind != yaml.MappingNode { return errors.New("yaml node in path is not a dictionary"), false } keyNode, valueNode := LookupKey(node, path[0]) if keyNode == nil { return nil, false } // end of path reached: rename key if len(path) == 1 { // Check that new key doesn't exist yet if newKeyNode, _ := LookupKey(node, newKey); newKeyNode != nil { return fmt.Errorf("new key `%s' already exists", newKey), false } keyNode.Value = newKey return nil, true } return renameYamlKey(valueNode, path[1:], newKey) } // Traverses a yaml document, calling the callback function for each node. The // callback is expected to modify the node in place func Walk(rootNode *yaml.Node, callback func(node *yaml.Node, path string)) error { // Empty document: nothing to do. if len(rootNode.Content) == 0 { return nil } body := rootNode.Content[0] if err := walk(body, "", callback); err != nil { return err } return nil } func walk(node *yaml.Node, path string, callback func(*yaml.Node, string)) error { callback(node, path) switch node.Kind { case yaml.DocumentNode: return errors.New("Unexpected document node in the middle of a yaml tree") case yaml.MappingNode: for i := 0; i < len(node.Content); i += 2 { name := node.Content[i].Value childNode := node.Content[i+1] var childPath string if path == "" { childPath = name } else { childPath = fmt.Sprintf("%s.%s", path, name) } err := walk(childNode, childPath, callback) if err != nil { return err } } case yaml.SequenceNode: for i := range len(node.Content) { childPath := fmt.Sprintf("%s[%d]", path, i) err := walk(node.Content[i], childPath, callback) if err != nil { return err } } case yaml.ScalarNode: // nothing to do case yaml.AliasNode: return errors.New("Alias nodes are not supported") } return nil } func YamlMarshal(node *yaml.Node) ([]byte, error) { var buffer bytes.Buffer encoder := yaml.NewEncoder(&buffer) encoder.SetIndent(2) err := encoder.Encode(node) return buffer.Bytes(), err }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/utils/yaml_utils/yaml_utils_test.go
pkg/utils/yaml_utils/yaml_utils_test.go
package yaml_utils import ( "fmt" "testing" "github.com/stretchr/testify/assert" "gopkg.in/yaml.v3" ) func TestRenameYamlKey(t *testing.T) { tests := []struct { name string in string path []string newKey string expectedOut string expectedDidRename bool expectedErr string }{ { name: "rename key", in: "foo: 5\n", path: []string{"foo"}, newKey: "bar", expectedOut: "bar: 5\n", expectedDidRename: true, expectedErr: "", }, { name: "rename key, nested", in: "foo:\n bar: 5\n", path: []string{"foo", "bar"}, newKey: "baz", expectedOut: "foo:\n baz: 5\n", expectedDidRename: true, expectedErr: "", }, { name: "rename non-scalar key", in: "foo:\n bar: 5\n", path: []string{"foo"}, newKey: "qux", expectedOut: "qux:\n bar: 5\n", expectedDidRename: true, expectedErr: "", }, { name: "don't rewrite file if value didn't change", in: "foo:\n bar: 5\n", path: []string{"nonExistingKey"}, newKey: "qux", expectedOut: "foo:\n bar: 5\n", expectedDidRename: false, expectedErr: "", }, // Error cases { name: "existing document is not a dictionary", in: "42\n", path: []string{"foo"}, newKey: "bar", expectedOut: "42\n", expectedDidRename: false, expectedErr: "yaml node in path is not a dictionary", }, { name: "not all path elements are dictionaries", in: "foo:\n bar: [1, 2, 3]\n", path: []string{"foo", "bar", "baz"}, newKey: "qux", expectedOut: "foo:\n bar: [1, 2, 3]\n", expectedDidRename: false, expectedErr: "yaml node in path is not a dictionary", }, { name: "new key exists", in: "foo: 5\nbar: 7\n", path: []string{"foo"}, newKey: "bar", expectedOut: "foo: 5\nbar: 7\n", expectedDidRename: false, expectedErr: "new key `bar' already exists", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { node := unmarshalForTest(t, test.in) actualErr, didRename := RenameYamlKey(&node, test.path, test.newKey) if test.expectedErr == "" { assert.NoError(t, actualErr) } else { assert.EqualError(t, actualErr, test.expectedErr) } out := marshalForTest(t, &node) assert.Equal(t, test.expectedOut, out) assert.Equal(t, test.expectedDidRename, didRename) }) } } func TestWalk_paths(t *testing.T) { tests := []struct { name string document string expectedPaths []string }{ { name: "empty document", document: "", expectedPaths: []string{}, }, { name: "scalar", document: "x: 5", expectedPaths: []string{"", "x"}, // called with an empty path for the root node }, { name: "nested", document: "foo:\n x: 5", expectedPaths: []string{"", "foo", "foo.x"}, }, { name: "deeply nested", document: "foo:\n bar:\n baz: 5", expectedPaths: []string{"", "foo", "foo.bar", "foo.bar.baz"}, }, { name: "array", document: "foo:\n bar: [3, 7]", expectedPaths: []string{"", "foo", "foo.bar", "foo.bar[0]", "foo.bar[1]"}, }, { name: "nested arrays", document: "foo:\n bar: [[3, 7], [8, 9]]", expectedPaths: []string{"", "foo", "foo.bar", "foo.bar[0]", "foo.bar[0][0]", "foo.bar[0][1]", "foo.bar[1]", "foo.bar[1][0]", "foo.bar[1][1]"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { node := unmarshalForTest(t, test.document) paths := []string{} err := Walk(&node, func(node *yaml.Node, path string) { paths = append(paths, path) }) assert.NoError(t, err) assert.Equal(t, test.expectedPaths, paths) }) } } func TestWalk_inPlaceChanges(t *testing.T) { tests := []struct { name string in string callback func(node *yaml.Node, path string) expectedOut string }{ { name: "no change", in: "x: 5", callback: func(node *yaml.Node, path string) {}, }, { name: "change value", in: "x: 5\ny: 3", callback: func(node *yaml.Node, path string) { if path == "x" { node.Value = "7" } }, expectedOut: "x: 7\ny: 3\n", }, { name: "change nested value", in: "x:\n y: 5", callback: func(node *yaml.Node, path string) { if path == "x.y" { node.Value = "7" } }, expectedOut: "x:\n y: 7\n", }, { name: "change array value", in: "x:\n - y: 5", callback: func(node *yaml.Node, path string) { if path == "x[0].y" { node.Value = "7" } }, expectedOut: "x:\n - y: 7\n", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { node := unmarshalForTest(t, test.in) err := Walk(&node, test.callback) assert.NoError(t, err) if test.expectedOut == "" { unmodifiedOriginal := unmarshalForTest(t, test.in) assert.Equal(t, unmodifiedOriginal, node) } else { result := marshalForTest(t, &node) assert.Equal(t, test.expectedOut, result) } }) } } func TestTransformNode(t *testing.T) { transformIntValueToString := func(node *yaml.Node) error { if node.Kind == yaml.ScalarNode { if node.ShortTag() == "!!int" { node.Tag = "!!str" return nil } else if node.ShortTag() == "!!str" { // We have already transformed it, return nil } return fmt.Errorf("Node was of bad type") } return fmt.Errorf("Node was not a scalar") } tests := []struct { name string in string path []string transform func(node *yaml.Node) error expectedOut string }{ { name: "Path not present", in: "foo: 1", path: []string{"bar"}, transform: transformIntValueToString, }, { name: "Part of path present", in: ` foo: bar: 2`, path: []string{"foo", "baz"}, transform: transformIntValueToString, }, { name: "Successfully Transforms to string", in: ` foo: bar: 2`, path: []string{"foo", "bar"}, transform: transformIntValueToString, expectedOut: `foo: bar: "2" `, // Note the trailing newline changes because of how it re-marshalls }, { name: "Does nothing when already transformed", in: ` foo: bar: "2"`, path: []string{"foo", "bar"}, transform: transformIntValueToString, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { node := unmarshalForTest(t, test.in) err := TransformNode(&node, test.path, test.transform) if err != nil { t.Fatal(err) } if test.expectedOut == "" { unmodifiedOriginal := unmarshalForTest(t, test.in) assert.Equal(t, unmodifiedOriginal, node) } else { result := marshalForTest(t, &node) assert.Equal(t, test.expectedOut, result) } }) } } func TestRemoveKey(t *testing.T) { tests := []struct { name string in string key string expectedOut string expectedRemovedKey string expectedRemovedValue string }{ { name: "Key not present", in: "foo: 1", key: "bar", }, { name: "Key present", in: "foo: 1\nbar: 2\nbaz: 3\n", key: "bar", expectedOut: "foo: 1\nbaz: 3\n", expectedRemovedKey: "bar", expectedRemovedValue: "2", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { node := unmarshalForTest(t, test.in) removedKey, removedValue := RemoveKey(node.Content[0], test.key) if test.expectedOut == "" { unmodifiedOriginal := unmarshalForTest(t, test.in) assert.Equal(t, unmodifiedOriginal, node) } else { result := marshalForTest(t, &node) assert.Equal(t, test.expectedOut, result) } if test.expectedRemovedKey == "" { assert.Nil(t, removedKey) } else { assert.Equal(t, test.expectedRemovedKey, removedKey.Value) } if test.expectedRemovedValue == "" { assert.Nil(t, removedValue) } else { assert.Equal(t, test.expectedRemovedValue, removedValue.Value) } }) } } func unmarshalForTest(t *testing.T, input string) yaml.Node { t.Helper() var node yaml.Node err := yaml.Unmarshal([]byte(input), &node) if err != nil { t.Fatal(err) } return node } func marshalForTest(t *testing.T, node *yaml.Node) string { t.Helper() result, err := YamlMarshal(node) if err != nil { t.Fatal(err) } return string(result) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/common/dummies.go
pkg/common/dummies.go
package common import ( "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/i18n" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/spf13/afero" ) func NewDummyCommon() *Common { tr := i18n.EnglishTranslationSet() cmn := &Common{ Log: utils.NewDummyLog(), Tr: tr, Fs: afero.NewOsFs(), } cmn.SetUserConfig(config.GetDefaultConfig()) return cmn } func NewDummyCommonWithUserConfigAndAppState(userConfig *config.UserConfig, appState *config.AppState) *Common { tr := i18n.EnglishTranslationSet() cmn := &Common{ Log: utils.NewDummyLog(), Tr: tr, AppState: appState, // TODO: remove dependency on actual filesystem in tests and switch to using // in-memory for everything Fs: afero.NewOsFs(), } cmn.SetUserConfig(userConfig) return cmn }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/common/common.go
pkg/common/common.go
package common import ( "sync/atomic" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/i18n" "github.com/sirupsen/logrus" "github.com/spf13/afero" ) // Commonly used things wrapped into one struct for convenience when passing it around type Common struct { Log *logrus.Entry Tr *i18n.TranslationSet userConfig atomic.Pointer[config.UserConfig] AppState *config.AppState Debug bool // for interacting with the filesystem. We use afero rather than the default // `os` package for the sake of mocking the filesystem in tests Fs afero.Fs } func (c *Common) UserConfig() *config.UserConfig { return c.userConfig.Load() } func (c *Common) SetUserConfig(userConfig *config.UserConfig) { c.userConfig.Store(userConfig) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/theme/style_test.go
pkg/theme/style_test.go
package theme import ( "reflect" "testing" "github.com/gookit/color" "github.com/jesseduffield/lazygit/pkg/gui/style" ) func TestGetTextStyle(t *testing.T) { scenarios := []struct { name string keys []string background bool expected style.TextStyle }{ { name: "empty", keys: []string{""}, background: true, expected: style.New(), }, { name: "named color, fg", keys: []string{"blue"}, background: false, expected: style.New().SetFg(style.NewBasicColor(color.FgBlue)), }, { name: "named color, bg", keys: []string{"blue"}, background: true, expected: style.New().SetBg(style.NewBasicColor(color.BgBlue)), }, { name: "hex color, fg", keys: []string{"#123456"}, background: false, expected: style.New().SetFg(style.NewRGBColor(color.RGBColor{0x12, 0x34, 0x56, 0})), }, { name: "hex color, bg", keys: []string{"#abcdef"}, background: true, expected: style.New().SetBg(style.NewRGBColor(color.RGBColor{0xab, 0xcd, 0xef, 1})), }, } for _, scenario := range scenarios { t.Run(scenario.name, func(t *testing.T) { if actual := GetTextStyle(scenario.keys, scenario.background); !reflect.DeepEqual(actual, scenario.expected) { t.Errorf("GetTextStyle() = %v, expected %v", actual, scenario.expected) } }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/theme/style.go
pkg/theme/style.go
package theme import ( "github.com/gookit/color" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/utils" ) func GetTextStyle(keys []string, background bool) style.TextStyle { s := style.New() for _, key := range keys { switch key { case "bold": s = s.SetBold() case "reverse": s = s.SetReverse() case "underline": s = s.SetUnderline() case "strikethrough": s = s.SetStrikethrough() default: value, present := style.ColorMap[key] if present { var c style.TextStyle if background { c = value.Background } else { c = value.Foreground } s = s.MergeStyle(c) } else if utils.IsValidHexValue(key) { c := style.NewRGBColor(color.HEX(key, background)) if background { s = s.SetBg(c) } else { s = s.SetFg(c) } } } } return s }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/theme/theme.go
pkg/theme/theme.go
package theme import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/style" ) var ( // DefaultTextColor is the default text color DefaultTextColor = style.FgDefault // GocuiDefaultTextColor does the same as DefaultTextColor but this one only colors gocui default text colors GocuiDefaultTextColor = gocui.ColorDefault // ActiveBorderColor is the border color of the active frame ActiveBorderColor gocui.Attribute // InactiveBorderColor is the border color of the inactive active frames InactiveBorderColor gocui.Attribute // FilteredActiveBorderColor is the border color of the active frame, when it's being searched/filtered SearchingActiveBorderColor gocui.Attribute // GocuiSelectedLineBgColor is the background color for the selected line in gocui GocuiSelectedLineBgColor gocui.Attribute // GocuiInactiveViewSelectedLineBgColor is the background color for the selected line in gocui if the view doesn't have focus GocuiInactiveViewSelectedLineBgColor gocui.Attribute OptionsColor gocui.Attribute // SelectedLineBgColor is the background color for the selected line SelectedLineBgColor = style.New() // InactiveViewSelectedLineBgColor is the background color for the selected line if the view doesn't have the focus InactiveViewSelectedLineBgColor = style.New() // CherryPickedCommitColor is the text style when cherry picking a commit CherryPickedCommitTextStyle = style.New() // MarkedBaseCommitTextStyle is the text style of the marked rebase base commit MarkedBaseCommitTextStyle = style.New() OptionsFgColor = style.New() DiffTerminalColor = style.FgMagenta UnstagedChangesColor = style.New() ) // UpdateTheme updates all theme variables func UpdateTheme(themeConfig config.ThemeConfig) { ActiveBorderColor = GetGocuiStyle(themeConfig.ActiveBorderColor) InactiveBorderColor = GetGocuiStyle(themeConfig.InactiveBorderColor) SearchingActiveBorderColor = GetGocuiStyle(themeConfig.SearchingActiveBorderColor) SelectedLineBgColor = GetTextStyle(themeConfig.SelectedLineBgColor, true) InactiveViewSelectedLineBgColor = GetTextStyle(themeConfig.InactiveViewSelectedLineBgColor, true) cherryPickedCommitBgTextStyle := GetTextStyle(themeConfig.CherryPickedCommitBgColor, true) cherryPickedCommitFgTextStyle := GetTextStyle(themeConfig.CherryPickedCommitFgColor, false) CherryPickedCommitTextStyle = cherryPickedCommitBgTextStyle.MergeStyle(cherryPickedCommitFgTextStyle) markedBaseCommitBgTextStyle := GetTextStyle(themeConfig.MarkedBaseCommitBgColor, true) markedBaseCommitFgTextStyle := GetTextStyle(themeConfig.MarkedBaseCommitFgColor, false) MarkedBaseCommitTextStyle = markedBaseCommitBgTextStyle.MergeStyle(markedBaseCommitFgTextStyle) unstagedChangesTextStyle := GetTextStyle(themeConfig.UnstagedChangesColor, false) UnstagedChangesColor = unstagedChangesTextStyle GocuiSelectedLineBgColor = GetGocuiStyle(themeConfig.SelectedLineBgColor) GocuiInactiveViewSelectedLineBgColor = GetGocuiStyle(themeConfig.InactiveViewSelectedLineBgColor) OptionsColor = GetGocuiStyle(themeConfig.OptionsTextColor) OptionsFgColor = GetTextStyle(themeConfig.OptionsTextColor, false) DefaultTextColor = GetTextStyle(themeConfig.DefaultFgColor, false) GocuiDefaultTextColor = GetGocuiStyle(themeConfig.DefaultFgColor) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/theme/gocui.go
pkg/theme/gocui.go
package theme import ( "github.com/gookit/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/utils" ) var gocuiColorMap = map[string]gocui.Attribute{ "default": gocui.ColorDefault, "black": gocui.ColorBlack, "red": gocui.ColorRed, "green": gocui.ColorGreen, "yellow": gocui.ColorYellow, "blue": gocui.ColorBlue, "magenta": gocui.ColorMagenta, "cyan": gocui.ColorCyan, "white": gocui.ColorWhite, "bold": gocui.AttrBold, "reverse": gocui.AttrReverse, "underline": gocui.AttrUnderline, } // GetGocuiAttribute gets the gocui color attribute from the string func GetGocuiAttribute(key string) gocui.Attribute { if utils.IsValidHexValue(key) { values := color.HEX(key).Values() return gocui.NewRGBColor(int32(values[0]), int32(values[1]), int32(values[2])) } value, present := gocuiColorMap[key] if present { return value } return gocui.ColorWhite } // GetGocuiStyle bitwise OR's a list of attributes obtained via the given keys func GetGocuiStyle(keys []string) gocui.Attribute { var attribute gocui.Attribute for _, key := range keys { attribute |= GetGocuiAttribute(key) } return attribute }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/config_windows.go
pkg/config/config_windows.go
package config // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { return OSConfig{ Open: `start "" {{filename}}`, OpenLink: `start "" {{link}}`, } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/editor_presets_test.go
pkg/config/editor_presets_test.go
package config import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetEditTemplate(t *testing.T) { trueVal := true scenarios := []struct { name string osConfig *OSConfig guessDefaultEditor func() string expectedEditTemplate string expectedEditAtLineTemplate string expectedEditAtLineAndWaitTemplate string expectedSuspend bool }{ { "Default template is vim", &OSConfig{}, func() string { return "" }, "vim -- {{filename}}", "vim +{{line}} -- {{filename}}", "vim +{{line}} -- {{filename}}", true, }, { "Setting a preset", &OSConfig{ EditPreset: "vscode", }, func() string { return "" }, "code --reuse-window -- {{filename}}", "code --reuse-window --goto -- {{filename}}:{{line}}", "code --reuse-window --goto --wait -- {{filename}}:{{line}}", false, }, { "Setting a preset wins over guessed editor", &OSConfig{ EditPreset: "vscode", }, func() string { return "nano" }, "code --reuse-window -- {{filename}}", "code --reuse-window --goto -- {{filename}}:{{line}}", "code --reuse-window --goto --wait -- {{filename}}:{{line}}", false, }, { "Overriding a preset with explicit config (edit)", &OSConfig{ EditPreset: "vscode", Edit: "myeditor {{filename}}", SuspendOnEdit: &trueVal, }, func() string { return "" }, "myeditor {{filename}}", "code --reuse-window --goto -- {{filename}}:{{line}}", "code --reuse-window --goto --wait -- {{filename}}:{{line}}", true, }, { "Overriding a preset with explicit config (edit at line)", &OSConfig{ EditPreset: "vscode", EditAtLine: "myeditor --line={{line}} {{filename}}", SuspendOnEdit: &trueVal, }, func() string { return "" }, "code --reuse-window -- {{filename}}", "myeditor --line={{line}} {{filename}}", "code --reuse-window --goto --wait -- {{filename}}:{{line}}", true, }, { "Overriding a preset with explicit config (edit at line and wait)", &OSConfig{ EditPreset: "vscode", EditAtLineAndWait: "myeditor --line={{line}} -w {{filename}}", SuspendOnEdit: &trueVal, }, func() string { return "" }, "code --reuse-window -- {{filename}}", "code --reuse-window --goto -- {{filename}}:{{line}}", "myeditor --line={{line}} -w {{filename}}", true, }, { "Unknown preset name", &OSConfig{ EditPreset: "thisPresetDoesNotExist", }, func() string { return "" }, "vim -- {{filename}}", "vim +{{line}} -- {{filename}}", "vim +{{line}} -- {{filename}}", true, }, { "Guessing a preset from guessed editor", &OSConfig{}, func() string { return "emacs" }, "emacs -- {{filename}}", "emacs +{{line}} -- {{filename}}", "emacs +{{line}} -- {{filename}}", true, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { template, suspend := GetEditTemplate("bash", s.osConfig, s.guessDefaultEditor) assert.Equal(t, s.expectedEditTemplate, template) assert.Equal(t, s.expectedSuspend, suspend) template, suspend = GetEditAtLineTemplate("bash", s.osConfig, s.guessDefaultEditor) assert.Equal(t, s.expectedEditAtLineTemplate, template) assert.Equal(t, s.expectedSuspend, suspend) template = GetEditAtLineAndWaitTemplate("bash", s.osConfig, s.guessDefaultEditor) assert.Equal(t, s.expectedEditAtLineAndWaitTemplate, template) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/dummies.go
pkg/config/dummies.go
package config import ( "gopkg.in/yaml.v3" ) // NewDummyAppConfig creates a new dummy AppConfig for testing func NewDummyAppConfig() *AppConfig { appConfig := &AppConfig{ name: "lazygit", version: "unversioned", debug: false, userConfig: GetDefaultConfig(), appState: &AppState{}, } _ = yaml.Unmarshal([]byte{}, appConfig.appState) return appConfig }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/app_config_test.go
pkg/config/app_config_test.go
package config import ( "testing" "github.com/stretchr/testify/assert" ) func TestMigrationOfRenamedKeys(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Empty String", input: "", expectedDidChange: false, expectedChanges: []string{}, }, { name: "No rename needed", input: `foo: bar: 5 `, expectedDidChange: false, expectedChanges: []string{}, }, { name: "Rename one", input: `gui: skipUnstageLineWarning: true `, expected: `gui: skipDiscardChangeWarning: true `, expectedDidChange: true, expectedChanges: []string{"Renamed 'gui.skipUnstageLineWarning' to 'skipDiscardChangeWarning'"}, }, { name: "Rename several", input: `gui: windowSize: half skipUnstageLineWarning: true keybinding: universal: executeCustomCommand: a `, expected: `gui: screenMode: half skipDiscardChangeWarning: true keybinding: universal: executeShellCommand: a `, expectedDidChange: true, expectedChanges: []string{ "Renamed 'gui.skipUnstageLineWarning' to 'skipDiscardChangeWarning'", "Renamed 'keybinding.universal.executeCustomCommand' to 'executeShellCommand'", "Renamed 'gui.windowSize' to 'screenMode'", }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { changes := NewChangesSet() actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes) assert.NoError(t, err) assert.Equal(t, s.expectedDidChange, didChange) if didChange { assert.Equal(t, s.expected, string(actual)) } assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest()) }) } } func TestMigrateNullKeybindingsToDisabled(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Empty String", input: "", expectedDidChange: false, expectedChanges: []string{}, }, { name: "No change needed", input: `keybinding: universal: quit: q `, expectedDidChange: false, expectedChanges: []string{}, }, { name: "Change one", input: `keybinding: universal: quit: null `, expected: `keybinding: universal: quit: <disabled> `, expectedDidChange: true, expectedChanges: []string{"Changed 'null' to '<disabled>' for keybinding 'keybinding.universal.quit'"}, }, { name: "Change several", input: `keybinding: universal: quit: null return: <esc> new: null `, expected: `keybinding: universal: quit: <disabled> return: <esc> new: <disabled> `, expectedDidChange: true, expectedChanges: []string{ "Changed 'null' to '<disabled>' for keybinding 'keybinding.universal.quit'", "Changed 'null' to '<disabled>' for keybinding 'keybinding.universal.new'", }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { changes := NewChangesSet() actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes) assert.NoError(t, err) assert.Equal(t, s.expectedDidChange, didChange) if didChange { assert.Equal(t, s.expected, string(actual)) } assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest()) }) } } func TestCommitPrefixMigrations(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Empty String", input: "", expectedDidChange: false, expectedChanges: []string{}, }, { name: "Single CommitPrefix Rename", input: `git: commitPrefix: pattern: "^\\w+-\\w+.*" replace: '[JIRA $0] ' `, expected: `git: commitPrefix: - pattern: "^\\w+-\\w+.*" replace: '[JIRA $0] ' `, expectedDidChange: true, expectedChanges: []string{"Changed 'git.commitPrefix' to an array of strings"}, }, { name: "Complicated CommitPrefixes Rename", input: `git: commitPrefixes: foo: pattern: "^\\w+-\\w+.*" replace: '[OTHER $0] ' CrazyName!@#$^*&)_-)[[}{f{[]: pattern: "^foo.bar*" replace: '[FUN $0] ' `, expected: `git: commitPrefixes: foo: - pattern: "^\\w+-\\w+.*" replace: '[OTHER $0] ' CrazyName!@#$^*&)_-)[[}{f{[]: - pattern: "^foo.bar*" replace: '[FUN $0] ' `, expectedDidChange: true, expectedChanges: []string{"Changed 'git.commitPrefixes' elements to arrays of strings"}, }, { name: "Incomplete Configuration", input: "git:", expectedDidChange: false, expectedChanges: []string{}, }, { name: "No changes made when already migrated", input: ` git: commitPrefix: - pattern: "Hello World" replace: "Goodbye" commitPrefixes: foo: - pattern: "^\\w+-\\w+.*" replace: '[JIRA $0] '`, expectedDidChange: false, expectedChanges: []string{}, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { changes := NewChangesSet() actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes) assert.NoError(t, err) assert.Equal(t, s.expectedDidChange, didChange) if didChange { assert.Equal(t, s.expected, string(actual)) } assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest()) }) } } func TestCustomCommandsOutputMigration(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Empty String", input: "", expectedDidChange: false, expectedChanges: []string{}, }, { name: "Convert subprocess to output=terminal", input: `customCommands: - command: echo 'hello' subprocess: true `, expected: `customCommands: - command: echo 'hello' output: terminal `, expectedDidChange: true, expectedChanges: []string{"Changed 'subprocess: true' to 'output: terminal' in custom command"}, }, { name: "Convert stream to output=log", input: `customCommands: - command: echo 'hello' stream: true `, expected: `customCommands: - command: echo 'hello' output: log `, expectedDidChange: true, expectedChanges: []string{"Changed 'stream: true' to 'output: log' in custom command"}, }, { name: "Convert showOutput to output=popup", input: `customCommands: - command: echo 'hello' showOutput: true `, expected: `customCommands: - command: echo 'hello' output: popup `, expectedDidChange: true, expectedChanges: []string{"Changed 'showOutput: true' to 'output: popup' in custom command"}, }, { name: "Subprocess wins over the other two", input: `customCommands: - command: echo 'hello' subprocess: true stream: true showOutput: true `, expected: `customCommands: - command: echo 'hello' output: terminal `, expectedDidChange: true, expectedChanges: []string{ "Changed 'subprocess: true' to 'output: terminal' in custom command", "Deleted redundant 'stream: true' property in custom command", "Deleted redundant 'showOutput: true' property in custom command", }, }, { name: "Stream wins over showOutput", input: `customCommands: - command: echo 'hello' stream: true showOutput: true `, expected: `customCommands: - command: echo 'hello' output: log `, expectedDidChange: true, expectedChanges: []string{ "Changed 'stream: true' to 'output: log' in custom command", "Deleted redundant 'showOutput: true' property in custom command", }, }, { name: "Explicitly setting to false doesn't create an output=none key", input: `customCommands: - command: echo 'hello' subprocess: false stream: false showOutput: false `, expected: `customCommands: - command: echo 'hello' `, expectedDidChange: true, expectedChanges: []string{ "Deleted redundant 'subprocess: false' in custom command", "Deleted redundant 'stream: false' property in custom command", "Deleted redundant 'showOutput: false' property in custom command", }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { changes := NewChangesSet() actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes) assert.NoError(t, err) assert.Equal(t, s.expectedDidChange, didChange) if didChange { assert.Equal(t, s.expected, string(actual)) } assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest()) }) } } var largeConfiguration = []byte(` # Config relating to the Lazygit UI gui: # The number of lines you scroll by when scrolling the main window scrollHeight: 2 # If true, allow scrolling past the bottom of the content in the main window scrollPastBottom: true # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#scroll-off-margin scrollOffMargin: 2 # One of: 'margin' (default) | 'jump' scrollOffBehavior: margin # The number of spaces per tab; used for everything that's shown in the main view, but probably mostly relevant for diffs. # Note that when using a pager, the pager has its own tab width setting, so you need to pass it separately in the pager command. tabWidth: 4 # If true, capture mouse events. # When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS. mouseEvents: true # If true, do not show a warning when amending a commit. skipAmendWarning: false # If true, do not show a warning when discarding changes in the staging view. skipDiscardChangeWarning: false # If true, do not show warning when applying/popping the stash skipStashWarning: false # If true, do not show a warning when attempting to commit without any staged files; instead stage all unstaged files. skipNoStagedFilesWarning: false # If true, do not show a warning when rewording a commit via an external editor skipRewordInEditorWarning: false # Fraction of the total screen width to use for the left side section. You may want to pick a small number (e.g. 0.2) if you're using a narrow screen, so that you can see more of the main section. # Number from 0 to 1.0. sidePanelWidth: 0.3333 # If true, increase the height of the focused side window; creating an accordion effect. expandFocusedSidePanel: false # The weight of the expanded side panel, relative to the other panels. 2 means # twice as tall as the other panels. Only relevant if expandFocusedSidePanel is true. expandedSidePanelWeight: 2 # Sometimes the main window is split in two (e.g. when the selected file has both staged and unstaged changes). This setting controls how the two sections are split. # Options are: # - 'horizontal': split the window horizontally # - 'vertical': split the window vertically # - 'flexible': (default) split the window horizontally if the window is wide enough, otherwise split vertically mainPanelSplitMode: flexible # How the window is split when in half screen mode (i.e. after hitting '+' once). # Possible values: # - 'left': split the window horizontally (side panel on the left, main view on the right) # - 'top': split the window vertically (side panel on top, main view below) enlargedSideViewLocation: left # If true, wrap lines in the staging view to the width of the view. This # makes it much easier to work with diffs that have long lines, e.g. # paragraphs of markdown text. wrapLinesInStagingView: true # One of 'auto' (default) | 'en' | 'zh-CN' | 'zh-TW' | 'pl' | 'nl' | 'ja' | 'ko' | 'ru' language: auto # Format used when displaying time e.g. commit time. # Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format timeFormat: 02 Jan 06 # Format used when displaying time if the time is less than 24 hours ago. # Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format shortTimeFormat: 3:04PM # Config relating to colors and styles. # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes theme: # Border color of focused window activeBorderColor: - green - bold # Border color of non-focused windows inactiveBorderColor: - default # Border color of focused window when searching in that window searchingActiveBorderColor: - cyan - bold # Color of keybindings help text in the bottom line optionsTextColor: - blue # Background color of selected line. # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line selectedLineBgColor: - blue # Background color of selected line when view doesn't have focus. inactiveViewSelectedLineBgColor: - bold # Foreground color of copied commit cherryPickedCommitFgColor: - blue # Background color of copied commit cherryPickedCommitBgColor: - cyan # Foreground color of marked base commit (for rebase) markedBaseCommitFgColor: - blue # Background color of marked base commit (for rebase) markedBaseCommitBgColor: - yellow # Color for file with unstaged changes unstagedChangesColor: - red # Default text color defaultFgColor: - default # Config relating to the commit length indicator commitLength: # If true, show an indicator of commit message length show: true # If true, show the '5 of 20' footer at the bottom of list views showListFooter: true # If true, display the files in the file views as a tree. If false, display the files as a flat list. # This can be toggled from within Lazygit with the '' key, but that will not change the default. showFileTree: true # If true, show the number of lines changed per file in the Files view showNumstatInFilesView: false # If true, show a random tip in the command log when Lazygit starts showRandomTip: true # If true, show the command log showCommandLog: true # If true, show the bottom line that contains keybinding info and useful buttons. If false, this line will be hidden except to display a loader for an in-progress action. showBottomLine: true # If true, show jump-to-window keybindings in window titles. showPanelJumps: true # Deprecated: use nerdFontsVersion instead showIcons: false # Nerd fonts version to use. # One of: '2' | '3' | empty string (default) # If empty, do not show icons. nerdFontsVersion: "" # If true (default), file icons are shown in the file views. Only relevant if NerdFontsVersion is not empty. showFileIcons: true # Length of author name in (non-expanded) commits view. 2 means show initials only. commitAuthorShortLength: 2 # Length of author name in expanded commits view. 2 means show initials only. commitAuthorLongLength: 17 # Length of commit hash in commits view. 0 shows '*' if NF icons aren't on. commitHashLength: 8 # If true, show commit hashes alongside branch names in the branches view. showBranchCommitHash: false # Whether to show the divergence from the base branch in the branches view. # One of: 'none' | 'onlyArrow' | 'arrowAndNumber' showDivergenceFromBaseBranch: none # Height of the command log view commandLogSize: 8 # Whether to split the main window when viewing file changes. # One of: 'auto' | 'always' # If 'auto', only split the main window when a file has both staged and unstaged changes splitDiff: auto # Default size for focused window. Can be changed from within Lazygit with '+' and '_' (but this won't change the default). # One of: 'normal' (default) | 'half' | 'full' screenMode: normal # Window border style. # One of 'rounded' (default) | 'single' | 'double' | 'hidden' | 'bold' border: rounded # If true, show a seriously epic explosion animation when nuking the working tree. animateExplosion: true # Whether to stack UI components on top of each other. # One of 'auto' (default) | 'always' | 'never' portraitMode: auto # How things are filtered when typing '/'. # One of 'substring' (default) | 'fuzzy' filterMode: substring # Config relating to the spinner. spinner: # The frames of the spinner animation. frames: - '|' - / - '-' - \ # The "speed" of the spinner in milliseconds. rate: 50 # Status panel view. # One of 'dashboard' (default) | 'allBranchesLog' statusPanelView: dashboard # If true, jump to the Files panel after popping a stash switchToFilesAfterStashPop: true # If true, jump to the Files panel after applying a stash switchToFilesAfterStashApply: true # If true, when using the panel jump keys (default 1 through 5) and target panel is already active, go to next tab instead switchTabsWithPanelJumpKeys: false # Config relating to git git: # See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md paging: # Value of the --color arg in the git diff command. Some pagers want this to be set to 'always' and some want it set to 'never' colorArg: always # e.g. # diff-so-fancy # delta --dark --paging=never # ydiff -p cat -s --wrap --width={{columnWidth}} pager: "" useConfig: false # e.g. 'difft --color=always' externalDiffCommand: "" # Config relating to committing commit: # If true, pass '--signoff' flag when committing signOff: false # Automatic WYSIWYG wrapping of the commit message as you type autoWrapCommitMessage: true # If autoWrapCommitMessage is true, the width to wrap to autoWrapWidth: 72 # Config relating to merging merging: # If true, run merges in a subprocess so that if a commit message is required, Lazygit will not hang # Only applicable to unix users. manualCommit: false # Extra args passed to , e.g. --no-ff args: "" # The commit message to use for a squash merge commit. Can contain "{{selectedRef}}" and "{{currentBranch}}" placeholders. squashMergeMessage: Squash merge {{selectedRef}} into {{currentBranch}} # list of branches that are considered 'main' branches, used when displaying commits mainBranches: - master - main # Prefix to use when skipping hooks. E.g. if set to 'WIP', then pre-commit hooks will be skipped when the commit message starts with 'WIP' skipHookPrefix: WIP # If true, periodically fetch from remote autoFetch: true # If true, periodically refresh files and submodules autoRefresh: true # If true, pass the --all arg to git fetch fetchAll: true # If true, lazygit will automatically stage files that used to have merge # conflicts but no longer do; and it will also ask you if you want to # continue a merge or rebase if you've resolved all conflicts. If false, it # won't do either of these things. autoStageResolvedConflicts: true # Command used when displaying the current branch git log in the main window branchLogCmd: git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} -- # Command used to display git log of all branches in the main window. # Deprecated: Use allBranchesLogCmds instead. allBranchesLogCmd: git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium # If true, do not spawn a separate process when using GPG overrideGpg: false # If true, do not allow force pushes disableForcePushing: false # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix branchPrefix: "" # If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀 # (This should really be under 'gui', not 'git') parseEmoji: false # Config for showing the log in the commits view log: # One of: 'date-order' | 'author-date-order' | 'topo-order' | 'default' # 'topo-order' makes it easier to read the git log graph, but commits may not # appear chronologically. See https://git-scm.com/docs/ # # Deprecated: Configure this with Log menu -> Commit sort order (<c-l> in the commits window by default). order: topo-order # This determines whether the git graph is rendered in the commits panel # One of 'always' | 'never' | 'when-maximised' # # Deprecated: Configure this with Log menu -> Show git graph (<c-l> in the commits window by default). showGraph: always # displays the whole git graph by default in the commits view (equivalent to passing the --all argument to git log) showWholeGraph: false # When copying commit hashes to the clipboard, truncate them to this # length. Set to 40 to disable truncation. truncateCopiedCommitHashesTo: 12 # Periodic update checks update: # One of: 'prompt' (default) | 'background' | 'never' method: prompt # Period in days between update checks days: 14 # Background refreshes refresher: # File/submodule refresh interval in seconds. # Auto-refresh can be disabled via option 'git.autoRefresh'. refreshInterval: 10 # Re-fetch interval in seconds. # Auto-fetch can be disabled via option 'git.autoFetch'. fetchInterval: 60 # If true, show a confirmation popup before quitting Lazygit confirmOnQuit: false # If true, exit Lazygit when the user presses escape in a context where there is nothing to cancel/close quitOnTopLevelReturn: false # Config relating to things outside of Lazygit like how files are opened, copying to clipboard, etc os: # Command for editing a file. Should contain "{{filename}}". edit: "" # Command for editing a file at a given line number. Should contain # "{{filename}}", and may optionally contain "{{line}}". editAtLine: "" # Same as EditAtLine, except that the command needs to wait until the # window is closed. editAtLineAndWait: "" # Whether lazygit suspends until an edit process returns editInTerminal: false # For opening a directory in an editor openDirInEditor: "" # A built-in preset that sets all of the above settings. Supported presets # are defined in the getPreset function in editor_presets.go. editPreset: "" # Command for opening a file, as if the file is double-clicked. Should # contain "{{filename}}", but doesn't support "{{line}}". open: "" # Command for opening a link. Should contain "{{link}}". openLink: "" # EditCommand is the command for editing a file. # Deprecated: use Edit instead. Note that semantics are different: # EditCommand is just the command itself, whereas Edit contains a # "{{filename}}" variable. editCommand: "" # EditCommandTemplate is the command template for editing a file # Deprecated: use EditAtLine instead. editCommandTemplate: "" # OpenCommand is the command for opening a file # Deprecated: use Open instead. openCommand: "" # OpenLinkCommand is the command for opening a link # Deprecated: use OpenLink instead. openLinkCommand: "" # CopyToClipboardCmd is the command for copying to clipboard. # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard copyToClipboardCmd: "" # ReadFromClipboardCmd is the command for reading the clipboard. # See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard readFromClipboardCmd: "" # If true, don't display introductory popups upon opening Lazygit. disableStartupPopups: false # What to do when opening Lazygit outside of a git repo. # - 'prompt': (default) ask whether to initialize a new repo or open in the most recent repo # - 'create': initialize a new repo # - 'skip': open most recent repo # - 'quit': exit Lazygit notARepository: prompt # If true, display a confirmation when subprocess terminates. This allows you to view the output of the subprocess before returning to Lazygit. promptToReturnFromSubprocess: true # Keybindings keybinding: universal: quit: q quit-alt1: <c-c> return: <esc> quitWithoutChangingDirectory: Q togglePanel: <tab> prevItem: <up> nextItem: <down> prevItem-alt: k nextItem-alt: j prevPage: ',' nextPage: . scrollLeft: H scrollRight: L gotoTop: < gotoBottom: '>' toggleRangeSelect: v rangeSelectDown: <s-down> rangeSelectUp: <s-up> prevBlock: <left> nextBlock: <right> prevBlock-alt: h nextBlock-alt: l nextBlock-alt2: <tab> prevBlock-alt2: <backtab> jumpToBlock: - "1" - "2" - "3" - "4" - "5" nextMatch: "n" prevMatch: "N" startSearch: / optionMenu: <disabled> optionMenu-alt1: '?' select: <space> goInto: <enter> confirm: <enter> confirmInEditor: <a-enter> remove: d new: "n" edit: e openFile: o scrollUpMain: <pgup> scrollDownMain: <pgdown> scrollUpMain-alt1: K scrollDownMain-alt1: J scrollUpMain-alt2: <c-u> scrollDownMain-alt2: <c-d> executeShellCommand: ':' createRebaseOptionsMenu: m # 'Files' appended for legacy reasons pushFiles: P # 'Files' appended for legacy reasons pullFiles: p refresh: R createPatchOptionsMenu: <c-p> nextTab: ']' prevTab: '[' nextScreenMode: + prevScreenMode: _ undo: z redo: Z filteringMenu: <c-s> diffingMenu: W diffingMenu-alt: <c-e> copyToClipboard: <c-o> openRecentRepos: <c-r> submitEditorText: <enter> extrasMenu: '@' toggleWhitespaceInDiffView: <c-w> increaseContextInDiffView: '}' decreaseContextInDiffView: '{' increaseRenameSimilarityThreshold: ) decreaseRenameSimilarityThreshold: ( openDiffTool: <c-t> status: checkForUpdate: u recentRepos: <enter> allBranchesLogGraph: a files: commitChanges: c commitChangesWithoutHook: w amendLastCommit: A commitChangesWithEditor: C findBaseCommitForFixup: <c-f> confirmDiscard: x ignoreFile: i refreshFiles: r stashAllChanges: s viewStashOptions: S toggleStagedAll: a viewResetOptions: D fetch: f openMergeOptions: M openStatusFilter: <c-b> copyFileInfoToClipboard: "y" collapseAll: '-' expandAll: = branches: createPullRequest: o viewPullRequestOptions: O copyPullRequestURL: <c-y> checkoutBranchByName: c forceCheckoutBranch: F rebaseBranch: r renameBranch: R mergeIntoCurrentBranch: M viewGitFlowOptions: i fastForward: f createTag: T pushTag: P setUpstream: u fetchRemote: f sortOrder: s worktrees: viewWorktreeOptions: w commits: squashDown: s renameCommit: r renameCommitWithEditor: R viewResetOptions: g markCommitAsFixup: f createFixupCommit: F squashAboveCommits: S moveDownCommit: <c-j> moveUpCommit: <c-k> amendToCommit: A resetCommitAuthor: a pickCommit: p revertCommit: t cherryPickCopy: C pasteCommits: V markCommitAsBaseForRebase: B tagCommit: T checkoutCommit: <space> resetCherryPick: <c-R> copyCommitAttributeToClipboard: "y" openLogMenu: <c-l> openInBrowser: o viewBisectOptions: b startInteractiveRebase: i amendAttribute: resetAuthor: a setAuthor: A addCoAuthor: c stash: popStash: g renameStash: r commitFiles: checkoutCommitFile: c main: toggleSelectHunk: a pickBothHunks: b editSelectHunk: E submodules: init: i update: u bulkMenu: b commitMessage: commitMenu: <c-o> `) func BenchmarkMigrationOnLargeConfiguration(b *testing.B) { for b.Loop() { changes := NewChangesSet() _, _, _ = computeMigratedConfig("path doesn't matter", largeConfiguration, changes) } } func TestAllBranchesLogCmdMigrations(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Incomplete Configuration Passes uneventfully", input: "git:", expectedDidChange: false, expectedChanges: []string{}, }, { name: "Single Cmd with no Cmds", input: `git: allBranchesLogCmd: git log --graph --oneline `, expected: `git: allBranchesLogCmds: - git log --graph --oneline `, expectedDidChange: true, expectedChanges: []string{ "Created git.allBranchesLogCmds array containing value of git.allBranchesLogCmd", "Removed obsolete git.allBranchesLogCmd", }, }, { name: "Cmd with one existing Cmds", input: `git: allBranchesLogCmd: git log --graph --oneline allBranchesLogCmds: - git log --graph --oneline --pretty `, expected: `git: allBranchesLogCmds: - git log --graph --oneline - git log --graph --oneline --pretty `, expectedDidChange: true, expectedChanges: []string{ "Prepended git.allBranchesLogCmd value to git.allBranchesLogCmds array", "Removed obsolete git.allBranchesLogCmd", }, }, { name: "Only Cmds set have no changes", input: `git: allBranchesLogCmds: - git log `, expected: "", expectedChanges: []string{}, }, { name: "Removes Empty Cmd When at end of yaml", input: `git: allBranchesLogCmds: - git log --graph --oneline allBranchesLogCmd: `, expected: `git: allBranchesLogCmds: - git log --graph --oneline `, expectedDidChange: true, expectedChanges: []string{"Removed obsolete git.allBranchesLogCmd"}, }, { name: "Migrates when sequence defined inline", input: `git: allBranchesLogCmds: [foo, bar] allBranchesLogCmd: baz `, expected: `git: allBranchesLogCmds: [baz, foo, bar] `, expectedDidChange: true, expectedChanges: []string{ "Prepended git.allBranchesLogCmd value to git.allBranchesLogCmds array", "Removed obsolete git.allBranchesLogCmd", }, }, { name: "Removes Empty Cmd With Keys Afterwards", input: `git: allBranchesLogCmds: - git log --graph --oneline allBranchesLogCmd: foo: bar `, expected: `git: allBranchesLogCmds: - git log --graph --oneline foo: bar `, expectedDidChange: true, expectedChanges: []string{"Removed obsolete git.allBranchesLogCmd"}, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { changes := NewChangesSet() actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes) assert.NoError(t, err) assert.Equal(t, s.expectedDidChange, didChange) if didChange { assert.Equal(t, s.expected, string(actual)) } assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest()) }) } } func TestPagerMigration(t *testing.T) { scenarios := []struct { name string input string expected string expectedDidChange bool expectedChanges []string }{ { name: "Incomplete Configuration Passes uneventfully", input: "git:", expectedDidChange: false, expectedChanges: []string{}, }, { name: "No paging section", input: `git: autoFetch: true `, expected: `git: autoFetch: true `, expectedDidChange: false, expectedChanges: []string{}, }, { name: "Both paging and pagers exist", input: `git: paging: pager: delta --dark --paging=never pagers: - diff: diff-so-fancy `, expected: `git: paging: pager: delta --dark --paging=never pagers: - diff: diff-so-fancy `, expectedDidChange: false, expectedChanges: []string{}, }, { name: "paging is not an object", input: `git: paging: 5 `, expected: `git: paging: 5 `, expectedDidChange: false, expectedChanges: []string{}, }, { name: "paging is moved to pagers array (keeping the order)", input: `git: paging: pager: delta --dark --paging=never autoFetch: true `, expected: `git: pagers: - pager: delta --dark --paging=never autoFetch: true `, expectedDidChange: true, expectedChanges: []string{"Moved git.paging object to git.pagers array"}, }, { name: "paging is moved to pagers array even if empty", input: `git: paging: {} `, expected: `git: pagers: [{}] `, expectedDidChange: true, expectedChanges: []string{"Moved git.paging object to git.pagers array"}, }, }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/config_linux.go
pkg/config/config_linux.go
package config import ( "os" "strings" ) func isWSL() bool { data, err := os.ReadFile("/proc/sys/kernel/osrelease") return err == nil && strings.Contains(string(data), "microsoft") } func isContainer() bool { data, err := os.ReadFile("/proc/1/cgroup") return err == nil && (strings.Contains(string(data), "docker") || strings.Contains(string(data), "/lxc/") || os.Getenv("CONTAINER") != "") } // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { if isWSL() && !isContainer() { return OSConfig{ Open: `powershell.exe start explorer.exe "$(wslpath -w {{filename}})" >/dev/null`, OpenLink: `powershell.exe start '{{link}}' >/dev/null`, } } return OSConfig{ Open: `xdg-open {{filename}} >/dev/null`, OpenLink: `xdg-open {{link}} >/dev/null`, } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/user_config_validation_test.go
pkg/config/user_config_validation_test.go
package config import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestUserConfigValidate_enums(t *testing.T) { type testCase struct { value string valid bool } scenarios := []struct { name string setup func(config *UserConfig, value string) testCases []testCase }{ { name: "Gui.StatusPanelView", setup: func(config *UserConfig, value string) { config.Gui.StatusPanelView = value }, testCases: []testCase{ {value: "dashboard", valid: true}, {value: "allBranchesLog", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Gui.ShowDivergenceFromBaseBranch", setup: func(config *UserConfig, value string) { config.Gui.ShowDivergenceFromBaseBranch = value }, testCases: []testCase{ {value: "none", valid: true}, {value: "onlyArrow", valid: true}, {value: "arrowAndNumber", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Git.AutoForwardBranches", setup: func(config *UserConfig, value string) { config.Git.AutoForwardBranches = value }, testCases: []testCase{ {value: "none", valid: true}, {value: "onlyMainBranches", valid: true}, {value: "allBranches", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Git.LocalBranchSortOrder", setup: func(config *UserConfig, value string) { config.Git.LocalBranchSortOrder = value }, testCases: []testCase{ {value: "date", valid: true}, {value: "recency", valid: true}, {value: "alphabetical", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Git.RemoteBranchSortOrder", setup: func(config *UserConfig, value string) { config.Git.RemoteBranchSortOrder = value }, testCases: []testCase{ {value: "date", valid: true}, {value: "recency", valid: false}, {value: "alphabetical", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Git.Log.Order", setup: func(config *UserConfig, value string) { config.Git.Log.Order = value }, testCases: []testCase{ {value: "date-order", valid: true}, {value: "author-date-order", valid: true}, {value: "topo-order", valid: true}, {value: "default", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Git.Log.ShowGraph", setup: func(config *UserConfig, value string) { config.Git.Log.ShowGraph = value }, testCases: []testCase{ {value: "always", valid: true}, {value: "never", valid: true}, {value: "when-maximised", valid: true}, {value: "", valid: false}, {value: "invalid_value", valid: false}, }, }, { name: "Keybindings", setup: func(config *UserConfig, value string) { config.Keybinding.Universal.Quit = value }, testCases: []testCase{ {value: "", valid: true}, {value: "<disabled>", valid: true}, {value: "q", valid: true}, {value: "<c-c>", valid: true}, {value: "invalid_value", valid: false}, }, }, { name: "JumpToBlock keybinding", setup: func(config *UserConfig, value string) { config.Keybinding.Universal.JumpToBlock = strings.Split(value, ",") }, testCases: []testCase{ {value: "", valid: false}, {value: "1,2,3", valid: false}, {value: "1,2,3,4,5", valid: true}, {value: "1,2,3,4,invalid", valid: false}, {value: "1,2,3,4,5,6", valid: false}, }, }, { name: "Custom command keybinding", setup: func(config *UserConfig, value string) { config.CustomCommands = []CustomCommand{ { Key: value, Command: "echo 'hello'", }, } }, testCases: []testCase{ {value: "", valid: true}, {value: "<disabled>", valid: true}, {value: "q", valid: true}, {value: "<c-c>", valid: true}, {value: "invalid_value", valid: false}, }, }, { name: "Custom command keybinding in sub menu", setup: func(config *UserConfig, value string) { config.CustomCommands = []CustomCommand{ { Key: "X", Description: "My Custom Commands", CommandMenu: []CustomCommand{ {Key: value, Command: "echo 'hello'", Context: "global"}, }, }, } }, testCases: []testCase{ {value: "", valid: true}, {value: "<disabled>", valid: true}, {value: "q", valid: true}, {value: "<c-c>", valid: true}, {value: "invalid_value", valid: false}, }, }, { name: "Custom command keybinding in prompt menu", setup: func(config *UserConfig, value string) { config.CustomCommands = []CustomCommand{ { Key: "X", Description: "My Custom Commands", Prompts: []CustomCommandPrompt{ { Options: []CustomCommandMenuOption{ {Key: value}, }, }, }, }, } }, testCases: []testCase{ {value: "", valid: true}, {value: "<disabled>", valid: true}, {value: "q", valid: true}, {value: "<c-c>", valid: true}, {value: "invalid_value", valid: false}, }, }, { name: "Custom command output", setup: func(config *UserConfig, value string) { config.CustomCommands = []CustomCommand{ { Output: value, }, } }, testCases: []testCase{ {value: "", valid: true}, {value: "none", valid: true}, {value: "terminal", valid: true}, {value: "log", valid: true}, {value: "logWithPty", valid: true}, {value: "popup", valid: true}, {value: "invalid_value", valid: false}, }, }, { name: "Custom command sub menu", setup: func(config *UserConfig, _ string) { config.CustomCommands = []CustomCommand{ { Key: "X", Description: "My Custom Commands", CommandMenu: []CustomCommand{ {Key: "1", Command: "echo 'hello'", Context: "global"}, }, }, } }, testCases: []testCase{ {value: "", valid: true}, }, }, { name: "Custom command sub menu", setup: func(config *UserConfig, _ string) { config.CustomCommands = []CustomCommand{ { Key: "X", Context: "global", // context is not allowed for submenus CommandMenu: []CustomCommand{ {Key: "1", Command: "echo 'hello'", Context: "global"}, }, }, } }, testCases: []testCase{ {value: "", valid: false}, }, }, { name: "Custom command sub menu", setup: func(config *UserConfig, _ string) { config.CustomCommands = []CustomCommand{ { Key: "X", LoadingText: "loading", // other properties are not allowed for submenus (using loadingText as an example) CommandMenu: []CustomCommand{ {Key: "1", Command: "echo 'hello'", Context: "global"}, }, }, } }, testCases: []testCase{ {value: "", valid: false}, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { for _, testCase := range s.testCases { config := GetDefaultConfig() s.setup(config, testCase.value) err := config.Validate() if testCase.valid { assert.NoError(t, err) } else { assert.Error(t, err) } } }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/config_default_platform.go
pkg/config/config_default_platform.go
//go:build !windows && !linux package config // GetPlatformDefaultConfig gets the defaults for the platform func GetPlatformDefaultConfig() OSConfig { return OSConfig{ Open: "open -- {{filename}}", OpenLink: "open {{link}}", } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/app_config.go
pkg/config/app_config.go
package config import ( "errors" "fmt" "log" "os" "path/filepath" "reflect" "strings" "time" "github.com/adrg/xdg" "github.com/jesseduffield/generics/orderedset" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/jesseduffield/lazygit/pkg/utils/yaml_utils" "github.com/samber/lo" "gopkg.in/yaml.v3" ) // AppConfig contains the base configuration fields required for lazygit. type AppConfig struct { debug bool `long:"debug" env:"DEBUG" default:"false"` version string `long:"version" env:"VERSION" default:"unversioned"` buildDate string `long:"build-date" env:"BUILD_DATE"` name string `long:"name" env:"NAME" default:"lazygit"` buildSource string `long:"build-source" env:"BUILD_SOURCE" default:""` userConfig *UserConfig globalUserConfigFiles []*ConfigFile userConfigFiles []*ConfigFile userConfigDir string tempDir string appState *AppState } type AppConfigurer interface { GetDebug() bool // build info GetVersion() string GetName() string GetBuildSource() string GetUserConfig() *UserConfig GetUserConfigPaths() []string GetUserConfigDir() string ReloadUserConfigForRepo(repoConfigFiles []*ConfigFile) error ReloadChangedUserConfigFiles() (error, bool) GetTempDir() string GetAppState() *AppState SaveAppState() error } type ConfigFilePolicy int const ( ConfigFilePolicyCreateIfMissing ConfigFilePolicy = iota ConfigFilePolicyErrorIfMissing ConfigFilePolicySkipIfMissing ) type ConfigFile struct { Path string Policy ConfigFilePolicy modDate time.Time exists bool } // NewAppConfig makes a new app config func NewAppConfig( name string, version, commit, date string, buildSource string, debuggingFlag bool, tempDir string, ) (*AppConfig, error) { configDir, err := findOrCreateConfigDir() if err != nil && !os.IsPermission(err) { return nil, err } var configFiles []*ConfigFile customConfigFiles := os.Getenv("LG_CONFIG_FILE") if customConfigFiles != "" { // Load user defined config files userConfigPaths := strings.Split(customConfigFiles, ",") configFiles = lo.Map(userConfigPaths, func(path string, _ int) *ConfigFile { return &ConfigFile{Path: path, Policy: ConfigFilePolicyErrorIfMissing} }) } else { // Load default config files path := filepath.Join(configDir, ConfigFilename) configFile := &ConfigFile{Path: path, Policy: ConfigFilePolicyCreateIfMissing} configFiles = []*ConfigFile{configFile} } userConfig, err := loadUserConfigWithDefaults(configFiles, false) if err != nil { return nil, err } appState, err := loadAppState() if err != nil { return nil, err } appConfig := &AppConfig{ name: name, version: version, buildDate: date, debug: debuggingFlag, buildSource: buildSource, userConfig: userConfig, globalUserConfigFiles: configFiles, userConfigFiles: configFiles, userConfigDir: configDir, tempDir: tempDir, appState: appState, } return appConfig, nil } func ConfigDir() string { _, filePath := findConfigFile(ConfigFilename) return filepath.Dir(filePath) } func findOrCreateConfigDir() (string, error) { folder := ConfigDir() return folder, os.MkdirAll(folder, 0o755) } func loadUserConfigWithDefaults(configFiles []*ConfigFile, isGuiInitialized bool) (*UserConfig, error) { return loadUserConfig(configFiles, GetDefaultConfig(), isGuiInitialized) } func loadUserConfig(configFiles []*ConfigFile, base *UserConfig, isGuiInitialized bool) (*UserConfig, error) { for _, configFile := range configFiles { path := configFile.Path statInfo, err := os.Stat(path) if err == nil { configFile.exists = true configFile.modDate = statInfo.ModTime() } else { if !os.IsNotExist(err) { return nil, err } switch configFile.Policy { case ConfigFilePolicyErrorIfMissing: return nil, err case ConfigFilePolicySkipIfMissing: configFile.exists = false continue case ConfigFilePolicyCreateIfMissing: file, err := os.Create(path) if err != nil { if os.IsPermission(err) { // apparently when people have read-only permissions they prefer us to fail silently continue } return nil, err } file.Close() configFile.exists = true statInfo, err := os.Stat(configFile.Path) if err != nil { return nil, err } configFile.modDate = statInfo.ModTime() } } content, err := os.ReadFile(path) if err != nil { return nil, err } content, err = migrateUserConfig(path, content, isGuiInitialized) if err != nil { return nil, err } existingCustomCommands := base.CustomCommands if err := yaml.Unmarshal(content, base); err != nil { return nil, fmt.Errorf("The config at `%s` couldn't be parsed, please inspect it before opening up an issue.\n%w", path, err) } base.CustomCommands = append(base.CustomCommands, existingCustomCommands...) if err := base.Validate(); err != nil { return nil, fmt.Errorf("The config at `%s` has a validation error.\n%w", path, err) } } return base, nil } type ChangesSet = orderedset.OrderedSet[string] func NewChangesSet() *ChangesSet { return orderedset.New[string]() } // Do any backward-compatibility migrations of things that have changed in the // config over time; examples are renaming a key to a better name, moving a key // from one container to another, or changing the type of a key (e.g. from bool // to an enum). func migrateUserConfig(path string, content []byte, isGuiInitialized bool) ([]byte, error) { changes := NewChangesSet() changedContent, didChange, err := computeMigratedConfig(path, content, changes) if err != nil { return nil, err } // Nothing to do if config didn't change if !didChange { return content, nil } changesText := "The following changes were made:\n\n" changesText += strings.Join(lo.Map(changes.ToSliceFromOldest(), func(change string, _ int) string { return fmt.Sprintf("- %s\n", change) }), "") // Write config back if !isGuiInitialized { fmt.Printf("The user config file %s must be migrated. Attempting to do this automatically.\n", path) fmt.Println(changesText) } if err := os.WriteFile(path, changedContent, 0o644); err != nil { errorMsg := fmt.Sprintf("While attempting to write back migrated user config to %s, an error occurred: %s", path, err) if isGuiInitialized { errorMsg += "\n\n" + changesText } return nil, errors.New(errorMsg) } if !isGuiInitialized { fmt.Printf("Config file saved successfully to %s\n", path) } return changedContent, nil } // A pure function helper for testing purposes func computeMigratedConfig(path string, content []byte, changes *ChangesSet) ([]byte, bool, error) { var err error var rootNode yaml.Node err = yaml.Unmarshal(content, &rootNode) if err != nil { return nil, false, fmt.Errorf("failed to parse YAML: %w", err) } var originalCopy yaml.Node err = yaml.Unmarshal(content, &originalCopy) if err != nil { return nil, false, fmt.Errorf("failed to parse YAML, but only the second time!?!? How did that happen: %w", err) } pathsToReplace := []struct { oldPath []string newName string }{ {[]string{"gui", "skipUnstageLineWarning"}, "skipDiscardChangeWarning"}, {[]string{"keybinding", "universal", "executeCustomCommand"}, "executeShellCommand"}, {[]string{"gui", "windowSize"}, "screenMode"}, {[]string{"keybinding", "files", "openMergeTool"}, "openMergeOptions"}, } for _, pathToReplace := range pathsToReplace { err, didReplace := yaml_utils.RenameYamlKey(&rootNode, pathToReplace.oldPath, pathToReplace.newName) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s` for key %s: %w", path, strings.Join(pathToReplace.oldPath, "."), err) } if didReplace { changes.Add(fmt.Sprintf("Renamed '%s' to '%s'", strings.Join(pathToReplace.oldPath, "."), pathToReplace.newName)) } } err = changeNullKeybindingsToDisabled(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } err = changeElementToSequence(&rootNode, []string{"git", "commitPrefix"}, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } err = changeCommitPrefixesMap(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } err = changeCustomCommandStreamAndOutputToOutputEnum(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } err = migrateAllBranchesLogCmd(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } err = migratePagers(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) } // Add more migrations here... if reflect.DeepEqual(rootNode, originalCopy) { return nil, false, nil } newContent, err := yaml_utils.YamlMarshal(&rootNode) if err != nil { return nil, false, fmt.Errorf("Failed to remarsal!\n %w", err) } return newContent, true, nil } func changeNullKeybindingsToDisabled(rootNode *yaml.Node, changes *ChangesSet) error { return yaml_utils.Walk(rootNode, func(node *yaml.Node, path string) { if strings.HasPrefix(path, "keybinding.") && node.Kind == yaml.ScalarNode && node.Tag == "!!null" { node.Value = "<disabled>" node.Tag = "!!str" changes.Add(fmt.Sprintf("Changed 'null' to '<disabled>' for keybinding '%s'", path)) } }) } func changeElementToSequence(rootNode *yaml.Node, path []string, changes *ChangesSet) error { return yaml_utils.TransformNode(rootNode, path, func(node *yaml.Node) error { if node.Kind == yaml.MappingNode { nodeContentCopy := node.Content node.Kind = yaml.SequenceNode node.Value = "" node.Tag = "!!seq" node.Content = []*yaml.Node{{ Kind: yaml.MappingNode, Content: nodeContentCopy, }} changes.Add(fmt.Sprintf("Changed '%s' to an array of strings", strings.Join(path, "."))) return nil } return nil }) } func changeCommitPrefixesMap(rootNode *yaml.Node, changes *ChangesSet) error { return yaml_utils.TransformNode(rootNode, []string{"git", "commitPrefixes"}, func(prefixesNode *yaml.Node) error { if prefixesNode.Kind == yaml.MappingNode { for _, contentNode := range prefixesNode.Content { if contentNode.Kind == yaml.MappingNode { nodeContentCopy := contentNode.Content contentNode.Kind = yaml.SequenceNode contentNode.Value = "" contentNode.Tag = "!!seq" contentNode.Content = []*yaml.Node{{ Kind: yaml.MappingNode, Content: nodeContentCopy, }} changes.Add("Changed 'git.commitPrefixes' elements to arrays of strings") } } } return nil }) } func changeCustomCommandStreamAndOutputToOutputEnum(rootNode *yaml.Node, changes *ChangesSet) error { return yaml_utils.Walk(rootNode, func(node *yaml.Node, path string) { // We are being lazy here and rely on the fact that the only mapping // nodes in the tree under customCommands are actual custom commands. If // this ever changes (e.g. because we add a struct field to // customCommand), then we need to change this to iterate properly. if strings.HasPrefix(path, "customCommands[") && node.Kind == yaml.MappingNode { output := "" if streamKey, streamValue := yaml_utils.RemoveKey(node, "subprocess"); streamKey != nil { if streamValue.Kind == yaml.ScalarNode && streamValue.Value == "true" { output = "terminal" changes.Add("Changed 'subprocess: true' to 'output: terminal' in custom command") } else { changes.Add("Deleted redundant 'subprocess: false' in custom command") } } if streamKey, streamValue := yaml_utils.RemoveKey(node, "stream"); streamKey != nil { if streamValue.Kind == yaml.ScalarNode && streamValue.Value == "true" && output == "" { output = "log" changes.Add("Changed 'stream: true' to 'output: log' in custom command") } else { changes.Add(fmt.Sprintf("Deleted redundant 'stream: %v' property in custom command", streamValue.Value)) } } if streamKey, streamValue := yaml_utils.RemoveKey(node, "showOutput"); streamKey != nil { if streamValue.Kind == yaml.ScalarNode && streamValue.Value == "true" && output == "" { changes.Add("Changed 'showOutput: true' to 'output: popup' in custom command") output = "popup" } else { changes.Add(fmt.Sprintf("Deleted redundant 'showOutput: %v' property in custom command", streamValue.Value)) } } if output != "" { outputKeyNode := &yaml.Node{ Kind: yaml.ScalarNode, Value: "output", Tag: "!!str", } outputValueNode := &yaml.Node{ Kind: yaml.ScalarNode, Value: output, Tag: "!!str", } node.Content = append(node.Content, outputKeyNode, outputValueNode) } } }) } // This migration is special because users have already defined // a single element at `allBranchesLogCmd` and the sequence at `allBranchesLogCmds`. // Some users have explicitly set `allBranchesLogCmd` to be an empty string in order // to remove it, so in that case we just delete the element, and add nothing to the list func migrateAllBranchesLogCmd(rootNode *yaml.Node, changes *ChangesSet) error { return yaml_utils.TransformNode(rootNode, []string{"git"}, func(gitNode *yaml.Node) error { cmdKeyNode, cmdValueNode := yaml_utils.LookupKey(gitNode, "allBranchesLogCmd") // Nothing to do if they do not have the deprecated item if cmdKeyNode == nil { return nil } cmdsKeyNode, cmdsValueNode := yaml_utils.LookupKey(gitNode, "allBranchesLogCmds") var change string if cmdsKeyNode == nil { // Create empty sequence node and attach it onto the root git node // We will later populate it with the individual allBranchesLogCmd record cmdsKeyNode = &yaml.Node{Kind: yaml.ScalarNode, Value: "allBranchesLogCmds"} cmdsValueNode = &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{}} gitNode.Content = append(gitNode.Content, cmdsKeyNode, cmdsValueNode, ) change = "Created git.allBranchesLogCmds array containing value of git.allBranchesLogCmd" } else { if cmdsValueNode.Kind != yaml.SequenceNode { return errors.New("You should have an allBranchesLogCmds defined as a sequence!") } change = "Prepended git.allBranchesLogCmd value to git.allBranchesLogCmds array" } if cmdValueNode.Value != "" { // Prepending the individual element to make it show up first in the list, which was prior behavior cmdsValueNode.Content = utils.Prepend(cmdsValueNode.Content, &yaml.Node{Kind: yaml.ScalarNode, Value: cmdValueNode.Value}) changes.Add(change) } // Clear out the existing allBranchesLogCmd, now that we have migrated it into the list _, _ = yaml_utils.RemoveKey(gitNode, "allBranchesLogCmd") changes.Add("Removed obsolete git.allBranchesLogCmd") return nil }) } func migratePagers(rootNode *yaml.Node, changes *ChangesSet) error { return yaml_utils.TransformNode(rootNode, []string{"git"}, func(gitNode *yaml.Node) error { pagingKeyNode, pagingValueNode := yaml_utils.LookupKey(gitNode, "paging") if pagingKeyNode == nil || pagingValueNode.Kind != yaml.MappingNode { // If there's no "paging" section (or it's not an object), there's nothing to do return nil } pagersKeyNode, _ := yaml_utils.LookupKey(gitNode, "pagers") if pagersKeyNode != nil { // Conversely, if there *is* already a "pagers" array, we also have nothing to do. // This covers the case where the user keeps both the "paging" section and the "pagers" // array for the sake of easier testing of old versions. return nil } pagingKeyNode.Value = "pagers" pagingContentCopy := pagingValueNode.Content pagingValueNode.Kind = yaml.SequenceNode pagingValueNode.Tag = "!!seq" pagingValueNode.Content = []*yaml.Node{{ Kind: yaml.MappingNode, Content: pagingContentCopy, }} changes.Add("Moved git.paging object to git.pagers array") return nil }) } func (c *AppConfig) GetDebug() bool { return c.debug } func (c *AppConfig) GetVersion() string { return c.version } func (c *AppConfig) GetName() string { return c.name } // GetBuildSource returns the source of the build. For builds from goreleaser // this will be binaryBuild func (c *AppConfig) GetBuildSource() string { return c.buildSource } // GetUserConfig returns the user config func (c *AppConfig) GetUserConfig() *UserConfig { return c.userConfig } // GetAppState returns the app state func (c *AppConfig) GetAppState() *AppState { return c.appState } func (c *AppConfig) GetUserConfigPaths() []string { return lo.FilterMap(c.userConfigFiles, func(f *ConfigFile, _ int) (string, bool) { return f.Path, f.exists }) } func (c *AppConfig) GetUserConfigDir() string { return c.userConfigDir } func (c *AppConfig) ReloadUserConfigForRepo(repoConfigFiles []*ConfigFile) error { configFiles := append(c.globalUserConfigFiles, repoConfigFiles...) userConfig, err := loadUserConfigWithDefaults(configFiles, true) if err != nil { return err } c.userConfig = userConfig c.userConfigFiles = configFiles return nil } func (c *AppConfig) ReloadChangedUserConfigFiles() (error, bool) { fileHasChanged := func(f *ConfigFile) bool { info, err := os.Stat(f.Path) if err != nil && !os.IsNotExist(err) { // If we can't stat the file, assume it hasn't changed return false } exists := err == nil return exists != f.exists || (exists && info.ModTime() != f.modDate) } if lo.NoneBy(c.userConfigFiles, fileHasChanged) { return nil, false } userConfig, err := loadUserConfigWithDefaults(c.userConfigFiles, true) if err != nil { return err, false } c.userConfig = userConfig return nil, true } func (c *AppConfig) GetTempDir() string { return c.tempDir } // findConfigFile looks for a possibly existing config file. // This function does NOT create any folders or files. func findConfigFile(filename string) (exists bool, path string) { if envConfigDir := os.Getenv("CONFIG_DIR"); envConfigDir != "" { return true, filepath.Join(envConfigDir, filename) } // look for jesseduffield/lazygit/filename in XDG_CONFIG_HOME and XDG_CONFIG_DIRS legacyConfigPath, err := xdg.SearchConfigFile(filepath.Join("jesseduffield", "lazygit", filename)) if err == nil { return true, legacyConfigPath } // look for lazygit/filename in XDG_CONFIG_HOME and XDG_CONFIG_DIRS configFilepath, err := xdg.SearchConfigFile(filepath.Join("lazygit", filename)) if err == nil { return true, configFilepath } return false, filepath.Join(xdg.ConfigHome, "lazygit", filename) } var ConfigFilename = "config.yml" // stateFilePath looks for a possibly existing state file. // if none exist, the default path is returned and all parent directories are created. func stateFilePath(filename string) (string, error) { exists, legacyStateFile := findConfigFile(filename) if exists { return legacyStateFile, nil } // looks for XDG_STATE_HOME/lazygit/filename return xdg.StateFile(filepath.Join("lazygit", filename)) } // SaveAppState marshalls the AppState struct and writes it to the disk func (c *AppConfig) SaveAppState() error { marshalledAppState, err := yaml.Marshal(c.appState) if err != nil { return err } filepath, err := stateFilePath(stateFileName) if err != nil { return err } err = os.WriteFile(filepath, marshalledAppState, 0o644) if err != nil && os.IsPermission(err) { // apparently when people have read-only permissions they prefer us to fail silently return nil } return err } var stateFileName = "state.yml" // loadAppState loads recorded AppState from file func loadAppState() (*AppState, error) { appState := getDefaultAppState() filepath, err := stateFilePath(stateFileName) if err != nil { if os.IsPermission(err) { // apparently when people have read-only permissions they prefer us to fail silently return appState, nil } return nil, err } appStateBytes, err := os.ReadFile(filepath) if err != nil && !os.IsNotExist(err) { return nil, err } if len(appStateBytes) == 0 { return appState, nil } err = yaml.Unmarshal(appStateBytes, appState) if err != nil { return nil, err } return appState, nil } // SaveGlobalUserConfig saves the UserConfig back to disk. This is only used in // integration tests, so we are a bit sloppy with error handling. func (c *AppConfig) SaveGlobalUserConfig() { if len(c.globalUserConfigFiles) != 1 { panic("expected exactly one global user config file") } yamlContent, err := yaml.Marshal(c.userConfig) if err != nil { log.Fatalf("error marshalling user config: %v", err) } err = os.WriteFile(c.globalUserConfigFiles[0].Path, yamlContent, 0o644) if err != nil { log.Fatalf("error saving user config: %v", err) } } // AppState stores data between runs of the app like when the last update check // was performed and which other repos have been checked out type AppState struct { LastUpdateCheck int64 RecentRepos []string StartupPopupVersion int DidShowHunkStagingHint bool LastVersion string // this is the last version the user was using, for the purpose of showing release notes // these are for shell commands typed in directly, not for custom commands in the lazygit config. // For backwards compatibility we keep the old name in yaml files. ShellCommandsHistory []string `yaml:"customcommandshistory"` HideCommandLog bool } func getDefaultAppState() *AppState { return &AppState{} } func LogPath() (string, error) { if os.Getenv("LAZYGIT_LOG_PATH") != "" { return os.Getenv("LAZYGIT_LOG_PATH"), nil } return stateFilePath("development.log") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/editor_presets.go
pkg/config/editor_presets.go
package config import ( "os" "strings" ) func GetEditTemplate(shell string, osConfig *OSConfig, guessDefaultEditor func() string) (string, bool) { preset := getPreset(shell, osConfig, guessDefaultEditor) template := osConfig.Edit if template == "" { template = preset.editTemplate } return template, getEditInTerminal(osConfig, preset) } func GetEditAtLineTemplate(shell string, osConfig *OSConfig, guessDefaultEditor func() string) (string, bool) { preset := getPreset(shell, osConfig, guessDefaultEditor) template := osConfig.EditAtLine if template == "" { template = preset.editAtLineTemplate } return template, getEditInTerminal(osConfig, preset) } func GetEditAtLineAndWaitTemplate(shell string, osConfig *OSConfig, guessDefaultEditor func() string) string { preset := getPreset(shell, osConfig, guessDefaultEditor) template := osConfig.EditAtLineAndWait if template == "" { template = preset.editAtLineAndWaitTemplate } return template } func GetOpenDirInEditorTemplate(shell string, osConfig *OSConfig, guessDefaultEditor func() string) (string, bool) { preset := getPreset(shell, osConfig, guessDefaultEditor) template := osConfig.OpenDirInEditor if template == "" { template = preset.openDirInEditorTemplate } return template, getEditInTerminal(osConfig, preset) } type editPreset struct { editTemplate string editAtLineTemplate string editAtLineAndWaitTemplate string openDirInEditorTemplate string suspend func() bool } func returnBool(a bool) func() bool { return (func() bool { return a }) } // IF YOU ADD A PRESET TO THIS FUNCTION YOU MUST UPDATE THE `Supported presets` SECTION OF docs/Config.md func getPreset(shell string, osConfig *OSConfig, guessDefaultEditor func() string) *editPreset { var nvimRemoteEditTemplate, nvimRemoteEditAtLineTemplate, nvimRemoteOpenDirInEditorTemplate string // By default fish doesn't have SHELL variable set, but it does have FISH_VERSION since Nov 2012. if (strings.HasSuffix(shell, "fish")) || (os.Getenv("FISH_VERSION") != "") { nvimRemoteEditTemplate = `begin; if test -z "$NVIM"; nvim -- {{filename}}; else; nvim --server "$NVIM" --remote-send "q"; nvim --server "$NVIM" --remote-tab {{filename}}; end; end` nvimRemoteEditAtLineTemplate = `begin; if test -z "$NVIM"; nvim +{{line}} -- {{filename}}; else; nvim --server "$NVIM" --remote-send "q"; nvim --server "$NVIM" --remote-tab {{filename}}; nvim --server "$NVIM" --remote-send ":{{line}}<CR>"; end; end` nvimRemoteOpenDirInEditorTemplate = `begin; if test -z "$NVIM"; nvim -- {{dir}}; else; nvim --server "$NVIM" --remote-send "q"; nvim --server "$NVIM" --remote-tab {{dir}}; end; end` } else { nvimRemoteEditTemplate = `[ -z "$NVIM" ] && (nvim -- {{filename}}) || (nvim --server "$NVIM" --remote-send "q" && nvim --server "$NVIM" --remote-tab {{filename}})` nvimRemoteEditAtLineTemplate = `[ -z "$NVIM" ] && (nvim +{{line}} -- {{filename}}) || (nvim --server "$NVIM" --remote-send "q" && nvim --server "$NVIM" --remote-tab {{filename}} && nvim --server "$NVIM" --remote-send ":{{line}}<CR>")` nvimRemoteOpenDirInEditorTemplate = `[ -z "$NVIM" ] && (nvim -- {{dir}}) || (nvim --server "$NVIM" --remote-send "q" && nvim --server "$NVIM" --remote-tab {{dir}})` } presets := map[string]*editPreset{ "vi": standardTerminalEditorPreset("vi"), "vim": standardTerminalEditorPreset("vim"), "nvim": standardTerminalEditorPreset("nvim"), "nvim-remote": { editTemplate: nvimRemoteEditTemplate, editAtLineTemplate: nvimRemoteEditAtLineTemplate, // No remote-wait support yet. See https://github.com/neovim/neovim/pull/17856 editAtLineAndWaitTemplate: `nvim +{{line}} {{filename}}`, openDirInEditorTemplate: nvimRemoteOpenDirInEditorTemplate, suspend: func() bool { _, ok := os.LookupEnv("NVIM") return !ok }, }, "lvim": standardTerminalEditorPreset("lvim"), "emacs": standardTerminalEditorPreset("emacs"), "micro": { editTemplate: "micro {{filename}}", editAtLineTemplate: "micro +{{line}} {{filename}}", editAtLineAndWaitTemplate: "micro +{{line}} {{filename}}", openDirInEditorTemplate: "micro {{dir}}", suspend: returnBool(true), }, "nano": standardTerminalEditorPreset("nano"), "kakoune": standardTerminalEditorPreset("kak"), "helix": { editTemplate: "helix -- {{filename}}", editAtLineTemplate: "helix -- {{filename}}:{{line}}", editAtLineAndWaitTemplate: "helix -- {{filename}}:{{line}}", openDirInEditorTemplate: "helix -- {{dir}}", suspend: returnBool(true), }, "helix (hx)": { editTemplate: "hx -- {{filename}}", editAtLineTemplate: "hx -- {{filename}}:{{line}}", editAtLineAndWaitTemplate: "hx -- {{filename}}:{{line}}", openDirInEditorTemplate: "hx -- {{dir}}", suspend: returnBool(true), }, "vscode": { editTemplate: "code --reuse-window -- {{filename}}", editAtLineTemplate: "code --reuse-window --goto -- {{filename}}:{{line}}", editAtLineAndWaitTemplate: "code --reuse-window --goto --wait -- {{filename}}:{{line}}", openDirInEditorTemplate: "code -- {{dir}}", suspend: returnBool(false), }, "sublime": { editTemplate: "subl -- {{filename}}", editAtLineTemplate: "subl -- {{filename}}:{{line}}", editAtLineAndWaitTemplate: "subl --wait -- {{filename}}:{{line}}", openDirInEditorTemplate: "subl -- {{dir}}", suspend: returnBool(false), }, "bbedit": { editTemplate: "bbedit -- {{filename}}", editAtLineTemplate: "bbedit +{{line}} -- {{filename}}", editAtLineAndWaitTemplate: "bbedit +{{line}} --wait -- {{filename}}", openDirInEditorTemplate: "bbedit -- {{dir}}", suspend: returnBool(false), }, "xcode": { editTemplate: "xed -- {{filename}}", editAtLineTemplate: "xed --line {{line}} -- {{filename}}", editAtLineAndWaitTemplate: "xed --line {{line}} --wait -- {{filename}}", openDirInEditorTemplate: "xed -- {{dir}}", suspend: returnBool(false), }, "zed": { editTemplate: "zed -- {{filename}}", editAtLineTemplate: "zed -- {{filename}}:{{line}}", editAtLineAndWaitTemplate: "zed --wait -- {{filename}}:{{line}}", openDirInEditorTemplate: "zed -- {{dir}}", suspend: returnBool(false), }, "acme": { editTemplate: "B {{filename}}", editAtLineTemplate: "B {{filename}}:{{line}}", editAtLineAndWaitTemplate: "E {{filename}}:{{line}}", openDirInEditorTemplate: "B {{dir}}", suspend: returnBool(false), }, } // Some of our presets have a different name than the editor they are using. editorToPreset := map[string]string{ "kak": "kakoune", "helix": "helix", "hx": "helix (hx)", "code": "vscode", "subl": "sublime", "xed": "xcode", } presetName := osConfig.EditPreset if presetName == "" { defaultEditor := guessDefaultEditor() if presets[defaultEditor] != nil { presetName = defaultEditor } else if p := editorToPreset[defaultEditor]; p != "" { presetName = p } } if presetName == "" || presets[presetName] == nil { presetName = "vim" } return presets[presetName] } func standardTerminalEditorPreset(editor string) *editPreset { return &editPreset{ editTemplate: editor + " -- {{filename}}", editAtLineTemplate: editor + " +{{line}} -- {{filename}}", editAtLineAndWaitTemplate: editor + " +{{line}} -- {{filename}}", openDirInEditorTemplate: editor + " -- {{dir}}", suspend: returnBool(true), } } func getEditInTerminal(osConfig *OSConfig, preset *editPreset) bool { if osConfig.SuspendOnEdit != nil { return *osConfig.SuspendOnEdit } return preset.suspend() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/pager_config.go
pkg/config/pager_config.go
package config import ( "strconv" "github.com/jesseduffield/lazygit/pkg/utils" ) type PagerConfig struct { getUserConfig func() *UserConfig pagerIndex int } func NewPagerConfig(getUserConfig func() *UserConfig) *PagerConfig { return &PagerConfig{getUserConfig: getUserConfig} } func (self *PagerConfig) currentPagerConfig() *PagingConfig { pagers := self.getUserConfig().Git.Pagers if len(pagers) == 0 { return nil } // Guard against the pager index being out of range, which can happen if the user // has removed pagers from their config file while lazygit is running. if self.pagerIndex >= len(pagers) { self.pagerIndex = 0 } return &pagers[self.pagerIndex] } func (self *PagerConfig) GetPagerCommand(width int) string { currentPagerConfig := self.currentPagerConfig() if currentPagerConfig == nil { return "" } templateValues := map[string]string{ "columnWidth": strconv.Itoa(width/2 - 6), } pagerTemplate := string(currentPagerConfig.Pager) return utils.ResolvePlaceholderString(pagerTemplate, templateValues) } func (self *PagerConfig) GetColorArg() string { currentPagerConfig := self.currentPagerConfig() if currentPagerConfig == nil { return "always" } colorArg := currentPagerConfig.ColorArg if colorArg == "" { return "always" } return colorArg } func (self *PagerConfig) GetExternalDiffCommand() string { currentPagerConfig := self.currentPagerConfig() if currentPagerConfig == nil { return "" } return currentPagerConfig.ExternalDiffCommand } func (self *PagerConfig) GetUseExternalDiffGitConfig() bool { currentPagerConfig := self.currentPagerConfig() if currentPagerConfig == nil { return false } return currentPagerConfig.UseExternalDiffGitConfig } func (self *PagerConfig) CyclePagers() { self.pagerIndex = (self.pagerIndex + 1) % len(self.getUserConfig().Git.Pagers) } func (self *PagerConfig) CurrentPagerIndex() (int, int) { return self.pagerIndex, len(self.getUserConfig().Git.Pagers) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/user_config.go
pkg/config/user_config.go
package config import ( "time" "github.com/karimkhaleel/jsonschema" ) type UserConfig struct { // Config relating to the Lazygit UI Gui GuiConfig `yaml:"gui"` // Config relating to git Git GitConfig `yaml:"git"` // Periodic update checks Update UpdateConfig `yaml:"update"` // Background refreshes Refresher RefresherConfig `yaml:"refresher"` // If true, show a confirmation popup before quitting Lazygit ConfirmOnQuit bool `yaml:"confirmOnQuit"` // If true, exit Lazygit when the user presses escape in a context where there is nothing to cancel/close QuitOnTopLevelReturn bool `yaml:"quitOnTopLevelReturn"` // Config relating to things outside of Lazygit like how files are opened, copying to clipboard, etc OS OSConfig `yaml:"os,omitempty"` // If true, don't display introductory popups upon opening Lazygit. DisableStartupPopups bool `yaml:"disableStartupPopups"` // User-configured commands that can be invoked from within Lazygit // See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Command_Keybindings.md CustomCommands []CustomCommand `yaml:"customCommands" jsonschema:"uniqueItems=true"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-pull-request-urls Services map[string]string `yaml:"services"` // What to do when opening Lazygit outside of a git repo. // - 'prompt': (default) ask whether to initialize a new repo or open in the most recent repo // - 'create': initialize a new repo // - 'skip': open most recent repo // - 'quit': exit Lazygit NotARepository string `yaml:"notARepository" jsonschema:"enum=prompt,enum=create,enum=skip,enum=quit"` // If true, display a confirmation when subprocess terminates. This allows you to view the output of the subprocess before returning to Lazygit. PromptToReturnFromSubprocess bool `yaml:"promptToReturnFromSubprocess"` // Keybindings Keybinding KeybindingConfig `yaml:"keybinding"` } type RefresherConfig struct { // File/submodule refresh interval in seconds. // Auto-refresh can be disabled via option 'git.autoRefresh'. RefreshInterval int `yaml:"refreshInterval" jsonschema:"minimum=0"` // Re-fetch interval in seconds. // Auto-fetch can be disabled via option 'git.autoFetch'. FetchInterval int `yaml:"fetchInterval" jsonschema:"minimum=0"` } func (c *RefresherConfig) RefreshIntervalDuration() time.Duration { return time.Second * time.Duration(c.RefreshInterval) } func (c *RefresherConfig) FetchIntervalDuration() time.Duration { return time.Second * time.Duration(c.FetchInterval) } type GuiConfig struct { // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-author-color AuthorColors map[string]string `yaml:"authorColors"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color // Deprecated: use branchColorPatterns instead BranchColors map[string]string `yaml:"branchColors" jsonschema:"deprecated"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color BranchColorPatterns map[string]string `yaml:"branchColorPatterns"` // Custom icons for filenames and file extensions // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-files-icon--color CustomIcons CustomIconsConfig `yaml:"customIcons"` // The number of lines you scroll by when scrolling the main window ScrollHeight int `yaml:"scrollHeight" jsonschema:"minimum=1"` // If true, allow scrolling past the bottom of the content in the main window ScrollPastBottom bool `yaml:"scrollPastBottom"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#scroll-off-margin ScrollOffMargin int `yaml:"scrollOffMargin"` // One of: 'margin' (default) | 'jump' ScrollOffBehavior string `yaml:"scrollOffBehavior"` // The number of spaces per tab; used for everything that's shown in the main view, but probably mostly relevant for diffs. // Note that when using a pager, the pager has its own tab width setting, so you need to pass it separately in the pager command. TabWidth int `yaml:"tabWidth" jsonschema:"minimum=1"` // If true, capture mouse events. // When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS. MouseEvents bool `yaml:"mouseEvents"` // If true, do not show a warning when amending a commit. SkipAmendWarning bool `yaml:"skipAmendWarning"` // If true, do not show a warning when discarding changes in the staging view. SkipDiscardChangeWarning bool `yaml:"skipDiscardChangeWarning"` // If true, do not show warning when applying/popping the stash SkipStashWarning bool `yaml:"skipStashWarning"` // If true, do not show a warning when attempting to commit without any staged files; instead stage all unstaged files. SkipNoStagedFilesWarning bool `yaml:"skipNoStagedFilesWarning"` // If true, do not show a warning when rewording a commit via an external editor SkipRewordInEditorWarning bool `yaml:"skipRewordInEditorWarning"` // If true, switch to a different worktree without confirmation when checking out a branch that is checked out in that worktree SkipSwitchWorktreeOnCheckoutWarning bool `yaml:"skipSwitchWorktreeOnCheckoutWarning"` // Fraction of the total screen width to use for the left side section. You may want to pick a small number (e.g. 0.2) if you're using a narrow screen, so that you can see more of the main section. // Number from 0 to 1.0. SidePanelWidth float64 `yaml:"sidePanelWidth" jsonschema:"maximum=1,minimum=0"` // If true, increase the height of the focused side window; creating an accordion effect. ExpandFocusedSidePanel bool `yaml:"expandFocusedSidePanel"` // The weight of the expanded side panel, relative to the other panels. 2 means twice as tall as the other panels. Only relevant if `expandFocusedSidePanel` is true. ExpandedSidePanelWeight int `yaml:"expandedSidePanelWeight"` // Sometimes the main window is split in two (e.g. when the selected file has both staged and unstaged changes). This setting controls how the two sections are split. // Options are: // - 'horizontal': split the window horizontally // - 'vertical': split the window vertically // - 'flexible': (default) split the window horizontally if the window is wide enough, otherwise split vertically MainPanelSplitMode string `yaml:"mainPanelSplitMode" jsonschema:"enum=horizontal,enum=flexible,enum=vertical"` // How the window is split when in half screen mode (i.e. after hitting '+' once). // Possible values: // - 'left': split the window horizontally (side panel on the left, main view on the right) // - 'top': split the window vertically (side panel on top, main view below) EnlargedSideViewLocation string `yaml:"enlargedSideViewLocation"` // If true, wrap lines in the staging view to the width of the view. This makes it much easier to work with diffs that have long lines, e.g. paragraphs of markdown text. WrapLinesInStagingView bool `yaml:"wrapLinesInStagingView"` // If true, hunk selection mode will be enabled by default when entering the staging view. UseHunkModeInStagingView bool `yaml:"useHunkModeInStagingView"` // One of 'auto' (default) | 'en' | 'zh-CN' | 'zh-TW' | 'pl' | 'nl' | 'ja' | 'ko' | 'ru' | 'pt' Language string `yaml:"language" jsonschema:"enum=auto,enum=en,enum=zh-TW,enum=zh-CN,enum=pl,enum=nl,enum=ja,enum=ko,enum=ru"` // Format used when displaying time e.g. commit time. // Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format TimeFormat string `yaml:"timeFormat"` // Format used when displaying time if the time is less than 24 hours ago. // Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format ShortTimeFormat string `yaml:"shortTimeFormat"` // Config relating to colors and styles. // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes Theme ThemeConfig `yaml:"theme"` // Config relating to the commit length indicator CommitLength CommitLengthConfig `yaml:"commitLength"` // If true, show the '5 of 20' footer at the bottom of list views ShowListFooter bool `yaml:"showListFooter"` // If true, display the files in the file views as a tree. If false, display the files as a flat list. // This can be toggled from within Lazygit with the '`' key, but that will not change the default. ShowFileTree bool `yaml:"showFileTree"` // If true, add a "/" root item in the file tree representing the root of the repository. It is only added when necessary, i.e. when there is more than one item at top level. ShowRootItemInFileTree bool `yaml:"showRootItemInFileTree"` // If true, show the number of lines changed per file in the Files view ShowNumstatInFilesView bool `yaml:"showNumstatInFilesView"` // If true, show a random tip in the command log when Lazygit starts ShowRandomTip bool `yaml:"showRandomTip"` // If true, show the command log ShowCommandLog bool `yaml:"showCommandLog"` // If true, show the bottom line that contains keybinding info and useful buttons. If false, this line will be hidden except to display a loader for an in-progress action. ShowBottomLine bool `yaml:"showBottomLine"` // If true, show jump-to-window keybindings in window titles. ShowPanelJumps bool `yaml:"showPanelJumps"` // Deprecated: use nerdFontsVersion instead ShowIcons bool `yaml:"showIcons" jsonschema:"deprecated"` // Nerd fonts version to use. // One of: '2' | '3' | empty string (default) // If empty, do not show icons. NerdFontsVersion string `yaml:"nerdFontsVersion" jsonschema:"enum=2,enum=3,enum="` // If true (default), file icons are shown in the file views. Only relevant if NerdFontsVersion is not empty. ShowFileIcons bool `yaml:"showFileIcons"` // Length of author name in (non-expanded) commits view. 2 means show initials only. CommitAuthorShortLength int `yaml:"commitAuthorShortLength"` // Length of author name in expanded commits view. 2 means show initials only. CommitAuthorLongLength int `yaml:"commitAuthorLongLength"` // Length of commit hash in commits view. 0 shows '*' if NF icons aren't on. CommitHashLength int `yaml:"commitHashLength" jsonschema:"minimum=0"` // If true, show commit hashes alongside branch names in the branches view. ShowBranchCommitHash bool `yaml:"showBranchCommitHash"` // Whether to show the divergence from the base branch in the branches view. // One of: 'none' | 'onlyArrow' | 'arrowAndNumber' ShowDivergenceFromBaseBranch string `yaml:"showDivergenceFromBaseBranch" jsonschema:"enum=none,enum=onlyArrow,enum=arrowAndNumber"` // Height of the command log view CommandLogSize int `yaml:"commandLogSize" jsonschema:"minimum=0"` // Whether to split the main window when viewing file changes. // One of: 'auto' | 'always' // If 'auto', only split the main window when a file has both staged and unstaged changes SplitDiff string `yaml:"splitDiff" jsonschema:"enum=auto,enum=always"` // Default size for focused window. Can be changed from within Lazygit with '+' and '_' (but this won't change the default). // One of: 'normal' (default) | 'half' | 'full' ScreenMode string `yaml:"screenMode" jsonschema:"enum=normal,enum=half,enum=full"` // Window border style. // One of 'rounded' (default) | 'single' | 'double' | 'hidden' | 'bold' Border string `yaml:"border" jsonschema:"enum=single,enum=double,enum=rounded,enum=hidden,enum=bold"` // If true, show a seriously epic explosion animation when nuking the working tree. AnimateExplosion bool `yaml:"animateExplosion"` // Whether to stack UI components on top of each other. // One of 'auto' (default) | 'always' | 'never' PortraitMode string `yaml:"portraitMode"` // How things are filtered when typing '/'. // One of 'substring' (default) | 'fuzzy' FilterMode string `yaml:"filterMode" jsonschema:"enum=substring,enum=fuzzy"` // Config relating to the spinner. Spinner SpinnerConfig `yaml:"spinner"` // Status panel view. // One of 'dashboard' (default) | 'allBranchesLog' StatusPanelView string `yaml:"statusPanelView" jsonschema:"enum=dashboard,enum=allBranchesLog"` // If true, jump to the Files panel after popping a stash SwitchToFilesAfterStashPop bool `yaml:"switchToFilesAfterStashPop"` // If true, jump to the Files panel after applying a stash SwitchToFilesAfterStashApply bool `yaml:"switchToFilesAfterStashApply"` // If true, when using the panel jump keys (default 1 through 5) and target panel is already active, go to next tab instead SwitchTabsWithPanelJumpKeys bool `yaml:"switchTabsWithPanelJumpKeys"` } func (c *GuiConfig) UseFuzzySearch() bool { return c.FilterMode == "fuzzy" } type ThemeConfig struct { // Border color of focused window ActiveBorderColor []string `yaml:"activeBorderColor" jsonschema:"minItems=1,uniqueItems=true"` // Border color of non-focused windows InactiveBorderColor []string `yaml:"inactiveBorderColor" jsonschema:"minItems=1,uniqueItems=true"` // Border color of focused window when searching in that window SearchingActiveBorderColor []string `yaml:"searchingActiveBorderColor" jsonschema:"minItems=1,uniqueItems=true"` // Color of keybindings help text in the bottom line OptionsTextColor []string `yaml:"optionsTextColor" jsonschema:"minItems=1,uniqueItems=true"` // Background color of selected line. // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line SelectedLineBgColor []string `yaml:"selectedLineBgColor" jsonschema:"minItems=1,uniqueItems=true"` // Background color of selected line when view doesn't have focus. InactiveViewSelectedLineBgColor []string `yaml:"inactiveViewSelectedLineBgColor" jsonschema:"minItems=1,uniqueItems=true"` // Foreground color of copied commit CherryPickedCommitFgColor []string `yaml:"cherryPickedCommitFgColor" jsonschema:"minItems=1,uniqueItems=true"` // Background color of copied commit CherryPickedCommitBgColor []string `yaml:"cherryPickedCommitBgColor" jsonschema:"minItems=1,uniqueItems=true"` // Foreground color of marked base commit (for rebase) MarkedBaseCommitFgColor []string `yaml:"markedBaseCommitFgColor"` // Background color of marked base commit (for rebase) MarkedBaseCommitBgColor []string `yaml:"markedBaseCommitBgColor"` // Color for file with unstaged changes UnstagedChangesColor []string `yaml:"unstagedChangesColor" jsonschema:"minItems=1,uniqueItems=true"` // Default text color DefaultFgColor []string `yaml:"defaultFgColor" jsonschema:"minItems=1,uniqueItems=true"` } type CommitLengthConfig struct { // If true, show an indicator of commit message length Show bool `yaml:"show"` } type SpinnerConfig struct { // The frames of the spinner animation. Frames []string `yaml:"frames"` // The "speed" of the spinner in milliseconds. Rate int `yaml:"rate" jsonschema:"minimum=1"` } type GitConfig struct { // Array of pagers. Each entry has the following format: // [dev] The following documentation is duplicated from the PagingConfig struct below. // // # Value of the --color arg in the git diff command. Some pagers want // # this to be set to 'always' and some want it set to 'never' // colorArg: "always" // // # e.g. // # diff-so-fancy // # delta --dark --paging=never // # ydiff -p cat -s --wrap --width={{columnWidth}} // pager: "" // // # e.g. 'difft --color=always' // externalDiffCommand: "" // // # If true, Lazygit will use git's `diff.external` config for paging. // # The advantage over `externalDiffCommand` is that this can be // # configured per file type in .gitattributes; see // # https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver. // useExternalDiffGitConfig: false // // See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md for more information. Pagers []PagingConfig `yaml:"pagers"` // Config relating to committing Commit CommitConfig `yaml:"commit"` // Config relating to merging Merging MergingConfig `yaml:"merging"` // list of branches that are considered 'main' branches, used when displaying commits MainBranches []string `yaml:"mainBranches" jsonschema:"uniqueItems=true"` // Prefix to use when skipping hooks. E.g. if set to 'WIP', then pre-commit hooks will be skipped when the commit message starts with 'WIP' SkipHookPrefix string `yaml:"skipHookPrefix"` // If true, periodically fetch from remote AutoFetch bool `yaml:"autoFetch"` // If true, periodically refresh files and submodules AutoRefresh bool `yaml:"autoRefresh"` // If not "none", lazygit will automatically fast-forward local branches to match their upstream after fetching. Applies to branches that are not the currently checked out branch, and only to those that are strictly behind their upstream (as opposed to diverged). // Possible values: 'none' | 'onlyMainBranches' | 'allBranches' AutoForwardBranches string `yaml:"autoForwardBranches" jsonschema:"enum=none,enum=onlyMainBranches,enum=allBranches"` // If true, pass the --all arg to git fetch FetchAll bool `yaml:"fetchAll"` // If true, lazygit will automatically stage files that used to have merge conflicts but no longer do; and it will also ask you if you want to continue a merge or rebase if you've resolved all conflicts. If false, it won't do either of these things. AutoStageResolvedConflicts bool `yaml:"autoStageResolvedConflicts"` // Command used when displaying the current branch git log in the main window BranchLogCmd string `yaml:"branchLogCmd"` // Commands used to display git log of all branches in the main window, they will be cycled in order of appearance (array of strings) AllBranchesLogCmds []string `yaml:"allBranchesLogCmds"` // If true, git diffs are rendered with the `--ignore-all-space` flag, which ignores whitespace changes. Can be toggled from within Lazygit with `<c-w>`. IgnoreWhitespaceInDiffView bool `yaml:"ignoreWhitespaceInDiffView"` // The number of lines of context to show around each diff hunk. Can be changed from within Lazygit with the `{` and `}` keys. DiffContextSize uint64 `yaml:"diffContextSize"` // The threshold for considering a file to be renamed, in percent. Can be changed from within Lazygit with the `(` and `)` keys. RenameSimilarityThreshold int `yaml:"renameSimilarityThreshold" jsonschema:"minimum=0,maximum=100"` // If true, do not spawn a separate process when using GPG OverrideGpg bool `yaml:"overrideGpg"` // If true, do not allow force pushes DisableForcePushing bool `yaml:"disableForcePushing"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix CommitPrefix []CommitPrefixConfig `yaml:"commitPrefix"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix CommitPrefixes map[string][]CommitPrefixConfig `yaml:"commitPrefixes"` // See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix BranchPrefix string `yaml:"branchPrefix"` // If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀 // (This should really be under 'gui', not 'git') ParseEmoji bool `yaml:"parseEmoji"` // Config for showing the log in the commits view Log LogConfig `yaml:"log"` // How branches are sorted in the local branches view. // One of: 'date' (default) | 'recency' | 'alphabetical' // Can be changed from within Lazygit with the Sort Order menu (`s`) in the branches panel. LocalBranchSortOrder string `yaml:"localBranchSortOrder" jsonschema:"enum=date,enum=recency,enum=alphabetical"` // How branches are sorted in the remote branches view. // One of: 'date' (default) | 'alphabetical' // Can be changed from within Lazygit with the Sort Order menu (`s`) in the remote branches panel. RemoteBranchSortOrder string `yaml:"remoteBranchSortOrder" jsonschema:"enum=date,enum=alphabetical"` // When copying commit hashes to the clipboard, truncate them to this length. Set to 40 to disable truncation. TruncateCopiedCommitHashesTo int `yaml:"truncateCopiedCommitHashesTo"` } type PagerType string func (PagerType) JSONSchemaExtend(schema *jsonschema.Schema) { schema.Examples = []any{ "delta --dark --paging=never", "diff-so-fancy", "ydiff -p cat -s --wrap --width={{columnWidth}}", } } // [dev] This documentation is duplicated in the GitConfig struct. If you make changes here, make them there too. type PagingConfig struct { // Value of the --color arg in the git diff command. Some pagers want this to be set to 'always' and some want it set to 'never' ColorArg string `yaml:"colorArg" jsonschema:"enum=always,enum=never"` // e.g. // diff-so-fancy // delta --dark --paging=never // ydiff -p cat -s --wrap --width={{columnWidth}} Pager PagerType `yaml:"pager"` // e.g. 'difft --color=always' ExternalDiffCommand string `yaml:"externalDiffCommand"` // If true, Lazygit will use git's `diff.external` config for paging. The advantage over `externalDiffCommand` is that this can be configured per file type in .gitattributes; see https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver. UseExternalDiffGitConfig bool `yaml:"useExternalDiffGitConfig"` } type CommitConfig struct { // If true, pass '--signoff' flag when committing SignOff bool `yaml:"signOff"` // Automatic WYSIWYG wrapping of the commit message as you type AutoWrapCommitMessage bool `yaml:"autoWrapCommitMessage"` // If autoWrapCommitMessage is true, the width to wrap to AutoWrapWidth int `yaml:"autoWrapWidth"` } type MergingConfig struct { // If true, run merges in a subprocess so that if a commit message is required, Lazygit will not hang // Only applicable to unix users. ManualCommit bool `yaml:"manualCommit"` // Extra args passed to `git merge`, e.g. --no-ff Args string `yaml:"args" jsonschema:"example=--no-ff"` // The commit message to use for a squash merge commit. Can contain "{{selectedRef}}" and "{{currentBranch}}" placeholders. SquashMergeMessage string `yaml:"squashMergeMessage"` } type LogConfig struct { // One of: 'date-order' | 'author-date-order' | 'topo-order' | 'default' // 'topo-order' makes it easier to read the git log graph, but commits may not appear chronologically. See https://git-scm.com/docs/ // // Can be changed from within Lazygit with `Log menu -> Commit sort order` (`<c-l>` in the commits window by default). Order string `yaml:"order" jsonschema:"enum=date-order,enum=author-date-order,enum=topo-order,enum=default"` // This determines whether the git graph is rendered in the commits panel // One of 'always' | 'never' | 'when-maximised' // // Can be toggled from within lazygit with `Log menu -> Show git graph` (`<c-l>` in the commits window by default). ShowGraph string `yaml:"showGraph" jsonschema:"enum=always,enum=never,enum=when-maximised"` // displays the whole git graph by default in the commits view (equivalent to passing the `--all` argument to `git log`) ShowWholeGraph bool `yaml:"showWholeGraph"` } type CommitPrefixConfig struct { // pattern to match on. E.g. for 'feature/AB-123' to match on the AB-123 use "^\\w+\\/(\\w+-\\w+).*" Pattern string `yaml:"pattern" jsonschema:"example=^\\w+\\/(\\w+-\\w+).*"` // Replace directive. E.g. for 'feature/AB-123' to start the commit message with 'AB-123 ' use "[$1] " Replace string `yaml:"replace" jsonschema:"example=[$1]"` } type UpdateConfig struct { // One of: 'prompt' (default) | 'background' | 'never' Method string `yaml:"method" jsonschema:"enum=prompt,enum=background,enum=never"` // Period in days between update checks Days int64 `yaml:"days" jsonschema:"minimum=0"` } type KeybindingConfig struct { Universal KeybindingUniversalConfig `yaml:"universal"` Status KeybindingStatusConfig `yaml:"status"` Files KeybindingFilesConfig `yaml:"files"` Branches KeybindingBranchesConfig `yaml:"branches"` Worktrees KeybindingWorktreesConfig `yaml:"worktrees"` Commits KeybindingCommitsConfig `yaml:"commits"` AmendAttribute KeybindingAmendAttributeConfig `yaml:"amendAttribute"` Stash KeybindingStashConfig `yaml:"stash"` CommitFiles KeybindingCommitFilesConfig `yaml:"commitFiles"` Main KeybindingMainConfig `yaml:"main"` Submodules KeybindingSubmodulesConfig `yaml:"submodules"` CommitMessage KeybindingCommitMessageConfig `yaml:"commitMessage"` } // damn looks like we have some inconsistencies here with -alt and -alt1 type KeybindingUniversalConfig struct { Quit string `yaml:"quit"` QuitAlt1 string `yaml:"quit-alt1"` SuspendApp string `yaml:"suspendApp"` Return string `yaml:"return"` QuitWithoutChangingDirectory string `yaml:"quitWithoutChangingDirectory"` TogglePanel string `yaml:"togglePanel"` PrevItem string `yaml:"prevItem"` NextItem string `yaml:"nextItem"` PrevItemAlt string `yaml:"prevItem-alt"` NextItemAlt string `yaml:"nextItem-alt"` PrevPage string `yaml:"prevPage"` NextPage string `yaml:"nextPage"` ScrollLeft string `yaml:"scrollLeft"` ScrollRight string `yaml:"scrollRight"` GotoTop string `yaml:"gotoTop"` GotoBottom string `yaml:"gotoBottom"` GotoTopAlt string `yaml:"gotoTop-alt"` GotoBottomAlt string `yaml:"gotoBottom-alt"` ToggleRangeSelect string `yaml:"toggleRangeSelect"` RangeSelectDown string `yaml:"rangeSelectDown"` RangeSelectUp string `yaml:"rangeSelectUp"` PrevBlock string `yaml:"prevBlock"` NextBlock string `yaml:"nextBlock"` PrevBlockAlt string `yaml:"prevBlock-alt"` NextBlockAlt string `yaml:"nextBlock-alt"` NextBlockAlt2 string `yaml:"nextBlock-alt2"` PrevBlockAlt2 string `yaml:"prevBlock-alt2"` JumpToBlock []string `yaml:"jumpToBlock"` FocusMainView string `yaml:"focusMainView"` NextMatch string `yaml:"nextMatch"` PrevMatch string `yaml:"prevMatch"` StartSearch string `yaml:"startSearch"` OptionMenu string `yaml:"optionMenu"` OptionMenuAlt1 string `yaml:"optionMenu-alt1"` Select string `yaml:"select"` GoInto string `yaml:"goInto"` Confirm string `yaml:"confirm"` ConfirmMenu string `yaml:"confirmMenu"` ConfirmSuggestion string `yaml:"confirmSuggestion"` ConfirmInEditor string `yaml:"confirmInEditor"` ConfirmInEditorAlt string `yaml:"confirmInEditor-alt"` Remove string `yaml:"remove"` New string `yaml:"new"` Edit string `yaml:"edit"` OpenFile string `yaml:"openFile"` ScrollUpMain string `yaml:"scrollUpMain"` ScrollDownMain string `yaml:"scrollDownMain"` ScrollUpMainAlt1 string `yaml:"scrollUpMain-alt1"` ScrollDownMainAlt1 string `yaml:"scrollDownMain-alt1"` ScrollUpMainAlt2 string `yaml:"scrollUpMain-alt2"` ScrollDownMainAlt2 string `yaml:"scrollDownMain-alt2"` ExecuteShellCommand string `yaml:"executeShellCommand"` CreateRebaseOptionsMenu string `yaml:"createRebaseOptionsMenu"` Push string `yaml:"pushFiles"` // 'Files' appended for legacy reasons Pull string `yaml:"pullFiles"` // 'Files' appended for legacy reasons Refresh string `yaml:"refresh"` CreatePatchOptionsMenu string `yaml:"createPatchOptionsMenu"` NextTab string `yaml:"nextTab"` PrevTab string `yaml:"prevTab"` NextScreenMode string `yaml:"nextScreenMode"` PrevScreenMode string `yaml:"prevScreenMode"` CyclePagers string `yaml:"cyclePagers"` Undo string `yaml:"undo"` Redo string `yaml:"redo"` FilteringMenu string `yaml:"filteringMenu"` DiffingMenu string `yaml:"diffingMenu"` DiffingMenuAlt string `yaml:"diffingMenu-alt"` CopyToClipboard string `yaml:"copyToClipboard"` OpenRecentRepos string `yaml:"openRecentRepos"` SubmitEditorText string `yaml:"submitEditorText"` ExtrasMenu string `yaml:"extrasMenu"` ToggleWhitespaceInDiffView string `yaml:"toggleWhitespaceInDiffView"` IncreaseContextInDiffView string `yaml:"increaseContextInDiffView"` DecreaseContextInDiffView string `yaml:"decreaseContextInDiffView"` IncreaseRenameSimilarityThreshold string `yaml:"increaseRenameSimilarityThreshold"` DecreaseRenameSimilarityThreshold string `yaml:"decreaseRenameSimilarityThreshold"` OpenDiffTool string `yaml:"openDiffTool"` } type KeybindingStatusConfig struct { CheckForUpdate string `yaml:"checkForUpdate"` RecentRepos string `yaml:"recentRepos"` AllBranchesLogGraph string `yaml:"allBranchesLogGraph"` } type KeybindingFilesConfig struct { CommitChanges string `yaml:"commitChanges"` CommitChangesWithoutHook string `yaml:"commitChangesWithoutHook"` AmendLastCommit string `yaml:"amendLastCommit"` CommitChangesWithEditor string `yaml:"commitChangesWithEditor"` FindBaseCommitForFixup string `yaml:"findBaseCommitForFixup"` ConfirmDiscard string `yaml:"confirmDiscard"` IgnoreFile string `yaml:"ignoreFile"` RefreshFiles string `yaml:"refreshFiles"` StashAllChanges string `yaml:"stashAllChanges"` ViewStashOptions string `yaml:"viewStashOptions"` ToggleStagedAll string `yaml:"toggleStagedAll"` ViewResetOptions string `yaml:"viewResetOptions"` Fetch string `yaml:"fetch"` ToggleTreeView string `yaml:"toggleTreeView"` OpenMergeOptions string `yaml:"openMergeOptions"` OpenStatusFilter string `yaml:"openStatusFilter"` CopyFileInfoToClipboard string `yaml:"copyFileInfoToClipboard"` CollapseAll string `yaml:"collapseAll"` ExpandAll string `yaml:"expandAll"` } type KeybindingBranchesConfig struct { CreatePullRequest string `yaml:"createPullRequest"` ViewPullRequestOptions string `yaml:"viewPullRequestOptions"` CopyPullRequestURL string `yaml:"copyPullRequestURL"` CheckoutBranchByName string `yaml:"checkoutBranchByName"` ForceCheckoutBranch string `yaml:"forceCheckoutBranch"` CheckoutPreviousBranch string `yaml:"checkoutPreviousBranch"` RebaseBranch string `yaml:"rebaseBranch"` RenameBranch string `yaml:"renameBranch"` MergeIntoCurrentBranch string `yaml:"mergeIntoCurrentBranch"` MoveCommitsToNewBranch string `yaml:"moveCommitsToNewBranch"` ViewGitFlowOptions string `yaml:"viewGitFlowOptions"` FastForward string `yaml:"fastForward"` CreateTag string `yaml:"createTag"` PushTag string `yaml:"pushTag"` SetUpstream string `yaml:"setUpstream"` FetchRemote string `yaml:"fetchRemote"` AddForkRemote string `yaml:"addForkRemote"` SortOrder string `yaml:"sortOrder"` } type KeybindingWorktreesConfig struct { ViewWorktreeOptions string `yaml:"viewWorktreeOptions"` } type KeybindingCommitsConfig struct { SquashDown string `yaml:"squashDown"` RenameCommit string `yaml:"renameCommit"` RenameCommitWithEditor string `yaml:"renameCommitWithEditor"` ViewResetOptions string `yaml:"viewResetOptions"` MarkCommitAsFixup string `yaml:"markCommitAsFixup"` CreateFixupCommit string `yaml:"createFixupCommit"` SquashAboveCommits string `yaml:"squashAboveCommits"`
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/user_config_validation.go
pkg/config/user_config_validation.go
package config import ( "fmt" "log" "reflect" "slices" "strings" "github.com/jesseduffield/lazygit/pkg/constants" ) func (config *UserConfig) Validate() error { if err := validateEnum("gui.statusPanelView", config.Gui.StatusPanelView, []string{"dashboard", "allBranchesLog"}); err != nil { return err } if err := validateEnum("gui.showDivergenceFromBaseBranch", config.Gui.ShowDivergenceFromBaseBranch, []string{"none", "onlyArrow", "arrowAndNumber"}); err != nil { return err } if err := validateEnum("git.autoForwardBranches", config.Git.AutoForwardBranches, []string{"none", "onlyMainBranches", "allBranches"}); err != nil { return err } if err := validateEnum("git.localBranchSortOrder", config.Git.LocalBranchSortOrder, []string{"date", "recency", "alphabetical"}); err != nil { return err } if err := validateEnum("git.remoteBranchSortOrder", config.Git.RemoteBranchSortOrder, []string{"date", "alphabetical"}); err != nil { return err } if err := validateEnum("git.log.order", config.Git.Log.Order, []string{"date-order", "author-date-order", "topo-order", "default"}); err != nil { return err } if err := validateEnum("git.log.showGraph", config.Git.Log.ShowGraph, []string{"always", "never", "when-maximised"}); err != nil { return err } if err := validateKeybindings(config.Keybinding); err != nil { return err } if err := validateCustomCommands(config.CustomCommands); err != nil { return err } return nil } func validateEnum(name string, value string, allowedValues []string) error { if slices.Contains(allowedValues, value) { return nil } allowedValuesStr := strings.Join(allowedValues, ", ") return fmt.Errorf("Unexpected value '%s' for '%s'. Allowed values: %s", value, name, allowedValuesStr) } func validateKeybindingsRecurse(path string, node any) error { value := reflect.ValueOf(node) if value.Kind() == reflect.Struct { for _, field := range reflect.VisibleFields(reflect.TypeOf(node)) { var newPath string if len(path) == 0 { newPath = field.Name } else { newPath = fmt.Sprintf("%s.%s", path, field.Name) } if err := validateKeybindingsRecurse(newPath, value.FieldByName(field.Name).Interface()); err != nil { return err } } } else if value.Kind() == reflect.Slice { for i := range value.Len() { if err := validateKeybindingsRecurse( fmt.Sprintf("%s[%d]", path, i), value.Index(i).Interface()); err != nil { return err } } } else if value.Kind() == reflect.String { key := node.(string) if !isValidKeybindingKey(key) { return fmt.Errorf("Unrecognized key '%s' for keybinding '%s'. For permitted values see %s", key, path, constants.Links.Docs.CustomKeybindings) } } else { log.Fatalf("Unexpected type for property '%s': %s", path, value.Kind()) } return nil } func validateKeybindings(keybindingConfig KeybindingConfig) error { if err := validateKeybindingsRecurse("", keybindingConfig); err != nil { return err } if len(keybindingConfig.Universal.JumpToBlock) != 5 { return fmt.Errorf("keybinding.universal.jumpToBlock must have 5 elements; found %d.", len(keybindingConfig.Universal.JumpToBlock)) } return nil } func validateCustomCommandKey(key string) error { if !isValidKeybindingKey(key) { return fmt.Errorf("Unrecognized key '%s' for custom command. For permitted values see %s", key, constants.Links.Docs.CustomKeybindings) } return nil } func validateCustomCommands(customCommands []CustomCommand) error { for _, customCommand := range customCommands { if err := validateCustomCommandKey(customCommand.Key); err != nil { return err } if len(customCommand.CommandMenu) > 0 { if len(customCommand.Context) > 0 || len(customCommand.Command) > 0 || len(customCommand.Prompts) > 0 || len(customCommand.LoadingText) > 0 || len(customCommand.Output) > 0 || len(customCommand.OutputTitle) > 0 || customCommand.After != nil { commandRef := "" if len(customCommand.Key) > 0 { commandRef = fmt.Sprintf(" with key '%s'", customCommand.Key) } return fmt.Errorf("Error with custom command%s: it is not allowed to use both commandMenu and any of the other fields except key and description.", commandRef) } if err := validateCustomCommands(customCommand.CommandMenu); err != nil { return err } } else { for _, prompt := range customCommand.Prompts { if err := validateCustomCommandPrompt(prompt); err != nil { return err } } if err := validateEnum("customCommand.output", customCommand.Output, []string{"", "none", "terminal", "log", "logWithPty", "popup"}); err != nil { return err } } } return nil } func validateCustomCommandPrompt(prompt CustomCommandPrompt) error { for _, option := range prompt.Options { if !isValidKeybindingKey(option.Key) { return fmt.Errorf("Unrecognized key '%s' for custom command prompt option. For permitted values see %s", option.Key, constants.Links.Docs.CustomKeybindings) } } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/config/keynames.go
pkg/config/keynames.go
package config import ( "strings" "unicode/utf8" "github.com/jesseduffield/gocui" "github.com/samber/lo" ) // NOTE: if you make changes to this table, be sure to update // docs/keybindings/Custom_Keybindings.md as well var LabelByKey = map[gocui.Key]string{ gocui.KeyF1: "<f1>", gocui.KeyF2: "<f2>", gocui.KeyF3: "<f3>", gocui.KeyF4: "<f4>", gocui.KeyF5: "<f5>", gocui.KeyF6: "<f6>", gocui.KeyF7: "<f7>", gocui.KeyF8: "<f8>", gocui.KeyF9: "<f9>", gocui.KeyF10: "<f10>", gocui.KeyF11: "<f11>", gocui.KeyF12: "<f12>", gocui.KeyInsert: "<insert>", gocui.KeyDelete: "<delete>", gocui.KeyHome: "<home>", gocui.KeyEnd: "<end>", gocui.KeyPgup: "<pgup>", gocui.KeyPgdn: "<pgdown>", gocui.KeyArrowUp: "<up>", gocui.KeyShiftArrowUp: "<s-up>", gocui.KeyArrowDown: "<down>", gocui.KeyShiftArrowDown: "<s-down>", gocui.KeyArrowLeft: "<left>", gocui.KeyArrowRight: "<right>", gocui.KeyTab: "<tab>", // <c-i> gocui.KeyBacktab: "<backtab>", gocui.KeyEnter: "<enter>", // <c-m> gocui.KeyAltEnter: "<a-enter>", gocui.KeyEsc: "<esc>", // <c-[>, <c-3> gocui.KeyBackspace: "<backspace>", // <c-h> gocui.KeyCtrlSpace: "<c-space>", // <c-~>, <c-2> gocui.KeyCtrlSlash: "<c-/>", // <c-_> gocui.KeySpace: "<space>", gocui.KeyCtrlA: "<c-a>", gocui.KeyCtrlB: "<c-b>", gocui.KeyCtrlC: "<c-c>", gocui.KeyCtrlD: "<c-d>", gocui.KeyCtrlE: "<c-e>", gocui.KeyCtrlF: "<c-f>", gocui.KeyCtrlG: "<c-g>", gocui.KeyCtrlJ: "<c-j>", gocui.KeyCtrlK: "<c-k>", gocui.KeyCtrlL: "<c-l>", gocui.KeyCtrlN: "<c-n>", gocui.KeyCtrlO: "<c-o>", gocui.KeyCtrlP: "<c-p>", gocui.KeyCtrlQ: "<c-q>", gocui.KeyCtrlR: "<c-r>", gocui.KeyCtrlS: "<c-s>", gocui.KeyCtrlT: "<c-t>", gocui.KeyCtrlU: "<c-u>", gocui.KeyCtrlV: "<c-v>", gocui.KeyCtrlW: "<c-w>", gocui.KeyCtrlX: "<c-x>", gocui.KeyCtrlY: "<c-y>", gocui.KeyCtrlZ: "<c-z>", gocui.KeyCtrl4: "<c-4>", // <c-\> gocui.KeyCtrl5: "<c-5>", // <c-]> gocui.KeyCtrl6: "<c-6>", gocui.KeyCtrl8: "<c-8>", gocui.MouseWheelUp: "mouse wheel up", gocui.MouseWheelDown: "mouse wheel down", } var KeyByLabel = lo.Invert(LabelByKey) func isValidKeybindingKey(key string) bool { runeCount := utf8.RuneCountInString(key) if key == "<disabled>" { return true } if runeCount > 1 { _, ok := KeyByLabel[strings.ToLower(key)] return ok } return true }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/cheatsheet/generate_test.go
pkg/cheatsheet/generate_test.go
package cheatsheet import ( "testing" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/i18n" "github.com/stretchr/testify/assert" ) func TestGetBindingSections(t *testing.T) { tr := i18n.EnglishTranslationSet() tests := []struct { testName string bindings []*types.Binding expected []*bindingSection }{ { testName: "no bindings", bindings: []*types.Binding{}, expected: []*bindingSection{}, }, { testName: "one binding", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, }, expected: []*bindingSection{ { title: "Files", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, }, }, }, }, { testName: "global binding", bindings: []*types.Binding{ { ViewName: "", Description: "quit", Key: 'a', }, }, expected: []*bindingSection{ { title: "Global keybindings", bindings: []*types.Binding{ { ViewName: "", Description: "quit", Key: 'a', }, }, }, }, }, { testName: "grouped bindings", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, { ViewName: "submodules", Description: "drop submodule", Key: 'a', }, }, expected: []*bindingSection{ { title: "Files", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, }, }, { title: "Submodules", bindings: []*types.Binding{ { ViewName: "submodules", Description: "drop submodule", Key: 'a', }, }, }, }, }, { testName: "with navigation bindings", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, { ViewName: "files", Description: "scroll", Key: 'a', Tag: "navigation", }, { ViewName: "commits", Description: "revert commit", Key: 'a', }, }, expected: []*bindingSection{ { title: "List panel navigation", bindings: []*types.Binding{ { ViewName: "files", Description: "scroll", Key: 'a', Tag: "navigation", }, }, }, { title: "Commits", bindings: []*types.Binding{ { ViewName: "commits", Description: "revert commit", Key: 'a', }, }, }, { title: "Files", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, }, }, }, }, { testName: "with duplicate navigation bindings", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, { ViewName: "files", Description: "scroll", Key: 'a', Tag: "navigation", }, { ViewName: "commits", Description: "revert commit", Key: 'a', }, { ViewName: "commits", Description: "scroll", Key: 'a', Tag: "navigation", }, { ViewName: "commits", Description: "page up", Key: 'a', Tag: "navigation", }, }, expected: []*bindingSection{ { title: "List panel navigation", bindings: []*types.Binding{ { ViewName: "files", Description: "scroll", Key: 'a', Tag: "navigation", }, { ViewName: "commits", Description: "page up", Key: 'a', Tag: "navigation", }, }, }, { title: "Commits", bindings: []*types.Binding{ { ViewName: "commits", Description: "revert commit", Key: 'a', }, }, }, { title: "Files", bindings: []*types.Binding{ { ViewName: "files", Description: "stage file", Key: 'a', }, { ViewName: "files", Description: "unstage file", Key: 'a', }, }, }, }, }, } for _, test := range tests { t.Run(test.testName, func(t *testing.T) { actual := getBindingSections(test.bindings, tr) assert.EqualValues(t, test.expected, actual) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/cheatsheet/generator.go
pkg/cheatsheet/generator.go
//go:build ignore package main import ( "fmt" "github.com/jesseduffield/lazygit/pkg/cheatsheet" ) func main() { fmt.Printf("Generating cheatsheets in %s...\n", cheatsheet.GetKeybindingsDir()) cheatsheet.Generate() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/cheatsheet/generate.go
pkg/cheatsheet/generate.go
//go:generate go run generator.go // This "script" generates files called Keybindings_{{.LANG}}.md // in the docs-master/keybindings directory. // // The content of these generated files is a keybindings cheatsheet. // // To generate the cheatsheets, run: // go generate pkg/cheatsheet/generate.go package cheatsheet import ( "cmp" "fmt" "log" "os" "slices" "strings" "github.com/jesseduffield/generics/maps" "github.com/jesseduffield/lazycore/pkg/utils" "github.com/jesseduffield/lazygit/pkg/app" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/i18n" "github.com/samber/lo" ) type bindingSection struct { title string bindings []*types.Binding } type header struct { // priority decides the order of the headers in the cheatsheet (lower means higher) priority int title string } type headerWithBindings struct { header header bindings []*types.Binding } func CommandToRun() string { return "go generate ./..." } func GetKeybindingsDir() string { return utils.GetLazyRootDirectory() + "/docs-master/keybindings" } func generateAtDir(cheatsheetDir string) { translationSetsByLang, err := i18n.GetTranslationSets() if err != nil { log.Fatal(err) } mConfig := config.NewDummyAppConfig() for lang := range translationSetsByLang { mConfig.GetUserConfig().Gui.Language = lang common, err := app.NewCommon(mConfig) if err != nil { log.Fatal(err) } tr, err := i18n.NewTranslationSetFromConfig(common.Log, lang) if err != nil { log.Fatal(err) } common.Tr = tr mApp, _ := app.NewApp(mConfig, nil, common) path := cheatsheetDir + "/Keybindings_" + lang + ".md" file, err := os.Create(path) if err != nil { panic(err) } bindings := mApp.Gui.GetCheatsheetKeybindings() bindingSections := getBindingSections(bindings, mApp.Tr) content := formatSections(mApp.Tr, bindingSections) content = fmt.Sprintf("_This file is auto-generated. To update, make the changes in the "+ "pkg/i18n directory and then run `%s` from the project root._\n\n%s", CommandToRun(), content) writeString(file, content) } } func Generate() { generateAtDir(GetKeybindingsDir()) } func writeString(file *os.File, str string) { _, err := file.WriteString(str) if err != nil { log.Fatal(err) } } func localisedTitle(tr *i18n.TranslationSet, str string) string { contextTitleMap := map[string]string{ "global": tr.GlobalTitle, "navigation": tr.NavigationTitle, "branches": tr.BranchesTitle, "localBranches": tr.LocalBranchesTitle, "files": tr.FilesTitle, "status": tr.StatusTitle, "submodules": tr.SubmodulesTitle, "subCommits": tr.SubCommitsTitle, "remoteBranches": tr.RemoteBranchesTitle, "remotes": tr.RemotesTitle, "reflogCommits": tr.ReflogCommitsTitle, "tags": tr.TagsTitle, "commitFiles": tr.CommitFilesTitle, "commitMessage": tr.CommitSummaryTitle, "commitDescription": tr.CommitDescriptionTitle, "commits": tr.CommitsTitle, "confirmation": tr.ConfirmationTitle, "prompt": tr.PromptTitle, "information": tr.InformationTitle, "main": tr.NormalTitle, "patchBuilding": tr.PatchBuildingTitle, "mergeConflicts": tr.MergingTitle, "staging": tr.StagingTitle, "menu": tr.MenuTitle, "search": tr.SearchTitle, "secondary": tr.SecondaryTitle, "stash": tr.StashTitle, "suggestions": tr.SuggestionsCheatsheetTitle, "extras": tr.ExtrasTitle, "worktrees": tr.WorktreesTitle, } title, ok := contextTitleMap[str] if !ok { panic(fmt.Sprintf("title not found for %s", str)) } return title } func getBindingSections(bindings []*types.Binding, tr *i18n.TranslationSet) []*bindingSection { excludedViews := []string{"stagingSecondary", "patchBuildingSecondary"} bindingsToDisplay := lo.Filter(bindings, func(binding *types.Binding, _ int) bool { if lo.Contains(excludedViews, binding.ViewName) { return false } return (binding.Description != "" || binding.Alternative != "") && binding.Key != nil }) bindingsByHeader := lo.GroupBy(bindingsToDisplay, func(binding *types.Binding) header { return getHeader(binding, tr) }) bindingGroups := maps.MapToSlice( bindingsByHeader, func(header header, hBindings []*types.Binding) headerWithBindings { uniqBindings := lo.UniqBy(hBindings, func(binding *types.Binding) string { return binding.Description + keybindings.LabelFromKey(binding.Key) }) return headerWithBindings{ header: header, bindings: uniqBindings, } }, ) slices.SortFunc(bindingGroups, func(a, b headerWithBindings) int { if a.header.priority != b.header.priority { return cmp.Compare(b.header.priority, a.header.priority) } return strings.Compare(a.header.title, b.header.title) }) return lo.Map(bindingGroups, func(hb headerWithBindings, _ int) *bindingSection { return &bindingSection{ title: hb.header.title, bindings: hb.bindings, } }) } func getHeader(binding *types.Binding, tr *i18n.TranslationSet) header { if binding.Tag == "navigation" { return header{priority: 2, title: localisedTitle(tr, "navigation")} } if binding.ViewName == "" { return header{priority: 3, title: localisedTitle(tr, "global")} } return header{priority: 1, title: localisedTitle(tr, binding.ViewName)} } func formatSections(tr *i18n.TranslationSet, bindingSections []*bindingSection) string { var content strings.Builder content.WriteString(fmt.Sprintf("# Lazygit %s\n", tr.Keybindings)) content.WriteString(fmt.Sprintf("\n%s\n", italicize(tr.KeybindingsLegend))) for _, section := range bindingSections { content.WriteString(formatTitle(section.title)) content.WriteString("| Key | Action | Info |\n") content.WriteString("|-----|--------|-------------|\n") for _, binding := range section.bindings { content.WriteString(formatBinding(binding)) } } return content.String() } func formatTitle(title string) string { return fmt.Sprintf("\n## %s\n\n", title) } func formatBinding(binding *types.Binding) string { action := keybindings.LabelFromKey(binding.Key) description := binding.Description if binding.Alternative != "" { action += fmt.Sprintf(" (%s)", binding.Alternative) } // Replace newlines with <br> tags for proper markdown table formatting tooltip := strings.ReplaceAll(binding.Tooltip, "\n", "<br>") // Escape pipe characters to avoid breaking the table format action = strings.ReplaceAll(action, `|`, `\|`) description = strings.ReplaceAll(description, `|`, `\|`) tooltip = strings.ReplaceAll(tooltip, `|`, `\|`) // Use backticks for keyboard keys. Two backticks are needed with an inner space // to escape a key that is itself a backtick. return fmt.Sprintf("| `` %s `` | %s | %s |\n", action, description, tooltip) } func italicize(str string) string { return fmt.Sprintf("_%s_", str) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/updates/updates.go
pkg/updates/updates.go
package updates import ( "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "runtime" "strings" "time" "github.com/go-errors/errors" "github.com/kardianos/osext" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/utils" ) // Updater checks for updates and does updates type Updater struct { *common.Common Config config.AppConfigurer OSCommand *oscommands.OSCommand } // Updaterer implements the check and update methods type Updaterer interface { CheckForNewUpdate() Update() } // NewUpdater creates a new updater func NewUpdater(cmn *common.Common, config config.AppConfigurer, osCommand *oscommands.OSCommand) (*Updater, error) { return &Updater{ Common: cmn, Config: config, OSCommand: osCommand, }, nil } func (u *Updater) getLatestVersionNumber() (string, error) { req, err := http.NewRequest("GET", constants.Links.RepoUrl+"/releases/latest", nil) if err != nil { return "", err } req.Header.Set("Accept", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) data := struct { TagName string `json:"tag_name"` }{} if err := dec.Decode(&data); err != nil { return "", err } return data.TagName, nil } // RecordLastUpdateCheck records last time an update check was performed func (u *Updater) RecordLastUpdateCheck() error { u.Config.GetAppState().LastUpdateCheck = time.Now().Unix() return u.Config.SaveAppState() } // expecting version to be of the form `v12.34.56` func (u *Updater) majorVersionDiffers(oldVersion, newVersion string) bool { if oldVersion == "unversioned" { return false } oldVersion = strings.TrimPrefix(oldVersion, "v") newVersion = strings.TrimPrefix(newVersion, "v") return strings.Split(oldVersion, ".")[0] != strings.Split(newVersion, ".")[0] } func (u *Updater) currentVersion() string { versionNumber := u.Config.GetVersion() if versionNumber == "unversioned" { return versionNumber } return fmt.Sprintf("v%s", u.Config.GetVersion()) } func (u *Updater) checkForNewUpdate() (string, error) { u.Log.Info("Checking for an updated version") currentVersion := u.currentVersion() if err := u.RecordLastUpdateCheck(); err != nil { return "", err } newVersion, err := u.getLatestVersionNumber() if err != nil { return "", err } u.Log.Info("Current version is " + currentVersion) u.Log.Info("New version is " + newVersion) if newVersion == currentVersion { return "", errors.New(u.Tr.OnLatestVersionErr) } if u.majorVersionDiffers(currentVersion, newVersion) { errMessage := utils.ResolvePlaceholderString( u.Tr.MajorVersionErr, map[string]string{ "newVersion": newVersion, "currentVersion": currentVersion, }, ) return "", errors.New(errMessage) } rawUrl := u.getBinaryUrl(newVersion) u.Log.Info("Checking for resource at url " + rawUrl) if !u.verifyResourceFound(rawUrl) { errMessage := utils.ResolvePlaceholderString( u.Tr.CouldNotFindBinaryErr, map[string]string{ "url": rawUrl, }, ) return "", errors.New(errMessage) } u.Log.Info("Verified resource is available, ready to update") return newVersion, nil } // CheckForNewUpdate checks if there is an available update func (u *Updater) CheckForNewUpdate(onFinish func(string, error) error, userRequested bool) { if !userRequested && u.skipUpdateCheck() { return } newVersion, err := u.checkForNewUpdate() if err = onFinish(newVersion, err); err != nil { u.Log.Error(err) } } func (u *Updater) skipUpdateCheck() bool { // will remove the check for windows after adding a manifest file asking for // the required permissions if runtime.GOOS == "windows" { u.Log.Info("Updating is currently not supported for windows until we can fix permission issues") return true } if u.Config.GetVersion() == "unversioned" { u.Log.Info("Current version is not built from an official release so we won't check for an update") return true } if u.Config.GetBuildSource() != "buildBinary" { u.Log.Info("Binary is not built with the buildBinary flag so we won't check for an update") return true } userConfig := u.UserConfig() if userConfig.Update.Method == "never" { u.Log.Info("Update method is set to never so we won't check for an update") return true } currentTimestamp := time.Now().Unix() lastUpdateCheck := u.Config.GetAppState().LastUpdateCheck days := userConfig.Update.Days if (currentTimestamp-lastUpdateCheck)/(60*60*24) < days { u.Log.Info("Last update was too recent so we won't check for an update") return true } return false } func (u *Updater) mappedOs(os string) string { osMap := map[string]string{ "darwin": "Darwin", "linux": "Linux", "windows": "Windows", } result, found := osMap[os] if found { return result } return os } func (u *Updater) mappedArch(arch string) string { archMap := map[string]string{ "386": "32-bit", "amd64": "x86_64", } result, found := archMap[arch] if found { return result } return arch } func (u *Updater) zipExtension() string { if runtime.GOOS == "windows" { return "zip" } return "tar.gz" } // example: https://github.com/jesseduffield/lazygit/releases/download/v0.1.73/lazygit_0.1.73_Darwin_x86_64.tar.gz func (u *Updater) getBinaryUrl(newVersion string) string { url := fmt.Sprintf( "%s/releases/download/%s/lazygit_%s_%s_%s.%s", constants.Links.RepoUrl, newVersion, newVersion[1:], u.mappedOs(runtime.GOOS), u.mappedArch(runtime.GOARCH), u.zipExtension(), ) u.Log.Info("Url for latest release is " + url) return url } // Update downloads the latest binary and replaces the current binary with it func (u *Updater) Update(newVersion string) error { return u.update(newVersion) } func (u *Updater) update(newVersion string) error { rawUrl := u.getBinaryUrl(newVersion) u.Log.Info("Updating with url " + rawUrl) return u.downloadAndInstall(rawUrl) } func (u *Updater) downloadAndInstall(rawUrl string) error { configDir := u.Config.GetUserConfigDir() u.Log.Info("Download directory is " + configDir) zipPath := filepath.Join(configDir, "temp_lazygit."+u.zipExtension()) u.Log.Info("Temp path to tarball/zip file is " + zipPath) // remove existing zip file if err := os.RemoveAll(zipPath); err != nil && !os.IsNotExist(err) { return err } // Create the zip file out, err := os.Create(zipPath) if err != nil { return err } defer out.Close() // Get the data resp, err := http.Get(rawUrl) if err != nil { return err } defer resp.Body.Close() // Check server response if resp.StatusCode != http.StatusOK { return fmt.Errorf("error while trying to download latest lazygit: %s", resp.Status) } // Write the body to file _, err = io.Copy(out, resp.Body) if err != nil { return err } u.Log.Info("untarring tarball/unzipping zip file") err = u.OSCommand.Cmd.New([]string{"tar", "-zxf", zipPath, "lazygit"}).Run() if err != nil { return err } // the `tar` terminal cannot store things in a new location without permission // so it creates it in the current directory. As such our path is fairly simple. // You won't see it because it's gitignored. tempLazygitFilePath := "lazygit" u.Log.Infof("Path to temp binary is %s", tempLazygitFilePath) // get the path of the current binary binaryPath, err := osext.Executable() if err != nil { return err } u.Log.Info("Binary path is " + binaryPath) // Verify the main file exists if _, err := os.Stat(zipPath); err != nil { return err } // swap out the old binary for the new one err = os.Rename(tempLazygitFilePath, binaryPath) if err != nil { return err } u.Log.Info("Update complete!") return nil } func (u *Updater) verifyResourceFound(rawUrl string) bool { resp, err := http.Head(rawUrl) if err != nil { return false } defer resp.Body.Close() u.Log.Info("Received status code ", resp.StatusCode) // OK (200) indicates that the resource is present. return resp.StatusCode == http.StatusOK }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/constants/links.go
pkg/constants/links.go
package constants type Docs struct { CustomPagers string CustomCommands string CustomKeybindings string Keybindings string Undoing string Config string Tutorial string CustomPatchDemo string } var Links = struct { Docs Docs Issues string Donate string Discussions string RepoUrl string Releases string }{ RepoUrl: "https://github.com/jesseduffield/lazygit", Issues: "https://github.com/jesseduffield/lazygit/issues", Donate: "https://github.com/sponsors/jesseduffield", Discussions: "https://github.com/jesseduffield/lazygit/discussions", Releases: "https://github.com/jesseduffield/lazygit/releases", Docs: Docs{ CustomPagers: "https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md", CustomKeybindings: "https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Custom_Keybindings.md", CustomCommands: "https://github.com/jesseduffield/lazygit/wiki/Custom-Commands-Compendium", Keybindings: "https://github.com/jesseduffield/lazygit/blob/%s/docs/keybindings", Undoing: "https://github.com/jesseduffield/lazygit/blob/master/docs/Undoing.md", Config: "https://github.com/jesseduffield/lazygit/blob/%s/docs/Config.md", Tutorial: "https://youtu.be/VDXvbHZYeKY", CustomPatchDemo: "https://github.com/jesseduffield/lazygit#rebase-magic-custom-patches", }, }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/gui_driver.go
pkg/gui/gui_driver.go
package gui import ( "fmt" "os" "strings" "time" "github.com/gdamore/tcell/v2" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types" ) // this gives our integration test a way of interacting with the gui for sending keypresses // and reading state. type GuiDriver struct { gui *Gui isIdleChan chan struct{} toastChan chan string headless bool } var _ integrationTypes.GuiDriver = &GuiDriver{} func (self *GuiDriver) PressKey(keyStr string) { self.CheckAllToastsAcknowledged() key := keybindings.GetKey(keyStr) var r rune var tcellKey tcell.Key switch v := key.(type) { case rune: r = v tcellKey = tcell.KeyRune case gocui.Key: tcellKey = tcell.Key(v) } self.gui.g.ReplayedEvents.Keys <- gocui.NewTcellKeyEventWrapper( tcell.NewEventKey(tcellKey, r, tcell.ModNone), 0, ) self.waitTillIdle() } func (self *GuiDriver) Click(x, y int) { self.CheckAllToastsAcknowledged() self.gui.g.ReplayedEvents.MouseEvents <- gocui.NewTcellMouseEventWrapper( tcell.NewEventMouse(x, y, tcell.ButtonPrimary, 0), 0, ) self.waitTillIdle() self.gui.g.ReplayedEvents.MouseEvents <- gocui.NewTcellMouseEventWrapper( tcell.NewEventMouse(x, y, tcell.ButtonNone, 0), 0, ) self.waitTillIdle() } // wait until lazygit is idle (i.e. all processing is done) before continuing func (self *GuiDriver) waitTillIdle() { <-self.isIdleChan } func (self *GuiDriver) CheckAllToastsAcknowledged() { if t := self.NextToast(); t != nil { self.Fail("Toast not acknowledged: " + *t) } } func (self *GuiDriver) Keys() config.KeybindingConfig { return self.gui.Config.GetUserConfig().Keybinding } func (self *GuiDriver) CurrentContext() types.Context { return self.gui.c.Context().Current() } func (self *GuiDriver) ContextForView(viewName string) types.Context { context, ok := self.gui.helpers.View.ContextForView(viewName) if !ok { return nil } return context } func (self *GuiDriver) Fail(message string) { currentView := self.gui.g.CurrentView() // Check for unacknowledged toast: it may give us a hint as to why the test failed toastMessage := "" if t := self.NextToast(); t != nil { toastMessage = fmt.Sprintf("Unacknowledged toast message: %s\n", *t) } fullMessage := fmt.Sprintf( "%s\nFinal Lazygit state:\n%s\nUpon failure, focused view was '%s'.\n%sLog:\n%s", message, self.gui.g.Snapshot(), currentView.Name(), toastMessage, strings.Join(self.gui.GuiLog, "\n"), ) self.gui.g.Close() // need to give the gui time to close time.Sleep(time.Millisecond * 100) _, err := fmt.Fprintln(os.Stderr, fullMessage) if err != nil { panic("Test failed. Failed writing to stderr") } panic("Test failed") } // logs to the normal place that you log to i.e. viewable with `lazygit --logs` func (self *GuiDriver) Log(message string) { self.gui.c.Log.Warn(message) } // logs in the actual UI (in the commands panel) func (self *GuiDriver) LogUI(message string) { self.gui.c.LogAction(message) } func (self *GuiDriver) CheckedOutRef() *models.Branch { return self.gui.helpers.Refs.GetCheckedOutRef() } func (self *GuiDriver) MainView() *gocui.View { return self.gui.mainView() } func (self *GuiDriver) SecondaryView() *gocui.View { return self.gui.secondaryView() } func (self *GuiDriver) View(viewName string) *gocui.View { view, err := self.gui.g.View(viewName) if err != nil { panic(err) } return view } func (self *GuiDriver) SetCaption(caption string) { self.gui.setCaption(caption) self.waitTillIdle() } func (self *GuiDriver) SetCaptionPrefix(prefix string) { self.gui.setCaptionPrefix(prefix) self.waitTillIdle() } func (self *GuiDriver) NextToast() *string { select { case t := <-self.toastChan: return &t default: return nil } } func (self *GuiDriver) Headless() bool { return self.headless }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/pty.go
pkg/gui/pty.go
//go:build !windows package gui import ( "io" "os" "os/exec" "strings" "github.com/creack/pty" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) desiredPtySize(view *gocui.View) *pty.Winsize { width, height := view.InnerSize() return &pty.Winsize{Cols: uint16(width), Rows: uint16(height)} } func (gui *Gui) onResize() error { gui.Mutexes.PtyMutex.Lock() defer gui.Mutexes.PtyMutex.Unlock() for viewName, ptmx := range gui.viewPtmxMap { // TODO: handle resizing properly: we need to actually clear the main view // and re-read the output from our pty. Or we could just re-run the original // command from scratch view, _ := gui.g.View(viewName) if err := pty.Setsize(ptmx, gui.desiredPtySize(view)); err != nil { return utils.WrapError(err) } } return nil } // Some commands need to output for a terminal to active certain behaviour. // For example, git won't invoke the GIT_PAGER env var unless it thinks it's // talking to a terminal. We typically write cmd outputs straight to a view, // which is just an io.Reader. the pty package lets us wrap a command in a // pseudo-terminal meaning we'll get the behaviour we want from the underlying // command. func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error { width := view.InnerWidth() pager := gui.stateAccessor.GetPagerConfig().GetPagerCommand(width) externalDiffCommand := gui.stateAccessor.GetPagerConfig().GetExternalDiffCommand() useExtDiffGitConfig := gui.stateAccessor.GetPagerConfig().GetUseExternalDiffGitConfig() if pager == "" && externalDiffCommand == "" && !useExtDiffGitConfig { // If we're not using a custom pager nor external diff command, then we don't need to use a pty return gui.newCmdTask(view, cmd, prefix) } // Run the pty after layout so that it gets the correct size gui.afterLayout(func() error { // Need to get the width and the pager again because the layout might have // changed the size of the view width = view.InnerWidth() pager := gui.stateAccessor.GetPagerConfig().GetPagerCommand(width) cmdStr := strings.Join(cmd.Args, " ") // This communicates to pagers that we're in a very simple // terminal that they should not expect to have much capabilities. // Moving the cursor, clearing the screen, or querying for colors are among such "advanced" capabilities. // Context: https://github.com/jesseduffield/lazygit/issues/3419 cmd.Env = removeExistingTermEnvVars(cmd.Env) cmd.Env = append(cmd.Env, "TERM=dumb") cmd.Env = append(cmd.Env, "GIT_PAGER="+pager) manager := gui.getManager(view) var ptmx *os.File start := func() (*exec.Cmd, io.Reader) { var err error ptmx, err = pty.StartWithSize(cmd, gui.desiredPtySize(view)) if err != nil { gui.c.Log.Error(err) } gui.Mutexes.PtyMutex.Lock() gui.viewPtmxMap[view.Name()] = ptmx gui.Mutexes.PtyMutex.Unlock() return cmd, ptmx } onClose := func() { gui.Mutexes.PtyMutex.Lock() ptmx.Close() delete(gui.viewPtmxMap, view.Name()) gui.Mutexes.PtyMutex.Unlock() } linesToRead := gui.linesToReadFromCmdTask(view) return manager.NewTask(manager.NewCmdTask(start, prefix, linesToRead, onClose), cmdStr) }) return nil } func removeExistingTermEnvVars(env []string) []string { return lo.Filter(env, func(envVar string, _ int) bool { return !isTermEnvVar(envVar) }) } // Terminals set a variety of different environment variables // to identify themselves to processes. This list should catch the most common among them. func isTermEnvVar(envVar string) bool { return strings.HasPrefix(envVar, "TERM=") || strings.HasPrefix(envVar, "TERM_PROGRAM=") || strings.HasPrefix(envVar, "TERM_PROGRAM_VERSION=") || strings.HasPrefix(envVar, "TERMINAL_EMULATOR=") || strings.HasPrefix(envVar, "TERMINAL_NAME=") || strings.HasPrefix(envVar, "TERMINAL_VERSION_") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/controllers.go
pkg/gui/controllers.go
package gui import ( "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/controllers" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/services/custom_commands" "github.com/jesseduffield/lazygit/pkg/gui/status" "github.com/jesseduffield/lazygit/pkg/gui/types" ) func (gui *Gui) Helpers() *helpers.Helpers { return gui.helpers } // Note, the order of controllers determines the order in which keybindings appear // in the keybinding menu: the earlier that the controller is attached to a context, // the lower in the list the keybindings will appear. func (gui *Gui) resetHelpersAndControllers() { for _, context := range gui.Contexts().Flatten() { context.ClearAllAttachedControllerFunctions() } helperCommon := gui.c recordDirectoryHelper := helpers.NewRecordDirectoryHelper(helperCommon) reposHelper := helpers.NewRecentReposHelper(helperCommon, recordDirectoryHelper, gui.onSwitchToNewRepo) rebaseHelper := helpers.NewMergeAndRebaseHelper(helperCommon) refsHelper := helpers.NewRefsHelper(helperCommon, rebaseHelper) suggestionsHelper := helpers.NewSuggestionsHelper(helperCommon) worktreeHelper := helpers.NewWorktreeHelper(helperCommon, reposHelper, refsHelper, suggestionsHelper) setCommitSummary := gui.getCommitMessageSetTextareaTextFn(func() *gocui.View { return gui.Views.CommitMessage }) setCommitDescription := gui.getCommitMessageSetTextareaTextFn(func() *gocui.View { return gui.Views.CommitDescription }) getCommitSummary := func() string { return strings.TrimSpace(gui.Views.CommitMessage.TextArea.GetContent()) } getCommitDescription := func() string { return strings.TrimSpace(gui.Views.CommitDescription.TextArea.GetContent()) } getUnwrappedCommitDescription := func() string { return strings.TrimSpace(gui.Views.CommitDescription.TextArea.GetUnwrappedContent()) } commitsHelper := helpers.NewCommitsHelper(helperCommon, getCommitSummary, setCommitSummary, getCommitDescription, getUnwrappedCommitDescription, setCommitDescription, ) gpgHelper := helpers.NewGpgHelper(helperCommon) viewHelper := helpers.NewViewHelper(helperCommon, gui.State.Contexts) patchBuildingHelper := helpers.NewPatchBuildingHelper(helperCommon) stagingHelper := helpers.NewStagingHelper(helperCommon) mergeConflictsHelper := helpers.NewMergeConflictsHelper(helperCommon) searchHelper := helpers.NewSearchHelper(helperCommon) refreshHelper := helpers.NewRefreshHelper( helperCommon, refsHelper, rebaseHelper, patchBuildingHelper, stagingHelper, mergeConflictsHelper, worktreeHelper, searchHelper, ) diffHelper := helpers.NewDiffHelper(helperCommon) cherryPickHelper := helpers.NewCherryPickHelper( helperCommon, rebaseHelper, ) bisectHelper := helpers.NewBisectHelper(helperCommon) windowHelper := helpers.NewWindowHelper(helperCommon, viewHelper) modeHelper := helpers.NewModeHelper( helperCommon, diffHelper, patchBuildingHelper, cherryPickHelper, rebaseHelper, bisectHelper, ) appStatusHelper := helpers.NewAppStatusHelper( helperCommon, func() *status.StatusManager { return gui.statusManager }, modeHelper, ) gui.helpers = &helpers.Helpers{ Refs: refsHelper, Host: helpers.NewHostHelper(helperCommon), PatchBuilding: patchBuildingHelper, Staging: stagingHelper, Bisect: bisectHelper, Suggestions: suggestionsHelper, Files: helpers.NewFilesHelper(helperCommon), WorkingTree: helpers.NewWorkingTreeHelper(helperCommon, refsHelper, commitsHelper, gpgHelper, rebaseHelper), Tags: helpers.NewTagsHelper(helperCommon, commitsHelper, gpgHelper), BranchesHelper: helpers.NewBranchesHelper(helperCommon, worktreeHelper), GPG: helpers.NewGpgHelper(helperCommon), MergeAndRebase: rebaseHelper, MergeConflicts: mergeConflictsHelper, CherryPick: cherryPickHelper, Upstream: helpers.NewUpstreamHelper(helperCommon, suggestionsHelper.GetRemoteBranchesSuggestionsFunc), AmendHelper: helpers.NewAmendHelper(helperCommon, gpgHelper), FixupHelper: helpers.NewFixupHelper(helperCommon), Commits: commitsHelper, SuspendResume: helpers.NewSuspendResumeHelper(helperCommon), Snake: helpers.NewSnakeHelper(helperCommon), Diff: diffHelper, Repos: reposHelper, RecordDirectory: recordDirectoryHelper, Update: helpers.NewUpdateHelper(helperCommon, gui.Updater), Window: windowHelper, View: viewHelper, Refresh: refreshHelper, Confirmation: helpers.NewConfirmationHelper(helperCommon), Mode: modeHelper, AppStatus: appStatusHelper, InlineStatus: helpers.NewInlineStatusHelper(helperCommon, windowHelper), WindowArrangement: helpers.NewWindowArrangementHelper( gui.c, windowHelper, modeHelper, appStatusHelper, ), Search: searchHelper, Worktree: worktreeHelper, SubCommits: helpers.NewSubCommitsHelper(helperCommon, refreshHelper), } gui.CustomCommandsClient = custom_commands.NewClient( helperCommon, gui.helpers, ) common := controllers.NewControllerCommon(helperCommon, gui) syncController := controllers.NewSyncController( common, ) submodulesController := controllers.NewSubmodulesController(common) bisectController := controllers.NewBisectController(common) commitMessageController := controllers.NewCommitMessageController( common, ) commitDescriptionController := controllers.NewCommitDescriptionController( common, ) remoteBranchesController := controllers.NewRemoteBranchesController(common) menuController := controllers.NewMenuController(common) localCommitsController := controllers.NewLocalCommitsController(common, syncController.HandlePull) tagsController := controllers.NewTagsController(common) filesController := controllers.NewFilesController( common, ) mergeConflictsController := controllers.NewMergeConflictsController(common) remotesController := controllers.NewRemotesController( common, func(branches []*models.RemoteBranch) { gui.State.Model.RemoteBranches = branches }, ) worktreesController := controllers.NewWorktreesController(common) undoController := controllers.NewUndoController(common) globalController := controllers.NewGlobalController(common) contextLinesController := controllers.NewContextLinesController(common) renameSimilarityThresholdController := controllers.NewRenameSimilarityThresholdController(common) verticalScrollControllerFactory := controllers.NewVerticalScrollControllerFactory(common) viewSelectionControllerFactory := controllers.NewViewSelectionControllerFactory(common) branchesController := controllers.NewBranchesController(common) gitFlowController := controllers.NewGitFlowController(common) stashController := controllers.NewStashController(common) commitFilesController := controllers.NewCommitFilesController(common) patchExplorerControllerFactory := controllers.NewPatchExplorerControllerFactory(common) stagingController := controllers.NewStagingController(common, gui.State.Contexts.Staging, gui.State.Contexts.StagingSecondary, false) stagingSecondaryController := controllers.NewStagingController(common, gui.State.Contexts.StagingSecondary, gui.State.Contexts.Staging, true) mainViewController := controllers.NewMainViewController(common, gui.State.Contexts.Normal, gui.State.Contexts.NormalSecondary) secondaryViewController := controllers.NewMainViewController(common, gui.State.Contexts.NormalSecondary, gui.State.Contexts.Normal) patchBuildingController := controllers.NewPatchBuildingController(common) snakeController := controllers.NewSnakeController(common) reflogCommitsController := controllers.NewReflogCommitsController(common) subCommitsController := controllers.NewSubCommitsController(common) statusController := controllers.NewStatusController(common) commandLogController := controllers.NewCommandLogController(common) confirmationController := controllers.NewConfirmationController(common) promptController := controllers.NewPromptController(common) suggestionsController := controllers.NewSuggestionsController(common) jumpToSideWindowController := controllers.NewJumpToSideWindowController(common, gui.handleNextTab) sideWindowControllerFactory := controllers.NewSideWindowControllerFactory(common) filterControllerFactory := controllers.NewFilterControllerFactory(common) for _, context := range gui.c.Context().AllFilterable() { controllers.AttachControllers(context, filterControllerFactory.Create(context)) } searchControllerFactory := controllers.NewSearchControllerFactory(common) for _, context := range gui.c.Context().AllSearchable() { controllers.AttachControllers(context, searchControllerFactory.Create(context)) } for _, context := range []controllers.CanViewWorktreeOptions{ gui.State.Contexts.LocalCommits, gui.State.Contexts.ReflogCommits, gui.State.Contexts.SubCommits, gui.State.Contexts.Stash, gui.State.Contexts.Branches, gui.State.Contexts.RemoteBranches, gui.State.Contexts.Tags, } { controllers.AttachControllers(context, controllers.NewWorktreeOptionsController(common, context)) } // allow for navigating between side window contexts for _, context := range []types.Context{ gui.State.Contexts.Status, gui.State.Contexts.Remotes, gui.State.Contexts.Worktrees, gui.State.Contexts.Tags, gui.State.Contexts.Branches, gui.State.Contexts.RemoteBranches, gui.State.Contexts.Files, gui.State.Contexts.Submodules, gui.State.Contexts.ReflogCommits, gui.State.Contexts.LocalCommits, gui.State.Contexts.CommitFiles, gui.State.Contexts.SubCommits, gui.State.Contexts.Stash, } { controllers.AttachControllers(context, sideWindowControllerFactory.Create(context)) } for _, context := range []controllers.CanSwitchToSubCommits{ gui.State.Contexts.Branches, gui.State.Contexts.RemoteBranches, gui.State.Contexts.Tags, gui.State.Contexts.ReflogCommits, } { controllers.AttachControllers(context, controllers.NewSwitchToSubCommitsController( common, context, )) } for _, context := range []controllers.CanSwitchToDiffFiles{ gui.State.Contexts.LocalCommits, gui.State.Contexts.SubCommits, gui.State.Contexts.Stash, } { controllers.AttachControllers(context, controllers.NewSwitchToDiffFilesController( common, context, )) } for _, context := range []types.Context{ gui.State.Contexts.Status, gui.State.Contexts.Files, gui.State.Contexts.Branches, gui.State.Contexts.RemoteBranches, gui.State.Contexts.Tags, gui.State.Contexts.LocalCommits, gui.State.Contexts.ReflogCommits, gui.State.Contexts.SubCommits, gui.State.Contexts.CommitFiles, gui.State.Contexts.Stash, } { controllers.AttachControllers(context, controllers.NewSwitchToFocusedMainViewController( common, context, )) } for _, context := range []controllers.ContainsCommits{ gui.State.Contexts.LocalCommits, gui.State.Contexts.ReflogCommits, gui.State.Contexts.SubCommits, } { controllers.AttachControllers(context, controllers.NewBasicCommitsController(common, context)) } controllers.AttachControllers(gui.State.Contexts.ReflogCommits, reflogCommitsController, ) controllers.AttachControllers(gui.State.Contexts.SubCommits, subCommitsController, ) // TODO: add scroll controllers for main panels (need to bring some more functionality across for that e.g. reading more from the currently displayed git command) controllers.AttachControllers(gui.State.Contexts.Staging, stagingController, patchExplorerControllerFactory.Create(gui.State.Contexts.Staging), verticalScrollControllerFactory.Create(gui.State.Contexts.Staging), ) controllers.AttachControllers(gui.State.Contexts.StagingSecondary, stagingSecondaryController, patchExplorerControllerFactory.Create(gui.State.Contexts.StagingSecondary), verticalScrollControllerFactory.Create(gui.State.Contexts.StagingSecondary), ) controllers.AttachControllers(gui.State.Contexts.CustomPatchBuilder, patchBuildingController, patchExplorerControllerFactory.Create(gui.State.Contexts.CustomPatchBuilder), verticalScrollControllerFactory.Create(gui.State.Contexts.CustomPatchBuilder), ) controllers.AttachControllers(gui.State.Contexts.CustomPatchBuilderSecondary, verticalScrollControllerFactory.Create(gui.State.Contexts.CustomPatchBuilderSecondary), ) controllers.AttachControllers(gui.State.Contexts.MergeConflicts, mergeConflictsController, ) controllers.AttachControllers(gui.State.Contexts.Normal, mainViewController, verticalScrollControllerFactory.Create(gui.State.Contexts.Normal), viewSelectionControllerFactory.Create(gui.State.Contexts.Normal), ) controllers.AttachControllers(gui.State.Contexts.NormalSecondary, secondaryViewController, verticalScrollControllerFactory.Create(gui.State.Contexts.NormalSecondary), viewSelectionControllerFactory.Create(gui.State.Contexts.NormalSecondary), ) controllers.AttachControllers(gui.State.Contexts.Files, filesController, ) controllers.AttachControllers(gui.State.Contexts.Tags, tagsController, ) controllers.AttachControllers(gui.State.Contexts.Submodules, submodulesController, ) controllers.AttachControllers(gui.State.Contexts.Branches, branchesController, gitFlowController, ) controllers.AttachControllers(gui.State.Contexts.LocalCommits, localCommitsController, bisectController, ) controllers.AttachControllers(gui.State.Contexts.CommitFiles, commitFilesController, ) controllers.AttachControllers(gui.State.Contexts.Remotes, remotesController, ) controllers.AttachControllers(gui.State.Contexts.Worktrees, worktreesController, ) controllers.AttachControllers(gui.State.Contexts.Stash, stashController, ) controllers.AttachControllers(gui.State.Contexts.Menu, menuController, ) controllers.AttachControllers(gui.State.Contexts.CommitMessage, commitMessageController, ) controllers.AttachControllers(gui.State.Contexts.CommitDescription, commitDescriptionController, verticalScrollControllerFactory.Create(gui.State.Contexts.CommitDescription), ) controllers.AttachControllers(gui.State.Contexts.RemoteBranches, remoteBranchesController, ) controllers.AttachControllers(gui.State.Contexts.Status, statusController, ) controllers.AttachControllers(gui.State.Contexts.CommandLog, commandLogController, ) controllers.AttachControllers(gui.State.Contexts.Confirmation, confirmationController, ) controllers.AttachControllers(gui.State.Contexts.Prompt, promptController, ) controllers.AttachControllers(gui.State.Contexts.Suggestions, suggestionsController, ) controllers.AttachControllers(gui.State.Contexts.Search, controllers.NewSearchPromptController(common), ) controllers.AttachControllers(gui.State.Contexts.Global, undoController, globalController, contextLinesController, renameSimilarityThresholdController, jumpToSideWindowController, syncController, ) controllers.AttachControllers(gui.State.Contexts.Snake, snakeController, ) // this must come last so that we've got our click handlers defined against the context listControllerFactory := controllers.NewListControllerFactory(common) for _, context := range gui.c.Context().AllList() { controllers.AttachControllers(context, listControllerFactory.Create(context)) } } func (gui *Gui) getCommitMessageSetTextareaTextFn(getView func() *gocui.View) func(string) { return func(text string) { // using a getView function so that we don't need to worry about when the view is created view := getView() view.ClearTextArea() view.TextArea.TypeString(text) view.RenderTextArea() } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/test_mode.go
pkg/gui/test_mode.go
package gui import ( "log" "os" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/popup" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/integration/components" "github.com/jesseduffield/lazygit/pkg/utils" ) type IntegrationTest interface { Run(*GuiDriver) } func (gui *Gui) handleTestMode() { test := gui.integrationTest if os.Getenv(components.SANDBOX_ENV_VAR) == "true" { return } if test != nil { isIdleChan := make(chan struct{}) gui.c.GocuiGui().AddIdleListener(isIdleChan) waitUntilIdle := func() { <-isIdleChan } go func() { waitUntilIdle() toastChan := make(chan string, 100) gui.PopupHandler.(*popup.PopupHandler).SetToastFunc( func(message string, kind types.ToastKind) { toastChan <- message }) test.Run(&GuiDriver{gui: gui, isIdleChan: isIdleChan, toastChan: toastChan, headless: Headless()}) gui.g.Update(func(*gocui.Gui) error { return gocui.ErrQuit }) waitUntilIdle() time.Sleep(time.Second * 1) log.Fatal("gocui should have already exited") }() if os.Getenv(components.WAIT_FOR_DEBUGGER_ENV_VAR) == "" { go utils.Safe(func() { time.Sleep(time.Second * 40) log.Fatal("40 seconds is up, lazygit recording took too long to complete") }) } } } func Headless() bool { return os.Getenv("LAZYGIT_HEADLESS") != "" }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/options_map.go
pkg/gui/options_map.go
package gui import ( "fmt" "strings" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) type OptionsMapMgr struct { c *helpers.HelperCommon } func (gui *Gui) renderContextOptionsMap() { // In demos, we render our own content to this view if gui.integrationTest != nil && gui.integrationTest.IsDemo() { return } mgr := OptionsMapMgr{c: gui.c} mgr.renderContextOptionsMap() } // Render the options available for the current context at the bottom of the screen // STYLE GUIDE: we use the default options fg color for most keybindings. We can // only use a different color if we're in a specific mode where the user is likely // to want to press that key. For example, when in cherry-picking mode, we // want to prominently show the keybinding for pasting commits. func (self *OptionsMapMgr) renderContextOptionsMap() { currentContext := self.c.Context().Current() currentContextBindings := currentContext.GetKeybindings(self.c.KeybindingsOpts()) globalBindings := self.c.Contexts().Global.GetKeybindings(self.c.KeybindingsOpts()) currentContextKeys := set.NewFromSlice( lo.Map(currentContextBindings, func(binding *types.Binding, _ int) types.Key { return binding.Key })) allBindings := append(currentContextBindings, lo.Filter(globalBindings, func(b *types.Binding, _ int) bool { return !currentContextKeys.Includes(b.Key) })...) bindingsToDisplay := lo.Filter(allBindings, func(binding *types.Binding, _ int) bool { return binding.DisplayOnScreen && !binding.IsDisabled() }) optionsMap := lo.Map(bindingsToDisplay, func(binding *types.Binding, _ int) bindingInfo { displayStyle := theme.OptionsFgColor if binding.DisplayStyle != nil { displayStyle = *binding.DisplayStyle } return bindingInfo{ key: keybindings.LabelFromKey(binding.Key), description: binding.GetShortDescription(), style: displayStyle, } }) // Mode-specific local keybindings if currentContext.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY { if self.c.Modes().CherryPicking.Active() { optionsMap = utils.Prepend(optionsMap, bindingInfo{ key: keybindings.Label(self.c.KeybindingsOpts().Config.Commits.PasteCommits), description: self.c.Tr.PasteCommits, style: style.FgCyan, }) } if self.c.Model().BisectInfo.Started() { optionsMap = utils.Prepend(optionsMap, bindingInfo{ key: keybindings.Label(self.c.KeybindingsOpts().Config.Commits.ViewBisectOptions), description: self.c.Tr.ViewBisectOptions, style: style.FgGreen, }) } } // Mode-specific global keybindings if state := self.c.Model().WorkingTreeStateAtLastCommitRefresh; state.Any() { optionsMap = utils.Prepend(optionsMap, bindingInfo{ key: keybindings.Label(self.c.KeybindingsOpts().Config.Universal.CreateRebaseOptionsMenu), description: state.OptionsMapTitle(self.c.Tr), style: style.FgYellow, }) } if self.c.Git().Patch.PatchBuilder.Active() { optionsMap = utils.Prepend(optionsMap, bindingInfo{ key: keybindings.Label(self.c.KeybindingsOpts().Config.Universal.CreatePatchOptionsMenu), description: self.c.Tr.ViewPatchOptions, style: style.FgYellow, }) } self.renderOptions(self.formatBindingInfos(optionsMap)) } func (self *OptionsMapMgr) formatBindingInfos(bindingInfos []bindingInfo) string { width := self.c.Views().Options.InnerWidth() - 2 // -2 for some padding var builder strings.Builder ellipsis := "…" separator := " | " length := 0 for i, info := range bindingInfos { plainText := fmt.Sprintf("%s: %s", info.description, info.key) // Check if adding the next formatted string exceeds the available width textLen := utils.StringWidth(plainText) if i > 0 && length+len(separator)+textLen > width { builder.WriteString(theme.OptionsFgColor.Sprint(separator + ellipsis)) break } formatted := info.style.Sprintf(plainText) if i > 0 { builder.WriteString(theme.OptionsFgColor.Sprint(separator)) length += len(separator) } builder.WriteString(formatted) length += textLen } return builder.String() } func (self *OptionsMapMgr) renderOptions(options string) { self.c.SetViewContent(self.c.Views().Options, options) } type bindingInfo struct { key string description string style style.TextStyle }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/information_panel.go
pkg/gui/information_panel.go
package gui import ( "fmt" "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/utils" ) func (gui *Gui) informationStr() string { if activeMode, ok := gui.helpers.Mode.GetActiveMode(); ok { return activeMode.InfoLabel() } if gui.g.Mouse { donate := style.FgMagenta.Sprint(style.PrintHyperlink(gui.c.Tr.Donate, constants.Links.Donate)) askQuestion := style.FgYellow.Sprint(style.PrintHyperlink(gui.c.Tr.AskQuestion, constants.Links.Discussions)) return fmt.Sprintf("%s %s %s", donate, askQuestion, gui.Config.GetVersion()) } return gui.Config.GetVersion() } func (gui *Gui) handleInfoClick() error { if !gui.g.Mouse { return nil } view := gui.Views.Information cx, _ := view.Cursor() width := view.Width() if activeMode, ok := gui.helpers.Mode.GetActiveMode(); ok { if width-cx > utils.StringWidth(gui.c.Tr.ResetInParentheses) { return nil } return activeMode.Reset() } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/keybindings.go
pkg/gui/keybindings.go
package gui import ( "errors" "log" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" ) func (gui *Gui) noPopupPanel(f func() error) func() error { return func() error { if gui.helpers.Confirmation.IsPopupPanelFocused() { return nil } return f() } } func (gui *Gui) outsideFilterMode(f func() error) func() error { return func() error { if !gui.validateNotInFilterMode() { return nil } return f() } } func (gui *Gui) validateNotInFilterMode() bool { if gui.State.Modes.Filtering.Active() { gui.c.Confirm(types.ConfirmOpts{ Title: gui.c.Tr.MustExitFilterModeTitle, Prompt: gui.c.Tr.MustExitFilterModePrompt, HandleConfirm: gui.helpers.Mode.ExitFilterMode, }) return false } return true } // only to be called from the cheatsheet generate script. This mutates the Gui struct. func (gui *Gui) GetCheatsheetKeybindings() []*types.Binding { gui.g = &gocui.Gui{} if err := gui.createAllViews(); err != nil { panic(err) } // need to instantiate views gui.helpers = helpers.NewStubHelpers() gui.State = &GuiRepoState{} gui.State.Contexts = gui.contextTree() gui.State.ContextMgr = NewContextMgr(gui, gui.State.Contexts) gui.resetHelpersAndControllers() bindings, _ := gui.GetInitialKeybindings() return bindings } func (gui *Gui) keybindingOpts() types.KeybindingsOpts { config := gui.c.UserConfig().Keybinding guards := types.KeybindingGuards{ OutsideFilterMode: gui.outsideFilterMode, NoPopupPanel: gui.noPopupPanel, } return types.KeybindingsOpts{ GetKey: keybindings.GetKey, Config: config, Guards: guards, } } func (gui *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBinding) { opts := gui.c.KeybindingsOpts() bindings := []*types.Binding{ { ViewName: "", Key: opts.GetKey(opts.Config.Universal.OpenRecentRepos), Handler: opts.Guards.NoPopupPanel(gui.helpers.Repos.CreateRecentReposMenu), Description: gui.c.Tr.SwitchRepo, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollUpMain), Handler: gui.scrollUpMain, Alternative: "fn+up/shift+k", Description: gui.c.Tr.ScrollUpMainWindow, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollDownMain), Handler: gui.scrollDownMain, Alternative: "fn+down/shift+j", Description: gui.c.Tr.ScrollDownMainWindow, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollUpMainAlt1), Modifier: gocui.ModNone, Handler: gui.scrollUpMain, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollDownMainAlt1), Modifier: gocui.ModNone, Handler: gui.scrollDownMain, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollUpMainAlt2), Modifier: gocui.ModNone, Handler: gui.scrollUpMain, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ScrollDownMainAlt2), Modifier: gocui.ModNone, Handler: gui.scrollDownMain, }, { ViewName: "files", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyPathToClipboard, }, { ViewName: "localBranches", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyBranchNameToClipboard, }, { ViewName: "remoteBranches", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyBranchNameToClipboard, }, { ViewName: "tags", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyTagToClipboard, }, { ViewName: "commits", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemCommitHashToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyCommitHashToClipboard, }, { ViewName: "commits", Key: opts.GetKey(opts.Config.Commits.ResetCherryPick), Handler: gui.helpers.CherryPick.Reset, Description: gui.c.Tr.ResetCherryPick, }, { ViewName: "reflogCommits", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyCommitHashToClipboard, }, { ViewName: "subCommits", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemCommitHashToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyCommitHashToClipboard, }, { ViewName: "information", Key: gocui.MouseLeft, Modifier: gocui.ModNone, Handler: gui.handleInfoClick, }, { ViewName: "commitFiles", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopyPathToClipboard, }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.ExtrasMenu), Handler: opts.Guards.NoPopupPanel(gui.handleCreateExtrasMenuPanel), Description: gui.c.Tr.OpenCommandLogMenu, Tooltip: gui.c.Tr.OpenCommandLogMenuTooltip, OpensMenu: true, }, { ViewName: "main", Key: gocui.MouseWheelDown, Handler: gui.scrollDownMain, Description: gui.c.Tr.ScrollDown, Alternative: "fn+up", }, { ViewName: "main", Key: gocui.MouseWheelUp, Handler: gui.scrollUpMain, Description: gui.c.Tr.ScrollUp, Alternative: "fn+down", }, { ViewName: "secondary", Key: gocui.MouseWheelDown, Modifier: gocui.ModNone, Handler: gui.scrollDownSecondary, }, { ViewName: "secondary", Key: gocui.MouseWheelUp, Modifier: gocui.ModNone, Handler: gui.scrollUpSecondary, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.PrevItem), Modifier: gocui.ModNone, Handler: gui.scrollUpConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.NextItem), Modifier: gocui.ModNone, Handler: gui.scrollDownConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Modifier: gocui.ModNone, Handler: gui.scrollUpConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Modifier: gocui.ModNone, Handler: gui.scrollDownConfirmationPanel, }, { ViewName: "confirmation", Key: gocui.MouseWheelUp, Handler: gui.scrollUpConfirmationPanel, }, { ViewName: "confirmation", Key: gocui.MouseWheelDown, Handler: gui.scrollDownConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.NextPage), Modifier: gocui.ModNone, Handler: gui.pageDownConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.PrevPage), Modifier: gocui.ModNone, Handler: gui.pageUpConfirmationPanel, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.GotoTop), Modifier: gocui.ModNone, Handler: gui.goToConfirmationPanelTop, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.GotoTopAlt), Modifier: gocui.ModNone, Handler: gui.goToConfirmationPanelTop, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.GotoBottom), Modifier: gocui.ModNone, Handler: gui.goToConfirmationPanelBottom, }, { ViewName: "confirmation", Key: opts.GetKey(opts.Config.Universal.GotoBottomAlt), Modifier: gocui.ModNone, Handler: gui.goToConfirmationPanelBottom, }, { ViewName: "submodules", Key: opts.GetKey(opts.Config.Universal.CopyToClipboard), Handler: gui.handleCopySelectedSideContextItemToClipboard, GetDisabledReason: gui.getCopySelectedSideContextItemToClipboardDisabledReason, Description: gui.c.Tr.CopySubmoduleNameToClipboard, }, { ViewName: "extras", Key: gocui.MouseWheelUp, Handler: gui.scrollUpExtra, }, { ViewName: "extras", Key: gocui.MouseWheelDown, Handler: gui.scrollDownExtra, }, { ViewName: "extras", Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItemAlt), Modifier: gocui.ModNone, Handler: gui.scrollUpExtra, }, { ViewName: "extras", Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.PrevItem), Modifier: gocui.ModNone, Handler: gui.scrollUpExtra, }, { ViewName: "extras", Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItem), Modifier: gocui.ModNone, Handler: gui.scrollDownExtra, }, { ViewName: "extras", Tag: "navigation", Key: opts.GetKey(opts.Config.Universal.NextItemAlt), Modifier: gocui.ModNone, Handler: gui.scrollDownExtra, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.NextPage), Modifier: gocui.ModNone, Handler: gui.pageDownExtrasPanel, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.PrevPage), Modifier: gocui.ModNone, Handler: gui.pageUpExtrasPanel, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.GotoTop), Modifier: gocui.ModNone, Handler: gui.goToExtrasPanelTop, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.GotoTopAlt), Modifier: gocui.ModNone, Handler: gui.goToExtrasPanelTop, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.GotoBottom), Modifier: gocui.ModNone, Handler: gui.goToExtrasPanelBottom, }, { ViewName: "extras", Key: opts.GetKey(opts.Config.Universal.GotoBottomAlt), Modifier: gocui.ModNone, Handler: gui.goToExtrasPanelBottom, }, { ViewName: "extras", Tag: "navigation", Key: gocui.MouseLeft, Modifier: gocui.ModNone, Handler: gui.handleFocusCommandLog, }, } mouseKeybindings := []*gocui.ViewMouseBinding{} for _, c := range gui.State.Contexts.Flatten() { viewName := c.GetViewName() for _, binding := range c.GetKeybindings(opts) { // TODO: move all mouse keybindings into the mouse keybindings approach below binding.ViewName = viewName bindings = append(bindings, binding) } mouseKeybindings = append(mouseKeybindings, c.GetMouseKeybindings(opts)...) } bindings = append(bindings, []*types.Binding{ { ViewName: "", Key: opts.GetKey(opts.Config.Universal.NextTab), Handler: opts.Guards.NoPopupPanel(gui.handleNextTab), Description: gui.c.Tr.NextTab, Tag: "navigation", }, { ViewName: "", Key: opts.GetKey(opts.Config.Universal.PrevTab), Handler: opts.Guards.NoPopupPanel(gui.handlePrevTab), Description: gui.c.Tr.PrevTab, Tag: "navigation", }, }...) return bindings, mouseKeybindings } func (gui *Gui) GetInitialKeybindingsWithCustomCommands() ([]*types.Binding, []*gocui.ViewMouseBinding) { // if the search or filter prompt is open, we only want the keybindings for // that context. It shouldn't be possible, for example, to open a menu while // the prompt is showing; you first need to confirm or cancel the search/filter. if currentContext := gui.State.ContextMgr.Current(); currentContext.GetKey() == context.SEARCH_CONTEXT_KEY { bindings := currentContext.GetKeybindings(gui.c.KeybindingsOpts()) viewName := currentContext.GetViewName() for _, binding := range bindings { binding.ViewName = viewName } return bindings, nil } bindings, mouseBindings := gui.GetInitialKeybindings() customBindings, err := gui.CustomCommandsClient.GetCustomCommandKeybindings() if err != nil { log.Fatal(err) } // prepending because we want to give our custom keybindings precedence over default keybindings bindings = append(customBindings, bindings...) return bindings, mouseBindings } func (gui *Gui) resetKeybindings() error { gui.g.DeleteAllKeybindings() bindings, mouseBindings := gui.GetInitialKeybindingsWithCustomCommands() for _, binding := range bindings { if err := gui.SetKeybinding(binding); err != nil { return err } } for _, binding := range mouseBindings { if err := gui.SetMouseKeybinding(binding); err != nil { return err } } for _, values := range gui.viewTabMap() { for _, value := range values { viewName := value.ViewName tabClickCallback := func(tabIndex int) error { return gui.onViewTabClick(gui.helpers.Window.WindowForView(viewName), tabIndex) } if err := gui.g.SetTabClickBinding(viewName, tabClickCallback); err != nil { return err } } } return nil } func (gui *Gui) wrappedHandler(f func() error) func(g *gocui.Gui, v *gocui.View) error { return func(g *gocui.Gui, v *gocui.View) error { return f() } } func (gui *Gui) SetKeybinding(binding *types.Binding) error { handler := func() error { return gui.callKeybindingHandler(binding) } // TODO: move all mouse-ey stuff into new mouse approach if gocui.IsMouseKey(binding.Key) { handler = func() error { // we ignore click events on views that aren't popup panels, when a popup panel is focused if gui.helpers.Confirmation.IsPopupPanelFocused() && gui.currentViewName() != binding.ViewName { return nil } return binding.Handler() } } return gui.g.SetKeybinding(binding.ViewName, binding.Key, binding.Modifier, gui.wrappedHandler(handler)) } // warning: mutates the binding func (gui *Gui) SetMouseKeybinding(binding *gocui.ViewMouseBinding) error { baseHandler := binding.Handler newHandler := func(opts gocui.ViewMouseBindingOpts) error { if gui.helpers.Confirmation.IsPopupPanelFocused() && gui.currentViewName() != binding.ViewName && !gocui.IsMouseScrollKey(opts.Key) { // we ignore click events on views that aren't popup panels, when a popup panel is focused. // Unless both the current view and the clicked-on view are either commit message or commit // description, or a prompt and the suggestions view, because we want to allow switching // between those two views by clicking. isCommitMessageOrSuggestionsView := func(viewName string) bool { return viewName == "commitMessage" || viewName == "commitDescription" || viewName == "prompt" || viewName == "suggestions" } if !isCommitMessageOrSuggestionsView(gui.currentViewName()) || !isCommitMessageOrSuggestionsView(binding.ViewName) { return nil } } return baseHandler(opts) } binding.Handler = newHandler return gui.g.SetViewClickBinding(binding) } func (gui *Gui) callKeybindingHandler(binding *types.Binding) error { if binding.GetDisabledReason != nil { if disabledReason := binding.GetDisabledReason(); disabledReason != nil { if disabledReason.AllowFurtherDispatching { return &types.ErrKeybindingNotHandled{DisabledReason: disabledReason} } if disabledReason.ShowErrorInPanel { return errors.New(disabledReason.Text) } if len(disabledReason.Text) > 0 { gui.c.ErrorToast(gui.Tr.DisabledMenuItemPrefix + disabledReason.Text) } return nil } } return binding.Handler() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/view_helpers.go
pkg/gui/view_helpers.go
package gui import ( "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/tasks" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/spkg/bom" ) func (gui *Gui) resetViewOrigin(v *gocui.View) { v.SetCursor(0, 0) v.SetOrigin(0, 0) } // Returns the number of lines that we should read initially from a cmd task so // that the scrollbar has the correct size, along with the number of lines after // which the view is filled and we can do a first refresh. func (gui *Gui) linesToReadFromCmdTask(v *gocui.View) tasks.LinesToRead { height := v.InnerHeight() oy := v.OriginY() linesForFirstRefresh := height + oy + 10 // We want to read as many lines initially as necessary to let the // scrollbar go to its minimum height, so that the scrollbar thumb doesn't // change size as you scroll down. minScrollbarHeight := 1 linesToReadForAccurateScrollbar := min( // However, cap it at some arbitrary max limit, so that we don't get // performance problems for huge monitors or tiny font sizes height*(height-1)/minScrollbarHeight+oy, 5000) return tasks.LinesToRead{ Total: linesToReadForAccurateScrollbar, InitialRefreshAfter: linesForFirstRefresh, } } func (gui *Gui) cleanString(s string) string { output := string(bom.Clean([]byte(s))) return utils.NormalizeLinefeeds(output) } func (gui *Gui) setViewContent(v *gocui.View, s string) { v.SetContent(gui.cleanString(s)) } func (gui *Gui) currentViewName() string { currentView := gui.g.CurrentView() if currentView == nil { return "" } return currentView.Name() } func (gui *Gui) onViewTabClick(windowName string, tabIndex int) error { tabs := gui.viewTabMap()[windowName] if len(tabs) == 0 { return nil } viewName := tabs[tabIndex].ViewName context, ok := gui.helpers.View.ContextForView(viewName) if !ok { return nil } gui.c.Context().Push(context, types.OnFocusOpts{}) return nil } func (gui *Gui) handleNextTab() error { view := getTabbedView(gui) if view == nil { return nil } for _, context := range gui.State.Contexts.Flatten() { if context.GetViewName() == view.Name() { return gui.onViewTabClick( context.GetWindowName(), utils.ModuloWithWrap(view.TabIndex+1, len(view.Tabs)), ) } } return nil } func (gui *Gui) handlePrevTab() error { view := getTabbedView(gui) if view == nil { return nil } for _, context := range gui.State.Contexts.Flatten() { if context.GetViewName() == view.Name() { return gui.onViewTabClick( context.GetWindowName(), utils.ModuloWithWrap(view.TabIndex-1, len(view.Tabs)), ) } } return nil } func getTabbedView(gui *Gui) *gocui.View { // It safe assumption that only static contexts have tabs context := gui.c.Context().CurrentStatic() view, _ := gui.g.View(context.GetViewName()) return view } func (gui *Gui) render() { gui.c.OnUIThread(func() error { return nil }) } // postRefreshUpdate is to be called on a context after the state that it depends on has been refreshed // if the context's view is set to another context we do nothing. // if the context's view is the current view we trigger a focus; re-selecting the current item. func (gui *Gui) postRefreshUpdate(c types.Context) { t := time.Now() defer func() { gui.Log.Infof("postRefreshUpdate for %s took %s", c.GetKey(), time.Since(t)) }() c.HandleRender() if gui.currentViewName() == c.GetViewName() { c.HandleFocus(types.OnFocusOpts{}) } else { // The FocusLine call is included in the HandleFocus method which we // call for focused views above; but we need to call it here for // non-focused views to ensure that an inactive selection is painted // correctly, and that integration tests see the up to date selection // state. c.FocusLine(false) currentCtx := gui.State.ContextMgr.Current() if currentCtx.GetKey() == context.NORMAL_MAIN_CONTEXT_KEY || currentCtx.GetKey() == context.NORMAL_SECONDARY_CONTEXT_KEY { // Searching can't cope well with the view being updated while it is being searched. // We might be able to fix the problems with this, but it doesn't seem easy, so for now // just don't rerender the view while searching, on the assumption that users will probably // either search or change their data, but not both at the same time. if !currentCtx.GetView().IsSearching() { sidePanelContext := gui.State.ContextMgr.NextInStack(currentCtx) if sidePanelContext != nil && sidePanelContext.GetKey() == c.GetKey() { sidePanelContext.HandleRenderToMain() } } } else if c.GetKey() == gui.State.ContextMgr.CurrentStatic().GetKey() { // If our view is not the current one, but it is the current static context, then this // can only mean that a popup is showing. In that case we want to refresh the main view // behind the popup. c.HandleRenderToMain() } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/dummies.go
pkg/gui/dummies.go
package gui import ( "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/updates" ) func NewDummyUpdater() *updates.Updater { newAppConfig := config.NewDummyAppConfig() dummyUpdater, _ := updates.NewUpdater(common.NewDummyCommon(), newAppConfig, oscommands.NewDummyOSCommand()) return dummyUpdater } // NewDummyGui creates a new dummy GUI for testing func NewDummyGui() *Gui { newAppConfig := config.NewDummyAppConfig() dummyGui, _ := NewGui(common.NewDummyCommon(), newAppConfig, &git_commands.GitVersion{Major: 2, Minor: 0, Patch: 0}, NewDummyUpdater(), false, "", nil) return dummyGui }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/extras_panel.go
pkg/gui/extras_panel.go
package gui import ( "io" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) func (gui *Gui) handleCreateExtrasMenuPanel() error { return gui.c.Menu(types.CreateMenuOptions{ Title: gui.c.Tr.CommandLog, Items: []*types.MenuItem{ { Label: gui.c.Tr.ToggleShowCommandLog, Key: 't', OnPress: func() error { currentContext := gui.c.Context().CurrentStatic() if gui.c.State().GetShowExtrasWindow() && currentContext.GetKey() == context.COMMAND_LOG_CONTEXT_KEY { gui.c.Context().Pop() } show := !gui.c.State().GetShowExtrasWindow() gui.c.State().SetShowExtrasWindow(show) gui.c.GetAppState().HideCommandLog = !show gui.c.SaveAppStateAndLogError() return nil }, }, { Label: gui.c.Tr.FocusCommandLog, Key: 'f', OnPress: gui.handleFocusCommandLog, }, }, }) } func (gui *Gui) handleFocusCommandLog() error { gui.c.State().SetShowExtrasWindow(true) // TODO: is this necessary? Can't I just call 'return from context'? gui.State.Contexts.CommandLog.SetParentContext(gui.c.Context().CurrentSide()) gui.c.Context().Push(gui.State.Contexts.CommandLog, types.OnFocusOpts{}) return nil } func (gui *Gui) scrollUpExtra() error { gui.Views.Extras.Autoscroll = false gui.scrollUpView(gui.Views.Extras) return nil } func (gui *Gui) scrollDownExtra() error { gui.Views.Extras.Autoscroll = false gui.scrollDownView(gui.Views.Extras) return nil } func (gui *Gui) pageUpExtrasPanel() error { gui.Views.Extras.Autoscroll = false gui.Views.Extras.ScrollUp(gui.Contexts().CommandLog.GetViewTrait().PageDelta()) return nil } func (gui *Gui) pageDownExtrasPanel() error { gui.Views.Extras.Autoscroll = false gui.Views.Extras.ScrollDown(gui.Contexts().CommandLog.GetViewTrait().PageDelta()) return nil } func (gui *Gui) goToExtrasPanelTop() error { gui.Views.Extras.Autoscroll = false gui.Views.Extras.ScrollUp(gui.Views.Extras.ViewLinesHeight()) return nil } func (gui *Gui) goToExtrasPanelBottom() error { gui.Views.Extras.Autoscroll = true gui.Views.Extras.ScrollDown(gui.Views.Extras.ViewLinesHeight()) return nil } func (gui *Gui) getCmdWriter() io.Writer { return &prefixWriter{writer: gui.Views.Extras, prefix: style.FgMagenta.Sprintf("\n\n%s\n", gui.c.Tr.GitOutput)} } // Ensures that the first write is preceded by writing a prefix. // This allows us to say 'Git output:' before writing the actual git output. // We could just write directly to the view in this package before running the command but we already have code in the commands package that writes to the same view beforehand (with the command it's about to run) so things would be out of order. type prefixWriter struct { prefix string prefixWritten bool writer io.Writer } func (self *prefixWriter) Write(p []byte) (int, error) { if !self.prefixWritten { self.prefixWritten = true // assuming we can write this prefix in one go n, err := self.writer.Write([]byte(self.prefix)) if err != nil { return n, err } } return self.writer.Write(p) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context_config.go
pkg/gui/context_config.go
package gui import ( "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) func (gui *Gui) contextTree() *context.ContextTree { contextCommon := &context.ContextCommon{ IGuiCommon: gui.c.IGuiCommon, Common: gui.c.Common, } return context.NewContextTree(contextCommon) } func (gui *Gui) defaultSideContext() types.Context { if gui.State.Modes.Filtering.Active() { return gui.State.Contexts.LocalCommits } return gui.State.Contexts.Files }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/command_log_panel.go
pkg/gui/command_log_panel.go
package gui import ( "fmt" "math/rand" "strings" "time" "github.com/jesseduffield/lazygit/pkg/constants" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/theme" ) // our UI command log looks like this: // Stage File: // git add -- 'filename' // Unstage File: // git reset HEAD 'filename' // // The 'Stage File' and 'Unstage File' lines are actions i.e they group up a set // of command logs (typically there's only one command under an action but there may be more). // So we call logAction to log the 'Stage File' part and then we call logCommand to log the command itself. // We pass logCommand to our OSCommand struct so that it can handle logging commands // for us. func (gui *Gui) LogAction(action string) { if gui.Views.Extras == nil { return } gui.Views.Extras.Autoscroll = true gui.GuiLog = append(gui.GuiLog, action) fmt.Fprint(gui.Views.Extras, "\n"+style.FgYellow.Sprint(action)) } func (gui *Gui) LogCommand(cmdStr string, commandLine bool) { if gui.Views.Extras == nil { return } gui.Views.Extras.Autoscroll = true textStyle := theme.DefaultTextColor if !commandLine { // if we're not dealing with a direct command that could be run on the command line, // we style it differently to communicate that textStyle = style.FgMagenta } gui.GuiLog = append(gui.GuiLog, cmdStr) indentedCmdStr := " " + strings.ReplaceAll(cmdStr, "\n", "\n ") fmt.Fprint(gui.Views.Extras, "\n"+textStyle.Sprint(indentedCmdStr)) } func (gui *Gui) printCommandLogHeader() { introStr := fmt.Sprintf( gui.c.Tr.CommandLogHeader, keybindings.Label(gui.c.UserConfig().Keybinding.Universal.ExtrasMenu), ) fmt.Fprintln(gui.Views.Extras, style.FgCyan.Sprint(introStr)) if gui.c.UserConfig().Gui.ShowRandomTip { fmt.Fprintf( gui.Views.Extras, "%s: %s", style.FgYellow.Sprint(gui.c.Tr.RandomTip), style.FgGreen.Sprint(gui.getRandomTip()), ) } } func (gui *Gui) getRandomTip() string { config := gui.c.UserConfig().Keybinding formattedKey := func(key string) string { return keybindings.Label(key) } tips := []string{ // keybindings and lazygit-specific advice fmt.Sprintf( "To force push, press '%s' and then if the push is rejected you will be asked if you want to force push", formattedKey(config.Universal.Push), ), fmt.Sprintf( "To filter commits by path, press '%s'", formattedKey(config.Universal.FilteringMenu), ), fmt.Sprintf( "To start an interactive rebase, press '%s' on a commit. You can always abort the rebase by pressing '%s' and selecting 'abort'", formattedKey(config.Universal.Edit), formattedKey(config.Universal.CreateRebaseOptionsMenu), ), fmt.Sprintf( "In flat file view, merge conflicts are sorted to the top. To switch to flat file view press '%s'", formattedKey(config.Files.ToggleTreeView), ), "If you want to learn Go and can think of ways to improve lazygit, join the team! Click 'Ask Question' and express your interest", fmt.Sprintf( "If you press '%s'/'%s' you can undo/redo your changes. Be wary though, this only applies to branches/commits, so only do this if your worktree is clear.\nDocs: %s", formattedKey(config.Universal.Undo), formattedKey(config.Universal.Redo), constants.Links.Docs.Undoing, ), fmt.Sprintf( "to hard reset onto your current upstream branch, press '%s' in the files panel", formattedKey(config.Commits.ViewResetOptions), ), fmt.Sprintf( "To push a tag, navigate to the tag in the tags tab and press '%s'", formattedKey(config.Branches.PushTag), ), fmt.Sprintf( "You can view the individual files of a stash entry by pressing '%s'", formattedKey(config.Universal.GoInto), ), fmt.Sprintf( "You can diff two commits by pressing '%s' on one commit and then navigating to the other. You can then press '%s' to view the files of the diff", formattedKey(config.Universal.DiffingMenu), formattedKey(config.Universal.GoInto), ), fmt.Sprintf( "press '%s' on a commit to drop it (delete it)", formattedKey(config.Universal.Remove), ), fmt.Sprintf( "If you need to pull out the big guns to resolve merge conflicts, you can press '%s' in the files panel to open merge options", formattedKey(config.Files.OpenMergeOptions), ), fmt.Sprintf( "To revert a commit, press '%s' on that commit", formattedKey(config.Commits.RevertCommit), ), fmt.Sprintf( "To escape a mode, for example cherry-picking, patch-building, diffing, or filtering mode, you can just spam the '%s' button. Unless of course you have `quitOnTopLevelReturn` enabled in your config", formattedKey(config.Universal.Return), ), fmt.Sprintf( "You can page through the items of a panel using '%s' and '%s'", formattedKey(config.Universal.PrevPage), formattedKey(config.Universal.NextPage), ), fmt.Sprintf( "You can jump to the top/bottom of a panel using '%s (or %s)' and '%s (or %s)'", formattedKey(config.Universal.GotoTop), formattedKey(config.Universal.GotoTopAlt), formattedKey(config.Universal.GotoBottom), formattedKey(config.Universal.GotoBottomAlt), ), fmt.Sprintf( "To collapse/expand a directory, press '%s'", formattedKey(config.Universal.GoInto), ), fmt.Sprintf( "You can append your staged changes to an older commit by pressing '%s' on that commit", formattedKey(config.Commits.AmendToCommit), ), fmt.Sprintf( "You can amend the last commit with your new file changes by pressing '%s' in the files panel", formattedKey(config.Files.AmendLastCommit), ), fmt.Sprintf( "You can now navigate the side panels with '%s' and '%s'", formattedKey(config.Universal.NextBlockAlt2), formattedKey(config.Universal.PrevBlockAlt2), ), "You can use lazygit with a bare repo by passing the --git-dir and --work-tree arguments as you would for the git CLI", // general advice "`git commit` is really just the programmer equivalent of saving your game. Always do it before embarking on an ambitious change!", "Try to separate commits that refactor code from commits that add new functionality: if they're squashed into one commit, it can be hard to spot what's new.", "If you ever want to experiment, it's easy to create a new branch off your current one and go nuts, then delete it afterwards", "Always read through the diff of your changes before assigning somebody to review your code. Better for you to catch any silly mistakes than your colleagues!", "If something goes wrong, you can always checkout a commit from your reflog to return to an earlier state", "The stash is a good place to save snippets of code that you always find yourself adding when debugging.", // links fmt.Sprintf( "If you want a git diff with syntax colouring, check out lazygit's integration with delta:\n%s", constants.Links.Docs.CustomPagers, ), fmt.Sprintf( "You can build your own custom menus and commands to run from within lazygit. For examples see:\n%s", constants.Links.Docs.CustomCommands, ), fmt.Sprintf( "If you ever find a bug, do not hesitate to raise an issue on the repo:\n%s", constants.Links.Issues, ), } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) randomIndex := rnd.Intn(len(tips)) return tips[randomIndex] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/tasks_adapter.go
pkg/gui/tasks_adapter.go
package gui import ( "io" "os/exec" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/tasks" ) func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error { cmdStr := strings.Join(cmd.Args, " ") gui.c.Log.WithField( "command", cmdStr, ).Debug("RunCommand") manager := gui.getManager(view) var r io.ReadCloser start := func() (*exec.Cmd, io.Reader) { var err error r, err = cmd.StdoutPipe() if err != nil { gui.c.Log.Error(err) r = nil } cmd.Stderr = cmd.Stdout if err := cmd.Start(); err != nil { gui.c.Log.Error(err) } return cmd, r } onClose := func() { if r != nil { r.Close() r = nil } } linesToRead := gui.linesToReadFromCmdTask(view) if err := manager.NewTask(manager.NewCmdTask(start, prefix, linesToRead, onClose), cmdStr); err != nil { gui.c.Log.Error(err) } return nil } func (gui *Gui) newStringTask(view *gocui.View, str string) error { // using str so that if rendering the exact same thing we don't reset the origin return gui.newStringTaskWithKey(view, str, str) } func (gui *Gui) newStringTaskWithoutScroll(view *gocui.View, str string) error { manager := gui.getManager(view) f := func(tasks.TaskOpts) error { gui.c.SetViewContent(view, str) return nil } if err := manager.NewTask(f, manager.GetTaskKey()); err != nil { return err } return nil } func (gui *Gui) newStringTaskWithScroll(view *gocui.View, str string, originX int, originY int) error { manager := gui.getManager(view) f := func(tasks.TaskOpts) error { gui.c.SetViewContent(view, str) view.SetOrigin(originX, originY) return nil } if err := manager.NewTask(f, manager.GetTaskKey()); err != nil { return err } return nil } func (gui *Gui) newStringTaskWithKey(view *gocui.View, str string, key string) error { manager := gui.getManager(view) f := func(tasks.TaskOpts) error { gui.c.ResetViewOrigin(view) gui.c.SetViewContent(view, str) return nil } if err := manager.NewTask(f, key); err != nil { return err } return nil } func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager { manager, ok := gui.viewBufferManagerMap[view.Name()] if !ok { manager = tasks.NewViewBufferManager( gui.Log, view, func() { // we could clear here, but that actually has the effect of causing a flicker // where the view may contain no content momentarily as the gui refreshes. // Instead, we're rewinding the write pointer so that we will just start // overwriting the existing content from the top down. Once we've reached // the end of the content do display, we call view.FlushStaleCells() to // clear out the remaining content from the previous render. view.Reset() }, func() { gui.render() }, func() { // Need to check if the content of the view is well past the origin. linesHeight := view.ViewLinesHeight() _, originY := view.Origin() if linesHeight < originY { newOriginY := linesHeight view.SetOrigin(0, newOriginY) } view.FlushStaleCells() }, func() { view.SetOrigin(0, 0) }, func() gocui.Task { return gui.c.GocuiGui().NewTask() }, ) gui.viewBufferManagerMap[view.Name()] = manager } return manager }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/gui_common.go
pkg/gui/gui_common.go
package gui import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/tasks" ) // hacking this by including the gui struct for now until we split more things out type guiCommon struct { gui *Gui types.IPopupHandler } var _ types.IGuiCommon = &guiCommon{} func (self *guiCommon) LogAction(msg string) { self.gui.LogAction(msg) } func (self *guiCommon) LogCommand(cmdStr string, isCommandLine bool) { self.gui.LogCommand(cmdStr, isCommandLine) } func (self *guiCommon) Refresh(opts types.RefreshOptions) { self.gui.helpers.Refresh.Refresh(opts) } func (self *guiCommon) PostRefreshUpdate(context types.Context) { self.gui.postRefreshUpdate(context) } func (self *guiCommon) RunSubprocessAndRefresh(cmdObj *oscommands.CmdObj) error { return self.gui.runSubprocessWithSuspenseAndRefresh(cmdObj) } func (self *guiCommon) RunSubprocess(cmdObj *oscommands.CmdObj) (bool, error) { return self.gui.runSubprocessWithSuspense(cmdObj) } func (self *guiCommon) Suspend() error { return self.gui.suspend() } func (self *guiCommon) Resume() error { return self.gui.resume() } func (self *guiCommon) Context() types.IContextMgr { return self.gui.State.ContextMgr } func (self *guiCommon) ContextForKey(key types.ContextKey) types.Context { return self.gui.State.ContextMgr.ContextForKey(key) } func (self *guiCommon) GetAppState() *config.AppState { return self.gui.Config.GetAppState() } func (self *guiCommon) SaveAppState() error { return self.gui.Config.SaveAppState() } func (self *guiCommon) SaveAppStateAndLogError() { if err := self.gui.Config.SaveAppState(); err != nil { self.gui.Log.Errorf("error when saving app state: %v", err) } } func (self *guiCommon) GetConfig() config.AppConfigurer { return self.gui.Config } func (self *guiCommon) ResetViewOrigin(view *gocui.View) { self.gui.resetViewOrigin(view) } func (self *guiCommon) SetViewContent(view *gocui.View, content string) { self.gui.setViewContent(view, content) } func (self *guiCommon) Render() { self.gui.render() } func (self *guiCommon) Views() types.Views { return self.gui.Views } func (self *guiCommon) Git() *commands.GitCommand { return self.gui.git } func (self *guiCommon) OS() *oscommands.OSCommand { return self.gui.os } func (self *guiCommon) Modes() *types.Modes { return self.gui.State.Modes } func (self *guiCommon) Model() *types.Model { return self.gui.State.Model } func (self *guiCommon) Mutexes() *types.Mutexes { return &self.gui.Mutexes } func (self *guiCommon) GocuiGui() *gocui.Gui { return self.gui.g } func (self *guiCommon) OnUIThread(f func() error) { self.gui.onUIThread(f) } func (self *guiCommon) OnWorker(f func(gocui.Task) error) { self.gui.onWorker(f) } func (self *guiCommon) RenderToMainViews(opts types.RefreshMainOpts) { self.gui.refreshMainViews(opts) } func (self *guiCommon) MainViewPairs() types.MainViewPairs { return types.MainViewPairs{ Normal: self.gui.normalMainContextPair(), Staging: self.gui.stagingMainContextPair(), PatchBuilding: self.gui.patchBuildingMainContextPair(), MergeConflicts: self.gui.mergingMainContextPair(), } } func (self *guiCommon) GetViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager { return self.gui.getViewBufferManagerForView(view) } func (self *guiCommon) State() types.IStateAccessor { return self.gui.stateAccessor } func (self *guiCommon) KeybindingsOpts() types.KeybindingsOpts { return self.gui.keybindingOpts() } func (self *guiCommon) CallKeybindingHandler(binding *types.Binding) error { return self.gui.callKeybindingHandler(binding) } func (self *guiCommon) ResetKeybindings() error { return self.gui.resetKeybindings() } func (self *guiCommon) IsAnyModeActive() bool { return self.gui.helpers.Mode.IsAnyModeActive() } func (self *guiCommon) GetInitialKeybindingsWithCustomCommands() ([]*types.Binding, []*gocui.ViewMouseBinding) { return self.gui.GetInitialKeybindingsWithCustomCommands() } func (self *guiCommon) AfterLayout(f func() error) { self.gui.afterLayout(f) } func (self *guiCommon) RunningIntegrationTest() bool { return self.gui.integrationTest != nil } func (self *guiCommon) InDemo() bool { return self.gui.integrationTest != nil && self.gui.integrationTest.IsDemo() } func (self *guiCommon) WithInlineStatus(item types.HasUrn, operation types.ItemOperation, contextKey types.ContextKey, f func(gocui.Task) error) error { self.gui.helpers.InlineStatus.WithInlineStatus(helpers.InlineStatusOpts{Item: item, Operation: operation, ContextKey: contextKey}, f) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/views.go
pkg/gui/views.go
package gui import ( "errors" "fmt" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/theme" "github.com/samber/lo" "golang.org/x/exp/slices" ) type viewNameMapping struct { viewPtr **gocui.View name string } func (gui *Gui) orderedViews() []*gocui.View { return lo.Map(gui.orderedViewNameMappings(), func(v viewNameMapping, _ int) *gocui.View { return *v.viewPtr }) } func (gui *Gui) orderedViewNameMappings() []viewNameMapping { return []viewNameMapping{ // first layer. Ordering within this layer does not matter because there are // no overlapping views {viewPtr: &gui.Views.Status, name: "status"}, {viewPtr: &gui.Views.Snake, name: "snake"}, {viewPtr: &gui.Views.Submodules, name: "submodules"}, {viewPtr: &gui.Views.Worktrees, name: "worktrees"}, {viewPtr: &gui.Views.Files, name: "files"}, {viewPtr: &gui.Views.Tags, name: "tags"}, {viewPtr: &gui.Views.Remotes, name: "remotes"}, {viewPtr: &gui.Views.Branches, name: "localBranches"}, {viewPtr: &gui.Views.RemoteBranches, name: "remoteBranches"}, {viewPtr: &gui.Views.ReflogCommits, name: "reflogCommits"}, {viewPtr: &gui.Views.Commits, name: "commits"}, {viewPtr: &gui.Views.Stash, name: "stash"}, {viewPtr: &gui.Views.SubCommits, name: "subCommits"}, {viewPtr: &gui.Views.CommitFiles, name: "commitFiles"}, {viewPtr: &gui.Views.Staging, name: "staging"}, {viewPtr: &gui.Views.StagingSecondary, name: "stagingSecondary"}, {viewPtr: &gui.Views.PatchBuilding, name: "patchBuilding"}, {viewPtr: &gui.Views.PatchBuildingSecondary, name: "patchBuildingSecondary"}, {viewPtr: &gui.Views.MergeConflicts, name: "mergeConflicts"}, {viewPtr: &gui.Views.Secondary, name: "secondary"}, {viewPtr: &gui.Views.Main, name: "main"}, {viewPtr: &gui.Views.Extras, name: "extras"}, // bottom line {viewPtr: &gui.Views.Options, name: "options"}, {viewPtr: &gui.Views.AppStatus, name: "appStatus"}, {viewPtr: &gui.Views.Information, name: "information"}, {viewPtr: &gui.Views.Search, name: "search"}, // this view shows either the "Search:" prompt when searching, or the "Filter:" prompt when filtering {viewPtr: &gui.Views.SearchPrefix, name: "searchPrefix"}, // these views contain one space, and are used as spacers between the various views in the bottom line {viewPtr: &gui.Views.StatusSpacer1, name: "statusSpacer1"}, {viewPtr: &gui.Views.StatusSpacer2, name: "statusSpacer2"}, // popups. {viewPtr: &gui.Views.CommitMessage, name: "commitMessage"}, {viewPtr: &gui.Views.CommitDescription, name: "commitDescription"}, {viewPtr: &gui.Views.Menu, name: "menu"}, {viewPtr: &gui.Views.Suggestions, name: "suggestions"}, {viewPtr: &gui.Views.Confirmation, name: "confirmation"}, {viewPtr: &gui.Views.Prompt, name: "prompt"}, {viewPtr: &gui.Views.Tooltip, name: "tooltip"}, // this guy will cover everything else when it appears {viewPtr: &gui.Views.Limit, name: "limit"}, } } func (gui *Gui) createAllViews() error { var err error for _, mapping := range gui.orderedViewNameMappings() { *mapping.viewPtr, err = gui.prepareView(mapping.name) if err != nil && !errors.Is(err, gocui.ErrUnknownView) { return err } } gui.Views.Options.Frame = false gui.Views.SearchPrefix.BgColor = gocui.ColorDefault gui.Views.SearchPrefix.FgColor = gocui.ColorCyan gui.Views.SearchPrefix.Frame = false gui.Views.StatusSpacer1.Frame = false gui.Views.StatusSpacer2.Frame = false gui.Views.Search.BgColor = gocui.ColorDefault gui.Views.Search.FgColor = gocui.ColorCyan gui.Views.Search.Editable = true gui.Views.Search.Frame = false gui.Views.Search.Editor = gocui.EditorFunc(gui.searchEditor) for _, view := range []*gocui.View{gui.Views.Main, gui.Views.Secondary, gui.Views.Staging, gui.Views.StagingSecondary, gui.Views.PatchBuilding, gui.Views.PatchBuildingSecondary, gui.Views.MergeConflicts} { view.Wrap = true view.IgnoreCarriageReturns = true view.UnderlineHyperLinksOnlyOnHover = true view.AutoRenderHyperLinks = true } gui.Views.Staging.Wrap = true gui.Views.StagingSecondary.Wrap = true gui.Views.PatchBuilding.Wrap = true gui.Views.PatchBuildingSecondary.Wrap = true gui.Views.MergeConflicts.Wrap = false gui.Views.Limit.Wrap = true gui.Views.AppStatus.BgColor = gocui.ColorDefault gui.Views.AppStatus.FgColor = gocui.ColorCyan gui.Views.AppStatus.Visible = false gui.Views.AppStatus.Frame = false gui.Views.CommitMessage.Visible = false gui.Views.CommitMessage.Editable = true gui.Views.CommitMessage.Editor = gocui.EditorFunc(gui.commitMessageEditor) gui.Views.CommitDescription.Visible = false gui.Views.CommitDescription.Editable = true gui.Views.CommitDescription.Editor = gocui.EditorFunc(gui.commitDescriptionEditor) gui.Views.Confirmation.Visible = false gui.Views.Confirmation.Wrap = true gui.Views.Confirmation.AutoRenderHyperLinks = true gui.Views.Prompt.Visible = false gui.Views.Prompt.Wrap = false // We don't want wrapping in one-line prompts gui.Views.Prompt.Editable = true gui.Views.Prompt.Editor = gocui.EditorFunc(gui.promptEditor) gui.Views.Suggestions.Visible = false gui.Views.Menu.Visible = false gui.Views.Tooltip.Visible = false gui.Views.Tooltip.AutoRenderHyperLinks = true gui.Views.Information.BgColor = gocui.ColorDefault gui.Views.Information.FgColor = gocui.ColorGreen gui.Views.Information.Frame = false gui.Views.Extras.Autoscroll = true gui.Views.Extras.Wrap = true gui.Views.Extras.AutoRenderHyperLinks = true gui.Views.Snake.FgColor = gocui.ColorGreen return nil } func (gui *Gui) configureViewProperties() { frameRunes := []rune{'─', '│', '┌', '┐', '└', '┘'} switch gui.c.UserConfig().Gui.Border { case "double": frameRunes = []rune{'═', '║', '╔', '╗', '╚', '╝'} case "rounded": frameRunes = []rune{'─', '│', '╭', '╮', '╰', '╯'} case "hidden": frameRunes = []rune{' ', ' ', ' ', ' ', ' ', ' '} case "bold": frameRunes = []rune{'━', '┃', '┏', '┓', '┗', '┛'} } for _, mapping := range gui.orderedViewNameMappings() { (*mapping.viewPtr).FrameRunes = frameRunes (*mapping.viewPtr).BgColor = gui.g.BgColor (*mapping.viewPtr).FgColor = theme.GocuiDefaultTextColor (*mapping.viewPtr).SelBgColor = theme.GocuiSelectedLineBgColor (*mapping.viewPtr).SelFgColor = gui.g.SelFgColor (*mapping.viewPtr).InactiveViewSelBgColor = theme.GocuiInactiveViewSelectedLineBgColor } gui.c.SetViewContent(gui.Views.SearchPrefix, gui.c.Tr.SearchPrefix) gui.Views.Stash.Title = gui.c.Tr.StashTitle gui.Views.Commits.Title = gui.c.Tr.CommitsTitle gui.Views.CommitFiles.Title = gui.c.Tr.CommitFiles gui.Views.Branches.Title = gui.c.Tr.BranchesTitle gui.Views.Remotes.Title = gui.c.Tr.RemotesTitle gui.Views.Worktrees.Title = gui.c.Tr.WorktreesTitle gui.Views.Tags.Title = gui.c.Tr.TagsTitle gui.Views.Files.Title = gui.c.Tr.FilesTitle gui.Views.PatchBuilding.Title = gui.c.Tr.Patch gui.Views.PatchBuildingSecondary.Title = gui.c.Tr.CustomPatch gui.Views.MergeConflicts.Title = gui.c.Tr.MergeConflictsTitle gui.Views.Limit.Title = gui.c.Tr.NotEnoughSpace gui.Views.Status.Title = gui.c.Tr.StatusTitle gui.Views.Staging.Title = gui.c.Tr.UnstagedChanges gui.Views.StagingSecondary.Title = gui.c.Tr.StagedChanges gui.Views.CommitMessage.Title = gui.c.Tr.CommitSummary gui.Views.CommitDescription.Title = gui.c.Tr.CommitDescriptionTitle gui.Views.Extras.Title = gui.c.Tr.CommandLog gui.Views.Snake.Title = gui.c.Tr.SnakeTitle for _, view := range []*gocui.View{gui.Views.Main, gui.Views.Secondary, gui.Views.Staging, gui.Views.StagingSecondary, gui.Views.PatchBuilding, gui.Views.PatchBuildingSecondary, gui.Views.MergeConflicts} { view.Title = gui.c.Tr.DiffTitle view.CanScrollPastBottom = gui.c.UserConfig().Gui.ScrollPastBottom view.TabWidth = gui.c.UserConfig().Gui.TabWidth } gui.Views.CommitDescription.FgColor = theme.GocuiDefaultTextColor gui.Views.CommitDescription.TextArea.AutoWrap = gui.c.UserConfig().Git.Commit.AutoWrapCommitMessage gui.Views.CommitDescription.TextArea.AutoWrapWidth = gui.c.UserConfig().Git.Commit.AutoWrapWidth if gui.c.UserConfig().Gui.ShowPanelJumps { keyToTitlePrefix := func(key string) string { if key == "<disabled>" { return "" } return fmt.Sprintf("[%s]", key) } jumpBindings := gui.c.UserConfig().Keybinding.Universal.JumpToBlock jumpLabels := lo.Map(jumpBindings, func(binding string, _ int) string { return keyToTitlePrefix(binding) }) gui.Views.Status.TitlePrefix = jumpLabels[0] gui.Views.Files.TitlePrefix = jumpLabels[1] gui.Views.Worktrees.TitlePrefix = jumpLabels[1] gui.Views.Submodules.TitlePrefix = jumpLabels[1] gui.Views.Branches.TitlePrefix = jumpLabels[2] gui.Views.Remotes.TitlePrefix = jumpLabels[2] gui.Views.Tags.TitlePrefix = jumpLabels[2] gui.Views.Commits.TitlePrefix = jumpLabels[3] gui.Views.ReflogCommits.TitlePrefix = jumpLabels[3] gui.Views.Stash.TitlePrefix = jumpLabels[4] gui.Views.Main.TitlePrefix = keyToTitlePrefix(gui.c.UserConfig().Keybinding.Universal.FocusMainView) } else { gui.Views.Status.TitlePrefix = "" gui.Views.Files.TitlePrefix = "" gui.Views.Worktrees.TitlePrefix = "" gui.Views.Submodules.TitlePrefix = "" gui.Views.Branches.TitlePrefix = "" gui.Views.Remotes.TitlePrefix = "" gui.Views.Tags.TitlePrefix = "" gui.Views.Commits.TitlePrefix = "" gui.Views.ReflogCommits.TitlePrefix = "" gui.Views.Stash.TitlePrefix = "" gui.Views.Main.TitlePrefix = "" } for _, view := range gui.g.Views() { // if the view is in our mapping, we'll set the tabs and the tab index for _, values := range gui.viewTabMap() { index := slices.IndexFunc(values, func(tabContext context.TabView) bool { return tabContext.ViewName == view.Name() }) if index != -1 { view.Tabs = lo.Map(values, func(tabContext context.TabView, _ int) string { return tabContext.Tab }) view.TabIndex = index } } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/layout.go
pkg/gui/layout.go
package gui import ( "errors" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // layout is called for every screen re-render e.g. when the screen is resized func (gui *Gui) layout(g *gocui.Gui) error { if !gui.ViewsSetup { gui.printCommandLogHeader() if _, err := gui.g.SetCurrentView(gui.defaultSideContext().GetViewName()); err != nil { return err } } g.Highlight = true width, height := g.Size() informationStr := gui.informationStr() appStatus := gui.helpers.AppStatus.GetStatusString() viewDimensions := gui.getWindowDimensions(informationStr, appStatus) // reading more lines into main view buffers upon resize prevMainView := gui.Views.Main if prevMainView != nil { prevMainHeight := prevMainView.Height() newMainHeight := viewDimensions["main"].Y1 - viewDimensions["main"].Y0 + 1 heightDiff := newMainHeight - prevMainHeight if heightDiff > 0 { if manager := gui.getViewBufferManagerForView(gui.Views.Main); manager != nil { manager.ReadLines(heightDiff) } if manager := gui.getViewBufferManagerForView(gui.Views.Secondary); manager != nil { manager.ReadLines(heightDiff) } } } contextsToRerender := []types.Context{} // we assume that the view has already been created. setViewFromDimensions := func(context types.Context) (*gocui.View, error) { viewName := context.GetViewName() windowName := context.GetWindowName() dimensionsObj, ok := viewDimensions[windowName] view, err := g.View(viewName) if err != nil { return nil, err } if !ok { // view not specified in dimensions object: so create the view and hide it // making the view take up the whole space in the background in case it needs // to render content as soon as it appears, because lazyloaded content (via a pty task) // cares about the size of the view. _, err := g.SetView(viewName, 0, 0, width, height, 0) view.Visible = false return view, err } frameOffset := 1 if view.Frame { frameOffset = 0 } mustRerender := false newHeight := dimensionsObj.Y1 - dimensionsObj.Y0 + 2*frameOffset maxOriginY := context.TotalContentHeight() if !view.CanScrollPastBottom { maxOriginY -= newHeight - 1 } if oldOriginY := view.OriginY(); oldOriginY > maxOriginY { view.ScrollUp(oldOriginY - maxOriginY) // the view might not have scrolled actually (if it was at the limit // already), so we need to check if it did if oldOriginY != view.OriginY() && context.NeedsRerenderOnHeightChange() { mustRerender = true } } if context.NeedsRerenderOnWidthChange() == types.NEEDS_RERENDER_ON_WIDTH_CHANGE_WHEN_WIDTH_CHANGES { oldWidth := view.Width() newWidth := dimensionsObj.X1 - dimensionsObj.X0 + 1 if oldWidth != newWidth { mustRerender = true } } if context.NeedsRerenderOnHeightChange() { oldHeight := view.Height() newHeight := dimensionsObj.Y1 - dimensionsObj.Y0 + 1 if oldHeight != newHeight { mustRerender = true } } if mustRerender { contextsToRerender = append(contextsToRerender, context) } _, err = g.SetView( viewName, dimensionsObj.X0-frameOffset, dimensionsObj.Y0-frameOffset, dimensionsObj.X1+frameOffset, dimensionsObj.Y1+frameOffset, 0, ) view.Visible = true return view, err } for _, context := range gui.State.Contexts.Flatten() { if !context.HasControlledBounds() { continue } _, err := setViewFromDimensions(context) if err != nil && !errors.Is(err, gocui.ErrUnknownView) { return err } } minimumHeight := 9 minimumWidth := 10 gui.Views.Limit.Visible = height < minimumHeight || width < minimumWidth gui.Views.Tooltip.Visible = gui.Views.Menu.Visible && gui.Views.Tooltip.Buffer() != "" for _, context := range gui.transientContexts() { view, err := gui.g.View(context.GetViewName()) if err != nil && !errors.Is(err, gocui.ErrUnknownView) { return err } view.Visible = gui.helpers.Window.GetViewNameForWindow(context.GetWindowName()) == context.GetViewName() } if gui.PrevLayout.Information != informationStr { gui.c.SetViewContent(gui.Views.Information, informationStr) gui.PrevLayout.Information = informationStr } if !gui.ViewsSetup { if err := gui.onInitialViewsCreation(); err != nil { return err } gui.handleTestMode() gui.ViewsSetup = true } if !gui.State.ViewsSetup { if err := gui.onInitialViewsCreationForRepo(); err != nil { return err } gui.State.ViewsSetup = true } mainViewWidth, mainViewHeight := gui.Views.Main.Size() if mainViewWidth != gui.PrevLayout.MainWidth || mainViewHeight != gui.PrevLayout.MainHeight { gui.PrevLayout.MainWidth = mainViewWidth gui.PrevLayout.MainHeight = mainViewHeight if err := gui.onResize(); err != nil { return err } } for _, context := range contextsToRerender { context.HandleRender() } // here is a good place log some stuff // if you run `lazygit --logs` // this will let you see these branches as prettified json // gui.c.Log.Info(utils.AsJson(gui.State.Model.Branches[0:4])) gui.helpers.Confirmation.ResizeCurrentPopupPanels() gui.renderContextOptionsMap() outer: for { select { case f := <-gui.afterLayoutFuncs: if err := f(); err != nil { return err } default: break outer } } return nil } func (gui *Gui) prepareView(viewName string) (*gocui.View, error) { // arbitrarily giving the view enough size so that we don't get an error, but // it's expected that the view will be given the correct size before being shown return gui.g.SetView(viewName, 0, 0, 10, 10, 0) } func (gui *Gui) onInitialViewsCreationForRepo() error { if err := gui.onRepoViewReset(); err != nil { return err } // hide any popup views. This only applies when we've just switched repos for _, viewName := range gui.popupViewNames() { view, err := gui.g.View(viewName) if err == nil { view.Visible = false } } initialContext := gui.c.Context().Current() gui.c.Context().Activate(initialContext, types.OnFocusOpts{}) return gui.loadNewRepo() } func (gui *Gui) popupViewNames() []string { popups := lo.Filter(gui.State.Contexts.Flatten(), func(c types.Context, _ int) bool { return c.GetKind() == types.PERSISTENT_POPUP || c.GetKind() == types.TEMPORARY_POPUP }) return lo.Map(popups, func(c types.Context, _ int) string { return c.GetViewName() }) } func (gui *Gui) onRepoViewReset() error { // now we order the views (in order of bottom first) for _, view := range gui.orderedViews() { if _, err := gui.g.SetViewOnTop(view.Name()); err != nil { return err } } return nil } func (gui *Gui) onInitialViewsCreation() error { if !gui.c.UserConfig().DisableStartupPopups { storedPopupVersion := gui.c.GetAppState().StartupPopupVersion if storedPopupVersion < StartupPopupVersion { gui.showIntroPopupMessage() } else { gui.showBreakingChangesMessage() } } gui.c.GetAppState().LastVersion = gui.Config.GetVersion() gui.c.SaveAppStateAndLogError() if gui.showRecentRepos { if err := gui.helpers.Repos.CreateRecentReposMenu(); err != nil { return err } gui.showRecentRepos = false } gui.helpers.Update.CheckForUpdateInBackground() gui.waitForIntro.Done() return nil } func (gui *Gui) transientContexts() []types.Context { return lo.Filter(gui.State.Contexts.Flatten(), func(context types.Context, _ int) bool { return context.IsTransient() }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/background.go
pkg/gui/background.go
package gui import ( "fmt" "runtime" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) type BackgroundRoutineMgr struct { gui *Gui // if we've suspended the gui (e.g. because we've switched to a subprocess) // we typically want to pause some things that are running like background // file refreshes pauseBackgroundRefreshes bool // a channel to trigger an immediate background fetch; we use this when switching repos triggerFetch chan struct{} } func (self *BackgroundRoutineMgr) PauseBackgroundRefreshes(pause bool) { self.pauseBackgroundRefreshes = pause } func (self *BackgroundRoutineMgr) startBackgroundRoutines() { userConfig := self.gui.UserConfig() if userConfig.Git.AutoFetch { fetchInterval := userConfig.Refresher.FetchInterval if fetchInterval > 0 { go utils.Safe(self.startBackgroundFetch) } else { self.gui.c.Log.Errorf( "Value of config option 'refresher.fetchInterval' (%d) is invalid, disabling auto-fetch", fetchInterval) } } if userConfig.Git.AutoRefresh { refreshInterval := userConfig.Refresher.RefreshInterval if refreshInterval > 0 { go utils.Safe(self.startBackgroundFilesRefresh) } else { self.gui.c.Log.Errorf( "Value of config option 'refresher.refreshInterval' (%d) is invalid, disabling auto-refresh", refreshInterval) } } if self.gui.Config.GetDebug() { self.goEvery(time.Second*time.Duration(10), self.gui.stopChan, func() error { formatBytes := func(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := uint64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) } m := runtime.MemStats{} runtime.ReadMemStats(&m) self.gui.c.Log.Infof("Heap memory in use: %s", formatBytes(m.HeapAlloc)) return nil }) } } func (self *BackgroundRoutineMgr) startBackgroundFetch() { self.gui.waitForIntro.Wait() fetch := func() error { // Do this on the UI thread so that we don't have to deal with synchronization around the // access of the repo state. self.gui.onUIThread(func() error { // There's a race here, where we might be recording the time stamp for a different repo // than where the fetch actually ran. It's not very likely though, and not harmful if it // does happen; guarding against it would be more effort than it's worth. self.gui.State.LastBackgroundFetchTime = time.Now() return nil }) return self.gui.helpers.AppStatus.WithWaitingStatusImpl(self.gui.Tr.FetchingStatus, func(gocui.Task) error { return self.backgroundFetch() }, nil) } // We want an immediate fetch at startup, and since goEvery starts by // waiting for the interval, we need to trigger one manually first _ = fetch() userConfig := self.gui.UserConfig() self.triggerFetch = self.goEvery(userConfig.Refresher.FetchIntervalDuration(), self.gui.stopChan, fetch) } func (self *BackgroundRoutineMgr) startBackgroundFilesRefresh() { self.gui.waitForIntro.Wait() userConfig := self.gui.UserConfig() self.goEvery(userConfig.Refresher.RefreshIntervalDuration(), self.gui.stopChan, func() error { self.gui.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return nil }) } // returns a channel that can be used to trigger the callback immediately func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop chan struct{}, function func() error) chan struct{} { done := make(chan struct{}) retrigger := make(chan struct{}) go utils.Safe(func() { ticker := time.NewTicker(interval) defer ticker.Stop() doit := func() { if self.pauseBackgroundRefreshes { return } self.gui.c.OnWorker(func(gocui.Task) error { _ = function() done <- struct{}{} return nil }) // waiting so that we don't bunch up refreshes if the refresh takes longer than the // interval, or if a retrigger comes in while we're still processing a timer-based one // (or vice versa) <-done } for { select { case <-ticker.C: doit() case <-retrigger: ticker.Reset(interval) doit() case <-stop: return } } }) return retrigger } func (self *BackgroundRoutineMgr) backgroundFetch() (err error) { err = self.gui.git.Sync.FetchBackground() self.gui.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.COMMITS, types.REMOTES, types.TAGS}, Mode: types.SYNC}) if err == nil { err = self.gui.helpers.BranchesHelper.AutoForwardBranches() } return err } func (self *BackgroundRoutineMgr) triggerImmediateFetch() { if self.triggerFetch != nil { self.triggerFetch <- struct{}{} } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/editors.go
pkg/gui/editors.go
package gui import ( "github.com/jesseduffield/gocui" ) func (gui *Gui) handleEditorKeypress(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier, allowMultiline bool) bool { if key == gocui.KeyEnter && allowMultiline { v.TextArea.TypeCharacter("\n") v.RenderTextArea() return true } return gocui.DefaultEditor.Edit(v, key, ch, mod) } // we've just copy+pasted the editor from gocui to here so that we can also re- // render the commit message length on each keypress func (gui *Gui) commitMessageEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { matched := gui.handleEditorKeypress(v, key, ch, mod, false) v.RenderTextArea() gui.c.Contexts().CommitMessage.RenderSubtitle() return matched } func (gui *Gui) commitDescriptionEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { matched := gui.handleEditorKeypress(v, key, ch, mod, true) v.RenderTextArea() return matched } func (gui *Gui) promptEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { matched := gui.handleEditorKeypress(v, key, ch, mod, false) v.RenderTextArea() suggestionsContext := gui.State.Contexts.Suggestions if suggestionsContext.State.FindSuggestions != nil { input := v.TextArea.GetContent() suggestionsContext.State.AsyncHandler.Do(func() func() { suggestions := suggestionsContext.State.FindSuggestions(input) return func() { suggestionsContext.SetSuggestions(suggestions) } }) } return matched } func (gui *Gui) searchEditor(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { matched := gui.handleEditorKeypress(v, key, ch, mod, false) v.RenderTextArea() searchString := v.TextArea.GetContent() gui.helpers.Search.OnPromptContentChanged(searchString) return matched }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/menu_panel.go
pkg/gui/menu_panel.go
package gui import ( "fmt" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/theme" "github.com/samber/lo" ) // note: items option is mutated by this function func (gui *Gui) createMenu(opts types.CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.c.Tr.Cancel}, OnPress: func() error { return nil }, }) } maxColumnSize := 1 essentialKeys := []types.Key{ keybindings.GetKey(gui.c.UserConfig().Keybinding.Universal.ConfirmMenu), keybindings.GetKey(gui.c.UserConfig().Keybinding.Universal.Return), keybindings.GetKey(gui.c.UserConfig().Keybinding.Universal.PrevItem), keybindings.GetKey(gui.c.UserConfig().Keybinding.Universal.NextItem), } for _, item := range opts.Items { if item.LabelColumns == nil { item.LabelColumns = []string{item.Label} } if item.OpensMenu { item.LabelColumns[0] = fmt.Sprintf("%s...", item.LabelColumns[0]) } maxColumnSize = max(maxColumnSize, len(item.LabelColumns)) // Remove all item keybindings that are the same as one of the essential bindings if !opts.KeepConflictingKeybindings && lo.Contains(essentialKeys, item.Key) { item.Key = nil } } for _, item := range opts.Items { if len(item.LabelColumns) < maxColumnSize { // we require that each item has the same number of columns so we're padding out with blank strings // if this item has too few item.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...) } } gui.State.Contexts.Menu.SetMenuItems(opts.Items, opts.ColumnAlignment) gui.State.Contexts.Menu.SetPrompt(opts.Prompt) gui.State.Contexts.Menu.SetAllowFilteringKeybindings(opts.AllowFilteringKeybindings) gui.State.Contexts.Menu.SetKeybindingsTakePrecedence(!opts.KeepConflictingKeybindings) gui.State.Contexts.Menu.SetSelection(0) gui.Views.Menu.Title = opts.Title gui.Views.Menu.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Wrap = true gui.Views.Tooltip.FgColor = theme.GocuiDefaultTextColor gui.Views.Tooltip.Visible = true // resetting keybindings so that the menu-specific keybindings are registered if err := gui.resetKeybindings(); err != nil { return err } gui.c.PostRefreshUpdate(gui.State.Contexts.Menu) // TODO: ensure that if we're opened a menu from within a menu that it renders correctly gui.c.Context().Push(gui.State.Contexts.Menu, types.OnFocusOpts{}) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/global_handlers.go
pkg/gui/global_handlers.go
package gui import ( "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) const HORIZONTAL_SCROLL_FACTOR = 3 func (gui *Gui) scrollUpView(view *gocui.View) { view.ScrollUp(gui.c.UserConfig().Gui.ScrollHeight) } func (gui *Gui) scrollDownView(view *gocui.View) { scrollHeight := gui.c.UserConfig().Gui.ScrollHeight view.ScrollDown(scrollHeight) if manager := gui.getViewBufferManagerForView(view); manager != nil { manager.ReadLines(scrollHeight) } } func (gui *Gui) scrollUpMain() error { var view *gocui.View if gui.c.Context().Current().GetWindowName() == "secondary" { view = gui.secondaryView() } else { view = gui.mainView() } if view.Name() == "mergeConflicts" { // although we have this same logic in the controller, this method can be invoked // via the global scroll up/down keybindings, as opposed to just the mouse wheel keybinding. // It would be nice to have a concept of a global keybinding that runs on the top context in a // window but that might be overkill for this one use case. gui.State.Contexts.MergeConflicts.SetUserScrolling(true) } gui.scrollUpView(view) return nil } func (gui *Gui) scrollDownMain() error { var view *gocui.View if gui.c.Context().Current().GetWindowName() == "secondary" { view = gui.secondaryView() } else { view = gui.mainView() } if view.Name() == "mergeConflicts" { gui.State.Contexts.MergeConflicts.SetUserScrolling(true) } gui.scrollDownView(view) return nil } func (gui *Gui) mainView() *gocui.View { viewName := gui.helpers.Window.GetViewNameForWindow("main") view, _ := gui.g.View(viewName) return view } func (gui *Gui) secondaryView() *gocui.View { viewName := gui.helpers.Window.GetViewNameForWindow("secondary") view, _ := gui.g.View(viewName) return view } func (gui *Gui) scrollUpSecondary() error { gui.scrollUpView(gui.secondaryView()) return nil } func (gui *Gui) scrollDownSecondary() error { secondaryView := gui.secondaryView() gui.scrollDownView(secondaryView) return nil } func (gui *Gui) scrollUpConfirmationPanel() error { gui.scrollUpView(gui.Views.Confirmation) return nil } func (gui *Gui) scrollDownConfirmationPanel() error { gui.scrollDownView(gui.Views.Confirmation) return nil } func (gui *Gui) pageUpConfirmationPanel() error { gui.Views.Confirmation.ScrollUp(gui.Contexts().Confirmation.GetViewTrait().PageDelta()) return nil } func (gui *Gui) pageDownConfirmationPanel() error { gui.Views.Confirmation.ScrollDown(gui.Contexts().Confirmation.GetViewTrait().PageDelta()) return nil } func (gui *Gui) goToConfirmationPanelTop() error { gui.Views.Confirmation.ScrollUp(gui.Views.Confirmation.ViewLinesHeight()) return nil } func (gui *Gui) goToConfirmationPanelBottom() error { gui.Views.Confirmation.ScrollDown(gui.Views.Confirmation.ViewLinesHeight()) return nil } func (gui *Gui) handleCopySelectedSideContextItemToClipboard() error { return gui.handleCopySelectedSideContextItemToClipboardWithTruncation(-1) } func (gui *Gui) handleCopySelectedSideContextItemCommitHashToClipboard() error { return gui.handleCopySelectedSideContextItemToClipboardWithTruncation( gui.UserConfig().Git.TruncateCopiedCommitHashesTo) } func (gui *Gui) handleCopySelectedSideContextItemToClipboardWithTruncation(maxWidth int) error { // important to note that this assumes we've selected an item in a side context currentSideContext := gui.c.Context().CurrentSide() if currentSideContext == nil { return nil } listContext, ok := currentSideContext.(types.IListContext) if !ok { return nil } itemId := listContext.GetSelectedItemId() if itemId == "" { return nil } if maxWidth > 0 { itemId = itemId[:min(len(itemId), maxWidth)] } gui.c.LogAction(gui.c.Tr.Actions.CopyToClipboard) if err := gui.os.CopyToClipboard(itemId); err != nil { return err } truncatedItemId := utils.TruncateWithEllipsis(strings.ReplaceAll(itemId, "\n", " "), 50) gui.c.Toast(fmt.Sprintf("'%s' %s", truncatedItemId, gui.c.Tr.CopiedToClipboard)) return nil } func (gui *Gui) getCopySelectedSideContextItemToClipboardDisabledReason() *types.DisabledReason { // important to note that this assumes we've selected an item in a side context currentSideContext := gui.c.Context().CurrentSide() if currentSideContext == nil { // This should never happen but if it does we'll just ignore the keypress return nil } listContext, ok := currentSideContext.(types.IListContext) if !ok { // This should never happen but if it does we'll just ignore the keypress return nil } startIdx, endIdx := listContext.GetList().GetSelectionRange() if startIdx != endIdx { return &types.DisabledReason{Text: gui.Tr.RangeSelectNotSupported} } return nil } func (gui *Gui) setCaption(caption string) { gui.Views.Options.FgColor = gocui.ColorWhite gui.Views.Options.FgColor |= gocui.AttrBold gui.Views.Options.SetContent(captionPrefix + " " + style.FgCyan.SetBold().Sprint(caption)) gui.c.Render() } var captionPrefix = "" func (gui *Gui) setCaptionPrefix(prefix string) { gui.Views.Options.FgColor = gocui.ColorWhite gui.Views.Options.FgColor |= gocui.AttrBold captionPrefix = prefix gui.Views.Options.SetContent(prefix) gui.c.Render() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/main_panels.go
pkg/gui/main_panels.go
package gui import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" ) func (gui *Gui) runTaskForView(view *gocui.View, task types.UpdateTask) error { switch v := task.(type) { case *types.RenderStringTask: return gui.newStringTask(view, v.Str) case *types.RenderStringWithoutScrollTask: return gui.newStringTaskWithoutScroll(view, v.Str) case *types.RenderStringWithScrollTask: return gui.newStringTaskWithScroll(view, v.Str, v.OriginX, v.OriginY) case *types.RunCommandTask: return gui.newCmdTask(view, v.Cmd, v.Prefix) case *types.RunPtyTask: return gui.newPtyTask(view, v.Cmd, v.Prefix) } return nil } func (gui *Gui) moveMainContextPairToTop(pair types.MainContextPair) { gui.moveMainContextToTop(pair.Main) if pair.Secondary != nil { gui.moveMainContextToTop(pair.Secondary) } } func (gui *Gui) moveMainContextToTop(context types.Context) { gui.helpers.Window.SetWindowContext(context) view := context.GetView() topView := gui.helpers.Window.TopViewInWindow(context.GetWindowName(), true) if topView != nil && topView != view { // We need to copy the content to avoid a flicker effect: If we're flicking // through files in the files panel, we use a different view to render the // files vs the directories, and if you select dir A, then file B, then dir // C, you'll briefly see dir A's contents again before the view is updated. // So here we're copying the content from the top window to avoid that // flicker effect. gui.g.CopyContent(topView, view) if err := gui.g.SetViewOnTopOf(view.Name(), topView.Name()); err != nil { gui.Log.Error(err) } } } func (gui *Gui) RefreshMainView(opts *types.ViewUpdateOpts, context types.Context) { view := context.GetView() if opts.Title != "" { view.Title = opts.Title } view.Subtitle = opts.SubTitle if err := gui.runTaskForView(view, opts.Task); err != nil { gui.c.Log.Error(err) } } func (gui *Gui) normalMainContextPair() types.MainContextPair { return types.NewMainContextPair( gui.State.Contexts.Normal, gui.State.Contexts.NormalSecondary, ) } func (gui *Gui) stagingMainContextPair() types.MainContextPair { return types.NewMainContextPair( gui.State.Contexts.Staging, gui.State.Contexts.StagingSecondary, ) } func (gui *Gui) patchBuildingMainContextPair() types.MainContextPair { return types.NewMainContextPair( gui.State.Contexts.CustomPatchBuilder, gui.State.Contexts.CustomPatchBuilderSecondary, ) } func (gui *Gui) mergingMainContextPair() types.MainContextPair { return types.NewMainContextPair( gui.State.Contexts.MergeConflicts, nil, ) } func (gui *Gui) allMainContextPairs() []types.MainContextPair { return []types.MainContextPair{ gui.normalMainContextPair(), gui.stagingMainContextPair(), gui.patchBuildingMainContextPair(), gui.mergingMainContextPair(), } } func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) { // need to reset scroll positions of all other main views for _, pair := range gui.allMainContextPairs() { if pair.Main != opts.Pair.Main { pair.Main.GetView().SetOrigin(0, 0) } if pair.Secondary != nil && pair.Secondary != opts.Pair.Secondary { pair.Secondary.GetView().SetOrigin(0, 0) } } if opts.Main != nil { gui.RefreshMainView(opts.Main, opts.Pair.Main) } if opts.Secondary != nil { gui.RefreshMainView(opts.Secondary, opts.Pair.Secondary) } else if opts.Pair.Secondary != nil { opts.Pair.Secondary.GetView().Clear() } gui.moveMainContextPairToTop(opts.Pair) gui.splitMainPanel(opts.Secondary != nil) } func (gui *Gui) splitMainPanel(splitMainPanel bool) { gui.State.SplitMainPanel = splitMainPanel }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/pty_windows.go
pkg/gui/pty_windows.go
package gui import ( "fmt" "os/exec" "github.com/jesseduffield/gocui" ) func (gui *Gui) onResize() error { return nil } func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error { cmd.Env = append(cmd.Env, fmt.Sprintf("LAZYGIT_COLUMNS=%d", view.InnerWidth())) return gui.newCmdTask(view, cmd, prefix) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/context.go
pkg/gui/context.go
package gui import ( "sync" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) // This file is for the management of contexts. There is a context stack such that // for example you might start off in the commits context and then open a menu, putting // you in the menu context. When contexts are activated/deactivated certain things need // to happen like showing/hiding views and rendering content. type ContextMgr struct { ContextStack []types.Context sync.RWMutex gui *Gui allContexts *context.ContextTree } func NewContextMgr( gui *Gui, allContexts *context.ContextTree, ) *ContextMgr { return &ContextMgr{ ContextStack: []types.Context{}, RWMutex: sync.RWMutex{}, gui: gui, allContexts: allContexts, } } // use when you don't want to return to the original context upon // hitting escape: you want to go that context's parent instead. func (self *ContextMgr) Replace(c types.Context) { if !c.IsFocusable() { return } self.Lock() if len(self.ContextStack) == 0 { self.ContextStack = []types.Context{c} } else { // replace the last item with the given item self.ContextStack = append(self.ContextStack[0:len(self.ContextStack)-1], c) } self.Unlock() self.Activate(c, types.OnFocusOpts{}) } func (self *ContextMgr) Push(c types.Context, opts types.OnFocusOpts) { if !c.IsFocusable() { return } contextsToDeactivate, contextToActivate := self.pushToContextStack(c) for _, contextToDeactivate := range contextsToDeactivate { self.deactivate(contextToDeactivate, types.OnFocusLostOpts{NewContextKey: c.GetKey()}) } if contextToActivate != nil { self.Activate(contextToActivate, opts) } } // Adjusts the context stack based on the context that's being pushed and // returns (contexts to deactivate, context to activate) func (self *ContextMgr) pushToContextStack(c types.Context) ([]types.Context, types.Context) { contextsToDeactivate := []types.Context{} self.Lock() defer self.Unlock() if len(self.ContextStack) > 0 && c.GetKey() == self.ContextStack[len(self.ContextStack)-1].GetKey() { // Context being pushed is already on top of the stack: nothing to // deactivate or activate return contextsToDeactivate, nil } if len(self.ContextStack) == 0 { self.ContextStack = append(self.ContextStack, c) } else if c.GetKind() == types.SIDE_CONTEXT { // if we are switching to a side context, remove all other contexts in the stack contextsToDeactivate = lo.Filter(self.ContextStack, func(context types.Context, _ int) bool { return context.GetKey() != c.GetKey() }) self.ContextStack = []types.Context{c} } else if c.GetKind() == types.MAIN_CONTEXT { // if we're switching to a main context, remove all other main contexts in the stack contextsToKeep := []types.Context{} for _, stackContext := range self.ContextStack { if stackContext.GetKind() == types.MAIN_CONTEXT { contextsToDeactivate = append(contextsToDeactivate, stackContext) } else { contextsToKeep = append(contextsToKeep, stackContext) } } self.ContextStack = append(contextsToKeep, c) } else { topContext := self.currentContextWithoutLock() // if we're pushing the same context on, we do nothing. if topContext.GetKey() != c.GetKey() { // if top one is a temporary popup, we remove it. Ideally you'd be able to // escape back to previous temporary popups, but because we're currently reusing // views for this, you might not be able to get back to where you previously were. // The exception is when going to the search context e.g. for searching a menu. if (topContext.GetKind() == types.TEMPORARY_POPUP && c.GetKey() != context.SEARCH_CONTEXT_KEY) || // we only ever want one main context on the stack at a time. (topContext.GetKind() == types.MAIN_CONTEXT && c.GetKind() == types.MAIN_CONTEXT) { contextsToDeactivate = append(contextsToDeactivate, topContext) _, self.ContextStack = utils.Pop(self.ContextStack) } self.ContextStack = append(self.ContextStack, c) } } return contextsToDeactivate, c } func (self *ContextMgr) Pop() { self.Lock() if len(self.ContextStack) == 1 { // cannot escape from bottommost context self.Unlock() return } var currentContext types.Context currentContext, self.ContextStack = utils.Pop(self.ContextStack) newContext := self.ContextStack[len(self.ContextStack)-1] self.Unlock() self.deactivate(currentContext, types.OnFocusLostOpts{NewContextKey: newContext.GetKey()}) self.Activate(newContext, types.OnFocusOpts{}) } func (self *ContextMgr) deactivate(c types.Context, opts types.OnFocusLostOpts) { view, _ := self.gui.c.GocuiGui().View(c.GetViewName()) if opts.NewContextKey != context.SEARCH_CONTEXT_KEY { if c.GetKind() == types.MAIN_CONTEXT || c.GetKind() == types.TEMPORARY_POPUP { self.gui.helpers.Search.CancelSearchIfSearching(c) } } // if we are the kind of context that is sent to back upon deactivation, we should do that if view != nil && (c.GetKind() == types.TEMPORARY_POPUP || c.GetKind() == types.PERSISTENT_POPUP) { view.Visible = false } c.HandleFocusLost(opts) } func (self *ContextMgr) Activate(c types.Context, opts types.OnFocusOpts) { viewName := c.GetViewName() v, err := self.gui.c.GocuiGui().View(viewName) if err != nil { panic(err) } self.gui.helpers.Window.SetWindowContext(c) self.gui.helpers.Window.MoveToTopOfWindow(c) oldView := self.gui.c.GocuiGui().CurrentView() if oldView != nil && oldView.Name() != viewName { oldView.HighlightInactive = true } if _, err := self.gui.c.GocuiGui().SetCurrentView(viewName); err != nil { panic(err) } self.gui.helpers.Search.RenderSearchStatus(c) desiredTitle := c.Title() if desiredTitle != "" { v.Title = desiredTitle } v.Visible = true self.gui.c.GocuiGui().Cursor = v.Editable && v.Mask == "" c.HandleFocus(opts) } func (self *ContextMgr) Current() types.Context { self.RLock() defer self.RUnlock() return self.currentContextWithoutLock() } func (self *ContextMgr) currentContextWithoutLock() types.Context { if len(self.ContextStack) == 0 { return self.gui.defaultSideContext() } return self.ContextStack[len(self.ContextStack)-1] } // Note that this could return the 'status' context which is not itself a list context. func (self *ContextMgr) CurrentSide() types.Context { self.RLock() defer self.RUnlock() stack := self.ContextStack // find the first context in the stack with the type of types.SIDE_CONTEXT for i := range stack { context := stack[len(stack)-1-i] if context.GetKind() == types.SIDE_CONTEXT { return context } } return self.gui.defaultSideContext() } // static as opposed to popup func (self *ContextMgr) CurrentStatic() types.Context { self.RLock() defer self.RUnlock() return self.currentStaticContextWithoutLock() } func (self *ContextMgr) currentStaticContextWithoutLock() types.Context { stack := self.ContextStack if len(stack) == 0 { return self.gui.defaultSideContext() } // find the first context in the stack without a popup type for i := range stack { context := stack[len(stack)-1-i] if context.GetKind() != types.TEMPORARY_POPUP && context.GetKind() != types.PERSISTENT_POPUP { return context } } return self.gui.defaultSideContext() } func (self *ContextMgr) ForEach(f func(types.Context)) { self.RLock() defer self.RUnlock() for _, context := range self.gui.State.ContextMgr.ContextStack { f(context) } } func (self *ContextMgr) IsCurrent(c types.Context) bool { return self.Current().GetKey() == c.GetKey() } func (self *ContextMgr) IsCurrentOrParent(c types.Context) bool { current := self.Current() for current != nil { if current.GetKey() == c.GetKey() { return true } current = current.GetParentContext() } return false } func (self *ContextMgr) AllFilterable() []types.IFilterableContext { var result []types.IFilterableContext for _, context := range self.allContexts.Flatten() { if ctx, ok := context.(types.IFilterableContext); ok { result = append(result, ctx) } } return result } func (self *ContextMgr) AllSearchable() []types.ISearchableContext { var result []types.ISearchableContext for _, context := range self.allContexts.Flatten() { if ctx, ok := context.(types.ISearchableContext); ok { result = append(result, ctx) } } return result } // all list contexts func (self *ContextMgr) AllList() []types.IListContext { var listContexts []types.IListContext for _, context := range self.allContexts.Flatten() { if listContext, ok := context.(types.IListContext); ok { listContexts = append(listContexts, listContext) } } return listContexts } func (self *ContextMgr) AllPatchExplorer() []types.IPatchExplorerContext { var listContexts []types.IPatchExplorerContext for _, context := range self.allContexts.Flatten() { if listContext, ok := context.(types.IPatchExplorerContext); ok { listContexts = append(listContexts, listContext) } } return listContexts } func (self *ContextMgr) ContextForKey(key types.ContextKey) types.Context { self.RLock() defer self.RUnlock() for _, context := range self.allContexts.Flatten() { if context.GetKey() == key { return context } } return nil } func (self *ContextMgr) CurrentPopup() []types.Context { self.RLock() defer self.RUnlock() return lo.Filter(self.ContextStack, func(context types.Context, _ int) bool { return context.GetKind() == types.TEMPORARY_POPUP || context.GetKind() == types.PERSISTENT_POPUP }) } func (self *ContextMgr) NextInStack(c types.Context) types.Context { self.RLock() defer self.RUnlock() for i := range self.ContextStack { if self.ContextStack[i].GetKey() == c.GetKey() { if i == 0 { return nil } return self.ContextStack[i-1] } } panic("context not in stack") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/recent_repos_panel.go
pkg/gui/recent_repos_panel.go
package gui import ( "os" "path/filepath" ) // updateRecentRepoList registers the fact that we opened lazygit in this repo, // so that we can open the same repo via the 'recent repos' menu func (gui *Gui) updateRecentRepoList() error { if gui.git.Status.IsBareRepo() { // we could totally do this but it would require storing both the git-dir and the // worktree in our recent repos list, which is a change that would need to be // backwards compatible gui.c.Log.Info("Not appending bare repo to recent repo list") return nil } recentRepos := gui.c.GetAppState().RecentRepos currentRepo, err := os.Getwd() if err != nil { return err } recentRepos = newRecentReposList(recentRepos, currentRepo) // TODO: migrate this file to use forward slashes on all OSes for consistency // (windows uses backslashes at the moment) gui.c.GetAppState().RecentRepos = recentRepos return gui.c.SaveAppState() } // newRecentReposList returns a new repo list with a new entry but only when it doesn't exist yet func newRecentReposList(recentRepos []string, currentRepo string) []string { newRepos := []string{currentRepo} for _, repo := range recentRepos { if repo != currentRepo { if _, err := os.Stat(filepath.Join(repo, ".git")); err != nil { continue } newRepos = append(newRepos, repo) } } return newRepos }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/gui.go
pkg/gui/gui.go
package gui import ( goContext "context" "errors" "fmt" "io" "os" "path/filepath" "reflect" "regexp" "sort" "strings" "sync" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazycore/pkg/boxlayout" appTypes "github.com/jesseduffield/lazygit/pkg/app/types" "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/git_config" "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/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "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" "github.com/jesseduffield/lazygit/pkg/gui/popup" "github.com/jesseduffield/lazygit/pkg/gui/presentation" "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/services/custom_commands" "github.com/jesseduffield/lazygit/pkg/gui/status" "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/integration/components" integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types" "github.com/jesseduffield/lazygit/pkg/tasks" "github.com/jesseduffield/lazygit/pkg/theme" "github.com/jesseduffield/lazygit/pkg/updates" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" "github.com/sasha-s/go-deadlock" "gopkg.in/ozeidan/fuzzy-patricia.v3/patricia" ) const StartupPopupVersion = 5 // OverlappingEdges determines if panel edges overlap var OverlappingEdges = false type Repo string // Gui wraps the gocui Gui object which handles rendering and events type Gui struct { *common.Common g *gocui.Gui gitVersion *git_commands.GitVersion git *commands.GitCommand os *oscommands.OSCommand // this is the state of the GUI for the current repo State *GuiRepoState pagerConfig *config.PagerConfig CustomCommandsClient *custom_commands.Client // this is a mapping of repos to gui states, so that we can restore the original // gui state when returning from a subrepo. // In repos with multiple worktrees, we store a separate repo state per worktree. RepoStateMap map[Repo]*GuiRepoState Config config.AppConfigurer Updater *updates.Updater statusManager *status.StatusManager waitForIntro sync.WaitGroup viewBufferManagerMap map[string]*tasks.ViewBufferManager // holds a mapping of view names to ptmx's. This is for rendering command outputs // from within a pty. The point of keeping track of them is so that if we re-size // the window, we can tell the pty it needs to resize accordingly. viewPtmxMap map[string]*os.File stopChan chan struct{} // when lazygit is opened outside a git directory we want to open to the most // recent repo with the recent repos popup showing showRecentRepos bool Mutexes types.Mutexes // when you enter into a submodule we'll append the superproject's path to this array // so that you can return to the superproject RepoPathStack *utils.StringStack // this tells us whether our views have been initially set up ViewsSetup bool Views types.Views // Log of the commands/actions logged in the Command Log panel. GuiLog []string // the extras window contains things like the command log ShowExtrasWindow bool PopupHandler types.IPopupHandler IsRefreshingFiles bool // we use this to decide whether we'll return to the original directory that // lazygit was opened in, or if we'll retain the one we're currently in. RetainOriginalDir bool // stores long-running operations associated with items (e.g. when a branch // is being pushed). At the moment the rule is to use an item operation when // we need to talk to the remote. itemOperations map[string]types.ItemOperation itemOperationsMutex deadlock.Mutex PrevLayout PrevLayout // this is the initial dir we are in upon opening lazygit. We hold onto this // in case we want to restore it before quitting for users who have set up // the feature for changing directory upon quit. // The reason we don't just wait until quit time to handle changing directories // is because some users want to keep track of the current lazygit directory in an outside // process InitialDir string BackgroundRoutineMgr *BackgroundRoutineMgr // for accessing the gui's state from outside this package stateAccessor *StateAccessor Updating bool c *helpers.HelperCommon helpers *helpers.Helpers previousLanguageConfig string integrationTest integrationTypes.IntegrationTest afterLayoutFuncs chan func() error } type StateAccessor struct { gui *Gui } var _ types.IStateAccessor = new(StateAccessor) func (self *StateAccessor) GetRepoPathStack() *utils.StringStack { return self.gui.RepoPathStack } func (self *StateAccessor) GetUpdating() bool { return self.gui.Updating } func (self *StateAccessor) SetUpdating(value bool) { self.gui.Updating = value } func (self *StateAccessor) GetRepoState() types.IRepoStateAccessor { return self.gui.State } func (self *StateAccessor) GetPagerConfig() *config.PagerConfig { return self.gui.pagerConfig } func (self *StateAccessor) GetIsRefreshingFiles() bool { return self.gui.IsRefreshingFiles } func (self *StateAccessor) SetIsRefreshingFiles(value bool) { self.gui.IsRefreshingFiles = value } func (self *StateAccessor) GetShowExtrasWindow() bool { return self.gui.ShowExtrasWindow } func (self *StateAccessor) SetShowExtrasWindow(value bool) { self.gui.ShowExtrasWindow = value } func (self *StateAccessor) GetRetainOriginalDir() bool { return self.gui.RetainOriginalDir } func (self *StateAccessor) SetRetainOriginalDir(value bool) { self.gui.RetainOriginalDir = value } func (self *StateAccessor) GetItemOperation(item types.HasUrn) types.ItemOperation { self.gui.itemOperationsMutex.Lock() defer self.gui.itemOperationsMutex.Unlock() return self.gui.itemOperations[item.URN()] } func (self *StateAccessor) SetItemOperation(item types.HasUrn, operation types.ItemOperation) { self.gui.itemOperationsMutex.Lock() defer self.gui.itemOperationsMutex.Unlock() self.gui.itemOperations[item.URN()] = operation } func (self *StateAccessor) ClearItemOperation(item types.HasUrn) { self.gui.itemOperationsMutex.Lock() defer self.gui.itemOperationsMutex.Unlock() delete(self.gui.itemOperations, item.URN()) } // we keep track of some stuff from one render to the next to see if certain // things have changed type PrevLayout struct { Information string MainWidth int MainHeight int } type GuiRepoState struct { Model *types.Model Modes *types.Modes SplitMainPanel bool SearchState *types.SearchState StartupStage types.StartupStage // Allows us to not load everything at once ContextMgr *ContextMgr Contexts *context.ContextTree // WindowViewNameMap is a mapping of windows to the current view of that window. // Some views move between windows for example the commitFiles view and when cycling through // side windows we need to know which view to give focus to for a given window WindowViewNameMap *utils.ThreadSafeMap[string, string] // tells us whether we've set up our views for the current repo. We'll need to // do this whenever we switch back and forth between repos to get the views // back in sync with the repo state ViewsSetup bool ScreenMode types.ScreenMode CurrentPopupOpts *types.CreatePopupPanelOpts LastBackgroundFetchTime time.Time } var _ types.IRepoStateAccessor = new(GuiRepoState) func (self *GuiRepoState) GetViewsSetup() bool { return self.ViewsSetup } func (self *GuiRepoState) GetWindowViewNameMap() *utils.ThreadSafeMap[string, string] { return self.WindowViewNameMap } func (self *GuiRepoState) GetStartupStage() types.StartupStage { return self.StartupStage } func (self *GuiRepoState) SetStartupStage(value types.StartupStage) { self.StartupStage = value } func (self *GuiRepoState) GetCurrentPopupOpts() *types.CreatePopupPanelOpts { return self.CurrentPopupOpts } func (self *GuiRepoState) SetCurrentPopupOpts(value *types.CreatePopupPanelOpts) { self.CurrentPopupOpts = value } func (self *GuiRepoState) GetScreenMode() types.ScreenMode { return self.ScreenMode } func (self *GuiRepoState) SetScreenMode(value types.ScreenMode) { self.ScreenMode = value } func (self *GuiRepoState) InSearchPrompt() bool { return self.SearchState.SearchType() != types.SearchTypeNone } func (self *GuiRepoState) GetSearchState() *types.SearchState { return self.SearchState } func (self *GuiRepoState) SetSplitMainPanel(value bool) { self.SplitMainPanel = value } func (self *GuiRepoState) GetSplitMainPanel() bool { return self.SplitMainPanel } func (gui *Gui) onSwitchToNewRepo(startArgs appTypes.StartArgs, contextKey types.ContextKey) error { err := gui.onNewRepo(startArgs, contextKey) if err == nil && gui.UserConfig().Git.AutoFetch && gui.UserConfig().Refresher.FetchInterval > 0 { if time.Since(gui.State.LastBackgroundFetchTime) > gui.UserConfig().Refresher.FetchIntervalDuration() { gui.BackgroundRoutineMgr.triggerImmediateFetch() } } return err } func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.ContextKey) error { var err error gui.git, err = commands.NewGitCommand( gui.Common, gui.gitVersion, gui.os, git_config.NewStdCachedGitConfig(gui.Log), gui.pagerConfig, ) if err != nil { return err } err = gui.Config.ReloadUserConfigForRepo(gui.getPerRepoConfigFiles()) if err != nil { return err } err = gui.onUserConfigLoaded() if err != nil { return err } contextToPush := gui.resetState(startArgs) gui.resetHelpersAndControllers() if err := gui.resetKeybindings(); err != nil { return err } gui.g.SetFocusHandler(func(Focused bool) error { if Focused { gui.git.Config.DropConfigCache() oldConfig := gui.Config.GetUserConfig() reloadErr, didChange := gui.Config.ReloadChangedUserConfigFiles() if didChange && reloadErr == nil { gui.c.Log.Info("User config changed - reloading") reloadErr = gui.onUserConfigLoaded() if err := gui.resetKeybindings(); err != nil { return err } if err := gui.checkForChangedConfigsThatDontAutoReload(oldConfig, gui.Config.GetUserConfig()); err != nil { return err } } gui.c.Log.Info("Receiving focus - refreshing") gui.helpers.Refresh.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return reloadErr } return nil }) gui.g.SetOpenHyperlinkFunc(func(url string, viewname string) error { if strings.HasPrefix(url, "lazygit-edit:") { re := regexp.MustCompile(`^lazygit-edit://(.+?)(?::(\d+))?$`) matches := re.FindStringSubmatch(url) if matches == nil { return fmt.Errorf(gui.Tr.InvalidLazygitEditURL, url) } filepath := matches[1] if matches[2] != "" { lineNumber := utils.MustConvertToInt(matches[2]) lineNumber = gui.helpers.Diff.AdjustLineNumber(filepath, lineNumber, viewname) return gui.helpers.Files.EditFileAtLine(filepath, lineNumber) } return gui.helpers.Files.EditFiles([]string{filepath}) } if err := gui.os.OpenLink(url); err != nil { return fmt.Errorf(gui.Tr.FailedToOpenURL, url, err) } return nil }) // if a context key has been given, push that instead, and set its index to 0 if contextKey != context.NO_CONTEXT { contextToPush = gui.c.ContextForKey(contextKey) // when we pass a list context, the expectation is that our cursor goes to the top, // because e.g. with worktrees, we'll show the current worktree at the top of the list. listContext, ok := contextToPush.(types.IListContext) if ok { listContext.GetList().SetSelection(0) } } gui.c.Context().Push(contextToPush, types.OnFocusOpts{}) return nil } func (gui *Gui) getPerRepoConfigFiles() []*config.ConfigFile { repoConfigFiles := []*config.ConfigFile{ // TODO: add filepath.Join(gui.git.RepoPaths.RepoPath(), ".lazygit.yml"), // with trust prompt { Path: filepath.Join(gui.git.RepoPaths.RepoGitDirPath(), "lazygit.yml"), Policy: config.ConfigFilePolicySkipIfMissing, }, } prevDir := gui.c.Git().RepoPaths.RepoPath() dir := filepath.Dir(prevDir) for dir != prevDir { repoConfigFiles = utils.Prepend(repoConfigFiles, &config.ConfigFile{ Path: filepath.Join(dir, ".lazygit.yml"), Policy: config.ConfigFilePolicySkipIfMissing, }) prevDir = dir dir = filepath.Dir(dir) } return repoConfigFiles } func (gui *Gui) onUserConfigLoaded() error { userConfig := gui.Config.GetUserConfig() gui.Common.SetUserConfig(userConfig) if gui.previousLanguageConfig != userConfig.Gui.Language { tr, err := i18n.NewTranslationSetFromConfig(gui.Log, userConfig.Gui.Language) if err != nil { return err } gui.c.Tr = tr gui.previousLanguageConfig = userConfig.Gui.Language } gui.setColorScheme() gui.configureViewProperties() gui.g.SearchEscapeKey = keybindings.GetKey(userConfig.Keybinding.Universal.Return) gui.g.NextSearchMatchKey = keybindings.GetKey(userConfig.Keybinding.Universal.NextMatch) gui.g.PrevSearchMatchKey = keybindings.GetKey(userConfig.Keybinding.Universal.PrevMatch) gui.g.ShowListFooter = userConfig.Gui.ShowListFooter gui.g.Mouse = userConfig.Gui.MouseEvents // originally we could only hide the command log permanently via the config // but now we do it via state. So we need to still support the config for the // sake of backwards compatibility. We're making use of short circuiting here gui.ShowExtrasWindow = userConfig.Gui.ShowCommandLog && !gui.c.GetAppState().HideCommandLog authors.SetCustomAuthors(userConfig.Gui.AuthorColors) if userConfig.Gui.NerdFontsVersion != "" { icons.SetNerdFontsVersion(userConfig.Gui.NerdFontsVersion) } else if userConfig.Gui.ShowIcons { icons.SetNerdFontsVersion("2") } if len(userConfig.Gui.BranchColorPatterns) > 0 { presentation.SetCustomBranches(userConfig.Gui.BranchColorPatterns, true) } else { // Fall back to the deprecated branchColors config presentation.SetCustomBranches(userConfig.Gui.BranchColors, false) } return nil } func (gui *Gui) checkForChangedConfigsThatDontAutoReload(oldConfig *config.UserConfig, newConfig *config.UserConfig) error { configsThatDontAutoReload := []string{ "Git.AutoFetch", "Git.AutoRefresh", "Refresher.RefreshInterval", "Refresher.FetchInterval", "Update.Method", "Update.Days", } changedConfigs := []string{} for _, config := range configsThatDontAutoReload { old := reflect.ValueOf(oldConfig).Elem() new := reflect.ValueOf(newConfig).Elem() fieldNames := strings.Split(config, ".") userFacingPath := make([]string, 0, len(fieldNames)) // navigate to the leaves in old and new config for _, fieldName := range fieldNames { f, _ := old.Type().FieldByName(fieldName) userFacingName := f.Tag.Get("yaml") if userFacingName == "" { userFacingName = fieldName } userFacingPath = append(userFacingPath, userFacingName) old = old.FieldByName(fieldName) new = new.FieldByName(fieldName) } // if the value has changed, ... if !old.Equal(new) { // ... append it to the list of changed configs changedConfigs = append(changedConfigs, strings.Join(userFacingPath, ".")) } } if len(changedConfigs) == 0 { return nil } message := utils.ResolvePlaceholderString( gui.c.Tr.NonReloadableConfigWarning, map[string]string{ "configs": strings.Join(changedConfigs, "\n"), }, ) gui.c.Confirm(types.ConfirmOpts{ Title: gui.c.Tr.NonReloadableConfigWarningTitle, Prompt: message, }) return nil } // resetState reuses the repo state from our repo state map, if the repo was // open before; otherwise it creates a new one. func (gui *Gui) resetState(startArgs appTypes.StartArgs) types.Context { // Un-highlight the current view if there is one. The reason we do this is // that the repo we are switching to might have a different view focused, // and would then show an inactive highlight for the previous view. if oldCurrentView := gui.g.CurrentView(); oldCurrentView != nil { oldCurrentView.Highlight = false } worktreePath := gui.git.RepoPaths.WorktreePath() if state := gui.RepoStateMap[Repo(worktreePath)]; state != nil { gui.State = state gui.State.ViewsSetup = false contextTree := gui.State.Contexts gui.State.WindowViewNameMap = initialWindowViewNameMap(contextTree) // setting this to nil so we don't get stuck based on a popup that was // previously opened gui.Mutexes.PopupMutex.Lock() gui.State.CurrentPopupOpts = nil gui.Mutexes.PopupMutex.Unlock() return gui.c.Context().Current() } contextTree := gui.contextTree() initialScreenMode := initialScreenMode(startArgs, gui.Config) gui.State = &GuiRepoState{ ViewsSetup: false, Model: &types.Model{ CommitFiles: nil, Files: make([]*models.File, 0), Commits: make([]*models.Commit, 0), StashEntries: make([]*models.StashEntry, 0), FilteredReflogCommits: make([]*models.Commit, 0), ReflogCommits: make([]*models.Commit, 0), BisectInfo: git_commands.NewNullBisectInfo(), FilesTrie: patricia.NewTrie(), Authors: map[string]*models.Author{}, MainBranches: git_commands.NewMainBranches(gui.c.Common, gui.os.Cmd), HashPool: &utils.StringPool{}, }, Modes: &types.Modes{ Filtering: filtering.New(startArgs.FilterPath, ""), CherryPicking: cherrypicking.New(), Diffing: diffing.New(), MarkedBaseCommit: marked_base_commit.New(), }, ScreenMode: initialScreenMode, // TODO: only use contexts from context manager ContextMgr: NewContextMgr(gui, contextTree), Contexts: contextTree, WindowViewNameMap: initialWindowViewNameMap(contextTree), SearchState: types.NewSearchState(), } gui.RepoStateMap[Repo(worktreePath)] = gui.State return initialContext(contextTree, startArgs) } func (gui *Gui) getViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager { manager, ok := gui.viewBufferManagerMap[view.Name()] if !ok { return nil } return manager } func initialWindowViewNameMap(contextTree *context.ContextTree) *utils.ThreadSafeMap[string, string] { result := utils.NewThreadSafeMap[string, string]() for _, context := range contextTree.Flatten() { result.Set(context.GetWindowName(), context.GetViewName()) } return result } func initialScreenMode(startArgs appTypes.StartArgs, config config.AppConfigurer) types.ScreenMode { if startArgs.ScreenMode != "" { return parseScreenModeArg(startArgs.ScreenMode) } else if startArgs.FilterPath != "" || startArgs.GitArg != appTypes.GitArgNone { return types.SCREEN_HALF } return parseScreenModeArg(config.GetUserConfig().Gui.ScreenMode) } func parseScreenModeArg(screenModeArg string) types.ScreenMode { switch screenModeArg { case "half": return types.SCREEN_HALF case "full": return types.SCREEN_FULL default: return types.SCREEN_NORMAL } } func initialContext(contextTree *context.ContextTree, startArgs appTypes.StartArgs) types.IListContext { var initialContext types.IListContext = contextTree.Files if startArgs.FilterPath != "" { initialContext = contextTree.LocalCommits } else if startArgs.GitArg != appTypes.GitArgNone { switch startArgs.GitArg { case appTypes.GitArgStatus: initialContext = contextTree.Files case appTypes.GitArgBranch: initialContext = contextTree.Branches case appTypes.GitArgLog: initialContext = contextTree.LocalCommits case appTypes.GitArgStash: initialContext = contextTree.Stash default: panic("unhandled git arg") } } return initialContext } func (gui *Gui) Contexts() *context.ContextTree { return gui.State.Contexts } // for now the split view will always be on // NewGui builds a new gui handler func NewGui( cmn *common.Common, configurer config.AppConfigurer, gitVersion *git_commands.GitVersion, updater *updates.Updater, showRecentRepos bool, initialDir string, test integrationTypes.IntegrationTest, ) (*Gui, error) { gui := &Gui{ Common: cmn, gitVersion: gitVersion, Config: configurer, Updater: updater, statusManager: status.NewStatusManager(), viewBufferManagerMap: map[string]*tasks.ViewBufferManager{}, viewPtmxMap: map[string]*os.File{}, showRecentRepos: showRecentRepos, RepoPathStack: &utils.StringStack{}, RepoStateMap: map[Repo]*GuiRepoState{}, GuiLog: []string{}, // initializing this to true for the time being; it will be reset to the // real value after loading the user config: ShowExtrasWindow: true, InitialDir: initialDir, afterLayoutFuncs: make(chan func() error, 1000), itemOperations: make(map[string]types.ItemOperation), } gui.PopupHandler = popup.NewPopupHandler( cmn, func(ctx goContext.Context, opts types.CreatePopupPanelOpts) { gui.helpers.Confirmation.CreatePopupPanel(ctx, opts) }, func() error { gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}); return nil }, func() { gui.State.ContextMgr.Pop() }, func() types.Context { return gui.State.ContextMgr.Current() }, gui.createMenu, func(message string, f func(gocui.Task) error) { gui.helpers.AppStatus.WithWaitingStatus(message, f) }, func(message string, f func() error) error { return gui.helpers.AppStatus.WithWaitingStatusSync(message, f) }, func(message string, kind types.ToastKind) { gui.helpers.AppStatus.Toast(message, kind) }, func() string { return gui.Views.Prompt.TextArea.GetContent() }, func() bool { return gui.c.InDemo() }, ) guiCommon := &guiCommon{gui: gui, IPopupHandler: gui.PopupHandler} helperCommon := &helpers.HelperCommon{IGuiCommon: guiCommon, Common: cmn, IGetContexts: gui} credentialsHelper := helpers.NewCredentialsHelper(helperCommon) guiIO := oscommands.NewGuiIO( cmn.Log, gui.LogCommand, gui.getCmdWriter, credentialsHelper.PromptUserForCredential, ) osCommand := oscommands.NewOSCommand(cmn, configurer, oscommands.GetPlatform(), guiIO) gui.os = osCommand // storing this stuff on the gui for now to ease refactoring // TODO: reset these controllers upon changing repos due to state changing gui.c = helperCommon gui.BackgroundRoutineMgr = &BackgroundRoutineMgr{gui: gui} gui.stateAccessor = &StateAccessor{gui: gui} gui.pagerConfig = config.NewPagerConfig(func() *config.UserConfig { return gui.UserConfig() }) return gui, nil } var RuneReplacements = map[rune]string{ // for the commit graph graph.MergeSymbol: "M", graph.CommitSymbol: "o", } func (gui *Gui) initGocui(headless bool, test integrationTypes.IntegrationTest) (*gocui.Gui, error) { runInSandbox := os.Getenv(components.SANDBOX_ENV_VAR) == "true" playRecording := test != nil && !runInSandbox width, height := 0, 0 if test != nil { if test.RequiresHeadless() { if runInSandbox { panic("Test requires headless, can't run in sandbox") } headless = true } width, height = test.HeadlessDimensions() } g, err := gocui.NewGui(gocui.NewGuiOpts{ OutputMode: gocui.OutputTrue, SupportOverlaps: OverlappingEdges, PlayRecording: playRecording, Headless: headless, RuneReplacements: RuneReplacements, Width: width, Height: height, }) if err != nil { return nil, err } return g, nil } func (gui *Gui) viewTabMap() map[string][]context.TabView { result := map[string][]context.TabView{ "branches": { { Tab: gui.c.Tr.LocalBranchesTitle, ViewName: "localBranches", }, { Tab: gui.c.Tr.RemotesTitle, ViewName: "remotes", }, { Tab: gui.c.Tr.TagsTitle, ViewName: "tags", }, }, "commits": { { Tab: gui.c.Tr.CommitsTitle, ViewName: "commits", }, { Tab: gui.c.Tr.ReflogCommitsTitle, ViewName: "reflogCommits", }, }, "files": { { Tab: gui.c.Tr.FilesTitle, ViewName: "files", }, context.TabView{ Tab: gui.c.Tr.WorktreesTitle, ViewName: "worktrees", }, { Tab: gui.c.Tr.SubmodulesTitle, ViewName: "submodules", }, }, } return result } // Run: setup the gui with keybindings and start the mainloop func (gui *Gui) Run(startArgs appTypes.StartArgs) error { g, err := gui.initGocui(Headless(), startArgs.IntegrationTest) if err != nil { return err } gui.g = g defer gui.g.Close() g.ErrorHandler = gui.PopupHandler.ErrorHandler // if the deadlock package wants to report a deadlock, we first need to // close the gui so that we can actually read what it prints. deadlock.Opts.LogBuf = utils.NewOnceWriter(os.Stderr, func() { gui.g.Close() }) // disable deadlock reporting if we're not running in debug mode, or if // we're debugging an integration test. In this latter case, stopping at // breakpoints and stepping through code can easily take more than 30s. deadlock.Opts.Disable = !gui.Debug || os.Getenv(components.WAIT_FOR_DEBUGGER_ENV_VAR) != "" gui.g.OnSearchEscape = func() error { gui.helpers.Search.Cancel(); return nil } gui.g.SetManager(gocui.ManagerFunc(gui.layout)) if err := gui.createAllViews(); err != nil { return err } // onNewRepo must be called after g.SetManager because SetManager deletes keybindings if err := gui.onNewRepo(startArgs, context.NO_CONTEXT); err != nil { return err } gui.waitForIntro.Add(1) gui.BackgroundRoutineMgr.startBackgroundRoutines() gui.Helpers().SuspendResume.InstallResumeSignalHandler() gui.c.Log.Info("starting main loop") // setting here so we can use it in layout.go gui.integrationTest = startArgs.IntegrationTest return gui.g.MainLoop() } func (gui *Gui) RunAndHandleError(startArgs appTypes.StartArgs) error { gui.stopChan = make(chan struct{}) return utils.SafeWithError(func() error { if err := gui.Run(startArgs); err != nil { for _, manager := range gui.viewBufferManagerMap { manager.Close() } close(gui.stopChan) if errors.Is(err, gocui.ErrQuit) { if gui.c.State().GetRetainOriginalDir() { if err := gui.helpers.RecordDirectory.RecordDirectory(gui.InitialDir); err != nil { return err } } else { if err := gui.helpers.RecordDirectory.RecordCurrentDirectory(); err != nil { return err } } return nil } return err } return nil }) } // returns whether command exited without error or not func (gui *Gui) runSubprocessWithSuspenseAndRefresh(subprocess *oscommands.CmdObj) error { _, err := gui.runSubprocessWithSuspense(subprocess) if err != nil { return err } gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) return nil } func (gui *Gui) suspend() error { if err := gui.g.Suspend(); err != nil { return err } gui.BackgroundRoutineMgr.PauseBackgroundRefreshes(true) return nil } func (gui *Gui) resume() error { if err := gui.g.Resume(); err != nil { return err } gui.BackgroundRoutineMgr.PauseBackgroundRefreshes(false) return nil } // returns whether command exited without error or not func (gui *Gui) runSubprocessWithSuspense(subprocess *oscommands.CmdObj) (bool, error) { gui.Mutexes.SubprocessMutex.Lock() defer gui.Mutexes.SubprocessMutex.Unlock() if err := gui.suspend(); err != nil { return false, err } cmdErr := gui.runSubprocess(subprocess) if err := gui.resume(); err != nil { return false, err } if cmdErr != nil { return false, cmdErr } return true, nil } func (gui *Gui) runSubprocess(cmdObj *oscommands.CmdObj) error { gui.LogCommand(cmdObj.ToString(), true) subprocess := cmdObj.GetCmd() subprocess.Stdout = os.Stdout subprocess.Stderr = os.Stderr subprocess.Stdin = os.Stdin fmt.Fprintf(os.Stdout, "\n%s\n\n", style.FgBlue.Sprint("+ "+strings.Join(subprocess.Args, " "))) err := subprocess.Run() subprocess.Stdout = io.Discard subprocess.Stderr = io.Discard subprocess.Stdin = nil if gui.integrationTest == nil && (gui.Config.GetUserConfig().PromptToReturnFromSubprocess || err != nil) { fmt.Fprintf(os.Stdout, "\n%s", style.FgGreen.Sprint(gui.Tr.PressEnterToReturn)) // scan to buffer to prevent run unintentional operations when TUI resumes. var buffer string _, _ = fmt.Scanln(&buffer) // wait for enter press } return err } func (gui *Gui) loadNewRepo() error { if err := gui.updateRecentRepoList(); err != nil { return err } gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) if err := gui.os.UpdateWindowTitle(); err != nil { return err } return nil } func (gui *Gui) showIntroPopupMessage() { gui.waitForIntro.Add(1) gui.c.OnUIThread(func() error { onConfirm := func() error { gui.c.GetAppState().StartupPopupVersion = StartupPopupVersion err := gui.c.SaveAppState() gui.waitForIntro.Done() return err } introMessage := utils.ResolvePlaceholderString( gui.c.Tr.IntroPopupMessage, map[string]string{ "confirmationKey": gui.c.UserConfig().Keybinding.Universal.Confirm, }, ) gui.c.Confirm(types.ConfirmOpts{ Title: "", Prompt: introMessage, HandleConfirm: onConfirm, HandleClose: onConfirm, }) return nil }) } func (gui *Gui) showBreakingChangesMessage() { _, err := types.ParseVersionNumber(gui.Config.GetVersion()) if err != nil { // We don't have a parseable version, so we'll assume it's a developer // build, or a build from HEAD with a version such as 0.40.0-g1234567; // in these cases we don't show release notes. return } last := &types.VersionNumber{} lastVersionStr := gui.c.GetAppState().LastVersion // If there's no saved last version, we show all release notes. This is for // people upgrading from a version before we started to save lastVersion. // First time new users won't see the release notes because we show them the // intro popup instead. if lastVersionStr != "" { last, err = types.ParseVersionNumber(lastVersionStr) if err != nil { // The last version was a developer build, so don't show release // notes in this case either. return } } // Now collect all release notes texts for versions newer than lastVersion. // We don't need to bother checking the current version here, because we // can't possibly have texts for versions newer than current. type versionAndText struct { version *types.VersionNumber text string } texts := []versionAndText{} for versionStr, text := range gui.Tr.BreakingChangesByVersion { v, err := types.ParseVersionNumber(versionStr) if err != nil { // Ignore bogus entries in the BreakingChanges map continue } if last.IsOlderThan(v) { texts = append(texts, versionAndText{version: v, text: text}) } } if len(texts) > 0 { sort.Slice(texts, func(i, j int) bool { return texts[i].version.IsOlderThan(texts[j].version) }) message := strings.Join(lo.Map(texts, func(t versionAndText, _ int) string { return t.text }), "\n") gui.waitForIntro.Add(1) gui.c.OnUIThread(func() error { onConfirm := func() error { gui.waitForIntro.Done() return nil } gui.c.Confirm(types.ConfirmOpts{ Title: gui.Tr.BreakingChangesTitle, Prompt: gui.Tr.BreakingChangesMessage + "\n\n" + message, HandleConfirm: onConfirm, HandleClose: onConfirm, }) return nil }) } } // setColorScheme sets the color scheme for the app based on the user config func (gui *Gui) setColorScheme() { userConfig := gui.UserConfig() theme.UpdateTheme(userConfig.Gui.Theme) gui.g.FgColor = theme.InactiveBorderColor gui.g.SelFgColor = theme.ActiveBorderColor gui.g.FrameColor = theme.InactiveBorderColor gui.g.SelFrameColor = theme.ActiveBorderColor } func (gui *Gui) onUIThread(f func() error) { gui.g.Update(func(*gocui.Gui) error { return f() }) } func (gui *Gui) onWorker(f func(gocui.Task) error) { gui.g.OnWorker(f) } func (gui *Gui) getWindowDimensions(informationStr string, appStatus string) map[string]boxlayout.Dimensions { return gui.helpers.WindowArrangement.GetWindowDimensions(informationStr, appStatus) } func (gui *Gui) afterLayout(f func() error) {
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/menu_generator.go
pkg/gui/services/custom_commands/menu_generator.go
package custom_commands import ( "bytes" "errors" "regexp" "strconv" "strings" "text/template" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/style" ) type MenuGenerator struct { c *common.Common } // takes the output of a command and returns a list of menu entries based on a filter // and value/label format templates provided by the user func NewMenuGenerator(c *common.Common) *MenuGenerator { return &MenuGenerator{c: c} } type commandMenuItem struct { label string value string } func (self *MenuGenerator) call(commandOutput, filter, valueFormat, labelFormat string) ([]*commandMenuItem, error) { menuItemFromLine, err := self.getMenuItemFromLinefn(filter, valueFormat, labelFormat) if err != nil { return nil, err } menuItems := []*commandMenuItem{} for line := range strings.SplitSeq(commandOutput, "\n") { if line == "" { continue } menuItem, err := menuItemFromLine(line) if err != nil { return nil, err } menuItems = append(menuItems, menuItem) } return menuItems, nil } func (self *MenuGenerator) getMenuItemFromLinefn(filter string, valueFormat string, labelFormat string) (func(line string) (*commandMenuItem, error), error) { if filter == "" && valueFormat == "" && labelFormat == "" { // showing command output lines as-is in suggestions panel return func(line string) (*commandMenuItem, error) { return &commandMenuItem{label: line, value: line}, nil }, nil } regex, err := regexp.Compile(filter) if err != nil { return nil, errors.New("unable to parse filter regex, error: " + err.Error()) } valueTemplateAux, err := template.New("format").Parse(valueFormat) if err != nil { return nil, errors.New("unable to parse value format, error: " + err.Error()) } valueTemplate := NewTrimmerTemplate(valueTemplateAux) var labelTemplate *TrimmerTemplate if labelFormat != "" { colorFuncMap := style.TemplateFuncMapAddColors(template.FuncMap{}) labelTemplateAux, err := template.New("format").Funcs(colorFuncMap).Parse(labelFormat) if err != nil { return nil, errors.New("unable to parse label format, error: " + err.Error()) } labelTemplate = NewTrimmerTemplate(labelTemplateAux) } else { labelTemplate = valueTemplate } return func(line string) (*commandMenuItem, error) { return self.generateMenuItem( line, regex, valueTemplate, labelTemplate, ) }, nil } func (self *MenuGenerator) generateMenuItem( line string, regex *regexp.Regexp, valueTemplate *TrimmerTemplate, labelTemplate *TrimmerTemplate, ) (*commandMenuItem, error) { tmplData := self.parseLine(line, regex) entry := &commandMenuItem{} var err error entry.value, err = valueTemplate.execute(tmplData) if err != nil { return nil, err } entry.label, err = labelTemplate.execute(tmplData) if err != nil { return nil, err } return entry, nil } func (self *MenuGenerator) parseLine(line string, regex *regexp.Regexp) map[string]string { tmplData := map[string]string{} out := regex.FindAllStringSubmatch(line, -1) if len(out) > 0 { for groupIdx, group := range regex.SubexpNames() { // Record matched group with group ids matchName := "group_" + strconv.Itoa(groupIdx) tmplData[matchName] = out[0][groupIdx] // Record last named group non-empty matches as group matches if group != "" { tmplData[group] = out[0][groupIdx] } } } return tmplData } // wrapper around a template which trims the output type TrimmerTemplate struct { template *template.Template buffer *bytes.Buffer } func NewTrimmerTemplate(template *template.Template) *TrimmerTemplate { return &TrimmerTemplate{ template: template, buffer: bytes.NewBuffer(nil), } } func (self *TrimmerTemplate) execute(tmplData map[string]string) (string, error) { self.buffer.Reset() err := self.template.Execute(self.buffer, tmplData) if err != nil { return "", err } return strings.TrimSpace(self.buffer.String()), nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/models.go
pkg/gui/services/custom_commands/models.go
package custom_commands import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/stefanhaller/git-todo-parser/todo" ) // We create shims for all the model classes in order to get a more stable API // for custom commands. At the moment these are almost identical to the model // classes, but this allows us to add "private" fields to the model classes that // we don't want to expose to custom commands, or rename a model field to a // better name without breaking people's custom commands. In such a case we add // the new, better name to the shim but keep the old one for backwards // compatibility. We already did this for Commit.Sha, which was renamed to Hash. type Commit struct { Hash string Sha string // deprecated: use Hash Name string Status models.CommitStatus Action todo.TodoCommand Tags []string ExtraInfo string AuthorName string AuthorEmail string UnixTimestamp int64 Divergence models.Divergence Parents []string } type File struct { Name string PreviousName string HasStagedChanges bool HasUnstagedChanges bool Tracked bool Added bool Deleted bool HasMergeConflicts bool HasInlineMergeConflicts bool DisplayString string ShortStatus string IsWorktree bool } type Submodule struct { Name string Path string Url string } type Branch struct { Name string DisplayName string Recency string Pushables string // deprecated: use AheadForPull Pullables string // deprecated: use BehindForPull AheadForPull string BehindForPull string AheadForPush string BehindForPush string UpstreamGone bool Head bool DetachedHead bool UpstreamRemote string UpstreamBranch string Subject string CommitHash string } type RemoteBranch struct { Name string RemoteName string } type Remote struct { Name string Urls []string Branches []*RemoteBranch } type Tag struct { Name string Message string } type StashEntry struct { Index int Recency string Name string } type CommitFile struct { Name string ChangeStatus string } type Worktree struct { IsMain bool IsCurrent bool Path string IsPathMissing bool GitDir string Branch string Name string }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/client.go
pkg/gui/services/custom_commands/client.go
package custom_commands import ( "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/i18n" "github.com/samber/lo" ) // Client is the entry point to this package. It returns a list of keybindings based on the config's user-defined custom commands. // See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Command_Keybindings.md for more info. type Client struct { c *helpers.HelperCommon handlerCreator *HandlerCreator keybindingCreator *KeybindingCreator } func NewClient( c *helpers.HelperCommon, helpers *helpers.Helpers, ) *Client { sessionStateLoader := NewSessionStateLoader(c, helpers.Refs) handlerCreator := NewHandlerCreator( c, sessionStateLoader, helpers.Suggestions, helpers.MergeAndRebase, ) keybindingCreator := NewKeybindingCreator(c) return &Client{ c: c, keybindingCreator: keybindingCreator, handlerCreator: handlerCreator, } } func (self *Client) GetCustomCommandKeybindings() ([]*types.Binding, error) { bindings := []*types.Binding{} for _, customCommand := range self.c.UserConfig().CustomCommands { if len(customCommand.CommandMenu) > 0 { handler := func() error { return self.showCustomCommandsMenu(customCommand) } bindings = append(bindings, &types.Binding{ ViewName: "", // custom commands menus are global; we filter the commands inside by context Key: keybindings.GetKey(customCommand.Key), Modifier: gocui.ModNone, Handler: handler, Description: getCustomCommandsMenuDescription(customCommand, self.c.Tr), OpensMenu: true, }) } else { handler := self.handlerCreator.call(customCommand) compoundBindings, err := self.keybindingCreator.call(customCommand, handler) if err != nil { return nil, err } bindings = append(bindings, compoundBindings...) } } return bindings, nil } func (self *Client) showCustomCommandsMenu(customCommand config.CustomCommand) error { menuItems := make([]*types.MenuItem, 0, len(customCommand.CommandMenu)) for _, subCommand := range customCommand.CommandMenu { if len(subCommand.CommandMenu) > 0 { handler := func() error { return self.showCustomCommandsMenu(subCommand) } menuItems = append(menuItems, &types.MenuItem{ Label: subCommand.GetDescription(), Key: keybindings.GetKey(subCommand.Key), OnPress: handler, OpensMenu: true, }) } else { if subCommand.Context != "" && subCommand.Context != "global" { viewNames, err := self.keybindingCreator.getViewNamesAndContexts(subCommand) if err != nil { return err } currentView := self.c.GocuiGui().CurrentView() enabled := currentView != nil && lo.Contains(viewNames, currentView.Name()) if !enabled { continue } } menuItems = append(menuItems, &types.MenuItem{ Label: subCommand.GetDescription(), Key: keybindings.GetKey(subCommand.Key), OnPress: self.handlerCreator.call(subCommand), }) } } if len(menuItems) == 0 { menuItems = append(menuItems, &types.MenuItem{ Label: self.c.Tr.NoApplicableCommandsInThisContext, OnPress: func() error { return nil }, }) } title := getCustomCommandsMenuDescription(customCommand, self.c.Tr) return self.c.Menu(types.CreateMenuOptions{Title: title, Items: menuItems, HideCancel: true}) } func getCustomCommandsMenuDescription(customCommand config.CustomCommand, tr *i18n.TranslationSet) string { if customCommand.Description != "" { return customCommand.Description } return tr.CustomCommands }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/keybinding_creator.go
pkg/gui/services/custom_commands/keybinding_creator.go
package custom_commands import ( "fmt" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // KeybindingCreator takes a custom command along with its handler and returns a corresponding keybinding type KeybindingCreator struct { c *helpers.HelperCommon } func NewKeybindingCreator(c *helpers.HelperCommon) *KeybindingCreator { return &KeybindingCreator{ c: c, } } func (self *KeybindingCreator) call(customCommand config.CustomCommand, handler func() error) ([]*types.Binding, error) { if customCommand.Context == "" { return nil, formatContextNotProvidedError(customCommand) } viewNames, err := self.getViewNamesAndContexts(customCommand) if err != nil { return nil, err } return lo.Map(viewNames, func(viewName string, _ int) *types.Binding { return &types.Binding{ ViewName: viewName, Key: keybindings.GetKey(customCommand.Key), Modifier: gocui.ModNone, Handler: handler, Description: customCommand.GetDescription(), } }), nil } func (self *KeybindingCreator) getViewNamesAndContexts(customCommand config.CustomCommand) ([]string, error) { if customCommand.Context == "global" { return []string{""}, nil } contexts := strings.Split(customCommand.Context, ",") contexts = lo.Map(contexts, func(context string, _ int) string { return strings.TrimSpace(context) }) viewNames := []string{} for _, context := range contexts { ctx, ok := self.contextForContextKey(types.ContextKey(context)) if !ok { return []string{}, formatUnknownContextError(customCommand) } viewNames = append(viewNames, ctx.GetViewName()) } return viewNames, nil } func (self *KeybindingCreator) contextForContextKey(contextKey types.ContextKey) (types.Context, bool) { for _, context := range self.c.Contexts().Flatten() { if context.GetKey() == contextKey { return context, true } } return nil, false } func formatUnknownContextError(customCommand config.CustomCommand) error { allContextKeyStrings := lo.Map(context.AllContextKeys, func(key types.ContextKey, _ int) string { return string(key) }) return fmt.Errorf("Error when setting custom command keybindings: unknown context: %s. Key: %s, Command: %s.\nPermitted contexts: %s", customCommand.Context, customCommand.Key, customCommand.Command, strings.Join(allContextKeyStrings, ", ")) } func formatContextNotProvidedError(customCommand config.CustomCommand) error { return fmt.Errorf("Error parsing custom command keybindings: context not provided (use context: 'global' for the global context). Key: %s, Command: %s", customCommand.Key, customCommand.Command) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/resolver.go
pkg/gui/services/custom_commands/resolver.go
package custom_commands import ( "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" ) // takes a prompt that is defined in terms of template strings and resolves the templates to contain actual values type Resolver struct { c *common.Common } func NewResolver(c *common.Common) *Resolver { return &Resolver{c: c} } func (self *Resolver) resolvePrompt( prompt *config.CustomCommandPrompt, resolveTemplate func(string) (string, error), ) (*config.CustomCommandPrompt, error) { var err error result := &config.CustomCommandPrompt{ ValueFormat: prompt.ValueFormat, LabelFormat: prompt.LabelFormat, } result.Title, err = resolveTemplate(prompt.Title) if err != nil { return nil, err } result.InitialValue, err = resolveTemplate(prompt.InitialValue) if err != nil { return nil, err } result.Suggestions.Preset, err = resolveTemplate(prompt.Suggestions.Preset) if err != nil { return nil, err } result.Suggestions.Command, err = resolveTemplate(prompt.Suggestions.Command) if err != nil { return nil, err } result.Body, err = resolveTemplate(prompt.Body) if err != nil { return nil, err } result.Command, err = resolveTemplate(prompt.Command) if err != nil { return nil, err } result.Filter, err = resolveTemplate(prompt.Filter) if err != nil { return nil, err } if prompt.Type == "menu" { result.Options, err = self.resolveMenuOptions(prompt, resolveTemplate) if err != nil { return nil, err } } return result, nil } func (self *Resolver) resolveMenuOptions(prompt *config.CustomCommandPrompt, resolveTemplate func(string) (string, error)) ([]config.CustomCommandMenuOption, error) { newOptions := make([]config.CustomCommandMenuOption, 0, len(prompt.Options)) for _, option := range prompt.Options { newOption, err := self.resolveMenuOption(&option, resolveTemplate) if err != nil { return nil, err } newOptions = append(newOptions, *newOption) } return newOptions, nil } func (self *Resolver) resolveMenuOption(option *config.CustomCommandMenuOption, resolveTemplate func(string) (string, error)) (*config.CustomCommandMenuOption, error) { nameTemplate := option.Name if nameTemplate == "" { // this allows you to only pass values rather than bother with names/descriptions nameTemplate = option.Value } name, err := resolveTemplate(nameTemplate) if err != nil { return nil, err } description, err := resolveTemplate(option.Description) if err != nil { return nil, err } value, err := resolveTemplate(option.Value) if err != nil { return nil, err } return &config.CustomCommandMenuOption{ Name: name, Description: description, Value: value, Key: option.Key, }, nil } type CustomCommandObject struct { // deprecated. Use Responses instead PromptResponses []string Form map[string]string }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/session_state_loader.go
pkg/gui/services/custom_commands/session_state_loader.go
package custom_commands import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/samber/lo" ) // loads the session state at the time that a custom command is invoked, for use // in the custom command's template strings type SessionStateLoader struct { c *helpers.HelperCommon refsHelper *helpers.RefsHelper } func NewSessionStateLoader(c *helpers.HelperCommon, refsHelper *helpers.RefsHelper) *SessionStateLoader { return &SessionStateLoader{ c: c, refsHelper: refsHelper, } } func commitShimFromModelCommit(commit *models.Commit) *Commit { if commit == nil { return nil } return &Commit{ Hash: commit.Hash(), Sha: commit.Hash(), Name: commit.Name, Status: commit.Status, Action: commit.Action, Tags: commit.Tags, ExtraInfo: commit.ExtraInfo, AuthorName: commit.AuthorName, AuthorEmail: commit.AuthorEmail, UnixTimestamp: commit.UnixTimestamp, Divergence: commit.Divergence, Parents: commit.Parents(), } } func fileShimFromModelFile(file *models.File) *File { if file == nil { return nil } return &File{ Name: file.Path, PreviousName: file.PreviousPath, HasStagedChanges: file.HasStagedChanges, HasUnstagedChanges: file.HasUnstagedChanges, Tracked: file.Tracked, Added: file.Added, Deleted: file.Deleted, HasMergeConflicts: file.HasMergeConflicts, HasInlineMergeConflicts: file.HasInlineMergeConflicts, DisplayString: file.DisplayString, ShortStatus: file.ShortStatus, IsWorktree: file.IsWorktree, } } func submoduleShimFromModelSubmodule(submodule *models.SubmoduleConfig) *Submodule { if submodule == nil { return nil } return &Submodule{ Name: submodule.Name, Path: submodule.Path, Url: submodule.Url, } } func branchShimFromModelBranch(branch *models.Branch) *Branch { if branch == nil { return nil } return &Branch{ Name: branch.Name, DisplayName: branch.DisplayName, Recency: branch.Recency, Pushables: branch.AheadForPull, Pullables: branch.BehindForPull, AheadForPull: branch.AheadForPull, BehindForPull: branch.BehindForPull, AheadForPush: branch.AheadForPush, BehindForPush: branch.BehindForPush, UpstreamGone: branch.UpstreamGone, Head: branch.Head, DetachedHead: branch.DetachedHead, UpstreamRemote: branch.UpstreamRemote, UpstreamBranch: branch.UpstreamBranch, Subject: branch.Subject, CommitHash: branch.CommitHash, } } func remoteBranchShimFromModelRemoteBranch(remoteBranch *models.RemoteBranch) *RemoteBranch { if remoteBranch == nil { return nil } return &RemoteBranch{ Name: remoteBranch.Name, RemoteName: remoteBranch.RemoteName, } } func remoteShimFromModelRemote(remote *models.Remote) *Remote { if remote == nil { return nil } return &Remote{ Name: remote.Name, Urls: remote.Urls, Branches: lo.Map(remote.Branches, func(branch *models.RemoteBranch, _ int) *RemoteBranch { return remoteBranchShimFromModelRemoteBranch(branch) }), } } func tagShimFromModelRemote(tag *models.Tag) *Tag { if tag == nil { return nil } return &Tag{ Name: tag.Name, Message: tag.Message, } } func stashEntryShimFromModelRemote(stashEntry *models.StashEntry) *StashEntry { if stashEntry == nil { return nil } return &StashEntry{ Index: stashEntry.Index, Recency: stashEntry.Recency, Name: stashEntry.Name, } } func commitFileShimFromModelRemote(commitFile *models.CommitFile) *CommitFile { if commitFile == nil { return nil } return &CommitFile{ Name: commitFile.Path, ChangeStatus: commitFile.ChangeStatus, } } func worktreeShimFromModelRemote(worktree *models.Worktree) *Worktree { if worktree == nil { return nil } return &Worktree{ IsMain: worktree.IsMain, IsCurrent: worktree.IsCurrent, Path: worktree.Path, IsPathMissing: worktree.IsPathMissing, GitDir: worktree.GitDir, Branch: worktree.Branch, Name: worktree.Name, } } type CommitRange struct { From string To string } func makeCommitRange(commits []*models.Commit, _ int, _ int) *CommitRange { if len(commits) == 0 { return nil } return &CommitRange{ From: commits[len(commits)-1].Hash(), To: commits[0].Hash(), } } // SessionState captures the current state of the application for use in custom commands type SessionState struct { SelectedLocalCommit *Commit // deprecated, use SelectedCommit SelectedReflogCommit *Commit // deprecated, use SelectedCommit SelectedSubCommit *Commit // deprecated, use SelectedCommit SelectedCommit *Commit SelectedCommitRange *CommitRange SelectedFile *File SelectedSubmodule *Submodule SelectedPath string SelectedLocalBranch *Branch SelectedRemoteBranch *RemoteBranch SelectedRemote *Remote SelectedTag *Tag SelectedStashEntry *StashEntry SelectedCommitFile *CommitFile SelectedCommitFilePath string SelectedWorktree *Worktree CheckedOutBranch *Branch } func (self *SessionStateLoader) call() *SessionState { selectedLocalCommit := commitShimFromModelCommit(self.c.Contexts().LocalCommits.GetSelected()) selectedLocalCommitRange := makeCommitRange(self.c.Contexts().LocalCommits.GetSelectedItems()) selectedReflogCommit := commitShimFromModelCommit(self.c.Contexts().ReflogCommits.GetSelected()) selectedReflogCommitRange := makeCommitRange(self.c.Contexts().ReflogCommits.GetSelectedItems()) selectedSubCommit := commitShimFromModelCommit(self.c.Contexts().SubCommits.GetSelected()) selectedSubCommitRange := makeCommitRange(self.c.Contexts().SubCommits.GetSelectedItems()) selectedCommit := selectedLocalCommit selectedCommitRange := selectedLocalCommitRange if self.c.Context().IsCurrentOrParent(self.c.Contexts().ReflogCommits) { selectedCommit = selectedReflogCommit selectedCommitRange = selectedReflogCommitRange } else if self.c.Context().IsCurrentOrParent(self.c.Contexts().SubCommits) { selectedCommit = selectedSubCommit selectedCommitRange = selectedSubCommitRange } selectedPath := self.c.Contexts().Files.GetSelectedPath() selectedCommitFilePath := self.c.Contexts().CommitFiles.GetSelectedPath() if self.c.Context().IsCurrent(self.c.Contexts().CommitFiles) { selectedPath = selectedCommitFilePath } return &SessionState{ SelectedFile: fileShimFromModelFile(self.c.Contexts().Files.GetSelectedFile()), SelectedSubmodule: submoduleShimFromModelSubmodule(self.c.Contexts().Submodules.GetSelected()), SelectedPath: selectedPath, SelectedLocalCommit: selectedLocalCommit, SelectedReflogCommit: selectedReflogCommit, SelectedSubCommit: selectedSubCommit, SelectedCommit: selectedCommit, SelectedCommitRange: selectedCommitRange, SelectedLocalBranch: branchShimFromModelBranch(self.c.Contexts().Branches.GetSelected()), SelectedRemoteBranch: remoteBranchShimFromModelRemoteBranch(self.c.Contexts().RemoteBranches.GetSelected()), SelectedRemote: remoteShimFromModelRemote(self.c.Contexts().Remotes.GetSelected()), SelectedTag: tagShimFromModelRemote(self.c.Contexts().Tags.GetSelected()), SelectedStashEntry: stashEntryShimFromModelRemote(self.c.Contexts().Stash.GetSelected()), SelectedCommitFile: commitFileShimFromModelRemote(self.c.Contexts().CommitFiles.GetSelectedFile()), SelectedCommitFilePath: selectedCommitFilePath, SelectedWorktree: worktreeShimFromModelRemote(self.c.Contexts().Worktrees.GetSelected()), CheckedOutBranch: branchShimFromModelBranch(self.refsHelper.GetCheckedOutRef()), } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/menu_generator_test.go
pkg/gui/services/custom_commands/menu_generator_test.go
package custom_commands import ( "testing" "github.com/jesseduffield/lazygit/pkg/common" "github.com/stretchr/testify/assert" ) func TestMenuGenerator(t *testing.T) { type scenario struct { testName string cmdOut string filter string valueFormat string labelFormat string test func([]*commandMenuItem, error) } scenarios := []scenario{ { "Extract remote branch name", "upstream/pr-1", "(?P<remote>[a-z_]+)/(?P<branch>.*)", "{{ .branch }}", "Remote: {{ .remote }}", func(actualEntry []*commandMenuItem, err error) { assert.NoError(t, err) assert.EqualValues(t, "pr-1", actualEntry[0].value) assert.EqualValues(t, "Remote: upstream", actualEntry[0].label) }, }, { "Multiple named groups with empty labelFormat", "upstream/pr-1", "(?P<remote>[a-z]*)/(?P<branch>.*)", "{{ .branch }}|{{ .remote }}", "", func(actualEntry []*commandMenuItem, err error) { assert.NoError(t, err) assert.EqualValues(t, "pr-1|upstream", actualEntry[0].value) assert.EqualValues(t, "pr-1|upstream", actualEntry[0].label) }, }, { "Multiple named groups with group ids", "upstream/pr-1", "(?P<remote>[a-z]*)/(?P<branch>.*)", "{{ .group_2 }}|{{ .group_1 }}", "Remote: {{ .group_1 }}", func(actualEntry []*commandMenuItem, err error) { assert.NoError(t, err) assert.EqualValues(t, "pr-1|upstream", actualEntry[0].value) assert.EqualValues(t, "Remote: upstream", actualEntry[0].label) }, }, { "No named groups", "upstream/pr-1", "([a-z]*)/(.*)", "{{ .group_2 }}|{{ .group_1 }}", "Remote: {{ .group_1 }}", func(actualEntry []*commandMenuItem, err error) { assert.NoError(t, err) assert.EqualValues(t, "pr-1|upstream", actualEntry[0].value) assert.EqualValues(t, "Remote: upstream", actualEntry[0].label) }, }, { "No filter", "upstream/pr-1", "", "", "", func(actualEntry []*commandMenuItem, err error) { assert.NoError(t, err) assert.EqualValues(t, "upstream/pr-1", actualEntry[0].value) assert.EqualValues(t, "upstream/pr-1", actualEntry[0].label) }, }, } for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { s.test(NewMenuGenerator(common.NewDummyCommon()).call(s.cmdOut, s.filter, s.valueFormat, s.labelFormat)) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/services/custom_commands/handler_creator.go
pkg/gui/services/custom_commands/handler_creator.go
package custom_commands import ( "errors" "fmt" "strings" "text/template" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/keybindings" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) // takes a custom command and returns a function that will be called when the corresponding user-defined keybinding is pressed type HandlerCreator struct { c *helpers.HelperCommon sessionStateLoader *SessionStateLoader resolver *Resolver menuGenerator *MenuGenerator suggestionsHelper *helpers.SuggestionsHelper mergeAndRebaseHelper *helpers.MergeAndRebaseHelper } func NewHandlerCreator( c *helpers.HelperCommon, sessionStateLoader *SessionStateLoader, suggestionsHelper *helpers.SuggestionsHelper, mergeAndRebaseHelper *helpers.MergeAndRebaseHelper, ) *HandlerCreator { resolver := NewResolver(c.Common) menuGenerator := NewMenuGenerator(c.Common) return &HandlerCreator{ c: c, sessionStateLoader: sessionStateLoader, resolver: resolver, menuGenerator: menuGenerator, suggestionsHelper: suggestionsHelper, mergeAndRebaseHelper: mergeAndRebaseHelper, } } func (self *HandlerCreator) call(customCommand config.CustomCommand) func() error { return func() error { sessionState := self.sessionStateLoader.call() promptResponses := make([]string, len(customCommand.Prompts)) form := make(map[string]string) f := func() error { return self.finalHandler(customCommand, sessionState, promptResponses, form) } // if we have prompts we'll recursively wrap our confirm handlers with more prompts // until we reach the actual command for reverseIdx := range customCommand.Prompts { // reassigning so that we don't end up with an infinite recursion g := f idx := len(customCommand.Prompts) - 1 - reverseIdx // going backwards so the outermost prompt is the first one prompt := customCommand.Prompts[idx] wrappedF := func(response string) error { promptResponses[idx] = response form[prompt.Key] = response return g() } resolveTemplate := self.getResolveTemplateFn(form, promptResponses, sessionState) switch prompt.Type { case "input": f = func() error { resolvedPrompt, err := self.resolver.resolvePrompt(&prompt, resolveTemplate) if err != nil { return err } return self.inputPrompt(resolvedPrompt, wrappedF) } case "menu": f = func() error { resolvedPrompt, err := self.resolver.resolvePrompt(&prompt, resolveTemplate) if err != nil { return err } return self.menuPrompt(resolvedPrompt, wrappedF) } case "menuFromCommand": f = func() error { resolvedPrompt, err := self.resolver.resolvePrompt(&prompt, resolveTemplate) if err != nil { return err } return self.menuPromptFromCommand(resolvedPrompt, wrappedF) } case "confirm": f = func() error { resolvedPrompt, err := self.resolver.resolvePrompt(&prompt, resolveTemplate) if err != nil { return err } return self.confirmPrompt(resolvedPrompt, g) } default: return errors.New("custom command prompt must have a type of 'input', 'menu', 'menuFromCommand', or 'confirm'") } } return f() } } func (self *HandlerCreator) inputPrompt(prompt *config.CustomCommandPrompt, wrappedF func(string) error) error { findSuggestionsFn, err := self.generateFindSuggestionsFunc(prompt) if err != nil { return err } self.c.Prompt(types.PromptOpts{ Title: prompt.Title, InitialContent: prompt.InitialValue, FindSuggestionsFunc: findSuggestionsFn, HandleConfirm: func(str string) error { return wrappedF(str) }, AllowEmptyInput: true, PreserveWhitespace: true, }) return nil } func (self *HandlerCreator) generateFindSuggestionsFunc(prompt *config.CustomCommandPrompt) (func(string) []*types.Suggestion, error) { if prompt.Suggestions.Preset != "" && prompt.Suggestions.Command != "" { return nil, fmt.Errorf( "Custom command prompt cannot have both a preset and a command for suggestions. Preset: '%s', Command: '%s'", prompt.Suggestions.Preset, prompt.Suggestions.Command, ) } else if prompt.Suggestions.Preset != "" { return self.getPresetSuggestionsFn(prompt.Suggestions.Preset) } else if prompt.Suggestions.Command != "" { return self.getCommandSuggestionsFn(prompt.Suggestions.Command) } return nil, nil } func (self *HandlerCreator) getCommandSuggestionsFn(command string) (func(string) []*types.Suggestion, error) { lines := []*types.Suggestion{} err := self.c.OS().Cmd.NewShell(command, self.c.UserConfig().OS.ShellFunctionsFile).RunAndProcessLines(func(line string) (bool, error) { lines = append(lines, &types.Suggestion{Value: line, Label: line}) return false, nil }) if err != nil { return nil, err } return func(currentWord string) []*types.Suggestion { return lo.Filter(lines, func(suggestion *types.Suggestion, _ int) bool { return strings.Contains(strings.ToLower(suggestion.Value), strings.ToLower(currentWord)) }) }, nil } func (self *HandlerCreator) getPresetSuggestionsFn(preset string) (func(string) []*types.Suggestion, error) { switch preset { case "authors": return self.suggestionsHelper.GetAuthorsSuggestionsFunc(), nil case "branches": return self.suggestionsHelper.GetBranchNameSuggestionsFunc(), nil case "files": return self.suggestionsHelper.GetFilePathSuggestionsFunc(), nil case "refs": return self.suggestionsHelper.GetRefsSuggestionsFunc(), nil case "remotes": return self.suggestionsHelper.GetRemoteSuggestionsFunc(), nil case "remoteBranches": return self.suggestionsHelper.GetRemoteBranchesSuggestionsFunc("/"), nil case "tags": return self.suggestionsHelper.GetTagsSuggestionsFunc(), nil default: return nil, fmt.Errorf("Unknown value for suggestionsPreset in custom command: %s. Valid values: files, branches, remotes, remoteBranches, refs", preset) } } func (self *HandlerCreator) confirmPrompt(prompt *config.CustomCommandPrompt, handleConfirm func() error) error { self.c.Confirm(types.ConfirmOpts{ Title: prompt.Title, Prompt: prompt.Body, HandleConfirm: handleConfirm, }) return nil } func (self *HandlerCreator) menuPrompt(prompt *config.CustomCommandPrompt, wrappedF func(string) error) error { menuItems := lo.Map(prompt.Options, func(option config.CustomCommandMenuOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{option.Name, style.FgYellow.Sprint(option.Description)}, OnPress: func() error { return wrappedF(option.Value) }, Key: keybindings.GetKey(option.Key), } }) return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems}) } func (self *HandlerCreator) menuPromptFromCommand(prompt *config.CustomCommandPrompt, wrappedF func(string) error) error { // Run and save output message, err := self.c.Git().Custom.RunWithOutput(prompt.Command) if err != nil { return err } // Need to make a menu out of what the cmd has displayed candidates, err := self.menuGenerator.call(message, prompt.Filter, prompt.ValueFormat, prompt.LabelFormat) if err != nil { return err } menuItems := lo.Map(candidates, func(candidate *commandMenuItem, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{candidate.label}, OnPress: func() error { return wrappedF(candidate.value) }, } }) return self.c.Menu(types.CreateMenuOptions{Title: prompt.Title, Items: menuItems}) } type CustomCommandObjects struct { *SessionState PromptResponses []string Form map[string]string } func (self *HandlerCreator) getResolveTemplateFn(form map[string]string, promptResponses []string, sessionState *SessionState) func(string) (string, error) { objects := CustomCommandObjects{ SessionState: sessionState, PromptResponses: promptResponses, Form: form, } funcs := template.FuncMap{ "quote": self.c.OS().Quote, "runCommand": self.c.Git().Custom.TemplateFunctionRunCommand, } return func(templateStr string) (string, error) { return utils.ResolveTemplate(templateStr, objects, funcs) } } func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, sessionState *SessionState, promptResponses []string, form map[string]string) error { resolveTemplate := self.getResolveTemplateFn(form, promptResponses, sessionState) cmdStr, err := resolveTemplate(customCommand.Command) if err != nil { return err } cmdObj := self.c.OS().Cmd.NewShell(cmdStr, self.c.UserConfig().OS.ShellFunctionsFile) if customCommand.Output == "terminal" { return self.c.RunSubprocessAndRefresh(cmdObj) } loadingText := customCommand.LoadingText if loadingText == "" { loadingText = self.c.Tr.RunningCustomCommandStatus } return self.c.WithWaitingStatus(loadingText, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.CustomCommand) if customCommand.Output == "log" || customCommand.Output == "logWithPty" { cmdObj.StreamOutput() } if customCommand.Output == "logWithPty" { cmdObj.UsePty() } output, err := cmdObj.RunWithOutput() self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) if err != nil { if customCommand.After != nil && customCommand.After.CheckForConflicts { return self.mergeAndRebaseHelper.CheckForConflicts(err) } return err } if customCommand.Output == "popup" { if strings.TrimSpace(output) == "" { output = self.c.Tr.EmptyOutput } title := cmdStr if customCommand.OutputTitle != "" { title, err = resolveTemplate(customCommand.OutputTitle) if err != nil { return err } } self.c.Alert(title, output) } return nil }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/popup/popup_handler.go
pkg/gui/popup/popup_handler.go
package popup import ( "context" "errors" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" ) type PopupHandler struct { *common.Common createPopupPanelFn func(context.Context, types.CreatePopupPanelOpts) onErrorFn func() error popContextFn func() currentContextFn func() types.Context createMenuFn func(types.CreateMenuOptions) error withWaitingStatusFn func(message string, f func(gocui.Task) error) withWaitingStatusSyncFn func(message string, f func() error) error toastFn func(message string, kind types.ToastKind) getPromptInputFn func() string inDemo func() bool } var _ types.IPopupHandler = &PopupHandler{} func NewPopupHandler( common *common.Common, createPopupPanelFn func(context.Context, types.CreatePopupPanelOpts), onErrorFn func() error, popContextFn func(), currentContextFn func() types.Context, createMenuFn func(types.CreateMenuOptions) error, withWaitingStatusFn func(message string, f func(gocui.Task) error), withWaitingStatusSyncFn func(message string, f func() error) error, toastFn func(message string, kind types.ToastKind), getPromptInputFn func() string, inDemo func() bool, ) *PopupHandler { return &PopupHandler{ Common: common, createPopupPanelFn: createPopupPanelFn, onErrorFn: onErrorFn, popContextFn: popContextFn, currentContextFn: currentContextFn, createMenuFn: createMenuFn, withWaitingStatusFn: withWaitingStatusFn, withWaitingStatusSyncFn: withWaitingStatusSyncFn, toastFn: toastFn, getPromptInputFn: getPromptInputFn, inDemo: inDemo, } } func (self *PopupHandler) Menu(opts types.CreateMenuOptions) error { return self.createMenuFn(opts) } func (self *PopupHandler) Toast(message string) { self.toastFn(message, types.ToastKindStatus) } func (self *PopupHandler) ErrorToast(message string) { self.toastFn(message, types.ToastKindError) } func (self *PopupHandler) SetToastFunc(f func(string, types.ToastKind)) { self.toastFn = f } func (self *PopupHandler) WithWaitingStatus(message string, f func(gocui.Task) error) error { self.withWaitingStatusFn(message, f) return nil } func (self *PopupHandler) WithWaitingStatusSync(message string, f func() error) error { return self.withWaitingStatusSyncFn(message, f) } func (self *PopupHandler) ErrorHandler(err error) error { var notHandledError *types.ErrKeybindingNotHandled if errors.As(err, &notHandledError) { if !notHandledError.DisabledReason.ShowErrorInPanel { if msg := notHandledError.DisabledReason.Text; len(msg) > 0 { self.ErrorToast(self.Tr.DisabledMenuItemPrefix + msg) } return nil } } // Need to set bold here explicitly; otherwise it gets cancelled by the red colouring. coloredMessage := style.FgRed.SetBold().Sprint(strings.TrimSpace(err.Error())) if err := self.onErrorFn(); err != nil { return err } self.Alert(self.Tr.Error, coloredMessage) return nil } func (self *PopupHandler) Alert(title string, message string) { self.Confirm(types.ConfirmOpts{Title: title, Prompt: message}) } func (self *PopupHandler) Confirm(opts types.ConfirmOpts) { self.createPopupPanelFn(context.Background(), types.CreatePopupPanelOpts{ Title: opts.Title, Prompt: opts.Prompt, HandleConfirm: opts.HandleConfirm, HandleClose: opts.HandleClose, }) } func (self *PopupHandler) ConfirmIf(condition bool, opts types.ConfirmOpts) error { if condition { self.createPopupPanelFn(context.Background(), types.CreatePopupPanelOpts{ Title: opts.Title, Prompt: opts.Prompt, HandleConfirm: opts.HandleConfirm, HandleClose: opts.HandleClose, }) return nil } return opts.HandleConfirm() } func (self *PopupHandler) Prompt(opts types.PromptOpts) { self.createPopupPanelFn(context.Background(), types.CreatePopupPanelOpts{ Title: opts.Title, Prompt: opts.InitialContent, Editable: true, HandleConfirmPrompt: opts.HandleConfirm, HandleClose: opts.HandleClose, HandleDeleteSuggestion: opts.HandleDeleteSuggestion, FindSuggestionsFunc: opts.FindSuggestionsFunc, AllowEditSuggestion: opts.AllowEditSuggestion, AllowEmptyInput: opts.AllowEmptyInput, PreserveWhitespace: opts.PreserveWhitespace, Mask: opts.Mask, }) } // returns the content that has currently been typed into the prompt. Useful for // asynchronously updating the suggestions list under the prompt. func (self *PopupHandler) GetPromptInput() string { return self.getPromptInputFn() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/build_tree.go
pkg/gui/filetree/build_tree.go
package filetree import ( "sort" "strings" "github.com/jesseduffield/lazygit/pkg/commands/models" ) func BuildTreeFromFiles(files []*models.File, showRootItem bool) *Node[models.File] { root := &Node[models.File]{} childrenMapsByNode := make(map[*Node[models.File]]map[string]*Node[models.File]) var curr *Node[models.File] for _, file := range files { splitPath := SplitFileTreePath(file.Path, showRootItem) curr = root outer: for i := range splitPath { var setFile *models.File isFile := i == len(splitPath)-1 if isFile { setFile = file } path := join(splitPath[:i+1]) var currNodeChildrenMap map[string]*Node[models.File] var isCurrNodeMapped bool if currNodeChildrenMap, isCurrNodeMapped = childrenMapsByNode[curr]; !isCurrNodeMapped { currNodeChildrenMap = make(map[string]*Node[models.File]) childrenMapsByNode[curr] = currNodeChildrenMap } child, doesCurrNodeHaveChildAlready := currNodeChildrenMap[path] if doesCurrNodeHaveChildAlready { curr = child continue outer } if i == 0 && len(files) == 1 && len(splitPath) == 2 { // skip the root item when there's only one file at top level; we don't need it in that case continue outer } newChild := &Node[models.File]{ path: path, File: setFile, } curr.Children = append(curr.Children, newChild) currNodeChildrenMap[path] = newChild curr = newChild } } root.Sort() root.Compress() return root } func BuildFlatTreeFromCommitFiles(files []*models.CommitFile, showRootItem bool) *Node[models.CommitFile] { rootAux := BuildTreeFromCommitFiles(files, showRootItem) sortedFiles := rootAux.GetLeaves() return &Node[models.CommitFile]{Children: sortedFiles} } func BuildTreeFromCommitFiles(files []*models.CommitFile, showRootItem bool) *Node[models.CommitFile] { root := &Node[models.CommitFile]{} var curr *Node[models.CommitFile] for _, file := range files { splitPath := SplitFileTreePath(file.Path, showRootItem) curr = root outer: for i := range splitPath { var setFile *models.CommitFile isFile := i == len(splitPath)-1 if isFile { setFile = file } path := join(splitPath[:i+1]) for _, existingChild := range curr.Children { if existingChild.path == path { curr = existingChild continue outer } } if i == 0 && len(files) == 1 && len(splitPath) == 2 { // skip the root item when there's only one file at top level; we don't need it in that case continue outer } newChild := &Node[models.CommitFile]{ path: path, File: setFile, } curr.Children = append(curr.Children, newChild) curr = newChild } } root.Sort() root.Compress() return root } func BuildFlatTreeFromFiles(files []*models.File, showRootItem bool) *Node[models.File] { rootAux := BuildTreeFromFiles(files, showRootItem) sortedFiles := rootAux.GetLeaves() // from top down we have merge conflict files, then tracked file, then untracked // files. This is the one way in which sorting differs between flat mode and // tree mode sort.SliceStable(sortedFiles, func(i, j int) bool { iFile := sortedFiles[i].File jFile := sortedFiles[j].File // never going to happen but just to be safe if iFile == nil || jFile == nil { return false } if iFile.HasMergeConflicts && !jFile.HasMergeConflicts { return true } if jFile.HasMergeConflicts && !iFile.HasMergeConflicts { return false } if iFile.Tracked && !jFile.Tracked { return true } if jFile.Tracked && !iFile.Tracked { return false } return false }) return &Node[models.File]{Children: sortedFiles} } func split(str string) []string { return strings.Split(str, "/") } func join(strs []string) string { return strings.Join(strs, "/") } func SplitFileTreePath(path string, showRootItem bool) []string { return split(InternalTreePathForFilePath(path, showRootItem)) } func InternalTreePathForFilePath(path string, showRootItem bool) string { if showRootItem { return "./" + path } return path }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/commit_file_tree.go
pkg/gui/filetree/commit_file_tree.go
package filetree import ( "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type ICommitFileTree interface { ITree[models.CommitFile] Get(index int) *CommitFileNode GetFile(path string) *models.CommitFile GetAllItems() []*CommitFileNode GetAllFiles() []*models.CommitFile GetRoot() *CommitFileNode } type CommitFileTree struct { getFiles func() []*models.CommitFile tree *Node[models.CommitFile] showTree bool common *common.Common collapsedPaths *CollapsedPaths } func (self *CommitFileTree) CollapseAll() { dirPaths := lo.FilterMap(self.GetAllItems(), func(file *CommitFileNode, index int) (string, bool) { return file.path, !file.IsFile() }) for _, path := range dirPaths { self.collapsedPaths.Collapse(path) } } func (self *CommitFileTree) ExpandAll() { self.collapsedPaths.ExpandAll() } var _ ICommitFileTree = &CommitFileTree{} func NewCommitFileTree(getFiles func() []*models.CommitFile, common *common.Common, showTree bool) *CommitFileTree { return &CommitFileTree{ getFiles: getFiles, common: common, showTree: showTree, collapsedPaths: NewCollapsedPaths(), } } func (self *CommitFileTree) ExpandToPath(path string) { self.collapsedPaths.ExpandToPath(path) } func (self *CommitFileTree) ToggleShowTree() { self.showTree = !self.showTree self.SetTree() } func (self *CommitFileTree) Get(index int) *CommitFileNode { // need to traverse the three depth first until we get to the index. return NewCommitFileNode(self.tree.GetNodeAtIndex(index+1, self.collapsedPaths)) // ignoring root } func (self *CommitFileTree) GetIndexForPath(path string) (int, bool) { index, found := self.tree.GetIndexForPath(path, self.collapsedPaths) return index - 1, found } func (self *CommitFileTree) GetAllItems() []*CommitFileNode { if self.tree == nil { return nil } // ignoring root return lo.Map(self.tree.Flatten(self.collapsedPaths)[1:], func(node *Node[models.CommitFile], _ int) *CommitFileNode { return NewCommitFileNode(node) }) } func (self *CommitFileTree) Len() int { return self.tree.Size(self.collapsedPaths) - 1 // ignoring root } func (self *CommitFileTree) GetItem(index int) types.HasUrn { // Unimplemented because we don't yet need to show inlines statuses in commit file views return nil } func (self *CommitFileTree) GetAllFiles() []*models.CommitFile { return self.getFiles() } func (self *CommitFileTree) SetTree() { showRootItem := self.common.UserConfig().Gui.ShowRootItemInFileTree if self.showTree { self.tree = BuildTreeFromCommitFiles(self.getFiles(), showRootItem) } else { self.tree = BuildFlatTreeFromCommitFiles(self.getFiles(), showRootItem) } } func (self *CommitFileTree) IsCollapsed(path string) bool { return self.collapsedPaths.IsCollapsed(path) } func (self *CommitFileTree) ToggleCollapsed(path string) { self.collapsedPaths.ToggleCollapsed(path) } func (self *CommitFileTree) GetRoot() *CommitFileNode { return NewCommitFileNode(self.tree) } func (self *CommitFileTree) CollapsedPaths() *CollapsedPaths { return self.collapsedPaths } func (self *CommitFileTree) GetFile(path string) *models.CommitFile { for _, file := range self.getFiles() { if file.Path == path { return file } } return nil } func (self *CommitFileTree) InTreeMode() bool { return self.showTree }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/node.go
pkg/gui/filetree/node.go
package filetree import ( "path" "slices" "strings" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) // Represents a file or directory in a file tree. type Node[T any] struct { // File will be nil if the node is a directory. File *T // If the node is a directory, Children contains the contents of the directory, // otherwise it's nil. Children []*Node[T] // path of the file/directory // private; use either GetPath() or GetInternalPath() to access path string // rather than render a tree as: // a/ // b/ // file.blah // // we instead render it as: // a/b/ // file.blah // This saves vertical space. The CompressionLevel of a node is equal to the // number of times a 'compression' like the above has happened, where two // nodes are squished into one. CompressionLevel int } var _ types.ListItem = &Node[models.File]{} func (self *Node[T]) IsFile() bool { return self.File != nil } func (self *Node[T]) GetFile() *T { return self.File } // This returns the logical path from the user's point of view. It is the // relative path from the root of the repository. // Use this for display, or when you want to perform some action on the path // (e.g. a git command). func (self *Node[T]) GetPath() string { return strings.TrimPrefix(self.path, "./") } // This returns the internal path from the tree's point of view. It's the same // as GetPath(), but prefixed with "./" for the root item. // Use this when interacting with the tree itself, e.g. when calling // ToggleCollapsed. func (self *Node[T]) GetInternalPath() string { return self.path } func (self *Node[T]) Sort() { self.SortChildren() for _, child := range self.Children { child.Sort() } } func (self *Node[T]) ForEachFile(cb func(*T) error) error { if self.IsFile() { if err := cb(self.File); err != nil { return err } } for _, child := range self.Children { if err := child.ForEachFile(cb); err != nil { return err } } return nil } func (self *Node[T]) SortChildren() { if self.IsFile() { return } children := slices.Clone(self.Children) slices.SortFunc(children, func(a, b *Node[T]) int { if !a.IsFile() && b.IsFile() { return -1 } if a.IsFile() && !b.IsFile() { return 1 } return strings.Compare(a.path, b.path) }) // TODO: think about making this in-place self.Children = children } func (self *Node[T]) Some(predicate func(*Node[T]) bool) bool { if predicate(self) { return true } for _, child := range self.Children { if child.Some(predicate) { return true } } return false } func (self *Node[T]) SomeFile(predicate func(*T) bool) bool { if self.IsFile() { if predicate(self.File) { return true } } else { for _, child := range self.Children { if child.SomeFile(predicate) { return true } } } return false } func (self *Node[T]) Every(predicate func(*Node[T]) bool) bool { if !predicate(self) { return false } for _, child := range self.Children { if !child.Every(predicate) { return false } } return true } func (self *Node[T]) EveryFile(predicate func(*T) bool) bool { if self.IsFile() { if !predicate(self.File) { return false } } else { for _, child := range self.Children { if !child.EveryFile(predicate) { return false } } } return true } func (self *Node[T]) FindFirstFileBy(predicate func(*T) bool) *T { if self.IsFile() { if predicate(self.File) { return self.File } } else { for _, child := range self.Children { if file := child.FindFirstFileBy(predicate); file != nil { return file } } } return nil } func (self *Node[T]) Flatten(collapsedPaths *CollapsedPaths) []*Node[T] { result := []*Node[T]{self} if len(self.Children) > 0 && !collapsedPaths.IsCollapsed(self.path) { result = append(result, lo.FlatMap(self.Children, func(child *Node[T], _ int) []*Node[T] { return child.Flatten(collapsedPaths) })...) } return result } func (self *Node[T]) GetNodeAtIndex(index int, collapsedPaths *CollapsedPaths) *Node[T] { if self == nil { return nil } node, _ := self.getNodeAtIndexAux(index, collapsedPaths) return node } func (self *Node[T]) getNodeAtIndexAux(index int, collapsedPaths *CollapsedPaths) (*Node[T], int) { offset := 1 if index == 0 { return self, offset } if !collapsedPaths.IsCollapsed(self.path) { for _, child := range self.Children { foundNode, offsetChange := child.getNodeAtIndexAux(index-offset, collapsedPaths) offset += offsetChange if foundNode != nil { return foundNode, offset } } } return nil, offset } func (self *Node[T]) GetIndexForPath(path string, collapsedPaths *CollapsedPaths) (int, bool) { offset := 0 if self.path == path { return offset, true } if !collapsedPaths.IsCollapsed(self.path) { for _, child := range self.Children { offsetChange, found := child.GetIndexForPath(path, collapsedPaths) offset += offsetChange + 1 if found { return offset, true } } } return offset, false } func (self *Node[T]) Size(collapsedPaths *CollapsedPaths) int { if self == nil { return 0 } output := 1 if !collapsedPaths.IsCollapsed(self.path) { for _, child := range self.Children { output += child.Size(collapsedPaths) } } return output } func (self *Node[T]) Compress() { if self == nil { return } self.compressAux() } func (self *Node[T]) compressAux() *Node[T] { if self.IsFile() { return self } children := self.Children for i := range children { grandchildren := children[i].Children for len(grandchildren) == 1 && !grandchildren[0].IsFile() { grandchildren[0].CompressionLevel = children[i].CompressionLevel + 1 children[i] = grandchildren[0] grandchildren = children[i].Children } } for i := range children { children[i] = children[i].compressAux() } self.Children = children return self } func (self *Node[T]) GetPathsMatching(predicate func(*Node[T]) bool) []string { paths := []string{} if predicate(self) { paths = append(paths, self.GetPath()) } for _, child := range self.Children { paths = append(paths, child.GetPathsMatching(predicate)...) } return paths } func (self *Node[T]) GetFilePathsMatching(predicate func(*T) bool) []string { matchingFileNodes := lo.Filter(self.GetLeaves(), func(node *Node[T], _ int) bool { return predicate(node.File) }) return lo.Map(matchingFileNodes, func(node *Node[T], _ int) string { return node.GetPath() }) } func (self *Node[T]) GetLeaves() []*Node[T] { if self.IsFile() { return []*Node[T]{self} } return lo.FlatMap(self.Children, func(child *Node[T], _ int) []*Node[T] { return child.GetLeaves() }) } func (self *Node[T]) ID() string { return self.GetPath() } func (self *Node[T]) Description() string { return self.GetPath() } func (self *Node[T]) Name() string { return path.Base(self.path) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/commit_file_tree_view_model.go
pkg/gui/filetree/commit_file_tree_view_model.go
package filetree import ( "strings" "sync" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/gui/context/traits" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" ) type ICommitFileTreeViewModel interface { ICommitFileTree types.IListCursor GetRef() models.Ref SetRef(models.Ref) GetRefRange() *types.RefRange // can be nil, in which case GetRef should be used SetRefRange(*types.RefRange) // should be set to nil when selection is not a range GetCanRebase() bool SetCanRebase(bool) } type CommitFileTreeViewModel struct { sync.RWMutex types.IListCursor ICommitFileTree // this is e.g. the commit for which we're viewing the files, if there is no // range selection, or if the range selection can't be used for some reason ref models.Ref // this is a commit range for which we're viewing the files. Can be nil, in // which case ref is used. refRange *types.RefRange // we set this to true when you're viewing the files within the checked-out branch's commits. // If you're viewing the files of some random other branch we can't do any rebase stuff. canRebase bool } var _ ICommitFileTreeViewModel = &CommitFileTreeViewModel{} func NewCommitFileTreeViewModel(getFiles func() []*models.CommitFile, common *common.Common, showTree bool) *CommitFileTreeViewModel { fileTree := NewCommitFileTree(getFiles, common, showTree) listCursor := traits.NewListCursor(fileTree.Len) return &CommitFileTreeViewModel{ ICommitFileTree: fileTree, IListCursor: listCursor, ref: nil, refRange: nil, canRebase: false, } } func (self *CommitFileTreeViewModel) GetRef() models.Ref { return self.ref } func (self *CommitFileTreeViewModel) SetRef(ref models.Ref) { self.ref = ref } func (self *CommitFileTreeViewModel) GetRefRange() *types.RefRange { return self.refRange } func (self *CommitFileTreeViewModel) SetRefRange(refsForRange *types.RefRange) { self.refRange = refsForRange } func (self *CommitFileTreeViewModel) GetCanRebase() bool { return self.canRebase } func (self *CommitFileTreeViewModel) SetCanRebase(canRebase bool) { self.canRebase = canRebase } func (self *CommitFileTreeViewModel) GetSelected() *CommitFileNode { if self.Len() == 0 { return nil } return self.Get(self.GetSelectedLineIdx()) } func (self *CommitFileTreeViewModel) GetSelectedItemId() string { item := self.GetSelected() if item == nil { return "" } return item.ID() } func (self *CommitFileTreeViewModel) GetSelectedItems() ([]*CommitFileNode, int, int) { if self.Len() == 0 { return nil, 0, 0 } startIdx, endIdx := self.GetSelectionRange() nodes := []*CommitFileNode{} for i := startIdx; i <= endIdx; i++ { nodes = append(nodes, self.Get(i)) } return nodes, startIdx, endIdx } func (self *CommitFileTreeViewModel) GetSelectedItemIds() ([]string, int, int) { selectedItems, startIdx, endIdx := self.GetSelectedItems() ids := lo.Map(selectedItems, func(item *CommitFileNode, _ int) string { return item.ID() }) return ids, startIdx, endIdx } func (self *CommitFileTreeViewModel) GetSelectedFile() *models.CommitFile { node := self.GetSelected() if node == nil { return nil } return node.File } func (self *CommitFileTreeViewModel) GetSelectedPath() string { node := self.GetSelected() if node == nil { return "" } return node.GetPath() } // duplicated from file_tree_view_model.go. Generics will help here func (self *CommitFileTreeViewModel) ToggleShowTree() { selectedNode := self.GetSelected() self.ICommitFileTree.ToggleShowTree() if selectedNode == nil { return } path := selectedNode.path if self.InTreeMode() { self.ExpandToPath(path) } else if len(selectedNode.Children) > 0 { path = selectedNode.GetLeaves()[0].path } index, found := self.GetIndexForPath(path) if found { self.SetSelection(index) } } func (self *CommitFileTreeViewModel) CollapseAll() { selectedNode := self.GetSelected() self.ICommitFileTree.CollapseAll() if selectedNode == nil { return } topLevelPath := strings.Split(selectedNode.path, "/")[0] index, found := self.GetIndexForPath(topLevelPath) if found { self.SetSelectedLineIdx(index) } } func (self *CommitFileTreeViewModel) ExpandAll() { selectedNode := self.GetSelected() self.ICommitFileTree.ExpandAll() if selectedNode == nil { return } index, found := self.GetIndexForPath(selectedNode.path) if found { self.SetSelectedLineIdx(index) } } // Try to select the given path if present. If it doesn't exist, or one of the parent directories is // collapsed, do nothing. // Note that filepath is an actual file path, not an internal tree path as with e.g. // ToggleCollapsed. It must be a relative path (relative to the repo root), and it must contain // forward slashes rather than backslashes even on Windows. func (self *CommitFileTreeViewModel) SelectPath(filepath string, showRootItem bool) { index, found := self.GetIndexForPath(InternalTreePathForFilePath(filepath, showRootItem)) if found { self.SetSelection(index) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/file_tree_test.go
pkg/gui/filetree/file_tree_test.go
package filetree import ( "testing" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/stretchr/testify/assert" ) func TestFilterAction(t *testing.T) { scenarios := []struct { name string filter FileTreeDisplayFilter files []*models.File expected []*models.File }{ { name: "filter files with unstaged changes", filter: DisplayUnstaged, files: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "dir2/file5", ShortStatus: "M ", HasStagedChanges: true}, {Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, }, expected: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, }, }, { name: "filter files with staged changes", filter: DisplayStaged, files: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasStagedChanges: true}, {Path: "dir2/file5", ShortStatus: "M ", HasStagedChanges: false}, {Path: "file1", ShortStatus: "M ", HasStagedChanges: true}, }, expected: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasStagedChanges: true}, {Path: "file1", ShortStatus: "M ", HasStagedChanges: true}, }, }, { name: "filter files that are tracked", filter: DisplayTracked, files: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", Tracked: true}, {Path: "dir2/file5", ShortStatus: "M ", Tracked: false}, {Path: "file1", ShortStatus: "M ", Tracked: true}, }, expected: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", Tracked: true}, {Path: "file1", ShortStatus: "M ", Tracked: true}, }, }, { name: "filter all files", filter: DisplayAll, files: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "dir2/file5", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, }, expected: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "dir2/file5", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "file1", ShortStatus: "M ", HasUnstagedChanges: true}, }, }, { name: "filter conflicted files", filter: DisplayConflicted, files: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "DU", HasMergeConflicts: true}, {Path: "dir2/file5", ShortStatus: "M ", HasUnstagedChanges: true}, {Path: "dir2/file6", ShortStatus: " M", HasStagedChanges: true}, {Path: "file1", ShortStatus: "UU", HasMergeConflicts: true, HasInlineMergeConflicts: true}, }, expected: []*models.File{ {Path: "dir2/dir2/file4", ShortStatus: "DU", HasMergeConflicts: true}, {Path: "file1", ShortStatus: "UU", HasMergeConflicts: true, HasInlineMergeConflicts: true}, }, }, } for _, s := range scenarios { t.Run(s.name, func(t *testing.T) { mngr := &FileTree{getFiles: func() []*models.File { return s.files }, filter: s.filter} result := mngr.getFilesForDisplay() assert.EqualValues(t, s.expected, result) }) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/gui/filetree/collapsed_paths.go
pkg/gui/filetree/collapsed_paths.go
package filetree import "github.com/jesseduffield/generics/set" type CollapsedPaths struct { collapsedPaths *set.Set[string] } func NewCollapsedPaths() *CollapsedPaths { return &CollapsedPaths{ collapsedPaths: set.New[string](), } } func (self *CollapsedPaths) ExpandToPath(path string) { // need every directory along the way splitPath := split(path) for i := range splitPath { dir := join(splitPath[0 : i+1]) self.collapsedPaths.Remove(dir) } } func (self *CollapsedPaths) IsCollapsed(path string) bool { return self.collapsedPaths.Includes(path) } func (self *CollapsedPaths) Collapse(path string) { self.collapsedPaths.Add(path) } func (self *CollapsedPaths) ToggleCollapsed(path string) { if self.collapsedPaths.Includes(path) { self.collapsedPaths.Remove(path) } else { self.collapsedPaths.Add(path) } } func (self *CollapsedPaths) ExpandAll() { // Could be cleaner if Set had a Clear() method... self.collapsedPaths.RemoveSlice(self.collapsedPaths.ToSlice()) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false