From 29b70105c2cf04327c11a8471146c3761c03831b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 15:29:57 +0200 Subject: [PATCH 001/218] Reintroduce the gitCmdObjBuilder wrapper This reverts commit eb988395e6d1, which removed the wrapper on the grounds that it no longer had anything to do but delegate. We're about to give it a job again: hosting a git-specific default environment variable on every command. Restore the scaffolding first, as a pure behaviour-preserving step, so the behaviour change that follows is minimal. --- pkg/commands/git_cmd_obj_builder.go | 35 +++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/pkg/commands/git_cmd_obj_builder.go b/pkg/commands/git_cmd_obj_builder.go index 6b6bd26d8..495582722 100644 --- a/pkg/commands/git_cmd_obj_builder.go +++ b/pkg/commands/git_cmd_obj_builder.go @@ -5,16 +5,37 @@ import ( "github.com/sirupsen/logrus" ) -// NewGitCmdObjBuilder returns a command object builder whose runner is wrapped -// with our git-specific runner (logging, credential handling, etc.). -func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder) *oscommands.CmdObjBuilder { - // We decorate the runner rather than exposing the builder's runner field: - // that field stays unexported so there's a single API for running commands - // across the codebase. - return innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner { +// all we're doing here is wrapping the default command object builder with +// some git-specific stuff: e.g. adding a git-specific env var + +type gitCmdObjBuilder struct { + innerBuilder *oscommands.CmdObjBuilder +} + +var _ oscommands.ICmdObjBuilder = &gitCmdObjBuilder{} + +func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder) *gitCmdObjBuilder { + // the price of having a convenient interface where we can say .New(...).Run() is that our builder now depends on our runner, so when we want to wrap the default builder/runner in new functionality we need to jump through some hoops. We could avoid the use of a decorator function here by just exporting the runner field on the default builder but that would be misleading because we don't want anybody using that to run commands (i.e. we want there to be a single API used across the codebase) + updatedBuilder := innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner { return &gitCmdObjRunner{ log: log, innerRunner: runner, } }) + + return &gitCmdObjBuilder{ + innerBuilder: updatedBuilder, + } +} + +func (self *gitCmdObjBuilder) New(args []string) *oscommands.CmdObj { + return self.innerBuilder.New(args) +} + +func (self *gitCmdObjBuilder) NewShell(cmdStr string, shellFunctionsFile string) *oscommands.CmdObj { + return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile) +} + +func (self *gitCmdObjBuilder) Quote(str string) string { + return self.innerBuilder.Quote(str) } From ccaa96b29dab7bc982d3e976a3cf8cf720a953f8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 16:05:08 +0200 Subject: [PATCH 002/218] Suppress optional locks by default again, except foreground refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit d94f2f05 dropped the GIT_OPTIONAL_LOCKS=0 env var that we used to set on every git command, and re-added lock suppression only as a --no-optional-locks flag on the background files refresh. The intent was sound — a foreground `git status` should persist git's refreshed stat-cache — but the change was too broad: it stopped suppressing optional locks for every other command too. The one that bites is the main-view diff. When a folder containing submodules is selected, we render `git diff --submodule -- `, and `--submodule` makes git run `git status` inside each submodule to describe its "modified" state. That status now grabs the submodule's index.lock. It runs as a PTY task on its own goroutine, so it races any submodule-mutating action the user triggers — e.g. resetting a submodule runs `git -C stash`, which then fails with "index.lock: File exists". This is what made submodule/reset_folder flaky. `git status` is in fact the only command that takes the optional lock, but the env var also covered its use inside `git diff --submodule`, inside PTY-run commands, and inside git's own submodule child processes — none of which a per-command flag reaches cleanly. Invert the polarity to match how it worked before d94f2f05: the git command builder disables optional locks on every command by default, and the single command that benefits from taking the lock — the foreground files refresh — opts back in. This restores the original contention avoidance (including against the user's terminal git) while keeping d94f2f05's stat-cache-persistence win for the foreground refresh. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_builder.go | 11 +++++++-- pkg/commands/git_cmd_obj_builder_test.go | 24 +++++++++++++++++++ pkg/commands/git_commands/file_loader.go | 22 ++++++++++++----- pkg/commands/git_commands/file_loader_test.go | 11 +-------- .../git_commands/git_command_builder.go | 10 ++++++++ pkg/commands/oscommands/cmd_obj.go | 13 ++++++++++ pkg/commands/oscommands/cmd_obj_test.go | 21 ++++++++++++++++ pkg/gui/types/refresh.go | 11 +++++---- 8 files changed, 100 insertions(+), 23 deletions(-) create mode 100644 pkg/commands/git_cmd_obj_builder_test.go diff --git a/pkg/commands/git_cmd_obj_builder.go b/pkg/commands/git_cmd_obj_builder.go index 495582722..6bc3b7d19 100644 --- a/pkg/commands/git_cmd_obj_builder.go +++ b/pkg/commands/git_cmd_obj_builder.go @@ -1,6 +1,7 @@ package commands import ( + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/sirupsen/logrus" ) @@ -14,6 +15,12 @@ type gitCmdObjBuilder struct { var _ oscommands.ICmdObjBuilder = &gitCmdObjBuilder{} +// We disable git's optional locks on every command by default so that our git +// invocations never contend for index.lock. See git_commands.OptionalLocksEnvVar +// for the full rationale. Individual commands that do want the lock (currently +// only the foreground files refresh) opt back in via CmdObj.RemoveEnvVar. +var defaultEnvVar = git_commands.OptionalLocksEnvVar + "=0" + func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder) *gitCmdObjBuilder { // the price of having a convenient interface where we can say .New(...).Run() is that our builder now depends on our runner, so when we want to wrap the default builder/runner in new functionality we need to jump through some hoops. We could avoid the use of a decorator function here by just exporting the runner field on the default builder but that would be misleading because we don't want anybody using that to run commands (i.e. we want there to be a single API used across the codebase) updatedBuilder := innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner { @@ -29,11 +36,11 @@ func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuild } func (self *gitCmdObjBuilder) New(args []string) *oscommands.CmdObj { - return self.innerBuilder.New(args) + return self.innerBuilder.New(args).AddEnvVars(defaultEnvVar) } func (self *gitCmdObjBuilder) NewShell(cmdStr string, shellFunctionsFile string) *oscommands.CmdObj { - return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile) + return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile).AddEnvVars(defaultEnvVar) } func (self *gitCmdObjBuilder) Quote(str string) string { diff --git a/pkg/commands/git_cmd_obj_builder_test.go b/pkg/commands/git_cmd_obj_builder_test.go new file mode 100644 index 000000000..ca7e54cfe --- /dev/null +++ b/pkg/commands/git_cmd_obj_builder_test.go @@ -0,0 +1,24 @@ +package commands + +import ( + "testing" + + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/stretchr/testify/assert" +) + +// Every git command we build disables optional locks by default, so that our +// invocations never contend for index.lock (see git_commands.OptionalLocksEnvVar +// for the rationale). Commands that want the lock opt back in with +// CmdObj.RemoveEnvVar. +func TestGitCmdObjBuilderDisablesOptionalLocksByDefault(t *testing.T) { + builder := NewGitCmdObjBuilder( + utils.NewDummyLog(), + oscommands.NewDummyCmdObjBuilder(oscommands.NewFakeRunner(t)), + ) + + assert.Contains(t, builder.New([]string{"git", "status"}).GetEnvVars(), git_commands.OptionalLocksEnvVar+"=0") + assert.Contains(t, builder.NewShell("git status", "").GetEnvVars(), git_commands.OptionalLocksEnvVar+"=0") +} diff --git a/pkg/commands/git_commands/file_loader.go b/pkg/commands/git_commands/file_loader.go index 9df977bb9..7e2bdf0f3 100644 --- a/pkg/commands/git_commands/file_loader.go +++ b/pkg/commands/git_commands/file_loader.go @@ -36,10 +36,11 @@ type GetStatusFileOptions struct { // This is useful for users with bare repos for dotfiles who default to hiding untracked files, // but want to occasionally see them to `git add` a new file. ForceShowUntracked bool - // When true, this status is part of an unattended background refresh, so we - // pass --no-optional-locks to avoid index.lock contention with git commands - // the user runs in a terminal (at the cost of not persisting git's refreshed - // stat-cache). + // When true, this status is part of an unattended background refresh, so it + // keeps the default suppression of optional locks (avoiding index.lock + // contention with git commands the user runs in a terminal, at the cost of + // not persisting git's refreshed stat-cache). A foreground status opts back + // in; see gitStatus. Background bool } @@ -175,7 +176,6 @@ func (self *FileLoader) gitDiffNumStat() (string, error) { func (self *FileLoader) gitStatus(opts GitStatusOptions) ([]FileStatus, error) { cmdArgs := NewGitCmd("status"). - GlobalArgIf(opts.Background, "--no-optional-locks"). Arg(opts.UntrackedFilesArg). Arg("--porcelain"). Arg("-z"). @@ -186,7 +186,17 @@ func (self *FileLoader) gitStatus(opts GitStatusOptions) ([]FileStatus, error) { ). ToArgv() - statusLines, _, err := self.cmd.New(cmdArgs).DontLog().RunWithOutputs() + cmdObj := self.cmd.New(cmdArgs).DontLog() + if !opts.Background { + // Every git command suppresses optional locks by default (see + // OptionalLocksEnvVar). A foreground refresh is the one exception: we let + // it take the lock so it persists git's refreshed stat-cache, which keeps + // subsequent status calls fast. Background refreshes leave it suppressed so + // they can't contend for index.lock. + cmdObj.RemoveEnvVar(OptionalLocksEnvVar) + } + + statusLines, _, err := cmdObj.RunWithOutputs() if err != nil { return []FileStatus{}, err } diff --git a/pkg/commands/git_commands/file_loader_test.go b/pkg/commands/git_commands/file_loader_test.go index 4f6b5e136..ec1f502f1 100644 --- a/pkg/commands/git_commands/file_loader_test.go +++ b/pkg/commands/git_commands/file_loader_test.go @@ -13,7 +13,6 @@ func TestFileGetStatusFiles(t *testing.T) { type scenario struct { testName string similarityThreshold int - background bool runner oscommands.ICmdObjRunner showNumstatInFilesView bool expectedFiles []*models.File @@ -27,14 +26,6 @@ func TestFileGetStatusFiles(t *testing.T) { ExpectGitArgs([]string{"status", "--untracked-files=yes", "--porcelain", "-z", "--find-renames=50%"}, "", nil), expectedFiles: []*models.File{}, }, - { - testName: "Background refresh passes --no-optional-locks", - similarityThreshold: 50, - background: true, - runner: oscommands.NewFakeRunner(t). - ExpectGitArgs([]string{"--no-optional-locks", "status", "--untracked-files=yes", "--porcelain", "-z", "--find-renames=50%"}, "", nil), - expectedFiles: []*models.File{}, - }, { testName: "Several files found", similarityThreshold: 50, @@ -255,7 +246,7 @@ func TestFileGetStatusFiles(t *testing.T) { getFileType: func(string) string { return "file" }, } - assert.EqualValues(t, s.expectedFiles, loader.GetStatusFiles(GetStatusFileOptions{Background: s.background})) + assert.EqualValues(t, s.expectedFiles, loader.GetStatusFiles(GetStatusFileOptions{})) }) } } diff --git a/pkg/commands/git_commands/git_command_builder.go b/pkg/commands/git_commands/git_command_builder.go index 4178cbd22..ebd060928 100644 --- a/pkg/commands/git_commands/git_command_builder.go +++ b/pkg/commands/git_commands/git_command_builder.go @@ -6,6 +6,16 @@ import ( "github.com/jesseduffield/lazygit/pkg/commands/oscommands" ) +// OptionalLocksEnvVar is the name of the environment variable that tells git +// whether it may take "optional" locks — chiefly the index.lock that `git +// status` grabs to write back a refreshed stat-cache. We set it to 0 on every +// git command by default (see NewGitCmdObjBuilder) so our invocations never +// contend for index.lock, neither with each other (e.g. a main-view `git diff +// --submodule`, which runs `git status` inside submodules, racing a submodule +// action) nor with git commands the user runs in a terminal. The one command +// that opts back in is the foreground files refresh; see FileLoader.gitStatus. +const OptionalLocksEnvVar = "GIT_OPTIONAL_LOCKS" + // convenience struct for building git commands. Especially useful when // including conditional args type GitCommandBuilder struct { diff --git a/pkg/commands/oscommands/cmd_obj.go b/pkg/commands/oscommands/cmd_obj.go index 0df6ed43c..57bc295ed 100644 --- a/pkg/commands/oscommands/cmd_obj.go +++ b/pkg/commands/oscommands/cmd_obj.go @@ -91,6 +91,19 @@ func (self *CmdObj) AddEnvVars(vars ...string) *CmdObj { return self } +// RemoveEnvVar removes every occurrence of the named environment variable from +// the command's environment. It's the counterpart to AddEnvVars, used to opt a +// single command out of a variable that the builder sets on every command by +// default. +func (self *CmdObj) RemoveEnvVar(name string) *CmdObj { + prefix := name + "=" + self.cmd.Env = lo.Filter(self.cmd.Env, func(envVar string, _ int) bool { + return !strings.HasPrefix(envVar, prefix) + }) + + return self +} + func (self *CmdObj) GetEnvVars() []string { return self.cmd.Env } diff --git a/pkg/commands/oscommands/cmd_obj_test.go b/pkg/commands/oscommands/cmd_obj_test.go index 269b5dac2..56aab918b 100644 --- a/pkg/commands/oscommands/cmd_obj_test.go +++ b/pkg/commands/oscommands/cmd_obj_test.go @@ -5,8 +5,29 @@ import ( "testing" "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/stretchr/testify/assert" ) +func TestRemoveEnvVar(t *testing.T) { + cmd := exec.Command("git", "status") + cmd.Env = []string{ + "PATH=/usr/bin", + "GIT_OPTIONAL_LOCKS=0", + "GIT_OPTIONAL_LOCKS_OTHER=1", // name is a prefix of ours but not the same var + "GIT_OPTIONAL_LOCKS=0", // duplicates must all be removed + "HOME=/home/me", + } + cmdObj := &CmdObj{cmd: cmd} + + cmdObj.RemoveEnvVar("GIT_OPTIONAL_LOCKS") + + assert.Equal(t, []string{ + "PATH=/usr/bin", + "GIT_OPTIONAL_LOCKS_OTHER=1", + "HOME=/home/me", + }, cmdObj.GetEnvVars()) +} + func TestCmdObjToString(t *testing.T) { quote := func(s string) string { return "\"" + s + "\"" diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index 17d917bf6..8d9704d55 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -72,10 +72,11 @@ type RefreshOptions struct { CommitSelection CommitSelectionBehavior // When true, this refresh was initiated by a background routine rather than - // by a user action. We use it to keep background `git status` calls from - // taking optional git locks, so they don't contend for index.lock with git - // commands the user runs in a terminal. The cost is that such a status won't - // persist git's refreshed stat-cache, which is the right trade-off for - // unattended work; foreground refreshes leave this false so they do persist. + // by a user action. Every git command suppresses optional locks by default + // so it can't contend for index.lock (see git_commands.OptionalLocksEnvVar); + // a foreground files refresh (this false) is the one command that opts back + // in, so it persists git's refreshed stat-cache and keeps later status calls + // fast. Background refreshes leave the suppression in place: not persisting + // the stat-cache is the right trade-off for unattended work. Background bool } From 4fcf6ddb5f21701833069602793836764f419b4d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 16:49:00 +0200 Subject: [PATCH 003/218] Revert "Add GlobalArg/GlobalArgIf to GitCommandBuilder" After the previous commit this is no longer needed. This reverts commit 94db69f64b7b05840cdf2839bd987f856f9b1d63. --- pkg/commands/git_commands/git_command_builder.go | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/pkg/commands/git_commands/git_command_builder.go b/pkg/commands/git_commands/git_command_builder.go index ebd060928..f37681223 100644 --- a/pkg/commands/git_commands/git_command_builder.go +++ b/pkg/commands/git_commands/git_command_builder.go @@ -48,22 +48,6 @@ func (self *GitCommandBuilder) ArgIfElse(condition bool, ifTrue string, ifFalse return self.Arg(ifFalse) } -// GlobalArg adds top-level options for git itself (e.g. --no-optional-locks). -// Unlike Arg, these are prepended before the command, where git expects them. -func (self *GitCommandBuilder) GlobalArg(args ...string) *GitCommandBuilder { - self.args = append(append([]string{}, args...), self.args...) - - return self -} - -func (self *GitCommandBuilder) GlobalArgIf(condition bool, args ...string) *GitCommandBuilder { - if condition { - self.GlobalArg(args...) - } - - return self -} - func (self *GitCommandBuilder) Config(value string) *GitCommandBuilder { // config settings come before the command self.args = append([]string{"-c", value}, self.args...) From e53c72be52277509957070a27a7051719ed685c2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 11 May 2026 17:46:57 +0200 Subject: [PATCH 004/218] Make ViewBufferManager.NewTask respect call order NewTask was incrementing newTaskID and reading taskID inside the spawned goroutine, so for two NewTask calls in quick succession the assignment was determined by goroutine scheduling order rather than call order. When the goroutines reordered, the first NewTask call could end up with the higher taskID and "win" the staleness check, superseding the second call's task even though the caller intended the second to be the latest. Worse, the staleness check ran after onNewKey, so a goroutine destined to bail as stale would still reset the view buffer first, potentially wiping the winning task's already-written output. Take newTaskID++ synchronously in NewTask so taskIDs follow call order, and move the first staleness check ahead of onNewKey so a stale task doesn't side-effect the view before exiting. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/tasks/tasks.go | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index f534d01b4..7fadbb451 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -403,12 +403,29 @@ func (self *ViewBufferManager) NewTask(f func(TaskOpts) error, key string) error }) } + // Assign the taskID synchronously so it reflects NewTask call order + // rather than the order in which the spawned goroutines happen to be + // scheduled. Otherwise two NewTask calls in quick succession can have + // their goroutines race, with the later-called task ending up with the + // lower taskID and losing the staleness check below. + self.taskIDMutex.Lock() + self.newTaskID++ + taskID := self.newTaskID + self.taskIDMutex.Unlock() + go utils.Safe(func() { defer completeGocuiTask() self.taskIDMutex.Lock() - self.newTaskID++ - taskID := self.newTaskID + + // Bail out before touching shared view state if a newer task has + // already been queued: if we ran onNewKey here we'd reset the view + // for a task that's about to exit, potentially wiping output the + // winning task has already written. + if taskID < self.newTaskID { + self.taskIDMutex.Unlock() + return + } if self.GetTaskKey() != key && self.onNewKey != nil { self.onNewKey() @@ -419,6 +436,8 @@ func (self *ViewBufferManager) NewTask(f func(TaskOpts) error, key string) error self.waitingMutex.Lock() + // Re-check staleness after acquiring waitingMutex: a newer task + // may have arrived while we were blocked here. self.taskIDMutex.Lock() if taskID < self.newTaskID { self.waitingMutex.Unlock() From badf398a94fbd4fe39eb569ce95b8543c2289c8e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 11 May 2026 20:42:05 +0200 Subject: [PATCH 005/218] Run moveMainContextPairToTop before queueing main-view tasks Copy the outgoing view's content into the target view (the flicker- prevention step) before queuing the render task, rather than after. The task writes the fresh content from a worker goroutine, so with the old order the worker write races the UI-thread copy, and the copy can land last and clobber the fresh content with stale output. This is only needed while view writes happen concurrently. Once view writes are serialized on the UI thread and the view write-mutex goes away, the synchronous copy always precedes the FIFO-queued write regardless of order, so the reorder becomes unnecessary. No code comment is added for it, since that comment would be obsoleted by that work and likely left behind. --- pkg/gui/main_panels.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index 82f4fcac0..03b7469d2 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -117,6 +117,8 @@ func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) { } } + gui.moveMainContextPairToTop(opts.Pair) + if opts.Main != nil { gui.RefreshMainView(opts.Main, opts.Pair.Main) } @@ -127,8 +129,6 @@ func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) { opts.Pair.Secondary.GetView().Clear() } - gui.moveMainContextPairToTop(opts.Pair) - gui.splitMainPanel(opts.Secondary != nil) } From 873804a37b24e3c23c3c5f3374dd7965a6de4b98 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 15:27:31 +0200 Subject: [PATCH 006/218] Make Gui.Update a synchronous FIFO enqueue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update spawned a goroutine per call that then sent on the user-events channel, so multiple Update calls from the same goroutine could be reordered by the scheduler — the doc comment even admitted "the order in which the user events will be handled is not guaranteed." That non-determinism is a latent source of flaky rendering: code that queues a model update and then a render in source order could see them run in the opposite order. Send on the channel directly instead, so same-goroutine calls arrive in source order. The send is non-blocking and panics on a full channel rather than blocking (a blocked send from the UI goroutine would deadlock against itself) or silently reordering; the buffer is sized generously so this is unreachable in normal use. UpdateAsync is now identical to Update and unused, so it's removed along with the shared updateAsyncAux helper. --- pkg/gocui/gui.go | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 558b9d619..ee1995911 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -238,7 +238,12 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { g.stop = make(chan struct{}) g.gEvents = make(chan GocuiEvent, 20) - g.userEvents = make(chan userEvent, 20) + // Update does a non-blocking send and panics on a full channel rather than + // blocking (which would deadlock the UI goroutine against itself) or + // silently reordering. The buffer is sized well above the peak occupancy we + // see in practice, so the panic stays unreachable in normal use; if it ever + // fires, that's a real anomaly to investigate, not a cue to grow the buffer. + g.userEvents = make(chan userEvent, 256) g.taskManager = newTaskManager() if opts.PlayRecording { @@ -613,28 +618,23 @@ type userEvent struct { contentOnly bool } -// Update executes the passed function. This method can be called safely from a -// goroutine in order to update the GUI. It is important to note that the -// passed function won't be executed immediately, instead it will be added to -// the user events queue. Given that Update spawns a goroutine, the order in -// which the user events will be handled is not guaranteed. +// Update enqueues f on the user-events channel for the UI loop to run on its +// next iteration. Multiple Update calls from the same goroutine arrive in +// source order via the channel's FIFO. The send is non-blocking — if the +// channel is full we panic rather than block or silently reorder, since a +// blocked send from the UI goroutine would deadlock against itself and +// silently switching to inline execution would break the ordering guarantee +// callers rely on. The buffer is sized generously enough that this should +// never fire in practice; if it does, that's a signal to investigate, not +// to grow the buffer reflexively. func (g *Gui) Update(f func(*Gui) error) { task := g.NewTask() - go g.updateAsyncAux(f, task) -} - -// UpdateAsync is a version of Update that does not spawn a go routine, it can -// be a bit more efficient in cases where Update is called many times like when -// tailing a file. In general you should use Update() -func (g *Gui) UpdateAsync(f func(*Gui) error) { - task := g.NewTask() - - g.updateAsyncAux(f, task) -} - -func (g *Gui) updateAsyncAux(f func(*Gui) error, task Task) { - g.userEvents <- userEvent{f: f, task: task} + select { + case g.userEvents <- userEvent{f: f, task: task}: + default: + panic("gocui: userEvents channel full; refusing to block or reorder") + } } // Like Update, but signals that the callback only modifies content. From ad507d67f48674ab71669b766fe061d0a933dda1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 17:38:09 +0200 Subject: [PATCH 007/218] Only prompt to continue a rebase/merge if we started it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When conflicts of an in-progress rebase/merge/cherry-pick/revert are resolved, lazygit pops up a prompt offering to continue it. This is helpful when you started the operation in lazygit and resolved the conflicts in your editor. But it's confusing when the operation was started outside lazygit — e.g. by a coding agent in another terminal that resolves the conflicts but hasn't continued yet because it's still running tests or fixing the build. lazygit would then prompt unbidden. Track whether the in-progress operation was started from within lazygit, and only show the prompt in that case. We record this right after running a merge/rebase step (in CheckMergeOrRebaseWithRefreshOptions, the subprocess branch of genericMergeCommand, and the custom-command conflict path), and clear it whenever a refresh observes that no operation is in progress — which also handles an operation that was finished or aborted externally. The conflict-resolution tests start their operation by running git directly (not through lazygit's UI), so they call the new test helper Common.PretendMergeOrRebaseStartedInLazygit to have lazygit treat the operation as its own and still get the prompt. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 13 ++++++ pkg/gui/controllers/helpers/refresh_helper.go | 11 ++++- pkg/gui/gui.go | 16 ++++++++ pkg/gui/gui_driver.go | 9 ++++ .../custom_commands/handler_creator.go | 4 ++ pkg/gui/types/common.go | 2 + pkg/integration/components/common.go | 8 ++++ pkg/integration/components/test_test.go | 2 + .../tests/conflicts/merge_file_both.go | 2 + .../tests/conflicts/merge_file_current.go | 2 + .../tests/conflicts/merge_file_incoming.go | 2 + .../tests/conflicts/pick_both_hunks_diff3.go | 2 + .../tests/conflicts/resolve_externally.go | 2 + ...olve_externally_started_merge_no_prompt.go | 41 +++++++++++++++++++ .../tests/conflicts/resolve_multiple_files.go | 2 + .../conflicts/resolve_without_trailing_lf.go | 2 + .../tests/file/discard_all_dir_changes.go | 2 + .../tests/file/discard_various_changes.go | 2 + .../discard_various_changes_range_select.go | 2 + pkg/integration/tests/test_list.go | 1 + pkg/integration/types/types.go | 5 +++ 21 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 pkg/integration/tests/conflicts/resolve_externally_started_merge_no_prompt.go diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 536c254dd..2b7f9cd16 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -113,6 +113,7 @@ func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(success && selectHeadCommitOnSuccess), }) + self.RecordWhetherMergeOrRebaseStartedInLazygit() return err } result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) @@ -165,9 +166,21 @@ func isMergeConflictErr(errStr string) bool { return false } +// RecordWhetherMergeOrRebaseStartedInLazygit is called right after we run a +// merge/rebase/cherry-pick/revert step. If it left an operation in progress, +// that operation is one we started, which is what later lets us auto-prompt to +// continue it once its conflicts are resolved. If nothing is in progress +// anymore (the step completed or aborted the operation), we clear the flag. +func (self *MergeAndRebaseHelper) RecordWhetherMergeOrRebaseStartedInLazygit() { + self.c.State().GetRepoState().SetMergeOrRebaseStartedInLazygit( + self.c.Git().Status.WorkingTreeState().Any()) +} + func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result error, refreshOptions types.RefreshOptions) error { self.c.Refresh(refreshOptions) + self.RecordWhetherMergeOrRebaseStartedInLazygit() + if result == nil { return nil } else if strings.Contains(result.Error(), "No changes - did you forget to use") { diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 605309f9f..e40e0acd5 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -806,7 +806,16 @@ func (self *RefreshHelper) refreshStateFiles(background bool) error { } } - if self.c.Git().Status.WorkingTreeState().Any() && conflictFileCount == 0 && prevConflictFileCount > 0 { + repoState := self.c.State().GetRepoState() + if self.c.Git().Status.WorkingTreeState().None() { + // No operation is in progress (any more), so forget that we started one. + // This also covers an operation that was finished or aborted externally. + repoState.SetMergeOrRebaseStartedInLazygit(false) + } else if conflictFileCount == 0 && prevConflictFileCount > 0 && repoState.GetMergeOrRebaseStartedInLazygit() { + // The conflicts of an operation we started have just been resolved (e.g. + // in the user's editor). Offer to continue it. We only do this for + // operations we started ourselves; prompting for one that was started + // outside lazygit (e.g. by a coding agent) would be confusing. self.c.OnUIThread(func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) } diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index dfc71d642..08d560ce5 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -255,6 +255,14 @@ type GuiRepoState struct { CurrentPopupOpts *types.CreatePopupPanelOpts LastBackgroundFetchTime time.Time + + // Whether the rebase/merge/cherry-pick/revert that's currently in progress + // was started from within lazygit (as opposed to being started externally, + // e.g. in another terminal or by a coding agent). We only auto-prompt to + // continue such an operation once its conflicts are resolved if we started + // it ourselves; for an externally started one, popping up unbidden would be + // confusing. Reset whenever we observe that no operation is in progress. + mergeOrRebaseStartedInLazygit bool } var _ types.IRepoStateAccessor = new(GuiRepoState) @@ -283,6 +291,14 @@ func (self *GuiRepoState) SetCurrentPopupOpts(value *types.CreatePopupPanelOpts) self.CurrentPopupOpts = value } +func (self *GuiRepoState) GetMergeOrRebaseStartedInLazygit() bool { + return self.mergeOrRebaseStartedInLazygit +} + +func (self *GuiRepoState) SetMergeOrRebaseStartedInLazygit(value bool) { + self.mergeOrRebaseStartedInLazygit = value +} + func (self *GuiRepoState) GetScreenMode() types.ScreenMode { return self.ScreenMode } diff --git a/pkg/gui/gui_driver.go b/pkg/gui/gui_driver.go index 57425231a..fef33bf66 100644 --- a/pkg/gui/gui_driver.go +++ b/pkg/gui/gui_driver.go @@ -68,6 +68,15 @@ func (self *GuiDriver) FocusIn() { self.waitTillIdle() } +func (self *GuiDriver) PretendMergeOrRebaseStartedInLazygit() { + self.gui.onUIThread(func() error { + self.gui.State.SetMergeOrRebaseStartedInLazygit(true) + return nil + }) + + self.waitTillIdle() +} + // wait until lazygit is idle (i.e. all processing is done) before continuing func (self *GuiDriver) waitTillIdle() { <-self.isIdleChan diff --git a/pkg/gui/services/custom_commands/handler_creator.go b/pkg/gui/services/custom_commands/handler_creator.go index 19694c481..1e321c2de 100644 --- a/pkg/gui/services/custom_commands/handler_creator.go +++ b/pkg/gui/services/custom_commands/handler_creator.go @@ -318,6 +318,10 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses if err != nil { if customCommand.After != nil && customCommand.After.CheckForConflicts { + // The custom command may have started a rebase/merge/etc.; if so, + // it's one we consider started in lazygit, so that we offer to + // continue it once its conflicts are resolved. + self.mergeAndRebaseHelper.RecordWhetherMergeOrRebaseStartedInLazygit() return self.mergeAndRebaseHelper.CheckForConflicts(err) } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index b81fb15e1..7621f8686 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -401,6 +401,8 @@ type IRepoStateAccessor interface { GetSearchState() *SearchState SetSplitMainPanel(bool) GetSplitMainPanel() bool + GetMergeOrRebaseStartedInLazygit() bool + SetMergeOrRebaseStartedInLazygit(bool) } // startup stages so we don't need to load everything at once diff --git a/pkg/integration/components/common.go b/pkg/integration/components/common.go index 2d62e9ea3..f338be52f 100644 --- a/pkg/integration/components/common.go +++ b/pkg/integration/components/common.go @@ -38,6 +38,14 @@ func (self *Common) AbortMerge() { Confirm() } +// PretendMergeOrRebaseStartedInLazygit tells lazygit to treat the in-progress +// rebase/merge/etc. as one that it started, so that it will prompt to continue +// once the conflicts are resolved. Use it when a test sets up an operation by +// running git directly rather than through lazygit's UI. +func (self *Common) PretendMergeOrRebaseStartedInLazygit() { + self.t.gui.PretendMergeOrRebaseStartedInLazygit() +} + func (self *Common) AcknowledgeConflicts() { self.t.ExpectPopup().Menu(). Title(Equals("Conflicts!")). diff --git a/pkg/integration/components/test_test.go b/pkg/integration/components/test_test.go index e7d03ada9..e7fd0b66a 100644 --- a/pkg/integration/components/test_test.go +++ b/pkg/integration/components/test_test.go @@ -93,6 +93,8 @@ func (self *fakeGuiDriver) CheckAllToastsAcknowledged() {} func (self *fakeGuiDriver) Headless() bool { return false } +func (self *fakeGuiDriver) PretendMergeOrRebaseStartedInLazygit() {} + func TestManualFailure(t *testing.T) { test := NewIntegrationTest(NewIntegrationTestArgs{ Description: unitTestDescription, diff --git a/pkg/integration/tests/conflicts/merge_file_both.go b/pkg/integration/tests/conflicts/merge_file_both.go index 083572125..eb1d0b192 100644 --- a/pkg/integration/tests/conflicts/merge_file_both.go +++ b/pkg/integration/tests/conflicts/merge_file_both.go @@ -55,6 +55,8 @@ var MergeFileBoth = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { _, _, _, expected := testDataBoth() + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/merge_file_current.go b/pkg/integration/tests/conflicts/merge_file_current.go index b80917446..68cf990e5 100644 --- a/pkg/integration/tests/conflicts/merge_file_current.go +++ b/pkg/integration/tests/conflicts/merge_file_current.go @@ -54,6 +54,8 @@ var MergeFileCurrent = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { _, _, _, expected := testDataCurrent() + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/merge_file_incoming.go b/pkg/integration/tests/conflicts/merge_file_incoming.go index 8216b4a4d..17667b296 100644 --- a/pkg/integration/tests/conflicts/merge_file_incoming.go +++ b/pkg/integration/tests/conflicts/merge_file_incoming.go @@ -54,6 +54,8 @@ var MergeFileIncoming = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { _, _, _, expected := testDataIncoming() + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/pick_both_hunks_diff3.go b/pkg/integration/tests/conflicts/pick_both_hunks_diff3.go index 59a634c3b..6e9a6eb92 100644 --- a/pkg/integration/tests/conflicts/pick_both_hunks_diff3.go +++ b/pkg/integration/tests/conflicts/pick_both_hunks_diff3.go @@ -16,6 +16,8 @@ var PickBothHunksDiff3 = NewIntegrationTest(NewIntegrationTestArgs{ shared.CreateMergeConflictFile(shell) }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/resolve_externally.go b/pkg/integration/tests/conflicts/resolve_externally.go index ab045f233..bffb2d023 100644 --- a/pkg/integration/tests/conflicts/resolve_externally.go +++ b/pkg/integration/tests/conflicts/resolve_externally.go @@ -15,6 +15,8 @@ var ResolveExternally = NewIntegrationTest(NewIntegrationTestArgs{ shared.CreateMergeConflictFile(shell) }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/resolve_externally_started_merge_no_prompt.go b/pkg/integration/tests/conflicts/resolve_externally_started_merge_no_prompt.go new file mode 100644 index 000000000..ec83f3f08 --- /dev/null +++ b/pkg/integration/tests/conflicts/resolve_externally_started_merge_no_prompt.go @@ -0,0 +1,41 @@ +package conflicts + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var ResolveExternallyStartedMergeNoPrompt = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "When a merge started outside lazygit has its conflicts resolved, don't prompt to continue it", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + // Start the merge by running git directly and never tell lazygit it was + // the one to start it, so from lazygit's point of view it was started + // externally (e.g. by a coding agent in another terminal). + shared.CreateMergeConflictFile(shell) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("UU file").IsSelected(), + ). + Tap(func() { + t.Shell().UpdateFile("file", "resolved content") + }). + Press(keys.Universal.Refresh) + + // No prompt to continue the merge appears; we stay in the files view + // with the conflict resolved and the merge still in progress. + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file"), + ) + + t.Views().Information().Content(Contains("Merging")) + }, +}) diff --git a/pkg/integration/tests/conflicts/resolve_multiple_files.go b/pkg/integration/tests/conflicts/resolve_multiple_files.go index 7dd88e02c..5a8f9447e 100644 --- a/pkg/integration/tests/conflicts/resolve_multiple_files.go +++ b/pkg/integration/tests/conflicts/resolve_multiple_files.go @@ -15,6 +15,8 @@ var ResolveMultipleFiles = NewIntegrationTest(NewIntegrationTestArgs{ shared.CreateMergeConflictFiles(shell) }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/conflicts/resolve_without_trailing_lf.go b/pkg/integration/tests/conflicts/resolve_without_trailing_lf.go index 3deafb288..30ae73e54 100644 --- a/pkg/integration/tests/conflicts/resolve_without_trailing_lf.go +++ b/pkg/integration/tests/conflicts/resolve_without_trailing_lf.go @@ -24,6 +24,8 @@ var ResolveWithoutTrailingLf = NewIntegrationTest(NewIntegrationTestArgs{ RunCommandExpectError([]string{"git", "merge", "--no-edit", "branch2"}) }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/file/discard_all_dir_changes.go b/pkg/integration/tests/file/discard_all_dir_changes.go index 6caa3d519..d4c7c4d0f 100644 --- a/pkg/integration/tests/file/discard_all_dir_changes.go +++ b/pkg/integration/tests/file/discard_all_dir_changes.go @@ -73,6 +73,8 @@ var DiscardAllDirChanges = NewIntegrationTest(NewIntegrationTestArgs{ shell.RunShellCommand(`echo "renamed\nhaha" > dir/renamed2.txt && git add dir/renamed2.txt`) }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/file/discard_various_changes.go b/pkg/integration/tests/file/discard_various_changes.go index bc68fd218..453c8708c 100644 --- a/pkg/integration/tests/file/discard_various_changes.go +++ b/pkg/integration/tests/file/discard_various_changes.go @@ -16,6 +16,8 @@ var DiscardVariousChanges = NewIntegrationTest(NewIntegrationTestArgs{ }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + type statusFile struct { status string label string diff --git a/pkg/integration/tests/file/discard_various_changes_range_select.go b/pkg/integration/tests/file/discard_various_changes_range_select.go index 937c50114..16ecedd04 100644 --- a/pkg/integration/tests/file/discard_various_changes_range_select.go +++ b/pkg/integration/tests/file/discard_various_changes_range_select.go @@ -16,6 +16,8 @@ var DiscardVariousChangesRangeSelect = NewIntegrationTest(NewIntegrationTestArgs }, Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + t.Views().Files(). IsFocused(). Lines( diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index a6105c646..554dc726f 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -169,6 +169,7 @@ var tests = []*components.IntegrationTest{ conflicts.MergeFileIncoming, conflicts.PickBothHunksDiff3, conflicts.ResolveExternally, + conflicts.ResolveExternallyStartedMergeNoPrompt, conflicts.ResolveMultipleFiles, conflicts.ResolveNoAutoStage, conflicts.ResolveNonTextualConflicts, diff --git a/pkg/integration/types/types.go b/pkg/integration/types/types.go index cd6102cdf..34ce499cc 100644 --- a/pkg/integration/types/types.go +++ b/pkg/integration/types/types.go @@ -52,4 +52,9 @@ type GuiDriver interface { NextToast() *string CheckAllToastsAcknowledged() Headless() bool + // Record that the in-progress rebase/merge/etc. is to be treated as one + // that was started from within lazygit. Lets a test that starts an + // operation by running git directly (rather than through the UI) still get + // the "continue?" prompt when its conflicts are resolved. + PretendMergeOrRebaseStartedInLazygit() } From 90d8ef499c726efde9e2b68844a7337090e9d214 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 17:43:05 +0200 Subject: [PATCH 008/218] Auto-dismiss the continue-rebase prompt when it becomes stale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The prompt offering to continue a rebase/merge is opened from a refresh and then left to sit until the user acts on it. But the operation can change out from under it: a coding agent (or the user in another terminal) might continue or abort it, or advance it to a commit with new conflicts. The prompt then becomes stale — pressing continue fails with "no rebase in progress" or acts on the wrong state. Track whether the prompt is showing, and on each refresh dismiss it if the operation is no longer in the "resolved, ready to continue" state that the prompt is offering to act on. This runs on the same refreshes that would open it (including the background poll and the refresh on window focus), so the prompt disappears on its own shortly after the operation moves on. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 35 +++++++++++++ pkg/gui/controllers/helpers/refresh_helper.go | 28 ++++++++--- ...ompt_dismissed_when_resolved_externally.go | 49 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 4 files changed, 106 insertions(+), 7 deletions(-) create mode 100644 pkg/integration/tests/conflicts/continue_prompt_dismissed_when_resolved_externally.go diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 2b7f9cd16..be1d7b3a9 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -18,6 +18,13 @@ import ( type MergeAndRebaseHelper struct { c *HelperCommon + + // Whether the "continue the rebase/merge?" prompt is currently on screen. + // We use this to auto-dismiss it if the operation stops being in the state + // that the prompt is offering to act on (e.g. it was continued or aborted + // externally), so the user isn't left with a stale prompt. Only accessed on + // the UI thread. + continueRebasePromptShowing bool } func NewMergeAndRebaseHelper( @@ -259,10 +266,17 @@ func (self *MergeAndRebaseHelper) AbortMergeOrRebaseWithConfirm() error { // PromptToContinueRebase asks the user if they want to continue the rebase/merge that's in progress func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { + self.continueRebasePromptShowing = true self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Continue, Prompt: fmt.Sprintf(self.c.Tr.ConflictsResolved, self.c.Git().Status.WorkingTreeState().CommandName()), + HandleClose: func() error { + self.continueRebasePromptShowing = false + return nil + }, HandleConfirm: func() error { + self.continueRebasePromptShowing = false + // By the time we get here, we might have unstaged changes again, // e.g. if the user had to fix build errors after resolving the // conflicts, but after lazygit opened the prompt already. Ask again @@ -300,6 +314,27 @@ func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { return nil } +// DismissContinueRebasePromptIfShowing closes the "continue the rebase/merge?" +// prompt if it's currently on screen. It's called when the operation is no +// longer in the state the prompt is offering to act on (e.g. it was continued +// or aborted outside lazygit, or new conflicts have appeared), so that the +// user isn't left with a prompt whose "continue" would now be wrong or fail. +// Must be called on the UI thread. +func (self *MergeAndRebaseHelper) DismissContinueRebasePromptIfShowing() { + if !self.continueRebasePromptShowing { + return + } + + self.continueRebasePromptShowing = false + + // Guard against popping something else: while our prompt is up no other + // popup can open, and confirming or closing it would have cleared the flag, + // so if it's set the confirmation context is ours. + if self.c.Context().Current() == self.c.Contexts().Confirmation { + self.c.Context().Pop() + } +} + func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { checkedOutBranch := self.c.Model().Branches[0] checkedOutBranchName := checkedOutBranch.Name diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index e40e0acd5..3dbd19674 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -807,16 +807,30 @@ func (self *RefreshHelper) refreshStateFiles(background bool) error { } repoState := self.c.State().GetRepoState() - if self.c.Git().Status.WorkingTreeState().None() { + workingTreeState := self.c.Git().Status.WorkingTreeState() + if workingTreeState.None() { // No operation is in progress (any more), so forget that we started one. // This also covers an operation that was finished or aborted externally. repoState.SetMergeOrRebaseStartedInLazygit(false) - } else if conflictFileCount == 0 && prevConflictFileCount > 0 && repoState.GetMergeOrRebaseStartedInLazygit() { - // The conflicts of an operation we started have just been resolved (e.g. - // in the user's editor). Offer to continue it. We only do this for - // operations we started ourselves; prompting for one that was started - // outside lazygit (e.g. by a coding agent) would be confusing. - self.c.OnUIThread(func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) + } + + if workingTreeState.Any() && conflictFileCount == 0 { + if prevConflictFileCount > 0 && repoState.GetMergeOrRebaseStartedInLazygit() { + // The conflicts of an operation we started have just been resolved + // (e.g. in the user's editor). Offer to continue it. We only do this + // for operations we started ourselves; prompting for one that was + // started outside lazygit (e.g. by a coding agent) would be confusing. + self.c.OnUIThread(func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) + } + } else { + // Either there's no operation in progress any more, or new conflicts have + // appeared. Either way, a "continue?" prompt we're showing is now stale + // (e.g. the operation was continued or aborted outside lazygit), so + // dismiss it rather than leave the user with a prompt that would fail. + self.c.OnUIThread(func() error { + self.mergeAndRebaseHelper.DismissContinueRebasePromptIfShowing() + return nil + }) } fileTreeViewModel.RWMutex.Lock() diff --git a/pkg/integration/tests/conflicts/continue_prompt_dismissed_when_resolved_externally.go b/pkg/integration/tests/conflicts/continue_prompt_dismissed_when_resolved_externally.go new file mode 100644 index 000000000..e9b2ba3aa --- /dev/null +++ b/pkg/integration/tests/conflicts/continue_prompt_dismissed_when_resolved_externally.go @@ -0,0 +1,49 @@ +package conflicts + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var ContinuePromptDismissedWhenResolvedExternally = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "When the prompt to continue a merge is showing and the merge is then continued outside lazygit, dismiss the prompt", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shared.CreateMergeConflictFile(shell) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Common().PretendMergeOrRebaseStartedInLazygit() + + // Resolve the conflict and refresh so lazygit prompts us to continue. + t.Views().Files(). + IsFocused(). + Lines( + Contains("UU file").IsSelected(), + ). + Tap(func() { + t.Shell().UpdateFile("file", "resolved content") + }). + Press(keys.Universal.Refresh) + + t.ExpectPopup().Confirmation(). + Title(Equals("Continue")). + Content(Contains("All merge conflicts resolved. Continue the merge?")) + + // While the prompt is up, the merge is continued outside lazygit (e.g. by + // a coding agent). + t.Shell().ContinueMerge() + + // Simulate lazygit noticing the change (as it would on its next refresh or + // when the window regains focus); the stale prompt is dismissed. + t.FocusIn() + + t.Views().Files(). + IsFocused(). + IsEmpty() + + t.Views().Information().Content(DoesNotContain("Merging")) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 554dc726f..74e471713 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -163,6 +163,7 @@ var tests = []*components.IntegrationTest{ config.NegativeRefspec, config.RemoteNamedStar, config.SidePanelsInPerRepoConfig, + conflicts.ContinuePromptDismissedWhenResolvedExternally, conflicts.Filter, conflicts.MergeFileBoth, conflicts.MergeFileCurrent, From 3c04b30336ecf52c7767e4b5f6c569e739019872 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 009/218] Have "just lint" show all issues instead of just the first so many --- .golangci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.golangci.yml b/.golangci.yml index c46e438ac..5ed7fb32d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,6 +1,10 @@ version: "2" run: go: "1.25" +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + uniq-by-line: false linters: enable: - copyloopvar From 51c8f9e6add7cc90c23816f1654d6aa58d936d21 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 010/218] Always set LAZYGIT_COLUMNS The env var was previously set only on Windows, where the no-op pty stub was just running the command without a pty and needed to expose the width to pager scripts another way. With ConPTY coming to Windows the rationale disappears there, but the env var is documented in docs/Custom_Pagers.md for pager scripts that can't query the terminal width directly. Set it on every platform so those scripts remain portable, regardless of whether a pty is in play. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/gui/pty.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go index f6356b9c0..fbe8d5d38 100644 --- a/pkg/gui/pty.go +++ b/pkg/gui/pty.go @@ -3,6 +3,7 @@ package gui import ( + "fmt" "io" "os" "os/exec" @@ -45,6 +46,12 @@ func (gui *Gui) onResize() error { // command. func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error { width := view.InnerWidth() + + // LAZYGIT_COLUMNS is documented in docs/Custom_Pagers.md for pager + // scripts that can't query the terminal width directly. We set it on + // every platform so those scripts remain portable. + cmd.Env = append(cmd.Env, fmt.Sprintf("LAZYGIT_COLUMNS=%d", width)) + pager := gui.stateAccessor.GetPagerConfig().GetPagerCommand(width) externalDiffCommand := gui.stateAccessor.GetPagerConfig().GetExternalDiffCommand() useExtDiffGitConfig := gui.stateAccessor.GetPagerConfig().GetUseExternalDiffGitConfig() From 8ec4283e5551dc653f01be296020e03aeef8318d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 011/218] Abstract task command over *exec.Cmd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows ConPTY can't attach a child process to a pseudoconsole via os/exec — Go's stdlib doesn't expose PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE (golang/go#62708). The ConPTY path has to call CreateProcess directly, so it can't hand an *exec.Cmd back to the task runner. Widen NewCmdTask to accept a small Cmd interface satisfied by both *exec.Cmd (via the ExecCmd adapter) and the Windows ConPTY command type we're about to add. Change TerminateProcessGracefully to take *os.Process, which both cmd shapes can provide. Behavior is unchanged on every platform. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../oscommands/os_default_platform.go | 6 ++-- pkg/commands/oscommands/os_windows.go | 2 +- pkg/gui/pty.go | 5 ++-- pkg/gui/tasks_adapter.go | 4 +-- pkg/tasks/tasks.go | 28 ++++++++++++++++--- pkg/tasks/tasks_test.go | 12 ++++---- 6 files changed, 39 insertions(+), 18 deletions(-) diff --git a/pkg/commands/oscommands/os_default_platform.go b/pkg/commands/oscommands/os_default_platform.go index 5e73c994f..09f9f1d6d 100644 --- a/pkg/commands/oscommands/os_default_platform.go +++ b/pkg/commands/oscommands/os_default_platform.go @@ -45,10 +45,10 @@ func (c *OSCommand) UpdateWindowTitle() error { // this call is reached on every host; only the Windows build does anything. func setRawCmdLine(cmd *exec.Cmd, cmdLine string) {} -func TerminateProcessGracefully(cmd *exec.Cmd) error { - if cmd.Process == nil { +func TerminateProcessGracefully(proc *os.Process) error { + if proc == nil { return nil } - return cmd.Process.Signal(syscall.SIGTERM) + return proc.Signal(syscall.SIGTERM) } diff --git a/pkg/commands/oscommands/os_windows.go b/pkg/commands/oscommands/os_windows.go index bd4cc5151..d0252f5b1 100644 --- a/pkg/commands/oscommands/os_windows.go +++ b/pkg/commands/oscommands/os_windows.go @@ -41,7 +41,7 @@ func (c *OSCommand) UpdateWindowTitle() error { return c.Cmd.NewShell(argString, c.UserConfig().OS.ShellFunctionsFile).Run() } -func TerminateProcessGracefully(cmd *exec.Cmd) error { +func TerminateProcessGracefully(proc *os.Process) error { // Signals other than SIGKILL are not supported on Windows return nil } diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go index fbe8d5d38..0455c0abf 100644 --- a/pkg/gui/pty.go +++ b/pkg/gui/pty.go @@ -11,6 +11,7 @@ import ( "github.com/creack/pty" "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/jesseduffield/lazygit/pkg/tasks" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) @@ -82,7 +83,7 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error manager := gui.getManager(view) var ptmx *os.File - start := func() (*exec.Cmd, io.Reader) { + start := func() (tasks.Cmd, io.Reader) { var err error ptmx, err = pty.StartWithSize(cmd, gui.desiredPtySize(view)) if err != nil { @@ -93,7 +94,7 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error gui.viewPtmxMap[view.Name()] = ptmx gui.Mutexes.PtyMutex.Unlock() - return cmd, ptmx + return tasks.ExecCmd{Cmd: cmd}, ptmx } onClose := func() { diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 3bfc64100..09edd2d36 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -19,7 +19,7 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error manager := gui.getManager(view) var r io.ReadCloser - start := func() (*exec.Cmd, io.Reader) { + start := func() (tasks.Cmd, io.Reader) { var err error r, err = cmd.StdoutPipe() if err != nil { @@ -32,7 +32,7 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error gui.c.Log.Error(err) } - return cmd, r + return tasks.ExecCmd{Cmd: cmd}, r } onClose := func() { diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 7fadbb451..26145c784 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -4,6 +4,7 @@ import ( "bufio" "fmt" "io" + "os" "os/exec" "sync" "time" @@ -15,6 +16,25 @@ import ( "github.com/sirupsen/logrus" ) +// Cmd abstracts over a started external process. *exec.Cmd satisfies the bulk +// of it via ExecCmd, but pty implementations can supply their own types — on +// Windows, ConPTY has to spawn via CreateProcess directly and can't use +// *exec.Cmd (see golang/go#62708). +type Cmd interface { + Wait() error + String() string + GetProcess() *os.Process +} + +// ExecCmd adapts *exec.Cmd to Cmd. +type ExecCmd struct { + *exec.Cmd +} + +func (c ExecCmd) GetProcess() *os.Process { + return c.Process +} + // This file revolves around running commands that will be output to the main panel // in the gui. If we're flicking through the commits panel, we want to invoke a // `git show` command for each commit, but we don't want to read the entire output @@ -117,7 +137,7 @@ func (self *ViewBufferManager) ReadToEnd(then func()) { } } -func (self *ViewBufferManager) NewCmdTask(start func() (*exec.Cmd, io.Reader), prefix string, linesToRead LinesToRead, onDoneFn func()) func(TaskOpts) error { +func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix string, linesToRead LinesToRead, onDoneFn func()) func(TaskOpts) error { return func(opts TaskOpts) error { var onDoneOnce sync.Once var onFirstPageShownOnce sync.Once @@ -173,8 +193,8 @@ func (self *ViewBufferManager) NewCmdTask(start func() (*exec.Cmd, io.Reader), p // // Unfortunately this will do nothing on Windows, so Windows users will have to live // with the higher CPU usage. - if err := oscommands.TerminateProcessGracefully(cmd); err != nil { - self.Log.Errorf("error when trying to terminate cmd task: %v; Command: %v %v", err, cmd.Path, cmd.Args) + if err := oscommands.TerminateProcessGracefully(cmd.GetProcess()); err != nil { + self.Log.Errorf("error when trying to terminate cmd task: %v; Command: %v", err, cmd.String()) } // close the task's stdout pipe (or the pty if we're using one) to make the command terminate @@ -338,7 +358,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (*exec.Cmd, io.Reader), p go func() { _ = cmd.Wait() }() default: if err := cmd.Wait(); err != nil { - self.Log.Errorf("Unexpected error when running cmd task: %v; Failed command: %v %v", err, cmd.Path, cmd.Args) + self.Log.Errorf("Unexpected error when running cmd task: %v; Failed command: %v", err, cmd.String()) } } diff --git a/pkg/tasks/tasks_test.go b/pkg/tasks/tasks_test.go index 40ff0033d..c025e8e16 100644 --- a/pkg/tasks/tasks_test.go +++ b/pkg/tasks/tasks_test.go @@ -43,13 +43,13 @@ func TestNewCmdTaskInstantStop(t *testing.T) { stop := make(chan struct{}) reader := bytes.NewBufferString("test") - start := func() (*exec.Cmd, io.Reader) { + start := func() (Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") close(stop) - return cmd, reader + return ExecCmd{Cmd: cmd}, reader } fn := manager.NewCmdTask(start, "prefix\n", LinesToRead{20, -1, nil}, onDone) @@ -108,11 +108,11 @@ func TestNewCmdTask(t *testing.T) { stop := make(chan struct{}) reader := bytes.NewBufferString("test") - start := func() (*exec.Cmd, io.Reader) { + start := func() (Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") - return cmd, reader + return ExecCmd{Cmd: cmd}, reader } fn := manager.NewCmdTask(start, "prefix\n", LinesToRead{20, -1, nil}, onDone) @@ -241,11 +241,11 @@ func TestNewCmdTaskRefresh(t *testing.T) { stop := make(chan struct{}) reader := BlankLineReader{totalLinesToYield: s.totalTaskLines} - start := func() (*exec.Cmd, io.Reader) { + start := func() (Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") - return cmd, &reader + return ExecCmd{Cmd: cmd}, &reader } fn := manager.NewCmdTask(start, "", s.linesToRead, func() {}) From c85f7530bb1617c8a16245636a224a432709f8f7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 012/218] Abstract pty startup behind a platform-specific primitive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the pty master behind a small interface (Read/Write/Close/Resize), and push the actual startup into a platform-specific StartPty function in pkg/commands/oscommands. The Unix implementation still uses creack/pty; the Windows implementation is a stub that returns ErrPtyUnsupported, at which point newPtyTask falls back to a plain cmd task — matching the existing Windows behavior. The primitive lives in oscommands rather than pkg/gui because the cmd_obj_runner pty handler (also in oscommands) is going to consume it too, and tasks → oscommands is the existing dependency direction. Same observable behavior on every platform; this just carves out a seam for a real ConPTY implementation on Windows. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/commands/oscommands/pty.go | 39 +++++++++++++++++++++ pkg/commands/oscommands/pty_unix.go | 34 ++++++++++++++++++ pkg/commands/oscommands/pty_windows.go | 12 +++++++ pkg/gui/gui.go | 4 +-- pkg/gui/pty.go | 48 ++++++++++++++++++-------- pkg/gui/pty_windows.go | 17 --------- 6 files changed, 120 insertions(+), 34 deletions(-) create mode 100644 pkg/commands/oscommands/pty.go create mode 100644 pkg/commands/oscommands/pty_unix.go create mode 100644 pkg/commands/oscommands/pty_windows.go delete mode 100644 pkg/gui/pty_windows.go diff --git a/pkg/commands/oscommands/pty.go b/pkg/commands/oscommands/pty.go new file mode 100644 index 000000000..8a803fe60 --- /dev/null +++ b/pkg/commands/oscommands/pty.go @@ -0,0 +1,39 @@ +package oscommands + +import ( + "errors" + "io" + "os" +) + +// Pty is the master side of a pseudo-terminal running a subprocess. The +// concrete implementation is platform-specific: creack/pty on Unix and +// ConPTY on Windows. +type Pty interface { + io.ReadWriteCloser + Resize(cols, rows uint16) error +} + +// StartedPty is the result of StartPty. +type StartedPty struct { + // Pty is the master side of the pseudo-terminal; read from it to get + // the child's combined stdout/stderr and write to it to feed stdin. + Pty Pty + // Process is the spawned child. Useful for signalling; on Windows the + // original *exec.Cmd was not Start()ed (ConPTY spawns via + // CreateProcess, not os/exec) so cmd.Process is nil and this is the + // only handle. + Process *os.Process + // Wait blocks until the child exits and returns a non-nil error on a + // nonzero exit status, matching *exec.Cmd.Wait semantics. + Wait func() error +} + +// ErrPtyUnsupported is returned by StartPty on platforms without a pty +// implementation. Callers may fall back to running the command without a pty. +var ErrPtyUnsupported = errors.New("pty not supported on this platform") + +// StartPty runs cmd in a pseudo-terminal with the given initial dimensions. +// Implemented per-platform in pty_unix.go / pty_windows.go. +// +// func StartPty(cmd *exec.Cmd, cols, rows uint16) (StartedPty, error) diff --git a/pkg/commands/oscommands/pty_unix.go b/pkg/commands/oscommands/pty_unix.go new file mode 100644 index 000000000..6cf63cdff --- /dev/null +++ b/pkg/commands/oscommands/pty_unix.go @@ -0,0 +1,34 @@ +//go:build !windows + +package oscommands + +import ( + "os" + "os/exec" + + creackpty "github.com/creack/pty" +) + +type unixPty struct { + master *os.File +} + +func (u *unixPty) Read(p []byte) (int, error) { return u.master.Read(p) } +func (u *unixPty) Write(p []byte) (int, error) { return u.master.Write(p) } +func (u *unixPty) Close() error { return u.master.Close() } + +func (u *unixPty) Resize(cols, rows uint16) error { + return creackpty.Setsize(u.master, &creackpty.Winsize{Cols: cols, Rows: rows}) +} + +func StartPty(cmd *exec.Cmd, cols, rows uint16) (StartedPty, error) { + f, err := creackpty.StartWithSize(cmd, &creackpty.Winsize{Cols: cols, Rows: rows}) + if err != nil { + return StartedPty{}, err + } + return StartedPty{ + Pty: &unixPty{master: f}, + Process: cmd.Process, + Wait: cmd.Wait, + }, nil +} diff --git a/pkg/commands/oscommands/pty_windows.go b/pkg/commands/oscommands/pty_windows.go new file mode 100644 index 000000000..6d0d7c6ff --- /dev/null +++ b/pkg/commands/oscommands/pty_windows.go @@ -0,0 +1,12 @@ +package oscommands + +import ( + "os/exec" +) + +// StartPty is a stub on Windows for now; callers fall back to the non-pty +// path when ErrPtyUnsupported is returned. A real ConPTY implementation +// replaces this in a follow-up commit. +func StartPty(cmd *exec.Cmd, cols, rows uint16) (StartedPty, error) { + return StartedPty{}, ErrPtyUnsupported +} diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 08d560ce5..e23afd124 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -85,7 +85,7 @@ type Gui struct { // 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 + viewPtmxMap map[string]oscommands.Pty stopChan chan struct{} // when lazygit is opened outside a git directory we want to open to the most @@ -761,7 +761,7 @@ func NewGui( Updater: updater, statusManager: status.NewStatusManager(), viewBufferManagerMap: map[string]*tasks.ViewBufferManager{}, - viewPtmxMap: map[string]*os.File{}, + viewPtmxMap: map[string]oscommands.Pty{}, showRecentRepos: showRecentRepos, RepoPathStack: &utils.StringStack{}, RepoStateMap: map[Repo]*GuiRepoState{}, diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go index 0455c0abf..e5ef2a770 100644 --- a/pkg/gui/pty.go +++ b/pkg/gui/pty.go @@ -1,37 +1,36 @@ -//go:build !windows - package gui import ( + "errors" "fmt" "io" "os" "os/exec" "strings" - "github.com/creack/pty" + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/tasks" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) -func (gui *Gui) desiredPtySize(view *gocui.View) *pty.Winsize { +func (gui *Gui) desiredPtySize(view *gocui.View) (cols, rows uint16) { width, height := view.InnerSize() - - return &pty.Winsize{Cols: uint16(width), Rows: uint16(height)} + return uint16(width), uint16(height) } func (gui *Gui) onResize() error { gui.Mutexes.PtyMutex.Lock() defer gui.Mutexes.PtyMutex.Unlock() - for viewName, ptmx := range gui.viewPtmxMap { + for viewName, p := 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 { + cols, rows := gui.desiredPtySize(view) + if err := p.Resize(cols, rows); err != nil { return utils.WrapError(err) } } @@ -39,6 +38,19 @@ func (gui *Gui) onResize() error { return nil } +// ptyCmd adapts an oscommands.StartedPty result into the tasks.Cmd shape. +// On Windows the original *exec.Cmd was never Start()ed, so we go through +// the explicit Process handle rather than cmd.Process. +type ptyCmd struct { + cmd *exec.Cmd + process *os.Process + wait func() error +} + +func (p ptyCmd) Wait() error { return p.wait() } +func (p ptyCmd) String() string { return p.cmd.String() } +func (p ptyCmd) GetProcess() *os.Process { return p.process } + // 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, @@ -82,24 +94,30 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error manager := gui.getManager(view) - var ptmx *os.File + var p oscommands.Pty start := func() (tasks.Cmd, io.Reader) { - var err error - ptmx, err = pty.StartWithSize(cmd, gui.desiredPtySize(view)) + cols, rows := gui.desiredPtySize(view) + sp, err := oscommands.StartPty(cmd, cols, rows) if err != nil { - gui.c.Log.Error(err) + if !errors.Is(err, oscommands.ErrPtyUnsupported) { + gui.c.Log.Error(err) + } + return tasks.ExecCmd{Cmd: cmd}, nil } + p = sp.Pty gui.Mutexes.PtyMutex.Lock() - gui.viewPtmxMap[view.Name()] = ptmx + gui.viewPtmxMap[view.Name()] = p gui.Mutexes.PtyMutex.Unlock() - return tasks.ExecCmd{Cmd: cmd}, ptmx + return ptyCmd{cmd: cmd, process: sp.Process, wait: sp.Wait}, p } onClose := func() { gui.Mutexes.PtyMutex.Lock() - ptmx.Close() + if p != nil { + p.Close() + } delete(gui.viewPtmxMap, view.Name()) gui.Mutexes.PtyMutex.Unlock() } diff --git a/pkg/gui/pty_windows.go b/pkg/gui/pty_windows.go deleted file mode 100644 index 31d763870..000000000 --- a/pkg/gui/pty_windows.go +++ /dev/null @@ -1,17 +0,0 @@ -package gui - -import ( - "fmt" - "os/exec" - - "github.com/jesseduffield/lazygit/pkg/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) -} From 1935117141b98d7931fc04731bceff8e4baf83a5 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 013/218] Add pty support on Windows via ConPTY MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the StartPty stub with a real ConPTY implementation: CreatePipe + CreatePseudoConsole + PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE + CreateProcess. Pagers and external diff tools now get real terminal behavior instead of being handed pipes. One Windows-specific quirk worth flagging: ConPTY does not EOF the output pipe when the child exits; conhost keeps it alive until ClosePseudoConsole is called explicitly. A background waiter goroutine calls ClosePseudoConsole as soon as proc.Wait returns, so callers see EOF on outRead — restoring the Unix master-fd-EOFs-when-slave-closes semantics they depend on. The ErrPtyUnsupported sentinel and the no-pty fallback in newPtyTask are gone now that both platforms have a real implementation. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/commands/oscommands/pty.go | 5 - pkg/commands/oscommands/pty_windows.go | 257 ++++++++++++++++++++++++- pkg/gui/pty.go | 5 +- 3 files changed, 253 insertions(+), 14 deletions(-) diff --git a/pkg/commands/oscommands/pty.go b/pkg/commands/oscommands/pty.go index 8a803fe60..a4a369633 100644 --- a/pkg/commands/oscommands/pty.go +++ b/pkg/commands/oscommands/pty.go @@ -1,7 +1,6 @@ package oscommands import ( - "errors" "io" "os" ) @@ -29,10 +28,6 @@ type StartedPty struct { Wait func() error } -// ErrPtyUnsupported is returned by StartPty on platforms without a pty -// implementation. Callers may fall back to running the command without a pty. -var ErrPtyUnsupported = errors.New("pty not supported on this platform") - // StartPty runs cmd in a pseudo-terminal with the given initial dimensions. // Implemented per-platform in pty_unix.go / pty_windows.go. // diff --git a/pkg/commands/oscommands/pty_windows.go b/pkg/commands/oscommands/pty_windows.go index 6d0d7c6ff..0a4a06477 100644 --- a/pkg/commands/oscommands/pty_windows.go +++ b/pkg/commands/oscommands/pty_windows.go @@ -1,12 +1,259 @@ package oscommands import ( + "fmt" + "os" "os/exec" + "sync" + "unsafe" + + "golang.org/x/sys/windows" ) -// StartPty is a stub on Windows for now; callers fall back to the non-pty -// path when ErrPtyUnsupported is returned. A real ConPTY implementation -// replaces this in a follow-up commit. -func StartPty(cmd *exec.Cmd, cols, rows uint16) (StartedPty, error) { - return StartedPty{}, ErrPtyUnsupported +type winPty struct { + hpc windows.Handle + inWrite *os.File + outRead *os.File + + // mu guards the teardown state below and serializes it against Resize. + // hpcClosed gates ClosePseudoConsole (it must run exactly once) and also + // keeps Resize from touching the HPCON once it's been freed: the + // background waiter in StartPty closes the pseudoconsole on child exit, + // which would otherwise race a concurrent onResize and hand + // ResizePseudoConsole a freed handle. + mu sync.Mutex + hpcClosed bool + closed bool +} + +func (p *winPty) Read(buf []byte) (int, error) { return p.outRead.Read(buf) } +func (p *winPty) Write(buf []byte) (int, error) { return p.inWrite.Write(buf) } + +func (p *winPty) Resize(cols, rows uint16) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.hpcClosed { + // The child already exited and the pseudoconsole was torn down, so + // there is nothing left to resize. + return nil + } + return windows.ResizePseudoConsole(p.hpc, windows.Coord{X: int16(cols), Y: int16(rows)}) +} + +// closeHpc closes the pseudoconsole exactly once. Safe to call from multiple +// goroutines and at any time. We need this separately from Close because the +// background waiter in StartPty closes the pseudoconsole as soon as the child +// exits — that's what makes outRead return EOF, matching the Unix behavior +// where the master fd EOFs when the slave closes — while the pipe fds stay +// open until somebody explicitly tears the pty down. +func (p *winPty) closeHpc() { + p.mu.Lock() + defer p.mu.Unlock() + p.closeHpcLocked() +} + +// closeHpcLocked closes the pseudoconsole; the caller must hold p.mu. +func (p *winPty) closeHpcLocked() { + if p.hpcClosed { + return + } + p.hpcClosed = true + windows.ClosePseudoConsole(p.hpc) +} + +func (p *winPty) Close() error { + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return nil + } + p.closed = true + // Closing the pseudoconsole breaks the pipes; the child's next write + // fails and it exits. Then we close our ends of the pipes. + p.closeHpcLocked() + p.inWrite.Close() + p.outRead.Close() + return nil +} + +// startWaiter runs proc.Wait in a goroutine and, as soon as the child exits, +// closes the pseudoconsole so that any pending Read on outRead returns EOF +// after buffered output drains. Returns a Wait func that blocks until the +// child has exited and reports its exit status with *exec.Cmd.Wait semantics. +// +// This shape exists because on Unix the master fd EOFs naturally when the +// slave closes on child exit, but ConPTY keeps the pipe alive until we call +// ClosePseudoConsole explicitly. Without doing that on child exit, the +// scanner in pkg/tasks.NewCmdTask would block forever on the next read and +// the post-content view never gets cleared (FlushStaleCells never fires). +func startWaiter(proc *os.Process, p *winPty) func() error { + done := make(chan struct{}) + var waitErr error + go func() { + defer close(done) + state, err := proc.Wait() + p.closeHpc() + if err != nil { + waitErr = err + return + } + if !state.Success() { + waitErr = fmt.Errorf("exit status %d", state.ExitCode()) + } + }() + return func() error { + <-done + return waitErr + } +} + +func StartPty(cmd *exec.Cmd, cols, rows uint16) (sp StartedPty, err error) { + // Two pipes: one for the child's stdin (we never write to it, but ConPTY + // needs a handle), one for the child's stdout/stderr multiplexed through + // the pseudoconsole. + var inRead, inWrite, outRead, outWrite windows.Handle + if err = windows.CreatePipe(&inRead, &inWrite, nil, 0); err != nil { + return StartedPty{}, fmt.Errorf("CreatePipe (in): %w", err) + } + defer func() { + if err != nil { + _ = windows.CloseHandle(inWrite) + } + }() + if err = windows.CreatePipe(&outRead, &outWrite, nil, 0); err != nil { + _ = windows.CloseHandle(inRead) + return StartedPty{}, fmt.Errorf("CreatePipe (out): %w", err) + } + defer func() { + if err != nil { + _ = windows.CloseHandle(outRead) + } + }() + + // CreatePseudoConsole dupes the handles it needs internally; we release + // our references to the child-side ends immediately after. + var hpc windows.Handle + size := windows.Coord{X: int16(cols), Y: int16(rows)} + if err = windows.CreatePseudoConsole(size, inRead, outWrite, 0, &hpc); err != nil { + _ = windows.CloseHandle(inRead) + _ = windows.CloseHandle(outWrite) + return StartedPty{}, fmt.Errorf("CreatePseudoConsole: %w", err) + } + _ = windows.CloseHandle(inRead) + _ = windows.CloseHandle(outWrite) + defer func() { + if err != nil { + windows.ClosePseudoConsole(hpc) + } + }() + + // Attach the pseudoconsole to the child via a process attribute list. + attrList, err := windows.NewProcThreadAttributeList(1) + if err != nil { + return StartedPty{}, fmt.Errorf("NewProcThreadAttributeList: %w", err) + } + defer attrList.Delete() + // PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE wants the HPCON value itself as + // the attribute value, not a pointer to it — an HPCON is already a + // pointer-sized handle, per Microsoft's ConPTY sample. Spelling that as + // unsafe.Pointer(hpc) trips go vet's unsafeptr check (a uintptr-based + // type converted straight to unsafe.Pointer), which gopls surfaces in + // the editor. Reinterpret the handle's bits through its address instead: + // &hpc is a real pointer, so none of these conversions is the flagged + // uintptr→unsafe.Pointer cast, while the resulting value is identical. + if err = attrList.Update( + windows.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, + *(*unsafe.Pointer)(unsafe.Pointer(&hpc)), + unsafe.Sizeof(hpc), + ); err != nil { + return StartedPty{}, fmt.Errorf("UpdateProcThreadAttribute: %w", err) + } + + var si windows.StartupInfoEx + si.Cb = uint32(unsafe.Sizeof(si)) + si.ProcThreadAttributeList = attrList.List() + + var appNamePtr *uint16 + if cmd.Path != "" { + if appNamePtr, err = windows.UTF16PtrFromString(cmd.Path); err != nil { + return StartedPty{}, err + } + } + cmdLinePtr, err := windows.UTF16PtrFromString(windows.ComposeCommandLine(cmd.Args)) + if err != nil { + return StartedPty{}, err + } + var dirPtr *uint16 + if cmd.Dir != "" { + if dirPtr, err = windows.UTF16PtrFromString(cmd.Dir); err != nil { + return StartedPty{}, err + } + } + envBlock, err := createEnvBlock(cmd.Env) + if err != nil { + return StartedPty{}, err + } + var envPtr *uint16 + if envBlock != nil { + envPtr = &envBlock[0] + } + + var pi windows.ProcessInformation + err = windows.CreateProcess( + appNamePtr, + cmdLinePtr, + nil, // process security + nil, // thread security + false, + windows.EXTENDED_STARTUPINFO_PRESENT|windows.CREATE_UNICODE_ENVIRONMENT, + envPtr, + dirPtr, + &si.StartupInfo, + &pi, + ) + if err != nil { + return StartedPty{}, fmt.Errorf("CreateProcess: %w", err) + } + _ = windows.CloseHandle(pi.Thread) + + // Re-open the process by PID to get an *os.Process to wait on. Do this + // while pi.Process is still open: Windows won't recycle a PID while any + // handle to the process remains, so FindProcess can't latch onto a + // different process that has since reused the PID. Release the original + // handle once we have our own. + proc, err := os.FindProcess(int(pi.ProcessId)) + _ = windows.CloseHandle(pi.Process) + if err != nil { + return StartedPty{}, err + } + + wp := &winPty{ + hpc: hpc, + inWrite: os.NewFile(uintptr(inWrite), "conpty-in"), + outRead: os.NewFile(uintptr(outRead), "conpty-out"), + } + return StartedPty{ + Pty: wp, + Process: proc, + Wait: startWaiter(proc, wp), + }, nil +} + +// createEnvBlock packs env vars into the UTF-16 double-null-terminated block +// that CreateProcess expects. Returns nil if env is empty, which tells +// CreateProcess to inherit the parent's environment. +func createEnvBlock(env []string) ([]uint16, error) { + if len(env) == 0 { + return nil, nil + } + var block []uint16 + for _, s := range env { + utf16s, err := windows.UTF16FromString(s) + if err != nil { + return nil, err + } + block = append(block, utf16s...) + } + block = append(block, 0) + return block, nil } diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go index e5ef2a770..1a774fc3d 100644 --- a/pkg/gui/pty.go +++ b/pkg/gui/pty.go @@ -1,7 +1,6 @@ package gui import ( - "errors" "fmt" "io" "os" @@ -99,9 +98,7 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error cols, rows := gui.desiredPtySize(view) sp, err := oscommands.StartPty(cmd, cols, rows) if err != nil { - if !errors.Is(err, oscommands.ErrPtyUnsupported) { - gui.c.Log.Error(err) - } + gui.c.Log.Error(err) return tasks.ExecCmd{Cmd: cmd}, nil } p = sp.Pty From 8c035ebe60541722e9b28c782f8d7bee592d16eb Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 014/218] Use ConPTY on Windows for pty-backed command execution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-platform getCmdHandlerPty split existed because the Unix side had creack/pty and the Windows side had nothing — so it fell back to a non-pty handler. Now that oscommands.StartPty provides a pty on both platforms, the two files collapse into one cross-platform implementation and the stub is gone. cmdHandler grows a 'wait' field because the pty path on Windows spawns via CreateProcess and never runs exec.Cmd.Start — so cmd.Wait wouldn't work there. Non-pty handlers set wait = cmd.Wait; pty handlers set it to the wait closure StartPty returns. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/commands/oscommands/cmd_obj.go | 2 +- pkg/commands/oscommands/cmd_obj_runner.go | 26 ++++++++++++++++--- .../oscommands/cmd_obj_runner_default.go | 24 ----------------- .../oscommands/cmd_obj_runner_windows.go | 10 ------- 4 files changed, 23 insertions(+), 39 deletions(-) delete mode 100644 pkg/commands/oscommands/cmd_obj_runner_default.go delete mode 100644 pkg/commands/oscommands/cmd_obj_runner_windows.go diff --git a/pkg/commands/oscommands/cmd_obj.go b/pkg/commands/oscommands/cmd_obj.go index 57bc295ed..1fbe84087 100644 --- a/pkg/commands/oscommands/cmd_obj.go +++ b/pkg/commands/oscommands/cmd_obj.go @@ -157,7 +157,7 @@ func (self *CmdObj) ShouldStreamOutput() bool { } // when you call this, then call Run(), we'll use a PTY to run the command. Only -// has an effect if StreamOutput() was also called. Ignored on Windows. +// has an effect if StreamOutput() was also called. func (self *CmdObj) UsePty() *CmdObj { self.usePty = true diff --git a/pkg/commands/oscommands/cmd_obj_runner.go b/pkg/commands/oscommands/cmd_obj_runner.go index 978682618..b70668431 100644 --- a/pkg/commands/oscommands/cmd_obj_runner.go +++ b/pkg/commands/oscommands/cmd_obj_runner.go @@ -219,6 +219,10 @@ type cmdHandler struct { stdoutPipe io.Reader stdinPipe io.Writer close func() error + // wait blocks until the child process exits. Needed as a separate + // field because the pty path on Windows spawns via CreateProcess and + // never runs *exec.Cmd.Start — so cmd.Wait wouldn't work there. + wait func() error } func (self *cmdObjRunner) runAndStream(cmdObj *CmdObj) error { @@ -274,7 +278,7 @@ func (self *cmdObjRunner) runAndStreamAux( onRun(handler, cmdWriter) - err = cmd.Wait() + err = handler.wait() self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t)) @@ -376,9 +380,7 @@ func (self *cmdObjRunner) processOutput( responseChan := promptUserForCredential(askFor) if responseChan == nil { // Returning a nil channel means we should terminate the process. - // We achieve this by closing the pty that it's running in. Note that this won't - // work for the case where we're not running in a pty (i.e. on Windows), but - // in that case we'll never be prompted for credentials, so it's not a concern. + // We achieve this by closing the pty that it's running in. if err := closeFunc(); err != nil { self.log.Error(err) } @@ -481,5 +483,21 @@ func (self *cmdObjRunner) getCmdHandlerNonPty(cmd *exec.Cmd) (*cmdHandler, error stdoutPipe: stdoutReader, stdinPipe: buf, close: func() error { return nil }, + wait: cmd.Wait, + }, nil +} + +func (self *cmdObjRunner) getCmdHandlerPty(cmd *exec.Cmd) (*cmdHandler, error) { + // Size will be adjusted by the caller if it cares; this just avoids a + // zero-size pty. + sp, err := StartPty(cmd, 80, 24) + if err != nil { + return nil, err + } + return &cmdHandler{ + stdoutPipe: sp.Pty, + stdinPipe: sp.Pty, + close: sp.Pty.Close, + wait: sp.Wait, }, nil } diff --git a/pkg/commands/oscommands/cmd_obj_runner_default.go b/pkg/commands/oscommands/cmd_obj_runner_default.go deleted file mode 100644 index 72cbc26c6..000000000 --- a/pkg/commands/oscommands/cmd_obj_runner_default.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !windows - -package oscommands - -import ( - "os/exec" - - "github.com/creack/pty" -) - -// we define this separately for windows and non-windows given that windows does -// not have great PTY support and we need a PTY to handle a credential request -func (self *cmdObjRunner) getCmdHandlerPty(cmd *exec.Cmd) (*cmdHandler, error) { - ptmx, err := pty.Start(cmd) - if err != nil { - return nil, err - } - - return &cmdHandler{ - stdoutPipe: ptmx, - stdinPipe: ptmx, - close: ptmx.Close, - }, nil -} diff --git a/pkg/commands/oscommands/cmd_obj_runner_windows.go b/pkg/commands/oscommands/cmd_obj_runner_windows.go deleted file mode 100644 index f92e36c69..000000000 --- a/pkg/commands/oscommands/cmd_obj_runner_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -package oscommands - -import ( - "os/exec" -) - -func (self *cmdObjRunner) getCmdHandlerPty(cmd *exec.Cmd) (*cmdHandler, error) { - // We don't have PTY support on Windows yet, so we just return a non-PTY handler. - return self.getCmdHandlerNonPty(cmd) -} From 79bc8e0bc64f50028b3e0a159afb8d96ca65bf4a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 015/218] Demonstrate that cursor positioning escapes collapse blank rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ConPTY presents its child's stdout as a screen buffer and uses CUP (`\x1b[;H`) to skip over blank rows rather than emitting LFs for them. Our escape interpreter swallows CUP via the catch-all "valid CSI final byte we don't implement" branch, so the blank rows the child put between non-blank ones disappear and the surrounding lines collapse together — which is what makes the delta-rendered diff in the screenshot look like its blank lines and section breaks were removed. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/gocui/view_test.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/pkg/gocui/view_test.go b/pkg/gocui/view_test.go index f65418821..58c83e126 100644 --- a/pkg/gocui/view_test.go +++ b/pkg/gocui/view_test.go @@ -238,6 +238,27 @@ func TestContainsColoredText(t *testing.T) { } } +func TestWriteCursorPositionEscape(t *testing.T) { + // ConPTY presents its child's output as a screen buffer and uses cursor + // positioning escapes (CUP, `\x1b[;H`) to skip over blank rows + // rather than emitting empty LFs for them. The escape interpreter must + // synthesize the row advances those CUPs imply; otherwise non-blank rows + // that the child separated with blank lines end up adjacent in the view. + v := NewView("name", 0, 0, 20, 10, OutputNormal) + // "a", then "skip to row 3" (i.e. one blank row), then "b". + v.writeString("a\r\n\x1b[3;1Hb\r\n") + + got := make([][]string, 0, len(v.lines)) + for _, l := range v.lines { + got = append(got, cellsToStrings(l.cells)) + } + + /* EXPECTED: + assert.Equal(t, [][]string{{"a"}, {}, {"b"}}, got) + ACTUAL: */ + assert.Equal(t, [][]string{{"a"}, {"b"}}, got) +} + func stringToCells(s string) []cell { var cells []cell state := -1 From 180fe0cd267ff52a9afe8b004fa6dbdaab352634 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 016/218] Convert forward cursor-positioning escapes into row advances MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ConPTY presents its child's output as a screen buffer and uses CUP / CUD / CNL / VPA to skip over blank rows rather than emitting LFs. The previous behaviour swallowed all of those and the visible content collapsed together. Now the escape parser tracks the screen-relative cursor row, and any CSI that moves the cursor past the current row emits a cursorDown instruction that the view turns into the matching number of empty lines. Column tracking is deliberately omitted: doing it correctly would mean duplicating the view's grapheme-cluster width math in the parser, and ConPTY in practice positions to column 1 after a CR-equivalent, which the existing wx-reset path already handles. ConPTY-internal scrolling needs no special handling either: it only emits cursor-positioning escapes within the first, un-scrolled screenful — once its screen scrolls it switches to plain linefeeds, which the view advances on directly regardless of the tracked cursor. Backward cursor moves are silently dropped — the view's buffer is append-style and can't undo earlier writes. The exception is cursor-home (CUP to row 1): ConPTY emits it at the start of every screen, so rather than drop it we re-anchor the row tracking to the current write position. Without that, a view not rewound in lockstep with ConPTY's screen (the command log, which streams pty output without a rewind) accumulates drift, and every later absolute CUP becomes a dropped backward move that collapses the rows ConPTY positioned with. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/gocui/escape.go | 139 ++++++++++++++++++++++++++++++++++++++- pkg/gocui/escape_test.go | 67 +++++++++++++++++-- pkg/gocui/view.go | 22 +++++++ pkg/gocui/view_test.go | 3 - 4 files changed, 221 insertions(+), 10 deletions(-) diff --git a/pkg/gocui/escape.go b/pkg/gocui/escape.go index 726fd4de7..c252fa20b 100644 --- a/pkg/gocui/escape.go +++ b/pkg/gocui/escape.go @@ -19,6 +19,21 @@ type escapeInterpreter struct { mode OutputMode instruction instruction hyperlink strings.Builder + + // ConPTY emits cursor-positioning escapes (CUP) to skip over blank + // rows rather than emitting LFs for them. To convert those into row + // advances the view can act on, we track where in the pseudo-terminal + // screen the cursor currently is. 1-based to match the escape + // sequences. + // + // We also have to track the column, but only well enough to count + // soft-wraps when written content runs past the right edge: ConPTY's + // CUPs are addressed against its post-wrap screen, so a logical line + // long enough to wrap in ConPTY's screen counts for two rows from the + // next CUP's perspective. Column accuracy past wrap-counting isn't + // modelled — we don't track the col argument of CUPs, and most + // pager-style emitters use col 1 anyway. + screenRow, screenCol int } type ( @@ -32,6 +47,13 @@ type eraseInLineFromCursor struct{} func (self eraseInLineFromCursor) isInstruction() {} +// cursorDown asks the view to advance N rows. Emitted when CUP / CUD / +// CNL / VPA targets a row past the current one; backward moves are +// ignored because the view's buffer is line-based and can't undo. +type cursorDown struct{ n int } + +func (self cursorDown) isInstruction() {} + type noInstruction struct{} func (self noInstruction) isInstruction() {} @@ -99,11 +121,15 @@ func newEscapeInterpreter(mode OutputMode) *escapeInterpreter { curBgColor: ColorDefault, mode: mode, instruction: noInstruction{}, + screenRow: 1, + screenCol: 1, } return ei } -// reset sets the escapeInterpreter in initial state. +// reset sets the escapeInterpreter in initial state. Note: this only resets +// escape-parsing state. Screen cursor state survives so that mid-stream +// malformed escapes don't desync the row tracking from the view. func (ei *escapeInterpreter) reset() { ei.state = stateNone ei.curFgColor = ColorDefault @@ -111,6 +137,80 @@ func (ei *escapeInterpreter) reset() { ei.csiParam = nil } +// resetScreenCursor returns the screen-cursor tracking to the top of the +// pseudo-terminal screen. Called when the view is rewound before a fresh pty +// render, and on cursor-home (which ConPTY emits at the start of each screen) +// for views that aren't rewound in lockstep — see the CUP handling in parseOne. +func (ei *escapeInterpreter) resetScreenCursor() { + ei.screenRow = 1 + ei.screenCol = 1 +} + +// notifyRowAdvance must be called by the view whenever it advances to the +// next row in response to an LF / CRLF outside of an escape sequence +// (i.e. the row transitions the parser doesn't see directly). Keeps the +// parser's notion of the current screen row in sync with the view. +func (ei *escapeInterpreter) notifyRowAdvance() { + ei.screenRow++ + ei.screenCol = 1 +} + +// notifyColumnReset must be called when the view processes a bare CR +// (column reset without row advance). Keeps screenCol in sync so wrap +// counting starts over from col 1. +func (ei *escapeInterpreter) notifyColumnReset() { + ei.screenCol = 1 +} + +// notifyCellsWritten must be called after the view writes visible cells +// to its buffer. Advances the parser's idea of the cursor by `width` +// columns; if that crosses the right edge of a `screenColMax`-wide pty +// screen, the corresponding number of soft-wraps are added to screenRow +// so subsequent CUPs land on the right line. +func (ei *escapeInterpreter) notifyCellsWritten(width, screenColMax int) { + if screenColMax <= 0 { + return + } + // One column at a time: matches ConPTY's "pending wrap" semantics + // where the cursor stays at col max+1 after writing the rightmost + // cell and only wraps on the next cell. Loops over individual + // columns rather than doing the math in one shot so wide cells on a + // row boundary still wrap cleanly. + for range width { + if ei.screenCol > screenColMax { + ei.screenRow++ + ei.screenCol = 1 + } + ei.screenCol++ + } +} + +// emitCursorAdvance schedules a cursorDown instruction for the next time +// the view checks ei.instruction, advancing the parser's screen row by +// the same amount. n <= 0 is a no-op (backward / same-row CUPs are +// ignored — the view's buffer is line-based and can't undo). +func (ei *escapeInterpreter) emitCursorAdvance(n int) { + if n <= 0 { + return + } + ei.instruction = cursorDown{n: n} + ei.screenRow += n + ei.screenCol = 1 +} + +// firstParamOrDefault returns the first CSI parameter parsed as an int, +// or dflt if it's absent / empty / unparseable. +func (ei *escapeInterpreter) firstParamOrDefault(dflt int) int { + if len(ei.csiParam) == 0 || ei.csiParam[0] == "" { + return dflt + } + n, err := strconv.Atoi(ei.csiParam[0]) + if err != nil { + return dflt + } + return n +} + func (ei *escapeInterpreter) instructionRead() { ei.instruction = noInstruction{} } @@ -170,8 +270,12 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) { ei.csiParam = append(ei.csiParam, "") case characterEquals(ch, 'm'): ei.csiParam = append(ei.csiParam, "0") - case characterEquals(ch, 'K'): - // fall through + case characterEquals(ch, 'K'), + characterEquals(ch, 'H'), characterEquals(ch, 'f'), characterEquals(ch, 'd'), + characterEquals(ch, 'B'), characterEquals(ch, 'E'): + // fall through — let stateParams handle these with default + // params (CUP/VPA default to row 1, CUD/CNL default to advance + // by 1). case characterEquals(ch, ';'): // Empty first param ([;Xm ≡ [0;Xm). Seed a slot for the // empty param; stateParams will append the next one when it @@ -240,6 +344,35 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) { ei.instruction = noInstruction{} } + ei.state = stateNone + ei.csiParam = nil + return true, nil + case characterEquals(ch, 'H'), characterEquals(ch, 'f'), + characterEquals(ch, 'd'): + // CUP / HVP (absolute (row, col), col ignored) or VPA (absolute row). + targetRow := ei.firstParamOrDefault(1) + if targetRow <= 1 { + // Cursor home. ConPTY emits this (after [2J) at the start of + // every screen, so it marks where ConPTY's coordinate origin + // now sits. Re-anchor our row tracking to the current write + // position rather than treating it as a backward move: a view + // that isn't rewound in lockstep with ConPTY's screen (the + // command log) would otherwise carry stale drift, making every + // later absolute CUP compute a negative, dropped advance and + // collapsing the blank rows ConPTY positioned with. + ei.resetScreenCursor() + } else { + // Skip forward to the target row; ignore backward moves. + ei.emitCursorAdvance(targetRow - ei.screenRow) + } + ei.state = stateNone + ei.csiParam = nil + return true, nil + case characterEquals(ch, 'B'), characterEquals(ch, 'E'): + // CUD / CNL — relative row advance by N. CNL also resets + // the column, which we don't track, so the two are + // equivalent for our purposes. + ei.emitCursorAdvance(ei.firstParamOrDefault(1)) ei.state = stateNone ei.csiParam = nil return true, nil diff --git a/pkg/gocui/escape_test.go b/pkg/gocui/escape_test.go index cb8eb1a4b..a7e8ce02f 100644 --- a/pkg/gocui/escape_test.go +++ b/pkg/gocui/escape_test.go @@ -153,17 +153,16 @@ func TestParseOneColours(t *testing.T) { func TestParseOneIgnoresUnknownSequences(t *testing.T) { // Escape sequences the interpreter doesn't implement -- whether well-formed-but-unsupported - // (cursor movement, private modes, DECSCUSR, …) or outright malformed -- must be silently + // (private modes, DECSCUSR, …) or outright malformed -- must be silently // consumed rather than leaked into the view as literal text. scenarios := []string{ "\x1b[?9001h", // DEC private-mode set (?-prefix) "\x1b[?25l", // hide cursor "\x1b[?25h", // show cursor "\x1b[2;J", // erase display (unusual 2;J variant) - "\x1b[H", // cursor home — final byte immediately after [ - "\x1b[5;1;H", // cursor position with multiple params + "\x1b[H", // cursor home — re-anchors to row 1 (no-op when already there) "\x1bc", // RIS — single-char ESC sequence - "\x1b[;5H", // empty first param (';' immediately after '[') + "\x1b[;5H", // empty first param — defaults to row 1, no-op "\x1b[ q", // intermediate byte with no params (DECSCUSR family) "\x1b[0 q", // intermediate byte after a param "\x1b[1;;m", // malformed SGR: empty middle param @@ -184,6 +183,66 @@ func TestParseOneIgnoresUnknownSequences(t *testing.T) { } } +func TestParseOneCursorPositioning(t *testing.T) { + // Cursor-positioning escapes that advance the row forward emit a + // cursorDown instruction; backward / same-row moves are ignored + // because the view's buffer is line-based. + scenarios := []struct { + input string + startRow int // parser's screenRow before parsing + wantAdvance int // 0 means "no instruction emitted" + }{ + {"\x1b[5;1H", 1, 4}, // CUP — absolute row 5 from row 1 + {"\x1b[5H", 1, 4}, // CUP with only the row param + {"\x1b[5;1H", 5, 0}, // CUP to the same row we're on — no-op + {"\x1b[2;1H", 5, 0}, // CUP backward — ignored + {"\x1b[5;1f", 1, 4}, // HVP alias for CUP + {"\x1b[5d", 1, 4}, // VPA — absolute row + {"\x1b[2d", 5, 0}, // VPA backward — ignored + {"\x1b[3B", 1, 3}, // CUD — relative + {"\x1b[B", 1, 1}, // CUD with default param of 1 + {"\x1b[2E", 1, 2}, // CNL — relative + } + + for _, s := range scenarios { + ei := newEscapeInterpreter(OutputNormal) + ei.screenRow = s.startRow + parseEscRunes(t, ei, s.input) + if s.wantAdvance == 0 { + _, noop := ei.instruction.(noInstruction) + assert.True(t, noop, "input %q at row %d should be a no-op", s.input, s.startRow) + } else { + cd, ok := ei.instruction.(cursorDown) + if assert.True(t, ok, "input %q at row %d should emit cursorDown", s.input, s.startRow) { + assert.Equal(t, s.wantAdvance, cd.n, "input %q at row %d", s.input, s.startRow) + } + } + } +} + +func TestParseOneCursorHomeReanchors(t *testing.T) { + // ConPTY emits cursor-home ([H) after [2J at the start of every screen. + // In a view that isn't rewound in lockstep with ConPTY (the command log) + // screenRow has drifted, so home must re-anchor it to the current write + // position rather than be dropped as a backward move — otherwise the + // absolute CUPs that follow compute negative, dropped advances and the + // rows ConPTY positioned with collapse together. + ei := newEscapeInterpreter(OutputNormal) + ei.screenRow = 12 // accumulated drift from earlier command-log output + + parseEscRunes(t, ei, "\x1b[H") + assert.Equal(t, 1, ei.screenRow, "home should re-anchor screenRow") + _, noop := ei.instruction.(noInstruction) + assert.True(t, noop, "home should not emit an instruction") + + // A subsequent CUP now advances relative to the re-anchored origin. + parseEscRunes(t, ei, "\x1b[3;1H") + cd, ok := ei.instruction.(cursorDown) + if assert.True(t, ok, "CUP after home should emit cursorDown") { + assert.Equal(t, 2, cd.n) + } +} + func parseEscRunes(t *testing.T, ei *escapeInterpreter, runes string) { t.Helper() for _, b := range []byte(runes) { diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index 77492b9b1..1e67f8535 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -834,6 +834,7 @@ func (v *View) write(p []byte) { if v.pendingNewline { advanceToNextLine() + v.ei.notifyRowAdvance() v.pendingNewline = false } @@ -855,11 +856,20 @@ func (v *View) write(p []byte) { case characterEquals(chr, '\n') || isCRLF(chr): finishLine() advanceToNextLine() + v.ei.notifyRowAdvance() case characterEquals(chr, '\r'): finishLine() v.wx = 0 + v.ei.notifyColumnReset() default: truncateLine, cells := v.parseInput(chr, width, v.wx, v.wy) + if cd, ok := v.ei.instruction.(cursorDown); ok { + v.ei.instructionRead() + for range cd.n { + v.autoRenderHyperlinksInCurrentLine() + advanceToNextLine() + } + } if cells == nil { continue } @@ -867,6 +877,17 @@ func (v *View) write(p []byte) { if truncateLine { v.lines[v.wy].cells = v.lines[v.wy].cells[:v.wx] } + // Soft-wrap tracking. truncateLine is true exactly when the + // cells are from \x1b[K filling to end of line — ConPTY + // doesn't advance the cursor for that, so we shouldn't count + // it toward wraps either. + if !truncateLine { + totalWidth := 0 + for _, c := range cells { + totalWidth += c.width + } + v.ei.notifyCellsWritten(totalWidth, v.InnerWidth()) + } } } @@ -1116,6 +1137,7 @@ func (v *View) FlushStaleCells() { func (v *View) rewind() { v.ei.reset() + v.ei.resetScreenCursor() v.SetReadPos(0, 0) v.SetWritePos(0, 0) diff --git a/pkg/gocui/view_test.go b/pkg/gocui/view_test.go index 58c83e126..e8d68f1b4 100644 --- a/pkg/gocui/view_test.go +++ b/pkg/gocui/view_test.go @@ -253,10 +253,7 @@ func TestWriteCursorPositionEscape(t *testing.T) { got = append(got, cellsToStrings(l.cells)) } - /* EXPECTED: assert.Equal(t, [][]string{{"a"}, {}, {"b"}}, got) - ACTUAL: */ - assert.Equal(t, [][]string{{"a"}, {"b"}}, got) } func stringToCells(s string) []cell { From 0c0c50c3f2385f1fb59717d9c88dcf05a3f85b5f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 017/218] Demonstrate that cursor forward escapes collapse runs of spaces ConPTY compresses runs of default-colored spaces into ECH + CUF (\x1b[NX\x1b[NC) rather than emitting them literally. Both currently fall through the parser's swallow path, so the gap they describe collapses entirely and content that the child wrote with leading indentation ends up slid left against the previous cell. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/gocui/view_test.go | 70 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/pkg/gocui/view_test.go b/pkg/gocui/view_test.go index e8d68f1b4..b23f914cd 100644 --- a/pkg/gocui/view_test.go +++ b/pkg/gocui/view_test.go @@ -256,6 +256,76 @@ func TestWriteCursorPositionEscape(t *testing.T) { assert.Equal(t, [][]string{{"a"}, {}, {"b"}}, got) } +func TestWriteCursorPositionEscapeAcrossWrites(t *testing.T) { + // Mirrors the production flow: bufio.Scanner splits the pty output on + // LF and feeds the view one Write per line (each with a trailing \n + // appended). The parser's screen-row counter must keep ticking across + // writes; otherwise CUPs are evaluated against a stale row and + // overshoot, producing too many blank lines instead of the right + // number. + v := NewView("name", 0, 0, 30, 30, OutputNormal) + v.writeString("a\n") + v.writeString("b\n") + // ConPTY is on row 3 here; CUP to row 5 should skip exactly one row. + v.writeString("c\x1b[5;1Hd\n") + + got := make([][]string, 0, len(v.lines)) + for _, l := range v.lines { + got = append(got, cellsToStrings(l.cells)) + } + assert.Equal(t, [][]string{ + {"a"}, + {"b"}, + {"c"}, + {}, + {"d"}, + }, got) +} + +func TestWriteCursorForwardEscape(t *testing.T) { + // ConPTY compresses runs of default-colored spaces into ECH (\x1b[NX, + // "clear N cells, cursor stationary") + CUF (\x1b[NC, "cursor forward + // N") rather than emitting them literally. The interpreter has to + // materialize CUF as N visible spaces; otherwise the gap collapses + // and content that followed the indentation slides left. + v := NewView("name", 0, 0, 20, 10, OutputNormal) + // "a" + ECH 5 + CUF 5 + "b" — visually "a b". + v.writeString("a\x1b[5X\x1b[5Cb\n") + + got := make([][]string, 0, len(v.lines)) + for _, l := range v.lines { + got = append(got, cellsToStrings(l.cells)) + } + + /* EXPECTED: + assert.Equal(t, [][]string{{"a", " ", " ", " ", " ", " ", "b"}}, got) + ACTUAL: */ + assert.Equal(t, [][]string{{"a", "b"}}, got) +} + +func TestWriteCursorPositionEscapeWithSoftWraps(t *testing.T) { + // If a logical line is longer than ConPTY's terminal width, ConPTY + // soft-wraps it onto multiple physical rows in its screen, and any + // subsequent CUP is addressed against the post-wrap row count. To + // keep our screen-row counter accurate we have to count those wraps + // as we write the cells. InnerWidth here is 5; "abcdefghij" (10 + // cells) wraps onto 2 rows, so ConPTY is on row 3 after the LF and a + // CUP to row 4 should skip exactly one row. + v := NewView("name", 0, 0, 6, 30, OutputNormal) // Width=7, InnerWidth=5 + v.writeString("abcdefghij\n") + v.writeString("\x1b[4;1Hxyz\n") + + got := make([][]string, 0, len(v.lines)) + for _, l := range v.lines { + got = append(got, cellsToStrings(l.cells)) + } + assert.Equal(t, [][]string{ + {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, + {}, + {"x", "y", "z"}, + }, got) +} + func stringToCells(s string) []cell { var cells []cell state := -1 From 2fce9c91b6d74b5da0d748311d06fb17cecf6144 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 018/218] Materialize cursor-forward escapes as space runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ConPTY compresses runs of default-colored spaces into ECH + CUF (\x1b[NX\x1b[NC) instead of emitting them literally. ECH is still a no-op for us — our buffer is built sequentially and has nothing to erase — but CUF has to materialize as N visible space cells so the gap actually appears, otherwise content the child wrote with leading indentation slides left against the preceding cell. The view's cursorForward branch reuses the same machinery as tab expansion: substitute the trigger byte for a space and let the repeatCount path emit the cells under the parser-tracked SGR. The existing notifyCellsWritten plumbing then advances screenCol over the gap, keeping subsequent CUP targets aligned. Co-Authored-By: Claude Opus 4.7 (1M context) --- pkg/gocui/escape.go | 23 ++++++++++++++++++++--- pkg/gocui/escape_test.go | 23 +++++++++++++++++++++++ pkg/gocui/view.go | 8 ++++++++ pkg/gocui/view_test.go | 3 --- 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/pkg/gocui/escape.go b/pkg/gocui/escape.go index c252fa20b..ad862a596 100644 --- a/pkg/gocui/escape.go +++ b/pkg/gocui/escape.go @@ -54,6 +54,14 @@ type cursorDown struct{ n int } func (self cursorDown) isInstruction() {} +// cursorForward asks the view to materialize N space cells. Emitted +// when CUF advances the cursor right — ConPTY uses CUF (often paired +// with ECH) to encode runs of default-colored spaces compactly, so we +// have to render the gap, not just bump a counter. +type cursorForward struct{ n int } + +func (self cursorForward) isInstruction() {} + type noInstruction struct{} func (self noInstruction) isInstruction() {} @@ -272,10 +280,11 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) { ei.csiParam = append(ei.csiParam, "0") case characterEquals(ch, 'K'), characterEquals(ch, 'H'), characterEquals(ch, 'f'), characterEquals(ch, 'd'), - characterEquals(ch, 'B'), characterEquals(ch, 'E'): + characterEquals(ch, 'B'), characterEquals(ch, 'E'), + characterEquals(ch, 'C'): // fall through — let stateParams handle these with default - // params (CUP/VPA default to row 1, CUD/CNL default to advance - // by 1). + // params (CUP/VPA default to row 1, CUD/CNL/CUF default to + // advance by 1). case characterEquals(ch, ';'): // Empty first param ([;Xm ≡ [0;Xm). Seed a slot for the // empty param; stateParams will append the next one when it @@ -376,6 +385,14 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) { ei.state = stateNone ei.csiParam = nil return true, nil + case characterEquals(ch, 'C'): + // CUF — cursor forward N. Emit space cells so the gap + // renders. (screenCol is updated by the view via + // notifyCellsWritten as those spaces are emitted.) + ei.instruction = cursorForward{n: ei.firstParamOrDefault(1)} + ei.state = stateNone + ei.csiParam = nil + return true, nil case len(ch) == 1 && ch[0] >= 0x20 && ch[0] <= 0x2F: // CSI intermediate byte after params. The final byte will // have a semantic we don't implement (e.g. `[0 q` = diff --git a/pkg/gocui/escape_test.go b/pkg/gocui/escape_test.go index a7e8ce02f..39ccbe908 100644 --- a/pkg/gocui/escape_test.go +++ b/pkg/gocui/escape_test.go @@ -243,6 +243,29 @@ func TestParseOneCursorHomeReanchors(t *testing.T) { } } +func TestParseOneCursorForward(t *testing.T) { + // CUF (\x1b[NC) emits a cursorForward instruction so the view can + // materialize the N-cell gap as spaces. ConPTY uses this (often + // paired with ECH) to encode runs of default-colored spaces. + scenarios := []struct { + input string + wantN int + }{ + {"\x1b[5C", 5}, + {"\x1b[1C", 1}, + {"\x1b[C", 1}, // no param defaults to 1 + } + + for _, s := range scenarios { + ei := newEscapeInterpreter(OutputNormal) + parseEscRunes(t, ei, s.input) + cf, ok := ei.instruction.(cursorForward) + if assert.True(t, ok, "input %q should emit cursorForward", s.input) { + assert.Equal(t, s.wantN, cf.n, "input %q", s.input) + } + } +} + func parseEscRunes(t *testing.T, ei *escapeInterpreter, runes string) { t.Helper() for _, b := range []byte(runes) { diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index 1e67f8535..d93f84954 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -1003,6 +1003,14 @@ func (v *View) parseInput(ch []byte, width int, x int, _ int) (bool, []cell) { bg: v.ei.curBgColor, } return truncateLine, []cell{} + } else if cf, ok := v.ei.instruction.(cursorForward); ok { + // emit `n` space cells under the parser-tracked SGR — used + // to materialize ConPTY's compressed runs of spaces (which + // it emits as ECH+CUF instead of literal whitespace). + v.ei.instructionRead() + repeatCount = cf.n + ch = []byte{' '} + width = 1 } else if isEscape { // do not output anything return truncateLine, nil diff --git a/pkg/gocui/view_test.go b/pkg/gocui/view_test.go index b23f914cd..f7e229f1c 100644 --- a/pkg/gocui/view_test.go +++ b/pkg/gocui/view_test.go @@ -297,10 +297,7 @@ func TestWriteCursorForwardEscape(t *testing.T) { got = append(got, cellsToStrings(l.cells)) } - /* EXPECTED: assert.Equal(t, [][]string{{"a", " ", " ", " ", " ", " ", "b"}}, got) - ACTUAL: */ - assert.Equal(t, [][]string{{"a", "b"}}, got) } func TestWriteCursorPositionEscapeWithSoftWraps(t *testing.T) { From 20af6ad23cbdbaf525b62ed2e772843653553f42 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 09:45:26 +0200 Subject: [PATCH 019/218] Remove the Windows limitation from Custom_Pagers.md --- docs-master/Custom_Pagers.md | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/docs-master/Custom_Pagers.md b/docs-master/Custom_Pagers.md index 0bfffe7dc..1b37766d0 100644 --- a/docs-master/Custom_Pagers.md +++ b/docs-master/Custom_Pagers.md @@ -2,8 +2,6 @@ Lazygit supports custom pagers, [configured](/docs/Config.md) in the config.yml file (which can be opened by pressing `e` in the Status panel). -Support does not extend to Windows users, because we're making use of a package which doesn't have Windows support. However, see [below](#emulating-custom-pagers-on-windows) for a workaround. - Multiple pagers are supported; you can cycle through them with the `|` key. This can be useful if you usually prefer a particular pager, but want to use a different one for certain kinds of diffs. Pagers are configured with the `pagers` array in the git section; here's an example for a multi-pager setup (use an empty object `{}` for the default builtin diff display that doesn't use a pager): @@ -92,30 +90,3 @@ git: This can be useful if you also want to use it for diffs on the command line, and it also has the advantage that you can configure it per file type in `.gitattributes`; see https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver. `pager`, `externalDiffCommand`, and `useExternalDiffGitConfig` are alternative ways of producing the diff, so a pager entry may use at most one of them. - -## Emulating custom pagers on Windows - -There is a trick to emulate custom pagers on Windows using a Powershell script configured as an external diff command. It's not perfect, but certainly better than nothing. To do this, save the following script as `lazygit-pager.ps1` at a convenient place on your disk: - -```pwsh -#!/usr/bin/env pwsh - -$old = $args[1].Replace('\', '/') -$new = $args[4].Replace('\', '/') -$path = $args[0] -git diff --no-index --no-ext-diff $old $new - | %{ $_.Replace($old, $path).Replace($new, $path) } - | delta --width=$env:LAZYGIT_COLUMNS -``` - -Use the pager of your choice with the arguments you like in the last line of the script. Personally I wouldn't want to use lazygit anymore without delta's `--hyperlinks --hyperlinks-file-link-format="lazygit-edit://{path}:{line}"` args, see [above](#delta). - -In your lazygit config, use - -```yml -git: - pagers: - - externalDiffCommand: "C:/wherever/lazygit-pager.ps1" -``` - -The main limitation of this approach compared to a "real" pager is that renames are not displayed correctly; they are shown as if they were modifications of the old file. (This affects only the hunk headers; the diff itself is always correct.) From ef73406a966a83a486b4344f5e79de06e47ab3b1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 07:54:02 +0200 Subject: [PATCH 020/218] Add worktree.defaultPath config The redesigned worktree-creation flow never asks the user to type a path from scratch; instead it offers candidate parent directories. Until a repo has any linked worktrees to learn from, there's nothing to offer, so let users seed that list with a configured default location. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs-master/Config.md | 8 ++++++++ pkg/config/user_config.go | 11 +++++++++++ schema-master/config.json | 15 +++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/docs-master/Config.md b/docs-master/Config.md index 5e57df34a..183a0c6b2 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -527,6 +527,14 @@ git: # to 40 to disable truncation. truncateCopiedCommitHashesTo: 12 +# Config relating to git worktrees +worktree: + # Default parent directory for new worktrees. It is offered as a candidate + # location alongside the parent directories of any worktrees you already have. + # A relative path is resolved against the repository's root directory, so + # "../worktrees" sits beside the repo and ".worktrees" sits inside it. + defaultPath: "" + # Periodic update checks update: # One of: 'prompt' (default) | 'background' | 'never' diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index 1b582c1a0..844ef32bd 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -11,6 +11,8 @@ type UserConfig struct { Gui GuiConfig `yaml:"gui"` // Config relating to git Git GitConfig `yaml:"git"` + // Config relating to git worktrees + Worktree WorktreeConfig `yaml:"worktree"` // Periodic update checks Update UpdateConfig `yaml:"update"` // Background refreshes @@ -422,6 +424,12 @@ type CommitPrefixConfig struct { Replace string `yaml:"replace" jsonschema:"example=[$1]"` } +type WorktreeConfig struct { + // Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have. + // A relative path is resolved against the repository's root directory, so "../worktrees" sits beside the repo and ".worktrees" sits inside it. + DefaultPath string `yaml:"defaultPath"` +} + type UpdateConfig struct { // One of: 'prompt' (default) | 'background' | 'never' Method string `yaml:"method" jsonschema:"enum=prompt,enum=background,enum=never"` @@ -959,6 +967,9 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig { ParseEmoji: false, TruncateCopiedCommitHashesTo: 12, }, + Worktree: WorktreeConfig{ + DefaultPath: "", + }, Refresher: RefresherConfig{ RefreshInterval: 10, FetchInterval: 60, diff --git a/schema-master/config.json b/schema-master/config.json index 85246d640..9963aae61 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -3834,6 +3834,10 @@ "$ref": "#/$defs/GitConfig", "description": "Config relating to git" }, + "worktree": { + "$ref": "#/$defs/WorktreeConfig", + "description": "Config relating to git worktrees" + }, "update": { "$ref": "#/$defs/UpdateConfig", "description": "Periodic update checks" @@ -3899,6 +3903,17 @@ }, "additionalProperties": false, "type": "object" + }, + "WorktreeConfig": { + "properties": { + "defaultPath": { + "type": "string", + "description": "Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have.\nA relative path is resolved against the repository's root directory, so \"../worktrees\" sits beside the repo and \".worktrees\" sits inside it." + } + }, + "additionalProperties": false, + "type": "object", + "description": "Config relating to git worktrees" } } } From b02eca451c876e7c58b7ab8a3a8aa06386cc8630 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 08:13:26 +0200 Subject: [PATCH 021/218] Add helper to compute candidate worktree parent directories This is the core of "never type a path from scratch": from the repo root, the configured default path, and the parents of existing worktrees, derive the ordered list of directories under which a new worktree could be placed. Pure and unit-tested here; wired into the creation flow in a later commit. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/worktree_helper.go | 34 +++++++ .../helpers/worktree_helper_test.go | 94 +++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 pkg/gui/controllers/helpers/worktree_helper_test.go diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 6cb22084b..5f5933746 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -2,6 +2,7 @@ package helpers import ( "errors" + "path/filepath" "strings" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" @@ -10,6 +11,7 @@ import ( "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/samber/lo" ) type WorktreeHelper struct { @@ -219,6 +221,38 @@ func (self *WorktreeHelper) Detach(worktree *models.Worktree) error { }) } +// worktreeParentDirCandidates returns the candidate parent directories in which +// to create a new worktree, in priority order and de-duplicated: +// +// 1. the parent directory of each existing linked worktree (in worktree order); +// 2. the configured default path (relative paths are resolved against repoPath); +// 3. the repo's parent directory, if nothing else is available. +// +// repoPath is RepoPaths.RepoPath(), which is stable regardless of which worktree +// we're currently standing in. All returned paths are absolute. +func worktreeParentDirCandidates(repoPath string, linkedWorktreePaths []string, defaultPath string) []string { + candidates := lo.Map(linkedWorktreePaths, func(path string, _ int) string { + return filepath.Dir(path) + }) + + if defaultPath != "" { + if filepath.IsAbs(defaultPath) { + defaultPath = filepath.Clean(defaultPath) + } else { + defaultPath = filepath.Join(repoPath, defaultPath) + } + candidates = append(candidates, defaultPath) + } + + candidates = lo.Uniq(candidates) + + if len(candidates) == 0 { + candidates = append(candidates, filepath.Dir(repoPath)) + } + + return candidates +} + func (self *WorktreeHelper) ViewWorktreeOptions(context types.IListContext, ref string) error { currentBranch := self.refsHelper.GetCheckedOutRef() canCheckoutBase := context == self.c.Contexts().Branches && ref != currentBranch.RefName() diff --git a/pkg/gui/controllers/helpers/worktree_helper_test.go b/pkg/gui/controllers/helpers/worktree_helper_test.go new file mode 100644 index 000000000..ea975d79d --- /dev/null +++ b/pkg/gui/controllers/helpers/worktree_helper_test.go @@ -0,0 +1,94 @@ +package helpers + +import ( + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/samber/lo" + "github.com/stretchr/testify/assert" +) + +// nativePath rewrites a forward-slash test path into one that is valid on the +// host OS, so the scenarios below can be written with readable Unix-style +// paths. On Windows a leading slash is not absolute (filepath.IsAbs wants a +// drive letter), so we graft one on; relative paths are left untouched. +func nativePath(p string) string { + if runtime.GOOS == "windows" && strings.HasPrefix(p, "/") { + p = "C:" + p + } + return filepath.FromSlash(p) +} + +func TestWorktreeParentDirCandidates(t *testing.T) { + scenarios := []struct { + name string + repoPath string + linkedWorktreePaths []string + defaultPath string + expected []string + }{ + { + name: "no worktrees and no default path falls back to the repo's parent", + repoPath: "/code/myrepo", + linkedWorktreePaths: nil, + defaultPath: "", + expected: []string{"/code"}, + }, + { + name: "uses the parent of each linked worktree, in order", + repoPath: "/code/myrepo", + linkedWorktreePaths: []string{"/code/worktrees/foo", "/elsewhere/bar"}, + defaultPath: "", + expected: []string{"/code/worktrees", "/elsewhere"}, + }, + { + name: "de-duplicates parents shared by multiple worktrees", + repoPath: "/code/myrepo", + linkedWorktreePaths: []string{"/code/worktrees/foo", "/code/worktrees/bar"}, + defaultPath: "", + expected: []string{"/code/worktrees"}, + }, + { + name: "appends the default path after the worktree parents", + repoPath: "/code/myrepo", + linkedWorktreePaths: []string{"/code/worktrees/foo"}, + defaultPath: "/somewhere/else", + expected: []string{"/code/worktrees", "/somewhere/else"}, + }, + { + name: "resolves a relative default path against the repo path", + repoPath: "/code/myrepo", + linkedWorktreePaths: nil, + defaultPath: "../worktrees", + expected: []string{"/code/worktrees"}, + }, + { + name: "resolves a dot-relative default path inside the repo", + repoPath: "/code/myrepo", + linkedWorktreePaths: nil, + defaultPath: ".worktrees", + expected: []string{"/code/myrepo/.worktrees"}, + }, + { + name: "de-duplicates the default path against a worktree parent", + repoPath: "/code/myrepo", + linkedWorktreePaths: []string{"/code/worktrees/foo"}, + defaultPath: "/code/worktrees", + expected: []string{"/code/worktrees"}, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + result := worktreeParentDirCandidates( + nativePath(s.repoPath), + lo.Map(s.linkedWorktreePaths, func(p string, _ int) string { return nativePath(p) }), + nativePath(s.defaultPath), + ) + expected := lo.Map(s.expected, func(p string, _ int) string { return nativePath(p) }) + assert.Equal(t, expected, result) + }) + } +} From 23d01ac1bd1a0f61b63f1b1f642081a6cb08f0fa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 08:40:22 +0200 Subject: [PATCH 022/218] Redesign the 'w' worktree-creation flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The old flow forced an up-front "normal vs detached" menu (meaningless for commits, tags and stashes), then asked the user to type a worktree path from scratch — easy to get wrong, and ambiguous about what relative paths resolve against. It also offered the same two actions everywhere regardless of what was selected. Replace it with per-context "Worktree" menus whose items imply the intent (new branch + worktree, worktree for an existing branch, detached worktree), each feeding a shared name -> location -> create pipeline. The location menu offers candidate parent directories as absolute paths instead of a blank field, and "Worktree for a branch" is disabled (with a reason) when that branch is already checked out somewhere, rather than failing after the fact. Each ref/commit panel binds 'w' in its own controller and calls the matching typed entry point on the worktree helper, so which menu opens is decided statically by the call site rather than by dispatching on a ref's dynamic type. The three commit panels share one menu through BasicCommitsController; there is no longer a shared worktree-options controller. The worktrees-panel 'n' flow and its old core (NewWorktree / NewWorktreeCheckout) are left untouched here so nothing is written and then rewritten; they migrate, and the dead i18n strings get removed, in a follow-up commit. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs-master/keybindings/Keybindings_en.md | 14 +- docs-master/keybindings/Keybindings_ja.md | 14 +- docs-master/keybindings/Keybindings_ko.md | 14 +- docs-master/keybindings/Keybindings_nl.md | 14 +- docs-master/keybindings/Keybindings_pl.md | 14 +- docs-master/keybindings/Keybindings_pt.md | 14 +- docs-master/keybindings/Keybindings_ru.md | 14 +- docs-master/keybindings/Keybindings_zh-CN.md | 14 +- docs-master/keybindings/Keybindings_zh-TW.md | 14 +- pkg/gui/controllers.go | 12 - .../controllers/basic_commits_controller.go | 6 + pkg/gui/controllers/branches_controller.go | 6 + .../controllers/helpers/worktree_helper.go | 231 ++++++++++++++++-- .../controllers/remote_branches_controller.go | 6 + pkg/gui/controllers/stash_controller.go | 6 + pkg/gui/controllers/tags_controller.go | 6 + .../worktree_options_controller.go | 51 ---- pkg/i18n/english.go | 26 +- .../demo/worktree_create_from_branches.go | 20 +- pkg/integration/tests/test_list.go | 5 + .../tests/worktree/add_for_existing_branch.go | 67 +++++ .../tests/worktree/add_from_branch.go | 23 +- .../worktree/add_from_branch_detached.go | 15 +- .../tests/worktree/add_from_commit.go | 17 +- .../tests/worktree/add_from_remote_branch.go | 61 +++++ .../tests/worktree/add_from_stash.go | 51 ++++ .../tests/worktree/add_from_tag.go | 54 ++++ .../tests/worktree/location_candidates.go | 52 ++++ 28 files changed, 662 insertions(+), 179 deletions(-) delete mode 100644 pkg/gui/controllers/worktree_options_controller.go create mode 100644 pkg/integration/tests/worktree/add_for_existing_branch.go create mode 100644 pkg/integration/tests/worktree/add_from_remote_branch.go create mode 100644 pkg/integration/tests/worktree/add_from_stash.go create mode 100644 pkg/integration/tests/worktree/add_from_tag.go create mode 100644 pkg/integration/tests/worktree/location_candidates.go diff --git a/docs-master/keybindings/Keybindings_en.md b/docs-master/keybindings/Keybindings_en.md index b105b8108..4aa202740 100644 --- a/docs-master/keybindings/Keybindings_en.md +++ b/docs-master/keybindings/Keybindings_en.md @@ -112,13 +112,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Search the current view by text | | ## Confirmation panel @@ -178,6 +178,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Checkout | Checkout selected item. | | `` n `` | New branch | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | Create pull request | | | `` O `` | View create pull request options | | | `` G `` | Open pull request in browser | | @@ -197,7 +198,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Main panel (merging) @@ -282,6 +282,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -289,7 +290,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remote branches @@ -299,6 +299,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy branch name to clipboard | | | `` `` | Checkout | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | New branch | | +| `` w `` | New worktree | | | `` M `` | Merge | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | Rebase | Rebase the checked-out branch onto the selected branch. | | `` d `` | Delete | Delete the remote branch from the remote. | @@ -308,7 +309,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remotes @@ -339,10 +339,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Drop | Remove the stash entry from the stash list. | | `` n `` | New branch | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Rename stash | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Status @@ -366,6 +366,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -373,7 +374,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Search the current view by text | | ## Submodules @@ -397,13 +397,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | Checkout | Checkout the selected tag as a detached HEAD. | | `` n `` | New tag | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | Delete | View delete options for local/remote tag. | | `` P `` | Push tag | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Worktrees diff --git a/docs-master/keybindings/Keybindings_ja.md b/docs-master/keybindings/Keybindings_ja.md index a31d93d1a..5b9c798a1 100644 --- a/docs-master/keybindings/Keybindings_ja.md +++ b/docs-master/keybindings/Keybindings_ja.md @@ -92,13 +92,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | 外部差分ツールを開く(git difftool) | | | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストで検索 | | ## コミットファイル @@ -138,6 +138,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | コピーされた(チェリーピックされた)コミットの選択をリセット | | @@ -145,7 +146,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストで検索 | | ## サブモジュール @@ -170,10 +170,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | ポップ | スタッシュエントリをワーキングディレクトリに適用し、スタッシュエントリを削除します。 | | `` d `` | 削除 | スタッシュリストからスタッシュエントリを削除します。 | | `` n `` | 新しいブランチ | 選択したスタッシュエントリから新しいブランチを作成します。これは、スタッシュエントリが作成されたコミットをgitがチェックアウトし、そのコミットから新しいブランチを作成した後、スタッシュエントリを追加のコミットとして新しいブランチに適用することで機能します。 | +| `` w `` | 新しいワークツリー | | | `` r `` | スタッシュの名前を変更 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ステータス @@ -202,13 +202,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | タグをクリップボードにコピー | | | `` `` | チェックアウト(ブランチの切り替え) | 選択したタグをデタッチドHEADとしてチェックアウトします。 | | `` n `` | 新しいタグを作成 | 現在のコミットから新しいタグを作成します。タグ名とオプションの説明を入力するよう促されます。 | +| `` w `` | 新しいワークツリー | | | `` d `` | 削除 | ローカル/リモートタグの削除オプションを表示します。 | | `` P `` | タグをプッシュ | 選択したタグをリモートにプッシュします。リモートを選択するよう促されます。 | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ファイル @@ -326,6 +326,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | コピーされた(チェリーピックされた)コミットの選択をリセット | | @@ -333,7 +334,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## リモート @@ -355,6 +355,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | ブランチ名をクリップボードにコピー | | | `` `` | チェックアウト(ブランチの切り替え) | 選択したリモートブランチに基づいて新しいローカルブランチをチェックアウトするか、リモートブランチをデタッチドヘッドとしてチェックアウトします。 | | `` n `` | 新しいブランチ | | +| `` w `` | 新しいワークツリー | | | `` M `` | マージ | 選択した項目を現在のブランチにマージするためのオプションを表示します(通常のマージ、スカッシュマージ) | | `` r `` | リベース | チェックアウトしたブランチを選択したブランチ上にリベースします。 | | `` d `` | 削除 | リモートからリモートブランチを削除します。 | @@ -364,7 +365,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ローカルブランチ @@ -376,6 +376,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | チェックアウト(ブランチの切り替え) | 選択した項目をチェックアウトします。 | | `` n `` | 新しいブランチ | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` o `` | プルリクエストを作成 | | | `` O `` | プルリクエスト作成オプションを表示 | | | `` G `` | Open pull request in browser | | @@ -395,7 +396,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ワークツリー diff --git a/docs-master/keybindings/Keybindings_ko.md b/docs-master/keybindings/Keybindings_ko.md index ebf943868..d1eb3afb1 100644 --- a/docs-master/keybindings/Keybindings_ko.md +++ b/docs-master/keybindings/Keybindings_ko.md @@ -69,6 +69,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (copied) commits selection | | @@ -76,7 +77,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Secondary @@ -95,10 +95,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Drop | Remove the stash entry from the stash list. | | `` n `` | 새 브랜치 생성 | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Rename stash | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Sub-commits @@ -111,6 +111,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (copied) commits selection | | @@ -118,7 +119,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | 검색 시작 | | ## Worktrees @@ -212,6 +212,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 체크아웃 | Checkout selected item. | | `` n `` | 새 브랜치 생성 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | 풀 리퀘스트 생성 | | | `` O `` | 풀 리퀘스트 생성 옵션 | | | `` G `` | Open pull request in browser | | @@ -231,7 +232,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 상태 @@ -278,6 +278,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 브랜치명을 클립보드에 복사 | | | `` `` | 체크아웃 | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | 새 브랜치 생성 | | +| `` w `` | New worktree | | | `` M `` | 현재 브랜치에 병합 | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | 체크아웃된 브랜치를 이 브랜치에 리베이스 | Rebase the checked-out branch onto the selected branch. | | `` d `` | 삭제 | Delete the remote branch from the remote. | @@ -287,7 +288,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 커밋 @@ -323,13 +323,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | 검색 시작 | | ## 커밋 파일 @@ -366,13 +366,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | 체크아웃 | Checkout the selected tag as a detached HEAD. | | `` n `` | 태그를 생성 | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | 삭제 | View delete options for local/remote tag. | | `` P `` | 태그를 push | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | 초기화 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 파일 diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index a7d7b09ac..7f1216b5f 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -102,6 +102,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Uitchecken | Checkout selected item. | | `` n `` | Nieuwe branch | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | Maak een pull-request | | | `` O `` | Bekijk opties voor pull-aanvraag | | | `` G `` | Open pull request in browser | | @@ -121,7 +122,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Commit bericht @@ -184,13 +184,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Start met zoeken | | ## Input prompt @@ -260,6 +260,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | @@ -267,7 +268,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remote branches @@ -277,6 +277,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Kopieer branch name naar klembord | | | `` `` | Uitchecken | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | Nieuwe branch | | +| `` w `` | New worktree | | | `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | Rebase branch | Rebase the checked-out branch onto the selected branch. | | `` d `` | Delete | Delete the remote branch from the remote. | @@ -286,7 +287,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remotes @@ -339,10 +339,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Laten vallen | Remove the stash entry from the stash list. | | `` n `` | Nieuwe branch | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Rename stash | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Status @@ -366,6 +366,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | @@ -373,7 +374,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Start met zoeken | | ## Submodules @@ -397,13 +397,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | Uitchecken | Checkout the selected tag as a detached HEAD. | | `` n `` | Creëer tag | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | Delete | View delete options for local/remote tag. | | `` P `` | Push tag | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Worktrees diff --git a/docs-master/keybindings/Keybindings_pl.md b/docs-master/keybindings/Keybindings_pl.md index 1f6710416..719a7e6c4 100644 --- a/docs-master/keybindings/Keybindings_pl.md +++ b/docs-master/keybindings/Keybindings_pl.md @@ -85,13 +85,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Dodatkowy @@ -122,6 +122,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Resetuj wybrane (cherry-picked) commity | | @@ -129,7 +130,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Główny panel (budowanie łatki) @@ -164,6 +164,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Przełącz | Przełącz wybrany element. | | `` n `` | Nowa gałąź | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` o `` | Utwórz żądanie ściągnięcia | | | `` O `` | Zobacz opcje tworzenia pull requesta | | | `` G `` | Otwórz żądanie ściągnięcia w przeglądarce | | @@ -183,7 +184,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Menu @@ -318,10 +318,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Wyciągnij | Zastosuj wpis schowka do katalogu roboczego i usuń wpis schowka. | | `` d `` | Usuń | Usuń wpis schowka z listy schowka. | | `` n `` | Nowa gałąź | Utwórz nową gałąź z wybranego wpisu schowka. Działa poprzez przełączenie git na commit, na którym wpis schowka został utworzony, tworzenie nowej gałęzi z tego commita, a następnie zastosowanie wpisu schowka do nowej gałęzi jako dodatkowego commita. | +| `` w `` | Nowe drzewo pracy | | | `` r `` | Zmień nazwę schowka | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Status @@ -345,6 +345,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Resetuj wybrane (cherry-picked) commity | | @@ -352,7 +353,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Submoduły @@ -376,13 +376,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Skopiuj tag do schowka | | | `` `` | Przełącz | Przełącz wybrany tag jako odłączoną głowę (detached HEAD). | | `` n `` | Nowy tag | Utwórz nowy tag z bieżącego commita. Zostaniesz poproszony o wprowadzenie nazwy tagu i opcjonalnego opisu. | +| `` w `` | Nowe drzewo pracy | | | `` d `` | Usuń | Wyświetl opcje usuwania lokalnego/odległego tagu. | | `` P `` | Wyślij tag | Wyślij wybrany tag do zdalnego. Zostaniesz poproszony o wybranie zdalnego. | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Zdalne @@ -404,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Kopiuj nazwę gałęzi do schowka | | | `` `` | Przełącz | Przełącz na nową lokalną gałąź na podstawie wybranej gałęzi zdalnej. Nowa gałąź będzie śledzić gałąź zdalną. | | `` n `` | Nowa gałąź | | +| `` w `` | Nowe drzewo pracy | | | `` M `` | Scal | Scal wybraną gałąź z aktualnie sprawdzoną gałęzią. | | `` r `` | Przebazuj | Przebazuj przełączoną gałąź na wybraną gałąź. | | `` d `` | Usuń | Usuń gałąź zdalną ze zdalnego. | @@ -413,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | diff --git a/docs-master/keybindings/Keybindings_pt.md b/docs-master/keybindings/Keybindings_pt.md index a2d163735..5fcba2688 100644 --- a/docs-master/keybindings/Keybindings_pt.md +++ b/docs-master/keybindings/Keybindings_pt.md @@ -94,6 +94,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Verificar | Checar item selecionado | | `` n `` | Nova branch | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` o `` | Criar solicitação de pull | | | `` O `` | View create pull request options | | | `` G `` | Open pull request in browser | | @@ -113,7 +114,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Branches remotos @@ -123,6 +123,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copiar nome da branch para área de transferência | | | `` `` | Verificar | Checar a nova branch baseada na brach remota selecionada, ou a branch remota como HEAD, desanexado | | `` n `` | Nova branch | | +| `` w `` | Nova árvore de trabalho | | | `` M `` | Mesclar | Ver opções para mesclar o item selecionado no branch atual (mesclar regularmente, mesclar squash) | | `` r `` | Refazer | Refazer a branch checada na branch selecionada | | `` d `` | Apagar | Excluir o branch remoto do controle remoto. | @@ -132,7 +133,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Commit arquivos @@ -188,13 +188,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Pesquisar na visualização atual por texto | | ## Etiquetas @@ -204,13 +204,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copiar etiqueta para área de transferência | | | `` `` | Verificar | Checar a tag selecionada como um HEAD, desanexado | | `` n `` | Nova etiqueta | Crie uma nova etiqueta a partir do commit atual. Você será solicitado a digitar um nome e uma descrição opcional. | +| `` w `` | Nova árvore de trabalho | | | `` d `` | Apagar | Ver opções de exclusão para tag local/remoto. | | `` P `` | Empurrar etiqueta | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Input prompt @@ -310,6 +310,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -317,7 +318,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Remotes @@ -348,10 +348,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Aplique a entrada de stash no seu diretório de trabalho e remova a entrada de stash. | | `` d `` | Descartar | Remova a entrada do stash da lista de armazenamento. | | `` n `` | Nova branch | Criar um novo ramo a partir da entrada de lixo selecionada. Isso funciona verificando o commit do qual a entrada de lixo foi criada, criar um novo branch a partir desse commit e, em seguida, aplicar a entrada de lixo ao novo branch como um commit adicional. | +| `` w `` | Nova árvore de trabalho | | | `` r `` | Renomear o stash | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Status @@ -375,6 +375,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -382,7 +383,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Pesquisar na visualização atual por texto | | ## Submódulos diff --git a/docs-master/keybindings/Keybindings_ru.md b/docs-master/keybindings/Keybindings_ru.md index 68be4a601..683135448 100644 --- a/docs-master/keybindings/Keybindings_ru.md +++ b/docs-master/keybindings/Keybindings_ru.md @@ -151,6 +151,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Сбросить отобранную (скопированную \| cherry-picked) выборку коммитов | | @@ -158,7 +159,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Коммиты @@ -194,13 +194,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Найти | | ## Локальные Ветки @@ -212,6 +212,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Переключить | Checkout selected item. | | `` n `` | Новая ветка | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | Создать запрос на принятие изменений | | | `` O `` | Создать параметры запроса принятие изменений | | | `` G `` | Open pull request in browser | | @@ -231,7 +232,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Меню @@ -260,6 +260,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Сбросить отобранную (скопированную \| cherry-picked) выборку коммитов | | @@ -267,7 +268,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Найти | | ## Подмодули @@ -329,13 +329,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | Переключить | Checkout the selected tag as a detached HEAD. | | `` n `` | Создать тег | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | Delete | View delete options for local/remote tag. | | `` P `` | Отправить тег | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Удалённые ветки @@ -345,6 +345,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Скопировать название ветки в буфер обмена | | | `` `` | Переключить | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | Новая ветка | | +| `` w `` | New worktree | | | `` M `` | Слияние с текущей переключённой веткой | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | Перебазировать переключённую ветку на эту ветку | Rebase the checked-out branch onto the selected branch. | | `` d `` | Delete | Delete the remote branch from the remote. | @@ -354,7 +355,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Удалённые репозитории @@ -410,8 +410,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Применить припрятанные изменения и тут же удалить их из хранилища | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Удалить припрятанные изменения из хранилища | Remove the stash entry from the stash list. | | `` n `` | Новая ветка | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Переименовать хранилище | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | diff --git a/docs-master/keybindings/Keybindings_zh-CN.md b/docs-master/keybindings/Keybindings_zh-CN.md index 6828c35e3..b4f1134ec 100644 --- a/docs-master/keybindings/Keybindings_zh-CN.md +++ b/docs-master/keybindings/Keybindings_zh-CN.md @@ -62,6 +62,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 重置已拣选(复制)的提交 | | @@ -69,7 +70,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 开始搜索 | | ## 子模块 @@ -106,6 +106,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 重置已拣选(复制)的提交 | | @@ -113,7 +114,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 提交 @@ -149,13 +149,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 使用外部差异比较工具(git difftool) | | | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 开始搜索 | | ## 提交信息 @@ -227,6 +227,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 检出 | 检出选中的项目 | | `` n `` | 新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` o `` | 创建拉取请求 | | | `` O `` | 创建拉取请求选项 | | | `` G `` | 在浏览器中打开拉取请求 | | @@ -246,7 +247,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 构建补丁中 @@ -272,13 +272,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 复制标签到剪贴板 | | | `` `` | 检出 | 检出选择的标签作为分离的HEAD | | `` n `` | 创建标签 | 基于当前提交创建一个新标签。您将在弹窗中输入标签名称和描述(可选)。 | +| `` w `` | 新建工作树 | | | `` d `` | 删除 | 查看本地/远程标签的删除选项 | | `` P `` | 推送标签 | 推送选择的标签到远端。您将在弹窗中选择一个远端。 | | `` g `` | 重置 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 次要 @@ -372,10 +372,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | 应用并删除 | 将存储项应用到工作目录并删除存储项。 | | `` d `` | 删除 | 从贮藏列表中删除该贮藏项 | | `` n `` | 新分支 | 从选定的贮藏项创建一个新分支。这是通过 git 检查创建贮藏项的提交,从该提交创建一个新分支,然后将贮藏项作为附加提交应用到新分支来实现的。 | +| `` w `` | 新建工作树 | | | `` r `` | 重命名贮藏 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 输入提示 @@ -404,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 复制分支名称到剪贴板 | | | `` `` | 检出 | 基于当前选中的远程分支检出一个新的本地分支,或者将远程分支作分离的HEAD。 | | `` n `` | 新分支 | | +| `` w `` | 新建工作树 | | | `` M `` | 合并到当前检出的分支 | 查看将选中项合并到当前分支的选项(正常合并,压缩合并) | | `` r `` | 变基 | 将检出的分支变基到所选的分支上。 | | `` d `` | 删除 | 从远程删除远程分支。 | @@ -413,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | diff --git a/docs-master/keybindings/Keybindings_zh-TW.md b/docs-master/keybindings/Keybindings_zh-TW.md index 56d383ff9..b50e25d35 100644 --- a/docs-master/keybindings/Keybindings_zh-TW.md +++ b/docs-master/keybindings/Keybindings_zh-TW.md @@ -141,6 +141,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 重設選定的揀選 (複製) 提交 | | @@ -148,7 +149,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 子模組 @@ -208,13 +208,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 開啟外部差異工具 (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 提交摘要 @@ -252,10 +252,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | 還原 | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | 捨棄 | Remove the stash entry from the stash list. | | `` n `` | 新分支 | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | 重新命名收藏 | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 日誌 @@ -268,6 +268,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 重設選定的揀選 (複製) 提交 | | @@ -275,7 +276,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 本地分支 @@ -287,6 +287,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 檢出 | 檢出選定的項目。 | | `` n `` | 新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | 建立拉取請求 | | | `` O `` | 建立拉取請求選項 | | | `` G `` | Open pull request in browser | | @@ -306,7 +307,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 標籤 @@ -316,13 +316,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | 檢出 | Checkout the selected tag as a detached HEAD. | | `` n `` | 建立標籤 | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | 刪除 | View delete options for local/remote tag. | | `` P `` | 推送標籤 | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | 重設 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 檔案 @@ -404,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 複製分支名稱到剪貼簿 | | | `` `` | 檢出 | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | 新分支 | | +| `` w `` | New worktree | | | `` M `` | 合併到當前檢出的分支 | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | 將已檢出的分支變基至此分支 | Rebase the checked-out branch onto the selected branch. | | `` d `` | 刪除 | Delete the remote branch from the remote. | @@ -413,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | diff --git a/pkg/gui/controllers.go b/pkg/gui/controllers.go index 51e240a5d..a7eb35919 100644 --- a/pkg/gui/controllers.go +++ b/pkg/gui/controllers.go @@ -207,18 +207,6 @@ func (gui *Gui) resetHelpersAndControllers() { 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, diff --git a/pkg/gui/controllers/basic_commits_controller.go b/pkg/gui/controllers/basic_commits_controller.go index 2ddb5055e..f8b8d6783 100644 --- a/pkg/gui/controllers/basic_commits_controller.go +++ b/pkg/gui/controllers/basic_commits_controller.go @@ -89,6 +89,12 @@ func (self *BasicCommitsController) GetKeybindings(opts types.KeybindingsOpts) [ Description: self.c.Tr.MoveCommitsToNewBranch, Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, + { + Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForCommit), + Description: self.c.Tr.NewWorktree, + OpensMenu: true, + }, { Keys: opts.GetKeys(opts.Config.Commits.ViewResetOptions), Handler: self.withItem(self.createResetMenu), diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index c2c0595c3..7846febbf 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -69,6 +69,12 @@ func (self *BranchesController) GetKeybindings(opts types.KeybindingsOpts) []*ty Description: self.c.Tr.MoveCommitsToNewBranch, Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, + { + Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForBranch), + Description: self.c.Tr.NewWorktree, + OpensMenu: true, + }, { Keys: opts.GetKeys(opts.Config.Branches.CreatePullRequest), Handler: self.withItem(self.handleCreatePullRequest), diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 5f5933746..3eef892cf 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -253,31 +253,218 @@ func worktreeParentDirCandidates(repoPath string, linkedWorktreePaths []string, return candidates } -func (self *WorktreeHelper) ViewWorktreeOptions(context types.IListContext, ref string) error { - currentBranch := self.refsHelper.GetCheckedOutRef() - canCheckoutBase := context == self.c.Contexts().Branches && ref != currentBranch.RefName() - - return self.ViewBranchWorktreeOptions(ref, canCheckoutBase) +func (self *WorktreeHelper) NewWorktreeMenuForBranch(branch *models.Branch) error { + return self.worktreeMenu( + self.newBranchAndWorktreeItem(branch.Name, branch.RefName()), + self.worktreeForBranchItem(branch), + self.detachedWorktreeItem(branch.Name, branch.RefName(), branch.Name), + ) } -func (self *WorktreeHelper) ViewBranchWorktreeOptions(branchName string, canCheckoutBase bool) error { - placeholders := map[string]string{"ref": branchName} +func (self *WorktreeHelper) NewWorktreeMenuForCommit(commit *models.Commit) error { + return self.worktreeMenu( + self.newBranchAndWorktreeItem(commit.ShortHash(), commit.RefName()), + self.detachedWorktreeItem(commit.ShortHash(), commit.RefName(), ""), + ) +} +func (self *WorktreeHelper) NewWorktreeMenuForTag(tag *models.Tag) error { + return self.worktreeMenu( + self.newBranchAndWorktreeItem(tag.Name, tag.RefName()), + self.detachedWorktreeItem(tag.Name, tag.RefName(), ""), + ) +} + +func (self *WorktreeHelper) NewWorktreeMenuForStash(stash *models.StashEntry) error { + return self.worktreeMenu( + self.newBranchAndWorktreeItem(stash.RefName(), stash.FullRefName()), + self.detachedWorktreeItem(stash.RefName(), stash.FullRefName(), ""), + ) +} + +func (self *WorktreeHelper) NewWorktreeMenuForRemoteBranch(remoteBranch *models.RemoteBranch) error { + // e.g. "origin/foo" -> "foo": the local branch's (and worktree's) default name + strippedName := strings.SplitAfterN(remoteBranch.RefName(), "/", 2)[1] + + return self.worktreeMenu( + self.newLocalBranchAndWorktreeItem(remoteBranch, strippedName), + self.detachedWorktreeItem(remoteBranch.FullName(), remoteBranch.FullName(), strippedName), + ) +} + +func (self *WorktreeHelper) worktreeMenu(items ...*types.MenuItem) error { return self.c.Menu(types.CreateMenuOptions{ - Title: self.c.Tr.WorktreeTitle, - Items: []*types.MenuItem{ - { - LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFrom, placeholders)}, - OnPress: func() error { - return self.NewWorktreeCheckout(branchName, canCheckoutBase, false, context.LOCAL_BRANCHES_CONTEXT_KEY) - }, - }, - { - LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFromDetached, placeholders)}, - OnPress: func() error { - return self.NewWorktreeCheckout(branchName, canCheckoutBase, true, context.LOCAL_BRANCHES_CONTEXT_KEY) - }, - }, - }, + Title: self.c.Tr.NewWorktree, + Items: items, + }) +} + +// newBranchAndWorktreeItem is the "new branch + worktree" action for a ref that +// isn't a remote branch (a branch, commit, tag or stash). ref is what we show the +// user (branch name, short hash, stash@{n}, ...); base is what we hand to +// `git worktree add`. +func (self *WorktreeHelper) newBranchAndWorktreeItem(ref string, base string) *types.MenuItem { + return &types.MenuItem{ + Label: utils.ResolvePlaceholderString(self.c.Tr.NewBranchAndWorktreeFromRef, map[string]string{"ref": ref}), + Keys: menuKey('b'), + OnPress: func() error { + return self.startNewBranchWorktree("", base, func(name string) string { + return utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptNewBranch, + map[string]string{"name": name, "base": ref}) + }) + }, + } +} + +// newLocalBranchAndWorktreeItem is the "new branch + worktree" action for a remote +// branch: the new local branch tracks the remote one, and its name defaults to the +// remote branch name with the remote stripped off. +func (self *WorktreeHelper) newLocalBranchAndWorktreeItem(remoteBranch *models.RemoteBranch, strippedName string) *types.MenuItem { + return &types.MenuItem{ + Label: utils.ResolvePlaceholderString(self.c.Tr.NewLocalBranchAndWorktreeFromRef, map[string]string{"ref": remoteBranch.FullName()}), + Keys: menuKey('b'), + OnPress: func() error { + return self.startNewBranchWorktree(strippedName, remoteBranch.FullName(), func(name string) string { + return utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptTrackingBranch, + map[string]string{"name": name, "ref": remoteBranch.FullName()}) + }) + }, + } +} + +// startNewBranchWorktree runs the shared name -> location -> create pipeline for the +// new-branch actions: prompt for the branch (and worktree) name, ask for the +// location, then create a worktree on a freshly created branch of that name. +// locationPrompt builds the location-menu prompt once the name is known. +func (self *WorktreeHelper) startNewBranchWorktree(nameInitialContent string, base string, locationPrompt func(name string) string) error { + return self.promptForName(self.c.Tr.NewBranchAndWorktreeName, nameInitialContent, func(name string) error { + return self.promptForWorktreeLocation(name, locationPrompt(name), func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Branch: name}) + }) + }) +} + +// worktreeForBranchItem is the "check out an existing branch in a new worktree" +// action. It's disabled when the branch is already checked out somewhere. +func (self *WorktreeHelper) worktreeForBranchItem(branch *models.Branch) *types.MenuItem { + return &types.MenuItem{ + Label: utils.ResolvePlaceholderString(self.c.Tr.WorktreeForRef, map[string]string{"ref": branch.Name}), + Keys: menuKey('w'), + OnPress: func() error { + prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptCheckout, + map[string]string{"branchName": branch.Name}) + return self.promptForWorktreeLocation(branch.Name, prompt, func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: branch.RefName()}) + }) + }, + DisabledReason: self.branchCheckedOutDisabledReason(branch), + } +} + +// detachedWorktreeItem is the "detached worktree at a ref" action. ref is shown to +// the user; base is handed to `git worktree add`. defaultDirName is the worktree +// directory name to use; when it's empty we prompt for one instead (commits, tags +// and stashes have no good name to derive). +func (self *WorktreeHelper) detachedWorktreeItem(ref string, base string, defaultDirName string) *types.MenuItem { + prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptDetached, map[string]string{"ref": ref}) + create := func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Detach: true}) + } + + return &types.MenuItem{ + Label: utils.ResolvePlaceholderString(self.c.Tr.DetachedWorktreeAtRef, map[string]string{"ref": ref}), + Keys: menuKey('d'), + OnPress: func() error { + if defaultDirName != "" { + return self.promptForWorktreeLocation(defaultDirName, prompt, create) + } + return self.promptForName(self.c.Tr.NewWorktreeName, "", func(name string) error { + return self.promptForWorktreeLocation(name, prompt, create) + }) + }, + } +} + +func (self *WorktreeHelper) branchCheckedOutDisabledReason(branch *models.Branch) *types.DisabledReason { + if worktree, ok := git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees); ok { + return &types.DisabledReason{ + Text: utils.ResolvePlaceholderString(self.c.Tr.BranchCheckedOutByWorktree, + map[string]string{"branchName": branch.Name, "worktreeName": worktree.Name}), + } + } + + return nil +} + +// promptForName asks for a branch/worktree name and sanitizes the response (most +// notably turning spaces into dashes so it's a valid branch name) before +// continuing. +func (self *WorktreeHelper) promptForName(title string, initialContent string, onConfirm func(name string) error) error { + self.c.Prompt(types.PromptOpts{ + Title: title, + InitialContent: initialContent, + HandleConfirm: func(response string) error { + return onConfirm(SanitizedBranchName(response)) + }, + }) + + return nil +} + +// promptForWorktreeLocation shows the location menu: one item per candidate parent +// directory (each labelled with the absolute path the worktree would end up at), +// plus an "Other…" item that opens a free-form path prompt. The chosen absolute +// path is passed to onConfirm. +func (self *WorktreeHelper) promptForWorktreeLocation(dirName string, prompt string, onConfirm func(path string) error) error { + linkedWorktreePaths := []string{} + for _, worktree := range self.c.Model().Worktrees { + if !worktree.IsMain { + linkedWorktreePaths = append(linkedWorktreePaths, worktree.Path) + } + } + parentDirs := worktreeParentDirCandidates( + self.c.Git().RepoPaths.RepoPath(), + linkedWorktreePaths, + self.c.UserConfig().Worktree.DefaultPath, + ) + + targets := lo.Map(parentDirs, func(parentDir string, _ int) string { + return filepath.Join(parentDir, dirName) + }) + + menuItems := lo.Map(targets, func(target string, _ int) *types.MenuItem { + return &types.MenuItem{ + Label: target, + OnPress: func() error { return onConfirm(target) }, + } + }) + + menuItems = append(menuItems, &types.MenuItem{ + Label: self.c.Tr.WorktreeLocationOther, + OnPress: func() error { + self.c.Prompt(types.PromptOpts{ + Title: self.c.Tr.NewWorktreePath, + InitialContent: targets[0], + HandleConfirm: onConfirm, + }) + return nil + }, + }) + + return self.c.Menu(types.CreateMenuOptions{ + Title: self.c.Tr.WorktreeLocationTitle, + Prompt: prompt, + Items: menuItems, + }) +} + +func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts) error { + return self.c.WithWaitingStatus(self.c.Tr.AddingWorktree, func(gocui.Task) error { + self.c.LogAction(self.c.Tr.Actions.AddWorktree) + if err := self.c.Git().Worktree.New(opts); err != nil { + return err + } + + return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, context.LOCAL_BRANCHES_CONTEXT_KEY) }) } diff --git a/pkg/gui/controllers/remote_branches_controller.go b/pkg/gui/controllers/remote_branches_controller.go index 3a49c0114..d232730c6 100644 --- a/pkg/gui/controllers/remote_branches_controller.go +++ b/pkg/gui/controllers/remote_branches_controller.go @@ -48,6 +48,12 @@ func (self *RemoteBranchesController) GetKeybindings(opts types.KeybindingsOpts) GetDisabledReason: self.require(self.singleItemSelected()), Description: self.c.Tr.NewBranch, }, + { + Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForRemoteBranch), + Description: self.c.Tr.NewWorktree, + OpensMenu: true, + }, { Keys: opts.GetKeys(opts.Config.Branches.MergeIntoCurrentBranch), Handler: opts.Guards.OutsideFilterMode(self.withItem(self.merge)), diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index 49abedd9f..3f0bd9be2 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -66,6 +66,12 @@ func (self *StashController) GetKeybindings(opts types.KeybindingsOpts) []*types Description: self.c.Tr.NewBranch, Tooltip: self.c.Tr.NewBranchFromStashTooltip, }, + { + Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForStash), + Description: self.c.Tr.NewWorktree, + OpensMenu: true, + }, { Keys: opts.GetKeys(opts.Config.Stash.RenameStash), Handler: self.withItem(self.handleRenameStashEntry), diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index a10f9a374..fd61e239d 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -53,6 +53,12 @@ func (self *TagsController) GetKeybindings(opts types.KeybindingsOpts) []*types. Tooltip: self.c.Tr.NewTagTooltip, DisplayOnScreen: true, }, + { + Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForTag), + Description: self.c.Tr.NewWorktree, + OpensMenu: true, + }, { Keys: opts.GetKeys(opts.Config.Universal.Remove), Handler: self.withItem(self.delete), diff --git a/pkg/gui/controllers/worktree_options_controller.go b/pkg/gui/controllers/worktree_options_controller.go deleted file mode 100644 index b1123e2a8..000000000 --- a/pkg/gui/controllers/worktree_options_controller.go +++ /dev/null @@ -1,51 +0,0 @@ -package controllers - -import ( - "github.com/jesseduffield/lazygit/pkg/gui/types" -) - -// This controller is for all contexts that have items you can create a worktree from - -var _ types.IController = &WorktreeOptionsController{} - -type CanViewWorktreeOptions interface { - types.IListContext -} - -type WorktreeOptionsController struct { - baseController - *ListControllerTrait[string] - c *ControllerCommon - context CanViewWorktreeOptions -} - -func NewWorktreeOptionsController(c *ControllerCommon, context CanViewWorktreeOptions) *WorktreeOptionsController { - return &WorktreeOptionsController{ - baseController: baseController{}, - ListControllerTrait: NewListControllerTrait( - c, - context, - context.GetSelectedItemId, - context.GetSelectedItemIds, - ), - c: c, - context: context, - } -} - -func (self *WorktreeOptionsController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding { - bindings := []*types.Binding{ - { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), - Handler: self.withItem(self.viewWorktreeOptions), - Description: self.c.Tr.ViewWorktreeOptions, - OpensMenu: true, - }, - } - - return bindings -} - -func (self *WorktreeOptionsController) viewWorktreeOptions(ref string) error { - return self.c.Helpers().Worktree.ViewWorktreeOptions(self.context, ref) -} diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index db8cdbd5e..bb8d8637e 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -894,9 +894,20 @@ type TranslationSet struct { RemoveWorktreeTooltip string NewBranchName string NewBranchNameLeaveBlank string - ViewWorktreeOptions string CreateWorktreeFrom string CreateWorktreeFromDetached string + NewWorktreeName string + NewBranchAndWorktreeName string + NewBranchAndWorktreeFromRef string + NewLocalBranchAndWorktreeFromRef string + WorktreeForRef string + DetachedWorktreeAtRef string + WorktreeLocationTitle string + WorktreeLocationOther string + WorktreeLocationPromptNewBranch string + WorktreeLocationPromptTrackingBranch string + WorktreeLocationPromptCheckout string + WorktreeLocationPromptDetached string LcWorktree string ChangingDirectoryTo string DirenvApprovalTitle string @@ -2028,9 +2039,20 @@ func EnglishTranslationSet() *TranslationSet { RemoveWorktreeTooltip: "Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory.", NewBranchName: "New branch name", NewBranchNameLeaveBlank: "New branch name (leave blank to checkout {{.default}})", - ViewWorktreeOptions: "View worktree options", CreateWorktreeFrom: "Create worktree from {{.ref}}", CreateWorktreeFromDetached: "Create worktree from {{.ref}} (detached)", + NewWorktreeName: "New worktree name", + NewBranchAndWorktreeName: "New branch and worktree name", + NewBranchAndWorktreeFromRef: "New branch and worktree from '{{.ref}}'", + NewLocalBranchAndWorktreeFromRef: "New local branch and worktree from '{{.ref}}'", + WorktreeForRef: "New worktree for '{{.ref}}'", + DetachedWorktreeAtRef: "New detached worktree at '{{.ref}}'", + WorktreeLocationTitle: "Worktree location", + WorktreeLocationOther: "Other…", + WorktreeLocationPromptNewBranch: "New branch '{{.name}}' from '{{.base}}':", + WorktreeLocationPromptTrackingBranch: "New branch '{{.name}}' tracking '{{.ref}}':", + WorktreeLocationPromptCheckout: "Worktree for branch '{{.branchName}}':", + WorktreeLocationPromptDetached: "Detached worktree at '{{.ref}}':", LcWorktree: "worktree", ChangingDirectoryTo: "Changing directory to {{.path}}", DirenvApprovalTitle: "Approve .envrc?", diff --git a/pkg/integration/tests/demo/worktree_create_from_branches.go b/pkg/integration/tests/demo/worktree_create_from_branches.go index 39d2cb73e..817cb704b 100644 --- a/pkg/integration/tests/demo/worktree_create_from_branches.go +++ b/pkg/integration/tests/demo/worktree_create_from_branches.go @@ -39,19 +39,25 @@ var WorktreeCreateFromBranches = NewIntegrationTest(NewIntegrationTestArgs{ t.Wait(500) t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(Contains("Create worktree from master").DoesNotContain("detached")). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from 'master'")). + Confirm() + + t.ExpectPopup().Prompt(). + Title(Equals("New branch and worktree name")). + Type("hotfix/db-on-fire"). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Select(Contains("Other…")). Confirm() t.ExpectPopup().Prompt(). Title(Equals("New worktree path")). + Clear(). Type("../hotfix"). Confirm() - - t.ExpectPopup().Prompt(). - Title(Contains("New branch name")). - Type("hotfix/db-on-fire"). - Confirm() }) }, }) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 74e471713..443b29fad 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -495,9 +495,13 @@ var tests = []*components.IntegrationTest{ undo.UndoCheckoutAndDrop, undo.UndoCommit, undo.UndoDrop, + worktree.AddForExistingBranch, worktree.AddFromBranch, worktree.AddFromBranchDetached, worktree.AddFromCommit, + worktree.AddFromRemoteBranch, + worktree.AddFromStash, + worktree.AddFromTag, worktree.AssociateBranchBisect, worktree.AssociateBranchRebase, worktree.BareRepo, @@ -512,6 +516,7 @@ var tests = []*components.IntegrationTest{ worktree.FastForwardWorktreeBranchShouldNotPolluteCurrentWorktree, worktree.ForceRemoveWorktree, worktree.ForceRemoveWorktreeWithSubmodules, + worktree.LocationCandidates, worktree.RemoveWorktreeFromBranch, worktree.ResetWindowTabs, worktree.SymlinkIntoRepoSubdir, diff --git a/pkg/integration/tests/worktree/add_for_existing_branch.go b/pkg/integration/tests/worktree/add_for_existing_branch.go new file mode 100644 index 000000000..fb238bcda --- /dev/null +++ b/pkg/integration/tests/worktree/add_for_existing_branch.go @@ -0,0 +1,67 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var AddForExistingBranch = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Create a worktree that checks out an existing branch (no new branch), and confirm the option is disabled for an already-checked-out branch", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.NewBranchFrom("otherbranch", "mybranch") + shell.Checkout("mybranch") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Branches(). + Focus(). + Lines( + Contains("mybranch").IsSelected(), + Contains("otherbranch"), + ). + // the current branch is checked out by this worktree, so "Worktree + // for 'mybranch'" is disabled + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup(). + Menu(). + Title(Equals("New worktree")). + Select(Contains("New worktree for 'mybranch'")). + Tooltip(Contains("Branch mybranch is checked out by worktree repo")). + Confirm(). + Tap(func() { + t.ExpectToast(Contains("Branch mybranch is checked out by worktree repo")) + }). + Cancel() + }). + // otherbranch is not checked out anywhere, so we can make a worktree for it + NavigateToLine(Contains("otherbranch")). + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New worktree for 'otherbranch'")). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }) + + // we've switched into the new worktree, which has otherbranch checked out + t.Views().Branches(). + IsFocused(). + Lines( + Contains("otherbranch").IsSelected(), + Contains("mybranch (worktree repo)"), + ) + + t.Views().Status(). + Content(Contains("repo(otherbranch) → otherbranch")) + }, +}) diff --git a/pkg/integration/tests/worktree/add_from_branch.go b/pkg/integration/tests/worktree/add_from_branch.go index ab7807571..87898c794 100644 --- a/pkg/integration/tests/worktree/add_from_branch.go +++ b/pkg/integration/tests/worktree/add_from_branch.go @@ -6,7 +6,7 @@ import ( ) var AddFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "Add a worktree via the branches view, then switch back to the main worktree via the branches view", + Description: "Create a new branch and worktree from a branch, then switch back to the main worktree via the branches view", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(config *config.AppConfig) {}, @@ -24,19 +24,20 @@ var AddFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ Press(keys.Worktrees.ViewWorktreeOptions). Tap(func() { t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(Contains(`Create worktree from mybranch`).DoesNotContain("detached")). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from 'mybranch'")). Confirm() t.ExpectPopup().Prompt(). - Title(Equals("New worktree path")). - Type("../linked-worktree"). - Confirm() - - t.ExpectPopup().Prompt(). - Title(Equals("New branch name")). + Title(Equals("New branch and worktree name")). Type("newbranch"). Confirm() + + // no existing worktrees and no configured default path, so the + // only candidate location is the repo's parent directory; accept it + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() }). // confirm we're still focused on the branches view IsFocused(). @@ -54,7 +55,9 @@ var AddFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("mybranch").IsSelected(), - Contains("newbranch (worktree linked-worktree)"), + // the worktree's directory name matches the branch name, so the + // branches view shows the compact "(worktree)" with no name + Contains("newbranch (worktree)"), ). // Confirm the files view is still showing in the files window Press(keys.Universal.PrevBlock) diff --git a/pkg/integration/tests/worktree/add_from_branch_detached.go b/pkg/integration/tests/worktree/add_from_branch_detached.go index 70f27dc81..6b74baff6 100644 --- a/pkg/integration/tests/worktree/add_from_branch_detached.go +++ b/pkg/integration/tests/worktree/add_from_branch_detached.go @@ -6,7 +6,7 @@ import ( ) var AddFromBranchDetached = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "Add a detached worktree via the branches view", + Description: "Add a detached worktree at a branch via the branches view, choosing a custom location", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(config *config.AppConfig) {}, @@ -24,12 +24,21 @@ var AddFromBranchDetached = NewIntegrationTest(NewIntegrationTestArgs{ Press(keys.Worktrees.ViewWorktreeOptions). Tap(func() { t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(Contains(`Create worktree from mybranch (detached)`)). + Title(Equals("New worktree")). + Select(Contains("New detached worktree at 'mybranch'")). + Confirm() + + // the location menu defaults the directory name to the branch + // name; pick "Other…" to type a different path instead + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Select(Contains("Other…")). Confirm() t.ExpectPopup().Prompt(). Title(Equals("New worktree path")). + InitialText(Contains("mybranch")). + Clear(). Type("../linked-worktree"). Confirm() }). diff --git a/pkg/integration/tests/worktree/add_from_commit.go b/pkg/integration/tests/worktree/add_from_commit.go index 49b69697b..484370ae3 100644 --- a/pkg/integration/tests/worktree/add_from_commit.go +++ b/pkg/integration/tests/worktree/add_from_commit.go @@ -6,7 +6,7 @@ import ( ) var AddFromCommit = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "Add a worktree via the commits view", + Description: "Create a new branch and worktree from a commit via the commits view", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(config *config.AppConfig) {}, @@ -27,19 +27,18 @@ var AddFromCommit = NewIntegrationTest(NewIntegrationTestArgs{ Press(keys.Worktrees.ViewWorktreeOptions). Tap(func() { t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(MatchesRegexp(`Create worktree from .*`).DoesNotContain("detached")). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from")). Confirm() t.ExpectPopup().Prompt(). - Title(Equals("New worktree path")). - Type("../linked-worktree"). - Confirm() - - t.ExpectPopup().Prompt(). - Title(Equals("New branch name")). + Title(Equals("New branch and worktree name")). Type("newbranch"). Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() }). Lines( Contains("initial commit"), diff --git a/pkg/integration/tests/worktree/add_from_remote_branch.go b/pkg/integration/tests/worktree/add_from_remote_branch.go new file mode 100644 index 000000000..6dd4ea761 --- /dev/null +++ b/pkg/integration/tests/worktree/add_from_remote_branch.go @@ -0,0 +1,61 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var AddFromRemoteBranch = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Create a new local tracking branch and worktree from a remote branch", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.NewBranch("feature") + shell.CloneIntoRemote("origin") + shell.Checkout("master") + // drop the local branch so only the remote one remains + shell.RunCommand([]string{"git", "branch", "-D", "feature"}) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Remotes(). + Focus(). + Lines( + Contains("origin").IsSelected(), + ). + PressEnter() + + t.Views().RemoteBranches(). + IsFocused(). + NavigateToLine(Contains("feature")). + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New local branch and worktree from 'origin/feature'")). + Confirm() + + // the new branch name defaults to the remote branch name with + // the remote stripped off + t.ExpectPopup().Prompt(). + Title(Equals("New branch and worktree name")). + InitialText(Equals("feature")). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }) + + // we've switched into the new worktree, on a local branch that tracks + // the remote one (the ✓ confirms tracking is set up) + t.Views().Branches(). + IsFocused(). + Lines( + Contains("feature").Contains("✓").IsSelected(), + Contains("master (worktree repo)"), + ) + }, +}) diff --git a/pkg/integration/tests/worktree/add_from_stash.go b/pkg/integration/tests/worktree/add_from_stash.go new file mode 100644 index 000000000..26a3b97c4 --- /dev/null +++ b/pkg/integration/tests/worktree/add_from_stash.go @@ -0,0 +1,51 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var AddFromStash = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Create a new branch and worktree from a stash entry", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.UpdateFile("README.md", "work in progress") + shell.Stash("my stash") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Stash(). + Focus(). + Lines( + Contains("my stash").IsSelected(), + ). + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from 'stash@{0}'")). + Confirm() + + t.ExpectPopup().Prompt(). + Title(Equals("New branch and worktree name")). + Type("from-stash"). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }) + + // we've switched into the new worktree, on the new branch + t.Views().Branches(). + IsFocused(). + Lines( + Contains("from-stash").IsSelected(), + Contains("mybranch (worktree repo)"), + ) + }, +}) diff --git a/pkg/integration/tests/worktree/add_from_tag.go b/pkg/integration/tests/worktree/add_from_tag.go new file mode 100644 index 000000000..22ef2bb07 --- /dev/null +++ b/pkg/integration/tests/worktree/add_from_tag.go @@ -0,0 +1,54 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var AddFromTag = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Create a detached worktree at a tag, entering a worktree name", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.CreateLightweightTag("v1.0", "HEAD") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Tags(). + Focus(). + Lines( + Contains("v1.0").IsSelected(), + ). + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New detached worktree at 'v1.0'")). + Confirm() + + // a tag has no good name to derive, so we're asked for one + t.ExpectPopup().Prompt(). + Title(Equals("New worktree name")). + Type("tag-worktree"). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }) + + // we've switched into the new worktree, with a detached head + t.Views().Branches(). + IsFocused(). + Lines( + Contains("(no branch)").IsSelected(), + Contains("mybranch (worktree repo)"), + ) + + t.Views().Status(). + Content(Contains("repo(tag-worktree)")) + }, +}) diff --git a/pkg/integration/tests/worktree/location_candidates.go b/pkg/integration/tests/worktree/location_candidates.go new file mode 100644 index 000000000..2160c6109 --- /dev/null +++ b/pkg/integration/tests/worktree/location_candidates.go @@ -0,0 +1,52 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var LocationCandidates = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The location menu offers the parents of existing worktrees and the configured default path, and sanitizes the typed name", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) { + config.GetUserConfig().Worktree.DefaultPath = "../config-worktrees" + }, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + // a pre-existing linked worktree, so its parent directory is offered as + // a candidate location alongside the configured default path + shell.RunCommand([]string{"git", "worktree", "add", "-b", "existing", "../manual-worktrees/existing"}) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Branches(). + Focus(). + NavigateToLine(Contains("mybranch")). + Press(keys.Worktrees.ViewWorktreeOptions). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from 'mybranch'")). + Confirm() + + // the space is sanitized to a dash so it's a valid branch (and + // directory) name + t.ExpectPopup().Prompt(). + Title(Equals("New branch and worktree name")). + Type("new feature"). + Confirm() + + // the parent of the existing worktree comes first, then the + // configured default path; both target the sanitized name + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + ContainsLines( + Contains("manual-worktrees").Contains("new-feature"), + Contains("config-worktrees").Contains("new-feature"), + ). + Cancel() + }) + }, +}) From 768d9f1a3f5c0cfc79297daf8f511dd50facb859 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 15:26:38 +0200 Subject: [PATCH 023/218] Rework the worktrees-panel 'n' into a branch picker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The old 'n' flow opened a "normal vs detached" menu (the same meaningless gate the 'w' flow used to have), then asked for a base ref, a path typed from scratch, and a branch name in three separate prompts. Replace it with a single picker prompt titled "New worktree for branch", suggesting local branches not already checked out anywhere, plus remote branches that don't yet have a local branch of the same name. The entered value is classified on confirm: an existing local branch checks out into a new worktree, a remote branch creates a new local tracking branch, and anything else creates a new branch off the current ref. All three then feed the same location menu the 'w' flow uses, so paths are chosen from candidates rather than typed blind. Picking a remote or new branch needs no separate name prompt — the picker value already is the name. Checked-out branches are filtered from the suggestions, and a verbatim type-in of one is rejected with an error. createWorktree now takes the context to switch focus to once the worktree is created, so 'n' lands back in the worktrees panel while 'w' still lands in the branches panel. This deletes the old NewWorktree / NewWorktreeCheckout core and the now- orphaned i18n (CreateWorktreeFrom, CreateWorktreeFromDetached, NewWorktreeBase, NewBranchNameLeaveBlank), completing the migration started for 'w'. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/suggestions_helper.go | 23 +++ .../controllers/helpers/worktree_helper.go | 147 ++++++------------ pkg/i18n/english.go | 10 +- pkg/integration/tests/test_list.go | 2 + pkg/integration/tests/worktree/crud.go | 20 ++- .../tests/worktree/new_worktree_picker.go | 64 ++++++++ .../worktree/new_worktree_picker_remote.go | 60 +++++++ .../tests/worktree/worktree_in_repo.go | 18 +-- 8 files changed, 217 insertions(+), 127 deletions(-) create mode 100644 pkg/integration/tests/worktree/new_worktree_picker.go create mode 100644 pkg/integration/tests/worktree/new_worktree_picker_remote.go diff --git a/pkg/gui/controllers/helpers/suggestions_helper.go b/pkg/gui/controllers/helpers/suggestions_helper.go index e88fe3822..d26f96f1c 100644 --- a/pkg/gui/controllers/helpers/suggestions_helper.go +++ b/pkg/gui/controllers/helpers/suggestions_helper.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/jesseduffield/generics/set" + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/presentation" @@ -84,6 +85,28 @@ func (self *SuggestionsHelper) GetBranchNameSuggestionsFunc() func(string) []*ty } } +// GetWorktreeBranchNameSuggestionsFunc suggests branches you can base a new +// worktree on: local branches that aren't checked out in any worktree (you can't +// make a second worktree for them), plus remote branches that don't yet have a +// local branch of the same name. Picking a remote branch creates a new local +// tracking branch, which would fail if that local branch already existed (whether +// or not it's checked out), so we leave those out and you reach the branch via its +// local entry instead. +func (self *SuggestionsHelper) GetWorktreeBranchNameSuggestionsFunc() func(string) []*types.Suggestion { + localBranchNames := lo.FilterMap(self.c.Model().Branches, func(branch *models.Branch, _ int) (string, bool) { + _, checkedOut := git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees) + return branch.Name, !checkedOut + }) + + existingLocalBranches := set.NewFromSlice(self.getBranchNames()) + remoteBranchNames := lo.Filter(self.getRemoteBranchNames("/"), func(remoteBranchName string, _ int) bool { + _, branchName, _ := strings.Cut(remoteBranchName, "/") + return !existingLocalBranches.Includes(branchName) + }) + + return FilterFunc(append(localBranchNames, remoteBranchNames...), self.c.UserConfig().Gui.UseFuzzySearch()) +} + // here we asynchronously fetch the latest set of paths in the repo and store in // self.c.Model().FilesTrie. On the main thread we'll be doing a fuzzy search via // self.c.Model().FilesTrie. So if we've looked for a file previously, we'll start with diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 3eef892cf..2bc877444 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -57,105 +57,58 @@ func (self *WorktreeHelper) GetLinkedWorktreeName() string { } func (self *WorktreeHelper) NewWorktree() error { - branch := self.refsHelper.GetCheckedOutRef() - currentBranchName := branch.RefName() - - f := func(detached bool) { - self.c.Prompt(types.PromptOpts{ - Title: self.c.Tr.NewWorktreeBase, - InitialContent: currentBranchName, - FindSuggestionsFunc: self.suggestionsHelper.GetRefsSuggestionsFunc(), - HandleConfirm: func(base string) error { - // we assume that the base can be checked out - canCheckoutBase := true - return self.NewWorktreeCheckout(base, canCheckoutBase, detached, context.WORKTREES_CONTEXT_KEY) - }, - }) - } - - placeholders := map[string]string{"ref": "ref"} - - return self.c.Menu(types.CreateMenuOptions{ - Title: self.c.Tr.WorktreeTitle, - Items: []*types.MenuItem{ - { - LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFrom, placeholders)}, - OnPress: func() error { - f(false) - return nil - }, - }, - { - LabelColumns: []string{utils.ResolvePlaceholderString(self.c.Tr.CreateWorktreeFromDetached, placeholders)}, - OnPress: func() error { - f(true) - return nil - }, - }, - }, - }) -} - -func (self *WorktreeHelper) NewWorktreeCheckout(base string, canCheckoutBase bool, detached bool, contextKey types.ContextKey) error { - opts := git_commands.NewWorktreeOpts{ - Base: base, - Detach: detached, - } - - f := func() error { - return self.c.WithWaitingStatus(self.c.Tr.AddingWorktree, func(gocui.Task) error { - self.c.LogAction(self.c.Tr.Actions.AddWorktree) - if err := self.c.Git().Worktree.New(opts); err != nil { - return err - } - - return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) - }) - } - self.c.Prompt(types.PromptOpts{ - Title: self.c.Tr.NewWorktreePath, - HandleConfirm: func(path string) error { - opts.Path = path - - if detached { - return f() - } - - if canCheckoutBase { - title := utils.ResolvePlaceholderString(self.c.Tr.NewBranchNameLeaveBlank, map[string]string{"default": base}) - // prompt for the new branch name where a blank means we just check out the branch - self.c.Prompt(types.PromptOpts{ - Title: title, - HandleConfirm: func(branchName string) error { - opts.Branch = branchName - - return f() - }, - AllowEmptyInput: true, - }) - - return nil - } - - // prompt for the new branch name - self.c.Prompt(types.PromptOpts{ - Title: self.c.Tr.NewBranchName, - HandleConfirm: func(branchName string) error { - opts.Branch = branchName - - return f() - }, - AllowEmptyInput: false, - }) - - return nil + Title: self.c.Tr.NewWorktreeForBranchTitle, + FindSuggestionsFunc: self.suggestionsHelper.GetWorktreeBranchNameSuggestionsFunc(), + HandleConfirm: func(value string) error { + return self.newWorktreeForPickerValue(value) }, }) return nil } +// newWorktreeForPickerValue classifies the value the user picked or typed in the +// worktrees-panel picker and routes to the matching creation flow: +// - an existing local branch -> a worktree that checks it out; +// - a remote branch -> a new local tracking branch + worktree; +// - anything else -> a new branch off the current ref + worktree. +// +// All three then feed the shared location menu. The picker filters out branches +// already checked out somewhere, but a verbatim type-in is still guarded here. +func (self *WorktreeHelper) newWorktreeForPickerValue(value string) error { + if branch, ok := lo.Find(self.c.Model().Branches, func(branch *models.Branch) bool { + return branch.Name == value + }); ok { + if worktree, ok := git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees); ok { + return errors.New(utils.ResolvePlaceholderString(self.c.Tr.BranchCheckedOutByWorktree, + map[string]string{"branchName": branch.Name, "worktreeName": worktree.Name})) + } + + prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptCheckout, + map[string]string{"branchName": branch.Name}) + return self.promptForWorktreeLocation(branch.Name, prompt, func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: branch.RefName()}, context.WORKTREES_CONTEXT_KEY) + }) + } + + if _, branchName, ok := self.refsHelper.ParseRemoteBranchName(value); ok { + prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptTrackingBranch, + map[string]string{"name": branchName, "ref": value}) + return self.promptForWorktreeLocation(branchName, prompt, func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: value, Branch: branchName}, context.WORKTREES_CONTEXT_KEY) + }) + } + + name := SanitizedBranchName(value) + base := self.refsHelper.GetCheckedOutRef().RefName() + prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptNewBranch, + map[string]string{"name": name, "base": base}) + return self.promptForWorktreeLocation(name, prompt, func(path string) error { + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Branch: name}, context.WORKTREES_CONTEXT_KEY) + }) +} + func (self *WorktreeHelper) Switch(worktree *models.Worktree, contextKey types.ContextKey) error { if worktree.IsCurrent { return errors.New(self.c.Tr.AlreadyInWorktree) @@ -339,7 +292,7 @@ func (self *WorktreeHelper) newLocalBranchAndWorktreeItem(remoteBranch *models.R func (self *WorktreeHelper) startNewBranchWorktree(nameInitialContent string, base string, locationPrompt func(name string) string) error { return self.promptForName(self.c.Tr.NewBranchAndWorktreeName, nameInitialContent, func(name string) error { return self.promptForWorktreeLocation(name, locationPrompt(name), func(path string) error { - return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Branch: name}) + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Branch: name}, context.LOCAL_BRANCHES_CONTEXT_KEY) }) }) } @@ -354,7 +307,7 @@ func (self *WorktreeHelper) worktreeForBranchItem(branch *models.Branch) *types. prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptCheckout, map[string]string{"branchName": branch.Name}) return self.promptForWorktreeLocation(branch.Name, prompt, func(path string) error { - return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: branch.RefName()}) + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: branch.RefName()}, context.LOCAL_BRANCHES_CONTEXT_KEY) }) }, DisabledReason: self.branchCheckedOutDisabledReason(branch), @@ -368,7 +321,7 @@ func (self *WorktreeHelper) worktreeForBranchItem(branch *models.Branch) *types. func (self *WorktreeHelper) detachedWorktreeItem(ref string, base string, defaultDirName string) *types.MenuItem { prompt := utils.ResolvePlaceholderString(self.c.Tr.WorktreeLocationPromptDetached, map[string]string{"ref": ref}) create := func(path string) error { - return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Detach: true}) + return self.createWorktree(git_commands.NewWorktreeOpts{Path: path, Base: base, Detach: true}, context.LOCAL_BRANCHES_CONTEXT_KEY) } return &types.MenuItem{ @@ -458,13 +411,13 @@ func (self *WorktreeHelper) promptForWorktreeLocation(dirName string, prompt str }) } -func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts) error { +func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts, contextKey types.ContextKey) error { return self.c.WithWaitingStatus(self.c.Tr.AddingWorktree, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddWorktree) if err := self.c.Git().Worktree.New(opts); err != nil { return err } - return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, context.LOCAL_BRANCHES_CONTEXT_KEY) + return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) }) } diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index bb8d8637e..822e47c10 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -890,13 +890,10 @@ type TranslationSet struct { MainWorktree string NewWorktree string NewWorktreePath string - NewWorktreeBase string RemoveWorktreeTooltip string NewBranchName string - NewBranchNameLeaveBlank string - CreateWorktreeFrom string - CreateWorktreeFromDetached string NewWorktreeName string + NewWorktreeForBranchTitle string NewBranchAndWorktreeName string NewBranchAndWorktreeFromRef string NewLocalBranchAndWorktreeFromRef string @@ -2035,13 +2032,10 @@ func EnglishTranslationSet() *TranslationSet { MainWorktree: "(main worktree)", NewWorktree: "New worktree", NewWorktreePath: "New worktree path", - NewWorktreeBase: "New worktree base ref", RemoveWorktreeTooltip: "Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory.", NewBranchName: "New branch name", - NewBranchNameLeaveBlank: "New branch name (leave blank to checkout {{.default}})", - CreateWorktreeFrom: "Create worktree from {{.ref}}", - CreateWorktreeFromDetached: "Create worktree from {{.ref}} (detached)", NewWorktreeName: "New worktree name", + NewWorktreeForBranchTitle: "New worktree for branch", NewBranchAndWorktreeName: "New branch and worktree name", NewBranchAndWorktreeFromRef: "New branch and worktree from '{{.ref}}'", NewLocalBranchAndWorktreeFromRef: "New local branch and worktree from '{{.ref}}'", diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 443b29fad..5aa8a21ee 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -517,6 +517,8 @@ var tests = []*components.IntegrationTest{ worktree.ForceRemoveWorktree, worktree.ForceRemoveWorktreeWithSubmodules, worktree.LocationCandidates, + worktree.NewWorktreePicker, + worktree.NewWorktreePickerRemote, worktree.RemoveWorktreeFromBranch, worktree.ResetWindowTabs, worktree.SymlinkIntoRepoSubdir, diff --git a/pkg/integration/tests/worktree/crud.go b/pkg/integration/tests/worktree/crud.go index cd539d10b..6cda94141 100644 --- a/pkg/integration/tests/worktree/crud.go +++ b/pkg/integration/tests/worktree/crud.go @@ -33,25 +33,23 @@ var Crud = NewIntegrationTest(NewIntegrationTestArgs{ ). Press(keys.Universal.New). Tap(func() { - t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(Contains(`Create worktree from ref`).DoesNotContain(("detached"))). + // a name that isn't an existing branch creates a new branch off + // the current one + t.ExpectPopup().Prompt(). + Title(Equals("New worktree for branch")). + Type("newbranch"). Confirm() - t.ExpectPopup().Prompt(). - Title(Equals("New worktree base ref")). - InitialText(Equals("mybranch")). + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Select(Contains("Other…")). Confirm() t.ExpectPopup().Prompt(). Title(Equals("New worktree path")). + Clear(). Type("../linked-worktree"). Confirm() - - t.ExpectPopup().Prompt(). - Title(Equals("New branch name (leave blank to checkout mybranch)")). - Type("newbranch"). - Confirm() }). Lines( Contains("linked-worktree").IsSelected(), diff --git a/pkg/integration/tests/worktree/new_worktree_picker.go b/pkg/integration/tests/worktree/new_worktree_picker.go new file mode 100644 index 000000000..58915e8b5 --- /dev/null +++ b/pkg/integration/tests/worktree/new_worktree_picker.go @@ -0,0 +1,64 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var NewWorktreePicker = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "From the worktrees panel, the picker suggests only branches not already checked out, guards verbatim type-ins, and checks out an existing branch", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.NewBranchFrom("feature", "mybranch") + shell.Checkout("mybranch") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Worktrees(). + Focus(). + Lines( + Contains("(main worktree)"), + ). + Press(keys.Universal.New). + Tap(func() { + // mybranch is checked out by the current worktree, so it's not + // suggested; feature is + t.ExpectPopup().Prompt(). + Title(Equals("New worktree for branch")). + SuggestionLines(Contains("feature")). + // typing a checked-out branch verbatim is still rejected + Type("mybranch"). + Confirm() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Contains("Branch mybranch is checked out by worktree repo")). + Confirm() + }). + Press(keys.Universal.New). + Tap(func() { + // picking an existing branch checks it out (no new branch) + t.ExpectPopup().Prompt(). + Title(Equals("New worktree for branch")). + Type("feature"). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }). + // we stay in the worktrees panel, now switched into the new worktree + IsFocused(). + Lines( + Contains("feature").IsSelected(), + Contains("(main worktree)"), + ) + + t.Views().Status(). + Content(Contains("repo(feature) → feature")) + }, +}) diff --git a/pkg/integration/tests/worktree/new_worktree_picker_remote.go b/pkg/integration/tests/worktree/new_worktree_picker_remote.go new file mode 100644 index 000000000..55b156d7f --- /dev/null +++ b/pkg/integration/tests/worktree/new_worktree_picker_remote.go @@ -0,0 +1,60 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var NewWorktreePickerRemote = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "From the worktrees panel, picking a remote branch creates a new local tracking branch and worktree; remote branches whose local branch already exists are filtered out", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.NewBranch("feature") + shell.NewBranch("existing") + shell.CloneIntoRemote("origin") + shell.Checkout("master") + // "feature" now exists only on the remote; "existing" stays as a local + // branch (not checked out) that also has a remote counterpart + shell.RunCommand([]string{"git", "branch", "-D", "feature"}) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Worktrees(). + Focus(). + Press(keys.Universal.New). + Tap(func() { + // master is checked out, so neither it nor origin/master is + // offered; "existing" already has a local branch, so + // origin/existing is left out too (you'd reach it via the local + // entry); origin/feature has no local branch, so it's offered + t.ExpectPopup().Prompt(). + Title(Equals("New worktree for branch")). + SuggestionLines( + Contains("existing"), + Contains("origin/feature"), + ). + Type("origin/feature"). + Confirm() + + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Confirm() + }). + IsFocused(). + Lines( + Contains("feature").IsSelected(), + Contains("(main worktree)"), + ) + + // the new worktree is on a local branch that tracks the remote one (the + // ✓ confirms tracking is set up) + t.Views().Branches(). + Focus(). + ContainsLines( + Contains("feature").Contains("✓").IsSelected(), + ) + }, +}) diff --git a/pkg/integration/tests/worktree/worktree_in_repo.go b/pkg/integration/tests/worktree/worktree_in_repo.go index 5f0ee66ec..f6b5b44a3 100644 --- a/pkg/integration/tests/worktree/worktree_in_repo.go +++ b/pkg/integration/tests/worktree/worktree_in_repo.go @@ -28,25 +28,21 @@ var WorktreeInRepo = NewIntegrationTest(NewIntegrationTestArgs{ ). Press(keys.Universal.New). Tap(func() { - t.ExpectPopup().Menu(). - Title(Equals("Worktree")). - Select(Contains(`Create worktree from ref`).DoesNotContain(("detached"))). + t.ExpectPopup().Prompt(). + Title(Equals("New worktree for branch")). + Type("newbranch"). Confirm() - t.ExpectPopup().Prompt(). - Title(Equals("New worktree base ref")). - InitialText(Equals("mybranch")). + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + Select(Contains("Other…")). Confirm() t.ExpectPopup().Prompt(). Title(Equals("New worktree path")). + Clear(). Type("linked-worktree"). Confirm() - - t.ExpectPopup().Prompt(). - Title(Equals("New branch name (leave blank to checkout mybranch)")). - Type("newbranch"). - Confirm() }). Lines( Contains("linked-worktree").IsSelected(), From d53a9ea854ae4529ef54e49e6ff6ea6926dd5ff6 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 17:43:30 +0200 Subject: [PATCH 024/218] Add MoveYamlKey helper to move config keys between sections RenameYamlKey can only rename a key in place, under the same parent. To migrate a keybinding from one section to another we need to relocate the key to a different parent mapping, which is a move, not a rename. MoveYamlKey creates intermediate maps at the destination as needed and prunes any maps left empty behind the key, so a section that held only the moved key doesn't linger as an empty mapping in the user's config. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/utils/yaml_utils/yaml_utils.go | 92 +++++++++++++++++++++++++ pkg/utils/yaml_utils/yaml_utils_test.go | 82 ++++++++++++++++++++++ 2 files changed, 174 insertions(+) diff --git a/pkg/utils/yaml_utils/yaml_utils.go b/pkg/utils/yaml_utils/yaml_utils.go index f8f7f0679..251d4dc01 100644 --- a/pkg/utils/yaml_utils/yaml_utils.go +++ b/pkg/utils/yaml_utils/yaml_utils.go @@ -101,6 +101,98 @@ func renameYamlKey(node *yaml.Node, path []string, newKey string) (error, bool) return renameYamlKey(valueNode, path[1:], newKey) } +// Takes the root node of a yaml document, the path to an existing key, and the +// path at which it should live instead. If the key exists, it (and its value) +// is moved to the new path, creating intermediate mapping nodes as needed, and +// any mapping nodes left empty behind it are removed. Does nothing if the key +// at oldPath doesn't exist. Returns an error if a key already exists at newPath, +// or if a node along either path exists but isn't a mapping. +func MoveYamlKey(rootNode *yaml.Node, oldPath []string, newPath []string) (error, bool) { + // Empty document: nothing to do. + if len(rootNode.Content) == 0 { + return nil, false + } + + body := rootNode.Content[0] + + // Bail out early if there's nothing to move. + oldParent, err := findContainingMap(body, oldPath, false) + if err != nil { + return err, false + } + if oldParent == nil { + return nil, false + } + keyNode, valueNode := LookupKey(oldParent, oldPath[len(oldPath)-1]) + if keyNode == nil { + return nil, false + } + + // Find or create the destination map, and make sure it's free. + newParent, err := findContainingMap(body, newPath, true) + if err != nil { + return err, false + } + newKey := newPath[len(newPath)-1] + if existing, _ := LookupKey(newParent, newKey); existing != nil { + return fmt.Errorf("new key `%s' already exists", newKey), false + } + + // Move the key, then prune any maps that became empty behind it. The + // destination is populated first so that a map shared by both paths isn't + // mistaken for empty during pruning. + RemoveKey(oldParent, oldPath[len(oldPath)-1]) + keyNode.Value = newKey + newParent.Content = append(newParent.Content, keyNode, valueNode) + removeEmptyMaps(body, oldPath[:len(oldPath)-1]) + + return nil, true +} + +// Descends path (excluding its final element) and returns the mapping node that +// should directly contain that final element. With create set, missing +// intermediate maps are created; otherwise a missing intermediate yields a nil +// result. Returns an error if a node along the path exists but isn't a mapping. +func findContainingMap(node *yaml.Node, path []string, create bool) (*yaml.Node, error) { + for _, key := range path[:len(path)-1] { + if node.Kind != yaml.MappingNode { + return nil, errors.New("yaml node in path is not a dictionary") + } + _, valueNode := LookupKey(node, key) + if valueNode == nil { + if !create { + return nil, nil + } + valueNode = &yaml.Node{Kind: yaml.MappingNode} + node.Content = append(node.Content, + &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, + valueNode) + } + node = valueNode + } + if node.Kind != yaml.MappingNode { + return nil, errors.New("yaml node in path is not a dictionary") + } + return node, nil +} + +// Walks path from node and removes any mapping that is empty once its child has +// been removed, cascading upward. Stops at the first non-empty ancestor (which +// keeps every ancestor above it non-empty too). +func removeEmptyMaps(node *yaml.Node, path []string) { + if len(path) == 0 { + return + } + _, child := LookupKey(node, path[0]) + if child == nil { + return + } + removeEmptyMaps(child, path[1:]) + if child.Kind == yaml.MappingNode && len(child.Content) == 0 { + RemoveKey(node, path[0]) + } +} + // 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 { diff --git a/pkg/utils/yaml_utils/yaml_utils_test.go b/pkg/utils/yaml_utils/yaml_utils_test.go index d4d1fe074..059f65022 100644 --- a/pkg/utils/yaml_utils/yaml_utils_test.go +++ b/pkg/utils/yaml_utils/yaml_utils_test.go @@ -103,6 +103,88 @@ func TestRenameYamlKey(t *testing.T) { } } +func TestMoveYamlKey(t *testing.T) { + tests := []struct { + name string + in string + oldPath []string + newPath []string + expectedOut string + expectedDidMove bool + expectedErr string + }{ + { + name: "move key into an existing section", + in: "keybinding:\n worktrees:\n viewWorktreeOptions: w\n universal:\n quit: q\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n universal:\n quit: q\n newWorktree: w\n", + expectedDidMove: true, + }, + { + name: "create the destination section if it doesn't exist", + in: "keybinding:\n worktrees:\n viewWorktreeOptions: w\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n universal:\n newWorktree: w\n", + expectedDidMove: true, + }, + { + name: "keep non-empty siblings when pruning the old section", + in: "keybinding:\n worktrees:\n viewWorktreeOptions: w\n other: x\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n worktrees:\n other: x\n universal:\n newWorktree: w\n", + expectedDidMove: true, + }, + { + name: "don't rewrite file if the key doesn't exist", + in: "keybinding:\n universal:\n quit: q\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n universal:\n quit: q\n", + expectedDidMove: false, + }, + + // Error cases + { + name: "destination key already exists", + in: "keybinding:\n worktrees:\n viewWorktreeOptions: w\n universal:\n newWorktree: x\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n worktrees:\n viewWorktreeOptions: w\n universal:\n newWorktree: x\n", + expectedDidMove: false, + expectedErr: "new key `newWorktree' already exists", + }, + { + name: "node in path is not a dictionary", + in: "keybinding:\n worktrees: nonsense\n", + oldPath: []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + newPath: []string{"keybinding", "universal", "newWorktree"}, + expectedOut: "keybinding:\n worktrees: nonsense\n", + expectedDidMove: false, + expectedErr: "yaml node in path is not a dictionary", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + node := unmarshalForTest(t, test.in) + actualErr, didMove := MoveYamlKey(&node, test.oldPath, test.newPath) + 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.expectedDidMove, didMove) + }) + } +} + func TestWalk_paths(t *testing.T) { tests := []struct { name string From 737fb989670cd6d57fc6b9862a0957c9ddbc6afd Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 29 Jun 2026 17:47:25 +0200 Subject: [PATCH 025/218] Move the new-worktree keybinding from worktrees to universal The command was renamed from "View worktree options" to "New worktree", but its keybinding config key was still 'worktrees.viewWorktreeOptions'. That name no longer matches the command, and the 'worktrees' section made little sense: it held a single binding that isn't even used in the worktrees panel (that panel uses universal.new), only in the branches, remotes, tags, commits, and stash panels. Other keybinding sections are named after the panel they're local to; this one wasn't local to any. Move it to universal.newWorktree, which describes the action and drops the spurious section, and migrate existing configs automatically. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs-master/Config.md | 3 +- pkg/config/app_config.go | 23 ++++++- pkg/config/app_config_test.go | 67 +++++++++++++++++++ pkg/config/user_config.go | 10 +-- .../controllers/basic_commits_controller.go | 2 +- pkg/gui/controllers/branches_controller.go | 2 +- .../controllers/remote_branches_controller.go | 2 +- pkg/gui/controllers/stash_controller.go | 2 +- pkg/gui/controllers/tags_controller.go | 2 +- .../demo/worktree_create_from_branches.go | 2 +- .../tests/worktree/add_for_existing_branch.go | 4 +- .../tests/worktree/add_from_branch.go | 2 +- .../worktree/add_from_branch_detached.go | 2 +- .../tests/worktree/add_from_commit.go | 2 +- .../tests/worktree/add_from_remote_branch.go | 2 +- .../tests/worktree/add_from_stash.go | 2 +- .../tests/worktree/add_from_tag.go | 2 +- .../tests/worktree/location_candidates.go | 2 +- schema-master/config.json | 37 ++++------ 19 files changed, 121 insertions(+), 49 deletions(-) diff --git a/docs-master/Config.md b/docs-master/Config.md index 183a0c6b2..bf0f5c2c6 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -689,6 +689,7 @@ keybinding: confirmInEditor: [, ] remove: d new: "n" + newWorktree: w edit: e openFile: o scrollUpMain: [, K, ] @@ -769,8 +770,6 @@ keybinding: fetchRemote: f addForkRemote: F sortOrder: s - worktrees: - viewWorktreeOptions: w commits: squashDown: s renameCommit: r diff --git a/pkg/config/app_config.go b/pkg/config/app_config.go index e7267158a..313d71dcf 100644 --- a/pkg/config/app_config.go +++ b/pkg/config/app_config.go @@ -287,6 +287,26 @@ func computeMigratedConfig(path string, content []byte, changes *ChangesSet) ([] } } + pathsToMove := []struct { + oldPath []string + newPath []string + }{ + { + []string{"keybinding", "worktrees", "viewWorktreeOptions"}, + []string{"keybinding", "universal", "newWorktree"}, + }, + } + + for _, pathToMove := range pathsToMove { + err, didMove := yaml_utils.MoveYamlKey(&rootNode, pathToMove.oldPath, pathToMove.newPath) + if err != nil { + return nil, false, fmt.Errorf("Couldn't migrate config file at `%s` for key %s: %w", path, strings.Join(pathToMove.oldPath, "."), err) + } + if didMove { + changes.Add(fmt.Sprintf("Moved '%s' to '%s'", strings.Join(pathToMove.oldPath, "."), strings.Join(pathToMove.newPath, "."))) + } + } + err = changeNullKeybindingsToDisabled(&rootNode, changes) if err != nil { return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err) @@ -449,7 +469,8 @@ func migrateAllBranchesLogCmd(rootNode *yaml.Node, changes *ChangesSet) error { // 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, + gitNode.Content = append( + gitNode.Content, cmdsKeyNode, cmdsValueNode, ) diff --git a/pkg/config/app_config_test.go b/pkg/config/app_config_test.go index 8e6c85f32..913bc47dc 100644 --- a/pkg/config/app_config_test.go +++ b/pkg/config/app_config_test.go @@ -78,6 +78,73 @@ keybinding: } } +func TestMigrationOfMovedKeys(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 move needed", + input: `foo: + bar: 5 +`, + expectedDidChange: false, + expectedChanges: []string{}, + }, + { + name: "Move worktree keybinding into the universal section", + input: `keybinding: + universal: + quit: q + worktrees: + viewWorktreeOptions: w +`, + expected: `keybinding: + universal: + quit: q + newWorktree: w +`, + expectedDidChange: true, + expectedChanges: []string{"Moved 'keybinding.worktrees.viewWorktreeOptions' to 'keybinding.universal.newWorktree'"}, + }, + { + name: "Create the universal section if it doesn't exist", + input: `keybinding: + worktrees: + viewWorktreeOptions: w +`, + expected: `keybinding: + universal: + newWorktree: w +`, + expectedDidChange: true, + expectedChanges: []string{"Moved 'keybinding.worktrees.viewWorktreeOptions' to 'keybinding.universal.newWorktree'"}, + }, + } + + 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 diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index 844ef32bd..f83e26ea3 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -442,7 +442,6 @@ type KeybindingConfig struct { 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"` @@ -510,6 +509,7 @@ type KeybindingUniversalConfig struct { ConfirmInEditorAlt Keybinding `yaml:"confirmInEditor-alt"` Remove Keybinding `yaml:"remove"` New Keybinding `yaml:"new"` + NewWorktree Keybinding `yaml:"newWorktree"` Edit Keybinding `yaml:"edit"` OpenFile Keybinding `yaml:"openFile"` ScrollUpMain Keybinding `yaml:"scrollUpMain"` @@ -604,10 +604,6 @@ type KeybindingBranchesConfig struct { SortOrder Keybinding `yaml:"sortOrder"` } -type KeybindingWorktreesConfig struct { - ViewWorktreeOptions Keybinding `yaml:"viewWorktreeOptions"` -} - type KeybindingCommitsConfig struct { SquashDown Keybinding `yaml:"squashDown"` RenameCommit Keybinding `yaml:"renameCommit"` @@ -1035,6 +1031,7 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig { ConfirmInEditorAlt: Keybinding{""}, Remove: Keybinding{"d"}, New: Keybinding{"n"}, + NewWorktree: Keybinding{"w"}, Edit: Keybinding{"e"}, OpenFile: Keybinding{"o"}, OpenRecentRepos: Keybinding{""}, @@ -1120,9 +1117,6 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig { AddForkRemote: Keybinding{"F"}, SortOrder: Keybinding{"s"}, }, - Worktrees: KeybindingWorktreesConfig{ - ViewWorktreeOptions: Keybinding{"w"}, - }, Commits: KeybindingCommitsConfig{ SquashDown: Keybinding{"s"}, RenameCommit: Keybinding{"r"}, diff --git a/pkg/gui/controllers/basic_commits_controller.go b/pkg/gui/controllers/basic_commits_controller.go index f8b8d6783..410335712 100644 --- a/pkg/gui/controllers/basic_commits_controller.go +++ b/pkg/gui/controllers/basic_commits_controller.go @@ -90,7 +90,7 @@ func (self *BasicCommitsController) GetKeybindings(opts types.KeybindingsOpts) [ Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Keys: opts.GetKeys(opts.Config.Universal.NewWorktree), Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForCommit), Description: self.c.Tr.NewWorktree, OpensMenu: true, diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index 7846febbf..27bef4b66 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -70,7 +70,7 @@ func (self *BranchesController) GetKeybindings(opts types.KeybindingsOpts) []*ty Tooltip: self.c.Tr.MoveCommitsToNewBranchTooltip, }, { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Keys: opts.GetKeys(opts.Config.Universal.NewWorktree), Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForBranch), Description: self.c.Tr.NewWorktree, OpensMenu: true, diff --git a/pkg/gui/controllers/remote_branches_controller.go b/pkg/gui/controllers/remote_branches_controller.go index d232730c6..f70145d7b 100644 --- a/pkg/gui/controllers/remote_branches_controller.go +++ b/pkg/gui/controllers/remote_branches_controller.go @@ -49,7 +49,7 @@ func (self *RemoteBranchesController) GetKeybindings(opts types.KeybindingsOpts) Description: self.c.Tr.NewBranch, }, { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Keys: opts.GetKeys(opts.Config.Universal.NewWorktree), Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForRemoteBranch), Description: self.c.Tr.NewWorktree, OpensMenu: true, diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index 3f0bd9be2..06e6991c6 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -67,7 +67,7 @@ func (self *StashController) GetKeybindings(opts types.KeybindingsOpts) []*types Tooltip: self.c.Tr.NewBranchFromStashTooltip, }, { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Keys: opts.GetKeys(opts.Config.Universal.NewWorktree), Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForStash), Description: self.c.Tr.NewWorktree, OpensMenu: true, diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index fd61e239d..879a73628 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -54,7 +54,7 @@ func (self *TagsController) GetKeybindings(opts types.KeybindingsOpts) []*types. DisplayOnScreen: true, }, { - Keys: opts.GetKeys(opts.Config.Worktrees.ViewWorktreeOptions), + Keys: opts.GetKeys(opts.Config.Universal.NewWorktree), Handler: self.withItem(self.c.Helpers().Worktree.NewWorktreeMenuForTag), Description: self.c.Tr.NewWorktree, OpensMenu: true, diff --git a/pkg/integration/tests/demo/worktree_create_from_branches.go b/pkg/integration/tests/demo/worktree_create_from_branches.go index 817cb704b..64e0761cc 100644 --- a/pkg/integration/tests/demo/worktree_create_from_branches.go +++ b/pkg/integration/tests/demo/worktree_create_from_branches.go @@ -34,7 +34,7 @@ var WorktreeCreateFromBranches = NewIntegrationTest(NewIntegrationTestArgs{ Focus(). NavigateToLine(Contains("master")). Wait(500). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.Wait(500) diff --git a/pkg/integration/tests/worktree/add_for_existing_branch.go b/pkg/integration/tests/worktree/add_for_existing_branch.go index fb238bcda..7fbbc3fc8 100644 --- a/pkg/integration/tests/worktree/add_for_existing_branch.go +++ b/pkg/integration/tests/worktree/add_for_existing_branch.go @@ -26,7 +26,7 @@ var AddForExistingBranch = NewIntegrationTest(NewIntegrationTestArgs{ ). // the current branch is checked out by this worktree, so "Worktree // for 'mybranch'" is disabled - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup(). Menu(). @@ -41,7 +41,7 @@ var AddForExistingBranch = NewIntegrationTest(NewIntegrationTestArgs{ }). // otherbranch is not checked out anywhere, so we can make a worktree for it NavigateToLine(Contains("otherbranch")). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_branch.go b/pkg/integration/tests/worktree/add_from_branch.go index 87898c794..46dbc09f5 100644 --- a/pkg/integration/tests/worktree/add_from_branch.go +++ b/pkg/integration/tests/worktree/add_from_branch.go @@ -21,7 +21,7 @@ var AddFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("mybranch"), ). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_branch_detached.go b/pkg/integration/tests/worktree/add_from_branch_detached.go index 6b74baff6..f17a50fef 100644 --- a/pkg/integration/tests/worktree/add_from_branch_detached.go +++ b/pkg/integration/tests/worktree/add_from_branch_detached.go @@ -21,7 +21,7 @@ var AddFromBranchDetached = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("mybranch"), ). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_commit.go b/pkg/integration/tests/worktree/add_from_commit.go index 484370ae3..21f26e4a2 100644 --- a/pkg/integration/tests/worktree/add_from_commit.go +++ b/pkg/integration/tests/worktree/add_from_commit.go @@ -24,7 +24,7 @@ var AddFromCommit = NewIntegrationTest(NewIntegrationTestArgs{ Contains("initial commit"), ). NavigateToLine(Contains("initial commit")). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_remote_branch.go b/pkg/integration/tests/worktree/add_from_remote_branch.go index 6dd4ea761..ac3d421fa 100644 --- a/pkg/integration/tests/worktree/add_from_remote_branch.go +++ b/pkg/integration/tests/worktree/add_from_remote_branch.go @@ -30,7 +30,7 @@ var AddFromRemoteBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().RemoteBranches(). IsFocused(). NavigateToLine(Contains("feature")). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_stash.go b/pkg/integration/tests/worktree/add_from_stash.go index 26a3b97c4..c2541183c 100644 --- a/pkg/integration/tests/worktree/add_from_stash.go +++ b/pkg/integration/tests/worktree/add_from_stash.go @@ -23,7 +23,7 @@ var AddFromStash = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("my stash").IsSelected(), ). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/add_from_tag.go b/pkg/integration/tests/worktree/add_from_tag.go index 22ef2bb07..bab7c03d8 100644 --- a/pkg/integration/tests/worktree/add_from_tag.go +++ b/pkg/integration/tests/worktree/add_from_tag.go @@ -22,7 +22,7 @@ var AddFromTag = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("v1.0").IsSelected(), ). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/pkg/integration/tests/worktree/location_candidates.go b/pkg/integration/tests/worktree/location_candidates.go index 2160c6109..5fd835626 100644 --- a/pkg/integration/tests/worktree/location_candidates.go +++ b/pkg/integration/tests/worktree/location_candidates.go @@ -24,7 +24,7 @@ var LocationCandidates = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Branches(). Focus(). NavigateToLine(Contains("mybranch")). - Press(keys.Worktrees.ViewWorktreeOptions). + Press(keys.Universal.NewWorktree). Tap(func() { t.ExpectPopup().Menu(). Title(Equals("New worktree")). diff --git a/schema-master/config.json b/schema-master/config.json index 9963aae61..5a0af4eb4 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -1658,9 +1658,6 @@ "branches": { "$ref": "#/$defs/KeybindingBranchesConfig" }, - "worktrees": { - "$ref": "#/$defs/KeybindingWorktreesConfig" - }, "commits": { "$ref": "#/$defs/KeybindingCommitsConfig" }, @@ -2881,6 +2878,20 @@ ], "default": "n" }, + "newWorktree": { + "oneOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "default": "w" + }, "edit": { "oneOf": [ { @@ -3407,26 +3418,6 @@ "additionalProperties": false, "type": "object" }, - "KeybindingWorktreesConfig": { - "properties": { - "viewWorktreeOptions": { - "oneOf": [ - { - "type": "string" - }, - { - "items": { - "type": "string" - }, - "type": "array" - } - ], - "default": "w" - } - }, - "additionalProperties": false, - "type": "object" - }, "LogConfig": { "properties": { "order": { From 7a67cea68760c21d680ae528a2ebb72249dca1b8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 13:35:11 +0200 Subject: [PATCH 026/218] Expand a leading ~ in worktree paths to the home directory Lazygit runs git directly rather than through a shell, so a literal "~" reaches `git worktree add` unexpanded and git creates a directory named "~" instead of using the home directory. Expand the tilde ourselves, both for paths typed into the "Other" location prompt and for the worktree.defaultPath config value. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs-master/Config.md | 1 + pkg/config/user_config.go | 1 + .../controllers/helpers/worktree_helper.go | 6 ++- pkg/integration/tests/test_list.go | 1 + .../tests/worktree/default_path_tilde.go | 51 +++++++++++++++++++ pkg/utils/utils.go | 24 +++++++++ pkg/utils/utils_test.go | 27 ++++++++++ schema-master/config.json | 2 +- 8 files changed, 110 insertions(+), 3 deletions(-) create mode 100644 pkg/integration/tests/worktree/default_path_tilde.go diff --git a/docs-master/Config.md b/docs-master/Config.md index bf0f5c2c6..152044be6 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -533,6 +533,7 @@ worktree: # location alongside the parent directories of any worktrees you already have. # A relative path is resolved against the repository's root directory, so # "../worktrees" sits beside the repo and ".worktrees" sits inside it. + # A leading "~" is expanded to your home directory, so "~/worktrees" works. defaultPath: "" # Periodic update checks diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index f83e26ea3..8314701ba 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -427,6 +427,7 @@ type CommitPrefixConfig struct { type WorktreeConfig struct { // Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have. // A relative path is resolved against the repository's root directory, so "../worktrees" sits beside the repo and ".worktrees" sits inside it. + // A leading "~" is expanded to your home directory, so "~/worktrees" works. DefaultPath string `yaml:"defaultPath"` } diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 2bc877444..7a32d898c 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -378,7 +378,7 @@ func (self *WorktreeHelper) promptForWorktreeLocation(dirName string, prompt str parentDirs := worktreeParentDirCandidates( self.c.Git().RepoPaths.RepoPath(), linkedWorktreePaths, - self.c.UserConfig().Worktree.DefaultPath, + utils.ExpandTilde(self.c.UserConfig().Worktree.DefaultPath), ) targets := lo.Map(parentDirs, func(parentDir string, _ int) string { @@ -398,7 +398,9 @@ func (self *WorktreeHelper) promptForWorktreeLocation(dirName string, prompt str self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.NewWorktreePath, InitialContent: targets[0], - HandleConfirm: onConfirm, + HandleConfirm: func(response string) error { + return onConfirm(utils.ExpandTilde(response)) + }, }) return nil }, diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 5aa8a21ee..136cd579b 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -508,6 +508,7 @@ var tests = []*components.IntegrationTest{ worktree.BareRepoWorktreeConfig, worktree.Crud, worktree.CustomCommand, + worktree.DefaultPathTilde, worktree.DetachWorktreeFromBranch, worktree.DotfileBareRepo, worktree.DoubleNestedLinkedSubmodule, diff --git a/pkg/integration/tests/worktree/default_path_tilde.go b/pkg/integration/tests/worktree/default_path_tilde.go new file mode 100644 index 000000000..57486f1a8 --- /dev/null +++ b/pkg/integration/tests/worktree/default_path_tilde.go @@ -0,0 +1,51 @@ +package worktree + +import ( + "os" + "path/filepath" + + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var DefaultPathTilde = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "A leading ~ in the worktree.defaultPath config is expanded to the home directory", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) { + config.GetUserConfig().Worktree.DefaultPath = "~/my-worktrees" + }, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Branches(). + Focus(). + NavigateToLine(Contains("mybranch")). + Press(keys.Universal.NewWorktree). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("New worktree")). + Select(Contains("New branch and worktree from 'mybranch'")). + Confirm() + + t.ExpectPopup().Prompt(). + Title(Equals("New branch and worktree name")). + Type("newbranch"). + Confirm() + + // The default path's "~" is expanded to an absolute home-directory + // path; without expansion it would stay a literal "~" resolved + // against the repo, so the candidate would still contain a "~". + home, _ := os.UserHomeDir() + t.ExpectPopup().Menu(). + Title(Equals("Worktree location")). + ContainsLines( + Contains(filepath.Join(home, "my-worktrees", "newbranch")).DoesNotContain("~"), + ). + Cancel() + }) + }, +}) diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 40411d520..0494bb035 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "os" + "path/filepath" "regexp" "runtime" "strconv" @@ -96,3 +97,26 @@ func FilePath(skip int) string { _, path, _, _ := runtime.Caller(skip) return path } + +// ExpandTilde expands a leading "~" that refers to the current user's home +// directory: "~" and "~/foo" become e.g. "/home/user" and "/home/user/foo". A +// tilde anywhere other than the start, or one immediately followed by a +// username ("~other/foo"), is left untouched, as is the path if the home +// directory can't be determined. We expand it ourselves because lazygit runs +// git directly, with no shell to do it for us. +func ExpandTilde(path string) string { + if path != "~" && !strings.HasPrefix(path, "~/") && + !(runtime.GOOS == "windows" && strings.HasPrefix(path, `~\`)) { + return path + } + + home, err := os.UserHomeDir() + if err != nil { + return path + } + + if path == "~" { + return home + } + return filepath.Join(home, path[2:]) +} diff --git a/pkg/utils/utils_test.go b/pkg/utils/utils_test.go index 41b40cd9f..8304e7ba4 100644 --- a/pkg/utils/utils_test.go +++ b/pkg/utils/utils_test.go @@ -1,6 +1,8 @@ package utils import ( + "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -98,3 +100,28 @@ func TestModuloWithWrap(t *testing.T) { } } } + +func TestExpandTilde(t *testing.T) { + home, err := os.UserHomeDir() + assert.NoError(t, err) + + scenarios := []struct { + name string + path string + expected string + }{ + {"bare tilde", "~", home}, + {"tilde with subpath", "~/worktrees", filepath.Join(home, "worktrees")}, + {"absolute path is untouched", "/absolute/path", "/absolute/path"}, + {"relative path is untouched", "relative/path", "relative/path"}, + {"tilde not at the start is untouched", "/foo/~/bar", "/foo/~/bar"}, + {"tilde followed by a username is untouched", "~other/worktrees", "~other/worktrees"}, + {"empty string is untouched", "", ""}, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + assert.Equal(t, s.expected, ExpandTilde(s.path)) + }) + } +} diff --git a/schema-master/config.json b/schema-master/config.json index 5a0af4eb4..0dd1d5d20 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -3899,7 +3899,7 @@ "properties": { "defaultPath": { "type": "string", - "description": "Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have.\nA relative path is resolved against the repository's root directory, so \"../worktrees\" sits beside the repo and \".worktrees\" sits inside it." + "description": "Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have.\nA relative path is resolved against the repository's root directory, so \"../worktrees\" sits beside the repo and \".worktrees\" sits inside it.\nA leading \"~\" is expanded to your home directory, so \"~/worktrees\" works." } }, "additionalProperties": false, From 3f6a21f7f8c5b1cd65660ac7fbb897724ff23c07 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 1 Jul 2026 10:44:29 +0200 Subject: [PATCH 027/218] AGENTS.md additions --- AGENTS.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 58e0a38f3..46ad3e506 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -279,6 +279,29 @@ languages), and the map form extends cleanly when a string later needs more than one placeholder. This holds for every user-facing string, including short ones like disabled-action reasons and toasts. +## Only edit the English translations + +`pkg/i18n/english.go` is the one translation file you edit; add, change, and +remove strings there. The other languages under `pkg/i18n/translations/` are +maintained by Crowdin and synced automatically — never edit them by hand, not +even to add a key you just introduced or to delete one you just removed. A +removed English string simply leaves an orphan key in those files, which +Crowdin cleans up on its own; an unknown key in a translation file is ignored +at load time, so it does no harm in the meantime. + +## Try to keep new english.go strings within the existing column alignment + +`gofumpt` aligns the `TranslationSet` struct fields and the `EnglishTranslationSet` +literal into columns, so a new field whose name is longer than the widest one in +its alignment block re-indents every line in that block. When there are several +feature branches in flight that all add strings, that reformatting churn turns +english.go into a rebase-conflict magnet. So when it's cheap to do so, make an +effort to keep a new field name within the current widest name in the block +(measure it; it's around 40 characters today), shortening the Go field name to +fit. This is a soft preference, not a rule: the usual "best name wins" still +applies, so don't mangle a name past the point of readability just to save a +column. Applies only to `pkg/i18n/english.go`. + ## Code comments are for future readers, not development history Comments in source code explain *why this code is shaped the way it is*. They From d6016d628651f13ec1bee215c6017a057a645b66 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 18:52:56 +0200 Subject: [PATCH 028/218] Extract reusable branch-deletion helpers Pull the merged-check-and-force-warning step and the actual git deletion out of ConfirmLocalDelete and ConfirmLocalAndRemoteDelete into helpers, so that the upcoming worktree-aware delete flows can reuse them instead of duplicating the logic. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/branches_helper.go | 106 +++++++++--------- 1 file changed, 56 insertions(+), 50 deletions(-) diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index ccc9d33ac..3e6c50b58 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -35,17 +35,9 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error return self.promptWorktreeBranchDelete(branches[0]) } - allBranchesMerged, err := self.allBranchesMerged(branches) - if err != nil { - return err - } - - doDelete := func() error { + return self.confirmForceIfUnmerged(branches, func() error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(_ gocui.Task) error { - self.c.LogAction(self.c.Tr.Actions.DeleteLocalBranch) - self.logBranchHashes(branches) - branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.Name }) - if err := self.c.Git().Branch.LocalDelete(branchNames, true); err != nil { + if err := self.doDeleteLocalBranches(branches); err != nil { return err } @@ -53,34 +45,7 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return nil }) - } - - if allBranchesMerged { - return doDelete() - } - - title := self.c.Tr.ForceDeleteBranchTitle - var message string - if len(branches) == 1 { - message = utils.ResolvePlaceholderString( - self.c.Tr.ForceDeleteBranchMessage, - map[string]string{ - "selectedBranchName": branches[0].Name, - }, - ) - } else { - message = self.c.Tr.ForceDeleteBranchesMessage - } - - self.c.Confirm(types.ConfirmOpts{ - Title: title, - Prompt: message, - HandleConfirm: func() error { - return doDelete() - }, }) - - return nil } func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteBranch, resetRemoteBranchesSelection bool) error { @@ -169,19 +134,7 @@ func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branc Prompt: prompt, HandleConfirm: func() error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(task gocui.Task) error { - // Delete the remote branches first so that we keep the local ones - // in case of failure - remoteBranches := lo.Map(branches, func(branch *models.Branch, _ int) *models.RemoteBranch { - return &models.RemoteBranch{Name: branch.UpstreamBranch, RemoteName: branch.UpstreamRemote} - }) - if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { - return err - } - - self.c.LogAction(self.c.Tr.Actions.DeleteLocalBranch) - self.logBranchHashes(branches) - branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.Name }) - if err := self.c.Git().Branch.LocalDelete(branchNames, true); err != nil { + if err := self.doDeleteLocalAndRemoteBranches(task, branches); err != nil { return err } @@ -244,6 +197,59 @@ func (self *BranchesHelper) promptWorktreeBranchDelete(selectedBranch *models.Br }) } +// confirmForceIfUnmerged runs onConfirm directly if all the branches are fully +// merged, and otherwise shows the force-delete warning first and runs onConfirm +// when the user confirms it. +func (self *BranchesHelper) confirmForceIfUnmerged(branches []*models.Branch, onConfirm func() error) error { + allBranchesMerged, err := self.allBranchesMerged(branches) + if err != nil { + return err + } + if allBranchesMerged { + return onConfirm() + } + + var message string + if len(branches) == 1 { + message = utils.ResolvePlaceholderString( + self.c.Tr.ForceDeleteBranchMessage, + map[string]string{ + "selectedBranchName": branches[0].Name, + }, + ) + } else { + message = self.c.Tr.ForceDeleteBranchesMessage + } + + self.c.Confirm(types.ConfirmOpts{ + Title: self.c.Tr.ForceDeleteBranchTitle, + Prompt: message, + HandleConfirm: onConfirm, + }) + + return nil +} + +func (self *BranchesHelper) doDeleteLocalBranches(branches []*models.Branch) error { + self.c.LogAction(self.c.Tr.Actions.DeleteLocalBranch) + self.logBranchHashes(branches) + branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.Name }) + return self.c.Git().Branch.LocalDelete(branchNames, true) +} + +func (self *BranchesHelper) doDeleteLocalAndRemoteBranches(task gocui.Task, branches []*models.Branch) error { + // Delete the remote branches first so that we keep the local ones + // in case of failure + remoteBranches := lo.Map(branches, func(branch *models.Branch, _ int) *models.RemoteBranch { + return &models.RemoteBranch{Name: branch.UpstreamBranch, RemoteName: branch.UpstreamRemote} + }) + if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { + return err + } + + return self.doDeleteLocalBranches(branches) +} + func (self *BranchesHelper) allBranchesMerged(branches []*models.Branch) (bool, error) { allBranchesMerged := true for _, branch := range branches { From 9a8244110ffaa538878e92a354df171912dd590a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 18:57:21 +0200 Subject: [PATCH 029/218] Let worktree removal/detach chain follow-up work Split the actual worktree removal out of the confirmation in Remove into a non-confirming helper, and give both Remove and Detach an optional `then` continuation that runs after a successful removal in place of the default refresh. Upcoming flows need to delete the worktree's branch once the worktree is out of the way; threading a continuation through (rather than the caller firing branch deletion independently) keeps it ordered after the git command that actually frees the branch. No behavior change yet. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/branches_helper.go | 4 +- .../controllers/helpers/worktree_helper.go | 84 ++++++++++++------- pkg/gui/controllers/worktrees_controller.go | 2 +- 3 files changed, 58 insertions(+), 32 deletions(-) diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 3e6c50b58..18f19aa97 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -184,13 +184,13 @@ func (self *BranchesHelper) promptWorktreeBranchDelete(selectedBranch *models.Br Label: self.c.Tr.DetachWorktree, Tooltip: self.c.Tr.DetachWorktreeTooltip, OnPress: func() error { - return self.worktreeHelper.Detach(worktree) + return self.worktreeHelper.Detach(worktree, nil) }, }, { Label: self.c.Tr.RemoveWorktree, OnPress: func() error { - return self.worktreeHelper.Remove(worktree, false) + return self.worktreeHelper.Remove(worktree) }, }, }, diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 7a32d898c..84973d705 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -119,56 +119,82 @@ func (self *WorktreeHelper) Switch(worktree *models.Worktree, contextKey types.C return self.reposHelper.DispatchSwitchTo(worktree.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) } -func (self *WorktreeHelper) Remove(worktree *models.Worktree, force bool) error { - title := self.c.Tr.RemoveWorktreeTitle - var templateStr string - if force { - templateStr = self.c.Tr.ForceRemoveWorktreePrompt - } else { - templateStr = self.c.Tr.RemoveWorktreePrompt - } +func (self *WorktreeHelper) Remove(worktree *models.Worktree) error { message := utils.ResolvePlaceholderString( - templateStr, + self.c.Tr.RemoveWorktreePrompt, map[string]string{ "worktreeName": worktree.Name, }, ) self.c.Confirm(types.ConfirmOpts{ - Title: title, + Title: self.c.Tr.RemoveWorktreeTitle, Prompt: message, HandleConfirm: func() error { - return self.c.WithWaitingStatus(self.c.Tr.RemovingWorktree, func(gocui.Task) error { - self.c.LogAction(self.c.Tr.RemoveWorktree) - if err := self.c.Git().Worktree.Delete(worktree.Path, force); err != nil { - errMessage := err.Error() - if !strings.Contains(errMessage, "--force") && - !strings.Contains(errMessage, "fatal: working trees containing submodules cannot be moved or removed") { - return err - } - - if !force { - return self.Remove(worktree, true) - } - return err - } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) - return nil - }) + return self.remove(worktree, false, nil) }, }) return nil } -func (self *WorktreeHelper) Detach(worktree *models.Worktree) error { - return self.c.WithWaitingStatus(self.c.Tr.DetachingWorktree, func(gocui.Task) error { +// remove deletes the worktree without confirming first; callers must have done +// so (or shown a menu) already. If git refuses because the worktree is dirty or +// contains submodules, we ask for confirmation and retry with --force. When then +// is non-nil it runs in place of the default refresh after a successful removal, +// letting callers chain further work such as deleting the worktree's branch. +func (self *WorktreeHelper) remove(worktree *models.Worktree, force bool, then func(gocui.Task) error) error { + return self.c.WithWaitingStatus(self.c.Tr.RemovingWorktree, func(task gocui.Task) error { + self.c.LogAction(self.c.Tr.RemoveWorktree) + if err := self.c.Git().Worktree.Delete(worktree.Path, force); err != nil { + errMessage := err.Error() + if !strings.Contains(errMessage, "--force") && + !strings.Contains(errMessage, "fatal: working trees containing submodules cannot be moved or removed") { + return err + } + + if force { + return err + } + + message := utils.ResolvePlaceholderString( + self.c.Tr.ForceRemoveWorktreePrompt, + map[string]string{ + "worktreeName": worktree.Name, + }, + ) + self.c.Confirm(types.ConfirmOpts{ + Title: self.c.Tr.RemoveWorktreeTitle, + Prompt: message, + HandleConfirm: func() error { + return self.remove(worktree, true, then) + }, + }) + return nil + } + + if then != nil { + return then(task) + } + + self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) + return nil + }) +} + +func (self *WorktreeHelper) Detach(worktree *models.Worktree, then func(gocui.Task) error) error { + return self.c.WithWaitingStatus(self.c.Tr.DetachingWorktree, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.RemovingWorktree) err := self.c.Git().Worktree.Detach(worktree.Path) if err != nil { return err } + + if then != nil { + return then(task) + } + self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) diff --git a/pkg/gui/controllers/worktrees_controller.go b/pkg/gui/controllers/worktrees_controller.go index 5128ad716..4f87362d6 100644 --- a/pkg/gui/controllers/worktrees_controller.go +++ b/pkg/gui/controllers/worktrees_controller.go @@ -130,7 +130,7 @@ func (self *WorktreesController) remove(worktree *models.Worktree) error { return errors.New(self.c.Tr.CantDeleteCurrentWorktree) } - return self.c.Helpers().Worktree.Remove(worktree, false) + return self.c.Helpers().Worktree.Remove(worktree) } func (self *WorktreesController) GetOnDoubleClick() func() error { From 4f078f5463d78cb5ffd6825a22602f45a35263ca Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 30 Jun 2026 19:02:32 +0200 Subject: [PATCH 030/218] Delete the branch when deleting it via its worktree When you delete a local branch that's checked out in another worktree, the menu offered to remove or detach the worktree but then stopped there, leaving the branch you asked to delete still around. Now both actions delete the branch afterwards, and the labels say so ("Remove worktree and delete branch" / "Detach worktree and delete branch") to avoid surprises. Also drop the "Switch to worktree" item: switching abandons the delete the user asked for, and it's already reachable by checking out the branch or via the worktrees panel. And drop the now-redundant "remove worktree?" confirmation: the explicit menu pick is the confirmation (the dirty-worktree force prompt and the unmerged-branch warning still appear when relevant). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/branches_helper.go | 61 ++++++++++++++----- pkg/i18n/english.go | 4 ++ .../worktree/detach_worktree_from_branch.go | 8 +-- .../worktree/remove_worktree_from_branch.go | 14 ++--- 4 files changed, 59 insertions(+), 28 deletions(-) diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 18f19aa97..73db775fe 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -8,7 +8,6 @@ import ( "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gocui" - "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" @@ -32,7 +31,12 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error return errors.New(self.c.Tr.SomeBranchesCheckedOutByWorktreeError) } } else if self.checkedOutByOtherWorktree(branches[0]) { - return self.promptWorktreeBranchDelete(branches[0]) + return self.promptWorktreeBranchDelete( + branches[0], + self.c.Tr.RemoveWorktreeAndDeleteBranch, + self.c.Tr.DetachWorktreeAndDeleteBranch, + self.deleteLocalBranchesContinuation(branches), + ) } return self.confirmForceIfUnmerged(branches, func() error { @@ -160,8 +164,18 @@ func (self *BranchesHelper) worktreeForBranch(branch *models.Branch) (*models.Wo return git_commands.WorktreeForBranch(branch, self.c.Model().Worktrees) } -func (self *BranchesHelper) promptWorktreeBranchDelete(selectedBranch *models.Branch) error { - worktree, ok := self.worktreeForBranch(selectedBranch) +// promptWorktreeBranchDelete handles deleting a branch that's checked out by +// another worktree: the worktree has to be removed or detached first to free the +// branch, so we offer both as menu items. Either way the branch is deleted +// afterwards (that's what the user asked for), via deleteBranches, which knows +// whether to delete just the local branch or the remote one too. +func (self *BranchesHelper) promptWorktreeBranchDelete( + branch *models.Branch, + removeLabel string, + detachLabel string, + deleteBranches func(gocui.Task) error, +) error { + worktree, ok := self.worktreeForBranch(branch) if !ok { self.c.Log.Error("promptWorktreeBranchDelete out of sync with list of worktrees") return nil @@ -169,28 +183,28 @@ func (self *BranchesHelper) promptWorktreeBranchDelete(selectedBranch *models.Br title := utils.ResolvePlaceholderString(self.c.Tr.BranchCheckedOutByWorktree, map[string]string{ "worktreeName": worktree.Name, - "branchName": selectedBranch.Name, + "branchName": branch.Name, }) return self.c.Menu(types.CreateMenuOptions{ Title: title, Items: []*types.MenuItem{ { - Label: self.c.Tr.SwitchToWorktree, + Label: removeLabel, + Keys: menuKey('r'), OnPress: func() error { - return self.worktreeHelper.Switch(worktree, context.LOCAL_BRANCHES_CONTEXT_KEY) + return self.confirmForceIfUnmerged([]*models.Branch{branch}, func() error { + return self.worktreeHelper.remove(worktree, false, deleteBranches) + }) }, }, { - Label: self.c.Tr.DetachWorktree, + Label: detachLabel, + Keys: menuKey('d'), Tooltip: self.c.Tr.DetachWorktreeTooltip, OnPress: func() error { - return self.worktreeHelper.Detach(worktree, nil) - }, - }, - { - Label: self.c.Tr.RemoveWorktree, - OnPress: func() error { - return self.worktreeHelper.Remove(worktree) + return self.confirmForceIfUnmerged([]*models.Branch{branch}, func() error { + return self.worktreeHelper.Detach(worktree, deleteBranches) + }) }, }, }, @@ -250,6 +264,23 @@ func (self *BranchesHelper) doDeleteLocalAndRemoteBranches(task gocui.Task, bran return self.doDeleteLocalBranches(branches) } +// deleteLocalBranchesContinuation returns a worktree-removal continuation that +// deletes the local branches and refreshes once the worktree is out of the way. +func (self *BranchesHelper) deleteLocalBranchesContinuation(branches []*models.Branch) func(gocui.Task) error { + return func(gocui.Task) error { + if err := self.doDeleteLocalBranches(branches); err != nil { + return err + } + + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.Refresh(types.RefreshOptions{ + Mode: types.ASYNC, + Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}, + }) + return nil + } +} + func (self *BranchesHelper) allBranchesMerged(branches []*models.Branch) (bool, error) { allBranchesMerged := true for _, branch := range branches { diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 822e47c10..213210fcd 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -874,7 +874,9 @@ type TranslationSet struct { Switching string RemoveWorktree string RemoveWorktreeTitle string + RemoveWorktreeAndDeleteBranch string DetachWorktree string + DetachWorktreeAndDeleteBranch string DetachingWorktree string WorktreesTitle string WorktreeTitle string @@ -2018,10 +2020,12 @@ func EnglishTranslationSet() *TranslationSet { Switching: "Switching", RemoveWorktree: "Remove worktree", RemoveWorktreeTitle: "Remove worktree", + RemoveWorktreeAndDeleteBranch: "Remove worktree and delete branch", RemoveWorktreePrompt: "Are you sure you want to remove worktree '{{.worktreeName}}'?", ForceRemoveWorktreePrompt: "'{{.worktreeName}}' contains modified or untracked files, or submodules (or all of these). Are you sure you want to remove it?", RemovingWorktree: "Deleting worktree", DetachWorktree: "Detach worktree", + DetachWorktreeAndDeleteBranch: "Detach worktree and delete branch", DetachingWorktree: "Detaching worktree", AddingWorktree: "Adding worktree", CantDeleteCurrentWorktree: "You cannot remove the current worktree!", diff --git a/pkg/integration/tests/worktree/detach_worktree_from_branch.go b/pkg/integration/tests/worktree/detach_worktree_from_branch.go index acd40e6ad..b36b89349 100644 --- a/pkg/integration/tests/worktree/detach_worktree_from_branch.go +++ b/pkg/integration/tests/worktree/detach_worktree_from_branch.go @@ -6,7 +6,7 @@ import ( ) var DetachWorktreeFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "Detach a worktree from the branches view", + Description: "Delete a branch that's checked out in another worktree by detaching that worktree", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(config *config.AppConfig) {}, @@ -37,12 +37,12 @@ var DetachWorktreeFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ Tap(func() { t.ExpectPopup().Menu(). Title(Equals("Branch newbranch is checked out by worktree linked-worktree")). - Select(Equals("Detach worktree")). + Select(Contains("Detach worktree and delete branch")). Confirm() }). + // The branch is gone; the worktree stays around (now detached) Lines( - Contains("mybranch"), - Contains("newbranch").DoesNotContain("(worktree)").IsSelected(), + Contains("mybranch").IsSelected(), ) t.Views().Worktrees(). diff --git a/pkg/integration/tests/worktree/remove_worktree_from_branch.go b/pkg/integration/tests/worktree/remove_worktree_from_branch.go index 1aa9645f3..7823af54c 100644 --- a/pkg/integration/tests/worktree/remove_worktree_from_branch.go +++ b/pkg/integration/tests/worktree/remove_worktree_from_branch.go @@ -6,7 +6,7 @@ import ( ) var RemoveWorktreeFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "Remove a worktree from the branches view", + Description: "Delete a branch that's checked out in another worktree by removing that worktree", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(config *config.AppConfig) {}, @@ -38,22 +38,18 @@ var RemoveWorktreeFromBranch = NewIntegrationTest(NewIntegrationTestArgs{ Tap(func() { t.ExpectPopup().Menu(). Title(Equals("Branch newbranch is checked out by worktree linked-worktree")). - Select(Equals("Remove worktree")). - Confirm() - - t.ExpectPopup().Confirmation(). - Title(Equals("Remove worktree")). - Content(Equals("Are you sure you want to remove worktree 'linked-worktree'?")). + Select(Contains("Remove worktree and delete branch")). Confirm() + // The worktree is dirty, so we get asked to force-remove it t.ExpectPopup().Confirmation(). Title(Equals("Remove worktree")). Content(Equals("'linked-worktree' contains modified or untracked files, or submodules (or all of these). Are you sure you want to remove it?")). Confirm() }). + // The branch is gone, not just unlinked from its worktree Lines( - Contains("mybranch"), - Contains("newbranch").DoesNotContain("(worktree)").IsSelected(), + Contains("mybranch").IsSelected(), ) t.Views().Worktrees(). From 22914da8e5c1c2dedb82d343d8c9915cda249e48 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 1 Jul 2026 10:42:13 +0200 Subject: [PATCH 031/218] Allow deleting local+remote of a worktree-checked-out branch at once Picking "Delete local and remote branch" for a single branch that's checked out in another worktree used to fail with "Some of the selected branches are checked out by other worktrees. Select them one by one to delete them." That message only makes sense for a multi-selection; for a single branch there's no reason we can't remove the worktree and delete both the local and remote branch in one go. Route that case through the same worktree menu as the local-only delete, with labels that spell out that the remote goes too. The multi-select error stays for actual multi-selections. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/branches_helper.go | 31 +++++++- pkg/i18n/english.go | 4 ++ pkg/integration/tests/test_list.go | 2 + ...tree_and_delete_local_and_remote_branch.go | 71 +++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 pkg/integration/tests/worktree/remove_worktree_and_delete_local_and_remote_branch.go diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 73db775fe..7c873f8f3 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -97,8 +97,17 @@ func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteB } func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branch) error { - if lo.SomeBy(branches, func(branch *models.Branch) bool { return self.checkedOutByOtherWorktree(branch) }) { - return errors.New(self.c.Tr.SomeBranchesCheckedOutByWorktreeError) + if len(branches) > 1 { + if lo.SomeBy(branches, func(branch *models.Branch) bool { return self.checkedOutByOtherWorktree(branch) }) { + return errors.New(self.c.Tr.SomeBranchesCheckedOutByWorktreeError) + } + } else if self.checkedOutByOtherWorktree(branches[0]) { + return self.promptWorktreeBranchDelete( + branches[0], + self.c.Tr.RemoveWorktreeAndDeleteBothBranches, + self.c.Tr.DetachWorktreeAndDeleteBothBranches, + self.deleteLocalAndRemoteBranchesContinuation(branches), + ) } allBranchesMerged, err := self.allBranchesMerged(branches) @@ -281,6 +290,24 @@ func (self *BranchesHelper) deleteLocalBranchesContinuation(branches []*models.B } } +// deleteLocalAndRemoteBranchesContinuation returns a worktree-removal +// continuation that deletes the local and remote branches and refreshes once the +// worktree is out of the way. +func (self *BranchesHelper) deleteLocalAndRemoteBranchesContinuation(branches []*models.Branch) func(gocui.Task) error { + return func(task gocui.Task) error { + if err := self.doDeleteLocalAndRemoteBranches(task, branches); err != nil { + return err + } + + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.Refresh(types.RefreshOptions{ + Mode: types.ASYNC, + Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.REMOTES, types.FILES}, + }) + return nil + } +} + func (self *BranchesHelper) allBranchesMerged(branches []*models.Branch) (bool, error) { allBranchesMerged := true for _, branch := range branches { diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 213210fcd..91f514796 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -875,8 +875,10 @@ type TranslationSet struct { RemoveWorktree string RemoveWorktreeTitle string RemoveWorktreeAndDeleteBranch string + RemoveWorktreeAndDeleteBothBranches string DetachWorktree string DetachWorktreeAndDeleteBranch string + DetachWorktreeAndDeleteBothBranches string DetachingWorktree string WorktreesTitle string WorktreeTitle string @@ -2021,11 +2023,13 @@ func EnglishTranslationSet() *TranslationSet { RemoveWorktree: "Remove worktree", RemoveWorktreeTitle: "Remove worktree", RemoveWorktreeAndDeleteBranch: "Remove worktree and delete branch", + RemoveWorktreeAndDeleteBothBranches: "Remove worktree and delete local and remote branch", RemoveWorktreePrompt: "Are you sure you want to remove worktree '{{.worktreeName}}'?", ForceRemoveWorktreePrompt: "'{{.worktreeName}}' contains modified or untracked files, or submodules (or all of these). Are you sure you want to remove it?", RemovingWorktree: "Deleting worktree", DetachWorktree: "Detach worktree", DetachWorktreeAndDeleteBranch: "Detach worktree and delete branch", + DetachWorktreeAndDeleteBothBranches: "Detach worktree and delete local and remote branch", DetachingWorktree: "Detaching worktree", AddingWorktree: "Adding worktree", CantDeleteCurrentWorktree: "You cannot remove the current worktree!", diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 136cd579b..ed32775d4 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -520,6 +520,8 @@ var tests = []*components.IntegrationTest{ worktree.LocationCandidates, worktree.NewWorktreePicker, worktree.NewWorktreePickerRemote, + worktree.RemoveWorktreeAndBothBranches, + worktree.RemoveWorktreeAndDeleteLocalAndRemoteBranch, worktree.RemoveWorktreeFromBranch, worktree.ResetWindowTabs, worktree.SymlinkIntoRepoSubdir, diff --git a/pkg/integration/tests/worktree/remove_worktree_and_delete_local_and_remote_branch.go b/pkg/integration/tests/worktree/remove_worktree_and_delete_local_and_remote_branch.go new file mode 100644 index 000000000..09fae45eb --- /dev/null +++ b/pkg/integration/tests/worktree/remove_worktree_and_delete_local_and_remote_branch.go @@ -0,0 +1,71 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RemoveWorktreeAndDeleteLocalAndRemoteBranch = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Delete the local branch, the remote branch, and the worktree of a single branch checked out in another worktree, all at once", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CloneIntoRemote("origin") + shell.EmptyCommit("initial commit") + shell.NewBranch("mybranch") + shell.EmptyCommit("commit on mybranch") + shell.PushBranchAndSetUpstream("origin", "mybranch") + shell.EmptyCommit("commit not pushed to the remote") // so mybranch isn't fully merged + shell.Checkout("master") + shell.AddWorktreeCheckout("mybranch", "../linked-worktree") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Branches(). + Focus(). + Lines( + Contains("master").IsSelected(), + Contains("mybranch (worktree linked-worktree)"), + ). + NavigateToLine(Contains("mybranch")). + Press(keys.Universal.Remove). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("Delete branch 'mybranch'?")). + Select(Contains("Delete local and remote branch")). + Confirm() + }). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("Branch mybranch is checked out by worktree linked-worktree")). + Select(Contains("Remove worktree and delete local and remote branch")). + Confirm() + + // mybranch is not contained in master, so we get the force-delete warning + t.ExpectPopup().Confirmation(). + Title(Equals("Force delete branch")). + Content(Equals("'mybranch' is not fully merged. Are you sure you want to delete it?")). + Confirm() + }). + // The local branch is gone + Lines( + Contains("master").IsSelected(), + ) + + // The remote branch is gone too + t.Views().Remotes(). + Focus(). + Lines(Contains("origin")). + PressEnter() + + t.Views().RemoteBranches(). + IsEmpty() + + // And so is the worktree + t.Views().Worktrees(). + Focus(). + Lines( + Contains("(main worktree)").IsSelected(), + ) + }, +}) From 0aed44c7f33355a53fbb6cd1769c413e9e4b1490 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 1 Jul 2026 10:44:11 +0200 Subject: [PATCH 032/218] Offer to delete the branch when removing a worktree Pressing `d` on a worktree only ever removed the worktree, leaving its branch behind even though deleting it too is often what you want. Turn the confirmation into a menu: "Remove worktree", "Remove worktree and delete branch", and "Remove worktree and delete local and remote branch". The branch-deleting items come after the plain removal (they do more harm if picked by accident); both are greyed out for a detached-HEAD worktree, and the local-and-remote one is also greyed when the branch has no upstream. The plain menu pick is the confirmation, so the standalone "remove worktree?" prompt is gone (and its now-dead translation string with it); the dirty-worktree force prompt and the unmerged-branch warning still appear when relevant. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/branches_helper.go | 32 +++++++- .../controllers/helpers/worktree_helper.go | 30 ++------ pkg/gui/controllers/worktrees_controller.go | 49 ++++++++++++- pkg/i18n/english.go | 6 +- pkg/integration/tests/test_list.go | 1 + pkg/integration/tests/worktree/crud.go | 6 +- .../tests/worktree/force_remove_worktree.go | 6 +- .../force_remove_worktree_with_submodules.go | 6 +- .../remove_worktree_and_both_branches.go | 64 ++++++++++++++++ .../worktree/remove_worktree_and_branch.go | 73 +++++++++++++++++++ 10 files changed, 238 insertions(+), 35 deletions(-) create mode 100644 pkg/integration/tests/worktree/remove_worktree_and_both_branches.go create mode 100644 pkg/integration/tests/worktree/remove_worktree_and_branch.go diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 7c873f8f3..4283bd29a 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -202,7 +202,7 @@ func (self *BranchesHelper) promptWorktreeBranchDelete( Keys: menuKey('r'), OnPress: func() error { return self.confirmForceIfUnmerged([]*models.Branch{branch}, func() error { - return self.worktreeHelper.remove(worktree, false, deleteBranches) + return self.worktreeHelper.Remove(worktree, deleteBranches) }) }, }, @@ -220,6 +220,36 @@ func (self *BranchesHelper) promptWorktreeBranchDelete( }) } +// RemoveWorktreeAndDeleteBranch removes the worktree and deletes the local branch +// it has checked out, force-warning first if the branch isn't fully merged. It's +// the worktrees-panel counterpart to deleting a worktree-checked-out branch from +// the branches panel. +func (self *BranchesHelper) RemoveWorktreeAndDeleteBranch( + worktree *models.Worktree, branch *models.Branch, +) error { + branches := []*models.Branch{branch} + return self.removeWorktreeAndDelete(worktree, branches, + self.deleteLocalBranchesContinuation(branches)) +} + +// RemoveWorktreeAndDeleteBothBranches is like RemoveWorktreeAndDeleteBranch but +// also deletes the branch's upstream. +func (self *BranchesHelper) RemoveWorktreeAndDeleteBothBranches( + worktree *models.Worktree, branch *models.Branch, +) error { + branches := []*models.Branch{branch} + return self.removeWorktreeAndDelete(worktree, branches, + self.deleteLocalAndRemoteBranchesContinuation(branches)) +} + +func (self *BranchesHelper) removeWorktreeAndDelete( + worktree *models.Worktree, branches []*models.Branch, deleteBranches func(gocui.Task) error, +) error { + return self.confirmForceIfUnmerged(branches, func() error { + return self.worktreeHelper.Remove(worktree, deleteBranches) + }) +} + // confirmForceIfUnmerged runs onConfirm directly if all the branches are fully // merged, and otherwise shows the force-delete warning first and runs onConfirm // when the user confirms it. diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 84973d705..7cec9f873 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -119,30 +119,16 @@ func (self *WorktreeHelper) Switch(worktree *models.Worktree, contextKey types.C return self.reposHelper.DispatchSwitchTo(worktree.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) } -func (self *WorktreeHelper) Remove(worktree *models.Worktree) error { - message := utils.ResolvePlaceholderString( - self.c.Tr.RemoveWorktreePrompt, - map[string]string{ - "worktreeName": worktree.Name, - }, - ) - - self.c.Confirm(types.ConfirmOpts{ - Title: self.c.Tr.RemoveWorktreeTitle, - Prompt: message, - HandleConfirm: func() error { - return self.remove(worktree, false, nil) - }, - }) - - return nil +// Remove deletes the worktree without confirming first; callers are expected to +// have confirmed (or shown a menu) already. If git refuses because the worktree +// is dirty or contains submodules, we ask for confirmation and retry with +// --force. When then is non-nil it runs in place of the default refresh after a +// successful removal, letting callers chain further work such as deleting the +// worktree's branch. +func (self *WorktreeHelper) Remove(worktree *models.Worktree, then func(gocui.Task) error) error { + return self.remove(worktree, false, then) } -// remove deletes the worktree without confirming first; callers must have done -// so (or shown a menu) already. If git refuses because the worktree is dirty or -// contains submodules, we ask for confirmation and retry with --force. When then -// is non-nil it runs in place of the default refresh after a successful removal, -// letting callers chain further work such as deleting the worktree's branch. func (self *WorktreeHelper) remove(worktree *models.Worktree, force bool, then func(gocui.Task) error) error { return self.c.WithWaitingStatus(self.c.Tr.RemovingWorktree, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.RemoveWorktree) diff --git a/pkg/gui/controllers/worktrees_controller.go b/pkg/gui/controllers/worktrees_controller.go index 4f87362d6..02d20b3f2 100644 --- a/pkg/gui/controllers/worktrees_controller.go +++ b/pkg/gui/controllers/worktrees_controller.go @@ -11,6 +11,7 @@ import ( "github.com/jesseduffield/lazygit/pkg/gui/style" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/samber/lo" ) type WorktreesController struct { @@ -130,7 +131,53 @@ func (self *WorktreesController) remove(worktree *models.Worktree) error { return errors.New(self.c.Tr.CantDeleteCurrentWorktree) } - return self.c.Helpers().Worktree.Remove(worktree) + removeWorktreeItem := &types.MenuItem{ + Label: self.c.Tr.RemoveWorktree, + Keys: menuKey('w'), + OnPress: func() error { + return self.c.Helpers().Worktree.Remove(worktree, nil) + }, + } + + branch, branchFound := lo.Find(self.c.Model().Branches, func(branch *models.Branch) bool { + return branch.Name == worktree.Branch + }) + // A worktree with a detached HEAD has no branch to delete + detachedReason := &types.DisabledReason{Text: self.c.Tr.WorktreeNotCheckedOutOnBranch} + + removeWorktreeAndBranchItem := &types.MenuItem{ + Label: self.c.Tr.RemoveWorktreeAndDeleteBranch, + Keys: menuKey('b'), + OnPress: func() error { + return self.c.Helpers().BranchesHelper.RemoveWorktreeAndDeleteBranch(worktree, branch) + }, + } + if !branchFound { + removeWorktreeAndBranchItem.DisabledReason = detachedReason + } + + removeWorktreeAndBothBranchesItem := &types.MenuItem{ + Label: self.c.Tr.RemoveWorktreeAndDeleteBothBranches, + Keys: menuKey('r'), + OnPress: func() error { + return self.c.Helpers().BranchesHelper.RemoveWorktreeAndDeleteBothBranches(worktree, branch) + }, + } + if !branchFound { + removeWorktreeAndBothBranchesItem.DisabledReason = detachedReason + } else if !branch.IsTrackingRemote() || branch.UpstreamGone { + removeWorktreeAndBothBranchesItem.DisabledReason = &types.DisabledReason{ + Text: self.c.Tr.UpstreamNotSetError, + } + } + + return self.c.Menu(types.CreateMenuOptions{ + Title: utils.ResolvePlaceholderString( + self.c.Tr.RemoveWorktreeMenuTitle, + map[string]string{"worktreeName": worktree.Name}, + ), + Items: []*types.MenuItem{removeWorktreeItem, removeWorktreeAndBranchItem, removeWorktreeAndBothBranchesItem}, + }) } func (self *WorktreesController) GetOnDoubleClick() func() error { diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 91f514796..be3886fbe 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -874,15 +874,16 @@ type TranslationSet struct { Switching string RemoveWorktree string RemoveWorktreeTitle string + RemoveWorktreeMenuTitle string RemoveWorktreeAndDeleteBranch string RemoveWorktreeAndDeleteBothBranches string + WorktreeNotCheckedOutOnBranch string DetachWorktree string DetachWorktreeAndDeleteBranch string DetachWorktreeAndDeleteBothBranches string DetachingWorktree string WorktreesTitle string WorktreeTitle string - RemoveWorktreePrompt string ForceRemoveWorktreePrompt string RemovingWorktree string AddingWorktree string @@ -2022,9 +2023,10 @@ func EnglishTranslationSet() *TranslationSet { Switching: "Switching", RemoveWorktree: "Remove worktree", RemoveWorktreeTitle: "Remove worktree", + RemoveWorktreeMenuTitle: "Remove worktree '{{.worktreeName}}'?", RemoveWorktreeAndDeleteBranch: "Remove worktree and delete branch", RemoveWorktreeAndDeleteBothBranches: "Remove worktree and delete local and remote branch", - RemoveWorktreePrompt: "Are you sure you want to remove worktree '{{.worktreeName}}'?", + WorktreeNotCheckedOutOnBranch: "This worktree is not checked out on a branch", ForceRemoveWorktreePrompt: "'{{.worktreeName}}' contains modified or untracked files, or submodules (or all of these). Are you sure you want to remove it?", RemovingWorktree: "Deleting worktree", DetachWorktree: "Detach worktree", diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index ed32775d4..380aca2b6 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -521,6 +521,7 @@ var tests = []*components.IntegrationTest{ worktree.NewWorktreePicker, worktree.NewWorktreePickerRemote, worktree.RemoveWorktreeAndBothBranches, + worktree.RemoveWorktreeAndBranch, worktree.RemoveWorktreeAndDeleteLocalAndRemoteBranch, worktree.RemoveWorktreeFromBranch, worktree.ResetWindowTabs, diff --git a/pkg/integration/tests/worktree/crud.go b/pkg/integration/tests/worktree/crud.go index 6cda94141..9a35d6cf7 100644 --- a/pkg/integration/tests/worktree/crud.go +++ b/pkg/integration/tests/worktree/crud.go @@ -106,9 +106,9 @@ var Crud = NewIntegrationTest(NewIntegrationTestArgs{ NavigateToLine(Contains("linked-worktree")). Press(keys.Universal.Remove). Tap(func() { - t.ExpectPopup().Confirmation(). - Title(Equals("Remove worktree")). - Content(Contains("Are you sure you want to remove worktree 'linked-worktree'?")). + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'linked-worktree'?")). + Select(MatchesRegexp("Remove worktree$")). Confirm() }). Lines( diff --git a/pkg/integration/tests/worktree/force_remove_worktree.go b/pkg/integration/tests/worktree/force_remove_worktree.go index cde9e9da3..3fafa9755 100644 --- a/pkg/integration/tests/worktree/force_remove_worktree.go +++ b/pkg/integration/tests/worktree/force_remove_worktree.go @@ -29,9 +29,9 @@ var ForceRemoveWorktree = NewIntegrationTest(NewIntegrationTestArgs{ NavigateToLine(Contains("linked-worktree")). Press(keys.Universal.Remove). Tap(func() { - t.ExpectPopup().Confirmation(). - Title(Equals("Remove worktree")). - Content(Equals("Are you sure you want to remove worktree 'linked-worktree'?")). + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'linked-worktree'?")). + Select(MatchesRegexp("Remove worktree$")). Confirm() t.ExpectPopup().Confirmation(). diff --git a/pkg/integration/tests/worktree/force_remove_worktree_with_submodules.go b/pkg/integration/tests/worktree/force_remove_worktree_with_submodules.go index 4af533e02..82e5a9303 100644 --- a/pkg/integration/tests/worktree/force_remove_worktree_with_submodules.go +++ b/pkg/integration/tests/worktree/force_remove_worktree_with_submodules.go @@ -29,9 +29,9 @@ var ForceRemoveWorktreeWithSubmodules = NewIntegrationTest(NewIntegrationTestArg NavigateToLine(Contains("linked-worktree")). Press(keys.Universal.Remove). Tap(func() { - t.ExpectPopup().Confirmation(). - Title(Equals("Remove worktree")). - Content(Equals("Are you sure you want to remove worktree 'linked-worktree'?")). + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'linked-worktree'?")). + Select(MatchesRegexp("Remove worktree$")). Confirm() t.ExpectPopup().Confirmation(). diff --git a/pkg/integration/tests/worktree/remove_worktree_and_both_branches.go b/pkg/integration/tests/worktree/remove_worktree_and_both_branches.go new file mode 100644 index 000000000..8ba8e9112 --- /dev/null +++ b/pkg/integration/tests/worktree/remove_worktree_and_both_branches.go @@ -0,0 +1,64 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RemoveWorktreeAndBothBranches = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "From the worktrees panel, remove a worktree and delete both its local and remote branch in one go", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CloneIntoRemote("origin") + shell.EmptyCommit("initial commit") + shell.NewBranch("mybranch") + shell.EmptyCommit("commit on mybranch") + shell.PushBranchAndSetUpstream("origin", "mybranch") + shell.EmptyCommit("commit not pushed to the remote") // so mybranch isn't fully merged + shell.Checkout("master") + shell.AddWorktreeCheckout("mybranch", "../linked-worktree") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Worktrees(). + Focus(). + Lines( + Contains("(main worktree)").IsSelected(), + Contains("linked-worktree"), + ). + NavigateToLine(Contains("linked-worktree")). + Press(keys.Universal.Remove). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'linked-worktree'?")). + Select(Contains("Remove worktree and delete local and remote branch")). + Confirm() + + // mybranch isn't fully merged, so we get the force-delete warning + t.ExpectPopup().Confirmation(). + Title(Equals("Force delete branch")). + Content(Equals("'mybranch' is not fully merged. Are you sure you want to delete it?")). + Confirm() + }). + Lines( + Contains("(main worktree)").IsSelected(), + ) + + // The remote branch is gone too + t.Views().Remotes(). + Focus(). + Lines(Contains("origin")). + PressEnter() + + t.Views().RemoteBranches(). + IsEmpty() + + // And so is the local branch + t.Views().Branches(). + Focus(). + Lines( + Contains("master").IsSelected(), + ) + }, +}) diff --git a/pkg/integration/tests/worktree/remove_worktree_and_branch.go b/pkg/integration/tests/worktree/remove_worktree_and_branch.go new file mode 100644 index 000000000..5910b6b7f --- /dev/null +++ b/pkg/integration/tests/worktree/remove_worktree_and_branch.go @@ -0,0 +1,73 @@ +package worktree + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RemoveWorktreeAndBranch = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "From the worktrees panel, remove a worktree and delete its branch in one go", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.NewBranch("mybranch") + shell.CreateFileAndAdd("README.md", "hello world") + shell.Commit("initial commit") + shell.NewBranch("newbranch") + shell.EmptyCommit("commit on newbranch") + shell.Checkout("mybranch") + shell.AddWorktreeCheckout("newbranch", "../linked-worktree") + shell.RunCommand([]string{"git", "worktree", "add", "--detach", "../detached-worktree"}) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Worktrees(). + Focus(). + Lines( + Contains("(main worktree)").IsSelected(), + Contains("detached-worktree"), + Contains("linked-worktree"), + ). + // A detached worktree has no branch, so neither delete action is offered + NavigateToLine(Contains("detached-worktree")). + Press(keys.Universal.Remove). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'detached-worktree'?")). + Select(Contains("Remove worktree and delete branch")). + Tooltip(Contains("This worktree is not checked out on a branch")). + Select(Contains("Remove worktree and delete local and remote branch")). + Tooltip(Contains("This worktree is not checked out on a branch")). + Cancel() + }). + // Remove a worktree and delete its branch at once. newbranch has no + // upstream, so deleting the remote branch too isn't offered. + NavigateToLine(Contains("linked-worktree")). + Press(keys.Universal.Remove). + Tap(func() { + t.ExpectPopup().Menu(). + Title(Equals("Remove worktree 'linked-worktree'?")). + Select(Contains("Remove worktree and delete local and remote branch")). + Tooltip(Contains("The selected branch has no upstream")). + Select(Contains("Remove worktree and delete branch")). + Confirm() + + // newbranch isn't fully merged, so we get the force-delete warning + t.ExpectPopup().Confirmation(). + Title(Equals("Force delete branch")). + Content(Equals("'newbranch' is not fully merged. Are you sure you want to delete it?")). + Confirm() + }). + Lines( + Contains("(main worktree)"), + Contains("detached-worktree"), + ) + + // The branch is gone too + t.Views().Branches(). + Focus(). + Lines( + Contains("mybranch").IsSelected(), + ) + }, +}) From 9a4ef7d1a1a86dd40b58850bedd620627bc42b73 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 4 Jun 2026 07:53:01 +0200 Subject: [PATCH 033/218] Allow overriding the platform used for default keybindings A handful of default keybindings differ by platform (e.g. word-wise cursor movement in text inputs uses alt on macOS but ctrl elsewhere). Lazygit chooses these based on the OS it runs on, but that's the wrong signal when the OS isn't where the user is actually typing: someone running lazygit in a Linux container that they access over ssh from a Mac gets the Linux bindings, when they'd rather have the Mac ones. Remapping each binding by hand via config is tedious, so add a single LAZYGIT_KEYBINDING_PLATFORM override. An unrecognized value falls back to the real OS rather than to the non-darwin default bindings, since the latter would be an arbitrary choice. --- docs-master/Config.md | 6 +++++ pkg/app/entry_point.go | 2 +- pkg/config/app_config.go | 17 +++++++++++++- pkg/config/app_config_test.go | 42 +++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 2 deletions(-) diff --git a/docs-master/Config.md b/docs-master/Config.md index 152044be6..98d64f1a2 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -1102,6 +1102,12 @@ keybinding: edit: # disable 'edit file' ``` +### Overriding the platform for default keybindings + +A few keybindings have different defaults on macOS than on Linux and Windows (e.g. word-wise cursor movement in text inputs uses `alt` on macOS but `ctrl` elsewhere). Lazygit picks these based on the OS it's running on, but you can override that with the `LAZYGIT_KEYBINDING_PLATFORM` environment variable. Set it to `darwin`, `linux`, or `windows`; any other value is ignored and the actual OS is used. + +This is useful when running lazygit in a Linux container that you access over ssh from a Mac, where you'd rather use the macOS keybindings. + ### Example Keybindings For Colemak Users ```yaml diff --git a/pkg/app/entry_point.go b/pkg/app/entry_point.go index 8b1a2a040..a3225e311 100644 --- a/pkg/app/entry_point.go +++ b/pkg/app/entry_point.go @@ -102,7 +102,7 @@ func Start(buildInfo *BuildInfo, integrationTest integrationTypes.IntegrationTes if cliArgs.PrintDefaultConfig { var buf bytes.Buffer encoder := yaml.NewEncoder(&buf) - err := encoder.Encode(config.GetDefaultConfigForPlatform(runtime.GOOS)) + err := encoder.Encode(config.GetDefaultConfigForPlatform(config.KeybindingPlatform())) if err != nil { log.Fatal(err.Error()) } diff --git a/pkg/config/app_config.go b/pkg/config/app_config.go index 313d71dcf..9b9db2c12 100644 --- a/pkg/config/app_config.go +++ b/pkg/config/app_config.go @@ -136,8 +136,23 @@ func findOrCreateConfigDir() (string, error) { return folder, os.MkdirAll(folder, 0o755) } +// KeybindingPlatform returns the platform whose default keybindings should be +// used. Normally this is the OS we're running on, but it can be overridden with +// the LAZYGIT_KEYBINDING_PLATFORM environment variable; this is useful e.g. when +// running lazygit in a Linux container that you access over ssh from a Mac, and +// you'd rather use the Mac keybindings. An unrecognized value falls back to the +// real OS, which gives meaningful bindings, rather than to the (arbitrary) +// non-darwin defaults. +func KeybindingPlatform() string { + platform := os.Getenv("LAZYGIT_KEYBINDING_PLATFORM") + if lo.Contains([]string{"darwin", "linux", "windows"}, platform) { + return platform + } + return runtime.GOOS +} + func loadUserConfigWithDefaults(configFiles []*ConfigFile, isGuiInitialized bool) (*UserConfig, error) { - return loadUserConfig(configFiles, GetDefaultConfigForPlatform(runtime.GOOS), isGuiInitialized) + return loadUserConfig(configFiles, GetDefaultConfigForPlatform(KeybindingPlatform()), isGuiInitialized) } func loadUserConfig(configFiles []*ConfigFile, base *UserConfig, isGuiInitialized bool) (*UserConfig, error) { diff --git a/pkg/config/app_config_test.go b/pkg/config/app_config_test.go index 913bc47dc..be97c2acb 100644 --- a/pkg/config/app_config_test.go +++ b/pkg/config/app_config_test.go @@ -1,11 +1,53 @@ package config import ( + "runtime" "testing" "github.com/stretchr/testify/assert" ) +func TestKeybindingPlatform(t *testing.T) { + scenarios := []struct { + name string + envValue string + expected string + }{ + { + name: "Not set falls back to the host OS", + envValue: "", + expected: runtime.GOOS, + }, + { + name: "darwin is honored", + envValue: "darwin", + expected: "darwin", + }, + { + name: "linux is honored", + envValue: "linux", + expected: "linux", + }, + { + name: "windows is honored", + envValue: "windows", + expected: "windows", + }, + { + name: "An unrecognized value falls back to the host OS", + envValue: "mac", + expected: runtime.GOOS, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + t.Setenv("LAZYGIT_KEYBINDING_PLATFORM", s.envValue) + assert.Equal(t, s.expected, KeybindingPlatform()) + }) + } +} + func TestMigrationOfRenamedKeys(t *testing.T) { scenarios := []struct { name string From b039d98b09ddc2540b76ad8d53bac0df57a58574 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 1 Jul 2026 17:05:11 +0200 Subject: [PATCH 034/218] Scale the side-panel layout height thresholds by panel count The height thresholds that decide between the proportional layout and the squashed layout (and, within the squashed layout, between 3-row and 1-row unfocused panels) were hard-coded constants tuned for the fixed set of five side panels. Now that the panels are configurable, a layout with fewer panels has less to fit, yet was still forced into the squashed layout at the same height as five panels would be. Scale the thresholds down in proportion to the panel count so a smaller layout keeps using the proportional layout at smaller heights. Only ever scale down: raising the thresholds for more panels would make them squash sooner, which works against the reason someone adds panels in the first place (they want to see them). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/window_arrangement_helper.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/helpers/window_arrangement_helper.go b/pkg/gui/controllers/helpers/window_arrangement_helper.go index 610c57f52..37a4465b1 100644 --- a/pkg/gui/controllers/helpers/window_arrangement_helper.go +++ b/pkg/gui/controllers/helpers/window_arrangement_helper.go @@ -430,6 +430,15 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [ return func(width int, height int) []*boxlayout.Box { windows := sideWindowNames(args.UserConfig) + // These thresholds were originally tuned for the default five side panels. + // With fewer panels there's less to fit, so scale them down proportionally + // to keep using the proportional layout at smaller heights rather than + // squashing unnecessarily. We only ever scale down: making more panels + // squash sooner tends to work against the reason people add panels. + const defaultSidePanelCount = 5 + minHeightForNormalLayout := min(28, 28*len(windows)/defaultSidePanelCount) + minHeightForTallSquashedPanels := min(21, 21*len(windows)/defaultSidePanelCount) + boxForEachWindow := func(boxForWindow func(window string) *boxlayout.Box) []*boxlayout.Box { boxes := make([]*boxlayout.Box, 0, len(windows)) for _, window := range windows { @@ -454,7 +463,7 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [ } return boxForEachWindow(fullHeightBox) - } else if height >= 28 { + } else if height >= minHeightForNormalLayout { accordionMode := args.UserConfig.Gui.ExpandFocusedSidePanel accordionBox := func(defaultBox *boxlayout.Box) *boxlayout.Box { if accordionMode && defaultBox.Window == args.CurrentSideWindow { @@ -487,7 +496,7 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [ } squashedHeight := 1 - if height >= 21 { + if height >= minHeightForTallSquashedPanels { squashedHeight = 3 } From a929f34c8437f250058fd9fad205631b01eb454c Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 1 Jul 2026 17:10:21 +0200 Subject: [PATCH 035/218] Add gui.shrinkSidePanelsToContent option Accordion mode expands the focused side panel, but when that panel has little content (an empty Files panel, a Branches panel with only master) it just fills the extra height with blank space. The same waste happens for any panel that gets more height than it has content to show. When this option is enabled, each side panel is sized to its own content (plus a blank line, so it's clear there's nothing more below) rather than to an equal share of the height. The height a small panel gives up flows to the panels that have more content than fits; those grow up to their content and then scroll, weighted toward the focused panel in accordion mode so the two features compose. Only when every panel fits with room to spare is the leftover shared out equally, regardless of focus: enlarging the focused panel there would reveal no more content and would only make the panels jump around as the focus moves. The option is independent of expandFocusedSidePanel and off by default. The status panel, and the stash panel when unfocused, keep their fixed one-line height as before. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs-master/Config.md | 5 + pkg/config/user_config.go | 27 +-- .../helpers/window_arrangement_helper.go | 171 +++++++++++++++- .../helpers/window_arrangement_helper_test.go | 190 ++++++++++++++++++ schema-master/config.json | 5 + 5 files changed, 377 insertions(+), 21 deletions(-) diff --git a/docs-master/Config.md b/docs-master/Config.md index 98d64f1a2..1d101be18 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -110,6 +110,11 @@ gui: # is true. expandedSidePanelWeight: 2 + # If true, don't give a side panel more height than it needs to show its + # content; when all panels fit, the leftover height is shared among them so that + # they still fill the screen. + shrinkSidePanelsToContent: false + # The side panels, in the order they appear from top to bottom. # Each entry is a list of one or more names that share a single panel as tabs # (cycle through them with the next-tab/previous-tab keys). diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index 8314701ba..30ce0377d 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -111,6 +111,8 @@ type GuiConfig struct { 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"` + // If true, don't give a side panel more height than it needs to show its content; when all panels fit, the leftover height is shared among them so that they still fill the screen. + ShrinkSidePanelsToContent bool `yaml:"shrinkSidePanelsToContent"` // The side panels, in the order they appear from top to bottom. // Each entry is a list of one or more names that share a single panel as tabs (cycle through them with the next-tab/previous-tab keys). // Omit a name to hide it; give a name its own one-element list to promote a tab to a top-level panel. @@ -847,18 +849,19 @@ func GetDefaultConfig() *UserConfig { func GetDefaultConfigForPlatform(platform string) *UserConfig { return &UserConfig{ Gui: GuiConfig{ - ScrollHeight: 2, - ScrollPastBottom: true, - ScrollOffMargin: 2, - ScrollOffBehavior: "margin", - TabWidth: 4, - MouseEvents: true, - SkipAmendWarning: false, - SkipDiscardChangeWarning: false, - SkipStashWarning: false, - SidePanelWidth: 0.3333, - ExpandFocusedSidePanel: false, - ExpandedSidePanelWeight: 2, + ScrollHeight: 2, + ScrollPastBottom: true, + ScrollOffMargin: 2, + ScrollOffBehavior: "margin", + TabWidth: 4, + MouseEvents: true, + SkipAmendWarning: false, + SkipDiscardChangeWarning: false, + SkipStashWarning: false, + SidePanelWidth: 0.3333, + ExpandFocusedSidePanel: false, + ExpandedSidePanelWeight: 2, + ShrinkSidePanelsToContent: false, SidePanels: []SidePanel{ {"status"}, {"files", "worktrees", "submodules"}, diff --git a/pkg/gui/controllers/helpers/window_arrangement_helper.go b/pkg/gui/controllers/helpers/window_arrangement_helper.go index 37a4465b1..90a651809 100644 --- a/pkg/gui/controllers/helpers/window_arrangement_helper.go +++ b/pkg/gui/controllers/helpers/window_arrangement_helper.go @@ -55,6 +55,9 @@ type WindowArrangementArgs struct { // stash height special-cases key off (rather than the window itself, whose // name is just its first tab). ActiveViewForWindow func(window string) string + // Returns the number of content lines of the view currently shown in the given + // window. Used by the shrink-to-content feature to size a panel to its content. + ContentHeightForWindow func(window string) int // Whether the main panel is split (as is the case e.g. when a file has both // staged and unstaged changes) SplitMainPanel bool @@ -97,15 +100,18 @@ func (self *WindowArrangementHelper) GetWindowDimensions(informationStr string, CurrentWindow: self.c.Context().CurrentStatic().GetWindowName(), CurrentSideWindow: self.c.Context().CurrentSide().GetWindowName(), ActiveViewForWindow: self.windowHelper.GetViewNameForWindow, - SplitMainPanel: repoState.GetSplitMainPanel(), - ScreenMode: repoState.GetScreenMode(), - AppStatus: appStatus, - InformationStr: informationStr, - ShowExtrasWindow: self.c.State().GetShowExtrasWindow(), - InDemo: self.c.InDemo(), - IsAnyModeActive: self.modeHelper.IsAnyModeActive(), - InSearchPrompt: repoState.InSearchPrompt(), - SearchPrefix: searchPrefix, + ContentHeightForWindow: func(window string) int { + return self.windowHelper.GetContextForWindow(window).TotalContentHeight() + }, + SplitMainPanel: repoState.GetSplitMainPanel(), + ScreenMode: repoState.GetScreenMode(), + AppStatus: appStatus, + InformationStr: informationStr, + ShowExtrasWindow: self.c.State().GetShowExtrasWindow(), + InDemo: self.c.InDemo(), + IsAnyModeActive: self.modeHelper.IsAnyModeActive(), + InSearchPrompt: repoState.InSearchPrompt(), + SearchPrefix: searchPrefix, } return GetWindowDimensions(args) @@ -464,6 +470,12 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [ return boxForEachWindow(fullHeightBox) } else if height >= minHeightForNormalLayout { + if args.UserConfig.Gui.ShrinkSidePanelsToContent { + if boxes, ok := shrinkToContentSidePanelBoxes(args, windows, height); ok { + return boxes + } + } + accordionMode := args.UserConfig.Gui.ExpandFocusedSidePanel accordionBox := func(defaultBox *boxlayout.Box) *boxlayout.Box { if accordionMode && defaultBox.Window == args.CurrentSideWindow { @@ -517,3 +529,144 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [ return boxForEachWindow(squashedSidePanelBox) } } + +// shrinkToContentSidePanelBoxes implements the gui.shrinkSidePanelsToContent +// feature: rather than giving every side panel an equal share of the height, we +// size each panel to its own content (plus one blank line, so it's clear there's +// nothing more below), which stops panels with little content from wasting space. +// +// The height freed up by a small panel flows to the panels that have more content +// than their share; those grow up to their own content and then scroll. If every +// panel fits its content with room to spare, there's nothing to absorb the +// leftover, so it's shared among all panels by weight (which, in accordion mode, +// gives the focused panel more of it). +// +// The status panel, and the stash panel when it's not focused, keep their +// constant height and don't take part; ok is false when there are no panels to +// size (so the caller falls back to the normal weighted layout). +func shrinkToContentSidePanelBoxes(args WindowArrangementArgs, windows []string, height int) ([]*boxlayout.Box, bool) { + const frameSize = 2 + + accordionMode := args.UserConfig.Gui.ExpandFocusedSidePanel + + // A flexible panel is one we size to its content. Fixed panels (the status + // panel, and the stash panel when unfocused) get their constant height and + // are excluded from the distribution below. + type flexiblePanel struct { + boxIndex int + desired int // target height: content rows (see below) plus the frame + weight int + height int // final height, only computed for the room-to-spare case + capped bool // true once it fits its content within its share + } + + boxes := make([]*boxlayout.Box, len(windows)) + flexible := []*flexiblePanel{} + availableForFlexible := height + for i, window := range windows { + focused := window == args.CurrentSideWindow + + // The status and stash sizing is a property of those views, so we key off + // the tab the window is currently showing, not the window's name (its first + // tab); see the comment on normalBox in sidePanelChildren. + activeView := args.ActiveViewForWindow(window) + if activeView == "status" || (activeView == "stash" && !focused) { + boxes[i] = &boxlayout.Box{Window: window, Size: 3} + availableForFlexible -= 3 + continue + } + + weight := 1 + if accordionMode && focused { + weight = args.UserConfig.Gui.ExpandedSidePanelWeight + } + // Show the content plus a blank line, so it's clear there's nothing more + // below, but never fewer than two rows: a lone blank row looks cramped, + // and an empty Files panel is the common state right after launching. + contentRows := max(args.ContentHeightForWindow(window)+1, 2) + flexible = append(flexible, &flexiblePanel{ + boxIndex: i, + desired: contentRows + frameSize, + weight: weight, + }) + } + + if len(flexible) == 0 || availableForFlexible <= 0 { + return nil, false + } + + // Water-filling: repeatedly cap the panels whose desired height is no more + // than their weighted share of what's left. Capping a panel only raises the + // others' shares, so this converges once no further panel fits its content. + // Whatever remains is what the still-uncapped panels have to share. + remaining := availableForFlexible + for { + totalWeight := 0 + for _, p := range flexible { + if !p.capped { + totalWeight += p.weight + } + } + if totalWeight == 0 { + break + } + + newlyCapped := []*flexiblePanel{} + for _, p := range flexible { + if !p.capped && p.desired*totalWeight <= remaining*p.weight { + newlyCapped = append(newlyCapped, p) + } + } + if len(newlyCapped) == 0 { + break + } + for _, p := range newlyCapped { + p.capped = true + remaining -= p.desired + } + } + + anyUncapped := false + for _, p := range flexible { + if !p.capped { + anyUncapped = true + } + } + + if anyUncapped { + // Some panels have more content than fits: give the ones that fit exactly + // their content, and let boxlayout share what's left among the rest by + // weight (they'll scroll). This is the common, real-world case. + for _, p := range flexible { + if p.capped { + boxes[p.boxIndex] = &boxlayout.Box{Window: windows[p.boxIndex], Size: p.desired} + } else { + boxes[p.boxIndex] = &boxlayout.Box{Window: windows[p.boxIndex], Weight: p.weight} + } + } + return boxes, true + } + + // Every panel fits its content with room to spare, so no panel needs to + // scroll. Share the leftover equally among them, regardless of focus and + // accordion mode: enlarging the focused panel here reveals no more content + // (it already fits) and would only make panels jump around as focus moves. + // Deal out the rounding remainder one row at a time so the heights fill the + // available space exactly. + base := remaining / len(flexible) + extra := remaining % len(flexible) + for i, p := range flexible { + p.height = p.desired + base + if i < extra { + p.height++ + } + } + + // boxlayout can't lay out a set of boxes that are all statically sized (it + // needs a weighted box to absorb the space), so we hand it the heights as + // weights: they sum to the available height, so it reproduces them exactly. + for _, p := range flexible { + boxes[p.boxIndex] = &boxlayout.Box{Window: windows[p.boxIndex], Weight: p.height} + } + return boxes, true +} diff --git a/pkg/gui/controllers/helpers/window_arrangement_helper_test.go b/pkg/gui/controllers/helpers/window_arrangement_helper_test.go index 63d7642b6..365d7f104 100644 --- a/pkg/gui/controllers/helpers/window_arrangement_helper_test.go +++ b/pkg/gui/controllers/helpers/window_arrangement_helper_test.go @@ -13,6 +13,14 @@ import ( "github.com/samber/lo" ) +// contentHeights builds a ContentHeightForWindow function from a map of window +// name to content height; windows not in the map report a height of 0. +func contentHeights(heights map[string]int) func(window string) int { + return func(window string) int { + return heights[window] + } +} + // The best way to add test cases here is to set your args and then get the // test to fail and copy+paste the output into the test case's expected string. // TODO: add more test cases @@ -710,6 +718,188 @@ func TestGetWindowDimensions(t *testing.T) { B: statusSpacer2 `, }, + { + name: "shrink to content, one panel overflows", + mutateArgs: func(args *WindowArrangementArgs) { + args.UserConfig.Gui.ShrinkSidePanelsToContent = true + args.ContentHeightForWindow = contentHeights(map[string]int{ + "files": 2, + "branches": 1, + "commits": 100, + }) + }, + expected: ` + ╭status─────────────────╮╭main────────────────────────────────────────────╮ + │ ││ │ + ╰───────────────────────╯│ │ + ╭files──────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭branches───────────────╮│ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭commits────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭stash──────────────────╮│ │ + │ ││ │ + ╰───────────────────────╯╰────────────────────────────────────────────────╯ + A + A: statusSpacer1 + B: information + `, + }, + { + name: "shrink to content, everything fits with room to spare", + mutateArgs: func(args *WindowArrangementArgs) { + args.UserConfig.Gui.ShrinkSidePanelsToContent = true + args.ContentHeightForWindow = contentHeights(map[string]int{ + "files": 2, + "branches": 1, + "commits": 3, + }) + }, + expected: ` + ╭status─────────────────╮╭main────────────────────────────────────────────╮ + │ ││ │ + ╰───────────────────────╯│ │ + ╭files──────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭branches───────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭commits────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭stash──────────────────╮│ │ + │ ││ │ + ╰───────────────────────╯╰────────────────────────────────────────────────╯ + A + A: statusSpacer1 + B: information + `, + }, + { + name: "shrink to content, accordion doesn't resize panels when everything fits", + mutateArgs: func(args *WindowArrangementArgs) { + args.UserConfig.Gui.ShrinkSidePanelsToContent = true + args.UserConfig.Gui.ExpandFocusedSidePanel = true + args.CurrentSideWindow = "branches" + args.ContentHeightForWindow = contentHeights(map[string]int{ + "files": 2, + "branches": 1, + "commits": 3, + }) + }, + expected: ` + ╭status─────────────────╮╭main────────────────────────────────────────────╮ + │ ││ │ + ╰───────────────────────╯│ │ + ╭files──────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭branches───────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭commits────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭stash──────────────────╮│ │ + │ ││ │ + ╰───────────────────────╯╰────────────────────────────────────────────────╯ + A + A: statusSpacer1 + B: information + `, + }, + { + name: "shrink to content, empty panel keeps two rows rather than one", + mutateArgs: func(args *WindowArrangementArgs) { + args.UserConfig.Gui.ShrinkSidePanelsToContent = true + args.ContentHeightForWindow = contentHeights(map[string]int{ + "files": 0, + "branches": 1, + "commits": 100, + }) + }, + expected: ` + ╭status─────────────────╮╭main────────────────────────────────────────────╮ + │ ││ │ + ╰───────────────────────╯│ │ + ╭files──────────────────╮│ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭branches───────────────╮│ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭commits────────────────╮│ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + │ ││ │ + ╰───────────────────────╯│ │ + ╭stash──────────────────╮│ │ + │ ││ │ + ╰───────────────────────╯╰────────────────────────────────────────────────╯ + A + A: statusSpacer1 + B: information + `, + }, } for _, test := range tests { diff --git a/schema-master/config.json b/schema-master/config.json index 0dd1d5d20..82dbebb0b 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -590,6 +590,11 @@ "description": "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.", "default": 2 }, + "shrinkSidePanelsToContent": { + "type": "boolean", + "description": "If true, don't give a side panel more height than it needs to show its content; when all panels fit, the leftover height is shared among them so that they still fill the screen.", + "default": false + }, "sidePanels": { "items": { "$ref": "#/$defs/SidePanel" From f84ada494121604316027cb63364024435351a7a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 22:31:52 +0200 Subject: [PATCH 036/218] Show renamed files in the custom patch builder When loading the files of a commit we passed --no-renames, so a rename showed up as a separate delete and add rather than a single R entry. That made it impossible to work with a rename that also modifies the file: the modifications were spread across a full deletion and a full addition instead of appearing as the handful of lines that actually changed. The staging view already shows renames and lets you stage their hunks, so there was no good reason for the patch builder to differ; the flag was only there because the commit-file parser couldn't cope with the rename record format. Switch the commit-file loader and the per-file diff to --find-renames, teach the parser about the rename record (a status followed by two paths), and carry the previous path through the patch builder so the diff for a rename is loaded with both paths, which is what makes git emit the rename in the first place. A whole-file selection keeps the rename in the header, so the rename moves or is discarded together with the file's contents. A partial selection instead strips the rename metadata and points the header at the new path, so applying the patch only changes the contents and leaves the rename in place; the blob index line is kept so that a 3-way apply can still fall back to a blob merge. Discarding a renamed file from a commit now discards both the new and the old path, so the new file is removed and the old one is restored. Changing the rename similarity threshold refreshes the commit files panel too, not just the files panel, so that a rename can turn into a delete and add or back. It is disabled while building a patch, however, because the patch builder caches each file's diff by path and would desync if a rename changed into a delete and add underneath it. Finally, copying a file's diff from the commit files panel now passes both paths for a rename, so the copied diff shows the rename instead of a new-file add. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git.go | 4 +- .../git_commands/commit_file_loader.go | 41 ++++++++--- .../git_commands/commit_file_loader_test.go | 19 +++++ pkg/commands/git_commands/working_tree.go | 12 ++- .../git_commands/working_tree_test.go | 26 ++++++- pkg/commands/models/commit_file.go | 21 ++++++ pkg/commands/patch/patch_builder.go | 47 +++++++----- pkg/commands/patch/patch_test.go | 55 ++++++++++++++ pkg/commands/patch/transform.go | 59 +++++++++++++-- pkg/gui/context/setup.go | 7 +- .../controllers/commits_files_controller.go | 22 ++++-- .../helpers/patch_building_helper.go | 9 ++- .../controllers/patch_building_controller.go | 8 +- .../rename_similarity_threshold_controller.go | 23 +++++- pkg/gui/presentation/files.go | 17 ++++- pkg/gui/presentation/files_test.go | 10 ++- pkg/i18n/english.go | 2 + .../tests/commit/discard_renamed_file.go | 57 +++++++++++++++ .../patch_building/copy_renamed_file_diff.go | 60 +++++++++++++++ .../rename_similarity_threshold_change.go | 66 +++++++++++++++++ .../patch_building/renamed_file_partial.go | 73 +++++++++++++++++++ .../patch_building/renamed_file_whole.go | 62 ++++++++++++++++ pkg/integration/tests/test_list.go | 5 ++ 23 files changed, 642 insertions(+), 63 deletions(-) create mode 100644 pkg/integration/tests/commit/discard_renamed_file.go create mode 100644 pkg/integration/tests/patch_building/copy_renamed_file_diff.go create mode 100644 pkg/integration/tests/patch_building/rename_similarity_threshold_change.go create mode 100644 pkg/integration/tests/patch_building/renamed_file_partial.go create mode 100644 pkg/integration/tests/patch_building/renamed_file_whole.go diff --git a/pkg/commands/git.go b/pkg/commands/git.go index 7f95fbafb..d9add2790 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -117,8 +117,8 @@ func NewGitCommandAux( rebaseCommands := git_commands.NewRebaseCommands(gitCommon, commitCommands, workingTreeCommands) stashCommands := git_commands.NewStashCommands(gitCommon, fileLoader, workingTreeCommands) patchBuilder := patch.NewPatchBuilder(cmn.Log, - func(from string, to string, reverse bool, filename string, plain bool) (string, error) { - return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, plain) + func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) { + return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, previousPath, plain) }) patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchBuilder) bisectCommands := git_commands.NewBisectCommands(gitCommon) diff --git a/pkg/commands/git_commands/commit_file_loader.go b/pkg/commands/git_commands/commit_file_loader.go index 33bd40e13..9500dabfd 100644 --- a/pkg/commands/git_commands/commit_file_loader.go +++ b/pkg/commands/git_commands/commit_file_loader.go @@ -1,12 +1,12 @@ package git_commands import ( + "fmt" "strings" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/common" - "github.com/samber/lo" ) type CommitFileLoader struct { @@ -29,7 +29,7 @@ func (self *CommitFileLoader) GetFilesInDiff(from string, to string, reverse boo Arg("--no-ext-diff"). Arg("--name-status"). Arg("-z"). - Arg("--no-renames"). + Arg(fmt.Sprintf("--find-renames=%d%%", self.UserConfig().Git.RenameSimilarityThreshold)). ArgIf(reverse, "-R"). Arg(from). Arg(to). @@ -44,18 +44,37 @@ func (self *CommitFileLoader) GetFilesInDiff(from string, to string, reverse boo } // filenames string is something like "MM\x00file1\x00MU\x00file2\x00AA\x00file3\x00" -// so we need to split it by the null character and then map each status-name pair to a commit file +// so we need to split it by the null character and then map each status-name pair +// to a commit file. Renames (and copies) are special: their status is followed by +// two paths (the old one and the new one) rather than one, e.g. +// "R100\x00old\x00new\x00". func getCommitFilesFromFilenames(filenames string) []*models.CommitFile { - lines := strings.Split(strings.TrimRight(filenames, "\x00"), "\x00") - if len(lines) == 1 { + fields := strings.Split(strings.TrimRight(filenames, "\x00"), "\x00") + if len(fields) == 1 { return []*models.CommitFile{} } - // typical result looks like 'A my_file' meaning my_file was added - return lo.Map(lo.Chunk(lines, 2), func(chunk []string, _ int) *models.CommitFile { - return &models.CommitFile{ - ChangeStatus: chunk[0], - Path: chunk[1], + commitFiles := make([]*models.CommitFile, 0, len(fields)/2) + for i := 0; i < len(fields)-1; { + changeStatus := fields[i] + if changeStatus[0] == 'R' || changeStatus[0] == 'C' { + // The status has a similarity score appended (e.g. "R100"); drop it + // so the rest of the code only has to deal with a plain "R" or "C". + commitFiles = append(commitFiles, &models.CommitFile{ + ChangeStatus: changeStatus[:1], + PreviousPath: fields[i+1], + Path: fields[i+2], + }) + i += 3 + } else { + // typical result looks like 'A my_file' meaning my_file was added + commitFiles = append(commitFiles, &models.CommitFile{ + ChangeStatus: changeStatus, + Path: fields[i+1], + }) + i += 2 } - }) + } + + return commitFiles } diff --git a/pkg/commands/git_commands/commit_file_loader_test.go b/pkg/commands/git_commands/commit_file_loader_test.go index ec91ec22e..2fa745f8b 100644 --- a/pkg/commands/git_commands/commit_file_loader_test.go +++ b/pkg/commands/git_commands/commit_file_loader_test.go @@ -60,6 +60,25 @@ func TestGetCommitFilesFromFilenames(t *testing.T) { }, }, }, + { + testName: "a rename among regular files", + input: "M\x00Myfile\x00R100\x00before\x00after\x00A\x00Added\x00", + output: []*models.CommitFile{ + { + Path: "Myfile", + ChangeStatus: "M", + }, + { + Path: "after", + PreviousPath: "before", + ChangeStatus: "R", + }, + { + Path: "Added", + ChangeStatus: "A", + }, + }, + }, } for _, test := range tests { diff --git a/pkg/commands/git_commands/working_tree.go b/pkg/commands/git_commands/working_tree.go index 328da1404..8625158ab 100644 --- a/pkg/commands/git_commands/working_tree.go +++ b/pkg/commands/git_commands/working_tree.go @@ -432,8 +432,14 @@ func (self *WorkingTreeCommands) WorktreeFileDiffCmdObj(node models.IFile, plain // ShowFileDiff get the diff of specified from and to. Typically this will be used for a single commit so it'll be 123abc^..123abc // but when we're in diff mode it could be any 'from' to any 'to'. The reverse flag is also here thanks to diff mode. -func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, plain bool) (string, error) { - return self.ShowFileDiffCmdObj(from, to, reverse, []string{fileName}, plain).RunWithOutput() +// For a renamed file, previousPath is the path it was renamed from (empty otherwise); +// both paths must be passed to git for the rename to be detected. +func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, previousPath string, plain bool) (string, error) { + fileNames := []string{fileName} + if previousPath != "" { + fileNames = append(fileNames, previousPath) + } + return self.ShowFileDiffCmdObj(from, to, reverse, fileNames, plain).RunWithOutput() } func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reverse bool, fileNames []string, plain bool) *oscommands.CmdObj { @@ -454,7 +460,7 @@ func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reve ArgIfElse(useExtDiff || useExtDiffGitConfig, "--ext-diff", "--no-ext-diff"). Arg("--submodule"). Arg(fmt.Sprintf("--unified=%d", contextSize)). - Arg("--no-renames"). + Arg(fmt.Sprintf("--find-renames=%d%%", self.UserConfig().Git.RenameSimilarityThreshold)). Arg(fmt.Sprintf("--color=%s", colorArg)). Arg(from). Arg(to). diff --git a/pkg/commands/git_commands/working_tree_test.go b/pkg/commands/git_commands/working_tree_test.go index bb4c8e750..8af2b707d 100644 --- a/pkg/commands/git_commands/working_tree_test.go +++ b/pkg/commands/git_commands/working_tree_test.go @@ -339,6 +339,8 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { from string to string reverse bool + fileName string + previousPath string plain bool ignoreWhitespace bool contextSize uint64 @@ -353,33 +355,49 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { from: "1234567890", to: "0987654321", reverse: false, + fileName: "test.txt", plain: false, ignoreWhitespace: false, contextSize: 3, runner: oscommands.NewFakeRunner(t). - ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=3", "--no-renames", "--color=always", "1234567890", "0987654321", "--", "test.txt"}, expectedResult, nil), + ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=3", "--find-renames=50%", "--color=always", "1234567890", "0987654321", "--", "test.txt"}, expectedResult, nil), }, { testName: "Show diff with custom context size", from: "1234567890", to: "0987654321", reverse: false, + fileName: "test.txt", plain: false, ignoreWhitespace: false, contextSize: 123, runner: oscommands.NewFakeRunner(t). - ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=123", "--no-renames", "--color=always", "1234567890", "0987654321", "--", "test.txt"}, expectedResult, nil), + ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=123", "--find-renames=50%", "--color=always", "1234567890", "0987654321", "--", "test.txt"}, expectedResult, nil), }, { testName: "Default case (ignore whitespace)", from: "1234567890", to: "0987654321", reverse: false, + fileName: "test.txt", plain: false, ignoreWhitespace: true, contextSize: 3, runner: oscommands.NewFakeRunner(t). - ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=3", "--no-renames", "--color=always", "1234567890", "0987654321", "--ignore-all-space", "--", "test.txt"}, expectedResult, nil), + ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=3", "--find-renames=50%", "--color=always", "1234567890", "0987654321", "--ignore-all-space", "--", "test.txt"}, expectedResult, nil), + }, + { + testName: "Renamed file passes both paths so the rename is detected", + from: "1234567890", + to: "0987654321", + reverse: false, + fileName: "new.txt", + previousPath: "old.txt", + plain: false, + ignoreWhitespace: false, + contextSize: 3, + runner: oscommands.NewFakeRunner(t). + ExpectGitArgs([]string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "diff", "--no-ext-diff", "--submodule", "--unified=3", "--find-renames=50%", "--color=always", "1234567890", "0987654321", "--", "new.txt", "old.txt"}, expectedResult, nil), }, } @@ -394,7 +412,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { instance := buildWorkingTreeCommands(commonDeps{runner: s.runner, userConfig: userConfig, appState: &config.AppState{}, repoPaths: &repoPaths}) - result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, "test.txt", s.plain) + result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, s.fileName, s.previousPath, s.plain) assert.NoError(t, err) assert.Equal(t, expectedResult, result) s.runner.CheckForMissingCalls() diff --git a/pkg/commands/models/commit_file.go b/pkg/commands/models/commit_file.go index 90ffd6365..5183fd380 100644 --- a/pkg/commands/models/commit_file.go +++ b/pkg/commands/models/commit_file.go @@ -4,6 +4,9 @@ package models type CommitFile struct { Path string + // For a renamed file, the path it was renamed from; empty otherwise. + PreviousPath string + ChangeStatus string // e.g. 'A' for added or 'M' for modified. This is based on the result from git diff --name-status } @@ -23,6 +26,24 @@ func (f *CommitFile) Deleted() bool { return f.ChangeStatus == "D" } +func (f *CommitFile) IsRename() bool { + return f.PreviousPath != "" +} + +// Names returns an array containing just the path, or in the case of a rename, +// the after path and the before path. +func (f *CommitFile) Names() []string { + result := []string{f.Path} + if f.PreviousPath != "" { + result = append(result, f.PreviousPath) + } + return result +} + func (f *CommitFile) GetPath() string { return f.Path } + +func (f *CommitFile) GetPreviousPath() string { + return f.PreviousPath +} diff --git a/pkg/commands/patch/patch_builder.go b/pkg/commands/patch/patch_builder.go index db834ba16..b730d9f62 100644 --- a/pkg/commands/patch/patch_builder.go +++ b/pkg/commands/patch/patch_builder.go @@ -25,10 +25,14 @@ type fileInfo struct { mode PatchStatus includedLineIndices []int diff string + // For a renamed file, the path it was renamed from; empty otherwise. We + // need to keep hold of it so we can re-render the file's patch (which is + // keyed by the new path) without the caller having to supply it again. + previousPath string } type ( - loadFileDiffFunc func(from string, to string, reverse bool, filename string, plain bool) (string, error) + loadFileDiffFunc func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) ) // PatchBuilder manages the building of a patch for a commit to be applied to another commit (or the working tree, or removed from the current commit). We also support building patches from things like stashes, for which there is less flexibility @@ -75,6 +79,7 @@ func (p *PatchBuilder) PatchToApply(reverse bool, turnAddedFilesIntoDiffAgainstE patch.WriteString(p.RenderPatchForFile(RenderPatchForFileOpts{ Filename: filename, + PreviousPath: info.previousPath, Plain: true, Reverse: reverse, TurnAddedFilesIntoDiffAgainstEmptyFile: turnAddedFilesIntoDiffAgainstEmptyFile, @@ -102,8 +107,8 @@ func (p *PatchBuilder) removeFile(info *fileInfo) { info.includedLineIndices = nil } -func (p *PatchBuilder) AddFileWhole(filename string) error { - info, err := p.getFileInfo(filename) +func (p *PatchBuilder) AddFileWhole(filename string, previousPath string) error { + info, err := p.getFileInfo(filename, previousPath) if err != nil { return err } @@ -113,8 +118,8 @@ func (p *PatchBuilder) AddFileWhole(filename string) error { return nil } -func (p *PatchBuilder) RemoveFile(filename string) error { - info, err := p.getFileInfo(filename) +func (p *PatchBuilder) RemoveFile(filename string, previousPath string) error { + info, err := p.getFileInfo(filename, previousPath) if err != nil { return err } @@ -124,19 +129,20 @@ func (p *PatchBuilder) RemoveFile(filename string) error { return nil } -func (p *PatchBuilder) getFileInfo(filename string) (*fileInfo, error) { +func (p *PatchBuilder) getFileInfo(filename string, previousPath string) (*fileInfo, error) { info, ok := p.fileInfoMap[filename] if ok { return info, nil } - diff, err := p.loadFileDiff(p.From, p.To, p.reverse, filename, true) + diff, err := p.loadFileDiff(p.From, p.To, p.reverse, filename, previousPath, true) if err != nil { return nil, err } info = &fileInfo{ - mode: UNSELECTED, - diff: diff, + mode: UNSELECTED, + diff: diff, + previousPath: previousPath, } p.fileInfoMap[filename] = info @@ -144,8 +150,8 @@ func (p *PatchBuilder) getFileInfo(filename string) (*fileInfo, error) { return info, nil } -func (p *PatchBuilder) AddFileLineRange(filename string, lineIndices []int) error { - info, err := p.getFileInfo(filename) +func (p *PatchBuilder) AddFileLineRange(filename string, previousPath string, lineIndices []int) error { + info, err := p.getFileInfo(filename, previousPath) if err != nil { return err } @@ -155,8 +161,8 @@ func (p *PatchBuilder) AddFileLineRange(filename string, lineIndices []int) erro return nil } -func (p *PatchBuilder) RemoveFileLineRange(filename string, lineIndices []int) error { - info, err := p.getFileInfo(filename) +func (p *PatchBuilder) RemoveFileLineRange(filename string, previousPath string, lineIndices []int) error { + info, err := p.getFileInfo(filename, previousPath) if err != nil { return err } @@ -171,13 +177,14 @@ func (p *PatchBuilder) RemoveFileLineRange(filename string, lineIndices []int) e type RenderPatchForFileOpts struct { Filename string + PreviousPath string Plain bool Reverse bool TurnAddedFilesIntoDiffAgainstEmptyFile bool } func (p *PatchBuilder) RenderPatchForFile(opts RenderPatchForFileOpts) string { - info, err := p.getFileInfo(opts.Filename) + info, err := p.getFileInfo(opts.Filename, opts.PreviousPath) if err != nil { p.Log.Error(err) return "" @@ -198,7 +205,12 @@ func (p *PatchBuilder) RenderPatchForFile(opts RenderPatchForFileOpts) string { Transform(TransformOpts{ Reverse: opts.Reverse, TurnAddedFilesIntoDiffAgainstEmptyFile: opts.TurnAddedFilesIntoDiffAgainstEmptyFile, - IncludedLineIndices: info.includedLineIndices, + // For a partial selection of a renamed file we keep only the + // content change and drop the rename, so that the rename stays in + // the commit. A whole-file selection keeps the rename (and short- + // circuits before this for plain output). + StripRename: info.mode == PART && info.previousPath != "", + IncludedLineIndices: info.includedLineIndices, }) if opts.Plain { @@ -215,6 +227,7 @@ func (p *PatchBuilder) renderEachFilePatch(plain bool) []string { patches := lo.Map(filenames, func(filename string, _ int) string { return p.RenderPatchForFile(RenderPatchForFileOpts{ Filename: filename, + PreviousPath: p.fileInfoMap[filename].previousPath, Plain: plain, Reverse: false, TurnAddedFilesIntoDiffAgainstEmptyFile: true, @@ -244,8 +257,8 @@ func (p *PatchBuilder) GetFileStatus(filename string, parent string) PatchStatus return info.mode } -func (p *PatchBuilder) GetFileIncLineIndices(filename string) ([]int, error) { - info, err := p.getFileInfo(filename) +func (p *PatchBuilder) GetFileIncLineIndices(filename string, previousPath string) ([]int, error) { + info, err := p.getFileInfo(filename, previousPath) if err != nil { return nil, err } diff --git a/pkg/commands/patch/patch_test.go b/pkg/commands/patch/patch_test.go index 91a65db68..4f84041d6 100644 --- a/pkg/commands/patch/patch_test.go +++ b/pkg/commands/patch/patch_test.go @@ -19,6 +19,22 @@ index dcd3485..1ba5540 100644 ... ` +const renameWithModificationDiff = `diff --git a/oldname b/newname +similarity index 62% +rename from oldname +rename to newname +index dcd3485..1ba5540 100644 +--- a/oldname ++++ b/newname +@@ -1,5 +1,5 @@ + apple +-orange ++grape + ... + ... + ... +` + const addNewlineToEndOfFile = `diff --git a/filename b/filename index 80a73f1..e48a11c 100644 --- a/filename @@ -152,6 +168,7 @@ func TestTransform(t *testing.T) { firstLineIndex int lastLineIndex int reverse bool + stripRename bool expected string } @@ -515,6 +532,43 @@ func TestTransform(t *testing.T) { orange banana lemon +`, + }, + { + testName: "renamed file, whole change selected, strips the rename so only the content change is applied", + firstLineIndex: 9, + lastLineIndex: 10, + stripRename: true, + diffText: renameWithModificationDiff, + expected: `diff --git a/newname b/newname +index dcd3485..1ba5540 100644 +--- a/newname ++++ b/newname +@@ -1,5 +1,5 @@ + apple +-orange ++grape + ... + ... + ... +`, + }, + { + testName: "renamed file, only removal selected, strips the rename", + firstLineIndex: 9, + lastLineIndex: 9, + stripRename: true, + diffText: renameWithModificationDiff, + expected: `diff --git a/newname b/newname +index dcd3485..1ba5540 100644 +--- a/newname ++++ b/newname +@@ -1,5 +1,4 @@ + apple +-orange + ... + ... + ... `, }, } @@ -527,6 +581,7 @@ func TestTransform(t *testing.T) { Transform(TransformOpts{ Reverse: s.reverse, FileNameOverride: s.filename, + StripRename: s.stripRename, IncludedLineIndices: lineIndices, }). FormatPlain() diff --git a/pkg/commands/patch/transform.go b/pkg/commands/patch/transform.go index cdf453939..31456bfc7 100644 --- a/pkg/commands/patch/transform.go +++ b/pkg/commands/patch/transform.go @@ -33,6 +33,13 @@ type TransformOpts struct { // treat it as a diff against an empty file. TurnAddedFilesIntoDiffAgainstEmptyFile bool + // When building a partial patch for a renamed file, strip the rename + // metadata from the header and point it at the new path. Applying the + // resulting patch then only changes the file's contents and leaves the + // rename itself in place. (For a whole-file selection we keep the rename + // so that it moves or is discarded together with the contents.) + StripRename bool + // The indices of lines that should be included in the patch. IncludedLineIndices []int } @@ -72,21 +79,61 @@ func (self *patchTransformer) transformHeader() []string { "--- a/" + self.opts.FileNameOverride, "+++ b/" + self.opts.FileNameOverride, } - } else if self.opts.TurnAddedFilesIntoDiffAgainstEmptyFile { - result := make([]string, 0, len(self.patch.header)) - for idx, line := range self.patch.header { + } + + header := self.patch.header + if self.opts.StripRename { + header = stripRenameFromHeader(header) + } + + if self.opts.TurnAddedFilesIntoDiffAgainstEmptyFile { + result := make([]string, 0, len(header)) + for idx, line := range header { if strings.HasPrefix(line, "new file mode") { continue } - if line == "--- /dev/null" && strings.HasPrefix(self.patch.header[idx+1], "+++ b/") { - line = "--- a/" + self.patch.header[idx+1][6:] + if line == "--- /dev/null" && strings.HasPrefix(header[idx+1], "+++ b/") { + line = "--- a/" + header[idx+1][6:] } result = append(result, line) } return result } - return self.patch.header + return header +} + +// stripRenameFromHeader rewrites a rename diff header so that it looks like a +// plain modification of the new path: it drops the rename metadata and points +// the diff at the new path on both sides, while keeping the blob index line so +// that `git apply --3way` can still fall back to a blob merge. See the +// StripRename option for why we do this. +func stripRenameFromHeader(header []string) []string { + newPath := "" + for _, line := range header { + if path, ok := strings.CutPrefix(line, "+++ b/"); ok { + newPath = path + break + } + } + + result := make([]string, 0, len(header)) + for _, line := range header { + switch { + case strings.HasPrefix(line, "similarity index "), + strings.HasPrefix(line, "dissimilarity index "), + strings.HasPrefix(line, "rename from "), + strings.HasPrefix(line, "rename to "): + // drop the rename metadata + case strings.HasPrefix(line, "diff --git "): + result = append(result, "diff --git a/"+newPath+" b/"+newPath) + case strings.HasPrefix(line, "--- "): + result = append(result, "--- a/"+newPath) + default: + result = append(result, line) + } + } + return result } func (self *patchTransformer) transformHunks() []*Hunk { diff --git a/pkg/gui/context/setup.go b/pkg/gui/context/setup.go index 8f498e6a9..ef1211313 100644 --- a/pkg/gui/context/setup.go +++ b/pkg/gui/context/setup.go @@ -60,8 +60,11 @@ func NewContextTree(c *ContextCommon) *ContextTree { "main", PATCH_BUILDING_MAIN_CONTEXT_KEY, func() []int { - filename := commitFilesContext.GetSelectedPath() - includedLineIndices, err := c.Git().Patch.PatchBuilder.GetFileIncLineIndices(filename) + file := commitFilesContext.GetSelectedFile() + if file == nil { + return nil + } + includedLineIndices, err := c.Git().Patch.PatchBuilder.GetFileIncLineIndices(file.Path, file.PreviousPath) if err != nil { c.Log.Error(err) return nil diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index eed9d02b9..f9fda0b93 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -191,11 +191,11 @@ func (self *CommitFilesController) GetOnRenderToMain() func() { } } -func (self *CommitFilesController) copyDiffToClipboard(path string, toastMessage string) error { +func (self *CommitFilesController) copyDiffToClipboard(paths []string, toastMessage string) error { from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) - cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, []string{path}, true) + cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, true) diff, err := cmdObj.RunWithOutput() if err != nil { return err @@ -263,7 +263,7 @@ func (self *CommitFilesController) openCopyMenu() error { copyFileDiffItem := &types.MenuItem{ Label: self.c.Tr.CopySelectedDiff, OnPress: func() error { - return self.copyDiffToClipboard(node.GetPath(), self.c.Tr.FileDiffCopiedToast) + return self.copyDiffToClipboard(self.pathsForDiff(node), self.c.Tr.FileDiffCopiedToast) }, DisabledReason: self.require(self.singleItemSelected())(), Keys: menuKey('s'), @@ -271,7 +271,7 @@ func (self *CommitFilesController) openCopyMenu() error { copyAllDiff := &types.MenuItem{ Label: self.c.Tr.CopyAllFilesDiff, OnPress: func() error { - return self.copyDiffToClipboard(".", self.c.Tr.AllFilesDiffCopiedToast) + return self.copyDiffToClipboard([]string{"."}, self.c.Tr.AllFilesDiffCopiedToast) }, DisabledReason: self.require(self.itemsSelected())(), Keys: menuKey('a'), @@ -348,7 +348,10 @@ func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileN for _, node := range selectedNodes { _ = node.ForEachFile(func(file *models.CommitFile) error { - filePaths = append(filePaths, file.GetPath()) + // For a rename we discard both the new and the old path, + // so that the new file is removed and the old one is + // restored. + filePaths = append(filePaths, file.Names()...) return nil }) } @@ -465,7 +468,7 @@ func (self *CommitFilesController) toggleForPatch(selectedNodes []*filetree.Comm for _, node := range selectedNodes { err := node.ForEachFile(func(file *models.CommitFile) error { - return patchOperationFunction(file.Path) + return patchOperationFunction(file.Path, file.PreviousPath) }) if err != nil { return err @@ -610,11 +613,16 @@ func (self *CommitFilesController) pathsForDiff(node *filetree.CommitFileNode) [ if !node.IsFile() && self.context().IsFiltering() { var paths []string _ = node.ForEachFile(func(file *models.CommitFile) error { - paths = append(paths, file.Path) + // For a rename we need to pass both paths so that git detects it as + // a rename rather than an unrelated delete and add. + paths = append(paths, file.Names()...) return nil }) return paths } + if file := node.GetFile(); file != nil { + return file.Names() + } return []string{node.GetPath()} } diff --git a/pkg/gui/controllers/helpers/patch_building_helper.go b/pkg/gui/controllers/helpers/patch_building_helper.go index 9369cca93..ac79ee8d7 100644 --- a/pkg/gui/controllers/helpers/patch_building_helper.go +++ b/pkg/gui/controllers/helpers/patch_building_helper.go @@ -66,20 +66,21 @@ func (self *PatchBuildingHelper) RefreshPatchBuildingPanel(opts types.OnFocusOpt } // get diff from commit file that's currently selected - path := self.c.Contexts().CommitFiles.GetSelectedPath() - if path == "" { + file := self.c.Contexts().CommitFiles.GetSelectedFile() + if file == nil { return } from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) - diff, err := self.c.Git().WorkingTree.ShowFileDiff(from, to, reverse, path, true) + diff, err := self.c.Git().WorkingTree.ShowFileDiff(from, to, reverse, file.Path, file.PreviousPath, true) if err != nil { return } secondaryDiff := self.c.Git().Patch.PatchBuilder.RenderPatchForFile(patch.RenderPatchForFileOpts{ - Filename: path, + Filename: file.Path, + PreviousPath: file.PreviousPath, Plain: false, Reverse: false, TurnAddedFilesIntoDiffAgainstEmptyFile: true, diff --git a/pkg/gui/controllers/patch_building_controller.go b/pkg/gui/controllers/patch_building_controller.go index dd8c89fff..5e4a17169 100644 --- a/pkg/gui/controllers/patch_building_controller.go +++ b/pkg/gui/controllers/patch_building_controller.go @@ -138,8 +138,8 @@ func (self *PatchBuildingController) toggleSelection() error { self.context().GetMutex().Lock() defer self.context().GetMutex().Unlock() - filename := self.c.Contexts().CommitFiles.GetSelectedPath() - if filename == "" { + file := self.c.Contexts().CommitFiles.GetSelectedFile() + if file == nil { return nil } @@ -152,7 +152,7 @@ func (self *PatchBuildingController) toggleSelection() error { return nil } - includedLineIndices, err := self.c.Git().Patch.PatchBuilder.GetFileIncLineIndices(filename) + includedLineIndices, err := self.c.Git().Patch.PatchBuilder.GetFileIncLineIndices(file.Path, file.PreviousPath) if err != nil { return err } @@ -164,7 +164,7 @@ func (self *PatchBuildingController) toggleSelection() error { } // add range of lines to those set for the file - if err := toggleFunc(filename, lineIndicesToToggle); err != nil { + if err := toggleFunc(file.Path, file.PreviousPath, lineIndicesToToggle); err != nil { // might actually want to return an error here self.c.Log.Error(err) } diff --git a/pkg/gui/controllers/rename_similarity_threshold_controller.go b/pkg/gui/controllers/rename_similarity_threshold_controller.go index 78b8bb7f4..e9bf13027 100644 --- a/pkg/gui/controllers/rename_similarity_threshold_controller.go +++ b/pkg/gui/controllers/rename_similarity_threshold_controller.go @@ -1,6 +1,7 @@ package controllers import ( + "errors" "fmt" "github.com/jesseduffield/lazygit/pkg/gui/context" @@ -49,6 +50,10 @@ func (self *RenameSimilarityThresholdController) Context() types.Context { } func (self *RenameSimilarityThresholdController) Increase() error { + if err := self.checkCanChangeThreshold(); err != nil { + return err + } + old_size := self.c.UserConfig().Git.RenameSimilarityThreshold if old_size < 100 { @@ -59,6 +64,10 @@ func (self *RenameSimilarityThresholdController) Increase() error { } func (self *RenameSimilarityThresholdController) Decrease() error { + if err := self.checkCanChangeThreshold(); err != nil { + return err + } + old_size := self.c.UserConfig().Git.RenameSimilarityThreshold if old_size > 5 { @@ -73,11 +82,23 @@ func (self *RenameSimilarityThresholdController) applyChange() error { currentContext := self.c.Context().CurrentSide() switch currentContext.GetKey() { - // we make an exception for our files context, because it actually need to refresh its state afterwards. + // we make an exception for the files and commit-files contexts, because + // they actually need to refresh their state afterwards: a changed threshold + // can turn a rename into a separate delete and add, or vice versa. case context.FILES_CONTEXT_KEY: self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) + case context.COMMIT_FILES_CONTEXT_KEY: + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMIT_FILES}}) default: currentContext.HandleRenderToMain() } return nil } + +func (self *RenameSimilarityThresholdController) checkCanChangeThreshold() error { + if self.c.Git().Patch.PatchBuilder.Active() { + return errors.New(self.c.Tr.CantChangeRenameThresholdError) + } + + return nil +} diff --git a/pkg/gui/presentation/files.go b/pkg/gui/presentation/files.go index cc0a93889..534229905 100644 --- a/pkg/gui/presentation/files.go +++ b/pkg/gui/presentation/files.go @@ -328,7 +328,8 @@ func fileNameAtDepth(node *filetree.Node[models.File], depth int, showRootItem b func commitFileNameAtDepth(node *filetree.Node[models.CommitFile], depth int) string { splitName := split(node.GetInternalPath()) - if depth == 0 && splitName[0] == "." { + showRootItem := splitName[0] == "." + if depth == 0 && showRootItem { if len(splitName) == 1 { return "/" } @@ -336,6 +337,20 @@ func commitFileNameAtDepth(node *filetree.Node[models.CommitFile], depth int) st } name := join(splitName[depth:]) + if node.File != nil && node.File.IsRename() { + splitPrevName := filetree.SplitFileTreePath(node.File.PreviousPath, showRootItem) + + prevName := node.File.PreviousPath + // if the file has just been renamed inside the same directory, we can shave off + // the prefix for the previous path too. Otherwise we'll keep it unchanged + sameParentDir := len(splitName) == len(splitPrevName) && join(splitName[0:depth]) == join(splitPrevName[0:depth]) + if sameParentDir { + prevName = join(splitPrevName[depth:]) + } + + return prevName + " → " + name + } + return name } diff --git a/pkg/gui/presentation/files_test.go b/pkg/gui/presentation/files_test.go index a5b01c156..c7e333682 100644 --- a/pkg/gui/presentation/files_test.go +++ b/pkg/gui/presentation/files_test.go @@ -151,6 +151,14 @@ func TestRenderCommitFileTree(t *testing.T) { showRootItem: true, expected: []string{"A test"}, }, + { + name: "renamed file", + files: []*models.CommitFile{ + {Path: "new.txt", PreviousPath: "old.txt", ChangeStatus: "R"}, + }, + showRootItem: false, + expected: []string{"R old.txt → new.txt"}, + }, { name: "big example", files: []*models.CommitFile{ @@ -219,7 +227,7 @@ M file1 } patchBuilder := patch.NewPatchBuilder( utils.NewDummyLog(), - func(from string, to string, reverse bool, filename string, plain bool) (string, error) { + func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) { return "", nil }, ) diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index be3886fbe..6f18842d5 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -819,6 +819,7 @@ type TranslationSet struct { SortCommits string SortCommitsTooltip string CantChangeContextSizeError string + CantChangeRenameThresholdError string OpenCommitInBrowser string ViewBisectOptions string ConfirmRevertCommit string @@ -1966,6 +1967,7 @@ func EnglishTranslationSet() *TranslationSet { SortCommits: "Commit sort order", SortCommitsTooltip: "Change the sort order of the commits in the commit log.\n\nThe default can be changed in the config file with the key 'git.log.sortOrder'.", CantChangeContextSizeError: "Cannot change context while in patch building mode because we were too lazy to support it when releasing the feature. If you really want it, please let us know!", + CantChangeRenameThresholdError: "Cannot change the rename similarity threshold while in patch building mode, because the custom patch can't cope with a rename turning into a delete and add underneath it.", OpenCommitInBrowser: "Open commit in browser", ViewBisectOptions: "View bisect options", ConfirmRevertCommit: "Are you sure you want to revert {{.selectedCommit}}?", diff --git a/pkg/integration/tests/commit/discard_renamed_file.go b/pkg/integration/tests/commit/discard_renamed_file.go new file mode 100644 index 000000000..01e729425 --- /dev/null +++ b/pkg/integration/tests/commit/discard_renamed_file.go @@ -0,0 +1,57 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var DiscardRenamedFile = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Discard a renamed file from an old commit; both the new and the old path are handled so the rename is undone", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("original", "line1\nline2\nline3\nline4\nline5\n") + shell.CreateFileAndAdd("other", "other content\n") + shell.Commit("first commit") + + shell.RenameFileInGit("original", "renamed") + shell.UpdateFileAndAdd("renamed", "line1\nline2 changed\nline3\nline4\nline5\n") + shell.Commit("rename with modification") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ). + PressEnter() + + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("original → renamed").IsSelected(), + ). + Press(keys.Universal.Remove) + + t.ExpectPopup().Confirmation(). + Title(Equals("Discard file changes")). + Content(Contains("Are you sure you want to discard changes to the selected file(s) from this commit?")). + Confirm() + + // The rename is undone: the commit no longer touches any file. (If only + // the new path were discarded, the commit would still delete the old + // path and show "D original" here instead.) + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("(none)"), + ). + PressEscape() + + // The working tree is clean; the original file is back at HEAD. + t.Views().Files(). + IsEmpty() + }, +}) diff --git a/pkg/integration/tests/patch_building/copy_renamed_file_diff.go b/pkg/integration/tests/patch_building/copy_renamed_file_diff.go new file mode 100644 index 000000000..6343527e5 --- /dev/null +++ b/pkg/integration/tests/patch_building/copy_renamed_file_diff.go @@ -0,0 +1,60 @@ +package patch_building + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +// note: this is required to simulate the clipboard during CI +func expectClipboard(t *TestDriver, matcher *TextMatcher) { + defer t.Shell().DeleteFile("clipboard") + + t.FileSystem().FileContent("clipboard", matcher) +} + +var CopyRenamedFileDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Copy the diff of a renamed file to the clipboard; the diff shows the rename rather than a delete and add", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) { + config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("original", "line1\nline2\nline3\nline4\nline5\n") + shell.Commit("first commit") + + shell.RenameFileInGit("original", "renamed") + shell.UpdateFileAndAdd("renamed", "line1\nline2 changed\nline3\nline4\nline5\n") + shell.Commit("rename with modification") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ). + PressEnter() + + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("original → renamed").IsSelected(), + ). + Press(keys.Files.CopyFileInfoToClipboard) + + t.ExpectPopup().Menu(). + Title(Equals("Copy to clipboard")). + Select(Contains("Diff of selected file")). + Confirm() + + t.ExpectToast(Contains("File diff copied to clipboard")) + + expectClipboard(t, + Contains("rename from original"). + Contains("rename to renamed"). + Contains("-line2"). + Contains("+line2 changed"), + ) + }, +}) diff --git a/pkg/integration/tests/patch_building/rename_similarity_threshold_change.go b/pkg/integration/tests/patch_building/rename_similarity_threshold_change.go new file mode 100644 index 000000000..d36e0450b --- /dev/null +++ b/pkg/integration/tests/patch_building/rename_similarity_threshold_change.go @@ -0,0 +1,66 @@ +package patch_building + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RenameSimilarityThresholdChange = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Changing the rename similarity threshold refreshes the commit files panel, but is disabled while building a patch", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("original", "one\ntwo\nthree\nfour\nfive\n") + shell.Commit("add original") + + shell.RenameFileInGit("original", "renamed") + shell.UpdateFileAndAdd("renamed", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("change name and contents") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("change name and contents").IsSelected(), + Contains("add original"), + ). + PressEnter() + + // At the default threshold of 50% the 50%-similar change is not detected + // as a rename. + t.Views().CommitFiles(). + IsFocused(). + Lines( + Equals("▼ /"), + Equals(" D original"), + Equals(" A renamed"), + ). + // Lowering the threshold turns it into a rename; the panel refreshes. + Press(keys.Universal.DecreaseRenameSimilarityThreshold). + Tap(func() { + t.ExpectToast(Equals("Changed rename similarity threshold to 45%")) + }). + Lines( + Equals("R original → renamed"), + ). + // Start building a patch from the renamed file. + PressPrimaryAction(). + Tap(func() { + t.Views().Information().Content(Contains("Building patch")) + + // Changing the threshold is now disabled: the patch builder + // can't cope with the rename turning into a delete and add. + t.Views().CommitFiles(). + Press(keys.Universal.IncreaseRenameSimilarityThreshold) + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Contains("Cannot change the rename similarity threshold while in patch building mode")). + Confirm() + }). + // The file is unchanged: still a rename, still in the patch. + Lines( + Contains("original → renamed").IsSelected(), + ) + }, +}) diff --git a/pkg/integration/tests/patch_building/renamed_file_partial.go b/pkg/integration/tests/patch_building/renamed_file_partial.go new file mode 100644 index 000000000..3c37c13a2 --- /dev/null +++ b/pkg/integration/tests/patch_building/renamed_file_partial.go @@ -0,0 +1,73 @@ +package patch_building + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RenamedFilePartial = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Select part of a renamed file's changes into a custom patch and remove it from the commit, keeping the rename in place", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("original", "line1\nline2\nline3\nline4\nline5\n") + shell.Commit("first commit") + + shell.RenameFileInGit("original", "renamed") + shell.UpdateFileAndAdd("renamed", "line1\nline2 changed\nline3\nline4\nline5\n") + shell.Commit("rename with modification") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ). + PressEnter() + + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("original → renamed").IsSelected(), + ). + PressEnter() + + // The main view shows the rename together with its content change. + t.Views().PatchBuilding(). + IsFocused(). + Content(Contains("rename from original").Contains("rename to renamed")). + ContainsLines( + Contains(" line1"), + Contains("-line2"), + Contains("+line2 changed"), + Contains(" line3"), + ). + // Add the hunk (a line selection, as opposed to adding the whole + // file), so this is a partial patch. + PressPrimaryAction() + + t.Views().Information().Content(Contains("Building patch")) + + t.Common().SelectPatchOption(Contains("Remove patch from original commit")) + + // The rename is preserved; only the content change is gone, so the file + // is still shown as a rename but now has no content change. + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("original → renamed").IsSelected(), + ) + + t.Views().Main(). + Content(DoesNotContain("line2 changed")) + + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ) + }, +}) diff --git a/pkg/integration/tests/patch_building/renamed_file_whole.go b/pkg/integration/tests/patch_building/renamed_file_whole.go new file mode 100644 index 000000000..f4151a766 --- /dev/null +++ b/pkg/integration/tests/patch_building/renamed_file_whole.go @@ -0,0 +1,62 @@ +package patch_building + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RenamedFileWhole = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Add a whole renamed file to a custom patch and remove it from the commit, taking the rename with it", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("original", "line1\nline2\nline3\nline4\nline5\n") + shell.Commit("first commit") + + shell.RenameFileInGit("original", "renamed") + shell.UpdateFileAndAdd("renamed", "line1\nline2 changed\nline3\nline4\nline5\n") + shell.Commit("rename with modification") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ). + PressEnter() + + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("original → renamed").IsSelected(), + ). + PressPrimaryAction() + + t.Views().Information().Content(Contains("Building patch")) + + // The whole file is added, so the patch carries the rename itself. + t.Views().Secondary(). + ContainsLines( + Contains("rename from original"), + Contains("rename to renamed"), + ) + + t.Common().SelectPatchOption(Contains("Remove patch from original commit")) + + // The rename went with the patch, so the commit no longer touches the file. + t.Views().CommitFiles(). + IsFocused(). + Lines( + Contains("(none)"), + ) + + t.Views().Commits(). + Focus(). + Lines( + Contains("rename with modification").IsSelected(), + Contains("first commit"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 380aca2b6..abf13073e 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -128,6 +128,7 @@ var tests = []*components.IntegrationTest{ commit.CreateTag, commit.DisableCopyCommitMessageBody, commit.DiscardOldFileChanges, + commit.DiscardRenamedFile, commit.DiscardSubmoduleChanges, commit.DoNotShowBranchMarkerForHeadCommit, commit.FailHooksThenCommitNoHooks, @@ -351,6 +352,7 @@ var tests = []*components.IntegrationTest{ patch_building.ApplyInReverseWithConflict, patch_building.ApplyWithModifiedFileConflict, patch_building.ApplyWithModifiedFileNoConflict, + patch_building.CopyRenamedFileDiff, patch_building.DiscardLinesFromCommit, patch_building.EditLineInPatchBuildingPanel, patch_building.MoveRangeToIndex, @@ -373,6 +375,9 @@ var tests = []*components.IntegrationTest{ patch_building.MoveToNewCommitPartialHunk, patch_building.RemoveFromCommit, patch_building.RemovePartsOfAddedFile, + patch_building.RenameSimilarityThresholdChange, + patch_building.RenamedFilePartial, + patch_building.RenamedFileWhole, patch_building.ResetWithEscape, patch_building.SelectAllFiles, patch_building.SpecificSelection, From aa46a69f77bdc063edbac586b33f84e6382feefc Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 13:03:47 +0200 Subject: [PATCH 037/218] Remove unused function ExpectClipboard This can't be used because it wouldn't work on CI; delete it so that coding agents aren't tempted to use it. --- pkg/integration/components/test_driver.go | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/pkg/integration/components/test_driver.go b/pkg/integration/components/test_driver.go index 301ab3862..376b0f4d6 100644 --- a/pkg/integration/components/test_driver.go +++ b/pkg/integration/components/test_driver.go @@ -4,7 +4,6 @@ import ( "fmt" "time" - "github.com/atotto/clipboard" "github.com/jesseduffield/lazygit/pkg/config" integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types" ) @@ -125,17 +124,6 @@ func (self *TestDriver) ExpectToast(matcher *TextMatcher) *TestDriver { return self } -func (self *TestDriver) ExpectClipboard(matcher *TextMatcher) { - self.assertWithRetries(func() (bool, string) { - text, err := clipboard.ReadAll() - if err != nil { - return false, "Error occurred when reading from clipboard: " + err.Error() - } - ok, _ := matcher.test(text) - return ok, fmt.Sprintf("Expected clipboard to match %s, but got %s", matcher.name(), text) - }) -} - func (self *TestDriver) ExpectSearch() *SearchDriver { self.inSearch() From 8e36fba91e4c6c824ae0962ec853d7cd43797fc0 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 14:36:49 +0200 Subject: [PATCH 038/218] Update translations from Crowdin --- docs-master/keybindings/Keybindings_nl.md | 122 +++++++------- pkg/i18n/translations/ja.json | 8 - pkg/i18n/translations/ko.json | 1 - pkg/i18n/translations/nl.json | 193 +++++++++++++++++++++- pkg/i18n/translations/pl.json | 8 - pkg/i18n/translations/pt.json | 5 - pkg/i18n/translations/ru.json | 2 - pkg/i18n/translations/zh-CN.json | 11 +- pkg/i18n/translations/zh-TW.json | 8 - 9 files changed, 251 insertions(+), 107 deletions(-) diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index 7f1216b5f..0eb61729b 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -10,15 +10,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` , K, (fn+up/shift+k) `` | Scroll naar beneden vanaf hoofdpaneel | | | `` , J, (fn+down/shift+j) `` | Scroll naar beneden vanaf hoofdpaneel | | | `` @ `` | View command log options | View options for the command log e.g. show/hide the command log and focus the command log. | -| `` P `` | Push | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. | -| `` p `` | Pull | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. | +| `` P `` | Push | Push de huidige branch naar de bijbehorende upstream-branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren. | +| `` p `` | Pull | Pull wijzigingen van de remote voor de huidige branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren. | | `` ) `` | Increase rename similarity threshold | Increase the similarity threshold for a deletion and addition pair to be treated as a rename.

The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. | | `` ( `` | Decrease rename similarity threshold | Decrease the similarity threshold for a deletion and addition pair to be treated as a rename.

The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. | | `` } `` | Increase diff context size | Increase the amount of the context shown around changes in the diff view.

The default can be changed in the config file with the key 'git.diffContextSize'. | | `` { `` | Decrease diff context size | Decrease the amount of the context shown around changes in the diff view.

The default can be changed in the config file with the key 'git.diffContextSize'. | | `` : `` | Execute shell command | Bring up a prompt where you can enter a shell command to execute. | | `` `` | Bekijk aangepaste patch opties | | -| `` m `` | Bekijk merge/rebase opties | View options to abort/continue/skip the current merge/rebase. | +| `` m `` | Bekijk merge/rebase opties | Toon abort/continue/skip opties voor huidige merge/rebase. | | `` R `` | Verversen | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | Volgende scherm modus (normaal/half/groot) | | | `` _ `` | Vorige scherm modus | | @@ -28,10 +28,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` ? `` | Open menu | | | `` `` | Bekijk scoping opties | View options for filtering the commit log, so that only commits matching the filter are shown. | | `` W, `` | Open diff menu | View options relating to diffing two refs e.g. diffing against selected ref, entering ref to diff against, and reversing the diff direction. | -| `` q, `` | Quit | | -| `` `` | Suspend the application | | +| `` q, `` | Afsluiten | | +| `` `` | Pauzeer de applicatie | | | `` `` | Toggle whitespace | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | -| `` `` | Verander config bestand | Open file in external editor. | +| `` `` | Verander config bestand | Open bestand in externe editor. | | `` z `` | Ongedaan maken (via reflog) (experimenteel) | The reflog will be used to determine what git command to run to undo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | | `` Z `` | Redo (via reflog) (experimenteel) | The reflog will be used to determine what git command to run to redo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | @@ -47,8 +47,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Range select down | | | `` `` | Range select up | | | `` / `` | Start met zoeken | | -| `` H `` | Scroll left | | -| `` L `` | Scroll right | | +| `` H `` | Scroll naar links | | +| `` L `` | Scroll naar rechts | | | `` ] `` | Volgende tabblad | | | `` [ `` | Vorige tabblad | | @@ -58,15 +58,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer de bestandsnaam naar het klembord | | | `` `` | Toggle staged | Toggle staged for selected file. | -| `` `` | Filter files by status | | -| `` y `` | Copy to clipboard | | -| `` c `` | Commit veranderingen | Commit staged changes. | +| `` `` | Filter bestanden op status | | +| `` y `` | Kopieer naar klembord | | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | | `` w `` | Commit veranderingen zonder pre-commit hook | | | `` A `` | Wijzig laatste commit | | | `` C `` | Commit veranderingen met de git editor | | -| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | -| `` e `` | Edit | Open file in external editor. | -| `` o `` | Open bestand | Open file in default application. | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | +| `` e `` | Edit | Open bestand in externe editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | | `` i `` | Ignore or exclude file | | | `` r `` | Refresh bestanden | | | `` s `` | Stash | Stash all changes. For other variations of stashing, use the view stash options keybinding. | @@ -75,13 +75,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Stage individuele hunks/lijnen | If the selected item is a file, focus the staging view so you can stage individual hunks/lines. If the selected item is a directory, collapse/expand it. | | `` d `` | Bekijk 'veranderingen ongedaan maken' opties | View options for discarding changes to the selected file. | | `` g `` | Bekijk upstream reset opties | | -| `` D `` | Reset | View reset options for working tree (e.g. nuking the working tree). | +| `` D `` | Resetten | View reset options for working tree (e.g. nuking the working tree). | | `` ` `` | Toggle bestandsboom weergave | Toggle file view between flat and tree layout. Flat layout shows all file paths in a single list, tree layout groups files by directory.

The default can be changed in the config file with the key 'gui.showFileTree'. | -| `` `` | Open external diff tool (git difftool) | | -| `` M `` | View merge conflict options | View options for resolving merge conflicts. | +| `` `` | Open externe diff applicatie (git difftool) | | +| `` M `` | Bekijk merge conflict opties | Bekijk opties voor het oplossen van mergeconflicten. | | `` f `` | Fetch | Fetch changes from remote. | | `` - `` | Collapse all files | Collapse all directories in the files tree | -| `` = `` | Expand all files | Expand all directories in the file tree | +| `` = `` | Vouw alle bestanden uit | Vouw alle mappen in de bestandsstructuur uit | | `` 0 `` | Focus main view | | | `` / `` | Filter the current view by text | | @@ -91,7 +91,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Bevestig | | | `` `` | Sluiten | | -| `` `` | Copy to clipboard | | +| `` `` | Kopieer naar klembord | | ## Branches @@ -99,19 +99,19 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer branch name naar klembord | | | `` i `` | Laat git-flow opties zien | | -| `` `` | Uitchecken | Checkout selected item. | +| `` `` | Uitchecken | Geselecteerd item uitchecken. | | `` n `` | Nieuwe branch | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | | `` w `` | New worktree | | | `` o `` | Maak een pull-request | | | `` O `` | Bekijk opties voor pull-aanvraag | | | `` G `` | Open pull request in browser | | | `` `` | Kopieer de URL van het pull-verzoek naar het klembord | | | `` c `` | Uitchecken bij naam | Checkout by name. In the input box you can enter '-' to switch to the previous branch. | -| `` - `` | Checkout previous branch | | +| `` - `` | Vorige branch uitchecken | | | `` F `` | Forceer checkout | Force checkout selected branch. This will discard all local changes in your working directory before checking out the selected branch. | -| `` d `` | Delete | View delete options for local/remote branch. | -| `` r `` | Rebase branch | Rebase the checked-out branch onto the selected branch. | +| `` d `` | Verwijderen | View delete options for local/remote branch. | +| `` r `` | Rebase branch | Rebase de uitgecheckte branch bovenop de geselecteerde branch. | | `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` f `` | Fast-forward deze branch vanaf zijn upstream | Fast-forward selected branch from its upstream. | | `` T `` | Creëer tag | | @@ -119,7 +119,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Bekijk reset opties | | | `` R `` | Hernoem branch | | | `` u `` | View upstream options | View options relating to the branch's upstream e.g. setting/unsetting the upstream and resetting to the upstream. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | | `` / `` | Filter the current view by text | | @@ -136,18 +136,18 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Kopieer de bestandsnaam naar het klembord | | -| `` y `` | Copy to clipboard | | +| `` y `` | Kopieer naar klembord | | | `` c `` | Uitchecken | Bestand uitchecken | | `` d `` | Bekijk 'veranderingen ongedaan maken' opties | Uitsluit deze commit zijn veranderingen aan dit bestand | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Edit | Open file in external editor. | -| `` `` | Open external diff tool (git difftool) | | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Edit | Open bestand in externe editor. | +| `` `` | Open externe diff applicatie (git difftool) | | | `` `` | Toggle bestand inbegrepen in patch | Toggle whether the file is included in the custom patch. See https://github.com/jesseduffield/lazygit#rebase-magic-custom-patches. | | `` a `` | Toggle all files | Add/remove all commit's files to custom patch. See https://github.com/jesseduffield/lazygit#rebase-magic-custom-patches. | | `` `` | Enter bestand om geselecteerde regels toe te voegen aan de patch | If a file is selected, enter the file so that you can add/remove individual lines to the custom patch. If a directory is selected, toggle the directory. | | `` ` `` | Toggle bestandsboom weergave | Toggle file view between flat and tree layout. Flat layout shows all file paths in a single list, tree layout groups files by directory.

The default can be changed in the config file with the key 'gui.showFileTree'. | | `` - `` | Collapse all files | Collapse all directories in the files tree | -| `` = `` | Expand all files | Expand all directories in the file tree | +| `` = `` | Vouw alle bestanden uit | Vouw alle mappen in de bestandsstructuur uit | | `` 0 `` | Focus main view | | | `` / `` | Filter the current view by text | | @@ -183,11 +183,11 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | | `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | @@ -219,9 +219,9 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` , h `` | Selecteer voorgaand conflict | | | `` , l `` | Selecteer volgende conflict | | | `` z `` | Ongedaan maken | Undo last merge conflict resolution. | -| `` e `` | Verander bestand | Open file in external editor. | -| `` o `` | Open bestand | Open file in default application. | -| `` M `` | View merge conflict options | View options for resolving merge conflicts. | +| `` e `` | Verander bestand | Open bestand in externe editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` M `` | Bekijk merge conflict opties | Bekijk opties voor het oplossen van mergeconflicten. | | `` `` | Ga terug naar het bestanden paneel | | ## Normaal @@ -243,8 +243,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle drag selecteer | | | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` `` | Copy selected text to clipboard | | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Verander bestand | Open file in external editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Voeg toe/verwijder lijn(en) in patch | | | `` d `` | Remove lines from commit | Remove the selected lines from this commit. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes these lines. | | `` `` | Sluit lijn-bij-lijn modus | | @@ -259,12 +259,12 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | | `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | @@ -275,16 +275,16 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Kopieer branch name naar klembord | | -| `` `` | Uitchecken | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | +| `` `` | Uitchecken | Geselecteerde remote branch uitchecken als nieuwe locale branch of als detached head. | | `` n `` | Nieuwe branch | | | `` w `` | New worktree | | | `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) | -| `` r `` | Rebase branch | Rebase the checked-out branch onto the selected branch. | -| `` d `` | Delete | Delete the remote branch from the remote. | -| `` u `` | Set as upstream | Stel in als upstream van uitgecheckte branch | +| `` r `` | Rebase branch | Rebase de uitgecheckte branch bovenop de geselecteerde branch. | +| `` d `` | Verwijderen | Delete the remote branch from the remote. | +| `` u `` | Instellen als upstream | Stel in als upstream van uitgecheckte branch | | `` s `` | Sort order | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | | `` / `` | Filter the current view by text | | @@ -293,9 +293,9 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| -| `` `` | View branches | | +| `` `` | Bekijk branches | | | `` n `` | Voeg een nieuwe remote toe | | -| `` d `` | Remove | Remove the selected remote. Any local branches tracking a remote branch from the remote will be unaffected. | +| `` d `` | Verwijderen | Remove the selected remote. Any local branches tracking a remote branch from the remote will be unaffected. | | `` e `` | Edit | Wijzig remote | | `` f `` | Fetch | Fetch remote | | `` F `` | Add fork remote | Quickly add a fork remote by replacing the owner in the origin URL and optionally check out a branch from new remote. | @@ -320,15 +320,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy selected text to clipboard | | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Verander bestand | Open file in external editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Ga terug naar het bestanden paneel | | | `` `` | Ga naar een ander paneel | Switch to other view (staged/unstaged changes). | | `` E `` | Edit hunk | Edit selected hunk in external editor. | -| `` c `` | Commit veranderingen | Commit staged changes. | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | | `` w `` | Commit veranderingen zonder pre-commit hook | | | `` C `` | Commit veranderingen met de git editor | | -| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | | `` / `` | Start met zoeken | | ## Stash @@ -340,7 +340,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` d `` | Laten vallen | Remove the stash entry from the stash list. | | `` n `` | Nieuwe branch | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | | `` w `` | New worktree | | -| `` r `` | Rename stash | | +| `` r `` | Hernoem stash | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | | `` / `` | Filter the current view by text | | @@ -349,7 +349,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| -| `` e `` | Verander config bestand | Open file in external editor. | +| `` e `` | Verander config bestand | Open bestand in externe editor. | | `` u `` | Check voor updates | | | `` `` | Wissel naar een recente repo | | | `` a `` | Show/cycle all branch logs | | @@ -365,12 +365,12 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | | `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | @@ -382,7 +382,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer submodule naam naar klembord | | | `` `` | Enter | Enter submodule | -| `` d `` | Remove | Remove the selected submodule and its corresponding directory. | +| `` d `` | Verwijderen | Remove the selected submodule and its corresponding directory. | | `` u `` | Update | Update selected submodule. | | `` n `` | Voeg nieuwe submodule toe | | | `` e `` | Update submodule URL | | @@ -395,13 +395,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Copy tag to clipboard | | -| `` `` | Uitchecken | Checkout the selected tag as a detached HEAD. | +| `` `` | Uitchecken | Geselecteerde tag uitchecken als detached HEAD. | | `` n `` | Creëer tag | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | | `` w `` | New worktree | | -| `` d `` | Delete | View delete options for local/remote tag. | +| `` d `` | Verwijderen | View delete options for local/remote tag. | | `` P `` | Push tag | Push the selected tag to a remote. You'll be prompted to select a remote. | -| `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | -| `` `` | Open external diff tool (git difftool) | | +| `` g `` | Resetten | View reset options (soft/mixed/hard) for resetting onto selected item. | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | | `` / `` | Filter the current view by text | | @@ -412,6 +412,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` n `` | New worktree | | | `` `` | Switch | Switch to the selected worktree. | -| `` o `` | Open in editor | | -| `` d `` | Remove | Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory. | +| `` o `` | Openen in editor | | +| `` d `` | Verwijderen | Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory. | | `` / `` | Filter the current view by text | | diff --git a/pkg/i18n/translations/ja.json b/pkg/i18n/translations/ja.json index ff9d804e5..593e253fb 100644 --- a/pkg/i18n/translations/ja.json +++ b/pkg/i18n/translations/ja.json @@ -207,7 +207,6 @@ "StashChanges": "変更をスタッシュ(一時保存)", "RenameStash": "スタッシュの名前を変更", "RenameStashPrompt": "スタッシュの名前を変更: {{.stashName}}", - "OpenConfig": "設定ファイルを開く", "EditConfig": "設定ファイルを編集", "ForcePush": "強制プッシュ", "ForcePushPrompt": "ローカルブランチはリモートブランチから分岐しています。キャンセルするには{{.cancelKey}}を、強制プッシュするには{{.confirmKey}}を押してください。", @@ -276,7 +275,6 @@ "ViewConflictsMenuItem": "コンフリクトを表示", "AbortMenuItem": "%s を中止", "PickHunk": "ハンクを選択", - "PickAllHunks": "すべてのハンクを選択", "ViewMergeRebaseOptions": "マージ/リベースオプションを表示", "ViewMergeRebaseOptionsTooltip": "現在のマージ/リベースを中止/継続/スキップするオプションを表示します。", "ViewMergeOptions": "マージオプションを表示", @@ -770,7 +768,6 @@ "DetachingWorktree": "ワークツリーをデタッチ中", "WorktreesTitle": "ワークツリー", "WorktreeTitle": "ワークツリー", - "RemoveWorktreePrompt": "ワークツリー '{{.worktreeName}}' を削除してよろしいですか?", "RemovingWorktree": "ワークツリーを削除中", "AddingWorktree": "ワークツリーを追加中", "CantDeleteCurrentWorktree": "現在のワークツリーは削除できません!", @@ -780,13 +777,8 @@ "MissingWorktree": "(見つかりません)", "NewWorktree": "新しいワークツリー", "NewWorktreePath": "新しいワークツリーのパス", - "NewWorktreeBase": "新しいワークツリーのベース参照", "RemoveWorktreeTooltip": "選択したワークツリーを削除します。これはワークツリーのディレクトリとワークツリーに関するメタデータの両方を.gitディレクトリから削除します。", "NewBranchName": "新しいブランチ名", - "NewBranchNameLeaveBlank": "新しいブランチ名({{.default}} をチェックアウトするには空白のままにしてください)", - "ViewWorktreeOptions": "ワークツリーオプションを表示", - "CreateWorktreeFrom": "{{.ref}} からワークツリーを作成", - "CreateWorktreeFromDetached": "{{.ref}} からワークツリーを作成(デタッチド)", "LcWorktree": "ワークツリー", "ChangingDirectoryTo": "ディレクトリを {{.path}} に変更中", "Name": "名前", diff --git a/pkg/i18n/translations/ko.json b/pkg/i18n/translations/ko.json index 1de57315e..dd02302ba 100644 --- a/pkg/i18n/translations/ko.json +++ b/pkg/i18n/translations/ko.json @@ -101,7 +101,6 @@ "StashApply": "Stash 적용", "SureApplyStashEntry": "정말로 Stash를 적용하시겠습니까?", "StashChanges": "변경을 Stash", - "OpenConfig": "설정 파일 열기", "EditConfig": "설정 파일 수정", "ForcePush": "강제 푸시", "ForcePushPrompt": "브랜치가 원격 브랜치에서 분기하고 있습니다. 'esc'를 눌러 취소하거나, 'enter'를 눌러 강제로 푸시하세요.", diff --git a/pkg/i18n/translations/nl.json b/pkg/i18n/translations/nl.json index 93a2dbe9e..e6369d85a 100644 --- a/pkg/i18n/translations/nl.json +++ b/pkg/i18n/translations/nl.json @@ -5,30 +5,81 @@ "BranchesTitle": "Branches", "CommitsTitle": "Commits", "StashTitle": "Stash", + "SnakeTitle": "Snake", + "EasterEgg": "Easter egg", "UnstagedChanges": "Unstaged wijzigingen", "StagedChanges": "Staged wijzigingen", "StagingTitle": "Staging", "MergingTitle": "Mergen", "NormalTitle": "Normaal", + "LogTitle": "Log", + "LogXOfYTitle": "Log (%d van %d)", "CommitSummary": "Commitbericht", "CredentialsUsername": "Gebruikersnaam", "CredentialsPassword": "Wachtwoord", "CredentialsPassphrase": "Voer een wachtwoordzin in voor de SSH-sleutel", + "CredentialsPIN": "Voer PIN voor SSH sleutel in", + "CredentialsToken": "Voer Token voor SSH sleutel in", "PassUnameWrong": "Wachtwoord en/of gebruikersnaam verkeerd", "Commit": "Commit veranderingen", + "CommitTooltip": "Commit gestagede wijzigingen.", "AmendLastCommit": "Wijzig laatste commit", "AmendLastCommitTitle": "Wijzig laatste commit", "SureToAmend": "Weet je zeker dat je de laatste commit wilt wijzigen? U kunt het commit-bericht wijzigen vanuit het commits-paneel.", "NoCommitToAmend": "Er is geen commits om te wijzigen.", "CommitChangesWithEditor": "Commit veranderingen met de git editor", + "FindBaseCommitForFixupTooltip": "Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: ", + "BaseCommitIsNotInCurrentView": "Basis commit is niet zichtbaar", + "StatusTitle": "Status", "GlobalTitle": "Globale sneltoetsen", "Execute": "Uitvoeren", "Stage": "Toggle staged", "ToggleStagedAll": "Toggle staged alle", "ToggleTreeView": "Toggle bestandsboom weergave", + "OpenDiffTool": "Open externe diff applicatie (git difftool)", + "OpenMergeTool": "Open externe merge applicatie", "Refresh": "Verversen", + "Push": "Push", + "Pull": "Pull", + "PushTooltip": "Push de huidige branch naar de bijbehorende upstream-branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren.", + "PullTooltip": "Pull wijzigingen van de remote voor de huidige branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren.", + "FileFilter": "Filter bestanden op status", + "CopyToClipboardMenu": "Kopieer naar klembord", + "CopyFileName": "Bestandsnaam", + "CopyRelativeFilePath": "Relatief pad", + "CopyAbsoluteFilePath": "Absoluut pad", + "CopyFileDiffTooltip": "Als er gestagede items zijn neemt dit commando alleen deze items mee. Zo niet, neemt het alle niet-gestagede items mee.", + "CopySelectedDiff": "Diff van geselecteerde bestand", + "CopyAllFilesDiff": "Diff van alle bestanden", + "CopyFileContent": "Inhoud van geselecteerde bestand", + "NoContentToCopyError": "Er is niks om te kopiëren", + "FileNameCopiedToast": "Bestandsnaam gekopieerd naar klembord", + "FilePathCopiedToast": "Bestandspad gekopieerd naar klembord", + "FileDiffCopiedToast": "Diff van bestand gekopieerd naar klembord", + "AllFilesDiffCopiedToast": "Diff van alle bestanden gekopieerd naar klembord", + "FileContentCopiedToast": "Bestandsinhoud gekopieerd naar klembord", + "FilterStagedFiles": "Toon alleen gestagede bestanden", + "FilterUnstagedFiles": "Toon alleen niet-gestagede bestanden", + "FilterTrackedFiles": "Toon alleen getrackte bestanden", + "FilterUntrackedFiles": "Toon alleen niet-getrackte bestanden", + "NoFilter": "Geen filter", + "FilterLabelStagedFiles": "(alleen gestaged)", + "FilterLabelUnstagedFiles": "(alleen niet-gestaged)", + "FilterLabelTrackedFiles": "(alleen getrackt)", + "FilterLabelUntrackedFiles": "(alleen niet-getrackt)", + "FilterLabelConflictingFiles": "(alleen conflicten)", "MergeConflictsTitle": "Merge conflicten", + "MergeConflictDescription_UD": "Conflict: dit bestand is gewijzigd in de current changes en verwijderd in incoming changes.\n\nDe meest waarschijnlijke oplossing is om dit bestand te verwijderen nadat de current changes wijzigingen handmatig zijn toegepast op een andere plaats in de code.", + "MergeConflictIncomingDiff": "Inkomende wijziging:", + "MergeConflictCurrentDiff": "Huidige wijzigingen:", + "MergeConflictPressEnterToResolve": "Druk op %s om op te lossen.", + "MergeConflictKeepFile": "Behoud bestanden", + "MergeConflictDeleteFile": "Bestand verwijderen", "Checkout": "Uitchecken", + "CheckoutTooltip": "Geselecteerd item uitchecken.", + "CantCheckoutBranchWhilePulling": "Je kan geen andere branch uitchecken tijdens het pullen van de huidige branch", + "TagCheckoutTooltip": "Geselecteerde tag uitchecken als detached HEAD.", + "RemoteBranchCheckoutTooltip": "Geselecteerde remote branch uitchecken als nieuwe locale branch of als detached head.", "NoChangedFiles": "Geen veranderde bestanden", "SoftReset": "Zacht reset", "AlreadyCheckedOutBranch": "Je hebt deze branch al uitgecheckt", @@ -37,54 +88,94 @@ "BranchName": "Branch naam", "NewBranchNameBranchOff": "Nieuw branch naam (Branch is afgeleid van '{{.branchName}}')", "CantDeleteCheckOutBranch": "Je kan een uitgecheckte branch niet verwijderen!", + "DeleteBranchTitle": "Verwijder branch '{{.selectedBranchName}}'?", + "DeleteBranchesTitle": "Geselecteerde branches verwijderen?", + "DeleteLocalBranch": "Lokale branch verwijderen", + "DeleteLocalBranches": "Lokale branches verwijderen", + "DeleteRemoteBranchPrompt": "Weet je zeker dat je de remote branch '{{.selectedBranchName}}' wilt verwijderen uit '{{.upstream}}'?", + "ForceDeleteBranchTitle": "Forceer verwijderen van branch", "ForceDeleteBranchMessage": "Weet je zeker dat je branch '{{.selectedBranchName}}' geforceerd wil verwijderen?", "RebaseBranch": "Rebase branch", + "RebaseBranchTooltip": "Rebase de uitgecheckte branch bovenop de geselecteerde branch.", "CantRebaseOntoSelf": "Je kan niet een branch rebasen op zichzelf", "CantMergeBranchIntoItself": "Je kan niet een branch in zichzelf mergen", "ForceCheckout": "Forceer checkout", "CheckoutByName": "Uitchecken bij naam", + "CheckoutPreviousBranch": "Vorige branch uitchecken", + "RemoteBranchCheckoutTitle": "{{.branchName}} uitchecken", + "RemoteBranchCheckoutPrompt": "Hoe wil je deze branch uitchecken?", + "CheckoutTypeNewBranch": "Nieuwe lokale branch", + "CheckoutTypeDetachedHead": "Detached head", "NewBranch": "Nieuwe branch", + "MoveCommitsToNewBranch": "Verplaats commits naar nieuwe branch", + "MoveCommitsToNewBranchTooltip": "Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.\n\nLet op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen).", + "CannotMoveCommitsFromDetachedHead": "Kan geen commits verplaatsen van een detached head", + "CannotMoveCommitsNoUpstream": "Kan geen commits verplaatsen vanaf een branch die geen upstream-branch heeft", + "CannotMoveCommitsBehindUpstream": "Kan geen commits verplaatsen van een branch die achterloopt zijn upstream-branch", "NoBranchesThisRepo": "Geen branches voor deze repo", "CommitWithoutMessageErr": "Je kan geen commit maken zonder commit bericht", "Close": "Sluiten", "CloseCancel": "Sluiten", "Confirm": "Bevestig", + "Quit": "Afsluiten", + "Fixup": "Fixup", "SureSquashThisCommit": "Weet je zeker dat je deze commit wil samenvoegen met de commit hieronder?", + "Squash": "Squash", "PickCommitTooltip": "Kies commit (wanneer midden in rebase)", "Reword": "Hernoem commit", "DropCommit": "Verwijder commit", "MoveDownCommit": "Verplaats commit 1 naar beneden", "MoveUpCommit": "Verplaats commit 1 naar boven", + "CannotMoveAnyFurther": "Kan niet verder verplaatsen", + "CannotMoveMergeCommit": "Kan een merge commit niet verplaatsen", "EditCommitTooltip": "Wijzig commit", "AmendCommitTooltip": "Wijzig commit met staged veranderingen", + "AddCoAuthor": "Voeg co-auteur toe", "RewordCommitEditor": "Hernoem commit met editor", "NoCommitsThisBranch": "Geen commits in deze branch", + "ExecCommandHere": "Voer het volgende commando hier uit:", "Error": "Foutmelding", "Undo": "Ongedaan maken", "UndoReflog": "Ongedaan maken (via reflog) (experimenteel)", "RedoReflog": "Redo (via reflog) (experimenteel)", + "DiscardAllTooltip": "Verwijder zowel gestagede als niet-gestagede wijzigingen in '{{.path}}'.", + "DiscardUnstagedTooltip": "Verwijder niet-gestagede wijzigingen in '{{.path}}'.", + "DiscardUnstagedDisabled": "De geselecteerde items hebben geen mix van gestagede en niet-gestagede wijzigingen.", + "Pop": "Pop", "Drop": "Laten vallen", "Apply": "Toepassen", "NoStashEntries": "Geen stash items", "StashDrop": "Stash laten vallen", + "SureDropStashEntry": "Weet je het zeker dat je de geselecteerde stash(es) wilt verwijderen?", + "StashPop": "Stash poppen", "SurePopStashEntry": "Weet je zeker dat je deze stash entry wil poppen?", "StashApply": "Stash toepassen", "SureApplyStashEntry": "Weet je zeker dat je deze stash entry wil toepassen?", "NoTrackedStagedFilesStash": "Je hebt geen tracked/staged bestanden om te laten stashen", + "NoFilesToStash": "Je hebt geen bestanden om te stashen", "StashChanges": "Stash veranderingen", - "OpenConfig": "Open config bestand", + "RenameStash": "Hernoem stash", + "RenameStashPrompt": "Hernoem stash: {{.stashName}}", "EditConfig": "Verander config bestand", "ForcePush": "Forceer push", "ForcePushPrompt": "Je branch is afgeweken van de remote branch. Druk {{.cancelKey}} om te annuleren, of {{.confirmKey}} om geforceerd te pushen.", "CheckForUpdate": "Check voor updates", "CheckingForUpdates": "Zoeken naar updates...", + "UpdateAvailableTitle": "Update beschikbaar!", + "FailedToRetrieveLatestVersionErr": "Ophalen versie-informatie mislukt", "OnLatestVersionErr": "Je hebt al de laatste versie", "MajorVersionErr": "Nieuwe versie ({{.newVersion}}) is niet backwards compatibele vergeleken met de huidige versie ({{.currentVersion}})", "CouldNotFindBinaryErr": "Kon geen binary vinden op {{.url}}", + "ConfirmQuitDuringUpdate": "Er is een update bezig. Weet je zeker dat je wilt afsluiten?", + "IntroPopupMessage": "\nBedankt voor het gebruik van lazygit! Je bent een kanjer. Deze vier dingen wil ik met je delen:\n\n 1) Als je meer wilt weten over lazygit's features, kijk dan deze video:\n https://youtu.be/CPLdltN7wgE\n\n 2) Lees de laatste release notes hier:\n https://github.com/jesseduffield/lazygit/releases\n\n 3) Als je git gebruikt, dan ben je een programmeur! Met jouw hulp kunnen we\n lazygit beter maken, dus overweeg mee te helpen met coden op\n https://github.com/jesseduffield/lazygit\n Of geef het repo een ster om te laten zien dat je het leuk vindt!\n\n 4) Als lazygit je leven makkelijker heeft gemaakt kan je \"dank je wel\" zeggen door\n op de donatie knop rechtsonder te drukken. Doneren geeft geen recht op voorrang bij ondersteuning\n maar wordt wel zeer gewaardeerd.\n\nDruk op {{confirmationKey}} om te beginnen.\n", "GitconfigParseErr": "Gogit kon je gitconfig bestand niet goed parsen door de aanwezigheid van losstaande '\\' tekens. Het weghalen van deze tekens zou het probleem moeten oplossen. ", "EditFile": "Verander bestand", + "EditFileTooltip": "Open bestand in externe editor.", "OpenFile": "Open bestand", + "OpenFileTooltip": "Open bestand in standaardapplicatie.", + "OpenInEditor": "Openen in editor", "IgnoreFile": "Voeg toe aan .gitignore", + "ExcludeFile": "Toevoegen aan .git/info/exclude", "RefreshFiles": "Refresh bestanden", "Merge": "Merge in met huidige checked out branch", "ConfirmQuit": "Weet je zeker dat je dit programma wil sluiten?", @@ -92,6 +183,8 @@ "UnsupportedGitService": "Niet-ondersteunde git-service", "CopyPullRequestURL": "Kopieer de URL van het pull-verzoek naar het klembord", "NoBranchOnRemote": "Deze branch bestaat niet op de remote. U moet het eerst naar de remote pushen.", + "ExpandAll": "Vouw alle bestanden uit", + "ExpandAllTooltip": "Vouw alle mappen in de bestandsstructuur uit", "FileEnter": "Stage individuele hunks/lijnen", "StageSelectionTooltip": "Toggle lijnen staged / unstaged", "DiscardSelection": "Verwijdert change (git reset)", @@ -100,26 +193,56 @@ "ReturnToFilesPanel": "Ga terug naar het bestanden paneel", "FastForward": "Fast-forward deze branch vanaf zijn upstream", "FoundConflictsTitle": "Conflicten!", + "ViewConflictsMenuItem": "Toon conflicten", + "AbortMenuItem": "Breek %s af", "PickHunk": "Kies stuk", - "PickAllHunks": "Kies beide stukken", "ViewMergeRebaseOptions": "Bekijk merge/rebase opties", + "ViewMergeRebaseOptionsTooltip": "Toon abort/continue/skip opties voor huidige merge/rebase.", + "ViewMergeOptions": "Toon merge opties", + "ViewRebaseOptions": "Toon rebase opties", + "ViewCherryPickOptions": "Toon cherry-pick opties", + "ViewRevertOptions": "Toon revert opties", "NotMergingOrRebasing": "Je bent momenteel niet aan het rebasen of mergen", + "AlreadyRebasing": "Deze actie kan niet worden uitgevoerd tijdens een rebase", + "NotMidRebase": "Deze actie werkt alleen tijdens een interactieve rebase", + "MustSelectFixupCommit": "Deze actie werkt alleen op fixup commits", "RecentRepos": "Recente repositories", "MergeOptionsTitle": "Merge opties", "RebaseOptionsTitle": "Rebase opties", + "CherryPickOptionsTitle": "Cherry-pick opties", + "RevertOptionsTitle": "Revert opties", "CommitSummaryTitle": "Commit bericht", + "CommitDescriptionTitle": "Commit beschrijving", "LocalBranchesTitle": "Branches", "SearchTitle": "Zoek", + "TagsTitle": "Tags", + "MenuTitle": "Menu", + "CommitMenuTitle": "Commit Menu", + "RemotesTitle": "Remotes", + "RemoteBranchesTitle": "Remote branches", "PatchBuildingTitle": "Patch bouwen", "InformationTitle": "Informatie", + "ReflogCommitsTitle": "Reflog", + "ConflictsResolved": "Alle mergeconflicten zijn opgelost. Doorgaan met de %s?", + "Continue": "Doorgaan", + "UnstagedFilesAfterConflictsResolved": "Er zijn bestanden gewijzigd nadat de mergeconflicten opgelost waren. Deze bestanden stagen en doorgaan?", + "RebasingTitle": "Rebase '{{.checkedOutBranch}}'", + "SimpleRebase": "Simpele rebase op '{{.ref}}'", + "InteractiveRebase": "Interactieve rebase op '{{.ref}}'", + "RebaseOntoBaseBranch": "Rebase op basis branch ({{.baseBranch}})", "FwdNoUpstream": "Kan niet de branch vooruitspoelen zonder upstream", "FwdCommitsToPush": "Je kan niet vooruitspoelen als de branch geen nieuwe commits heeft", "ErrorOccurred": "Er is iets fout gegaan! Zou je hier een issue aan willen maken", + "ConflictLabel": "CONFLICT", + "CommitsSectionHeader": "Commits", + "YouDied": "JE BENT DOOD!", "RewordNotSupported": "Herformatteren van commits in interactief rebasen is nog niet ondersteund", "CherryPickCopy": "Kopieer commit (cherry-pick)", "PasteCommits": "Plak commits (cherry-pick)", + "SureCherryPick": "Weet je zeker dat je de {{.numCommits}} gekopieerde commit(s) naar deze branch wilt cherry-picken?", "CherryPick": "Cherry-Pick", "Donate": "Doneer", + "AskQuestion": "Stel vraag", "PrevHunk": "Selecteer de vorige hunk", "NextHunk": "Selecteer de volgende hunk", "PrevConflict": "Selecteer voorgaand conflict", @@ -130,8 +253,10 @@ "ScrollUp": "Scroll omhoog", "ScrollUpMainWindow": "Scroll naar beneden vanaf hoofdpaneel", "ScrollDownMainWindow": "Scroll naar beneden vanaf hoofdpaneel", + "SuspendApp": "Pauzeer de applicatie", "AmendCommitTitle": "Commit wijzigen", "AmendCommitPrompt": "Weet je zeker dat je deze commit wil wijzigen met de vorige staged bestanden?", + "AmendCommitWithConflictsContinue": "Nee, doorgaan met rebase", "DropCommitTitle": "Verwijder commit", "DropCommitPrompt": "Weet je zeker dat je deze commit wil verwijderen?", "PullingStatus": "Pullen", @@ -145,12 +270,15 @@ "CherryPickingStatus": "Cherry-picken", "UndoingStatus": "Ongedaan maken", "CheckingOutStatus": "Uitchecken", + "RevertingStatus": "Bezig met reverten", "CommitFiles": "Commit bestanden", "ViewItemFiles": "Bekijk gecommite bestanden", "CommitFilesTitle": "Commit bestanden", "CheckoutCommitFileTooltip": "Bestand uitchecken", + "Remove": "Verwijderen", "DiscardOldFileChangeTooltip": "Uitsluit deze commit zijn veranderingen aan dit bestand", "DiscardFileChangesTitle": "Uitsluit bestand zijn veranderingen", + "CreateRepo": "Niet in een git repository. Maak een nieuwe git repository? (y/N): ", "AutoStashPrompt": "Je moet je veranderingen stashen en poppen om ze over te brengen. Dit automatisch doen? (enter/esc)", "Discard": "Bekijk 'veranderingen ongedaan maken' opties", "Cancel": "Annuleren", @@ -160,6 +288,8 @@ "DiscardAnyUnstagedChanges": "Gooi unstaged wijzigingen weg", "DiscardUntrackedFiles": "Negeer niet-gevonden bestanden", "HardReset": "Harde reset", + "Delete": "Verwijderen", + "Reset": "Resetten", "ViewResetOptions": "Bekijk reset opties", "CreateFixupCommit": "Creëer fixup commit", "CreateFixupCommitTooltip": "Creëer fixup commit", @@ -172,6 +302,8 @@ "StashAllChangesKeepIndex": "Stash staged wijzigingen", "StashOptions": "Stash opties", "NotARepository": "Fout: moet in een git repository uitgevoerd worden", + "ScrollLeft": "Scroll naar links", + "ScrollRight": "Scroll naar rechts", "DiscardPatch": "Patch weg gooien", "DiscardPatchConfirm": "Je kan alleen maar een patch bouwen van 1 commit. Huidige patch weggooien?", "CantPatchWhileRebasingError": "Je kan geen patch bouwen of patch commando uitvoeren wanneer je in een merging of rebasing state zit", @@ -185,12 +317,16 @@ "NewRemote": "Voeg een nieuwe remote toe", "NewRemoteName": "Nieuwe remote name:", "NewRemoteUrl": "Nieuwe remote url:", + "ViewBranches": "Bekijk branches", "EditRemoteName": "Enter updated remote naam voor {{.remoteName}}:", "EditRemoteUrl": "Enter updated remote url voor {{.remoteName}}:", "RemoveRemote": "Verwijder remote", "DeleteRemoteBranch": "Verwijder remote branch", + "SetAsUpstream": "Instellen als upstream", "SetAsUpstreamTooltip": "Stel in als upstream van uitgecheckte branch", "SetUpstream": "Stel in als upstream van uitgecheckte branch", + "DivergenceSectionHeaderLocal": "Lokaal", + "DivergenceSectionHeaderRemote": "Remote", "SetUpstreamTitle": "Stel in als upstream branch", "EditRemoteTooltip": "Wijzig remote", "TagNameTitle": "Tag naam:", @@ -207,6 +343,7 @@ "PrevScreenMode": "Vorige scherm modus", "StartSearch": "Start met zoeken", "Keybindings": "Sneltoetsen", + "KeybindingsMenuSectionGlobal": "Algemeen", "RenameBranch": "Hernoem branch", "NewGitFlowBranchPrompt": "Nieuwe '{{.branchType}}' naam:", "RenameBranchWarning": "Deze branch volgt een remote. Deze actie zal alleen de locale branch name wijzigen niet de naam van de remote branch. Verder gaan?", @@ -262,8 +399,54 @@ "CreatePullRequest": "Maak een pull-request", "ConfirmRevertCommit": "Weet u zeker dat u {{.selectedCommit}} ongedaan wilt maken?", "ToggleRangeSelect": "Toggle drag selecteer", - "Actions": {}, + "Actions": { + "CopyCommitAuthorToClipboard": "Kopieer commit auteur naar klembord", + "CopyCommitAttributeToClipboard": "Kopieer naar klembord", + "CopyCommitTagsToClipboard": "Kopieer commit tags naar klembord", + "CopyPatchToClipboard": "Kopieer patch naar klembord", + "Commit": "Commit", + "Push": "Push", + "Pull": "Pull", + "OpenFile": "Open bestand", + "CopyToClipboard": "Kopieer naar klembord", + "CopySelectedTextToClipboard": "Kopieer geselecteerde tekst naar klembord", + "AddRemote": "Voeg remote toe", + "RemoveSubmodule": "Verwijder submodule", + "ResetSubmodule": "Reset submodule", + "AddSubmodule": "Voeg submodule toe", + "UpdateSubmoduleUrl": "Update submodule URL", + "InitialiseSubmodule": "Initialiseer submodule", + "UpdateSubmodule": "Update submodule", + "NukeWorkingTree": "Blaas de working tree op met een kernbom", + "RemoveUntrackedFiles": "Verwijder niet-getrackte bestanden", + "SoftReset": "Soft reset", + "MixedReset": "Mixed reset", + "HardReset": "Hard reset", + "Undo": "Ongedaan maken", + "Redo": "Herhalen", + "OpenCommitInBrowser": "Open commit in browser", + "OpenPullRequest": "Open pull request in browser", + "AddWorktree": "Voeg worktree toe" + }, "Bisect": {}, - "Log": {}, - "BreakingChangesByVersion": {} + "Log": { + "RemoveFile": "Verwijder pad '{{.path}}'", + "RemoveEmptyDir": "Verwijder de lege map '{{.path}}'", + "CopyToClipboard": "Kopieer '{{.str}}' naar klembord", + "Remove": "Verwijder '{{.filename}}'", + "CreateFileWithContent": "Maak bestand '{{.path}}'", + "AppendingLineToFile": "Voeg {{.line}}' toe aan bestand '{{.filename}} '", + "EditRebaseFromBaseCommit": "Begin een interactieve rebase van '{{.baseCommit}}' op '{{.targetBranchName}}'", + "DroppingStash": "Verwijder stash %s", + "PoppingStash": "Pop stash %s", + "DeletingBranch": "Verwijder branch '{{.branchName}}' (was {{.hash}})" + }, + "BreakingChangesByVersion": {}, + "ViewMergeConflictOptions": "Bekijk merge conflict opties", + "ViewMergeConflictOptionsTooltip": "Bekijk opties voor het oplossen van mergeconflicten.", + "NoFilesWithMergeConflicts": "Er zijn geen files met mergeconflicten.", + "MergeConflictOptionsTitle": "Los mergeconflicten op", + "UseCurrentChanges": "Gebruik huidige wijzigingen", + "UseIncomingChanges": "Gebruik binnenkomende wijzigingen", + "UseBothChanges": "Gebruik beide" } diff --git a/pkg/i18n/translations/pl.json b/pkg/i18n/translations/pl.json index 560592524..60ecf6109 100644 --- a/pkg/i18n/translations/pl.json +++ b/pkg/i18n/translations/pl.json @@ -187,7 +187,6 @@ "StashChanges": "Schowaj zmiany", "RenameStash": "Zmień nazwę schowka", "RenameStashPrompt": "Zmień nazwę schowka: {{.stashName}}", - "OpenConfig": "Otwórz plik konfiguracyjny", "EditConfig": "Edytuj plik konfiguracyjny", "ForcePush": "Wymuś wysłanie", "ForcePushPrompt": "Twoja gałąź rozbiegła się z gałęzią zdalną. Naciśnij {{.cancelKey}}, aby anulować, lub {{.confirmKey}}, aby wymusić wysłanie.", @@ -244,7 +243,6 @@ "ViewConflictsMenuItem": "Pokaż konflikty", "AbortMenuItem": "Przerwij %s", "PickHunk": "Wybierz fragment", - "PickAllHunks": "Wybierz wszystkie fragmenty", "ViewMergeRebaseOptions": "Pokaż opcje scalania/rebase", "ViewMergeRebaseOptionsTooltip": "Pokaż opcje do przerwania/kontynuowania/pominięcia bieżącego scalania/rebase.", "ViewMergeOptions": "Pokaż opcje scalania", @@ -681,7 +679,6 @@ "DetachingWorktree": "Odłączanie drzewa pracy", "WorktreesTitle": "Drzewa pracy", "WorktreeTitle": "Drzewo pracy", - "RemoveWorktreePrompt": "Czy na pewno chcesz usunąć drzewo pracy '{{.worktreeName}}'?", "RemovingWorktree": "Usuwanie drzewa pracy", "AddingWorktree": "Dodawanie drzewa pracy", "CantDeleteCurrentWorktree": "Nie możesz usunąć bieżącego drzewa pracy!", @@ -691,13 +688,8 @@ "MissingWorktree": "(brakujące)", "NewWorktree": "Nowe drzewo pracy", "NewWorktreePath": "Nowa ścieżka drzewa pracy", - "NewWorktreeBase": "Nowa bazowa ref drzewa pracy", "RemoveWorktreeTooltip": "Usuń wybrane drzewo pracy. To usunie zarówno katalog drzewa pracy, jak i metadane o drzewie pracy w katalogu .git.", "NewBranchName": "Nowa nazwa brancha", - "NewBranchNameLeaveBlank": "Nowa nazwa brancha (pozostaw puste, aby przełączyć {{.default}})", - "ViewWorktreeOptions": "Zobacz opcje drzewa pracy", - "CreateWorktreeFrom": "Utwórz drzewo pracy z {{.ref}}", - "CreateWorktreeFromDetached": "Utwórz drzewo pracy z {{.ref}} (odłączone)", "LcWorktree": "drzewo pracy", "ChangingDirectoryTo": "Zmiana katalogu na {{.path}}", "Name": "Nazwa", diff --git a/pkg/i18n/translations/pt.json b/pkg/i18n/translations/pt.json index 6d9f83647..640ce2d65 100644 --- a/pkg/i18n/translations/pt.json +++ b/pkg/i18n/translations/pt.json @@ -206,7 +206,6 @@ "StashChanges": "Alterações preparadas", "RenameStash": "Renomear o stash", "RenameStashPrompt": "Renomear o estoque: {{.stashName}}", - "OpenConfig": "Abrir o ficheiro de config", "EditConfig": "Editar arquivo de configuração", "ForcePush": "Forçar push", "ForcePushPrompt": "Seu branch divergiu do branch remoto. Pressione {{.cancelKey}} para cancelar, ou {{.confirmKey}} para forçar a push.", @@ -279,7 +278,6 @@ "ViewConflictsMenuItem": "Visualizar conflitos", "AbortMenuItem": "Abortar %s", "PickHunk": "Escolha o local", - "PickAllHunks": "Pegar todos os pedaços", "ViewMergeRebaseOptions": "Ver opções de mesclar/rebase", "ViewMergeRebaseOptionsTooltip": "Ver opções para abortar/continuar/pular o merge/rebase atual.", "ViewMergeOptions": "Visualizar opções de merge", @@ -639,9 +637,6 @@ "MainWorktree": "(árvore de trabalho principal)", "NewWorktree": "Nova árvore de trabalho", "NewWorktreePath": "Caminho da nova árvore de trabalho", - "ViewWorktreeOptions": "Ver opções da árvore de trabalho", - "CreateWorktreeFrom": "Criar árvore de trabalho a partir de {{.ref}}", - "CreateWorktreeFromDetached": "Criar árvore de trabalho a partir de {{.ref}} (desanexado)", "LcWorktree": "árvore de trabalho", "Name": "Nome", "Path": "Caminho", diff --git a/pkg/i18n/translations/ru.json b/pkg/i18n/translations/ru.json index 89f09521e..34d7105fe 100644 --- a/pkg/i18n/translations/ru.json +++ b/pkg/i18n/translations/ru.json @@ -106,7 +106,6 @@ "StashChanges": "Припрятать изменения", "RenameStash": "Переименовать хранилище", "RenameStashPrompt": "Переименовать хранилище: {{.stashName}}", - "OpenConfig": "Открыть файл конфигурации", "EditConfig": "Редактировать файл конфигурации", "ForcePush": "Принудительная отправка изменении", "ForcePushPrompt": "Ветка отклонилась от удалённой ветки. Нажмите «esc», чтобы отменить, или «enter», чтобы начать принудительную отправку изменении.", @@ -152,7 +151,6 @@ "ViewConflictsMenuItem": "Просмотр конфликтов", "AbortMenuItem": "Прервать %s", "PickHunk": "Выбрать эту часть", - "PickAllHunks": "Выбрать все части", "ViewMergeRebaseOptions": "Просмотреть параметры слияния/перебазирования", "NotMergingOrRebasing": "В данный момент вы не выполняете ни перебазирования, ни слияние", "AlreadyRebasing": "Невозможно выполнить это действие во время перебазирования", diff --git a/pkg/i18n/translations/zh-CN.json b/pkg/i18n/translations/zh-CN.json index 0bbe1f117..6799fd0ae 100644 --- a/pkg/i18n/translations/zh-CN.json +++ b/pkg/i18n/translations/zh-CN.json @@ -219,7 +219,6 @@ "StashChanges": "贮藏变更", "RenameStash": "重命名贮藏", "RenameStashPrompt": "重命名贮藏: {{.stashName}}", - "OpenConfig": "打开配置文件", "EditConfig": "编辑配置文件", "ForcePush": "强制推送", "ForcePushPrompt": "您的分支已与远程分支不同。按‘esc’取消,或‘enter’强制推送.", @@ -305,7 +304,6 @@ "ViewConflictsMenuItem": "查看冲突", "AbortMenuItem": "中止 %s", "PickHunk": "选中区块", - "PickAllHunks": "选中所有区块", "ViewMergeRebaseOptions": "查看合并/变基选项", "ViewMergeRebaseOptionsTooltip": "查看当前合并或变基的中止、继续、跳过选项", "ViewMergeOptions": "查看合并选项", @@ -855,7 +853,6 @@ "DetachingWorktree": "正在分离工作树", "WorktreesTitle": "工作区", "WorktreeTitle": "工作区", - "RemoveWorktreePrompt": "您确定要删除工作树 {{.worktreeName}}' ?", "ForceRemoveWorktreePrompt": "'{{.worktreeName}}' 包含已修改或未跟踪的文件,或子模块(或包含所有这些)。确定要移除它吗?", "RemovingWorktree": "正在删除工作树", "AddingWorktree": "添加工作区", @@ -867,13 +864,8 @@ "MainWorktree": "(主工作树)", "NewWorktree": "新建工作树", "NewWorktreePath": "新建工作树路径", - "NewWorktreeBase": "新建工作树基于ref", "RemoveWorktreeTooltip": "删除选定的工作树。这将删除工作树的目录以及 .git 目录中有关工作树的元数据。", "NewBranchName": "新分支名称", - "NewBranchNameLeaveBlank": "新分支名称(为空则默认检出为 {{.default}})", - "ViewWorktreeOptions": "查看工作区选项", - "CreateWorktreeFrom": "从 {{.ref}} 创建工作树", - "CreateWorktreeFromDetached": "从 {{.ref}} 创建工作树(分离)", "LcWorktree": "工作区", "ChangingDirectoryTo": "将目录更改为 {{.path}}", "Name": "名称", @@ -1068,7 +1060,8 @@ "0.50.0": "- 拉取后,如果主分支落后于其上游分支,现在会自动前推。这对于自动保持主分支或 master 分支最新很有用。如果不希望这样,可以通过在配置中设置以下内容来禁用它:\n\ngit:\n autoForwardBranches: none\n\n相反,如果希望功能分支也这样做,可以将其设置为 'allBranches'。", "0.51.0": "- 自定义命令的 'subprocess'、'stream' 和 'showOutput' 字段已被替换为单个 'output' 字段。这应该是透明的,如果您在配置文件中使用了这些字段,它们应该已自动更新。但有一个显著变化:'stream' 字段过去意味着命令输出将流式传输到命令日志,并且命令将在伪终端 (pty) 中运行。我们将其转换为 'output: log',这意味着命令输出将流式传输到命令日志,但不使用 pty,假设这是大多数人想要的。如果您确实希望在 pty 中运行命令,可以将其更改为 'output: logWithPty'。", "0.54.0": "- 本地和远程分支的默认排序顺序已更改:过去本地分支是 'recency'(基于 reflog),远程分支是 'alphabetical'。这两者都已更改为 'date'(即提交者日期)。如果您更喜欢旧的默认设置,可以通过以下配置恢复:\n\ngit:\n localBranchSortOrder: recency\n remoteBranchSortOrder: alphabetical\n\n- 暂存区和自定义补丁构建视图中的默认选择模式已更改为块模式。在大多数情况下,这是更有用的模式,因为它通常可以节省大量按键。如果想切换回旧的行模式默认设置,可以通过在配置中添加以下内容来实现:\n\ngui:\n useHunkModeInStagingView: false\n", - "0.55.0": "- 原先绑定到 ctrl-z 的 'redo' 命令,现在改为绑定到 shift-Z。这是因为 ctrl-z 现在用于挂起应用程序;在 Linux 世界中,这是该功能的常用键绑定。如果你想恢复此更改,可以在配置中添加以下内容:\n\nkeybinding:\n universal:\n suspendApp: \n redo: \n\n- 'git.paging.useConfig' 选项已被移除。如果你之前依赖它来配置你的分页器,现在必须使用 'git.paging.pager' 选项重新明确设置分页器。" + "0.55.0": "- 原先绑定到 ctrl-z 的 'redo' 命令,现在改为绑定到 shift-Z。这是因为 ctrl-z 现在用于挂起应用程序;在 Linux 世界中,这是该功能的常用键绑定。如果你想恢复此更改,可以在配置中添加以下内容:\n\nkeybinding:\n universal:\n suspendApp: \n redo: \n\n- 'git.paging.useConfig' 选项已被移除。如果你之前依赖它来配置你的分页器,现在必须使用 'git.paging.pager' 选项重新明确设置分页器。", + "0.62.0": "从提交描述编辑器提交变更的默认快捷键已从 Mac 上的 alt-enter 改为 command-enter,在 Linux 和 Windows 上改为 ctrl-enter;这些和很多多行编辑框里用的快捷键一样,比如 GitHub 评论里用的那种。很遗憾,并非所有终端都支持这些快捷键;更多说明见:https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Custom_Keybindings.md#terminal-compatibility。如果你想恢复这个改动,可以在配置里加上:\n\nkeybinding:\n universal:\n confirmInEditor: \n" }, "ViewMergeConflictOptions": "查看合并冲突选项", "ViewMergeConflictOptionsTooltip": "查看用于解决合并冲突的选项。", diff --git a/pkg/i18n/translations/zh-TW.json b/pkg/i18n/translations/zh-TW.json index 7e47caec6..5c7b50e47 100644 --- a/pkg/i18n/translations/zh-TW.json +++ b/pkg/i18n/translations/zh-TW.json @@ -128,7 +128,6 @@ "StashChanges": "安置現有變更到收藏中", "RenameStash": "重新命名收藏", "RenameStashPrompt": "重新命名收藏:{{.stashName}}", - "OpenConfig": "開啟設定檔案", "EditConfig": "編輯設定檔案", "ForcePush": "強制推送", "ForcePushPrompt": "你的分支與遠端分支分岔。按 'ESC' 取消,或按 'Enter' 強制推送。", @@ -179,7 +178,6 @@ "ViewConflictsMenuItem": "檢視衝突", "AbortMenuItem": "中止%s", "PickHunk": "挑選程式碼片段", - "PickAllHunks": "挑選所有程式碼片段", "ViewMergeRebaseOptions": "查看合併/變基選項", "ViewRebaseOptions": "查看合併/變基選項", "NotMergingOrRebasing": "你當前既不在變基也不在合併中", @@ -528,7 +526,6 @@ "DetachingWorktree": "正在解除工作目錄連結", "WorktreesTitle": "工作目錄", "WorktreeTitle": "工作目錄", - "RemoveWorktreePrompt": "是否刪除 {{.worktreeName}} 工作目錄?", "RemovingWorktree": "正在刪除工作目錄", "AddingWorktree": "正在建立工作目錄", "CantDeleteCurrentWorktree": "無法刪除當前工作目錄!", @@ -537,12 +534,7 @@ "NoWorktreesThisRepo": "無工作目錄", "MissingWorktree": "(失蹤)", "NewWorktreePath": "工作目錄路徑", - "NewWorktreeBase": "工作目錄來源", "NewBranchName": "分支名稱", - "NewBranchNameLeaveBlank": "分支名稱(留空將檢出 {{.default}})", - "ViewWorktreeOptions": "檢視工作目錄選項", - "CreateWorktreeFrom": "從 {{.ref}} 建立工作目錄", - "CreateWorktreeFromDetached": "從 {{.ref}} 建立工作目錄(未連結)", "LcWorktree": "工作目錄", "ChangingDirectoryTo": "切換至 {{.path}}", "Name": "名稱", From 440f357319574a00aaa35c353485e8e9da5b9ff1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 14:40:33 +0200 Subject: [PATCH 039/218] Update docs and schema for release --- docs/Config.md | 58 ++++++++++- docs/Custom_Pagers.md | 31 +----- docs/keybindings/Keybindings_en.md | 21 ++-- docs/keybindings/Keybindings_ja.md | 21 ++-- docs/keybindings/Keybindings_ko.md | 21 ++-- docs/keybindings/Keybindings_nl.md | 141 +++++++++++++------------- docs/keybindings/Keybindings_pl.md | 21 ++-- docs/keybindings/Keybindings_pt.md | 21 ++-- docs/keybindings/Keybindings_ru.md | 21 ++-- docs/keybindings/Keybindings_zh-CN.md | 19 ++-- docs/keybindings/Keybindings_zh-TW.md | 21 ++-- schema/config.json | 131 +++++++++++++++++++++--- 12 files changed, 332 insertions(+), 195 deletions(-) diff --git a/docs/Config.md b/docs/Config.md index 9f7921821..1d101be18 100644 --- a/docs/Config.md +++ b/docs/Config.md @@ -110,6 +110,26 @@ gui: # is true. expandedSidePanelWeight: 2 + # If true, don't give a side panel more height than it needs to show its + # content; when all panels fit, the leftover height is shared among them so that + # they still fill the screen. + shrinkSidePanelsToContent: false + + # The side panels, in the order they appear from top to bottom. + # Each entry is a list of one or more names that share a single panel as tabs + # (cycle through them with the next-tab/previous-tab keys). + # Omit a name to hide it; give a name its own one-element list to promote a tab + # to a top-level panel. + # Valid names are: 'status', 'files', 'worktrees', 'submodules', 'branches', + # 'remotes', 'tags', 'commits', 'reflog', 'stash'. 'files', 'branches', and + # 'commits' must always be included; they can't be hidden. + sidePanels: + - [status] + - [files, worktrees, submodules] + - [branches, remotes, tags] + - [commits, reflog] + - [stash] + # 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. @@ -342,6 +362,11 @@ gui: git: # Array of pagers. Each entry has the following format: # + # # A name for the pager, shown in the notification when cycling pagers. + # # If not set, the name is derived from the first word of the pager + # # command (or of the external diff command). + # name: "" + # # # 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" @@ -361,6 +386,9 @@ git: # # https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver. # useExternalDiffGitConfig: false # + # 'pager', 'externalDiffCommand', and 'useExternalDiffGitConfig' are mutually + # exclusive; set at most one per entry. + # # See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md # for more information. pagers: [] @@ -406,6 +434,11 @@ git: # If true, periodically refresh files and submodules autoRefresh: true + # If true, poll the repo periodically for external ref changes (commits, branch + # updates, checkouts made outside lazygit) and refresh when one is detected. + # Independent of autoRefresh, which only governs the files panel. + autoDetectExternalChanges: true + # 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 @@ -499,6 +532,15 @@ git: # to 40 to disable truncation. truncateCopiedCommitHashesTo: 12 +# Config relating to git worktrees +worktree: + # Default parent directory for new worktrees. It is offered as a candidate + # location alongside the parent directories of any worktrees you already have. + # A relative path is resolved against the repository's root directory, so + # "../worktrees" sits beside the repo and ".worktrees" sits inside it. + # A leading "~" is expanded to your home directory, so "~/worktrees" works. + defaultPath: "" + # Periodic update checks update: # One of: 'prompt' (default) | 'background' | 'never' @@ -517,6 +559,11 @@ refresher: # Auto-fetch can be disabled via option 'git.autoFetch'. fetchInterval: 60 + # Interval in seconds at which lazygit polls for external ref changes (commits, + # branch updates, checkouts made outside lazygit). + # Detection can be disabled via option 'git.autoDetectExternalChanges'. + externalChangeCheckInterval: 2 + # If true, show a confirmation popup before quitting Lazygit confirmOnQuit: false @@ -648,6 +695,7 @@ keybinding: confirmInEditor: [, ] remove: d new: "n" + newWorktree: w edit: e openFile: o scrollUpMain: [, K, ] @@ -667,6 +715,7 @@ keybinding: nextScreenMode: + prevScreenMode: _ cyclePagers: '|' + cyclePagersReverse: \ undo: z redo: Z filteringMenu: @@ -681,6 +730,7 @@ keybinding: increaseRenameSimilarityThreshold: ) decreaseRenameSimilarityThreshold: ( openDiffTool: + editConfig: status: checkForUpdate: u recentRepos: @@ -726,8 +776,6 @@ keybinding: fetchRemote: f addForkRemote: F sortOrder: s - worktrees: - viewWorktreeOptions: w commits: squashDown: s renameCommit: r @@ -1059,6 +1107,12 @@ keybinding: edit: # disable 'edit file' ``` +### Overriding the platform for default keybindings + +A few keybindings have different defaults on macOS than on Linux and Windows (e.g. word-wise cursor movement in text inputs uses `alt` on macOS but `ctrl` elsewhere). Lazygit picks these based on the OS it's running on, but you can override that with the `LAZYGIT_KEYBINDING_PLATFORM` environment variable. Set it to `darwin`, `linux`, or `windows`; any other value is ignored and the actual OS is used. + +This is useful when running lazygit in a Linux container that you access over ssh from a Mac, where you'd rather use the macOS keybindings. + ### Example Keybindings For Colemak Users ```yaml diff --git a/docs/Custom_Pagers.md b/docs/Custom_Pagers.md index 903928d46..1b37766d0 100644 --- a/docs/Custom_Pagers.md +++ b/docs/Custom_Pagers.md @@ -2,8 +2,6 @@ Lazygit supports custom pagers, [configured](/docs/Config.md) in the config.yml file (which can be opened by pressing `e` in the Status panel). -Support does not extend to Windows users, because we're making use of a package which doesn't have Windows support. However, see [below](#emulating-custom-pagers-on-windows) for a workaround. - Multiple pagers are supported; you can cycle through them with the `|` key. This can be useful if you usually prefer a particular pager, but want to use a different one for certain kinds of diffs. Pagers are configured with the `pagers` array in the git section; here's an example for a multi-pager setup (use an empty object `{}` for the default builtin diff display that doesn't use a pager): @@ -71,7 +69,7 @@ git: - externalDiffCommand: difft --color=always ``` -The `colorArg` and `pager` options are not used in this case. +The `colorArg` option is not used in this case. You can add whatever extra arguments you prefer for your difftool; for instance @@ -91,29 +89,4 @@ git: This can be useful if you also want to use it for diffs on the command line, and it also has the advantage that you can configure it per file type in `.gitattributes`; see https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver. -## Emulating custom pagers on Windows - -There is a trick to emulate custom pagers on Windows using a Powershell script configured as an external diff command. It's not perfect, but certainly better than nothing. To do this, save the following script as `lazygit-pager.ps1` at a convenient place on your disk: - -```pwsh -#!/usr/bin/env pwsh - -$old = $args[1].Replace('\', '/') -$new = $args[4].Replace('\', '/') -$path = $args[0] -git diff --no-index --no-ext-diff $old $new - | %{ $_.Replace($old, $path).Replace($new, $path) } - | delta --width=$env:LAZYGIT_COLUMNS -``` - -Use the pager of your choice with the arguments you like in the last line of the script. Personally I wouldn't want to use lazygit anymore without delta's `--hyperlinks --hyperlinks-file-link-format="lazygit-edit://{path}:{line}"` args, see [above](#delta). - -In your lazygit config, use - -```yml -git: - pagers: - - externalDiffCommand: "C:/wherever/lazygit-pager.ps1" -``` - -The main limitation of this approach compared to a "real" pager is that renames are not displayed correctly; they are shown as if they were modifications of the old file. (This affects only the hunk headers; the diff itself is always correct.) +`pager`, `externalDiffCommand`, and `useExternalDiffGitConfig` are alternative ways of producing the diff, so a pager entry may use at most one of them. diff --git a/docs/keybindings/Keybindings_en.md b/docs/keybindings/Keybindings_en.md index d63058d82..4aa202740 100644 --- a/docs/keybindings/Keybindings_en.md +++ b/docs/keybindings/Keybindings_en.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | Refresh | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | Next screen mode (normal/half/fullscreen) | | | `` _ `` | Prev screen mode | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | Cancel | | | `` ? `` | Open keybindings menu | | | `` `` | View filter options | View options for filtering the commit log, so that only commits matching the filter are shown. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | Quit | | | `` `` | Suspend the application | | | `` `` | Toggle whitespace | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | Edit config file | Open file in external editor. | | `` z `` | Undo | The reflog will be used to determine what git command to run to undo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | | `` Z `` | Redo | The reflog will be used to determine what git command to run to redo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | @@ -110,13 +112,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Search the current view by text | | ## Confirmation panel @@ -176,6 +178,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Checkout | Checkout selected item. | | `` n `` | New branch | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | Create pull request | | | `` O `` | View create pull request options | | | `` G `` | Open pull request in browser | | @@ -195,7 +198,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Main panel (merging) @@ -203,7 +205,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Pick hunk | | -| `` b `` | Pick all hunks | | +| `` b `` | Pick both hunks | | | `` , k `` | Previous hunk | | | `` , j `` | Next hunk | | | `` , h `` | Previous conflict | | @@ -280,6 +282,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -287,7 +290,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remote branches @@ -297,6 +299,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy branch name to clipboard | | | `` `` | Checkout | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | New branch | | +| `` w `` | New worktree | | | `` M `` | Merge | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | Rebase | Rebase the checked-out branch onto the selected branch. | | `` d `` | Delete | Delete the remote branch from the remote. | @@ -306,7 +309,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remotes @@ -337,17 +339,16 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Drop | Remove the stash entry from the stash list. | | `` n `` | New branch | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Rename stash | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Status | Key | Action | Info | |-----|--------|-------------| -| `` o `` | Open config file | Open file in default application. | | `` e `` | Edit config file | Open file in external editor. | | `` u `` | Check for update | | | `` `` | Switch to a recent repo | | @@ -365,6 +366,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Open commit in browser | | | `` n `` | Create new branch off of commit | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Copy (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -372,7 +374,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View files | | -| `` w `` | View worktree options | | | `` / `` | Search the current view by text | | ## Submodules @@ -396,13 +397,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | Checkout | Checkout the selected tag as a detached HEAD. | | `` n `` | New tag | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | Delete | View delete options for local/remote tag. | | `` P `` | Push tag | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | View commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Worktrees diff --git a/docs/keybindings/Keybindings_ja.md b/docs/keybindings/Keybindings_ja.md index d9b87d747..5b9c798a1 100644 --- a/docs/keybindings/Keybindings_ja.md +++ b/docs/keybindings/Keybindings_ja.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | 更新 | Gitの状態を更新します(`git status`、`git branch`などをバックグラウンドで実行してパネルの内容を更新します)。これは`git fetch`を実行しません。 | | `` + `` | 次の画面モード(通常/半分/全画面) | | | `` _ `` | 前の画面モード | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | キャンセル | | | `` ? `` | キーバインディングメニューを開く | | | `` `` | フィルターオプションを表示 | コミットログのフィルタリングオプションを表示し、フィルタに一致するコミットのみを表示します。 | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | 終了 | | | `` `` | Suspend the application | | | `` `` | 空白表示の切り替え | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | 設定ファイルを編集 | 外部エディタでファイルを開きます。 | | `` z `` | 元に戻す | 最後のgitコマンドを元に戻すために実行するgitコマンドを決定するためにreflogが使用されます。これにはワーキングツリーへの変更は含まれません。コミットのみが考慮されます。 | | `` Z `` | やり直す | 最後のgitコマンドをやり直すために実行するgitコマンドを決定するためにreflogが使用されます。これにはワーキングツリーへの変更は含まれません。コミットのみが考慮されます。 | @@ -90,13 +92,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | 外部差分ツールを開く(git difftool) | | | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストで検索 | | ## コミットファイル @@ -136,6 +138,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | コピーされた(チェリーピックされた)コミットの選択をリセット | | @@ -143,7 +146,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストで検索 | | ## サブモジュール @@ -168,17 +170,16 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | ポップ | スタッシュエントリをワーキングディレクトリに適用し、スタッシュエントリを削除します。 | | `` d `` | 削除 | スタッシュリストからスタッシュエントリを削除します。 | | `` n `` | 新しいブランチ | 選択したスタッシュエントリから新しいブランチを作成します。これは、スタッシュエントリが作成されたコミットをgitがチェックアウトし、そのコミットから新しいブランチを作成した後、スタッシュエントリを追加のコミットとして新しいブランチに適用することで機能します。 | +| `` w `` | 新しいワークツリー | | | `` r `` | スタッシュの名前を変更 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | ファイルを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ステータス | Key | Action | Info | |-----|--------|-------------| -| `` o `` | 設定ファイルを開く | デフォルトのアプリケーションでファイルを開きます。 | | `` e `` | 設定ファイルを編集 | 外部エディタでファイルを開きます。 | | `` u `` | 更新を確認 | | | `` `` | 最近のリポジトリをチェックアウト | | @@ -201,13 +202,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | タグをクリップボードにコピー | | | `` `` | チェックアウト(ブランチの切り替え) | 選択したタグをデタッチドHEADとしてチェックアウトします。 | | `` n `` | 新しいタグを作成 | 現在のコミットから新しいタグを作成します。タグ名とオプションの説明を入力するよう促されます。 | +| `` w `` | 新しいワークツリー | | | `` d `` | 削除 | ローカル/リモートタグの削除オプションを表示します。 | | `` P `` | タグをプッシュ | 選択したタグをリモートにプッシュします。リモートを選択するよう促されます。 | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ファイル @@ -286,7 +287,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | ハンクを選択 | | -| `` b `` | すべてのハンクを選択 | | +| `` b `` | Pick both hunks | | | `` , k `` | 前のハンク | | | `` , j `` | 次のハンク | | | `` , h `` | 前のコンフリクト | | @@ -325,6 +326,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | ブラウザでコミットを開く | | | `` n `` | コミットから新しいブランチを作成 | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` g `` | リセット | 選択した項目へのリセットオプション(ソフト/ミックス/ハード)を表示します。各リセットタイプの詳細は次の通りです:
- ソフトリセット:変更を保持し、ステージされた状態にします
- ミックスリセット:変更を保持し、ステージされていない状態にします
- ハードリセット:すべての変更を破棄します | | `` C `` | コピー(チェリーピック) | コミットをコピーとしてマークします。ローカルコミットビューで `V` を押すと、コピーしたコミットをチェックアウトしたブランチにペースト(チェリーピック)できます。いつでも `` を押して選択をキャンセルできます。 | | `` `` | コピーされた(チェリーピックされた)コミットの選択をリセット | | @@ -332,7 +334,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 現在のブランチのコミットを選択 | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## リモート @@ -354,6 +355,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | ブランチ名をクリップボードにコピー | | | `` `` | チェックアウト(ブランチの切り替え) | 選択したリモートブランチに基づいて新しいローカルブランチをチェックアウトするか、リモートブランチをデタッチドヘッドとしてチェックアウトします。 | | `` n `` | 新しいブランチ | | +| `` w `` | 新しいワークツリー | | | `` M `` | マージ | 選択した項目を現在のブランチにマージするためのオプションを表示します(通常のマージ、スカッシュマージ) | | `` r `` | リベース | チェックアウトしたブランチを選択したブランチ上にリベースします。 | | `` d `` | 削除 | リモートからリモートブランチを削除します。 | @@ -363,7 +365,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ローカルブランチ @@ -375,6 +376,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | チェックアウト(ブランチの切り替え) | 選択した項目をチェックアウトします。 | | `` n `` | 新しいブランチ | | | `` N `` | コミットを新しいブランチに移動 | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | 新しいワークツリー | | | `` o `` | プルリクエストを作成 | | | `` O `` | プルリクエスト作成オプションを表示 | | | `` G `` | Open pull request in browser | | @@ -394,7 +396,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 外部差分ツールを開く(git difftool) | | | `` 0 `` | メインビューにフォーカス | | | `` `` | コミットを表示 | | -| `` w `` | ワークツリーオプションを表示 | | | `` / `` | 現在のビューをテキストでフィルタリング | | ## ワークツリー diff --git a/docs/keybindings/Keybindings_ko.md b/docs/keybindings/Keybindings_ko.md index 089543c5f..d1eb3afb1 100644 --- a/docs/keybindings/Keybindings_ko.md +++ b/docs/keybindings/Keybindings_ko.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | 새로고침 | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | 다음 스크린 모드 (normal/half/fullscreen) | | | `` _ `` | 이전 스크린 모드 | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | 취소 | | | `` ? `` | 매뉴 열기 | | | `` `` | View filter-by-path options | View options for filtering the commit log, so that only commits matching the filter are shown. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | 종료 | | | `` `` | Suspend the application | | | `` `` | 공백문자를 Diff 뷰에서 표시 여부 전환 | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | 설정 파일 수정 | Open file in external editor. | | `` z `` | 되돌리기 (reflog) (실험적) | The reflog will be used to determine what git command to run to undo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | | `` Z `` | 다시 실행 (reflog) (실험적) | The reflog will be used to determine what git command to run to redo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | @@ -67,6 +69,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (copied) commits selection | | @@ -74,7 +77,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Secondary @@ -93,10 +95,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Drop | Remove the stash entry from the stash list. | | `` n `` | 새 브랜치 생성 | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Rename stash | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Sub-commits @@ -109,6 +111,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (copied) commits selection | | @@ -116,7 +119,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | 검색 시작 | | ## Worktrees @@ -142,7 +144,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Pick hunk | | -| `` b `` | Pick all hunks | | +| `` b `` | Pick both hunks | | | `` , k `` | 이전 hunk를 선택 | | | `` , j `` | 다음 hunk를 선택 | | | `` , h `` | 이전 충돌을 선택 | | @@ -210,6 +212,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 체크아웃 | Checkout selected item. | | `` n `` | 새 브랜치 생성 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | 풀 리퀘스트 생성 | | | `` O `` | 풀 리퀘스트 생성 옵션 | | | `` G `` | Open pull request in browser | | @@ -229,14 +232,12 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 상태 | Key | Action | Info | |-----|--------|-------------| -| `` o `` | 설정 파일 열기 | Open file in default application. | | `` e `` | 설정 파일 수정 | Open file in external editor. | | `` u `` | 업데이트 확인 | | | `` `` | 최근에 사용한 저장소로 전환 | | @@ -277,6 +278,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 브랜치명을 클립보드에 복사 | | | `` `` | 체크아웃 | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | 새 브랜치 생성 | | +| `` w `` | New worktree | | | `` M `` | 현재 브랜치에 병합 | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | 체크아웃된 브랜치를 이 브랜치에 리베이스 | Rebase the checked-out branch onto the selected branch. | | `` d `` | 삭제 | Delete the remote branch from the remote. | @@ -286,7 +288,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 커밋 @@ -322,13 +323,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 브라우저에서 커밋 열기 | | | `` n `` | 커밋에서 새 브랜치를 만듭니다. | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | View reset options | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 커밋을 복사 (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | View selected item's files | | -| `` w `` | View worktree options | | | `` / `` | 검색 시작 | | ## 커밋 파일 @@ -365,13 +366,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | 체크아웃 | Checkout the selected tag as a detached HEAD. | | `` n `` | 태그를 생성 | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | 삭제 | View delete options for local/remote tag. | | `` P `` | 태그를 push | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | 초기화 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 커밋 보기 | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## 파일 diff --git a/docs/keybindings/Keybindings_nl.md b/docs/keybindings/Keybindings_nl.md index 1715c597e..0eb61729b 100644 --- a/docs/keybindings/Keybindings_nl.md +++ b/docs/keybindings/Keybindings_nl.md @@ -10,26 +10,28 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` , K, (fn+up/shift+k) `` | Scroll naar beneden vanaf hoofdpaneel | | | `` , J, (fn+down/shift+j) `` | Scroll naar beneden vanaf hoofdpaneel | | | `` @ `` | View command log options | View options for the command log e.g. show/hide the command log and focus the command log. | -| `` P `` | Push | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. | -| `` p `` | Pull | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. | +| `` P `` | Push | Push de huidige branch naar de bijbehorende upstream-branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren. | +| `` p `` | Pull | Pull wijzigingen van de remote voor de huidige branch. Als er geen upstream is geconfigureerd wordt er gevraagd om een upstream-branch te configureren. | | `` ) `` | Increase rename similarity threshold | Increase the similarity threshold for a deletion and addition pair to be treated as a rename.

The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. | | `` ( `` | Decrease rename similarity threshold | Decrease the similarity threshold for a deletion and addition pair to be treated as a rename.

The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. | | `` } `` | Increase diff context size | Increase the amount of the context shown around changes in the diff view.

The default can be changed in the config file with the key 'git.diffContextSize'. | | `` { `` | Decrease diff context size | Decrease the amount of the context shown around changes in the diff view.

The default can be changed in the config file with the key 'git.diffContextSize'. | | `` : `` | Execute shell command | Bring up a prompt where you can enter a shell command to execute. | | `` `` | Bekijk aangepaste patch opties | | -| `` m `` | Bekijk merge/rebase opties | View options to abort/continue/skip the current merge/rebase. | +| `` m `` | Bekijk merge/rebase opties | Toon abort/continue/skip opties voor huidige merge/rebase. | | `` R `` | Verversen | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | Volgende scherm modus (normaal/half/groot) | | | `` _ `` | Vorige scherm modus | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | Annuleren | | | `` ? `` | Open menu | | | `` `` | Bekijk scoping opties | View options for filtering the commit log, so that only commits matching the filter are shown. | | `` W, `` | Open diff menu | View options relating to diffing two refs e.g. diffing against selected ref, entering ref to diff against, and reversing the diff direction. | -| `` q, `` | Quit | | -| `` `` | Suspend the application | | +| `` q, `` | Afsluiten | | +| `` `` | Pauzeer de applicatie | | | `` `` | Toggle whitespace | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | Verander config bestand | Open bestand in externe editor. | | `` z `` | Ongedaan maken (via reflog) (experimenteel) | The reflog will be used to determine what git command to run to undo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | | `` Z `` | Redo (via reflog) (experimenteel) | The reflog will be used to determine what git command to run to redo the last git command. This does not include changes to the working tree; only commits are taken into consideration. | @@ -45,8 +47,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Range select down | | | `` `` | Range select up | | | `` / `` | Start met zoeken | | -| `` H `` | Scroll left | | -| `` L `` | Scroll right | | +| `` H `` | Scroll naar links | | +| `` L `` | Scroll naar rechts | | | `` ] `` | Volgende tabblad | | | `` [ `` | Vorige tabblad | | @@ -56,15 +58,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer de bestandsnaam naar het klembord | | | `` `` | Toggle staged | Toggle staged for selected file. | -| `` `` | Filter files by status | | -| `` y `` | Copy to clipboard | | -| `` c `` | Commit veranderingen | Commit staged changes. | +| `` `` | Filter bestanden op status | | +| `` y `` | Kopieer naar klembord | | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | | `` w `` | Commit veranderingen zonder pre-commit hook | | | `` A `` | Wijzig laatste commit | | | `` C `` | Commit veranderingen met de git editor | | -| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | -| `` e `` | Edit | Open file in external editor. | -| `` o `` | Open bestand | Open file in default application. | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | +| `` e `` | Edit | Open bestand in externe editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | | `` i `` | Ignore or exclude file | | | `` r `` | Refresh bestanden | | | `` s `` | Stash | Stash all changes. For other variations of stashing, use the view stash options keybinding. | @@ -73,13 +75,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Stage individuele hunks/lijnen | If the selected item is a file, focus the staging view so you can stage individual hunks/lines. If the selected item is a directory, collapse/expand it. | | `` d `` | Bekijk 'veranderingen ongedaan maken' opties | View options for discarding changes to the selected file. | | `` g `` | Bekijk upstream reset opties | | -| `` D `` | Reset | View reset options for working tree (e.g. nuking the working tree). | +| `` D `` | Resetten | View reset options for working tree (e.g. nuking the working tree). | | `` ` `` | Toggle bestandsboom weergave | Toggle file view between flat and tree layout. Flat layout shows all file paths in a single list, tree layout groups files by directory.

The default can be changed in the config file with the key 'gui.showFileTree'. | -| `` `` | Open external diff tool (git difftool) | | -| `` M `` | View merge conflict options | View options for resolving merge conflicts. | +| `` `` | Open externe diff applicatie (git difftool) | | +| `` M `` | Bekijk merge conflict opties | Bekijk opties voor het oplossen van mergeconflicten. | | `` f `` | Fetch | Fetch changes from remote. | | `` - `` | Collapse all files | Collapse all directories in the files tree | -| `` = `` | Expand all files | Expand all directories in the file tree | +| `` = `` | Vouw alle bestanden uit | Vouw alle mappen in de bestandsstructuur uit | | `` 0 `` | Focus main view | | | `` / `` | Filter the current view by text | | @@ -89,7 +91,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Bevestig | | | `` `` | Sluiten | | -| `` `` | Copy to clipboard | | +| `` `` | Kopieer naar klembord | | ## Branches @@ -97,18 +99,19 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer branch name naar klembord | | | `` i `` | Laat git-flow opties zien | | -| `` `` | Uitchecken | Checkout selected item. | +| `` `` | Uitchecken | Geselecteerd item uitchecken. | | `` n `` | Nieuwe branch | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | +| `` w `` | New worktree | | | `` o `` | Maak een pull-request | | | `` O `` | Bekijk opties voor pull-aanvraag | | | `` G `` | Open pull request in browser | | | `` `` | Kopieer de URL van het pull-verzoek naar het klembord | | | `` c `` | Uitchecken bij naam | Checkout by name. In the input box you can enter '-' to switch to the previous branch. | -| `` - `` | Checkout previous branch | | +| `` - `` | Vorige branch uitchecken | | | `` F `` | Forceer checkout | Force checkout selected branch. This will discard all local changes in your working directory before checking out the selected branch. | -| `` d `` | Delete | View delete options for local/remote branch. | -| `` r `` | Rebase branch | Rebase the checked-out branch onto the selected branch. | +| `` d `` | Verwijderen | View delete options for local/remote branch. | +| `` r `` | Rebase branch | Rebase de uitgecheckte branch bovenop de geselecteerde branch. | | `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` f `` | Fast-forward deze branch vanaf zijn upstream | Fast-forward selected branch from its upstream. | | `` T `` | Creëer tag | | @@ -116,10 +119,9 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Bekijk reset opties | | | `` R `` | Hernoem branch | | | `` u `` | View upstream options | View options relating to the branch's upstream e.g. setting/unsetting the upstream and resetting to the upstream. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Commit bericht @@ -134,18 +136,18 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Kopieer de bestandsnaam naar het klembord | | -| `` y `` | Copy to clipboard | | +| `` y `` | Kopieer naar klembord | | | `` c `` | Uitchecken | Bestand uitchecken | | `` d `` | Bekijk 'veranderingen ongedaan maken' opties | Uitsluit deze commit zijn veranderingen aan dit bestand | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Edit | Open file in external editor. | -| `` `` | Open external diff tool (git difftool) | | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Edit | Open bestand in externe editor. | +| `` `` | Open externe diff applicatie (git difftool) | | | `` `` | Toggle bestand inbegrepen in patch | Toggle whether the file is included in the custom patch. See https://github.com/jesseduffield/lazygit#rebase-magic-custom-patches. | | `` a `` | Toggle all files | Add/remove all commit's files to custom patch. See https://github.com/jesseduffield/lazygit#rebase-magic-custom-patches. | | `` `` | Enter bestand om geselecteerde regels toe te voegen aan de patch | If a file is selected, enter the file so that you can add/remove individual lines to the custom patch. If a directory is selected, toggle the directory. | | `` ` `` | Toggle bestandsboom weergave | Toggle file view between flat and tree layout. Flat layout shows all file paths in a single list, tree layout groups files by directory.

The default can be changed in the config file with the key 'gui.showFileTree'. | | `` - `` | Collapse all files | Collapse all directories in the files tree | -| `` = `` | Expand all files | Expand all directories in the file tree | +| `` = `` | Vouw alle bestanden uit | Vouw alle mappen in de bestandsstructuur uit | | `` 0 `` | Focus main view | | | `` / `` | Filter the current view by text | | @@ -181,14 +183,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Start met zoeken | | ## Input prompt @@ -211,15 +213,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Kies stuk | | -| `` b `` | Kies beide stukken | | +| `` b `` | Pick both hunks | | | `` , k `` | Selecteer bovenste hunk | | | `` , j `` | Selecteer onderste hunk | | | `` , h `` | Selecteer voorgaand conflict | | | `` , l `` | Selecteer volgende conflict | | | `` z `` | Ongedaan maken | Undo last merge conflict resolution. | -| `` e `` | Verander bestand | Open file in external editor. | -| `` o `` | Open bestand | Open file in default application. | -| `` M `` | View merge conflict options | View options for resolving merge conflicts. | +| `` e `` | Verander bestand | Open bestand in externe editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` M `` | Bekijk merge conflict opties | Bekijk opties voor het oplossen van mergeconflicten. | | `` `` | Ga terug naar het bestanden paneel | | ## Normaal @@ -241,8 +243,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle drag selecteer | | | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` `` | Copy selected text to clipboard | | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Verander bestand | Open file in external editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Voeg toe/verwijder lijn(en) in patch | | | `` d `` | Remove lines from commit | Remove the selected lines from this commit. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes these lines. | | `` `` | Sluit lijn-bij-lijn modus | | @@ -257,15 +259,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remote branches @@ -273,27 +275,27 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Kopieer branch name naar klembord | | -| `` `` | Uitchecken | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | +| `` `` | Uitchecken | Geselecteerde remote branch uitchecken als nieuwe locale branch of als detached head. | | `` n `` | Nieuwe branch | | +| `` w `` | New worktree | | | `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) | -| `` r `` | Rebase branch | Rebase the checked-out branch onto the selected branch. | -| `` d `` | Delete | Delete the remote branch from the remote. | -| `` u `` | Set as upstream | Stel in als upstream van uitgecheckte branch | +| `` r `` | Rebase branch | Rebase de uitgecheckte branch bovenop de geselecteerde branch. | +| `` d `` | Verwijderen | Delete the remote branch from the remote. | +| `` u `` | Instellen als upstream | Stel in als upstream van uitgecheckte branch | | `` s `` | Sort order | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Remotes | Key | Action | Info | |-----|--------|-------------| -| `` `` | View branches | | +| `` `` | Bekijk branches | | | `` n `` | Voeg een nieuwe remote toe | | -| `` d `` | Remove | Remove the selected remote. Any local branches tracking a remote branch from the remote will be unaffected. | +| `` d `` | Verwijderen | Remove the selected remote. Any local branches tracking a remote branch from the remote will be unaffected. | | `` e `` | Edit | Wijzig remote | | `` f `` | Fetch | Fetch remote | | `` F `` | Add fork remote | Quickly add a fork remote by replacing the owner in the origin URL and optionally check out a branch from new remote. | @@ -318,15 +320,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy selected text to clipboard | | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | -| `` o `` | Open bestand | Open file in default application. | -| `` e `` | Verander bestand | Open file in external editor. | +| `` o `` | Open bestand | Open bestand in standaardapplicatie. | +| `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Ga terug naar het bestanden paneel | | | `` `` | Ga naar een ander paneel | Switch to other view (staged/unstaged changes). | | `` E `` | Edit hunk | Edit selected hunk in external editor. | -| `` c `` | Commit veranderingen | Commit staged changes. | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | | `` w `` | Commit veranderingen zonder pre-commit hook | | | `` C `` | Commit veranderingen met de git editor | | -| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | | `` / `` | Start met zoeken | | ## Stash @@ -337,18 +339,17 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Laten vallen | Remove the stash entry from the stash list. | | `` n `` | Nieuwe branch | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | -| `` r `` | Rename stash | | +| `` w `` | New worktree | | +| `` r `` | Hernoem stash | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Status | Key | Action | Info | |-----|--------|-------------| -| `` o `` | Open config bestand | Open file in default application. | -| `` e `` | Verander config bestand | Open file in external editor. | +| `` e `` | Verander config bestand | Open bestand in externe editor. | | `` u `` | Check voor updates | | | `` `` | Wissel naar een recente repo | | | `` a `` | Show/cycle all branch logs | | @@ -364,15 +365,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` y `` | Copy commit attribute to clipboard | Copy commit attribute to clipboard (e.g. hash, URL, diff, message, author). | | `` o `` | Open commit in browser | | | `` n `` | Creëer nieuwe branch van commit | | -| `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` N `` | Verplaats commits naar nieuwe branch | Maak een nieuwe branch en verplaats niet-gepushte commits van de huidige branch hier naar toe. Gebruik dit in het geval dat je deze commits eigenlijk op een nieuwe branch had willen maken.

Let op dat de selectie genegeerd wordt. De nieuwe branch komt ofwel bovenop de main branch, of bovenop de huidige branch (je kan kiezen). | +| `` w `` | New worktree | | | `` g `` | Bekijk reset opties | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Kopieer commit (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Reset cherry-picked (gekopieerde) commits selectie | | -| `` `` | Open external diff tool (git difftool) | | +| `` `` | Open externe diff applicatie (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Bekijk gecommite bestanden | | -| `` w `` | View worktree options | | | `` / `` | Start met zoeken | | ## Submodules @@ -381,7 +382,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` `` | Kopieer submodule naam naar klembord | | | `` `` | Enter | Enter submodule | -| `` d `` | Remove | Remove the selected submodule and its corresponding directory. | +| `` d `` | Verwijderen | Remove the selected submodule and its corresponding directory. | | `` u `` | Update | Update selected submodule. | | `` n `` | Voeg nieuwe submodule toe | | | `` e `` | Update submodule URL | | @@ -394,15 +395,15 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Copy tag to clipboard | | -| `` `` | Uitchecken | Checkout the selected tag as a detached HEAD. | +| `` `` | Uitchecken | Geselecteerde tag uitchecken als detached HEAD. | | `` n `` | Creëer tag | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | -| `` d `` | Delete | View delete options for local/remote tag. | +| `` w `` | New worktree | | +| `` d `` | Verwijderen | View delete options for local/remote tag. | | `` P `` | Push tag | Push the selected tag to a remote. You'll be prompted to select a remote. | -| `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | -| `` `` | Open external diff tool (git difftool) | | +| `` g `` | Resetten | View reset options (soft/mixed/hard) for resetting onto selected item. | +| `` `` | Open externe diff applicatie (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Bekijk commits | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Worktrees @@ -411,6 +412,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct |-----|--------|-------------| | `` n `` | New worktree | | | `` `` | Switch | Switch to the selected worktree. | -| `` o `` | Open in editor | | -| `` d `` | Remove | Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory. | +| `` o `` | Openen in editor | | +| `` d `` | Verwijderen | Remove the selected worktree. This will both delete the worktree's directory, as well as metadata about the worktree in the .git directory. | | `` / `` | Filter the current view by text | | diff --git a/docs/keybindings/Keybindings_pl.md b/docs/keybindings/Keybindings_pl.md index b032a6606..719a7e6c4 100644 --- a/docs/keybindings/Keybindings_pl.md +++ b/docs/keybindings/Keybindings_pl.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | Odśwież | Odśwież stan git (tj. uruchom `git status`, `git branch`, itp. w tle, aby zaktualizować zawartość paneli). To nie uruchamia `git fetch`. | | `` + `` | Następny tryb ekranu (normalny/półpełny/pełnoekranowy) | | | `` _ `` | Poprzedni tryb ekranu | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | Anuluj | | | `` ? `` | Otwórz menu przypisań klawiszy | | | `` `` | Pokaż opcje filtrowania | Pokaż opcje filtrowania dziennika commitów, tak aby pokazywane były tylko commity pasujące do filtra. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | Wyjdź | | | `` `` | Suspend the application | | | `` `` | Przełącz białe znaki | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | Edytuj plik konfiguracyjny | Otwórz plik w zewnętrznym edytorze. | | `` z `` | Cofnij | Dziennik reflog zostanie użyty do określenia, jakie polecenie git należy uruchomić, aby cofnąć ostatnie polecenie git. Nie obejmuje to zmian w drzewie roboczym; brane są pod uwagę tylko commity. | | `` Z `` | Ponów | Dziennik reflog zostanie użyty do określenia, jakie polecenie git należy uruchomić, aby ponowić ostatnie polecenie git. Nie obejmuje to zmian w drzewie roboczym; brane są pod uwagę tylko commity. | @@ -83,13 +85,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Dodatkowy @@ -120,6 +122,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Resetuj wybrane (cherry-picked) commity | | @@ -127,7 +130,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Główny panel (budowanie łatki) @@ -162,6 +164,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Przełącz | Przełącz wybrany element. | | `` n `` | Nowa gałąź | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` o `` | Utwórz żądanie ściągnięcia | | | `` O `` | Zobacz opcje tworzenia pull requesta | | | `` G `` | Otwórz żądanie ściągnięcia w przeglądarce | | @@ -181,7 +184,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Menu @@ -207,7 +209,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Wybierz fragment | | -| `` b `` | Wybierz wszystkie fragmenty | | +| `` b `` | Pick both hunks | | | `` , k `` | Poprzedni fragment | | | `` , j `` | Następny fragment | | | `` , h `` | Poprzedni konflikt | | @@ -316,17 +318,16 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Wyciągnij | Zastosuj wpis schowka do katalogu roboczego i usuń wpis schowka. | | `` d `` | Usuń | Usuń wpis schowka z listy schowka. | | `` n `` | Nowa gałąź | Utwórz nową gałąź z wybranego wpisu schowka. Działa poprzez przełączenie git na commit, na którym wpis schowka został utworzony, tworzenie nowej gałęzi z tego commita, a następnie zastosowanie wpisu schowka do nowej gałęzi jako dodatkowego commita. | +| `` w `` | Nowe drzewo pracy | | | `` r `` | Zmień nazwę schowka | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Status | Key | Action | Info | |-----|--------|-------------| -| `` o `` | Otwórz plik konfiguracyjny | Otwórz plik w domyślnej aplikacji. | | `` e `` | Edytuj plik konfiguracyjny | Otwórz plik w zewnętrznym edytorze. | | `` u `` | Sprawdź aktualizacje | | | `` `` | Przełącz na ostatnie repozytorium | | @@ -344,6 +345,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Otwórz commit w przeglądarce | | | `` n `` | Utwórz nową gałąź z commita | | | `` N `` | Przenieś commity do nowej gałęzi | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nowe drzewo pracy | | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` C `` | Kopiuj (cherry-pick) | Oznacz commit jako skopiowany. Następnie, w widoku lokalnych commitów, możesz nacisnąć `V`, aby wkleić (cherry-pick) skopiowane commity do sprawdzonej gałęzi. W dowolnym momencie możesz nacisnąć ``, aby anulować zaznaczenie. | | `` `` | Resetuj wybrane (cherry-picked) commity | | @@ -351,7 +353,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Wyświetl pliki | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Submoduły @@ -375,13 +376,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Skopiuj tag do schowka | | | `` `` | Przełącz | Przełącz wybrany tag jako odłączoną głowę (detached HEAD). | | `` n `` | Nowy tag | Utwórz nowy tag z bieżącego commita. Zostaniesz poproszony o wprowadzenie nazwy tagu i opcjonalnego opisu. | +| `` w `` | Nowe drzewo pracy | | | `` d `` | Usuń | Wyświetl opcje usuwania lokalnego/odległego tagu. | | `` P `` | Wyślij tag | Wyślij wybrany tag do zdalnego. Zostaniesz poproszony o wybranie zdalnego. | | `` g `` | Reset | Wyświetl opcje resetu (miękki/mieszany/twardy) do wybranego elementu. | | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | ## Zdalne @@ -403,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Kopiuj nazwę gałęzi do schowka | | | `` `` | Przełącz | Przełącz na nową lokalną gałąź na podstawie wybranej gałęzi zdalnej. Nowa gałąź będzie śledzić gałąź zdalną. | | `` n `` | Nowa gałąź | | +| `` w `` | Nowe drzewo pracy | | | `` M `` | Scal | Scal wybraną gałąź z aktualnie sprawdzoną gałęzią. | | `` r `` | Przebazuj | Przebazuj przełączoną gałąź na wybraną gałąź. | | `` d `` | Usuń | Usuń gałąź zdalną ze zdalnego. | @@ -412,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Otwórz zewnętrzne narzędzie różnic (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Pokaż commity | | -| `` w `` | Zobacz opcje drzewa pracy | | | `` / `` | Filtruj bieżący widok po tekście | | diff --git a/docs/keybindings/Keybindings_pt.md b/docs/keybindings/Keybindings_pt.md index c19619191..5fcba2688 100644 --- a/docs/keybindings/Keybindings_pt.md +++ b/docs/keybindings/Keybindings_pt.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | Atualizar | Atualize o estado do git (ou seja, execute `git status`, `git branch`, etc em segundo plano para atualizar o conteúdo de painéis). Isso não executa `git fetch`. | | `` + `` | Modo de tela seguinte (normal/metade/tela cheia) | | | `` _ `` | Modo de tela anterior | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | Cancelar | | | `` ? `` | Abrir o menu de atalhos do teclado | | | `` `` | Ver opções de filtro | View options for filtering the commit log, so that only commits matching the filter are shown. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | Sair | | | `` `` | Suspender a aplicação | | | `` `` | Toggle whitespace | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | Editar arquivo de configuração | Abrir arquivo no editor externo. | | `` z `` | Desfazer | O reflog será usado para determinar qual comando git para executar para desfazer o último comando git. Isto não inclui mudanças na árvore de trabalho; apenas compromissos são tidos em consideração. | | `` Z `` | Refazer | O reflog será usado para determinar qual comando git para executar para refazer o último comando git. Isto não inclui mudanças na árvore de trabalho; apenas compromissos são tidos em consideração. | @@ -92,6 +94,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Verificar | Checar item selecionado | | `` n `` | Nova branch | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` o `` | Criar solicitação de pull | | | `` O `` | View create pull request options | | | `` G `` | Open pull request in browser | | @@ -111,7 +114,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Branches remotos @@ -121,6 +123,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copiar nome da branch para área de transferência | | | `` `` | Verificar | Checar a nova branch baseada na brach remota selecionada, ou a branch remota como HEAD, desanexado | | `` n `` | Nova branch | | +| `` w `` | Nova árvore de trabalho | | | `` M `` | Mesclar | Ver opções para mesclar o item selecionado no branch atual (mesclar regularmente, mesclar squash) | | `` r `` | Refazer | Refazer a branch checada na branch selecionada | | `` d `` | Apagar | Excluir o branch remoto do controle remoto. | @@ -130,7 +133,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Commit arquivos @@ -186,13 +188,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Pesquisar na visualização atual por texto | | ## Etiquetas @@ -202,13 +204,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copiar etiqueta para área de transferência | | | `` `` | Verificar | Checar a tag selecionada como um HEAD, desanexado | | `` n `` | Nova etiqueta | Crie uma nova etiqueta a partir do commit atual. Você será solicitado a digitar um nome e uma descrição opcional. | +| `` w `` | Nova árvore de trabalho | | | `` d `` | Apagar | Ver opções de exclusão para tag local/remoto. | | `` P `` | Empurrar etiqueta | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` `` | Abrir ferramenta de diff externa (git difftool) | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Input prompt @@ -271,7 +273,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Escolha o local | | -| `` b `` | Pegar todos os pedaços | | +| `` b `` | Pick both hunks | | | `` , k `` | Trecho anterior | | | `` , j `` | Próximo trecho | | | `` , h `` | Conflito anterior | | @@ -308,6 +310,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -315,7 +318,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver commits | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Remotes @@ -346,17 +348,16 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Pop | Aplique a entrada de stash no seu diretório de trabalho e remova a entrada de stash. | | `` d `` | Descartar | Remova a entrada do stash da lista de armazenamento. | | `` n `` | Nova branch | Criar um novo ramo a partir da entrada de lixo selecionada. Isso funciona verificando o commit do qual a entrada de lixo foi criada, criar um novo branch a partir desse commit e, em seguida, aplicar a entrada de lixo ao novo branch como um commit adicional. | +| `` w `` | Nova árvore de trabalho | | | `` r `` | Renomear o stash | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Filtrar a visualização atual por texto | | ## Status | Key | Action | Info | |-----|--------|-------------| -| `` o `` | Abrir o ficheiro de config | Abrir arquivo no aplicativo padrão. | | `` e `` | Editar arquivo de configuração | Abrir arquivo no editor externo. | | `` u `` | Verificar atualização | | | `` `` | Mudar para um repositório recente | | @@ -374,6 +375,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Abrir commit no navegador | | | `` n `` | Create new branch off of commit | | | `` N `` | Mover commits para uma nova branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | Nova árvore de trabalho | | | `` g `` | Restaurar | Ver opções de redefinição (soft/mixed/hard) para redefinir para o item selecionado. | | `` C `` | Copiar (cherry-pick) | Marcar commit como copiado. Então, dentro da visualização local de commits, você pode pressionar `V` para colar (cherry-pick) o(s) commit(s) copiado(s) em seu branch de check-out. A qualquer momento você pode pressionar `` para cancelar a seleção. | | `` `` | Reset copied (cherry-picked) commits selection | | @@ -381,7 +383,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focar visualização principal | | | `` `` | Ver arquivos | | -| `` w `` | Ver opções da árvore de trabalho | | | `` / `` | Pesquisar na visualização atual por texto | | ## Submódulos diff --git a/docs/keybindings/Keybindings_ru.md b/docs/keybindings/Keybindings_ru.md index c802678b3..683135448 100644 --- a/docs/keybindings/Keybindings_ru.md +++ b/docs/keybindings/Keybindings_ru.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | Обновить | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | Следующий режим экрана (нормальный/полуэкранный/полноэкранный) | | | `` _ `` | Предыдущий режим экрана | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | Отменить | | | `` ? `` | Открыть меню | | | `` `` | Просмотреть параметры фильтрации по пути | View options for filtering the commit log, so that only commits matching the filter are shown. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | Выйти | | | `` `` | Suspend the application | | | `` `` | Переключить отображение изменении пробелов в просмотрщике сравнении | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | Редактировать файл конфигурации | Open file in external editor. | | `` z `` | Отменить (через reflog) (экспериментальный) | Журнал ссылок (reflog) будет использоваться для определения того, какую команду git запустить, чтобы отменить последнюю команду git. Сюда не входят изменения в рабочем дереве; учитываются только коммиты. | | `` Z `` | Повторить (через reflog) (экспериментальный) | Журнал ссылок (reflog) будет использоваться для определения того, какую команду git нужно запустить, чтобы повторить последнюю команду git. Сюда не входят изменения в рабочем дереве; учитываются только коммиты. | @@ -112,7 +114,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | Выбрать эту часть | | -| `` b `` | Выбрать все части | | +| `` b `` | Pick both hunks | | | `` , k `` | Выбрать предыдущую часть | | | `` , j `` | Выбрать следующую часть | | | `` , h `` | Выбрать предыдущий конфликт | | @@ -149,6 +151,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Сбросить отобранную (скопированную \| cherry-picked) выборку коммитов | | @@ -156,7 +159,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Коммиты @@ -192,13 +194,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Open external diff tool (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Найти | | ## Локальные Ветки @@ -210,6 +212,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Переключить | Checkout selected item. | | `` n `` | Новая ветка | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | Создать запрос на принятие изменений | | | `` O `` | Создать параметры запроса принятие изменений | | | `` G `` | Open pull request in browser | | @@ -229,7 +232,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Меню @@ -258,6 +260,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | Открыть коммит в браузере | | | `` n `` | Создать новую ветку с этого коммита | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | Просмотреть параметры сброса | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | Скопировать отобранные коммит (cherry-pick) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | Сбросить отобранную (скопированную \| cherry-picked) выборку коммитов | | @@ -265,7 +268,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Найти | | ## Подмодули @@ -313,7 +315,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| -| `` o `` | Открыть файл конфигурации | Open file in default application. | | `` e `` | Редактировать файл конфигурации | Open file in external editor. | | `` u `` | Проверить обновления | | | `` `` | Переключиться на последний репозиторий | | @@ -328,13 +329,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | Переключить | Checkout the selected tag as a detached HEAD. | | `` n `` | Создать тег | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | Delete | View delete options for local/remote tag. | | `` P `` | Отправить тег | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | Reset | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Удалённые ветки @@ -344,6 +345,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Скопировать название ветки в буфер обмена | | | `` `` | Переключить | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | Новая ветка | | +| `` w `` | New worktree | | | `` M `` | Слияние с текущей переключённой веткой | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | Перебазировать переключённую ветку на эту ветку | Rebase the checked-out branch onto the selected branch. | | `` d `` | Delete | Delete the remote branch from the remote. | @@ -353,7 +355,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Open external diff tool (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть коммиты | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | ## Удалённые репозитории @@ -409,8 +410,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | Применить припрятанные изменения и тут же удалить их из хранилища | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | Удалить припрятанные изменения из хранилища | Remove the stash entry from the stash list. | | `` n `` | Новая ветка | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | Переименовать хранилище | | | `` 0 `` | Focus main view | | | `` `` | Просмотреть файлы выбранного элемента | | -| `` w `` | View worktree options | | | `` / `` | Filter the current view by text | | diff --git a/docs/keybindings/Keybindings_zh-CN.md b/docs/keybindings/Keybindings_zh-CN.md index 9cb7d5186..b4f1134ec 100644 --- a/docs/keybindings/Keybindings_zh-CN.md +++ b/docs/keybindings/Keybindings_zh-CN.md @@ -23,6 +23,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` + `` | 下一屏模式(正常/半屏/全屏) | | | `` _ `` | 上一屏模式 | | | `` \| `` | 切换分页器 | 从已配置的分页器列表中选择下一个分页器 | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | 取消 | | | `` ? `` | 打开菜单 | | | `` `` | 查看按路径过滤选项 | 查看用于过滤提交日志的选项,以便仅显示与过滤器匹配的提交。 | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | 退出 | | | `` `` | 挂起应用程序 | | | `` `` | 切换是否在差异视图中显示空白字符差异 | 切换是否在差异视图中显示空白字符更改。

默认值可在配置文件中通过键 'git.ignoreWhitespaceInDiffView' 更改。 | +| `` `` | 编辑配置文件 | 使用外部编辑器打开文件 | | `` z `` | 撤销 | Reflog将用于确定运行哪个git命令来撤消最后一个git命令。这并不包括对工作树的更改,只考虑提交。 | | `` Z `` | 重做 | Reflog将用于确定运行哪个git命令来重做上一个git命令。这并不包括对工作树的更改,只考虑提交。 | @@ -60,6 +62,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 重置已拣选(复制)的提交 | | @@ -67,7 +70,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 开始搜索 | | ## 子模块 @@ -104,6 +106,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 重置已拣选(复制)的提交 | | @@ -111,7 +114,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 提交 @@ -147,13 +149,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在浏览器中打开提交 | | | `` n `` | 从提交创建新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` g `` | 查看重置选项 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` C `` | 复制提交(拣选) | 标记提交为已复制。然后,在本地提交视图中,您可以按 `V` (Cherry-Pick) 将已复制的提交粘贴到已检出的分支中。任何时候都可以按 `` 来取消选择。 | | `` `` | 使用外部差异比较工具(git difftool) | | | `` * `` | 选择当前分支的提交 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 开始搜索 | | ## 提交信息 @@ -225,6 +227,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 检出 | 检出选中的项目 | | `` n `` | 新分支 | | | `` N `` | 移动提交至新分支 | 创建一个新分支,并将当前分支未推送的提交移动到该分支。如果您打算开始新工作但忘记先创建新分支,这会很有用。

请注意,此操作忽略选择,新分支总是从主分支创建或堆叠在当前分支之上(您可以选择哪种方式)。 | +| `` w `` | 新建工作树 | | | `` o `` | 创建拉取请求 | | | `` O `` | 创建拉取请求选项 | | | `` G `` | 在浏览器中打开拉取请求 | | @@ -244,7 +247,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 构建补丁中 @@ -270,13 +272,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 复制标签到剪贴板 | | | `` `` | 检出 | 检出选择的标签作为分离的HEAD | | `` n `` | 创建标签 | 基于当前提交创建一个新标签。您将在弹窗中输入标签名称和描述(可选)。 | +| `` w `` | 新建工作树 | | | `` d `` | 删除 | 查看本地/远程标签的删除选项 | | `` P `` | 推送标签 | 推送选择的标签到远端。您将在弹窗中选择一个远端。 | | `` g `` | 重置 | 查看重置选项 (soft/mixed/hard) 用于重置到选择项 | | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 次要 @@ -292,7 +294,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | 选中区块 | | -| `` b `` | 选中所有区块 | | +| `` b `` | Pick both hunks | | | `` , k `` | 选择顶部块 | | | `` , j `` | 选择底部块 | | | `` , h `` | 选择上一个冲突 | | @@ -339,7 +341,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| -| `` o `` | 打开配置文件 | 使用默认程序打开该文件 | | `` e `` | 编辑配置文件 | 使用外部编辑器打开文件 | | `` u `` | 检查更新 | | | `` `` | 切换到最近的仓库 | | @@ -371,10 +372,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | 应用并删除 | 将存储项应用到工作目录并删除存储项。 | | `` d `` | 删除 | 从贮藏列表中删除该贮藏项 | | `` n `` | 新分支 | 从选定的贮藏项创建一个新分支。这是通过 git 检查创建贮藏项的提交,从该提交创建一个新分支,然后将贮藏项作为附加提交应用到新分支来实现的。 | +| `` w `` | 新建工作树 | | | `` r `` | 重命名贮藏 | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交的文件 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | ## 输入提示 @@ -403,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 复制分支名称到剪贴板 | | | `` `` | 检出 | 基于当前选中的远程分支检出一个新的本地分支,或者将远程分支作分离的HEAD。 | | `` n `` | 新分支 | | +| `` w `` | 新建工作树 | | | `` M `` | 合并到当前检出的分支 | 查看将选中项合并到当前分支的选项(正常合并,压缩合并) | | `` r `` | 变基 | 将检出的分支变基到所选的分支上。 | | `` d `` | 删除 | 从远程删除远程分支。 | @@ -412,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 使用外部差异比较工具(git difftool) | | | `` 0 `` | 聚焦主视图 | | | `` `` | 查看提交 | | -| `` w `` | 查看工作区选项 | | | `` / `` | 通过文本过滤当前视图 | | diff --git a/docs/keybindings/Keybindings_zh-TW.md b/docs/keybindings/Keybindings_zh-TW.md index d6526b5b2..b50e25d35 100644 --- a/docs/keybindings/Keybindings_zh-TW.md +++ b/docs/keybindings/Keybindings_zh-TW.md @@ -22,7 +22,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` R `` | 重新整理 | Refresh the git state (i.e. run `git status`, `git branch`, etc in background to update the contents of panels). This does not run `git fetch`. | | `` + `` | 下一個螢幕模式(常規/半螢幕/全螢幕) | | | `` _ `` | 上一個螢幕模式 | | -| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers | +| `` \| `` | Cycle pagers | Choose the next pager in the list of configured pagers. | +| `` \ `` | Cycle pagers (reverse) | Choose the previous pager in the list of configured pagers. | | `` `` | 取消 | | | `` ? `` | 開啟選單 | | | `` `` | 檢視篩選路徑選項 | View options for filtering the commit log, so that only commits matching the filter are shown. | @@ -30,6 +31,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` q, `` | 結束 | | | `` `` | Suspend the application | | | `` `` | 切換是否在差異檢視中顯示空格變更 | Toggle whether or not whitespace changes are shown in the diff view.

The default can be changed in the config file with the key 'git.ignoreWhitespaceInDiffView'. | +| `` `` | 編輯設定檔案 | 使用外部編輯器開啟 | | `` z `` | 復原 | 將使用 reflog 確任 git 指令以復原。這不包括工作區更改;只考慮提交。 | | `` Z `` | 取消復原 | 將使用 reflog 確任 git 指令以重作。這不包括工作區更改;只考慮提交。 | @@ -88,7 +90,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| | `` `` | 挑選程式碼片段 | | -| `` b `` | 挑選所有程式碼片段 | | +| `` b `` | Pick both hunks | | | `` , k `` | 選擇上一段 | | | `` , j `` | 選擇下一段 | | | `` , h `` | 選擇上一個衝突 | | @@ -139,6 +141,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 重設選定的揀選 (複製) 提交 | | @@ -146,7 +149,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 子模組 @@ -206,13 +208,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 開啟外部差異工具 (git difftool) | | | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 提交摘要 @@ -250,10 +252,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` g `` | 還原 | Apply the stash entry to your working directory and remove the stash entry. | | `` d `` | 捨棄 | Remove the stash entry from the stash list. | | `` n `` | 新分支 | Create a new branch from the selected stash entry. This works by git checking out the commit that the stash entry was created from, creating a new branch from that commit, then applying the stash entry to the new branch as an additional commit. | +| `` w `` | New worktree | | | `` r `` | 重新命名收藏 | | | `` 0 `` | Focus main view | | | `` `` | 檢視所選項目的檔案 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 日誌 @@ -266,6 +268,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` o `` | 在瀏覽器中開啟提交 | | | `` n `` | 從提交建立新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` g `` | 檢視重設選項 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` C `` | 複製提交 (揀選) | Mark commit as copied. Then, within the local commits view, you can press `V` to paste (cherry-pick) the copied commit(s) into your checked out branch. At any time you can press `` to cancel the selection. | | `` `` | 重設選定的揀選 (複製) 提交 | | @@ -273,7 +276,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` * `` | Select commits of current branch | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 本地分支 @@ -285,6 +287,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 檢出 | 檢出選定的項目。 | | `` n `` | 新分支 | | | `` N `` | Move commits to new branch | Create a new branch and move the unpushed commits of the current branch to it. Useful if you meant to start new work and forgot to create a new branch first.

Note that this disregards the selection, the new branch is always created either from the main branch or stacked on top of the current branch (you get to choose which). | +| `` w `` | New worktree | | | `` o `` | 建立拉取請求 | | | `` O `` | 建立拉取請求選項 | | | `` G `` | Open pull request in browser | | @@ -304,7 +307,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 標籤 @@ -314,13 +316,13 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | Copy tag to clipboard | | | `` `` | 檢出 | Checkout the selected tag as a detached HEAD. | | `` n `` | 建立標籤 | Create new tag from current commit. You'll be prompted to enter a tag name and optional description. | +| `` w `` | New worktree | | | `` d `` | 刪除 | View delete options for local/remote tag. | | `` P `` | 推送標籤 | Push the selected tag to a remote. You'll be prompted to select a remote. | | `` g `` | 重設 | View reset options (soft/mixed/hard) for resetting onto selected item. | | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | ## 檔案 @@ -368,7 +370,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | Key | Action | Info | |-----|--------|-------------| -| `` o `` | 開啟設定檔案 | 使用預設軟體開啟 | | `` e `` | 編輯設定檔案 | 使用外部編輯器開啟 | | `` u `` | 檢查更新 | | | `` `` | 切換到最近使用的版本庫 | | @@ -403,6 +404,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 複製分支名稱到剪貼簿 | | | `` `` | 檢出 | Checkout a new local branch based on the selected remote branch, or the remote branch as a detached head. | | `` n `` | 新分支 | | +| `` w `` | New worktree | | | `` M `` | 合併到當前檢出的分支 | View options for merging the selected item into the current branch (regular merge, squash merge) | | `` r `` | 將已檢出的分支變基至此分支 | Rebase the checked-out branch onto the selected branch. | | `` d `` | 刪除 | Delete the remote branch from the remote. | @@ -412,5 +414,4 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` `` | 開啟外部差異工具 (git difftool) | | | `` 0 `` | Focus main view | | | `` `` | 檢視提交 | | -| `` w `` | 檢視工作目錄選項 | | | `` / `` | 搜尋 | | diff --git a/schema/config.json b/schema/config.json index 2e968ba8f..82dbebb0b 100644 --- a/schema/config.json +++ b/schema/config.json @@ -321,7 +321,7 @@ "$ref": "#/$defs/PagingConfig" }, "type": "array", - "description": "Array of pagers. Each entry has the following format:\n\n # Value of the --color arg in the git diff command. Some pagers want\n # this to be set to 'always' and some want it set to 'never'\n colorArg: \"always\"\n\n # e.g.\n # diff-so-fancy\n # delta --dark --paging=never\n # ydiff -p cat -s --wrap --width={{columnWidth}}\n pager: \"\"\n\n # e.g. 'difft --color=always'\n externalDiffCommand: \"\"\n\n # If true, Lazygit will use git's `diff.external` config for paging.\n # The advantage over `externalDiffCommand` is that this can be\n # configured per file type in .gitattributes; see\n # https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver.\n useExternalDiffGitConfig: false\n\nSee https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md for more information." + "description": "Array of pagers. Each entry has the following format:\n\n # A name for the pager, shown in the notification when cycling pagers.\n # If not set, the name is derived from the first word of the pager\n # command (or of the external diff command).\n name: \"\"\n\n # Value of the --color arg in the git diff command. Some pagers want\n # this to be set to 'always' and some want it set to 'never'\n colorArg: \"always\"\n\n # e.g.\n # diff-so-fancy\n # delta --dark --paging=never\n # ydiff -p cat -s --wrap --width={{columnWidth}}\n pager: \"\"\n\n # e.g. 'difft --color=always'\n externalDiffCommand: \"\"\n\n # If true, Lazygit will use git's `diff.external` config for paging.\n # The advantage over `externalDiffCommand` is that this can be\n # configured per file type in .gitattributes; see\n # https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver.\n useExternalDiffGitConfig: false\n\n'pager', 'externalDiffCommand', and 'useExternalDiffGitConfig' are mutually exclusive; set at most one per entry.\n\nSee https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md for more information." }, "commit": { "$ref": "#/$defs/CommitConfig", @@ -358,6 +358,11 @@ "description": "If true, periodically refresh files and submodules", "default": true }, + "autoDetectExternalChanges": { + "type": "boolean", + "description": "If true, poll the repo periodically for external ref changes (commits, branch updates, checkouts made outside lazygit) and refresh when one is detected. Independent of autoRefresh, which only governs the files panel.", + "default": true + }, "autoForwardBranches": { "type": "string", "enum": [ @@ -585,6 +590,40 @@ "description": "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.", "default": 2 }, + "shrinkSidePanelsToContent": { + "type": "boolean", + "description": "If true, don't give a side panel more height than it needs to show its content; when all panels fit, the leftover height is shared among them so that they still fill the screen.", + "default": false + }, + "sidePanels": { + "items": { + "$ref": "#/$defs/SidePanel" + }, + "type": "array", + "description": "The side panels, in the order they appear from top to bottom.\nEach entry is a list of one or more names that share a single panel as tabs (cycle through them with the next-tab/previous-tab keys).\nOmit a name to hide it; give a name its own one-element list to promote a tab to a top-level panel.\nValid names are: 'status', 'files', 'worktrees', 'submodules', 'branches', 'remotes', 'tags', 'commits', 'reflog', 'stash'. 'files', 'branches', and 'commits' must always be included; they can't be hidden.", + "default": [ + [ + "status" + ], + [ + "files", + "worktrees", + "submodules" + ], + [ + "branches", + "remotes", + "tags" + ], + [ + "commits", + "reflog" + ], + [ + "stash" + ] + ] + }, "mainPanelSplitMode": { "type": "string", "enum": [ @@ -1624,9 +1663,6 @@ "branches": { "$ref": "#/$defs/KeybindingBranchesConfig" }, - "worktrees": { - "$ref": "#/$defs/KeybindingWorktreesConfig" - }, "commits": { "$ref": "#/$defs/KeybindingCommitsConfig" }, @@ -2847,6 +2883,20 @@ ], "default": "n" }, + "newWorktree": { + "oneOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "default": "w" + }, "edit": { "oneOf": [ { @@ -3127,6 +3177,20 @@ ], "default": "|" }, + "cyclePagersReverse": { + "oneOf": [ + { + "type": "string" + }, + { + "items": { + "type": "string" + }, + "type": "array" + } + ], + "default": "\\" + }, "undo": { "oneOf": [ { @@ -3340,14 +3404,8 @@ } ], "default": "\u003cctrl+t\u003e" - } - }, - "additionalProperties": false, - "type": "object" - }, - "KeybindingWorktreesConfig": { - "properties": { - "viewWorktreeOptions": { + }, + "editConfig": { "oneOf": [ { "type": "string" @@ -3359,7 +3417,7 @@ "type": "array" } ], - "default": "w" + "default": "\u003calt+shift+c\u003e" } }, "additionalProperties": false, @@ -3488,6 +3546,10 @@ }, "PagingConfig": { "properties": { + "name": { + "type": "string", + "description": "A name for the pager, shown in the notification when cycling pagers. If not set, the name is derived from the first word of the pager command (or of the external diff command)." + }, "colorArg": { "type": "string", "enum": [ @@ -3521,21 +3583,45 @@ "properties": { "refreshInterval": { "type": "integer", - "minimum": 0, + "exclusiveMinimum": 0, "description": "File/submodule refresh interval in seconds.\nAuto-refresh can be disabled via option 'git.autoRefresh'.", "default": 10 }, "fetchInterval": { "type": "integer", - "minimum": 0, + "exclusiveMinimum": 0, "description": "Re-fetch interval in seconds.\nAuto-fetch can be disabled via option 'git.autoFetch'.", "default": 60 + }, + "externalChangeCheckInterval": { + "type": "integer", + "exclusiveMinimum": 0, + "description": "Interval in seconds at which lazygit polls for external ref changes (commits, branch updates, checkouts made outside lazygit).\nDetection can be disabled via option 'git.autoDetectExternalChanges'.", + "default": 2 } }, "additionalProperties": false, "type": "object", "description": "Background refreshes" }, + "SidePanel": { + "items": { + "type": "string", + "enum": [ + "status", + "files", + "worktrees", + "submodules", + "branches", + "remotes", + "tags", + "commits", + "reflog", + "stash" + ] + }, + "type": "array" + }, "SpinnerConfig": { "properties": { "frames": { @@ -3744,6 +3830,10 @@ "$ref": "#/$defs/GitConfig", "description": "Config relating to git" }, + "worktree": { + "$ref": "#/$defs/WorktreeConfig", + "description": "Config relating to git worktrees" + }, "update": { "$ref": "#/$defs/UpdateConfig", "description": "Periodic update checks" @@ -3809,6 +3899,17 @@ }, "additionalProperties": false, "type": "object" + }, + "WorktreeConfig": { + "properties": { + "defaultPath": { + "type": "string", + "description": "Default parent directory for new worktrees. It is offered as a candidate location alongside the parent directories of any worktrees you already have.\nA relative path is resolved against the repository's root directory, so \"../worktrees\" sits beside the repo and \".worktrees\" sits inside it.\nA leading \"~\" is expanded to your home directory, so \"~/worktrees\" works." + } + }, + "additionalProperties": false, + "type": "object", + "description": "Config relating to git worktrees" } } } From 44ba0d539fa1c059a7efd4770e973490b72a3fae Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 11:54:14 +0200 Subject: [PATCH 040/218] Show a waiting status while continuing a merge or rebase Continuing, skipping, or aborting a merge/rebase from the options menu ran the git command inline on the UI thread, freezing the UI with no spinner while it worked (a continue can replay many commits). Run the non-subprocess path on a worker with a waiting status instead, matching how the other merge/rebase entry points already behave. The auto-skip recursion in CheckMergeOrRebaseWithRefreshOptions must not start its own worker: it already runs on the caller's thread (the worker of the enclosing waiting status, or the UI thread for the synchronous callers). Route it through genericMergeCommandImpl with the waiting status suppressed so its behavior is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index be1d7b3a9..6badaf2b4 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -79,6 +79,18 @@ func (self *MergeAndRebaseHelper) ContinueRebase() error { } func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { + return self.genericMergeCommandImpl(command, true) +} + +// genericMergeCommandImpl runs a merge/rebase continue/skip/abort and handles +// the result. Continuing can be slow (it may replay many commits), so the +// non-subprocess path runs on a worker with a waiting status. +// +// showWaitingStatus is false only for the recursive auto-skip in +// CheckMergeOrRebaseWithRefreshOptions: that call already runs on the caller's +// thread (the worker of the enclosing waiting status, or the UI thread for the +// synchronous callers), so it must not spin up a second one. +func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWaitingStatus bool) error { status := self.c.Git().Status.WorkingTreeState() if status.None() { @@ -123,12 +135,22 @@ func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { self.RecordWhetherMergeOrRebaseStartedInLazygit() return err } - result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) - return self.CheckMergeOrRebaseWithRefreshOptions(result, - types.RefreshOptions{ - Mode: types.ASYNC, - CommitSelection: commitSelectionAfterMerge(result == nil && selectHeadCommitOnSuccess), + + runAction := func() error { + result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) + return self.CheckMergeOrRebaseWithRefreshOptions(result, + types.RefreshOptions{ + Mode: types.ASYNC, + CommitSelection: commitSelectionAfterMerge(result == nil && selectHeadCommitOnSuccess), + }) + } + + if showWaitingStatus { + return self.c.WithWaitingStatus(status.Title(self.c.Tr), func(gocui.Task) error { + return runAction() }) + } + return runAction() } // commitSelectionAfterMerge maps whether a merge/rebase/pull created a new @@ -191,9 +213,9 @@ func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result er if result == nil { return nil } else if strings.Contains(result.Error(), "No changes - did you forget to use") { - return self.genericMergeCommand(REBASE_OPTION_SKIP) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false) } else if strings.Contains(result.Error(), "The previous cherry-pick is now empty") { - return self.genericMergeCommand(REBASE_OPTION_SKIP) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false) } else if strings.Contains(result.Error(), "No rebase in progress?") { // assume in this case that we're already done return nil From 539ede2e1bb47ae466ad6ce2cc4bfa0b1dc2f352 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 11:54:38 +0200 Subject: [PATCH 041/218] Show a waiting status while merging a branch The regular and squash merges from the merge menu ran inline on the UI thread, freezing it with no spinner while git worked. Run them on a worker with a waiting status, like the rebase entry points already do. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 6badaf2b4..b00a4d41b 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -586,36 +586,42 @@ func (self *MergeAndRebaseHelper) MergeRefIntoCheckedOutBranch(refName string) e func (self *MergeAndRebaseHelper) RegularMerge(refName string, variant git_commands.MergeVariant) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.Merge) - err := self.c.Git().Branch.Merge(refName, variant) - return self.CheckMergeOrRebaseAndSelectHeadCommit(err) + return self.c.WithWaitingStatus(self.c.Tr.MergingStatus, func(gocui.Task) error { + err := self.c.Git().Branch.Merge(refName, variant) + return self.CheckMergeOrRebaseAndSelectHeadCommit(err) + }) } } func (self *MergeAndRebaseHelper) SquashMergeUncommitted(refName string) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.SquashMerge) - err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) - return self.CheckMergeOrRebase(err) + return self.c.WithWaitingStatus(self.c.Tr.MergingStatus, func(gocui.Task) error { + err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) + return self.CheckMergeOrRebase(err) + }) } } func (self *MergeAndRebaseHelper) SquashMergeCommitted(refName, checkedOutBranchName string) func() error { return func() error { self.c.LogAction(self.c.Tr.Actions.SquashMerge) - err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) - if err = self.CheckMergeOrRebase(err); err != nil { - return err - } - message := utils.ResolvePlaceholderString(self.c.UserConfig().Git.Merging.SquashMergeMessage, map[string]string{ - "selectedRef": refName, - "currentBranch": checkedOutBranchName, + return self.c.WithWaitingStatus(self.c.Tr.MergingStatus, func(gocui.Task) error { + err := self.c.Git().Branch.Merge(refName, git_commands.MERGE_VARIANT_SQUASH) + if err = self.CheckMergeOrRebase(err); err != nil { + return err + } + message := utils.ResolvePlaceholderString(self.c.UserConfig().Git.Merging.SquashMergeMessage, map[string]string{ + "selectedRef": refName, + "currentBranch": checkedOutBranchName, + }) + err = self.c.Git().Commit.CommitCmdObj(message, "", false).Run() + if err != nil { + return err + } + self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + return nil }) - err = self.c.Git().Commit.CommitCmdObj(message, "", false).Run() - if err != nil { - return err - } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) - return nil } } From 2bae29c6fd32b3477cb6ca82d031fe2c23b1a377 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 11:55:12 +0200 Subject: [PATCH 042/218] Show a waiting status when starting an interactive rebase onto a ref The interactive-rebase item in the rebase-onto-ref menu ran inline on the UI thread with no spinner, unlike its two siblings in the same menu (simple rebase and rebase onto base branch), which already run on a worker with a waiting status. Make it consistent. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index b00a4d41b..4b25d1a62 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -408,21 +408,23 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { Tooltip: self.c.Tr.InteractiveRebaseTooltip, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) - baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() - var err error - if baseCommit != "" { - err = self.c.Git().Rebase.EditRebaseFromBaseCommit(ref, baseCommit) - } else { - err = self.c.Git().Rebase.EditRebase(ref) - } - if err = self.CheckMergeOrRebase(err); err != nil { - return err - } - if err = self.ResetMarkedBaseCommit(); err != nil { - return err - } - self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) - return nil + return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { + baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() + var err error + if baseCommit != "" { + err = self.c.Git().Rebase.EditRebaseFromBaseCommit(ref, baseCommit) + } else { + err = self.c.Git().Rebase.EditRebase(ref) + } + if err = self.CheckMergeOrRebase(err); err != nil { + return err + } + if err = self.ResetMarkedBaseCommit(); err != nil { + return err + } + self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + return nil + }) }, }, { From ccf49c8112407c2788aa96469a1aa61f299a5db2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 11:55:28 +0200 Subject: [PATCH 043/218] Show a waiting status when editing a commit Setting a single commit to "edit" ran the interactive rebase inline on the UI thread with no spinner, while its sibling startInteractiveRebaseWithEdit (used when editing multiple commits or quick-starting a rebase) already runs on a worker with a waiting status. Make the direct path match. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/local_commits_controller.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 80f01fc03..9f3acb1d2 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -589,9 +589,11 @@ func (self *LocalCommitsController) edit(selectedCommits []*models.Commit, start commits := self.c.Model().Commits if !commits[endIdx].IsMerge() { - err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, todo.Edit, "") - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( - err, types.RefreshOptions{Mode: types.BLOCK_UI}) + return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { + err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, todo.Edit, "") + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + err, types.RefreshOptions{Mode: types.BLOCK_UI}) + }) } return self.startInteractiveRebaseWithEdit(selectedCommits) From 6681ba7eda2694d107727f5279b7b55cd3f7dd43 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 11:56:07 +0200 Subject: [PATCH 044/218] Show a waiting status while resetting to a ref Resetting to a commit/branch/tag from the reset menu ran inline on the UI thread with no spinner; a hard reset to a distant commit can take a while and blocks the UI meanwhile. Run it on a worker with a waiting status. The undo/redo callers of ResetToRef already wrap it this way. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refs_helper.go | 4 +++- pkg/i18n/english.go | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 99e9f47ec..b90b9150b 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -288,7 +288,9 @@ func (self *RefsHelper) CreateGitResetMenu(name string, ref string) error { Prompt: self.c.Tr.ResetHardConfirmation, HandleConfirm: func() error { self.c.LogAction("Reset") - return self.ResetToRef(ref, row.strength, []string{}) + return self.c.WithWaitingStatus(self.c.Tr.ResettingStatus, func(gocui.Task) error { + return self.ResetToRef(ref, row.strength, []string{}) + }) }, }) }, diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 6f18842d5..0ee0a9e86 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -430,6 +430,7 @@ type TranslationSet struct { CommittingStatus string RewordingStatus string RevertingStatus string + ResettingStatus string CreatingFixupCommitStatus string MovingCommitsToNewBranchStatus string CommitFiles string @@ -1582,6 +1583,7 @@ func EnglishTranslationSet() *TranslationSet { CommittingStatus: "Committing", RewordingStatus: "Rewording", RevertingStatus: "Reverting", + ResettingStatus: "Resetting", CreatingFixupCommitStatus: "Creating fixup commit", MovingCommitsToNewBranchStatus: "Moving commits to new branch", CommitFiles: "Commit files", From 775ebc9e44828e7672590df8e04b033c20fbc201 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 17:16:45 +0200 Subject: [PATCH 045/218] Re-render to clear an inline status when its operation finishes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operations that show an inline status ("Pushing", "Fast-forwarding", "Fetching", …) removed it by relying on the async refresh they trigger to redraw the view after the item operation had been cleared. That ordering was never guaranteed: the item operation is cleared on the worker once the operation's function returns, while the refresh redraws the item from the UI thread whenever its (asynchronous) git work happens to finish. If the refresh redrew before the clear, the status was left on screen with no later redraw to remove it, so the branch (or tag/remote) stayed stuck showing e.g. "Pushing" indefinitely even though the operation had completed. This is timing-dependent, which is why it surfaced as rare, hard-to-reproduce reports and as flaky CI failures. Fix it by re-rendering in stop() right after clearing the operation, and by making these refreshes synchronous rather than async. Because a synchronous refresh has already updated the model and queued its own redraw by the time stop() runs, and UI-thread callbacks run in order, the redraw we queue here runs last and draws the up-to-date model with the status removed. An async refresh couldn't give that guarantee: its model update might not have landed yet, so the redraw could briefly flash the pre-operation status. Pull refreshes through the shared CheckMergeOrRebaseAndSelectHeadCommit, so that helper becomes synchronous too; its only other caller, RegularMerge, thereby also refreshes synchronously, which is fine: a synchronous on-worker refresh is what we want anyway. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/branches_controller.go | 4 +-- .../helpers/inline_status_helper.go | 28 ++++++++----------- .../helpers/merge_and_rebase_helper.go | 2 +- pkg/gui/controllers/remotes_controller.go | 2 +- pkg/gui/controllers/sync_controller.go | 2 +- pkg/gui/controllers/tags_controller.go | 4 +-- 6 files changed, 19 insertions(+), 23 deletions(-) diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index 27bef4b66..45f98e9c5 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -734,7 +734,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { WorktreePath: worktreePath, }, ) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) return err } @@ -743,7 +743,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { err := self.c.Git().Sync.FastForward( task, branch.Name, branch.UpstreamRemote, branch.UpstreamBranch, ) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return err }) } diff --git a/pkg/gui/controllers/helpers/inline_status_helper.go b/pkg/gui/controllers/helpers/inline_status_helper.go index 0902c5bf2..f2ca7ec17 100644 --- a/pkg/gui/controllers/helpers/inline_status_helper.go +++ b/pkg/gui/controllers/helpers/inline_status_helper.go @@ -138,22 +138,18 @@ func (self *InlineStatusHelper) stop(opts InlineStatusOpts) { self.c.State().ClearItemOperation(opts.Item) - // When recording a demo we need to re-render the context again here to - // remove the inline status. In normal usage we don't want to do this - // because in the case of pushing a branch this would first reveal the ↑3↓7 - // status from before the push for a brief moment, to be replaced by a green - // checkmark a moment later when the async refresh is done. This looks - // jarring, so normally we rely on the async refresh to redraw with the - // status removed. (In some rare cases, where there's no refresh at all, we - // need to redraw manually in the controller; see TagsController.push() for - // an example.) - // - // In demos, however, we turn all async refreshes into sync ones, because - // this looks better in demos. In this case the refresh happens while the - // status is still set, so we need to render again after removing it. - if self.c.InDemo() { - self.renderContext(opts.ContextKey) - } + // Re-render the context to remove the inline status now that the operation + // finished. Any refresh it triggered must be synchronous, not async: by the + // time we get here a synchronous refresh has already updated the model and + // queued its own re-render, and since UI-thread callbacks run in order, the + // render we queue here runs after it and draws the up-to-date model without + // the inline status. An async refresh might not have updated the model yet, + // so this render could briefly show the stale, pre-operation model: when + // pushing a branch, for example, it would flash the old ↑3↓7 ahead/behind + // counts for a moment before the refresh replaced them with a green + // checkmark. (Operations that don't refresh at all are fine too: there's + // nothing stale to show, so this just drops the status.) + self.renderContext(opts.ContextKey) } func (self *InlineStatusHelper) renderContext(contextKey types.ContextKey) { diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 4b25d1a62..847b89893 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -233,7 +233,7 @@ func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { // before the refresh. func (self *MergeAndRebaseHelper) CheckMergeOrRebaseAndSelectHeadCommit(result error) error { return self.CheckMergeOrRebaseWithRefreshOptions(result, - types.RefreshOptions{Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(result == nil)}) + types.RefreshOptions{Mode: types.SYNC, CommitSelection: commitSelectionAfterMerge(result == nil)}) } func (self *MergeAndRebaseHelper) CheckForConflicts(result error) error { diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index dd5a171e4..f7b16e228 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -367,7 +367,7 @@ func (self *RemotesController) fetchAndCheckout(remote *models.Remote, branchNam } refreshOptions := types.RefreshOptions{ Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}, - Mode: types.ASYNC, + Mode: types.SYNC, } if branchName != "" { err = self.c.Git().Branch.New(branchName, remote.Name+"/"+branchName) diff --git a/pkg/gui/controllers/sync_controller.go b/pkg/gui/controllers/sync_controller.go index f1b794e97..0f754eb49 100644 --- a/pkg/gui/controllers/sync_controller.go +++ b/pkg/gui/controllers/sync_controller.go @@ -229,7 +229,7 @@ func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts) } return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) return nil }) } diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index 879a73628..3cb5e0450 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -210,7 +210,7 @@ func (self *TagsController) remoteDelete(tag *models.Tag) error { return err } self.c.Toast(self.c.Tr.RemoteTagDeletedMessage) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, @@ -264,7 +264,7 @@ func (self *TagsController) localAndRemoteDelete(tag *models.Tag) error { if err := self.c.Git().Tag.LocalDelete(tag.Name); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, From 78dd678ce518910dcf486a8cb2396a389cc60228 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 17:20:38 +0200 Subject: [PATCH 046/218] Drop the now-redundant manual re-render in tag push Pushing a tag triggers no refresh, so it used to redraw the tags view by hand to remove the "Pushing" inline status. WithInlineStatus now always re-renders after clearing the operation, so this is redundant. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/tags_controller.go | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index 3cb5e0450..fe2c4e80f 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -332,15 +332,7 @@ func (self *TagsController) push(tag *models.Tag) error { HandleConfirm: func(response string) error { return self.c.WithInlineStatus(tag, types.ItemOperationPushing, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.PushTag) - err := self.c.Git().Tag.Push(task, response, tag.Name) - - // Render again to remove the inline status: - self.c.OnUIThread(func() error { - self.c.Contexts().Tags.HandleRender() - return nil - }) - - return err + return self.c.Git().Tag.Push(task, response, tag.Name) }) }, }) From dd1576138a248b8d643921d7f6d6d5ad7c3fa238 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 22:44:07 +0200 Subject: [PATCH 047/218] AGENTS.md additions --- AGENTS.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 46ad3e506..6aa8f7017 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,9 @@ while still being meaningful and self-contained. commits that leave the tree broken and rely on a follow-up to fix it. - **Every commit must be `gofumpt`-formatted.** Run `just format` before committing. +- **Every commit must be lint-clean.** Run `just lint` before committing — + don't introduce a lint warning in one commit and rely on a later commit + (or the user) to clean it up. - **Commit messages explain _why_, not _what_.** The diff already shows what changed; the message should capture the motivation, the constraint, or the bug being fixed. If the reason is obvious from a one-line subject, no body @@ -157,6 +160,16 @@ genuine forks — the ones where a reasonable person might pick differently, or where you'd be trading away something the plan assumed (scope, UX, performance, reload behavior, …). When in doubt, surface it. +This applies with equal force to unforeseen _discoveries_, not just to +decisions you set out to make. If you find something the plan didn't account +for — a latent bug, a race, a wrong assumption, a case that turns out +unhandled — stop and raise it before designing or writing a fix, even when the +fix seems obvious and even when it's "just correctness." Finding the problem is +itself the fork: whether to fix it here or in a separate change, how generally +to solve it, and whether it reshapes the current work are all calls for me to +make with you. Don't quietly fold a self-directed fix for a newly-found problem +into the branch and let me discover it in the diff. + ## Prefer the cleaner design over the smaller diff When a task could be implemented either by tacking onto existing code or by From 5350b6c37b20258f9024be038f5b3c488534c606 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 22:09:25 +0200 Subject: [PATCH 048/218] Remove unused CommitFileTreeViewModel.RWMutex --- pkg/gui/filetree/commit_file_tree_view_model.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/pkg/gui/filetree/commit_file_tree_view_model.go b/pkg/gui/filetree/commit_file_tree_view_model.go index c2e7e74e4..e33316788 100644 --- a/pkg/gui/filetree/commit_file_tree_view_model.go +++ b/pkg/gui/filetree/commit_file_tree_view_model.go @@ -2,7 +2,6 @@ package filetree import ( "strings" - "sync" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" @@ -26,7 +25,6 @@ type ICommitFileTreeViewModel interface { } type CommitFileTreeViewModel struct { - sync.RWMutex types.IListCursor ICommitFileTree From b54d4c369bb64415b79e89ad0c5c275a971fd8dc Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 21:45:02 +0200 Subject: [PATCH 049/218] Remove unused IsRefreshingFiles state GetIsRefreshingFiles() is never called anywhere in the codebase, so the flag serves no purpose. Remove it from Gui, StateAccessor, and IStateAccessor, and drop the two SetIsRefreshingFiles calls in refreshFilesAndSubmodules that maintained it. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 6 +----- pkg/gui/gui.go | 10 ---------- pkg/gui/types/common.go | 2 -- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 3dbd19674..866ec90c3 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -735,11 +735,7 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { self.c.Mutexes().RefreshingFilesMutex.Lock() - self.c.State().SetIsRefreshingFiles(true) - defer func() { - self.c.State().SetIsRefreshingFiles(false) - self.c.Mutexes().RefreshingFilesMutex.Unlock() - }() + defer self.c.Mutexes().RefreshingFilesMutex.Unlock() if err := self.refreshStateSubmoduleConfigs(); err != nil { return err diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index e23afd124..87a87f7b2 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -111,8 +111,6 @@ type Gui struct { 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 @@ -175,14 +173,6 @@ 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 } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 7621f8686..ad28972ae 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -377,8 +377,6 @@ type IStateAccessor interface { // tells us whether we're currently updating lazygit GetUpdating() bool SetUpdating(bool) - SetIsRefreshingFiles(bool) - GetIsRefreshingFiles() bool GetShowExtrasWindow() bool SetShowExtrasWindow(bool) GetRetainOriginalDir() bool From 717448f105589033f562e17ac195b1a9e4725110 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 22:33:33 +0200 Subject: [PATCH 050/218] Make RefreshOptions.Then a func() error, queue it via OnUIThread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is preparation for upcoming commits that will bounce refresh-scope model updates (e.g. Model.Files) onto the UI thread by enqueuing the write via OnUIThread instead of applying it directly on the worker goroutine. Once that lands, a Then callback that reads the model must run after that queued write has been processed, not synchronously at wg.Wait() time — at that point the workers have returned, but a bounce they queued may not have been processed yet. Queuing Then via OnUIThread here, ahead of that change, guarantees the right ordering once it lands: a bounce queued earlier in the same refresh is already sitting in the channel by the time wg.Wait() returns, so Then enqueued after it will always be processed after, and see the post-refresh model. The signature change to func() error lets Then propagate errors through gocui's normal error handler (the same path key-handler errors take). Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/bisect_controller.go | 7 +++++-- pkg/gui/controllers/filtering_menu_action.go | 3 ++- pkg/gui/controllers/helpers/mode_helper.go | 3 ++- pkg/gui/controllers/helpers/refresh_helper.go | 8 +++++++- pkg/gui/controllers/local_commits_controller.go | 8 +++----- pkg/gui/types/refresh.go | 2 +- 6 files changed, 20 insertions(+), 11 deletions(-) diff --git a/pkg/gui/controllers/bisect_controller.go b/pkg/gui/controllers/bisect_controller.go index 1066237c1..eb568240b 100644 --- a/pkg/gui/controllers/bisect_controller.go +++ b/pkg/gui/controllers/bisect_controller.go @@ -274,10 +274,11 @@ func (self *BisectController) afterMark(selectCurrent bool, waitToReselect bool) } func (self *BisectController) afterBisectMarkRefresh(selectCurrent bool, waitToReselect bool) error { - selectFn := func() { + selectFn := func() error { if selectCurrent { self.selectCurrentBisectCommit() } + return nil } if waitToReselect { @@ -285,7 +286,9 @@ func (self *BisectController) afterBisectMarkRefresh(selectCurrent bool, waitToR return nil } - selectFn() + if err := selectFn(); err != nil { + return err + } self.c.Helpers().Bisect.PostBisectCommandRefresh() return nil diff --git a/pkg/gui/controllers/filtering_menu_action.go b/pkg/gui/controllers/filtering_menu_action.go index 01a236f7a..7ae26c4ef 100644 --- a/pkg/gui/controllers/filtering_menu_action.go +++ b/pkg/gui/controllers/filtering_menu_action.go @@ -122,9 +122,10 @@ func (self *FilteringMenuAction) setFiltering() error { self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) - self.c.Refresh(types.RefreshOptions{Scope: helpers.ScopesToRefreshWhenFilteringModeChanges(), Then: func() { + self.c.Refresh(types.RefreshOptions{Scope: helpers.ScopesToRefreshWhenFilteringModeChanges(), Then: func() error { self.c.Contexts().LocalCommits.SetSelection(0) self.c.Contexts().LocalCommits.HandleFocus(types.OnFocusOpts{}) + return nil }}) return nil diff --git a/pkg/gui/controllers/helpers/mode_helper.go b/pkg/gui/controllers/helpers/mode_helper.go index e44d7b01b..4947e42d1 100644 --- a/pkg/gui/controllers/helpers/mode_helper.go +++ b/pkg/gui/controllers/helpers/mode_helper.go @@ -191,7 +191,7 @@ func (self *ModeHelper) ClearFiltering() error { self.c.Refresh(types.RefreshOptions{ Scope: ScopesToRefreshWhenFilteringModeChanges(), - Then: func() { + Then: func() error { // Find the commit that was last selected in filtering mode, and select it again after refreshing if !self.c.Contexts().LocalCommits.SelectCommitByHash(selectedCommitHash) { // If we couldn't find it (either because no commit was selected @@ -202,6 +202,7 @@ func (self *ModeHelper) ClearFiltering() error { } self.c.PostRefreshUpdate(self.c.Contexts().LocalCommits) + return nil }, }) return nil diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 866ec90c3..2933d9378 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -255,7 +255,13 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { wg.Wait() if options.Then != nil { - options.Then() + // Queue Then via OnUIThread so it runs *after* the refresh-scope + // functions' model-update bounces (which are already queued by + // now), not synchronously here — at this point the workers have + // returned but their bounces haven't been processed yet, so + // invoking Then synchronously would run it on a model that's + // still pre-refresh. + self.c.OnUIThread(options.Then) } } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 9f3acb1d2..5150e8fba 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -616,7 +616,7 @@ func (self *LocalCommitsController) startInteractiveRebaseWithEdit( err := self.c.Git().Rebase.EditRebase(commitsToEdit[len(commitsToEdit)-1].Hash()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, - types.RefreshOptions{Mode: types.BLOCK_UI, Then: func() { + types.RefreshOptions{Mode: types.BLOCK_UI, Then: func() error { todos := make([]*models.Commit, 0, len(commitsToEdit)-1) for _, c := range commitsToEdit[:len(commitsToEdit)-1] { // Merge commits can't be set to "edit", so just skip them @@ -625,11 +625,9 @@ func (self *LocalCommitsController) startInteractiveRebaseWithEdit( } } if len(todos) > 0 { - err := self.updateTodos(todo.Edit, todos) - if err != nil { - self.c.Log.Errorf("error when updating todos: %v", err) - } + return self.updateTodos(todo.Edit, todos) } + return nil }}) }) } diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index 8d9704d55..591aff5f3 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -56,7 +56,7 @@ const ( ) type RefreshOptions struct { - Then func() + Then func() error Scope []RefreshableView // e.g. []RefreshableView{COMMITS, BRANCHES}. Leave empty to refresh everything Mode RefreshMode // one of SYNC (default), ASYNC, and BLOCK_UI From ea83f50dc35f5fac893a8bb641efe4b86995f2ee Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 22:01:39 +0200 Subject: [PATCH 051/218] Move post-FILES-refresh model reads into Then PromptToContinueRebase and WithEnsureCommittableFiles both read Model.Files right after a SYNC FILES refresh. This works today because the model write currently happens synchronously in the worker before Refresh's wg.Wait() returns, but an upcoming commit will bounce that write onto the UI thread instead, at which point wg.Wait() no longer guarantees it's been applied. Move both reads into Then ahead of that change. Then is already queued via OnUIThread (previous commit), so this is a behavior-preserving refactor on its own: the model is fully written by the time Then runs either way, whether that write is still synchronous or gets bounced later. As part of restructuring WithEnsureCommittableFiles, prepareFilesForCommit and syncRefresh are inlined into their single call sites. Co-Authored-By: Claude Sonnet 5 --- .../helpers/merge_and_rebase_helper.go | 41 ++++++++++--------- .../helpers/working_tree_helper.go | 39 +++++++----------- 2 files changed, 36 insertions(+), 44 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 847b89893..c25416a3b 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -309,27 +309,30 @@ func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { // but this is not supported by all terminals or on all platforms. self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}, + Then: func() error { + unstagedFiles := GetUnstagedFilesExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) + if len(unstagedFiles) > 0 { + self.c.Confirm(types.ConfirmOpts{ + Title: self.c.Tr.Continue, + Prompt: self.c.Tr.UnstagedFilesAfterConflictsResolved, + HandleConfirm: func() error { + self.c.LogAction(self.c.Tr.Actions.StageAllFiles) + if err := self.c.Git().WorkingTree.StageFiles(unstagedFiles, []string{}); err != nil { + return err + } + + return self.genericMergeCommand(REBASE_OPTION_CONTINUE) + }, + }) + + return nil + } + + return self.genericMergeCommand(REBASE_OPTION_CONTINUE) + }, }) - unstagedFiles := GetUnstagedFilesExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) - if len(unstagedFiles) > 0 { - self.c.Confirm(types.ConfirmOpts{ - Title: self.c.Tr.Continue, - Prompt: self.c.Tr.UnstagedFilesAfterConflictsResolved, - HandleConfirm: func() error { - self.c.LogAction(self.c.Tr.Actions.StageAllFiles) - if err := self.c.Git().WorkingTree.StageFiles(unstagedFiles, []string{}); err != nil { - return err - } - - return self.genericMergeCommand(REBASE_OPTION_CONTINUE) - }, - }) - - return nil - } - - return self.genericMergeCommand(REBASE_OPTION_CONTINUE) + return nil }, }) diff --git a/pkg/gui/controllers/helpers/working_tree_helper.go b/pkg/gui/controllers/helpers/working_tree_helper.go index 7e070ba31..7e321854b 100644 --- a/pkg/gui/controllers/helpers/working_tree_helper.go +++ b/pkg/gui/controllers/helpers/working_tree_helper.go @@ -222,15 +222,24 @@ func (self *WorkingTreeHelper) HandleCommitPress() error { } func (self *WorkingTreeHelper) WithEnsureCommittableFiles(handler func() error) error { - if err := self.prepareFilesForCommit(); err != nil { - return err - } - if len(self.c.Model().Files) == 0 { return errors.New(self.c.Tr.NoFilesStagedTitle) } if !self.AnyStagedFiles() { + if self.c.UserConfig().Gui.SkipNoStagedFilesWarning { + self.c.LogAction(self.c.Tr.Actions.StageAllFiles) + if err := self.c.Git().WorkingTree.StageAll(false); err != nil { + return err + } + self.c.Refresh(types.RefreshOptions{ + Mode: types.SYNC, + Scope: []types.RefreshableView{types.FILES}, + Then: handler, + }) + return nil + } + return self.promptToStageAllAndRetry(handler) } @@ -246,7 +255,7 @@ func (self *WorkingTreeHelper) promptToStageAllAndRetry(retry func() error) erro if err := self.c.Git().WorkingTree.StageAll(false); err != nil { return err } - self.syncRefresh() + self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) return retry() }, @@ -255,26 +264,6 @@ func (self *WorkingTreeHelper) promptToStageAllAndRetry(retry func() error) erro return nil } -// for when you need to refetch files before continuing an action. Runs synchronously. -func (self *WorkingTreeHelper) syncRefresh() { - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) -} - -func (self *WorkingTreeHelper) prepareFilesForCommit() error { - noStagedFiles := !self.AnyStagedFiles() - if noStagedFiles && self.c.UserConfig().Gui.SkipNoStagedFilesWarning { - self.c.LogAction(self.c.Tr.Actions.StageAllFiles) - err := self.c.Git().WorkingTree.StageAll(false) - if err != nil { - return err - } - - self.syncRefresh() - } - - return nil -} - func (self *WorkingTreeHelper) commitPrefixConfigsForRepo() []config.CommitPrefixConfig { cfg, ok := self.c.UserConfig().Git.CommitPrefixes[self.c.Git().RepoPaths.RepoName()] if ok { From be897ce55e5466eec66e703d18abd2b213376188 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:01:00 +0200 Subject: [PATCH 052/218] Bounce FILES model updates onto the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshStateFiles now does its git work on the worker and enqueues a single OnUIThread closure that writes Model.Submodules, Model.Files, and the FileTreeViewModel state together, instead of writing them directly from the worker goroutine. refreshStateSubmoduleConfigs becomes a pure getter (returns the configs; no model write) so the result can be threaded into that same bounce. The STAGING handler wraps RefreshStagingPanel in OnUIThread after fileWg.Wait() so it sees the post-bounce file model rather than the stale pre-refresh one — without this it would race the files bounce queued just above it. Bouncing the write opens a hazard the old synchronous write didn't have: if the user switches repos while this refresh is in flight, the queued closure would fire after resetState has replaced the model with a fresh one for the new repo, silently overwriting it with the previous repo's files. Guard against this with a repo generation: resetState bumps a counter on every switch, refreshStateFiles captures it before its git work, and onUIThreadUnlessRepoChanged drops the bounce if the generation has moved on. This one helper is the general mechanism the remaining scopes' bounces will use too; the same guard covers the rebase-continue prompt, which reads Model.Files right after. A generation counter, not a comparison of the *Model pointer: switching away from and back to a repo reuses that repo's cached state (the same Model pointer), which a pointer comparison would wrongly accept even though the in-flight data is stale. PromptToContinueRebase's Then callback (previous commit) now gets an explanatory comment, since this is the commit that makes it necessary. The explicit locking around these writes (RefreshingFilesMutex in refreshFilesAndSubmodules, FileTreeViewModel.RWMutex around the write in refreshStateFiles) is left in place for now even though it's becoming redundant, to keep this commit focused on the bounce itself; it's removed next. Co-Authored-By: Claude Sonnet 5 --- .../helpers/merge_and_rebase_helper.go | 4 + pkg/gui/controllers/helpers/refresh_helper.go | 84 +++++++++++-------- pkg/gui/gui.go | 15 ++++ pkg/gui/types/common.go | 7 ++ 4 files changed, 77 insertions(+), 33 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index c25416a3b..51488a922 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -307,6 +307,10 @@ func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { // Need to refresh the files to be really sure if this is the case. // We would otherwise be relying on lazygit's auto-refresh on focus, // but this is not supported by all terminals or on all platforms. + // + // The model.Files update is bounced onto the UI thread, so we have + // to read it in Then; reading it inline here would see the previous + // model. self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}, Then: func() error { diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2933d9378..2f2210f49 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -238,7 +238,14 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if scopeSet.Includes(types.STAGING) { refresh("staging", func() { fileWg.Wait() - self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) + // Bounce onto the UI thread so this runs after the files + // scope's model-update bounce — RefreshStagingPanel reads + // Model.Files (via Files.GetSelected) and would otherwise + // see the pre-refresh model. + self.c.OnUIThread(func() error { + self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) + return nil + }) }) } @@ -667,15 +674,8 @@ func (self *RefreshHelper) refreshTags() error { return nil } -func (self *RefreshHelper) refreshStateSubmoduleConfigs() error { - configs, err := self.c.Git().Submodule.GetConfigs(nil) - if err != nil { - return err - } - - self.c.Model().Submodules = configs - - return nil +func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleConfig, error) { + return self.c.Git().Submodule.GetConfigs(nil) } // self.refreshStatus is called at the end of this because that's when we can @@ -743,25 +743,40 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { self.c.Mutexes().RefreshingFilesMutex.Lock() defer self.c.Mutexes().RefreshingFilesMutex.Unlock() - if err := self.refreshStateSubmoduleConfigs(); err != nil { + configs, err := self.refreshStateSubmoduleConfigs() + if err != nil { return err } - if err := self.refreshStateFiles(background); err != nil { + if err := self.refreshStateFiles(background, configs); err != nil { return err } - self.c.OnUIThread(func() error { - self.refreshView(self.c.Contexts().Submodules) - self.refreshView(self.c.Contexts().Files) - return nil - }) + self.refreshView(self.c.Contexts().Submodules) + self.refreshView(self.c.Contexts().Files) return nil } -func (self *RefreshHelper) refreshStateFiles(background bool) error { +// onUIThreadUnlessRepoChanged bounces a refresh's model/view update onto the UI +// thread, but drops it if the repo was switched while the refresh was in flight. +// Refresh workers do their git work off the UI thread and enqueue their model +// writes here; a repo switch (which replaces the whole model and context tree) +// bumps the generation, so a write captured under the old generation must not +// clobber the new repo's state. Callers capture the generation with +// State().GetRepoGeneration() before doing their git work and pass it in. +func (self *RefreshHelper) onUIThreadUnlessRepoChanged(generation int, f func() error) { + self.c.OnUIThread(func() error { + if self.c.State().GetRepoGeneration() != generation { + return nil + } + return f() + }) +} + +func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs []*models.SubmoduleConfig) error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel + generation := self.c.State().GetRepoGeneration() prevConflictFileCount := 0 if self.c.UserConfig().Git.AutoStageResolvedConflicts { @@ -822,7 +837,9 @@ func (self *RefreshHelper) refreshStateFiles(background bool) error { // (e.g. in the user's editor). Offer to continue it. We only do this // for operations we started ourselves; prompting for one that was // started outside lazygit (e.g. by a coding agent) would be confusing. - self.c.OnUIThread(func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) + self.onUIThreadUnlessRepoChanged(generation, func() error { + return self.mergeAndRebaseHelper.PromptToContinueRebase() + }) } } else { // Either there's no operation in progress any more, or new conflicts have @@ -835,22 +852,23 @@ func (self *RefreshHelper) refreshStateFiles(background bool) error { }) } - fileTreeViewModel.RWMutex.Lock() - - // only taking over the filter if it hasn't already been set by the user. - if conflictFileCount > 0 && prevConflictFileCount == 0 { - if fileTreeViewModel.GetStatusFilter() == filetree.DisplayAll { - fileTreeViewModel.SetStatusFilter(filetree.DisplayConflicted) - self.c.Contexts().Files.GetView().Subtitle = self.c.Tr.FilterLabelConflictingFiles + self.onUIThreadUnlessRepoChanged(generation, func() error { + // only taking over the filter if it hasn't already been set by the user. + if conflictFileCount > 0 && prevConflictFileCount == 0 { + if fileTreeViewModel.GetStatusFilter() == filetree.DisplayAll { + fileTreeViewModel.SetStatusFilter(filetree.DisplayConflicted) + self.c.Contexts().Files.GetView().Subtitle = self.c.Tr.FilterLabelConflictingFiles + } + } else if conflictFileCount == 0 && fileTreeViewModel.GetStatusFilter() == filetree.DisplayConflicted { + fileTreeViewModel.SetStatusFilter(filetree.DisplayAll) + self.c.Contexts().Files.GetView().Subtitle = "" } - } else if conflictFileCount == 0 && fileTreeViewModel.GetStatusFilter() == filetree.DisplayConflicted { - fileTreeViewModel.SetStatusFilter(filetree.DisplayAll) - self.c.Contexts().Files.GetView().Subtitle = "" - } - self.c.Model().Files = files - fileTreeViewModel.SetTree() - fileTreeViewModel.RWMutex.Unlock() + self.c.Model().Submodules = submoduleConfigs + self.c.Model().Files = files + fileTreeViewModel.SetTree() + return nil + }) return nil } diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 87a87f7b2..834cf1e2d 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -12,6 +12,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "github.com/jesseduffield/lazycore/pkg/boxlayout" @@ -111,6 +112,11 @@ type Gui struct { PopupHandler types.IPopupHandler + // Bumped every time we switch to a different repository (in resetState). + // Used to drop refresh results that were computed for a repo we've since + // navigated away from. See RefreshHelper.onUIThreadUnlessRepoChanged. + repoGeneration atomic.Int32 + // 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 @@ -169,6 +175,10 @@ func (self *StateAccessor) GetRepoState() types.IRepoStateAccessor { return self.gui.State } +func (self *StateAccessor) GetRepoGeneration() int { + return int(self.gui.repoGeneration.Load()) +} + func (self *StateAccessor) GetPagerConfig() *config.PagerConfig { return self.gui.pagerConfig } @@ -575,6 +585,11 @@ func (gui *Gui) checkForChangedConfigsThatDontAutoReload(oldConfig *config.UserC // 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 { + // Bump the repo generation so that any refresh still in flight for the + // previous repo drops its model update instead of applying it here (see + // RefreshHelper.onUIThreadUnlessRepoChanged). + gui.repoGeneration.Add(1) + // 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. diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index ad28972ae..7fc75aee0 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -384,6 +384,13 @@ type IStateAccessor interface { GetItemOperation(item HasUrn) ItemOperation SetItemOperation(item HasUrn, operation ItemOperation) ClearItemOperation(item HasUrn) + + // A counter that is bumped every time we switch to a different repository + // (see Gui.resetState). Refresh workers capture it before doing their git + // work and pass it to onUIThreadUnlessRepoChanged, so that a model update + // computed for one repo can be dropped rather than applied to another if the + // user switched repos while the refresh was in flight. + GetRepoGeneration() int } type IRepoStateAccessor interface { From 2c139b6ac173842f88d03392017a3eecd5f05cc5 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:01:45 +0200 Subject: [PATCH 053/218] Remove RefreshingFilesMutex/FileTreeViewModel.RWMutex, dead code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FileTreeViewModel.RWMutex is removed along with the withFileTreeViewModelMutex wrapper in FilesController that RLocked it: every writer (the bounce closure, previous commit) and every reader (key handlers, disabled-reason callbacks) now runs on the UI thread, so the mutex is redundant. RefreshingFilesMutex is removed entirely, including its last use in repos_helper's DispatchSwitchTo. That use predates the bounce and was never about FilesController's optimistic-rendering concern; it serialized a repo switch's onNewRepo() against an in-flight FILES refresh for the repo being switched away from, so that a slow refresh from the old repo couldn't write into the freshly-reset model for the new one. Bouncing the write already broke that guarantee on its own terms — the mutex's critical section never covered the bounced closure's actual execution, only the (now-removed) code that enqueued it — so by this point it was only still locked here without protecting anything real; the previous commit's repo-generation guard is what now actually closes that race, making this lock fully redundant rather than just relocated. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/files_controller.go | 25 +++---------------- pkg/gui/controllers/helpers/refresh_helper.go | 3 --- pkg/gui/controllers/helpers/repos_helper.go | 3 --- pkg/gui/filetree/file_tree_view_model.go | 2 -- pkg/gui/types/common.go | 1 - 5 files changed, 4 insertions(+), 30 deletions(-) diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index a63c6a15a..d7720ee34 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -44,7 +44,7 @@ func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types { Keys: opts.GetKeys(opts.Config.Universal.Select), Handler: self.withItems(self.press), - GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected(self.canStageSelection))), + GetDisabledReason: self.require(self.itemsSelected(self.canStageSelection)), Description: self.c.Tr.Stage, Tooltip: self.c.Tr.StageTooltip, DisplayOnScreen: true, @@ -91,7 +91,7 @@ func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types { Keys: opts.GetKeys(opts.Config.Universal.Edit), Handler: self.withItems(self.edit), - GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected(self.canEditFiles))), + GetDisabledReason: self.require(self.itemsSelected(self.canEditFiles)), Description: self.c.Tr.Edit, Tooltip: self.c.Tr.EditFileTooltip, DisplayOnScreen: true, @@ -145,7 +145,7 @@ func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types { Keys: opts.GetKeys(opts.Config.Universal.Remove), Handler: self.withItems(self.remove), - GetDisabledReason: self.withFileTreeViewModelMutex(self.require(self.itemsSelected(self.canRemove))), + GetDisabledReason: self.require(self.itemsSelected(self.canRemove)), Description: self.c.Tr.Discard, Tooltip: self.c.Tr.DiscardFileChangesTooltip, OpensMenu: true, @@ -182,7 +182,7 @@ func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types Handler: self.withItems(self.openMergeConflictMenu), Description: self.c.Tr.ViewMergeConflictOptions, Tooltip: self.c.Tr.ViewMergeConflictOptionsTooltip, - GetDisabledReason: self.require(self.withFileTreeViewModelMutex(self.itemsSelected(self.canOpenMergeConflictMenu))), + GetDisabledReason: self.require(self.itemsSelected(self.canOpenMergeConflictMenu)), OpensMenu: true, DisplayOnScreen: true, }, @@ -209,15 +209,6 @@ func (self *FilesController) GetKeybindings(opts types.KeybindingsOpts) []*types } } -func (self *FilesController) withFileTreeViewModelMutex(callback func() *types.DisabledReason) func() *types.DisabledReason { - return func() *types.DisabledReason { - self.c.Contexts().Files.FileTreeViewModel.RWMutex.RLock() - defer self.c.Contexts().Files.FileTreeViewModel.RWMutex.RUnlock() - - return callback() - } -} - func (self *FilesController) GetMouseKeybindings(opts types.KeybindingsOpts) []*gocui.ViewMouseBinding { return []*gocui.ViewMouseBinding{ { @@ -574,11 +565,6 @@ func (self *FilesController) toggleStaged( } func (self *FilesController) pressWithLock(selectedNodes []*filetree.FileNode) error { - // Obtaining this lock because optimistic rendering requires us to mutate - // the files in our model. - self.c.Mutexes().RefreshingFilesMutex.Lock() - defer self.c.Mutexes().RefreshingFilesMutex.Unlock() - // When filtering, expand directory nodes to individual visible file paths // so that only filtered files are staged/unstaged. toPaths := func(nodes []*filetree.FileNode) []string { @@ -942,9 +928,6 @@ func (self *FilesController) toggleStagedAll() error { } func (self *FilesController) toggleStagedAllWithLock() error { - self.c.Mutexes().RefreshingFilesMutex.Lock() - defer self.c.Mutexes().RefreshingFilesMutex.Unlock() - root := self.context().FileTreeViewModel.GetRoot() stage := func(unstagedNodes []*filetree.FileNode) error { diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2f2210f49..875f55a30 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -740,9 +740,6 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele } func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { - self.c.Mutexes().RefreshingFilesMutex.Lock() - defer self.c.Mutexes().RefreshingFilesMutex.Unlock() - configs, err := self.refreshStateSubmoduleConfigs() if err != nil { return err diff --git a/pkg/gui/controllers/helpers/repos_helper.go b/pkg/gui/controllers/helpers/repos_helper.go index bde1c47c6..94c9e4368 100644 --- a/pkg/gui/controllers/helpers/repos_helper.go +++ b/pkg/gui/controllers/helpers/repos_helper.go @@ -177,9 +177,6 @@ func (self *ReposHelper) DispatchSwitchTo(path string, errMsg string, contextKey self.c.Log.Errorf("error recording current directory: %v", err) } - self.c.Mutexes().RefreshingFilesMutex.Lock() - defer self.c.Mutexes().RefreshingFilesMutex.Unlock() - if err := self.onNewRepo(appTypes.StartArgs{}, contextKey); err != nil { return err } diff --git a/pkg/gui/filetree/file_tree_view_model.go b/pkg/gui/filetree/file_tree_view_model.go index 741550c19..aabbbce7f 100644 --- a/pkg/gui/filetree/file_tree_view_model.go +++ b/pkg/gui/filetree/file_tree_view_model.go @@ -2,7 +2,6 @@ package filetree import ( "strings" - "sync" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/common" @@ -22,7 +21,6 @@ type IFileTreeViewModel interface { // which item is selected. It also contains logic for repositioning that cursor // after the files are refreshed type FileTreeViewModel struct { - sync.RWMutex types.IListCursor IFileTree searchHistory *utils.HistoryBuffer[string] diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 7fc75aee0..2b7dc2312 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -338,7 +338,6 @@ type Model struct { } type Mutexes struct { - RefreshingFilesMutex deadlock.Mutex RefreshingBranchesMutex deadlock.Mutex RefreshingStatusMutex deadlock.Mutex RefreshingPullRequestsMutex deadlock.Mutex From 6203a4e41119d04c738a5f2aa8fca7e2de71904d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 2 Jul 2026 22:07:16 +0200 Subject: [PATCH 054/218] Move post-COMMIT_FILES-refresh work into Then SwitchToDiffFilesController.enter calls SelectPath and Context.Push right after a (SYNC, by default) COMMIT_FILES refresh. This works today because the model write currently happens synchronously in the worker before Refresh's wg.Wait() returns, but an upcoming commit will bounce that write onto the UI thread instead, at which point wg.Wait() no longer guarantees it's been applied, and SelectPath would operate on a stale tree. Move both calls into Then ahead of that change, for the same reason as the earlier FILES-scope commit: Then is already queued via OnUIThread, so this is behavior-preserving on its own. Co-Authored-By: Claude Sonnet 5 --- .../switch_to_diff_files_controller.go | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/pkg/gui/controllers/switch_to_diff_files_controller.go b/pkg/gui/controllers/switch_to_diff_files_controller.go index c2ff4d674..afdf92c80 100644 --- a/pkg/gui/controllers/switch_to_diff_files_controller.go +++ b/pkg/gui/controllers/switch_to_diff_files_controller.go @@ -90,18 +90,19 @@ func (self *SwitchToDiffFilesController) enter() error { self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.COMMIT_FILES}, + Then: func() error { + if filterPath := self.c.Modes().Filtering.GetPath(); filterPath != "" { + path, err := filepath.Rel(self.c.Git().RepoPaths.RepoPath(), filterPath) + if err != nil { + path = filterPath + } + commitFilesContext.CommitFileTreeViewModel.SelectPath( + filepath.ToSlash(path), self.c.UserConfig().Gui.ShowRootItemInFileTree) + } + self.c.Context().Push(commitFilesContext, types.OnFocusOpts{}) + return nil + }, }) - - if filterPath := self.c.Modes().Filtering.GetPath(); filterPath != "" { - path, err := filepath.Rel(self.c.Git().RepoPaths.RepoPath(), filterPath) - if err != nil { - path = filterPath - } - commitFilesContext.CommitFileTreeViewModel.SelectPath( - filepath.ToSlash(path), self.c.UserConfig().Gui.ShowRootItemInFileTree) - } - - self.c.Context().Push(commitFilesContext, types.OnFocusOpts{}) return nil } From b203ec57acdc8c1bd930c23c459f587626dcfee3 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:04:44 +0200 Subject: [PATCH 055/218] Bounce COMMIT_FILES model updates onto the UI thread refreshCommitFilesContext now enqueues the Model.CommitFiles write and CommitFileTreeViewModel.SetTree() call via OnUIThread, instead of running them directly on the worker goroutine that drives async refreshes. This is what makes moving SwitchToDiffFilesController's post-refresh work into Then (previous commit) actually necessary, rather than just future-proofing. Same repo-switch hazard as the FILES bounce, closed the same way: it captures the repo generation before the git work and bounces through onUIThreadUnlessRepoChanged, so the write is dropped if the user switched repos while it was in flight. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 875f55a30..2fda422bc 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -635,14 +635,17 @@ func (self *RefreshHelper) RefreshAuthors(commits []*models.Commit) { func (self *RefreshHelper) refreshCommitFilesContext() error { from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) + generation := self.c.State().GetRepoGeneration() files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(from, to, reverse) if err != nil { return err } - self.c.Model().CommitFiles = files - self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() - + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().CommitFiles = files + self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() + return nil + }) self.refreshView(self.c.Contexts().CommitFiles) return nil } From 21f1dc336670da1c678369a1aa09fe867b2ffb48 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:21:31 +0200 Subject: [PATCH 056/218] Bounce TAGS model updates onto the UI thread refreshTags now captures the repo generation, loads the tags on the worker, and writes Model.Tags in an onUIThreadUnlessRepoChanged bounce rather than directly from the worker goroutine. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2fda422bc..e610fef13 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -666,12 +666,17 @@ func (self *RefreshHelper) refreshRebaseCommits() error { } func (self *RefreshHelper) refreshTags() error { + generation := self.c.State().GetRepoGeneration() + tags, err := self.c.Git().Loaders.TagLoader.GetTags() if err != nil { return err } - self.c.Model().Tags = tags + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().Tags = tags + return nil + }) self.refreshView(self.c.Contexts().Tags) return nil From ff7ecf2d2a427f030da7b80e6e3307461ea975be Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:21:51 +0200 Subject: [PATCH 057/218] Bounce STASH model updates onto the UI thread refreshStashEntries now loads the stash entries on the worker and writes Model.StashEntries in an onUIThreadUnlessRepoChanged bounce. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index e610fef13..2076e45ee 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -979,9 +979,16 @@ func (self *RefreshHelper) refreshWorktrees() { } func (self *RefreshHelper) refreshStashEntries() { - self.c.Model().StashEntries = self.c.Git().Loaders.StashLoader. + generation := self.c.State().GetRepoGeneration() + + stashEntries := self.c.Git().Loaders.StashLoader. GetStashEntries(self.c.Modes().Filtering.GetPath()) + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().StashEntries = stashEntries + return nil + }) + self.refreshView(self.c.Contexts().Stash) } From d6f6d0ceba534cd904773b26aaba6c8e5d40fec4 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:23:22 +0200 Subject: [PATCH 058/218] Bounce WORKTREES model updates onto the UI thread refreshWorktrees now writes Model.Worktrees in an onUIThreadUnlessRepoChanged bounce. loadWorktrees becomes a pure loader that returns the worktrees instead of writing them, since it's shared with refreshBranches; refreshWorktrees bounces the result, and the branches call site writes it directly for now (that write moves into refreshBranches's own bounce when that scope is migrated). Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2076e45ee..d1c1091da 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -719,7 +719,10 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele self.rebuildPullRequestsMap() if refreshWorktrees { - self.loadWorktrees() + // TODO: this synchronous worker write goes away when refreshBranches is + // itself migrated to bouncing; for now it matches the rest of this + // not-yet-bounced function. + self.c.Model().Worktrees = self.loadWorktrees() self.refreshView(self.c.Contexts().Worktrees) } @@ -959,18 +962,24 @@ func (self *RefreshHelper) refreshRemotes() error { return nil } -func (self *RefreshHelper) loadWorktrees() { +func (self *RefreshHelper) loadWorktrees() []*models.Worktree { worktrees, err := self.c.Git().Loaders.Worktrees.GetWorktrees() if err != nil { self.c.Log.Error(err) - self.c.Model().Worktrees = []*models.Worktree{} - } else { - self.c.Model().Worktrees = worktrees + return []*models.Worktree{} } + return worktrees } func (self *RefreshHelper) refreshWorktrees() { - self.loadWorktrees() + generation := self.c.State().GetRepoGeneration() + + worktrees := self.loadWorktrees() + + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().Worktrees = worktrees + return nil + }) // need to refresh branches because the branches view shows worktrees against // branches From 559b4bf298268871a8fcd07a4bedc7fad9a6756e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:24:20 +0200 Subject: [PATCH 059/218] Bounce REBASE_COMMITS model updates onto the UI thread refreshRebaseCommits now computes the merged rebasing commits and working tree state on the worker and writes Model.Commits / WorkingTreeStateAtLastCommitRefresh in an onUIThreadUnlessRepoChanged bounce. LocalCommitsMutex is left in place for now; it's shared with the commits and branches refreshes and comes out once they're all bounced. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index d1c1091da..4d511ed78 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -654,12 +654,19 @@ func (self *RefreshHelper) refreshRebaseCommits() error { self.c.Mutexes().LocalCommitsMutex.Lock() defer self.c.Mutexes().LocalCommitsMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(self.c.Model().HashPool, self.c.Model().Commits) if err != nil { return err } - self.c.Model().Commits = updatedCommits - self.c.Model().WorkingTreeStateAtLastCommitRefresh = self.c.Git().Status.WorkingTreeState() + workingTreeState := self.c.Git().Status.WorkingTreeState() + + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().Commits = updatedCommits + self.c.Model().WorkingTreeStateAtLastCommitRefresh = workingTreeState + return nil + }) self.refreshView(self.c.Contexts().LocalCommits) return nil From 0f85c2b2b4085d718ba5abd2d207a4f0f5a7eff9 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:25:10 +0200 Subject: [PATCH 060/218] Bounce SUB_COMMITS model updates onto the UI thread refreshSubCommitsWithLimit now loads the sub-commits on the worker and writes Model.SubCommits (and folds their authors into Model.Authors via RefreshAuthors) inside an onUIThreadUnlessRepoChanged bounce. SubCommitsMutex and AuthorsMutex are left in place: the former is shared with setSubCommits, the latter with the commits refresh's RefreshAuthors call, so both come out only once those other writers are on the UI thread too. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 4d511ed78..67b8e86f1 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -594,6 +594,8 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit() error { self.c.Mutexes().SubCommitsMutex.Lock() defer self.c.Mutexes().SubCommitsMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: self.c.Contexts().SubCommits.GetLimitCommits(), @@ -610,8 +612,11 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit() error { if err != nil { return err } - self.c.Model().SubCommits = commits - self.RefreshAuthors(commits) + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().SubCommits = commits + self.RefreshAuthors(commits) + return nil + }) self.refreshView(self.c.Contexts().SubCommits) return nil From db5eb6fd3964cd5a5b9fad5d7fe59d9c49797407 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 14:27:35 +0200 Subject: [PATCH 061/218] Bounce REMOTES model updates onto the UI thread refreshRemotes now loads the remotes on the worker and writes Model.Remotes, rebuilds the pull-requests map, and updates the selected remote's RemoteBranches inside an onUIThreadUnlessRepoChanged bounce. RemotesController.addAndCheckoutRemote read Model.Remotes right after its SYNC REMOTES refresh to select the newly-added remote; since that write now bounces, the selection (and the follow-up fetch) move into Then so they run against the post-refresh model rather than the stale one. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 34 +++++++++++-------- pkg/gui/controllers/remotes_controller.go | 32 +++++++++-------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 67b8e86f1..4811e026f 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -942,6 +942,7 @@ func (self *RefreshHelper) refreshReflogCommits() error { } func (self *RefreshHelper) refreshRemotes() error { + generation := self.c.State().GetRepoGeneration() prevSelectedRemote := self.c.Contexts().Remotes.GetSelected() remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() @@ -949,25 +950,28 @@ func (self *RefreshHelper) refreshRemotes() error { return err } - self.c.Model().Remotes = remotes + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().Remotes = remotes - hadPrs := len(self.c.Model().PullRequestsMap) != 0 - self.rebuildPullRequestsMap() - if !hadPrs && len(self.c.Model().PullRequestsMap) != 0 { - // if we didn't have PRs in the map before but now we do, we need to redraw the branches view - self.refreshView(self.c.Contexts().Branches) - } + hadPrs := len(self.c.Model().PullRequestsMap) != 0 + self.rebuildPullRequestsMap() + if !hadPrs && len(self.c.Model().PullRequestsMap) != 0 { + // if we didn't have PRs in the map before but now we do, we need to redraw the branches view + self.refreshView(self.c.Contexts().Branches) + } - // we need to ensure our selected remote branches aren't now outdated - if prevSelectedRemote != nil && self.c.Model().RemoteBranches != nil { - // find remote now - for _, remote := range remotes { - if remote.Name == prevSelectedRemote.Name { - self.c.Model().RemoteBranches = remote.Branches - break + // we need to ensure our selected remote branches aren't now outdated + if prevSelectedRemote != nil && self.c.Model().RemoteBranches != nil { + // find remote now + for _, remote := range remotes { + if remote.Name == prevSelectedRemote.Name { + self.c.Model().RemoteBranches = remote.Branches + break + } } } - } + return nil + }) self.refreshView(self.c.Contexts().Remotes) self.refreshView(self.c.Contexts().RemoteBranches) diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index f7b16e228..e4f606ca3 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -156,24 +156,28 @@ func (self *RemotesController) addAndCheckoutRemote(remoteName string, remoteUrl return err } - // Do a sync refresh of the remotes so that we can select - // the new one. Loading remotes is not expensive, so we can - // afford it. + // Refresh the remotes so that we can select the new one. The remotes model + // update is bounced onto the UI thread, so the selection (which reads + // Model.Remotes) has to run in Then; reading it inline here would see the + // previous model. Loading remotes is not expensive, so a sync refresh is + // affordable. self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.REMOTES}, Mode: types.SYNC, + Then: func() error { + // Select the remote + for idx, remote := range self.c.Model().Remotes { + if remote.Name == remoteName { + self.c.Contexts().Remotes.SetSelection(idx) + break + } + } + + // Fetch the remote + return self.fetchAndCheckout(self.c.Contexts().Remotes.GetSelected(), branchToCheckout) + }, }) - - // Select the remote - for idx, remote := range self.c.Model().Remotes { - if remote.Name == remoteName { - self.c.Contexts().Remotes.SetSelection(idx) - break - } - } - - // Fetch the remote - return self.fetchAndCheckout(self.c.Contexts().Remotes.GetSelected(), branchToCheckout) + return nil } // Ensures the fork remote exists (matching the given URL). From bd47106d03e60f14c72fe001805a3882d921b601 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:17:43 +0200 Subject: [PATCH 062/218] Thread reflog commits explicitly into the branches load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BranchLoader.Load reads the reflog commits to sort branches by recency. Today it reads them straight from Model.ReflogCommits, which works because in the recency path the reflog refresh writes that field synchronously just before the branches refresh reads it (same goroutine, sequential). An upcoming commit bounces the reflog model write onto the UI thread, at which point Model.ReflogCommits wouldn't be updated yet when branches runs — branches would sort by the previous refresh's reflog. To decouple the branches load from *when* that write lands, pass the reflog commits to refreshBranches explicitly: refreshReflogCommits now returns the commits it loaded, and the recency path hands them straight to refreshBranches. The non-recency path (branches and reflog run concurrently, as before) keeps passing Model.ReflogCommits. Pure refactor: behavior is identical, since the value passed is exactly what Load read from the model before. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 45 +++++++++++++------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 4811e026f..7cd8b6a59 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -179,10 +179,13 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { } else { branchesAndRemotesWg.Add(1) refresh("branches", func() { - self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true) + // Not a recency sort, so branches doesn't depend on the reflog + // being fresh; it runs concurrently with the reflog refresh + // below and reads whatever's in the model, as it always has. + self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true, self.c.Model().ReflogCommits) branchesAndRemotesWg.Done() }) - refresh("reflog", func() { _ = self.refreshReflogCommits() }) + refresh("reflog", func() { _, _ = self.refreshReflogCommits() }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one @@ -378,27 +381,38 @@ func getModeName(mode types.RefreshMode) string { // on startup to sort the branches by recency. So we have two phases: INITIAL, and COMPLETE. // In the initial phase we don't get any reflog commits, but we asynchronously get them // and refresh the branches after that -func (self *RefreshHelper) refreshReflogCommitsConsideringStartup() { +// refreshReflogCommitsConsideringStartup returns the reflog commits that the +// caller should hand to refreshBranches for recency sorting. In the COMPLETE +// (normal) case that's the freshly-loaded reflog; in the INITIAL case the +// reflog is loaded asynchronously (and drives its own branches refresh once +// ready), so we return the current model value for the immediate, +// non-recency-sorted branches refresh the caller does in the meantime. +func (self *RefreshHelper) refreshReflogCommitsConsideringStartup() []*models.Commit { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: self.c.OnWorker(func(_ gocui.Task) error { - _ = self.refreshReflogCommits() - self.refreshBranches(false, true, true) + reflogCommits, _ := self.refreshReflogCommits() + self.refreshBranches(false, true, true, reflogCommits) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) + return self.c.Model().ReflogCommits + case types.COMPLETE: - _ = self.refreshReflogCommits() + reflogCommits, _ := self.refreshReflogCommits() + return reflogCommits } + + return self.c.Model().ReflogCommits } func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { loadBehindCounts := self.c.State().GetRepoState().GetStartupStage() == types.COMPLETE - self.refreshReflogCommitsConsideringStartup() + reflogCommits := self.refreshReflogCommitsConsideringStartup() - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, loadBehindCounts) + self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, loadBehindCounts, reflogCommits) } func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior) { @@ -700,12 +714,12 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool) { +func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool, reflogCommits []*models.Commit) { self.c.Mutexes().RefreshingBranchesMutex.Lock() defer self.c.Mutexes().RefreshingBranchesMutex.Unlock() branches, err := self.c.Git().Loaders.BranchLoader.Load( - self.c.Model().ReflogCommits, + reflogCommits, self.c.Model().MainBranches, self.c.Model().Branches, loadBehindCounts, @@ -900,7 +914,10 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // This method also manages two things: ReflogCommits and FilteredReflogCommits. // FilteredReflogCommits are rendered in the reflogs panel, and ReflogCommits // are used by the branches panel to obtain recency values for sorting. -func (self *RefreshHelper) refreshReflogCommits() error { +// refreshReflogCommits returns the (non-filtered) ReflogCommits it loaded, so +// that a subsequent branches refresh can use them for recency sorting without +// having to read them back out of the model. +func (self *RefreshHelper) refreshReflogCommits() ([]*models.Commit, error) { // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception model := self.c.Model() @@ -926,19 +943,19 @@ func (self *RefreshHelper) refreshReflogCommits() error { } if err := refresh(&model.ReflogCommits, "", ""); err != nil { - return err + return nil, err } if self.c.Modes().Filtering.Active() { if err := refresh(&model.FilteredReflogCommits, self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()); err != nil { - return err + return nil, err } } else { model.FilteredReflogCommits = model.ReflogCommits } self.refreshView(self.c.Contexts().ReflogCommits) - return nil + return model.ReflogCommits, nil } func (self *RefreshHelper) refreshRemotes() error { From 063bba6b45ac0d8da36997f29d1c5599c0f6081b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:19:34 +0200 Subject: [PATCH 063/218] Bounce REFLOG model updates onto the UI thread refreshReflogCommits now does the git fetch on the worker and computes the new ReflogCommits / FilteredReflogCommits values (still reading the existing slices for the incremental prepend), then writes them in an onUIThreadUnlessRepoChanged bounce. The freshly-computed reflog is still returned for the branches load, so recency sorting is unaffected by the write now landing on the UI thread (see the previous commit). Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 7cd8b6a59..fc405c6bf 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -918,44 +918,53 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. func (self *RefreshHelper) refreshReflogCommits() ([]*models.Commit, error) { + generation := self.c.State().GetRepoGeneration() // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception model := self.c.Model() - refresh := func(stateCommits *[]*models.Commit, filterPath string, filterAuthor string) error { + // load does the git work on the worker and returns the new value for a + // reflog slice, reading the existing slice for the incremental fetch. The + // caller writes the result in the bounce. + load := func(existing []*models.Commit, filterPath string, filterAuthor string) ([]*models.Commit, error) { var lastReflogCommit *models.Commit - if filterPath == "" && filterAuthor == "" && len(*stateCommits) > 0 { - lastReflogCommit = (*stateCommits)[0] + if filterPath == "" && filterAuthor == "" && len(existing) > 0 { + lastReflogCommit = existing[0] } commits, onlyObtainedNewReflogCommits, err := self.c.Git().Loaders.ReflogCommitLoader. - GetReflogCommits(self.c.Model().HashPool, lastReflogCommit, filterPath, filterAuthor) + GetReflogCommits(model.HashPool, lastReflogCommit, filterPath, filterAuthor) if err != nil { - return err + return nil, err } if onlyObtainedNewReflogCommits { - *stateCommits = append(commits, *stateCommits...) - } else { - *stateCommits = commits + return append(commits, existing...), nil } - return nil + return commits, nil } - if err := refresh(&model.ReflogCommits, "", ""); err != nil { + reflogCommits, err := load(model.ReflogCommits, "", "") + if err != nil { return nil, err } + filteredReflogCommits := reflogCommits if self.c.Modes().Filtering.Active() { - if err := refresh(&model.FilteredReflogCommits, self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()); err != nil { + filteredReflogCommits, err = load(model.FilteredReflogCommits, self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()) + if err != nil { return nil, err } - } else { - model.FilteredReflogCommits = model.ReflogCommits } + self.onUIThreadUnlessRepoChanged(generation, func() error { + model.ReflogCommits = reflogCommits + model.FilteredReflogCommits = filteredReflogCommits + return nil + }) + self.refreshView(self.c.Contexts().ReflogCommits) - return model.ReflogCommits, nil + return reflogCommits, nil } func (self *RefreshHelper) refreshRemotes() error { From 4c9fdc42213eb4a7953c3e24c07140ec70c9e05f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:21:20 +0200 Subject: [PATCH 064/218] Bounce STATUS view update onto the UI thread refreshStatus computes the status line on the calling goroutine (as before) but now writes it to the status view in an onUIThreadUnlessRepoChanged bounce rather than calling SetViewContent directly from the worker. RefreshingStatusMutex is left in place for now; it only guards the compute phase between concurrent callers and comes out in the mutex cleanup. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index fc405c6bf..083907881 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1048,6 +1048,8 @@ func (self *RefreshHelper) refreshStatus() { self.c.Mutexes().RefreshingStatusMutex.Lock() defer self.c.Mutexes().RefreshingStatusMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + currentBranch := self.refsHelper.GetCheckedOutRef() if currentBranch == nil { // need to wait for branches to refresh @@ -1061,7 +1063,10 @@ func (self *RefreshHelper) refreshStatus() { status := presentation.FormatStatus(repoName, currentBranch, types.ItemOperationNone, linkedWorktreeName, workingTreeState, self.c.Tr, self.c.UserConfig()) - self.c.SetViewContent(self.c.Views().Status, status) + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.SetViewContent(self.c.Views().Status, status) + return nil + }) } func (self *RefreshHelper) refForLog() string { From 4c3f8b51ea57787a407f104e110c35ee2093e5ce Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:25:04 +0200 Subject: [PATCH 065/218] Bounce PULL_REQUESTS model updates onto the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshGithubPullRequests and setGithubPullRequests now do their network work on the worker and write Model.PullRequests / PullRequestsMap in an onUIThreadUnlessRepoChanged bounce (the "no github remotes" and "no base remote" early-returns clear them the same way). rebuildPullRequestsMap moves into the bounce so the map is built from Model.Branches and Model.Remotes as they stand on the UI thread — after those scopes' refreshes have applied their own bounces — rather than from whatever the worker happened to see. The remaining worker-side reads of Model.Branches (to pick which upstream branches to query) are the same not-yet-addressed worker-read race that applies to the other bounced scopes. RefreshingPullRequestsMutex is left in place for the mutex cleanup. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 083907881..917a58ecf 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1115,17 +1115,25 @@ func (self *RefreshHelper) refreshGithubPullRequests() { self.c.Mutexes().RefreshingPullRequestsMutex.Lock() defer self.c.Mutexes().RefreshingPullRequestsMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + + clearPullRequests := func() { + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().PullRequests = nil + self.c.Model().PullRequestsMap = nil + return nil + }) + } + githubRemotes := getAuthenticatedGithubRemotes(self.getGithubRemotes(), self.c.Git().GitHub.GetAuthToken) if len(githubRemotes) == 0 { - self.c.Model().PullRequests = nil - self.c.Model().PullRequestsMap = nil + clearPullRequests() return } baseInfo := getGithubBaseRemote(githubRemotes, self.c.Git().GitHub.ConfiguredBaseRemoteName()) if baseInfo == nil { - self.c.Model().PullRequests = nil - self.c.Model().PullRequestsMap = nil + clearPullRequests() if !self.githubBaseRemotePromptDismissed[self.c.Git().RepoPaths.RepoPath()] { self.promptForBaseGithubRepo(githubRemotes) @@ -1243,6 +1251,8 @@ func (self *RefreshHelper) rebuildPullRequestsMap() { } func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo) { + generation := self.c.State().GetRepoGeneration() + if len(self.c.Model().Branches) == 0 { return } @@ -1260,11 +1270,14 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo) { return } - self.c.Model().PullRequests = prs self.savePullRequestsToCache(prs) - self.rebuildPullRequestsMap() - self.c.OnUIThread(func() error { + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().PullRequests = prs + // Rebuilding here rather than on the worker means the map is built from + // the branches and remotes as they are on the UI thread, after their + // own refreshes' bounces have applied. + self.rebuildPullRequestsMap() self.c.PostRefreshUpdate(self.c.Contexts().Branches) return nil }) From 549df1727937e8ff706820a830d42904b9b469c0 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:32:11 +0200 Subject: [PATCH 066/218] Bounce COMMITS model updates onto the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshCommitsWithLimit now loads the commits, working-tree state and bisect info on the worker and writes them all — Model.Commits, Model.BisectInfo, Model.WorkingTreeStateAtLastCommitRefresh, Model.CheckedOutBranch, the authors, and the restored commit selection — in a single onUIThreadUnlessRepoChanged bounce. The selection restore (SelectHeadCommit / KeepCommitSelectionByHash) has to run in the bounce because it reads the freshly-loaded commits; the FocusLine scroll is enqueued from within the bounce so it still runs after refreshView's re-render, as before. refForLog no longer writes Model.BisectInfo as a side effect; it returns the bisect info it read, and the bounce writes it, keeping that model write on the UI thread. No caller reads Model.BisectInfo synchronously after a refresh (the bisect controller reads Git().Bisect.GetInfo() directly), so this is safe. refreshCommitsAndCommitFiles's post-refresh re-init of the commit files context depends on that restored selection, so it reads the selection in a bounce and dispatches the commit-files git work back to a worker. LocalCommitsMutex / AuthorsMutex are left in place for the mutex cleanup. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 109 +++++++++++------- 1 file changed, 68 insertions(+), 41 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 917a58ecf..a86e91111 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -416,6 +416,7 @@ func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepB } func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior) { + generation := self.c.State().GetRepoGeneration() _ = self.refreshCommitsWithLimit(commitSelection) ctx := self.c.Contexts().CommitFiles.GetParentContext() if ctx != nil && ctx.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY { @@ -425,12 +426,22 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.Co // Ideally we would know when to refresh the commit files context and when not to, // or perhaps we could just pop that context off the stack whenever cycling windows. // For now the awkwardness remains. - commit := self.c.Contexts().LocalCommits.GetSelected() - if commit != nil && commit.RefName() != "" { - refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() - self.c.Contexts().CommitFiles.ReInit(commit, refRange) - _ = self.refreshCommitFilesContext() - } + // + // The commit selection is restored in refreshCommitsWithLimit's bounce, + // so read it on the UI thread after that bounce; then load the commit + // files back on a worker (refreshCommitFilesContext does git work). + self.onUIThreadUnlessRepoChanged(generation, func() error { + commit := self.c.Contexts().LocalCommits.GetSelected() + if commit != nil && commit.RefName() != "" { + refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() + self.c.Contexts().CommitFiles.ReInit(commit, refRange) + self.c.OnWorker(func(gocui.Task) error { + _ = self.refreshCommitFilesContext() + return nil + }) + } + return nil + }) } } @@ -464,6 +475,8 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS self.c.Mutexes().LocalCommitsMutex.Lock() defer self.c.Mutexes().LocalCommitsMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + var selectionRange *localCommitSelectionRange if commitSelection == types.KeepCommitSelectionByHash { selectedIdx, rangeStartIdx, rangeSelectMode := self.c.Contexts().LocalCommits.GetSelectionRangeAndMode() @@ -471,13 +484,14 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS } checkedOutRef := self.determineCheckedOutRef() + refName, bisectInfo := self.refForLog() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: self.c.Contexts().LocalCommits.GetLimitCommits(), FilterPath: self.c.Modes().Filtering.GetPath(), FilterAuthor: self.c.Modes().Filtering.GetAuthor(), IncludeRebaseCommits: true, - RefName: self.refForLog(), + RefName: refName, RefForPushedStatus: checkedOutRef, All: self.c.Contexts().LocalCommits.GetShowWholeGitGraph(), MainBranches: self.c.Model().MainBranches, @@ -487,41 +501,51 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS if err != nil { return err } - self.c.Model().Commits = commits - self.RefreshAuthors(commits) - self.c.Model().WorkingTreeStateAtLastCommitRefresh = self.c.Git().Status.WorkingTreeState() - if checkedOutRef != nil { - self.c.Model().CheckedOutBranch = checkedOutRef.RefName() - } else { - self.c.Model().CheckedOutBranch = "" - } + workingTreeState := self.c.Git().Status.WorkingTreeState() - scrollSelectionIntoView := false - switch commitSelection { - case types.SelectHeadCommit: - if headCommitIdx := models.HeadCommitIdx(commits); headCommitIdx >= 0 { - self.c.Contexts().LocalCommits.SetSelection(headCommitIdx) - scrollSelectionIntoView = true + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().BisectInfo = bisectInfo + self.c.Model().Commits = commits + self.RefreshAuthors(commits) + self.c.Model().WorkingTreeStateAtLastCommitRefresh = workingTreeState + if checkedOutRef != nil { + self.c.Model().CheckedOutBranch = checkedOutRef.RefName() + } else { + self.c.Model().CheckedOutBranch = "" } - case types.KeepCommitSelectionByHash: - if selectionRange != nil { - selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, selectionRange) - if found { - self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, selectionRange.mode) - scrollSelectionIntoView = didMove + + scrollSelectionIntoView := false + switch commitSelection { + case types.SelectHeadCommit: + if headCommitIdx := models.HeadCommitIdx(commits); headCommitIdx >= 0 { + self.c.Contexts().LocalCommits.SetSelection(headCommitIdx) + scrollSelectionIntoView = true } + case types.KeepCommitSelectionByHash: + if selectionRange != nil { + selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, selectionRange) + if found { + self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, selectionRange.mode) + scrollSelectionIntoView = didMove + } + } + case types.KeepCommitSelectionIndex: + // The caller set the selection index deliberately; leave it untouched. } - case types.KeepCommitSelectionIndex: - // The caller set the selection index deliberately; leave it untouched. - } + + if scrollSelectionIntoView { + // Enqueued from within this bounce so it runs after refreshView's + // render below (which was enqueued first), matching the previous + // ordering where FocusLine ran after the view was re-rendered. + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Contexts().LocalCommits.FocusLine(true) + return nil + }) + } + return nil + }) self.refreshView(self.c.Contexts().LocalCommits) - if scrollSelectionIntoView { - self.c.OnUIThread(func() error { - self.c.Contexts().LocalCommits.FocusLine(true) - return nil - }) - } return nil } @@ -1069,20 +1093,23 @@ func (self *RefreshHelper) refreshStatus() { }) } -func (self *RefreshHelper) refForLog() string { +// refForLog returns the ref to log commits from, along with the bisect info it +// read to decide that. The caller writes the bisect info to the model (in its +// bounce) rather than refForLog doing it, so the model write stays on the UI +// thread. +func (self *RefreshHelper) refForLog() (string, *git_commands.BisectInfo) { bisectInfo := self.c.Git().Bisect.GetInfo() - self.c.Model().BisectInfo = bisectInfo if !bisectInfo.Started() { - return "HEAD" + return "HEAD", bisectInfo } // need to see if our bisect's current commit is reachable from our 'new' ref. if bisectInfo.Bisecting() && !self.c.Git().Bisect.ReachableFromStart(bisectInfo) { - return bisectInfo.GetNewHash() + return bisectInfo.GetNewHash(), bisectInfo } - return bisectInfo.GetStartHash() + return bisectInfo.GetStartHash(), bisectInfo } func (self *RefreshHelper) refreshView(context types.Context) { From f7a61443fa832d47bfec4bb9726a7cc52eb5f19f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 15:56:01 +0200 Subject: [PATCH 067/218] Bounce BRANCHES model updates onto the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshBranches now loads the branches (and worktrees) on the worker and writes Model.Branches, the pull-requests map, Model.Worktrees, and the restored branch selection in an onUIThreadUnlessRepoChanged bounce. The selection restore and rebuildPullRequestsMap run in the bounce so they see the branches we just wrote; the LocalCommits re-render (for branch head visualization) moves into the same bounce. refreshStatus is adjusted to read the checked-out branch and the linked worktree name inside its bounce rather than on the worker: both derive from models (Branches, Worktrees) that are now written via bounces, so reading them on the worker would format the status from stale values — which showed up as the status line dropping the "(worktree)" suffix right after entering a submodule or switching worktrees. The git work (WorkingTreeState) stays on the worker. Two callers that read the branches model right after a SYNC branches refresh move their reads into Then: - BranchesHelper.PostFetchRefresh: AutoForwardBranches reads Model.Branches, so it runs in Then (preserving that a fetch error is still returned to the caller and that background auto-forward errors aren't surfaced as a popup). - BranchesController rename: the re-select-by-name loop runs in Then. RefreshingBranchesMutex is left in place for the mutex cleanup. Co-Authored-By: Claude Sonnet 5 --- pkg/gui/controllers/branches_controller.go | 23 ++++--- .../controllers/helpers/branches_helper.go | 27 ++++++-- pkg/gui/controllers/helpers/refresh_helper.go | 68 +++++++++++-------- 3 files changed, 74 insertions(+), 44 deletions(-) diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index 45f98e9c5..131d19439 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -783,20 +783,25 @@ func (self *BranchesController) rename(branch *models.Branch) error { return err } - // need to find where the branch is now so that we can re-select it. That means we need to refetch the branches synchronously and then find our branch + // need to find where the branch is now so that we can re-select it. That means we need to + // refetch the branches and then find our branch. The branches model update is bounced + // onto the UI thread, so the re-selection (which reads Model.Branches) has to run in + // Then; reading it inline here would see the previous model. self.c.Refresh(types.RefreshOptions{ Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES, types.WORKTREES}, + Then: func() error { + // now that we've got our stuff again we need to find that branch and reselect it. + for i, newBranch := range self.c.Model().Branches { + if newBranch.Name == newBranchName { + self.context().SetSelection(i) + self.context().HandleRender() + } + } + return nil + }, }) - // now that we've got our stuff again we need to find that branch and reselect it. - for i, newBranch := range self.c.Model().Branches { - if newBranch.Name == newBranchName { - self.context().SetSelection(i) - self.context().HandleRender() - } - } - return nil }, }) diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 4283bd29a..e5c1a07e4 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -387,11 +387,28 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er if self.c.UserConfig().Git.AutoForwardBranches != "none" { scope = append(scope, types.WORKTREES) } - self.c.Refresh(types.RefreshOptions{Scope: scope, Mode: types.SYNC, Background: background}) - if fetchErr != nil { - return fetchErr - } - return self.AutoForwardBranches() + // AutoForwardBranches reads Model.Branches, which the branches refresh writes + // via a bounce, so it has to run in Then rather than right after Refresh + // returns (where it would still see the previous branches). + self.c.Refresh(types.RefreshOptions{ + Scope: scope, + Mode: types.SYNC, + Background: background, + Then: func() error { + if fetchErr != nil { + return nil + } + err := self.AutoForwardBranches() + if background && err != nil { + // The background poller discards this return value, so surface + // the error in the log rather than as a popup for background work. + self.c.Log.Error(err) + return nil + } + return err + }, + }) + return fetchErr } func (self *BranchesHelper) AutoForwardBranches() error { diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index a86e91111..876ce0f30 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -742,6 +742,8 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele self.c.Mutexes().RefreshingBranchesMutex.Lock() defer self.c.Mutexes().RefreshingBranchesMutex.Unlock() + generation := self.c.State().GetRepoGeneration() + branches, err := self.c.Git().Loaders.BranchLoader.Load( reflogCommits, self.c.Model().MainBranches, @@ -753,7 +755,7 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele }) }, func() { - self.c.OnUIThread(func() error { + self.onUIThreadUnlessRepoChanged(generation, func() error { self.c.Contexts().Branches.HandleRender() self.refreshStatus() return nil @@ -765,38 +767,42 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele prevSelectedBranch := self.c.Contexts().Branches.GetSelected() - self.c.Model().Branches = branches - self.rebuildPullRequestsMap() - + var worktrees []*models.Worktree if refreshWorktrees { - // TODO: this synchronous worker write goes away when refreshBranches is - // itself migrated to bouncing; for now it matches the rest of this - // not-yet-bounced function. - self.c.Model().Worktrees = self.loadWorktrees() - self.refreshView(self.c.Contexts().Worktrees) + worktrees = self.loadWorktrees() } - if !keepBranchSelectionIndex && prevSelectedBranch != nil { - self.searchHelper.ReApplyFilter(self.c.Contexts().Branches) + self.onUIThreadUnlessRepoChanged(generation, func() error { + self.c.Model().Branches = branches + // Rebuilding here (rather than on the worker) means the map is built from + // the branches we just wrote, on the UI thread. + self.rebuildPullRequestsMap() - _, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(), - func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name }) - if found { - self.c.Contexts().Branches.SetSelectedLineIdx(idx) + if refreshWorktrees { + self.c.Model().Worktrees = worktrees + self.refreshView(self.c.Contexts().Worktrees) } - } - self.refreshView(self.c.Contexts().Branches) + if !keepBranchSelectionIndex && prevSelectedBranch != nil { + self.searchHelper.ReApplyFilter(self.c.Contexts().Branches) - // Need to re-render the commits view because the visualization of local - // branch heads might have changed - self.c.OnUIThread(func() error { + _, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(), + func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name }) + if found { + self.c.Contexts().Branches.SetSelectedLineIdx(idx) + } + } + + // Need to re-render the commits view because the visualization of local + // branch heads might have changed self.c.Mutexes().LocalCommitsMutex.Lock() self.c.Contexts().LocalCommits.HandleRender() self.c.Mutexes().LocalCommitsMutex.Unlock() return nil }) + self.refreshView(self.c.Contexts().Branches) + self.refreshStatus() } @@ -1074,20 +1080,22 @@ func (self *RefreshHelper) refreshStatus() { generation := self.c.State().GetRepoGeneration() - currentBranch := self.refsHelper.GetCheckedOutRef() - if currentBranch == nil { - // need to wait for branches to refresh - return - } - workingTreeState := self.c.Git().Status.WorkingTreeState() - linkedWorktreeName := self.worktreeHelper.GetLinkedWorktreeName() - repoName := self.c.Git().RepoPaths.RepoName() - status := presentation.FormatStatus(repoName, currentBranch, types.ItemOperationNone, linkedWorktreeName, workingTreeState, self.c.Tr, self.c.UserConfig()) - self.onUIThreadUnlessRepoChanged(generation, func() error { + // Read the checked-out branch and the linked worktree name here on the UI + // thread: both derive from models (Branches, Worktrees) that their + // refreshes now write via bounces, so reading them on the worker would + // see stale values from before those bounces applied. + currentBranch := self.refsHelper.GetCheckedOutRef() + if currentBranch == nil { + // need to wait for branches to refresh + return nil + } + linkedWorktreeName := self.worktreeHelper.GetLinkedWorktreeName() + + status := presentation.FormatStatus(repoName, currentBranch, types.ItemOperationNone, linkedWorktreeName, workingTreeState, self.c.Tr, self.c.UserConfig()) self.c.SetViewContent(self.c.Views().Status, status) return nil }) From 805738034f727e246bebfc8f35e3adc721c6873a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 16:51:55 +0200 Subject: [PATCH 068/218] Remove refresh mutexes made redundant by bouncing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that every refresh scope writes its model updates on the UI thread via onUIThreadUnlessRepoChanged, the per-scope mutexes that used to serialize concurrent worker-goroutine access are redundant: Model().Commits, .SubCommits, .Authors, the status view content, and .PullRequests/.PullRequestsMap are all now written only on the UI thread, and their readers already ran there. setSubCommits only existed to take the lock, so it's inlined to match refreshSubCommitsWithLimit, which writes Model().SubCommits directly. The worker phases still *read* some of these fields (the commit selection range, MergeRebasingCommits), but those reads race a concurrent refresh's bounced write regardless of the mutex — the write happens in the bounce, outside the locked region — so the mutex never protected them. That residual read race belongs to the broader -race effort, not to these locks. RefreshingBranchesMutex is deliberately kept. It is load-bearing for a reason unrelated to data races: at the INITIAL startup stage two refreshBranches run concurrently — an immediate one with an empty reflog (non-recency order) and an async one with the freshly-loaded reflog (recency order). The mutex serializes them so the recency write's bounce is enqueued last and wins. Without it the stale non-recency write can land last, reordering the branches list (caught by the recency-sort e2e tests: cherry_pick/*, branch/rebase_*). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 20 ------------------- .../controllers/helpers/sub_commits_helper.go | 9 +-------- pkg/gui/types/common.go | 13 ++++-------- 3 files changed, 5 insertions(+), 37 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 876ce0f30..75d5d2fd4 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -472,9 +472,6 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { } func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitSelectionBehavior) error { - self.c.Mutexes().LocalCommitsMutex.Lock() - defer self.c.Mutexes().LocalCommitsMutex.Unlock() - generation := self.c.State().GetRepoGeneration() var selectionRange *localCommitSelectionRange @@ -629,9 +626,6 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit() error { return nil } - self.c.Mutexes().SubCommitsMutex.Lock() - defer self.c.Mutexes().SubCommitsMutex.Unlock() - generation := self.c.State().GetRepoGeneration() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( @@ -661,9 +655,6 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit() error { } func (self *RefreshHelper) RefreshAuthors(commits []*models.Commit) { - self.c.Mutexes().AuthorsMutex.Lock() - defer self.c.Mutexes().AuthorsMutex.Unlock() - authors := self.c.Model().Authors for _, commit := range commits { if _, ok := authors[commit.AuthorEmail]; !ok { @@ -694,9 +685,6 @@ func (self *RefreshHelper) refreshCommitFilesContext() error { } func (self *RefreshHelper) refreshRebaseCommits() error { - self.c.Mutexes().LocalCommitsMutex.Lock() - defer self.c.Mutexes().LocalCommitsMutex.Unlock() - generation := self.c.State().GetRepoGeneration() updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(self.c.Model().HashPool, self.c.Model().Commits) @@ -795,9 +783,7 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele // Need to re-render the commits view because the visualization of local // branch heads might have changed - self.c.Mutexes().LocalCommitsMutex.Lock() self.c.Contexts().LocalCommits.HandleRender() - self.c.Mutexes().LocalCommitsMutex.Unlock() return nil }) @@ -1075,9 +1061,6 @@ func (self *RefreshHelper) refreshStashEntries() { // never call this on its own, it should only be called from within refreshCommits() func (self *RefreshHelper) refreshStatus() { - self.c.Mutexes().RefreshingStatusMutex.Lock() - defer self.c.Mutexes().RefreshingStatusMutex.Unlock() - generation := self.c.State().GetRepoGeneration() workingTreeState := self.c.Git().Status.WorkingTreeState() @@ -1147,9 +1130,6 @@ func (self *RefreshHelper) refreshView(context types.Context) { } func (self *RefreshHelper) refreshGithubPullRequests() { - self.c.Mutexes().RefreshingPullRequestsMutex.Lock() - defer self.c.Mutexes().RefreshingPullRequestsMutex.Unlock() - generation := self.c.State().GetRepoGeneration() clearPullRequests := func() { diff --git a/pkg/gui/controllers/helpers/sub_commits_helper.go b/pkg/gui/controllers/helpers/sub_commits_helper.go index fbf100e16..7bd928826 100644 --- a/pkg/gui/controllers/helpers/sub_commits_helper.go +++ b/pkg/gui/controllers/helpers/sub_commits_helper.go @@ -49,7 +49,7 @@ func (self *SubCommitsHelper) ViewSubCommits(opts ViewSubCommitsOpts) error { return err } - self.setSubCommits(commits) + self.c.Model().SubCommits = commits self.refreshHelper.RefreshAuthors(commits) subCommitsContext := self.c.Contexts().SubCommits @@ -71,10 +71,3 @@ func (self *SubCommitsHelper) ViewSubCommits(opts ViewSubCommitsOpts) error { self.c.Context().Push(self.c.Contexts().SubCommits, types.OnFocusOpts{}) return nil } - -func (self *SubCommitsHelper) setSubCommits(commits []*models.Commit) { - self.c.Mutexes().SubCommitsMutex.Lock() - defer self.c.Mutexes().SubCommitsMutex.Unlock() - - self.c.Model().SubCommits = commits -} diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 2b7dc2312..35f38d21e 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -338,15 +338,10 @@ type Model struct { } type Mutexes struct { - RefreshingBranchesMutex deadlock.Mutex - RefreshingStatusMutex deadlock.Mutex - RefreshingPullRequestsMutex deadlock.Mutex - LocalCommitsMutex deadlock.Mutex - SubCommitsMutex deadlock.Mutex - AuthorsMutex deadlock.Mutex - SubprocessMutex deadlock.Mutex - PopupMutex deadlock.Mutex - PtyMutex deadlock.Mutex + RefreshingBranchesMutex deadlock.Mutex + SubprocessMutex deadlock.Mutex + PopupMutex deadlock.Mutex + PtyMutex deadlock.Mutex } // A long-running operation associated with an item. For example, we'll show From 6d8ab1d0639f19227786a67103eca9582e219dd2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 17:35:44 +0200 Subject: [PATCH 069/218] Run the immediate startup branch refresh before spawning the async one At the INITIAL startup stage two branch refreshes happen: an immediate one sorted by whatever reflog we have (empty, so not by recency), and an async one that loads the reflog first and re-sorts by recency. Until now the async one was spawned first and the immediate one ran afterwards; this inverts that so the immediate refresh runs before the async one is spawned. With RefreshingBranchesMutex still in place this is behavior-preserving (the mutex serializes the two either way). It's a preparatory step for replacing that mutex with a branch-load sequence guard: running the immediate refresh first establishes a happens-before relation between the two loads' sequence numbers, so the recency-sorted one is guaranteed the higher sequence. This also lets refreshReflogCommitsConsideringStartup fold into refreshReflogAndBranches, whose two-phase logic is now all in one place. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 35 ++++++------------- 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 75d5d2fd4..95c7fa4a7 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -377,19 +377,18 @@ func getModeName(mode types.RefreshMode) string { } } -// during startup, the bottleneck is fetching the reflog entries. We need these -// on startup to sort the branches by recency. So we have two phases: INITIAL, and COMPLETE. -// In the initial phase we don't get any reflog commits, but we asynchronously get them -// and refresh the branches after that -// refreshReflogCommitsConsideringStartup returns the reflog commits that the -// caller should hand to refreshBranches for recency sorting. In the COMPLETE -// (normal) case that's the freshly-loaded reflog; in the INITIAL case the -// reflog is loaded asynchronously (and drives its own branches refresh once -// ready), so we return the current model value for the immediate, -// non-recency-sorted branches refresh the caller does in the meantime. -func (self *RefreshHelper) refreshReflogCommitsConsideringStartup() []*models.Commit { +// During startup, the bottleneck is fetching the reflog entries, which we need +// in order to sort the branches by recency. So we have two phases: INITIAL and +// COMPLETE. In the INITIAL phase we don't have any reflog commits yet, so we +// show the branches right away sorted by whatever we have (typically nothing, +// i.e. not by recency), then load the reflog on a worker and refresh the +// branches again, this time recency-sorted. From then on we're in the COMPLETE +// phase and load the reflog synchronously before refreshing the branches. +func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: + self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, false, self.c.Model().ReflogCommits) + self.c.OnWorker(func(_ gocui.Task) error { reflogCommits, _ := self.refreshReflogCommits() self.refreshBranches(false, true, true, reflogCommits) @@ -397,22 +396,10 @@ func (self *RefreshHelper) refreshReflogCommitsConsideringStartup() []*models.Co return nil }) - return self.c.Model().ReflogCommits - case types.COMPLETE: reflogCommits, _ := self.refreshReflogCommits() - return reflogCommits + self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, true, reflogCommits) } - - return self.c.Model().ReflogCommits -} - -func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { - loadBehindCounts := self.c.State().GetRepoState().GetStartupStage() == types.COMPLETE - - reflogCommits := self.refreshReflogCommitsConsideringStartup() - - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, loadBehindCounts, reflogCommits) } func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior) { From 3103fe97ea9bb2653c4890dcbe8a1d67d1016aac Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 18:45:55 +0200 Subject: [PATCH 070/218] Replace RefreshingBranchesMutex with a branch-load sequence guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This removes the last refresh mutex. RefreshingBranchesMutex wasn't guarding a data race (Branch.BehindBaseBranch is atomic, and every model write is now bounced onto the UI thread); it was serializing the two branch loads that race at the INITIAL startup stage — an immediate one sorted without the reflog, and an async one that loads the reflog and sorts by recency — so that the recency-sorted write landed last and won. That serialization was never a real guarantee, only "very likely": it relied on the immediate load acquiring the lock before the async load, which had to load the reflog first. Instead, each branch load takes a monotonically increasing sequence number, and its bounce drops the write if a later-started load has already applied. Combined with the preceding commit (immediate load runs before the async one is spawned), this is an actual guarantee: the immediate non-recency load always has a lower sequence than its recency async partner, so the highest sequence number is always held by a recency-sorted load, and highest-wins converges on recency ordering — even if more refreshes fire during the INITIAL window, since each refresh's async out-sequences its own immediate. The guard also subsumes what the mutex gave post-startup: a slow, stale refresh's bounce can no longer clobber a newer refresh's branches. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 28 +++++++++++++++++-- pkg/gui/types/common.go | 7 ++--- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 95c7fa4a7..fe89bbad6 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -3,6 +3,7 @@ package helpers import ( "strings" "sync" + "sync/atomic" "time" "github.com/jesseduffield/generics/set" @@ -44,6 +45,15 @@ type RefreshHelper struct { // refresh that re-read refs/commits, read by the poller. refsSnapshotMutex deadlock.Mutex refsSnapshot string + + // branchLoadSeq hands out a monotonically increasing sequence number to + // each branch load (via Add, on the worker); appliedBranchLoadSeq is the + // highest sequence whose result has been written to the model (touched only + // on the UI thread, inside the bounce). Together they let a branch load's + // bounce drop its write if a later-started load has already applied, so + // concurrent branch loads don't clobber each other out of order. + branchLoadSeq atomic.Int64 + appliedBranchLoadSeq int64 } func NewRefreshHelper( @@ -384,6 +394,11 @@ func getModeName(mode types.RefreshMode) string { // i.e. not by recency), then load the reflog on a worker and refresh the // branches again, this time recency-sorted. From then on we're in the COMPLETE // phase and load the reflog synchronously before refreshing the branches. +// +// The immediate refresh must run before we spawn the async one, not after: that +// order gives the immediate (non-recency) load a lower branch-load sequence +// than the async (recency) load, so the sequence guard in refreshBranches keeps +// the recency-sorted result even if the two loads' bounces land out of order. func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: @@ -714,8 +729,7 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool, reflogCommits []*models.Commit) { - self.c.Mutexes().RefreshingBranchesMutex.Lock() - defer self.c.Mutexes().RefreshingBranchesMutex.Unlock() + loadSeq := self.branchLoadSeq.Add(1) generation := self.c.State().GetRepoGeneration() @@ -748,6 +762,16 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele } self.onUIThreadUnlessRepoChanged(generation, func() error { + // Drop this write if a branch load that started later has already applied + // its result. At the INITIAL startup stage an immediate load (not + // recency-sorted) and an async recency-sorted load run concurrently; this + // makes the later-started (recency-sorted) one win regardless of which + // finishes first, so its result isn't clobbered by the stale immediate one. + if loadSeq < self.appliedBranchLoadSeq { + return nil + } + self.appliedBranchLoadSeq = loadSeq + self.c.Model().Branches = branches // Rebuilding here (rather than on the worker) means the map is built from // the branches we just wrote, on the UI thread. diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 35f38d21e..2ce07f9c7 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -338,10 +338,9 @@ type Model struct { } type Mutexes struct { - RefreshingBranchesMutex deadlock.Mutex - SubprocessMutex deadlock.Mutex - PopupMutex deadlock.Mutex - PtyMutex deadlock.Mutex + SubprocessMutex deadlock.Mutex + PopupMutex deadlock.Mutex + PtyMutex deadlock.Mutex } // A long-running operation associated with an item. For example, we'll show From cf7c3d82e6e962ce78494e57c77058796ea617f2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 20:46:51 +0200 Subject: [PATCH 071/218] Run the repo switch on the UI thread DispatchSwitchTo wrapped its whole body in WithWaitingStatus, so the switch ran on a worker: it chdirs, reassigns gui.git, and swaps gui.State (in resetState), all of which the UI thread also reads. The generation guard prevents the refresh-in-flight logical corruption but not this pointer data race on gui.State. Run the switch synchronously on the UI thread instead. Every caller is already a UI-thread handler except NewWorktreeCheckout, which must create the worktree (git work) on a worker first; it now dispatches only the switch via OnUIThread. The heavy data loading still happens asynchronously via the refresh that onNewRepo triggers, so the synchronous part is small (a couple of git rev-parse plus direnv). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/repos_helper.go | 72 +++++++++---------- .../controllers/helpers/worktree_helper.go | 8 ++- 2 files changed, 43 insertions(+), 37 deletions(-) diff --git a/pkg/gui/controllers/helpers/repos_helper.go b/pkg/gui/controllers/helpers/repos_helper.go index 94c9e4368..6257327e9 100644 --- a/pkg/gui/controllers/helpers/repos_helper.go +++ b/pkg/gui/controllers/helpers/repos_helper.go @@ -13,7 +13,6 @@ import ( "github.com/jesseduffield/lazygit/pkg/commands/direnv" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/env" - "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/presentation/icons" "github.com/jesseduffield/lazygit/pkg/gui/style" @@ -145,52 +144,53 @@ func (self *ReposHelper) DispatchSwitchToRepo(path string, contextKey types.Cont return self.DispatchSwitchTo(path, self.c.Tr.ErrRepositoryMovedOrDeleted, contextKey) } +// DispatchSwitchTo switches lazygit to the repository (or worktree) at the +// given path. It runs synchronously on the UI thread: the switch swaps +// gui.State (in resetState) and reassigns gui.git and the process cwd, all of +// which the UI thread also reads, so doing it here rather than on a worker +// avoids racing those reads. The heavy data loading is still dispatched +// asynchronously by the refresh that onNewRepo kicks off. func (self *ReposHelper) DispatchSwitchTo(path string, errMsg string, contextKey types.ContextKey) error { - return self.c.WithWaitingStatus(self.c.Tr.Switching, func(gocui.Task) error { - env.UnsetGitLocationEnvVars() - originalPath, err := os.Getwd() - if err != nil { - return nil + env.UnsetGitLocationEnvVars() + originalPath, err := os.Getwd() + if err != nil { + return nil + } + + msg := utils.ResolvePlaceholderString(self.c.Tr.ChangingDirectoryTo, map[string]string{"path": path}) + self.c.LogCommand(msg, false) + + if err := os.Chdir(path); err != nil { + if os.IsNotExist(err) { + return errors.New(errMsg) } + return err + } - msg := utils.ResolvePlaceholderString(self.c.Tr.ChangingDirectoryTo, map[string]string{"path": path}) - self.c.LogCommand(msg, false) - - if err := os.Chdir(path); err != nil { - if os.IsNotExist(err) { - return errors.New(errMsg) - } + if err := commands.VerifyInGitRepo(self.c.OS()); err != nil { + if err := os.Chdir(originalPath); err != nil { return err } - if err := commands.VerifyInGitRepo(self.c.OS()); err != nil { - if err := os.Chdir(originalPath); err != nil { - return err - } + return err + } - return err - } + direnvResult := self.logDirenvResult(direnv.Load(self.c.OS().Cmd)) - direnvResult := self.logDirenvResult(direnv.Load(self.c.OS().Cmd)) + if err := self.recordDirectoryHelper.RecordCurrentDirectory(); err != nil { + self.c.Log.Errorf("error recording current directory: %v", err) + } - if err := self.recordDirectoryHelper.RecordCurrentDirectory(); err != nil { - self.c.Log.Errorf("error recording current directory: %v", err) - } + if err := self.onNewRepo(appTypes.StartArgs{}, contextKey); err != nil { + return err + } - if err := self.onNewRepo(appTypes.StartArgs{}, contextKey); err != nil { - return err - } + if direnvResult.Blocked { + self.promptDirenvApproval(direnvResult.EnvrcPath) + return nil + } - if direnvResult.Blocked { - self.c.OnUIThread(func() error { - self.promptDirenvApproval(direnvResult.EnvrcPath) - return nil - }) - return nil - } - - return direnvResult.Err - }) + return direnvResult.Err } // logDirenvResult writes whatever direnv emitted to the command log and the diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 7cec9f873..2a189a752 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -432,6 +432,12 @@ func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts, co return err } - return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) + // The switch swaps gui.State and must run on the UI thread, but + // we're on a worker here (creating the worktree is git work), so + // dispatch it rather than calling it directly. + self.c.OnUIThread(func() error { + return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) + }) + return nil }) } From e352cafd43bea26fedefa6e0f6e45bcad8213d4f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 20:56:00 +0200 Subject: [PATCH 072/218] Add background tasks and a synchronous busy query to gocui Repo-switch safety needs to answer, synchronously on the UI thread, "is any foreground work in flight right now?" so it can refuse a switch that would run against a repo about to be swapped out. gocui already tracks a task per OnWorker/Update for the test idle-listener; extend that. Tasks gain a background flag: background tasks (the ongoing routines like auto-fetch, and the refreshes they trigger) don't count towards busy, because their model writes are already guarded against a concurrent switch by the repo generation. Add OnWorkerBackground, UpdateBackground and UpdateContentOnlyBackground (plus the gui-layer OnUIThreadBackground / OnUIThreadContentOnlyBackground / OnWorkerBackground on IGuiCommon) so the few background call sites can opt in without touching the hundreds of foreground callers. TaskManager.hasBusyForegroundTaskExcept answers the query; Gui.Busy() wraps it, excluding the event currently being processed (recorded as currentTask) so a handler asking the question doesn't count itself. Nothing gates on Busy() yet; this is the mechanism only. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/gui.go | 65 ++++++++++++++++++++++++++++++---- pkg/gocui/task.go | 18 +++++++++- pkg/gocui/task_manager.go | 26 ++++++++++++-- pkg/gocui/task_manager_test.go | 63 ++++++++++++++++++++++++++++++++ pkg/gui/gui.go | 16 +++++++++ pkg/gui/gui_common.go | 12 +++++++ pkg/gui/types/common.go | 9 +++++ 7 files changed, 200 insertions(+), 9 deletions(-) create mode 100644 pkg/gocui/task_manager_test.go diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index ee1995911..ff113a2dd 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -193,6 +193,12 @@ type Gui struct { taskManager *TaskManager + // The task of the event currently being processed on the main goroutine, if + // any. Only touched from the main goroutine (in processEvent). It's excluded + // from the Busy() check so that an event handler asking "is anything else + // busy?" doesn't count itself. + currentTask Task + lastHoverView *View } @@ -273,7 +279,15 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { } func (g *Gui) NewTask() *TaskImpl { - return g.taskManager.NewTask() + return g.taskManager.NewTask(false) +} + +// Busy reports whether any foreground work is in flight, ignoring the event +// currently being processed on the main goroutine (see currentTask). Background +// routines (auto-fetch etc.) don't count. It's used to decide whether it's safe +// to switch repos. Must be called on the main goroutine. +func (g *Gui) Busy() bool { + return g.taskManager.hasBusyForegroundTaskExcept(g.currentTask) } // An idle listener listens for when the program is idle. This is useful for @@ -628,7 +642,18 @@ type userEvent struct { // never fire in practice; if it does, that's a signal to investigate, not // to grow the buffer reflexively. func (g *Gui) Update(f func(*Gui) error) { - task := g.NewTask() + g.update(f, false) +} + +// Like Update, but the enqueued work is a background routine (or triggered by +// one), so it doesn't count towards the program being busy for repo-switch +// safety. See TaskImpl.background. +func (g *Gui) UpdateBackground(f func(*Gui) error) { + g.update(f, true) +} + +func (g *Gui) update(f func(*Gui) error, background bool) { + task := g.taskManager.NewTask(background) select { case g.userEvents <- userEvent{f: f, task: task}: @@ -639,7 +664,16 @@ func (g *Gui) Update(f func(*Gui) error) { // Like Update, but signals that the callback only modifies content. func (g *Gui) UpdateContentOnly(f func(*Gui) error) { - task := g.NewTask() + g.updateContentOnly(f, false) +} + +// Like UpdateContentOnly, but for background work (see UpdateBackground). +func (g *Gui) UpdateContentOnlyBackground(f func(*Gui) error) { + g.updateContentOnly(f, true) +} + +func (g *Gui) updateContentOnly(f func(*Gui) error, background bool) { + task := g.taskManager.NewTask(background) g.userEvents <- userEvent{f: f, task: task, contentOnly: true} } @@ -650,7 +684,18 @@ func (g *Gui) UpdateContentOnly(f func(*Gui) error) { // background goroutines where you wouldn't want lazygit to be considered busy // (i.e. when you wouldn't want a loader to be shown to the user) func (g *Gui) OnWorker(f func(Task) error) { - task := g.NewTask() + g.onWorker(f, false) +} + +// Like OnWorker, but for a background routine (or work triggered by one), so it +// doesn't count towards the program being busy for repo-switch safety. See +// TaskImpl.background. +func (g *Gui) OnWorkerBackground(f func(Task) error) { + g.onWorker(f, true) +} + +func (g *Gui) onWorker(f func(Task) error, background bool) { + task := g.taskManager.NewTask(background) go func() { g.onWorkerAux(f, task) task.Done() @@ -758,17 +803,25 @@ func (g *Gui) handleError(err error) error { func (g *Gui) processEvent() error { contentOnly := false + // currentTask is the task of the event we're about to handle; recording it + // lets Busy() ignore it, so a handler asking "is anything else busy?" (the + // repo-switch guard does) doesn't count itself. Handlers of the remaining + // events drained below run with currentTask still set to this primary event; + // that's fine because the only Busy() callers are keybinding handlers, which + // are always the primary event here. select { case ev := <-g.gEvents: task := g.NewTask() - defer func() { task.Done() }() + g.currentTask = task + defer func() { g.currentTask = nil; task.Done() }() if err := g.handleError(g.handleEvent(&ev)); err != nil { return err } case ev := <-g.userEvents: contentOnly = ev.contentOnly - defer func() { ev.task.Done() }() + g.currentTask = ev.task + defer func() { g.currentTask = nil; ev.task.Done() }() if err := g.handleError(ev.f(g)); err != nil { return err diff --git a/pkg/gocui/task.go b/pkg/gocui/task.go index ace72f4a8..377781a4f 100644 --- a/pkg/gocui/task.go +++ b/pkg/gocui/task.go @@ -8,8 +8,9 @@ type Task interface { Done() Pause() Continue() - // not exporting because we don't need to + // not exporting these because we don't need to isBusy() bool + isBackground() bool } type TaskImpl struct { @@ -17,6 +18,13 @@ type TaskImpl struct { busy bool onDone func() withMutex func(func()) + // Background tasks don't count towards the program being "busy" for the + // purpose of deciding whether a repo switch is safe (see + // TaskManager.hasBusyForegroundTaskExcept). They're the ongoing background + // routines (auto-fetch, files refresh, external-change detection) and the + // refreshes they trigger, whose model writes are already guarded against a + // concurrent repo switch by the repo generation. + background bool } func (self *TaskImpl) Done() { @@ -39,6 +47,10 @@ func (self *TaskImpl) isBusy() bool { return self.busy } +func (self *TaskImpl) isBackground() bool { + return self.background +} + type TaskStatus int const ( @@ -73,6 +85,10 @@ func (self *FakeTask) isBusy() bool { return self.status == TaskStatusBusy } +func (self *FakeTask) isBackground() bool { + return false +} + func (self *FakeTask) Status() TaskStatus { return self.status } diff --git a/pkg/gocui/task_manager.go b/pkg/gocui/task_manager.go index e3c82b4d4..23ef0f77e 100644 --- a/pkg/gocui/task_manager.go +++ b/pkg/gocui/task_manager.go @@ -22,7 +22,7 @@ func newTaskManager() *TaskManager { } } -func (self *TaskManager) NewTask() *TaskImpl { +func (self *TaskManager) NewTask(background bool) *TaskImpl { self.mutex.Lock() defer self.mutex.Unlock() @@ -30,12 +30,34 @@ func (self *TaskManager) NewTask() *TaskImpl { taskId := self.nextId onDone := func() { self.delete(taskId) } - task := &TaskImpl{id: taskId, busy: true, onDone: onDone, withMutex: self.withMutex} + task := &TaskImpl{id: taskId, busy: true, background: background, onDone: onDone, withMutex: self.withMutex} self.tasks[taskId] = task return task } +// hasBusyForegroundTaskExcept reports whether any task other than `ignore` is +// currently busy and not a background task. It's used to decide whether a repo +// switch is safe: a foreground operation (or the refresh it triggers, or that +// refresh's follow-up callbacks) still in flight means the switch must wait, so +// it doesn't run against a repo that's about to be swapped out. +// +// `ignore` is the event currently being processed on the UI thread — the switch +// attempt itself — which is always busy and so must not count as a reason to +// refuse itself. +func (self *TaskManager) hasBusyForegroundTaskExcept(ignore Task) bool { + self.mutex.Lock() + defer self.mutex.Unlock() + + for _, task := range self.tasks { + if task != ignore && task.isBusy() && !task.isBackground() { + return true + } + } + + return false +} + func (self *TaskManager) addIdleListener(c chan struct{}) { self.idleListeners = append(self.idleListeners, c) } diff --git a/pkg/gocui/task_manager_test.go b/pkg/gocui/task_manager_test.go new file mode 100644 index 000000000..7fe706d7a --- /dev/null +++ b/pkg/gocui/task_manager_test.go @@ -0,0 +1,63 @@ +package gocui + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestTaskManagerHasBusyForegroundTaskExcept(t *testing.T) { + t.Run("no tasks", func(t *testing.T) { + tm := newTaskManager() + assert.False(t, tm.hasBusyForegroundTaskExcept(nil)) + }) + + t.Run("a busy foreground task counts", func(t *testing.T) { + tm := newTaskManager() + tm.NewTask(false) + assert.True(t, tm.hasBusyForegroundTaskExcept(nil)) + }) + + t.Run("a busy background task does not count", func(t *testing.T) { + tm := newTaskManager() + tm.NewTask(true) + assert.False(t, tm.hasBusyForegroundTaskExcept(nil)) + }) + + t.Run("a done foreground task does not count", func(t *testing.T) { + tm := newTaskManager() + task := tm.NewTask(false) + task.Done() + assert.False(t, tm.hasBusyForegroundTaskExcept(nil)) + }) + + t.Run("a paused foreground task does not count", func(t *testing.T) { + tm := newTaskManager() + task := tm.NewTask(false) + task.Pause() + assert.False(t, tm.hasBusyForegroundTaskExcept(nil)) + }) + + t.Run("the ignored task does not count", func(t *testing.T) { + tm := newTaskManager() + task := tm.NewTask(false) + assert.False(t, tm.hasBusyForegroundTaskExcept(task)) + }) + + t.Run("another foreground task counts even when one is ignored", func(t *testing.T) { + tm := newTaskManager() + ignored := tm.NewTask(false) + tm.NewTask(false) + assert.True(t, tm.hasBusyForegroundTaskExcept(ignored)) + }) + + t.Run("only a background task alongside the ignored current event", func(t *testing.T) { + // This is the repo-switch case: the switch is handled as the current + // event (ignored) while a background refresh is in flight; it must not + // be considered busy. + tm := newTaskManager() + current := tm.NewTask(false) + tm.NewTask(true) + assert.False(t, tm.hasBusyForegroundTaskExcept(current)) + }) +} diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 834cf1e2d..5aa8beaec 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -1194,16 +1194,32 @@ func (gui *Gui) onUIThread(f func() error) { }) } +func (gui *Gui) onUIThreadBackground(f func() error) { + gui.g.UpdateBackground(func(*gocui.Gui) error { + return f() + }) +} + func (gui *Gui) onUIThreadContentOnly(f func() error) { gui.g.UpdateContentOnly(func(*gocui.Gui) error { return f() }) } +func (gui *Gui) onUIThreadContentOnlyBackground(f func() error) { + gui.g.UpdateContentOnlyBackground(func(*gocui.Gui) error { + return f() + }) +} + func (gui *Gui) onWorker(f func(gocui.Task) error) { gui.g.OnWorker(f) } +func (gui *Gui) onWorkerBackground(f func(gocui.Task) error) { + gui.g.OnWorkerBackground(f) +} + func (gui *Gui) getWindowDimensions(informationStr string, appStatus string) map[string]boxlayout.Dimensions { return gui.helpers.WindowArrangement.GetWindowDimensions(informationStr, appStatus) } diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index c74a99a05..d13120508 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -124,14 +124,26 @@ func (self *guiCommon) OnUIThread(f func() error) { self.gui.onUIThread(f) } +func (self *guiCommon) OnUIThreadBackground(f func() error) { + self.gui.onUIThreadBackground(f) +} + func (self *guiCommon) OnUIThreadContentOnly(f func() error) { self.gui.onUIThreadContentOnly(f) } +func (self *guiCommon) OnUIThreadContentOnlyBackground(f func() error) { + self.gui.onUIThreadContentOnlyBackground(f) +} + func (self *guiCommon) OnWorker(f func(gocui.Task) error) { self.gui.onWorker(f) } +func (self *guiCommon) OnWorkerBackground(f func(gocui.Task) error) { + self.gui.onWorkerBackground(f) +} + func (self *guiCommon) RenderToMainViews(opts types.RefreshMainOpts) { self.gui.refreshMainViews(opts) } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 2ce07f9c7..766a5a757 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -75,13 +75,22 @@ type IGuiCommon interface { // Only necessary to call if you're not already on the UI thread i.e. you're inside a goroutine. // All controller handlers are executed on the UI thread. OnUIThread(f func() error) + // Like OnUIThread, but for work triggered by a background routine, so it + // doesn't count towards lazygit being busy (see the *Background methods on + // gocui.Gui and repo-switch safety). + OnUIThreadBackground(f func() error) // Like OnUIThread, but signals that the callback only modifies view // content (e.g. spinner), allows the event loop to skip // the expensive layout recalculation when only content changed. OnUIThreadContentOnly(f func() error) + // Like OnUIThreadContentOnly, but for background work (see OnUIThreadBackground). + OnUIThreadContentOnlyBackground(f func() error) // Runs a function in a goroutine. Use this whenever you want to run a goroutine and keep track of the fact // that lazygit is still busy. See docs/dev/Busy.md OnWorker(f func(gocui.Task) error) + // Like OnWorker, but for a background routine (or work it triggers), so it + // doesn't count towards lazygit being busy (see OnUIThreadBackground). + OnWorkerBackground(f func(gocui.Task) error) // Function to call at the end of our 'layout' function which renders views // For example, you may want a view's line to be focused only after that view is // resized, if in accordion mode. From d95900ccd08e64dddcee2606f4787c3224749130 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 3 Jul 2026 21:15:01 +0200 Subject: [PATCH 073/218] Tag background routines and their refreshes as background tasks For the busy query to be usable as a repo-switch guard it has to be false while the ongoing background routines run, or a switch would be refused every time a background fetch or files refresh happened to be in flight. Mark that work as background so it's excluded from the query. The background routine dispatch in goEvery becomes OnWorkerBackground, and the auto-fetch waiting status renders its spinner through the background variants. Within a refresh, the background flag (which Refresh already carries as options.Background, and which the files path already threaded) is now threaded through every place that enqueues a task: the async scope workers, the model-write bounces (onUIThreadUnlessRepoChanged), refreshView, the staging bounce, the Then dispatch, and the branch-loader's behind-count worker. Two single-caller chains reached by a background files refresh get the flag too: MergeConflictsHelper.EscapeMerge and BranchesHelper. AutoForwardBranches (whose follow-up refresh must stay background when triggered by the background fetch). Nothing gates on the busy query yet, so this is behavior-preserving; background tasks still count as busy for the test idle-listener, which looks at every task regardless of the background flag. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/background.go | 7 +- .../controllers/helpers/app_status_helper.go | 31 ++- .../controllers/helpers/branches_helper.go | 6 +- .../helpers/merge_conflicts_helper.go | 14 +- pkg/gui/controllers/helpers/refresh_helper.go | 189 ++++++++++-------- 5 files changed, 146 insertions(+), 101 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 94bf4f678..6215f0d45 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -114,7 +114,7 @@ func (self *BackgroundRoutineMgr) startBackgroundFetch() { if self.gui.UserConfig().Gui.ShowBottomLine || firstTimeOrRetriggered { return self.gui.helpers.AppStatus.WithWaitingStatusImpl(self.gui.Tr.FetchingStatus, func(gocui.Task) error { return self.backgroundFetch() - }, nil) + }, nil, true) } return self.backgroundFetch() @@ -198,7 +198,10 @@ func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop chan stru if self.backgroundRefreshesPaused() { return } - self.gui.c.OnWorker(func(gocui.Task) error { + // OnWorkerBackground, not OnWorker: these routines and the refreshes + // they trigger must not count towards lazygit being busy, or they'd + // spuriously block a repo switch every time one happens to be running. + self.gui.c.OnWorkerBackground(func(gocui.Task) error { _ = function(retriggered) done <- struct{}{} return nil diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index b691db4a4..bffd87866 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -34,7 +34,7 @@ func (self *AppStatusHelper) Toast(message string, kind types.ToastKind) { self.statusMgr().AddToastStatus(message, kind) - self.renderAppStatus() + self.renderAppStatus(false) } // A custom task for WithWaitingStatus calls; it wraps the original one and @@ -61,11 +61,14 @@ func (self appStatusHelperTask) Continue() { // WithWaitingStatus wraps a function and shows a waiting status while the function is still executing func (self *AppStatusHelper) WithWaitingStatus(message string, f func(gocui.Task) error) { self.c.OnWorker(func(task gocui.Task) error { - return self.WithWaitingStatusImpl(message, f, task) + return self.WithWaitingStatusImpl(message, f, task, false) }) } -func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui.Task) error, task gocui.Task) error { +// background reports whether this waiting status belongs to a background routine +// (the auto-fetch poller); when it does, the spinner it drives must not count +// towards lazygit being busy, or it'd block repo switches while a fetch runs. +func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui.Task) error, task gocui.Task, background bool) error { // A waiting status means lazygit is driving a git operation itself (often // one that internally runs a rebase and continues it). Pause the background // routines for its duration so they don't refresh from an intermediate @@ -73,7 +76,7 @@ func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui. self.c.PauseBackgroundRefreshes(true) defer self.c.PauseBackgroundRefreshes(false) - return self.statusMgr().WithWaitingStatus(message, self.renderAppStatus, func(waitingStatusHandle *status.WaitingStatusHandle) error { + return self.statusMgr().WithWaitingStatus(message, func() { self.renderAppStatus(background) }, func(waitingStatusHandle *status.WaitingStatusHandle) error { return f(appStatusHelperTask{task, waitingStatusHandle}) }) } @@ -100,21 +103,33 @@ func (self *AppStatusHelper) GetStatusString() string { return appStatus } -func (self *AppStatusHelper) renderAppStatus() { - self.c.OnWorker(func(_ gocui.Task) error { +func (self *AppStatusHelper) renderAppStatus(background bool) { + // A background waiting status (auto-fetch) must not count towards lazygit + // being busy, so its spinner worker and per-frame UI updates go through the + // background variants. + onWorker := self.c.OnWorker + onUIThread := self.c.OnUIThread + onUIThreadContentOnly := self.c.OnUIThreadContentOnly + if background { + onWorker = self.c.OnWorkerBackground + onUIThread = self.c.OnUIThreadBackground + onUIThreadContentOnly = self.c.OnUIThreadContentOnlyBackground + } + + onWorker(func(_ gocui.Task) error { ticker := time.NewTicker(time.Millisecond * time.Duration(self.c.UserConfig().Gui.Spinner.Rate)) defer ticker.Stop() prevAppStatus := "" for range ticker.C { appStatus, color := self.statusMgr().GetStatusString(self.c.UserConfig()) - update := self.c.OnUIThreadContentOnly + update := onUIThreadContentOnly if utils.StringWidth(appStatus) != utils.StringWidth(prevAppStatus) { // Need a full layout whenever the width of the status string changes. This can't // happen during normal spinning because we validate that all spinner frames have // the same width, so typically this will only be triggered at the beginning and end // of a status, or if the status string changes midway for some reason. - update = self.c.OnUIThread + update = onUIThread } update(func() error { self.c.Views().AppStatus.FgColor = color diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index e5c1a07e4..053804760 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -398,7 +398,7 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er if fetchErr != nil { return nil } - err := self.AutoForwardBranches() + err := self.AutoForwardBranches(background) if background && err != nil { // The background poller discards this return value, so surface // the error in the log rather than as a popup for background work. @@ -411,7 +411,7 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er return fetchErr } -func (self *BranchesHelper) AutoForwardBranches() error { +func (self *BranchesHelper) AutoForwardBranches(background bool) error { if self.c.UserConfig().Git.AutoForwardBranches == "none" { return nil } @@ -443,7 +443,7 @@ func (self *BranchesHelper) AutoForwardBranches() error { self.c.LogCommand(strings.TrimRight(updateCommands, "\n"), false) err := self.c.Git().Branch.UpdateBranchRefs(updateCommands) - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Mode: types.SYNC}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Mode: types.SYNC, Background: background}) return err } diff --git a/pkg/gui/controllers/helpers/merge_conflicts_helper.go b/pkg/gui/controllers/helpers/merge_conflicts_helper.go index 6e6a01531..175bc3cc0 100644 --- a/pkg/gui/controllers/helpers/merge_conflicts_helper.go +++ b/pkg/gui/controllers/helpers/merge_conflicts_helper.go @@ -51,11 +51,17 @@ func (self *MergeConflictsHelper) resetMergeState() { self.context().GetState().Reset() } -func (self *MergeConflictsHelper) EscapeMerge() error { +func (self *MergeConflictsHelper) EscapeMerge(background bool) error { self.resetMergeState() // doing this in separate UI thread so that we're not still holding the lock by the time refresh the file - self.c.OnUIThread(func() error { + onUIThread := self.c.OnUIThread + if background { + // Reached from a background files refresh; keep it off the busy count + // (see the *Background dispatch methods) so it doesn't block a repo switch. + onUIThread = self.c.OnUIThreadBackground + } + onUIThread(func() error { // There is a race condition here: refreshing the files scope can trigger the // confirmation context to be pushed if all conflicts are resolved (prompting // to continue the merge/rebase. In that case, we don't want to then push the @@ -120,7 +126,7 @@ func (self *MergeConflictsHelper) Render() { }) } -func (self *MergeConflictsHelper) RefreshMergeState() error { +func (self *MergeConflictsHelper) RefreshMergeState(background bool) error { self.c.Contexts().MergeConflicts.GetMutex().Lock() defer self.c.Contexts().MergeConflicts.GetMutex().Unlock() @@ -134,7 +140,7 @@ func (self *MergeConflictsHelper) RefreshMergeState() error { } if !hasConflicts { - return self.EscapeMerge() + return self.EscapeMerge(background) } return nil diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index fe89bbad6..c0543d095 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -154,7 +154,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // everything happens fast and it's better to have everything update // in the one frame if !self.c.InDemo() && options.Mode == types.ASYNC { - self.c.OnWorker(func(t gocui.Task) error { + self.onWorker(options.Background, func(t gocui.Task) error { f() return nil }) @@ -176,14 +176,14 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. refresh("commits and commit files", func() { - self.refreshCommitsAndCommitFiles(options.CommitSelection) + self.refreshCommitsAndCommitFiles(options.CommitSelection, options.Background) }) includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { branchesAndRemotesWg.Add(1) refresh("reflog and branches", func() { - self.refreshReflogAndBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex) + self.refreshReflogAndBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, options.Background) branchesAndRemotesWg.Done() }) } else { @@ -192,24 +192,24 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // Not a recency sort, so branches doesn't depend on the reflog // being fresh; it runs concurrently with the reflog refresh // below and reads whatever's in the model, as it always has. - self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true, self.c.Model().ReflogCommits) + self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true, self.c.Model().ReflogCommits, options.Background) branchesAndRemotesWg.Done() }) - refresh("reflog", func() { _, _ = self.refreshReflogCommits() }) + refresh("reflog", func() { _, _ = self.refreshReflogCommits(options.Background) }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one // if we've asked specifically for rebase commits and not those other things - refresh("rebase commits", func() { _ = self.refreshRebaseCommits() }) + refresh("rebase commits", func() { _ = self.refreshRebaseCommits(options.Background) }) } if scopeSet.Includes(types.SUB_COMMITS) { - refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit() }) + refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(options.Background) }) } // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { - refresh("commit files", func() { _ = self.refreshCommitFilesContext() }) + refresh("commit files", func() { _ = self.refreshCommitFilesContext(options.Background) }) } fileWg := sync.WaitGroup{} @@ -222,17 +222,17 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { } if scopeSet.Includes(types.STASH) { - refresh("stash", func() { self.refreshStashEntries() }) + refresh("stash", func() { self.refreshStashEntries(options.Background) }) } if scopeSet.Includes(types.TAGS) { - refresh("tags", func() { _ = self.refreshTags() }) + refresh("tags", func() { _ = self.refreshTags(options.Background) }) } if scopeSet.Includes(types.REMOTES) { branchesAndRemotesWg.Add(1) refresh("remotes", func() { - _ = self.refreshRemotes() + _ = self.refreshRemotes(options.Background) branchesAndRemotesWg.Done() }) } @@ -240,12 +240,12 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if scopeSet.Includes(types.PULL_REQUESTS) { refresh("pull requests", func() { branchesAndRemotesWg.Wait() - self.refreshGithubPullRequests() + self.refreshGithubPullRequests(options.Background) }) } if scopeSet.Includes(types.WORKTREES) && !includeWorktreesWithBranches { - refresh("worktrees", func() { self.refreshWorktrees() }) + refresh("worktrees", func() { self.refreshWorktrees(options.Background) }) } if scopeSet.Includes(types.STAGING) { @@ -255,7 +255,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // scope's model-update bounce — RefreshStagingPanel reads // Model.Files (via Files.GetSelected) and would otherwise // see the pre-refresh model. - self.c.OnUIThread(func() error { + self.onUIThread(options.Background, func() error { self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) return nil }) @@ -267,10 +267,10 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { } if scopeSet.Includes(types.MERGE_CONFLICTS) { - refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState() }) + refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(options.Background) }) } - self.refreshStatus() + self.refreshStatus(options.Background) wg.Wait() @@ -281,7 +281,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // returned but their bounces haven't been processed yet, so // invoking Then synchronously would run it on a model that's // still pre-refresh. - self.c.OnUIThread(options.Then) + self.onUIThread(options.Background, options.Then) } } @@ -399,27 +399,27 @@ func getModeName(mode types.RefreshMode) string { // order gives the immediate (non-recency) load a lower branch-load sequence // than the async (recency) load, so the sequence guard in refreshBranches keeps // the recency-sorted result even if the two loads' bounces land out of order. -func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool) { +func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, background bool) { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, false, self.c.Model().ReflogCommits) + self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, false, self.c.Model().ReflogCommits, background) - self.c.OnWorker(func(_ gocui.Task) error { - reflogCommits, _ := self.refreshReflogCommits() - self.refreshBranches(false, true, true, reflogCommits) + self.onWorker(background, func(_ gocui.Task) error { + reflogCommits, _ := self.refreshReflogCommits(background) + self.refreshBranches(false, true, true, reflogCommits, background) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) case types.COMPLETE: - reflogCommits, _ := self.refreshReflogCommits() - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, true, reflogCommits) + reflogCommits, _ := self.refreshReflogCommits(background) + self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, true, reflogCommits, background) } } -func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior) { +func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior, background bool) { generation := self.c.State().GetRepoGeneration() - _ = self.refreshCommitsWithLimit(commitSelection) + _ = self.refreshCommitsWithLimit(commitSelection, background) ctx := self.c.Contexts().CommitFiles.GetParentContext() if ctx != nil && ctx.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY { // This makes sense when we've e.g. just amended a commit, meaning we get a new commit hash at the same position. @@ -432,13 +432,13 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.Co // The commit selection is restored in refreshCommitsWithLimit's bounce, // so read it on the UI thread after that bounce; then load the commit // files back on a worker (refreshCommitFilesContext does git work). - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { commit := self.c.Contexts().LocalCommits.GetSelected() if commit != nil && commit.RefName() != "" { refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() self.c.Contexts().CommitFiles.ReInit(commit, refRange) - self.c.OnWorker(func(gocui.Task) error { - _ = self.refreshCommitFilesContext() + self.onWorker(background, func(gocui.Task) error { + _ = self.refreshCommitFilesContext(background) return nil }) } @@ -473,7 +473,7 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { return nil } -func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitSelectionBehavior) error { +func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitSelectionBehavior, background bool) error { generation := self.c.State().GetRepoGeneration() var selectionRange *localCommitSelectionRange @@ -502,7 +502,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().BisectInfo = bisectInfo self.c.Model().Commits = commits self.RefreshAuthors(commits) @@ -536,7 +536,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS // Enqueued from within this bounce so it runs after refreshView's // render below (which was enqueued first), matching the previous // ordering where FocusLine ran after the view was re-rendered. - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Contexts().LocalCommits.FocusLine(true) return nil }) @@ -544,7 +544,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS return nil }) - self.refreshView(self.c.Contexts().LocalCommits) + self.refreshView(self.c.Contexts().LocalCommits, background) return nil } @@ -623,7 +623,7 @@ func hasRestorableCommitHash(commits []*models.Commit, idx int) bool { return idx >= 0 && idx < len(commits) && commits[idx].Hash() != "" } -func (self *RefreshHelper) refreshSubCommitsWithLimit() error { +func (self *RefreshHelper) refreshSubCommitsWithLimit(background bool) error { if self.c.Contexts().SubCommits.GetRef() == nil { return nil } @@ -646,13 +646,13 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit() error { if err != nil { return err } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().SubCommits = commits self.RefreshAuthors(commits) return nil }) - self.refreshView(self.c.Contexts().SubCommits) + self.refreshView(self.c.Contexts().SubCommits, background) return nil } @@ -668,7 +668,7 @@ func (self *RefreshHelper) RefreshAuthors(commits []*models.Commit) { } } -func (self *RefreshHelper) refreshCommitFilesContext() error { +func (self *RefreshHelper) refreshCommitFilesContext(background bool) error { from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) generation := self.c.State().GetRepoGeneration() @@ -677,16 +677,16 @@ func (self *RefreshHelper) refreshCommitFilesContext() error { if err != nil { return err } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().CommitFiles = files self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() return nil }) - self.refreshView(self.c.Contexts().CommitFiles) + self.refreshView(self.c.Contexts().CommitFiles, background) return nil } -func (self *RefreshHelper) refreshRebaseCommits() error { +func (self *RefreshHelper) refreshRebaseCommits(background bool) error { generation := self.c.State().GetRepoGeneration() updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(self.c.Model().HashPool, self.c.Model().Commits) @@ -695,17 +695,17 @@ func (self *RefreshHelper) refreshRebaseCommits() error { } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().Commits = updatedCommits self.c.Model().WorkingTreeStateAtLastCommitRefresh = workingTreeState return nil }) - self.refreshView(self.c.Contexts().LocalCommits) + self.refreshView(self.c.Contexts().LocalCommits, background) return nil } -func (self *RefreshHelper) refreshTags() error { +func (self *RefreshHelper) refreshTags(background bool) error { generation := self.c.State().GetRepoGeneration() tags, err := self.c.Git().Loaders.TagLoader.GetTags() @@ -713,12 +713,12 @@ func (self *RefreshHelper) refreshTags() error { return err } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().Tags = tags return nil }) - self.refreshView(self.c.Contexts().Tags) + self.refreshView(self.c.Contexts().Tags, background) return nil } @@ -728,7 +728,7 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool, reflogCommits []*models.Commit) { +func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) { loadSeq := self.branchLoadSeq.Add(1) generation := self.c.State().GetRepoGeneration() @@ -739,14 +739,14 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele self.c.Model().Branches, loadBehindCounts, func(f func() error) { - self.c.OnWorker(func(_ gocui.Task) error { + self.onWorker(background, func(_ gocui.Task) error { return f() }) }, func() { - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Contexts().Branches.HandleRender() - self.refreshStatus() + self.refreshStatus(background) return nil }) }) @@ -761,7 +761,7 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele worktrees = self.loadWorktrees() } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { // Drop this write if a branch load that started later has already applied // its result. At the INITIAL startup stage an immediate load (not // recency-sorted) and an async recency-sorted load run concurrently; this @@ -779,7 +779,7 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele if refreshWorktrees { self.c.Model().Worktrees = worktrees - self.refreshView(self.c.Contexts().Worktrees) + self.refreshView(self.c.Contexts().Worktrees, background) } if !keepBranchSelectionIndex && prevSelectedBranch != nil { @@ -798,9 +798,9 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele return nil }) - self.refreshView(self.c.Contexts().Branches) + self.refreshView(self.c.Contexts().Branches, background) - self.refreshStatus() + self.refreshStatus(background) } func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { @@ -813,8 +813,8 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { return err } - self.refreshView(self.c.Contexts().Submodules) - self.refreshView(self.c.Contexts().Files) + self.refreshView(self.c.Contexts().Submodules, background) + self.refreshView(self.c.Contexts().Files, background) return nil } @@ -826,8 +826,8 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { // bumps the generation, so a write captured under the old generation must not // clobber the new repo's state. Callers capture the generation with // State().GetRepoGeneration() before doing their git work and pass it in. -func (self *RefreshHelper) onUIThreadUnlessRepoChanged(generation int, f func() error) { - self.c.OnUIThread(func() error { +func (self *RefreshHelper) onUIThreadUnlessRepoChanged(generation int, background bool, f func() error) { + self.onUIThread(background, func() error { if self.c.State().GetRepoGeneration() != generation { return nil } @@ -835,6 +835,27 @@ func (self *RefreshHelper) onUIThreadUnlessRepoChanged(generation int, f func() }) } +// onWorker and onUIThread pick the foreground or background variant of the +// corresponding dispatch method depending on whether we're servicing a +// background refresh. Background refreshes (auto-fetch and friends) must not +// count towards lazygit being busy, or they'd spuriously block a repo switch; +// see the *Background methods on gocui.Gui. +func (self *RefreshHelper) onWorker(background bool, f func(gocui.Task) error) { + if background { + self.c.OnWorkerBackground(f) + } else { + self.c.OnWorker(f) + } +} + +func (self *RefreshHelper) onUIThread(background bool, f func() error) { + if background { + self.c.OnUIThreadBackground(f) + } else { + self.c.OnUIThread(f) + } +} + func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs []*models.SubmoduleConfig) error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel generation := self.c.State().GetRepoGeneration() @@ -898,7 +919,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // (e.g. in the user's editor). Offer to continue it. We only do this // for operations we started ourselves; prompting for one that was // started outside lazygit (e.g. by a coding agent) would be confusing. - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) } @@ -913,7 +934,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ }) } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { // only taking over the filter if it hasn't already been set by the user. if conflictFileCount > 0 && prevConflictFileCount == 0 { if fileTreeViewModel.GetStatusFilter() == filetree.DisplayAll { @@ -944,7 +965,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // refreshReflogCommits returns the (non-filtered) ReflogCommits it loaded, so // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. -func (self *RefreshHelper) refreshReflogCommits() ([]*models.Commit, error) { +func (self *RefreshHelper) refreshReflogCommits(background bool) ([]*models.Commit, error) { generation := self.c.State().GetRepoGeneration() // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception @@ -984,17 +1005,17 @@ func (self *RefreshHelper) refreshReflogCommits() ([]*models.Commit, error) { } } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { model.ReflogCommits = reflogCommits model.FilteredReflogCommits = filteredReflogCommits return nil }) - self.refreshView(self.c.Contexts().ReflogCommits) + self.refreshView(self.c.Contexts().ReflogCommits, background) return reflogCommits, nil } -func (self *RefreshHelper) refreshRemotes() error { +func (self *RefreshHelper) refreshRemotes(background bool) error { generation := self.c.State().GetRepoGeneration() prevSelectedRemote := self.c.Contexts().Remotes.GetSelected() @@ -1003,14 +1024,14 @@ func (self *RefreshHelper) refreshRemotes() error { return err } - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().Remotes = remotes hadPrs := len(self.c.Model().PullRequestsMap) != 0 self.rebuildPullRequestsMap() if !hadPrs && len(self.c.Model().PullRequestsMap) != 0 { // if we didn't have PRs in the map before but now we do, we need to redraw the branches view - self.refreshView(self.c.Contexts().Branches) + self.refreshView(self.c.Contexts().Branches, background) } // we need to ensure our selected remote branches aren't now outdated @@ -1026,8 +1047,8 @@ func (self *RefreshHelper) refreshRemotes() error { return nil }) - self.refreshView(self.c.Contexts().Remotes) - self.refreshView(self.c.Contexts().RemoteBranches) + self.refreshView(self.c.Contexts().Remotes, background) + self.refreshView(self.c.Contexts().RemoteBranches, background) return nil } @@ -1040,44 +1061,44 @@ func (self *RefreshHelper) loadWorktrees() []*models.Worktree { return worktrees } -func (self *RefreshHelper) refreshWorktrees() { +func (self *RefreshHelper) refreshWorktrees(background bool) { generation := self.c.State().GetRepoGeneration() worktrees := self.loadWorktrees() - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().Worktrees = worktrees return nil }) // need to refresh branches because the branches view shows worktrees against // branches - self.refreshView(self.c.Contexts().Branches) - self.refreshView(self.c.Contexts().Worktrees) + self.refreshView(self.c.Contexts().Branches, background) + self.refreshView(self.c.Contexts().Worktrees, background) } -func (self *RefreshHelper) refreshStashEntries() { +func (self *RefreshHelper) refreshStashEntries(background bool) { generation := self.c.State().GetRepoGeneration() stashEntries := self.c.Git().Loaders.StashLoader. GetStashEntries(self.c.Modes().Filtering.GetPath()) - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().StashEntries = stashEntries return nil }) - self.refreshView(self.c.Contexts().Stash) + self.refreshView(self.c.Contexts().Stash, background) } // never call this on its own, it should only be called from within refreshCommits() -func (self *RefreshHelper) refreshStatus() { +func (self *RefreshHelper) refreshStatus(background bool) { generation := self.c.State().GetRepoGeneration() workingTreeState := self.c.Git().Status.WorkingTreeState() repoName := self.c.Git().RepoPaths.RepoName() - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { // Read the checked-out branch and the linked worktree name here on the UI // thread: both derive from models (Branches, Worktrees) that their // refreshes now write via bounces, so reading them on the worker would @@ -1114,10 +1135,10 @@ func (self *RefreshHelper) refForLog() (string, *git_commands.BisectInfo) { return bisectInfo.GetStartHash(), bisectInfo } -func (self *RefreshHelper) refreshView(context types.Context) { +func (self *RefreshHelper) refreshView(context types.Context, background bool) { // refreshView is called from the worker goroutine that drives async // refreshes, so bounce to the UI thread before mutating view content. - self.c.OnUIThread(func() error { + self.onUIThread(background, func() error { // Re-applying the filter must be done before re-rendering the view, so that // the filtered list model is up to date for rendering. self.searchHelper.ReApplyFilter(context) @@ -1140,11 +1161,11 @@ func (self *RefreshHelper) refreshView(context types.Context) { }) } -func (self *RefreshHelper) refreshGithubPullRequests() { +func (self *RefreshHelper) refreshGithubPullRequests(background bool) { generation := self.c.State().GetRepoGeneration() clearPullRequests := func() { - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().PullRequests = nil self.c.Model().PullRequestsMap = nil return nil @@ -1167,7 +1188,7 @@ func (self *RefreshHelper) refreshGithubPullRequests() { return } - self.setGithubPullRequests(baseInfo) + self.setGithubPullRequests(baseInfo, background) } type githubRemoteInfo struct { @@ -1248,7 +1269,7 @@ func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteI self.c.Log.Error(err) } - self.setGithubPullRequests(&info) + self.setGithubPullRequests(&info, false) return nil }) }, @@ -1276,7 +1297,7 @@ func (self *RefreshHelper) rebuildPullRequestsMap() { ) } -func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo) { +func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, background bool) { generation := self.c.State().GetRepoGeneration() if len(self.c.Model().Branches) == 0 { @@ -1298,7 +1319,7 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo) { self.savePullRequestsToCache(prs) - self.onUIThreadUnlessRepoChanged(generation, func() error { + self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().PullRequests = prs // Rebuilding here rather than on the worker means the map is built from // the branches and remotes as they are on the UI thread, after their From 8655d3f5a59d35cfc4176d66defed263b62d64a5 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 07:49:04 +0200 Subject: [PATCH 074/218] Exclude view-buffer render tasks from the busy query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repo-switch busy query must not count view-buffer content rendering: those tasks paint a view rather than drive a git operation, so leaving one running across a switch is harmless (the switch's own refresh re-renders). More importantly, they fire on nearly every focus/selection change — including the context activation that runs right before a menu/prompt confirmation handler (e.g. confirming worktree creation). A synchronous busy check in such a handler would otherwise see that render and make the very switch the handler is about to request refuse itself. Route ViewBufferManager's tasks through a new gocui NewBackgroundTask so they're tracked for idle detection but excluded from the busy query. The task "background" flag now covers two kinds of non-blocking work: the background routines (and their refreshes) tagged earlier, and view rendering. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/gui.go | 7 +++++++ pkg/gocui/task.go | 12 ++++++++---- pkg/gui/tasks_adapter.go | 9 ++++++++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index ff113a2dd..a13744997 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -282,6 +282,13 @@ func (g *Gui) NewTask() *TaskImpl { return g.taskManager.NewTask(false) } +// NewBackgroundTask creates a task that is tracked for idle detection but does +// not count towards the program being busy for repo-switch safety. See +// TaskImpl.background. +func (g *Gui) NewBackgroundTask() *TaskImpl { + return g.taskManager.NewTask(true) +} + // Busy reports whether any foreground work is in flight, ignoring the event // currently being processed on the main goroutine (see currentTask). Background // routines (auto-fetch etc.) don't count. It's used to decide whether it's safe diff --git a/pkg/gocui/task.go b/pkg/gocui/task.go index 377781a4f..08a77463f 100644 --- a/pkg/gocui/task.go +++ b/pkg/gocui/task.go @@ -20,10 +20,14 @@ type TaskImpl struct { withMutex func(func()) // Background tasks don't count towards the program being "busy" for the // purpose of deciding whether a repo switch is safe (see - // TaskManager.hasBusyForegroundTaskExcept). They're the ongoing background - // routines (auto-fetch, files refresh, external-change detection) and the - // refreshes they trigger, whose model writes are already guarded against a - // concurrent repo switch by the repo generation. + // TaskManager.hasBusyForegroundTaskExcept). Two kinds of work are tagged + // this way: the ongoing background routines (auto-fetch, files refresh, + // external-change detection) and the refreshes they trigger, whose model + // writes are already guarded against a concurrent repo switch by the repo + // generation; and view-buffer content rendering, which only paints a view + // and so is harmless to leave running across a switch. What stays + // foreground is lazygit driving a git operation and applying its results + // to the model — exactly the work a repo switch must not run underneath. background bool } diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 09edd2d36..dd7999107 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -136,7 +136,14 @@ func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager { view.SetOrigin(0, 0) }, func() gocui.Task { - return gui.c.GocuiGui().NewTask() + // A background task: rendering content into a view is display + // work, not lazygit driving a git operation, so it must not + // count towards being busy and block a repo switch. These + // renders fire on nearly every focus/selection change, including + // the context activation that happens right before a menu/prompt + // handler runs (e.g. confirming worktree creation), which would + // otherwise make the switch that handler triggers refuse itself. + return gui.c.GocuiGui().NewBackgroundTask() }, ) gui.viewBufferManagerMap[view.Name()] = manager From 56932abe0659edfa0bac2704366d6d8a431ab709 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 07:49:15 +0200 Subject: [PATCH 075/218] Refuse a repo switch while a foreground operation is in flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Switching repos reassigns gui.git and the process cwd; doing it while a foreground git operation (rebase/commit/push/…) is mid-flight would run that operation's remaining commands against the wrong repo. The same applies while the refresh an operation triggers is still settling: its model writes are generation-guarded, but the client-side Then/OnUIThread callbacks that run after it aren't, and shouldn't run against a repo that changed underneath them. Refuse the switch (with a toast) whenever gocui reports a busy foreground task. DispatchSwitchTo carries the guard for the simple callers. The callers that do work before the switch check up front instead, so a refused switch doesn't leave that work half-done: worktree creation checks before creating (its own waiting-status spinner would otherwise make the query busy and refuse its own switch); submodule-enter and the recent-repos menu check before mutating the repo-path stack (pushing / clearing it); and escape-to-parent (SwitchToParentRepo) checks before popping it, so a refusal doesn't consume the entry and strand the user with nowhere to escape back to. All then call the unguarded switchTo, which is safe because their own operation is complete by then. --- pkg/gui/controllers/helpers/repos_helper.go | 65 ++++++++++++++++--- .../controllers/helpers/worktree_helper.go | 13 +++- pkg/gui/controllers/quit_actions.go | 6 +- pkg/i18n/english.go | 2 + 4 files changed, 70 insertions(+), 16 deletions(-) diff --git a/pkg/gui/controllers/helpers/repos_helper.go b/pkg/gui/controllers/helpers/repos_helper.go index 6257327e9..a61ad0013 100644 --- a/pkg/gui/controllers/helpers/repos_helper.go +++ b/pkg/gui/controllers/helpers/repos_helper.go @@ -43,13 +43,20 @@ func NewRecentReposHelper( } func (self *ReposHelper) EnterSubmodule(submodule *models.SubmoduleConfig) error { + // Check before pushing onto the repo-path stack, so a refused switch + // doesn't leave a stale entry there (which escape would later switch back + // to, needlessly reloading the current repo). + if self.switchRefusedBecauseBusy() { + return nil + } + wd, err := os.Getwd() if err != nil { return err } self.c.State().GetRepoPathStack().Push(wd) - return self.DispatchSwitchToRepo(submodule.FullPath(), context.NO_CONTEXT) + return self.switchTo(submodule.FullPath(), self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT) } func (self *ReposHelper) getCurrentBranch(path string) string { @@ -129,10 +136,16 @@ func (self *ReposHelper) CreateRecentReposMenu() error { style.FgMagenta.Sprint(path), }, OnPress: func() error { + // Check before clearing the stack, so a refused switch doesn't + // forget the submodule breadcrumb (which would leave escape + // unable to return to the parent repo). + if self.switchRefusedBecauseBusy() { + return nil + } // if we were in a submodule, we want to forget about that stack of repos // so that hitting escape in the new repo does nothing self.c.State().GetRepoPathStack().Clear() - return self.DispatchSwitchToRepo(path, context.NO_CONTEXT) + return self.switchTo(path, self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT) }, } }) @@ -140,17 +153,49 @@ func (self *ReposHelper) CreateRecentReposMenu() error { return self.c.Menu(types.CreateMenuOptions{Title: self.c.Tr.RecentRepos, Items: menuItems}) } -func (self *ReposHelper) DispatchSwitchToRepo(path string, contextKey types.ContextKey) error { - return self.DispatchSwitchTo(path, self.c.Tr.ErrRepositoryMovedOrDeleted, contextKey) +// SwitchToParentRepo switches back to the repo the current submodule was +// entered from (the top of the repo-path stack). Like the other callers that do +// work before switching, it checks for an in-flight operation *before* popping +// the stack, so a refused switch leaves the stack intact — otherwise the entry +// would be consumed and escape would no longer return to the parent once the +// operation finished. The caller must only call this when the stack is +// non-empty. +func (self *ReposHelper) SwitchToParentRepo() error { + if self.switchRefusedBecauseBusy() { + return nil + } + return self.switchTo(self.c.State().GetRepoPathStack().Pop(), self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT) } -// DispatchSwitchTo switches lazygit to the repository (or worktree) at the -// given path. It runs synchronously on the UI thread: the switch swaps -// gui.State (in resetState) and reassigns gui.git and the process cwd, all of -// which the UI thread also reads, so doing it here rather than on a worker -// avoids racing those reads. The heavy data loading is still dispatched -// asynchronously by the refresh that onNewRepo kicks off. func (self *ReposHelper) DispatchSwitchTo(path string, errMsg string, contextKey types.ContextKey) error { + if self.switchRefusedBecauseBusy() { + return nil + } + return self.switchTo(path, errMsg, contextKey) +} + +// switchRefusedBecauseBusy reports (and shows a toast) whether a repo switch +// must be refused because a foreground git operation is in flight. Switching +// reassigns gui.git and the process cwd, so switching mid-operation would run +// the operation's remaining git commands against the wrong repo. Callers that +// do work before the switch (creating a worktree, recording the repo-path +// stack) check this up front, so they don't do that work only to have the +// switch refused; the switch itself (switchTo) is then unguarded. +func (self *ReposHelper) switchRefusedBecauseBusy() bool { + if self.c.GocuiGui().Busy() { + self.c.ErrorToast(self.c.Tr.CantSwitchWhileOperationInProgress) + return true + } + return false +} + +// switchTo switches lazygit to the repository (or worktree) at the given path. +// It runs synchronously on the UI thread: the switch swaps gui.State (in +// resetState) and reassigns gui.git and the process cwd, all of which the UI +// thread also reads, so doing it here rather than on a worker avoids racing +// those reads. The heavy data loading is still dispatched asynchronously by the +// refresh that onNewRepo kicks off. +func (self *ReposHelper) switchTo(path string, errMsg string, contextKey types.ContextKey) error { env.UnsetGitLocationEnvVars() originalPath, err := os.Getwd() if err != nil { diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 2a189a752..abfd1c0f6 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -426,6 +426,13 @@ func (self *WorktreeHelper) promptForWorktreeLocation(dirName string, prompt str } func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts, contextKey types.ContextKey) error { + // Check now, before we create the worktree, rather than when we come to + // switch to it afterwards: by then this operation's own waiting-status + // spinner would make Busy() true and refuse our own switch. + if self.reposHelper.switchRefusedBecauseBusy() { + return nil + } + return self.c.WithWaitingStatus(self.c.Tr.AddingWorktree, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddWorktree) if err := self.c.Git().Worktree.New(opts); err != nil { @@ -434,9 +441,11 @@ func (self *WorktreeHelper) createWorktree(opts git_commands.NewWorktreeOpts, co // The switch swaps gui.State and must run on the UI thread, but // we're on a worker here (creating the worktree is git work), so - // dispatch it rather than calling it directly. + // dispatch it. It's unguarded (switchTo, not DispatchSwitchTo) + // because we checked above and creating the worktree is now + // complete, so switching to it is safe. self.c.OnUIThread(func() error { - return self.reposHelper.DispatchSwitchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) + return self.reposHelper.switchTo(opts.Path, self.c.Tr.ErrWorktreeMovedOrRemoved, contextKey) }) return nil }) diff --git a/pkg/gui/controllers/quit_actions.go b/pkg/gui/controllers/quit_actions.go index 40ad6f7e3..9a7082542 100644 --- a/pkg/gui/controllers/quit_actions.go +++ b/pkg/gui/controllers/quit_actions.go @@ -2,7 +2,6 @@ package controllers import ( "github.com/jesseduffield/lazygit/pkg/gocui" - "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" ) @@ -81,9 +80,8 @@ func (self *QuitActions) Escape() error { } } - repoPathStack := self.c.State().GetRepoPathStack() - if !repoPathStack.IsEmpty() { - return self.c.Helpers().Repos.DispatchSwitchToRepo(repoPathStack.Pop(), context.NO_CONTEXT) + if !self.c.State().GetRepoPathStack().IsEmpty() { + return self.c.Helpers().Repos.SwitchToParentRepo() } if self.c.UserConfig().QuitOnTopLevelReturn { diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 0ee0a9e86..69ea7012f 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -769,6 +769,7 @@ type TranslationSet struct { ErrStageDirWithInlineMergeConflicts string ErrRepositoryMovedOrDeleted string ErrWorktreeMovedOrRemoved string + CantSwitchWhileOperationInProgress string CommandLog string ToggleShowCommandLog string FocusCommandLog string @@ -1921,6 +1922,7 @@ func EnglishTranslationSet() *TranslationSet { ErrRepositoryMovedOrDeleted: "Cannot find repo. It might have been moved or deleted ¯\\_(ツ)_/¯", CommandLog: "Command log", ErrWorktreeMovedOrRemoved: "Cannot find worktree. It might have been moved or removed ¯\\_(ツ)_/¯", + CantSwitchWhileOperationInProgress: "Can't switch repositories while an operation is in progress", ToggleShowCommandLog: "Toggle show/hide command log", FocusCommandLog: "Focus command log", CommandLogHeader: "You can hide/focus this panel by pressing '%s'\n", From 5414daf492901464734e145430bd6325026f73c9 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 12:28:13 +0200 Subject: [PATCH 076/218] Exclude toast rendering from the busy query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A toast keeps a foreground spinner task alive for its whole lifetime (~2-4s): showing one calls renderAppStatus, whose OnWorker loop runs until the status string clears. With the repo-switch guard in place that made the guard's own "can't switch, operation in progress" toast keep Busy() true, so the next escape/switch was refused until the toast faded — you had to wait it out. Render toasts in the background, like view-buffer content: a toast is a transient notification, not lazygit driving an operation, so a switch during one is fine. A real operation that shows a toast still keeps its own foreground task busy independently. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/app_status_helper.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index bffd87866..90b87b3b8 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -34,7 +34,12 @@ func (self *AppStatusHelper) Toast(message string, kind types.ToastKind) { self.statusMgr().AddToastStatus(message, kind) - self.renderAppStatus(false) + // Render the toast in the background: it's a transient notification, not + // lazygit driving an operation, so it must not count towards being busy — + // otherwise a toast (e.g. the "can't switch, operation in progress" one) + // would itself block a repo switch until it faded. A real operation showing + // a toast still keeps its own foreground task busy independently. + self.renderAppStatus(true) } // A custom task for WithWaitingStatus calls; it wraps the original one and From bd6081d601389a4814b5c964b94a950b53b8b266 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 4 Jul 2026 21:18:38 +0200 Subject: [PATCH 077/218] Select the checked-out branch via a refresh intent, not off-thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Operations that check something out (checkout, create branch, move commits to a new branch, fetch-and-checkout) selected the newly checked-out branch by calling SelectFirstBranchAndFirstCommit() before the refresh and passing KeepBranchSelectionIndex so the refresh wouldn't override it. That set the selection directly, usually from a worker goroutine (WithWaitingStatus/WithInlineStatus). Now that the refresh's own selection write is bounced onto the UI thread, the two writes could land in either order, and under load the refresh's "restore the previously-selected branch" write would win — leaving the old branch selected instead of the new one (flaky move_commits_to_new_branch_from_base_branch). Replace it with declarative selection intents applied inside the refresh's own bounce, so the selection is set on the UI thread and atomically with the list write (no off-thread write, and no BLOCK_UI needed to avoid a flicker): - BranchSelection: SelectCheckedOutBranch selects the checked-out branch (top of the list). The default, KeepBranchSelectionByName, restores the previously-selected branch by name as before. This replaces the KeepBranchSelectionIndex bool. - CommitSelection: SelectHeadCommit (already existed) for the commit. - SelectTopReflogCommit selects the top reflog entry, since a checkout adds a new entry there (reflog/checkout relies on this). SelectFirstBranchAndFirstCommit is gone. The previously-selected branch is now read at the top of the branches bounce, before the list is overwritten, so that read moves onto the UI thread too. fetchAndCheckout's refresh changes from ASYNC to SYNC so its post-refresh focus switch can run in Then on the UI thread; SYNC keeps the inline fetch spinner spinning (only BLOCK_UI would freeze it). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/branches_controller.go | 8 +-- pkg/gui/controllers/helpers/refresh_helper.go | 59 +++++++++++++------ pkg/gui/controllers/helpers/refs_helper.go | 47 ++++++--------- pkg/gui/controllers/remotes_controller.go | 17 ++++-- pkg/gui/types/refresh.go | 31 ++++++++-- 5 files changed, 99 insertions(+), 63 deletions(-) diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index 131d19439..a5c55884b 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -599,11 +599,11 @@ func (self *BranchesController) createNewBranchWithName(newBranchName string) er return err } - self.c.Helpers().Refs.SelectFirstBranchAndFirstCommit() self.c.Refresh(types.RefreshOptions{ - Mode: types.ASYNC, - KeepBranchSelectionIndex: true, - CommitSelection: types.KeepCommitSelectionIndex, + Mode: types.ASYNC, + BranchSelection: types.SelectCheckedOutBranch, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, }) return nil } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index c0543d095..cb1856aa9 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -183,7 +183,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { branchesAndRemotesWg.Add(1) refresh("reflog and branches", func() { - self.refreshReflogAndBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, options.Background) + self.refreshReflogAndBranches(includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) branchesAndRemotesWg.Done() }) } else { @@ -192,10 +192,10 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // Not a recency sort, so branches doesn't depend on the reflog // being fresh; it runs concurrently with the reflog refresh // below and reads whatever's in the model, as it always has. - self.refreshBranches(includeWorktreesWithBranches, options.KeepBranchSelectionIndex, true, self.c.Model().ReflogCommits, options.Background) + self.refreshBranches(includeWorktreesWithBranches, options.BranchSelection, true, self.c.Model().ReflogCommits, options.Background) branchesAndRemotesWg.Done() }) - refresh("reflog", func() { _, _ = self.refreshReflogCommits(options.Background) }) + refresh("reflog", func() { _, _ = self.refreshReflogCommits(options.Background, options.SelectTopReflogCommit) }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one @@ -399,21 +399,21 @@ func getModeName(mode types.RefreshMode) string { // order gives the immediate (non-recency) load a lower branch-load sequence // than the async (recency) load, so the sequence guard in refreshBranches keeps // the recency-sorted result even if the two loads' bounces land out of order. -func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, background bool) { +func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, false, self.c.Model().ReflogCommits, background) + self.refreshBranches(refreshWorktrees, branchSelection, false, self.c.Model().ReflogCommits, background) self.onWorker(background, func(_ gocui.Task) error { - reflogCommits, _ := self.refreshReflogCommits(background) - self.refreshBranches(false, true, true, reflogCommits, background) + reflogCommits, _ := self.refreshReflogCommits(background, false) + self.refreshBranches(false, types.SelectCheckedOutBranch, true, reflogCommits, background) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) case types.COMPLETE: - reflogCommits, _ := self.refreshReflogCommits(background) - self.refreshBranches(refreshWorktrees, keepBranchSelectionIndex, true, reflogCommits, background) + reflogCommits, _ := self.refreshReflogCommits(background, selectTopReflogCommit) + self.refreshBranches(refreshWorktrees, branchSelection, true, reflogCommits, background) } } @@ -728,7 +728,7 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSelectionIndex bool, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) { +func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) { loadSeq := self.branchLoadSeq.Add(1) generation := self.c.State().GetRepoGeneration() @@ -754,8 +754,6 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele self.c.Log.Error(err) } - prevSelectedBranch := self.c.Contexts().Branches.GetSelected() - var worktrees []*models.Worktree if refreshWorktrees { worktrees = self.loadWorktrees() @@ -772,6 +770,11 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele } self.appliedBranchLoadSeq = loadSeq + // Read the currently-selected branch before overwriting the list, so we + // can restore it by name below. Reading it here in the bounce keeps it on + // the UI thread. + prevSelectedBranch := self.c.Contexts().Branches.GetSelected() + self.c.Model().Branches = branches // Rebuilding here (rather than on the worker) means the map is built from // the branches we just wrote, on the UI thread. @@ -782,14 +785,25 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele self.refreshView(self.c.Contexts().Worktrees, background) } - if !keepBranchSelectionIndex && prevSelectedBranch != nil { - self.searchHelper.ReApplyFilter(self.c.Contexts().Branches) + // Setting the selection here, in the same bounce that writes the list, + // keeps it on the UI thread and keeps the list and selection updating in + // the same frame. + switch branchSelection { + case types.KeepBranchSelectionByName: + if prevSelectedBranch != nil { + self.searchHelper.ReApplyFilter(self.c.Contexts().Branches) - _, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(), - func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name }) - if found { - self.c.Contexts().Branches.SetSelectedLineIdx(idx) + _, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(), + func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name }) + if found { + self.c.Contexts().Branches.SetSelectedLineIdx(idx) + } } + case types.SelectCheckedOutBranch: + // The checked-out branch is always at the top of the list. Setting + // the selection doesn't scroll the view, so also reset the origin. + self.c.Contexts().Branches.SetSelectedLineIdx(0) + self.c.Contexts().Branches.GetView().SetOriginY(0) } // Need to re-render the commits view because the visualization of local @@ -965,7 +979,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // refreshReflogCommits returns the (non-filtered) ReflogCommits it loaded, so // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. -func (self *RefreshHelper) refreshReflogCommits(background bool) ([]*models.Commit, error) { +func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry bool) ([]*models.Commit, error) { generation := self.c.State().GetRepoGeneration() // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception @@ -1008,6 +1022,13 @@ func (self *RefreshHelper) refreshReflogCommits(background bool) ([]*models.Comm self.onUIThreadUnlessRepoChanged(generation, background, func() error { model.ReflogCommits = reflogCommits model.FilteredReflogCommits = filteredReflogCommits + // Setting the selection here, in the same bounce that writes the list, + // keeps it on the UI thread and atomic with the list update. Setting the + // selection doesn't scroll the view, so also reset the origin. + if selectTopEntry { + self.c.Contexts().ReflogCommits.SetSelectedLineIdx(0) + self.c.Contexts().ReflogCommits.GetView().SetOriginY(0) + } return nil }) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index b90b9150b..8d5e8397c 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -31,15 +31,6 @@ func NewRefsHelper( } } -func (self *RefsHelper) SelectFirstBranchAndFirstCommit() { - self.c.Contexts().Branches.SetSelection(0) - self.c.Contexts().ReflogCommits.SetSelection(0) - self.c.Contexts().LocalCommits.SetSelection(0) - self.c.Contexts().Branches.GetView().SetOriginY(0) - self.c.Contexts().ReflogCommits.GetView().SetOriginY(0) - self.c.Contexts().LocalCommits.GetView().SetOriginY(0) -} - func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions) error { waitingStatus := options.WaitingStatus if waitingStatus == "" { @@ -49,8 +40,6 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions cmdOptions := git_commands.CheckoutOptions{Force: false, EnvVars: options.EnvVars} refresh := func() { - self.SelectFirstBranchAndFirstCommit() - // loading a heap of commits is slow so we limit them whenever doing a reset self.c.Contexts().LocalCommits.SetLimitCommits(true) @@ -67,10 +56,11 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions scope = append(scope, types.PULL_REQUESTS) } self.c.Refresh(types.RefreshOptions{ - Mode: types.BLOCK_UI, - Scope: scope, - KeepBranchSelectionIndex: true, - CommitSelection: types.KeepCommitSelectionIndex, + Mode: types.BLOCK_UI, + Scope: scope, + BranchSelection: types.SelectCheckedOutBranch, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, }) } @@ -375,12 +365,11 @@ func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggest self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) } - self.SelectFirstBranchAndFirstCommit() - self.c.Refresh(types.RefreshOptions{ - Mode: types.BLOCK_UI, - KeepBranchSelectionIndex: true, - CommitSelection: types.KeepCommitSelectionIndex, + Mode: types.BLOCK_UI, + BranchSelection: types.SelectCheckedOutBranch, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, }) } @@ -534,12 +523,11 @@ func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchNa } } - self.SelectFirstBranchAndFirstCommit() - self.c.Refresh(types.RefreshOptions{ - Mode: types.BLOCK_UI, - KeepBranchSelectionIndex: true, - CommitSelection: types.KeepCommitSelectionIndex, + Mode: types.BLOCK_UI, + BranchSelection: types.SelectCheckedOutBranch, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, }) return nil } @@ -576,12 +564,11 @@ func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName stri } } - self.SelectFirstBranchAndFirstCommit() - self.c.Refresh(types.RefreshOptions{ - Mode: types.BLOCK_UI, - KeepBranchSelectionIndex: true, - CommitSelection: types.KeepCommitSelectionIndex, + Mode: types.BLOCK_UI, + BranchSelection: types.SelectCheckedOutBranch, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, }) return nil } diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index e4f606ca3..8bd19ad81 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -376,10 +376,19 @@ func (self *RemotesController) fetchAndCheckout(remote *models.Remote, branchNam if branchName != "" { err = self.c.Git().Branch.New(branchName, remote.Name+"/"+branchName) if err == nil { - self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) - self.c.Helpers().Refs.SelectFirstBranchAndFirstCommit() - refreshOptions.KeepBranchSelectionIndex = true - refreshOptions.CommitSelection = types.KeepCommitSelectionIndex + // Branch.New checks the new branch out, so HEAD moves: refresh the + // reflog (and, via scope expansion, the commits) as well, and select + // the newly checked-out branch and its head commit. + refreshOptions.Scope = append(refreshOptions.Scope, types.REFLOG) + refreshOptions.BranchSelection = types.SelectCheckedOutBranch + refreshOptions.CommitSelection = types.SelectHeadCommit + refreshOptions.SelectTopReflogCommit = true + // Focus the branches panel on the UI thread once the refresh has + // selected the newly checked-out branch. + refreshOptions.Then = func() error { + self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) + return nil + } } } self.c.Refresh(refreshOptions) diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index 591aff5f3..f4041bb2e 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -55,22 +55,41 @@ const ( SelectHeadCommit ) +// BranchSelectionBehavior controls which local branch is selected after the +// branches list is reloaded by a refresh. +type BranchSelectionBehavior int + +const ( + // Keep the same branch selected by name, restoring it at its new position if + // the order changed. This is the right default whenever the list reloads + // underneath a selection the user hasn't deliberately changed. + KeepBranchSelectionByName BranchSelectionBehavior = iota + + // Select the checked-out branch (the one at the top of the list). Used after + // operations that check something out - checkout, creating a branch, moving + // commits to a new branch - so the newly checked-out ref ends up selected. + SelectCheckedOutBranch +) + type RefreshOptions struct { Then func() error Scope []RefreshableView // e.g. []RefreshableView{COMMITS, BRANCHES}. Leave empty to refresh everything Mode RefreshMode // one of SYNC (default), ASYNC, and BLOCK_UI - // Normally a refresh of the branches tries to keep the same branch selected - // (by name); this is usually important in case the order of branches - // changes. Passing true for KeepBranchSelectionIndex suppresses this and - // keeps the selection index the same. Useful after checking out a detached - // head, and selecting index 0. - KeepBranchSelectionIndex bool + // Controls which local branch is selected after the refresh. Defaults to + // KeepBranchSelectionByName. + BranchSelection BranchSelectionBehavior // Controls which local commit is selected after the refresh. Defaults to // KeepCommitSelectionByHash. CommitSelection CommitSelectionBehavior + // When true, select the top (most recent) reflog entry after the refresh. + // Used alongside SelectCheckedOutBranch by operations that check something + // out, since the checkout adds a new reflog entry at the top. Defaults to + // keeping the reflog selection where it is. + SelectTopReflogCommit bool + // When true, this refresh was initiated by a background routine rather than // by a user action. Every git command suppresses optional locks by default // so it can't contend for index.lock (see git_commands.OptionalLocksEnvVar); From 7c4d8045f9dbcab76c8f627d3c9735de56af37ed Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 5 Jul 2026 17:12:42 +0200 Subject: [PATCH 078/218] Clamp the commit-file tree selection when the tree is rebuilt CommitFileTreeViewModel embedded the low-level tree's SetTree, which rebuilds the node list without touching the cursor. So after a shrinking rebuild (e.g. moving a patch out into the index removes a file), the selection index could be left past the end of the tree. GetSelectedItems then indexes out of range and returns a nil node, which segfaults callers such as canEditFiles when the options map is rendered during layout. Override SetTree to ClampSelection after the rebuild. Unlike FileTreeViewModel we deliberately don't also re-find the selected node by path: that walk lands on the containing directory when a file is removed from a dir that then collapses, whereas keeping the clamped index lands on the sibling file (see discard_old_file_changes). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../filetree/commit_file_tree_view_model.go | 16 ++++++++ .../commit_file_tree_view_model_test.go | 40 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 pkg/gui/filetree/commit_file_tree_view_model_test.go diff --git a/pkg/gui/filetree/commit_file_tree_view_model.go b/pkg/gui/filetree/commit_file_tree_view_model.go index e33316788..a58f7d93e 100644 --- a/pkg/gui/filetree/commit_file_tree_view_model.go +++ b/pkg/gui/filetree/commit_file_tree_view_model.go @@ -142,6 +142,22 @@ func (self *CommitFileTreeViewModel) GetSelectedPath() string { return node.GetPath() } +// SetTree rebuilds the tree and clamps the selection so it stays in range. The +// embedded tree's SetTree only rebuilds the node list and doesn't touch the +// cursor, so after a shrinking rebuild (e.g. moving a patch out into the index) +// the selection index could be left past the end of the tree; GetSelectedItems +// would then return a nil node and crash callers such as canEditFiles when the +// options map is rendered during layout. +// +// Unlike FileTreeViewModel.SetTree we don't re-find the selected node by path +// afterwards: that walk lands on the containing directory when a file is removed +// from a dir that then collapses, whereas keeping the (clamped) index lands on +// the sibling file, which is what we want here. +func (self *CommitFileTreeViewModel) SetTree() { + self.ICommitFileTree.SetTree() + self.ClampSelection() +} + // duplicated from file_tree_view_model.go. Generics will help here func (self *CommitFileTreeViewModel) ToggleShowTree() { selectedNode := self.GetSelected() diff --git a/pkg/gui/filetree/commit_file_tree_view_model_test.go b/pkg/gui/filetree/commit_file_tree_view_model_test.go new file mode 100644 index 000000000..c8862f6f9 --- /dev/null +++ b/pkg/gui/filetree/commit_file_tree_view_model_test.go @@ -0,0 +1,40 @@ +package filetree + +import ( + "testing" + + "github.com/jesseduffield/lazygit/pkg/commands/models" + "github.com/jesseduffield/lazygit/pkg/common" + "github.com/stretchr/testify/assert" +) + +// When the tree shrinks under the selection - e.g. moving a patch out into the +// index removes a file - SetTree must keep the selection in range. Otherwise +// GetSelectedItems returns a nil node, which crashes callers such as +// canEditFiles when the options map is rendered during layout. +func TestCommitFileTreeViewModelSetTreeClampsSelectionOnShrink(t *testing.T) { + files := []*models.CommitFile{ + {Path: "file1"}, + {Path: "file2"}, + {Path: "file3"}, + } + viewModel := NewCommitFileTreeViewModel( + func() []*models.CommitFile { return files }, + common.NewDummyCommon(), + false, // flat list + ) + viewModel.SetTree() + viewModel.SetSelectedLineIdx(viewModel.Len() - 1) + + // The file under the cursor goes away and the tree shrinks. + files = []*models.CommitFile{{Path: "file1"}} + viewModel.SetTree() + + assert.Less(t, viewModel.GetSelectedLineIdx(), viewModel.Len()) + assert.NotNil(t, viewModel.GetSelected()) + items, _, _ := viewModel.GetSelectedItems() + assert.NotEmpty(t, items) + for _, item := range items { + assert.NotNil(t, item) + } +} From 23cfa9b070900dc0ca785a1e8f2254e6ce7ae602 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 5 Jul 2026 20:50:33 +0200 Subject: [PATCH 079/218] Also refresh branches and remotes when refreshing pull requests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pull-request fetch queries GitHub for the tracking branches' upstreams against the configured remotes. It therefore depends on the branches and remotes being up to date; a refresh that asks for pull requests but not for those (e.g. checking out a branch) would fetch against a stale branch/remote list — for instance missing the PR of the branch just checked out. Expand the scope so pull requests always co-refresh branches and remotes. This also sets up the next commit to hand the freshly-loaded branches and remotes straight to the fetch, instead of reading them back from the model (which, now that those writes are bounced onto the UI thread, would be stale on the worker). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index cb1856aa9..c23c01d80 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -131,6 +131,8 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // can move HEAD), so refresh commits + branches alongside // - submodules are refreshed as part of the files refresh // - merge conflicts are part of what the files refresh produces + // - pull requests are fetched for the tracking branches against the + // remotes, so refresh both alongside to fetch against fresh data if scopeSet.Includes(types.REFLOG) || scopeSet.Includes(types.BISECT_INFO) { scopeSet.Add(types.COMMITS, types.BRANCHES) } @@ -140,6 +142,9 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if scopeSet.Includes(types.FILES) { scopeSet.Add(types.MERGE_CONFLICTS) } + if scopeSet.Includes(types.PULL_REQUESTS) { + scopeSet.Add(types.BRANCHES, types.REMOTES) + } // Capture the refs snapshot now, before we start reading git's state // below, rather than after. This is important to guard against the race From f0ea537956e938c633345c3a45139388daef46fa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 5 Jul 2026 20:55:13 +0200 Subject: [PATCH 080/218] Fetch pull requests using the freshly-loaded branches and remotes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR fetch needs the current branches (for their upstreams) and remotes to know what to query. It read them from Model().Branches / Model().Remotes on its own worker, after waiting on branchesAndRemotesWg for the branches and remotes refreshes to finish. That wait no longer guarantees fresh data: those refreshes now write the model in a bounce onto the UI thread, and Done() fires before the bounce has been processed. So the fetch read the pre-refresh lists — most visibly, checking out a branch that has a PR wouldn't show that PR until the next refresh, because the fetch queried the old branch set. Have refreshBranches / refreshReflogAndBranches / refreshRemotes return what they loaded, stash it in locals in Refresh, and hand it to the fetch. The wait on branchesAndRemotesWg orders the fetch after both loads have stored their slices, so it fetches against exactly the branches and remotes that were just loaded, with no model read on the worker. The previous commit guarantees both are always in scope when pull requests are, so no fallback is needed. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 69 ++++++++++++------- 1 file changed, 46 insertions(+), 23 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index c23c01d80..5e15e17c1 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -175,6 +175,14 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { } branchesAndRemotesWg := sync.WaitGroup{} + // The pull-request fetch (below) needs the just-loaded branches and + // remotes. Their model writes are bounced onto the UI thread, so the + // fetch worker can't read them back from the model without racing (and + // would see the pre-refresh values); instead the branches and remotes + // loads stash what they loaded here, and the wait on + // branchesAndRemotesWg gives the fetch the happens-before to read them. + var loadedBranches []*models.Branch + var loadedRemotes []*models.Remote includeWorktreesWithBranches := false if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) { // whenever we change commits, we should update branches because the upstream/downstream @@ -188,7 +196,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { branchesAndRemotesWg.Add(1) refresh("reflog and branches", func() { - self.refreshReflogAndBranches(includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) + loadedBranches = self.refreshReflogAndBranches(includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) branchesAndRemotesWg.Done() }) } else { @@ -197,7 +205,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // Not a recency sort, so branches doesn't depend on the reflog // being fresh; it runs concurrently with the reflog refresh // below and reads whatever's in the model, as it always has. - self.refreshBranches(includeWorktreesWithBranches, options.BranchSelection, true, self.c.Model().ReflogCommits, options.Background) + loadedBranches = self.refreshBranches(includeWorktreesWithBranches, options.BranchSelection, true, self.c.Model().ReflogCommits, options.Background) branchesAndRemotesWg.Done() }) refresh("reflog", func() { _, _ = self.refreshReflogCommits(options.Background, options.SelectTopReflogCommit) }) @@ -237,7 +245,7 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if scopeSet.Includes(types.REMOTES) { branchesAndRemotesWg.Add(1) refresh("remotes", func() { - _ = self.refreshRemotes(options.Background) + loadedRemotes, _ = self.refreshRemotes(options.Background) branchesAndRemotesWg.Done() }) } @@ -245,7 +253,11 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { if scopeSet.Includes(types.PULL_REQUESTS) { refresh("pull requests", func() { branchesAndRemotesWg.Wait() - self.refreshGithubPullRequests(options.Background) + // Use the branches and remotes the loads above stashed, not + // Model().Branches/Remotes: those writes are bounced onto the + // UI thread and may not have landed on this worker yet. The + // wait above orders us after both loads have stashed theirs. + self.refreshGithubPullRequests(loadedBranches, loadedRemotes, options.Background) }) } @@ -404,10 +416,13 @@ func getModeName(mode types.RefreshMode) string { // order gives the immediate (non-recency) load a lower branch-load sequence // than the async (recency) load, so the sequence guard in refreshBranches keeps // the recency-sorted result even if the two loads' bounces land out of order. -func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) { +func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) []*models.Branch { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: - self.refreshBranches(refreshWorktrees, branchSelection, false, self.c.Model().ReflogCommits, background) + // Return the immediate (non-recency) load's branches; the recency-sorted + // reload below runs on its own worker after we return. Both hold the same + // set of branches, which is all the caller (the PR fetch) needs. + branches := self.refreshBranches(refreshWorktrees, branchSelection, false, self.c.Model().ReflogCommits, background) self.onWorker(background, func(_ gocui.Task) error { reflogCommits, _ := self.refreshReflogCommits(background, false) @@ -416,10 +431,14 @@ func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branc return nil }) + return branches + case types.COMPLETE: reflogCommits, _ := self.refreshReflogCommits(background, selectTopReflogCommit) - self.refreshBranches(refreshWorktrees, branchSelection, true, reflogCommits, background) + return self.refreshBranches(refreshWorktrees, branchSelection, true, reflogCommits, background) } + + return nil } func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior, background bool) { @@ -733,7 +752,7 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) { +func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) []*models.Branch { loadSeq := self.branchLoadSeq.Add(1) generation := self.c.State().GetRepoGeneration() @@ -820,6 +839,10 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelectio self.refreshView(self.c.Contexts().Branches, background) self.refreshStatus(background) + + // Return the freshly-loaded branches so the caller can hand them to the PR + // fetch without reading them back from the (bounce-written) model. + return branches } func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { @@ -1041,13 +1064,13 @@ func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry return reflogCommits, nil } -func (self *RefreshHelper) refreshRemotes(background bool) error { +func (self *RefreshHelper) refreshRemotes(background bool) ([]*models.Remote, error) { generation := self.c.State().GetRepoGeneration() prevSelectedRemote := self.c.Contexts().Remotes.GetSelected() remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() if err != nil { - return err + return nil, err } self.onUIThreadUnlessRepoChanged(generation, background, func() error { @@ -1075,7 +1098,7 @@ func (self *RefreshHelper) refreshRemotes(background bool) error { self.refreshView(self.c.Contexts().Remotes, background) self.refreshView(self.c.Contexts().RemoteBranches, background) - return nil + return remotes, nil } func (self *RefreshHelper) loadWorktrees() []*models.Worktree { @@ -1187,7 +1210,7 @@ func (self *RefreshHelper) refreshView(context types.Context, background bool) { }) } -func (self *RefreshHelper) refreshGithubPullRequests(background bool) { +func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, remotes []*models.Remote, background bool) { generation := self.c.State().GetRepoGeneration() clearPullRequests := func() { @@ -1198,7 +1221,7 @@ func (self *RefreshHelper) refreshGithubPullRequests(background bool) { }) } - githubRemotes := getAuthenticatedGithubRemotes(self.getGithubRemotes(), self.c.Git().GitHub.GetAuthToken) + githubRemotes := getAuthenticatedGithubRemotes(self.getGithubRemotes(remotes), self.c.Git().GitHub.GetAuthToken) if len(githubRemotes) == 0 { clearPullRequests() return @@ -1209,12 +1232,12 @@ func (self *RefreshHelper) refreshGithubPullRequests(background bool) { clearPullRequests() if !self.githubBaseRemotePromptDismissed[self.c.Git().RepoPaths.RepoPath()] { - self.promptForBaseGithubRepo(githubRemotes) + self.promptForBaseGithubRepo(githubRemotes, branches) } return } - self.setGithubPullRequests(baseInfo, background) + self.setGithubPullRequests(baseInfo, branches, background) } type githubRemoteInfo struct { @@ -1223,8 +1246,8 @@ type githubRemoteInfo struct { authToken string } -func (self *RefreshHelper) getGithubRemotes() []githubRemoteInfo { - return lo.FilterMap(self.c.Model().Remotes, func(remote *models.Remote, _ int) (githubRemoteInfo, bool) { +func (self *RefreshHelper) getGithubRemotes(remotes []*models.Remote) []githubRemoteInfo { + return lo.FilterMap(remotes, func(remote *models.Remote, _ int) (githubRemoteInfo, bool) { if len(remote.Urls) == 0 { return githubRemoteInfo{}, false } @@ -1285,7 +1308,7 @@ func getGithubBaseRemote(githubRemotes []githubRemoteInfo, configuredRemoteName return nil } -func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteInfo) { +func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteInfo, branches []*models.Branch) { menuItems := lo.Map(githubRemotes, func(info githubRemoteInfo, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{info.remote.Name, style.FgCyan.Sprint(info.serviceInfo.RepoName)}, @@ -1295,7 +1318,7 @@ func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteI self.c.Log.Error(err) } - self.setGithubPullRequests(&info, false) + self.setGithubPullRequests(&info, branches, false) return nil }) }, @@ -1323,17 +1346,17 @@ func (self *RefreshHelper) rebuildPullRequestsMap() { ) } -func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, background bool) { +func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, branches []*models.Branch, background bool) { generation := self.c.State().GetRepoGeneration() - if len(self.c.Model().Branches) == 0 { + if len(branches) == 0 { return } - branches := lo.Filter(self.c.Model().Branches, func(branch *models.Branch, _ int) bool { + trackingBranches := lo.Filter(branches, func(branch *models.Branch, _ int) bool { return branch.IsTrackingRemote() }) - branchNames := lo.Map(branches, func(branch *models.Branch, _ int) string { + branchNames := lo.Map(trackingBranches, func(branch *models.Branch, _ int) string { return branch.UpstreamBranch }) From 1def541acb476be744f7a2a54e501300a9cf9493 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 14:44:23 +0200 Subject: [PATCH 081/218] Add IsUIThread and OnUIThreadAndWait to gocui The next commits move refresh workers to read UI-thread-owned state (the model, contexts, selection) on the UI thread rather than off it. Two primitives support that: - OnUIThreadAndWait runs a function on the main event loop and blocks the caller until it has run, so a worker can read that state without racing. OnUIThreadAndWaitBackground is the same for background routines, whose work must not count towards the program being busy. - IsUIThread reports whether the caller is on the main event loop, for a debug-only assertion that a refresh was issued from the thread it claims. It records the main loop's goroutine id in MainLoop and compares via goid, so it's promoted from an indirect to a direct dependency. goid is used only by that debug assertion, never to drive production control flow. Co-Authored-By: Claude Opus 4.8 (1M context) --- go.mod | 2 +- pkg/gocui/gui.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 6820d941d..c10004176 100644 --- a/go.mod +++ b/go.mod @@ -25,6 +25,7 @@ require ( github.com/lucasb-eyer/go-colorful v1.4.0 github.com/mgutz/str v1.2.0 github.com/mitchellh/go-ps v1.0.0 + github.com/petermattis/goid v0.0.0-20250813065127-a731cc31b4fe github.com/rivo/uniseg v0.4.7 github.com/sahilm/fuzzy v0.1.3 github.com/samber/lo v1.53.0 @@ -62,7 +63,6 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/onsi/ginkgo v1.10.3 // indirect github.com/onsi/gomega v1.34.1 // indirect - github.com/petermattis/goid v0.0.0-20250813065127-a731cc31b4fe // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect golang.org/x/mod v0.35.0 // indirect diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index a13744997..6002ebf9c 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -9,11 +9,13 @@ import ( "runtime" "strings" "sync" + "sync/atomic" "time" "github.com/gdamore/tcell/v3" "github.com/go-errors/errors" "github.com/jesseduffield/generics/set" + "github.com/petermattis/goid" "github.com/rivo/uniseg" "github.com/samber/lo" ) @@ -200,6 +202,11 @@ type Gui struct { currentTask Task lastHoverView *View + + // uiThreadID is the goroutine id of the main event loop, recorded when + // MainLoop starts. IsUIThread compares against it. Written once, read from + // worker goroutines, so it's atomic. + uiThreadID atomic.Int64 } type NewGuiOpts struct { @@ -684,6 +691,46 @@ func (g *Gui) updateContentOnly(f func(*Gui) error, background bool) { g.userEvents <- userEvent{f: f, task: task, contentOnly: true} } +// IsUIThread reports whether the caller is running on the main event-loop +// goroutine (the one running MainLoop). It calls goid.Get, so use it only for +// debug assertions, not to drive production control flow. +func (g *Gui) IsUIThread() bool { + return goid.Get() == g.uiThreadID.Load() +} + +// OnUIThreadAndWait runs f on the main event-loop goroutine and blocks the +// caller until f has run, returning f's error. Use it to read UI-thread-owned +// state (the model, contexts) from a worker without racing the UI thread. +// +// It must be called from a worker goroutine, never from the UI thread itself: +// the UI thread would block waiting for a callback only it can run, which +// deadlocks. Callers arrange this by construction (see the refresh helper's +// RefreshFromWorker); a debug-only assertion there guards against getting it +// wrong. +func (g *Gui) OnUIThreadAndWait(f func() error) error { + return g.onUIThreadAndWait(f, false) +} + +// Like OnUIThreadAndWait, but the enqueued work belongs to a background routine, +// so it doesn't count towards the program being busy (see UpdateBackground). +func (g *Gui) OnUIThreadAndWaitBackground(f func() error) error { + return g.onUIThreadAndWait(f, true) +} + +func (g *Gui) onUIThreadAndWait(f func() error, background bool) error { + enqueue := g.Update + if background { + enqueue = g.UpdateBackground + } + + result := make(chan error, 1) + enqueue(func(*Gui) error { + result <- f() + return nil + }) + return <-result +} + // Calls a function in a goroutine. Handles panics gracefully and tracks // number of background tasks. // Always use this when you want to spawn a goroutine and you want lazygit to @@ -766,6 +813,8 @@ func (g *Gui) SetManagerFunc(manager func(*Gui) error) { // MainLoop runs the main loop until an error is returned. A successful // finish should return ErrQuit. func (g *Gui) MainLoop() error { + g.uiThreadID.Store(goid.Get()) + go func() { for { select { From 080542c9fb1e3eebbbcc1ea3fd5d8e6f064527db Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 14:45:03 +0200 Subject: [PATCH 082/218] Capture the commits refresh's inputs on the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A commits refresh does its git work on a worker and then reads the model, the contexts, and the modes for that work directly from there: LocalCommits.GetSelectionRangeAndMode/GetLimitCommits/GetShowWholeGitGraph, Model.Commits/MainBranches/HashPool, the filtering path/author. Those are owned by the UI thread, which is concurrently running the cursor and render code, so the reads race it — the dominant, confirmed source of the commits-scope flakes (the startup ClampSelection vs GetSelectionRangeAndMode race, for one). Gather them into an immutable capturedCommitState on the UI thread, before the git work is dispatched, and have refreshCommitsWithLimit compute from that snapshot. UI-thread callers capture inline; worker callers can't (a SYNC/BLOCK_UI refresh parks the UI thread at wg.Wait, so hopping from a scope sub-worker would deadlock), so the capture is lifted out of the scope worker into the refresh orchestration, and worker callers announce themselves with a new RefreshFromWorker entry point that hops the capture to the UI thread and blocks for it (OnUIThreadAndWait). BLOCK_UI runs the whole refresh on the UI thread regardless of the caller, so it captures inline too. Every refresh issued from a worker that reaches the commits (or branches, which pulls in commits) scope is converted: the fast-forward, branch/tag delete, worktree remove/detach, push, reword-via-rebase, author edits, custom-command, hard-reset-with-autostash, reset-to-ref, fetch-and-checkout, gpg-stream, post-fetch, and external-change-poller refreshes, plus the branch checkout and move-commits-to-new-branch refreshes. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/background.go | 2 +- pkg/gui/controllers/branches_controller.go | 4 +- .../controllers/helpers/branches_helper.go | 12 +- pkg/gui/controllers/helpers/gpg_helper.go | 4 +- pkg/gui/controllers/helpers/refresh_helper.go | 130 +++++++++++++++--- pkg/gui/controllers/helpers/refs_helper.go | 8 +- .../controllers/helpers/worktree_helper.go | 4 +- .../controllers/local_commits_controller.go | 8 +- pkg/gui/controllers/remotes_controller.go | 2 +- pkg/gui/controllers/sync_controller.go | 2 +- pkg/gui/controllers/tags_controller.go | 6 +- pkg/gui/controllers/undo_controller.go | 2 +- pkg/gui/gui_common.go | 4 + .../custom_commands/handler_creator.go | 2 +- pkg/gui/types/common.go | 6 + 15 files changed, 147 insertions(+), 49 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 6215f0d45..17f3677f6 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -184,7 +184,7 @@ func (self *BackgroundRoutineMgr) checkForExternalChanges() { // No need to update the stored snapshot here; Refresh does that. self.gui.c.Log.Info("External ref change detected — refreshing") - self.gui.c.Refresh(types.RefreshOptions{Background: true}) + self.gui.c.RefreshFromWorker(types.RefreshOptions{Background: true}) } // returns a channel that can be used to trigger the callback immediately diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index a5c55884b..9b9e9e546 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -734,7 +734,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { WorktreePath: worktreePath, }, ) - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC}) return err } @@ -743,7 +743,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { err := self.c.Git().Sync.FastForward( task, branch.Name, branch.UpstreamRemote, branch.UpstreamBranch, ) - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return err }) } diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 053804760..683d26db3 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -46,7 +46,7 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error } self.c.Contexts().Branches.CollapseRangeSelectionToTop() - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return nil }) }) @@ -84,7 +84,7 @@ func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteB if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) if resetRemoteBranchesSelection { self.c.Contexts().RemoteBranches.CollapseRangeSelectionToTop() } @@ -152,7 +152,7 @@ func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branc } self.c.Contexts().Branches.CollapseRangeSelectionToTop() - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }) }, @@ -312,7 +312,7 @@ func (self *BranchesHelper) deleteLocalBranchesContinuation(branches []*models.B } self.c.Contexts().Branches.CollapseRangeSelectionToTop() - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}, }) @@ -330,7 +330,7 @@ func (self *BranchesHelper) deleteLocalAndRemoteBranchesContinuation(branches [] } self.c.Contexts().Branches.CollapseRangeSelectionToTop() - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.REMOTES, types.FILES}, }) @@ -390,7 +390,7 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er // AutoForwardBranches reads Model.Branches, which the branches refresh writes // via a bounce, so it has to run in Then rather than right after Refresh // returns (where it would still see the previous branches). - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Scope: scope, Mode: types.SYNC, Background: background, diff --git a/pkg/gui/controllers/helpers/gpg_helper.go b/pkg/gui/controllers/helpers/gpg_helper.go index fb8fae628..fd74a400b 100644 --- a/pkg/gui/controllers/helpers/gpg_helper.go +++ b/pkg/gui/controllers/helpers/gpg_helper.go @@ -88,7 +88,7 @@ func (self *GpgHelper) runAndStream( ) error { return self.c.WithWaitingStatus(waitingStatus, func(gocui.Task) error { if err := cmdObj.StreamOutput().Run(); err != nil { - self.c.Refresh(failureRefreshOptions) + self.c.RefreshFromWorker(failureRefreshOptions) return fmt.Errorf( self.c.Tr.GitCommandFailed, self.c.UserConfig().Keybinding.Universal.ExtrasMenu, ) @@ -100,7 +100,7 @@ func (self *GpgHelper) runAndStream( } } - self.c.Refresh(successRefreshOptions) + self.c.RefreshFromWorker(successRefreshOptions) return nil }) } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 5e15e17c1..48a6b6db8 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -79,6 +79,17 @@ func NewRefreshHelper( } func (self *RefreshHelper) Refresh(options types.RefreshOptions) { + self.performRefresh(options, false) +} + +// RefreshFromWorker is Refresh for callers already running on a worker +// goroutine (e.g. inside a WithWaitingStatus handler) rather than the UI +// thread. See IGuiCommon.RefreshFromWorker. +func (self *RefreshHelper) RefreshFromWorker(options types.RefreshOptions) { + self.performRefresh(options, true) +} + +func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { if options.Mode == types.ASYNC && options.Then != nil { panic("RefreshOptions.Then doesn't work with mode ASYNC") } @@ -101,6 +112,13 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { ) } + // f runs on the UI thread when the refresh was initiated there, and also for + // BLOCK_UI, which dispatches f onto the UI thread regardless of the caller. + // Only a SYNC/ASYNC refresh initiated from a worker runs f on that worker. + // This, not calledFromWorker alone, is what decides whether a scope capture + // runs inline or has to hop (see captureOnUIThread). + fRunsOnUIThread := options.Mode == types.BLOCK_UI || !calledFromWorker + f := func() { var scopeSet *set.Set[types.RefreshableView] if len(options.Scope) == 0 { @@ -188,8 +206,16 @@ func (self *RefreshHelper) Refresh(options types.RefreshOptions) { // whenever we change commits, we should update branches because the upstream/downstream // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. + // Capture the commits refresh's model/context/mode inputs on the UI + // thread, before the git work is dispatched to a worker, so the + // worker computes from an immutable snapshot instead of reading + // state the UI thread concurrently mutates. + var capturedCommits capturedCommitState + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + capturedCommits = self.captureCommitsState(options.CommitSelection) + }) refresh("commits and commit files", func() { - self.refreshCommitsAndCommitFiles(options.CommitSelection, options.Background) + self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, options.Background) }) includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) @@ -441,11 +467,49 @@ func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branc return nil } -func (self *RefreshHelper) refreshCommitsAndCommitFiles(commitSelection types.CommitSelectionBehavior, background bool) { +// capturedCommitState holds everything the commits refresh reads from the +// model, contexts, and modes. It is gathered on the UI thread (see +// captureCommitsState) before the git work is dispatched to a worker, so the +// worker computes from an immutable snapshot rather than reading state the UI +// thread concurrently mutates. +type capturedCommitState struct { + selectionRange *localCommitSelectionRange + limitCommits bool + showWholeGitGraph bool + filterPath string + filterAuthor string + mainBranches *git_commands.MainBranches + hashPool *utils.StringPool + parentIsLocalCommits bool +} + +// captureCommitsState reads the commits refresh's model/context/mode inputs +// into an immutable snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureCommitsState(commitSelection types.CommitSelectionBehavior) capturedCommitState { + var selectionRange *localCommitSelectionRange + if commitSelection == types.KeepCommitSelectionByHash { + selectedIdx, rangeStartIdx, rangeSelectMode := self.c.Contexts().LocalCommits.GetSelectionRangeAndMode() + selectionRange = captureLocalCommitSelectionRange(self.c.Model().Commits, selectedIdx, rangeStartIdx, rangeSelectMode) + } + + parentCtx := self.c.Contexts().CommitFiles.GetParentContext() + + return capturedCommitState{ + selectionRange: selectionRange, + limitCommits: self.c.Contexts().LocalCommits.GetLimitCommits(), + showWholeGitGraph: self.c.Contexts().LocalCommits.GetShowWholeGitGraph(), + filterPath: self.c.Modes().Filtering.GetPath(), + filterAuthor: self.c.Modes().Filtering.GetAuthor(), + mainBranches: self.c.Model().MainBranches, + hashPool: self.c.Model().HashPool, + parentIsLocalCommits: parentCtx != nil && parentCtx.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY, + } +} + +func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, background bool) { generation := self.c.State().GetRepoGeneration() - _ = self.refreshCommitsWithLimit(commitSelection, background) - ctx := self.c.Contexts().CommitFiles.GetParentContext() - if ctx != nil && ctx.GetKey() == context.LOCAL_COMMITS_CONTEXT_KEY { + _ = self.refreshCommitsWithLimit(captured, commitSelection, background) + if captured.parentIsLocalCommits { // This makes sense when we've e.g. just amended a commit, meaning we get a new commit hash at the same position. // However if we've just added a brand new commit, it pushes the list down by one and so we would end up // showing the contents of a different commit than the one we initially entered. @@ -497,28 +561,22 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { return nil } -func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitSelectionBehavior, background bool) error { +func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, background bool) error { generation := self.c.State().GetRepoGeneration() - var selectionRange *localCommitSelectionRange - if commitSelection == types.KeepCommitSelectionByHash { - selectedIdx, rangeStartIdx, rangeSelectMode := self.c.Contexts().LocalCommits.GetSelectionRangeAndMode() - selectionRange = captureLocalCommitSelectionRange(self.c.Model().Commits, selectedIdx, rangeStartIdx, rangeSelectMode) - } - checkedOutRef := self.determineCheckedOutRef() refName, bisectInfo := self.refForLog() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ - Limit: self.c.Contexts().LocalCommits.GetLimitCommits(), - FilterPath: self.c.Modes().Filtering.GetPath(), - FilterAuthor: self.c.Modes().Filtering.GetAuthor(), + Limit: captured.limitCommits, + FilterPath: captured.filterPath, + FilterAuthor: captured.filterAuthor, IncludeRebaseCommits: true, RefName: refName, RefForPushedStatus: checkedOutRef, - All: self.c.Contexts().LocalCommits.GetShowWholeGitGraph(), - MainBranches: self.c.Model().MainBranches, - HashPool: self.c.Model().HashPool, + All: captured.showWholeGitGraph, + MainBranches: captured.mainBranches, + HashPool: captured.hashPool, }, ) if err != nil { @@ -545,10 +603,10 @@ func (self *RefreshHelper) refreshCommitsWithLimit(commitSelection types.CommitS scrollSelectionIntoView = true } case types.KeepCommitSelectionByHash: - if selectionRange != nil { - selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, selectionRange) + if captured.selectionRange != nil { + selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, captured.selectionRange) if found { - self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, selectionRange.mode) + self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, captured.selectionRange.mode) scrollSelectionIntoView = didMove } } @@ -898,6 +956,36 @@ func (self *RefreshHelper) onUIThread(background bool, f func() error) { } } +// captureOnUIThread runs fn on the UI thread and returns once it has run. fn +// reads the model/context/mode state a refresh scope needs into locals, so the +// worker that follows computes from an immutable snapshot instead of reading +// state the UI thread concurrently mutates. When the enclosing refresh function +// runs on the UI thread (fRunsOnUIThread is true) fn runs inline; when it runs +// on a worker, fn is dispatched to the UI thread and we block for it. +// +// The inline case matters for correctness as much as the hop: a SYNC or +// BLOCK_UI refresh parks the UI thread in a wg.Wait while its scope workers +// run, so a scope worker that tried to hop to the UI thread there would +// deadlock. Capturing before those workers are spawned — inline, on the UI +// thread — avoids that entirely. This is why BLOCK_UI (which always runs on the +// UI thread, even from a worker caller) captures inline rather than hopping. +func (self *RefreshHelper) captureOnUIThread(fRunsOnUIThread bool, background bool, fn func()) { + if fRunsOnUIThread { + fn() + return + } + + wrapped := func() error { + fn() + return nil + } + if background { + _ = self.c.GocuiGui().OnUIThreadAndWaitBackground(wrapped) + } else { + _ = self.c.GocuiGui().OnUIThreadAndWait(wrapped) + } +} + func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs []*models.SubmoduleConfig) error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel generation := self.c.State().GetRepoGeneration() diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 8d5e8397c..70ff18593 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -55,7 +55,7 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions if options.RefreshPullRequests { scope = append(scope, types.PULL_REQUESTS) } - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.BLOCK_UI, Scope: scope, BranchSelection: types.SelectCheckedOutBranch, @@ -204,7 +204,7 @@ func (self *RefsHelper) ResetToRef(ref string, strength string, envVars []string // loading a heap of commits is slow so we limit them whenever doing a reset self.c.Contexts().LocalCommits.SetLimitCommits(true) - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.BRANCHES, types.REFLOG, types.COMMITS}, CommitSelection: types.KeepCommitSelectionIndex}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.BRANCHES, types.REFLOG, types.COMMITS}, CommitSelection: types.KeepCommitSelectionIndex}) return nil } @@ -523,7 +523,7 @@ func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchNa } } - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.BLOCK_UI, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, @@ -564,7 +564,7 @@ func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName stri } } - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.BLOCK_UI, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index abfd1c0f6..980d810ae 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -163,7 +163,7 @@ func (self *WorktreeHelper) remove(worktree *models.Worktree, force bool, then f return then(task) } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) } @@ -181,7 +181,7 @@ func (self *WorktreeHelper) Detach(worktree *models.Worktree, then func(gocui.Ta return then(task) } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 5150e8fba..04c7fc290 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -487,7 +487,7 @@ func (self *LocalCommitsController) handleReword(summary string, description str if err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } @@ -854,7 +854,7 @@ func (self *LocalCommitsController) resetAuthor(start, end int) error { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } @@ -870,7 +870,7 @@ func (self *LocalCommitsController) setAuthor(start, end int) error { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) return nil }) }, @@ -889,7 +889,7 @@ func (self *LocalCommitsController) addCoAuthor(start, end int) error { if err := self.c.Git().Rebase.AddCommitCoAuthor(self.c.Model().Commits, start, end, value); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) return nil }) }, diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index 8bd19ad81..d4c838f7c 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -391,7 +391,7 @@ func (self *RemotesController) fetchAndCheckout(remote *models.Remote, branchNam } } } - self.c.Refresh(refreshOptions) + self.c.RefreshFromWorker(refreshOptions) return err }) } diff --git a/pkg/gui/controllers/sync_controller.go b/pkg/gui/controllers/sync_controller.go index 0f754eb49..fafd4e7dd 100644 --- a/pkg/gui/controllers/sync_controller.go +++ b/pkg/gui/controllers/sync_controller.go @@ -229,7 +229,7 @@ func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts) } return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC}) return nil }) } diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index fe2c4e80f..2a59af5ec 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -168,7 +168,7 @@ func (self *TagsController) localDelete(tag *models.Tag) error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag) err := self.c.Git().Tag.LocalDelete(tag.Name) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return err }) } @@ -210,7 +210,7 @@ func (self *TagsController) remoteDelete(tag *models.Tag) error { return err } self.c.Toast(self.c.Tr.RemoteTagDeletedMessage) - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, @@ -264,7 +264,7 @@ func (self *TagsController) localAndRemoteDelete(tag *models.Tag) error { if err := self.c.Git().Tag.LocalDelete(tag.Name); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, diff --git a/pkg/gui/controllers/undo_controller.go b/pkg/gui/controllers/undo_controller.go index 775e871a4..0954d66b0 100644 --- a/pkg/gui/controllers/undo_controller.go +++ b/pkg/gui/controllers/undo_controller.go @@ -271,7 +271,7 @@ func (self *UndoController) hardResetWithAutoStash(commitHash string, options ha if err != nil { return err } - self.c.Refresh(types.RefreshOptions{}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) } diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index d13120508..c8de7545d 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -30,6 +30,10 @@ func (self *guiCommon) Refresh(opts types.RefreshOptions) { self.gui.helpers.Refresh.Refresh(opts) } +func (self *guiCommon) RefreshFromWorker(opts types.RefreshOptions) { + self.gui.helpers.Refresh.RefreshFromWorker(opts) +} + func (self *guiCommon) PostRefreshUpdate(context types.Context) { self.gui.postRefreshUpdate(context) } diff --git a/pkg/gui/services/custom_commands/handler_creator.go b/pkg/gui/services/custom_commands/handler_creator.go index 1e321c2de..4eb762019 100644 --- a/pkg/gui/services/custom_commands/handler_creator.go +++ b/pkg/gui/services/custom_commands/handler_creator.go @@ -314,7 +314,7 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses } output, err := cmdObj.RunWithOutput() - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) if err != nil { if customCommand.After != nil && customCommand.After.CheckForConflicts { diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 766a5a757..0f8e99ee8 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -30,6 +30,12 @@ type IGuiCommon interface { LogCommand(cmdStr string, isCommandLine bool) // we call this when we want to refetch some models and render the result. Internally calls PostRefreshUpdate Refresh(RefreshOptions) + // Like Refresh, but for callers running on a worker goroutine (e.g. inside + // a WithWaitingStatus handler) rather than the UI thread. The refresh + // captures the model/context state it needs on the UI thread before doing + // its git work; knowing which thread the caller is on lets it capture + // inline (UI thread) or hop across (worker) without racing or deadlocking. + RefreshFromWorker(RefreshOptions) // we call this when we've changed something in the view model but not the actual model, // e.g. expanding or collapsing a folder in a file view. Calling 'Refresh' in this // case would be overkill, although refresh will internally call 'PostRefreshUpdate' From 558fd2c9d349b597932483c3b81c66a3c1c21281 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 14:46:32 +0200 Subject: [PATCH 083/218] Route merge/rebase result handling to the right refresh entry point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CheckMergeOrRebaseWithRefreshOptions refreshes after a merge/rebase step, and until now always via the UI-thread Refresh. Most of its callers are on a worker (the WithWaitingStatus/WithInlineStatus merge, squash-merge, rebase, pull, amend, drop, and patch-move handlers), so that refresh reads the commits scope off the UI thread — the race the previous commit addresses for everything else. Split it: the default is for worker callers and refreshes via RefreshFromWorker; a new CheckMergeOrRebaseWithRefreshOptionsFromUIThread is for the handlers that run the step synchronously on the UI thread (WithWaitingStatusSync, kept sync so rapid key presses batch): move up/down, revert, squash-fixups, cherry-pick paste, and patch-discard. The two share a private impl carrying which thread the caller is on, and the auto-skip recursion (genericMergeCommandImpl for an empty commit) threads it through so the follow-up step refreshes on the same thread. The merge-and-commit refresh in SquashMergeCommitted, also on a worker, moves to RefreshFromWorker to match. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/cherry_pick_helper.go | 2 +- .../helpers/merge_and_rebase_helper.go | 66 ++++++++++++++----- .../controllers/local_commits_controller.go | 8 +-- .../controllers/patch_building_controller.go | 2 +- 4 files changed, 56 insertions(+), 22 deletions(-) diff --git a/pkg/gui/controllers/helpers/cherry_pick_helper.go b/pkg/gui/controllers/helpers/cherry_pick_helper.go index e2fe46545..673f657f5 100644 --- a/pkg/gui/controllers/helpers/cherry_pick_helper.go +++ b/pkg/gui/controllers/helpers/cherry_pick_helper.go @@ -95,7 +95,7 @@ func (self *CherryPickHelper) Paste() error { cherryPickedCommits := self.getData().CherryPickedCommits result := self.c.Git().Rebase.CherryPickCommits(cherryPickedCommits) - err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.SYNC}) + err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{Mode: types.SYNC}) if err != nil { return result } diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 51488a922..6adf84712 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -79,7 +79,9 @@ func (self *MergeAndRebaseHelper) ContinueRebase() error { } func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { - return self.genericMergeCommandImpl(command, true) + // The menu/prompt/confirm handlers that reach here run on the UI thread and + // spin up a worker (via the waiting status below) to do the actual work. + return self.genericMergeCommandImpl(command, true, false) } // genericMergeCommandImpl runs a merge/rebase continue/skip/abort and handles @@ -87,10 +89,12 @@ func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { // non-subprocess path runs on a worker with a waiting status. // // showWaitingStatus is false only for the recursive auto-skip in -// CheckMergeOrRebaseWithRefreshOptions: that call already runs on the caller's -// thread (the worker of the enclosing waiting status, or the UI thread for the -// synchronous callers), so it must not spin up a second one. -func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWaitingStatus bool) error { +// checkMergeOrRebaseImpl: that call already runs on the caller's thread (the +// worker of the enclosing waiting status, or the UI thread for the synchronous +// callers), so it must not spin up a second one. calledFromWorker says which of +// those two the body runs on, so the post-action refresh picks Refresh vs +// RefreshFromWorker correctly. +func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWaitingStatus bool, calledFromWorker bool) error { status := self.c.Git().Status.WorkingTreeState() if status.None() { @@ -128,29 +132,30 @@ func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWa if needsSubprocess { // TODO: see if we should be calling more of the code from self.Git.Rebase.GenericMergeOrRebaseAction success, err := self.c.RunSubprocess(self.c.Git().Rebase.GenericMergeOrRebaseActionCmdObj(commandType, command)) - self.c.Refresh(types.RefreshOptions{ + self.refreshAfterMergeOrRebase(types.RefreshOptions{ Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(success && selectHeadCommitOnSuccess), - }) + }, calledFromWorker) self.RecordWhetherMergeOrRebaseStartedInLazygit() return err } - runAction := func() error { + runAction := func(calledFromWorker bool) error { result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) - return self.CheckMergeOrRebaseWithRefreshOptions(result, + return self.checkMergeOrRebaseImpl(result, types.RefreshOptions{ Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(result == nil && selectHeadCommitOnSuccess), - }) + }, calledFromWorker) } if showWaitingStatus { return self.c.WithWaitingStatus(status.Title(self.c.Tr), func(gocui.Task) error { - return runAction() + // The waiting status ran runAction on a worker. + return runAction(true) }) } - return runAction() + return runAction(calledFromWorker) } // commitSelectionAfterMerge maps whether a merge/rebase/pull created a new @@ -205,17 +210,34 @@ func (self *MergeAndRebaseHelper) RecordWhetherMergeOrRebaseStartedInLazygit() { self.c.Git().Status.WorkingTreeState().Any()) } +// CheckMergeOrRebaseWithRefreshOptions handles the result of a merge/rebase +// step and refreshes. It's for callers running on a worker (the +// WithWaitingStatus / WithInlineStatus handlers), which is the large majority; +// UI-thread callers use CheckMergeOrRebaseWithRefreshOptionsFromUIThread. func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result error, refreshOptions types.RefreshOptions) error { - self.c.Refresh(refreshOptions) + return self.checkMergeOrRebaseImpl(result, refreshOptions, true) +} + +// CheckMergeOrRebaseWithRefreshOptionsFromUIThread is like +// CheckMergeOrRebaseWithRefreshOptions, but for the callers that run the +// merge/rebase synchronously on the UI thread (the WithWaitingStatusSync +// move/revert/squash-fixups/cherry-pick-paste/patch-discard handlers, kept sync +// so rapid key presses batch) rather than on a worker. +func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result error, refreshOptions types.RefreshOptions) error { + return self.checkMergeOrRebaseImpl(result, refreshOptions, false) +} + +func (self *MergeAndRebaseHelper) checkMergeOrRebaseImpl(result error, refreshOptions types.RefreshOptions, calledFromWorker bool) error { + self.refreshAfterMergeOrRebase(refreshOptions, calledFromWorker) self.RecordWhetherMergeOrRebaseStartedInLazygit() if result == nil { return nil } else if strings.Contains(result.Error(), "No changes - did you forget to use") { - return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, calledFromWorker) } else if strings.Contains(result.Error(), "The previous cherry-pick is now empty") { - return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, calledFromWorker) } else if strings.Contains(result.Error(), "No rebase in progress?") { // assume in this case that we're already done return nil @@ -223,6 +245,18 @@ func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result er return self.CheckForConflicts(result) } +// refreshAfterMergeOrRebase issues the post-action refresh on the entry point +// that matches the thread the merge/rebase ran on: RefreshFromWorker for the +// worker callers, Refresh for the ones that stayed synchronously on the UI +// thread. +func (self *MergeAndRebaseHelper) refreshAfterMergeOrRebase(refreshOptions types.RefreshOptions, calledFromWorker bool) { + if calledFromWorker { + self.c.RefreshFromWorker(refreshOptions) + } else { + self.c.Refresh(refreshOptions) + } +} + func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { return self.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.ASYNC}) } @@ -628,7 +662,7 @@ func (self *MergeAndRebaseHelper) SquashMergeCommitted(refName, checkedOutBranch if err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) return nil }) } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 04c7fc290..12244d983 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -741,7 +741,7 @@ func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, s self.context().MoveSelection(1) self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) } - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( err, types.RefreshOptions{Mode: types.SYNC, CommitSelection: types.KeepCommitSelectionIndex}) }) } @@ -769,7 +769,7 @@ func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, sta self.context().MoveSelection(-1) self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) } - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( err, types.RefreshOptions{Mode: types.SYNC, CommitSelection: types.KeepCommitSelectionIndex}) }) } @@ -927,7 +927,7 @@ func (self *LocalCommitsController) revert(commits []*models.Commit, start, end } result := self.c.Git().Commit.Revert(hashes, isMerge) - if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.SYNC}); err != nil { + if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{Mode: types.SYNC}); err != nil { return err } @@ -1127,7 +1127,7 @@ func (self *LocalCommitsController) squashFixupsImpl(commit *models.Commit, reba self.c.LogAction(self.c.Tr.Actions.SquashAllAboveFixupCommits) err := self.c.Git().Rebase.SquashAllAboveFixupCommits(commit) self.context().MoveSelectedLine(-selectionOffset) - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( err, types.RefreshOptions{Mode: types.SYNC}) }) } diff --git a/pkg/gui/controllers/patch_building_controller.go b/pkg/gui/controllers/patch_building_controller.go index 5e4a17169..d596c2ead 100644 --- a/pkg/gui/controllers/patch_building_controller.go +++ b/pkg/gui/controllers/patch_building_controller.go @@ -228,7 +228,7 @@ func (self *PatchBuildingController) discardSelectionFromCommit() error { self.c.LogAction(self.c.Tr.Actions.RemovePatchFromCommit) err := self.c.Git().Patch.DeletePatchesFromCommit(self.c.Model().Commits, commitIndex) self.c.Helpers().PatchBuilding.Escape() - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( err, types.RefreshOptions{Mode: types.SYNC}) }) } From 988d04bda9983c6c8c6dfbb26e479315522e4e13 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 14:47:13 +0200 Subject: [PATCH 084/218] Assert a refresh uses the entry point matching its goroutine Now that every commits-reaching refresh issued from a worker goes through RefreshFromWorker, guard the choice: in debug builds, panic if a refresh was issued from the UI thread as RefreshFromWorker or from a worker as Refresh. The caller's own goroutine is recorded at the top of performRefresh, before a BLOCK_UI refresh dispatches onto the UI thread, so the check holds for every mode rather than being fooled by BLOCK_UI. It's scoped to the commits refresh for now, the only converted scope; once the rest are converted the guard can move up to cover every refresh unconditionally. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 48a6b6db8..1d8e17913 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -119,6 +119,15 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // runs inline or has to hop (see captureOnUIThread). fRunsOnUIThread := options.Mode == types.BLOCK_UI || !calledFromWorker + // Record the caller's own goroutine now, before a BLOCK_UI refresh dispatches + // f onto the UI thread, so the debug assertion below can verify the caller + // picked the entry point matching its thread regardless of the mode. Only + // read in debug (goid stays out of production control flow). + callerIsUIThread := false + if self.c.GetConfig().GetDebug() { + callerIsUIThread = self.c.GocuiGui().IsUIThread() + } + f := func() { var scopeSet *set.Set[types.RefreshableView] if len(options.Scope) == 0 { @@ -203,6 +212,18 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr var loadedRemotes []*models.Remote includeWorktreesWithBranches := false if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) { + // Debug-only guard: the caller must have picked the entry point that + // matches its goroutine — Refresh on the UI thread, RefreshFromWorker + // on a worker. We check the caller's own thread (captured above, + // before any BLOCK_UI dispatch), so it holds regardless of the mode. + // It's scoped to the commits refresh for now, the one scope whose + // worker reads have moved to the UI-thread capture below; once the + // other scopes are converted too it can move up to guard every + // refresh unconditionally. + if self.c.GetConfig().GetDebug() && callerIsUIThread == calledFromWorker { + panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") + } + // whenever we change commits, we should update branches because the upstream/downstream // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. From 56989922e434f213638104c76877394dbd3b387e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 15:43:01 +0200 Subject: [PATCH 085/218] Capture the remotes/sub-commits/commit-files/rebase-commits inputs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These four refreshes each read model, context, and mode state directly on their worker — the same class of race the commits refresh had: - remotes reads the selected remote (Contexts().Remotes.GetSelected), needed to keep the remote-branches selection valid; - sub-commits reads the SubCommits ref/limit/divergence, the filtering path/author, and Model.MainBranches/HashPool; - commit-files reads the diff endpoints (CommitFiles from/to and the diffing args); - rebase-commits reads Model.HashPool/Commits. Give each the same treatment as commits: gather its inputs into an immutable snapshot on the UI thread (via captureOnUIThread, inline for a UI-thread refresh, hopped for a worker one) before dispatching the git work, and have the refresh compute from the snapshot. The commit-files re-init inside the commits refresh captures its endpoints in the bounce, right after ReInit sets them, before dispatching to the worker. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 111 ++++++++++++++---- 1 file changed, 90 insertions(+), 21 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 1d8e17913..66912b877 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -260,16 +260,29 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one // if we've asked specifically for rebase commits and not those other things - refresh("rebase commits", func() { _ = self.refreshRebaseCommits(options.Background) }) + var rebaseHashPool *utils.StringPool + var rebaseCommits []*models.Commit + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + rebaseHashPool, rebaseCommits = self.captureRebaseCommitState() + }) + refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, options.Background) }) } if scopeSet.Includes(types.SUB_COMMITS) { - refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(options.Background) }) + var capturedSubCommits capturedSubCommitState + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + capturedSubCommits = self.captureSubCommitState() + }) + refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, options.Background) }) } // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { - refresh("commit files", func() { _ = self.refreshCommitFilesContext(options.Background) }) + var capturedCommitFiles capturedCommitFilesState + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + capturedCommitFiles = self.captureCommitFilesState() + }) + refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, options.Background) }) } fileWg := sync.WaitGroup{} @@ -290,9 +303,16 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.REMOTES) { + // Capture the previously-selected remote on the UI thread; the worker + // needs it to keep the remote-branches selection valid, and reading + // the Remotes context off the UI thread races its render. + var prevSelectedRemote *models.Remote + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + prevSelectedRemote = self.c.Contexts().Remotes.GetSelected() + }) branchesAndRemotesWg.Add(1) refresh("remotes", func() { - loadedRemotes, _ = self.refreshRemotes(options.Background) + loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, options.Background) branchesAndRemotesWg.Done() }) } @@ -546,8 +566,11 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS if commit != nil && commit.RefName() != "" { refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() self.c.Contexts().CommitFiles.ReInit(commit, refRange) + // Capture the diff endpoints here, on the UI thread and after + // ReInit has set them, before dispatching the git work. + capturedCommitFiles := self.captureCommitFilesState() self.onWorker(background, func(gocui.Task) error { - _ = self.refreshCommitFilesContext(background) + _ = self.refreshCommitFilesContext(capturedCommitFiles, background) return nil }) } @@ -726,8 +749,35 @@ func hasRestorableCommitHash(commits []*models.Commit, idx int) bool { return idx >= 0 && idx < len(commits) && commits[idx].Hash() != "" } -func (self *RefreshHelper) refreshSubCommitsWithLimit(background bool) error { - if self.c.Contexts().SubCommits.GetRef() == nil { +// capturedSubCommitState holds the sub-commits refresh's model/context/mode +// inputs, gathered on the UI thread (see captureSubCommitState) before the git +// work is dispatched to a worker. +type capturedSubCommitState struct { + ref models.Ref + limitCommits bool + refToShowDivergenceFrom string + filterPath string + filterAuthor string + mainBranches *git_commands.MainBranches + hashPool *utils.StringPool +} + +// captureSubCommitState reads the sub-commits refresh's inputs into an immutable +// snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureSubCommitState() capturedSubCommitState { + return capturedSubCommitState{ + ref: self.c.Contexts().SubCommits.GetRef(), + limitCommits: self.c.Contexts().SubCommits.GetLimitCommits(), + refToShowDivergenceFrom: self.c.Contexts().SubCommits.GetRefToShowDivergenceFrom(), + filterPath: self.c.Modes().Filtering.GetPath(), + filterAuthor: self.c.Modes().Filtering.GetAuthor(), + mainBranches: self.c.Model().MainBranches, + hashPool: self.c.Model().HashPool, + } +} + +func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommitState, background bool) error { + if captured.ref == nil { return nil } @@ -735,15 +785,15 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit(background bool) error { commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ - Limit: self.c.Contexts().SubCommits.GetLimitCommits(), - FilterPath: self.c.Modes().Filtering.GetPath(), - FilterAuthor: self.c.Modes().Filtering.GetAuthor(), + Limit: captured.limitCommits, + FilterPath: captured.filterPath, + FilterAuthor: captured.filterAuthor, IncludeRebaseCommits: false, - RefName: self.c.Contexts().SubCommits.GetRef().FullRefName(), - RefToShowDivergenceFrom: self.c.Contexts().SubCommits.GetRefToShowDivergenceFrom(), - RefForPushedStatus: self.c.Contexts().SubCommits.GetRef(), - MainBranches: self.c.Model().MainBranches, - HashPool: self.c.Model().HashPool, + RefName: captured.ref.FullRefName(), + RefToShowDivergenceFrom: captured.refToShowDivergenceFrom, + RefForPushedStatus: captured.ref, + MainBranches: captured.mainBranches, + HashPool: captured.hashPool, }, ) if err != nil { @@ -771,12 +821,26 @@ func (self *RefreshHelper) RefreshAuthors(commits []*models.Commit) { } } -func (self *RefreshHelper) refreshCommitFilesContext(background bool) error { +// capturedCommitFilesState holds the commit-files refresh's context/mode inputs +// (the diff endpoints), gathered on the UI thread before the git work runs. +type capturedCommitFilesState struct { + from string + to string + reverse bool +} + +// captureCommitFilesState reads the commit-files refresh's diff endpoints into +// an immutable snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureCommitFilesState() capturedCommitFilesState { from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) + return capturedCommitFilesState{from: from, to: to, reverse: reverse} +} + +func (self *RefreshHelper) refreshCommitFilesContext(captured capturedCommitFilesState, background bool) error { generation := self.c.State().GetRepoGeneration() - files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(from, to, reverse) + files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(captured.from, captured.to, captured.reverse) if err != nil { return err } @@ -789,10 +853,16 @@ func (self *RefreshHelper) refreshCommitFilesContext(background bool) error { return nil } -func (self *RefreshHelper) refreshRebaseCommits(background bool) error { +// captureRebaseCommitState reads the rebase-commits refresh's model inputs into +// an immutable snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureRebaseCommitState() (hashPool *utils.StringPool, commits []*models.Commit) { + return self.c.Model().HashPool, self.c.Model().Commits +} + +func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, commits []*models.Commit, background bool) error { generation := self.c.State().GetRepoGeneration() - updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(self.c.Model().HashPool, self.c.Model().Commits) + updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(hashPool, commits) if err != nil { return err } @@ -1173,9 +1243,8 @@ func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry return reflogCommits, nil } -func (self *RefreshHelper) refreshRemotes(background bool) ([]*models.Remote, error) { +func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, background bool) ([]*models.Remote, error) { generation := self.c.State().GetRepoGeneration() - prevSelectedRemote := self.c.Contexts().Remotes.GetSelected() remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() if err != nil { From 3e5c99e1e4580607292529c5314b12c716164176 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 16:19:30 +0200 Subject: [PATCH 086/218] Make the started-in-lazygit and startup-stage flags atomic GuiRepoState.mergeOrRebaseStartedInLazygit and StartupStage are plain fields, but they're written and read from worker goroutines: the former from both the files refresh and the merge/rebase result path (which runs on a worker for the async callers), the latter from the reflog/branches load as it transitions the startup stage. Those are data races. Make both atomic, like Branch.BehindBaseBranch. They're leaf flags, not mutexes guarding model or view state, so an atomic is the natural fit and keeps the merge/rebase result path out of this change. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/gui.go | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 5aa8beaec..d77673e9c 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -234,8 +234,11 @@ type GuiRepoState struct { SplitMainPanel bool - SearchState *types.SearchState - StartupStage types.StartupStage // Allows us to not load everything at once + SearchState *types.SearchState + // Lets us not load everything at once. Written and read from refresh + // workers (the reflog/branches load transitions it INITIAL->COMPLETE), so + // it's atomic. Holds a types.StartupStage. + startupStage atomic.Int32 ContextMgr *ContextMgr Contexts *context.ContextTree @@ -262,7 +265,11 @@ type GuiRepoState struct { // continue such an operation once its conflicts are resolved if we started // it ourselves; for an externally started one, popping up unbidden would be // confusing. Reset whenever we observe that no operation is in progress. - mergeOrRebaseStartedInLazygit bool + // + // Written from both the files refresh worker and the merge/rebase result + // path (which runs on a worker for the async callers), and read from the + // files refresh worker, so it's atomic. + mergeOrRebaseStartedInLazygit atomic.Bool } var _ types.IRepoStateAccessor = new(GuiRepoState) @@ -276,11 +283,11 @@ func (self *GuiRepoState) GetWindowViewNameMap() *utils.ThreadSafeMap[string, st } func (self *GuiRepoState) GetStartupStage() types.StartupStage { - return self.StartupStage + return types.StartupStage(self.startupStage.Load()) } func (self *GuiRepoState) SetStartupStage(value types.StartupStage) { - self.StartupStage = value + self.startupStage.Store(int32(value)) } func (self *GuiRepoState) GetCurrentPopupOpts() *types.CreatePopupPanelOpts { @@ -292,11 +299,11 @@ func (self *GuiRepoState) SetCurrentPopupOpts(value *types.CreatePopupPanelOpts) } func (self *GuiRepoState) GetMergeOrRebaseStartedInLazygit() bool { - return self.mergeOrRebaseStartedInLazygit + return self.mergeOrRebaseStartedInLazygit.Load() } func (self *GuiRepoState) SetMergeOrRebaseStartedInLazygit(value bool) { - self.mergeOrRebaseStartedInLazygit = value + self.mergeOrRebaseStartedInLazygit.Store(value) } func (self *GuiRepoState) GetScreenMode() types.ScreenMode { From fd6b20847acba3331d06a1a375ea38b57509f0e2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 16:19:42 +0200 Subject: [PATCH 087/218] Capture the files, reflog, branches and stash refresh inputs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The remaining refresh scopes each still read model, context, and mode state directly on their worker, racing the UI thread — the same class of race the commits refresh had: - files reads Model.Files (to detect resolved conflicts and drive the auto-stage) and the Files context's ForceShowUntracked; - reflog reads the existing reflog slices (for the incremental fetch), Model.HashPool and the filtering path/author; - branches reads Model.MainBranches and the previous branches (for the BehindBaseBranch carry-over); - stash reads the filtering path. Gather each scope's inputs into an immutable snapshot on the UI thread (via captureOnUIThread) before dispatching the git work, and have the refresh compute from the snapshot — for branches, threaded through both the immediate and the recency-sorted startup loads, which share one snapshot (the BehindBaseBranch carry-over is identical either way). Status, tags and worktrees read nothing UI-owned, so they're left alone. For the snapshots to actually run on the UI thread, the worker callers that reach these scopes must announce themselves: convert the submodule operations, the submodule stash-and-reset, and the background files poller to RefreshFromWorker. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/background.go | 2 +- pkg/gui/controllers/files_controller.go | 2 +- pkg/gui/controllers/helpers/refresh_helper.go | 141 ++++++++++++++---- pkg/gui/controllers/submodules_controller.go | 16 +- 4 files changed, 118 insertions(+), 43 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 17f3677f6..8633f4624 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -133,7 +133,7 @@ func (self *BackgroundRoutineMgr) startBackgroundFilesRefresh() { userConfig := self.gui.UserConfig() self.goEvery(userConfig.Refresher.RefreshIntervalDuration(), self.gui.stopChan, func(_ bool) error { - self.gui.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Background: true}) + self.gui.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Background: true}) return nil }) } diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index d7720ee34..fc35518e7 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -1808,7 +1808,7 @@ func (self *FilesController) ResetSubmodule(submodule *models.SubmoduleConfig) e return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES, types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES, types.SUBMODULES}}) return nil }) } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 66912b877..cbf388d0a 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -227,13 +227,17 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // whenever we change commits, we should update branches because the upstream/downstream // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. - // Capture the commits refresh's model/context/mode inputs on the UI - // thread, before the git work is dispatched to a worker, so the - // worker computes from an immutable snapshot instead of reading - // state the UI thread concurrently mutates. + // Capture the commits, reflog and branches refresh inputs (model, + // contexts, modes) on the UI thread, before the git work is dispatched + // to a worker, so the workers compute from an immutable snapshot + // instead of reading state the UI thread concurrently mutates. var capturedCommits capturedCommitState + var capturedReflog capturedReflogState + var capturedBranches capturedBranchState self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { capturedCommits = self.captureCommitsState(options.CommitSelection) + capturedReflog = self.captureReflogState() + capturedBranches = self.captureBranchState() }) refresh("commits and commit files", func() { self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, options.Background) @@ -243,7 +247,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { branchesAndRemotesWg.Add(1) refresh("reflog and branches", func() { - loadedBranches = self.refreshReflogAndBranches(includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) + loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) branchesAndRemotesWg.Done() }) } else { @@ -251,11 +255,13 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr refresh("branches", func() { // Not a recency sort, so branches doesn't depend on the reflog // being fresh; it runs concurrently with the reflog refresh - // below and reads whatever's in the model, as it always has. - loadedBranches = self.refreshBranches(includeWorktreesWithBranches, options.BranchSelection, true, self.c.Model().ReflogCommits, options.Background) + // below and uses the reflog we captured up front, as it always has. + loadedBranches = self.refreshBranches(capturedBranches, includeWorktreesWithBranches, options.BranchSelection, true, capturedReflog.reflogCommits, options.Background) branchesAndRemotesWg.Done() }) - refresh("reflog", func() { _, _ = self.refreshReflogCommits(options.Background, options.SelectTopReflogCommit) }) + refresh("reflog", func() { + _, _ = self.refreshReflogCommits(capturedReflog, options.Background, options.SelectTopReflogCommit) + }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { // the above block handles rebase commits so we only need to call this one @@ -287,15 +293,23 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr fileWg := sync.WaitGroup{} if scopeSet.Includes(types.FILES) { + var capturedFiles capturedFilesState + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + capturedFiles = self.captureFilesState() + }) fileWg.Add(1) refresh("files", func() { - _ = self.refreshFilesAndSubmodules(options.Background) + _ = self.refreshFilesAndSubmodules(capturedFiles, options.Background) fileWg.Done() }) } if scopeSet.Includes(types.STASH) { - refresh("stash", func() { self.refreshStashEntries(options.Background) }) + var stashFilterPath string + self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + stashFilterPath = self.c.Modes().Filtering.GetPath() + }) + refresh("stash", func() { self.refreshStashEntries(stashFilterPath, options.Background) }) } if scopeSet.Includes(types.TAGS) { @@ -483,17 +497,60 @@ func getModeName(mode types.RefreshMode) string { // order gives the immediate (non-recency) load a lower branch-load sequence // than the async (recency) load, so the sequence guard in refreshBranches keeps // the recency-sorted result even if the two loads' bounces land out of order. -func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) []*models.Branch { +// capturedReflogState holds the reflog refresh's model/mode inputs, gathered on +// the UI thread before the git work runs. The existing reflog slices feed the +// incremental fetch (we only load entries newer than the ones we already have). +type capturedReflogState struct { + reflogCommits []*models.Commit + filteredReflogCommits []*models.Commit + hashPool *utils.StringPool + filteringActive bool + filterPath string + filterAuthor string +} + +// captureReflogState reads the reflog refresh's inputs into an immutable +// snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureReflogState() capturedReflogState { + return capturedReflogState{ + reflogCommits: self.c.Model().ReflogCommits, + filteredReflogCommits: self.c.Model().FilteredReflogCommits, + hashPool: self.c.Model().HashPool, + filteringActive: self.c.Modes().Filtering.Active(), + filterPath: self.c.Modes().Filtering.GetPath(), + filterAuthor: self.c.Modes().Filtering.GetAuthor(), + } +} + +// capturedBranchState holds the branches refresh's model inputs, gathered on the +// UI thread before the git work runs. oldBranches is used only to carry over the +// previous BehindBaseBranch values (to reduce flicker) — an atomic each, so a +// pre-refresh snapshot serves both the immediate and recency loads identically. +type capturedBranchState struct { + mainBranches *git_commands.MainBranches + oldBranches []*models.Branch +} + +// captureBranchState reads the branches refresh's model inputs into an immutable +// snapshot. It must run on the UI thread. +func (self *RefreshHelper) captureBranchState() capturedBranchState { + return capturedBranchState{ + mainBranches: self.c.Model().MainBranches, + oldBranches: self.c.Model().Branches, + } +} + +func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflogState, capturedBranches capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) []*models.Branch { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: // Return the immediate (non-recency) load's branches; the recency-sorted // reload below runs on its own worker after we return. Both hold the same // set of branches, which is all the caller (the PR fetch) needs. - branches := self.refreshBranches(refreshWorktrees, branchSelection, false, self.c.Model().ReflogCommits, background) + branches := self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, false, capturedReflog.reflogCommits, background) self.onWorker(background, func(_ gocui.Task) error { - reflogCommits, _ := self.refreshReflogCommits(background, false) - self.refreshBranches(false, types.SelectCheckedOutBranch, true, reflogCommits, background) + reflogCommits, _ := self.refreshReflogCommits(capturedReflog, background, false) + self.refreshBranches(capturedBranches, false, types.SelectCheckedOutBranch, true, reflogCommits, background) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) @@ -501,8 +558,8 @@ func (self *RefreshHelper) refreshReflogAndBranches(refreshWorktrees bool, branc return branches case types.COMPLETE: - reflogCommits, _ := self.refreshReflogCommits(background, selectTopReflogCommit) - return self.refreshBranches(refreshWorktrees, branchSelection, true, reflogCommits, background) + reflogCommits, _ := self.refreshReflogCommits(capturedReflog, background, selectTopReflogCommit) + return self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, true, reflogCommits, background) } return nil @@ -901,15 +958,15 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) []*models.Branch { +func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) []*models.Branch { loadSeq := self.branchLoadSeq.Add(1) generation := self.c.State().GetRepoGeneration() branches, err := self.c.Git().Loaders.BranchLoader.Load( reflogCommits, - self.c.Model().MainBranches, - self.c.Model().Branches, + captured.mainBranches, + captured.oldBranches, loadBehindCounts, func(f func() error) { self.onWorker(background, func(_ gocui.Task) error { @@ -994,13 +1051,13 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, branchSelectio return branches } -func (self *RefreshHelper) refreshFilesAndSubmodules(background bool) error { +func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState, background bool) error { configs, err := self.refreshStateSubmoduleConfigs() if err != nil { return err } - if err := self.refreshStateFiles(background, configs); err != nil { + if err := self.refreshStateFiles(captured, background, configs); err != nil { return err } @@ -1077,7 +1134,25 @@ func (self *RefreshHelper) captureOnUIThread(fRunsOnUIThread bool, background bo } } -func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs []*models.SubmoduleConfig) error { +// capturedFilesState holds the files refresh's context/model inputs, gathered +// on the UI thread before the git work runs: the previous files list (to detect +// resolved conflicts and drive the auto-stage), and whether untracked files are +// force-shown. +type capturedFilesState struct { + prevFiles []*models.File + forceShowUntracked bool +} + +// captureFilesState reads the files refresh's inputs into an immutable snapshot. +// It must run on the UI thread. +func (self *RefreshHelper) captureFilesState() capturedFilesState { + return capturedFilesState{ + prevFiles: self.c.Model().Files, + forceShowUntracked: self.c.Contexts().Files.ForceShowUntracked(), + } +} + +func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, background bool, submoduleConfigs []*models.SubmoduleConfig) error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel generation := self.c.State().GetRepoGeneration() @@ -1091,7 +1166,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // Although this also means that at startup we won't be staging anything until // we call git status again. pathsToStage := []string{} - for _, file := range self.c.Model().Files { + for _, file := range captured.prevFiles { if file.HasMergeConflicts { prevConflictFileCount++ } @@ -1115,7 +1190,7 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ files := self.c.Git().Loaders.FileLoader. GetStatusFiles(git_commands.GetStatusFileOptions{ - ForceShowUntracked: self.c.Contexts().Files.ForceShowUntracked(), + ForceShowUntracked: captured.forceShowUntracked, Background: background, }) @@ -1186,15 +1261,15 @@ func (self *RefreshHelper) refreshStateFiles(background bool, submoduleConfigs [ // refreshReflogCommits returns the (non-filtered) ReflogCommits it loaded, so // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. -func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry bool) ([]*models.Commit, error) { +func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, background bool, selectTopEntry bool) ([]*models.Commit, error) { generation := self.c.State().GetRepoGeneration() // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception model := self.c.Model() // load does the git work on the worker and returns the new value for a - // reflog slice, reading the existing slice for the incremental fetch. The - // caller writes the result in the bounce. + // reflog slice, reading the existing slice (captured on the UI thread) for + // the incremental fetch. The caller writes the result in the bounce. load := func(existing []*models.Commit, filterPath string, filterAuthor string) ([]*models.Commit, error) { var lastReflogCommit *models.Commit if filterPath == "" && filterAuthor == "" && len(existing) > 0 { @@ -1202,7 +1277,7 @@ func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry } commits, onlyObtainedNewReflogCommits, err := self.c.Git().Loaders.ReflogCommitLoader. - GetReflogCommits(model.HashPool, lastReflogCommit, filterPath, filterAuthor) + GetReflogCommits(captured.hashPool, lastReflogCommit, filterPath, filterAuthor) if err != nil { return nil, err } @@ -1213,14 +1288,14 @@ func (self *RefreshHelper) refreshReflogCommits(background bool, selectTopEntry return commits, nil } - reflogCommits, err := load(model.ReflogCommits, "", "") + reflogCommits, err := load(captured.reflogCommits, "", "") if err != nil { return nil, err } filteredReflogCommits := reflogCommits - if self.c.Modes().Filtering.Active() { - filteredReflogCommits, err = load(model.FilteredReflogCommits, self.c.Modes().Filtering.GetPath(), self.c.Modes().Filtering.GetAuthor()) + if captured.filteringActive { + filteredReflogCommits, err = load(captured.filteredReflogCommits, captured.filterPath, captured.filterAuthor) if err != nil { return nil, err } @@ -1304,11 +1379,11 @@ func (self *RefreshHelper) refreshWorktrees(background bool) { self.refreshView(self.c.Contexts().Worktrees, background) } -func (self *RefreshHelper) refreshStashEntries(background bool) { +func (self *RefreshHelper) refreshStashEntries(filterPath string, background bool) { generation := self.c.State().GetRepoGeneration() stashEntries := self.c.Git().Loaders.StashLoader. - GetStashEntries(self.c.Modes().Filtering.GetPath()) + GetStashEntries(filterPath) self.onUIThreadUnlessRepoChanged(generation, background, func() error { self.c.Model().StashEntries = stashEntries diff --git a/pkg/gui/controllers/submodules_controller.go b/pkg/gui/controllers/submodules_controller.go index 97b7ff3dd..a2dd22ed3 100644 --- a/pkg/gui/controllers/submodules_controller.go +++ b/pkg/gui/controllers/submodules_controller.go @@ -164,7 +164,7 @@ func (self *SubmodulesController) add() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -193,7 +193,7 @@ func (self *SubmodulesController) editURL(submodule *models.SubmoduleConfig) err return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -210,7 +210,7 @@ func (self *SubmodulesController) init(submodule *models.SubmoduleConfig) error return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) } @@ -229,7 +229,7 @@ func (self *SubmodulesController) openBulkActionsMenu() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -244,7 +244,7 @@ func (self *SubmodulesController) openBulkActionsMenu() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -259,7 +259,7 @@ func (self *SubmodulesController) openBulkActionsMenu() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -274,7 +274,7 @@ func (self *SubmodulesController) openBulkActionsMenu() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) }, @@ -292,7 +292,7 @@ func (self *SubmodulesController) update(submodule *models.SubmoduleConfig) erro return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.SUBMODULES}}) return nil }) } From 5162a768eb4c23531acbdf89d0519f6918060d9d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 16:20:11 +0200 Subject: [PATCH 088/218] Guard every refresh's entry point, not just the commits scope With every scope's worker reads now captured on the UI thread and every worker caller on RefreshFromWorker, the debug entry-point assertion no longer needs to be scoped to the commits refresh. Move it to the top of performRefresh so it guards every refresh regardless of which scopes it touches, and drop the per-scope gate. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 26 +++++-------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index cbf388d0a..65870ca20 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -119,13 +119,13 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // runs inline or has to hop (see captureOnUIThread). fRunsOnUIThread := options.Mode == types.BLOCK_UI || !calledFromWorker - // Record the caller's own goroutine now, before a BLOCK_UI refresh dispatches - // f onto the UI thread, so the debug assertion below can verify the caller - // picked the entry point matching its thread regardless of the mode. Only - // read in debug (goid stays out of production control flow). - callerIsUIThread := false - if self.c.GetConfig().GetDebug() { - callerIsUIThread = self.c.GocuiGui().IsUIThread() + // Debug-only guard: every refresh must be issued from the entry point that + // matches its goroutine — Refresh on the UI thread, RefreshFromWorker on a + // worker. We check the caller's own goroutine here, before a BLOCK_UI + // refresh dispatches f onto the UI thread, so it holds regardless of the + // mode. goid stays out of production control flow (debug only). + if self.c.GetConfig().GetDebug() && self.c.GocuiGui().IsUIThread() == calledFromWorker { + panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") } f := func() { @@ -212,18 +212,6 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr var loadedRemotes []*models.Remote includeWorktreesWithBranches := false if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) { - // Debug-only guard: the caller must have picked the entry point that - // matches its goroutine — Refresh on the UI thread, RefreshFromWorker - // on a worker. We check the caller's own thread (captured above, - // before any BLOCK_UI dispatch), so it holds regardless of the mode. - // It's scoped to the commits refresh for now, the one scope whose - // worker reads have moved to the UI-thread capture below; once the - // other scopes are converted too it can move up to guard every - // refresh unconditionally. - if self.c.GetConfig().GetDebug() && callerIsUIThread == calledFromWorker { - panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") - } - // whenever we change commits, we should update branches because the upstream/downstream // counts can change. Whenever we change branches we should also change commits // e.g. in the case of switching branches. From eb95ae15f39bcee6a57c36f876d689e355cbca73 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 17:22:38 +0200 Subject: [PATCH 089/218] Capture the custom-patch handlers' commit reads on the UI thread These handlers dispatch their rebase to a worker via WithWaitingStatus but read Model().Commits (and, for move-to-selected-commit, the selected line index) from inside that worker, racing the UI thread's model writes. Read them on the UI thread before dispatching and close over the results. getPatchCommitIndex stays as-is: moving its call out of the worker makes its own Model().Commits read UI-thread-bound too, so the identical copy in patch_building_controller.go needs no matching signature change. The two pull-patch-into-new-commit handlers still push a context and close the commit-message panel from the worker; those writes are a separate concern, left for a follow-up. --- .../custom_patch_options_menu_action.go | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/pkg/gui/controllers/custom_patch_options_menu_action.go b/pkg/gui/controllers/custom_patch_options_menu_action.go index cabba4739..20e36833e 100644 --- a/pkg/gui/controllers/custom_patch_options_menu_action.go +++ b/pkg/gui/controllers/custom_patch_options_menu_action.go @@ -132,10 +132,11 @@ func (self *CustomPatchOptionsMenuAction) returnFocusFromPatchExplorerIfNecessar func (self *CustomPatchOptionsMenuAction) handleDeletePatchFromCommit() error { self.returnFocusFromPatchExplorerIfNecessary() + commits := self.c.Model().Commits + commitIndex := self.getPatchCommitIndex() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { - commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.RemovePatchFromCommit) - err := self.c.Git().Patch.DeletePatchesFromCommit(self.c.Model().Commits, commitIndex) + err := self.c.Git().Patch.DeletePatchesFromCommit(commits, commitIndex) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) } @@ -143,10 +144,12 @@ func (self *CustomPatchOptionsMenuAction) handleDeletePatchFromCommit() error { func (self *CustomPatchOptionsMenuAction) handleMovePatchToSelectedCommit() error { self.returnFocusFromPatchExplorerIfNecessary() + commits := self.c.Model().Commits + commitIndex := self.getPatchCommitIndex() + toCommitIndex := self.c.Contexts().LocalCommits.GetSelectedLineIdx() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { - commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.MovePatchToSelectedCommit) - err := self.c.Git().Patch.MovePatchToSelectedCommit(self.c.Model().Commits, commitIndex, self.c.Contexts().LocalCommits.GetSelectedLineIdx()) + err := self.c.Git().Patch.MovePatchToSelectedCommit(commits, commitIndex, toCommitIndex) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) } @@ -159,10 +162,11 @@ func (self *CustomPatchOptionsMenuAction) handleMovePatchIntoWorkingTree() error Title: self.c.Tr.MustStashTitle, Prompt: self.c.Tr.MustStashWarning, HandleConfirm: func() error { + commits := self.c.Model().Commits + commitIndex := self.getPatchCommitIndex() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { - commitIndex := self.getPatchCommitIndex() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoIndex) - err := self.c.Git().Patch.MovePatchIntoIndex(self.c.Model().Commits, commitIndex, mustStash) + err := self.c.Git().Patch.MovePatchIntoIndex(commits, commitIndex, mustStash) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) }, @@ -183,10 +187,11 @@ func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error { DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: false, OnConfirm: func(summary string, description string) error { + commits := self.c.Model().Commits return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) - err := self.c.Git().Patch.PullPatchIntoNewCommit(self.c.Model().Commits, commitIndex, summary, description) + err := self.c.Git().Patch.PullPatchIntoNewCommit(commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } @@ -214,10 +219,11 @@ func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommitBefore() e DescriptionTitle: self.c.Tr.CommitDescriptionTitle, PreserveMessage: false, OnConfirm: func(summary string, description string) error { + commits := self.c.Model().Commits return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) - err := self.c.Git().Patch.PullPatchIntoNewCommitBefore(self.c.Model().Commits, commitIndex, summary, description) + err := self.c.Git().Patch.PullPatchIntoNewCommitBefore(commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } From b4a976834f9672bdf2bd2da0a7496d8851846efa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 17:24:32 +0200 Subject: [PATCH 090/218] Capture reword/amend/author commit reads on the UI thread handleReword, amendTo, and the reset/set/add-co-author handlers pass Model().Commits (and the selected line index) to a git rebase from inside the WithWaitingStatus worker, racing the UI thread's model writes. Read them on the UI thread before dispatching. The author handlers index the full commit list by absolute start/end, so the range sub-slice withItemsRange hands amendAttribute is not what they need; capture the full Model().Commits there and thread it through. --- .../controllers/local_commits_controller.go | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 12244d983..595918fb2 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -475,7 +475,9 @@ func (self *LocalCommitsController) switchFromCommitMessagePanelToEditor(filepat } func (self *LocalCommitsController) handleReword(summary string, description string) error { - if models.IsHeadCommit(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx()) { + commits := self.c.Model().Commits + selectedIdx := self.c.Contexts().LocalCommits.GetSelectedLineIdx() + if models.IsHeadCommit(commits, selectedIdx) { // we've selected the top commit so no rebase is required return self.c.Helpers().GPG.WithGpgHandling(self.c.Git().Commit.RewordLastCommit(summary, description), git_commands.CommitGpgSign, @@ -483,7 +485,7 @@ func (self *LocalCommitsController) handleReword(summary string, description str } return self.c.WithWaitingStatus(self.c.Tr.RewordingStatus, func(gocui.Task) error { - err := self.c.Git().Rebase.RewordCommit(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx(), summary, description) + err := self.c.Git().Rebase.RewordCommit(commits, selectedIdx, summary, description) if err != nil { return err } @@ -788,11 +790,13 @@ func (self *LocalCommitsController) amendTo(commit *models.Commit) error { }) } } else { + commits := self.c.Model().Commits + selectedIdx := self.context().GetView().SelectedLineIdx() handleCommit = func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AmendCommit) - err := self.c.Git().Rebase.AmendTo(self.c.Model().Commits, self.context().GetView().SelectedLineIdx()) + err := self.c.Git().Rebase.AmendTo(commits, selectedIdx) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) }) }) @@ -820,26 +824,30 @@ func (self *LocalCommitsController) canAmend(_ *models.Commit) *types.DisabledRe return self.canAmendRange(self.c.Model().Commits, idx, idx) } -func (self *LocalCommitsController) amendAttribute(commits []*models.Commit, start, end int) error { +func (self *LocalCommitsController) amendAttribute(_ []*models.Commit, start, end int) error { + // The author operations index into the full commit list by absolute + // start/end, so capture that here on the UI thread rather than reading + // Model().Commits from the worker the menu items dispatch to. + commits := self.c.Model().Commits opts := self.c.KeybindingsOpts() return self.c.Menu(types.CreateMenuOptions{ Title: "Amend commit attribute", Items: []*types.MenuItem{ { Label: self.c.Tr.ResetAuthor, - OnPress: func() error { return self.resetAuthor(start, end) }, + OnPress: func() error { return self.resetAuthor(commits, start, end) }, Keys: opts.GetKeys(opts.Config.AmendAttribute.ResetAuthor), Tooltip: self.c.Tr.ResetAuthorTooltip, }, { Label: self.c.Tr.SetAuthor, - OnPress: func() error { return self.setAuthor(start, end) }, + OnPress: func() error { return self.setAuthor(commits, start, end) }, Keys: opts.GetKeys(opts.Config.AmendAttribute.SetAuthor), Tooltip: self.c.Tr.SetAuthorTooltip, }, { Label: self.c.Tr.AddCoAuthor, - OnPress: func() error { return self.addCoAuthor(start, end) }, + OnPress: func() error { return self.addCoAuthor(commits, start, end) }, Keys: opts.GetKeys(opts.Config.AmendAttribute.AddCoAuthor), Tooltip: self.c.Tr.AddCoAuthorTooltip, }, @@ -847,10 +855,10 @@ func (self *LocalCommitsController) amendAttribute(commits []*models.Commit, sta }) } -func (self *LocalCommitsController) resetAuthor(start, end int) error { +func (self *LocalCommitsController) resetAuthor(commits []*models.Commit, start, end int) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.ResetCommitAuthor) - if err := self.c.Git().Rebase.ResetCommitAuthor(self.c.Model().Commits, start, end); err != nil { + if err := self.c.Git().Rebase.ResetCommitAuthor(commits, start, end); err != nil { return err } @@ -859,14 +867,14 @@ func (self *LocalCommitsController) resetAuthor(start, end int) error { }) } -func (self *LocalCommitsController) setAuthor(start, end int) error { +func (self *LocalCommitsController) setAuthor(commits []*models.Commit, start, end int) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.SetAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SetCommitAuthor) - if err := self.c.Git().Rebase.SetCommitAuthor(self.c.Model().Commits, start, end, value); err != nil { + if err := self.c.Git().Rebase.SetCommitAuthor(commits, start, end, value); err != nil { return err } @@ -879,14 +887,14 @@ func (self *LocalCommitsController) setAuthor(start, end int) error { return nil } -func (self *LocalCommitsController) addCoAuthor(start, end int) error { +func (self *LocalCommitsController) addCoAuthor(commits []*models.Commit, start, end int) error { self.c.Prompt(types.PromptOpts{ Title: self.c.Tr.AddCoAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddCommitCoAuthor) - if err := self.c.Git().Rebase.AddCommitCoAuthor(self.c.Model().Commits, start, end, value); err != nil { + if err := self.c.Git().Rebase.AddCommitCoAuthor(commits, start, end, value); err != nil { return err } self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) From fceba3121209658009109b98b2907db66e586e26 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 17:26:30 +0200 Subject: [PATCH 091/218] Capture moveCommitsToNewBranch's model reads on the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two move helpers run inside the WithWaitingStatus worker that withNewBranchNamePrompt dispatches to, but read Model().Files/Submodules (to decide whether to auto-stash) and Model().Commits (the unpushed commits to cherry-pick off the base branch) from there, racing the UI thread's model writes. Compute mustStash — needed by both paths — at the top, and the unpushed commits in the off-of-main menu item, on the UI thread, and pass them into the helpers. --- pkg/gui/controllers/helpers/refs_helper.go | 25 ++++++++++++---------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 70ff18593..61f3a232d 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -424,6 +424,8 @@ func (self *RefsHelper) MoveCommitsToNewBranch() error { return err } + mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) + withNewBranchNamePrompt := func(baseBranchName string, f func(string) error) error { prompt := utils.ResolvePlaceholderString( self.c.Tr.NewBranchNameBranchOff, @@ -462,7 +464,9 @@ func (self *RefsHelper) MoveCommitsToNewBranch() error { Title: self.c.Tr.MoveCommitsToNewBranch, Prompt: prompt, HandleConfirm: func() error { - return withNewBranchNamePrompt(currentBranch.Name, self.moveCommitsToNewBranchStackedOnCurrentBranch) + return withNewBranchNamePrompt(currentBranch.Name, func(newBranchName string) error { + return self.moveCommitsToNewBranchStackedOnCurrentBranch(newBranchName, mustStash) + }) }, }) return nil @@ -482,27 +486,31 @@ func (self *RefsHelper) MoveCommitsToNewBranch() error { { Label: fmt.Sprintf(self.c.Tr.MoveCommitsToNewBranchFromBaseItem, shortBaseBranchName), OnPress: func() error { + commitsToCherryPick := lo.Filter(self.c.Model().Commits, func(commit *models.Commit, _ int) bool { + return commit.Status == models.StatusUnpushed + }) return withNewBranchNamePrompt(shortBaseBranchName, func(newBranchName string) error { - return self.moveCommitsToNewBranchOffOfMainBranch(newBranchName, baseBranchRef) + return self.moveCommitsToNewBranchOffOfMainBranch(newBranchName, baseBranchRef, commitsToCherryPick, mustStash) }) }, }, { Label: fmt.Sprintf(self.c.Tr.MoveCommitsToNewBranchStackedItem, currentBranch.Name), OnPress: func() error { - return withNewBranchNamePrompt(currentBranch.Name, self.moveCommitsToNewBranchStackedOnCurrentBranch) + return withNewBranchNamePrompt(currentBranch.Name, func(newBranchName string) error { + return self.moveCommitsToNewBranchStackedOnCurrentBranch(newBranchName, mustStash) + }) }, }, }, }) } -func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchName string) error { +func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchName string, mustStash bool) error { if err := self.c.Git().Branch.NewWithoutCheckout(newBranchName, "HEAD"); err != nil { return err } - mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) if mustStash { if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil { return err @@ -532,12 +540,7 @@ func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchNa return nil } -func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName string, baseBranchRef string) error { - commitsToCherryPick := lo.Filter(self.c.Model().Commits, func(commit *models.Commit, _ int) bool { - return commit.Status == models.StatusUnpushed - }) - - mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) +func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName string, baseBranchRef string, commitsToCherryPick []*models.Commit, mustStash bool) error { if mustStash { if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil { return err From 462d75232bdd97d73981e0854ba04347e763f4b1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 17:27:07 +0200 Subject: [PATCH 092/218] Look up the submodule file and branch worktree on the UI thread ResetSubmodule and fastForward each call a helper that reads the model from inside their worker: FileForSubmodule reads Model().Files and worktreeForBranch reads Model().Worktrees, racing the UI thread's model writes. Hoist both lookups above the worker dispatch. --- pkg/gui/controllers/branches_controller.go | 2 +- pkg/gui/controllers/files_controller.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index 9b9e9e546..a886a410b 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -710,9 +710,9 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { } action := self.c.Tr.Actions.FastForwardBranch + worktree, ok := self.worktreeForBranch(branch) return self.c.WithInlineStatus(branch, types.ItemOperationFastForwarding, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error { - worktree, ok := self.worktreeForBranch(branch) if ok { self.c.LogAction(action) diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index fc35518e7..b70b67ab7 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -1791,10 +1791,10 @@ func (self *FilesController) remove(selectedNodes []*filetree.FileNode) error { } func (self *FilesController) ResetSubmodule(submodule *models.SubmoduleConfig) error { + file := self.c.Helpers().WorkingTree.FileForSubmodule(submodule) return self.c.WithWaitingStatus(self.c.Tr.ResettingSubmoduleStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.ResetSubmodule) - file := self.c.Helpers().WorkingTree.FileForSubmodule(submodule) if file != nil { if err := self.c.Git().WorkingTree.UnStageFile(file.Names(), file.Tracked); err != nil { return err From 2edfeac5382c2b9d4c107795d8e8cc7d0cccfbb0 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 6 Jul 2026 17:32:19 +0200 Subject: [PATCH 093/218] Capture the commit-file discard and patch-toggle reads on the UI thread discard reads Model().Commits and the selected commit index from its WithWaitingStatus worker; read them in HandleConfirm instead. toggleForPatch reads the commit-files ref name from the worker, and its startPatchBuilder call reads the context's canRebase and diff range from there too. Capture the ref name and run startPatchBuilder in HandleConfirm before dispatching; PatchBuilder.Start only assigns fields, so moving it off the worker changes no timing. discard still collapses the range selection from the worker; that write is a separate concern, left for a follow-up. --- .../controllers/commits_files_controller.go | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index f9fda0b93..07979de5f 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -337,6 +337,8 @@ func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileN Title: self.c.Tr.DiscardFileChangesTitle, Prompt: prompt, HandleConfirm: func() error { + commits := self.c.Model().Commits + selectedLineIdx := self.c.Contexts().LocalCommits.GetSelectedLineIdx() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { var filePaths []string selectedNodes = normalisedSelectedCommitFileNodes(selectedNodes) @@ -356,7 +358,7 @@ func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileN }) } - err := self.c.Git().Rebase.DiscardOldFileChanges(self.c.Model().Commits, self.c.Contexts().LocalCommits.GetSelectedLineIdx(), filePaths) + err := self.c.Git().Rebase.DiscardOldFileChanges(commits, selectedLineIdx, filePaths) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } @@ -442,20 +444,16 @@ func (self *CommitFilesController) toggleForPatch(selectedNodes []*filetree.Comm self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView) } + refName := self.context().GetRef().RefName() + toggle := func() error { return self.c.WithWaitingStatus(self.c.Tr.UpdatingPatch, func(gocui.Task) error { - if !self.c.Git().Patch.PatchBuilder.Active() { - if err := self.startPatchBuilder(); err != nil { - return err - } - } - selectedNodes = normalisedSelectedCommitFileNodes(selectedNodes) // Find if any file in the selection is unselected or partially added adding := lo.SomeBy(selectedNodes, func(node *filetree.CommitFileNode) bool { return node.SomeFile(func(file *models.CommitFile) bool { - fileStatus := self.c.Git().Patch.PatchBuilder.GetFileStatus(file.Path, self.context().GetRef().RefName()) + fileStatus := self.c.Git().Patch.PatchBuilder.GetFileStatus(file.Path, refName) return fileStatus == patch.PART || fileStatus == patch.UNSELECTED }) }) @@ -498,6 +496,12 @@ func (self *CommitFilesController) toggleForPatch(selectedNodes []*filetree.Comm self.c.Git().Patch.PatchBuilder.Reset() } + if !self.c.Git().Patch.PatchBuilder.Active() { + if err := self.startPatchBuilder(); err != nil { + return err + } + } + return toggle() }, }) From 6d21efb515f9e5850d30821fee35c71fda560ca2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 09:57:49 +0200 Subject: [PATCH 094/218] Make the local-commits limit-commits flag atomic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CheckoutRef and ResetToRef set this flag from their worker goroutine (to load fewer commits for speed) while the commits refresh reads it on the UI thread in captureCommitsState to decide how many to load — a data race. Make it an atomic.Bool so those writes are safe where they are, rather than routing the flag through a refresh intent. Precedent: Branch.BehindBaseBranch. --- pkg/gui/context/local_commits_context.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pkg/gui/context/local_commits_context.go b/pkg/gui/context/local_commits_context.go index 056035cce..d929aca88 100644 --- a/pkg/gui/context/local_commits_context.go +++ b/pkg/gui/context/local_commits_context.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "strings" + "sync/atomic" "time" "github.com/jesseduffield/lazygit/pkg/commands/models" @@ -142,7 +143,9 @@ type LocalCommitsViewModel struct { // If this is true we limit the amount of commits we load, for the sake of keeping things fast. // If the user attempts to scroll past the end of the list, we will load more commits. - limitCommits bool + // Atomic because a checkout or reset sets it from a worker goroutine while the + // commits refresh reads it on the UI thread to decide how many commits to load. + limitCommits atomic.Bool // If this is true we'll use git log --all when fetching the commits. showWholeGitGraph bool @@ -151,9 +154,9 @@ type LocalCommitsViewModel struct { func NewLocalCommitsViewModel(getModel func() []*models.Commit, c *ContextCommon) *LocalCommitsViewModel { self := &LocalCommitsViewModel{ ListViewModel: NewListViewModel(getModel), - limitCommits: true, showWholeGitGraph: c.UserConfig().Git.Log.ShowWholeGraph, } + self.limitCommits.Store(true) return self } @@ -225,11 +228,11 @@ func (self *LocalCommitsContext) ModelSearchResults(searchStr string, caseSensit } func (self *LocalCommitsViewModel) SetLimitCommits(value bool) { - self.limitCommits = value + self.limitCommits.Store(value) } func (self *LocalCommitsViewModel) GetLimitCommits() bool { - return self.limitCommits + return self.limitCommits.Load() } func (self *LocalCommitsViewModel) SetShowWholeGitGraph(value bool) { From 6c38ddc9a7e0fc5fbfb6a0c965534336e60c1aa1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:00:09 +0200 Subject: [PATCH 095/218] Set ResetToRef's post-reset selection via refresh intents ResetToRef ran on a worker and wrote the local-commits and reflog selection directly (SetSelection(0) on both) before its refresh, racing the UI thread. Fold those into the refresh's selection intents: SelectHeadCommit for the commits (after a reset HEAD is the top commit, and mid-interactive-rebase it correctly picks the real head over the first todo entry) and SelectTopReflogCommit for the reflog. The now-atomic SetLimitCommits stays where it is. --- pkg/gui/controllers/helpers/refs_helper.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 61f3a232d..5f07b8ea6 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -199,12 +199,14 @@ func (self *RefsHelper) ResetToRef(ref string, strength string, envVars []string return err } - self.c.Contexts().LocalCommits.SetSelection(0) - self.c.Contexts().ReflogCommits.SetSelection(0) // loading a heap of commits is slow so we limit them whenever doing a reset self.c.Contexts().LocalCommits.SetLimitCommits(true) - self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.BRANCHES, types.REFLOG, types.COMMITS}, CommitSelection: types.KeepCommitSelectionIndex}) + self.c.RefreshFromWorker(types.RefreshOptions{ + Scope: []types.RefreshableView{types.FILES, types.BRANCHES, types.REFLOG, types.COMMITS}, + CommitSelection: types.SelectHeadCommit, + SelectTopReflogCommit: true, + }) return nil } From 5d8c89349779622903a06f2e06c10c31650eb2c7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:03:16 +0200 Subject: [PATCH 096/218] Capture commits and set selection on the UI thread for squash/fixup/drop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit interactiveRebaseWithFlag and dropMergeCommit ran inside the WithWaitingStatus worker but read Model().Commits and wrote the selection (SetSelection(startIdx)) there, racing the UI thread. Thread the commits slice in from each caller, and hoist the pre-rebase selection into a UI-thread helper (selectRebaseResultCommit) called before dispatching — squash/fixup unconditionally, drop only on the non-merge path, matching the previous action guard. --- .../controllers/local_commits_controller.go | 47 ++++++++++++------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 595918fb2..23e94adf7 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -340,9 +340,11 @@ func (self *LocalCommitsController) squashDown(selectedCommits []*models.Commit, Title: self.c.Tr.Squash, Prompt: self.c.Tr.SureSquashThisCommit, HandleConfirm: func() error { + commits := self.c.Model().Commits + self.selectRebaseResultCommit(startIdx) return self.c.WithWaitingStatus(self.c.Tr.SquashingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SquashCommitDown) - return self.interactiveRebase(todo.Squash, startIdx, endIdx) + return self.interactiveRebase(commits, todo.Squash, startIdx, endIdx) }) }, }) @@ -362,9 +364,11 @@ func (self *LocalCommitsController) fixup(selectedCommits []*models.Commit, star Label: self.c.Tr.Fixup, Keys: menuKey('f'), OnPress: func() error { + commits := self.c.Model().Commits + self.selectRebaseResultCommit(startIdx) return self.c.WithWaitingStatus(self.c.Tr.FixingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.FixupCommit) - return self.interactiveRebase(todo.Fixup, startIdx, endIdx) + return self.interactiveRebase(commits, todo.Fixup, startIdx, endIdx) }) }, Tooltip: self.c.Tr.FixupTooltip, @@ -373,9 +377,11 @@ func (self *LocalCommitsController) fixup(selectedCommits []*models.Commit, star Label: self.c.Tr.FixupKeepMessage, Keys: menuKey('c'), OnPress: func() error { + commits := self.c.Model().Commits + self.selectRebaseResultCommit(startIdx) return self.c.WithWaitingStatus(self.c.Tr.FixingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.FixupCommitKeepMessage) - return self.interactiveRebaseWithFlag(todo.Fixup, startIdx, endIdx, "-C") + return self.interactiveRebaseWithFlag(commits, todo.Fixup, startIdx, endIdx, "-C") }) }, Tooltip: self.c.Tr.FixupKeepMessageTooltip, @@ -566,12 +572,16 @@ func (self *LocalCommitsController) drop(selectedCommits []*models.Commit, start Title: self.c.Tr.DropCommitTitle, Prompt: lo.Ternary(isMerge, self.c.Tr.DropMergeCommitPrompt, self.c.Tr.DropCommitPrompt), HandleConfirm: func() error { + commits := self.c.Model().Commits + if !isMerge { + self.selectRebaseResultCommit(startIdx) + } return self.c.WithWaitingStatus(self.c.Tr.DroppingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DropCommit) if isMerge { - return self.dropMergeCommit(startIdx) + return self.dropMergeCommit(commits, startIdx) } - return self.interactiveRebase(todo.Drop, startIdx, endIdx) + return self.interactiveRebase(commits, todo.Drop, startIdx, endIdx) }) }, }) @@ -579,8 +589,8 @@ func (self *LocalCommitsController) drop(selectedCommits []*models.Commit, start return nil } -func (self *LocalCommitsController) dropMergeCommit(commitIdx int) error { - err := self.c.Git().Rebase.DropMergeCommit(self.c.Model().Commits, commitIdx) +func (self *LocalCommitsController) dropMergeCommit(commits []*models.Commit, commitIdx int) error { + err := self.c.Git().Rebase.DropMergeCommit(commits, commitIdx) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) } @@ -658,22 +668,25 @@ func (self *LocalCommitsController) pick(selectedCommits []*models.Commit) error panic("should be disabled when not rebasing") } -func (self *LocalCommitsController) interactiveRebase(action todo.TodoCommand, startIdx int, endIdx int) error { - return self.interactiveRebaseWithFlag(action, startIdx, endIdx, "") +func (self *LocalCommitsController) interactiveRebase(commits []*models.Commit, action todo.TodoCommand, startIdx int, endIdx int) error { + return self.interactiveRebaseWithFlag(commits, action, startIdx, endIdx, "") } -func (self *LocalCommitsController) interactiveRebaseWithFlag(action todo.TodoCommand, startIdx int, endIdx int, flag string) error { - // When performing an action that will remove the selected commits, we need to select the - // next commit down (which will end up at the start index after the action is performed) - if action == todo.Drop || action == todo.Fixup || action == todo.Squash { - self.context().SetSelection(startIdx) - } - - err := self.c.Git().Rebase.InteractiveRebase(self.c.Model().Commits, startIdx, endIdx, action, flag) +func (self *LocalCommitsController) interactiveRebaseWithFlag(commits []*models.Commit, action todo.TodoCommand, startIdx int, endIdx int, flag string) error { + err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, action, flag) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) } +// selectRebaseResultCommit selects the commit that a drop/fixup/squash starting +// at startIdx will leave there. It must run on the UI thread before the rebase: +// the commit currently at startIdx is removed, so the refresh's +// keep-selection-by-hash can't restore it and falls back to the index, which by +// then holds the commit that shifted up into its place. +func (self *LocalCommitsController) selectRebaseResultCommit(startIdx int) { + self.context().SetSelection(startIdx) +} + // updateTodos sees if the selected commit is in fact a rebasing // commit meaning you are trying to edit the todo file rather than actually // begin a rebase. It then updates the todo file with that action From f07e94afe0cf236f52d75eef3b8177e119c70b67 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:12:13 +0200 Subject: [PATCH 097/218] Keep RebaseOntoRef's marked-base access on the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three rebase-onto menu items read Modes().MarkedBaseCommit.GetHash() (a bare string field) and, on success, cleared it via ResetMarkedBaseCommit and pushed the commits context — all from the WithWaitingStatus worker, racing the UI thread. Read the marked base hash before dispatching, and bounce the post-rebase reset and context push through OnUIThread, still guarded by the success check so they don't run on the conflict path. --- .../helpers/merge_and_rebase_helper.go | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 6adf84712..b0c53b831 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -424,8 +424,8 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { DisabledReason: disabledReason, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) + baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { - baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.RebaseBranchFromBaseCommit(ref, baseCommit) @@ -434,7 +434,9 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { } err = self.CheckMergeOrRebase(err) if err == nil { - return self.ResetMarkedBaseCommit() + self.c.OnUIThread(func() error { + return self.ResetMarkedBaseCommit() + }) } return err }) @@ -449,8 +451,8 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { Tooltip: self.c.Tr.InteractiveRebaseTooltip, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) + baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { - baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.EditRebaseFromBaseCommit(ref, baseCommit) @@ -460,10 +462,13 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { if err = self.CheckMergeOrRebase(err); err != nil { return err } - if err = self.ResetMarkedBaseCommit(); err != nil { - return err - } - self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + self.c.OnUIThread(func() error { + if err := self.ResetMarkedBaseCommit(); err != nil { + return err + } + self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + return nil + }) return nil }) }, @@ -477,8 +482,8 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { Tooltip: self.c.Tr.RebaseOntoBaseBranchTooltip, OnPress: func() error { self.c.LogAction(self.c.Tr.Actions.RebaseBranch) + baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(task gocui.Task) error { - baseCommit := self.c.Modes().MarkedBaseCommit.GetHash() var err error if baseCommit != "" { err = self.c.Git().Rebase.RebaseBranchFromBaseCommit(baseBranch, baseCommit) @@ -487,7 +492,9 @@ func (self *MergeAndRebaseHelper) RebaseOntoRef(ref string) error { } err = self.CheckMergeOrRebase(err) if err == nil { - return self.ResetMarkedBaseCommit() + self.c.OnUIThread(func() error { + return self.ResetMarkedBaseCommit() + }) } return err }) From 67b0a6b1a46ef80399454f5954fd1f5c33ddacfa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:12:19 +0200 Subject: [PATCH 098/218] Move the pull-patch panel close and focus off the worker The pull-patch-into-new-commit handlers closed the commit-message panel and, on success, pushed the local-commits context from inside the WithWaitingStatus worker. Close the panel in OnConfirm before dispatching (UI thread), and bounce the post-rebase context push through OnUIThread, keeping it on the success path. --- .../custom_patch_options_menu_action.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/pkg/gui/controllers/custom_patch_options_menu_action.go b/pkg/gui/controllers/custom_patch_options_menu_action.go index 20e36833e..3d15ce899 100644 --- a/pkg/gui/controllers/custom_patch_options_menu_action.go +++ b/pkg/gui/controllers/custom_patch_options_menu_action.go @@ -188,14 +188,17 @@ func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error { PreserveMessage: false, OnConfirm: func(summary string, description string) error { commits := self.c.Model().Commits + self.c.Helpers().Commits.CloseCommitMessagePanel() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { - self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) err := self.c.Git().Patch.PullPatchIntoNewCommit(commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } - self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + self.c.OnUIThread(func() error { + self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + return nil + }) return nil }) }, @@ -220,14 +223,17 @@ func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommitBefore() e PreserveMessage: false, OnConfirm: func(summary string, description string) error { commits := self.c.Model().Commits + self.c.Helpers().Commits.CloseCommitMessagePanel() return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { - self.c.Helpers().Commits.CloseCommitMessagePanel() self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit) err := self.c.Git().Patch.PullPatchIntoNewCommitBefore(commits, commitIndex, summary, description) if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil { return err } - self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + self.c.OnUIThread(func() error { + self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{}) + return nil + }) return nil }) }, From e7105a3138cebf767e15f6f5fd00d816f971609b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:17:33 +0200 Subject: [PATCH 099/218] Collapse the branch range selection on the UI thread after a delete The three branch-delete handlers and the two worktree-removal continuations collapsed the Branches/RemoteBranches range selection from their worker goroutine, racing the UI thread. Wrap each collapse in OnUIThread, keeping it in the same spot relative to the refresh (FIFO preserves the collapse-then-refresh order the name-restore depends on). --- .../controllers/helpers/branches_helper.go | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 683d26db3..5c72bacfd 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -45,7 +45,10 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error return err } - self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.OnUIThread(func() error { + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + return nil + }) self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) return nil }) @@ -86,7 +89,10 @@ func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteB } self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) if resetRemoteBranchesSelection { - self.c.Contexts().RemoteBranches.CollapseRangeSelectionToTop() + self.c.OnUIThread(func() error { + self.c.Contexts().RemoteBranches.CollapseRangeSelectionToTop() + return nil + }) } return nil }) @@ -151,7 +157,10 @@ func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branc return err } - self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.OnUIThread(func() error { + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + return nil + }) self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }) @@ -311,7 +320,10 @@ func (self *BranchesHelper) deleteLocalBranchesContinuation(branches []*models.B return err } - self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.OnUIThread(func() error { + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + return nil + }) self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}, @@ -329,7 +341,10 @@ func (self *BranchesHelper) deleteLocalAndRemoteBranchesContinuation(branches [] return err } - self.c.Contexts().Branches.CollapseRangeSelectionToTop() + self.c.OnUIThread(func() error { + self.c.Contexts().Branches.CollapseRangeSelectionToTop() + return nil + }) self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.REMOTES, types.FILES}, From 6cd93de5b9ba4938cbe648eeab034fc813eb1243 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:18:52 +0200 Subject: [PATCH 100/218] Cancel the commit-file range selection on the UI thread after discard The discard handler cancelled the commit-files range selection from its WithWaitingStatus worker. Bounce it through OnUIThread, keeping it after the successful CheckMergeOrRebase as before. --- pkg/gui/controllers/commits_files_controller.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index 07979de5f..b90e14b74 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -363,9 +363,12 @@ func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileN return err } - if self.context().RangeSelectEnabled() { - self.context().GetList().CancelRangeSelect() - } + self.c.OnUIThread(func() error { + if self.context().RangeSelectEnabled() { + self.context().GetList().CancelRangeSelect() + } + return nil + }) return nil }) From 12757e2723c830d6831913892bb2cc5cde785873 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:20:14 +0200 Subject: [PATCH 101/218] Swap the file-path suggestions trie on the UI thread GetFilePathSuggestionsFunc builds the trie on a worker (the slow AllRepoFiles walk) and then assigned Model().FilesTrie and refreshed the suggestions panel from there, racing the UI thread that reads the trie. Keep the build on the worker but bounce just the model assignment and the refresh through OnUIThread. --- pkg/gui/controllers/helpers/suggestions_helper.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pkg/gui/controllers/helpers/suggestions_helper.go b/pkg/gui/controllers/helpers/suggestions_helper.go index d26f96f1c..8a5916816 100644 --- a/pkg/gui/controllers/helpers/suggestions_helper.go +++ b/pkg/gui/controllers/helpers/suggestions_helper.go @@ -137,10 +137,12 @@ func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*type trie.Insert(patricia.Prefix(file), file) } - // cache the trie for future use - self.c.Model().FilesTrie = trie - - self.c.Contexts().Suggestions.RefreshSuggestions() + self.c.OnUIThread(func() error { + // cache the trie for future use + self.c.Model().FilesTrie = trie + self.c.Contexts().Suggestions.RefreshSuggestions() + return nil + }) return err }) From fefb3b632e79ea478d5883b5f5e25e64555c340d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 10:20:14 +0200 Subject: [PATCH 102/218] Clear the preserved commit message on the UI thread The commit's gpg onSuccess runs on a worker when the command output is streamed, so its ClearPreservedCommitMessage wrote commit-message context state off the UI thread. Bounce that write through OnUIThread. --- pkg/gui/controllers/helpers/working_tree_helper.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/working_tree_helper.go b/pkg/gui/controllers/helpers/working_tree_helper.go index 7e321854b..36dfd2032 100644 --- a/pkg/gui/controllers/helpers/working_tree_helper.go +++ b/pkg/gui/controllers/helpers/working_tree_helper.go @@ -149,7 +149,12 @@ func (self *WorkingTreeHelper) handleCommit(summary string, description string, self.c.LogAction(self.c.Tr.Actions.Commit) return self.gpgHelper.WithGpgHandlingAndSelectHeadCommit(cmdObj, git_commands.CommitGpgSign, self.c.Tr.CommittingStatus, func() error { - self.commitsHelper.ClearPreservedCommitMessage() + // This runs on a worker when the commit output is streamed, so + // bounce the preserved-message write to the UI thread. + self.c.OnUIThread(func() error { + self.commitsHelper.ClearPreservedCommitMessage() + return nil + }) return nil }) } From 2c3a6acafaf511696d4dfb8f5c46a63c2463a65d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 12:36:02 +0200 Subject: [PATCH 103/218] Thread a refreshEnv through the refresh scopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every refresh scope needs two ambient values to bounce its model and view updates back to the UI thread safely: the background flag (which picks the dispatch variant that doesn't count towards lazygit being busy) and the repo generation that guards the bounce against a repo switch. These were threaded separately — background as a parameter on every refreshXxx function, generation re-read from the model inside each one. Bundle them into a single refreshEnv passed through instead, so the guard has a home to grow into (the next commit needs the generation in refreshView, which currently has no access to it). Capturing the generation once, at the start of the refresh, is also more correct than the previous per-function re-read. The baseline should reflect the repo whose inputs the refresh snapshotted (all captured up front on the UI thread), not whenever each scope's worker happens to wake. With the per-function read, a background refresh whose worker woke after a repo switch would read the new generation and let its bounce through, writing data computed from the old repo's inputs into the new repo; capturing up front makes that bounce drop instead. No behavior change for foreground refreshes, where the UI thread is held for the whole refresh and the generation can't move under it. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 245 +++++++++--------- pkg/gui/types/common.go | 8 +- 2 files changed, 123 insertions(+), 130 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 65870ca20..b1b3ef017 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -89,6 +89,15 @@ func (self *RefreshHelper) RefreshFromWorker(options types.RefreshOptions) { self.performRefresh(options, true) } +type refreshEnv struct { + // whether this is a background refresh (which selects the dispatch variant that + // doesn't count towards lazygit being busy) + background bool + + // the repo generation captured when the refresh started + generation int +} + func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { if options.Mode == types.ASYNC && options.Then != nil { panic("RefreshOptions.Then doesn't work with mode ASYNC") @@ -129,6 +138,13 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } f := func() { + // Capture the repo generation once, here at the start, so every scope's + // bounce is guarded against the same baseline. + env := refreshEnv{ + background: options.Background, + generation: self.c.State().GetRepoGeneration(), + } + var scopeSet *set.Set[types.RefreshableView] if len(options.Scope) == 0 { // not refreshing staging/patch-building unless explicitly requested because we only need @@ -186,7 +202,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // everything happens fast and it's better to have everything update // in the one frame if !self.c.InDemo() && options.Mode == types.ASYNC { - self.onWorker(options.Background, func(t gocui.Task) error { + self.onWorker(env.background, func(t gocui.Task) error { f() return nil }) @@ -222,20 +238,20 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr var capturedCommits capturedCommitState var capturedReflog capturedReflogState var capturedBranches capturedBranchState - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { capturedCommits = self.captureCommitsState(options.CommitSelection) capturedReflog = self.captureReflogState() capturedBranches = self.captureBranchState() }) refresh("commits and commit files", func() { - self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, options.Background) + self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, env) }) includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { branchesAndRemotesWg.Add(1) refresh("reflog and branches", func() { - loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, options.Background) + loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, env) branchesAndRemotesWg.Done() }) } else { @@ -244,11 +260,11 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // Not a recency sort, so branches doesn't depend on the reflog // being fresh; it runs concurrently with the reflog refresh // below and uses the reflog we captured up front, as it always has. - loadedBranches = self.refreshBranches(capturedBranches, includeWorktreesWithBranches, options.BranchSelection, true, capturedReflog.reflogCommits, options.Background) + loadedBranches = self.refreshBranches(capturedBranches, includeWorktreesWithBranches, options.BranchSelection, true, capturedReflog.reflogCommits, env) branchesAndRemotesWg.Done() }) refresh("reflog", func() { - _, _ = self.refreshReflogCommits(capturedReflog, options.Background, options.SelectTopReflogCommit) + _, _ = self.refreshReflogCommits(capturedReflog, env, options.SelectTopReflogCommit) }) } } else if scopeSet.Includes(types.REBASE_COMMITS) { @@ -256,52 +272,52 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // if we've asked specifically for rebase commits and not those other things var rebaseHashPool *utils.StringPool var rebaseCommits []*models.Commit - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { rebaseHashPool, rebaseCommits = self.captureRebaseCommitState() }) - refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, options.Background) }) + refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, env) }) } if scopeSet.Includes(types.SUB_COMMITS) { var capturedSubCommits capturedSubCommitState - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { capturedSubCommits = self.captureSubCommitState() }) - refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, options.Background) }) + refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, env) }) } // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { var capturedCommitFiles capturedCommitFilesState - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { capturedCommitFiles = self.captureCommitFilesState() }) - refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, options.Background) }) + refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, env) }) } fileWg := sync.WaitGroup{} if scopeSet.Includes(types.FILES) { var capturedFiles capturedFilesState - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { capturedFiles = self.captureFilesState() }) fileWg.Add(1) refresh("files", func() { - _ = self.refreshFilesAndSubmodules(capturedFiles, options.Background) + _ = self.refreshFilesAndSubmodules(capturedFiles, env) fileWg.Done() }) } if scopeSet.Includes(types.STASH) { var stashFilterPath string - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { stashFilterPath = self.c.Modes().Filtering.GetPath() }) - refresh("stash", func() { self.refreshStashEntries(stashFilterPath, options.Background) }) + refresh("stash", func() { self.refreshStashEntries(stashFilterPath, env) }) } if scopeSet.Includes(types.TAGS) { - refresh("tags", func() { _ = self.refreshTags(options.Background) }) + refresh("tags", func() { _ = self.refreshTags(env) }) } if scopeSet.Includes(types.REMOTES) { @@ -309,12 +325,12 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // needs it to keep the remote-branches selection valid, and reading // the Remotes context off the UI thread races its render. var prevSelectedRemote *models.Remote - self.captureOnUIThread(fRunsOnUIThread, options.Background, func() { + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { prevSelectedRemote = self.c.Contexts().Remotes.GetSelected() }) branchesAndRemotesWg.Add(1) refresh("remotes", func() { - loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, options.Background) + loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, env) branchesAndRemotesWg.Done() }) } @@ -326,12 +342,12 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // Model().Branches/Remotes: those writes are bounced onto the // UI thread and may not have landed on this worker yet. The // wait above orders us after both loads have stashed theirs. - self.refreshGithubPullRequests(loadedBranches, loadedRemotes, options.Background) + self.refreshGithubPullRequests(loadedBranches, loadedRemotes, env) }) } if scopeSet.Includes(types.WORKTREES) && !includeWorktreesWithBranches { - refresh("worktrees", func() { self.refreshWorktrees(options.Background) }) + refresh("worktrees", func() { self.refreshWorktrees(env) }) } if scopeSet.Includes(types.STAGING) { @@ -341,7 +357,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // scope's model-update bounce — RefreshStagingPanel reads // Model.Files (via Files.GetSelected) and would otherwise // see the pre-refresh model. - self.onUIThread(options.Background, func() error { + self.onUIThread(env.background, func() error { self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) return nil }) @@ -353,10 +369,10 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.MERGE_CONFLICTS) { - refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(options.Background) }) + refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(env.background) }) } - self.refreshStatus(options.Background) + self.refreshStatus(env) wg.Wait() @@ -367,7 +383,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // returned but their bounces haven't been processed yet, so // invoking Then synchronously would run it on a model that's // still pre-refresh. - self.onUIThread(options.Background, options.Then) + self.onUIThread(env.background, options.Then) } } @@ -528,17 +544,17 @@ func (self *RefreshHelper) captureBranchState() capturedBranchState { } } -func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflogState, capturedBranches capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, background bool) []*models.Branch { +func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflogState, capturedBranches capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, env refreshEnv) []*models.Branch { switch self.c.State().GetRepoState().GetStartupStage() { case types.INITIAL: // Return the immediate (non-recency) load's branches; the recency-sorted // reload below runs on its own worker after we return. Both hold the same // set of branches, which is all the caller (the PR fetch) needs. - branches := self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, false, capturedReflog.reflogCommits, background) + branches := self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, false, capturedReflog.reflogCommits, env) - self.onWorker(background, func(_ gocui.Task) error { - reflogCommits, _ := self.refreshReflogCommits(capturedReflog, background, false) - self.refreshBranches(capturedBranches, false, types.SelectCheckedOutBranch, true, reflogCommits, background) + self.onWorker(env.background, func(_ gocui.Task) error { + reflogCommits, _ := self.refreshReflogCommits(capturedReflog, env, false) + self.refreshBranches(capturedBranches, false, types.SelectCheckedOutBranch, true, reflogCommits, env) self.c.State().GetRepoState().SetStartupStage(types.COMPLETE) return nil }) @@ -546,8 +562,8 @@ func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflo return branches case types.COMPLETE: - reflogCommits, _ := self.refreshReflogCommits(capturedReflog, background, selectTopReflogCommit) - return self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, true, reflogCommits, background) + reflogCommits, _ := self.refreshReflogCommits(capturedReflog, env, selectTopReflogCommit) + return self.refreshBranches(capturedBranches, refreshWorktrees, branchSelection, true, reflogCommits, env) } return nil @@ -592,9 +608,8 @@ func (self *RefreshHelper) captureCommitsState(commitSelection types.CommitSelec } } -func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, background bool) { - generation := self.c.State().GetRepoGeneration() - _ = self.refreshCommitsWithLimit(captured, commitSelection, background) +func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, env refreshEnv) { + _ = self.refreshCommitsWithLimit(captured, commitSelection, env) if captured.parentIsLocalCommits { // This makes sense when we've e.g. just amended a commit, meaning we get a new commit hash at the same position. // However if we've just added a brand new commit, it pushes the list down by one and so we would end up @@ -606,7 +621,7 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS // The commit selection is restored in refreshCommitsWithLimit's bounce, // so read it on the UI thread after that bounce; then load the commit // files back on a worker (refreshCommitFilesContext does git work). - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { commit := self.c.Contexts().LocalCommits.GetSelected() if commit != nil && commit.RefName() != "" { refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() @@ -614,8 +629,8 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS // Capture the diff endpoints here, on the UI thread and after // ReInit has set them, before dispatching the git work. capturedCommitFiles := self.captureCommitFilesState() - self.onWorker(background, func(gocui.Task) error { - _ = self.refreshCommitFilesContext(capturedCommitFiles, background) + self.onWorker(env.background, func(gocui.Task) error { + _ = self.refreshCommitFilesContext(capturedCommitFiles, env) return nil }) } @@ -650,9 +665,7 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { return nil } -func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, background bool) error { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, env refreshEnv) error { checkedOutRef := self.determineCheckedOutRef() refName, bisectInfo := self.refForLog() commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( @@ -673,7 +686,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().BisectInfo = bisectInfo self.c.Model().Commits = commits self.RefreshAuthors(commits) @@ -707,7 +720,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, // Enqueued from within this bounce so it runs after refreshView's // render below (which was enqueued first), matching the previous // ordering where FocusLine ran after the view was re-rendered. - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Contexts().LocalCommits.FocusLine(true) return nil }) @@ -715,7 +728,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, return nil }) - self.refreshView(self.c.Contexts().LocalCommits, background) + self.refreshView(self.c.Contexts().LocalCommits, env) return nil } @@ -821,13 +834,11 @@ func (self *RefreshHelper) captureSubCommitState() capturedSubCommitState { } } -func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommitState, background bool) error { +func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommitState, env refreshEnv) error { if captured.ref == nil { return nil } - generation := self.c.State().GetRepoGeneration() - commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: captured.limitCommits, @@ -844,13 +855,13 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommit if err != nil { return err } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().SubCommits = commits self.RefreshAuthors(commits) return nil }) - self.refreshView(self.c.Contexts().SubCommits, background) + self.refreshView(self.c.Contexts().SubCommits, env) return nil } @@ -882,19 +893,17 @@ func (self *RefreshHelper) captureCommitFilesState() capturedCommitFilesState { return capturedCommitFilesState{from: from, to: to, reverse: reverse} } -func (self *RefreshHelper) refreshCommitFilesContext(captured capturedCommitFilesState, background bool) error { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshCommitFilesContext(captured capturedCommitFilesState, env refreshEnv) error { files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(captured.from, captured.to, captured.reverse) if err != nil { return err } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().CommitFiles = files self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() return nil }) - self.refreshView(self.c.Contexts().CommitFiles, background) + self.refreshView(self.c.Contexts().CommitFiles, env) return nil } @@ -904,39 +913,35 @@ func (self *RefreshHelper) captureRebaseCommitState() (hashPool *utils.StringPoo return self.c.Model().HashPool, self.c.Model().Commits } -func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, commits []*models.Commit, background bool) error { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, commits []*models.Commit, env refreshEnv) error { updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(hashPool, commits) if err != nil { return err } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().Commits = updatedCommits self.c.Model().WorkingTreeStateAtLastCommitRefresh = workingTreeState return nil }) - self.refreshView(self.c.Contexts().LocalCommits, background) + self.refreshView(self.c.Contexts().LocalCommits, env) return nil } -func (self *RefreshHelper) refreshTags(background bool) error { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshTags(env refreshEnv) error { tags, err := self.c.Git().Loaders.TagLoader.GetTags() if err != nil { return err } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().Tags = tags return nil }) - self.refreshView(self.c.Contexts().Tags, background) + self.refreshView(self.c.Contexts().Tags, env) return nil } @@ -946,25 +951,23 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo // self.refreshStatus is called at the end of this because that's when we can // be sure there is a State.Model.Branches array to pick the current branch from -func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, background bool) []*models.Branch { +func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, env refreshEnv) []*models.Branch { loadSeq := self.branchLoadSeq.Add(1) - generation := self.c.State().GetRepoGeneration() - branches, err := self.c.Git().Loaders.BranchLoader.Load( reflogCommits, captured.mainBranches, captured.oldBranches, loadBehindCounts, func(f func() error) { - self.onWorker(background, func(_ gocui.Task) error { + self.onWorker(env.background, func(_ gocui.Task) error { return f() }) }, func() { - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Contexts().Branches.HandleRender() - self.refreshStatus(background) + self.refreshStatus(env) return nil }) }) @@ -977,7 +980,7 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh worktrees = self.loadWorktrees() } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { // Drop this write if a branch load that started later has already applied // its result. At the INITIAL startup stage an immediate load (not // recency-sorted) and an async recency-sorted load run concurrently; this @@ -1000,7 +1003,7 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh if refreshWorktrees { self.c.Model().Worktrees = worktrees - self.refreshView(self.c.Contexts().Worktrees, background) + self.refreshView(self.c.Contexts().Worktrees, env) } // Setting the selection here, in the same bounce that writes the list, @@ -1030,27 +1033,27 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh return nil }) - self.refreshView(self.c.Contexts().Branches, background) + self.refreshView(self.c.Contexts().Branches, env) - self.refreshStatus(background) + self.refreshStatus(env) // Return the freshly-loaded branches so the caller can hand them to the PR // fetch without reading them back from the (bounce-written) model. return branches } -func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState, background bool) error { +func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState, env refreshEnv) error { configs, err := self.refreshStateSubmoduleConfigs() if err != nil { return err } - if err := self.refreshStateFiles(captured, background, configs); err != nil { + if err := self.refreshStateFiles(captured, env, configs); err != nil { return err } - self.refreshView(self.c.Contexts().Submodules, background) - self.refreshView(self.c.Contexts().Files, background) + self.refreshView(self.c.Contexts().Submodules, env) + self.refreshView(self.c.Contexts().Files, env) return nil } @@ -1060,11 +1063,11 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState // Refresh workers do their git work off the UI thread and enqueue their model // writes here; a repo switch (which replaces the whole model and context tree) // bumps the generation, so a write captured under the old generation must not -// clobber the new repo's state. Callers capture the generation with -// State().GetRepoGeneration() before doing their git work and pass it in. -func (self *RefreshHelper) onUIThreadUnlessRepoChanged(generation int, background bool, f func() error) { - self.onUIThread(background, func() error { - if self.c.State().GetRepoGeneration() != generation { +// clobber the new repo's state. The generation is captured once at the start of +// the refresh and carried in env (see refreshEnv). +func (self *RefreshHelper) onUIThreadUnlessRepoChanged(env refreshEnv, f func() error) { + self.onUIThread(env.background, func() error { + if self.c.State().GetRepoGeneration() != env.generation { return nil } return f() @@ -1140,9 +1143,8 @@ func (self *RefreshHelper) captureFilesState() capturedFilesState { } } -func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, background bool, submoduleConfigs []*models.SubmoduleConfig) error { +func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env refreshEnv, submoduleConfigs []*models.SubmoduleConfig) error { fileTreeViewModel := self.c.Contexts().Files.FileTreeViewModel - generation := self.c.State().GetRepoGeneration() prevConflictFileCount := 0 if self.c.UserConfig().Git.AutoStageResolvedConflicts { @@ -1179,7 +1181,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, backgr files := self.c.Git().Loaders.FileLoader. GetStatusFiles(git_commands.GetStatusFileOptions{ ForceShowUntracked: captured.forceShowUntracked, - Background: background, + Background: env.background, }) conflictFileCount := 0 @@ -1203,7 +1205,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, backgr // (e.g. in the user's editor). Offer to continue it. We only do this // for operations we started ourselves; prompting for one that was // started outside lazygit (e.g. by a coding agent) would be confusing. - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { return self.mergeAndRebaseHelper.PromptToContinueRebase() }) } @@ -1218,7 +1220,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, backgr }) } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { // only taking over the filter if it hasn't already been set by the user. if conflictFileCount > 0 && prevConflictFileCount == 0 { if fileTreeViewModel.GetStatusFilter() == filetree.DisplayAll { @@ -1249,8 +1251,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, backgr // refreshReflogCommits returns the (non-filtered) ReflogCommits it loaded, so // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. -func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, background bool, selectTopEntry bool) ([]*models.Commit, error) { - generation := self.c.State().GetRepoGeneration() +func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, env refreshEnv, selectTopEntry bool) ([]*models.Commit, error) { // pulling state into its own variable in case it gets swapped out for another state // and we get an out of bounds exception model := self.c.Model() @@ -1289,7 +1290,7 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, ba } } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { model.ReflogCommits = reflogCommits model.FilteredReflogCommits = filteredReflogCommits // Setting the selection here, in the same bounce that writes the list, @@ -1302,26 +1303,24 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, ba return nil }) - self.refreshView(self.c.Contexts().ReflogCommits, background) + self.refreshView(self.c.Contexts().ReflogCommits, env) return reflogCommits, nil } -func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, background bool) ([]*models.Remote, error) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env refreshEnv) ([]*models.Remote, error) { remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() if err != nil { return nil, err } - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().Remotes = remotes hadPrs := len(self.c.Model().PullRequestsMap) != 0 self.rebuildPullRequestsMap() if !hadPrs && len(self.c.Model().PullRequestsMap) != 0 { // if we didn't have PRs in the map before but now we do, we need to redraw the branches view - self.refreshView(self.c.Contexts().Branches, background) + self.refreshView(self.c.Contexts().Branches, env) } // we need to ensure our selected remote branches aren't now outdated @@ -1337,8 +1336,8 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, bac return nil }) - self.refreshView(self.c.Contexts().Remotes, background) - self.refreshView(self.c.Contexts().RemoteBranches, background) + self.refreshView(self.c.Contexts().Remotes, env) + self.refreshView(self.c.Contexts().RemoteBranches, env) return remotes, nil } @@ -1351,44 +1350,38 @@ func (self *RefreshHelper) loadWorktrees() []*models.Worktree { return worktrees } -func (self *RefreshHelper) refreshWorktrees(background bool) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshWorktrees(env refreshEnv) { worktrees := self.loadWorktrees() - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().Worktrees = worktrees return nil }) // need to refresh branches because the branches view shows worktrees against // branches - self.refreshView(self.c.Contexts().Branches, background) - self.refreshView(self.c.Contexts().Worktrees, background) + self.refreshView(self.c.Contexts().Branches, env) + self.refreshView(self.c.Contexts().Worktrees, env) } -func (self *RefreshHelper) refreshStashEntries(filterPath string, background bool) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshStashEntries(filterPath string, env refreshEnv) { stashEntries := self.c.Git().Loaders.StashLoader. GetStashEntries(filterPath) - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().StashEntries = stashEntries return nil }) - self.refreshView(self.c.Contexts().Stash, background) + self.refreshView(self.c.Contexts().Stash, env) } // never call this on its own, it should only be called from within refreshCommits() -func (self *RefreshHelper) refreshStatus(background bool) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshStatus(env refreshEnv) { workingTreeState := self.c.Git().Status.WorkingTreeState() repoName := self.c.Git().RepoPaths.RepoName() - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { // Read the checked-out branch and the linked worktree name here on the UI // thread: both derive from models (Branches, Worktrees) that their // refreshes now write via bounces, so reading them on the worker would @@ -1425,10 +1418,10 @@ func (self *RefreshHelper) refForLog() (string, *git_commands.BisectInfo) { return bisectInfo.GetStartHash(), bisectInfo } -func (self *RefreshHelper) refreshView(context types.Context, background bool) { +func (self *RefreshHelper) refreshView(context types.Context, env refreshEnv) { // refreshView is called from the worker goroutine that drives async // refreshes, so bounce to the UI thread before mutating view content. - self.onUIThread(background, func() error { + self.onUIThread(env.background, func() error { // Re-applying the filter must be done before re-rendering the view, so that // the filtered list model is up to date for rendering. self.searchHelper.ReApplyFilter(context) @@ -1451,11 +1444,9 @@ func (self *RefreshHelper) refreshView(context types.Context, background bool) { }) } -func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, remotes []*models.Remote, background bool) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, remotes []*models.Remote, env refreshEnv) { clearPullRequests := func() { - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().PullRequests = nil self.c.Model().PullRequestsMap = nil return nil @@ -1478,7 +1469,7 @@ func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, return } - self.setGithubPullRequests(baseInfo, branches, background) + self.setGithubPullRequests(baseInfo, branches, env) } type githubRemoteInfo struct { @@ -1559,7 +1550,11 @@ func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteI self.c.Log.Error(err) } - self.setGithubPullRequests(&info, branches, false) + // This fetch runs on its own worker after the user picked a + // base remote, so it's not part of a performRefresh and has no + // ambient env; build a foreground one now, capturing the + // current generation as the guard baseline. + self.setGithubPullRequests(&info, branches, refreshEnv{generation: self.c.State().GetRepoGeneration()}) return nil }) }, @@ -1587,9 +1582,7 @@ func (self *RefreshHelper) rebuildPullRequestsMap() { ) } -func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, branches []*models.Branch, background bool) { - generation := self.c.State().GetRepoGeneration() - +func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, branches []*models.Branch, env refreshEnv) { if len(branches) == 0 { return } @@ -1609,7 +1602,7 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, bra self.savePullRequestsToCache(prs) - self.onUIThreadUnlessRepoChanged(generation, background, func() error { + self.onUIThreadUnlessRepoChanged(env, func() error { self.c.Model().PullRequests = prs // Rebuilding here rather than on the worker means the map is built from // the branches and remotes as they are on the UI thread, after their diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 0f8e99ee8..4ced8bd79 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -394,10 +394,10 @@ type IStateAccessor interface { ClearItemOperation(item HasUrn) // A counter that is bumped every time we switch to a different repository - // (see Gui.resetState). Refresh workers capture it before doing their git - // work and pass it to onUIThreadUnlessRepoChanged, so that a model update - // computed for one repo can be dropped rather than applied to another if the - // user switched repos while the refresh was in flight. + // (see Gui.resetState). A refresh captures it when it starts and carries it + // through to onUIThreadUnlessRepoChanged, so that a model update computed for + // one repo can be dropped rather than applied to another if the user switched + // repos while the refresh was in flight. GetRepoGeneration() int } From 19b34851ff5ffb31aef310686e74a4625404c2b3 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 12:39:28 +0200 Subject: [PATCH 104/218] Guard the view-render and prompt-dismiss bounces on the generation The model-update bounces already drop themselves when the repo is switched mid-refresh (onUIThreadUnlessRepoChanged), but three bounces that touch the UI without writing the model did not: refreshView's render, the staging-panel refresh, and the stale continue-rebase prompt dismissal. All three ran unconditionally on the UI thread, so a background refresh in flight across a repo switch could render the old repo's data (through a context object belonging to the now-replaced context tree), or pop the new repo's popup based on the old repo's prompt state. Route them through onUIThreadUnlessRepoChanged too, so they're dropped alongside the model writes they accompany. This also fixes the dismiss bounce using the raw foreground OnUIThread, which ignored the background flag every other bounce in a background refresh respects. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index b1b3ef017..3c8524ffe 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -356,8 +356,9 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // Bounce onto the UI thread so this runs after the files // scope's model-update bounce — RefreshStagingPanel reads // Model.Files (via Files.GetSelected) and would otherwise - // see the pre-refresh model. - self.onUIThread(env.background, func() error { + // see the pre-refresh model. Guard on the generation so a + // repo switch mid-refresh drops it, like the model bounces. + self.onUIThreadUnlessRepoChanged(env, func() error { self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) return nil }) @@ -1214,7 +1215,10 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re // appeared. Either way, a "continue?" prompt we're showing is now stale // (e.g. the operation was continued or aborted outside lazygit), so // dismiss it rather than leave the user with a prompt that would fail. - self.c.OnUIThread(func() error { + // Guard on the generation like the sibling PromptToContinueRebase + // bounce above: if the repo was switched while this refresh was in + // flight, a prompt showing now belongs to the new repo, so leave it be. + self.onUIThreadUnlessRepoChanged(env, func() error { self.mergeAndRebaseHelper.DismissContinueRebasePromptIfShowing() return nil }) @@ -1420,8 +1424,12 @@ func (self *RefreshHelper) refForLog() (string, *git_commands.BisectInfo) { func (self *RefreshHelper) refreshView(context types.Context, env refreshEnv) { // refreshView is called from the worker goroutine that drives async - // refreshes, so bounce to the UI thread before mutating view content. - self.onUIThread(env.background, func() error { + // refreshes, so bounce to the UI thread before mutating view content. Guard + // on the generation like the model-update bounces do: if the repo was + // switched while the refresh was in flight, its model write was already + // dropped, so there's nothing fresh to render — and the captured context + // belongs to the old repo's now-replaced context tree anyway. + self.onUIThreadUnlessRepoChanged(env, func() error { // Re-applying the filter must be done before re-rendering the view, so that // the filtered list model is up to date for rendering. self.searchHelper.ReApplyFilter(context) From 4d33d9df8be770c76df29bc29f3805985c47d130 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 15:37:25 +0200 Subject: [PATCH 105/218] Mention the `Then` rule in AGENTS.md --- AGENTS.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 6aa8f7017..947add510 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,6 +256,34 @@ Follow this even when the need for the refactor is only discovered in the middle of working on the branch; suggest to the user to rewrite the history to move the refactor to an earlier commit (but don't do it without asking first). +## Don't read model state right after a `Refresh` + +A `Refresh` (or `RefreshFromWorker`) does its git work on a worker and then +*enqueues* the model update onto the UI thread. So when `Refresh` returns, the +model is **not** updated yet — the write is still queued. Reading a field +synchronously right after refreshing its scope reads the stale, pre-refresh +value (and this is true even for SYNC refreshes): + +```go +self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) +files := self.c.Model().Files // BUG: still the pre-refresh value +``` + +Put the read in `RefreshOptions.Then` instead — it's queued after the scope's +model writes, so it sees the fresh value: + +```go +self.c.Refresh(types.RefreshOptions{ + Scope: []types.RefreshableView{types.FILES}, + Then: func() error { + files := self.c.Model().Files // fresh + return nil + }, +}) +``` + +`Then` is a `func() error` and works with any non-`ASYNC` mode. + ## Integration test conventions Don't bind views to local variables. Always chain method calls directly from From 2420fc7b76f52ee67c000b0a98248c3e50b88c2d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 18:24:18 +0200 Subject: [PATCH 106/218] Lock the status list when reading it GetStatusString and HasStatus read the statuses slice without holding the mutex that addStatus and removeStatus take when they mutate it. The readers run on the spinner-render worker (which polls GetStatusString every frame) while removeStatus fires from the waiting-status and toast-expiry goroutines, so the unguarded reads race the concurrent writes. Take the mutex in the readers too. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/status/status_manager.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/gui/status/status_manager.go b/pkg/gui/status/status_manager.go index 2f822c1ee..414568a69 100644 --- a/pkg/gui/status/status_manager.go +++ b/pkg/gui/status/status_manager.go @@ -70,6 +70,9 @@ func (self *StatusManager) AddToastStatus(message string, kind types.ToastKind) } func (self *StatusManager) GetStatusString(userConfig *config.UserConfig) (string, gocui.Attribute) { + self.mutex.Lock() + defer self.mutex.Unlock() + if len(self.statuses) == 0 { return "", gocui.ColorDefault } @@ -81,6 +84,9 @@ func (self *StatusManager) GetStatusString(userConfig *config.UserConfig) (strin } func (self *StatusManager) HasStatus() bool { + self.mutex.Lock() + defer self.mutex.Unlock() + return len(self.statuses) > 0 } From 1268a589d6996e3fac012907203efc59ab0936f1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 08:27:35 +0200 Subject: [PATCH 107/218] Write the command log on the UI thread LogAction and LogCommand are called from git worker goroutines (every command a worker runs logs itself, and controllers log an action before kicking off their worker), where they set the Extras view's Autoscroll flag and append to GuiLog while the UI thread reads both when it lays out and draws the view. Bounce the writes onto the UI thread instead. Use the background variant so the bounce doesn't count towards lazygit being busy: writing the command log is incidental display work, and a foreground task would let an in-flight log write refuse a concurrent repo switch (the same reason view-buffer renders and toasts are backgrounded). Ordering between successive log calls is preserved by the bounce FIFO. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/command_log_panel.go | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/pkg/gui/command_log_panel.go b/pkg/gui/command_log_panel.go index 8f2e06b98..6f7976c3e 100644 --- a/pkg/gui/command_log_panel.go +++ b/pkg/gui/command_log_panel.go @@ -27,10 +27,20 @@ func (gui *Gui) LogAction(action string) { return } - gui.Views.Extras.Autoscroll = true + // LogAction and LogCommand are called both from the UI thread and from git + // worker goroutines, so bounce the writes onto the UI thread: they touch the + // view's autoscroll flag and the GuiLog slice, which the layout/draw code + // reads. Ordering between successive log calls is preserved by the FIFO the + // bounce enqueues onto. It's a background bounce because writing the command + // log is incidental display work that must not count towards lazygit being + // busy (otherwise it could block a repo switch). + gui.onUIThreadBackground(func() error { + gui.Views.Extras.Autoscroll = true - gui.GuiLog = append(gui.GuiLog, action) - fmt.Fprint(gui.Views.Extras, "\n"+style.FgYellow.Sprint(action)) + gui.GuiLog = append(gui.GuiLog, action) + fmt.Fprint(gui.Views.Extras, "\n"+style.FgYellow.Sprint(action)) + return nil + }) } func (gui *Gui) LogCommand(cmdStr string, commandLine bool) { @@ -38,17 +48,23 @@ func (gui *Gui) LogCommand(cmdStr string, commandLine bool) { 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)) + + // See the comment in LogAction: bounce onto the UI thread since we may be + // called from a git worker, in the background so it can't block a repo switch. + gui.onUIThreadBackground(func() error { + gui.Views.Extras.Autoscroll = true + + gui.GuiLog = append(gui.GuiLog, cmdStr) + fmt.Fprint(gui.Views.Extras, "\n"+textStyle.Sprint(indentedCmdStr)) + return nil + }) } func (gui *Gui) printCommandLogHeader() { From cbf220c49781bb78f96820b24b68b8e76a3d025b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 19:12:49 +0200 Subject: [PATCH 108/218] Read lines based on scroll position instead of a fixed per-notch delta When scrolling a lazy-loaded view (a diff in the main view, the command log, etc.), we top up the view's line buffer by reading more lines from the still-running task. This was driven by asking the task to read a fixed number of *additional* lines on every scroll event, which had two problems: - It was decoupled from the scroll position. Scrolling down, back up, and down again re-read lines that had already been read, so the buffer crept towards the end of the input regardless of where the user actually scrolled. - A single wheel notch only bought a single notch worth of runway, so fast scrolling constantly outran the reader and had to wait for the next read (and re-render) on every notch. Make ReadLines take an absolute target total instead of a delta: the task tracks how many lines it has read and only reads the shortfall, so requests are idempotent. Callers now ask to fill the viewport at the current scroll position plus a few screenfuls of read-ahead, which gives scrolling enough runway to stay smooth. The four call sites all wanted the same "fill this view" computation, so consolidate them into a single ReadLinesToFillView helper. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/vertical_scroll_controller.go | 8 ++----- .../controllers/view_selection_controller.go | 7 +----- pkg/gui/global_handlers.go | 8 ++----- pkg/gui/gui.go | 17 +++++++++++++ pkg/gui/gui_common.go | 4 ++++ pkg/gui/layout.go | 13 ++++++---- pkg/gui/types/common.go | 4 ++++ pkg/tasks/tasks.go | 24 +++++++++++++++---- 8 files changed, 58 insertions(+), 27 deletions(-) diff --git a/pkg/gui/controllers/vertical_scroll_controller.go b/pkg/gui/controllers/vertical_scroll_controller.go index 1db9bb76e..84e312c1d 100644 --- a/pkg/gui/controllers/vertical_scroll_controller.go +++ b/pkg/gui/controllers/vertical_scroll_controller.go @@ -66,12 +66,8 @@ func (self *VerticalScrollController) HandleScrollUp() error { } func (self *VerticalScrollController) HandleScrollDown() error { - scrollHeight := self.c.UserConfig().Gui.ScrollHeight - self.context.GetViewTrait().ScrollDown(scrollHeight) - - if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { - manager.ReadLines(scrollHeight) - } + self.context.GetViewTrait().ScrollDown(self.c.UserConfig().Gui.ScrollHeight) + self.c.ReadLinesToFillView(self.context.GetView()) return nil } diff --git a/pkg/gui/controllers/view_selection_controller.go b/pkg/gui/controllers/view_selection_controller.go index 31cbd3695..1a97a9a30 100644 --- a/pkg/gui/controllers/view_selection_controller.go +++ b/pkg/gui/controllers/view_selection_controller.go @@ -50,17 +50,12 @@ func (self *ViewSelectionController) GetMouseKeybindings(opts types.KeybindingsO } func (self *ViewSelectionController) handleLineChange(delta int) { - if delta > 0 { - if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil { - manager.ReadLines(delta) - } - } - v := self.Context().GetView() if delta < 0 { v.ScrollUp(-delta) } else { v.ScrollDown(delta) + self.c.ReadLinesToFillView(v) } } diff --git a/pkg/gui/global_handlers.go b/pkg/gui/global_handlers.go index 3c4896af4..a5e59a84e 100644 --- a/pkg/gui/global_handlers.go +++ b/pkg/gui/global_handlers.go @@ -17,12 +17,8 @@ func (gui *Gui) scrollUpView(view *gocui.View) { } 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) - } + view.ScrollDown(gui.c.UserConfig().Gui.ScrollHeight) + gui.readLinesToFillView(view) } func (gui *Gui) scrollUpMain() error { diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index d77673e9c..1e6e8f9c3 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -691,6 +691,23 @@ func (gui *Gui) getViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferM return manager } +// When scrolling a lazy-loaded view, we read enough lines to fill the viewport +// plus this many extra screenfuls, so that further scrolling has some runway +// and doesn't have to block on reading (and re-rendering) more lines on every +// wheel notch. +const scrollReadAheadScreenfuls = 3 + +// readLinesToFillView reads enough lines into the view's buffer to cover +// everything currently scrolled into view, plus a few screenfuls of read-ahead. +// Reading is idempotent (see ViewBufferManager.ReadLines), so if the buffer +// already extends far enough this does nothing. +func (gui *Gui) readLinesToFillView(view *gocui.View) { + if manager := gui.getViewBufferManagerForView(view); manager != nil { + viewportBottom := view.OriginY() + view.InnerHeight() + manager.ReadLines(viewportBottom + scrollReadAheadScreenfuls*view.InnerHeight()) + } +} + func (gui *Gui) initialWindowViewNameMap(contextTree *context.ContextTree) *utils.ThreadSafeMap[string, string] { result := utils.NewThreadSafeMap[string, string]() diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index c8de7545d..69ec44781 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -165,6 +165,10 @@ func (self *guiCommon) GetViewBufferManagerForView(view *gocui.View) *tasks.View return self.gui.getViewBufferManagerForView(view) } +func (self *guiCommon) ReadLinesToFillView(view *gocui.View) { + self.gui.readLinesToFillView(view) +} + func (self *guiCommon) State() types.IStateAccessor { return self.gui.stateAccessor } diff --git a/pkg/gui/layout.go b/pkg/gui/layout.go index 6f7dc7187..de3bdbe9b 100644 --- a/pkg/gui/layout.go +++ b/pkg/gui/layout.go @@ -37,13 +37,18 @@ func (gui *Gui) layout(g *gocui.Gui) error { if prevMainView != nil { prevMainHeight := prevMainView.Height() newMainHeight := viewDimensions["main"].Y1 - viewDimensions["main"].Y0 + 1 - heightDiff := newMainHeight - prevMainHeight - if heightDiff > 0 { + if newMainHeight > prevMainHeight { + // The main views have grown taller, so make sure enough lines are + // loaded to fill them. The views haven't been resized yet at this + // point, so we can't rely on their current height; compute the target + // total from the new height instead. (Reading past the actual content + // is harmless: ReadLines stops at the end of input.) + linesToRead := prevMainView.OriginY() + newMainHeight if manager := gui.getViewBufferManagerForView(gui.Views.Main); manager != nil { - manager.ReadLines(heightDiff) + manager.ReadLines(linesToRead) } if manager := gui.getViewBufferManagerForView(gui.Views.Secondary); manager != nil { - manager.ReadLines(heightDiff) + manager.ReadLines(linesToRead) } } } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 4ced8bd79..08ff53bb0 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -58,6 +58,10 @@ type IGuiCommon interface { // return the view buffer manager for the given view, or nil if it doesn't have one GetViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager + // read enough lines into the given view's buffer to fill it at its current + // scroll position, plus some read-ahead for smooth scrolling + ReadLinesToFillView(view *gocui.View) + // returns true if command completed successfully RunSubprocess(cmdObj *oscommands.CmdObj) (bool, error) RunSubprocessAndRefresh(*oscommands.CmdObj) error diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 26145c784..bc08013ed 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -82,7 +82,11 @@ type ViewBufferManager struct { } type LinesToRead struct { - // Total number of lines to read + // The total number of lines the task should have read once this request is + // satisfied. This is an absolute count from the start of the task, not a + // delta: the task keeps track of how many lines it has already read and only + // reads the shortfall, so a request for a total at or below what has already + // been read reads nothing. -1 means read all the way to the end. Total int // Number of lines after which we have read enough to fill the view, and can @@ -119,10 +123,14 @@ func NewViewBufferManager( } } -func (self *ViewBufferManager) ReadLines(n int) { +// ReadLines asks the task to ensure it has read at least totalLines lines in +// total. Because the count is absolute rather than a delta, repeated requests +// (e.g. as the user scrolls down, back up, and down again) don't re-read lines +// that have already been read: the task only ever reads the shortfall. +func (self *ViewBufferManager) ReadLines(totalLines int) { if self.readLines != nil { go utils.Safe(func() { - self.readLines <- LinesToRead{Total: n, InitialRefreshAfter: -1} + self.readLines <- LinesToRead{Total: totalLines, InitialRefreshAfter: -1} }) } } @@ -283,6 +291,11 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix } } + // The total number of lines we have read so far. Requests specify an + // absolute target total (see LinesToRead.Total), so we compare against + // this to work out how many more lines, if any, we still need to read. + linesRead := 0 + outer: for { if stopped() { @@ -297,7 +310,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix linesToRead.Then() } } - for i := 0; linesToRead.Total == -1 || i < linesToRead.Total; i++ { + for linesToRead.Total == -1 || linesRead < linesToRead.Total { if stopped() { callThen() break outer @@ -331,8 +344,9 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix } writeToView(append(line, '\n')) lineWrittenChan <- struct{}{} + linesRead++ - if i+1 == linesToRead.InitialRefreshAfter { + if linesRead == linesToRead.InitialRefreshAfter { // We have read enough lines to fill the view, so do a first refresh // here to show what we have. Continue reading and refresh again at // the end to make sure the scrollbar has the right size. From 73d7b443ec2a534aa14ada8092900d0a3d941c64 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 19:15:45 +0200 Subject: [PATCH 109/218] Render content-only when a task reads more lines into a view Reading more lines into a lazy-loaded view (e.g. a diff being scrolled) never changes the window layout, and after the first screenful it doesn't even change the visible content - the new lines land below the viewport, so the only thing that changes on screen is the scrollbar thumb. Yet each read triggered a full render: a layout pass plus a redraw of every view. On a slow terminal that full-screen repaint on every read is a big part of why scrolling through a not-yet-fully-read diff stutters. Route the task's refresh through a content-only render instead. It skips the layout pass and only redraws the views whose content changed, leaving tcell's cell-level dirty tracking to emit just the cells that actually differ (in the steady state, the scrollbar column). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/tasks_adapter.go | 7 ++++++- pkg/gui/view_helpers.go | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index dd7999107..acad4fb75 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -118,7 +118,12 @@ func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager { view.Reset() }, func() { - gui.render() + // As the task reads more lines, the only thing that changes is the + // view's content (and its scrollbar); the window layout doesn't. So a + // content-only render is enough, and it's much cheaper than a full + // layout-and-redraw on every read - which matters a lot when reading + // a long diff, where reads happen repeatedly as the user scrolls. + gui.renderContentOnly() }, func() { // Need to check if the content of the view is well past the origin. diff --git a/pkg/gui/view_helpers.go b/pkg/gui/view_helpers.go index 453ccd6c9..d139984fa 100644 --- a/pkg/gui/view_helpers.go +++ b/pkg/gui/view_helpers.go @@ -121,6 +121,14 @@ func (gui *Gui) render() { gui.c.OnUIThread(func() error { return nil }) } +// renderContentOnly triggers a re-render that skips the layout pass and only +// redraws the views whose content changed (relying on tcell's cell-level dirty +// tracking to emit just the cells that actually differ). Use it when only a +// view's content changed, not the window layout. +func (gui *Gui) renderContentOnly() { + gui.c.OnUIThreadContentOnly(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. From 585c7f126d7fe48a9992f3a1d5ae928712186b9a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 22:29:31 +0200 Subject: [PATCH 110/218] Cache each line's wrapping so scrolling doesn't re-wrap the whole buffer refreshViewLinesIfNeeded re-wrapped every line of the buffer whenever the view was tainted. That's cheap for short content, but scrolling a long diff calls it constantly: adjustDownwardScrollAmount queries ViewLinesHeight on every scroll event, and each newly-read line taints the view, so every notch re-wrapped the entire buffer. Wrapping measures each cell's width (uniseg) and allocates per line, so once you'd scrolled far enough down the diff, scrolling turned sluggish - the cost grew with how much had been read. (A CPU profile of scrolling deep in a long diff put 77% of the time in lineWrap, reached almost entirely via ViewLinesHeight rather than draw.) Cache each line's wrapped result on the lineType, keyed by the width it was wrapped at, and only re-wrap lines that have actually changed since the last refresh. A firstDirtyLine index, updated in the same three places that set `tainted` (write, clearViewLines' callers, SetHighlight), marks the lowest line that might have changed; lines below it with a matching cached width reuse their cached wrapping. The cache lives on the line, so it's freed with the line when the view's content is replaced (e.g. selecting a different commit) - it doesn't accumulate across a session. The wrapping cost per scroll now scales with the number of lines just read, not with the total size of the buffer, so scrolling stays smooth no matter how far down you are. Co-Authored-By: Claude Opus 4.8 (1M context) --- cpu.out | Bin 0 -> 22717 bytes pkg/gocui/view.go | 120 ++++++++++++++++++++++++++++++---------------- 2 files changed, 79 insertions(+), 41 deletions(-) create mode 100644 cpu.out diff --git a/cpu.out b/cpu.out new file mode 100644 index 0000000000000000000000000000000000000000..24b4b40a40f2809d660809ebf24b5b82fa20ca33 GIT binary patch literal 22717 zcmV*WKv};ZiwFP!00004|Ga&7oK!{f_^4DjQP|%5k);k zJ;38U&)XYzAIr$>%s4YkxbVFtC{faqBuLIVM->16Yn>V`)#|*c3 ze<;20)vKFkjX#O@UyCQ~SKV2R zK>N;1dUCge5#IG4PO>X8!X4ny()7;vxU(3ALDy!9_mrP|P`s!7Hn>eo(>Fip&SDBI zXf<2BS9nLac&~53VDC&SDO@HfO1L@8Fjd z@!r8JK_#uSzEW{!aKe$$bO)h|>TqYVG${UTn1D~?dnJ4tuL4!H4E-C$oyBg0Ndu>g z_qXve^8IZ*6EZcfkH+^5PJSxiGv1wWlAX>N&w?zC>-F7P>~=UhYMl7|c77ILS7Ntw zCpa~izLvPNSUR-nCf}#?neu%)zXR^j?$iepcNVJz!}^RB-&f)%ZWF_)#P5Q;w7d0# zx4E-eWtcTwzOT$LRub>k`3O0BCw~wg z)ZBV6#O{K<1DE$f>@NO>!0zG?!9!YA{devxb_X0?HC}vu2j3>YzJosu4{O!*t;oAO zVNja|;{BccV|<^^?&QCMUun7?adUPT96j`Z4|It6x{ud@8d^=gH;VHwVBXKG#QR_HK~h|Q!M)(sYU+JZT~>ctnt_rK($sKEbA{scUsJ*khR?kx5IOj{`5Kft@o_Yd%= z;3@4%y#v12;J^im{};T!!f_fNgih_G5NLdtDo|?tX?R-G^qr_N+|X`}eE%RnD~I$T ze+Hh>H2sXj>9Y8he(!z1xc`?AX!k#eYTzL_wHdkOU~b+4=e81a^Jn2%Ek|#IomPcW zTds(4JjDCT_Yd)3!>_gH^gj6hVVHG5zOTwp$oEzG^YFa(oPHeNSA$tU&+UVf`!Js) z-#^S>fETpi=u=QKe+4JE<9n4=Xi{ztw)D=eV<&4khc__r8(l4RhSBFdU<$IkEkn2L{FTqP%Exk9s&xX@qebI(eoy_WuaKCRzFje+6FA>geZDN*;sFC*=D_`A_ow zqx@BPRjZ@_=y2X)vAohlRUfYQE4_O5Bac4j=F9`5+MsGx*<<{9G3LkkYw()(y8eWl zvmBV#TE6x0Ux~LK{yX@c_PYMCJB!tTC1VeZ`N-kN<%n|l8}NqqrhW`ZR1=mQ`Ch!Q z!7s=W)!=oZuJ)#W9_Pagm(F}A-q+-NW6W%YC%amG&(B#E%%5K|CTp`Mp~Z!m^+KT1e0c55MRH@x69sN%y$lCVtP@|q#QVs;U*ZK&pf%BZ;#9u^(@IW>rBj=K zB9~@u?gzj2p}q?ZZXGz#PQHJc&yxoEW!@B;Y9H#e@cpYWYtLEn{VV*cT>7u@00gu; z`uDfHv)F5Jse^o9hZoE5>+nJ-)avNF)7)9?bvS=nF3nf@nl!=tS9uVES{;27zW*I` z>bO;?hS&H8`Tc7=1R*V~cfE3*=i~SKw zK9@-Tz-LJ$f8cEiv=vCURdI5z@Zxr(GSY9WSHHo#e`xqecNTjOid!!eJvZdjkoi?u zL;f*=kBRmP(a{_H6I>fCy}dv3i#WO}?2o)1fp$c@TVI#%&SLMw^0>cvo^f1He}?-U%-kv~vqIDp;=H~1JIN44D{E7cU0Q`w}B+yX+-099@e}Q@XqD5@?iT=36aakAwMg#T;7d9H-xC?&SLq{sfPqe=WB^zmI0f$ zHAG$l6-s$cALR`yo5jr(Rvbn7&4;(P9K#Z zjrdv#(unsW&`W@Ie3)V}B0BZep@`!gLPTNMP853wE93*@DlX*12n-|IlX^cCu^5coCLx0S6A2OI!wC#Wh>sOF zXGPF|;o{z?5JTo1g!l*oBZxMV=uf#hYX*}xN`SDrw!(ZAfl)*oP4xTRoHd7Q+a)l?Xst%@rmL(ue^HFCIiEsciqJ;Cbvs!xflm7_2?=Y# zJIbkT!KV_Kijyy_L@NSaJ4+<*@!xXdcCyw4&c}Vc3#xe5hCrW9qr@_7$@`$QP=&SR z(+EsMwe=}_@@)xh?|_R)Wq;#^Vnl!A(+Nx`np^PtV*=Bzp#!I~zw_4wz~A`{0y7W* z9hOfB%<3uqzki5*YGw8hK9j&qqE*!&aywZ&0++r*3=Z~Bz8aZQh5eJyA~1_+)$~~WT_V)Mzj#Bzw}0_D1m+NJF42GQtZq%P z=E?cTKmYGv#iSMa;4itYNgL9Zd`vze?MQplf#4c;v5o|ar=uxPW5tAbkqWq&@OcF0 z5iL#cqPktI6M@rL=Jw?7G}emn6-ZSkw&oLDng~UffsHQ- zd?|qb;&!o53G5w%yTLTphVWj9DFa&z2rMAlLZauoovaIic|#D$!P*jzTlx%aEF!Q- zz`WpgvaSRUEtN1I6XAMhU}G_X#Y9^|^vB#T){Q{BwkrkMpAg;~JIln@QUXhfwv1q0 z#L2o7*nCxPNZJv8kFY@P2>*(}S43M*bZ|Ra4+0B*k}x%;Z(h@4vfhz&BAv;nqzmav zx{>ar2N90?^_X2k;OH1Mc4@3V;d?8KzS<*4VFlXtxs}~c)|0^bxM458ofEf<^&)U- zH?lU3bs%y#pNXxN1XdEXS5pzHH-XKgFZRZ1>PUERbV)O@wTi$hqOB%+*EF|_^&zl# zu7v7D_%R99iSRW9)(EJ{2-TNBo23$}GvQs(&}U+6ErGQH>eJiYF7_FLlSd`gr-ZM; zb(M*&bp+N4sO8M&%*t4rIcRN@YB3#i7Y^*1+o@g70Uc>EV{Ru2NF1_8Zg#TG^ zrYqqa32Y?VCZfOZcCi5jt}Wl$7suC)@Xm5RyAi&bz-FRtA$lhi!+`{r%t0sz>rRB$ z%)rK00$T;p!)_=0oItxF5~c^?_lw?o5WbDTHUV?D+rq&TDWM&4ob`sc0v^sj9G`EutA+UUx+)2D5Tv_Mimh@!5 zS3-J{UZgkaL;8}>NI%k_3?Ku^=VTBWOoos|m)XgN66n->uh3$>2!BM7-HY&D1a=W^ zH_@}*PBx6d-U+(}OmD*fDPVdNzK6gbqJ2&DpxecU6Igu`CnSyaA^cMuS|+x>A@Gfu zk#@+)5vYCTl=LOMn!wbT@Vx}~iYa;6?P4PdOd8QaFzGYG2Vz(=16%tD>?2w&y>BJA zi;W_%eK7`6(pW#jr=pZ(VC!1~-y+aN=612s1P-mk-qKiq!WZ2xy6aE)eggZ67SW(OgGBp|=-AtM0;6W{6)>M$ zis*B~zbEiL(GH;^aTmB#7UW#?sl>11eSawfkqPEUIL9I{3ilGA-Dw#&6lNpKg=3+AmT>J5ho~S5B z5q<^vl!2|&1Wps}b=*}r8JgX*G9NIS@IMKvM-zUAz!{>QC3=0glg%bjvU7}ZK*kWB zEnvnFevZI7qMau~Ps}0EZpJLp*;vA-fB+gx_yqzN(1Py1+wEj?2^@_lTgKfZl=?gZ zN57V)cO2nAN%0y-_(cL2@xy(%EanqvGf4uCC;WgM%6P(mCh#)??N^-l@FHH^{qzJi zJ#!|RMP`#ZWG=jquhKT2quL^hv%V zFzGl-R2rL(v&czyCbrs8XhXHORPT@6Sx%tSC4_RY8H7ubnnC!-6h5ZfCsfGY3IhGV zN0>A=lW-9^&%{|Zg+dnrbp@f;5jgO@gqlxeG&&PoT`6=GPzR~o z$<`B?H%Nwh>hb>RVsULCaI!BxOJiRU-VMi{AzBo=QSD!P*W2ArwvoWK!7_N$fbY!U z#97VKH}@|k%g9$`Iaxtgl2v3iSwq&6b!0u+KsJ(wZYSGBpi{{n;naLdcvwvKm*|^8 zcdGTEdcf^un+XgXA>EAb1b0c!Us?EnXsX~fLcg+FABY=)|=`j)a_*32yEYuP!6_;@Mi_FiwN&S zp%2yiQvFG{i)|;ccaL1%6A0f}nG>*#r%}{Bb;bh+s=(|}meVMhfSVs6j z3Ihex?{vG^UII%dAxs)h8irEcF1C-r(UF(LoPI_4NDQ20V(W7XpNnA+%5=Nfw*(Fh zl~BtGZ!Mvg6F!K-AOY1X)9qyY2`m{XUB(rJ*B5iLg7Co<22*qy>$#om0D)`k770;a zN%$)QW+mZ6C=8+6P^!P|cCv#6POg$LtB43+WME?$g<%5bX}61gN8tSD=LFrW37?6! zCIef;DGaAt9ep^On(ql*>MViQ5Pk%WNCvh>P#A$gAEOO9L||_TYV9<(mhi#S&s$6Q zND3nnXy9#b7duQ~Sa%6DfbdSYarCPxFW$BE_Vny;$lkcX?jzrl{p0{SNWLTAlSAZi zX+O`!ejqUYh?JlSgkM6@e~jPBi>GwYPp|re5c-?qI6~mq4`p#Uc=5MK?@q6JBsm;M z33MJFU-J9V;MqHcqX|p!rqmoGFuok7+j()Xv)Sp{$CAh7WXB2Y+k_J8K;gYpFxfPq z*~e31@(BW`Z2huLGC7?WFW#P$UiCzB3_3~RvaRjb;e6oJd7 zb*u9U{tI4wY|+OgJ^NJh{Bf}#2^?FC{7GZ$2%m*IBokYsD2$@oXsXY|CH)hDLH0WT z90`9sE~`J1pOPir$xahEXwS!8Vm_>iJ)O#YoFOp#$`oN=))T%3lRTN&8be`>u=y)+ z7krjL*NYNr1L0Ti682>S;bSR`6;Oxoa=X|$0(~Y(sEveg#YLTot#K5_38+E1s?QUc zH$pH&if(0I zJYc}H=~XW!C%Tsj4BjB+WD7=o1S7W)K9RyiAtx))@w-A`$yS6CtF1aG&L=tJ#fN)T zOMmn-xsvq!I-lX~6ka@U){2bu$1FcLx#2q5RRY6pZ{cZ9oH;y`7Y|$VYI?P+rW0@z zo;ley0!wWq&k7`FTCm!+WRVn87`{WYL;5Yw980HGE2h#Nxd|mM){4UDa@yUr6IEML z+&$bBM{5e5cOfBZY%AeiCan)#>|+X(%Z<(ynW`TrH@Z(KEVX5GB~tXHHCc~- zLX#Iew~Mu-u%jHVJ9u&1NxA8dwo46HdkP2bb+<{bJ5z|NwohhkPS$}!=l+Yt7Jj=G zSlmwd6be(QHkInQN$yDD&{`Rn-9dO~=|t}!d>Vym6w{EWacy>@FfN{v-i2GqyDUGj zN(b7JcA^c$=HQQRC+kdM@QnnwbFzZ_DTU6q(HMY6qoyVP`lrxFa&4=`iSuP^R-Z$g(Sw%ITeBKH zDHPkIM4jP$+CuH=nd&<4MPYt9|I*}q)n3W01sCg0p|kBil}Ldyap=916(}d`Lt#K! z={A>TwLUaSwcMA&_z}`!o=EsH+_pVpvB%w)F1VRoJK1LxPHjU)Dt5I`mNGG)B}+y> z3Ttc~vq9>ZO1${woF~$&_DhDZPS&5osV$O_WrRN@d@^%=W%s8^Z$zAI0ENl+>XMe% zoS$j~k{!`N3cEW^6OP?3!goq-wu|r?6lPFurU(hR*yj{>mq@7H@nFtw!e>#KC7@({KC`4|+(Y=XEU`D-L-=e8v#EBs{$&;>K`2a`D1p8vd<&MLWngO#g*gb+rwS%P zD70H@)i<}5X|16Yc8`pUz)vUw&sZXmlQxikP6yG!bO`N5hTdErTx=MHZnmDoG^O)N zi+zs{OHF$Wr?Ah~y+h?vQDh;HK0NuQGJ-27zzvQ&F6m9{0kCbrAT#!?tI>=B#wJVlI0|Pb;QAC%7E|w;3QHfC{A7-&aLOh| z`n2XcuQoneVkS^HW=kpN6%(AT38_e_lTD;B+m^0h3k_)Li;2k+G>O7!n;>)9nA~}E zQYr+w7<#%_WfpHQ;gh9+>?M32g?UulMD)q%Nll@!WN17ts&nGhEcv*5GMz%Nll^qw zZN&;Q?8u=w7~*78DRi@^Bqfd%S`JV7)6qaF}d=p0F7f~2C5zAlG*dfA?I7GPM5aC}@ z_=;-FsXoWycCy737Q~BS7o>CIyw?)9tS{)7bOBvR7tzIZgPF8gLg8>(hM6n9+LB}$ zwv@usqjG6YApElQm`trxb!l=ku#7@C+c)lpCgN#p>O9L*@{JQh0&-p7bk3dZD+>Fz zpg|B}7PoNN%sq4VS2Ssd&Bc~em|ku@SeAKtGQ4oI6%>w@ofMOu)m9`sDJv<=wkO35 zVLN&8*dy6-O<|$wn=d20hTyOjHeQ`Phn;K< zg?(kYV=}nfn&i0SWNRs0+BK#pcRSc&!ha)H++o63P*_1RkMD82*g6X9+szWo@(02v zVLl}TTPrE7#AP`FlP>EiOqwczju5^OHgak5<$ zHi$5Z7?{k*n7ql}mCC?&Q`lj1+1&V=-fY#~NpRWuxFuEDiRs~+IyZYLj4#It(+cT( zlI4VpeNAEhPMl&9lf^1F=hN2C-Sc%yHpJ~>-%yygUv6Sg68@9SHJ>DWJ%#lm26zf{ z&3h@#`d&hvB7B)N%clt6Kw*P`T7+hKABFxS5X!+S^R{Rp?Z8h5`VHMn_tB)I@!wMD zX)h_caWki>+PBFrsr?k%+B`RRKqeM_f08_R*0fBtZo9%ao$dn^dY0?j+`{PxlI+^; zVh1T4wx`<+r=`pMq32+#)BPQV)89$2??)^%73vpT6gHyQw*o!v?);$Y6_R^RNI=nIdT5N(jl(z==byx zJxtG%c&HIm(iFzqqwS0;*_NRnQXTCP3KvF8mu({9XV6i6#3I0bB$?RCQ3`vO$Y|;r z!Uy6(r%Y^Zp|C|nQ~PJQUF;ZzVPhrKM#6_;H1$O*QTFsvdh8Y>smCcC?j_NlC48tX zPdZEZRtj51=Y6p}=>&yN6D8C}!p~F^`@oYFPWHrG2-4U&Gwqgvt!)&xQ7v6xjNbhz z3fuchpz}lod$KdIwVlFt1nPrE@<$3?M@XOxgttfMJ_B1jDC|I>9SHOjg-c&bpo@g} z#5`pNwsun3i9l^JO?jHa@>K}rU@9LbLt$qqblN5>oqi^~JARmntz8s$QEfNXyW`QS zvlK=RL19x_E`L{?Y&b_@bNr;(S(#HkPht5Fcyuz2T_U`b^aw5yzK6mdsx`rLx-NEs z!l<1R=rZABMjOAMV|Vyr?1jI6Xnn zlU3v-Jw<<{Khe|l3_VNpE1je78|Uc-dXdJDg}d0#6xN@R3-Bu8vm`sO626zhUR;1P zv7+u0g-(ZLMcp;RgJN-ABYYo)eN_9F>VI;(*kuaqH%lMsDB)x8=fruZMN;LT=_PuZ z#vPq26xxkjCVaeN%KM{|&%oAx3j3*+q4!fU{YjxDeo;h6JWb_d*C-4tmejVQd@S-I z6I%x;9H81kDof9c6__`8t8g=0QyvxMwx;|$3g1!fd#Xp=PS#3+qeCZ%`fMkkg6rBo zkdt#@byly9Jr@-F55~dv$=gu>*ah$?&0rQ;O$=WMWauM%x zaIp52hs5cX_LQHXaDr;OsD$pIz_tAnqyrUI?p3gXD;Yr^z*8#SkKSSXR#WN?BFw>^M-uRglu^F=?QJ$O{ zpDJCHuF4ILnmAcE1v4oTb`13=X+icLk=|LOotedJhFIjY0WL zW8J8{vLFLn=P8`0np+olp_C{vuOkAPXQiCKv{u}m-IVT152ZvYebC6sdMa>q()`}s z?O@$4LF`WX1qv6ac99A@*-L?=I}j#~^`Lwn@-7owKU4Tw08POu>#ab$FTN0EW+jyO z!9|>jtxFUxQSCC-JD{i5M}Z}07YL}HlwXz#wI}6QC|sf1RjU7ts<^KL>yKR#RP~}< z9^dFi`85jHs8+1#4m{+d!1=aQL_u?JD#F>>nb>NjKr2OSt;lFxKLw`ko-7txAIckv zDeXgf8wJ`3pg&`tNP$Cx<_nm<)I4g`m-4m>v{kf^6&>6zHb8;?Gt3heR3s$vLQ8xl z1==H`jaZU1NP%%~ly^{|0|HG#puq}E+9ub?Kq?bT8QAKmKt}}HOcSRy;Yo?EHN%NMS;P`q&k>DcySd@oR3*6r0Nvq%Va{kQx%xJxu4Ln zLn#jktv8hNt_pNjv~G$XaJ$$v1=bJiCN%mm%4emE;QBDiyDQLL(RwKQq1!PRq(I3` z2{oMZk*FIpu~ni#iGXT_%5jDQqgHkixJFRxkm(4@dn(XVK=r_#SVha`6JYRk~k@AId z1QRL$T!GKUr}GeMkphS2NT^Aa&y!G-C?BN2AOSTOp%yDJX}W|OL-}w?+Y$v9*ep6K zA1+m(#3p4VK6J8W3Tz*YpF7xO%JHy%1~vvOFj(|~r=P!4V9Dms#0*cN{2NKg6v~Gv zFhtRYD*7%YWVr$-Hw+R`Qz`E)V@y*iAEv-CMH{Z@y)eeKLV*Q8pmlMuX_UVuBx)Mv zBNP~+V4}6I+r?HYFzF|0-KSH2L>A;vr+lOWBhgIlsEkp61$G~iKr<*`ErDiGK1zX6 z2s8(QRx5C5oCF#``3f`_Z(1v}_Ecq>GF_RW%v5G6vz0l@TxFgzU-?4$QdyuZROTs* zl*P&tMLt`qEK|NxmMbfimC7n*b=()oVrvvAE=G@4WessW7`9hnbKFKN48tX$yEY*C=+ z*tqfi1mop)5y_U+jPF(jifx)qV`)V{w%s9vAqh+zM-?dHx*}lp8{Ks$33<(sk(j1iPE)TYMV7~$f?PXqOFS0+$<%#Fv6j*p89v?`G$IhoMwcx=yPN|^(paN%ZIEsVG zj>5&hQ($3F+~B3LnUt@Td(@efk5*u`qTP*qR44mhf&Os|dmb&UeOJPF%J)k0_Uw=X zvu|jJ4kb_aVFeDC8@{QW^ux*H`9Xo{Wr`4O=i!G`Wc-K%-E4|X>tU`r{Ya7&IiKZb zQE?3{Z%Ik(JK0eMCJUV;DxKx3H>2*=jwU6Mn4D2yzP&NVD~uC3a!g5KV|-kJ!)K?6 zF#0UYXUIcgvvAJ>V-!48J{=E*olv094^jYUQ@#R2Gnv>LtH4+VPgRJ^VNNQrdl;rP z94uFO@J_n~__%UHIVs|;$sJvCu~Q06zM*D2mCCIDs6fwRImS7Zx5m(5Cbq^YFiwo| zDth5RDKKa~MwT4x9o_|<6#Ew3AC;dJ^Tt0HJFP(HF>wop_ns!WGpAFrP)>G6fy-s} zlNmItb|yJ#$YN&|xNsG#M$p~P5~kObsO+<;xYp+sm|d0_(}rii z1vTcH&pw}u3AmuZaC_C8CumJ_vM(e*|4w#Mfi-c>DE1z9eC%SfJC7{(vjS(XS!}Mu z@tmm{i+bc|WOH)+g_~VkasAWnmlT-x$;To}JeP930yF~~;}saMXcH8@24>F`=(HMP z(%8IsVrw4d6BU>!fX3iP?1}=1CTw=w{~h7i5JOSQ;OAA z>XI_IezaEMd_RfjOUl2(6Xv!M+yGDO>)>gl!ln6A6E2|qE2r43FQ9yy0@KhGk8rwO ztgQ;?=SrZ3ln;0y7nDmZJX-kLjs!bbwTEODOM&!RbtF%~oKxP;c!q1lC@KHbW)UEW(E% zBY$a`zB^^%LL0TM`my?n+D>h+ULXyfPK(jE*Q;-xhjXzGDjY6-GBQE^bx>1qkesZe z3Vk=khxZ02&KIpdpYCYUk>VL&C+nm_x3VVIR2pbirc4sx| z4ULn1s=~ptTGdpD)jmy*8W-!LLQi||VeVwiW#H+ernr;os=}al@_LV@l=pl{2=P+N z=O{2o(bDuz4>|9%Xe?7^*i{u}hTT-?W(&a}8BaIqd9+(!8U`QE)}=#o-BiU zsL;*!SqGx|wv!h<)FhJ^PFAAAmK&L`lH{k|#d@kx{IjeASw{ImYFEwdzskaLAhsxdCM8fyr^0trQ^;VNezx7e!uzet? z6>`u{k@Qi=q>>`(tHS7Vw%hcxv-_$kq<}tCVUO(v?nObfZ(H~*6-@n9*kMb^P#j-P zOUU(pNlJ+GSxd@mv`+mTYkw7Hmpk}ru9~X-)g+Q4E;c}g+2ve+i?svP6kPv-Dh%Ew z!-QLjEZnz8H&9JEkM+3WigLWN zJ_8%`6qqM6=XgigU=?#BVJIerhO02{8$4W@##T|jUnaCxQNB=tg<`9<5wF)9p+cvgm@9X%-}AG# zbCU4;5yRBs>Ik*LyLdmjlZ{lNZ~UnHPK4x^$lW&5gmSS_DxA6D;uw|u;xG+c4J_hJ zX=ChSqgCizZf|bxh4j&Ck{aB_#;7p3jA^pVEyt)SQZ-hEQ#Lld2O`1S8JmisbFpzM z4Br`FaAl16xKxe!colkiHNYP%`yQ9xO zQH9kT=ZJ8@8p^vqFFc1elrL6bF?tRs@Up*2Dh%2pf!0z!T>`D8e2D@}5NPW2c)U=B zVc*GGzjc(4|E0jRj`F1nEJdI*_hS}Wh2?7`&{4t{-^Ypb9!q-p1a+c1Nu8`tQR78{ zQ&s4D0L^I{J4tv~2Pe*_EcnN!s-jpsxosMzmQ@&R>oYURVhVWnw50W!+r_4&gU!`@6mD<#HBWI@;1;?o4AAyu*~_oRw3bKt{hTKXq5Tx^~S?Z?j+3uz#dU`a56&9(mef=U~j8_s79r0KkczB*VUv2n>`lY%+U8pWnZ+LgxViiu=7QhVp zn+r}~oTLRvQ1%^CRrX6%XuDo2=ygO!Fzt1^B$XAvRE5ho^z@b{vBVP64yemh*j2mO zG8HD5Q(UGc&0dzuFuqb@jjd0+p+2=Uw_izpnp`|Li!E1SL%b-UsfY`ju5b2oHR%EX z7h9o1ds~^BaX|~yisY54i>*{)bh+s^wQ2UsRQR+?g=6I;*Tkf+Qj_*wR;#eVbP=~v z-cD{Bw^6=UfwjU#`~>S^*Ql_!m$Y&-Dc^dVs19GN!mPpg(82!5Ps_st>r^;BJiaOX z0XK!VJg-*QsB6{tGu9=uIb5$o-!jgI?NqH#)pgmR!iG_Cy2NE6_GWd%P3cLfp0+do zH`4JNRhZmg>i9tff9oM(f3Z_4NL+=Ap0~b-P7{*&kz} zO&aS;`6Mh~a%!Px2kx*%rTYyu(4HvtqR@&f1lgQ_Np-I^SDU8%}Ihleyx6^?)^7nWnX72PjX*> zW}R%G3f&GY5rN-tD2Cv(GqABufo+PmUDlU>tHMcJJNH5D?6sIueV_WR)Xz8dt88(z zE_}K!Q3)#|@o?&OVcjmaUxh>Ky7l7jG`5%WZ_u~M#MTZ4b|~6TMgJO;ZU38~yi`7Q-^DcWvDe-Td$s&H*B{dC3GUp=56RKHWdS6?mtTMdU) zC@$@E+bla|I^EZ0gYyMzI-bD$$I9MWd9#_p)cGq5!!NCDl9-oi*SVSIxC*D1N@H=r3^!H5 z);9`#qiFxoKXSX+2^C6KNSK3^e~H>E16z9)*o!c8(CI#@!l19^*gp{70;bJX7&iH& zP;=i={u80F;_UN}Doi>lfi_USC9Tv2;m6ez>PZ!UDC``4KjW18<8`(# zKdI3ExQu1ZC47S-OvPyx7VMM{zo)zeY0kvfw+ei#;HC0Ckiau4wEI><9isA=!ZNY7 zUxEDssx_L5vnsS3EysVD@^)CUoq??b3LHR#dJ2z)ol{|ZD+%-i zRAJh5WOo`nM)|S~p{I$FGq8o#Hz+Af zk?EIJxHeBR{R9<`e0CrYXBRDq)csvAuxoj9&uQZK7l)T`6!{9ljH^QKTB<-YbODylTHGqH7Cf#YId+Zicr<$y^CB-Cm1lv5_QPAG6f zKy{?f`>mbj9SP@kuBpY2Rt|akueAf_m%CJf$n&vPTRV~p*0*uMiW@q*Z5%h9cl(&& z$#@0j^(~F<4VAu__4?5EVWskc+UtISNo@xlETgb(^4dDAJ!~vV*8MHH)L9+u7A3HvAl(w?h3rg9>+^Pt? z5k>7BFnpKXw@e`XD>OEC;H+J8BGKLf3+*7VdDVrvRrIuXq>{-^ICg|vuv8-33CU4= z>TYVYJ2;@Pea5d$lCi^0#TifgI^ayXaJo7AM>{%_4|61>s*q`^j2(Xk&jF|GNia)! z&9z;llOx5{my>mNz!uvhdcIT&yR##yiUSw>)B*cO#p}xOM#cnR?^8z#3D_*w#R2o< zwMsQgxq4k3DFj=(I-s*n(|OE!+5TtORA_RsZVp(uMw-vFly8yl!CA^rDR4?;wzi<9 z>h6G&^%81_c~b8#Yig==b98sucQdwwiGkyGgTPC#Y!yfvc7dpdeK8uoVdaSWn;9nurMsj;z>zgQZd;)?pr0T;^f*A5VU z=12vbGshZ6HEVZuQ_a-R0ULTv6;pDN@@cBD6&EQ#tH4=BJE!Q!(7);LfCc*`)X(zF zT6PAu&MR#OVTq%{}`drR;a+@CfVMGUv-yj3t<}Vo}Ebl>%e9_8a2VB14 zT{eT0u_r?uFlnTWC|#m_sq{rJQGQW@i;DKMqJM`vWhm+t>04elD-AQTbxDCs!na(9 zrG~>CFl)Ai>O}arxGA#lLU?a27SIoI40Q~1BzlR%9WdCgPuYzM(hji>cO+ZslJJpm zT9VopxLs_71J;yr%Ivbn5y?x{NCzw}Hw@D*XOB#J7+6W*fYBr3R_qWm#I_itQn46W zY_tQW$F0~SoFurBqaA-rCUl*U{*6~?e38Vjd^qiUXMR%Gl67P~!Fq~>X%a^&lEY;? zq@qr^RM_X=JEYb{o;Pwx$2j1yeU;NN{Mj?RfO3rERxfE9>wqnGg**P3cfuTwO<@l2 zbuq$=i--2)P+WX;0M{=o&k*nb^WGNq6@~*w)a%F#6$N8nB`;j$trYYHLs26y6wHr$ zt3--|F@K@qY3^%kguTDc358=hO+tl6qlnQwr?wFY_#!z4p`4l??^B*9asvKFMhhb^ zCmPAii4+B6{z4-s90}!l3PN62L_Y8ogra#(jQrON!vU|$!e0;yM+~Dd9Lp{Aa_eEx zXdaFE@|t>|yM=zmm!5)XF;srNUxfX^2#%=JYIpL)U*^?Lomm=Ov30y!q` z9A7L{=+E=$+3yCUzQ)EoApud{Q$H4p7;l9dzT|x)g+9f{<UqZ>P8mtqAGVR)6N=^-EesUx+J*Tj(D|XF z*sY*NEaHDi+xrFnSd*egp1e?D&WA=cYUCF+ZtOP#`8fgK-&z*#ib1vz=4!a`p# zKbjMY=7kCieZl;wN6*eH%zwMlhxLkrK_gP#Q?DpkE13UIB$Q`Fqi_0yM${Y1c{gfA zqB+r6)13OTra3Pg&2nBU@(1#xIRT%t_JBbwtc3`auEjK`vRkx(G;So0=^ z5qK=%E4UE_IeCToxuHfM=0=K;0s$8o=;s_w{gg)I(X$KuvD!BqMU$M0A4P#bmRp|u zcT*xir_^M~VN~~AXBz$+1F-wHrUCiiB((tuE|{X_(X;Crg`t@7W(Zekbx(m2lMh~s z_=0&&jOa@(<==1l3Jq`gzcnc)IXMwQOm09>gJVl^rTp8my=sju>S(t5640gbK37M16Dugi^Rk`Zy9dBYQ(%5jSFLF$KHtu zcP1t7HZF|igz-D1xDq0&FaB)ot(TO5#FtZ<<$%MEFLZybe#{puih6?;C(hUHSej*f zNjI#pF}!M+W59t$y}3ytE-3Qn`xyC+l#&J4dymhh! z4{Lf|(U#FXUm)O#_?nx|p!dZT)UD~L=R{jZbMt+X=KdfO#!Xxv^WUI1(`;E!yf3HF ziTSPdZ$d|Lv=PIXA25P;&y7QormwUx^1Q#jg^tj{&b6HXJIwB-k~ZCAZ)Pa!iK5oF z9;C9fHno3lI24r|48$gEfQ9YJ6sR__A>;3`+B&+ExX18CVrZzukgTWmih|xhB_%s? zC2V_(*V{Ir@9=g}EL;?eqP(Z5m6OKpeLE$hZ?HQ^AlCc)ln|DtG{Ij_L|MfW7h(ES z3Rak3=KRfUn1XHwOA10ZZsBftUrIqpOqABYap}HaxD*&635Nm!kG~)oiui*Cue|nIVO%m~K3zfS%8x;}sK%}^-peLT5uZRY_M zbc2eK!*J6AbQkbHWcI7KKuWD({%gKqe!vjhL(_Ap^&cZjk}bY)*rR9H3Wr5xq$1hk z3y1MPWXq#TjRr}%Xlz6pgfKi^KhGERzLtWSFwx``7UUKBB29A(PyxjZUxDyooaSp! zG|v}&TZVBnt!D*!FGqa-p!bDa?+(Z1E`zVGFVa+c>n|Jm{ybmI$oKxjhIy&L1`yKk z^*(!R1Yqa!L`}41G-edaG|FAq@6D#7&?w9cL`3vEY$hk7-deXpg+OGw6jASeR>xKt zT}0a73L*EscM9Wdx}?=TVSj!@pFft8IWqmxxQ&xBlQ_!eh_B2u(TB_Y&~jPD!}~2_ z^=y$@sqXOy{jt{!U-%_|EP88F(a0Yw^a&kMDouiG4D&Drkx=te{l?#jGzcyLJMmEH zYidLT{yZZkC&nC9j`$KKghylOf{8Fy{cyk^OKD{0$JW1yFvEQ25!l}H{xvE675DuM zFw|{ERdGH-g@yi@75gz-#3H`Dn0$!Qx;Op7|3PpU>G8)BB0(Qi;Fw-D%<-7PT~AH# zoBsiN3|C41NPOOk@-fl2BO@@IQ)-sPQbYU3lG;HPm& zZ>3OFkb_SINrE;lft}HC4>_!=9Lkmv1a9SQFBSByz6?@}jpmxCegkoTb*5QDLi zm;DjUx^O^6)XF` z>l$lQ!XF4l%Sib91tCwgi7#w;{K41<-uuhg+uEVRM*g6YFQYo%_fngVWFtBlEc(NL z2X%@PbkkUo_nrTM&g+JXyeS5sN||8{+P>BNdmUNT1PP}74%0*OM2vvpiyHNd@;Or* zuhet9k2gbkO}$P*Uc6uN?3omH0{FSz)gAaJrtTY>;}H0MohrUa^EmN$n+nQf&Ptt7 zq^UrfN(GgPBL~CySVel`x|EVpnlX9I1~EaWIB)uq5MXb}TDu#E^*E z=Jy{|AV-TNKg|TEFuX4(rKKf#1x0>zL_@*qIKV_A->+CA3yS=?sB=Ris**|w?(J~Q z9|}h6`oeV!L>f7mZ$!+86&Y4SR)%C>x#o5_IqM`jX;M_0OflmvV)na~MlO=55i#EK zh@MJemIb1KuVttxR-wze$e$yz;&M(UL0s1t^c5J9Iz_=e&zq92*ODENs5UTK#7v#g zAma1Kg!Bp?1!La4ij`a}ZZKNJgxboDVQ)Cvq(#H}-lJ!~>5obxTf|JNWlXuAnBt1s zmY{!*Gh@*m@JD00<{viwDaWqEp=iu3K6p2r?~55JiE@ITd8Ztr+?1w1*+LUkW~S>O zs@M)f!FOM8&;+-X?*;=#G+NIHhiW(R1q+OPv%@5-5^M`$qckxjxg4+*!b`!#c5okoWn7nJe{OzCRic_*ypi=f|3OO#SMSq`ztn$NPW(lOZIMlEBM? zkoU0!>I=#wUNMSj1Oir`Gh7s_sB+Nq9535<4kmw7BoIp)Z!(@nxG@nqO<4h1K^vtc z#$#tvQ%R1B960)QMj+tLtr%Gm+80-)%&_O?NBqqUk%dmhK3eW>Ucm50>J?!bdMX36 zJ{Jk?Bpn5$+0rE9yO$D#_r~F;Qr|VkG_z@j-wp;^+NqUrOz2CrL;1N;e?ia}NJw)T zg}&y#rbbaXrTC_~JIx6tmR-ejXTea+_z#fcRyG$2!)20Tb|tHw3hjeTXaib$@3dYQ zgv0|=g(sQv7K{)0gGR%MFYJ9IC9b25i&s|SADDTFzTWsP!^k)CQ=CHlzPbnhFR;93 z_zRlEk}Q!;a5y}A_DjB~A;h3Xth%Q`DCP@@zk)Fnr%{1x%`87f4-NGXN*Mlu)0SvF z{*46NR@iiAWi|Uf)~uG2T?}2?n`{)2XuvSSwn(7hcvC7%GW#(_F6<9B@(c3sFkc9i zSYB1n7i@aVm?OSm)7((w#>kk;iJ0xAww_(s#PEfyd&D86`e9%2mXde^33e0DAD2d4 z*B31E1rqYTMhwsDSb!|Bm>+7~*q&KEyC4svd(}OSd;woD z&#=>+W}4m3dcU3@FuaRt!t#vz3L6=boIuD^C*X_K^@Z(ta(0nF7<=Z?czih;ixlO> zw7)0jO8$*R3YE~*Xo=~HR6cn_e)3!@-$Y{(P3A^Z`m8XNpGq%vL;3#3ej}p&^8@dP z6|?%wy9MzHvGd3e6b1cxp?o8!DAxEH&&vk3(Vo5@l)hq01}71hL|70irR5|3W+8-% z8U>y@{zx=txuUfLMbVfMiT4`%Z?PbOg19S+RJs%7HUY-;m>Z%O?G5}dh>{L_LC7|m zL8CeDTuiO|+XO;ywn8j7Cu+oMH}PQ#-iX}HM~xTzy&DvoI`es7Q7j}5!(h$JZ%U;z z6FC(r3L276b#H-0U;c+h(b&tO=E3H^NPc~BIIvcsI46B8exXEw=#t$i+Gf&Zn;C&f zz~oDATqY)S8;;nFNX(z-3rJM8<7Yvto8b-lToBv5Vnj?h*`?{oX=YN9D^FhLV#Gtz zh|>09g^%r3BUTr;(Qg?vJN?@^lS!^kK{36B|3cg{qOi`l5 zhiDoDhKLw=^#ooeu7GeP6gDEUmX=bBdOxa|=`63w6S~bYyYT$0uXf&@CF@nCj zzLw@vj#rfhjpk^#ML|>?KJJ6~gZ`NCZEoP6n2IP~ju!t=ctxf3O9Gj3?!4lQ#%e|V zzMxbViMy}sf!8;Dk-R3h=kWgHABbf112>rj+XpQ$Vz1V&>x(u`DPv`NfZ`GWTp)2i z;jI8xb)7iNZu_Cgay*_c7#mMCMPp4H73DQGVz=fjh9e>2lg7Q>!gnH}#<_JRx8qL{ z%pWl1)A)wV%7VS=ixe2%hY}66C%>GruaBw8R}vWeZw!ps6cpImk%VRbb~qNboytOA zelvg6NZ?1y=(|xP|Lyv>bcm?XC^U~e;H<=}K24vX6t6$9dk~xQ zy0-spUZGLfdn+ZD5?j3LD84HohWL5y3Yb8bXZ%9@&3 zv9vbq%afs(xU6DOpv-=)@Eu>Isl9!R#zNsjn^%qf!Tfqf!Jw~Ez_3{(t{f=}7%`z6|Z=R@6-wlePNr8 z(UwuM65p<$K$Q8+ULB=MMC}zGS7=c~D8i_%>qI3ko`go-y3 zI?iQ0ax9+PedZhaMR~FM%?%@5J7VPfW4Ah|QAB~_oGDIuh%|S7QEz&Oe4xjVj$j7d z3uT|iPgKW)I!z4>l-nyIXvFXwP)f)1%!$r1zs+s>QISz36l-S^FJ!QQBPeS?Mf&&j$4BCjep7B@faF2@u7-<$=1_J4F1+-p~EHqHyi0$4vKPf%l}5*|1f z7y86Ki$bHYFw`uyqnf6cLU#ziji1#>?euG65oXjE^vC>BLzJQWf>u?hGh!4NEyC#A zz9g@3Fj6y3;`5wFzPzS*2tb4&@0Aa+qD;KS@S^$pI`8sB$g-lCk&;r9UC1NNSobXd zPUy0ZKbS9LTzDseFP7INHUC^tZgzt`JeSl0kvF1X-x#~huZ#T}QSW;dvr)u-zvv-> zuD>KjS6tyV2}NV#IDipp=Fc-c_2s`W8;x;a=nn{^F!EM3ns- z*_~W4=7z)4vtN?~HOD7Pr|^CcIo#KSjYI$8`GwN>tCvMyLAhU?@%SJUb@}ypmYzdC?%nrc*xmP#~+9pk&4U$lnHQIbjmxO zwEx7(NH)@c0}9NwgF=*C4j?{*Wdz?^eTeBlq{&wlYtkUp)Cii%3`{g6ry6cFO1#Re zG2U2nBYF5QT_q!B?wz7Qpq}wjkr9pkZ`=oOjfCx9{M@OzM~x@d@QnzbRq*XL<~=>u zEos8Z^?GW0f0wY3_R>L znmz9EM{}bXCa9>xF;*xuu_sTn$3>6fh`*UHW{6WkctvShT9B$-qtG9V8IfFH&=+X= zHzOAvD_^9dk5H8*&+Jtk&V8)ZTgj&Dk|wv!Rc{84xV`S{KK*}8P%)PF zMpGa=L))s~oS6D~K4kmD{~l8A_nO@dtk4&UHt_|#kK7bnQC_T>ko}t8YX2U%&=(H- zgE#M6MiiP|cbXC=Ky2%p-HbDZzOY5!O(ql}Z;nl{<>gSG_ulIawyu0#QNcTv z67L)?5SfeW9*la0?F)9}VNw~}6oFMqc08kmq1jrPZF;+LlGn4|*sG`;$~P>R0%fKs zYD6ol^b^JA20e=~lX*-8<^7NU;glo}<5eS8D=+46X5horkH`3fc(a`kcVG2m5pSc4 zTSCZ-1njwCU(gV%{n_M3FA8zY9Bq9ghLt19)^;a;iuIIrBECZ7mHYxDYWrDuQKCPJ zXNp7wy{27$ROXFo6XN%0mw9bRb@lAV{uTn6S;du7flEB=XoE2Z8=#?SL;DEfqtscTT1DOz(dnjjA2@lz)Ga>oNG^!%!kE2{76yoqk@R9k)6)LC()SU3)qjupO~C0l@2dkW?rVm9j|f4 zJ-ihfzYci3ItN#bD9eu1WtIumw1v%l;(a}-wH)(Bo8l%P>sw{fy?F?!x=0C$lGlp7 zidgg~|BtJvc2Y!2yDc^{SV=61Y7na94+N0xBu6TdB;>9!}M55*J5R<^x?KbTN|fY)ZmFjZlThd&rIA0>GZrmV8WlTvj;A*|<0WL#e2@s-45 z7ar>fizvFVvl5bu54?Y?7?Wc8kRmE1ZkxX$MRuWE;z^zxf}@eKj;)j zv%dWN)PlM4$1-xFv7$yo8h=?33iyHro=~J9rv)A~#;U~@9)Bn=7I-HX@&3JH`E|X{ za&CCTk8y=uf7`h!vb-wbc;e?X&PNN!OO%NgY5F;65+epv;EHyI}0r6}}& zeWdlVfAdx14TKRx3@v^+mo8GDuLtpXfK}2YZ+yB=Z2<91;kaaD{ zLk(|s7r!LSu9=QSTE1$;-fr}vt)$JW>9=e&1$nii=;PGF!l9Zrno`e&d*iirQmL1A zeYz|nkoe3hf_N@GuEsE3WOJdEX%w{s(q*ac5r5c}i$Ad}C7!lwR3M(+(lK>;?`DGp z?%z0gB@6|YQTmOthUqP%dF{gd2EJ%h!J(R-r#v;2JdlwRR$J}o`S(Z&M9Xkv`LK+m5zX_3jo0zFg2E9ahGDa? zFA_E04jL7iUlZNs$j*?+7m^ZU@s%mW)g@i82k}f}1zpD&@cpf2fj{>D0{{U3|6k=y Ir#|%n09n;AKL7v# literal 0 HcmV?d00001 diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index d93f84954..e4c5a5f98 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -50,6 +50,14 @@ type View struct { // tained is true if the viewLines must be updated tainted bool + // firstDirtyLine is the index of the lowest line in `lines` that has been + // written to or highlighted since viewLines was last refreshed, and whose + // cached wrapping (lineType.wrappedCells) may therefore be stale. Lines + // below it are unchanged and can reuse their cached wrapping instead of + // being re-wrapped, which keeps refreshViewLinesIfNeeded cheap while + // scrolling appends new lines to a long buffer. + firstDirtyLine int + // the last position that the mouse was hovering over; nil if the mouse is outside of // this view, or not hovering over a cell lastHoverPosition *pos @@ -457,6 +465,16 @@ type viewLine struct { type lineType struct { cells cells trailingFillAttributes *trailingFillAttributes + + // wrappedCells caches the result of wrapping `cells` to `wrappedColumns` + // columns, so that unchanged lines don't have to be re-wrapped on every + // refreshViewLinesIfNeeded (which runs on every scroll event, via + // ViewLinesHeight). Wrapping measures every cell's width and allocates, so + // for a long buffer that dominates the cost of scrolling. The cache is used + // only for lines below View.firstDirtyLine whose wrappedColumns still + // matches the current width; nil means nothing is cached yet. + wrappedCells [][]cell + wrappedColumns int } // trailingFillAttributes describes the fg/bg colors that draw() should @@ -815,6 +833,9 @@ func (v *View) Write(p []byte) (n int, err error) { func (v *View) write(p []byte) { v.tainted = true + // write only ever touches lines from v.wy onwards, so any cached wrapping + // below that stays valid. + v.firstDirtyLine = min(v.firstDirtyLine, v.wy) v.clearHover() // Fill with empty cells, if writing outside current view buffer @@ -1358,48 +1379,64 @@ func (v *View) draw() { } func (v *View) refreshViewLinesIfNeeded() { - if v.tainted { - maxX := v.InnerWidth() - lineIdx := 0 - lines := v.lines - for i, line := range lines { - wrap := 0 - if v.Wrap { - wrap = maxX - } - - ls := lineWrap(line.cells, wrap) - for j := range ls { - // Per-segment trailing fill. When the source line opted in - // via '\x1b[K', the LAST wrapped segment uses those colors - // directly; earlier segments use the colors of their own - // last cell, so the trailing area matches the bg active - // where that segment ended rather than bleeding the - // '\x1b[K' bg back across color changes in the line. - var attrs *trailingFillAttributes - if line.trailingFillAttributes != nil { - if j == len(ls)-1 { - attrs = line.trailingFillAttributes - } else if len(ls[j]) > 0 { - last := ls[j][len(ls[j])-1] - attrs = &trailingFillAttributes{fg: last.fgColor, bg: last.bgColor} - } - } - vline := viewLine{ - linesX: j, linesY: i, line: ls[j], - trailingFillAttributes: attrs, - } - - if lineIdx > len(v.viewLines)-1 { - v.viewLines = append(v.viewLines, vline) - } else { - v.viewLines[lineIdx] = vline - } - lineIdx++ - } - } - v.tainted = false + if !v.tainted { + return } + + maxX := v.InnerWidth() + wrap := 0 + if v.Wrap { + wrap = maxX + } + + lineIdx := 0 + lines := v.lines + for i := range lines { + line := &lines[i] + + // Reuse the previously wrapped result for lines that haven't changed + // since the last refresh (i.e. below firstDirtyLine) and were wrapped at + // the current width. Wrapping is expensive and this loop runs on every + // scroll event, so only the lines that were actually just read (or + // re-highlighted) should be wrapped afresh. + if line.wrappedCells == nil || line.wrappedColumns != wrap || i >= v.firstDirtyLine { + line.wrappedCells = lineWrap(line.cells, wrap) + line.wrappedColumns = wrap + } + ls := line.wrappedCells + + for j := range ls { + // Per-segment trailing fill. When the source line opted in + // via '\x1b[K', the LAST wrapped segment uses those colors + // directly; earlier segments use the colors of their own + // last cell, so the trailing area matches the bg active + // where that segment ended rather than bleeding the + // '\x1b[K' bg back across color changes in the line. + var attrs *trailingFillAttributes + if line.trailingFillAttributes != nil { + if j == len(ls)-1 { + attrs = line.trailingFillAttributes + } else if len(ls[j]) > 0 { + last := ls[j][len(ls[j])-1] + attrs = &trailingFillAttributes{fg: last.fgColor, bg: last.bgColor} + } + } + vline := viewLine{ + linesX: j, linesY: i, line: ls[j], + trailingFillAttributes: attrs, + } + + if lineIdx > len(v.viewLines)-1 { + v.viewLines = append(v.viewLines, vline) + } else { + v.viewLines[lineIdx] = vline + } + lineIdx++ + } + } + + v.firstDirtyLine = len(lines) + v.tainted = false } // if autoscroll is enabled but we only have a single row of cells shown to the @@ -1599,6 +1636,7 @@ func (v *View) SetHighlight(y int, on bool) { cells = append(cells, c) } v.tainted = true + v.firstDirtyLine = min(v.firstDirtyLine, y) v.lines[y].cells = cells v.clearHover() } From d181615c315b682a2c26c89ef70ca141a0e66cc2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 11:46:19 +0200 Subject: [PATCH 111/218] Make integration tests using commits more robust Some tests assert that a specific commit subject does or doesn't occur in the main view; interactive_rebase/outside_rebase_range_select.go is an example for this, it asserts `t.Views().Main().Content( DoesNotContain("commit 06"))`. The problem with this kind of assertion and our test commit naming scheme is that the diff view begins with a "commit " line, and when that hash happens to start with "06" the assertion matched it and failed spuriously. This was usually masked by our MaxAttempts=2 that we currently use for integration tests (it's quite unlikely that the commit gets a hash beginning with "06" twice in a row). However, we want to get to a state where we can set MaxAttempts to 1, so make this more robust by changing our naming scheme. --- pkg/integration/components/shell.go | 2 +- pkg/integration/tests/bisect/basic.go | 16 +- pkg/integration/tests/bisect/choose_terms.go | 32 +-- .../tests/bisect/from_other_branch.go | 10 +- pkg/integration/tests/bisect/skip.go | 48 ++--- .../select_commits_of_current_branch.go | 26 +-- .../tests/commit/create_amend_commit.go | 24 +-- .../tests/custom_commands/selected_commit.go | 20 +- .../custom_commands/selected_commit_range.go | 10 +- .../tests/filter_by_author/select_author.go | 20 +- .../tests/filter_by_author/shared.go | 2 +- .../tests/filter_by_author/type_author.go | 8 +- .../interactive_rebase/amend_first_commit.go | 10 +- .../interactive_rebase/amend_fixup_commit.go | 26 +-- .../amend_head_commit_during_rebase.go | 20 +- .../amend_non_head_commit_during_rebase.go | 16 +- .../delete_update_ref_todo.go | 38 ++-- .../dont_show_branch_heads_for_todo_items.go | 38 ++-- ...commit_in_copied_branch_with_update_ref.go | 18 +- .../drop_todo_commit_with_update_ref.go | 46 ++-- .../drop_with_custom_comment_char.go | 6 +- .../interactive_rebase/edit_and_auto_amend.go | 20 +- .../interactive_rebase/edit_first_commit.go | 14 +- .../edit_last_commit_of_stacked_branch.go | 32 +-- .../edit_non_todo_commit_during_rebase.go | 10 +- ...nge_select_down_to_merge_outside_rebase.go | 8 +- .../interactive_rebase/fixup_first_commit.go | 10 +- .../interactive_rebase_of_copied_branch.go | 14 +- ...e_rebase_with_conflict_for_edit_command.go | 12 +- .../mid_rebase_range_select.go | 200 +++++++++--------- .../tests/interactive_rebase/move.go | 72 +++---- ...e_across_branch_boundary_outside_rebase.go | 22 +- .../interactive_rebase/move_in_rebase.go | 82 +++---- .../move_update_ref_todo.go | 38 ++-- .../move_with_custom_comment_char.go | 12 +- .../outside_rebase_range_select.go | 102 ++++----- .../quick_start_keep_selection.go | 30 +-- .../quick_start_keep_selection_range.go | 30 +-- ...vert_during_rebase_when_stopped_on_edit.go | 30 +-- .../reword_commit_with_editor_and_fail.go | 14 +- .../interactive_rebase/reword_first_commit.go | 10 +- .../interactive_rebase/reword_last_commit.go | 8 +- .../reword_last_commit_of_stacked_branch.go | 22 +- .../reword_you_are_here_commit.go | 20 +- .../reword_you_are_here_commit_with_editor.go | 18 +- .../interactive_rebase/show_exec_todos.go | 18 +- .../squash_down_first_commit.go | 10 +- .../squash_down_second_commit.go | 14 +- .../interactive_rebase/squash_fixups_above.go | 22 +- .../squash_fixups_above_first_commit.go | 12 +- .../squash_fixups_in_current_branch.go | 12 +- .../view_files_of_todo_entries.go | 6 +- ...commit_in_last_commit_of_stacked_branch.go | 28 +-- pkg/integration/tests/ui/accordion.go | 30 +-- .../mode_specific_keybinding_suggestions.go | 4 +- 55 files changed, 711 insertions(+), 711 deletions(-) diff --git a/pkg/integration/components/shell.go b/pkg/integration/components/shell.go index 70b12146a..72cc3d95c 100644 --- a/pkg/integration/components/shell.go +++ b/pkg/integration/components/shell.go @@ -256,7 +256,7 @@ func (self *Shell) CreateNCommitsStartingAt(n, startIndex int) *Shell { fmt.Sprintf("file%02d.txt", i), fmt.Sprintf("file%02d content", i), ). - Commit(fmt.Sprintf("commit %02d", i)) + Commit(fmt.Sprintf("commit-%02d", i)) } return self diff --git a/pkg/integration/tests/bisect/basic.go b/pkg/integration/tests/bisect/basic.go index dbce50969..fda3c11a0 100644 --- a/pkg/integration/tests/bisect/basic.go +++ b/pkg/integration/tests/bisect/basic.go @@ -34,29 +34,29 @@ var Basic = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). - SelectedLine(Contains("CI commit 10")). - NavigateToLine(Contains("CI commit 09")). + SelectedLine(Contains("CI commit-10")). + NavigateToLine(Contains("CI commit-09")). Tap(func() { markCommitAsBad() t.Views().Information().Content(Contains("Bisecting")) }). SelectedLine(Contains("<-- bad")). - NavigateToLine(Contains("CI commit 02")). + NavigateToLine(Contains("CI commit-02")). Tap(markCommitAsGood). - TopLines(Contains("CI commit 10")). + TopLines(Contains("CI commit-10")). // lazygit will land us in the commit between our good and bad commits. - SelectedLine(Contains("CI commit 05").Contains("<-- current")). + SelectedLine(Contains("CI commit-05").Contains("<-- current")). Tap(markCommitAsBad). - SelectedLine(Contains("CI commit 04").Contains("<-- current")). + SelectedLine(Contains("CI commit-04").Contains("<-- current")). Tap(func() { markCommitAsGood() // commit 5 is the culprit because we marked 4 as good and 5 as bad. - t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit 05.*Do you want to reset")).Confirm() + t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit-05.*Do you want to reset")).Confirm() }). IsFocused(). - Content(Contains("CI commit 04")) + Content(Contains("CI commit-04")) t.Views().Information().Content(DoesNotContain("Bisecting")) }, diff --git a/pkg/integration/tests/bisect/choose_terms.go b/pkg/integration/tests/bisect/choose_terms.go index 51c9246ba..5e3b0ed27 100644 --- a/pkg/integration/tests/bisect/choose_terms.go +++ b/pkg/integration/tests/bisect/choose_terms.go @@ -34,40 +34,40 @@ var ChooseTerms = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). - SelectedLine(Contains("CI commit 10")). + SelectedLine(Contains("CI commit-10")). Press(keys.Commits.ViewBisectOptions). Tap(func() { t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(Contains("Choose bisect terms")).Confirm() t.ExpectPopup().Prompt().Title(Equals("Term for old/good commit:")).Type("broken").Confirm() t.ExpectPopup().Prompt().Title(Equals("Term for new/bad commit:")).Type("fixed").Confirm() }). - NavigateToLine(Contains("CI commit 09")). + NavigateToLine(Contains("CI commit-09")). Tap(markCommitAsFixed). SelectedLine(Contains("<-- fixed")). - NavigateToLine(Contains("CI commit 02")). + NavigateToLine(Contains("CI commit-02")). Tap(markCommitAsBroken). Lines( - Contains("CI commit 10").DoesNotContain("<--"), - Contains("CI commit 09").Contains("<-- fixed"), - Contains("CI commit 08").DoesNotContain("<--"), - Contains("CI commit 07").DoesNotContain("<--"), - Contains("CI commit 06").DoesNotContain("<--"), - Contains("CI commit 05").Contains("<-- current").IsSelected(), - Contains("CI commit 04").DoesNotContain("<--"), - Contains("CI commit 03").DoesNotContain("<--"), - Contains("CI commit 02").Contains("<-- broken"), - Contains("CI commit 01").DoesNotContain("<--"), + Contains("CI commit-10").DoesNotContain("<--"), + Contains("CI commit-09").Contains("<-- fixed"), + Contains("CI commit-08").DoesNotContain("<--"), + Contains("CI commit-07").DoesNotContain("<--"), + Contains("CI commit-06").DoesNotContain("<--"), + Contains("CI commit-05").Contains("<-- current").IsSelected(), + Contains("CI commit-04").DoesNotContain("<--"), + Contains("CI commit-03").DoesNotContain("<--"), + Contains("CI commit-02").Contains("<-- broken"), + Contains("CI commit-01").DoesNotContain("<--"), ). Tap(markCommitAsFixed). - SelectedLine(Contains("CI commit 04").Contains("<-- current")). + SelectedLine(Contains("CI commit-04").Contains("<-- current")). Tap(func() { markCommitAsBroken() // commit 5 is the culprit because we marked 4 as broken and 5 as fixed. - t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit 05.*Do you want to reset")).Confirm() + t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit-05.*Do you want to reset")).Confirm() }). IsFocused(). - Content(Contains("CI commit 04")) + Content(Contains("CI commit-04")) t.Views().Information().Content(DoesNotContain("Bisecting")) }, diff --git a/pkg/integration/tests/bisect/from_other_branch.go b/pkg/integration/tests/bisect/from_other_branch.go index 24e49104b..b65c88594 100644 --- a/pkg/integration/tests/bisect/from_other_branch.go +++ b/pkg/integration/tests/bisect/from_other_branch.go @@ -24,17 +24,17 @@ var FromOtherBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). TopLines( - MatchesRegexp(`<-- bad.*commit 08`), - MatchesRegexp(`<-- current.*commit 07`), - MatchesRegexp(`\?.*commit 06`), - MatchesRegexp(`<-- good.*commit 05`), + MatchesRegexp(`<-- bad.*commit-08`), + MatchesRegexp(`<-- current.*commit-07`), + MatchesRegexp(`\?.*commit-06`), + MatchesRegexp(`<-- good.*commit-05`), ). SelectNextItem(). Press(keys.Commits.ViewBisectOptions). Tap(func() { t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(MatchesRegexp(`Mark .* as good`)).Confirm() - t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit 08.*Do you want to reset")).Confirm() + t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s)commit-08.*Do you want to reset")).Confirm() t.Views().Information().Content(DoesNotContain("Bisecting")) }). diff --git a/pkg/integration/tests/bisect/skip.go b/pkg/integration/tests/bisect/skip.go index c879cc408..7c9ef4aea 100644 --- a/pkg/integration/tests/bisect/skip.go +++ b/pkg/integration/tests/bisect/skip.go @@ -19,28 +19,28 @@ var Skip = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). Focus(). - SelectedLine(Contains("commit 10")). + SelectedLine(Contains("commit-10")). Press(keys.Commits.ViewBisectOptions). Tap(func() { t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(MatchesRegexp(`Mark .* as bad`)).Confirm() }). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.ViewBisectOptions). Tap(func() { t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(MatchesRegexp(`Mark .* as good`)).Confirm() t.Views().Information().Content(Contains("Bisecting")) }). Lines( - Contains("CI commit 10").Contains("<-- bad"), - Contains("CI commit 09").DoesNotContain("<--"), - Contains("CI commit 08").DoesNotContain("<--"), - Contains("CI commit 07").DoesNotContain("<--"), - Contains("CI commit 06").DoesNotContain("<--"), - Contains("CI commit 05").Contains("<-- current").IsSelected(), - Contains("CI commit 04").DoesNotContain("<--"), - Contains("CI commit 03").DoesNotContain("<--"), - Contains("CI commit 02").DoesNotContain("<--"), - Contains("CI commit 01").Contains("<-- good"), + Contains("CI commit-10").Contains("<-- bad"), + Contains("CI commit-09").DoesNotContain("<--"), + Contains("CI commit-08").DoesNotContain("<--"), + Contains("CI commit-07").DoesNotContain("<--"), + Contains("CI commit-06").DoesNotContain("<--"), + Contains("CI commit-05").Contains("<-- current").IsSelected(), + Contains("CI commit-04").DoesNotContain("<--"), + Contains("CI commit-03").DoesNotContain("<--"), + Contains("CI commit-02").DoesNotContain("<--"), + Contains("CI commit-01").Contains("<-- good"), ). Press(keys.Commits.ViewBisectOptions). Tap(func() { @@ -57,18 +57,18 @@ var Skip = NewIntegrationTest(NewIntegrationTestArgs{ }). // Skipping the current commit selects the new current commit: Lines( - Contains("CI commit 10").Contains("<-- bad"), - Contains("CI commit 09").DoesNotContain("<--"), - Contains("CI commit 08").DoesNotContain("<--"), - Contains("CI commit 07").DoesNotContain("<--"), - Contains("CI commit 06").Contains("<-- current").IsSelected(), - Contains("CI commit 05").Contains("<-- skipped"), - Contains("CI commit 04").DoesNotContain("<--"), - Contains("CI commit 03").DoesNotContain("<--"), - Contains("CI commit 02").DoesNotContain("<--"), - Contains("CI commit 01").Contains("<-- good"), + Contains("CI commit-10").Contains("<-- bad"), + Contains("CI commit-09").DoesNotContain("<--"), + Contains("CI commit-08").DoesNotContain("<--"), + Contains("CI commit-07").DoesNotContain("<--"), + Contains("CI commit-06").Contains("<-- current").IsSelected(), + Contains("CI commit-05").Contains("<-- skipped"), + Contains("CI commit-04").DoesNotContain("<--"), + Contains("CI commit-03").DoesNotContain("<--"), + Contains("CI commit-02").DoesNotContain("<--"), + Contains("CI commit-01").Contains("<-- good"), ). - NavigateToLine(Contains("commit 07")). + NavigateToLine(Contains("commit-07")). Press(keys.Commits.ViewBisectOptions). Tap(func() { t.ExpectPopup().Menu().Title(Equals("Bisect")). @@ -85,6 +85,6 @@ var Skip = NewIntegrationTest(NewIntegrationTestArgs{ }). // Skipping a selected, non-current commit keeps the selection // there: - SelectedLine(Contains("CI commit 07").Contains("<-- skipped")) + SelectedLine(Contains("CI commit-07").Contains("<-- skipped")) }, }) diff --git a/pkg/integration/tests/branch/select_commits_of_current_branch.go b/pkg/integration/tests/branch/select_commits_of_current_branch.go index 7b57455c3..6c1ee2a86 100644 --- a/pkg/integration/tests/branch/select_commits_of_current_branch.go +++ b/pkg/integration/tests/branch/select_commits_of_current_branch.go @@ -22,25 +22,25 @@ var SelectCommitsOfCurrentBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), Contains("master 02"), Contains("master 01"), ). Press(keys.Commits.SelectCommitsOfCurrentBranch). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02").IsSelected(), - Contains("commit 01").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-02").IsSelected(), + Contains("commit-01").IsSelected(), Contains("master 02"), Contains("master 01"), ). PressEscape(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), Contains("master 02"), Contains("master 01"), ) @@ -58,15 +58,15 @@ var SelectCommitsOfCurrentBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().SubCommits(). IsFocused(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), Contains("master 02"), Contains("master 01"), ). Press(keys.Commits.SelectCommitsOfCurrentBranch). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01").IsSelected(), + Contains("commit-02").IsSelected(), + Contains("commit-01").IsSelected(), Contains("master 02"), Contains("master 01"), ) diff --git a/pkg/integration/tests/commit/create_amend_commit.go b/pkg/integration/tests/commit/create_amend_commit.go index 474e24099..7d311a983 100644 --- a/pkg/integration/tests/commit/create_amend_commit.go +++ b/pkg/integration/tests/commit/create_amend_commit.go @@ -19,11 +19,11 @@ var CreateAmendCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Commits.CreateFixupCommit). Tap(func() { t.ExpectPopup().Menu(). @@ -31,14 +31,14 @@ var CreateAmendCommit = NewIntegrationTest(NewIntegrationTestArgs{ Select(Contains("amend! commit with changes")). Confirm() t.ExpectPopup().CommitMessagePanel(). - Content(Equals("commit 02")). + Content(Equals("commit-02")). Type(" amended").Confirm() }). Lines( - Contains("amend! commit 02"), - Contains("commit 03"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("amend! commit-02"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Views().Commits(). @@ -50,9 +50,9 @@ var CreateAmendCommit = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 03"), - Contains("commit 02 amended").IsSelected(), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02 amended").IsSelected(), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/custom_commands/selected_commit.go b/pkg/integration/tests/custom_commands/selected_commit.go index 0265759a8..1add8b45a 100644 --- a/pkg/integration/tests/custom_commands/selected_commit.go +++ b/pkg/integration/tests/custom_commands/selected_commit.go @@ -24,44 +24,44 @@ var SelectedCommit = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { // Select different commits in each of the commit views t.Views().Commits().Focus(). - NavigateToLine(Contains("commit 01")) + NavigateToLine(Contains("commit-01")) t.Views().ReflogCommits().Focus(). - NavigateToLine(Contains("commit 02")) + NavigateToLine(Contains("commit-02")) t.Views().Branches().Focus(). Lines(Contains("master").IsSelected()). PressEnter() t.Views().SubCommits().IsFocused(). - NavigateToLine(Contains("commit 03")) + NavigateToLine(Contains("commit-03")) // SubCommits t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 03")) + t.FileSystem().FileContent("file.txt", Equals("commit-03")) t.Views().SubCommits().PressEnter() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 03")) + t.FileSystem().FileContent("file.txt", Equals("commit-03")) // ReflogCommits t.Views().ReflogCommits().Focus() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit: commit 02")) + t.FileSystem().FileContent("file.txt", Equals("commit: commit-02")) t.Views().ReflogCommits().PressEnter() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit: commit 02")) + t.FileSystem().FileContent("file.txt", Equals("commit: commit-02")) // LocalCommits t.Views().Commits().Focus() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 01")) + t.FileSystem().FileContent("file.txt", Equals("commit-01")) t.Views().Commits().PressEnter() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 01")) + t.FileSystem().FileContent("file.txt", Equals("commit-01")) // None of these t.Views().Files().Focus() t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 01")) + t.FileSystem().FileContent("file.txt", Equals("commit-01")) }, }) diff --git a/pkg/integration/tests/custom_commands/selected_commit_range.go b/pkg/integration/tests/custom_commands/selected_commit_range.go index 6ef1305aa..662a28090 100644 --- a/pkg/integration/tests/custom_commands/selected_commit_range.go +++ b/pkg/integration/tests/custom_commands/selected_commit_range.go @@ -24,18 +24,18 @@ var SelectedCommitRange = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits().Focus(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ) t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 03\n")) + t.FileSystem().FileContent("file.txt", Equals("commit-03\n")) t.Views().Commits().Focus(). Press(keys.Universal.RangeSelectDown) t.GlobalPress(config.Keybinding{"X"}) - t.FileSystem().FileContent("file.txt", Equals("commit 03\ncommit 02\n")) + t.FileSystem().FileContent("file.txt", Equals("commit-03\ncommit-02\n")) }, }) diff --git a/pkg/integration/tests/filter_by_author/select_author.go b/pkg/integration/tests/filter_by_author/select_author.go index 281034c12..3e7759ce8 100644 --- a/pkg/integration/tests/filter_by_author/select_author.go +++ b/pkg/integration/tests/filter_by_author/select_author.go @@ -29,14 +29,14 @@ var SelectAuthor = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). Lines( - Contains("commit 7"), - Contains("commit 6"), - Contains("commit 5"), - Contains("commit 4"), - Contains("commit 3"), - Contains("commit 2"), - Contains("commit 1"), - Contains("commit 0"), + Contains("commit-7"), + Contains("commit-6"), + Contains("commit-5"), + Contains("commit-4"), + Contains("commit-3"), + Contains("commit-2"), + Contains("commit-1"), + Contains("commit-0"), ) t.Views().Information().Content(Contains("Filtering by 'Paul Oberstein '")) @@ -51,7 +51,7 @@ var SelectAuthor = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). - NavigateToLine(Contains("SK commit 0")). + NavigateToLine(Contains("SK commit-0")). Press(keys.Universal.FilteringMenu) t.ExpectPopup().Menu(). @@ -62,7 +62,7 @@ var SelectAuthor = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). Lines( - Contains("commit 0"), + Contains("commit-0"), ) t.Views().Information().Content(Contains("Filtering by 'Siegfried Kircheis '")) diff --git a/pkg/integration/tests/filter_by_author/shared.go b/pkg/integration/tests/filter_by_author/shared.go index 22d08ad5c..33130db66 100644 --- a/pkg/integration/tests/filter_by_author/shared.go +++ b/pkg/integration/tests/filter_by_author/shared.go @@ -20,7 +20,7 @@ func commonSetup(shell *Shell) { for _, authorInfo := range authors { for i := range authorInfo.numberOfCommits { authorEmail := strings.ToLower(strings.ReplaceAll(authorInfo.name, " ", ".")) + "@email.com" - commitMessage := fmt.Sprintf("commit %d", i) + commitMessage := fmt.Sprintf("commit-%d", i) shell.SetAuthor(authorInfo.name, authorEmail) shell.EmptyCommitDaysAgo(commitMessage, repoStartDaysAgo-totalCommits) diff --git a/pkg/integration/tests/filter_by_author/type_author.go b/pkg/integration/tests/filter_by_author/type_author.go index cb84d5757..79750fab3 100644 --- a/pkg/integration/tests/filter_by_author/type_author.go +++ b/pkg/integration/tests/filter_by_author/type_author.go @@ -33,9 +33,9 @@ var TypeAuthor = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). Lines( - Contains("commit 2"), - Contains("commit 1"), - Contains("commit 0"), + Contains("commit-2"), + Contains("commit-1"), + Contains("commit-0"), ) t.Views().Information().Content(Contains("Filtering by 'Yang Wen-li '")) @@ -58,7 +58,7 @@ var TypeAuthor = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). Lines( - Contains("commit 0"), + Contains("commit-0"), ) t.Views().Information().Content(Contains("Filtering by 'Siegfried Kircheis '")) diff --git a/pkg/integration/tests/interactive_rebase/amend_first_commit.go b/pkg/integration/tests/interactive_rebase/amend_first_commit.go index 02ce4e112..b811a5638 100644 --- a/pkg/integration/tests/interactive_rebase/amend_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/amend_first_commit.go @@ -19,10 +19,10 @@ var AmendFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.AmendToCommit). Tap(func() { t.ExpectPopup().Confirmation(). @@ -31,8 +31,8 @@ var AmendFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 02"), - Contains("commit 01").IsSelected(), + Contains("commit-02"), + Contains("commit-01").IsSelected(), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/amend_fixup_commit.go b/pkg/integration/tests/interactive_rebase/amend_fixup_commit.go index 3140899be..8943f1580 100644 --- a/pkg/integration/tests/interactive_rebase/amend_fixup_commit.go +++ b/pkg/integration/tests/interactive_rebase/amend_fixup_commit.go @@ -13,22 +13,22 @@ var AmendFixupCommit = NewIntegrationTest(NewIntegrationTestArgs{ SetupRepo: func(shell *Shell) { shell. CreateNCommits(1). - CreateFileAndAdd("first-fixup-file", "").Commit("fixup! commit 01"). + CreateFileAndAdd("first-fixup-file", "").Commit("fixup! commit-01"). CreateNCommitsStartingAt(2, 2). - CreateFileAndAdd("unrelated-fixup-file", "fixup 03").Commit("fixup! commit 03"). + CreateFileAndAdd("unrelated-fixup-file", "fixup 03").Commit("fixup! commit-03"). CreateFileAndAdd("fixup-file", "fixup 01") }, Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). Focus(). Lines( - Contains("fixup! commit 03"), - Contains("commit 03"), - Contains("commit 02"), - Contains("fixup! commit 01"), - Contains("commit 01"), + Contains("fixup! commit-03"), + Contains("commit-03"), + Contains("commit-02"), + Contains("fixup! commit-01"), + Contains("commit-01"), ). - NavigateToLine(Contains("fixup! commit 01")). + NavigateToLine(Contains("fixup! commit-01")). Press(keys.Commits.AmendToCommit). Tap(func() { t.ExpectPopup().Confirmation(). @@ -37,11 +37,11 @@ var AmendFixupCommit = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("fixup! commit 03"), - Contains("commit 03"), - Contains("commit 02"), - Contains("fixup! commit 01").IsSelected(), - Contains("commit 01"), + Contains("fixup! commit-03"), + Contains("commit-03"), + Contains("commit-02"), + Contains("fixup! commit-01").IsSelected(), + Contains("commit-01"), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/amend_head_commit_during_rebase.go b/pkg/integration/tests/interactive_rebase/amend_head_commit_during_rebase.go index 66be297f0..0ca3ffaaa 100644 --- a/pkg/integration/tests/interactive_rebase/amend_head_commit_during_rebase.go +++ b/pkg/integration/tests/interactive_rebase/amend_head_commit_during_rebase.go @@ -17,18 +17,18 @@ var AmendHeadCommitDuringRebase = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Shell().CreateFile("fixup-file", "fixup content") @@ -51,10 +51,10 @@ var AmendHeadCommitDuringRebase = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/amend_non_head_commit_during_rebase.go b/pkg/integration/tests/interactive_rebase/amend_non_head_commit_during_rebase.go index 1216655e8..3e4df1404 100644 --- a/pkg/integration/tests/interactive_rebase/amend_non_head_commit_during_rebase.go +++ b/pkg/integration/tests/interactive_rebase/amend_non_head_commit_during_rebase.go @@ -17,21 +17,21 @@ var AmendNonHeadCommitDuringRebase = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ) - for _, commit := range []string{"commit 01", "commit 03"} { + for _, commit := range []string{"commit-01", "commit-03"} { t.Views().Commits(). NavigateToLine(Contains(commit)). Press(keys.Commits.AmendToCommit) diff --git a/pkg/integration/tests/interactive_rebase/delete_update_ref_todo.go b/pkg/integration/tests/interactive_rebase/delete_update_ref_todo.go index 3b7642bf6..86b2ed950 100644 --- a/pkg/integration/tests/interactive_rebase/delete_update_ref_todo.go +++ b/pkg/integration/tests/interactive_rebase/delete_update_ref_todo.go @@ -23,18 +23,18 @@ var DeleteUpdateRefTodo = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). Focus(). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 06"), - Contains("pick").Contains("CI commit 05"), - Contains("pick").Contains("CI commit 04"), + Contains("pick").Contains("CI commit-06"), + Contains("pick").Contains("CI commit-05"), + Contains("pick").Contains("CI commit-04"), Contains("update-ref").Contains("branch1"), - Contains("pick").Contains("CI commit 03"), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-03"), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-01"), ). NavigateToLine(Contains("update-ref")). Press(keys.Universal.Remove). @@ -46,25 +46,25 @@ var DeleteUpdateRefTodo = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 06"), - Contains("pick").Contains("CI commit 05"), - Contains("pick").Contains("CI commit 04"), - Contains("pick").Contains("CI commit 03").IsSelected(), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-06"), + Contains("pick").Contains("CI commit-05"), + Contains("pick").Contains("CI commit-04"), + Contains("pick").Contains("CI commit-03").IsSelected(), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Remove). Tap(func() { t.Common().ContinueRebase() }). Lines( - Contains("CI ○ commit 06"), - Contains("CI ○ commit 05"), - Contains("CI ○ commit 04"), - Contains("CI ○ commit 03"), // No star on this commit, so there's no branch head here - Contains("CI ○ commit 01"), + Contains("CI ○ commit-06"), + Contains("CI ○ commit-05"), + Contains("CI ○ commit-04"), + Contains("CI ○ commit-03"), // No star on this commit, so there's no branch head here + Contains("CI ○ commit-01"), ) t.Views().Branches(). diff --git a/pkg/integration/tests/interactive_rebase/dont_show_branch_heads_for_todo_items.go b/pkg/integration/tests/interactive_rebase/dont_show_branch_heads_for_todo_items.go index e5b43ee81..1b8674593 100644 --- a/pkg/integration/tests/interactive_rebase/dont_show_branch_heads_for_todo_items.go +++ b/pkg/integration/tests/interactive_rebase/dont_show_branch_heads_for_todo_items.go @@ -28,31 +28,31 @@ var DontShowBranchHeadsForTodoItems = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 09"), - Contains("CI commit 08"), - Contains("CI commit 07"), - Contains("CI * commit 06"), - Contains("CI commit 05"), - Contains("CI commit 04"), - Contains("CI commit 03"), - Contains("CI * commit 02"), - Contains("CI commit 01"), + Contains("CI commit-09"), + Contains("CI commit-08"), + Contains("CI commit-07"), + Contains("CI * commit-06"), + Contains("CI commit-05"), + Contains("CI commit-04"), + Contains("CI commit-03"), + Contains("CI * commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 04")). + NavigateToLine(Contains("commit-04")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 09"), - Contains("pick").Contains("CI commit 08"), - Contains("pick").Contains("CI commit 07"), + Contains("pick").Contains("CI commit-09"), + Contains("pick").Contains("CI commit-08"), + Contains("pick").Contains("CI commit-07"), Contains("update-ref").Contains("branch2"), - Contains("pick").Contains("CI commit 06"), // no star on this entry, even though branch2 points to it - Contains("pick").Contains("CI commit 05"), + Contains("pick").Contains("CI commit-06"), // no star on this entry, even though branch2 points to it + Contains("pick").Contains("CI commit-05"), Contains("--- Commits ---"), - Contains("CI commit 04"), - Contains("CI commit 03"), - Contains("CI * commit 02"), // this star is fine though - Contains("CI commit 01"), + Contains("CI commit-04"), + Contains("CI commit-03"), + Contains("CI * commit-02"), // this star is fine though + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/drop_commit_in_copied_branch_with_update_ref.go b/pkg/integration/tests/interactive_rebase/drop_commit_in_copied_branch_with_update_ref.go index 81462296b..b66dcd2d7 100644 --- a/pkg/integration/tests/interactive_rebase/drop_commit_in_copied_branch_with_update_ref.go +++ b/pkg/integration/tests/interactive_rebase/drop_commit_in_copied_branch_with_update_ref.go @@ -25,11 +25,11 @@ var DropCommitInCopiedBranchWithUpdateRef = NewIntegrationTest(NewIntegrationTes t.Views().Commits(). Focus(). Lines( - Contains("CI * commit 03").IsSelected(), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI * commit-03").IsSelected(), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Remove). Tap(func() { t.ExpectPopup().Confirmation(). @@ -38,8 +38,8 @@ var DropCommitInCopiedBranchWithUpdateRef = NewIntegrationTest(NewIntegrationTes Confirm() }). Lines( - Contains("CI commit 03"), // no start on this commit because branch1 is no longer pointing to it - Contains("CI commit 01"), + Contains("CI commit-03"), // no start on this commit because branch1 is no longer pointing to it + Contains("CI commit-01"), ) t.Views().Branches(). @@ -48,9 +48,9 @@ var DropCommitInCopiedBranchWithUpdateRef = NewIntegrationTest(NewIntegrationTes PressPrimaryAction() t.Views().Commits().Lines( - Contains("CI commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/drop_todo_commit_with_update_ref.go b/pkg/integration/tests/interactive_rebase/drop_todo_commit_with_update_ref.go index ca481e986..9fb450afe 100644 --- a/pkg/integration/tests/interactive_rebase/drop_todo_commit_with_update_ref.go +++ b/pkg/integration/tests/interactive_rebase/drop_todo_commit_with_update_ref.go @@ -28,32 +28,32 @@ var DropTodoCommitWithUpdateRef = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 07").IsSelected(), - Contains("CI commit 06"), - Contains("CI commit 05"), - Contains("CI * commit 04"), - Contains("CI commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-07").IsSelected(), + Contains("CI commit-06"), + Contains("CI commit-05"), + Contains("CI * commit-04"), + Contains("CI commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 07"), - Contains("pick").Contains("CI commit 06"), - Contains("pick").Contains("CI commit 05"), + Contains("pick").Contains("CI commit-07"), + Contains("pick").Contains("CI commit-06"), + Contains("pick").Contains("CI commit-05"), Contains("update-ref").Contains("branch1").DoesNotContain("*"), - Contains("pick").Contains("CI commit 04"), - Contains("pick").Contains("CI commit 03"), + Contains("pick").Contains("CI commit-04"), + Contains("pick").Contains("CI commit-03"), Contains("--- Commits ---"), - Contains("CI commit 02").IsSelected(), - Contains("CI commit 01"), + Contains("CI commit-02").IsSelected(), + Contains("CI commit-01"), ). Tap(func() { - t.Views().Main().Content(Contains("commit 02")) + t.Views().Main().Content(Contains("commit-02")) }). - NavigateToLine(Contains("commit 06")). + NavigateToLine(Contains("commit-06")). Press(keys.Universal.Remove) t.Common().ContinueRebase() @@ -61,12 +61,12 @@ var DropTodoCommitWithUpdateRef = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). IsFocused(). Lines( - Contains("CI commit 07"), - Contains("CI commit 05"), - Contains("CI * commit 04"), - Contains("CI commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-07"), + Contains("CI commit-05"), + Contains("CI * commit-04"), + Contains("CI commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/drop_with_custom_comment_char.go b/pkg/integration/tests/interactive_rebase/drop_with_custom_comment_char.go index a6868e44f..734567d00 100644 --- a/pkg/integration/tests/interactive_rebase/drop_with_custom_comment_char.go +++ b/pkg/integration/tests/interactive_rebase/drop_with_custom_comment_char.go @@ -17,8 +17,8 @@ var DropWithCustomCommentChar = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits().Focus(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Universal.Remove). Tap(func() { @@ -28,7 +28,7 @@ var DropWithCustomCommentChar = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 01").IsSelected(), + Contains("commit-01").IsSelected(), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/edit_and_auto_amend.go b/pkg/integration/tests/interactive_rebase/edit_and_auto_amend.go index 2107c8a58..3045a5088 100644 --- a/pkg/integration/tests/interactive_rebase/edit_and_auto_amend.go +++ b/pkg/integration/tests/interactive_rebase/edit_and_auto_amend.go @@ -18,18 +18,18 @@ var EditAndAutoAmend = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Shell().CreateFile("fixup-file", "fixup content") @@ -46,9 +46,9 @@ var EditAndAutoAmend = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/edit_first_commit.go b/pkg/integration/tests/interactive_rebase/edit_first_commit.go index f09b7f27d..2ba657370 100644 --- a/pkg/integration/tests/interactive_rebase/edit_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/edit_first_commit.go @@ -18,23 +18,23 @@ var EditFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 02"), + Contains("commit-02"), Contains("--- Commits ---"), - Contains("commit 01").IsSelected(), + Contains("commit-01").IsSelected(), ). Tap(func() { t.Common().ContinueRebase() }). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/edit_last_commit_of_stacked_branch.go b/pkg/integration/tests/interactive_rebase/edit_last_commit_of_stacked_branch.go index 528afb7a4..7db9bb262 100644 --- a/pkg/integration/tests/interactive_rebase/edit_last_commit_of_stacked_branch.go +++ b/pkg/integration/tests/interactive_rebase/edit_last_commit_of_stacked_branch.go @@ -28,23 +28,23 @@ var EditLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 05").IsSelected(), - Contains("CI commit 04"), - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05").IsSelected(), + Contains("CI commit-04"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 03")). + NavigateToLine(Contains("commit-03")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 05"), - Contains("pick").Contains("CI commit 04"), + Contains("pick").Contains("CI commit-05"), + Contains("pick").Contains("CI commit-04"), Contains("update-ref").Contains("branch1"), Contains("--- Commits ---"), - Contains("CI * commit 03").IsSelected(), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI * commit-03").IsSelected(), + Contains("CI commit-02"), + Contains("CI commit-01"), ) t.Shell().CreateFile("fixup-file", "fixup content") @@ -66,11 +66,11 @@ var EditLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 05"), - Contains("CI commit 04"), - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05"), + Contains("CI commit-04"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/edit_non_todo_commit_during_rebase.go b/pkg/integration/tests/interactive_rebase/edit_non_todo_commit_during_rebase.go index 6a21412de..00f77594e 100644 --- a/pkg/integration/tests/interactive_rebase/edit_non_todo_commit_during_rebase.go +++ b/pkg/integration/tests/interactive_rebase/edit_non_todo_commit_during_rebase.go @@ -18,17 +18,17 @@ var EditNonTodoCommitDuringRebase = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), Contains("--- Commits ---"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit) t.ExpectToast(Contains("Disabled: When rebasing, this action only works on a selection of TODO commits.")) diff --git a/pkg/integration/tests/interactive_rebase/edit_range_select_down_to_merge_outside_rebase.go b/pkg/integration/tests/interactive_rebase/edit_range_select_down_to_merge_outside_rebase.go index 832b99652..a57ab8acd 100644 --- a/pkg/integration/tests/interactive_rebase/edit_range_select_down_to_merge_outside_rebase.go +++ b/pkg/integration/tests/interactive_rebase/edit_range_select_down_to_merge_outside_rebase.go @@ -19,8 +19,8 @@ var EditRangeSelectDownToMergeOutsideRebase = NewIntegrationTest(NewIntegrationT t.Views().Commits(). Focus(). TopLines( - Contains("CI ○ commit 02").IsSelected(), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-02").IsSelected(), + Contains("CI ○ commit-01"), Contains("Merge branch 'second-change-branch' into first-change-branch"), ). Press(keys.Universal.RangeSelectDown). @@ -28,8 +28,8 @@ var EditRangeSelectDownToMergeOutsideRebase = NewIntegrationTest(NewIntegrationT Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("edit CI commit 02").IsSelected(), - Contains("edit CI commit 01").IsSelected(), + Contains("edit CI commit-02").IsSelected(), + Contains("edit CI commit-01").IsSelected(), Contains("--- Commits ---").IsSelected(), Contains(" CI ◎─╮ Merge branch 'second-change-branch' into first-change-branch").IsSelected(), Contains(" CI │ ○ * second-change-branch unrelated change"), diff --git a/pkg/integration/tests/interactive_rebase/fixup_first_commit.go b/pkg/integration/tests/interactive_rebase/fixup_first_commit.go index ff099d760..9dc90c5c7 100644 --- a/pkg/integration/tests/interactive_rebase/fixup_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/fixup_first_commit.go @@ -18,17 +18,17 @@ var FixupFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.MarkCommitAsFixup). Tap(func() { t.ExpectToast(Equals("Disabled: There's no commit below to squash into")) }). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/interactive_rebase_of_copied_branch.go b/pkg/integration/tests/interactive_rebase/interactive_rebase_of_copied_branch.go index 73ace9105..de0bb28d0 100644 --- a/pkg/integration/tests/interactive_rebase/interactive_rebase_of_copied_branch.go +++ b/pkg/integration/tests/interactive_rebase/interactive_rebase_of_copied_branch.go @@ -25,19 +25,19 @@ var InteractiveRebaseOfCopiedBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), // No update-ref todo for branch1 here, even though command-line git would have added it - Contains("pick").Contains("CI commit 03"), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-03"), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI commit 01"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/interactive_rebase_with_conflict_for_edit_command.go b/pkg/integration/tests/interactive_rebase/interactive_rebase_with_conflict_for_edit_command.go index 11596e758..5b341e61c 100644 --- a/pkg/integration/tests/interactive_rebase/interactive_rebase_with_conflict_for_edit_command.go +++ b/pkg/integration/tests/interactive_rebase/interactive_rebase_with_conflict_for_edit_command.go @@ -24,9 +24,9 @@ var InteractiveRebaseWithConflictForEditCommand = NewIntegrationTest(NewIntegrat Focus(). Lines( Contains("this will conflict").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), Contains("initial commit"), ) @@ -55,9 +55,9 @@ var InteractiveRebaseWithConflictForEditCommand = NewIntegrationTest(NewIntegrat Contains("--- Pending rebase todos ---"), Contains("edit").Contains("<-- CONFLICT --- this will conflict").IsSelected(), Contains("--- Commits ---"), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), Contains("master commit"), Contains("initial commit"), ) diff --git a/pkg/integration/tests/interactive_rebase/mid_rebase_range_select.go b/pkg/integration/tests/interactive_rebase/mid_rebase_range_select.go index cb96b8308..95dab3056 100644 --- a/pkg/integration/tests/interactive_rebase/mid_rebase_range_select.go +++ b/pkg/integration/tests/interactive_rebase/mid_rebase_range_select.go @@ -18,95 +18,95 @@ var MidRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). TopLines( - Contains("commit 10").IsSelected(), + Contains("commit-10").IsSelected(), ). - NavigateToLine(Contains("commit 05")). + NavigateToLine(Contains("commit-05")). // Start a rebase Press(keys.Universal.Edit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("pick").Contains("commit 07"), - Contains("pick").Contains("commit 06"), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("pick").Contains("commit-07"), + Contains("pick").Contains("commit-06"), Contains("--- Commits ---"), - Contains("commit 05").IsSelected(), - Contains("commit 04"), + Contains("commit-05").IsSelected(), + Contains("commit-04"), ). SelectPreviousItem(). // perform various actions on a range of commits Press(keys.Universal.RangeSelectUp). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("pick").Contains("commit 07").IsSelected(), - Contains("pick").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("pick").Contains("commit-07").IsSelected(), + Contains("pick").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.MarkCommitAsFixup). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("fixup").Contains("commit 07").IsSelected(), - Contains("fixup").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("fixup").Contains("commit-07").IsSelected(), + Contains("fixup").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.PickCommit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("pick").Contains("commit 07").IsSelected(), - Contains("pick").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("pick").Contains("commit-07").IsSelected(), + Contains("pick").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Universal.Edit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("edit").Contains("commit 07").IsSelected(), - Contains("edit").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("edit").Contains("commit-07").IsSelected(), + Contains("edit").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.SquashDown). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.MoveDownCommit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Tap(func() { t.ExpectToast(Contains("Disabled: Cannot move any further")) @@ -114,38 +114,38 @@ var MidRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ Press(keys.Commits.MoveUpCommit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), - Contains("pick").Contains("commit 08"), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), + Contains("pick").Contains("commit-08"), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.MoveUpCommit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 10"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), + Contains("pick").Contains("commit-10"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.MoveUpCommit). TopLines( Contains("--- Pending rebase todos ---"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). Press(keys.Commits.MoveUpCommit). Tap(func() { @@ -153,29 +153,29 @@ var MidRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ }). TopLines( Contains("--- Pending rebase todos ---"), - Contains("squash").Contains("commit 07").IsSelected(), - Contains("squash").Contains("commit 06").IsSelected(), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08"), + Contains("squash").Contains("commit-07").IsSelected(), + Contains("squash").Contains("commit-06").IsSelected(), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08"), Contains("--- Commits ---"), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-05"), + Contains("commit-04"), ). // Verify we can't perform an action on a range that includes both // TODO and non-TODO commits - NavigateToLine(Contains("commit 08")). + NavigateToLine(Contains("commit-08")). Press(keys.Universal.RangeSelectDown). TopLines( Contains("--- Pending rebase todos ---"), - Contains("squash").Contains("commit 07"), - Contains("squash").Contains("commit 06"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08").IsSelected(), + Contains("squash").Contains("commit-07"), + Contains("squash").Contains("commit-06"), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08").IsSelected(), Contains("--- Commits ---").IsSelected(), - Contains("commit 05").IsSelected(), - Contains("commit 04"), + Contains("commit-05").IsSelected(), + Contains("commit-04"), ). Press(keys.Commits.MarkCommitAsFixup). Tap(func() { @@ -183,28 +183,28 @@ var MidRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ }). TopLines( Contains("--- Pending rebase todos ---"), - Contains("squash").Contains("commit 07"), - Contains("squash").Contains("commit 06"), - Contains("pick").Contains("commit 10"), - Contains("pick").Contains("commit 09"), - Contains("pick").Contains("commit 08").IsSelected(), + Contains("squash").Contains("commit-07"), + Contains("squash").Contains("commit-06"), + Contains("pick").Contains("commit-10"), + Contains("pick").Contains("commit-09"), + Contains("pick").Contains("commit-08").IsSelected(), Contains("--- Commits ---").IsSelected(), - Contains("commit 05").IsSelected(), - Contains("commit 04"), + Contains("commit-05").IsSelected(), + Contains("commit-04"), ). // continue the rebase Tap(func() { t.Common().ContinueRebase() }). TopLines( - Contains("commit 10"), - Contains("commit 09"), - Contains("commit 08"), - Contains("commit 05"), + Contains("commit-10"), + Contains("commit-09"), + Contains("commit-08"), + Contains("commit-05"), // selected indexes are retained, though we may want to clear it // in future (not sure what the best behaviour is right now) - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/move.go b/pkg/integration/tests/interactive_rebase/move.go index 3f1f23755..4f37f2c19 100644 --- a/pkg/integration/tests/interactive_rebase/move.go +++ b/pkg/integration/tests/interactive_rebase/move.go @@ -17,31 +17,31 @@ var Move = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( - Contains("commit 03"), - Contains("commit 04").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-04").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 04").IsSelected(), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-04").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), - Contains("commit 04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), + Contains("commit-04").IsSelected(), ). // assert nothing happens upon trying to move beyond the last commit Press(keys.Commits.MoveDownCommit). @@ -49,31 +49,31 @@ var Move = NewIntegrationTest(NewIntegrationTestArgs{ t.ExpectToast(Contains("Disabled: Cannot move any further")) }). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), - Contains("commit 04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), + Contains("commit-04").IsSelected(), ). Press(keys.Commits.MoveUpCommit). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 04").IsSelected(), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-04").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.MoveUpCommit). Lines( - Contains("commit 03"), - Contains("commit 04").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-04").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). Press(keys.Commits.MoveUpCommit). Lines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). // assert nothing happens upon trying to move beyond the first commit Press(keys.Commits.MoveUpCommit). @@ -81,10 +81,10 @@ var Move = NewIntegrationTest(NewIntegrationTestArgs{ t.ExpectToast(Contains("Disabled: Cannot move any further")) }). Lines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/move_across_branch_boundary_outside_rebase.go b/pkg/integration/tests/interactive_rebase/move_across_branch_boundary_outside_rebase.go index 0f341d5b5..36f1f5312 100644 --- a/pkg/integration/tests/interactive_rebase/move_across_branch_boundary_outside_rebase.go +++ b/pkg/integration/tests/interactive_rebase/move_across_branch_boundary_outside_rebase.go @@ -28,20 +28,20 @@ var MoveAcrossBranchBoundaryOutsideRebase = NewIntegrationTest(NewIntegrationTes t.Views().Commits(). Focus(). Lines( - Contains("CI commit 05").IsSelected(), - Contains("CI commit 04"), - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05").IsSelected(), + Contains("CI commit-04"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 04")). + NavigateToLine(Contains("commit-04")). Press(keys.Commits.MoveDownCommit). Lines( - Contains("CI commit 05"), - Contains("CI * commit 03"), - Contains("CI commit 04").IsSelected(), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05"), + Contains("CI * commit-03"), + Contains("CI commit-04").IsSelected(), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/move_in_rebase.go b/pkg/integration/tests/interactive_rebase/move_in_rebase.go index 1cc9dd785..9138839b6 100644 --- a/pkg/integration/tests/interactive_rebase/move_in_rebase.go +++ b/pkg/integration/tests/interactive_rebase/move_in_rebase.go @@ -17,39 +17,39 @@ var MoveInRebase = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 03"), - Contains("commit 02"), + Contains("commit-04"), + Contains("commit-03"), + Contains("commit-02"), Contains("--- Commits ---"), - Contains("commit 01").IsSelected(), + Contains("commit-01").IsSelected(), ). SelectPreviousItem(). Press(keys.Commits.MoveUpCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 02").IsSelected(), - Contains("commit 03"), + Contains("commit-04"), + Contains("commit-02").IsSelected(), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). Press(keys.Commits.MoveUpCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 02").IsSelected(), - Contains("commit 04"), - Contains("commit 03"), + Contains("commit-02").IsSelected(), + Contains("commit-04"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). // assert we can't move past the top Press(keys.Commits.MoveUpCommit). @@ -58,29 +58,29 @@ var MoveInRebase = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 02").IsSelected(), - Contains("commit 04"), - Contains("commit 03"), + Contains("commit-02").IsSelected(), + Contains("commit-04"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 02").IsSelected(), - Contains("commit 03"), + Contains("commit-04"), + Contains("commit-02").IsSelected(), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 03"), - Contains("commit 02").IsSelected(), + Contains("commit-04"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). // assert we can't move past the bottom Press(keys.Commits.MoveDownCommit). @@ -89,30 +89,30 @@ var MoveInRebase = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 03"), - Contains("commit 02").IsSelected(), + Contains("commit-04"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). // move it back up one so that we land in a different order than we started with Press(keys.Commits.MoveUpCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 04"), - Contains("commit 02").IsSelected(), - Contains("commit 03"), + Contains("commit-04"), + Contains("commit-02").IsSelected(), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 01"), + Contains("commit-01"), ). Tap(func() { t.Common().ContinueRebase() }). Lines( - Contains("commit 04"), - Contains("commit 02").IsSelected(), - Contains("commit 03"), - Contains("commit 01"), + Contains("commit-04"), + Contains("commit-02").IsSelected(), + Contains("commit-03"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/move_update_ref_todo.go b/pkg/integration/tests/interactive_rebase/move_update_ref_todo.go index 619efe7fb..c730fd995 100644 --- a/pkg/integration/tests/interactive_rebase/move_update_ref_todo.go +++ b/pkg/integration/tests/interactive_rebase/move_update_ref_todo.go @@ -23,43 +23,43 @@ var MoveUpdateRefTodo = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). Focus(). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 06"), - Contains("pick").Contains("CI commit 05"), - Contains("pick").Contains("CI commit 04"), + Contains("pick").Contains("CI commit-06"), + Contains("pick").Contains("CI commit-05"), + Contains("pick").Contains("CI commit-04"), Contains("update-ref").Contains("branch1"), - Contains("pick").Contains("CI commit 03"), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-03"), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-01"), ). NavigateToLine(Contains("update-ref")). Press(keys.Commits.MoveUpCommit). Press(keys.Commits.MoveUpCommit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 06"), + Contains("pick").Contains("CI commit-06"), Contains("update-ref").Contains("branch1"), - Contains("pick").Contains("CI commit 05"), - Contains("pick").Contains("CI commit 04"), - Contains("pick").Contains("CI commit 03"), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-05"), + Contains("pick").Contains("CI commit-04"), + Contains("pick").Contains("CI commit-03"), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-01"), ). Tap(func() { t.Common().ContinueRebase() }). Lines( - Contains("CI ○ commit 06"), - Contains("CI ○ * commit 05"), - Contains("CI ○ commit 04"), - Contains("CI ○ commit 03"), - Contains("CI ○ commit 02"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-06"), + Contains("CI ○ * commit-05"), + Contains("CI ○ commit-04"), + Contains("CI ○ commit-03"), + Contains("CI ○ commit-02"), + Contains("CI ○ commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/move_with_custom_comment_char.go b/pkg/integration/tests/interactive_rebase/move_with_custom_comment_char.go index eefbcea33..db5177cff 100644 --- a/pkg/integration/tests/interactive_rebase/move_with_custom_comment_char.go +++ b/pkg/integration/tests/interactive_rebase/move_with_custom_comment_char.go @@ -17,18 +17,18 @@ var MoveWithCustomCommentChar = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits().Focus(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). Lines( - Contains("commit 01"), - Contains("commit 02").IsSelected(), + Contains("commit-01"), + Contains("commit-02").IsSelected(), ). Press(keys.Commits.MoveUpCommit). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/outside_rebase_range_select.go b/pkg/integration/tests/interactive_rebase/outside_rebase_range_select.go index 4aeb28b28..fe9d2b762 100644 --- a/pkg/integration/tests/interactive_rebase/outside_rebase_range_select.go +++ b/pkg/integration/tests/interactive_rebase/outside_rebase_range_select.go @@ -18,13 +18,13 @@ var OutsideRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). TopLines( - Contains("commit 10").IsSelected(), + Contains("commit-10").IsSelected(), ). Press(keys.Universal.RangeSelectDown). TopLines( - Contains("commit 10").IsSelected(), - Contains("commit 09").IsSelected(), - Contains("commit 08"), + Contains("commit-10").IsSelected(), + Contains("commit-09").IsSelected(), + Contains("commit-08"), ). // Drop commits Press(keys.Universal.Remove). @@ -35,14 +35,14 @@ var OutsideRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). TopLines( - Contains("commit 08").IsSelected(), - Contains("commit 07"), + Contains("commit-08").IsSelected(), + Contains("commit-07"), ). Press(keys.Universal.RangeSelectDown). TopLines( - Contains("commit 08").IsSelected(), - Contains("commit 07").IsSelected(), - Contains("commit 06"), + Contains("commit-08").IsSelected(), + Contains("commit-07").IsSelected(), + Contains("commit-06"), ). // Squash commits Press(keys.Commits.SquashDown). @@ -53,27 +53,27 @@ var OutsideRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). TopLines( - Contains("commit 06").IsSelected(), - Contains("commit 05"), - Contains("commit 04"), + Contains("commit-06").IsSelected(), + Contains("commit-05"), + Contains("commit-04"), ). // Verify commit messages are concatenated Tap(func() { t.Views().Main(). ContainsLines( - Contains("commit 06"), + Contains("commit-06"), AnyString(), - Contains("commit 07"), + Contains("commit-07"), AnyString(), - Contains("commit 08"), + Contains("commit-08"), ) }). // Fixup commits Press(keys.Universal.RangeSelectDown). TopLines( - Contains("commit 06").IsSelected(), - Contains("commit 05").IsSelected(), - Contains("commit 04"), + Contains("commit-06").IsSelected(), + Contains("commit-05").IsSelected(), + Contains("commit-04"), ). Press(keys.Commits.MarkCommitAsFixup). Tap(func() { @@ -82,73 +82,73 @@ var OutsideRebaseRangeSelect = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). TopLines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), ). // Verify commit messages are dropped Tap(func() { t.Views().Main(). Content( - Contains("commit 04"). - DoesNotContain("commit 06"). - DoesNotContain("commit 05"), + Contains("commit-04"). + DoesNotContain("commit-06"). + DoesNotContain("commit-05"), ) }). Press(keys.Universal.RangeSelectDown). TopLines( - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), - Contains("commit 02"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-02"), ). // Move commits Press(keys.Commits.MoveDownCommit). TopLines( - Contains("commit 02"), - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.MoveDownCommit). TopLines( - Contains("commit 02"), - Contains("commit 01"), - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), ). Press(keys.Commits.MoveDownCommit). TopLines( - Contains("commit 02"), - Contains("commit 01"), - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), ). Tap(func() { t.ExpectToast(Contains("Disabled: Cannot move any further")) }). Press(keys.Commits.MoveUpCommit). TopLines( - Contains("commit 02"), - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.MoveUpCommit). TopLines( - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). Press(keys.Commits.MoveUpCommit). Tap(func() { t.ExpectToast(Contains("Disabled: Cannot move any further")) }). TopLines( - Contains("commit 04").IsSelected(), - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/quick_start_keep_selection.go b/pkg/integration/tests/interactive_rebase/quick_start_keep_selection.go index 55be5ea4a..4d045c8fc 100644 --- a/pkg/integration/tests/interactive_rebase/quick_start_keep_selection.go +++ b/pkg/integration/tests/interactive_rebase/quick_start_keep_selection.go @@ -28,27 +28,27 @@ var QuickStartKeepSelection = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 07").IsSelected(), - Contains("CI commit 06"), - Contains("CI commit 05"), - Contains("CI * commit 04"), - Contains("CI commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-07").IsSelected(), + Contains("CI commit-06"), + Contains("CI commit-05"), + Contains("CI * commit-04"), + Contains("CI commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Commits.StartInteractiveRebase). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 07"), - Contains("pick").Contains("CI commit 06"), - Contains("pick").Contains("CI commit 05"), + Contains("pick").Contains("CI commit-07"), + Contains("pick").Contains("CI commit-06"), + Contains("pick").Contains("CI commit-05"), Contains("update-ref").Contains("branch1"), - Contains("pick").Contains("CI commit 04"), - Contains("pick").Contains("CI commit 03"), - Contains("CI commit 02").IsSelected(), + Contains("pick").Contains("CI commit-04"), + Contains("pick").Contains("CI commit-03"), + Contains("CI commit-02").IsSelected(), Contains("--- Commits ---"), - Contains("CI commit 01"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/quick_start_keep_selection_range.go b/pkg/integration/tests/interactive_rebase/quick_start_keep_selection_range.go index 8ff8f1065..4d25a883c 100644 --- a/pkg/integration/tests/interactive_rebase/quick_start_keep_selection_range.go +++ b/pkg/integration/tests/interactive_rebase/quick_start_keep_selection_range.go @@ -29,31 +29,31 @@ var QuickStartKeepSelectionRange = NewIntegrationTest(NewIntegrationTestArgs{ Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). Focus(). - NavigateToLine(Contains("commit 04")). + NavigateToLine(Contains("commit-04")). Press(keys.Universal.RangeSelectDown). Press(keys.Universal.RangeSelectDown). Lines( - Contains("CI commit 07"), - Contains("CI commit 06"), - Contains("CI * commit 05"), - Contains("CI commit 04").IsSelected(), - Contains("CI * commit 03").IsSelected(), - Contains("CI commit 02").IsSelected(), - Contains("CI commit 01"), + Contains("CI commit-07"), + Contains("CI commit-06"), + Contains("CI * commit-05"), + Contains("CI commit-04").IsSelected(), + Contains("CI * commit-03").IsSelected(), + Contains("CI commit-02").IsSelected(), + Contains("CI commit-01"), ). Press(keys.Commits.StartInteractiveRebase). Lines( Contains("--- Pending rebase todos ---"), - Contains("CI commit 07"), - Contains("CI commit 06"), + Contains("CI commit-07"), + Contains("CI commit-06"), Contains("update-ref").Contains("branch2"), - Contains("CI commit 05"), - Contains("CI commit 04").IsSelected(), + Contains("CI commit-05"), + Contains("CI commit-04").IsSelected(), Contains("update-ref").Contains("branch1").IsSelected(), - Contains("CI commit 03").IsSelected(), - Contains("CI commit 02").IsSelected(), + Contains("CI commit-03").IsSelected(), + Contains("CI commit-02").IsSelected(), Contains("--- Commits ---"), - Contains("CI commit 01"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/revert_during_rebase_when_stopped_on_edit.go b/pkg/integration/tests/interactive_rebase/revert_during_rebase_when_stopped_on_edit.go index 16a2b8c25..44a39200b 100644 --- a/pkg/integration/tests/interactive_rebase/revert_during_rebase_when_stopped_on_edit.go +++ b/pkg/integration/tests/interactive_rebase/revert_during_rebase_when_stopped_on_edit.go @@ -20,22 +20,22 @@ var RevertDuringRebaseWhenStoppedOnEdit = NewIntegrationTest(NewIntegrationTestA t.Views().Commits(). Focus(). Lines( - Contains("commit 04").IsSelected(), - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), Contains("master commit 2"), Contains("master commit 1"), ). - NavigateToLine(Contains("commit 03")). + NavigateToLine(Contains("commit-03")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 04"), + Contains("pick").Contains("commit-04"), Contains("--- Commits ---"), - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), Contains("master commit 2"), Contains("master commit 1"), ). @@ -50,13 +50,13 @@ var RevertDuringRebaseWhenStoppedOnEdit = NewIntegrationTest(NewIntegrationTestA }). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("commit 04"), + Contains("pick").Contains("commit-04"), Contains("--- Commits ---"), - Contains(`Revert "commit 01"`), - Contains(`Revert "commit 02"`), - Contains("commit 03"), - Contains("commit 02").IsSelected(), - Contains("commit 01").IsSelected(), + Contains(`Revert "commit-01"`), + Contains(`Revert "commit-02"`), + Contains("commit-03"), + Contains("commit-02").IsSelected(), + Contains("commit-01").IsSelected(), Contains("master commit 2"), Contains("master commit 1"), ) diff --git a/pkg/integration/tests/interactive_rebase/reword_commit_with_editor_and_fail.go b/pkg/integration/tests/interactive_rebase/reword_commit_with_editor_and_fail.go index df6486772..b8cf20ae8 100644 --- a/pkg/integration/tests/interactive_rebase/reword_commit_with_editor_and_fail.go +++ b/pkg/integration/tests/interactive_rebase/reword_commit_with_editor_and_fail.go @@ -20,11 +20,11 @@ var RewordCommitWithEditorAndFail = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Commits.RenameCommitWithEditor). Tap(func() { t.ExpectPopup().Confirmation(). @@ -34,10 +34,10 @@ var RewordCommitWithEditorAndFail = NewIntegrationTest(NewIntegrationTestArgs{ }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.ExpectPopup().Alert(). diff --git a/pkg/integration/tests/interactive_rebase/reword_first_commit.go b/pkg/integration/tests/interactive_rebase/reword_first_commit.go index cb9afc3c4..b61ceb93a 100644 --- a/pkg/integration/tests/interactive_rebase/reword_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/reword_first_commit.go @@ -21,21 +21,21 @@ var RewordFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.RenameCommit). Tap(func() { t.ExpectPopup().CommitMessagePanel(). Title(Equals("Reword commit")). - InitialText(Equals("commit 01")). + InitialText(Equals("commit-01")). Clear(). Type("renamed 01"). Confirm() }). Lines( - Contains("commit 02"), + Contains("commit-02"), Contains("renamed 01"), ) }, diff --git a/pkg/integration/tests/interactive_rebase/reword_last_commit.go b/pkg/integration/tests/interactive_rebase/reword_last_commit.go index 5d3038feb..80a57cc32 100644 --- a/pkg/integration/tests/interactive_rebase/reword_last_commit.go +++ b/pkg/integration/tests/interactive_rebase/reword_last_commit.go @@ -18,21 +18,21 @@ var RewordLastCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.RenameCommit). Tap(func() { t.ExpectPopup().CommitMessagePanel(). Title(Equals("Reword commit")). - InitialText(Equals("commit 02")). + InitialText(Equals("commit-02")). Clear(). Type("renamed 02"). Confirm() }). Lines( Contains("renamed 02"), - Contains("commit 01"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/reword_last_commit_of_stacked_branch.go b/pkg/integration/tests/interactive_rebase/reword_last_commit_of_stacked_branch.go index e9cdc3a1a..b353e69cc 100644 --- a/pkg/integration/tests/interactive_rebase/reword_last_commit_of_stacked_branch.go +++ b/pkg/integration/tests/interactive_rebase/reword_last_commit_of_stacked_branch.go @@ -28,28 +28,28 @@ var RewordLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("CI commit 05").IsSelected(), - Contains("CI commit 04"), - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05").IsSelected(), + Contains("CI commit-04"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 03")). + NavigateToLine(Contains("commit-03")). Press(keys.Commits.RenameCommit). Tap(func() { t.ExpectPopup().CommitMessagePanel(). Title(Equals("Reword commit")). - InitialText(Equals("commit 03")). + InitialText(Equals("commit-03")). Clear(). Type("renamed 03"). Confirm() }). Lines( - Contains("CI commit 05"), - Contains("CI commit 04"), + Contains("CI commit-05"), + Contains("CI commit-04"), Contains("CI * renamed 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit.go b/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit.go index 92aaf1a43..bd58ab083 100644 --- a/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit.go +++ b/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit.go @@ -18,34 +18,34 @@ var RewordYouAreHereCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.RenameCommit). Tap(func() { t.ExpectPopup().CommitMessagePanel(). Title(Equals("Reword commit")). - InitialText(Equals("commit 02")). + InitialText(Equals("commit-02")). Clear(). Type("renamed 02"). Confirm() }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), Contains("renamed 02").IsSelected(), - Contains("commit 01"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit_with_editor.go b/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit_with_editor.go index b927684fe..5406ed02b 100644 --- a/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit_with_editor.go +++ b/pkg/integration/tests/interactive_rebase/reword_you_are_here_commit_with_editor.go @@ -20,18 +20,18 @@ var RewordYouAreHereCommitWithEditor = NewIntegrationTest(NewIntegrationTestArgs t.Views().Commits(). Focus(). Lines( - Contains("commit 03").IsSelected(), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03").IsSelected(), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Universal.Edit). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.RenameCommitWithEditor). Tap(func() { @@ -42,10 +42,10 @@ var RewordYouAreHereCommitWithEditor = NewIntegrationTest(NewIntegrationTestArgs }). Lines( Contains("--- Pending rebase todos ---"), - Contains("commit 03"), + Contains("commit-03"), Contains("--- Commits ---"), Contains("renamed 02").IsSelected(), - Contains("commit 01"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/show_exec_todos.go b/pkg/integration/tests/interactive_rebase/show_exec_todos.go index 948bfb7d8..fad0e44e8 100644 --- a/pkg/integration/tests/interactive_rebase/show_exec_todos.go +++ b/pkg/integration/tests/interactive_rebase/show_exec_todos.go @@ -33,10 +33,10 @@ var ShowExecTodos = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("--- Pending rebase todos ---"), Contains("exec").Contains("false"), - Contains("pick").Contains("CI commit 03"), + Contains("pick").Contains("CI commit-03"), Contains("--- Commits ---"), - Contains("CI ○ commit 02"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-02"), + Contains("CI ○ commit-01"), ). Tap(func() { t.Common().ContinueRebase() @@ -45,17 +45,17 @@ var ShowExecTodos = NewIntegrationTest(NewIntegrationTestArgs{ Lines( Contains("--- Pending rebase todos ---"), Contains("--- Commits ---"), - Contains("CI ○ commit 03"), - Contains("CI ○ commit 02"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-03"), + Contains("CI ○ commit-02"), + Contains("CI ○ commit-01"), ). Tap(func() { t.Common().ContinueRebase() }). Lines( - Contains("CI ○ commit 03"), - Contains("CI ○ commit 02"), - Contains("CI ○ commit 01"), + Contains("CI ○ commit-03"), + Contains("CI ○ commit-02"), + Contains("CI ○ commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/squash_down_first_commit.go b/pkg/integration/tests/interactive_rebase/squash_down_first_commit.go index 65d6bfaa7..97f3f3567 100644 --- a/pkg/integration/tests/interactive_rebase/squash_down_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/squash_down_first_commit.go @@ -18,17 +18,17 @@ var SquashDownFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.SquashDown). Tap(func() { t.ExpectToast(Equals("Disabled: There's no commit below to squash into")) }). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ) }, }) diff --git a/pkg/integration/tests/interactive_rebase/squash_down_second_commit.go b/pkg/integration/tests/interactive_rebase/squash_down_second_commit.go index 6ba313f7a..ba5f33705 100644 --- a/pkg/integration/tests/interactive_rebase/squash_down_second_commit.go +++ b/pkg/integration/tests/interactive_rebase/squash_down_second_commit.go @@ -18,11 +18,11 @@ var SquashDownSecondCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Commits.SquashDown). Tap(func() { t.ExpectPopup().Confirmation(). @@ -31,12 +31,12 @@ var SquashDownSecondCommit = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 03"), - Contains("commit 01").IsSelected(), + Contains("commit-03"), + Contains("commit-01").IsSelected(), ) t.Views().Main(). - Content(Contains(" commit 01\n \n commit 02")). + Content(Contains(" commit-01\n \n commit-02")). Content(Contains("+file01 content")). Content(Contains("+file02 content")) }, diff --git a/pkg/integration/tests/interactive_rebase/squash_fixups_above.go b/pkg/integration/tests/interactive_rebase/squash_fixups_above.go index 467a66154..fdbcf7817 100644 --- a/pkg/integration/tests/interactive_rebase/squash_fixups_above.go +++ b/pkg/integration/tests/interactive_rebase/squash_fixups_above.go @@ -19,11 +19,11 @@ var SquashFixupsAbove = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 03"), - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 02")). + NavigateToLine(Contains("commit-02")). Press(keys.Commits.CreateFixupCommit). Tap(func() { t.ExpectPopup().Menu(). @@ -32,10 +32,10 @@ var SquashFixupsAbove = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("fixup! commit 02"), - Contains("commit 03"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("fixup! commit-02"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Press(keys.Commits.SquashAboveCommits). Tap(func() { @@ -45,9 +45,9 @@ var SquashFixupsAbove = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 03"), - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-03"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/squash_fixups_above_first_commit.go b/pkg/integration/tests/interactive_rebase/squash_fixups_above_first_commit.go index 2d71093ba..4786dfd72 100644 --- a/pkg/integration/tests/interactive_rebase/squash_fixups_above_first_commit.go +++ b/pkg/integration/tests/interactive_rebase/squash_fixups_above_first_commit.go @@ -19,10 +19,10 @@ var SquashFixupsAboveFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). Lines( - Contains("commit 02"), - Contains("commit 01"), + Contains("commit-02"), + Contains("commit-01"), ). - NavigateToLine(Contains("commit 01")). + NavigateToLine(Contains("commit-01")). Press(keys.Commits.CreateFixupCommit). Tap(func() { t.ExpectPopup().Menu(). @@ -30,7 +30,7 @@ var SquashFixupsAboveFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ Select(Contains("fixup! commit")). Confirm() }). - NavigateToLine(Contains("commit 01").DoesNotContain("fixup!")). + NavigateToLine(Contains("commit-01").DoesNotContain("fixup!")). Press(keys.Commits.SquashAboveCommits). Tap(func() { t.ExpectPopup().Menu(). @@ -39,8 +39,8 @@ var SquashFixupsAboveFirstCommit = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 02"), - Contains("commit 01").IsSelected(), + Contains("commit-02"), + Contains("commit-01").IsSelected(), ) t.Views().Main(). diff --git a/pkg/integration/tests/interactive_rebase/squash_fixups_in_current_branch.go b/pkg/integration/tests/interactive_rebase/squash_fixups_in_current_branch.go index c6721d829..7e9caeebf 100644 --- a/pkg/integration/tests/interactive_rebase/squash_fixups_in_current_branch.go +++ b/pkg/integration/tests/interactive_rebase/squash_fixups_in_current_branch.go @@ -22,7 +22,7 @@ var SquashFixupsInCurrentBranch = NewIntegrationTest(NewIntegrationTestArgs{ Commit("fixup! master commit"). CreateNCommits(2). CreateFileAndAdd("fixup-file", "fixup content"). - Commit("fixup! commit 01") + Commit("fixup! commit-01") }, Run: func(t *TestDriver, keys config.KeybindingConfig) { t.Views().Commits(). @@ -30,9 +30,9 @@ var SquashFixupsInCurrentBranch = NewIntegrationTest(NewIntegrationTestArgs{ SelectNextItem(). SelectNextItem(). Lines( - Contains("fixup! commit 01"), - Contains("commit 02"), - Contains("commit 01").IsSelected(), + Contains("fixup! commit-01"), + Contains("commit-02"), + Contains("commit-01").IsSelected(), Contains("fixup! master commit"), Contains("master commit"), ). @@ -44,8 +44,8 @@ var SquashFixupsInCurrentBranch = NewIntegrationTest(NewIntegrationTestArgs{ Confirm() }). Lines( - Contains("commit 02"), - Contains("commit 01").IsSelected(), + Contains("commit-02"), + Contains("commit-01").IsSelected(), Contains("fixup! master commit"), Contains("master commit"), ) diff --git a/pkg/integration/tests/interactive_rebase/view_files_of_todo_entries.go b/pkg/integration/tests/interactive_rebase/view_files_of_todo_entries.go index f52e80703..3746633c7 100644 --- a/pkg/integration/tests/interactive_rebase/view_files_of_todo_entries.go +++ b/pkg/integration/tests/interactive_rebase/view_files_of_todo_entries.go @@ -29,11 +29,11 @@ var ViewFilesOfTodoEntries = NewIntegrationTest(NewIntegrationTestArgs{ Press(keys.Commits.StartInteractiveRebase). Lines( Contains("--- Pending rebase todos ---"), - Contains("pick").Contains("CI commit 03").IsSelected(), + Contains("pick").Contains("CI commit-03").IsSelected(), Contains("update-ref").Contains("branch1"), - Contains("pick").Contains("CI commit 02"), + Contains("pick").Contains("CI commit-02"), Contains("--- Commits ---"), - Contains("CI commit 01"), + Contains("CI commit-01"), ). Press(keys.Universal.GoInto) diff --git a/pkg/integration/tests/patch_building/move_to_new_commit_in_last_commit_of_stacked_branch.go b/pkg/integration/tests/patch_building/move_to_new_commit_in_last_commit_of_stacked_branch.go index c9fd80d0e..67170b35a 100644 --- a/pkg/integration/tests/patch_building/move_to_new_commit_in_last_commit_of_stacked_branch.go +++ b/pkg/integration/tests/patch_building/move_to_new_commit_in_last_commit_of_stacked_branch.go @@ -15,12 +15,12 @@ var MoveToNewCommitInLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrati }, SetupRepo: func(shell *Shell) { shell. - EmptyCommit("commit 01"). + EmptyCommit("commit-01"). NewBranch("branch1"). - EmptyCommit("commit 02"). + EmptyCommit("commit-02"). CreateFileAndAdd("file1", "file1 content"). CreateFileAndAdd("file2", "file2 content"). - Commit("commit 03"). + Commit("commit-03"). NewBranch("branch2"). CreateNCommitsStartingAt(2, 4) @@ -30,13 +30,13 @@ var MoveToNewCommitInLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrati t.Views().Commits(). Focus(). Lines( - Contains("CI commit 05").IsSelected(), - Contains("CI commit 04"), - Contains("CI * commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-05").IsSelected(), + Contains("CI commit-04"), + Contains("CI * commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ). - NavigateToLine(Contains("commit 03")). + NavigateToLine(Contains("commit-03")). PressEnter() t.Views().CommitFiles(). @@ -61,12 +61,12 @@ var MoveToNewCommitInLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrati t.Views().Commits(). IsFocused(). Lines( - Contains("CI commit 05"), - Contains("CI commit 04"), + Contains("CI commit-05"), + Contains("CI commit-04"), Contains("CI * new commit").IsSelected(), - Contains("CI commit 03"), - Contains("CI commit 02"), - Contains("CI commit 01"), + Contains("CI commit-03"), + Contains("CI commit-02"), + Contains("CI commit-01"), ) }, }) diff --git a/pkg/integration/tests/ui/accordion.go b/pkg/integration/tests/ui/accordion.go index 1e2ed1480..0a18d2881 100644 --- a/pkg/integration/tests/ui/accordion.go +++ b/pkg/integration/tests/ui/accordion.go @@ -11,9 +11,9 @@ import ( // ╶─Files - Submodules──────0 of 0─╴│commit 6e56dd04b70e548976f7f2928c4d9c359574e2bc ▲ // ╶─Local branches - Remotes1 of 1─╴│Author: CI █ // ┌─Commits - Reflog───────────────┐│Date: Wed Jul 19 22:00:03 2023 +1000 │ -// │7fe02805 CI commit 12 ▲│ ▼ -// │6e56dd04 CI commit 11 █└────────────────────────────────────────────────────────────────┘ -// │a35c687d CI commit 10 ▼┌─Command log────────────────────────────────────────────────────┐ +// │7fe02805 CI commit-12 ▲│ ▼ +// │6e56dd04 CI commit-11 █└────────────────────────────────────────────────────────────────┘ +// │a35c687d CI commit-10 ▼┌─Command log────────────────────────────────────────────────────┐ // └───────────────────────10 of 20─┘│Random tip: To filter commits by path, press '' │ // ╶─Stash───────────────────0 of 0─╴└────────────────────────────────────────────────────────────────┘ // /: Scroll, : Cancel, q: Quit, ?: Keybindings, 1-Donate Ask Question unversioned @@ -32,18 +32,18 @@ var Accordion = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). VisibleLines( - Contains("commit 20").IsSelected(), - Contains("commit 19"), - Contains("commit 18"), + Contains("commit-20").IsSelected(), + Contains("commit-19"), + Contains("commit-18"), ). // go past commit 11, then come back, so that it ends up in the centre of the viewport - NavigateToLine(Contains("commit 11")). - NavigateToLine(Contains("commit 10")). - NavigateToLine(Contains("commit 11")). + NavigateToLine(Contains("commit-11")). + NavigateToLine(Contains("commit-10")). + NavigateToLine(Contains("commit-11")). VisibleLines( - Contains("commit 12"), - Contains("commit 11").IsSelected(), - Contains("commit 10"), + Contains("commit-12"), + Contains("commit-11").IsSelected(), + Contains("commit-10"), ) t.Views().Files(). @@ -53,9 +53,9 @@ var Accordion = NewIntegrationTest(NewIntegrationTestArgs{ t.Views().Commits(). Focus(). VisibleLines( - Contains("commit 12"), - Contains("commit 11").IsSelected(), - Contains("commit 10"), + Contains("commit-12"), + Contains("commit-11").IsSelected(), + Contains("commit-10"), ) }, }) diff --git a/pkg/integration/tests/ui/mode_specific_keybinding_suggestions.go b/pkg/integration/tests/ui/mode_specific_keybinding_suggestions.go index 73f09da3c..550cac2b5 100644 --- a/pkg/integration/tests/ui/mode_specific_keybinding_suggestions.go +++ b/pkg/integration/tests/ui/mode_specific_keybinding_suggestions.go @@ -27,8 +27,8 @@ var ModeSpecificKeybindingSuggestions = NewIntegrationTest(NewIntegrationTestArg t.Views().Commits(). Focus(). Lines( - Contains("commit 02").IsSelected(), - Contains("commit 01"), + Contains("commit-02").IsSelected(), + Contains("commit-01"), ). Tap(func() { // These suggestions are mode-specific so are not shown by default From c21ce617298f11e0ac4733a43d26917197612518 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 14:28:29 +0200 Subject: [PATCH 112/218] Synchronize ViewBufferManager.Close with a starting task Close read and called stopCurrentTask with no lock, while NewTask's goroutine assigns it (and constructs the sync.Once it closes over) under waitingMutex. On shutdown Close runs while a render task spawned by the last layout is still starting, so the two raced on the field and the once (three DATA RACE blocks under -race, e.g. cherry_pick). Read stopCurrentTask once under waitingMutex and call the captured value instead of re-reading the field, which establishes the happens-before the once needs. This can't deadlock: no task holds waitingMutex across a blocking UI-thread hop, so Close can always take it, and a task wedged in such a hop is still bounded by the existing 3s timeout. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/tasks/tasks.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index bc08013ed..9da12d40b 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -393,14 +393,21 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix // Close closes the task manager, killing whatever task may currently be running func (self *ViewBufferManager) Close() { - if self.stopCurrentTask == nil { + // stopCurrentTask is written by NewTask's goroutine under waitingMutex (and + // so is the sync.Once it closes over), so read it under the lock and call + // the captured value; a task starting on shutdown must not race us here. + self.waitingMutex.Lock() + stopCurrentTask := self.stopCurrentTask + self.waitingMutex.Unlock() + + if stopCurrentTask == nil { return } c := make(chan struct{}) go utils.Safe(func() { - self.stopCurrentTask() + stopCurrentTask() c <- struct{}{} }) From d4a606c68503cc7f8e0e9e5c4de0c3b344ca59b8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 14:19:29 +0200 Subject: [PATCH 113/218] Demonstrate that list index conversions depend on rendering ModelIndexToViewIndex and ViewIndexToModelIndex read conversion arrays that only renderLines populates. So converting an index before the list has been rendered ignores the non-model items (e.g. section headers) and returns a wrong result; the same staleness makes a conversion after the model has grown index a too-short array and panic (seen in cherry_pick under -race). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/context/list_renderer_test.go | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pkg/gui/context/list_renderer_test.go b/pkg/gui/context/list_renderer_test.go index 08af680ff..24e4aa822 100644 --- a/pkg/gui/context/list_renderer_test.go +++ b/pkg/gui/context/list_renderer_test.go @@ -267,3 +267,31 @@ func TestListRenderer_ModelIndexToViewIndex_and_back(t *testing.T) { }) } } + +// The index conversions must not depend on the list having been rendered +// first. It used to be renderLines that populated the conversion arrays, so +// converting an index before the first render silently ignored the non-model +// items (and converting after the model changed used a stale snapshot). +func TestListRenderer_IndexConversionsAreRenderIndependent(t *testing.T) { + modelInts := lo.Map(lo.Range(3), func(i int, _ int) myint { return myint(i) }) + self := &ListRenderer{ + list: NewListViewModel(func() []myint { return modelInts }), + getDisplayStrings: func(startIdx int, endIdx int) [][]string { + return lo.Map(modelInts[startIdx:endIdx], + func(i myint, _ int) []string { return []string{fmt.Sprint(i)} }) + }, + // A section header sits at model index 1, so model item 1 is pushed down + // to view index 2, and view index 2 maps back to model item 1. + getNonModelItems: func() []*NonModelItem { + return []*NonModelItem{{Index: 1, Content: "--- header ---"}} + }, + } + + // Deliberately convert without rendering first. + /* EXPECTED: + assert.Equal(t, 2, self.ModelIndexToViewIndex(1)) + assert.Equal(t, 1, self.ViewIndexToModelIndex(2)) + ACTUAL: */ + assert.Equal(t, 1, self.ModelIndexToViewIndex(1)) + assert.Equal(t, 2, self.ViewIndexToModelIndex(2)) +} From 4e907c6b3e00d22fa954b10a9fd97bfb1f601c7b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 14:25:25 +0200 Subject: [PATCH 114/218] Compute list index conversions independently of rendering The model<->view index conversions were derived from arrays that only renderLines populated. That made them depend on the list having been rendered (so a conversion before the first render ignored the non-model items), and it made them go stale whenever the model changed after a render: converting an index then returned a wrong result, and once the model had grown past the last rendered length the conversion indexed a too-short array and panicked (seen in cherry_pick under -race). The conversion is a pure function of the current list length and the current non-model items, and needs none of the rendered display strings. Compute it directly and drop the cached arrays, so the result is always consistent with the current model and no longer depends on rendering. searchModelCommits converts every commit's index, and building the non-model items can be O(len) mid-rebase, so it would now be quadratic; snapshot the non-model items once via modelToViewIndexConverter instead of rebuilding them per index. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/context/list_renderer.go | 96 ++++++++++++++---------- pkg/gui/context/list_renderer_test.go | 7 -- pkg/gui/context/local_commits_context.go | 2 +- pkg/gui/context/sub_commits_context.go | 2 +- 4 files changed, 60 insertions(+), 47 deletions(-) diff --git a/pkg/gui/context/list_renderer.go b/pkg/gui/context/list_renderer.go index e863045e0..b8d036778 100644 --- a/pkg/gui/context/list_renderer.go +++ b/pkg/gui/context/list_renderer.go @@ -32,34 +32,76 @@ type ListRenderer struct { getNonModelItems func() []*NonModelItem // The remaining fields are private and shouldn't be initialized by clients - numNonModelItems int - viewIndicesByModelIndex []int - modelIndicesByViewIndex []int - columnPositions []int + columnPositions []int } func (self *ListRenderer) GetList() types.IList { return self.list } -func (self *ListRenderer) ModelIndexToViewIndex(modelIndex int) int { - modelIndex = lo.Clamp(modelIndex, 0, self.list.Len()) - if self.viewIndicesByModelIndex != nil { - return self.viewIndicesByModelIndex[modelIndex] +func (self *ListRenderer) getNonModelItemList() []*NonModelItem { + if self.getNonModelItems == nil { + return nil } + return self.getNonModelItems() +} - return modelIndex +func (self *ListRenderer) ModelIndexToViewIndex(modelIndex int) int { + return modelIndexToViewIndex(self.list.Len(), self.getNonModelItemList(), modelIndex) } func (self *ListRenderer) ViewIndexToModelIndex(viewIndex int) int { - viewIndex = lo.Clamp(viewIndex, 0, self.list.Len()+self.numNonModelItems) - if self.modelIndicesByViewIndex != nil { - return self.modelIndicesByViewIndex[viewIndex] - } + return viewIndexToModelIndex(self.list.Len(), self.getNonModelItemList(), viewIndex) +} +// modelToViewIndexConverter returns a model-to-view index conversion that +// reuses a single snapshot of the non-model items. Callers that convert many +// indices in a row (e.g. search, which converts every commit) should use this +// rather than calling ModelIndexToViewIndex per index, which would rebuild the +// non-model items each time. +func (self *ListRenderer) modelToViewIndexConverter() func(modelIndex int) int { + listLength := self.list.Len() + nonModelItems := self.getNonModelItemList() + return func(modelIndex int) int { + return modelIndexToViewIndex(listLength, nonModelItems, modelIndex) + } +} + +// The view shows the model items with the non-model items (e.g. section +// headers) inserted at their model indices. The two conversions below are +// computed directly from the current list length and non-model items, so they +// don't depend on the list having been rendered, and they can never be stale +// with respect to a model that changed since the last render (which used to +// cause both wrong results and index-out-of-range panics). +// +// The non-model items are assumed to be ordered by their Index, which is how +// all producers build them; the i-th one therefore ends up at view index +// Index+i. +func modelIndexToViewIndex(listLength int, nonModelItems []*NonModelItem, modelIndex int) int { + modelIndex = lo.Clamp(modelIndex, 0, listLength) + // Each non-model item inserted at or before this model item pushes it down + // by one row in the view. + viewIndex := modelIndex + for _, item := range nonModelItems { + if item.Index <= modelIndex { + viewIndex++ + } + } return viewIndex } +func viewIndexToModelIndex(listLength int, nonModelItems []*NonModelItem, viewIndex int) int { + viewIndex = lo.Clamp(viewIndex, 0, listLength+len(nonModelItems)) + // Subtract the non-model items that appear before this view index. + modelIndex := viewIndex + for i, item := range nonModelItems { + if item.Index+i < viewIndex { + modelIndex-- + } + } + return modelIndex +} + func (self *ListRenderer) ColumnPositions() []int { return self.columnPositions } @@ -71,23 +113,18 @@ func (self *ListRenderer) renderLines(startIdx int, endIdx int) string { if self.getColumnAlignments != nil { columnAlignments = self.getColumnAlignments() } - nonModelItems := []*NonModelItem{} - self.numNonModelItems = 0 - if self.getNonModelItems != nil { - nonModelItems = self.getNonModelItems() - self.prepareConversionArrays(nonModelItems) - } + nonModelItems := self.getNonModelItemList() startModelIdx := 0 if startIdx == -1 { startIdx = 0 } else { - startModelIdx = self.ViewIndexToModelIndex(startIdx) + startModelIdx = viewIndexToModelIndex(self.list.Len(), nonModelItems, startIdx) } endModelIdx := self.list.Len() if endIdx == -1 { endIdx = endModelIdx + len(nonModelItems) } else { - endModelIdx = self.ViewIndexToModelIndex(endIdx) + endModelIdx = viewIndexToModelIndex(self.list.Len(), nonModelItems, endIdx) } lines, columnPositions := utils.RenderDisplayStrings( self.getDisplayStrings(startModelIdx, endModelIdx), @@ -97,23 +134,6 @@ func (self *ListRenderer) renderLines(startIdx int, endIdx int) string { return strings.Join(lines, "\n") } -func (self *ListRenderer) prepareConversionArrays(nonModelItems []*NonModelItem) { - self.numNonModelItems = len(nonModelItems) - viewIndicesByModelIndex := lo.Range(self.list.Len() + 1) - modelIndicesByViewIndex := lo.Range(self.list.Len() + 1) - offset := 0 - for _, item := range nonModelItems { - for i := item.Index; i <= self.list.Len(); i++ { - viewIndicesByModelIndex[i]++ - } - modelIndicesByViewIndex = slices.Insert( - modelIndicesByViewIndex, item.Index+offset, modelIndicesByViewIndex[item.Index+offset]) - offset++ - } - self.viewIndicesByModelIndex = viewIndicesByModelIndex - self.modelIndicesByViewIndex = modelIndicesByViewIndex -} - func (self *ListRenderer) insertNonModelItems( nonModelItems []*NonModelItem, endIdx int, startIdx int, lines []string, columnPositions []int, ) []string { diff --git a/pkg/gui/context/list_renderer_test.go b/pkg/gui/context/list_renderer_test.go index 24e4aa822..11398a995 100644 --- a/pkg/gui/context/list_renderer_test.go +++ b/pkg/gui/context/list_renderer_test.go @@ -254,9 +254,6 @@ func TestListRenderer_ModelIndexToViewIndex_and_back(t *testing.T) { getNonModelItems: getNonModelItems, } - // Need to render first so that it knows the non-model items - self.renderLines(-1, -1) - for i := range len(s.modelIndices) { assert.Equal(t, s.expectedViewIndices[i], self.ModelIndexToViewIndex(s.modelIndices[i])) } @@ -288,10 +285,6 @@ func TestListRenderer_IndexConversionsAreRenderIndependent(t *testing.T) { } // Deliberately convert without rendering first. - /* EXPECTED: assert.Equal(t, 2, self.ModelIndexToViewIndex(1)) assert.Equal(t, 1, self.ViewIndexToModelIndex(2)) - ACTUAL: */ - assert.Equal(t, 1, self.ModelIndexToViewIndex(1)) - assert.Equal(t, 2, self.ViewIndexToModelIndex(2)) } diff --git a/pkg/gui/context/local_commits_context.go b/pkg/gui/context/local_commits_context.go index d929aca88..a66c720c9 100644 --- a/pkg/gui/context/local_commits_context.go +++ b/pkg/gui/context/local_commits_context.go @@ -224,7 +224,7 @@ func (self *LocalCommitsContext) RefForAdjustingLineNumberInDiff() string { } func (self *LocalCommitsContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition { - return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.ModelIndexToViewIndex, searchStr) + return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.modelToViewIndexConverter(), searchStr) } func (self *LocalCommitsViewModel) SetLimitCommits(value bool) { diff --git a/pkg/gui/context/sub_commits_context.go b/pkg/gui/context/sub_commits_context.go index fee5492ac..4e05c9594 100644 --- a/pkg/gui/context/sub_commits_context.go +++ b/pkg/gui/context/sub_commits_context.go @@ -223,7 +223,7 @@ func (self *SubCommitsContext) RefForAdjustingLineNumberInDiff() string { } func (self *SubCommitsContext) ModelSearchResults(searchStr string, caseSensitive bool) []gocui.SearchPosition { - return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.ModelIndexToViewIndex, searchStr) + return searchModelCommits(caseSensitive, self.GetCommits(), self.ColumnPositions(), self.modelToViewIndexConverter(), searchStr) } func (self *SubCommitsContext) IndexForGotoBottom() int { From c81c08071f8fbeaa755032b97204eac217dae4fa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 15:41:58 +0200 Subject: [PATCH 115/218] Add a hint about how to use diff --color-words or --word-diff in lazygit Since this frequently comes up as a feature request (but there are reasons why we don't want to add it), explain how to do this in lazygit today. --- docs-master/Custom_Pagers.md | 16 ++++++++++++++++ docs/Custom_Pagers.md | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/docs-master/Custom_Pagers.md b/docs-master/Custom_Pagers.md index 1b37766d0..f74005c19 100644 --- a/docs-master/Custom_Pagers.md +++ b/docs-master/Custom_Pagers.md @@ -79,6 +79,22 @@ git: - externalDiffCommand: difft --color=always --display=inline --syntax-highlight=off ``` +This can also be used for normal git diffs with custom parameters, such as `--color-words` or `--word-diff` which some people find useful. To do that, save a script like this to, say, `~/bin/color-words.sh`: + +```sh +#!/bin/sh + +git diff --color-words --no-index --color=always --no-ext-diff "$2" "$5" +``` + +And then use it in your git config like so: + +```yaml +git: + pagers: + - externalDiffCommand: ~/bin/color-words.sh +``` + Instead of setting this command in lazygit's `externalDiffCommand` config, you can also tell lazygit to use the external diff command that is configured in git itself (`diff.external`), by using ```yaml diff --git a/docs/Custom_Pagers.md b/docs/Custom_Pagers.md index 1b37766d0..f74005c19 100644 --- a/docs/Custom_Pagers.md +++ b/docs/Custom_Pagers.md @@ -79,6 +79,22 @@ git: - externalDiffCommand: difft --color=always --display=inline --syntax-highlight=off ``` +This can also be used for normal git diffs with custom parameters, such as `--color-words` or `--word-diff` which some people find useful. To do that, save a script like this to, say, `~/bin/color-words.sh`: + +```sh +#!/bin/sh + +git diff --color-words --no-index --color=always --no-ext-diff "$2" "$5" +``` + +And then use it in your git config like so: + +```yaml +git: + pagers: + - externalDiffCommand: ~/bin/color-words.sh +``` + Instead of setting this command in lazygit's `externalDiffCommand` config, you can also tell lazygit to use the external diff command that is configured in git itself (`diff.external`), by using ```yaml From 58e121b9330836c3201f73f8246787ef67536345 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 16:48:42 +0200 Subject: [PATCH 116/218] Don't block the UI thread when triggering an immediate fetch on repo switch Switching repos triggers an immediate background fetch by sending on the goEvery retrigger channel. The send was blocking, but the goEvery loop only receives between callbacks: while a fetch is in flight, it waits for that fetch to finish before returning to its select. So a repo switch that landed while a fetch was in flight would stall the UI thread for the remainder of the fetch. Worse, since worker refreshes capture state on the UI thread with a blocking OnUIThreadAndWaitBackground call, the in-flight fetch's post-fetch refresh can itself be waiting for the UI thread, turning that stall into a deadlock cycle: UI thread: switchTo -> triggerImmediateFetch, blocking send goEvery loop: waiting for the in-flight fetch to finish fetch worker: PostFetchRefresh -> RefreshFromWorker, waiting for the UI thread Make the send non-blocking, and give the channel a buffer of one so that a trigger arriving while a fetch is in flight is latched rather than dropped; that fetch is fetching the previous repo, so we still need another one after it. The goEvery loop picks the trigger up as soon as it returns to its select, and concurrent triggers coalesce. Co-Authored-By: Claude Fable 5 --- pkg/gui/background.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 8633f4624..8b5e4b8d4 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -190,7 +190,11 @@ func (self *BackgroundRoutineMgr) checkForExternalChanges() { // returns a channel that can be used to trigger the callback immediately func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop chan struct{}, function func(bool) error) chan struct{} { done := make(chan struct{}) - retrigger := make(chan struct{}) + // Buffered so that a retrigger arriving while the callback is running is + // latched rather than lost: the loop below doesn't receive again until the + // callback has finished, and the callback (a fetch) may be for the wrong + // repo if the retrigger came from a repo switch. + retrigger := make(chan struct{}, 1) go utils.Safe(func() { ticker := time.NewTicker(interval) defer ticker.Stop() @@ -234,6 +238,16 @@ func (self *BackgroundRoutineMgr) backgroundFetch() (err error) { func (self *BackgroundRoutineMgr) triggerImmediateFetch() { if self.triggerFetch != nil { - self.triggerFetch <- struct{}{} + // This runs on the UI thread, which must never block waiting for a + // background routine; in particular, the goEvery loop only receives + // between callbacks, and an in-flight fetch can itself be waiting for + // the UI thread to perform its post-fetch refresh, so a blocking send + // here would deadlock. The channel has a buffer of one, so the trigger + // is latched even when the loop isn't currently receiving; if one is + // already pending, the two coalesce. + select { + case self.triggerFetch <- struct{}{}: + default: + } } } From 3a0ba6bf4d33ce355237497b560a19bfd4a855ba Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 17:16:46 +0200 Subject: [PATCH 117/218] Fix data race on the triggerFetch field startBackgroundFetch assigned the field from its own goroutine, and only after the initial fetch had completed, while the UI thread reads it in triggerImmediateFetch on every repo switch, with no synchronization. Create the channel in startBackgroundRoutines instead, which runs on the UI thread before the fetch goroutine is spawned; everything the UI thread does afterwards is ordered after the write, so the read is race-free without any locking. To make this possible, goEvery now takes the retrigger channel as a parameter instead of creating and returning it; callers that have no use for a retrigger channel pass nil, and a nil channel in a select is simply never ready. As a side effect, a repo switch that happens before the fetch loop has started (during the intro popup or the initial fetch) now latches a trigger and causes an immediate fetch once the loop is running, where previously it was silently dropped. Co-Authored-By: Claude Fable 5 --- pkg/gui/background.go | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 8b5e4b8d4..f9eff420b 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -43,6 +43,11 @@ func (self *BackgroundRoutineMgr) startBackgroundRoutines() { if userConfig.Git.AutoFetch { fetchInterval := userConfig.Refresher.FetchInterval if fetchInterval > 0 { + // The channel must be created here, on the UI thread and before + // the fetch goroutine spawns, so that triggerImmediateFetch (also + // running on the UI thread) can read the field without racing the + // write. See triggerImmediateFetch for why it is buffered. + self.triggerFetch = make(chan struct{}, 1) go utils.Safe(self.startBackgroundFetch) } else { self.gui.c.Log.Errorf( @@ -74,7 +79,7 @@ func (self *BackgroundRoutineMgr) startBackgroundRoutines() { } if self.gui.Config.GetDebug() { - self.goEvery(time.Second*time.Duration(10), self.gui.stopChan, func(_ bool) error { + self.goEvery(time.Second*time.Duration(10), self.gui.stopChan, nil, func(_ bool) error { formatBytes := func(b uint64) string { const unit = 1000 if b < unit { @@ -125,14 +130,14 @@ func (self *BackgroundRoutineMgr) startBackgroundFetch() { _ = fetch(true) userConfig := self.gui.UserConfig() - self.triggerFetch = self.goEvery(userConfig.Refresher.FetchIntervalDuration(), self.gui.stopChan, fetch) + self.goEvery(userConfig.Refresher.FetchIntervalDuration(), self.gui.stopChan, self.triggerFetch, fetch) } func (self *BackgroundRoutineMgr) startBackgroundFilesRefresh() { self.gui.waitForIntro.Wait() userConfig := self.gui.UserConfig() - self.goEvery(userConfig.Refresher.RefreshIntervalDuration(), self.gui.stopChan, func(_ bool) error { + self.goEvery(userConfig.Refresher.RefreshIntervalDuration(), self.gui.stopChan, nil, func(_ bool) error { self.gui.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Background: true}) return nil }) @@ -151,6 +156,7 @@ func (self *BackgroundRoutineMgr) startBackgroundExternalChangeDetection() { self.goEvery( userConfig.Refresher.ExternalChangeCheckIntervalDuration(), self.gui.stopChan, + nil, func(_ bool) error { self.checkForExternalChanges() return nil @@ -187,14 +193,10 @@ func (self *BackgroundRoutineMgr) checkForExternalChanges() { self.gui.c.RefreshFromWorker(types.RefreshOptions{Background: true}) } -// returns a channel that can be used to trigger the callback immediately -func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop chan struct{}, function func(bool) error) chan struct{} { +// Runs function every interval until stop is closed. A send on retrigger (if +// non-nil) runs the callback immediately and restarts the interval. +func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop, retrigger chan struct{}, function func(bool) error) { done := make(chan struct{}) - // Buffered so that a retrigger arriving while the callback is running is - // latched rather than lost: the loop below doesn't receive again until the - // callback has finished, and the callback (a fetch) may be for the wrong - // repo if the retrigger came from a repo switch. - retrigger := make(chan struct{}, 1) go utils.Safe(func() { ticker := time.NewTicker(interval) defer ticker.Stop() @@ -227,7 +229,6 @@ func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop chan stru } } }) - return retrigger } func (self *BackgroundRoutineMgr) backgroundFetch() (err error) { From 76ad5a35521a6c972acf2d1802f5467e55bc5729 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 14:54:40 +0200 Subject: [PATCH 118/218] Clarify the contribution policy --- CONTRIBUTING.md | 277 ++++-------------------------------------------- 1 file changed, 19 insertions(+), 258 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fd62a0eb7..49a9a625c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,273 +1,34 @@ # Contributing -This project does not accept pull requests. +## The short version -In todays world of agentic coding I have decided that it no longer makes sense for me to look at incoming pull requests. As far as I can tell, the vast majority of these is AI-generated these days, which in itself is not necessarily a bad thing; however, there's no way for me to tell whether the person posting the PR actually understands anything about the code that is being contributed or not, and I don't feel like spending time and energy on finding out whether they do. +This project does not accept pull requests. Don't bother making one, it won't be merged. -Now you might ask why this even matters; coding agents are capable of producing amazingly high-quality code, so why is it important that the person opening the PR understands it, as long as the code works and tests are green? It does actually matter very much to me. AI generated code needs to be carefully reviewed and iterated on, and it is the contributor's job to do that, not mine. And I have no idea to what extent the contributor has done this, or whether they are even capable of it. +However, there are other forms of contributions that are very welcome and encouraged; see below for what those are. -Every PR needs work and iterations until it is mergeable, whether manually coded or AI generated (even very good ones do), and if I don't know whether the person posting the PR will act on my review feedback themselves or just pass it on to their coding agent (which I guess is the much more likely case today), then it doesn't make sense for me to work with them. +## Why no PRs? -For this reason I will close incoming pull requests by default from now on, without comment. Sorry if this sounds hostile, but honestly I don't feel I have much of a choice if I want maintaining this project to still be enjoyable for me. +There are two main reasons for this, and I want to be very honest about them: -With that said, if you are indeed serious about contributing a high-quality PR to lazygit, and you are familiar with go, and you have learned enough about lazygit's code base to tell whether your changes are good, then do raise an issue and explain what you are planning to do, and somehow make it plausible that your PR will be worth my time reviewing it. In such a case I might make an exception from the default rule. +- I am maintaining lazygit for fun, as a hobby in my free time (which is quite limited). I'd like to spend my free time on things that I enjoy doing. I enjoy working on lazygit's code and improving it myself; I don't enjoy reviewing PRs. It's that simple, really. Reviewing PRs takes a lot of time; time that I would rather spend on developing lazygit myself. +- Even if I had the time and inclination to review PRs, this has become quite difficult today: most PRs nowadays are AI-generated to some extent (often completely), which in itself is not necessarily a bad thing; I heavily use AI myself these days, and I get great results from it. However, agentic coding needs to be guided by humans so that the results are good, and for contributed PRs I can't tell to what extent the human contributor did this, or is even capable of it; and I don't want to do the work of guiding a contributor's coding agent. If I post PR review feedback and have to suspect that the contributor simply passes it on to their coding agent, then that is a work mode that doesn't make sense to me, and I would rather just drive my own agent to do the work. -In the future I might also consider adopting a vouch system similar to [Ghostty's](https://github.com/ghostty-org/ghostty/blob/main/CONTRIBUTING.md#first-time-contributors), but right now I feel the effort needed to set this up and maintain is not justified given the rather low number of high-quality contributions I have seen in recent times. +### Why it might still make sense to post a PR -Even though we no longer accept pull requests, I find it important to emphasize that Lazygit is still a community project, and non-PR contributions are still very welcome. Do file issues for bug reports or feature requests, and help shape the future of lazygit by actively participating in discussing UX designs. Also, the localization system very much depends on everybody's help with translating texts (see https://crowdin.com/project/lazygit). +I can think of two such reasons: ---- +- You implemented a lazygit improvement that you want to use yourself; in this case it could make sense to let others merge this change into their forks if they find it useful too. And if enough people say they want the feature, this can persuade me to add it, so putting it out there to give it visibility can be helpful. +- You posted an issue for a feature request, and have a prototype that implements it; it could be useful to publish the branch as a draft PR to better illustrate how the feature works. -The remainder of this document is the old version from a time when contributing pull requests was still encouraged. Keeping it here in case I reconsider my policy in the future. +For this reason I usually don't close pull requests to give them more visibility. Just don't expect your PR to be merged. -## PR walkthrough +## So how can I contribute then? -[This video](https://www.youtube.com/watch?v=kNavnhzZHtk) walks through the process of adding a small feature to lazygit. If you have no idea where to start, watching that video is a good first step. +There are other forms of contributions to a project besides source code that are very welcome and encouraged; for instance: -## Design principles +- File issues for bugs that you find, and I'll do my best to take care of fixing them (if they are important enough). +- File feature requests for new functionality that you want to see in lazygit. I have a lot of ideas for future improvement myself, but I have also implemented a lot of feature ideas that weren't mine, and I'm grateful for those ideas. (Of course, there are also lots of feature requests that I don't implement, so don't be disappointed if I don't jump on yours.) +- Help make other people's bug reports reproducible. Sometimes people report bugs that they have only seen once, and in such a case it can be helpful to come up with reproducible scenarios. +- Help complete or improve the translation into other languages; join https://crowdin.com/project/lazygit for that. -See [here](./VISION.md) for a set of design principles that we want to consider when building a feature or making a change. - -## Codebase guide - -[This doc](./docs/dev/Codebase_Guide.md) explains: - -- what the different packages in the codebase are for -- where important files live -- important concepts in the code -- how the event loop works -- other useful information - -## All code changes happen through Pull Requests - -Pull requests are the best way to propose changes to the codebase. We actively -welcome your pull requests: - -1. Fork the repo and create your branch from `master`. -2. If you've added code that should be tested, add tests. -3. If you've added code that needs documentation, update the documentation. -4. Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). -5. Issue that pull request! - -Please do not raise pull request from your fork's master branch: make a feature branch instead. Lazygit maintainers will sometimes push changes to your branch when reviewing a PR and we often can't do this if you use your master branch. - -If you've never written Go in your life, then join the club! Lazygit was the maintainer's first Go program, and most contributors have never used Go before. Go is widely considered an easy-to-learn language, so if you're looking for an open source project to gain dev experience, you've come to the right place. - -## Commit history - -We value a clean and useful commit history, so please take some time to organize your commits so that they make sense. Don't assume that they will be squashed on merge anyway; we don't do that here. - -In particular: - -- Refactorings and behavior changes should be in separate commits. There are very few exceptions where this is not possible, but in my experience they are very rare. -- Strive for minimal commits; every change that is independent from other changes should be in a commit of its own (with a good commit message that explains why the change is made). -- When you need to iterate over your implementation during review (e.g. because you discovered a bug, or a maintainer requested changes), don't just pile new commits on top. Use fixup commits to make your changes transparent while still maintaining a good commit history. If you don't know what that means, [here's a brief introduction](docs/Fixup_Commits.md). - -## A note about AI - -It has become common recently to throw an issue at a coding agent and submit whatever comes out of it as a PR. This is not appreciated here, and I will close PRs where I can tell this was the case, or where I even suspect it was the case. - -Some of these PRs may actually be good and useful, but many are not, and it's not a good use of my time as a maintainer to look at generated PRs to decide. This is the job of the PR's contributor, and if you don't speak enough go or can't be bothered to get familiar enough with lazygit's codebase to tell, then don't contribute the PR. - -## Running in a VSCode dev container - -If you want to spare yourself the hassle of setting up your dev environment yourself (i.e. installing Go, extensions, and extra tools), you can run the Lazygit code in a VSCode dev container like so: - -![image](https://user-images.githubusercontent.com/8456633/201500508-0d55f99f-5035-4a6f-a0f8-eaea5c003e5d.png) - -This requires that: - -- you have docker installed -- you have the dev containers extension installed in VSCode - -See [here](https://code.visualstudio.com/docs/devcontainers/containers) for more info about dev containers. - -## Running in a Github Codespace - -If you want to start contributing to Lazygit with the click of a button, you can open the lazygit codebase in a Codespace. First fork the repo, then click to create a codespace: - -![image](https://user-images.githubusercontent.com/8456633/201500566-ffe9105d-6030-4cc7-a525-6570b0b413a2.png) - -To run lazygit from within the integrated terminal just go `go run main.go` - -This allows you to contribute to Lazygit without needing to install anything on your local machine. The Codespace has all the necessary tools and extensions pre-installed. - -## Using Nix for development - -If you use Nix, you can leverage the included flake to set up a complete development environment with all necessary dependencies: - -```sh -nix develop -``` - -This will drop you into a development shell that includes: - -- Latest Go toolchain -- golangci-lint for code linting -- git and make - -You can also build and run lazygit using nix: - -```sh -# Build lazygit -nix build - -# Run lazygit directly -nix run -``` - -The nix flake supports multiple architectures (x86_64-linux, aarch64-linux, x86_64-darwin, aarch64-darwin) and provides a consistent development environment across different systems. - -## Code of conduct - -Please note by participating in this project, you agree to abide by the [code of conduct]. - -[code of conduct]: https://github.com/jesseduffield/lazygit/blob/master/CODE-OF-CONDUCT.md - -## Any contributions you make will be under the MIT Software License - -In short, when you submit code changes, your submissions are understood to be -under the same [MIT License](http://choosealicense.com/licenses/mit/) that -covers the project. Feel free to contact the maintainers if that's a concern. - -## Report bugs using Github's [issues](https://github.com/jesseduffield/lazygit/issues) - -We use GitHub issues to track public bugs. Report a bug by [opening a new -issue](https://github.com/jesseduffield/lazygit/issues/new); it's that easy! - -## Go - -This project is written in Go. Go is an opinionated language with strict idioms, but some of those idioms are a little extreme. Some things we do differently: - -1. There is no shame in using `self` as a receiver name in a struct method. In fact we encourage it -2. There is no shame in prefixing an interface with 'I' instead of suffixing with 'er' when there are several methods on the interface. -3. If a struct implements an interface, we make it explicit with something like: - -```go -var _ MyInterface = &MyStruct{} -``` - -This makes the intent clearer and means that if we fail to satisfy the interface we'll get an error in the file that needs fixing. - -### Code Formatting - -To check code formatting [gofumpt](https://pkg.go.dev/mvdan.cc/gofumpt#section-readme) (which is a bit stricter than [gofmt](https://pkg.go.dev/cmd/gofmt)) is used. -VSCode will format the code correctly if you tell the Go extension to use `gofumpt` via your [`settings.json`](https://code.visualstudio.com/docs/getstarted/settings#_settingsjson) -by setting [`formatting.gofumpt`](https://github.com/golang/tools/blob/master/gopls/doc/settings.md#gofumpt-bool) to `true`: - -```jsonc -// .vscode/settings.json -{ - "gopls": { - "formatting.gofumpt": true - } -} -``` - -To run gofumpt from your terminal go: - -``` -go install mvdan.cc/gofumpt@latest && gofumpt -l -w . -``` - -## Programming Font - -Lazygit supports [Nerd Fonts](https://www.nerdfonts.com) to render certain icons. Sometimes we use some of these icons verbatim in string literals in the code (mainly in tests), so you need to set your development environment to use a nerd font to see these. - -## Internationalisation - -Boy that's a hard word to spell. Anyway, lazygit is translated into several languages within the pkg/i18n package. - -### For developers adding new text - -If you need to render text to the user, you should add a new field to the TranslationSet struct in `pkg/i18n/english.go` and add the actual content within the `EnglishTranslationSet()` method in the same file. Then you can access via `gui.Tr.YourNewText` (or `self.c.Tr.YourNewText`, etc). - -Note, we use 'Sentence case' for everything (so no 'Title Case' or 'whatever-it's-called-when-there's-no-capital-letters-case') - -### For translators - -Lazygit translations are managed through [Crowdin](https://crowdin.com/project/lazygit/). If you'd like to contribute translations: - -1. Join the Crowdin project at https://crowdin.com/project/lazygit/ -2. Select your target language and help translate missing strings -3. The translation files in `pkg/i18n/translations/` are managed by the maintainers - please don't edit them directly - -For detailed information about the translation process, including how maintainers sync translations, see `pkg/i18n/translations/README.md`. - -## Debugging - -The easiest way to debug lazygit is to have two terminal tabs open at once: one for running lazygit (via `go run main.go -debug` in the project root) and one for viewing lazygit's logs (which can be done via `go run main.go --logs` or just `lazygit --logs`). - -From most places in the codebase you have access to a logger e.g. `gui.Log.Warn("blah")` or `self.c.Log.Warn("blah")`. - -If you find that the existing logs are too noisy, you can set the log level with e.g. `LOG_LEVEL=warn go run main.go -debug` and then only use `Warn` logs yourself. - -If you need to log from code in the vendor directory (e.g. the `gocui` package), you won't have access to the logger, but you can easily add logging support by setting the `LAZYGIT_LOG_PATH` environment variable and using `logs.Global.Warn("blah")`. This is a global logger that's only intended for development purposes. - -If you keep having to do some setup steps to reproduce an issue, read the Testing section below to see how to create an integration test by recording a lazygit session. It's pretty easy! - -### VSCode debugger - -If you want to trigger a debug session from VSCode, you can use the following snippet. Note that the `console` key is, at the time of writing, still an experimental feature. - -```jsonc -// .vscode/launch.json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "debug lazygit", - "type": "go", - "request": "launch", - "mode": "auto", - "program": "main.go", - "args": ["--debug"], - "console": "externalTerminal" // <-- you need this to actually see the lazygit UI in a window while debugging - } - ] -} -``` - -## Profiling - -If you want to investigate what's contributing to CPU or memory usage, see [this separate document](docs/dev/Profiling.md). - -## Testing - -Lazygit has two kinds of tests: unit tests and integration tests. Unit tests go in files that end in `_test.go`, and are written in Go. For integration tests, see [here](https://github.com/jesseduffield/lazygit/blob/master/pkg/integration/README.md) - -## Updating Gocui - -Sometimes you will need to make a change in the gocui fork (https://github.com/jesseduffield/gocui). Gocui is the package responsible for rendering windows and handling user input. Here's the typical process to follow: - -1. Make the changes in gocui inside lazygit's vendor directory so it's easy to test against lazygit -2. Copy the changes over to the actual gocui repo (clone it if you haven't already, and use the `awesome` branch, not `master`) -3. Raise a PR on the gocui repo with your changes -4. After that PR is merged, make a PR in lazygit bumping the gocui version. You can bump the version by running the following at the lazygit repo root: - -```sh -./scripts/bump_gocui.sh -``` - -5. Raise a PR in lazygit with those changes - -## Updating Lazycore - -[Lazycore](https://github.com/jesseduffield/lazycore) is a repo containing shared functionality between lazygit and lazydocker. Sometimes you will need to make a change to that repo and import the changes into lazygit. Similar to updating Gocui, here's what you do: - -1. Make the changes in lazycore inside lazygit's vendor directory so it's easy to test against lazygit -2. Copy the changes over to the actual lazycore repo (clone it if you haven't already, and use the `master` branch) -3. Raise a PR on the lazycore repo with your changes -4. After that PR is merged, make a PR in lazygit bumping the lazycore version. You can bump the version by running the following at the lazygit repo root: - -```sh -./scripts/bump_lazycore.sh -``` - -Or if you're using VSCode, there is a bump lazycore task you can find by going `cmd+shift+p` and typing 'Run task' - -5. Raise a PR in lazygit with those changes - -## Improvements - -If you can think of any way to improve these docs let us know. +Importantly, if you file issues (whether bug reports or feature requests), stay around to answer questions and discuss your issue. There are few things that I find more annoying than spending time on responding to someone's issue (sometimes even making a PR that addresses it), and to then never hear from the OP again. So please set up your Github notifications so that you see when there's activity on your issue, and continue to participate. From 50122e6886855a01f33a1ccb3e8b7d6de1f624d8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 14:54:56 +0200 Subject: [PATCH 119/218] Don't invite for contributions at startup --- pkg/i18n/english.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 69ea7012f..22b05e6c0 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -1130,12 +1130,7 @@ Thanks for using lazygit! Seriously you rock. Three things to share with you: 2) Be sure to read the latest release notes at: https://github.com/jesseduffield/lazygit/releases - 3) If you're using git, that makes you a programmer! With your help we can make - lazygit better, so consider becoming a contributor and joining the fun at - https://github.com/jesseduffield/lazygit - Or even just star the repo to share the love! - - 4) If lazygit has made your life easier, you can say thanks by clicking the + 3) If lazygit has made your life easier, you can say thanks by clicking the donate button at the bottom right. Donation does not grant priority support, but it is much appreciated. From e90daaf81287b4ab5d53166d69651d9aba75ec9e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:56:06 +0200 Subject: [PATCH 120/218] Unify the git command lock-retry loops RunWithOutput and RunWithOutputs each carried their own near-identical copy of the index.lock retry loop. Extract the loop into a single retryOnLockError helper so the retry policy lives in one place, ahead of changing that policy. Behavior is unchanged; the added tests characterize it (success and non-lock errors run once, a lock error in the output is retried). Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_runner.go | 42 +++++------ pkg/commands/git_cmd_obj_runner_test.go | 92 +++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 pkg/commands/git_cmd_obj_runner_test.go diff --git a/pkg/commands/git_cmd_obj_runner.go b/pkg/commands/git_cmd_obj_runner.go index 668feef93..a72565b5c 100644 --- a/pkg/commands/git_cmd_obj_runner.go +++ b/pkg/commands/git_cmd_obj_runner.go @@ -33,11 +33,30 @@ func (self *gitCmdObjRunner) Run(cmdObj *oscommands.CmdObj) error { } func (self *gitCmdObjRunner) RunWithOutput(cmdObj *oscommands.CmdObj) (string, error) { + return self.retryOnLockError(func() (string, error) { + return self.innerRunner.RunWithOutput(cmdObj.Clone()) + }) +} + +func (self *gitCmdObjRunner) RunWithOutputs(cmdObj *oscommands.CmdObj) (string, string, error) { + var stdout, stderr string + _, err := self.retryOnLockError(func() (string, error) { + var runErr error + stdout, stderr, runErr = self.innerRunner.RunWithOutputs(cmdObj.Clone()) + return stdout + stderr, runErr + }) + return stdout, stderr, err +} + +// retryOnLockError runs the given function, retrying if it fails with a +// transient lock error (see isRetryableError). The string returned by run is +// the command output we inspect to classify the failure. We clone the command +// for each attempt (inside run) because an *exec.Cmd can only be run once. +func (self *gitCmdObjRunner) retryOnLockError(run func() (string, error)) (string, error) { var output string var err error for range RetryCount { - newCmdObj := cmdObj.Clone() - output, err = self.innerRunner.RunWithOutput(newCmdObj) + output, err = run() if err == nil || !isRetryableError(output) { return output, err @@ -51,25 +70,6 @@ func (self *gitCmdObjRunner) RunWithOutput(cmdObj *oscommands.CmdObj) (string, e return output, err } -func (self *gitCmdObjRunner) RunWithOutputs(cmdObj *oscommands.CmdObj) (string, string, error) { - var stdout, stderr string - var err error - for range RetryCount { - newCmdObj := cmdObj.Clone() - stdout, stderr, err = self.innerRunner.RunWithOutputs(newCmdObj) - - if err == nil || !isRetryableError(stdout+stderr) { - return stdout, stderr, err - } - - // if we have an error based on a lock, we should wait a bit and then retry - self.log.Warn("lock error prevented command from running. Retrying command after a small wait") - time.Sleep(WaitTime) - } - - return stdout, stderr, err -} - // Retry logic not implemented here, but these commands typically don't need to obtain a lock. func (self *gitCmdObjRunner) RunAndProcessLines(cmdObj *oscommands.CmdObj, onLine func(line string) (bool, error)) error { return self.innerRunner.RunAndProcessLines(cmdObj, onLine) diff --git a/pkg/commands/git_cmd_obj_runner_test.go b/pkg/commands/git_cmd_obj_runner_test.go new file mode 100644 index 000000000..e8c73727d --- /dev/null +++ b/pkg/commands/git_cmd_obj_runner_test.go @@ -0,0 +1,92 @@ +package commands + +import ( + "errors" + "testing" + + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/stretchr/testify/assert" +) + +type runnerResult struct { + output string + err error +} + +// scriptedRunner is an ICmdObjRunner stub that returns a preconfigured result +// for each successive call, letting us drive the retry loop deterministically. +// It counts calls so tests can assert whether a command was retried. +type scriptedRunner struct { + results []runnerResult + calls int +} + +func (self *scriptedRunner) next() (string, error) { + result := self.results[self.calls] + self.calls++ + return result.output, result.err +} + +func (self *scriptedRunner) Run(*oscommands.CmdObj) error { + _, err := self.next() + return err +} + +func (self *scriptedRunner) RunWithOutput(*oscommands.CmdObj) (string, error) { + return self.next() +} + +func (self *scriptedRunner) RunWithOutputs(*oscommands.CmdObj) (string, string, error) { + output, err := self.next() + return output, "", err +} + +func (self *scriptedRunner) RunAndProcessLines(*oscommands.CmdObj, func(string) (bool, error)) error { + panic("not implemented") +} + +func newTestRunner(inner *scriptedRunner) *gitCmdObjRunner { + return &gitCmdObjRunner{ + log: utils.NewDummyLog(), + innerRunner: inner, + } +} + +// dummyCmdObj returns a throwaway command; only its clonability matters, since +// the scriptedRunner ignores it and returns preconfigured results. +func dummyCmdObj() *oscommands.CmdObj { + return oscommands.NewDummyCmdObjBuilder(nil).New([]string{"git", "status"}) +} + +func TestRunWithOutputReturnsSuccessWithoutRetrying(t *testing.T) { + inner := &scriptedRunner{results: []runnerResult{{output: "done", err: nil}}} + + output, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + assert.NoError(t, err) + assert.Equal(t, "done", output) + assert.Equal(t, 1, inner.calls) +} + +func TestRunWithOutputDoesNotRetryNonLockError(t *testing.T) { + inner := &scriptedRunner{results: []runnerResult{{output: "boom", err: errors.New("boom")}}} + + _, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + assert.Error(t, err) + assert.Equal(t, 1, inner.calls) +} + +func TestRunWithOutputRetriesWhenLockErrorIsInOutput(t *testing.T) { + inner := &scriptedRunner{results: []runnerResult{ + {output: "fatal: Unable to create '/repo/.git/index.lock': File exists.", err: errors.New("exit status 128")}, + {output: "done", err: nil}, + }} + + output, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + assert.NoError(t, err) + assert.Equal(t, "done", output) + assert.Equal(t, 2, inner.calls) +} From 0902c5c05878b97c17611cec804a99562694372f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:56:26 +0200 Subject: [PATCH 121/218] Demonstrate that a lock error in a streamed command isn't retried The gpg helper runs commands like amend with StreamOutput, so their output isn't captured and a failed run returns an empty output string; the index.lock message is carried by the error instead. isRetryableError only inspects the output, so the retry loop never fires for these commands. In practice this means a `shift-A` amend issued while a foreground `git status` refresh briefly holds index.lock fails outright instead of retrying. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_runner_test.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pkg/commands/git_cmd_obj_runner_test.go b/pkg/commands/git_cmd_obj_runner_test.go index e8c73727d..2ff2795dc 100644 --- a/pkg/commands/git_cmd_obj_runner_test.go +++ b/pkg/commands/git_cmd_obj_runner_test.go @@ -90,3 +90,22 @@ func TestRunWithOutputRetriesWhenLockErrorIsInOutput(t *testing.T) { assert.Equal(t, "done", output) assert.Equal(t, 2, inner.calls) } + +func TestRunWithOutputRetriesWhenLockErrorIsOnlyInError(t *testing.T) { + // A streamed command (e.g. an amend run through the gpg helper) doesn't + // capture its output, so a lock failure surfaces only in the returned error + // with an empty output string. The retry logic must still recognize it. + inner := &scriptedRunner{results: []runnerResult{ + {output: "", err: errors.New("fatal: Unable to create '/repo/.git/index.lock': File exists.")}, + {output: "", err: nil}, + }} + + _, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + /* EXPECTED: + assert.NoError(t, err) + assert.Equal(t, 2, inner.calls) + ACTUAL: */ + assert.Error(t, err) + assert.Equal(t, 1, inner.calls) +} From c1cd500fa776c54f61b4cf6dddf6de0d90c7aa1a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:56:56 +0200 Subject: [PATCH 122/218] Retry lock errors reported only through the command's error Have isRetryableError also inspect the returned error, not just the captured output. Streamed commands (amend, commit, and other operations run through the gpg helper) don't capture output, so their index.lock failures were slipping past the retry loop and surfacing to the user as a hard "Git command failed". Now they retry like every other command. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_runner.go | 18 ++++++++++++------ pkg/commands/git_cmd_obj_runner_test.go | 4 ---- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/pkg/commands/git_cmd_obj_runner.go b/pkg/commands/git_cmd_obj_runner.go index a72565b5c..f22a0f7aa 100644 --- a/pkg/commands/git_cmd_obj_runner.go +++ b/pkg/commands/git_cmd_obj_runner.go @@ -20,11 +20,17 @@ type gitCmdObjRunner struct { innerRunner oscommands.ICmdObjRunner } -// isRetryableError returns true if the error output indicates a transient -// lock-related error that may succeed on retry -func isRetryableError(output string) bool { - return strings.Contains(output, ".git/index.lock") || - strings.Contains(output, "cannot lock ref") +// isRetryableError returns true if a failed command hit a transient +// lock-related condition that may succeed on retry. The lock message can reach +// us either in the command's captured output or, for streamed commands whose +// output we don't capture, only in the returned error, so we check both. +func isRetryableError(output string, err error) bool { + text := output + if err != nil { + text += "\n" + err.Error() + } + return strings.Contains(text, ".git/index.lock") || + strings.Contains(text, "cannot lock ref") } func (self *gitCmdObjRunner) Run(cmdObj *oscommands.CmdObj) error { @@ -58,7 +64,7 @@ func (self *gitCmdObjRunner) retryOnLockError(run func() (string, error)) (strin for range RetryCount { output, err = run() - if err == nil || !isRetryableError(output) { + if err == nil || !isRetryableError(output, err) { return output, err } diff --git a/pkg/commands/git_cmd_obj_runner_test.go b/pkg/commands/git_cmd_obj_runner_test.go index 2ff2795dc..903c6a90b 100644 --- a/pkg/commands/git_cmd_obj_runner_test.go +++ b/pkg/commands/git_cmd_obj_runner_test.go @@ -102,10 +102,6 @@ func TestRunWithOutputRetriesWhenLockErrorIsOnlyInError(t *testing.T) { _, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) - /* EXPECTED: assert.NoError(t, err) assert.Equal(t, 2, inner.calls) - ACTUAL: */ - assert.Error(t, err) - assert.Equal(t, 1, inner.calls) } From e3ecb77939e191281ef3a70509be1183acc2b41e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:57:26 +0200 Subject: [PATCH 123/218] Recognize index.lock contention in worktrees and submodules The retry check matched the literal ".git/index.lock", which only ever appears for the main worktree. A linked worktree's lock is at .git/worktrees//index.lock and a submodule's is under its own git dir, so contention there was never retried. Match the bare "index.lock" fragment instead, which covers all of them. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_runner.go | 7 ++++++- pkg/commands/git_cmd_obj_runner_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/commands/git_cmd_obj_runner.go b/pkg/commands/git_cmd_obj_runner.go index f22a0f7aa..c4d2ec049 100644 --- a/pkg/commands/git_cmd_obj_runner.go +++ b/pkg/commands/git_cmd_obj_runner.go @@ -24,12 +24,17 @@ type gitCmdObjRunner struct { // lock-related condition that may succeed on retry. The lock message can reach // us either in the command's captured output or, for streamed commands whose // output we don't capture, only in the returned error, so we check both. +// +// We match the bare "index.lock" fragment rather than a fuller path or message +// so we catch the lock wherever git puts it: the main .git dir, a linked +// worktree's git dir (.git/worktrees//index.lock), or a submodule's git +// dir. func isRetryableError(output string, err error) bool { text := output if err != nil { text += "\n" + err.Error() } - return strings.Contains(text, ".git/index.lock") || + return strings.Contains(text, "index.lock") || strings.Contains(text, "cannot lock ref") } diff --git a/pkg/commands/git_cmd_obj_runner_test.go b/pkg/commands/git_cmd_obj_runner_test.go index 903c6a90b..2cde503f5 100644 --- a/pkg/commands/git_cmd_obj_runner_test.go +++ b/pkg/commands/git_cmd_obj_runner_test.go @@ -105,3 +105,18 @@ func TestRunWithOutputRetriesWhenLockErrorIsOnlyInError(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 2, inner.calls) } + +func TestRunWithOutputRetriesLockErrorInLinkedWorktree(t *testing.T) { + // In a linked worktree the lock lives at .git/worktrees//index.lock + // rather than .git/index.lock, so only matching the bare "index.lock" + // fragment lets the retry fire there too. + inner := &scriptedRunner{results: []runnerResult{ + {output: "", err: errors.New("fatal: Unable to create '/repo/.git/worktrees/feature/index.lock': File exists.")}, + {output: "", err: nil}, + }} + + _, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + assert.NoError(t, err) + assert.Equal(t, 2, inner.calls) +} From 4052057eee1073f2afe7c5cc1e3027995167c642 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:58:22 +0200 Subject: [PATCH 124/218] Back off exponentially between lock-error retries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The retry budget was five fixed 50ms waits (250ms total). A foreground `git status` refresh can hold index.lock for longer than that on a large repo, so the retries could be exhausted before the lock clears. Wait 20ms before the first retry and double each time, giving seven attempts over a bit more than a second — enough to outlast a slow refresh while keeping the common case (a lock that clears almost immediately) fast. The initial delay is now a runner field so tests can zero it out instead of sleeping. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/git_cmd_obj_builder.go | 5 +++-- pkg/commands/git_cmd_obj_runner.go | 28 ++++++++++++++++++------- pkg/commands/git_cmd_obj_runner_test.go | 15 +++++++++++++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/pkg/commands/git_cmd_obj_builder.go b/pkg/commands/git_cmd_obj_builder.go index 6bc3b7d19..20d31c11c 100644 --- a/pkg/commands/git_cmd_obj_builder.go +++ b/pkg/commands/git_cmd_obj_builder.go @@ -25,8 +25,9 @@ func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuild // the price of having a convenient interface where we can say .New(...).Run() is that our builder now depends on our runner, so when we want to wrap the default builder/runner in new functionality we need to jump through some hoops. We could avoid the use of a decorator function here by just exporting the runner field on the default builder but that would be misleading because we don't want anybody using that to run commands (i.e. we want there to be a single API used across the codebase) updatedBuilder := innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner { return &gitCmdObjRunner{ - log: log, - innerRunner: runner, + log: log, + innerRunner: runner, + initialRetryDelay: defaultInitialRetryDelay, } }) diff --git a/pkg/commands/git_cmd_obj_runner.go b/pkg/commands/git_cmd_obj_runner.go index c4d2ec049..8112b0f30 100644 --- a/pkg/commands/git_cmd_obj_runner.go +++ b/pkg/commands/git_cmd_obj_runner.go @@ -11,13 +11,24 @@ import ( // here we're wrapping the default command runner in some git-specific stuff e.g. retry logic if we get an error due to the presence of .git/index.lock const ( - WaitTime = 50 * time.Millisecond - RetryCount = 5 + // defaultInitialRetryDelay is how long we wait before the first retry of a + // command that failed with a transient lock error. We double it before each + // subsequent retry (see retryOnLockError), so across maxRetries attempts we + // wait for a bit over a second in total. That's long enough to outlast the + // brief window during which another git process holds a lock we need — + // typically our own foreground `git status` refresh, which takes index.lock + // to persist its refreshed stat-cache. + defaultInitialRetryDelay = 20 * time.Millisecond + maxRetries = 7 ) type gitCmdObjRunner struct { log *logrus.Entry innerRunner oscommands.ICmdObjRunner + // initialRetryDelay is the wait before the first lock-error retry. It's a + // field rather than the constant directly so tests can set it to zero and + // not actually sleep. + initialRetryDelay time.Duration } // isRetryableError returns true if a failed command hit a transient @@ -64,18 +75,21 @@ func (self *gitCmdObjRunner) RunWithOutputs(cmdObj *oscommands.CmdObj) (string, // the command output we inspect to classify the failure. We clone the command // for each attempt (inside run) because an *exec.Cmd can only be run once. func (self *gitCmdObjRunner) retryOnLockError(run func() (string, error)) (string, error) { + delay := self.initialRetryDelay var output string var err error - for range RetryCount { + for attempt := range maxRetries { output, err = run() if err == nil || !isRetryableError(output, err) { - return output, err + break } - // if we have an error based on a lock, we should wait a bit and then retry - self.log.Warn("lock error prevented command from running. Retrying command after a small wait") - time.Sleep(WaitTime) + if attempt < maxRetries-1 { + self.log.Warnf("lock error prevented command from running; retrying in %s", delay) + time.Sleep(delay) + delay *= 2 + } } return output, err diff --git a/pkg/commands/git_cmd_obj_runner_test.go b/pkg/commands/git_cmd_obj_runner_test.go index 2cde503f5..bf938da54 100644 --- a/pkg/commands/git_cmd_obj_runner_test.go +++ b/pkg/commands/git_cmd_obj_runner_test.go @@ -50,6 +50,8 @@ func newTestRunner(inner *scriptedRunner) *gitCmdObjRunner { return &gitCmdObjRunner{ log: utils.NewDummyLog(), innerRunner: inner, + // don't actually sleep between retries + initialRetryDelay: 0, } } @@ -106,6 +108,19 @@ func TestRunWithOutputRetriesWhenLockErrorIsOnlyInError(t *testing.T) { assert.Equal(t, 2, inner.calls) } +func TestRunWithOutputGivesUpAfterMaxRetries(t *testing.T) { + results := make([]runnerResult, maxRetries) + for i := range results { + results[i] = runnerResult{err: errors.New("fatal: Unable to create '/repo/.git/index.lock': File exists.")} + } + inner := &scriptedRunner{results: results} + + _, err := newTestRunner(inner).RunWithOutput(dummyCmdObj()) + + assert.Error(t, err) + assert.Equal(t, maxRetries, inner.calls) +} + func TestRunWithOutputRetriesLockErrorInLinkedWorktree(t *testing.T) { // In a linked worktree the lock lives at .git/worktrees//index.lock // rather than .git/index.lock, so only matching the bare "index.lock" From 49eefbcf379935999132041f3e24d4b60f6e1d7d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 09:35:24 +0200 Subject: [PATCH 125/218] Make the user-event queue unbounded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update and friends enqueued onto a fixed 256-slot channel with a non-blocking send that panicked when the channel was full. That guard was firing in real use: - Toggling a directory of several hundred files into a custom patch (reliably): the operation runs on a worker behind a waiting status, whose spinner enqueues a content-only render on every tick, and over the long operation these outrun the UI loop and overflow the buffer. - Editing the config in an editor that suspends lazygit: the editor subprocess runs on the UI thread, so the loop drains nothing for the whole editing session, and the full refresh fired on resume fans out across every scope at once — a burst of updates that overflows before the just-resumed loop catches up. - Any time the UI thread blocks for a long time, the periodic refreshes keep enqueuing and eventually overflow. The 256-slot buffer was chosen deliberately, with the panic as a "should never happen" guard, to preserve two properties: FIFO ordering of same-goroutine Update calls (an earlier goroutine-per-Update design reordered them), and no self-deadlock (a blocking send from the UI thread would block against the loop that drains it). But a fixed channel can only offer those by crashing on overflow. Replace it with an unbounded, order-preserving queue: a mutex-guarded slice plus a buffered(1) doorbell channel that wakes the main loop's select. Enqueuing appends and rings the doorbell; the loop drains the slice to empty on each wake. This keeps FIFO order and never blocks the caller, so there is no self-deadlock and no overflow to panic on — under a stall the queue just grows and then drains. This also removes an inconsistency: updateContentOnly did a plain blocking send while update panicked, so the two paths disagreed on what happened when the queue was full. Both now share the same enqueue. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/flush_test.go | 10 +-- pkg/gocui/gui.go | 111 ++++++++++++++++++++++------- pkg/gocui/user_event_queue_test.go | 80 +++++++++++++++++++++ 3 files changed, 171 insertions(+), 30 deletions(-) create mode 100644 pkg/gocui/user_event_queue_test.go diff --git a/pkg/gocui/flush_test.go b/pkg/gocui/flush_test.go index 59bae427c..d4082fcf6 100644 --- a/pkg/gocui/flush_test.go +++ b/pkg/gocui/flush_test.go @@ -39,15 +39,15 @@ func setupViews(t *testing.T, g *Gui) (*View, *View) { return status, main } -// pushContentOnly pushes a content-only event directly to the channel -// (synchronous, deterministic — unlike Update which spawns a goroutine). +// pushContentOnly enqueues a content-only event directly, letting the test +// control the contentOnly flag (which Update/UpdateContentOnly hard-code). func pushContentOnly(g *Gui, f func(*Gui) error) { - g.userEvents <- userEvent{f: f, task: g.NewTask(), contentOnly: true} + g.userEvents.enqueue(userEvent{f: f, task: g.NewTask(), contentOnly: true}) } -// pushRegular pushes a regular event directly to the channel. +// pushRegular enqueues a regular (non-content-only) event directly. func pushRegular(g *Gui, f func(*Gui) error) { - g.userEvents <- userEvent{f: f, task: g.NewTask(), contentOnly: false} + g.userEvents.enqueue(userEvent{f: f, task: g.NewTask(), contentOnly: false}) } func TestFlushContentOnly_SkipsUntaintedViews(t *testing.T) { diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index ee1995911..103c90483 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -131,7 +131,7 @@ type Gui struct { viewMouseBindings []*ViewMouseBinding lastClick *clickInfo gEvents chan GocuiEvent - userEvents chan userEvent + userEvents *userEventQueue views []*View currentView *View managers []Manager @@ -238,12 +238,7 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { g.stop = make(chan struct{}) g.gEvents = make(chan GocuiEvent, 20) - // Update does a non-blocking send and panics on a full channel rather than - // blocking (which would deadlock the UI goroutine against itself) or - // silently reordering. The buffer is sized well above the peak occupancy we - // see in practice, so the panic stays unreachable in normal use; if it ever - // fires, that's a real anomaly to investigate, not a cue to grow the buffer. - g.userEvents = make(chan userEvent, 256) + g.userEvents = newUserEventQueue() g.taskManager = newTaskManager() if opts.PlayRecording { @@ -618,29 +613,83 @@ type userEvent struct { contentOnly bool } -// Update enqueues f on the user-events channel for the UI loop to run on its -// next iteration. Multiple Update calls from the same goroutine arrive in -// source order via the channel's FIFO. The send is non-blocking — if the -// channel is full we panic rather than block or silently reorder, since a -// blocked send from the UI goroutine would deadlock against itself and -// silently switching to inline execution would break the ordering guarantee -// callers rely on. The buffer is sized generously enough that this should -// never fire in practice; if it does, that's a signal to investigate, not -// to grow the buffer reflexively. -func (g *Gui) Update(f func(*Gui) error) { - task := g.NewTask() +// userEventQueue is an unbounded, order-preserving FIFO of work enqueued by +// Update and friends for the main loop to run. +// +// It's unbounded (rather than a fixed-size channel) because producers must +// never block or lose work. Update can be called from the UI goroutine itself, +// where a blocking send would deadlock against the loop that drains the queue; +// and it can be called from arbitrary worker goroutines that may enqueue faster +// than the loop drains. That happens while the loop is stalled — suspended for +// a subprocess (the editor runs on the UI thread), or hung in a long handler — +// and also when a long-running worker operation emits a steady stream of +// updates that outpaces the loop (e.g. the waiting-status spinner ticks while a +// large directory is toggled into a custom patch). A fixed channel forces a +// choice between blocking (deadlock), dropping or reordering, and panicking on +// overflow; an unbounded queue avoids all three while preserving FIFO order. +// +// enqueue appends under the mutex and rings the doorbell; the main loop selects +// on the doorbell to wake, then drains the slice to empty. The doorbell is +// buffered(1) and rung with a non-blocking send, so it's a coalescing "work +// pending" flag rather than a per-event signal: a burst of appends leaves at +// most one token, and the loop drains everything the token represents on a +// single wake. A token left over after a drain (because the drain happened to +// empty the slice after the ring) just causes one harmless empty wake. +type userEventQueue struct { + mutex sync.Mutex + events []userEvent + doorbell chan struct{} +} + +func newUserEventQueue() *userEventQueue { + return &userEventQueue{doorbell: make(chan struct{}, 1)} +} + +// enqueue appends an event and wakes the main loop. It never blocks. +func (q *userEventQueue) enqueue(ev userEvent) { + q.mutex.Lock() + q.events = append(q.events, ev) + q.mutex.Unlock() select { - case g.userEvents <- userEvent{f: f, task: task}: + case q.doorbell <- struct{}{}: default: - panic("gocui: userEvents channel full; refusing to block or reorder") } } +// dequeue pops the oldest event, reporting false when the queue is empty. +func (q *userEventQueue) dequeue() (userEvent, bool) { + q.mutex.Lock() + defer q.mutex.Unlock() + + if len(q.events) == 0 { + return userEvent{}, false + } + ev := q.events[0] + if len(q.events) == 1 { + // Release the backing array whenever the queue drains, so a one-off + // burst doesn't pin its peak size for the rest of the session. + q.events = nil + } else { + q.events[0] = userEvent{} + q.events = q.events[1:] + } + return ev, true +} + +// Update enqueues f for the UI loop to run on its next iteration. Multiple +// Update calls from the same goroutine arrive in source order (the queue is +// FIFO). The enqueue never blocks and never drops work; see userEventQueue for +// why the queue is unbounded. +func (g *Gui) Update(f func(*Gui) error) { + task := g.NewTask() + g.userEvents.enqueue(userEvent{f: f, task: task}) +} + // Like Update, but signals that the callback only modifies content. func (g *Gui) UpdateContentOnly(f func(*Gui) error) { task := g.NewTask() - g.userEvents <- userEvent{f: f, task: task, contentOnly: true} + g.userEvents.enqueue(userEvent{f: f, task: task, contentOnly: true}) } // Calls a function in a goroutine. Handles panics gracefully and tracks @@ -766,7 +815,14 @@ func (g *Gui) processEvent() error { if err := g.handleError(g.handleEvent(&ev)); err != nil { return err } - case ev := <-g.userEvents: + case <-g.userEvents.doorbell: + ev, ok := g.userEvents.dequeue() + if !ok { + // A leftover doorbell token whose events were already drained by a + // previous iteration's processRemainingEvents: nothing to run and + // nothing new to render. + return nil + } contentOnly = ev.contentOnly defer func() { ev.task.Done() }() @@ -798,15 +854,20 @@ func (g *Gui) processRemainingEvents() (bool, error) { if err := g.handleError(g.handleEvent(&ev)); err != nil { return false, err } - case ev := <-g.userEvents: + default: + // No gui event is pending; drain a queued user event instead. + // gui events take priority so input stays responsive, but they're + // bounded (buffer of 20), so this can't starve the user-event queue. + ev, ok := g.userEvents.dequeue() + if !ok { + return contentOnly, nil + } contentOnly = ev.contentOnly && contentOnly err := g.handleError(ev.f(g)) ev.task.Done() if err != nil { return false, err } - default: - return contentOnly, nil } } } diff --git a/pkg/gocui/user_event_queue_test.go b/pkg/gocui/user_event_queue_test.go new file mode 100644 index 000000000..10e86eef8 --- /dev/null +++ b/pkg/gocui/user_event_queue_test.go @@ -0,0 +1,80 @@ +package gocui + +import ( + "sync" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Enqueuing far more events than the old fixed 256-slot buffer, without the +// main loop draining them, used to panic ("userEvents channel full"). It must +// not: producers can legitimately burst faster than a stalled UI loop drains +// (e.g. one command-log entry per git command when adding a large directory to +// a custom patch, or any producer while the loop is blocked in a subprocess). +// The events must also stay in FIFO order. +func TestUpdateIsUnboundedAndPreservesOrder(t *testing.T) { + g := newTestGui(t) + + const n = 1000 + var got []int + for i := range n { + g.Update(func(*Gui) error { + got = append(got, i) + return nil + }) + } + + // Drain the whole queue the way the main loop's inner drain does. + _, err := g.processRemainingEvents() + assert.NoError(t, err) + + want := make([]int, n) + for i := range want { + want[i] = i + } + assert.Equal(t, want, got) +} + +// Concurrent producers must be able to enqueue safely (run under -race). Only +// same-goroutine order is guaranteed, so we check that every event is delivered +// exactly once and that each producer's own events stay in order. +func TestUpdateConcurrentProducers(t *testing.T) { + g := newTestGui(t) + + const producers = 8 + const perProducer = 500 + + type item struct{ producer, seq int } + var got []item + + var wg sync.WaitGroup + for p := range producers { + wg.Add(1) + go func() { + defer wg.Done() + for seq := range perProducer { + g.Update(func(*Gui) error { + got = append(got, item{p, seq}) + return nil + }) + } + }() + } + // Update is a synchronous, non-blocking enqueue, so once every producer has + // returned, every event is in the queue and a single drain sees them all. + wg.Wait() + + _, err := g.processRemainingEvents() + assert.NoError(t, err) + + assert.Len(t, got, producers*perProducer) + lastSeq := make([]int, producers) + for p := range lastSeq { + lastSeq[p] = -1 + } + for _, it := range got { + assert.Equal(t, lastSeq[it.producer]+1, it.seq, "producer %d events out of order", it.producer) + lastSeq[it.producer] = it.seq + } +} From f0b139f3ab42f833b42792c10fd63f361de04a76 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 12:50:57 +0200 Subject: [PATCH 126/218] Log the user-event queue's high-water mark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that the queue is unbounded, its depth is a useful signal for understanding how the event loop behaves under load — and we expect it to look very different across builds (e.g. master, which carries the bounce-state-updates-to-ui-thread work, versus the v0.63.0 release this fix ships in). Track the deepest the queue has ever been and log an Info line whenever that record is broken, so the numbers show up in the log for later reasoning. The mark is session-wide and doesn't reset when the queue drains. gocui has no logger of its own, so it exposes the new depth through a handler (matching the existing SetFocusHandler / SetOpenHyperlinkFunc pattern) that the gui registers to log via its own logger. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/gui.go | 32 ++++++++++++++++++++++++++++++ pkg/gocui/user_event_queue_test.go | 31 +++++++++++++++++++++++++++++ pkg/gui/gui.go | 4 ++++ 3 files changed, 67 insertions(+) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 103c90483..bb9fc9874 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -603,6 +603,13 @@ func (g *Gui) SetRenderSearchStatusFunc(renderSearchStatusFunc func(*View, int, g.renderSearchStatusFunc = renderSearchStatusFunc } +// SetUpdateQueueHighWaterMarkHandler registers a diagnostic callback invoked +// with the new depth whenever the queue of pending Update callbacks reaches a +// new maximum. It may be called from any goroutine. +func (g *Gui) SetUpdateQueueHighWaterMarkHandler(f func(depth int)) { + g.userEvents.setHighWaterMarkHandler(f) +} + // userEvent represents an event triggered by the user. type userEvent struct { f func(*Gui) error @@ -639,6 +646,13 @@ type userEventQueue struct { mutex sync.Mutex events []userEvent doorbell chan struct{} + + // highWaterMark is the deepest the queue has ever been, and + // onHighWaterMark (if set) is called with the new depth each time that + // record is broken. Purely diagnostic: it lets us see how deep the queue + // gets in practice (see SetUpdateQueueHighWaterMarkHandler). + highWaterMark int + onHighWaterMark func(int) } func newUserEventQueue() *userEventQueue { @@ -649,14 +663,32 @@ func newUserEventQueue() *userEventQueue { func (q *userEventQueue) enqueue(ev userEvent) { q.mutex.Lock() q.events = append(q.events, ev) + newHighWaterMark := 0 + if len(q.events) > q.highWaterMark { + q.highWaterMark = len(q.events) + newHighWaterMark = q.highWaterMark + } + onHighWaterMark := q.onHighWaterMark q.mutex.Unlock() + // Report outside the lock: the handler does I/O (logging) and must not + // stall other producers or the draining loop. + if newHighWaterMark > 0 && onHighWaterMark != nil { + onHighWaterMark(newHighWaterMark) + } + select { case q.doorbell <- struct{}{}: default: } } +func (q *userEventQueue) setHighWaterMarkHandler(f func(int)) { + q.mutex.Lock() + q.onHighWaterMark = f + q.mutex.Unlock() +} + // dequeue pops the oldest event, reporting false when the queue is empty. func (q *userEventQueue) dequeue() (userEvent, bool) { q.mutex.Lock() diff --git a/pkg/gocui/user_event_queue_test.go b/pkg/gocui/user_event_queue_test.go index 10e86eef8..e547debb4 100644 --- a/pkg/gocui/user_event_queue_test.go +++ b/pkg/gocui/user_event_queue_test.go @@ -36,6 +36,37 @@ func TestUpdateIsUnboundedAndPreservesOrder(t *testing.T) { assert.Equal(t, want, got) } +// The high-water-mark handler fires only when the queue reaches a new maximum +// depth, reporting that depth. It does not reset when the queue drains. +func TestUpdateQueueHighWaterMark(t *testing.T) { + g := newTestGui(t) + + var marks []int + g.SetUpdateQueueHighWaterMarkHandler(func(depth int) { marks = append(marks, depth) }) + + noop := func(*Gui) error { return nil } + + // Three enqueues with no drain: new highs 1, 2, 3. + g.Update(noop) + g.Update(noop) + g.Update(noop) + _, err := g.processRemainingEvents() + assert.NoError(t, err) + + // Two enqueues stay below the previous high of 3: no new marks. + g.Update(noop) + g.Update(noop) + _, err = g.processRemainingEvents() + assert.NoError(t, err) + + // Four enqueues with no drain: only depth 4 beats the previous high. + for range 4 { + g.Update(noop) + } + + assert.Equal(t, []int{1, 2, 3, 4}, marks) +} + // Concurrent producers must be able to enqueue safely (run under -race). Only // same-goroutine order is guaranteed, so we check that every event is delivered // exactly once and that each producer's own events stay in order. diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index e23afd124..61d4a90e2 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -414,6 +414,10 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context return nil }) + gui.g.SetUpdateQueueHighWaterMarkHandler(func(depth int) { + gui.c.Log.Infof("User-event queue reached a new high-water mark: %d", depth) + }) + gui.g.SetOnSelectSearchResultFunc(func(v *gocui.View, selectedLineIdx int) { ctx, ok := gui.helpers.View.ContextForView(v.Name()) if ok { From f116874f0a8c243642ee7ea3ae5caffa1e2ec782 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 10:07:15 +0200 Subject: [PATCH 127/218] Fix a deadlock when a Windows pty task is stopped mid-output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit winPty.Close could block indefinitely, and it is called while holding the global PtyMutex and while the task's onDone sync.Once is executing, so blocking there wedges the task's entire cleanup chain: the next NewTask call blocks on <-notifyStopped while holding waitingMutex, every later task for that view queues up behind it, and onResize blocks on PtyMutex — a full UI freeze. (Reported by a user via go-deadlock's 30s watchdog; a regression from the ConPTY support introduced for v0.63.0.) ClosePseudoConsole is what blocks; before Windows 11 24H2 it can do so in two ways. It flushes the client's pending output into the out pipe, but a stopped task's scanner goroutine has already quit draining, so with a client that's still producing output the flush never completes; this can also wedge the background waiter's closeHpc, which runs with the pipes deliberately left open. And it waits for the console host to exit, but closing only delivers CTRL_CLOSE_EVENT to the attached client without terminating it, so a client that keeps running (git still computing an expensive diff, a pager waiting for input) keeps the host alive arbitrarily long. Run the teardown on a background goroutine so Close returns immediately no matter which of these strikes, and within it close our pipe ends before the pseudoconsole, without taking p.mu: breaking the pipes fails a pending flush fast, which also unblocks a waiter already stuck in one. Co-Authored-By: Claude Fable 5 --- pkg/commands/oscommands/pty_windows.go | 53 +++++++++++++++----------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/pkg/commands/oscommands/pty_windows.go b/pkg/commands/oscommands/pty_windows.go index 0a4a06477..72ade5110 100644 --- a/pkg/commands/oscommands/pty_windows.go +++ b/pkg/commands/oscommands/pty_windows.go @@ -7,6 +7,7 @@ import ( "sync" "unsafe" + "github.com/jesseduffield/lazygit/pkg/utils" "golang.org/x/sys/windows" ) @@ -15,15 +16,13 @@ type winPty struct { inWrite *os.File outRead *os.File - // mu guards the teardown state below and serializes it against Resize. - // hpcClosed gates ClosePseudoConsole (it must run exactly once) and also - // keeps Resize from touching the HPCON once it's been freed: the - // background waiter in StartPty closes the pseudoconsole on child exit, - // which would otherwise race a concurrent onResize and hand - // ResizePseudoConsole a freed handle. + // mu guards hpcClosed, which gates ClosePseudoConsole (it must run + // exactly once) and also keeps Resize from touching the HPCON once it's + // been freed: the background waiter in StartPty closes the pseudoconsole + // on child exit, which would otherwise race a concurrent onResize and + // hand ResizePseudoConsole a freed handle. mu sync.Mutex hpcClosed bool - closed bool } func (p *winPty) Read(buf []byte) (int, error) { return p.outRead.Read(buf) } @@ -49,11 +48,6 @@ func (p *winPty) Resize(cols, rows uint16) error { func (p *winPty) closeHpc() { p.mu.Lock() defer p.mu.Unlock() - p.closeHpcLocked() -} - -// closeHpcLocked closes the pseudoconsole; the caller must hold p.mu. -func (p *winPty) closeHpcLocked() { if p.hpcClosed { return } @@ -61,18 +55,31 @@ func (p *winPty) closeHpcLocked() { windows.ClosePseudoConsole(p.hpc) } +// Close tears the pty down without waiting for it: the teardown runs on a +// background goroutine and Close returns immediately. +// +// It has to, because ClosePseudoConsole can block for a long time: before +// Windows 11 24H2 it waits for the console host to exit, and since closing +// only delivers CTRL_CLOSE_EVENT to the attached client without terminating +// it, a client that keeps running (git still computing an expensive diff, a +// pager waiting for input) keeps the host — and with it ClosePseudoConsole — +// alive arbitrarily long. Close is called while holding the global PtyMutex +// and while the task's onDone once is executing, where blocking wedges every +// subsequent task for the view (and with it the UI), so none of this may +// happen on the caller's thread. +// +// Within the teardown, the pipe ends must be closed before the +// pseudoconsole, and without holding p.mu: closing the pseudoconsole flushes +// the client's pending output into the out pipe, and with the task stopped +// nobody is reading anymore, so that flush can only complete once the pipe +// is broken. The background waiter's closeHpc may already be wedged in such +// a flush while holding p.mu; closing the pipes is what unblocks it. func (p *winPty) Close() error { - p.mu.Lock() - defer p.mu.Unlock() - if p.closed { - return nil - } - p.closed = true - // Closing the pseudoconsole breaks the pipes; the child's next write - // fails and it exits. Then we close our ends of the pipes. - p.closeHpcLocked() - p.inWrite.Close() - p.outRead.Close() + go utils.Safe(func() { + p.inWrite.Close() + p.outRead.Close() + p.closeHpc() + }) return nil } From a65d468cd3812b98c0acb2baf8ad3e548911be40 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 10:56:56 +0200 Subject: [PATCH 128/218] Determine the latest tag from the checked-out commit's history The Get Latest Tag step used to pick the most recently created tag in the entire repo, regardless of whether it is reachable from the commit being released. In preparation for supporting releases from branches other than master, use the nearest tag that is an ancestor of the checked-out commit instead. This way, a patch release cut from an older release branch bumps that branch's own latest tag even when master already carries a newer release, and the "changes since last release" check compares against the release that actually precedes this one in history. --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9b9815d44..84636424b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -54,7 +54,7 @@ jobs: - name: Get Latest Tag run: | - latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1) || echo "v0.0.0") + latest_tag=$(git describe --tags --abbrev=0 || echo "v0.0.0") if ! [[ $latest_tag =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "Error: Tag format is invalid. Expected format: vX.X.X" From dda0af0f483b34c7105d64dceca0b088c2e7e55f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 13:16:21 +0200 Subject: [PATCH 129/218] Allow having branch and tag with the same name When creating a patch release from a branch called `v0.63.1`, the new tag would get the same name and pushing it would fail with `error: src refspec v0.63.1 matches more than one`. --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 84636424b..a3a5f62c2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -151,7 +151,7 @@ jobs: git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" git tag "$NEW_TAG" -a -m "Release $NEW_TAG" - git push origin "$NEW_TAG" + git push origin "refs/tags/$NEW_TAG" - name: Setup Go uses: actions/setup-go@v6 From 1d99ba56fc768ae64ffc125c1f5d300060eed860 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 10:57:22 +0200 Subject: [PATCH 130/218] Allow releasing from a branch other than master This is useful for cutting a patch release for the previous version when master already contains work that shouldn't be released yet; for example, v0.63.1 had to be tagged and released by hand from a v0.63.1 branch off the v0.63.0 tag because the workflow could only release master. Scheduled runs are unaffected: with no input provided, the ref is empty and the checkout falls back to the default branch. --- .github/workflows/release.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a3a5f62c2..1ef271d6f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,6 +17,11 @@ on: options: - minor - patch + branch: + description: 'Branch to release from' + type: string + required: true + default: 'master' ignore_blocks: description: 'Ignore blocking PRs/issues' type: boolean @@ -49,6 +54,7 @@ jobs: uses: actions/checkout@v7 with: repository: jesseduffield/lazygit + ref: ${{ inputs.branch }} token: ${{ secrets.LAZYGIT_RELEASE_PAT }} fetch-depth: 0 From bd8c06ddc0910bccd6522131a2ad9c0c7c143396 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 11:01:56 +0200 Subject: [PATCH 131/218] Rename version_bump options to be extra clear I keep getting slightly confused as to which is which, so make this extra clear. While at it, change the default to minor, this is the option that is more often used now that we don't have regular scheduled releases any more. --- .github/workflows/release.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ef271d6f..e3cf63bbf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,10 +13,10 @@ on: description: 'Version bump type' type: choice required: true - default: 'patch' + default: 'minor (normal)' options: - - minor - - patch + - minor (normal) + - patch (hotfix) branch: description: 'Branch to release from' type: string @@ -127,7 +127,7 @@ jobs: IFS='.' read -r major minor patch <<< "$LATEST_TAG" if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then - if [[ "$VERSION_BUMP" == "patch" ]]; then + if [[ "$VERSION_BUMP" == "patch (hotfix)" ]]; then patch=$((patch + 1)) else minor=$((minor + 1)) From 7e1073a0ee1d8338bb1c3d39d3cbbd7eedbdacee Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 14:32:48 +0200 Subject: [PATCH 132/218] Extract the tcell-to-gocui event conversion out of pollEvent A following commit needs pollEvent to attach information from the replayed-event wrappers to the GocuiEvent it returns. With the conversion inlined there is no seam to do that in, because every branch of the type switch returns directly. Co-Authored-By: Claude Fable 5 --- pkg/gocui/tcell_driver.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pkg/gocui/tcell_driver.go b/pkg/gocui/tcell_driver.go index 226ee0580..857e35bfc 100644 --- a/pkg/gocui/tcell_driver.go +++ b/pkg/gocui/tcell_driver.go @@ -300,6 +300,10 @@ func (g *Gui) pollEvent() GocuiEvent { tev = <-Screen.EventQ() } + return gocuiEventFromTcellEvent(tev) +} + +func gocuiEventFromTcellEvent(tev tcell.Event) GocuiEvent { switch tev := tev.(type) { case *tcell.EventInterrupt: return GocuiEvent{Type: eventInterrupt} From 664a65d5843765b6a0e89f2267c276c6e1bc1aab Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 14:45:52 +0200 Subject: [PATCH 133/218] Track replayed test input as busy from the moment it is submitted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Integration tests synchronize with lazygit through the task manager: after submitting an input event, the test driver waits until the program goes idle before asserting. But a submitted event only got its task once the main loop picked it up from the events channel; while it was still in flight (handed to the poller goroutine, or sitting in the channel), no task existed for it, so the program could look idle even though input was still pending. The edge-triggered idle protocol mostly papers over this: each wait is satisfied by the *next* busy-to-idle transition, which in practice is the one produced by processing the submitted event. It only goes wrong when some other task (e.g. a background refresh) completes in that window, producing an edge the waiting test mistakes for its own — a rare source of test flakes. The next commit replaces that protocol with a level-triggered one, for which the window would be fatal rather than rare: a wait falling into the gap would return immediately. Close the gap by creating the task on the test goroutine before the event is submitted, and carrying it through the poller into the main loop, which uses it instead of creating its own. The new Replay* methods own this invariant, and the replayed-events channels are no longer exported, so tests can't submit an untracked event. Co-Authored-By: Claude Fable 5 --- pkg/gocui/gui.go | 46 ++++++++++++++++++++++++++++++++++----- pkg/gocui/tcell_driver.go | 28 +++++++++++++++++++----- pkg/gui/gui_driver.go | 16 +++++++------- 3 files changed, 72 insertions(+), 18 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index ceb570c59..e5588e262 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -125,8 +125,11 @@ type clickInfo struct { // and keybindings. type Gui struct { RecordingConfig - // ReplayedEvents is for passing pre-recorded input events, for the purposes of testing - ReplayedEvents replayedEvents + // replayedEvents is for passing simulated input events, for the purposes + // of testing. Events must be submitted through the Replay* methods, which + // attach a task to each event; pushing into the channels directly would + // bypass the busy-tracking that integration tests rely on. + replayedEvents replayedEvents playRecording bool tabClickBindings []*tabClickBinding @@ -255,7 +258,7 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { g.taskManager = newTaskManager() if opts.PlayRecording { - g.ReplayedEvents = replayedEvents{ + g.replayedEvents = replayedEvents{ Keys: make(chan *TcellKeyEventWrapper), Resizes: make(chan *TcellResizeEventWrapper), MouseEvents: make(chan *TcellMouseEventWrapper), @@ -291,6 +294,30 @@ func (g *Gui) NewBackgroundTask() *TaskImpl { return g.taskManager.NewTask(true) } +// ReplayKeyEvent simulates a key press, as if the user had typed it. It's used +// by integration tests. The event carries a task, so that the program counts +// as busy from before the event is submitted until the main loop has fully +// processed it; the test driver relies on this when it waits for the program +// to go idle after submitting an event. (If the task were only created once +// the main loop picks the event up, there would be a window in which the event +// is still in flight but nothing counts as busy.) +func (g *Gui) ReplayKeyEvent(ev *TcellKeyEventWrapper) { + ev.task = g.NewTask() + g.replayedEvents.Keys <- ev +} + +// ReplayMouseEvent is like ReplayKeyEvent, but for mouse events. +func (g *Gui) ReplayMouseEvent(ev *TcellMouseEventWrapper) { + ev.task = g.NewTask() + g.replayedEvents.MouseEvents <- ev +} + +// ReplayFocusEvent is like ReplayKeyEvent, but for focus events. +func (g *Gui) ReplayFocusEvent(ev *TcellFocusEventWrapper) { + ev.task = g.NewTask() + g.replayedEvents.FocusEvents <- ev +} + // Busy reports whether any foreground work is in flight, ignoring the event // currently being processed on the main goroutine (see currentTask). Background // routines (auto-fetch etc.) don't count. It's used to decide whether it's safe @@ -948,7 +975,12 @@ func (g *Gui) processEvent() error { // are always the primary event here. select { case ev := <-g.gEvents: - task := g.NewTask() + // Replayed test events already carry their task (see ReplayKeyEvent); + // organic events get theirs here. + task := ev.task + if task == nil { + task = g.NewTask() + } g.currentTask = task defer func() { g.currentTask = nil; task.Done() }() @@ -992,7 +1024,11 @@ func (g *Gui) processRemainingEvents() (bool, error) { select { case ev := <-g.gEvents: contentOnly = false - if err := g.handleError(g.handleEvent(&ev)); err != nil { + err := g.handleError(g.handleEvent(&ev)) + if ev.task != nil { + ev.task.Done() + } + if err != nil { return false, err } default: diff --git a/pkg/gocui/tcell_driver.go b/pkg/gocui/tcell_driver.go index 857e35bfc..885bcbabb 100644 --- a/pkg/gocui/tcell_driver.go +++ b/pkg/gocui/tcell_driver.go @@ -172,6 +172,12 @@ type GocuiEvent struct { Focused bool Start bool N int + + // task tracks the processing of this event for idle detection. Events + // replayed by integration tests carry a task from the moment they are + // submitted (see Gui.ReplayKeyEvent); for organic events it is nil, and + // the main loop creates a task when it picks the event up. + task Task } // Event types. @@ -208,6 +214,8 @@ type TcellKeyEventWrapper struct { Mod tcell.ModMask Key tcell.Key Ch string + + task Task // see GocuiEvent.task } func NewTcellKeyEventWrapper(event *tcell.EventKey, timestamp int64) *TcellKeyEventWrapper { @@ -229,6 +237,8 @@ type TcellMouseEventWrapper struct { Y int ButtonMask tcell.ButtonMask ModMask tcell.ModMask + + task Task // see GocuiEvent.task } func NewTcellMouseEventWrapper(event *tcell.EventMouse, timestamp int64) *TcellMouseEventWrapper { @@ -269,6 +279,8 @@ func (wrapper TcellResizeEventWrapper) toTcellEvent() tcell.Event { type TcellFocusEventWrapper struct { Timestamp int64 Focused bool + + task Task // see GocuiEvent.task } func NewTcellFocusEventWrapper(event *tcell.EventFocus, timestamp int64) *TcellFocusEventWrapper { @@ -285,22 +297,28 @@ func (wrapper TcellFocusEventWrapper) toTcellEvent() tcell.Event { // pollEvent get tcell.Event and transform it into gocuiEvent func (g *Gui) pollEvent() GocuiEvent { var tev tcell.Event + var task Task if g.playRecording { select { - case ev := <-g.ReplayedEvents.Keys: + case ev := <-g.replayedEvents.Keys: tev = (ev).toTcellEvent() - case ev := <-g.ReplayedEvents.Resizes: + task = ev.task + case ev := <-g.replayedEvents.Resizes: tev = (ev).toTcellEvent() - case ev := <-g.ReplayedEvents.MouseEvents: + case ev := <-g.replayedEvents.MouseEvents: tev = (ev).toTcellEvent() - case ev := <-g.ReplayedEvents.FocusEvents: + task = ev.task + case ev := <-g.replayedEvents.FocusEvents: tev = (ev).toTcellEvent() + task = ev.task } } else { tev = <-Screen.EventQ() } - return gocuiEventFromTcellEvent(tev) + event := gocuiEventFromTcellEvent(tev) + event.task = task + return event } func gocuiEventFromTcellEvent(tev tcell.Event) GocuiEvent { diff --git a/pkg/gui/gui_driver.go b/pkg/gui/gui_driver.go index fef33bf66..a54530791 100644 --- a/pkg/gui/gui_driver.go +++ b/pkg/gui/gui_driver.go @@ -33,10 +33,10 @@ func (self *GuiDriver) PressKey(keyStr string) { self.Fail("Unrecognized key: " + keyStr) } - self.gui.g.ReplayedEvents.Keys <- gocui.NewTcellKeyEventWrapper( + self.gui.g.ReplayKeyEvent(gocui.NewTcellKeyEventWrapper( tcell.NewEventKey(tcell.Key(key.KeyName()), key.Str(), tcell.ModMask(key.Mod())), 0, - ) + )) self.waitTillIdle() } @@ -44,15 +44,15 @@ func (self *GuiDriver) PressKey(keyStr string) { func (self *GuiDriver) Click(x, y int) { self.CheckAllToastsAcknowledged() - self.gui.g.ReplayedEvents.MouseEvents <- gocui.NewTcellMouseEventWrapper( + self.gui.g.ReplayMouseEvent(gocui.NewTcellMouseEventWrapper( tcell.NewEventMouse(x, y, tcell.ButtonPrimary, 0), 0, - ) + )) self.waitTillIdle() - self.gui.g.ReplayedEvents.MouseEvents <- gocui.NewTcellMouseEventWrapper( + self.gui.g.ReplayMouseEvent(gocui.NewTcellMouseEventWrapper( tcell.NewEventMouse(x, y, tcell.ButtonNone, 0), 0, - ) + )) self.waitTillIdle() } @@ -60,10 +60,10 @@ func (self *GuiDriver) Click(x, y int) { // learns to reload changed config files. Tests use it to exercise the live // config-reload path. func (self *GuiDriver) FocusIn() { - self.gui.g.ReplayedEvents.FocusEvents <- gocui.NewTcellFocusEventWrapper( + self.gui.g.ReplayFocusEvent(gocui.NewTcellFocusEventWrapper( tcell.NewEventFocus(true), 0, - ) + )) self.waitTillIdle() } From 0ce857c717b391172261cb2f6498a07dccf6c076 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 14:56:27 +0200 Subject: [PATCH 134/218] Fix a deadlock between task.Done() and the integration test's idle wait MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Running the integration tests in a loop under the race detector eventually hung in demo/bisect. The goroutine dump shows the cycle: a background worker's task.Done() held the task manager's mutex while blocking on the unbuffered idle-listener channel send, and the test runner goroutine — the only reader of that channel — was itself blocked in NewTask on that same mutex, on its way to enqueueing a caption render (SetCaption -> Render -> OnUIThread). Neither side could proceed: the notification couldn't be delivered until the test goroutine got the mutex, and the mutex couldn't be released until the notification was delivered. The root problem is that the busy-to-idle notification is a blocking rendezvous performed while holding the mutex, so it needs the waiter's cooperation at a moment where the waiter may legitimately need the mutex first. Make the notification fire-and-forget instead: WaitUntilIdle waits on a condition variable and re-checks "is any task busy?" under the mutex, and the busy-to-idle transition broadcasts, which never blocks. Waiting is now level-triggered rather than edge-triggered, which is also more robust: a wait can no longer be satisfied by a stale idle transition produced by an unrelated background task, because the predicate is evaluated against the current state. This relies on the previous commit having made replayed input events carry their task from submission; without that, the wait could return in the window where an event is in flight but not yet picked up by the main loop. Co-Authored-By: Claude Fable 5 --- pkg/gocui/gui.go | 10 +++--- pkg/gocui/task_manager.go | 54 ++++++++++++++++++---------- pkg/gocui/task_manager_test.go | 66 ++++++++++++++++++++++++++++++++++ pkg/gui/gui_driver.go | 9 +++-- pkg/gui/test_mode.go | 8 ++--- 5 files changed, 112 insertions(+), 35 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index e5588e262..9da5225c0 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -326,11 +326,11 @@ func (g *Gui) Busy() bool { return g.taskManager.hasBusyForegroundTaskExcept(g.currentTask) } -// An idle listener listens for when the program is idle. This is useful for -// integration tests which can wait for the program to be idle before taking -// the next step in the test. -func (g *Gui) AddIdleListener(c chan struct{}) { - g.taskManager.addIdleListener(c) +// WaitUntilIdle blocks until the program is idle (no busy tasks). This is +// useful for integration tests which want to wait for the program to finish +// processing before taking the next step in the test. +func (g *Gui) WaitUntilIdle() { + g.taskManager.WaitUntilIdle() } // Close finalizes the library. It should be called after a successful diff --git a/pkg/gocui/task_manager.go b/pkg/gocui/task_manager.go index 23ef0f77e..8d6daaa20 100644 --- a/pkg/gocui/task_manager.go +++ b/pkg/gocui/task_manager.go @@ -6,20 +6,23 @@ import "sync" // the main goroutine or a worker goroutine). Used by integration tests // to wait until the program is idle before progressing. type TaskManager struct { - // each of these listeners will be notified when the program goes from busy to idle - idleListeners []chan struct{} - tasks map[int]Task + tasks map[int]Task // auto-incrementing id for new tasks nextId int mutex sync.Mutex + // signalled whenever the program transitions from busy to idle; used by + // WaitUntilIdle + idleCond *sync.Cond } func newTaskManager() *TaskManager { - return &TaskManager{ - tasks: make(map[int]Task), - idleListeners: []chan struct{}{}, + self := &TaskManager{ + tasks: make(map[int]Task), } + self.idleCond = sync.NewCond(&self.mutex) + + return self } func (self *TaskManager) NewTask(background bool) *TaskImpl { @@ -58,8 +61,26 @@ func (self *TaskManager) hasBusyForegroundTaskExcept(ignore Task) bool { return false } -func (self *TaskManager) addIdleListener(c chan struct{}) { - self.idleListeners = append(self.idleListeners, c) +// WaitUntilIdle blocks until no task is busy. Integration tests use it to wait +// for the program to finish processing before taking the next step. +func (self *TaskManager) WaitUntilIdle() { + self.mutex.Lock() + defer self.mutex.Unlock() + + for self.hasBusyTask() { + self.idleCond.Wait() + } +} + +// caller must hold self.mutex +func (self *TaskManager) hasBusyTask() bool { + for _, task := range self.tasks { + if task.isBusy() { + return true + } + } + + return false } func (self *TaskManager) withMutex(f func()) { @@ -68,17 +89,12 @@ func (self *TaskManager) withMutex(f func()) { f() - // Check if all tasks are done - for _, task := range self.tasks { - if task.isBusy() { - return - } - } - - // If we get here, all tasks are done, so - // notify listeners that the program is idle - for _, listener := range self.idleListeners { - listener <- struct{}{} + // Wake up any goroutine blocked in WaitUntilIdle. This must not block on + // the waiter (we hold the mutex, and the waiter may itself be trying to + // acquire it, e.g. by creating a task, before it next waits) — which is + // exactly what Broadcast guarantees. + if !self.hasBusyTask() { + self.idleCond.Broadcast() } } diff --git a/pkg/gocui/task_manager_test.go b/pkg/gocui/task_manager_test.go index 7fe706d7a..b83b678ea 100644 --- a/pkg/gocui/task_manager_test.go +++ b/pkg/gocui/task_manager_test.go @@ -2,6 +2,7 @@ package gocui import ( "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -61,3 +62,68 @@ func TestTaskManagerHasBusyForegroundTaskExcept(t *testing.T) { assert.False(t, tm.hasBusyForegroundTaskExcept(current)) }) } + +func TestTaskManagerWaitUntilIdle(t *testing.T) { + // returnsWithin reports whether f returns within the given duration. + returnsWithin := func(d time.Duration, f func()) bool { + done := make(chan struct{}) + go func() { + f() + close(done) + }() + select { + case <-done: + return true + case <-time.After(d): + return false + } + } + + t.Run("returns immediately when no task was ever created", func(t *testing.T) { + tm := newTaskManager() + assert.True(t, returnsWithin(time.Second, tm.WaitUntilIdle)) + }) + + t.Run("blocks while a task is busy", func(t *testing.T) { + tm := newTaskManager() + tm.NewTask(false) + assert.False(t, returnsWithin(50*time.Millisecond, tm.WaitUntilIdle)) + }) + + t.Run("wakes up when the last busy task completes", func(t *testing.T) { + tm := newTaskManager() + task := tm.NewTask(false) + go func() { + time.Sleep(10 * time.Millisecond) + task.Done() + }() + assert.True(t, returnsWithin(time.Second, tm.WaitUntilIdle)) + }) + + t.Run("a paused task counts as idle", func(t *testing.T) { + tm := newTaskManager() + task := tm.NewTask(false) + task.Pause() + assert.True(t, returnsWithin(time.Second, tm.WaitUntilIdle)) + }) + + t.Run("a task completing while nobody waits must not block", func(t *testing.T) { + // This is the deadlock case: the waiter (the integration-test runner) + // is between waits, and itself needs the task manager's mutex (it + // creates a task whenever it enqueues work) before it waits again. The + // idle notification must neither block the completing task while it + // holds the mutex, nor get lost. + tm := newTaskManager() + assert.True(t, returnsWithin(time.Second, func() { + // the program goes idle with nobody waiting... + tm.NewTask(true).Done() + + // ...and creating and completing more tasks afterwards must still + // be possible + task := tm.NewTask(false) + tm.NewTask(false).Done() + task.Done() + })) + assert.True(t, returnsWithin(time.Second, tm.WaitUntilIdle)) + }) +} diff --git a/pkg/gui/gui_driver.go b/pkg/gui/gui_driver.go index a54530791..31094b253 100644 --- a/pkg/gui/gui_driver.go +++ b/pkg/gui/gui_driver.go @@ -17,10 +17,9 @@ import ( // 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 + gui *Gui + toastChan chan string + headless bool } var _ integrationTypes.GuiDriver = &GuiDriver{} @@ -79,7 +78,7 @@ func (self *GuiDriver) PretendMergeOrRebaseStartedInLazygit() { // wait until lazygit is idle (i.e. all processing is done) before continuing func (self *GuiDriver) waitTillIdle() { - <-self.isIdleChan + self.gui.g.WaitUntilIdle() } func (self *GuiDriver) CheckAllToastsAcknowledged() { diff --git a/pkg/gui/test_mode.go b/pkg/gui/test_mode.go index 2ba381078..2d5958fbb 100644 --- a/pkg/gui/test_mode.go +++ b/pkg/gui/test_mode.go @@ -23,12 +23,8 @@ func (gui *Gui) handleTestMode() { } if test != nil { - isIdleChan := make(chan struct{}) - - gui.c.GocuiGui().AddIdleListener(isIdleChan) - waitUntilIdle := func() { - <-isIdleChan + gui.c.GocuiGui().WaitUntilIdle() } go func() { @@ -38,7 +34,7 @@ func (gui *Gui) handleTestMode() { gui.PopupHandler.(*popup.PopupHandler).SetToastFunc( func(message string, kind types.ToastKind) { toastChan <- message }) - test.Run(&GuiDriver{gui: gui, isIdleChan: isIdleChan, toastChan: toastChan, headless: Headless()}) + test.Run(&GuiDriver{gui: gui, toastChan: toastChan, headless: Headless()}) gui.g.Update(func(*gocui.Gui) error { return gocui.ErrQuit From d786c9d79bbf7370705d2140acb7398287b3bcd2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 16 Jul 2026 09:11:16 +0200 Subject: [PATCH 135/218] Escape the merge conflicts view before prompting to continue the rebase MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the last conflict of a file is resolved, a files refresh both offers to continue the rebase/merge (if we started it ourselves) and, via its merge-conflicts scope, escapes from the merge conflicts view back to the files context. The two race: the prompt is bounced onto the UI thread by the files worker, while the escape's context push is queued separately by EscapeMerge, and it deliberately refuses to push the files context over a popup. So if the prompt opens first, the escape does nothing, and closing the prompt lands the user in the stale merge conflicts view — usually already emptied by the escape's state reset — instead of the files panel. No later refresh rescues this. Fix this by escaping from the merge conflicts view right before opening the prompt. This runs on the UI thread and doesn't hold the merge conflicts mutex, so it can reset the state and push the files context synchronously; whichever side runs first, the prompt now always opens on top of the files context, and EscapeMerge's guarded push still does nothing only when that's the right thing to do. This is a timing race with no deterministic regression test; it showed up as a rare flake in tests that cancel the continue prompt (e.g. commit/amend_when_there_are_conflicts_and_continue) when looping the integration tests under the race detector. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 3c8524ffe..21fdc8a7a 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1207,6 +1207,19 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re // for operations we started ourselves; prompting for one that was // started outside lazygit (e.g. by a coding agent) would be confusing. self.onUIThreadUnlessRepoChanged(env, func() error { + // The merge-conflicts scope of this refresh also notices that + // the conflicts are gone and escapes from the merge conflicts + // view to the files context (see RefreshMergeState), but it + // runs concurrently with us, and its escape refuses to push + // the files context over a popup. So if our prompt opens + // first, the escape does nothing, and closing the prompt + // would land the user in the dead merge conflicts view. + // Escape it ourselves before opening the prompt, so that the + // prompt always opens on top of the files context. + if self.c.Context().IsCurrent(self.c.Contexts().MergeConflicts) { + self.mergeConflictsHelper.ResetMergeState() + self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) + } return self.mergeAndRebaseHelper.PromptToContinueRebase() }) } From 14d717d77f7ac2e722656d5405cac61b29d54379 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 08:41:25 +0200 Subject: [PATCH 136/218] Bump tcell to an unreleased snapshot to fix a shutdown race tcell's filterEvents goroutine sends events into eventQ with a plain blocking send, while Fini (via finish/finalize) closes eventQ after closing the quit channel. The goroutine can have already committed to the ev = <-inQ select arm when quit is closed, so its send into eventQ races with the close; the race detector flags this (send and close on the same channel are unsynchronized), and if the close wins, the send panics with "send on closed channel". This was caught by the integration tests under the race detector, where every test drives a real tScreen over a MockTerm and tears it down via Fini, but it equally affects real-terminal shutdown. Upstream fixed it in 243630d2 ("Fix screen Init/Fini races") by tracking the filter goroutine in a WaitGroup that finalize waits for before closing eventQ, and guarding the send with a select on quit. That commit is not in a tagged release yet (latest is v3.4.0), so pin the pseudo-version; the delta over v3.4.0 is just this fix, a Windows key-release fix, a cell-rendering perf tweak, and dependency bumps. Co-Authored-By: Claude Fable 5 --- go.mod | 10 ++-- go.sum | 20 ++++---- vendor/github.com/gdamore/tcell/v3/cell.go | 18 ++++--- vendor/github.com/gdamore/tcell/v3/tscreen.go | 28 ++++++++++- .../gdamore/tcell/v3/tty/tty_win.go | 49 ++++++++++++++----- vendor/modules.txt | 10 ++-- 6 files changed, 97 insertions(+), 38 deletions(-) diff --git a/go.mod b/go.mod index c10004176..12af7493b 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/cli/go-gh/v2 v2.13.0 github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 github.com/creack/pty v1.1.24 - github.com/gdamore/tcell/v3 v3.4.0 + github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 github.com/go-errors/errors v1.5.1 github.com/gookit/color v1.6.1 github.com/integrii/flaggy v1.8.0 @@ -65,11 +65,11 @@ require ( github.com/onsi/gomega v1.34.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect - golang.org/x/mod v0.35.0 // indirect + golang.org/x/mod v0.36.0 // indirect golang.org/x/net v0.55.0 // indirect - golang.org/x/term v0.43.0 // indirect - golang.org/x/text v0.37.0 // indirect - golang.org/x/tools v0.44.0 // indirect + golang.org/x/term v0.44.0 // indirect + golang.org/x/text v0.38.0 // indirect + golang.org/x/tools v0.45.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/fsnotify.v1 v1.4.7 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect diff --git a/go.sum b/go.sum index 1ca3151b4..2f734de11 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,8 @@ github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= -github.com/gdamore/tcell/v3 v3.4.0 h1:VUym1HQZiYodA5PGQrqLxF7QwqQndcAUwQD7G7XUy5E= -github.com/gdamore/tcell/v3 v3.4.0/go.mod h1:fjKxNiIFwbzTxDU+i+AAMz+xPOgXVaZq5tbShsKseHc= +github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 h1:kUXexBZYoVdAJIOIuP6uLgK3k0G7ClDIRO27Z3epgtU= +github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59/go.mod h1:Ev/2PFhL0QtVmu6XPZG9NEuITAZ6XH7i7/BF3wupBdw= github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= @@ -139,8 +139,8 @@ golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= -golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -168,21 +168,21 @@ golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= -golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= +golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= -golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/vendor/github.com/gdamore/tcell/v3/cell.go b/vendor/github.com/gdamore/tcell/v3/cell.go index cbe2732de..b3be03b13 100644 --- a/vendor/github.com/gdamore/tcell/v3/cell.go +++ b/vendor/github.com/gdamore/tcell/v3/cell.go @@ -72,12 +72,18 @@ func (cb *CellBuffer) put(x int, y int, str string, style Style) (string, int) { if x >= 0 && y >= 0 && x < cb.w && y < cb.h { var cl string c := &cb.cells[(y*cb.w)+x] - g := textWidthOptions.StringGraphemes(str) - for width == 0 && g.Next() { - cluster := g.Value() - cl += cluster - width = g.Width() - str = str[len(cluster):] + if str == c.currStr && c.width > 0 { + // Identical re-Put (a full-screen redraw): the grapheme split is + // unchanged, so reuse the measured width instead of segmenting. + cl, width, str = str, c.width, "" + } else { + g := textWidthOptions.StringGraphemes(str) + for width == 0 && g.Next() { + cluster := g.Value() + cl += cluster + width = g.Width() + str = str[len(cluster):] + } } // Wide characters: we want to mark the "wide" cells diff --git a/vendor/github.com/gdamore/tcell/v3/tscreen.go b/vendor/github.com/gdamore/tcell/v3/tscreen.go index 2fa180f63..9fe3cf8fe 100644 --- a/vendor/github.com/gdamore/tcell/v3/tscreen.go +++ b/vendor/github.com/gdamore/tcell/v3/tscreen.go @@ -243,6 +243,7 @@ type tScreen struct { legacy bool hasClipboard bool // true if OSC 52 reported via DA1 finiOnce sync.Once + initFiniLock sync.Mutex enterUrl string exitUrl string setWinSize string @@ -258,6 +259,7 @@ type tScreen struct { running bool startTime time.Time wg sync.WaitGroup + eventWg sync.WaitGroup mouseFlags MouseFlags pasteEnabled bool focusEnabled bool @@ -355,6 +357,20 @@ func (t *tScreen) applyEnvironmentOverrides() { } func (t *tScreen) Init() error { + t.initFiniLock.Lock() + defer t.initFiniLock.Unlock() + + t.Lock() + if t.fini { + t.Unlock() + return errors.New("screen finalized") + } + if t.running { + t.Unlock() + return errors.New("already initialized") + } + t.Unlock() + if e := t.initialize(); e != nil { return e } @@ -525,7 +541,9 @@ func (t *tScreen) processInitQ() { func (t *tScreen) filterEvents() chan Event { inQ := make(chan Event, 128) + t.eventWg.Add(1) go func() { + defer t.eventWg.Done() for { var ev Event select { @@ -541,7 +559,11 @@ func (t *tScreen) filterEvents() chan Event { } default: - t.eventQ <- ev + select { + case t.eventQ <- ev: + case <-t.quit: + return + } } } }() @@ -596,6 +618,9 @@ func (t *tScreen) prepareCursorStyles() { } func (t *tScreen) Fini() { + t.initFiniLock.Lock() + defer t.initFiniLock.Unlock() + // Ensure that enough time passes for terminals to finish sending // their initial response (gnome-terminal sends terminal dimensions // asynchronously later than the response to primary DA for some reason.) @@ -1659,6 +1684,7 @@ func (t *tScreen) Beep() error { func (t *tScreen) finalize() { t.disengage() _ = t.tty.Close() + t.eventWg.Wait() close(t.eventQ) } diff --git a/vendor/github.com/gdamore/tcell/v3/tty/tty_win.go b/vendor/github.com/gdamore/tcell/v3/tty/tty_win.go index 853c1e136..e17cd7dab 100644 --- a/vendor/github.com/gdamore/tcell/v3/tty/tty_win.go +++ b/vendor/github.com/gdamore/tcell/v3/tty/tty_win.go @@ -20,6 +20,7 @@ package tty import ( "encoding/binary" "errors" + "fmt" "sync" "syscall" "time" @@ -98,6 +99,38 @@ type inputRecord struct { data [16]byte } +func encodeWinKeyRecord(data [16]byte, surrogate *rune) []byte { + keyDown := binary.LittleEndian.Uint32(data[0:]) != 0 + repeat := binary.LittleEndian.Uint16(data[4:]) + virtualKey := binary.LittleEndian.Uint16(data[6:]) + scanCode := binary.LittleEndian.Uint16(data[8:]) + // we normally only expect to see ascii, but paste data may come in as UTF-16. + wc := rune(binary.LittleEndian.Uint16(data[10:])) + controlState := binary.LittleEndian.Uint32(data[12:]) + + if virtualKey != 0 || scanCode != 0 { + kd := 0 + if keyDown { + kd = 1 + } + return fmt.Appendf(nil, "\x1b[%d;%d;%d;%d;%d;%d_", + virtualKey, scanCode, wc, kd, controlState, max(1, repeat)) + } + + if !keyDown { + return nil + } + + var encoded []byte + decodedRunes := decodeUTF16Rune(surrogate, wc) + for range max(1, repeat) { + for _, decoded := range decodedRunes { + encoded = append(encoded, []byte(string(decoded))...) + } + } + return encoded +} + type winTty struct { buf chan byte out syscall.Handle @@ -207,17 +240,11 @@ func (w *winTty) getConsoleInput() error { ir := rec[i] switch ir.typ { case keyEvent: - // we normally only expect to see ascii, but paste data may come in as UTF-16. - wc := rune(binary.LittleEndian.Uint16(ir.data[10:])) - for _, decoded := range decodeUTF16Rune(&w.surrogate, wc) { - for _, chr := range []byte(string(decoded)) { - // We normally expect only to see ASCII (win32-input-mode), - // but apparently pasted data can arrive in UTF-16 here. - select { - case w.buf <- chr: - case <-w.stopQ: - break loop - } + for _, chr := range encodeWinKeyRecord(ir.data, &w.surrogate) { + select { + case w.buf <- chr: + case <-w.stopQ: + break loop } } diff --git a/vendor/modules.txt b/vendor/modules.txt index 3b50432bf..2c60d9282 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -48,7 +48,7 @@ github.com/fatih/color # github.com/gdamore/encoding v1.0.1 ## explicit; go 1.9 github.com/gdamore/encoding -# github.com/gdamore/tcell/v3 v3.4.0 +# github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 ## explicit; go 1.25.0 github.com/gdamore/tcell/v3 github.com/gdamore/tcell/v3/color @@ -175,7 +175,7 @@ github.com/xo/terminfo ## explicit; go 1.20 golang.org/x/exp/constraints golang.org/x/exp/slices -# golang.org/x/mod v0.35.0 +# golang.org/x/mod v0.36.0 ## explicit; go 1.25.0 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile @@ -192,10 +192,10 @@ golang.org/x/sync/semaphore golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.43.0 +# golang.org/x/term v0.44.0 ## explicit; go 1.25.0 golang.org/x/term -# golang.org/x/text v0.37.0 +# golang.org/x/text v0.38.0 ## explicit; go 1.25.0 golang.org/x/text/cases golang.org/x/text/encoding @@ -208,7 +208,7 @@ golang.org/x/text/language golang.org/x/text/runes golang.org/x/text/transform golang.org/x/text/unicode/norm -# golang.org/x/tools v0.44.0 +# golang.org/x/tools v0.45.0 ## explicit; go 1.25.0 golang.org/x/tools/go/ast/astutil # gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c From 38e1fe0493325283128519f36746ffdc7aa30894 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 11:56:47 +0200 Subject: [PATCH 137/218] Add tests showing ghost views when branches/commits are not their panel's first tab With gui.sidePanels, a panel's gocui window is named after its first tab. The transient contexts (remoteBranches, subCommits, commitFiles) initially point at the windows "branches" and "commits"; when the config gives no panel that name, their views end up visible at full screen size, covering every side panel below them in z-order (issue #5823). Co-Authored-By: Claude Fable 5 --- pkg/integration/tests/test_list.go | 2 ++ .../tests/ui/branches_not_first_tab.go | 34 +++++++++++++++++++ .../tests/ui/commits_not_first_tab.go | 32 +++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 pkg/integration/tests/ui/branches_not_first_tab.go create mode 100644 pkg/integration/tests/ui/commits_not_first_tab.go diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index abf13073e..8213d5159 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -484,6 +484,8 @@ var tests = []*components.IntegrationTest{ tag.Reset, tag.ResetToDuplicateNamedBranch, ui.Accordion, + ui.BranchesNotFirstTab, + ui.CommitsNotFirstTab, ui.DisableSwitchTabWithPanelJumpKeys, ui.EmptyMenu, ui.HideSidePanel, diff --git a/pkg/integration/tests/ui/branches_not_first_tab.go b/pkg/integration/tests/ui/branches_not_first_tab.go new file mode 100644 index 000000000..0e60b5ed9 --- /dev/null +++ b/pkg/integration/tests/ui/branches_not_first_tab.go @@ -0,0 +1,34 @@ +package ui + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var BranchesNotFirstTab = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "With gui.sidePanels grouping branches behind another tab, no ghost view must appear over the side panels", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.SidePanels = []config.SidePanel{ + {"worktrees", "branches", "remotes"}, + {"files"}, + {"commits", "tags"}, + {"stash"}, + } + }, + SetupRepo: func(shell *Shell) { + shell.EmptyCommit("one") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // The remote branches and sub-commits views are only shown after + // drilling into a remote or a branch; at startup both must be hidden, + // or they'd cover the side panels. + t.Views().RemoteBranches(). + /* EXPECTED: + IsInvisible() + ACTUAL: */ + IsVisible() + t.Views().SubCommits().IsInvisible() + }, +}) diff --git a/pkg/integration/tests/ui/commits_not_first_tab.go b/pkg/integration/tests/ui/commits_not_first_tab.go new file mode 100644 index 000000000..db50e4c08 --- /dev/null +++ b/pkg/integration/tests/ui/commits_not_first_tab.go @@ -0,0 +1,32 @@ +package ui + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var CommitsNotFirstTab = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "With gui.sidePanels grouping commits behind another tab, no ghost view must appear over the side panels", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.SidePanels = []config.SidePanel{ + {"branches", "worktrees", "remotes"}, + {"files"}, + {"tags", "commits"}, + {"stash"}, + } + }, + SetupRepo: func(shell *Shell) { + shell.EmptyCommit("one") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // The commit files view is only shown after drilling into a commit; at + // startup it must be hidden, or it'd cover the side panels. + t.Views().CommitFiles(). + /* EXPECTED: + IsInvisible() + ACTUAL: */ + IsVisible() + }, +}) From bf4f5827e748574b9267520f48856e2c5ff7f049 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 12:00:00 +0200 Subject: [PATCH 138/218] Don't show a transient view whose window is not part of the layout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With gui.sidePanels, a panel's gocui window is named after its first tab, so when branches is grouped behind, say, worktrees, there is no window called "branches" at all. The transient contexts (remoteBranches, subCommits, commitFiles) initially point at the windows "branches" and "commits", and layout() showed their views whenever the window-to-view map named them as their window's current view — without checking that the window exists in the layout. Since the map is seeded from the contexts themselves, a window that no panel owns keeps naming a transient view as its current view, and that view had just been parked at full screen size (the fallback for views in unlaid-out windows), so it covered every side panel below it in z-order. Only show a transient view if its window actually received dimensions in this layout. Fixes #5823. Co-Authored-By: Claude Fable 5 --- pkg/gui/layout.go | 9 ++++++++- pkg/integration/tests/ui/branches_not_first_tab.go | 3 --- pkg/integration/tests/ui/commits_not_first_tab.go | 3 --- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pkg/gui/layout.go b/pkg/gui/layout.go index de3bdbe9b..bcdc0edfc 100644 --- a/pkg/gui/layout.go +++ b/pkg/gui/layout.go @@ -154,7 +154,14 @@ func (gui *Gui) layout(g *gocui.Gui) error { if err != nil && !errors.Is(err, gocui.ErrUnknownView) { return err } - view.Visible = gui.helpers.Window.GetViewNameForWindow(context.GetWindowName()) == context.GetViewName() + // A transient view is visible if it is the view its window is currently + // showing — but only if that window is part of the layout at all. For a + // window without dimensions, setViewFromDimensions parks the view at full + // screen size in the background, so making it visible would cover all + // windows below it. + _, windowHasDimensions := viewDimensions[context.GetWindowName()] + view.Visible = windowHasDimensions && + gui.helpers.Window.GetViewNameForWindow(context.GetWindowName()) == context.GetViewName() } if gui.PrevLayout.Information != informationStr { diff --git a/pkg/integration/tests/ui/branches_not_first_tab.go b/pkg/integration/tests/ui/branches_not_first_tab.go index 0e60b5ed9..47e8a4fd5 100644 --- a/pkg/integration/tests/ui/branches_not_first_tab.go +++ b/pkg/integration/tests/ui/branches_not_first_tab.go @@ -25,10 +25,7 @@ var BranchesNotFirstTab = NewIntegrationTest(NewIntegrationTestArgs{ // drilling into a remote or a branch; at startup both must be hidden, // or they'd cover the side panels. t.Views().RemoteBranches(). - /* EXPECTED: IsInvisible() - ACTUAL: */ - IsVisible() t.Views().SubCommits().IsInvisible() }, }) diff --git a/pkg/integration/tests/ui/commits_not_first_tab.go b/pkg/integration/tests/ui/commits_not_first_tab.go index db50e4c08..505aa4307 100644 --- a/pkg/integration/tests/ui/commits_not_first_tab.go +++ b/pkg/integration/tests/ui/commits_not_first_tab.go @@ -24,9 +24,6 @@ var CommitsNotFirstTab = NewIntegrationTest(NewIntegrationTestArgs{ // The commit files view is only shown after drilling into a commit; at // startup it must be hidden, or it'd cover the side panels. t.Views().CommitFiles(). - /* EXPECTED: IsInvisible() - ACTUAL: */ - IsVisible() }, }) From 74a77e58be5f8c478481fe4ee3b1ce6de3351600 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 12:02:23 +0200 Subject: [PATCH 139/218] Assign the transient contexts' initial windows from the side panel config The transient contexts (remoteBranches, subCommits, commitFiles) take over the window of the context they are drilled into from, but until then they carry a hardcoded initial window ("branches" or "commits"). Under a gui.sidePanels config where those tabs aren't their panel's first, no window of that name exists, leaving the window-to-view map with entries for windows the layout never produces. The previous commit made such entries harmless, but there's no reason to have contexts point at nonexistent windows in the first place; assign them the window hosting branches or commits instead, which the config validation guarantees to exist. Co-Authored-By: Claude Fable 5 --- pkg/gui/side_panels.go | 9 +++++++++ pkg/gui/side_panels_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/pkg/gui/side_panels.go b/pkg/gui/side_panels.go index 361d54fb1..8b327b197 100644 --- a/pkg/gui/side_panels.go +++ b/pkg/gui/side_panels.go @@ -125,4 +125,13 @@ func (gui *Gui) assignSidePanelWindows(contextTree *context.ContextTree) { ctx.SetWindowName(name) } } + + // The transient contexts take over the window of the context they are + // drilled into from, but they need a valid initial window before their + // first use. Assign the window hosting branches or commits, respectively; + // unlike e.g. remotes, those tabs can't be hidden, so their windows are + // always part of the layout. + contextTree.RemoteBranches.SetWindowName(contextTree.Branches.GetWindowName()) + contextTree.SubCommits.SetWindowName(contextTree.Branches.GetWindowName()) + contextTree.CommitFiles.SetWindowName(contextTree.LocalCommits.GetWindowName()) } diff --git a/pkg/gui/side_panels_test.go b/pkg/gui/side_panels_test.go index b1240c357..24813b4ae 100644 --- a/pkg/gui/side_panels_test.go +++ b/pkg/gui/side_panels_test.go @@ -28,3 +28,23 @@ func TestSidePanelLookupsCoverAllValidTabs(t *testing.T) { assert.Equal(t, want, sortedKeys(gui.sidePanelTabTitles())) assert.Equal(t, want, sortedKeys(sidePanelContexts(gui.contextTree()))) } + +// The transient contexts must end up in windows that exist under the configured +// panel layout, or their views would be laid out for a window that is never +// shown. +func TestAssignSidePanelWindowsCoversTransientContexts(t *testing.T) { + gui := NewDummyGui() + gui.c.UserConfig().Gui.SidePanels = []config.SidePanel{ + {"worktrees", "branches", "remotes"}, + {"files"}, + {"tags", "commits"}, + {"stash"}, + } + + contextTree := gui.contextTree() + gui.assignSidePanelWindows(contextTree) + + assert.Equal(t, "worktrees", contextTree.RemoteBranches.GetWindowName()) + assert.Equal(t, "worktrees", contextTree.SubCommits.GetWindowName()) + assert.Equal(t, "tags", contextTree.CommitFiles.GetWindowName()) +} From d097519c05174ed2dd98251e9aafc4d38c6074f3 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 19:13:33 +0200 Subject: [PATCH 140/218] Serialize concurrent writes to the streamed command's output writer runAndStreamAux funnels a command's stdout and stderr into a single cmdWriter (the command-log panel, or a buffer when output is suppressed) from two separate goroutines: stderr through the MultiWriter set on cmd.Stderr, and stdout through the onRun callback. Those goroutines wrote the shared writer without any synchronization, racing on the prefixWriter's prefixWritten flag and interleaving the two streams. Wrap the writer so its writes are serialized. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/oscommands/cmd_obj_runner.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/pkg/commands/oscommands/cmd_obj_runner.go b/pkg/commands/oscommands/cmd_obj_runner.go index b70668431..74b7e721d 100644 --- a/pkg/commands/oscommands/cmd_obj_runner.go +++ b/pkg/commands/oscommands/cmd_obj_runner.go @@ -244,6 +244,10 @@ func (self *cmdObjRunner) runAndStreamAux( } else { cmdWriter = self.guiIO.newCmdWriterFn() } + // The command's stdout and stderr are streamed to cmdWriter concurrently + // from separate goroutines (stderr via the MultiWriter below, stdout via + // onRun), so it must be safe for concurrent writes. + cmdWriter = &synchronizedWriter{writer: cmdWriter} if cmdObj.ShouldLog() { self.logCmdObj(cmdObj) @@ -451,6 +455,20 @@ func (self *cmdObjRunner) getCheckForCredentialRequestFunc() func([]byte) (Crede } } +// synchronizedWriter serializes writes to its underlying writer so that it can +// be written from multiple goroutines at once (see runAndStreamAux, which +// streams a command's stdout and stderr to one writer from two goroutines). +type synchronizedWriter struct { + mutex deadlock.Mutex + writer io.Writer +} + +func (self *synchronizedWriter) Write(p []byte) (int, error) { + self.mutex.Lock() + defer self.mutex.Unlock() + return self.writer.Write(p) +} + type Buffer struct { b bytes.Buffer m deadlock.Mutex From a61be44e920948cfef3dbe5adf0e7893e1447dd3 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 20:12:36 +0200 Subject: [PATCH 141/218] Wait for the streamed command's output goroutine before reading its buffers runAndStreamAux reads the stdout buffer (and, when output is suppressed, the combinedOutput buffer) for its error message after handler.wait() returns, but the goroutine that fills those buffers by draining the command's output isn't awaited, so the reads raced its final writes. Own the goroutine here rather than letting the onRun callbacks spawn it, and join it before reading the buffers. The pty reader reaches EOF on its own once the process exits, but the non-pty pipe never does, so its handler now closes the read end to unblock the reader; the pipe is synchronous, so by the time the command has exited all of its output has already been read and nothing is lost. This also plugs the goroutine that the non-pty streaming path previously leaked on every command. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/oscommands/cmd_obj_runner.go | 37 +++++++++++++++++------ 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/pkg/commands/oscommands/cmd_obj_runner.go b/pkg/commands/oscommands/cmd_obj_runner.go index 74b7e721d..6178ac816 100644 --- a/pkg/commands/oscommands/cmd_obj_runner.go +++ b/pkg/commands/oscommands/cmd_obj_runner.go @@ -227,9 +227,7 @@ type cmdHandler struct { func (self *cmdObjRunner) runAndStream(cmdObj *CmdObj) error { return self.runAndStreamAux(cmdObj, func(handler *cmdHandler, cmdWriter io.Writer) { - go func() { - _, _ = io.Copy(cmdWriter, handler.stdoutPipe) - }() + _, _ = io.Copy(cmdWriter, handler.stdoutPipe) }) } @@ -280,10 +278,29 @@ func (self *cmdObjRunner) runAndStreamAux( t := time.Now() - onRun(handler, cmdWriter) + // Stream the command's output on a goroutine while it runs, but keep a + // handle on it: the buffers it fills (stdout, and combinedOutput when + // output is suppressed) must not be read below until it has finished. + streamingDone := make(chan struct{}) + go utils.Safe(func() { + defer close(streamingDone) + onRun(handler, cmdWriter) + }) err = handler.wait() + // The command has exited; wait for the streaming goroutine to drain the + // last of its output before reading those buffers. A pty reader reaches + // EOF on its own now the process is gone, but the non-pty pipe never does, + // so close it to unblock the reader — the pipe is synchronous, so all + // output has already been read by now and nothing is lost. + if !cmdObj.ShouldUsePty() { + if closeErr := handler.close(); closeErr != nil { + self.log.Error(closeErr) + } + } + <-streamingDone + self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t)) if err != nil { @@ -358,10 +375,7 @@ func (self *cmdObjRunner) runAndDetectCredentialRequest( return self.runAndStreamAux(cmdObj, func(handler *cmdHandler, cmdWriter io.Writer) { tr := io.TeeReader(handler.stdoutPipe, cmdWriter) - - go utils.Safe(func() { - self.processOutput(tr, handler.stdinPipe, promptUserForCredential, handler.close, cmdObj) - }) + self.processOutput(tr, handler.stdinPipe, promptUserForCredential, handler.close, cmdObj) }) } @@ -500,8 +514,11 @@ func (self *cmdObjRunner) getCmdHandlerNonPty(cmd *exec.Cmd) (*cmdHandler, error return &cmdHandler{ stdoutPipe: stdoutReader, stdinPipe: buf, - close: func() error { return nil }, - wait: cmd.Wait, + // Closing the read end makes a blocked read on it return, which is how + // runAndStreamAux unblocks and joins the streaming goroutine once the + // command has finished (the pipe delivers no EOF of its own). + close: func() error { return stdoutReader.Close() }, + wait: cmd.Wait, }, nil } From 2765147b711826b54408b48b5e3850fa09d39e61 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 18:11:30 +0200 Subject: [PATCH 142/218] Note in AGENTS.md that gocui lives in-tree Agents (and humans new to the repo) repeatedly go looking for the gocui sources in go.mod, go.sum, or the module cache and hit a dead end, because gocui is a fork maintained in-tree under pkg/gocui rather than pulled in as a dependency. Record that in AGENTS.md so the dead end is avoided. Co-Authored-By: Claude Opus 4.8 (1M context) --- AGENTS.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 947add510..88e818249 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -411,3 +411,12 @@ Never run `find` (or similar) from `/` or other paths outside the project. All third-party code we use is vendored under `vendor/`, so dependency sources are reachable from inside the working tree — search there instead of the host filesystem. + +## gocui is in-tree, not a dependency + +The `gocui` TUI library is a fork maintained directly in this repo under +`pkg/gocui` — it's an ordinary package, not a Go module dependency. Don't look +for it in `go.mod`/`go.sum` or the module cache (`$GOMODCACHE`); it isn't +there. When you need to read or change gocui internals (the task manager, the +event loop, worker/UI-thread dispatch, view rendering), edit `pkg/gocui` +directly. From 36f193a2e86bfd19c8e651d0bfa7f23524e125c4 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 12:00:33 +0200 Subject: [PATCH 143/218] Remove return value from PromptToContinueRebase It always returned nil. --- pkg/gui/controllers/helpers/merge_and_rebase_helper.go | 4 +--- pkg/gui/controllers/helpers/refresh_helper.go | 3 ++- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index b0c53b831..267453a86 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -321,7 +321,7 @@ func (self *MergeAndRebaseHelper) AbortMergeOrRebaseWithConfirm() error { } // PromptToContinueRebase asks the user if they want to continue the rebase/merge that's in progress -func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { +func (self *MergeAndRebaseHelper) PromptToContinueRebase() { self.continueRebasePromptShowing = true self.c.Confirm(types.ConfirmOpts{ Title: self.c.Tr.Continue, @@ -373,8 +373,6 @@ func (self *MergeAndRebaseHelper) PromptToContinueRebase() error { return nil }, }) - - return nil } // DismissContinueRebasePromptIfShowing closes the "continue the rebase/merge?" diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 21fdc8a7a..dd6b87ae0 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1220,7 +1220,8 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re self.mergeConflictsHelper.ResetMergeState() self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) } - return self.mergeAndRebaseHelper.PromptToContinueRebase() + self.mergeAndRebaseHelper.PromptToContinueRebase() + return nil }) } } else { From 504e5b3f741d0149deda0ffdbbb7fa60be3e7669 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 12:01:26 +0200 Subject: [PATCH 144/218] Remove the error return value from the onUIThreadUnlessRepoChanged lambda All clients pass a function that returns nil. --- pkg/gui/controllers/helpers/refresh_helper.go | 72 +++++++------------ 1 file changed, 26 insertions(+), 46 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index dd6b87ae0..47cd51ff7 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -358,9 +358,8 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // Model.Files (via Files.GetSelected) and would otherwise // see the pre-refresh model. Guard on the generation so a // repo switch mid-refresh drops it, like the model bounces. - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) - return nil }) }) } @@ -622,7 +621,7 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS // The commit selection is restored in refreshCommitsWithLimit's bounce, // so read it on the UI thread after that bounce; then load the commit // files back on a worker (refreshCommitFilesContext does git work). - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { commit := self.c.Contexts().LocalCommits.GetSelected() if commit != nil && commit.RefName() != "" { refRange := self.c.Contexts().LocalCommits.GetSelectedRefRangeForDiffFiles() @@ -635,7 +634,6 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS return nil }) } - return nil }) } } @@ -687,7 +685,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().BisectInfo = bisectInfo self.c.Model().Commits = commits self.RefreshAuthors(commits) @@ -721,12 +719,10 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, // Enqueued from within this bounce so it runs after refreshView's // render below (which was enqueued first), matching the previous // ordering where FocusLine ran after the view was re-rendered. - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Contexts().LocalCommits.FocusLine(true) - return nil }) } - return nil }) self.refreshView(self.c.Contexts().LocalCommits, env) @@ -856,10 +852,9 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommit if err != nil { return err } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().SubCommits = commits self.RefreshAuthors(commits) - return nil }) self.refreshView(self.c.Contexts().SubCommits, env) @@ -899,10 +894,9 @@ func (self *RefreshHelper) refreshCommitFilesContext(captured capturedCommitFile if err != nil { return err } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().CommitFiles = files self.c.Contexts().CommitFiles.CommitFileTreeViewModel.SetTree() - return nil }) self.refreshView(self.c.Contexts().CommitFiles, env) return nil @@ -921,10 +915,9 @@ func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, comm } workingTreeState := self.c.Git().Status.WorkingTreeState() - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Commits = updatedCommits self.c.Model().WorkingTreeStateAtLastCommitRefresh = workingTreeState - return nil }) self.refreshView(self.c.Contexts().LocalCommits, env) @@ -937,9 +930,8 @@ func (self *RefreshHelper) refreshTags(env refreshEnv) error { return err } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Tags = tags - return nil }) self.refreshView(self.c.Contexts().Tags, env) @@ -966,10 +958,9 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh }) }, func() { - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Contexts().Branches.HandleRender() self.refreshStatus(env) - return nil }) }) if err != nil { @@ -981,14 +972,14 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh worktrees = self.loadWorktrees() } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { // Drop this write if a branch load that started later has already applied // its result. At the INITIAL startup stage an immediate load (not // recency-sorted) and an async recency-sorted load run concurrently; this // makes the later-started (recency-sorted) one win regardless of which // finishes first, so its result isn't clobbered by the stale immediate one. if loadSeq < self.appliedBranchLoadSeq { - return nil + return } self.appliedBranchLoadSeq = loadSeq @@ -1031,7 +1022,6 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh // Need to re-render the commits view because the visualization of local // branch heads might have changed self.c.Contexts().LocalCommits.HandleRender() - return nil }) self.refreshView(self.c.Contexts().Branches, env) @@ -1066,12 +1056,13 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState // bumps the generation, so a write captured under the old generation must not // clobber the new repo's state. The generation is captured once at the start of // the refresh and carried in env (see refreshEnv). -func (self *RefreshHelper) onUIThreadUnlessRepoChanged(env refreshEnv, f func() error) { +func (self *RefreshHelper) onUIThreadUnlessRepoChanged(env refreshEnv, f func()) { self.onUIThread(env.background, func() error { if self.c.State().GetRepoGeneration() != env.generation { return nil } - return f() + f() + return nil }) } @@ -1206,7 +1197,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re // (e.g. in the user's editor). Offer to continue it. We only do this // for operations we started ourselves; prompting for one that was // started outside lazygit (e.g. by a coding agent) would be confusing. - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { // The merge-conflicts scope of this refresh also notices that // the conflicts are gone and escapes from the merge conflicts // view to the files context (see RefreshMergeState), but it @@ -1221,7 +1212,6 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) } self.mergeAndRebaseHelper.PromptToContinueRebase() - return nil }) } } else { @@ -1232,13 +1222,12 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re // Guard on the generation like the sibling PromptToContinueRebase // bounce above: if the repo was switched while this refresh was in // flight, a prompt showing now belongs to the new repo, so leave it be. - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.mergeAndRebaseHelper.DismissContinueRebasePromptIfShowing() - return nil }) } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { // only taking over the filter if it hasn't already been set by the user. if conflictFileCount > 0 && prevConflictFileCount == 0 { if fileTreeViewModel.GetStatusFilter() == filetree.DisplayAll { @@ -1253,7 +1242,6 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re self.c.Model().Submodules = submoduleConfigs self.c.Model().Files = files fileTreeViewModel.SetTree() - return nil }) return nil @@ -1308,7 +1296,7 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en } } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { model.ReflogCommits = reflogCommits model.FilteredReflogCommits = filteredReflogCommits // Setting the selection here, in the same bounce that writes the list, @@ -1318,7 +1306,6 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en self.c.Contexts().ReflogCommits.SetSelectedLineIdx(0) self.c.Contexts().ReflogCommits.GetView().SetOriginY(0) } - return nil }) self.refreshView(self.c.Contexts().ReflogCommits, env) @@ -1331,7 +1318,7 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env return nil, err } - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Remotes = remotes hadPrs := len(self.c.Model().PullRequestsMap) != 0 @@ -1351,7 +1338,6 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env } } } - return nil }) self.refreshView(self.c.Contexts().Remotes, env) @@ -1371,9 +1357,8 @@ func (self *RefreshHelper) loadWorktrees() []*models.Worktree { func (self *RefreshHelper) refreshWorktrees(env refreshEnv) { worktrees := self.loadWorktrees() - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Worktrees = worktrees - return nil }) // need to refresh branches because the branches view shows worktrees against @@ -1386,9 +1371,8 @@ func (self *RefreshHelper) refreshStashEntries(filterPath string, env refreshEnv stashEntries := self.c.Git().Loaders.StashLoader. GetStashEntries(filterPath) - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().StashEntries = stashEntries - return nil }) self.refreshView(self.c.Contexts().Stash, env) @@ -1399,7 +1383,7 @@ func (self *RefreshHelper) refreshStatus(env refreshEnv) { workingTreeState := self.c.Git().Status.WorkingTreeState() repoName := self.c.Git().RepoPaths.RepoName() - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { // Read the checked-out branch and the linked worktree name here on the UI // thread: both derive from models (Branches, Worktrees) that their // refreshes now write via bounces, so reading them on the worker would @@ -1407,13 +1391,12 @@ func (self *RefreshHelper) refreshStatus(env refreshEnv) { currentBranch := self.refsHelper.GetCheckedOutRef() if currentBranch == nil { // need to wait for branches to refresh - return nil + return } linkedWorktreeName := self.worktreeHelper.GetLinkedWorktreeName() status := presentation.FormatStatus(repoName, currentBranch, types.ItemOperationNone, linkedWorktreeName, workingTreeState, self.c.Tr, self.c.UserConfig()) self.c.SetViewContent(self.c.Views().Status, status) - return nil }) } @@ -1443,7 +1426,7 @@ func (self *RefreshHelper) refreshView(context types.Context, env refreshEnv) { // switched while the refresh was in flight, its model write was already // dropped, so there's nothing fresh to render — and the captured context // belongs to the old repo's now-replaced context tree anyway. - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { // Re-applying the filter must be done before re-rendering the view, so that // the filtered list model is up to date for rendering. self.searchHelper.ReApplyFilter(context) @@ -1462,16 +1445,14 @@ func (self *RefreshHelper) refreshView(context types.Context, env refreshEnv) { self.searchHelper.ReApplySearch(context) return nil }) - return nil }) } func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, remotes []*models.Remote, env refreshEnv) { clearPullRequests := func() { - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().PullRequests = nil self.c.Model().PullRequestsMap = nil - return nil }) } @@ -1624,14 +1605,13 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, bra self.savePullRequestsToCache(prs) - self.onUIThreadUnlessRepoChanged(env, func() error { + self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().PullRequests = prs // Rebuilding here rather than on the worker means the map is built from // the branches and remotes as they are on the UI thread, after their // own refreshes' bounces have applied. self.rebuildPullRequestsMap() self.c.PostRefreshUpdate(self.c.Contexts().Branches) - return nil }) } From 4acfc8806506b8abfac9140d0e25e170720c8d0e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 7 Jul 2026 14:02:04 +0200 Subject: [PATCH 145/218] Replace the BLOCK_UI refresh mode with a BatchUIUpdates flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BLOCK_UI ran the whole refresh on the UI thread and parked it in a wg.Wait for the duration, so the UI (and its spinner) froze while the git work ran. Blocking the UI was never the point — the point was to apply all the scopes' updates in one frame instead of a per-scope cascade — and if we genuinely wanted to block input it should span the whole operation, not just its refresh, which needs a gocui-level mechanism we don't have. So drop the mode and add a BatchUIUpdates option that achieves the "one frame" effect without blocking: each scope's UI-thread bounce is collected into a shared refreshBounceBatch during the refresh, and once every scope has finished they're all applied inside a single OnUIThread task. gocui drains every queued event before it redraws, so one task means one repaint. The refresh itself now runs SYNC — on a worker when issued from one (checkout, move-to-new-branch, the rebase-edit result handling), so the UI thread stays live and the spinner keeps animating. The batch needs a mutex because the scopes add concurrently from their worker goroutines, and a closed flag so that any bounces enqueued after the flush starts — the nested ones a flushed bounce produces in turn, e.g. scrolling the selection into view — are dispatched immediately as ordinary follow-ups rather than collected into a batch that nothing will drain. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 110 +++++++++++++----- pkg/gui/controllers/helpers/refs_helper.go | 12 +- .../controllers/local_commits_controller.go | 4 +- pkg/gui/types/refresh.go | 12 +- 4 files changed, 100 insertions(+), 38 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 47cd51ff7..2f0f10657 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -96,6 +96,49 @@ type refreshEnv struct { // the repo generation captured when the refresh started generation int + + // When non-nil, each scope's UI-thread bounce is collected here instead of + // being dispatched as it's produced, so they can all be applied in a single + // frame once the whole refresh is done (see RefreshOptions.BatchUIUpdates). + // Held by pointer so the copies of env that flow through the scope functions + // all share the one batch. + batch *refreshBounceBatch +} + +// refreshBounceBatch collects the UI-thread bounces of a batched refresh so they +// can be applied together in one frame rather than one scope at a time. The +// scopes run on separate worker goroutines and add concurrently, hence the +// mutex. Once the refresh starts flushing it closes the batch, so that any +// bounces enqueued afterwards — the nested ones a flushed bounce produces in +// turn, e.g. scrolling the selection into view — are dispatched immediately as +// ordinary follow-ups instead of being collected into a batch that nothing +// will drain. +type refreshBounceBatch struct { + mutex deadlock.Mutex + funcs []func() + closed bool +} + +// add collects f and returns true. Once the batch is closed it collects nothing +// and returns false, telling the caller to dispatch f immediately instead. +func (self *refreshBounceBatch) add(f func()) bool { + self.mutex.Lock() + defer self.mutex.Unlock() + + if self.closed { + return false + } + self.funcs = append(self.funcs, f) + return true +} + +// close marks the batch flushed and returns everything collected so far. +func (self *refreshBounceBatch) close() []func() { + self.mutex.Lock() + defer self.mutex.Unlock() + + self.closed = true + return self.funcs } func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { @@ -121,18 +164,15 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr ) } - // f runs on the UI thread when the refresh was initiated there, and also for - // BLOCK_UI, which dispatches f onto the UI thread regardless of the caller. - // Only a SYNC/ASYNC refresh initiated from a worker runs f on that worker. - // This, not calledFromWorker alone, is what decides whether a scope capture - // runs inline or has to hop (see captureOnUIThread). - fRunsOnUIThread := options.Mode == types.BLOCK_UI || !calledFromWorker + // f runs on the UI thread when the refresh was initiated there (Refresh); a + // refresh initiated from a worker (RefreshFromWorker) runs f on that worker. + // This decides whether a scope capture runs inline or has to hop (see + // captureOnUIThread). + fRunsOnUIThread := !calledFromWorker // Debug-only guard: every refresh must be issued from the entry point that // matches its goroutine — Refresh on the UI thread, RefreshFromWorker on a - // worker. We check the caller's own goroutine here, before a BLOCK_UI - // refresh dispatches f onto the UI thread, so it holds regardless of the - // mode. goid stays out of production control flow (debug only). + // worker. goid stays out of production control flow (debug only). if self.c.GetConfig().GetDebug() && self.c.GocuiGui().IsUIThread() == calledFromWorker { panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") } @@ -144,6 +184,9 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr background: options.Background, generation: self.c.State().GetRepoGeneration(), } + if options.BatchUIUpdates { + env.batch = &refreshBounceBatch{} + } var scopeSet *set.Set[types.RefreshableView] if len(options.Scope) == 0 { @@ -376,6 +419,20 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr wg.Wait() + if env.batch != nil { + // Apply all the scopes' collected bounces in a single UI-thread task, + // so they land in one frame: gocui drains every queued event before it + // redraws, so one task means one repaint. Bounces enqueued from within + // these (see refreshBounceBatch) run as ordinary follow-ups. + bounces := env.batch.close() + self.onUIThread(env.background, func() error { + for _, bounce := range bounces { + bounce() + } + return nil + }) + } + if options.Then != nil { // Queue Then via OnUIThread so it runs *after* the refresh-scope // functions' model-update bounces (which are already queued by @@ -387,14 +444,6 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } } - if options.Mode == types.BLOCK_UI { - self.c.OnUIThread(func() error { - f() - return nil - }) - return - } - f() } @@ -482,8 +531,6 @@ func getModeName(mode types.RefreshMode) string { return "sync" case types.ASYNC: return "async" - case types.BLOCK_UI: - return "block-ui" default: return "unknown mode" } @@ -1057,13 +1104,21 @@ func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState // clobber the new repo's state. The generation is captured once at the start of // the refresh and carried in env (see refreshEnv). func (self *RefreshHelper) onUIThreadUnlessRepoChanged(env refreshEnv, f func()) { - self.onUIThread(env.background, func() error { + wrapper := func() { if self.c.State().GetRepoGeneration() != env.generation { - return nil + return } f() - return nil - }) + } + + // A batched refresh collects its bounces and fires them together at the end + // (see refreshBounceBatch); add reports false once the batch is flushing, so + // bounces enqueued from within a flushed bounce dispatch immediately. + if env.batch != nil && env.batch.add(wrapper) { + return + } + + self.onUIThread(env.background, func() error { wrapper(); return nil }) } // onWorker and onUIThread pick the foreground or background variant of the @@ -1094,12 +1149,11 @@ func (self *RefreshHelper) onUIThread(background bool, f func() error) { // runs on the UI thread (fRunsOnUIThread is true) fn runs inline; when it runs // on a worker, fn is dispatched to the UI thread and we block for it. // -// The inline case matters for correctness as much as the hop: a SYNC or -// BLOCK_UI refresh parks the UI thread in a wg.Wait while its scope workers -// run, so a scope worker that tried to hop to the UI thread there would +// The inline case matters for correctness as much as the hop: a SYNC refresh +// initiated on the UI thread parks that thread in a wg.Wait while its scope +// workers run, so a scope worker that tried to hop to the UI thread there would // deadlock. Capturing before those workers are spawned — inline, on the UI -// thread — avoids that entirely. This is why BLOCK_UI (which always runs on the -// UI thread, even from a worker caller) captures inline rather than hopping. +// thread — avoids that entirely. func (self *RefreshHelper) captureOnUIThread(fRunsOnUIThread bool, background bool, fn func()) { if fRunsOnUIThread { fn() diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 5f07b8ea6..dda3d918a 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -56,7 +56,8 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions scope = append(scope, types.PULL_REQUESTS) } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.BLOCK_UI, + Mode: types.SYNC, + BatchUIUpdates: true, Scope: scope, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, @@ -368,7 +369,8 @@ func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggest } self.c.Refresh(types.RefreshOptions{ - Mode: types.BLOCK_UI, + Mode: types.SYNC, + BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, SelectTopReflogCommit: true, @@ -534,7 +536,8 @@ func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchNa } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.BLOCK_UI, + Mode: types.SYNC, + BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, SelectTopReflogCommit: true, @@ -570,7 +573,8 @@ func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName stri } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.BLOCK_UI, + Mode: types.SYNC, + BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, SelectTopReflogCommit: true, diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 23e94adf7..ade7d1a9a 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -604,7 +604,7 @@ func (self *LocalCommitsController) edit(selectedCommits []*models.Commit, start return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, todo.Edit, "") return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( - err, types.RefreshOptions{Mode: types.BLOCK_UI}) + err, types.RefreshOptions{BatchUIUpdates: true}) }) } @@ -628,7 +628,7 @@ func (self *LocalCommitsController) startInteractiveRebaseWithEdit( err := self.c.Git().Rebase.EditRebase(commitsToEdit[len(commitsToEdit)-1].Hash()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, - types.RefreshOptions{Mode: types.BLOCK_UI, Then: func() error { + types.RefreshOptions{BatchUIUpdates: true, Then: func() error { todos := make([]*models.Commit, 0, len(commitsToEdit)-1) for _, c := range commitsToEdit[:len(commitsToEdit)-1] { // Merge commits can't be set to "edit", so just skip them diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index f4041bb2e..7b304b15d 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -28,9 +28,8 @@ const ( type RefreshMode int const ( - SYNC RefreshMode = iota // wait until everything is done before returning - ASYNC // return immediately, allowing each independent thing to update itself - BLOCK_UI // wrap code in an update call to ensure UI updates all at once and keybindings aren't executed till complete + SYNC RefreshMode = iota // wait until everything is done before returning + ASYNC // return immediately, allowing each independent thing to update itself ) // CommitSelectionBehavior controls which local commit is selected after the @@ -74,7 +73,12 @@ const ( type RefreshOptions struct { Then func() error Scope []RefreshableView // e.g. []RefreshableView{COMMITS, BRANCHES}. Leave empty to refresh everything - Mode RefreshMode // one of SYNC (default), ASYNC, and BLOCK_UI + Mode RefreshMode // one of SYNC (default) and ASYNC + + // If true, hold off on updating the UI until all scopes have finished + // refreshing and then apply them together in a single frame, rather than + // letting each scope update the UI as soon as it's done. + BatchUIUpdates bool // Controls which local branch is selected after the refresh. Defaults to // KeepBranchSelectionByName. From d70d70aad2007df539b682767c47b5eba282b5e2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 14:31:01 +0200 Subject: [PATCH 146/218] Get rid of pointless f() indirection This was useful when there was a BLOCK_UI mode where f() was called differently, but now we no longer need it. I'm making this change as a separate commit because folding it into the previous one (which would conceptually have made sense) would have made that diff unreadable because of the indentation change. The variable `fRunsOnUIThread` and its comment no longer make sense now; we'll clean this up next. The diff is best viewed with --ignore-all-space. --- pkg/gui/controllers/helpers/refresh_helper.go | 514 +++++++++--------- 1 file changed, 255 insertions(+), 259 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2f0f10657..0da2f08d0 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -177,274 +177,270 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") } - f := func() { - // Capture the repo generation once, here at the start, so every scope's - // bounce is guarded against the same baseline. - env := refreshEnv{ - background: options.Background, - generation: self.c.State().GetRepoGeneration(), - } - if options.BatchUIUpdates { - env.batch = &refreshBounceBatch{} - } + // Capture the repo generation once, here at the start, so every scope's + // bounce is guarded against the same baseline. + env := refreshEnv{ + background: options.Background, + generation: self.c.State().GetRepoGeneration(), + } + if options.BatchUIUpdates { + env.batch = &refreshBounceBatch{} + } - var scopeSet *set.Set[types.RefreshableView] - if len(options.Scope) == 0 { - // not refreshing staging/patch-building unless explicitly requested because we only need - // to refresh those while focused. - scopeSet = set.NewFromSlice([]types.RefreshableView{ - types.COMMITS, - types.BRANCHES, - types.FILES, - types.STASH, - types.REFLOG, - types.TAGS, - types.REMOTES, - types.WORKTREES, - types.STATUS, - types.BISECT_INFO, - types.STAGING, - types.PULL_REQUESTS, - }) - } else { - scopeSet = set.NewFromSlice(options.Scope) - } + var scopeSet *set.Set[types.RefreshableView] + if len(options.Scope) == 0 { + // not refreshing staging/patch-building unless explicitly requested because we only need + // to refresh those while focused. + scopeSet = set.NewFromSlice([]types.RefreshableView{ + types.COMMITS, + types.BRANCHES, + types.FILES, + types.STASH, + types.REFLOG, + types.TAGS, + types.REMOTES, + types.WORKTREES, + types.STATUS, + types.BISECT_INFO, + types.STAGING, + types.PULL_REQUESTS, + }) + } else { + scopeSet = set.NewFromSlice(options.Scope) + } - // Expand co-refreshing scopes up front so downstream conditions can be - // simple single-scope checks. The relationships are: - // - whenever the reflog or bisect info changes, commits and branches - // can change too (e.g. switching branches updates the reflog and - // can move HEAD), so refresh commits + branches alongside - // - submodules are refreshed as part of the files refresh - // - merge conflicts are part of what the files refresh produces - // - pull requests are fetched for the tracking branches against the - // remotes, so refresh both alongside to fetch against fresh data - if scopeSet.Includes(types.REFLOG) || scopeSet.Includes(types.BISECT_INFO) { - scopeSet.Add(types.COMMITS, types.BRANCHES) - } - if scopeSet.Includes(types.SUBMODULES) { - scopeSet.Add(types.FILES) - } - if scopeSet.Includes(types.FILES) { - scopeSet.Add(types.MERGE_CONFLICTS) - } - if scopeSet.Includes(types.PULL_REQUESTS) { - scopeSet.Add(types.BRANCHES, types.REMOTES) - } + // Expand co-refreshing scopes up front so downstream conditions can be + // simple single-scope checks. The relationships are: + // - whenever the reflog or bisect info changes, commits and branches + // can change too (e.g. switching branches updates the reflog and + // can move HEAD), so refresh commits + branches alongside + // - submodules are refreshed as part of the files refresh + // - merge conflicts are part of what the files refresh produces + // - pull requests are fetched for the tracking branches against the + // remotes, so refresh both alongside to fetch against fresh data + if scopeSet.Includes(types.REFLOG) || scopeSet.Includes(types.BISECT_INFO) { + scopeSet.Add(types.COMMITS, types.BRANCHES) + } + if scopeSet.Includes(types.SUBMODULES) { + scopeSet.Add(types.FILES) + } + if scopeSet.Includes(types.FILES) { + scopeSet.Add(types.MERGE_CONFLICTS) + } + if scopeSet.Includes(types.PULL_REQUESTS) { + scopeSet.Add(types.BRANCHES, types.REMOTES) + } - // Capture the refs snapshot now, before we start reading git's state - // below, rather than after. This is important to guard against the race - // of git's state changing externally while (or right after) we are - // refreshing; the risk is one potential extra refresh, but capturing the - // snapshot at the end would risk missing one, which is worse. - self.updateRefsSnapshotIfRelevant(scopeSet) + // Capture the refs snapshot now, before we start reading git's state + // below, rather than after. This is important to guard against the race + // of git's state changing externally while (or right after) we are + // refreshing; the risk is one potential extra refresh, but capturing the + // snapshot at the end would risk missing one, which is worse. + self.updateRefsSnapshotIfRelevant(scopeSet) - wg := sync.WaitGroup{} - refresh := func(name string, f func()) { - // if we're in a demo we don't want any async refreshes because - // everything happens fast and it's better to have everything update - // in the one frame - if !self.c.InDemo() && options.Mode == types.ASYNC { - self.onWorker(env.background, func(t gocui.Task) error { - f() - return nil - }) - } else { - wg.Add(1) - go utils.Safe(func() { - t := time.Now() - defer wg.Done() - f() - self.c.Log.Infof("refreshed %s in %s", name, time.Since(t)) - }) - } - } - - branchesAndRemotesWg := sync.WaitGroup{} - // The pull-request fetch (below) needs the just-loaded branches and - // remotes. Their model writes are bounced onto the UI thread, so the - // fetch worker can't read them back from the model without racing (and - // would see the pre-refresh values); instead the branches and remotes - // loads stash what they loaded here, and the wait on - // branchesAndRemotesWg gives the fetch the happens-before to read them. - var loadedBranches []*models.Branch - var loadedRemotes []*models.Remote - includeWorktreesWithBranches := false - if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) { - // whenever we change commits, we should update branches because the upstream/downstream - // counts can change. Whenever we change branches we should also change commits - // e.g. in the case of switching branches. - // Capture the commits, reflog and branches refresh inputs (model, - // contexts, modes) on the UI thread, before the git work is dispatched - // to a worker, so the workers compute from an immutable snapshot - // instead of reading state the UI thread concurrently mutates. - var capturedCommits capturedCommitState - var capturedReflog capturedReflogState - var capturedBranches capturedBranchState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - capturedCommits = self.captureCommitsState(options.CommitSelection) - capturedReflog = self.captureReflogState() - capturedBranches = self.captureBranchState() - }) - refresh("commits and commit files", func() { - self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, env) - }) - - includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) - if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { - branchesAndRemotesWg.Add(1) - refresh("reflog and branches", func() { - loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, env) - branchesAndRemotesWg.Done() - }) - } else { - branchesAndRemotesWg.Add(1) - refresh("branches", func() { - // Not a recency sort, so branches doesn't depend on the reflog - // being fresh; it runs concurrently with the reflog refresh - // below and uses the reflog we captured up front, as it always has. - loadedBranches = self.refreshBranches(capturedBranches, includeWorktreesWithBranches, options.BranchSelection, true, capturedReflog.reflogCommits, env) - branchesAndRemotesWg.Done() - }) - refresh("reflog", func() { - _, _ = self.refreshReflogCommits(capturedReflog, env, options.SelectTopReflogCommit) - }) - } - } else if scopeSet.Includes(types.REBASE_COMMITS) { - // the above block handles rebase commits so we only need to call this one - // if we've asked specifically for rebase commits and not those other things - var rebaseHashPool *utils.StringPool - var rebaseCommits []*models.Commit - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - rebaseHashPool, rebaseCommits = self.captureRebaseCommitState() - }) - refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, env) }) - } - - if scopeSet.Includes(types.SUB_COMMITS) { - var capturedSubCommits capturedSubCommitState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - capturedSubCommits = self.captureSubCommitState() - }) - refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, env) }) - } - - // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway - if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { - var capturedCommitFiles capturedCommitFilesState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - capturedCommitFiles = self.captureCommitFilesState() - }) - refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, env) }) - } - - fileWg := sync.WaitGroup{} - if scopeSet.Includes(types.FILES) { - var capturedFiles capturedFilesState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - capturedFiles = self.captureFilesState() - }) - fileWg.Add(1) - refresh("files", func() { - _ = self.refreshFilesAndSubmodules(capturedFiles, env) - fileWg.Done() - }) - } - - if scopeSet.Includes(types.STASH) { - var stashFilterPath string - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - stashFilterPath = self.c.Modes().Filtering.GetPath() - }) - refresh("stash", func() { self.refreshStashEntries(stashFilterPath, env) }) - } - - if scopeSet.Includes(types.TAGS) { - refresh("tags", func() { _ = self.refreshTags(env) }) - } - - if scopeSet.Includes(types.REMOTES) { - // Capture the previously-selected remote on the UI thread; the worker - // needs it to keep the remote-branches selection valid, and reading - // the Remotes context off the UI thread races its render. - var prevSelectedRemote *models.Remote - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { - prevSelectedRemote = self.c.Contexts().Remotes.GetSelected() - }) - branchesAndRemotesWg.Add(1) - refresh("remotes", func() { - loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, env) - branchesAndRemotesWg.Done() - }) - } - - if scopeSet.Includes(types.PULL_REQUESTS) { - refresh("pull requests", func() { - branchesAndRemotesWg.Wait() - // Use the branches and remotes the loads above stashed, not - // Model().Branches/Remotes: those writes are bounced onto the - // UI thread and may not have landed on this worker yet. The - // wait above orders us after both loads have stashed theirs. - self.refreshGithubPullRequests(loadedBranches, loadedRemotes, env) - }) - } - - if scopeSet.Includes(types.WORKTREES) && !includeWorktreesWithBranches { - refresh("worktrees", func() { self.refreshWorktrees(env) }) - } - - if scopeSet.Includes(types.STAGING) { - refresh("staging", func() { - fileWg.Wait() - // Bounce onto the UI thread so this runs after the files - // scope's model-update bounce — RefreshStagingPanel reads - // Model.Files (via Files.GetSelected) and would otherwise - // see the pre-refresh model. Guard on the generation so a - // repo switch mid-refresh drops it, like the model bounces. - self.onUIThreadUnlessRepoChanged(env, func() { - self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) - }) - }) - } - - if scopeSet.Includes(types.PATCH_BUILDING) { - refresh("patch building", func() { self.patchBuildingHelper.RefreshPatchBuildingPanel(types.OnFocusOpts{}) }) - } - - if scopeSet.Includes(types.MERGE_CONFLICTS) { - refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(env.background) }) - } - - self.refreshStatus(env) - - wg.Wait() - - if env.batch != nil { - // Apply all the scopes' collected bounces in a single UI-thread task, - // so they land in one frame: gocui drains every queued event before it - // redraws, so one task means one repaint. Bounces enqueued from within - // these (see refreshBounceBatch) run as ordinary follow-ups. - bounces := env.batch.close() - self.onUIThread(env.background, func() error { - for _, bounce := range bounces { - bounce() - } + wg := sync.WaitGroup{} + refresh := func(name string, f func()) { + // if we're in a demo we don't want any async refreshes because + // everything happens fast and it's better to have everything update + // in the one frame + if !self.c.InDemo() && options.Mode == types.ASYNC { + self.onWorker(env.background, func(t gocui.Task) error { + f() return nil }) - } - - if options.Then != nil { - // Queue Then via OnUIThread so it runs *after* the refresh-scope - // functions' model-update bounces (which are already queued by - // now), not synchronously here — at this point the workers have - // returned but their bounces haven't been processed yet, so - // invoking Then synchronously would run it on a model that's - // still pre-refresh. - self.onUIThread(env.background, options.Then) + } else { + wg.Add(1) + go utils.Safe(func() { + t := time.Now() + defer wg.Done() + f() + self.c.Log.Infof("refreshed %s in %s", name, time.Since(t)) + }) } } - f() + branchesAndRemotesWg := sync.WaitGroup{} + // The pull-request fetch (below) needs the just-loaded branches and + // remotes. Their model writes are bounced onto the UI thread, so the + // fetch worker can't read them back from the model without racing (and + // would see the pre-refresh values); instead the branches and remotes + // loads stash what they loaded here, and the wait on + // branchesAndRemotesWg gives the fetch the happens-before to read them. + var loadedBranches []*models.Branch + var loadedRemotes []*models.Remote + includeWorktreesWithBranches := false + if scopeSet.Includes(types.COMMITS) || scopeSet.Includes(types.BRANCHES) { + // whenever we change commits, we should update branches because the upstream/downstream + // counts can change. Whenever we change branches we should also change commits + // e.g. in the case of switching branches. + // Capture the commits, reflog and branches refresh inputs (model, + // contexts, modes) on the UI thread, before the git work is dispatched + // to a worker, so the workers compute from an immutable snapshot + // instead of reading state the UI thread concurrently mutates. + var capturedCommits capturedCommitState + var capturedReflog capturedReflogState + var capturedBranches capturedBranchState + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + capturedCommits = self.captureCommitsState(options.CommitSelection) + capturedReflog = self.captureReflogState() + capturedBranches = self.captureBranchState() + }) + refresh("commits and commit files", func() { + self.refreshCommitsAndCommitFiles(capturedCommits, options.CommitSelection, env) + }) + + includeWorktreesWithBranches = scopeSet.Includes(types.WORKTREES) + if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" { + branchesAndRemotesWg.Add(1) + refresh("reflog and branches", func() { + loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, includeWorktreesWithBranches, options.BranchSelection, options.SelectTopReflogCommit, env) + branchesAndRemotesWg.Done() + }) + } else { + branchesAndRemotesWg.Add(1) + refresh("branches", func() { + // Not a recency sort, so branches doesn't depend on the reflog + // being fresh; it runs concurrently with the reflog refresh + // below and uses the reflog we captured up front, as it always has. + loadedBranches = self.refreshBranches(capturedBranches, includeWorktreesWithBranches, options.BranchSelection, true, capturedReflog.reflogCommits, env) + branchesAndRemotesWg.Done() + }) + refresh("reflog", func() { + _, _ = self.refreshReflogCommits(capturedReflog, env, options.SelectTopReflogCommit) + }) + } + } else if scopeSet.Includes(types.REBASE_COMMITS) { + // the above block handles rebase commits so we only need to call this one + // if we've asked specifically for rebase commits and not those other things + var rebaseHashPool *utils.StringPool + var rebaseCommits []*models.Commit + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + rebaseHashPool, rebaseCommits = self.captureRebaseCommitState() + }) + refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, env) }) + } + + if scopeSet.Includes(types.SUB_COMMITS) { + var capturedSubCommits capturedSubCommitState + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + capturedSubCommits = self.captureSubCommitState() + }) + refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, env) }) + } + + // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway + if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { + var capturedCommitFiles capturedCommitFilesState + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + capturedCommitFiles = self.captureCommitFilesState() + }) + refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, env) }) + } + + fileWg := sync.WaitGroup{} + if scopeSet.Includes(types.FILES) { + var capturedFiles capturedFilesState + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + capturedFiles = self.captureFilesState() + }) + fileWg.Add(1) + refresh("files", func() { + _ = self.refreshFilesAndSubmodules(capturedFiles, env) + fileWg.Done() + }) + } + + if scopeSet.Includes(types.STASH) { + var stashFilterPath string + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + stashFilterPath = self.c.Modes().Filtering.GetPath() + }) + refresh("stash", func() { self.refreshStashEntries(stashFilterPath, env) }) + } + + if scopeSet.Includes(types.TAGS) { + refresh("tags", func() { _ = self.refreshTags(env) }) + } + + if scopeSet.Includes(types.REMOTES) { + // Capture the previously-selected remote on the UI thread; the worker + // needs it to keep the remote-branches selection valid, and reading + // the Remotes context off the UI thread races its render. + var prevSelectedRemote *models.Remote + self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + prevSelectedRemote = self.c.Contexts().Remotes.GetSelected() + }) + branchesAndRemotesWg.Add(1) + refresh("remotes", func() { + loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, env) + branchesAndRemotesWg.Done() + }) + } + + if scopeSet.Includes(types.PULL_REQUESTS) { + refresh("pull requests", func() { + branchesAndRemotesWg.Wait() + // Use the branches and remotes the loads above stashed, not + // Model().Branches/Remotes: those writes are bounced onto the + // UI thread and may not have landed on this worker yet. The + // wait above orders us after both loads have stashed theirs. + self.refreshGithubPullRequests(loadedBranches, loadedRemotes, env) + }) + } + + if scopeSet.Includes(types.WORKTREES) && !includeWorktreesWithBranches { + refresh("worktrees", func() { self.refreshWorktrees(env) }) + } + + if scopeSet.Includes(types.STAGING) { + refresh("staging", func() { + fileWg.Wait() + // Bounce onto the UI thread so this runs after the files + // scope's model-update bounce — RefreshStagingPanel reads + // Model.Files (via Files.GetSelected) and would otherwise + // see the pre-refresh model. Guard on the generation so a + // repo switch mid-refresh drops it, like the model bounces. + self.onUIThreadUnlessRepoChanged(env, func() { + self.stagingHelper.RefreshStagingPanel(types.OnFocusOpts{}) + }) + }) + } + + if scopeSet.Includes(types.PATCH_BUILDING) { + refresh("patch building", func() { self.patchBuildingHelper.RefreshPatchBuildingPanel(types.OnFocusOpts{}) }) + } + + if scopeSet.Includes(types.MERGE_CONFLICTS) { + refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(env.background) }) + } + + self.refreshStatus(env) + + wg.Wait() + + if env.batch != nil { + // Apply all the scopes' collected bounces in a single UI-thread task, + // so they land in one frame: gocui drains every queued event before it + // redraws, so one task means one repaint. Bounces enqueued from within + // these (see refreshBounceBatch) run as ordinary follow-ups. + bounces := env.batch.close() + self.onUIThread(env.background, func() error { + for _, bounce := range bounces { + bounce() + } + return nil + }) + } + + if options.Then != nil { + // Queue Then via OnUIThread so it runs *after* the refresh-scope + // functions' model-update bounces (which are already queued by + // now), not synchronously here — at this point the workers have + // returned but their bounces haven't been processed yet, so + // invoking Then synchronously would run it on a model that's + // still pre-refresh. + self.onUIThread(env.background, options.Then) + } } // SetRefsSnapshot stores the given snapshot as the last observed refs state. From f319522d5b91a93170b5150cdaed296771a32444 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 14:37:16 +0200 Subject: [PATCH 147/218] Remove fRunsOnUIThread variable; use calledFromWorker directly There is no f() function any more, so a variable named "f runs on" doesn't make sense. And we also don't need it any more; it used to be necessary when its meaning was not exactly the same as `!calledFromWorker`, but also included the BLOCK_UI case, but that has changed several commits ago. --- pkg/gui/controllers/helpers/refresh_helper.go | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 0da2f08d0..002391aa1 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -164,12 +164,6 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr ) } - // f runs on the UI thread when the refresh was initiated there (Refresh); a - // refresh initiated from a worker (RefreshFromWorker) runs f on that worker. - // This decides whether a scope capture runs inline or has to hop (see - // captureOnUIThread). - fRunsOnUIThread := !calledFromWorker - // Debug-only guard: every refresh must be issued from the entry point that // matches its goroutine — Refresh on the UI thread, RefreshFromWorker on a // worker. goid stays out of production control flow (debug only). @@ -280,7 +274,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr var capturedCommits capturedCommitState var capturedReflog capturedReflogState var capturedBranches capturedBranchState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { capturedCommits = self.captureCommitsState(options.CommitSelection) capturedReflog = self.captureReflogState() capturedBranches = self.captureBranchState() @@ -314,7 +308,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // if we've asked specifically for rebase commits and not those other things var rebaseHashPool *utils.StringPool var rebaseCommits []*models.Commit - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { rebaseHashPool, rebaseCommits = self.captureRebaseCommitState() }) refresh("rebase commits", func() { _ = self.refreshRebaseCommits(rebaseHashPool, rebaseCommits, env) }) @@ -322,7 +316,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr if scopeSet.Includes(types.SUB_COMMITS) { var capturedSubCommits capturedSubCommitState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { capturedSubCommits = self.captureSubCommitState() }) refresh("sub commits", func() { _ = self.refreshSubCommitsWithLimit(capturedSubCommits, env) }) @@ -331,7 +325,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // reason we're not doing this if the COMMITS type is included is that if the COMMITS type _is_ included we will refresh the commit files context anyway if scopeSet.Includes(types.COMMIT_FILES) && !scopeSet.Includes(types.COMMITS) { var capturedCommitFiles capturedCommitFilesState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { capturedCommitFiles = self.captureCommitFilesState() }) refresh("commit files", func() { _ = self.refreshCommitFilesContext(capturedCommitFiles, env) }) @@ -340,7 +334,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr fileWg := sync.WaitGroup{} if scopeSet.Includes(types.FILES) { var capturedFiles capturedFilesState - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { capturedFiles = self.captureFilesState() }) fileWg.Add(1) @@ -352,7 +346,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr if scopeSet.Includes(types.STASH) { var stashFilterPath string - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { stashFilterPath = self.c.Modes().Filtering.GetPath() }) refresh("stash", func() { self.refreshStashEntries(stashFilterPath, env) }) @@ -367,7 +361,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // needs it to keep the remote-branches selection valid, and reading // the Remotes context off the UI thread races its render. var prevSelectedRemote *models.Remote - self.captureOnUIThread(fRunsOnUIThread, env.background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { prevSelectedRemote = self.c.Contexts().Remotes.GetSelected() }) branchesAndRemotesWg.Add(1) @@ -1142,7 +1136,7 @@ func (self *RefreshHelper) onUIThread(background bool, f func() error) { // reads the model/context/mode state a refresh scope needs into locals, so the // worker that follows computes from an immutable snapshot instead of reading // state the UI thread concurrently mutates. When the enclosing refresh function -// runs on the UI thread (fRunsOnUIThread is true) fn runs inline; when it runs +// runs on the UI thread (calledFromWorker is false) fn runs inline; when it runs // on a worker, fn is dispatched to the UI thread and we block for it. // // The inline case matters for correctness as much as the hop: a SYNC refresh @@ -1150,8 +1144,8 @@ func (self *RefreshHelper) onUIThread(background bool, f func() error) { // workers run, so a scope worker that tried to hop to the UI thread there would // deadlock. Capturing before those workers are spawned — inline, on the UI // thread — avoids that entirely. -func (self *RefreshHelper) captureOnUIThread(fRunsOnUIThread bool, background bool, fn func()) { - if fRunsOnUIThread { +func (self *RefreshHelper) captureOnUIThread(calledFromWorker bool, background bool, fn func()) { + if !calledFromWorker { fn() return } From bfd3b7b47e57b423c11cdfba58f0a2a5938eaabb Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 14:47:06 +0200 Subject: [PATCH 148/218] Allow Then and BatchUIUpdates to work with an async refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Then, and BatchUIUpdates, previously only worked for a SYNC refresh: the calling goroutine blocked in wg.Wait until every scope had finished, and only then flushed the batch and ran Then. An ASYNC refresh had no such join point — it dispatched each scope onto its own worker and returned right away — so Then was forbidden (it would have run before the scopes finished) and a batch would never be drained. Give the async path a join of its own. Both paths now register their scopes in the WaitGroup, and the finishing work — wg.Wait, the batch flush, and Then — moves into a closure. A SYNC refresh runs it inline as before; an ASYNC refresh dispatches it to a worker, so the caller still returns immediately but the batch and Then run once every scope is done. Besides lifting the restriction, this makes SYNC and ASYNC differ only in whether the finishing work blocks the caller, which is what lets a later commit drop the mode entirely and key the choice off the calling thread instead. --- pkg/gui/controllers/helpers/refresh_helper.go | 61 +++++++++++-------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 002391aa1..dd6d948f7 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -142,10 +142,6 @@ func (self *refreshBounceBatch) close() []func() { } func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { - if options.Mode == types.ASYNC && options.Then != nil { - panic("RefreshOptions.Then doesn't work with mode ASYNC") - } - t := time.Now() defer func() { self.c.Log.Infof("Refresh took %s", time.Since(t)) @@ -234,16 +230,18 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr wg := sync.WaitGroup{} refresh := func(name string, f func()) { + wg.Add(1) + // if we're in a demo we don't want any async refreshes because // everything happens fast and it's better to have everything update // in the one frame if !self.c.InDemo() && options.Mode == types.ASYNC { self.onWorker(env.background, func(t gocui.Task) error { + defer wg.Done() f() return nil }) } else { - wg.Add(1) go utils.Safe(func() { t := time.Now() defer wg.Done() @@ -410,30 +408,41 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr self.refreshStatus(env) - wg.Wait() + waitAndFinalize := func() { + wg.Wait() - if env.batch != nil { - // Apply all the scopes' collected bounces in a single UI-thread task, - // so they land in one frame: gocui drains every queued event before it - // redraws, so one task means one repaint. Bounces enqueued from within - // these (see refreshBounceBatch) run as ordinary follow-ups. - bounces := env.batch.close() - self.onUIThread(env.background, func() error { - for _, bounce := range bounces { - bounce() - } - return nil - }) + if env.batch != nil { + // Apply all the scopes' collected bounces in a single UI-thread task, + // so they land in one frame: gocui drains every queued event before it + // redraws, so one task means one repaint. Bounces enqueued from within + // these (see refreshBounceBatch) run as ordinary follow-ups. + bounces := env.batch.close() + self.onUIThread(env.background, func() error { + for _, bounce := range bounces { + bounce() + } + return nil + }) + } + + if options.Then != nil { + // Queue Then via OnUIThread so it runs *after* the refresh-scope + // functions' model-update bounces (which are already queued by + // now), not synchronously here — at this point the workers have + // returned but their bounces haven't been processed yet, so + // invoking Then synchronously would run it on a model that's + // still pre-refresh. + self.onUIThread(env.background, options.Then) + } } - if options.Then != nil { - // Queue Then via OnUIThread so it runs *after* the refresh-scope - // functions' model-update bounces (which are already queued by - // now), not synchronously here — at this point the workers have - // returned but their bounces haven't been processed yet, so - // invoking Then synchronously would run it on a model that's - // still pre-refresh. - self.onUIThread(env.background, options.Then) + if options.Mode == types.SYNC { + waitAndFinalize() + } else { + self.onWorker(env.background, func(t gocui.Task) error { + waitAndFinalize() + return nil + }) } } From 63bd2d98c0fa56e5d6c852b933b59f283e64c63c Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 15:46:57 +0200 Subject: [PATCH 149/218] Show a waiting status while creating a branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Creating a branch checks it out, and checking out a distant ref (a tag or a commit far from HEAD) can take a noticeable while. NewBranch ran that synchronously in the prompt's confirm handler, on the UI thread, so the UI froze — no spinner, no repaint — until it finished. Move the branch creation (and the autostash path) onto a worker with a waiting status, mirroring CheckoutRef, and refresh from the worker so the UI thread stays live and the spinner keeps animating. Push the branches context from the refresh's Then rather than up front: the refresh already batches its UI updates, so switching panels there lands the switch in the same frame as the refreshed branch list instead of flashing the pre-refresh list while the checkout is still running. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refs_helper.go | 76 +++++++++++++--------- pkg/i18n/english.go | 2 + 2 files changed, 48 insertions(+), 30 deletions(-) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index dda3d918a..e91a6c500 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -364,16 +364,22 @@ func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggest } refresh := func() { - if self.c.Context().Current() != self.c.Contexts().Branches { - self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) - } - - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Mode: types.SYNC, BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, SelectTopReflogCommit: true, + Then: func() error { + // Switch to the branches panel only now, in the same batched + // frame that applies the refreshed data, so the panel switch + // and the new branch appear together rather than flashing the + // old branch list while the checkout is still in progress. + if self.c.Context().Current() != self.c.Contexts().Branches { + self.c.Context().Push(self.c.Contexts().Branches, types.OnFocusOpts{}) + } + return nil + }, }) } @@ -387,34 +393,44 @@ func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggest if newBranchName != suggestedBranchName { newBranchFunc = self.c.Git().Branch.NewWithoutTracking } - if err := newBranchFunc(newBranchName, from); err != nil { - if IsSwitchBranchUncommittedChangesError(err) { - // offer to autostash changes - self.c.Confirm(types.ConfirmOpts{ - Title: self.c.Tr.AutoStashTitle, - Prompt: self.c.Tr.AutoStashPrompt, - HandleConfirm: func() error { - if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil { - return err - } - if err := newBranchFunc(newBranchName, from); err != nil { - return err - } - err := self.c.Git().Stash.Pop(0) - // Branch switch successful so re-render the UI even if the pop operation failed (e.g. conflict). - refresh() - return err - }, - }) - return nil + // Creating the branch checks it out, which can take a while when + // the ref we're branching off is distant, so do it on a worker. + return self.c.WithWaitingStatus(self.c.Tr.CreatingBranchStatus, func(gocui.Task) error { + if err := newBranchFunc(newBranchName, from); err != nil { + if IsSwitchBranchUncommittedChangesError(err) { + // offer to autostash changes + self.c.OnUIThread(func() error { + self.c.Confirm(types.ConfirmOpts{ + Title: self.c.Tr.AutoStashTitle, + Prompt: self.c.Tr.AutoStashPrompt, + HandleConfirm: func() error { + return self.c.WithWaitingStatus(self.c.Tr.CreatingBranchStatus, func(gocui.Task) error { + if err := self.c.Git().Stash.Push(fmt.Sprintf(self.c.Tr.AutoStashForNewBranch, newBranchName)); err != nil { + return err + } + if err := newBranchFunc(newBranchName, from); err != nil { + return err + } + err := self.c.Git().Stash.Pop(0) + // Branch switch successful so re-render the UI even if the pop operation failed (e.g. conflict). + refresh() + return err + }) + }, + }) + return nil + }) + + return nil + } + + return err } - return err - } - - refresh() - return nil + refresh() + return nil + }) }, }) diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 22b05e6c0..2e83fed9b 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -427,6 +427,7 @@ type TranslationSet struct { UndoingStatus string RedoingStatus string CheckingOutStatus string + CreatingBranchStatus string CommittingStatus string RewordingStatus string RevertingStatus string @@ -1576,6 +1577,7 @@ func EnglishTranslationSet() *TranslationSet { UndoingStatus: "Undoing", RedoingStatus: "Redoing", CheckingOutStatus: "Checking out", + CreatingBranchStatus: "Creating branch", CommittingStatus: "Committing", RewordingStatus: "Rewording", RevertingStatus: "Reverting", From 8580c78cc020e79d4bfd6805f76eeadc973c4df5 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 15:57:07 +0200 Subject: [PATCH 150/218] Derive sync vs async refresh from the calling thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Whether a refresh should block or run in the background was controlled by the Mode field, but that always lined up with the calling thread: a UI-thread Refresh must not block the UI, while a RefreshFromWorker runs on a worker where blocking is exactly what we want. Now that Then and BatchUIUpdates work regardless of that choice, drop Mode from the decision and key it off calledFromWorker instead: - Refresh (UI thread) runs its scopes and the finishing step (wait, batch flush, Then) on workers, so the caller returns immediately — what ASYNC used to mean. - RefreshFromWorker runs them on the calling worker, blocking it until everything is done — what SYNC used to mean. Demos keep taking the blocking, inline path so everything still lands in one deterministic frame. In practice this flips the handful of RefreshFromWorker calls that passed ASYNC — they now block their worker until the refresh finishes, keeping the waiting-status spinner up until the UI actually updates — and the many UI-thread refreshes that defaulted to SYNC, which no longer freeze the UI thread while the git work runs. Mode now only feeds the log line; the next commit removes it. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index dd6d948f7..2482e6015 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -232,10 +232,13 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr refresh := func(name string, f func()) { wg.Add(1) - // if we're in a demo we don't want any async refreshes because - // everything happens fast and it's better to have everything update - // in the one frame - if !self.c.InDemo() && options.Mode == types.ASYNC { + // A refresh issued from the UI thread must not block it, so its scopes + // run as their own worker tasks and the caller returns immediately (the + // finishing step below is dispatched to a worker too). A refresh issued + // from a worker blocks that worker instead, running its scopes as plain + // goroutines that it joins. In a demo we always take the blocking path + // so everything updates in a single, deterministic frame. + if !self.c.InDemo() && !calledFromWorker { self.onWorker(env.background, func(t gocui.Task) error { defer wg.Done() f() @@ -436,7 +439,10 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } } - if options.Mode == types.SYNC { + // waitAndFinalize blocks until every scope is done. Run it inline when we're + // already on a worker (or in a demo, for a deterministic single frame); when + // we're on the UI thread, dispatch it to a worker so it doesn't block the UI. + if calledFromWorker || self.c.InDemo() { waitAndFinalize() } else { self.onWorker(env.background, func(t gocui.Task) error { From 88811e6795c0bc15e50fea1a0488cbff561165fd Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 16:10:01 +0200 Subject: [PATCH 151/218] Remove the RefreshMode field With sync vs async now derived from the calling thread, the Mode field and its SYNC/ASYNC constants no longer carry any information: Refresh is always async, RefreshFromWorker always sync. Drop the field, the type, and the Mode argument at every call site, and reduce the debug log's mode name to a plain sync/async derived from calledFromWorker. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/bisect_controller.go | 2 +- pkg/gui/controllers/branches_controller.go | 12 +++---- .../controllers/commits_files_controller.go | 2 +- .../custom_patch_options_menu_action.go | 2 +- pkg/gui/controllers/diffing_menu_action.go | 8 ++--- pkg/gui/controllers/files_controller.go | 12 +++---- pkg/gui/controllers/global_controller.go | 2 +- pkg/gui/controllers/helpers/bisect_helper.go | 2 +- .../controllers/helpers/branches_helper.go | 11 +++--- .../controllers/helpers/cherry_pick_helper.go | 2 +- .../controllers/helpers/credentials_helper.go | 2 +- pkg/gui/controllers/helpers/diff_helper.go | 2 +- pkg/gui/controllers/helpers/fixup_helper.go | 2 +- pkg/gui/controllers/helpers/gpg_helper.go | 6 ++-- .../helpers/merge_and_rebase_helper.go | 10 +++--- pkg/gui/controllers/helpers/refresh_helper.go | 26 +++++--------- pkg/gui/controllers/helpers/refs_helper.go | 7 +--- .../helpers/working_tree_helper.go | 5 ++- .../controllers/helpers/worktree_helper.go | 4 +-- .../controllers/local_commits_controller.go | 35 +++++++++---------- .../controllers/merge_conflicts_controller.go | 2 +- .../controllers/patch_building_controller.go | 2 +- .../controllers/remote_branches_controller.go | 2 +- pkg/gui/controllers/remotes_controller.go | 2 -- pkg/gui/controllers/sub_commits_controller.go | 2 +- pkg/gui/controllers/sync_controller.go | 2 +- pkg/gui/controllers/tags_controller.go | 6 ++-- .../controllers/workspace_reset_controller.go | 14 ++++---- pkg/gui/gui.go | 8 ++--- .../custom_commands/handler_creator.go | 2 +- pkg/gui/types/refresh.go | 8 ----- 31 files changed, 84 insertions(+), 120 deletions(-) diff --git a/pkg/gui/controllers/bisect_controller.go b/pkg/gui/controllers/bisect_controller.go index eb568240b..685f932b1 100644 --- a/pkg/gui/controllers/bisect_controller.go +++ b/pkg/gui/controllers/bisect_controller.go @@ -282,7 +282,7 @@ func (self *BisectController) afterBisectMarkRefresh(selectCurrent bool, waitToR } if waitToReselect { - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{}, Then: selectFn}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{}, Then: selectFn}) return nil } diff --git a/pkg/gui/controllers/branches_controller.go b/pkg/gui/controllers/branches_controller.go index a886a410b..a73ee3bc2 100644 --- a/pkg/gui/controllers/branches_controller.go +++ b/pkg/gui/controllers/branches_controller.go @@ -331,7 +331,6 @@ func (self *BranchesController) viewUpstreamOptions(selectedBranch *models.Branc return err } self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{ types.BRANCHES, types.COMMITS, @@ -355,7 +354,6 @@ func (self *BranchesController) viewUpstreamOptions(selectedBranch *models.Branc return err } self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{ types.BRANCHES, types.COMMITS, @@ -546,7 +544,7 @@ func (self *BranchesController) forceCheckout() error { if err := self.c.Git().Branch.Checkout(branch.Name, git_commands.CheckoutOptions{Force: true}); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }) @@ -600,7 +598,6 @@ func (self *BranchesController) createNewBranchWithName(newBranchName string) er } self.c.Refresh(types.RefreshOptions{ - Mode: types.ASYNC, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, SelectTopReflogCommit: true, @@ -734,7 +731,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { WorktreePath: worktreePath, }, ) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return err } @@ -743,7 +740,7 @@ func (self *BranchesController) fastForward(branch *models.Branch) error { err := self.c.Git().Sync.FastForward( task, branch.Name, branch.UpstreamRemote, branch.UpstreamBranch, ) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}}) return err }) } @@ -760,7 +757,7 @@ func (self *BranchesController) createSortMenu() error { if self.c.UserConfig().Git.LocalBranchSortOrder != sortOrder { self.c.UserConfig().Git.LocalBranchSortOrder = sortOrder self.c.Contexts().Branches.SetSelection(0) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}}) return nil } return nil @@ -788,7 +785,6 @@ func (self *BranchesController) rename(branch *models.Branch) error { // onto the UI thread, so the re-selection (which reads Model.Branches) has to run in // Then; reading it inline here would see the previous model. self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES, types.WORKTREES}, Then: func() error { // now that we've got our stuff again we need to find that branch and reselect it. diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index b90e14b74..14e1c1a50 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -324,7 +324,7 @@ func (self *CommitFilesController) checkout(node *filetree.CommitFileNode) error return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil } diff --git a/pkg/gui/controllers/custom_patch_options_menu_action.go b/pkg/gui/controllers/custom_patch_options_menu_action.go index 3d15ce899..2882ab808 100644 --- a/pkg/gui/controllers/custom_patch_options_menu_action.go +++ b/pkg/gui/controllers/custom_patch_options_menu_action.go @@ -269,7 +269,7 @@ func (self *CustomPatchOptionsMenuAction) handleApplyPatch(reverse bool) error { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }) diff --git a/pkg/gui/controllers/diffing_menu_action.go b/pkg/gui/controllers/diffing_menu_action.go index 3ae5903d9..8372d7919 100644 --- a/pkg/gui/controllers/diffing_menu_action.go +++ b/pkg/gui/controllers/diffing_menu_action.go @@ -22,7 +22,7 @@ func (self *DiffingMenuAction) Call() error { OnPress: func() error { self.c.Modes().Diffing.Ref = name // can scope this down based on current view but too lazy right now - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }, @@ -38,7 +38,7 @@ func (self *DiffingMenuAction) Call() error { FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRefsSuggestionsFunc(), HandleConfirm: func(response string) error { self.c.Modes().Diffing.Ref = response - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }) @@ -54,7 +54,7 @@ func (self *DiffingMenuAction) Call() error { Label: self.c.Tr.SwapDiff, OnPress: func() error { self.c.Modes().Diffing.Reverse = !self.c.Modes().Diffing.Reverse - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }, @@ -62,7 +62,7 @@ func (self *DiffingMenuAction) Call() error { Label: self.c.Tr.ExitDiffMode, OnPress: func() error { self.c.Modes().Diffing = diffing.New() - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, }, diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index b70b67ab7..bf73d4c8b 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -636,7 +636,7 @@ func (self *FilesController) press(nodes []*filetree.FileNode) error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) self.context().HandleFocus(types.OnFocusOpts{}) return nil @@ -921,7 +921,7 @@ func (self *FilesController) toggleStagedAll() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) self.context().HandleFocus(types.OnFocusOpts{}) return nil @@ -1204,7 +1204,7 @@ func (self *FilesController) setStatusFiltering(filter filetree.FileTreeDisplayF // Whenever we switch between untracked and other filters, we need to refresh the files view // because the untracked files filter applies when running `git status`. if previousFilter != filter && (previousFilter == filetree.DisplayUntracked || filter == filetree.DisplayUntracked) { - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } else { self.c.PostRefreshUpdate(self.context()) } @@ -1740,7 +1740,7 @@ func (self *FilesController) remove(selectedNodes []*filetree.FileNode) error { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES, types.WORKTREES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.WORKTREES}}) return nil }, Keys: self.c.KeybindingsOpts().GetKeys(self.c.UserConfig().Keybinding.Files.ConfirmDiscard), @@ -1766,7 +1766,7 @@ func (self *FilesController) remove(selectedNodes []*filetree.FileNode) error { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES, types.WORKTREES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.WORKTREES}}) return nil }, Keys: menuKey('u'), @@ -1808,7 +1808,7 @@ func (self *FilesController) ResetSubmodule(submodule *models.SubmoduleConfig) e return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES, types.SUBMODULES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.SUBMODULES}}) return nil }) } diff --git a/pkg/gui/controllers/global_controller.go b/pkg/gui/controllers/global_controller.go index 8b9871294..77ef29070 100644 --- a/pkg/gui/controllers/global_controller.go +++ b/pkg/gui/controllers/global_controller.go @@ -158,7 +158,7 @@ func (self *GlobalController) createCustomPatchOptionsMenu() error { } func (self *GlobalController) refresh() error { - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil } diff --git a/pkg/gui/controllers/helpers/bisect_helper.go b/pkg/gui/controllers/helpers/bisect_helper.go index 6ce517dac..bc9548c4c 100644 --- a/pkg/gui/controllers/helpers/bisect_helper.go +++ b/pkg/gui/controllers/helpers/bisect_helper.go @@ -31,5 +31,5 @@ func (self *BisectHelper) Reset() error { } func (self *BisectHelper) PostBisectCommandRefresh() { - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{}}) } diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 5c72bacfd..83735d87d 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -49,7 +49,7 @@ func (self *BranchesHelper) ConfirmLocalDelete(branches []*models.Branch) error self.c.Contexts().Branches.CollapseRangeSelectionToTop() return nil }) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}}) return nil }) }) @@ -87,7 +87,7 @@ func (self *BranchesHelper) ConfirmDeleteRemote(remoteBranches []*models.RemoteB if err := self.deleteRemoteBranches(remoteBranches, task); err != nil { return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) if resetRemoteBranchesSelection { self.c.OnUIThread(func() error { self.c.Contexts().RemoteBranches.CollapseRangeSelectionToTop() @@ -161,7 +161,7 @@ func (self *BranchesHelper) ConfirmLocalAndRemoteDelete(branches []*models.Branc self.c.Contexts().Branches.CollapseRangeSelectionToTop() return nil }) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}}) return nil }) }, @@ -325,7 +325,6 @@ func (self *BranchesHelper) deleteLocalBranchesContinuation(branches []*models.B return nil }) self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}, }) return nil @@ -346,7 +345,6 @@ func (self *BranchesHelper) deleteLocalAndRemoteBranchesContinuation(branches [] return nil }) self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.REMOTES, types.FILES}, }) return nil @@ -407,7 +405,6 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er // returns (where it would still see the previous branches). self.c.RefreshFromWorker(types.RefreshOptions{ Scope: scope, - Mode: types.SYNC, Background: background, Then: func() error { if fetchErr != nil { @@ -458,7 +455,7 @@ func (self *BranchesHelper) AutoForwardBranches(background bool) error { self.c.LogCommand(strings.TrimRight(updateCommands, "\n"), false) err := self.c.Git().Branch.UpdateBranchRefs(updateCommands) - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Mode: types.SYNC, Background: background}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Background: background}) return err } diff --git a/pkg/gui/controllers/helpers/cherry_pick_helper.go b/pkg/gui/controllers/helpers/cherry_pick_helper.go index 673f657f5..b69b68514 100644 --- a/pkg/gui/controllers/helpers/cherry_pick_helper.go +++ b/pkg/gui/controllers/helpers/cherry_pick_helper.go @@ -95,7 +95,7 @@ func (self *CherryPickHelper) Paste() error { cherryPickedCommits := self.getData().CherryPickedCommits result := self.c.Git().Rebase.CherryPickCommits(cherryPickedCommits) - err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{Mode: types.SYNC}) + err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{}) if err != nil { return result } diff --git a/pkg/gui/controllers/helpers/credentials_helper.go b/pkg/gui/controllers/helpers/credentials_helper.go index 9b2198ccb..7c765020e 100644 --- a/pkg/gui/controllers/helpers/credentials_helper.go +++ b/pkg/gui/controllers/helpers/credentials_helper.go @@ -33,7 +33,7 @@ func (self *CredentialsHelper) PromptUserForCredential(passOrUname oscommands.Cr HandleConfirm: func(input string) error { ch <- input + "\n" - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }, HandleClose: func() error { diff --git a/pkg/gui/controllers/helpers/diff_helper.go b/pkg/gui/controllers/helpers/diff_helper.go index 668ee916a..6af3b2b5c 100644 --- a/pkg/gui/controllers/helpers/diff_helper.go +++ b/pkg/gui/controllers/helpers/diff_helper.go @@ -94,7 +94,7 @@ func (self *DiffHelper) FilterPathsForCommit(commit *models.Commit) []string { func (self *DiffHelper) ExitDiffMode() error { self.c.Modes().Diffing = diffing.New() - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil } diff --git a/pkg/gui/controllers/helpers/fixup_helper.go b/pkg/gui/controllers/helpers/fixup_helper.go index dfde8365b..a958e58a8 100644 --- a/pkg/gui/controllers/helpers/fixup_helper.go +++ b/pkg/gui/controllers/helpers/fixup_helper.go @@ -137,7 +137,7 @@ func (self *FixupHelper) HandleFindBaseCommitForFixupPress() error { if err := self.c.Git().WorkingTree.StageAll(true); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } self.c.Contexts().LocalCommits.SetSelection(index) diff --git a/pkg/gui/controllers/helpers/gpg_helper.go b/pkg/gui/controllers/helpers/gpg_helper.go index fd74a400b..9c7667a6d 100644 --- a/pkg/gui/controllers/helpers/gpg_helper.go +++ b/pkg/gui/controllers/helpers/gpg_helper.go @@ -26,7 +26,7 @@ func (self *GpgHelper) WithGpgHandling( onSuccess func() error, refreshScope []types.RefreshableView, ) error { - refreshOptions := types.RefreshOptions{Mode: types.ASYNC, Scope: refreshScope} + refreshOptions := types.RefreshOptions{Scope: refreshScope} return self.withGpgHandling( cmdObj, configKey, waitingStatus, onSuccess, refreshOptions, refreshOptions) } @@ -40,8 +40,8 @@ func (self *GpgHelper) WithGpgHandlingAndSelectHeadCommit( waitingStatus string, onSuccess func() error, ) error { - failureRefreshOptions := types.RefreshOptions{Mode: types.ASYNC} - successRefreshOptions := types.RefreshOptions{Mode: types.ASYNC, CommitSelection: types.SelectHeadCommit} + failureRefreshOptions := types.RefreshOptions{} + successRefreshOptions := types.RefreshOptions{CommitSelection: types.SelectHeadCommit} return self.withGpgHandling( cmdObj, configKey, waitingStatus, onSuccess, failureRefreshOptions, successRefreshOptions) } diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 267453a86..7f1a31188 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -133,7 +133,6 @@ func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWa // TODO: see if we should be calling more of the code from self.Git.Rebase.GenericMergeOrRebaseAction success, err := self.c.RunSubprocess(self.c.Git().Rebase.GenericMergeOrRebaseActionCmdObj(commandType, command)) self.refreshAfterMergeOrRebase(types.RefreshOptions{ - Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(success && selectHeadCommitOnSuccess), }, calledFromWorker) self.RecordWhetherMergeOrRebaseStartedInLazygit() @@ -144,7 +143,6 @@ func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWa result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) return self.checkMergeOrRebaseImpl(result, types.RefreshOptions{ - Mode: types.ASYNC, CommitSelection: commitSelectionAfterMerge(result == nil && selectHeadCommitOnSuccess), }, calledFromWorker) } @@ -258,7 +256,7 @@ func (self *MergeAndRebaseHelper) refreshAfterMergeOrRebase(refreshOptions types } func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { - return self.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{Mode: types.ASYNC}) + return self.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{}) } // Like CheckMergeOrRebase, but for operations that create a new commit at HEAD @@ -267,7 +265,7 @@ func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { // before the refresh. func (self *MergeAndRebaseHelper) CheckMergeOrRebaseAndSelectHeadCommit(result error) error { return self.CheckMergeOrRebaseWithRefreshOptions(result, - types.RefreshOptions{Mode: types.SYNC, CommitSelection: commitSelectionAfterMerge(result == nil)}) + types.RefreshOptions{CommitSelection: commitSelectionAfterMerge(result == nil)}) } func (self *MergeAndRebaseHelper) CheckForConflicts(result error) error { @@ -346,7 +344,7 @@ func (self *MergeAndRebaseHelper) PromptToContinueRebase() { // to read it in Then; reading it inline here would see the previous // model. self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}, + Scope: []types.RefreshableView{types.FILES}, Then: func() error { unstagedFiles := GetUnstagedFilesExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) if len(unstagedFiles) > 0 { @@ -667,7 +665,7 @@ func (self *MergeAndRebaseHelper) SquashMergeCommitted(refName, checkedOutBranch if err != nil { return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 2482e6015..fdb526549 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -147,15 +147,18 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr self.c.Log.Infof("Refresh took %s", time.Since(t)) }() + // A refresh from a worker blocks that worker until it's done; one from the + // UI thread returns immediately and finishes in the background. + syncOrAsync := "async" + if calledFromWorker { + syncOrAsync = "sync" + } if options.Scope == nil { - self.c.Log.Infof( - "refreshing all scopes in %s mode", - getModeName(options.Mode), - ) + self.c.Log.Infof("refreshing all scopes (%s)", syncOrAsync) } else { self.c.Log.Infof( - "refreshing the following scopes in %s mode: %s", - getModeName(options.Mode), + "refreshing the following scopes (%s): %s", + syncOrAsync, strings.Join(getScopeNames(options.Scope), ","), ) } @@ -530,17 +533,6 @@ func getScopeNames(scopes []types.RefreshableView) []string { }) } -func getModeName(mode types.RefreshMode) string { - switch mode { - case types.SYNC: - return "sync" - case types.ASYNC: - return "async" - default: - return "unknown mode" - } -} - // During startup, the bottleneck is fetching the reflog entries, which we need // in order to sort the branches by recency. So we have two phases: INITIAL and // COMPLETE. In the INITIAL phase we don't have any reflog commits yet, so we diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index e91a6c500..675c332a0 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -56,7 +56,6 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions scope = append(scope, types.PULL_REQUESTS) } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.SYNC, BatchUIUpdates: true, Scope: scope, BranchSelection: types.SelectCheckedOutBranch, @@ -161,7 +160,6 @@ func (self *RefsHelper) CheckoutRemoteBranch(fullBranchName string, localBranchN // Do a sync refresh to make sure the new branch is visible, // so that we see an inline status when checking it out self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.BRANCHES}, }) return checkout(localBranchName, true) @@ -365,7 +363,6 @@ func (self *RefsHelper) NewBranch(from string, fromFormattedName string, suggest refresh := func() { self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.SYNC, BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, @@ -552,7 +549,6 @@ func (self *RefsHelper) moveCommitsToNewBranchStackedOnCurrentBranch(newBranchNa } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.SYNC, BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, @@ -577,7 +573,7 @@ func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName stri } err := self.c.Git().Rebase.CherryPickCommits(commitsToCherryPick) - err = self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(err, types.RefreshOptions{Mode: types.SYNC}) + err = self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(err, types.RefreshOptions{}) if err != nil { return err } @@ -589,7 +585,6 @@ func (self *RefsHelper) moveCommitsToNewBranchOffOfMainBranch(newBranchName stri } self.c.RefreshFromWorker(types.RefreshOptions{ - Mode: types.SYNC, BatchUIUpdates: true, BranchSelection: types.SelectCheckedOutBranch, CommitSelection: types.SelectHeadCommit, diff --git a/pkg/gui/controllers/helpers/working_tree_helper.go b/pkg/gui/controllers/helpers/working_tree_helper.go index 36dfd2032..5f68cb822 100644 --- a/pkg/gui/controllers/helpers/working_tree_helper.go +++ b/pkg/gui/controllers/helpers/working_tree_helper.go @@ -238,7 +238,6 @@ func (self *WorkingTreeHelper) WithEnsureCommittableFiles(handler func() error) return err } self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}, Then: handler, }) @@ -260,7 +259,7 @@ func (self *WorkingTreeHelper) promptToStageAllAndRetry(retry func() error) erro if err := self.c.Git().WorkingTree.StageAll(false); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return retry() }, @@ -360,7 +359,7 @@ func (self *WorkingTreeHelper) CreateMergeConflictMenu(selectedFilepaths []strin } err := self.c.Git().WorkingTree.StageFiles(selectedFilepaths, nil) - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.FILES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) return err } diff --git a/pkg/gui/controllers/helpers/worktree_helper.go b/pkg/gui/controllers/helpers/worktree_helper.go index 980d810ae..35d515d6e 100644 --- a/pkg/gui/controllers/helpers/worktree_helper.go +++ b/pkg/gui/controllers/helpers/worktree_helper.go @@ -163,7 +163,7 @@ func (self *WorktreeHelper) remove(worktree *models.Worktree, force bool, then f return then(task) } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) } @@ -181,7 +181,7 @@ func (self *WorktreeHelper) Detach(worktree *models.Worktree, then func(gocui.Ta return then(task) } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.WORKTREES, types.BRANCHES, types.FILES}}) return nil }) } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index ade7d1a9a..19e0a7c17 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -476,7 +476,7 @@ func (self *LocalCommitsController) switchFromCommitMessagePanelToEditor(filepat return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil } @@ -495,7 +495,7 @@ func (self *LocalCommitsController) handleReword(summary string, description str if err != nil { return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) } @@ -700,7 +700,7 @@ func (self *LocalCommitsController) updateTodosWithFlag(action todo.TodoCommand, } self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, + Scope: []types.RefreshableView{types.REBASE_COMMITS}, }) return nil @@ -742,7 +742,6 @@ func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, s self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, CommitSelection: types.KeepCommitSelectionIndex, }) @@ -757,7 +756,7 @@ func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, s self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) } return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{Mode: types.SYNC, CommitSelection: types.KeepCommitSelectionIndex}) + err, types.RefreshOptions{CommitSelection: types.KeepCommitSelectionIndex}) }) } @@ -770,7 +769,6 @@ func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, sta self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) self.c.Refresh(types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS}, CommitSelection: types.KeepCommitSelectionIndex, }) @@ -785,7 +783,7 @@ func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, sta self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) } return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{Mode: types.SYNC, CommitSelection: types.KeepCommitSelectionIndex}) + err, types.RefreshOptions{CommitSelection: types.KeepCommitSelectionIndex}) }) } @@ -798,7 +796,7 @@ func (self *LocalCommitsController) amendTo(commit *models.Commit) error { if err := self.c.Helpers().AmendHelper.AmendHead(); err != nil { return err } - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }) } @@ -875,7 +873,7 @@ func (self *LocalCommitsController) resetAuthor(commits []*models.Commit, start, return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) } @@ -891,7 +889,7 @@ func (self *LocalCommitsController) setAuthor(commits []*models.Commit, start, e return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) }, @@ -910,7 +908,7 @@ func (self *LocalCommitsController) addCoAuthor(commits []*models.Commit, start, if err := self.c.Git().Rebase.AddCommitCoAuthor(commits, start, end, value); err != nil { return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) }, @@ -948,7 +946,7 @@ func (self *LocalCommitsController) revert(commits []*models.Commit, start, end } result := self.c.Git().Commit.Revert(hashes, isMerge) - if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{Mode: types.SYNC}); err != nil { + if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{}); err != nil { return err } @@ -996,7 +994,7 @@ func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) err return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }) }) @@ -1096,7 +1094,7 @@ func (self *LocalCommitsController) createAmendCommit(commit *models.Commit, inc return err } - self.c.Refresh(types.RefreshOptions{Mode: types.SYNC}) + self.c.Refresh(types.RefreshOptions{}) return nil }) }, @@ -1149,7 +1147,7 @@ func (self *LocalCommitsController) squashFixupsImpl(commit *models.Commit, reba err := self.c.Git().Rebase.SquashAllAboveFixupCommits(commit) self.context().MoveSelectedLine(-selectionOffset) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{Mode: types.SYNC}) + err, types.RefreshOptions{}) }) } @@ -1196,7 +1194,7 @@ func (self *LocalCommitsController) openSearch() error { // we usually lazyload these commits but now that we're searching we need to load them now if self.context().GetLimitCommits() { self.context().SetLimitCommits(false) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS}}) } return self.c.Helpers().Search.OpenSearchPrompt(self.context()) @@ -1217,7 +1215,7 @@ func (self *LocalCommitsController) handleOpenLogMenu() error { return self.c.WithWaitingStatus(self.c.Tr.LoadingCommits, func(gocui.Task) error { self.c.Refresh( - types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS}}, ) return nil }) @@ -1271,7 +1269,6 @@ func (self *LocalCommitsController) handleOpenLogMenu() error { return self.c.WithWaitingStatus(self.c.Tr.LoadingCommits, func(gocui.Task) error { self.c.Refresh( types.RefreshOptions{ - Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS}, }, ) @@ -1316,7 +1313,7 @@ func (self *LocalCommitsController) GetOnFocus() func(types.OnFocusOpts) { context := self.context() if context.GetSelectedLineIdx() > COMMIT_THRESHOLD && context.GetLimitCommits() { context.SetLimitCommits(false) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS}}) } } } diff --git a/pkg/gui/controllers/merge_conflicts_controller.go b/pkg/gui/controllers/merge_conflicts_controller.go index 898eb356b..1af53fded 100644 --- a/pkg/gui/controllers/merge_conflicts_controller.go +++ b/pkg/gui/controllers/merge_conflicts_controller.go @@ -302,7 +302,7 @@ func (self *MergeConflictsController) resolveConflict(selection mergeconflicts.S func (self *MergeConflictsController) onLastConflictResolved() { // as part of refreshing files, we handle the situation where a file has had // its merge conflicts resolved. - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) } func (self *MergeConflictsController) openMergeConflictMenu() error { diff --git a/pkg/gui/controllers/patch_building_controller.go b/pkg/gui/controllers/patch_building_controller.go index d596c2ead..fe28ca603 100644 --- a/pkg/gui/controllers/patch_building_controller.go +++ b/pkg/gui/controllers/patch_building_controller.go @@ -229,7 +229,7 @@ func (self *PatchBuildingController) discardSelectionFromCommit() error { err := self.c.Git().Patch.DeletePatchesFromCommit(self.c.Model().Commits, commitIndex) self.c.Helpers().PatchBuilding.Escape() return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{Mode: types.SYNC}) + err, types.RefreshOptions{}) }) } diff --git a/pkg/gui/controllers/remote_branches_controller.go b/pkg/gui/controllers/remote_branches_controller.go index f70145d7b..0d50068f3 100644 --- a/pkg/gui/controllers/remote_branches_controller.go +++ b/pkg/gui/controllers/remote_branches_controller.go @@ -158,7 +158,7 @@ func (self *RemoteBranchesController) createSortMenu() error { if self.c.UserConfig().Git.RemoteBranchSortOrder != sortOrder { self.c.UserConfig().Git.RemoteBranchSortOrder = sortOrder self.c.Contexts().RemoteBranches.SetSelection(0) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.REMOTES}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.REMOTES}}) } return nil }, diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index d4c838f7c..76bd16bb1 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -163,7 +163,6 @@ func (self *RemotesController) addAndCheckoutRemote(remoteName string, remoteUrl // affordable. self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.REMOTES}, - Mode: types.SYNC, Then: func() error { // Select the remote for idx, remote := range self.c.Model().Remotes { @@ -371,7 +370,6 @@ func (self *RemotesController) fetchAndCheckout(remote *models.Remote, branchNam } refreshOptions := types.RefreshOptions{ Scope: []types.RefreshableView{types.BRANCHES, types.REMOTES}, - Mode: types.SYNC, } if branchName != "" { err = self.c.Git().Branch.New(branchName, remote.Name+"/"+branchName) diff --git a/pkg/gui/controllers/sub_commits_controller.go b/pkg/gui/controllers/sub_commits_controller.go index 8799cd3c6..d3d0c0b98 100644 --- a/pkg/gui/controllers/sub_commits_controller.go +++ b/pkg/gui/controllers/sub_commits_controller.go @@ -66,7 +66,7 @@ func (self *SubCommitsController) GetOnFocus() func(types.OnFocusOpts) { context := self.context() if context.GetSelectedLineIdx() > COMMIT_THRESHOLD && context.GetLimitCommits() { context.SetLimitCommits(false) - self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.SUB_COMMITS}}) + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.SUB_COMMITS}}) } } } diff --git a/pkg/gui/controllers/sync_controller.go b/pkg/gui/controllers/sync_controller.go index fafd4e7dd..61b92747b 100644 --- a/pkg/gui/controllers/sync_controller.go +++ b/pkg/gui/controllers/sync_controller.go @@ -229,7 +229,7 @@ func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts) } return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) return nil }) } diff --git a/pkg/gui/controllers/tags_controller.go b/pkg/gui/controllers/tags_controller.go index 2a59af5ec..a6c0e7e14 100644 --- a/pkg/gui/controllers/tags_controller.go +++ b/pkg/gui/controllers/tags_controller.go @@ -168,7 +168,7 @@ func (self *TagsController) localDelete(tag *models.Tag) error { return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag) err := self.c.Git().Tag.LocalDelete(tag.Name) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return err }) } @@ -210,7 +210,7 @@ func (self *TagsController) remoteDelete(tag *models.Tag) error { return err } self.c.Toast(self.c.Tr.RemoteTagDeletedMessage) - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, @@ -264,7 +264,7 @@ func (self *TagsController) localAndRemoteDelete(tag *models.Tag) error { if err := self.c.Git().Tag.LocalDelete(tag.Name); err != nil { return err } - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}}) return nil }) }, diff --git a/pkg/gui/controllers/workspace_reset_controller.go b/pkg/gui/controllers/workspace_reset_controller.go index 9a9005254..27e736648 100644 --- a/pkg/gui/controllers/workspace_reset_controller.go +++ b/pkg/gui/controllers/workspace_reset_controller.go @@ -46,7 +46,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -68,7 +68,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -86,7 +86,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -111,7 +111,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -129,7 +129,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -147,7 +147,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, @@ -170,7 +170,7 @@ func (self *FilesController) createResetMenu() error { } self.c.Refresh( - types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}}, + types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}, ) return nil }, diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 931b0909e..25e543abb 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -391,7 +391,7 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context } gui.c.Log.Info("Receiving focus - refreshing") - gui.helpers.Refresh.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + gui.helpers.Refresh.Refresh(types.RefreshOptions{}) return reloadErr } @@ -815,7 +815,7 @@ func NewGui( 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() error { gui.c.Refresh(types.RefreshOptions{}); return nil }, func() { gui.State.ContextMgr.Pop() }, func() types.Context { return gui.State.ContextMgr.Current() }, gui.createMenu, @@ -1023,7 +1023,7 @@ func (gui *Gui) runSubprocessWithSuspenseAndRefresh(subprocess *oscommands.CmdOb return err } - gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + gui.c.Refresh(types.RefreshOptions{}) return nil } @@ -1100,7 +1100,7 @@ func (gui *Gui) loadNewRepo() error { return err } - gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) + gui.c.Refresh(types.RefreshOptions{}) if err := gui.os.UpdateWindowTitle(); err != nil { return err diff --git a/pkg/gui/services/custom_commands/handler_creator.go b/pkg/gui/services/custom_commands/handler_creator.go index 4eb762019..6046d974a 100644 --- a/pkg/gui/services/custom_commands/handler_creator.go +++ b/pkg/gui/services/custom_commands/handler_creator.go @@ -314,7 +314,7 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses } output, err := cmdObj.RunWithOutput() - self.c.RefreshFromWorker(types.RefreshOptions{Mode: types.ASYNC}) + self.c.RefreshFromWorker(types.RefreshOptions{}) if err != nil { if customCommand.After != nil && customCommand.After.CheckForConflicts { diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index 7b304b15d..937c3a30e 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -25,13 +25,6 @@ const ( PULL_REQUESTS ) -type RefreshMode int - -const ( - SYNC RefreshMode = iota // wait until everything is done before returning - ASYNC // return immediately, allowing each independent thing to update itself -) - // CommitSelectionBehavior controls which local commit is selected after the // commits list is reloaded by a refresh. type CommitSelectionBehavior int @@ -73,7 +66,6 @@ const ( type RefreshOptions struct { Then func() error Scope []RefreshableView // e.g. []RefreshableView{COMMITS, BRANCHES}. Leave empty to refresh everything - Mode RefreshMode // one of SYNC (default) and ASYNC // If true, hold off on updating the UI until all scopes have finished // refreshing and then apply them together in a single frame, rather than From 6893d9a7590239c7a39aae3d2f3fd09a3e62f12d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 17:40:41 +0200 Subject: [PATCH 152/218] Add gocui primitives to block input during an operation Long-running operations that lazygit drives itself (rebases, and the commit surgery built on them) can be corrupted by keys the user presses while they run: pressing e to start an interactive rebase, then up+d before it finishes, must act on the resulting todo list, not race the rebase. WithWaitingStatusSync gets this today only as a side effect of freezing the UI thread, which the rest of this branch is moving away from. Add a nestable counter, BeginBlockingEvents/EndBlockingEvents, that withholds input at the event-dispatch layer without freezing anything: while blocked, key events are buffered and replayed in order once the count returns to zero (so they act on the now-current context), mouse clicks and hover are dropped (replaying them against a changed layout would target the wrong thing), and scrolling, resize, focus and all rendering keep flowing. These are the reusable core; a gui-level helper that brackets them around a worker operation follows. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/block_events_test.go | 98 ++++++++++++++++++++++++++++++++++ pkg/gocui/gui.go | 73 +++++++++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 pkg/gocui/block_events_test.go diff --git a/pkg/gocui/block_events_test.go b/pkg/gocui/block_events_test.go new file mode 100644 index 000000000..277bac89a --- /dev/null +++ b/pkg/gocui/block_events_test.go @@ -0,0 +1,98 @@ +package gocui + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestEventWithheldWhileBlocking(t *testing.T) { + scenarios := []struct { + name string + event GocuiEvent + withheld bool + }{ + {"key", GocuiEvent{Type: eventKey, Key: NewKeyRune('x')}, true}, + {"mouse click", GocuiEvent{Type: eventMouse, Key: NewKeyName(MouseLeft)}, true}, + {"mouse scroll", GocuiEvent{Type: eventMouse, Key: NewKeyName(MouseWheelDown)}, false}, + {"mouse move", GocuiEvent{Type: eventMouseMove}, true}, + {"resize", GocuiEvent{Type: eventResize}, false}, + {"focus", GocuiEvent{Type: eventFocus}, false}, + {"paste", GocuiEvent{Type: eventPaste}, false}, + {"error", GocuiEvent{Type: eventError}, false}, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + assert.Equal(t, s.withheld, eventWithheldWhileBlocking(&s.event)) + }) + } +} + +// setupKeyRecorder wires a keybinding on a focused view that records each time +// it fires, and returns the key event that triggers it plus the record slice. +func setupKeyRecorder(t *testing.T, g *Gui) (GocuiEvent, *[]int) { + t.Helper() + + _, _ = g.SetView("main", 0, 0, 80, 22, 0) + _, err := g.SetCurrentView("main") + assert.NoError(t, err) + + fired := []int{} + callCount := 0 + key := NewKeyRune('x') + g.SetKeybinding("main", key, func(*Gui, *View) error { + callCount++ + fired = append(fired, callCount) + return nil + }) + + return GocuiEvent{Type: eventKey, Key: key}, &fired +} + +func TestBlockingEvents_KeysBufferedAndReplayed(t *testing.T) { + g := newTestGui(t) + keyEvent, fired := setupKeyRecorder(t, g) + + // Not blocking: the key dispatches immediately. + assert.NoError(t, g.handleEvent(&keyEvent)) + assert.Len(t, *fired, 1) + + // While blocking: the key is buffered, not dispatched. + g.BeginBlockingEvents() + assert.NoError(t, g.handleEvent(&keyEvent)) + assert.NoError(t, g.handleEvent(&keyEvent)) + assert.Len(t, *fired, 1, "buffered keys must not dispatch while blocking") + + // Unblocking replays the buffered keys. + assert.NoError(t, g.EndBlockingEvents()) + assert.Len(t, *fired, 3, "both buffered keys should replay on unblock") + assert.Empty(t, g.bufferedKeyEvents) +} + +func TestBlockingEvents_NestsWithCounter(t *testing.T) { + g := newTestGui(t) + keyEvent, fired := setupKeyRecorder(t, g) + + g.BeginBlockingEvents() + g.BeginBlockingEvents() + assert.NoError(t, g.handleEvent(&keyEvent)) + + // The inner block ending still leaves us blocked: no replay yet. + assert.NoError(t, g.EndBlockingEvents()) + assert.Empty(t, *fired) + + // Only the outermost block ending replays. + assert.NoError(t, g.EndBlockingEvents()) + assert.Len(t, *fired, 1) +} + +func TestBlockingEvents_MouseClicksDroppedNotBuffered(t *testing.T) { + g := newTestGui(t) + + g.BeginBlockingEvents() + click := GocuiEvent{Type: eventMouse, Key: NewKeyName(MouseLeft)} + assert.NoError(t, g.handleEvent(&click)) + assert.Empty(t, g.bufferedKeyEvents, "mouse clicks must be dropped, not buffered") + assert.NoError(t, g.EndBlockingEvents()) +} diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 9da5225c0..700c2b54c 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -210,6 +210,14 @@ type Gui struct { // MainLoop starts. IsUIThread compares against it. Written once, read from // worker goroutines, so it's atomic. uiThreadID atomic.Int64 + + // blockInputCount, when greater than zero, withholds keyboard input from + // the handlers: key events are buffered into bufferedKeyEvents and replayed + // once the count drops back to zero, while mouse clicks and hover are + // dropped outright. It's a counter so blocking can nest. Both fields are + // only touched on the UI thread. See BeginBlockingEvents. + blockInputCount int + bufferedKeyEvents []GocuiEvent } type NewGuiOpts struct { @@ -806,6 +814,42 @@ func (g *Gui) IsUIThread() bool { return goid.Get() == g.uiThreadID.Load() } +// BeginBlockingEvents starts withholding keyboard input from the handlers, so a +// long-running operation can't be disrupted by keys the user presses while it +// runs. Keys are buffered and replayed once EndBlockingEvents balances this +// call; mouse clicks and hover are dropped for the duration. Scrolling, +// resizing, focus changes and all rendering keep working throughout. It's a +// counter, so blocking nests; every call must be paired with EndBlockingEvents. +// +// Must be called on the UI thread. Callers arrange this by beginning the block +// synchronously from the keybinding handler, before dispatching the operation +// to a worker — beginning it from the worker would race the next queued +// keypress, which is exactly the input we mean to withhold. +func (g *Gui) BeginBlockingEvents() { + g.blockInputCount++ +} + +// EndBlockingEvents balances a BeginBlockingEvents call. When the last nested +// block ends, the keys buffered while blocked are replayed in order through the +// normal dispatch path, so they act on the now-current context (a key whose +// binding no longer exists is simply ignored, just as if it had been pressed +// now). Must be called on the UI thread. +func (g *Gui) EndBlockingEvents() error { + g.blockInputCount-- + if g.blockInputCount > 0 { + return nil + } + + buffered := g.bufferedKeyEvents + g.bufferedKeyEvents = nil + for i := range buffered { + if err := g.handleEvent(&buffered[i]); err != nil { + return err + } + } + return nil +} + // OnUIThreadAndWait runs f on the main event-loop goroutine and blocks the // caller until f has run, returning f's error. Use it to read UI-thread-owned // state (the model, contexts) from a worker without racing the UI thread. @@ -1052,6 +1096,17 @@ func (g *Gui) processRemainingEvents() (bool, error) { // handleEvent handles an event, based on its type (key-press, error, // etc.) func (g *Gui) handleEvent(ev *GocuiEvent) error { + if g.blockInputCount > 0 && eventWithheldWhileBlocking(ev) { + if ev.Type == eventKey { + // Buffer keys so they replay against fresh state on unblock. + g.bufferedKeyEvents = append(g.bufferedKeyEvents, *ev) + } + // Mouse clicks and hover fall through to here without being buffered: + // replaying them once the operation has changed the layout underneath + // them would target the wrong thing, so we drop them outright. + return nil + } + switch ev.Type { case eventKey, eventMouse, eventMouseMove: return g.onKey(ev) @@ -1070,6 +1125,24 @@ func (g *Gui) handleEvent(ev *GocuiEvent) error { } } +// eventWithheldWhileBlocking reports whether an event must not reach the +// handlers while input is blocked (see BeginBlockingEvents). Key events are +// withheld (buffered for replay); mouse clicks and hover are withheld (dropped). +// Everything else — mouse scrolling, resize, focus, paste, errors — flows +// through as usual. +func eventWithheldWhileBlocking(ev *GocuiEvent) bool { + switch ev.Type { + case eventKey: + return true + case eventMouse: + return !IsMouseScrollKey(ev.Key.KeyName()) + case eventMouseMove: + return true + default: + return false + } +} + func (g *Gui) onResize() { // not sure if we actually need this // g.screen.Sync() From 707b04a8c2b1b93908e41343abf19b877e9ef9a0 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 17:43:06 +0200 Subject: [PATCH 153/218] Add a WithWaitingStatusBlockingInput helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bracket gocui's BeginBlockingEvents/EndBlockingEvents around a worker operation that shows a waiting status. The block is begun synchronously on the UI thread, before the operation is dispatched to a worker, so no keypress can slip through in between; it ends via OnUIThread once the operation and its refresh have applied their UI updates, so the replayed keys act on the refreshed state. This composes what the retiring WithWaitingStatusSync did — show a status and block input — but on a worker, so the UI keeps rendering (spinner animates, model updates land) instead of freezing. Callers follow in subsequent commits. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/app_status_helper.go | 24 +++++++++ pkg/gui/gui.go | 3 ++ pkg/gui/popup/popup_handler.go | 50 +++++++++++-------- pkg/gui/types/common.go | 1 + 4 files changed, 57 insertions(+), 21 deletions(-) diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index 90b87b3b8..a366909f6 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -86,6 +86,30 @@ func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui. }) } +// WithWaitingStatusBlockingInput is like WithWaitingStatus, but it also blocks +// keyboard input for the whole duration of the operation: keys the user presses +// while it runs are buffered and replayed against the post-operation state (see +// gocui.BeginBlockingEvents). Use it for operations that manipulate an +// in-progress rebase or otherwise rewrite commits, where a racing keypress +// would target the wrong commit or todo. +// +// Must be called on the UI thread: the block is begun synchronously here, before +// the operation is dispatched to a worker, so no keypress can slip through in +// between. +func (self *AppStatusHelper) WithWaitingStatusBlockingInput(message string, f func(gocui.Task) error) { + self.c.GocuiGui().BeginBlockingEvents() + self.c.OnWorker(func(task gocui.Task) error { + // End the block once the operation and its refresh have applied their UI + // updates: OnUIThread queues this after the refresh's model bounces and + // Then (which RefreshFromWorker has already enqueued by the time f + // returns), so the replayed keys act on the refreshed state. + defer self.c.OnUIThread(func() error { + return self.c.GocuiGui().EndBlockingEvents() + }) + return self.WithWaitingStatusImpl(message, f, task, false) + }) +} + func (self *AppStatusHelper) WithWaitingStatusSync(message string, f func() error) error { self.c.PauseBackgroundRefreshes(true) defer self.c.PauseBackgroundRefreshes(false) diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 25e543abb..a6baaf373 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -820,6 +820,9 @@ func NewGui( 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(gocui.Task) error) { + gui.helpers.AppStatus.WithWaitingStatusBlockingInput(message, f) + }, func(message string, f func() error) error { return gui.helpers.AppStatus.WithWaitingStatusSync(message, f) }, diff --git a/pkg/gui/popup/popup_handler.go b/pkg/gui/popup/popup_handler.go index ab067410d..23084f9ce 100644 --- a/pkg/gui/popup/popup_handler.go +++ b/pkg/gui/popup/popup_handler.go @@ -13,16 +13,17 @@ import ( 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 + 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) + withWaitingStatusBlockingInputFn 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{} @@ -35,23 +36,25 @@ func NewPopupHandler( currentContextFn func() types.Context, createMenuFn func(types.CreateMenuOptions) error, withWaitingStatusFn func(message string, f func(gocui.Task) error), + withWaitingStatusBlockingInputFn 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, + Common: common, + createPopupPanelFn: createPopupPanelFn, + onErrorFn: onErrorFn, + popContextFn: popContextFn, + currentContextFn: currentContextFn, + createMenuFn: createMenuFn, + withWaitingStatusFn: withWaitingStatusFn, + withWaitingStatusBlockingInputFn: withWaitingStatusBlockingInputFn, + withWaitingStatusSyncFn: withWaitingStatusSyncFn, + toastFn: toastFn, + getPromptInputFn: getPromptInputFn, + inDemo: inDemo, } } @@ -76,6 +79,11 @@ func (self *PopupHandler) WithWaitingStatus(message string, f func(gocui.Task) e return nil } +func (self *PopupHandler) WithWaitingStatusBlockingInput(message string, f func(gocui.Task) error) error { + self.withWaitingStatusBlockingInputFn(message, f) + return nil +} + func (self *PopupHandler) WithWaitingStatusSync(message string, f func() error) error { return self.withWaitingStatusSyncFn(message, f) } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 08ff53bb0..964143c5a 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -161,6 +161,7 @@ type IPopupHandler interface { // Shows a popup prompting the user for input. Prompt(opts PromptOpts) WithWaitingStatus(message string, f func(gocui.Task) error) error + WithWaitingStatusBlockingInput(message string, f func(gocui.Task) error) error WithWaitingStatusSync(message string, f func() error) error Menu(opts CreateMenuOptions) error Toast(message string) From 62098ca6039bb7fd40c4fda2d266292e1de9996f Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 17:53:44 +0200 Subject: [PATCH 154/218] Pass captured state to moveFixupCommitToOwnerStackedBranch It reads the selected index and the commits and branches models to decide where to move the fixup commit. Take those as parameters, captured on the UI thread by the callers, so the function can run its rebase on a worker without reading the model there. No behavior change; the callers still run on the UI thread for now. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/local_commits_controller.go | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 19e0a7c17..17547f6c8 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -985,12 +985,15 @@ func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) err OnPress: func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { self.c.LogAction(self.c.Tr.Actions.CreateFixupCommit) + selectedIdx := self.context().GetSelectedLineIdx() + commits := self.c.Model().Commits + branches := self.c.Model().Branches return self.c.WithWaitingStatusSync(self.c.Tr.CreatingFixupCommitStatus, func() error { if err := self.c.Git().Commit.CreateFixupCommit(commit.Hash()); err != nil { return err } - if err := self.moveFixupCommitToOwnerStackedBranch(commit); err != nil { + if err := self.moveFixupCommitToOwnerStackedBranch(commit, selectedIdx, commits, branches); err != nil { return err } @@ -1023,7 +1026,12 @@ func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) err }) } -func (self *LocalCommitsController) moveFixupCommitToOwnerStackedBranch(targetCommit *models.Commit) error { +// moveFixupCommitToOwnerStackedBranch takes state captured on the UI thread +// (the selected index and the commits and branches models) so that it can run +// its rebase on a worker without reading the model there. +func (self *LocalCommitsController) moveFixupCommitToOwnerStackedBranch( + targetCommit *models.Commit, selectedIdx int, commits []*models.Commit, branches []*models.Branch, +) error { if self.c.Git().Version.IsOlderThan(2, 38, 0) { // Git 2.38.0 introduced the `rebase.updateRefs` config option. Don't // move the commit down with older versions, as it would break the stack. @@ -1051,9 +1059,9 @@ func (self *LocalCommitsController) moveFixupCommitToOwnerStackedBranch(targetCo } headOfOwnerBranchIdx := -1 - for i := self.context().GetSelectedLineIdx(); i > 0; i-- { - if lo.SomeBy(self.c.Model().Branches, func(b *models.Branch) bool { - return b.CommitHash == self.c.Model().Commits[i].Hash() + for i := selectedIdx; i > 0; i-- { + if lo.SomeBy(branches, func(b *models.Branch) bool { + return b.CommitHash == commits[i].Hash() }) { headOfOwnerBranchIdx = i break @@ -1064,7 +1072,7 @@ func (self *LocalCommitsController) moveFixupCommitToOwnerStackedBranch(targetCo return nil } - return self.c.Git().Rebase.MoveFixupCommitDown(self.c.Model().Commits, headOfOwnerBranchIdx) + return self.c.Git().Rebase.MoveFixupCommitDown(commits, headOfOwnerBranchIdx) } func (self *LocalCommitsController) createAmendCommit(commit *models.Commit, includeFileChanges bool) error { @@ -1085,12 +1093,15 @@ func (self *LocalCommitsController) createAmendCommit(commit *models.Commit, inc PreserveMessage: false, OnConfirm: func(summary string, description string) error { self.c.LogAction(self.c.Tr.Actions.CreateFixupCommit) + selectedIdx := self.context().GetSelectedLineIdx() + commits := self.c.Model().Commits + branches := self.c.Model().Branches return self.c.WithWaitingStatusSync(self.c.Tr.CreatingFixupCommitStatus, func() error { if err := self.c.Git().Commit.CreateAmendCommit(originalSubject, summary, description, includeFileChanges); err != nil { return err } - if err := self.moveFixupCommitToOwnerStackedBranch(commit); err != nil { + if err := self.moveFixupCommitToOwnerStackedBranch(commit, selectedIdx, commits, branches); err != nil { return err } From 352883c52b442e751ab5b12e2c87bcfac306f1f1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 17:57:26 +0200 Subject: [PATCH 155/218] Run the sync commit-surgery ops on a worker with input blocked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move, revert, squash-fixups, create-fixup and cherry-pick paste ran their rebase synchronously on the UI thread via WithWaitingStatusSync, which froze the UI for the duration but kept the user from disrupting the operation with a stray keypress. Switch them to WithWaitingStatusBlockingInput so the git work runs on a worker — the UI keeps rendering and the spinner animates — while input stays blocked for the whole operation, as before. discard-patch-from-commit also moves off WithWaitingStatusSync, but as a plain WithWaitingStatus: it's a custom-patch command, and those don't block input. The bodies now follow the worker conventions: model state they need is captured on the UI thread before dispatching, self.c.Refresh becomes RefreshFromWorker, and CheckMergeOrRebase uses the worker variant. An operation that moves the selection does so in the refresh's Then, so it lands in the same frame as the refreshed commit list; squash sets it as an absolute index there, because the shorter list would clamp a relative move. --- .../controllers/helpers/cherry_pick_helper.go | 22 +++-- .../controllers/local_commits_controller.go | 92 +++++++++++++------ .../controllers/patch_building_controller.go | 16 +++- 3 files changed, 88 insertions(+), 42 deletions(-) diff --git a/pkg/gui/controllers/helpers/cherry_pick_helper.go b/pkg/gui/controllers/helpers/cherry_pick_helper.go index b69b68514..fc96b9d1b 100644 --- a/pkg/gui/controllers/helpers/cherry_pick_helper.go +++ b/pkg/gui/controllers/helpers/cherry_pick_helper.go @@ -4,6 +4,7 @@ import ( "strconv" "github.com/jesseduffield/lazygit/pkg/commands/models" + "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" @@ -82,9 +83,9 @@ func (self *CherryPickHelper) Paste() error { "numCommits": strconv.Itoa(len(self.getData().CherryPickedCommits)), }), HandleConfirm: func() error { - return self.c.WithWaitingStatusSync(self.c.Tr.CherryPickingStatus, func() error { - mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) - + mustStash := IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) + cherryPickedCommits := self.getData().CherryPickedCommits + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.CherryPickingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.CherryPick) if mustStash { @@ -93,9 +94,9 @@ func (self *CherryPickHelper) Paste() error { } } - cherryPickedCommits := self.getData().CherryPickedCommits result := self.c.Git().Rebase.CherryPickCommits(cherryPickedCommits) - err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{}) + err := self.rebaseHelper.CheckMergeOrRebaseWithRefreshOptions(result, + types.RefreshOptions{BatchUIUpdates: true}) if err != nil { return result } @@ -109,14 +110,19 @@ func (self *CherryPickHelper) Paste() error { return result } if !isInCherryPick { - self.getData().DidPaste = true - self.rerender() + // DidPaste and the re-render touch mode state and contexts, + // so run them on the UI thread. + self.c.OnUIThread(func() error { + self.getData().DidPaste = true + self.rerender() + return nil + }) if mustStash { if err := self.c.Git().Stash.Pop(0); err != nil { return err } - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Scope: []types.RefreshableView{types.STASH, types.FILES}, }) } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 17547f6c8..1234b80ec 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -748,15 +748,24 @@ func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, s return nil } - return self.c.WithWaitingStatusSync(self.c.Tr.MovingStatus, func() error { + commits := self.c.Model().Commits + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.MovingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.MoveCommitDown) - err := self.c.Git().Rebase.MoveCommitsDown(self.c.Model().Commits, startIdx, endIdx) - if err == nil { - self.context().MoveSelection(1) - self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) - } - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{CommitSelection: types.KeepCommitSelectionIndex}) + err := self.c.Git().Rebase.MoveCommitsDown(commits, startIdx, endIdx) + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + err, types.RefreshOptions{ + BatchUIUpdates: true, + CommitSelection: types.KeepCommitSelectionIndex, + // Move the selection to follow the moved commit, in Then so it + // lands in the same frame as the refreshed commit list. + Then: func() error { + if err == nil { + self.context().MoveSelection(1) + self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) + } + return nil + }, + }) }) } @@ -775,15 +784,24 @@ func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, sta return nil } - return self.c.WithWaitingStatusSync(self.c.Tr.MovingStatus, func() error { + commits := self.c.Model().Commits + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.MovingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.MoveCommitUp) - err := self.c.Git().Rebase.MoveCommitsUp(self.c.Model().Commits, startIdx, endIdx) - if err == nil { - self.context().MoveSelection(-1) - self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) - } - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{CommitSelection: types.KeepCommitSelectionIndex}) + err := self.c.Git().Rebase.MoveCommitsUp(commits, startIdx, endIdx) + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + err, types.RefreshOptions{ + BatchUIUpdates: true, + CommitSelection: types.KeepCommitSelectionIndex, + // Move the selection to follow the moved commit, in Then so it + // lands in the same frame as the refreshed commit list. + Then: func() error { + if err == nil { + self.context().MoveSelection(-1) + self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) + } + return nil + }, + }) }) } @@ -936,9 +954,8 @@ func (self *LocalCommitsController) revert(commits []*models.Commit, start, end Prompt: promptText, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.RevertCommit) - return self.c.WithWaitingStatusSync(self.c.Tr.RevertingStatus, func() error { - mustStash := helpers.IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) - + mustStash := helpers.IsWorkingTreeDirtyExceptSubmodules(self.c.Model().Files, self.c.Model().Submodules) + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.RevertingStatus, func(gocui.Task) error { if mustStash { if err := self.c.Git().Stash.Push(self.c.Tr.AutoStashForReverting); err != nil { return err @@ -946,7 +963,8 @@ func (self *LocalCommitsController) revert(commits []*models.Commit, start, end } result := self.c.Git().Commit.Revert(hashes, isMerge) - if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result, types.RefreshOptions{}); err != nil { + if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions(result, + types.RefreshOptions{BatchUIUpdates: true}); err != nil { return err } @@ -954,7 +972,7 @@ func (self *LocalCommitsController) revert(commits []*models.Commit, start, end if err := self.c.Git().Stash.Pop(0); err != nil { return err } - self.c.Refresh(types.RefreshOptions{ + self.c.RefreshFromWorker(types.RefreshOptions{ Scope: []types.RefreshableView{types.STASH, types.FILES}, }) } @@ -988,7 +1006,7 @@ func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) err selectedIdx := self.context().GetSelectedLineIdx() commits := self.c.Model().Commits branches := self.c.Model().Branches - return self.c.WithWaitingStatusSync(self.c.Tr.CreatingFixupCommitStatus, func() error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.CreatingFixupCommitStatus, func(gocui.Task) error { if err := self.c.Git().Commit.CreateFixupCommit(commit.Hash()); err != nil { return err } @@ -997,7 +1015,7 @@ func (self *LocalCommitsController) createFixupCommit(commit *models.Commit) err return err } - self.c.Refresh(types.RefreshOptions{}) + self.c.RefreshFromWorker(types.RefreshOptions{BatchUIUpdates: true}) return nil }) }) @@ -1096,7 +1114,7 @@ func (self *LocalCommitsController) createAmendCommit(commit *models.Commit, inc selectedIdx := self.context().GetSelectedLineIdx() commits := self.c.Model().Commits branches := self.c.Model().Branches - return self.c.WithWaitingStatusSync(self.c.Tr.CreatingFixupCommitStatus, func() error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.CreatingFixupCommitStatus, func(gocui.Task) error { if err := self.c.Git().Commit.CreateAmendCommit(originalSubject, summary, description, includeFileChanges); err != nil { return err } @@ -1105,7 +1123,7 @@ func (self *LocalCommitsController) createAmendCommit(commit *models.Commit, inc return err } - self.c.Refresh(types.RefreshOptions{}) + self.c.RefreshFromWorker(types.RefreshOptions{BatchUIUpdates: true}) return nil }) }, @@ -1153,12 +1171,28 @@ func (self *LocalCommitsController) squashAllFixupsInCurrentBranch() error { func (self *LocalCommitsController) squashFixupsImpl(commit *models.Commit, rebaseStartIdx int) error { selectionOffset := countSquashableCommitsAbove(self.c.Model().Commits, self.context().GetSelectedLineIdx(), rebaseStartIdx) - return self.c.WithWaitingStatusSync(self.c.Tr.SquashingStatus, func() error { + // The squashed fixups above the selection are removed, so the selection moves + // up by that many rows to stay on the same commit. Compute the target as an + // absolute index now, on the current list. + targetIdx := self.context().GetSelectedLineIdx() - selectionOffset + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.SquashingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SquashAllAboveFixupCommits) err := self.c.Git().Rebase.SquashAllAboveFixupCommits(commit) - self.context().MoveSelectedLine(-selectionOffset) - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( - err, types.RefreshOptions{}) + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( + err, types.RefreshOptions{ + BatchUIUpdates: true, + // Set the selection in Then so it lands in the same frame as the + // refreshed commit list. It has to be an absolute index: the new + // list is shorter, so a relative move from the (clamped) old index + // could overshoot. PostRefreshUpdate repaints the moved selection. + Then: func() error { + if err == nil { + self.context().SetSelectedLineIdx(targetIdx) + self.c.PostRefreshUpdate(self.context()) + } + return nil + }, + }) }) } diff --git a/pkg/gui/controllers/patch_building_controller.go b/pkg/gui/controllers/patch_building_controller.go index fe28ca603..f3e26e303 100644 --- a/pkg/gui/controllers/patch_building_controller.go +++ b/pkg/gui/controllers/patch_building_controller.go @@ -223,12 +223,18 @@ func (self *PatchBuildingController) discardSelectionFromCommit() error { return nil } - return self.c.WithWaitingStatusSync(self.c.Tr.RebasingStatus, func() error { - commitIndex := self.getPatchCommitIndex() + commits := self.c.Model().Commits + commitIndex := self.getPatchCommitIndex() + return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.RemovePatchFromCommit) - err := self.c.Git().Patch.DeletePatchesFromCommit(self.c.Model().Commits, commitIndex) - self.c.Helpers().PatchBuilding.Escape() - return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptionsFromUIThread( + err := self.c.Git().Patch.DeletePatchesFromCommit(commits, commitIndex) + // Escape pops the patch-building context, so run it on the UI thread + // before the refresh below. + _ = self.c.GocuiGui().OnUIThreadAndWait(func() error { + self.c.Helpers().PatchBuilding.Escape() + return nil + }) + return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{}) }) } From d802cbdddf43868435fd6df997ba0fae214b41bd Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 18:00:53 +0200 Subject: [PATCH 156/218] Block input during the worker commit-surgery ops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit edit, quick-start rebase, drop, reword, squash, fixup, amend (including the amend-attribute author operations) and discard-file-from-commit all run a rebase on a worker. A key pressed while one is in flight could act on a stale commit or todo — pressing e to start an interactive rebase, then up+d before it finishes, is the motivating example. Switch them from WithWaitingStatus to WithWaitingStatusBlockingInput so input is held and replayed against the post-operation state, matching the commit-surgery ops that were already sync. Left alone: the custom-patch move/delete/pull-into-commit rebases (no need to block input while building and applying a patch), the loading-more-commits and patch-building toggle spinners (no rebase to disrupt), and fetches and other non-surgery operations where blocking navigation would only get in the way. --- .../controllers/commits_files_controller.go | 2 +- .../controllers/local_commits_controller.go | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index 14e1c1a50..d129b3f90 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -339,7 +339,7 @@ func (self *CommitFilesController) discard(selectedNodes []*filetree.CommitFileN HandleConfirm: func() error { commits := self.c.Model().Commits selectedLineIdx := self.c.Contexts().LocalCommits.GetSelectedLineIdx() - return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.RebasingStatus, func(gocui.Task) error { var filePaths []string selectedNodes = normalisedSelectedCommitFileNodes(selectedNodes) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 1234b80ec..2da502b79 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -342,7 +342,7 @@ func (self *LocalCommitsController) squashDown(selectedCommits []*models.Commit, HandleConfirm: func() error { commits := self.c.Model().Commits self.selectRebaseResultCommit(startIdx) - return self.c.WithWaitingStatus(self.c.Tr.SquashingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.SquashingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SquashCommitDown) return self.interactiveRebase(commits, todo.Squash, startIdx, endIdx) }) @@ -366,7 +366,7 @@ func (self *LocalCommitsController) fixup(selectedCommits []*models.Commit, star OnPress: func() error { commits := self.c.Model().Commits self.selectRebaseResultCommit(startIdx) - return self.c.WithWaitingStatus(self.c.Tr.FixingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.FixingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.FixupCommit) return self.interactiveRebase(commits, todo.Fixup, startIdx, endIdx) }) @@ -379,7 +379,7 @@ func (self *LocalCommitsController) fixup(selectedCommits []*models.Commit, star OnPress: func() error { commits := self.c.Model().Commits self.selectRebaseResultCommit(startIdx) - return self.c.WithWaitingStatus(self.c.Tr.FixingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.FixingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.FixupCommitKeepMessage) return self.interactiveRebaseWithFlag(commits, todo.Fixup, startIdx, endIdx, "-C") }) @@ -490,7 +490,7 @@ func (self *LocalCommitsController) handleReword(summary string, description str self.c.Tr.RewordingStatus, nil, nil) } - return self.c.WithWaitingStatus(self.c.Tr.RewordingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.RewordingStatus, func(gocui.Task) error { err := self.c.Git().Rebase.RewordCommit(commits, selectedIdx, summary, description) if err != nil { return err @@ -576,7 +576,7 @@ func (self *LocalCommitsController) drop(selectedCommits []*models.Commit, start if !isMerge { self.selectRebaseResultCommit(startIdx) } - return self.c.WithWaitingStatus(self.c.Tr.DroppingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.DroppingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.DropCommit) if isMerge { return self.dropMergeCommit(commits, startIdx) @@ -601,7 +601,7 @@ func (self *LocalCommitsController) edit(selectedCommits []*models.Commit, start commits := self.c.Model().Commits if !commits[endIdx].IsMerge() { - return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.RebasingStatus, func(gocui.Task) error { err := self.c.Git().Rebase.InteractiveRebase(commits, startIdx, endIdx, todo.Edit, "") return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( err, types.RefreshOptions{BatchUIUpdates: true}) @@ -623,7 +623,7 @@ func (self *LocalCommitsController) quickStartInteractiveRebase() error { func (self *LocalCommitsController) startInteractiveRebaseWithEdit( commitsToEdit []*models.Commit, ) error { - return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.RebasingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.EditCommit) err := self.c.Git().Rebase.EditRebase(commitsToEdit[len(commitsToEdit)-1].Hash()) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebaseWithRefreshOptions( @@ -823,7 +823,7 @@ func (self *LocalCommitsController) amendTo(commit *models.Commit) error { selectedIdx := self.context().GetView().SelectedLineIdx() handleCommit = func() error { return self.c.Helpers().WorkingTree.WithEnsureCommittableFiles(func() error { - return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AmendCommit) err := self.c.Git().Rebase.AmendTo(commits, selectedIdx) return self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err) @@ -885,7 +885,7 @@ func (self *LocalCommitsController) amendAttribute(_ []*models.Commit, start, en } func (self *LocalCommitsController) resetAuthor(commits []*models.Commit, start, end int) error { - return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.ResetCommitAuthor) if err := self.c.Git().Rebase.ResetCommitAuthor(commits, start, end); err != nil { return err @@ -901,7 +901,7 @@ func (self *LocalCommitsController) setAuthor(commits []*models.Commit, start, e Title: self.c.Tr.SetAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { - return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.SetCommitAuthor) if err := self.c.Git().Rebase.SetCommitAuthor(commits, start, end, value); err != nil { return err @@ -921,7 +921,7 @@ func (self *LocalCommitsController) addCoAuthor(commits []*models.Commit, start, Title: self.c.Tr.AddCoAuthorPromptTitle, FindSuggestionsFunc: self.c.Helpers().Suggestions.GetAuthorsSuggestionsFunc(), HandleConfirm: func(value string) error { - return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func(gocui.Task) error { + return self.c.WithWaitingStatusBlockingInput(self.c.Tr.AmendingStatus, func(gocui.Task) error { self.c.LogAction(self.c.Tr.Actions.AddCommitCoAuthor) if err := self.c.Git().Rebase.AddCommitCoAuthor(commits, start, end, value); err != nil { return err From a324f8aef181bd264a1c048ffd280619f6fe6e2d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 18:05:11 +0200 Subject: [PATCH 157/218] Drop the now-unused UI-thread CheckMergeOrRebase path With the last synchronous commit-surgery callers moved to workers, nothing runs CheckMergeOrRebase on the UI thread anymore, so CheckMergeOrRebaseWithRefreshOptionsFromUIThread has no callers. Remove it and fold the shared checkMergeOrRebaseImpl back into CheckMergeOrRebaseWithRefreshOptions, which is now always on a worker. The runAction closure loses its calledFromWorker parameter for the same reason. genericMergeCommandImpl keeps its calledFromWorker flag: the merge/rebase-continue subprocess path still runs on the UI thread when invoked straight from the menu, and on a worker for the recursive auto-skip. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 52 +++++++------------ 1 file changed, 20 insertions(+), 32 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index 7f1a31188..a8696a21c 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -89,11 +89,11 @@ func (self *MergeAndRebaseHelper) genericMergeCommand(command string) error { // non-subprocess path runs on a worker with a waiting status. // // showWaitingStatus is false only for the recursive auto-skip in -// checkMergeOrRebaseImpl: that call already runs on the caller's thread (the -// worker of the enclosing waiting status, or the UI thread for the synchronous -// callers), so it must not spin up a second one. calledFromWorker says which of -// those two the body runs on, so the post-action refresh picks Refresh vs -// RefreshFromWorker correctly. +// CheckMergeOrRebaseWithRefreshOptions, which already runs on a worker, so it +// must not spin up a second waiting status. calledFromWorker is used only by the +// subprocess path below: it's true for that recursive worker skip and false for +// genericMergeCommand's UI-thread invocation, so the post-action refresh picks +// RefreshFromWorker vs Refresh correctly. func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWaitingStatus bool, calledFromWorker bool) error { status := self.c.Git().Status.WorkingTreeState() @@ -139,21 +139,23 @@ func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWa return err } - runAction := func(calledFromWorker bool) error { + // runAction always ends up on a worker: either the waiting status below spins + // one up, or we're the recursive auto-skip reached from + // CheckMergeOrRebaseWithRefreshOptions, which already runs on one. + runAction := func() error { result := self.c.Git().Rebase.GenericMergeOrRebaseAction(commandType, command) - return self.checkMergeOrRebaseImpl(result, + return self.CheckMergeOrRebaseWithRefreshOptions(result, types.RefreshOptions{ CommitSelection: commitSelectionAfterMerge(result == nil && selectHeadCommitOnSuccess), - }, calledFromWorker) + }) } if showWaitingStatus { return self.c.WithWaitingStatus(status.Title(self.c.Tr), func(gocui.Task) error { - // The waiting status ran runAction on a worker. - return runAction(true) + return runAction() }) } - return runAction(calledFromWorker) + return runAction() } // commitSelectionAfterMerge maps whether a merge/rebase/pull created a new @@ -209,33 +211,19 @@ func (self *MergeAndRebaseHelper) RecordWhetherMergeOrRebaseStartedInLazygit() { } // CheckMergeOrRebaseWithRefreshOptions handles the result of a merge/rebase -// step and refreshes. It's for callers running on a worker (the -// WithWaitingStatus / WithInlineStatus handlers), which is the large majority; -// UI-thread callers use CheckMergeOrRebaseWithRefreshOptionsFromUIThread. +// step and refreshes. It always runs on a worker (the WithWaitingStatus / +// WithWaitingStatusBlockingInput / WithInlineStatus handlers). func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result error, refreshOptions types.RefreshOptions) error { - return self.checkMergeOrRebaseImpl(result, refreshOptions, true) -} - -// CheckMergeOrRebaseWithRefreshOptionsFromUIThread is like -// CheckMergeOrRebaseWithRefreshOptions, but for the callers that run the -// merge/rebase synchronously on the UI thread (the WithWaitingStatusSync -// move/revert/squash-fixups/cherry-pick-paste/patch-discard handlers, kept sync -// so rapid key presses batch) rather than on a worker. -func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptionsFromUIThread(result error, refreshOptions types.RefreshOptions) error { - return self.checkMergeOrRebaseImpl(result, refreshOptions, false) -} - -func (self *MergeAndRebaseHelper) checkMergeOrRebaseImpl(result error, refreshOptions types.RefreshOptions, calledFromWorker bool) error { - self.refreshAfterMergeOrRebase(refreshOptions, calledFromWorker) + self.refreshAfterMergeOrRebase(refreshOptions, true) self.RecordWhetherMergeOrRebaseStartedInLazygit() if result == nil { return nil } else if strings.Contains(result.Error(), "No changes - did you forget to use") { - return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, calledFromWorker) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, true) } else if strings.Contains(result.Error(), "The previous cherry-pick is now empty") { - return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, calledFromWorker) + return self.genericMergeCommandImpl(REBASE_OPTION_SKIP, false, true) } else if strings.Contains(result.Error(), "No rebase in progress?") { // assume in this case that we're already done return nil @@ -245,8 +233,8 @@ func (self *MergeAndRebaseHelper) checkMergeOrRebaseImpl(result error, refreshOp // refreshAfterMergeOrRebase issues the post-action refresh on the entry point // that matches the thread the merge/rebase ran on: RefreshFromWorker for the -// worker callers, Refresh for the ones that stayed synchronously on the UI -// thread. +// worker callers, Refresh for the merge/rebase-continue subprocess path that +// stays on the UI thread. func (self *MergeAndRebaseHelper) refreshAfterMergeOrRebase(refreshOptions types.RefreshOptions, calledFromWorker bool) { if calledFromWorker { self.c.RefreshFromWorker(refreshOptions) From a247dfd76d63c235f4e94dfc5ee31e57d0e4a07e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 19:01:46 +0200 Subject: [PATCH 158/218] Retire WithWaitingStatusSync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nothing calls it anymore now that the commit-surgery operations run on a worker with input blocked. Remove the helper, its bespoke synchronous spinner loop (renderAppStatusSync/setAppStatusContent), the popup-handler plumbing, and the interface method. That loop was also the only thing suppressing the yellow "Rebasing" mode indicator (and its reset button) while lazygit drives a rebase itself. Move that suppression to WithWaitingStatusBlockingInput so it applies to every input-blocking commit-surgery op — including the ones that already ran on a worker (edit, drop, and so on) and previously let the indicator flash on mid-operation. It's cleared after the refresh, so an operation that legitimately leaves a rebase in progress still shows the mode. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/app_status_helper.go | 81 +++---------------- pkg/gui/gui.go | 3 - pkg/gui/popup/popup_handler.go | 7 -- pkg/gui/types/common.go | 1 - 4 files changed, 10 insertions(+), 82 deletions(-) diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index a366909f6..69daa7d7a 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -98,31 +98,24 @@ func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui. // between. func (self *AppStatusHelper) WithWaitingStatusBlockingInput(message string, f func(gocui.Task) error) { self.c.GocuiGui().BeginBlockingEvents() + // Hide the rebasing-mode indicator (and its reset button) while we drive the + // rebase ourselves; it reflects the transient on-disk state and would + // otherwise flash on for the duration of the operation. + self.modeHelper.SetSuppressRebasingMode(true) self.c.OnWorker(func(task gocui.Task) error { - // End the block once the operation and its refresh have applied their UI - // updates: OnUIThread queues this after the refresh's model bounces and - // Then (which RefreshFromWorker has already enqueued by the time f - // returns), so the replayed keys act on the refreshed state. + // End the block and restore the mode indicator once the operation and its + // refresh have applied their UI updates: OnUIThread queues this after the + // refresh's model bounces and Then (which RefreshFromWorker has already + // enqueued by the time f returns), so the replayed keys act on the + // refreshed state and any resulting rebase state shows correctly. defer self.c.OnUIThread(func() error { + self.modeHelper.SetSuppressRebasingMode(false) return self.c.GocuiGui().EndBlockingEvents() }) return self.WithWaitingStatusImpl(message, f, task, false) }) } -func (self *AppStatusHelper) WithWaitingStatusSync(message string, f func() error) error { - self.c.PauseBackgroundRefreshes(true) - defer self.c.PauseBackgroundRefreshes(false) - - return self.statusMgr().WithWaitingStatus(message, func() {}, func(*status.WaitingStatusHandle) error { - stop := make(chan struct{}) - defer func() { close(stop) }() - self.renderAppStatusSync(stop) - - return f() - }) -} - func (self *AppStatusHelper) HasStatus() bool { return self.statusMgr().HasStatus() } @@ -174,57 +167,3 @@ func (self *AppStatusHelper) renderAppStatus(background bool) { return nil }) } - -func (self *AppStatusHelper) renderAppStatusSync(stop chan struct{}) { - go func() { - ticker := time.NewTicker(time.Millisecond * time.Duration(self.c.UserConfig().Gui.Spinner.Rate)) - defer ticker.Stop() - - // Write the status into the view before the first layout below, so that - // layout (which sizes the bottom line based on the actual content of the - // AppStatus view) leaves room for it and it shows right away. The ticker - // only updates the spinner frame using ForceFlushViewsContentOnly, so this - // doesn't re-layout. - self.setAppStatusContent() - - // Forcing a re-layout and redraw after we added the waiting status; - // this is needed in case the gui.showBottomLine config is set to false, - // to make sure the bottom line appears. It's also useful for redrawing - // once after each of several consecutive keypresses, e.g. pressing - // ctrl-j to move a commit down several steps. - _ = self.c.GocuiGui().ForceLayoutAndRedraw() - - self.modeHelper.SetSuppressRebasingMode(true) - defer func() { self.modeHelper.SetSuppressRebasingMode(false) }() - - outer: - for { - select { - case <-ticker.C: - self.setAppStatusContent() - // Redraw all views of the bottom line: - bottomLineViews := []*gocui.View{ - self.c.Views().AppStatus, self.c.Views().Options, self.c.Views().Information, - self.c.Views().StatusSpacer1, self.c.Views().StatusSpacer2, - } - _ = self.c.GocuiGui().ForceFlushViewsContentOnly(bottomLineViews) - case <-stop: - // Clear the status from the view and re-layout, otherwise the - // stale content would keep layout reserving room for it forever. - // The UI thread is free again at this point, so we go through - // OnUIThread like the async renderAppStatus does. - self.c.OnUIThread(func() error { - self.c.SetViewContent(self.c.Views().AppStatus, "") - return nil - }) - break outer - } - } - }() -} - -func (self *AppStatusHelper) setAppStatusContent() { - appStatus, color := self.statusMgr().GetStatusString(self.c.UserConfig()) - self.c.Views().AppStatus.FgColor = color - self.c.SetViewContent(self.c.Views().AppStatus, appStatus) -} diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index a6baaf373..ce70cb2d5 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -823,9 +823,6 @@ func NewGui( func(message string, f func(gocui.Task) error) { gui.helpers.AppStatus.WithWaitingStatusBlockingInput(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() }, diff --git a/pkg/gui/popup/popup_handler.go b/pkg/gui/popup/popup_handler.go index 23084f9ce..7c15c56ea 100644 --- a/pkg/gui/popup/popup_handler.go +++ b/pkg/gui/popup/popup_handler.go @@ -20,7 +20,6 @@ type PopupHandler struct { createMenuFn func(types.CreateMenuOptions) error withWaitingStatusFn func(message string, f func(gocui.Task) error) withWaitingStatusBlockingInputFn 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 @@ -37,7 +36,6 @@ func NewPopupHandler( createMenuFn func(types.CreateMenuOptions) error, withWaitingStatusFn func(message string, f func(gocui.Task) error), withWaitingStatusBlockingInputFn 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, @@ -51,7 +49,6 @@ func NewPopupHandler( createMenuFn: createMenuFn, withWaitingStatusFn: withWaitingStatusFn, withWaitingStatusBlockingInputFn: withWaitingStatusBlockingInputFn, - withWaitingStatusSyncFn: withWaitingStatusSyncFn, toastFn: toastFn, getPromptInputFn: getPromptInputFn, inDemo: inDemo, @@ -84,10 +81,6 @@ func (self *PopupHandler) WithWaitingStatusBlockingInput(message string, f func( 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, ¬HandledError) { diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 964143c5a..5a256b434 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -162,7 +162,6 @@ type IPopupHandler interface { Prompt(opts PromptOpts) WithWaitingStatus(message string, f func(gocui.Task) error) error WithWaitingStatusBlockingInput(message string, f func(gocui.Task) error) error - WithWaitingStatusSync(message string, f func() error) error Menu(opts CreateMenuOptions) error Toast(message string) ErrorToast(message string) From 9bb9fc8933315e72f096fd4141f602e89feb3a22 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 18:11:24 +0200 Subject: [PATCH 159/218] Run all refresh scopes on plain goroutines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two branches of the `refresh` closure ran the scope function identically; they differed only in that the UI-thread path registered each scope as its own gocui task while the worker/demo path used a bare goroutine (and only the latter logged per-scope timing). Those per-scope tasks were redundant. performRefresh always runs under a task that stays busy until the wg.Wait in waitAndFinalize joins every scope goroutine: the calling worker's own task when called from a worker, or the waitAndFinalize worker task when called from the UI thread — and that task is created (busy) before the triggering event's task goes Done, so there is no window in which nothing is busy. Repo-switch safety and the integration-test idle signal are therefore already covered without giving each scope its own task. Collapsing to the single goroutine path also means the timing log now fires for UI-thread refreshes too, not just worker ones. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 34 +++++++------------ 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index fdb526549..08a2e615c 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -234,27 +234,19 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr wg := sync.WaitGroup{} refresh := func(name string, f func()) { wg.Add(1) - - // A refresh issued from the UI thread must not block it, so its scopes - // run as their own worker tasks and the caller returns immediately (the - // finishing step below is dispatched to a worker too). A refresh issued - // from a worker blocks that worker instead, running its scopes as plain - // goroutines that it joins. In a demo we always take the blocking path - // so everything updates in a single, deterministic frame. - if !self.c.InDemo() && !calledFromWorker { - self.onWorker(env.background, func(t gocui.Task) error { - defer wg.Done() - f() - return nil - }) - } else { - go utils.Safe(func() { - t := time.Now() - defer wg.Done() - f() - self.c.Log.Infof("refreshed %s in %s", name, time.Since(t)) - }) - } + // Each scope runs on its own goroutine, joined by the wg.Wait in + // waitAndFinalize. They don't need to be registered as gocui tasks for + // repo-switch safety: performRefresh always runs under a task that stays + // busy until that wg.Wait returns — the calling worker's task when + // called from a worker, or the waitAndFinalize worker task when called + // from the UI thread (created before the triggering event's task ends, + // so there's no gap) — and that task already covers the whole refresh. + go utils.Safe(func() { + t := time.Now() + defer wg.Done() + f() + self.c.Log.Infof("refreshed %s in %s", name, time.Since(t)) + }) } branchesAndRemotesWg := sync.WaitGroup{} From 2f60280eb694a79921dd2eb980aa4ab519789cd1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 18:21:45 +0200 Subject: [PATCH 160/218] Log Refresh timing information for both sync/async For async refreshes (from UI thread) it would only log the time it took to schedule the refreshXxx calls, which is not useful. --- pkg/gui/controllers/helpers/refresh_helper.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 08a2e615c..5fa5ffbec 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -142,10 +142,7 @@ func (self *refreshBounceBatch) close() []func() { } func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { - t := time.Now() - defer func() { - self.c.Log.Infof("Refresh took %s", time.Since(t)) - }() + startTime := time.Now() // A refresh from a worker blocks that worker until it's done; one from the // UI thread returns immediately and finishes in the background. @@ -432,6 +429,8 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // still pre-refresh. self.onUIThread(env.background, options.Then) } + + self.c.Log.Infof("Refresh took %s", time.Since(startTime)) } // waitAndFinalize blocks until every scope is done. Run it inline when we're From 4ff161b48d94b077920ca9a8b8d0f971072a021b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 18:28:59 +0200 Subject: [PATCH 161/218] Don't wait for pull requests to be fetched in refresh Fetching pull requests can take a long time, and we don't want to delay the refresh by it; in particular, for a WithWaitingStatusBlockingInput we want the UI thread to be unblocked again while pull requests are still fetching in the background. This is similar to how we fetch the behind values for branches in BranchLoader; this will update the UI without much flicker when done, and doesn't have to block anything. --- pkg/gui/controllers/helpers/refresh_helper.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 5fa5ffbec..768e7a618 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -365,13 +365,17 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.PULL_REQUESTS) { - refresh("pull requests", func() { + self.onWorker(env.background, func(gocui.Task) error { branchesAndRemotesWg.Wait() + + t := time.Now() // Use the branches and remotes the loads above stashed, not // Model().Branches/Remotes: those writes are bounced onto the // UI thread and may not have landed on this worker yet. The // wait above orders us after both loads have stashed theirs. self.refreshGithubPullRequests(loadedBranches, loadedRemotes, env) + self.c.Log.Infof("refreshed pull requests in %s", time.Since(t)) + return nil }) } From 303372d91789b0dd0614033b58122fa450ffa2bb Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 07:53:14 +0200 Subject: [PATCH 162/218] Perform string-task view updates on the UI thread The closures that render static content to a main view (newStringTask and friends) ran on the ViewBufferManager's task goroutine, calling SetViewContent/SetOrigin/ResetViewOrigin directly on the view. Those touch view state (the line buffer, hover cells, the origin) that the UI thread concurrently reads and mutates while laying out and drawing, so they raced it -- e.g. a string task's SetContent clearing the view's lines while the UI thread's CopyContent read them, or its SetOrigin racing the layout's OriginY read. Bounce the whole closure onto the UI thread instead, so the view is only touched there. The bounce blocks (OnUIThreadAndWaitBackground) so the task still completes only once the content has actually been rendered, which the integration-test idle detection relies on; the background variant keeps it from counting towards the app being busy, matching the existing treatment of view rendering as work that must not block a repo switch. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/tasks_adapter.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index acad4fb75..808a4341d 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -59,8 +59,10 @@ 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 + return gui.g.OnUIThreadAndWaitBackground(func() error { + gui.c.SetViewContent(view, str) + return nil + }) } if err := manager.NewTask(f, manager.GetTaskKey()); err != nil { @@ -74,9 +76,11 @@ func (gui *Gui) newStringTaskWithScroll(view *gocui.View, str string, originX in manager := gui.getManager(view) f := func(tasks.TaskOpts) error { - gui.c.SetViewContent(view, str) - view.SetOrigin(originX, originY) - return nil + return gui.g.OnUIThreadAndWaitBackground(func() error { + gui.c.SetViewContent(view, str) + view.SetOrigin(originX, originY) + return nil + }) } if err := manager.NewTask(f, manager.GetTaskKey()); err != nil { @@ -90,9 +94,11 @@ func (gui *Gui) newStringTaskWithKey(view *gocui.View, str string, key string) e manager := gui.getManager(view) f := func(tasks.TaskOpts) error { - gui.c.ResetViewOrigin(view) - gui.c.SetViewContent(view, str) - return nil + return gui.g.OnUIThreadAndWaitBackground(func() error { + gui.c.ResetViewOrigin(view) + gui.c.SetViewContent(view, str) + return nil + }) } if err := manager.NewTask(f, key); err != nil { From 99c1bcbf23ee9f08e8a694d53af08bc1b59394b7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 08:04:08 +0200 Subject: [PATCH 163/218] Reset the view origin for a new task on the UI thread When a task renders different content to a view (a new task key), the view's scroll origin is reset to the top via onNewKey. That ran on the task's own goroutine, racing the UI thread, which reads the origin (OriginY) while laying out and drawing the view -- the single largest source of view-render data races. Give ViewBufferManager a bounce primitive (onUIThread) that runs a function on the UI thread and waits for it, and reset the origin through it. This is the first use of the primitive; subsequent commits route the rest of the task's view mutations through it too, so that the view is only ever touched on the UI thread. It runs as background work (OnUIThreadAndWaitBackground) so rendering doesn't count towards the app being busy, matching how the render's gocui task is already created. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/tasks_adapter.go | 3 +++ pkg/tasks/tasks.go | 30 ++++++++++++++++++++++++------ pkg/tasks/tasks_test.go | 6 ++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 808a4341d..9f9488048 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -156,6 +156,9 @@ func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager { // otherwise make the switch that handler triggers refuse itself. return gui.c.GocuiGui().NewBackgroundTask() }, + // Rendering is background work too (see above), so the view mutations + // it bounces onto the UI thread mustn't count towards being busy. + gui.g.OnUIThreadAndWaitBackground, ) gui.viewBufferManagerMap[view.Name()] = manager } diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 9da12d40b..c8f5b8244 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -74,6 +74,12 @@ type ViewBufferManager struct { // whereas the tasks in this file are about rendering content to a view. newGocuiTask func() gocui.Task + // Runs f on the UI thread and blocks until it has completed. All mutations + // of the view happen through this, so that the view is only ever touched on + // the UI thread (where it is also laid out and drawn), never on the task's + // own goroutine. + onUIThread func(f func() error) error + // if the user flicks through a heap of items, with each one // spawning a process to render something to the main view, // it can slow things down quite a bit. In these situations we @@ -110,6 +116,7 @@ func NewViewBufferManager( onEndOfInput func(), onNewKey func(), newGocuiTask func() gocui.Task, + onUIThread func(f func() error) error, ) *ViewBufferManager { return &ViewBufferManager{ Log: log, @@ -120,6 +127,7 @@ func NewViewBufferManager( readLines: nil, onNewKey: onNewKey, newGocuiTask: newGocuiTask, + onUIThread: onUIThread, } } @@ -460,21 +468,31 @@ func (self *ViewBufferManager) NewTask(f func(TaskOpts) error, key string) error self.taskIDMutex.Lock() // Bail out before touching shared view state if a newer task has - // already been queued: if we ran onNewKey here we'd reset the view - // for a task that's about to exit, potentially wiping output the - // winning task has already written. + // already been queued: if we reset the view here we'd do it for a task + // that's about to exit, potentially wiping output the winning task has + // already written. if taskID < self.newTaskID { self.taskIDMutex.Unlock() return } - if self.GetTaskKey() != key && self.onNewKey != nil { - self.onNewKey() - } + resetOrigin := self.GetTaskKey() != key && self.onNewKey != nil self.taskKey = key self.taskIDMutex.Unlock() + if resetOrigin { + // onNewKey resets the view's scroll origin, which is view state the + // UI thread reads while laying out and drawing, so do it there. This + // must happen after releasing taskIDMutex: it blocks until the UI + // thread runs it, and a NewTask call on the UI thread takes + // taskIDMutex, so holding it here would deadlock. + _ = self.onUIThread(func() error { + self.onNewKey() + return nil + }) + } + self.waitingMutex.Lock() // Re-check staleness after acquiring waitingMutex: a newer task diff --git a/pkg/tasks/tasks_test.go b/pkg/tasks/tasks_test.go index c025e8e16..2cea139e8 100644 --- a/pkg/tasks/tasks_test.go +++ b/pkg/tasks/tasks_test.go @@ -39,6 +39,8 @@ func TestNewCmdTaskInstantStop(t *testing.T) { onEndOfInput, onNewKey, newTask, + // no UI thread in the test; run the view mutations inline + func(f func() error) error { return f() }, ) stop := make(chan struct{}) @@ -104,6 +106,8 @@ func TestNewCmdTask(t *testing.T) { onEndOfInput, onNewKey, newTask, + // no UI thread in the test; run the view mutations inline + func(f func() error) error { return f() }, ) stop := make(chan struct{}) @@ -237,6 +241,8 @@ func TestNewCmdTaskRefresh(t *testing.T) { func() {}, func() {}, newTask, + // no UI thread in the test; run the view mutations inline + func(f func() error) error { return f() }, ) stop := make(chan struct{}) From 40868a93895d8920cb89dc084644e9344d403d4d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 08:08:47 +0200 Subject: [PATCH 164/218] Hold the ViewBufferManager readLines channel in an atomic The readLines channel, by which a running task is told to read more lines as the user scrolls, is swapped out as tasks start and finish. It was a plain field written from the task goroutines (when a task starts, ends, or is replaced) and read from the UI thread in ReadLines/ ReadToEnd, so those accesses raced -- a longstanding data race (and a plausible cause of the occasional "main view stops updating" hang, since a torn read there could drop a scroll's read request). Make the field an atomic.Pointer and give the running task a captured local copy of the channel for its own send/receive, so the field itself is only ever loaded/stored atomically. No lock is involved, so there's nothing to untangle later. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/tasks/tasks.go | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index c8f5b8244..50a94a15c 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "sync" + "sync/atomic" "time" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" @@ -59,9 +60,13 @@ type ViewBufferManager struct { taskIDMutex deadlock.Mutex Log *logrus.Entry newTaskID int - readLines chan LinesToRead - taskKey string - onNewKey func() + // The channel by which the currently-running task is told to read more + // lines (e.g. as the user scrolls). Held in an atomic because it's swapped + // out as tasks come and go while ReadLines/ReadToEnd read it from the UI + // thread; nil when no task is running. + readLines atomic.Pointer[chan LinesToRead] + taskKey string + onNewKey func() // beforeStart is the function that is called before starting a new task beforeStart func() @@ -124,7 +129,6 @@ func NewViewBufferManager( beforeStart: beforeStart, refreshView: refreshView, onEndOfInput: onEndOfInput, - readLines: nil, onNewKey: onNewKey, newGocuiTask: newGocuiTask, onUIThread: onUIThread, @@ -136,17 +140,19 @@ func NewViewBufferManager( // (e.g. as the user scrolls down, back up, and down again) don't re-read lines // that have already been read: the task only ever reads the shortfall. func (self *ViewBufferManager) ReadLines(totalLines int) { - if self.readLines != nil { + if ch := self.readLines.Load(); ch != nil { + readLines := *ch go utils.Safe(func() { - self.readLines <- LinesToRead{Total: totalLines, InitialRefreshAfter: -1} + readLines <- LinesToRead{Total: totalLines, InitialRefreshAfter: -1} }) } } func (self *ViewBufferManager) ReadToEnd(then func()) { - if self.readLines != nil { + if ch := self.readLines.Load(); ch != nil { + readLines := *ch go utils.Safe(func() { - self.readLines <- LinesToRead{Total: -1, InitialRefreshAfter: -1, Then: then} + readLines <- LinesToRead{Total: -1, InitialRefreshAfter: -1, Then: then} }) } else if then != nil { then() @@ -220,7 +226,8 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix loadingMutex := deadlock.Mutex{} - self.readLines = make(chan LinesToRead, 1024) + readLines := make(chan LinesToRead, 1024) + self.readLines.Store(&readLines) scanner := bufio.NewScanner(r) scanner.Split(utils.ScanLinesAndTruncateWhenLongerThanBuffer(bufio.MaxScanTokenSize)) @@ -312,7 +319,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix select { case <-opts.Stop: break outer - case linesToRead := <-self.readLines: + case linesToRead := <-readLines: callThen := func() { if linesToRead.Then != nil { linesToRead.Then() @@ -367,7 +374,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix } } - self.readLines = nil + self.readLines.Store(nil) refreshViewIfStale() @@ -391,7 +398,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix close(lineWrittenChan) }) - self.readLines <- linesToRead + readLines <- linesToRead <-done @@ -509,7 +516,7 @@ func (self *ViewBufferManager) NewTask(f func(TaskOpts) error, key string) error self.stopCurrentTask() } - self.readLines = nil + self.readLines.Store(nil) stop := make(chan struct{}) notifyStopped := make(chan struct{}) From e75688c101ce3e6b2a8c668a182f0e8c6c7aa1e8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 08:39:00 +0200 Subject: [PATCH 165/218] Make the ViewBufferManager throttle flag atomic The throttle flag is set from the goroutine that watches a task for being stopped, and read when the next task starts up -- two different goroutines, so the plain bool field was a data race. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/tasks/tasks.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 50a94a15c..d58be3a92 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -88,8 +88,9 @@ type ViewBufferManager struct { // if the user flicks through a heap of items, with each one // spawning a process to render something to the main view, // it can slow things down quite a bit. In these situations we - // want to throttle the spawning of processes. - throttle bool + // want to throttle the spawning of processes. Atomic because it's set + // from one task's stop goroutine and read when the next task starts. + throttle atomic.Bool } type LinesToRead struct { @@ -177,7 +178,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix onFirstPageShown() } - if self.throttle { + if self.throttle.Load() { self.Log.Info("throttling task") time.Sleep(THROTTLE_TIME) } @@ -200,13 +201,13 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix case <-done: // The command finished and did not have to be preemptively stopped before the next command. // No need to throttle. - self.throttle = false + self.throttle.Store(false) case <-opts.Stop: // we use the time it took to start the program as a way of checking if things // are running slow at the moment. This is admittedly a crude estimate, but // the point is that we only want to throttle when things are running slow // and the user is flicking through a bunch of items. - self.throttle = time.Since(startTime) < THROTTLE_TIME && timeToStart > COMMAND_START_THRESHOLD + self.throttle.Store(time.Since(startTime) < THROTTLE_TIME && timeToStart > COMMAND_START_THRESHOLD) // Kill the still-running command. The only reason to do this is to save CPU usage // when flicking through several very long diffs when diff.algorithm = histogram is From f6eaed8cd4f2298fad4126ff56df77b71daed730 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 13:00:49 +0200 Subject: [PATCH 166/218] Snapshot the view width for command-task rendering on the UI thread A command task streams its output into a view from its own goroutine. To track soft-wraps (so cursor-positioning escapes from a pager land on the right line) the write path read the view's live InnerWidth, and the pty setup read its InnerSize -- both off the UI thread, racing the UI thread mutating the view's dimensions during layout. Capture the width on the UI thread instead and hand it to the task: the escape interpreter keeps a screenColMax it reads from, seeded in NewView and refreshed per render via View.SetContentWidth (called from newCmdTask/newPtyTask before the task's goroutine starts), and the pty size is computed in the after-layout callback rather than in the task's start func. The view's dimensions stay UI-thread-only; the task uses the snapshot rather than reading them live. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/escape.go | 14 +++++++++++--- pkg/gocui/view.go | 13 ++++++++++++- pkg/gui/pty.go | 11 ++++++++++- pkg/gui/tasks_adapter.go | 9 +++++++++ 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/pkg/gocui/escape.go b/pkg/gocui/escape.go index ad862a596..7f3de9e6e 100644 --- a/pkg/gocui/escape.go +++ b/pkg/gocui/escape.go @@ -34,6 +34,14 @@ type escapeInterpreter struct { // modelled — we don't track the col argument of CUPs, and most // pager-style emitters use col 1 anyway. screenRow, screenCol int + + // The screen width that soft-wraps are counted against (see + // notifyCellsWritten). It's a snapshot of the view's InnerWidth taken on + // the UI thread (in NewView, and refreshed per render via + // View.SetContentWidth), rather than read live from the view's dimensions: + // a view's output is written from a task goroutine, and reading the live + // dimensions there would race the UI thread updating them during layout. + screenColMax int } type ( @@ -175,8 +183,8 @@ func (ei *escapeInterpreter) notifyColumnReset() { // columns; if that crosses the right edge of a `screenColMax`-wide pty // screen, the corresponding number of soft-wraps are added to screenRow // so subsequent CUPs land on the right line. -func (ei *escapeInterpreter) notifyCellsWritten(width, screenColMax int) { - if screenColMax <= 0 { +func (ei *escapeInterpreter) notifyCellsWritten(width int) { + if ei.screenColMax <= 0 { return } // One column at a time: matches ConPTY's "pending wrap" semantics @@ -185,7 +193,7 @@ func (ei *escapeInterpreter) notifyCellsWritten(width, screenColMax int) { // columns rather than doing the math in one shot so wide cells on a // row boundary still wrap cleanly. for range width { - if ei.screenCol > screenColMax { + if ei.screenCol > ei.screenColMax { ei.screenRow++ ei.screenCol = 1 } diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index e4c5a5f98..ae8aea880 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -536,9 +536,20 @@ func NewView(name string, x0, y0, x1, y1 int, mode OutputMode) *View { v.SelFgColor, v.SelBgColor = ColorDefault, ColorDefault v.InactiveViewSelBgColor = ColorDefault v.TitleColor, v.FrameColor = ColorDefault, ColorDefault + v.ei.screenColMax = v.InnerWidth() return v } +// SetContentWidth tells the view the screen width that content written to it +// should count soft-wraps against (see escapeInterpreter.notifyCellsWritten). +// Callers pass the view's InnerWidth; it's a separate call, made on the UI +// thread when a render starts, so that the task goroutine that streams the +// content can consult this snapshot instead of reading the view's live +// dimensions (which the UI thread mutates during layout). +func (v *View) SetContentWidth(width int) { + v.ei.screenColMax = width +} + // Dimensions returns the dimensions of the View func (v *View) Dimensions() (int, int, int, int) { return v.x0, v.y0, v.x1, v.y1 @@ -907,7 +918,7 @@ func (v *View) write(p []byte) { for _, c := range cells { totalWidth += c.width } - v.ei.notifyCellsWritten(totalWidth, v.InnerWidth()) + v.ei.notifyCellsWritten(totalWidth) } } } diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go index 1a774fc3d..d4f739c6d 100644 --- a/pkg/gui/pty.go +++ b/pkg/gui/pty.go @@ -93,9 +93,18 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error manager := gui.getManager(view) + // Size the pty from the view's dimensions here, on the UI thread; the + // start func below runs on the task's goroutine, which must not read the + // view's live dimensions while the UI thread is laying it out. + cols, rows := gui.desiredPtySize(view) + var p oscommands.Pty start := func() (tasks.Cmd, io.Reader) { - cols, rows := gui.desiredPtySize(view) + // The pty (and pager) wrap to this width; apply it here, on the + // task's goroutine once the previous task has stopped, so it doesn't + // race that task's writes (see View.SetContentWidth). + view.SetContentWidth(width) + sp, err := oscommands.StartPty(cmd, cols, rows) if err != nil { gui.c.Log.Error(err) diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 9f9488048..27aacf58b 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -18,8 +18,17 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error manager := gui.getManager(view) + // Snapshot the view width here, on the UI thread, so the task goroutine + // doesn't read the view's live dimensions while it streams output. It's + // applied inside start() below rather than now, because start() runs once + // the previous task has stopped -- applying it here would race that task's + // still-running writes (see View.SetContentWidth). + contentWidth := view.InnerWidth() + var r io.ReadCloser start := func() (tasks.Cmd, io.Reader) { + view.SetContentWidth(contentWidth) + var err error r, err = cmd.StdoutPipe() if err != nil { From 65cb439076b665d458609f7f3a769786200029e8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 13:01:01 +0200 Subject: [PATCH 167/218] Take the write mutex when clearing view lines and reading the buffer A view's line buffer, its viewLines/tainted flags, and its hover state are all written from the command-task goroutine (under writeMutex) as it renders. But three accessors reached that same state from the UI thread without the lock: SetView and the GUI-resize path cleared a view's lines directly, viewsToRedrawContentOnly read the tainted flag, and Buffer read the line buffer. Each raced a rendering task. Guard them with writeMutex, matching the view's other buffer accessors. These are reads/clears of state writeMutex already protects, not new callers of it -- the view's geometry stays outside the mutex. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/gui.go | 6 +++--- pkg/gocui/view.go | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 700c2b54c..936e1a310 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -385,7 +385,7 @@ func (g *Gui) SetView(name string, x0, y0, x1, y1 int, overlaps byte) (*View, er v.y1 = y1 if sizeChanged { - v.clearViewLines() + v.ClearViewLines() if v.Editable { cursorX, cursorY := v.TextArea.GetCursorXY() @@ -1461,7 +1461,7 @@ func (g *Gui) flush() error { // if GUI's size has changed, we need to redraw all views if maxX != g.maxX || maxY != g.maxY { for _, v := range g.views { - v.clearViewLines() + v.ClearViewLines() } } g.maxX, g.maxY = maxX, maxY @@ -1500,7 +1500,7 @@ func viewsToRedrawContentOnly(views []*View) []*View { redrawIndexes := set.New[int]() for i, v := range views { - if !v.tainted && !redrawIndexes.Includes(i) { + if !v.IsTainted() && !redrawIndexes.Includes(i) { continue } diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index ae8aea880..39f2d78a9 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -214,6 +214,16 @@ func (v *View) clearViewLines() { v.clearHover() } +// ClearViewLines is clearViewLines guarded by writeMutex. It's for callers on +// the UI thread (the layout pass) that touch a view whose content a task +// goroutine may be writing concurrently: viewLines/tainted/hover are all +// buffer state that writeMutex protects. +func (v *View) ClearViewLines() { + v.writeMutex.Lock() + defer v.writeMutex.Unlock() + v.clearViewLines() +} + type searcher struct { searchString string searchPositions []SearchPosition @@ -1287,6 +1297,8 @@ func (v *View) updateSearchPositions() { // IsTainted tells us if the view is tainted func (v *View) IsTainted() bool { + v.writeMutex.Lock() + defer v.writeMutex.Unlock() return v.tainted } @@ -1535,6 +1547,9 @@ func (v *View) BufferLines() []string { // Buffer returns a string with the contents of the view's internal // buffer. func (v *View) Buffer() string { + v.writeMutex.Lock() + defer v.writeMutex.Unlock() + return linesToString(v.lines) } From eda215133072bfd135dae7c9001711358221e4b1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 13:01:09 +0200 Subject: [PATCH 168/218] Handle a command task's end-of-input on the UI thread When a command task reaches EOF it runs onEndOfInput, which reads the view's line height (and thus its dimensions) to decide whether to scroll, sets the view's origin, and flushes stale cells. Reading the dimensions and setting the origin are UI-thread-only, but this ran on the task's own goroutine, racing the UI thread. Bounce onEndOfInput onto the UI thread, as we already do for the new-task origin reset. It's once per render, so it doesn't add the per-line UI-thread churn that streaming the content would. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/tasks/tasks.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index d58be3a92..3a964c838 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -353,8 +353,14 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix if !ok { // if we're here then there's nothing left to scan from the source - // so we're at the EOF and can flush the stale content - self.onEndOfInput() + // so we're at the EOF and can flush the stale content. + // onEndOfInput reads the view's dimensions (to decide + // whether to scroll) and sets the origin, both of which + // are UI-thread-only, so run it there. + _ = self.onUIThread(func() error { + self.onEndOfInput() + return nil + }) callThen() break outer } From 9754a77b64439149a455ba91679ffe88efbebb3b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 15:08:07 +0200 Subject: [PATCH 169/218] Create popups and menus on the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Raising a popup or menu pushes a context and mutates the popup views, so it must happen on the UI thread. But it can be triggered from a worker goroutine — for example a WithWaitingStatus handler that hits a merge conflict and calls PromptForConflictHandling, or a worker that shows a confirmation — where it raced the UI thread's layout and draw code. Bounce the creation onto the UI thread at the one point where the popup and menu producers are injected into the popup handler, so every caller stays oblivious to the threading. For a caller that is already on the UI thread this adds no delay: the main loop drains the enqueued closure in the same event-processing cycle, before it draws. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/gui.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index ce70cb2d5..993798e42 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -812,13 +812,25 @@ func NewGui( gui.PopupHandler = popup.NewPopupHandler( cmn, + // Raising a popup or menu pushes a context and mutates the popup views, + // and it can be triggered from a worker goroutine (e.g. a + // WithWaitingStatus handler that hits a merge conflict and asks the user + // how to proceed). Bounce the creation onto the UI thread so it can't + // race the layout/draw code. Doing it here, at the one point where these + // producers are injected, keeps every caller oblivious to the threading. func(ctx goContext.Context, opts types.CreatePopupPanelOpts) { - gui.helpers.Confirmation.CreatePopupPanel(ctx, opts) + gui.onUIThread(func() error { + gui.helpers.Confirmation.CreatePopupPanel(ctx, opts) + return nil + }) }, func() error { gui.c.Refresh(types.RefreshOptions{}); return nil }, func() { gui.State.ContextMgr.Pop() }, func() types.Context { return gui.State.ContextMgr.Current() }, - gui.createMenu, + func(opts types.CreateMenuOptions) error { + gui.onUIThread(func() error { return gui.createMenu(opts) }) + return nil + }, func(message string, f func(gocui.Task) error) { gui.helpers.AppStatus.WithWaitingStatus(message, f) }, func(message string, f func(gocui.Task) error) { gui.helpers.AppStatus.WithWaitingStatusBlockingInput(message, f) From 435e02efa83e8659e3befd2082852bc4df415a00 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 8 Jul 2026 15:44:54 +0200 Subject: [PATCH 170/218] Remove the now-dead PopupMutex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PopupMutex guarded CurrentPopupOpts against a popup being created on a worker goroutine while the UI thread deactivated it, or reset it on a repo switch. Now that popup and menu creation is bounced onto the UI thread, every access to CurrentPopupOpts — create, deactivate, and the reset-on-switch (which already runs on the UI thread) — happens on the one goroutine, so the mutex protects nothing. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/confirmation_helper.go | 7 ------- pkg/gui/gui.go | 2 -- pkg/gui/types/common.go | 1 - 3 files changed, 10 deletions(-) diff --git a/pkg/gui/controllers/helpers/confirmation_helper.go b/pkg/gui/controllers/helpers/confirmation_helper.go index 3663cd4ea..beffeb5e2 100644 --- a/pkg/gui/controllers/helpers/confirmation_helper.go +++ b/pkg/gui/controllers/helpers/confirmation_helper.go @@ -77,9 +77,7 @@ func (self *ConfirmationHelper) wrappedPromptConfirmationFunction( } func (self *ConfirmationHelper) DeactivateConfirmation() { - self.c.Mutexes().PopupMutex.Lock() self.c.State().GetRepoState().SetCurrentPopupOpts(nil) - self.c.Mutexes().PopupMutex.Unlock() self.c.Views().Confirmation.Visible = false @@ -87,9 +85,7 @@ func (self *ConfirmationHelper) DeactivateConfirmation() { } func (self *ConfirmationHelper) DeactivatePrompt() { - self.c.Mutexes().PopupMutex.Lock() self.c.State().GetRepoState().SetCurrentPopupOpts(nil) - self.c.Mutexes().PopupMutex.Unlock() self.c.Views().Prompt.Visible = false self.c.Views().Suggestions.Visible = false @@ -188,9 +184,6 @@ func characterForMask(mask bool) string { } func (self *ConfirmationHelper) CreatePopupPanel(ctx goContext.Context, opts types.CreatePopupPanelOpts) { - self.c.Mutexes().PopupMutex.Lock() - defer self.c.Mutexes().PopupMutex.Unlock() - _, cancel := goContext.WithCancel(ctx) // we don't allow interruptions of non-loader popups in case we get stuck somehow diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 993798e42..9b592ffae 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -620,9 +620,7 @@ func (gui *Gui) resetState(startArgs appTypes.StartArgs) types.Context { // 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() } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 5a256b434..6e7f72541 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -358,7 +358,6 @@ type Model struct { type Mutexes struct { SubprocessMutex deadlock.Mutex - PopupMutex deadlock.Mutex PtyMutex deadlock.Mutex } From 59ed1517bc1b3d42e91a5f65fc77ab427edbb5aa Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 10:25:13 +0200 Subject: [PATCH 171/218] Wait for the event loop to exit in integration tests The test harness enqueued ErrQuit after a test finished, waited for the program to go idle, then slept a fixed second and declared "gocui should have already exited" if it hadn't. That fixed grace is fragile: under the race detector the shutdown legitimately takes longer than a second, so nearly every test failed with that message even though nothing was wrong. Wait for the main loop to actually return instead. gocui now closes a loopExited channel when MainLoop exits, and the harness blocks on it; the existing 40s watchdog still fails a test whose loop genuinely never quits. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/gui.go | 12 ++++++++++++ pkg/gui/test_mode.go | 7 ++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 936e1a310..dbef57b59 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -148,6 +148,10 @@ type Gui struct { maxX, maxY int outputMode OutputMode stop chan struct{} + // loopExited is closed when MainLoop returns, so callers (e.g. the + // integration-test harness) can wait for the event loop to actually finish + // rather than polling or sleeping a fixed interval. + loopExited chan struct{} // BgColor and FgColor allow to configure the background and foreground // colors of the GUI. @@ -260,6 +264,7 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { g.outputMode = opts.OutputMode g.stop = make(chan struct{}) + g.loopExited = make(chan struct{}) g.gEvents = make(chan GocuiEvent, 20) g.userEvents = newUserEventQueue() @@ -348,6 +353,11 @@ func (g *Gui) Close() { Screen.Fini() } +// LoopExited returns a channel that is closed once MainLoop has returned. +func (g *Gui) LoopExited() <-chan struct{} { + return g.loopExited +} + // Size returns the terminal's size. func (g *Gui) Size() (x, y int) { return g.maxX, g.maxY @@ -965,6 +975,8 @@ func (g *Gui) SetManagerFunc(manager func(*Gui) error) { // MainLoop runs the main loop until an error is returned. A successful // finish should return ErrQuit. func (g *Gui) MainLoop() error { + defer close(g.loopExited) + g.uiThreadID.Store(goid.Get()) go func() { diff --git a/pkg/gui/test_mode.go b/pkg/gui/test_mode.go index 2d5958fbb..d6893c92d 100644 --- a/pkg/gui/test_mode.go +++ b/pkg/gui/test_mode.go @@ -40,11 +40,8 @@ func (gui *Gui) handleTestMode() { return gocui.ErrQuit }) - waitUntilIdle() - - time.Sleep(time.Second * 1) - - log.Fatal("gocui should have already exited") + // Wait for the event loop to actually exit. + <-gui.g.LoopExited() }() if os.Getenv(components.WAIT_FOR_DEBUGGER_ENV_VAR) == "" { From 33b8d497c22f131829b1b3181b9b19ce3800a80c Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 10:25:22 +0200 Subject: [PATCH 172/218] Guard the patch builder against concurrent access MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The custom-patch git operations (move/pull/delete patch, and their rebase continuations) run on worker goroutines and call PatchBuilder.Reset when they've consumed the patch, clearing To and the fileInfoMap. Meanwhile the UI thread reads that state every layout — the options bar and the mode indicator both call Active() — so the reset raced the render. Add a mutex. The map's entries are only ever touched on the UI thread, so the lock only has to serialize the To field and the fileInfoMap pointer: readers snapshot the pointer under the lock and iterate the local, and getFileInfo drops the lock across its git diff I/O rather than holding it. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/commands/patch/patch_builder.go | 63 ++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/pkg/commands/patch/patch_builder.go b/pkg/commands/patch/patch_builder.go index b730d9f62..0d5ca34f8 100644 --- a/pkg/commands/patch/patch_builder.go +++ b/pkg/commands/patch/patch_builder.go @@ -6,6 +6,7 @@ import ( "github.com/jesseduffield/generics/maps" "github.com/samber/lo" + "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" ) @@ -50,6 +51,13 @@ type PatchBuilder struct { fileInfoMap map[string]*fileInfo Log *logrus.Entry + // mutex guards the fields that a git worker can mutate (via Reset, at the + // end of a patch-consuming operation) while the UI thread reads them to + // render — chiefly To and the fileInfoMap pointer. The map's *entries* are + // only ever touched on the UI thread, so we only hold the lock long enough + // to read or swap the fields, never across the git I/O in getFileInfo. + mutex deadlock.Mutex + // loadFileDiff loads the diff of a file, for a given to (typically a commit hash) loadFileDiff loadFileDiffFunc } @@ -62,6 +70,9 @@ func NewPatchBuilder(log *logrus.Entry, loadFileDiff loadFileDiffFunc) *PatchBui } func (p *PatchBuilder) Start(from, to string, reverse bool, canRebase bool) { + p.mutex.Lock() + defer p.mutex.Unlock() + p.To = to p.From = from p.reverse = reverse @@ -69,10 +80,21 @@ func (p *PatchBuilder) Start(from, to string, reverse bool, canRebase bool) { p.fileInfoMap = map[string]*fileInfo{} } +// snapshotFileInfoMap returns the current fileInfoMap under the lock. The map's +// entries are only mutated on the UI thread, so callers can read the returned +// map without holding the lock; the lock only serializes the pointer swap that +// Reset/Start do (potentially from a git worker) against these reads. +func (p *PatchBuilder) snapshotFileInfoMap() map[string]*fileInfo { + p.mutex.Lock() + defer p.mutex.Unlock() + + return p.fileInfoMap +} + func (p *PatchBuilder) PatchToApply(reverse bool, turnAddedFilesIntoDiffAgainstEmptyFile bool) string { var patch strings.Builder - for filename, info := range p.fileInfoMap { + for filename, info := range p.snapshotFileInfoMap() { if info.mode == UNSELECTED { continue } @@ -130,12 +152,17 @@ func (p *PatchBuilder) RemoveFile(filename string, previousPath string) error { } func (p *PatchBuilder) getFileInfo(filename string, previousPath string) (*fileInfo, error) { - info, ok := p.fileInfoMap[filename] + p.mutex.Lock() + fileInfoMap := p.fileInfoMap + from, to, reverse := p.From, p.To, p.reverse + p.mutex.Unlock() + + info, ok := fileInfoMap[filename] if ok { return info, nil } - diff, err := p.loadFileDiff(p.From, p.To, p.reverse, filename, previousPath, true) + diff, err := p.loadFileDiff(from, to, reverse, filename, previousPath, true) if err != nil { return nil, err } @@ -145,7 +172,7 @@ func (p *PatchBuilder) getFileInfo(filename string, previousPath string) (*fileI previousPath: previousPath, } - p.fileInfoMap[filename] = info + fileInfoMap[filename] = info return info, nil } @@ -220,14 +247,16 @@ func (p *PatchBuilder) RenderPatchForFile(opts RenderPatchForFileOpts) string { } func (p *PatchBuilder) renderEachFilePatch(plain bool) []string { + fileInfoMap := p.snapshotFileInfoMap() + // sort files by name then iterate through and render each patch - filenames := maps.Keys(p.fileInfoMap) + filenames := maps.Keys(fileInfoMap) sort.Strings(filenames) patches := lo.Map(filenames, func(filename string, _ int) string { return p.RenderPatchForFile(RenderPatchForFileOpts{ Filename: filename, - PreviousPath: p.fileInfoMap[filename].previousPath, + PreviousPath: fileInfoMap[filename].previousPath, Plain: plain, Reverse: false, TurnAddedFilesIntoDiffAgainstEmptyFile: true, @@ -245,11 +274,16 @@ func (p *PatchBuilder) RenderAggregatedPatch(plain bool) string { } func (p *PatchBuilder) GetFileStatus(filename string, parent string) PatchStatus { - if parent != p.To { + p.mutex.Lock() + to := p.To + fileInfoMap := p.fileInfoMap + p.mutex.Unlock() + + if parent != to { return UNSELECTED } - info, ok := p.fileInfoMap[filename] + info, ok := fileInfoMap[filename] if !ok { return UNSELECTED } @@ -267,16 +301,22 @@ func (p *PatchBuilder) GetFileIncLineIndices(filename string, previousPath strin // clears the patch func (p *PatchBuilder) Reset() { + p.mutex.Lock() + defer p.mutex.Unlock() + p.To = "" p.fileInfoMap = map[string]*fileInfo{} } func (p *PatchBuilder) Active() bool { + p.mutex.Lock() + defer p.mutex.Unlock() + return p.To != "" } func (p *PatchBuilder) IsEmpty() bool { - for _, fileInfo := range p.fileInfoMap { + for _, fileInfo := range p.snapshotFileInfoMap() { if fileInfo.mode == WHOLE || (fileInfo.mode == PART && len(fileInfo.includedLineIndices) > 0) { return false } @@ -287,9 +327,12 @@ func (p *PatchBuilder) IsEmpty() bool { // if any of these things change we'll need to reset and start a new patch func (p *PatchBuilder) NewPatchRequired(from string, to string, reverse bool) bool { + p.mutex.Lock() + defer p.mutex.Unlock() + return from != p.From || to != p.To || reverse != p.reverse } func (p *PatchBuilder) AllFilesInPatch() []string { - return lo.Keys(p.fileInfoMap) + return lo.Keys(p.snapshotFileInfoMap()) } From d48c8174d5d1a7af209c2a3935bc61719f610be1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 10:25:28 +0200 Subject: [PATCH 173/218] Refresh the patch-building panel on the UI thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The patch-building scope ran RefreshPatchBuildingPanel directly on the refresh worker, where it read the commit-files selection and set the patch view's origin off the UI thread — the latter raced the UI thread's draw. Bounce it onto the UI thread, exactly as the staging panel just above already does, guarded on the generation so a repo switch drops it. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/helpers/refresh_helper.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 768e7a618..39a8c2fe1 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -398,7 +398,16 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.PATCH_BUILDING) { - refresh("patch building", func() { self.patchBuildingHelper.RefreshPatchBuildingPanel(types.OnFocusOpts{}) }) + refresh("patch building", func() { + // Bounce onto the UI thread, like the staging panel above: + // RefreshPatchBuildingPanel reads the commit-files selection and + // sets the patch view's origin, neither of which may run off the UI + // thread. Guard on the generation so a repo switch mid-refresh drops + // it, like the model bounces. + self.onUIThreadUnlessRepoChanged(env, func() { + self.patchBuildingHelper.RefreshPatchBuildingPanel(types.OnFocusOpts{}) + }) + }) } if scopeSet.Includes(types.MERGE_CONFLICTS) { From 1efcfcc1484ee2d4bdb8abc0c04219f1fcfe2577 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 10:50:13 +0200 Subject: [PATCH 174/218] Don't share a live view's buffer when copying its content moveMainContextToTop copies the current top view's content into the view it's promoting, to avoid a flicker. The source can be a main view with a live streaming task (e.g. resolving a conflict promotes the merge-conflicts view over a main view that's mid-diff), and CopyContent both read and published that source's buffer unsafely: - it read the source's lines/viewLines while locking only the destination, racing the task's concurrent Write; and - it aliased the source's row slices into the destination, so the source's ongoing appends (growslice reading the shared array) and refreshViewLinesIfNeeded's in-place wrapping-cache writes (&lines[i]) kept racing this view's rendering after the copy. Lock the source for the read, and shallow-clone the row slices so the destination gets its own arrays. The per-row cell data is immutable once written, so it stays shared -- the clone cost is proportional to the number of rows, not their contents. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gocui/view.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index 39f2d78a9..b106eb21f 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -7,6 +7,7 @@ package gocui import ( "fmt" "io" + "slices" "strings" "sync" "unicode" @@ -1146,10 +1147,25 @@ func (v *View) CopyContent(from *View) { v.writeMutex.Lock() defer v.writeMutex.Unlock() + // A background task may be streaming output into the source view's buffer + // via Write, so read it under its own lock. The source is always a + // different view than the destination (see the sole caller, + // moveMainContextToTop), and no other code holds two view write locks at + // once, so this can't deadlock. + from.writeMutex.Lock() + defer from.writeMutex.Unlock() + v.clear() - v.lines = from.lines - v.viewLines = from.viewLines + // Clone the row slices rather than sharing them: the source view stays + // live (its streaming task keeps appending rows, and refreshViewLinesIfNeeded + // fills each row's wrapping cache in place via &lines[i]), so sharing the + // backing arrays would race those writes against this view's own rendering. + // This is a shallow clone -- the per-row cell data is immutable once written + // and stays shared, so the cost is proportional to the number of rows, not + // their contents. + v.lines = slices.Clone(from.lines) + v.viewLines = slices.Clone(from.viewLines) v.ox = from.ox v.oy = from.oy v.cx = from.cx From 1b0cc02e1e5106308ec0e1e4ae233987f3d50795 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 12:21:45 +0200 Subject: [PATCH 175/218] Refresh once when dropping multiple stash entries Dropping a range of stashes ran a refresh after each drop. A refresh issued from the UI thread does its git work on a worker and applies the model update in the background, so firing one per iteration let the workers race: an earlier drop's refresh (which read a stash list that still contained a later-dropped entry) could apply its result last, leaving the stash view showing an entry that git had already removed. Refresh once, after all the drops, so a single worker reads the final stash list. The indices are captured up front and dropped highest-first, so the remaining lower indices stay valid without an intervening refresh. It's also cheaper: one `git stash list` instead of one per entry. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/controllers/stash_controller.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index 06e6991c6..a2b7e9e97 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -170,11 +170,16 @@ func (self *StashController) handleStashDrop(stashEntries []*models.StashEntry) Prompt: self.c.Tr.SureDropStashEntry, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.DropStash) + // Refresh once at the end rather than after each drop: an async + // refresh from the UI thread finishes in the background, so firing + // one per iteration lets the workers race and an earlier, stale + // result can land last. The indices are captured up front and we + // drop highest-first, so the remaining lower indices stay valid + // without an intervening refresh. + defer self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) for i := len(stashEntries) - 1; i >= 0; i-- { self.c.LogCommand(fmt.Sprintf(self.c.Tr.Log.DroppingStash, stashEntries[i].Hash), false) - err := self.c.Git().Stash.Drop(stashEntries[i].Index) - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) - if err != nil { + if err := self.c.Git().Stash.Drop(stashEntries[i].Index); err != nil { return err } } From d36ce5155968b318d0ecd3d3b068699410deb332 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 21:40:51 +0200 Subject: [PATCH 176/218] Capture suggestions inputs on the UI thread RefreshSuggestions dispatched to an AsyncHandler worker that read State.FindSuggestions and the prompt's TextArea (via GetPromptInput) from the worker goroutine. The main thread rewrites both in preparePromptPanel when it (re)creates a prompt panel, so an in-flight suggestions worker races those writes -- two data races surfaced under -race (filter_by_path/reword_commit_in_filtering_mode). Capture both on the UI thread (RefreshSuggestions is only ever called from UI-thread handlers) before dispatching to the worker. This is also more correct: we search for the input as it was when dispatched, which is what this request's AsyncHandler id corresponds to. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/context/suggestions_context.go | 11 +++++++++-- pkg/gui/editors.go | 7 +++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/pkg/gui/context/suggestions_context.go b/pkg/gui/context/suggestions_context.go index fb69b34d9..6f0b3eae6 100644 --- a/pkg/gui/context/suggestions_context.go +++ b/pkg/gui/context/suggestions_context.go @@ -81,10 +81,17 @@ func (self *SuggestionsContext) SetSuggestions(suggestions []*types.Suggestion) } func (self *SuggestionsContext) RefreshSuggestions() { + // Capture the suggestions function and the prompt input here, on the UI + // thread, rather than inside the worker below: the main thread rewrites both + // (State.FindSuggestions and the prompt's TextArea) when it (re)creates a + // prompt panel, so reading them from the worker races those writes. It's + // also more correct -- we search for the input as it was when dispatched, + // which is what this request's AsyncHandler id corresponds to. + findSuggestionsFn := self.State.FindSuggestions + promptInput := self.c.GetPromptInput() self.State.AsyncHandler.Do(func() func() { - findSuggestionsFn := self.State.FindSuggestions if findSuggestionsFn != nil { - suggestions := findSuggestionsFn(self.c.GetPromptInput()) + suggestions := findSuggestionsFn(promptInput) return func() { self.SetSuggestions(suggestions) } } return func() {} diff --git a/pkg/gui/editors.go b/pkg/gui/editors.go index 7d3a93de3..37eacf416 100644 --- a/pkg/gui/editors.go +++ b/pkg/gui/editors.go @@ -35,10 +35,13 @@ func (gui *Gui) promptEditor(v *gocui.View, key gocui.Key) bool { v.RenderTextArea() suggestionsContext := gui.State.Contexts.Suggestions - if suggestionsContext.State.FindSuggestions != nil { + // Capture the suggestions function and the input here, on the UI thread; the + // main thread rewrites State.FindSuggestions when it (re)creates a prompt + // panel, so reading it from the worker below would race that write. + if findSuggestions := suggestionsContext.State.FindSuggestions; findSuggestions != nil { input := v.TextArea.GetContent() suggestionsContext.State.AsyncHandler.Do(func() func() { - suggestions := suggestionsContext.State.FindSuggestions(input) + suggestions := findSuggestions(input) return func() { suggestionsContext.SetSuggestions(suggestions) } }) } From 2a7b74d3f310ed33bb4635290358c860e74171af Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 22:43:26 +0200 Subject: [PATCH 177/218] Don't access Model in refreshReflogCommits This was old code that was supposed to make a race less likely, but now that we capture model stuff on the UI thread we don't need it any more. --- pkg/gui/controllers/helpers/refresh_helper.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 39a8c2fe1..d0a0610e2 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1313,10 +1313,6 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re // that a subsequent branches refresh can use them for recency sorting without // having to read them back out of the model. func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, env refreshEnv, selectTopEntry bool) ([]*models.Commit, error) { - // pulling state into its own variable in case it gets swapped out for another state - // and we get an out of bounds exception - model := self.c.Model() - // load does the git work on the worker and returns the new value for a // reflog slice, reading the existing slice (captured on the UI thread) for // the incremental fetch. The caller writes the result in the bounce. @@ -1352,8 +1348,8 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en } self.onUIThreadUnlessRepoChanged(env, func() { - model.ReflogCommits = reflogCommits - model.FilteredReflogCommits = filteredReflogCommits + self.c.Model().ReflogCommits = reflogCommits + self.c.Model().FilteredReflogCommits = filteredReflogCommits // Setting the selection here, in the same bounce that writes the list, // keeps it on the UI thread and atomic with the list update. Setting the // selection doesn't scroll the view, so also reset the origin. From 25a3689c016955595a43a90410b235a775af1ae8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 13:19:03 +0200 Subject: [PATCH 178/218] Refresh the merge conflicts state on the UI thread The "merge conflicts" refresh scope ran on a worker like the others, but unlike them it does UI work rather than git work: RefreshMergeState reads the current context and renders (or escapes) the merge-conflicts view. Reading the context manager and rendering from a worker races the UI thread. Bounce it onto the UI thread with onUIThreadUnlessRepoChanged, exactly as the staging and patch-building scopes already do. Running on the UI thread also lets EscapeMerge push the files context directly instead of deferring the push to a separate UI task; it only needs to drop the merge-conflicts mutex first, because the push renders the newly focused file, which can take the mutex again. The deferred push could lose a race against the same refresh's prompt to continue the rebase/merge: if the prompt opened between RefreshMergeState and the deferred push, the push declined to cover the popup and was dropped, so closing the prompt landed the user in the emptied merge conflicts view. Co-Authored-By: Claude Opus 4.8 (1M context) Co-Authored-By: Claude Fable 5 --- .../helpers/merge_conflicts_helper.go | 49 ++++++++----------- pkg/gui/controllers/helpers/refresh_helper.go | 10 +++- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_conflicts_helper.go b/pkg/gui/controllers/helpers/merge_conflicts_helper.go index 175bc3cc0..34ae285f0 100644 --- a/pkg/gui/controllers/helpers/merge_conflicts_helper.go +++ b/pkg/gui/controllers/helpers/merge_conflicts_helper.go @@ -51,32 +51,28 @@ func (self *MergeConflictsHelper) resetMergeState() { self.context().GetState().Reset() } -func (self *MergeConflictsHelper) EscapeMerge(background bool) error { - self.resetMergeState() +// EscapeMerge returns from the merge conflicts view to the files context. It +// must be called on the UI thread, without the merge-conflicts mutex held: +// pushing the files context renders the newly focused file to the main view, +// which can take the mutex again (via SetMergeState). +func (self *MergeConflictsHelper) EscapeMerge() { + self.ResetMergeState() - // doing this in separate UI thread so that we're not still holding the lock by the time refresh the file - onUIThread := self.c.OnUIThread - if background { - // Reached from a background files refresh; keep it off the busy count - // (see the *Background dispatch methods) so it doesn't block a repo switch. - onUIThread = self.c.OnUIThreadBackground + // The files refresh may already have opened the prompt to continue the + // rebase/merge on top of us (if all conflicts are resolved); in that case + // don't push the files context over it. + if self.c.Context().IsCurrent(self.c.Contexts().MergeConflicts) { + self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) } - onUIThread(func() error { - // There is a race condition here: refreshing the files scope can trigger the - // confirmation context to be pushed if all conflicts are resolved (prompting - // to continue the merge/rebase. In that case, we don't want to then push the - // files context over it. - // So long as both places call OnUIThread, we're fine. - if self.c.Context().IsCurrent(self.c.Contexts().MergeConflicts) { - self.c.Context().Push(self.c.Contexts().Files, types.OnFocusOpts{}) - } - return nil - }) - return nil } -func (self *MergeConflictsHelper) SetConflictsAndRender(path string) (bool, error) { - hasConflicts, err := self.setMergeStateWithoutLock(path) +// SetConflictsAndRender re-reads the file being merged and re-renders the +// merge conflicts view. Returns whether the file still has conflicts. +func (self *MergeConflictsHelper) SetConflictsAndRender() (bool, error) { + self.context().GetMutex().Lock() + defer self.context().GetMutex().Unlock() + + hasConflicts, err := self.setMergeStateWithoutLock(self.context().GetState().GetPath()) if err != nil { return false, err } @@ -126,21 +122,18 @@ func (self *MergeConflictsHelper) Render() { }) } -func (self *MergeConflictsHelper) RefreshMergeState(background bool) error { - self.c.Contexts().MergeConflicts.GetMutex().Lock() - defer self.c.Contexts().MergeConflicts.GetMutex().Unlock() - +func (self *MergeConflictsHelper) RefreshMergeState() error { if self.c.Context().Current().GetKey() != context.MERGE_CONFLICTS_CONTEXT_KEY { return nil } - hasConflicts, err := self.SetConflictsAndRender(self.c.Contexts().MergeConflicts.GetState().GetPath()) + hasConflicts, err := self.SetConflictsAndRender() if err != nil { return err } if !hasConflicts { - return self.EscapeMerge(background) + self.EscapeMerge() } return nil diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index d0a0610e2..4fedf9c7d 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -411,7 +411,15 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.MERGE_CONFLICTS) { - refresh("merge conflicts", func() { _ = self.mergeConflictsHelper.RefreshMergeState(env.background) }) + refresh("merge conflicts", func() { + // Bounce onto the UI thread, like the staging and patch-building + // panels above: RefreshMergeState reads the current context and + // renders (or escapes) the merge-conflicts view, none of which may + // run off the UI thread. + self.onUIThreadUnlessRepoChanged(env, func() { + _ = self.mergeConflictsHelper.RefreshMergeState() + }) + }) } self.refreshStatus(env) From 9f2886f96f75f0c127212562e05cc4d53e49b147 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 13:37:38 +0200 Subject: [PATCH 179/218] Hold the file-path suggestions trie outside the model The file-path suggestions trie is rebuilt asynchronously and then read by the suggestions search, which runs on an AsyncHandler worker. It lived in Model().FilesTrie, so that worker read the (UI-thread-only) model. Move it to an atomic pointer on the SuggestionsHelper instead: it's the only place that uses it, the helper is recreated per repo (so the cache still resets on a repo switch), and an atomic pointer is safe to store from the build and load from the search worker. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../controllers/helpers/suggestions_helper.go | 22 +++++++++++++------ pkg/gui/gui.go | 2 -- pkg/gui/types/common.go | 4 ---- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/pkg/gui/controllers/helpers/suggestions_helper.go b/pkg/gui/controllers/helpers/suggestions_helper.go index 8a5916816..8784d82fc 100644 --- a/pkg/gui/controllers/helpers/suggestions_helper.go +++ b/pkg/gui/controllers/helpers/suggestions_helper.go @@ -3,6 +3,7 @@ package helpers import ( "fmt" "strings" + "sync/atomic" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" @@ -28,14 +29,20 @@ import ( type SuggestionsHelper struct { c *HelperCommon + + // filesTrie holds the repo's file paths for file-path suggestions. It's + // rebuilt asynchronously and read from the suggestions worker goroutine, so + // it lives here as an atomic pointer rather than in the (UI-thread-only) + // model. + filesTrie atomic.Pointer[patricia.Trie] } func NewSuggestionsHelper( c *HelperCommon, ) *SuggestionsHelper { - return &SuggestionsHelper{ - c: c, - } + self := &SuggestionsHelper{c: c} + self.filesTrie.Store(patricia.NewTrie()) + return self } func (self *SuggestionsHelper) getRemoteNames() []string { @@ -137,9 +144,9 @@ func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*type trie.Insert(patricia.Prefix(file), file) } + // cache the trie for future use + self.filesTrie.Store(trie) self.c.OnUIThread(func() error { - // cache the trie for future use - self.c.Model().FilesTrie = trie self.c.Contexts().Suggestions.RefreshSuggestions() return nil }) @@ -148,9 +155,10 @@ func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*type }) return func(input string) []*types.Suggestion { + filesTrie := self.filesTrie.Load() matchingNames := []string{} if self.c.UserConfig().Gui.UseFuzzySearch() { - _ = self.c.Model().FilesTrie.VisitFuzzy(patricia.Prefix(input), true, func(prefix patricia.Prefix, item patricia.Item, skipped int) error { + _ = filesTrie.VisitFuzzy(patricia.Prefix(input), true, func(prefix patricia.Prefix, item patricia.Item, skipped int) error { matchingNames = append(matchingNames, item.(string)) return nil }) @@ -159,7 +167,7 @@ func (self *SuggestionsHelper) GetFilePathSuggestionsFunc() func(string) []*type matchingNames = utils.FilterStrings(input, matchingNames, true) } else { substrings := strings.Fields(input) - _ = self.c.Model().FilesTrie.Visit(func(prefix patricia.Prefix, item patricia.Item) error { + _ = filesTrie.Visit(func(prefix patricia.Prefix, item patricia.Item) error { for _, sub := range substrings { if !utils.CaseAwareContains(item.(string), sub) { return nil diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 9b592ffae..533c01fbd 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -49,7 +49,6 @@ import ( "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 @@ -639,7 +638,6 @@ func (gui *Gui) resetState(startArgs appTypes.StartArgs) types.Context { 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{}, diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 6e7f72541..6d11e29db 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -11,7 +11,6 @@ import ( "github.com/jesseduffield/lazygit/pkg/tasks" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/sasha-s/go-deadlock" - "gopkg.in/ozeidan/fuzzy-patricia.v3/patricia" ) type HelperCommon struct { @@ -348,9 +347,6 @@ type Model struct { MainBranches *git_commands.MainBranches - // for displaying suggestions while typing in a file name - FilesTrie *patricia.Trie - Authors map[string]*models.Author HashPool *utils.StringPool From 87ef96974e26ba31b34eae4acfc5d1365a86ddc1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 13:42:24 +0200 Subject: [PATCH 180/218] Check for exec todos on the UI thread hasExecTodos reads Model().Commits. genericMergeCommandImpl evaluates it when deciding whether to use a subprocess, and on the recursive auto-skip path that runs on a worker -- so the read raced the UI thread. Bounce it onto the UI thread there, keyed off the calledFromWorker flag the function already carries (on the UI-thread entry path the read stays inline). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../helpers/merge_and_rebase_helper.go | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go index a8696a21c..7c7ab3e9a 100644 --- a/pkg/gui/controllers/helpers/merge_and_rebase_helper.go +++ b/pkg/gui/controllers/helpers/merge_and_rebase_helper.go @@ -127,7 +127,7 @@ func (self *MergeAndRebaseHelper) genericMergeCommandImpl(command string, showWa needsSubprocess := (effectiveStatus == models.WORKING_TREE_STATE_MERGING && command != REBASE_OPTION_ABORT && self.c.UserConfig().Git.Merging.ManualCommit) || // but we'll also use a subprocess if we have exec todos; those are likely to be lengthy build // tasks whose output the user will want to see in the terminal - (effectiveStatus == models.WORKING_TREE_STATE_REBASING && command != REBASE_OPTION_ABORT && self.hasExecTodos()) + (effectiveStatus == models.WORKING_TREE_STATE_REBASING && command != REBASE_OPTION_ABORT && self.hasExecTodos(calledFromWorker)) if needsSubprocess { // TODO: see if we should be calling more of the code from self.Git.Rebase.GenericMergeOrRebaseAction @@ -168,16 +168,31 @@ func commitSelectionAfterMerge(createdNewCommit bool) types.CommitSelectionBehav return types.KeepCommitSelectionByHash } -func (self *MergeAndRebaseHelper) hasExecTodos() bool { - for _, commit := range self.c.Model().Commits { - if !commit.IsTODO() { - break - } - if commit.Action == todo.Exec { - return true +func (self *MergeAndRebaseHelper) hasExecTodos(calledFromWorker bool) bool { + check := func() bool { + for _, commit := range self.c.Model().Commits { + if !commit.IsTODO() { + break + } + if commit.Action == todo.Exec { + return true + } } + return false } - return false + + // This reads the model, which is only safe on the UI thread, so bounce there + // when we're being called from a worker. + if !calledFromWorker { + return check() + } + + result := false + _ = self.c.GocuiGui().OnUIThreadAndWait(func() error { + result = check() + return nil + }) + return result } var conflictStrings = []string{ From c23bcd6d9423f3fd51bd8b8d39a5b01dbc52ca65 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 15 Jul 2026 15:19:55 +0200 Subject: [PATCH 181/218] Store the UI thread ID earlier --- pkg/gocui/gui.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index dbef57b59..20beb2af7 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -293,6 +293,12 @@ func NewGui(opts NewGuiOpts) (*Gui, error) { g.playRecording = opts.PlayRecording + // Record the UI thread here, at construction. This assumes NewGui is called + // on the same goroutine that will run MainLoop, which holds for all our + // callers -- and it means IsUIThread is already correct for the UI work that + // runs during startup, before we reach MainLoop. + g.uiThreadID.Store(goid.Get()) + return g, nil } @@ -977,8 +983,6 @@ func (g *Gui) SetManagerFunc(manager func(*Gui) error) { func (g *Gui) MainLoop() error { defer close(g.loopExited) - g.uiThreadID.Store(goid.Get()) - go func() { for { select { From e299de32700ab1a2d865652b6375a6c1131ec76c Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 14 Jul 2026 13:11:07 +0200 Subject: [PATCH 182/218] Assert that Model() and Context() are only accessed on the UI thread The bounce model requires that a worker never touch UI-thread-owned state: it should capture what it needs on the UI thread and pass that in. Guard the two central accessors -- Model() (the git model) and Context() (the context manager, which owns the mutable current-context/stack) -- with a debug-only panic when they're called off the UI thread. Since the integration tests run with -debug, a stray worker access now fails deterministically and points at itself, rather than surfacing later as a probabilistic data race. One supporting change make the assertion usable: the integration test driver inspects gui state from the test goroutine, so GuiDriver.CurrentContext reads the context manager directly rather than through the now-guarded c.Context(). Contexts() (the registry of context objects) is deliberately left unguarded: workers legitimately fetch a context to grab its mutex or check identity, so a blanket assertion there would flag safe accesses. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/gui_common.go | 12 ++++++++++++ pkg/gui/gui_driver.go | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index 69ec44781..80b2b9ded 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -58,7 +58,18 @@ func (self *guiCommon) PauseBackgroundRefreshes(pause bool) { self.gui.BackgroundRoutineMgr.PauseBackgroundRefreshes(pause) } +// assertOnUIThread panics (in debug builds) if called from a worker goroutine. +// Use it to guard accessors for state that only the UI thread may touch, so +// that a stray worker access fails deterministically -- and points at itself -- +// rather than surfacing later as a probabilistic data race. +func (self *guiCommon) assertOnUIThread(accessor string) { + if self.GetConfig().GetDebug() && !self.GocuiGui().IsUIThread() { + panic(accessor + " accessed from a worker") + } +} + func (self *guiCommon) Context() types.IContextMgr { + self.assertOnUIThread("Context()") return self.gui.State.ContextMgr } @@ -113,6 +124,7 @@ func (self *guiCommon) Modes() *types.Modes { } func (self *guiCommon) Model() *types.Model { + self.assertOnUIThread("Model()") return self.gui.State.Model } diff --git a/pkg/gui/gui_driver.go b/pkg/gui/gui_driver.go index 31094b253..7bd31d93d 100644 --- a/pkg/gui/gui_driver.go +++ b/pkg/gui/gui_driver.go @@ -92,7 +92,10 @@ func (self *GuiDriver) Keys() config.KeybindingConfig { } func (self *GuiDriver) CurrentContext() types.Context { - return self.gui.c.Context().Current() + // Read the context manager directly rather than through c.Context(): the + // driver runs on the test goroutine, not the UI thread, so it must bypass + // the UI-thread assertion that accessor carries. + return self.gui.State.ContextMgr.Current() } func (self *GuiDriver) ContextForView(viewName string) types.Context { From 5769ab219069daafbbdba09c2e8529cd17d250f1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 08:16:25 +0200 Subject: [PATCH 183/218] Don't retry failed integration tests Now that we solved all known concurrency issues and our tests should be 100% deterministic, reduce MaxAttempts to 1 so that tests fail immediately. We don't want to paper over existing flakiness any more. --- pkg/integration/clients/go_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/integration/clients/go_test.go b/pkg/integration/clients/go_test.go index 211e73d28..11f6e754e 100644 --- a/pkg/integration/clients/go_test.go +++ b/pkg/integration/clients/go_test.go @@ -56,7 +56,7 @@ func TestIntegration(t *testing.T) { CodeCoverageDir: codeCoverageDir, InputDelay: 0, // Allow two attempts at each test to get around flakiness - MaxAttempts: 2, + MaxAttempts: 1, }) assert.NoError(t, err) From 5055c4fb654b1780330f941c27e828fbf44ebcd8 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 13:37:23 +0200 Subject: [PATCH 184/218] Fetch GitHub pull requests as a background task Every full refresh includes the PULL_REQUESTS scope, and the worker it spawns inherited the refresh's foreground/background flag. Full foreground refreshes happen at startup, after switching repos or worktrees, and when the terminal regains focus, so the GitHub API request ran as a foreground task there, keeping Busy() true until it completed. On a healthy network that's a few hundred milliseconds and nobody notices; on a very slow one the request can stall for minutes, and every attempt to switch repos in that window was refused with "Can't switch repositories while an operation is in progress" even though lazygit looked completely idle. (The request has no visible status; at most, a background fetch hanging on the same bad network was showing its "Fetching..." spinner, pointing the blame at the wrong operation.) The switch-safety guard only needs to wait for operations whose remaining git commands would run against the wrong repo after a switch. The pull-request fetch runs no git commands at all, and its model writes are dropped when the repo generation has changed in the meantime, so there is no reason for it to block switching. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 4fedf9c7d..a7c18aeb8 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -365,7 +365,17 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr } if scopeSet.Includes(types.PULL_REQUESTS) { - self.onWorker(env.background, func(gocui.Task) error { + // Fetching pull requests talks to the GitHub API over the network; on + // a bad connection that request can stall for a long time. It runs no + // git commands against the repo, and its model writes are guarded by + // the repo generation (a repo switch mid-fetch simply drops the + // result), so it is safe to run as a background task even when the + // enclosing refresh is a foreground one — a foreground task would + // block repo switching for as long as the request takes. The env copy + // makes the downstream UI-thread bounces background as well. + prEnv := env + prEnv.background = true + self.c.OnWorkerBackground(func(gocui.Task) error { branchesAndRemotesWg.Wait() t := time.Now() @@ -373,7 +383,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // Model().Branches/Remotes: those writes are bounced onto the // UI thread and may not have landed on this worker yet. The // wait above orders us after both loads have stashed theirs. - self.refreshGithubPullRequests(loadedBranches, loadedRemotes, env) + self.refreshGithubPullRequests(loadedBranches, loadedRemotes, prEnv) self.c.Log.Infof("refreshed pull requests in %s", time.Since(t)) return nil }) From 7360a8459d21be50acb135d8cc43c5e2be4f7b90 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 13:51:38 +0200 Subject: [PATCH 185/218] Give the GitHub GraphQL requests a timeout The http.Client used for fetching pull requests had no timeout, so on a network that silently drops packets a request could stay in flight until the OS-level TCP timeouts kick in, which can take many minutes. The fetch has no visible status, so nothing tells the user it is still running; bounding it keeps the refresh's worst case short, and the next refresh simply tries again. Co-Authored-By: Claude Fable 5 --- pkg/commands/git_commands/github.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/commands/git_commands/github.go b/pkg/commands/git_commands/github.go index e05472ef1..b74815301 100644 --- a/pkg/commands/git_commands/github.go +++ b/pkg/commands/git_commands/github.go @@ -210,7 +210,10 @@ func (self *GitHubCommands) fetchRecentPRsAux(endpoint string, repoOwner string, req.Header.Set("Authorization", "token "+token) req.Header.Set("Content-Type", "application/json") - client := &http.Client{} + // Bound the request so that a dead or extremely slow network can't leave + // the pull-request refresh in flight for minutes. The data is auxiliary, + // so giving up and retrying on the next refresh beats waiting. + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return nil, err From a1561a5e6967cf8a7f93c2f787afed4c773a9d61 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 15:55:01 +0200 Subject: [PATCH 186/218] Render the app status in a single background render loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each status used to start a spinner render loop of its own, running on a worker that inherited the foreground/background flavor of the status's owner, and exiting only once the entire status stack was empty. That shape had a real bug: a foreground operation's loop could be kept alive by someone else's status. Finish a quick operation with a waiting status while a background fetch's "Fetching..." status is still showing, and the operation's render loop — a foreground worker task — keeps ticking until the fetch ends. Busy() stays true for that whole time, so repo switching is refused even though nothing is in flight anymore; with a fetch hanging on a slow network, that means minutes. The shape was also wasteful: overlapping statuses were each drawn by their own loop (plus a duplicate whenever a task was paused and resumed while another status was showing), all redundantly redrawing the same top status. Replace the per-status loops with a single loop owned by the status stack as a whole: whoever shows the first status starts it, and it exits after drawing a final empty frame once the last status is removed. The claim/release methods on StatusManager keep the loop flag's transitions atomic with the stack under the one mutex, so a status added while the loop is about to exit starts a fresh loop instead of going unrendered. The loop always runs as a background task now: rendering issues no git commands, so it never needs to block repo switching, and a foreground operation's busy-ness is already carried by its own worker task. This is what fixes the bug above, and it retires the need to thread a foreground/background flag through the waiting-status helpers altogether. Co-Authored-By: Claude Fable 5 --- pkg/gui/background.go | 2 +- .../controllers/helpers/app_status_helper.go | 57 ++++++++++--------- pkg/gui/status/status_manager.go | 38 +++++++++++++ 3 files changed, 68 insertions(+), 29 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index f9eff420b..1e2db853f 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -119,7 +119,7 @@ func (self *BackgroundRoutineMgr) startBackgroundFetch() { if self.gui.UserConfig().Gui.ShowBottomLine || firstTimeOrRetriggered { return self.gui.helpers.AppStatus.WithWaitingStatusImpl(self.gui.Tr.FetchingStatus, func(gocui.Task) error { return self.backgroundFetch() - }, nil, true) + }, nil) } return self.backgroundFetch() diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index 69daa7d7a..d0bb03395 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -34,12 +34,7 @@ func (self *AppStatusHelper) Toast(message string, kind types.ToastKind) { self.statusMgr().AddToastStatus(message, kind) - // Render the toast in the background: it's a transient notification, not - // lazygit driving an operation, so it must not count towards being busy — - // otherwise a toast (e.g. the "can't switch, operation in progress" one) - // would itself block a repo switch until it faded. A real operation showing - // a toast still keeps its own foreground task busy independently. - self.renderAppStatus(true) + self.renderAppStatus() } // A custom task for WithWaitingStatus calls; it wraps the original one and @@ -66,14 +61,15 @@ func (self appStatusHelperTask) Continue() { // WithWaitingStatus wraps a function and shows a waiting status while the function is still executing func (self *AppStatusHelper) WithWaitingStatus(message string, f func(gocui.Task) error) { self.c.OnWorker(func(task gocui.Task) error { - return self.WithWaitingStatusImpl(message, f, task, false) + return self.WithWaitingStatusImpl(message, f, task) }) } -// background reports whether this waiting status belongs to a background routine -// (the auto-fetch poller); when it does, the spinner it drives must not count -// towards lazygit being busy, or it'd block repo switches while a fetch runs. -func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui.Task) error, task gocui.Task, background bool) error { +// WithWaitingStatusImpl is WithWaitingStatus for callers that already run on a +// goroutine of their own (e.g. the auto-fetch poller) rather than wanting the +// work dispatched to a worker. task is used to hide the status while the task +// is paused; it may be nil for callers whose f ignores its task. +func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui.Task) error, task gocui.Task) error { // A waiting status means lazygit is driving a git operation itself (often // one that internally runs a rebase and continues it). Pause the background // routines for its duration so they don't refresh from an intermediate @@ -81,7 +77,7 @@ func (self *AppStatusHelper) WithWaitingStatusImpl(message string, f func(gocui. self.c.PauseBackgroundRefreshes(true) defer self.c.PauseBackgroundRefreshes(false) - return self.statusMgr().WithWaitingStatus(message, func() { self.renderAppStatus(background) }, func(waitingStatusHandle *status.WaitingStatusHandle) error { + return self.statusMgr().WithWaitingStatus(message, self.renderAppStatus, func(waitingStatusHandle *status.WaitingStatusHandle) error { return f(appStatusHelperTask{task, waitingStatusHandle}) }) } @@ -112,7 +108,7 @@ func (self *AppStatusHelper) WithWaitingStatusBlockingInput(message string, f fu self.modeHelper.SetSuppressRebasingMode(false) return self.c.GocuiGui().EndBlockingEvents() }) - return self.WithWaitingStatusImpl(message, f, task, false) + return self.WithWaitingStatusImpl(message, f, task) }) } @@ -125,33 +121,36 @@ func (self *AppStatusHelper) GetStatusString() string { return appStatus } -func (self *AppStatusHelper) renderAppStatus(background bool) { - // A background waiting status (auto-fetch) must not count towards lazygit - // being busy, so its spinner worker and per-frame UI updates go through the - // background variants. - onWorker := self.c.OnWorker - onUIThread := self.c.OnUIThread - onUIThreadContentOnly := self.c.OnUIThreadContentOnly - if background { - onWorker = self.c.OnWorkerBackground - onUIThread = self.c.OnUIThreadBackground - onUIThreadContentOnly = self.c.OnUIThreadContentOnlyBackground +// renderAppStatus ensures the render loop that keeps the app-status view up to +// date is running. There is one loop for the whole status stack, no matter how +// many statuses are showing: it draws whatever the top status currently is, +// and exits after drawing a final empty frame once the last status is removed. +// +// The loop always runs as a background task, regardless of what kind of +// operation owns a status: rendering runs no git commands, so it must never +// count towards lazygit being busy — otherwise it would block repo switching +// for as long as anything is showing (e.g. for the whole duration of a hung +// background fetch, or of a toast fading). A foreground operation's busy-ness +// is carried by its own worker task, not by the renderer. +func (self *AppStatusHelper) renderAppStatus() { + if !self.statusMgr().ClaimRenderLoop() { + return } - onWorker(func(_ gocui.Task) error { + self.c.OnWorkerBackground(func(_ gocui.Task) error { ticker := time.NewTicker(time.Millisecond * time.Duration(self.c.UserConfig().Gui.Spinner.Rate)) defer ticker.Stop() prevAppStatus := "" for range ticker.C { appStatus, color := self.statusMgr().GetStatusString(self.c.UserConfig()) - update := onUIThreadContentOnly + update := self.c.OnUIThreadContentOnlyBackground if utils.StringWidth(appStatus) != utils.StringWidth(prevAppStatus) { // Need a full layout whenever the width of the status string changes. This can't // happen during normal spinning because we validate that all spinner frames have // the same width, so typically this will only be triggered at the beginning and end // of a status, or if the status string changes midway for some reason. - update = onUIThread + update = self.c.OnUIThreadBackground } update(func() error { self.c.Views().AppStatus.FgColor = color @@ -160,7 +159,9 @@ func (self *AppStatusHelper) renderAppStatus(background bool) { }) prevAppStatus = appStatus - if appStatus == "" { + // Checked after rendering, so that the frame which clears the view + // has already been drawn when we exit. + if self.statusMgr().ReleaseRenderLoopIfEmpty() { break } } diff --git a/pkg/gui/status/status_manager.go b/pkg/gui/status/status_manager.go index 414568a69..35e1b7746 100644 --- a/pkg/gui/status/status_manager.go +++ b/pkg/gui/status/status_manager.go @@ -17,6 +17,11 @@ type StatusManager struct { statuses []appStatus nextId int mutex deadlock.Mutex + + // Whether a render loop is currently drawing the statuses. Guarded by + // mutex, so that claiming and releasing the loop stay atomic with the + // changes to statuses; see ClaimRenderLoop and ReleaseRenderLoopIfEmpty. + renderLoopRunning bool } // Can be used to manipulate a waiting status while it is running (e.g. pause @@ -90,6 +95,39 @@ func (self *StatusManager) HasStatus() bool { return len(self.statuses) > 0 } +// ClaimRenderLoop is called by whoever just added a status; it reports whether +// they must start the render loop. When it returns false, a loop is already +// running and will pick the new status up on its next tick. +func (self *StatusManager) ClaimRenderLoop() bool { + self.mutex.Lock() + defer self.mutex.Unlock() + + if self.renderLoopRunning { + return false + } + + self.renderLoopRunning = true + return true +} + +// ReleaseRenderLoopIfEmpty is called by the render loop after each frame it +// draws; a true result releases the loop's claim and tells it to exit, because +// there are no statuses left to draw. The emptiness check and the release are +// atomic with respect to ClaimRenderLoop, so a status added around this moment +// either sees the still-running loop or starts a fresh one — it can't end up +// unrendered. +func (self *StatusManager) ReleaseRenderLoopIfEmpty() bool { + self.mutex.Lock() + defer self.mutex.Unlock() + + if len(self.statuses) > 0 { + return false + } + + self.renderLoopRunning = false + return true +} + func (self *StatusManager) addStatus(message string, statusType string, kind types.ToastKind) int { self.mutex.Lock() defer self.mutex.Unlock() From 33a2dc302efe6db7020b4bc838f8a204f7d782c4 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 19:19:47 +0200 Subject: [PATCH 187/218] Suppress command logs for tag commands The command log is supposed to show only commands initiated by the user; these are commands that we run to get information for rendering, so they pollute the log and are confusing. --- pkg/commands/git_commands/tag.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/commands/git_commands/tag.go b/pkg/commands/git_commands/tag.go index 4d15027e1..c6fe2e807 100644 --- a/pkg/commands/git_commands/tag.go +++ b/pkg/commands/git_commands/tag.go @@ -43,7 +43,7 @@ func (self *TagCommands) HasTag(tagName string) bool { Arg("refs/tags/" + tagName). ToArgv() - return self.cmd.New(cmdArgs).Run() == nil + return self.cmd.New(cmdArgs).DontLog().Run() == nil } func (self *TagCommands) LocalDelete(tagName string) error { @@ -74,7 +74,7 @@ func (self *TagCommands) ShowAnnotationInfo(tagName string) (string, error) { Arg("refs/tags/" + tagName). ToArgv() - return self.cmd.New(cmdArgs).RunWithOutput() + return self.cmd.New(cmdArgs).DontLog().RunWithOutput() } func (self *TagCommands) IsTagAnnotated(tagName string) (bool, error) { @@ -83,6 +83,6 @@ func (self *TagCommands) IsTagAnnotated(tagName string) (bool, error) { Arg("refs/tags/" + tagName). ToArgv() - output, err := self.cmd.New(cmdArgs).RunWithOutput() + output, err := self.cmd.New(cmdArgs).DontLog().RunWithOutput() return strings.TrimSpace(output) == "tag", err } From 197916aafb3b9a7f6e7535263d44bf78b0b7638d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 19:22:48 +0200 Subject: [PATCH 188/218] Suppress command logs for git calls related to the ctrl+f command --- pkg/commands/git_commands/blame.go | 2 +- pkg/gui/controllers/helpers/fixup_helper.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/commands/git_commands/blame.go b/pkg/commands/git_commands/blame.go index aba1c63fe..e1a9469eb 100644 --- a/pkg/commands/git_commands/blame.go +++ b/pkg/commands/git_commands/blame.go @@ -29,5 +29,5 @@ func (self *BlameCommands) BlameLineRange(filename string, commit string, firstL Arg("--"). Arg(filename) - return self.cmd.New(cmdArgs.ToArgv()).RunWithOutput() + return self.cmd.New(cmdArgs.ToArgv()).DontLog().RunWithOutput() } diff --git a/pkg/gui/controllers/helpers/fixup_helper.go b/pkg/gui/controllers/helpers/fixup_helper.go index a958e58a8..e8fa43f2d 100644 --- a/pkg/gui/controllers/helpers/fixup_helper.go +++ b/pkg/gui/controllers/helpers/fixup_helper.go @@ -199,12 +199,12 @@ func (self *FixupHelper) getDiff() (string, bool, error) { // Try staged changes first hasStagedChanges := true - diff, err := self.c.Git().Diff.DiffIndexCmdObj(append([]string{"--cached"}, args...)...).RunWithOutput() + diff, err := self.c.Git().Diff.DiffIndexCmdObj(append([]string{"--cached"}, args...)...).DontLog().RunWithOutput() if err == nil && diff == "" { hasStagedChanges = false // If there are no staged changes, try unstaged changes - diff, err = self.c.Git().Diff.DiffIndexCmdObj(args...).RunWithOutput() + diff, err = self.c.Git().Diff.DiffIndexCmdObj(args...).DontLog().RunWithOutput() } return diff, hasStagedChanges, err From b37141156719332fa53f268bce91f33ad34d9ac3 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 22:52:47 +0200 Subject: [PATCH 189/218] Recommend the gopls MCP tools for symbol navigation in AGENTS.md Grep-based navigation needs manual filtering for the many colliding method names in this codebase, while gopls answers reference and implementation questions type-aware and exactly. Scope the guidance to the symbol tools and keep grep for textual searches: gopls' own MCP instructions prescribe running vulncheck at session start and go_file_context after every file read, which costs more than it helps here. The server is registered per user and machine, so sessions without it must just fall back to grep rather than try to set it up. --- AGENTS.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 88e818249..2cafd9d50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,24 @@ Windows box has only `just`). (most useful with `--sandbox` or `--slow`). - `just lint` — run golangci-lint. +## Prefer gopls MCP tools for Go symbol questions + +When the gopls MCP tools are available in the session, prefer them over grep +for type-aware questions about Go code: who calls a function or method +(`go_symbol_references`), finding a symbol by fuzzy name (`go_search`), or +inspecting a package's API (`go_package_api`). Method names in this codebase +collide a lot (`draw`, `Show`, `Refresh` exist on several types), and grep +needs manual filtering that gopls doesn't. This includes code under +`vendor/`, which gopls resolves as part of the module build. + +Grep remains the right tool for strings, comments, config keys, non-Go +files, and anything textual. Don't adopt the full workflow from +`gopls mcp -instructions` (vulncheck on session start, `go_file_context` +after every file read); that overhead isn't worth it here. + +If the tools aren't available in a session, fall back to grep silently — +don't try to install, register, or start the server. + ## When to commit Do not leave completed work uncommitted. Once a logical unit of work is done From 3ed6ce8f670caf023bf510f6c7b3592e472d3b27 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 13:55:34 +0200 Subject: [PATCH 190/218] Add test showing that resuming after a suspend schedules no redraw When lazygit is suspended with ctrl+z and brought back with fg, nothing deliberately triggers a redraw. The screen only repaints because the UI thread happens to have a flush pending from the suspend keybinding, and that flush races the SIGCONT handler's resume; when it loses in the right way, the terminal shows a blank screen until the next input event arrives (#5309). --- pkg/gocui/suspend_test.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 pkg/gocui/suspend_test.go diff --git a/pkg/gocui/suspend_test.go b/pkg/gocui/suspend_test.go new file mode 100644 index 000000000..25a15c921 --- /dev/null +++ b/pkg/gocui/suspend_test.go @@ -0,0 +1,27 @@ +package gocui + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestResumeSchedulesRedraw(t *testing.T) { + g := newTestGui(t) + + assert.NoError(t, g.Suspend()) + assert.NoError(t, g.Resume()) + + ev := GocuiEvent{Type: eventNone} + select { + case ev = <-g.gEvents: + case <-time.After(100 * time.Millisecond): + } + + /* EXPECTED: + assert.Equal(t, eventResize, ev.Type, + "resuming must schedule a redraw; without one the screen stays blank until the next event arrives") + ACTUAL: */ + assert.Equal(t, eventNone, ev.Type) +} From d887a41ad2c386ca8b43fab9262553525e57af72 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 13:58:32 +0200 Subject: [PATCH 191/218] Don't flush the screen while suspended When suspending with ctrl+z, the suspend keybinding handler disengages the screen and then sends SIGSTOP to the process group, so the UI thread freezes at the return from kill(2) with the handler's follow-up flush still pending. When fg continues the process, that pending flush races the SIGCONT handler's Resume. If the flush wins, Show() draws against the disengaged screen, whose cell buffer tcell has released to 0x0 while its width/height still hold the old size; drawCell() then reports width 0 for the out-of-range cell, the draw loop's 'x += width - 1' never advances, and the UI thread spins forever while holding the tcell screen lock. Resume in turn blocks forever on that lock, so the screen never re-engages and no input is ever read again: the hard stall of #5309, only recoverable by killing the process. Guard both flush paths with the suspended flag. For the flag to guarantee that the screen is engaged whenever it is false, Resume must clear it only after re-engaging (it used to clear it before); Suspend already sets it before disengaging. This also covers the pre-existing unsynchronized suspended check in draw(), which is subsumed by the guards and can go. The regression test cannot use the demonstrate-then-fix pattern: on unfixed code the flush goroutine spins holding the screen lock, which deadlocks any subsequent screen call including the test cleanup's Close(). --- pkg/gocui/gui.go | 42 ++++++++++++++++++++++++++++++------ pkg/gocui/suspend_test.go | 45 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 20beb2af7..2785f07d4 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -1470,6 +1470,11 @@ func (g *Gui) drawListFooter(v *View, fgColor, bgColor Attribute) error { // flush updates the gui, re-drawing frames and buffers. func (g *Gui) flush() error { + // The screen must not be touched while suspended (see Suspend). + if g.isSuspended() { + return nil + } + // pretty sure we don't need this, but keeping it here in case we get weird visual artifacts // g.clear(g.FgColor, g.BgColor) @@ -1502,6 +1507,11 @@ func (g *Gui) flush() error { // actually-changed cells are emitted to the terminal. // Will also redraw any views that overlap tainted views func (g *Gui) flushContentOnly(views []*View) error { + // The screen must not be touched while suspended (see Suspend). + if g.isSuspended() { + return nil + } + for _, v := range viewsToRedrawContentOnly(views) { if err := g.draw(v); err != nil { return err @@ -1555,10 +1565,6 @@ func (g *Gui) ForceFlushViewsContentOnly(views []*View) error { // draw manages the cursor and calls the draw function of a view. func (g *Gui) draw(v *View) error { - if g.suspended { - return nil - } - if !v.Visible || v.y1 < v.y0 || v.x1 < v.x0 { return nil } @@ -1930,6 +1936,14 @@ func (g *Gui) onFocus(ev *GocuiEvent) error { return nil } +// While g.suspended is true, nothing must be drawn to the screen: tcell +// releases the screen's cell buffer when disengaging, and drawing to a +// disengaged screen spins forever inside tcell while holding the screen lock, +// which then blocks Resume (and with it all further input) forever. For the +// flag to guarantee that, it must only ever be false while the screen is +// engaged: Suspend sets it before disengaging, and Resume clears it only +// after re-engaging. + func (g *Gui) Suspend() error { g.suspendedMutex.Lock() defer g.suspendedMutex.Unlock() @@ -1940,7 +1954,12 @@ func (g *Gui) Suspend() error { g.suspended = true - return g.screen.Suspend() + if err := g.screen.Suspend(); err != nil { + g.suspended = false + return err + } + + return nil } func (g *Gui) Resume() error { @@ -1951,9 +1970,20 @@ func (g *Gui) Resume() error { return errors.New("Cannot resume because we are not suspended") } + if err := g.screen.Resume(); err != nil { + return err + } + g.suspended = false - return g.screen.Resume() + return nil +} + +func (g *Gui) isSuspended() bool { + g.suspendedMutex.Lock() + defer g.suspendedMutex.Unlock() + + return g.suspended } // matchView returns if the keybinding matches the current view (and the view's context) diff --git a/pkg/gocui/suspend_test.go b/pkg/gocui/suspend_test.go index 25a15c921..d5ea5a132 100644 --- a/pkg/gocui/suspend_test.go +++ b/pkg/gocui/suspend_test.go @@ -7,6 +7,51 @@ import ( "github.com/stretchr/testify/assert" ) +// A flush while suspended must return without touching the screen: tcell +// releases the screen's cell buffer when disengaging, and drawing to a +// disengaged screen spins forever inside tcell while holding the screen lock, +// blocking the resume triggered by fg (#5309). The flush runs in a goroutine +// so that a regression fails the test instead of hanging the suite. +func TestFlushIsNoOpWhileSuspended(t *testing.T) { + tests := []struct { + name string + flush func(g *Gui) error + }{ + {"flush", func(g *Gui) error { return g.flush() }}, + {"flushContentOnly", func(g *Gui) error { return g.flushContentOnly(g.views) }}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // Deliberately not newTestGui: its cleanup closes the screen, + // which would deadlock on the screen lock if a regression makes + // the flush below spin. + g, err := NewGui(NewGuiOpts{ + OutputMode: OutputNormal, + Headless: true, + Width: 80, + Height: 24, + }) + assert.NoError(t, err) + + assert.NoError(t, g.Suspend()) + + flushReturned := make(chan error, 1) + go func() { flushReturned <- tc.flush(g) }() + + select { + case err := <-flushReturned: + assert.NoError(t, err) + case <-time.After(time.Second): + t.Fatal("flush touched the suspended screen and got stuck") + } + + assert.NoError(t, g.Resume()) + g.Close() + }) + } +} + func TestResumeSchedulesRedraw(t *testing.T) { g := newTestGui(t) From 319f43e1660cfee71f8479626c8f48020f9642cc Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 17 Jul 2026 14:00:06 +0200 Subject: [PATCH 192/218] Schedule a redraw when resuming from suspension Until now the repaint after fg was accidental: it only happened because the suspend keybinding handler still had a flush pending on the UI thread, and only if that flush happened to run after the SIGCONT handler had re-engaged the screen. Now that flushes are skipped while suspended, losing that race would leave the screen blank until the next input event arrives, so schedule a redraw explicitly (#5309). --- pkg/gocui/gui.go | 5 +++++ pkg/gocui/suspend_test.go | 3 --- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 2785f07d4..57818960c 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -1976,6 +1976,11 @@ func (g *Gui) Resume() error { g.suspended = false + // Schedule a redraw of the whole screen. Nothing else guarantees one: + // flushes are skipped while suspended, and after re-engaging the screen + // the terminal shows nothing until we draw again. + go func() { g.gEvents <- GocuiEvent{Type: eventResize} }() + return nil } diff --git a/pkg/gocui/suspend_test.go b/pkg/gocui/suspend_test.go index d5ea5a132..ded220bea 100644 --- a/pkg/gocui/suspend_test.go +++ b/pkg/gocui/suspend_test.go @@ -64,9 +64,6 @@ func TestResumeSchedulesRedraw(t *testing.T) { case <-time.After(100 * time.Millisecond): } - /* EXPECTED: assert.Equal(t, eventResize, ev.Type, "resuming must schedule a redraw; without one the screen stays blank until the next event arrives") - ACTUAL: */ - assert.Equal(t, eventNone, ev.Type) } From 94e5f570f668a6332439970a46e2d52909178549 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 20:57:35 +0200 Subject: [PATCH 193/218] Bump tcell to v3.4.1 to fix drawing on a suspended screen The previous two commits stop gocui from flushing while suspended, but that guard cannot be fully airtight from gocui's side: it is a check-then-act on the suspended flag, so a flush racing the suspend itself (e.g. from a spinner goroutine) could still reach the screen just as it disengages, and tcell's disengageFinish mutates the cell buffer without holding the screen lock. Upstream now closes this at the source (gdamore/tcell#1139): draw() returns immediately on a disengaged screen, and the draw scan loop can no longer stall on the width-0 cells that a released cell buffer reports (#5309). The delta over the previously pinned snapshot is these two fixes, a CSI R input decode fix, a wasm packaging chore, and dependency bumps. Co-Authored-By: Claude Fable 5 --- go.mod | 15 ++--- go.sum | 32 ++++----- .../github.com/gdamore/tcell/v3/CHANGESv3.md | 10 ++- .../gdamore/tcell/v3/README-wasm.md | 2 + vendor/github.com/gdamore/tcell/v3/input.go | 1 + vendor/github.com/gdamore/tcell/v3/tscreen.go | 11 ++++ vendor/golang.org/x/mod/modfile/read.go | 8 +-- vendor/golang.org/x/mod/modfile/rule.go | 65 ++++++++++++++++--- .../golang.org/x/sync/semaphore/semaphore.go | 17 +++-- vendor/golang.org/x/sys/unix/syscall_linux.go | 1 + .../x/sys/unix/syscall_linux_386.go | 1 - .../x/sys/unix/syscall_linux_amd64.go | 1 - .../x/sys/unix/syscall_linux_arm.go | 1 - .../x/sys/unix/syscall_linux_arm64.go | 1 - .../x/sys/unix/syscall_linux_loong64.go | 1 - .../x/sys/unix/syscall_linux_mips64x.go | 1 - .../x/sys/unix/syscall_linux_mipsx.go | 1 - .../x/sys/unix/syscall_linux_ppc.go | 1 - .../x/sys/unix/syscall_linux_ppc64x.go | 1 - .../x/sys/unix/syscall_linux_riscv64.go | 1 - .../x/sys/unix/syscall_linux_s390x.go | 1 - .../x/sys/unix/syscall_linux_sparc64.go | 1 - vendor/golang.org/x/sys/unix/zerrors_linux.go | 8 ++- .../golang.org/x/sys/unix/zsyscall_linux.go | 17 +++++ .../x/sys/unix/zsyscall_linux_386.go | 17 ----- .../x/sys/unix/zsyscall_linux_amd64.go | 17 ----- .../x/sys/unix/zsyscall_linux_arm.go | 17 ----- .../x/sys/unix/zsyscall_linux_arm64.go | 17 ----- .../x/sys/unix/zsyscall_linux_loong64.go | 17 ----- .../x/sys/unix/zsyscall_linux_mips.go | 17 ----- .../x/sys/unix/zsyscall_linux_mips64.go | 17 ----- .../x/sys/unix/zsyscall_linux_mips64le.go | 17 ----- .../x/sys/unix/zsyscall_linux_mipsle.go | 17 ----- .../x/sys/unix/zsyscall_linux_ppc.go | 17 ----- .../x/sys/unix/zsyscall_linux_ppc64.go | 17 ----- .../x/sys/unix/zsyscall_linux_ppc64le.go | 17 ----- .../x/sys/unix/zsyscall_linux_riscv64.go | 17 ----- .../x/sys/unix/zsyscall_linux_s390x.go | 17 ----- .../x/sys/unix/zsyscall_linux_sparc64.go | 17 ----- .../x/sys/windows/security_windows.go | 36 ++++++++++ .../x/sys/windows/syscall_windows.go | 8 ++- .../golang.org/x/sys/windows/types_windows.go | 1 + vendor/golang.org/x/text/cases/context.go | 2 +- vendor/golang.org/x/text/cases/map.go | 4 +- .../x/text/unicode/norm/forminfo.go | 9 ++- vendor/golang.org/x/text/unicode/norm/iter.go | 8 +-- .../x/text/unicode/norm/normalize.go | 20 +++--- vendor/modules.txt | 16 ++--- 48 files changed, 216 insertions(+), 342 deletions(-) diff --git a/go.mod b/go.mod index 12af7493b..515bb8f1b 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/cli/go-gh/v2 v2.13.0 github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 github.com/creack/pty v1.1.24 - github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 + github.com/gdamore/tcell/v3 v3.4.1 github.com/go-errors/errors v1.5.1 github.com/gookit/color v1.6.1 github.com/integrii/flaggy v1.8.0 @@ -38,8 +38,8 @@ require ( github.com/stretchr/testify v1.11.1 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 - golang.org/x/sync v0.21.0 - golang.org/x/sys v0.46.0 + golang.org/x/sync v0.22.0 + golang.org/x/sys v0.47.0 gopkg.in/ozeidan/fuzzy-patricia.v3 v3.0.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -65,11 +65,10 @@ require ( github.com/onsi/gomega v1.34.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect - golang.org/x/mod v0.36.0 // indirect - golang.org/x/net v0.55.0 // indirect - golang.org/x/term v0.44.0 // indirect - golang.org/x/text v0.38.0 // indirect - golang.org/x/tools v0.45.0 // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/term v0.45.0 // indirect + golang.org/x/text v0.40.0 // indirect + golang.org/x/tools v0.47.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/fsnotify.v1 v1.4.7 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect diff --git a/go.sum b/go.sum index 2f734de11..1b8cb7d66 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,8 @@ github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= -github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 h1:kUXexBZYoVdAJIOIuP6uLgK3k0G7ClDIRO27Z3epgtU= -github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59/go.mod h1:Ev/2PFhL0QtVmu6XPZG9NEuITAZ6XH7i7/BF3wupBdw= +github.com/gdamore/tcell/v3 v3.4.1 h1:22227t1EUwqxTlmCX9vw0RUE2IEPGw6oYcNan+bPe4w= +github.com/gdamore/tcell/v3 v3.4.1/go.mod h1:YWwuxZNi14VGQC5g2VGNEDRXpBraTwvVjMovRH6G6hw= github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= @@ -139,19 +139,19 @@ golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= -golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= -golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= -golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20170407050850-f3918c30c5c2/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -163,26 +163,26 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= -golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= -golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= -golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= -golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/vendor/github.com/gdamore/tcell/v3/CHANGESv3.md b/vendor/github.com/gdamore/tcell/v3/CHANGESv3.md index 26a0c2e57..c3fcb3f4f 100644 --- a/vendor/github.com/gdamore/tcell/v3/CHANGESv3.md +++ b/vendor/github.com/gdamore/tcell/v3/CHANGESv3.md @@ -100,7 +100,7 @@ These functions weren't reliable and served no useful purpose. `NewConsoleScreen` is removed as is support for Windows console mode. Instead this uses the more modern Windows VT modes. -As a consequence, this means that _Tcell_ on Windows requires at least Winows 10 build 1703 (the Creators Update). +As a consequence, this means that _Tcell_ on Windows requires at least Windows 10 build 1703 (the Creators Update). If you are using a version of Windows 10 older than that, you should really upgrade for _many_ reasons, not just because _Tcell_ doesn't support it anymore. @@ -108,3 +108,11 @@ because _Tcell_ doesn't support it anymore. This structure, and the associated `NewInputProcessor` function, were made public incorrectly. They are not part of our public API going forward, and are now private symbols. + +## SimulationScreen is Removed + +While never part of the public _Tcell_ API, some projects may have used the +`SimulationScreen` for their own tests. That facility was very limited, and +we implemented a much more complete emulation of a terminal in `MockScreen` +and `MockTerm`. (To be clear, those facilities are still intended for _Tcell_'s +own testing, and are still not part of the public API.) diff --git a/vendor/github.com/gdamore/tcell/v3/README-wasm.md b/vendor/github.com/gdamore/tcell/v3/README-wasm.md index 4e29a3dac..1a92a4e5c 100644 --- a/vendor/github.com/gdamore/tcell/v3/README-wasm.md +++ b/vendor/github.com/gdamore/tcell/v3/README-wasm.md @@ -24,6 +24,8 @@ cp -R webfiles/ghostty-web /path/to/dir/to/serve/ The vendored `ghostty-web.js` is intentionally browser-only. Its upstream Node `readFile` fallback import is removed so browser-oriented servers and bundlers such as Vite do not try to resolve a Node file-system shim; the bundled code loads `ghostty-vt.wasm` with `fetch`. +The vendored `ghostty-web.js` is also de-inlined: upstream embeds a base64 copy of `ghostty-vt.wasm` twice inside the JS (as default candidates for `Ghostty.load()`), which more than tripled the shipped bytes. Those inline `data:application/wasm;base64,...` defaults are removed; `tcell.js` passes an explicit URL to `Ghostty.load()`, and the `./ghostty-vt.wasm` / `/ghostty-vt.wasm` relative paths remain as no-argument fallbacks. The wasm is therefore shipped once, as the separate `ghostty-vt.wasm`. + For example: ```sh diff --git a/vendor/github.com/gdamore/tcell/v3/input.go b/vendor/github.com/gdamore/tcell/v3/input.go index 58c8a7e0d..74e234d1e 100644 --- a/vendor/github.com/gdamore/tcell/v3/input.go +++ b/vendor/github.com/gdamore/tcell/v3/input.go @@ -222,6 +222,7 @@ var csiAllKeys = map[csiParamMode]keyMap{ {M: 'L'}: {Key: KeyInsert}, {M: 'P'}: {Key: KeyF1}, // except for aixterm, where this is Delete {M: 'Q'}: {Key: KeyF2}, + {M: 'R'}: {Key: KeyF3}, {M: 'S'}: {Key: KeyF4}, {M: 'Z'}: {Key: KeyBacktab}, {M: 'a'}: {Key: KeyUp, Mod: ModShift}, diff --git a/vendor/github.com/gdamore/tcell/v3/tscreen.go b/vendor/github.com/gdamore/tcell/v3/tscreen.go index 9fe3cf8fe..d50101903 100644 --- a/vendor/github.com/gdamore/tcell/v3/tscreen.go +++ b/vendor/github.com/gdamore/tcell/v3/tscreen.go @@ -1009,6 +1009,13 @@ func (t *tScreen) hideCursor() { } func (t *tScreen) draw() { + if !t.running { + // While disengaged (e.g. suspended) the terminal belongs to some + // other application, so we must not emit anything; also the cell + // buffer is released, so there is nothing valid to draw from. + return + } + // clobber cursor position, because we're going to change it all t.cx = -1 t.cy = -1 @@ -1040,6 +1047,10 @@ func (t *tScreen) draw() { // actually will *draw* it. t.cells.SetDirty(x+1, y, true) } + } else if width < 1 { + // drawCell reports width 0 for coordinates outside the + // cell buffer; never let the scan stall + width = 1 } x += width - 1 } diff --git a/vendor/golang.org/x/mod/modfile/read.go b/vendor/golang.org/x/mod/modfile/read.go index 504a2f1df..5b528c718 100644 --- a/vendor/golang.org/x/mod/modfile/read.go +++ b/vendor/golang.org/x/mod/modfile/read.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "os" + "slices" "strconv" "strings" "unicode" @@ -105,8 +106,7 @@ func (x *FileSyntax) addLine(hint Expr, tokens ...string) *Line { if hint == nil { // If no hint given, add to the last statement of the given type. Loop: - for i := len(x.Stmt) - 1; i >= 0; i-- { - stmt := x.Stmt[i] + for _, stmt := range slices.Backward(x.Stmt) { switch stmt := stmt.(type) { case *Line: if stmt.Token != nil && stmt.Token[0] == tokens[0] { @@ -718,9 +718,7 @@ func (in *input) assignComments() { } // Assign suffix comments to syntax immediately before. - for i := len(in.post) - 1; i >= 0; i-- { - x := in.post[i] - + for _, x := range slices.Backward(in.post) { start, end := x.Span() if debug { fmt.Fprintf(os.Stderr, "post %T :%d:%d #%d :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte, end.Line, end.LineRune, end.Byte) diff --git a/vendor/golang.org/x/mod/modfile/rule.go b/vendor/golang.org/x/mod/modfile/rule.go index c5b8305de..9ab203b56 100644 --- a/vendor/golang.org/x/mod/modfile/rule.go +++ b/vendor/golang.org/x/mod/modfile/rule.go @@ -327,6 +327,7 @@ func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (parse } var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))?([a-z]+[0-9]+)?$`) + var laxGoVersionRE = lazyregexp.New(`^v?(([1-9][0-9]*)\.(0|[1-9][0-9]*))([^0-9].*)$`) // Toolchains must be named beginning with `go1`, @@ -1272,6 +1273,17 @@ func (f *File) SetRequire(req []*Require) { // SetRequireSeparateIndirect will split it into a direct-only and indirect-only // block. This aids in the transition to separate blocks. func (f *File) SetRequireSeparateIndirect(req []*Require) { + f.setRequireSeparateIndirect(req, false) +} + +// SetRequireAtMostTwo is like SetRequireSeparateIndirect but it aggressively +// consolidates all requirements into at most two blocks (one direct, one indirect). +// It ignores existing blocks and comments when deciding where to place requirements. +func (f *File) SetRequireAtMostTwo(req []*Require) { + f.setRequireSeparateIndirect(req, true) +} + +func (f *File) setRequireSeparateIndirect(req []*Require, simplify bool) { // hasComments returns whether a line or block has comments // other than "indirect". hasComments := func(c Comments) bool { @@ -1304,6 +1316,17 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { } // Examine existing require lines and blocks. + need := make(map[string]*Require) + for _, r := range req { + need[r.Mod.Path] = r + } + lineIndirect := make(map[*Line]bool) + for _, r := range f.Require { + if n := need[r.Mod.Path]; n != nil { + lineIndirect[r.Syntax] = n.Indirect + } + } + var ( // We may insert new requirements into the last uncommented // direct-only and indirect-only blocks. We may also move requirements @@ -1321,7 +1344,9 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { // Track the block each requirement belongs to (if any) so we can // move them later. - lineToBlock = make(map[*Line]*LineBlock) + lineToBlock = make(map[*Line]*LineBlock) + directBlockComments []Comment + indirectBlockComments []Comment ) for i, stmt := range f.Syntax.Stmt { switch stmt := stmt.(type) { @@ -1364,6 +1389,24 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { if allIndirect { lastIndirectIndex = i } + if simplify { + anyDirect := false + for _, line := range stmt.Line { + if ind, ok := lineIndirect[line]; ok && !ind { + anyDirect = true + break + } + } + target := &directBlockComments + if !anyDirect && len(stmt.Line) > 0 { + target = &indirectBlockComments + } + if len(*target) > 0 && len(stmt.Comments.Before) > 0 { + *target = append(*target, Comment{Token: "//"}) + } + *target = append(*target, stmt.Comments.Before...) + stmt.Comments.Before = nil + } } } @@ -1422,6 +1465,15 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { lastIndirectBlock = ensureBlock(lastIndirectIndex) } + if simplify { + if len(directBlockComments) > 0 { + lastDirectBlock.Comments.Before = append(lastDirectBlock.Comments.Before, directBlockComments...) + } + if len(indirectBlockComments) > 0 { + lastIndirectBlock.Comments.Before = append(lastIndirectBlock.Comments.Before, indirectBlockComments...) + } + } + // Delete requirements we don't want anymore. // Update versions and indirect comments on requirements we want to keep. // If a requirement is in last{Direct,Indirect}Block with the wrong @@ -1430,10 +1482,6 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { // correct block. // // Some blocks may be empty after this. Cleanup will remove them. - need := make(map[string]*Require) - for _, r := range req { - need[r.Mod.Path] = r - } have := make(map[string]*Require) for _, r := range f.Require { path := r.Mod.Path @@ -1446,10 +1494,10 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { r.setVersion(need[path].Mod.Version) r.setIndirect(need[path].Indirect) if need[path].Indirect && - (oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastDirectBlock) { + (simplify || oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastDirectBlock) { moveReq(r, lastIndirectBlock) } else if !need[path].Indirect && - (oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastIndirectBlock) { + (simplify || oneFlatUncommentedBlock || lineToBlock[r.Syntax] == lastIndirectBlock) { moveReq(r, lastDirectBlock) } } @@ -1736,8 +1784,7 @@ func removeDups(syntax *FileSyntax, exclude *[]*Exclude, replace *[]*Replace, to // Remove duplicate replacements. // Later replacements take priority over earlier ones. haveReplace := make(map[module.Version]bool) - for i := len(*replace) - 1; i >= 0; i-- { - x := (*replace)[i] + for _, x := range slices.Backward(*replace) { if haveReplace[x.Old] { kill[x.Syntax] = true continue diff --git a/vendor/golang.org/x/sync/semaphore/semaphore.go b/vendor/golang.org/x/sync/semaphore/semaphore.go index 040c5bc50..96a035aed 100644 --- a/vendor/golang.org/x/sync/semaphore/semaphore.go +++ b/vendor/golang.org/x/sync/semaphore/semaphore.go @@ -24,7 +24,7 @@ func NewWeighted(n int64) *Weighted { } // Weighted provides a way to bound concurrent access to a resource. -// The callers can request access with a given weight. +// The callers can request access with a given non-negative weight. type Weighted struct { size int64 cur int64 @@ -32,10 +32,13 @@ type Weighted struct { waiters list.List } -// Acquire acquires the semaphore with a weight of n, blocking until resources +// Acquire acquires the semaphore with a non-negative weight of n, blocking until resources // are available or ctx is done. On success, returns nil. On failure, returns // ctx.Err() and leaves the semaphore unchanged. func (s *Weighted) Acquire(ctx context.Context, n int64) error { + if n < 0 { + panic("semaphore: n < 0") + } done := ctx.Done() s.mu.Lock() @@ -106,9 +109,12 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { } } -// TryAcquire acquires the semaphore with a weight of n without blocking. +// TryAcquire acquires the semaphore with a non-negative weight of n without blocking. // On success, returns true. On failure, returns false and leaves the semaphore unchanged. func (s *Weighted) TryAcquire(n int64) bool { + if n < 0 { + panic("semaphore: n < 0") + } s.mu.Lock() success := s.size-s.cur >= n && s.waiters.Len() == 0 if success { @@ -118,8 +124,11 @@ func (s *Weighted) TryAcquire(n int64) bool { return success } -// Release releases the semaphore with a weight of n. +// Release releases the semaphore with a non-negative weight of n. func (s *Weighted) Release(n int64) { + if n < 0 { + panic("semaphore: n < 0") + } s.mu.Lock() s.cur -= n if s.cur < 0 { diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index ce4d7ab1e..21e2bfa39 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1874,6 +1874,7 @@ func Dup2(oldfd, newfd int) error { //sys Dup3(oldfd int, newfd int, flags int) (err error) //sysnb EpollCreate1(flag int) (fd int, err error) //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) +//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2 //sys Exit(code int) = SYS_EXIT_GROUP //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go index 506dafa7b..210d545c9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -20,7 +20,6 @@ func setTimeval(sec, usec int64) Timeval { // 64-bit file system and 32-bit uid calls // (386 default is 32-bit file system and 16-bit uid). -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index d557cf8de..a9a52f231 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index ecf92bfa2..54474c20f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -44,7 +44,6 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { // 64-bit file system and 32-bit uid calls // (16-bit uid calls are not always supported in newer kernels) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index 173738077..e9f30db97 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index a3fd1d0b8..6f09ca200 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index 70963a95a..ca3b56597 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index c218ebd28..54ba667b1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -13,7 +13,6 @@ import ( func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go index e6c48500c..ce4628590 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go @@ -11,7 +11,6 @@ import ( "unsafe" ) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go index 7286a9aa8..33f7af380 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index fc5543c5f..c658871e3 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -8,7 +8,6 @@ package unix import "unsafe" -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go index 66f31210d..2c8587691 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go @@ -10,7 +10,6 @@ import ( "unsafe" ) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 11d1f1698..4964119af 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -6,7 +6,6 @@ package unix -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 9d72a6b73..5bb51d7ae 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -1359,6 +1359,7 @@ const ( FAN_UNLIMITED_MARKS = 0x20 FAN_UNLIMITED_QUEUE = 0x10 FD_CLOEXEC = 0x1 + FD_PIDFS_ROOT = -0x2712 FD_SETSIZE = 0x400 FF0 = 0x0 FIB_RULE_DEV_DETACHED = 0x8 @@ -1970,6 +1971,8 @@ const ( MADV_DONTNEED = 0x4 MADV_DONTNEED_LOCKED = 0x18 MADV_FREE = 0x8 + MADV_GUARD_INSTALL = 0x66 + MADV_GUARD_REMOVE = 0x67 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_KEEPONFORK = 0x13 @@ -2114,7 +2117,7 @@ const ( MS_NOSEC = 0x10000000 MS_NOSUID = 0x2 MS_NOSYMFOLLOW = 0x100 - MS_NOUSER = -0x80000000 + MS_NOUSER = 0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 @@ -3786,6 +3789,9 @@ const ( TCPOPT_TIMESTAMP = 0x8 TCPOPT_TSTAMP_HDR = 0x101080a TCPOPT_WINDOW = 0x3 + TCP_AO_KEYF_EXCLUDE_OPT = 0x2 + TCP_AO_KEYF_IFINDEX = 0x1 + TCP_AO_MAXKEYLEN = 0x50 TCP_CC_INFO = 0x1a TCP_CM_INQ = 0x24 TCP_CONGESTION = 0xd diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 80f40e401..5788c2a58 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -700,6 +700,23 @@ func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + var _p0 unsafe.Pointer + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Eventfd(initval uint, flags int) (fd int, err error) { r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 0) fd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 4def3e9fc..254f33988 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index fef2bc8ba..27c05db1a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index a9fd76a88..840d85bfc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -213,23 +213,6 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index 460065028..fe414498b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go index c8987d264..eb358ce05 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index 921f43061..c437622f1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset>>32), uintptr(offset), uintptr(length>>32), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index 44f067829..bc4ca2558 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index e7fa0abf0..5051435ce 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index 8c5125675..33aa5418a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go index 7392fd45e..3bef8ef1d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index 41180434e..fc1bd4e2c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 40c6ce7ae..d78fe7dab 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go index 2cfe34adb..76dcf87d0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_PWAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 61e6f0709..2cf020f2b 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 834b84204..527637623 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -45,23 +45,6 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 6c955cea1..783621561 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -1109,17 +1109,53 @@ const ( ) // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. +// +// Go pointers stored in a TrusteeValue must be pinned using [runtime.Pinner] +// for the lifetime of the TrusteeValue. type TrusteeValue uintptr +// TrusteeValueFromString is unsafe and should not be used. +// +// It returns a uintptr containing a reference to newly-allocated memory +// which will be freed by the garbage collector. +// There is no way for the caller to safely reference this memory. +// +// To create a [TrusteeValue] from a string, use: +// +// p, err := windows.UTF16PtrFromString(s) +// if err != nil { +// // handle error +// } +// +// // Pin the string for as long as it is used. +// var pinner runtime.Pinner +// pinner.Pin(p) +// defer pinner.Unpin() +// +// tv := TrusteeValue(unsafe.Pointer(p)) +// +// Deprecated: TrusteeValueFromString is unsafe and should not be used. func TrusteeValueFromString(str string) TrusteeValue { return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str))) } + +// TrusteeValueFromSID returns a [TrusteeValue] referencing sid. +// +// The caller must pin sid using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromSID(sid *SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(sid)) } + +// TrusteeValueFromObjectsAndSid returns a [TrusteeValue] referencing objectsAndSid. +// +// The caller must pin objectsAndSid using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndSid)) } + +// TrusteeValueFromObjectsAndName returns a [TrusteeValue] referencing objectsAndName. +// +// The caller must pin objectsAndName using a [runtime.Pinner] for the lifetime of the TrusteeValue. func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndName)) } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 9755bca9f..e6966b4c3 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -1728,11 +1728,15 @@ func (s *NTUnicodeString) String() string { // the more common *uint16 string type. func NewNTString(s string) (*NTString, error) { var nts NTString - s8, err := BytePtrFromString(s) + s8, err := ByteSliceFromString(s) if err != nil { return nil, err } - RtlInitString(&nts, s8) + // The source string plus its terminating NUL must fit within MAX_USHORT. + if len(s8) > MAX_USHORT { + return nil, syscall.EINVAL + } + RtlInitString(&nts, &s8[0]) return &nts, nil } diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index d2574a73e..75a50b316 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -169,6 +169,7 @@ const ( FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192 FORMAT_MESSAGE_MAX_WIDTH_MASK = 255 + MAX_USHORT = 0xffff MAX_PATH = 260 MAX_LONG_PATH = 32768 diff --git a/vendor/golang.org/x/text/cases/context.go b/vendor/golang.org/x/text/cases/context.go index e9aa9e193..a28f45d7b 100644 --- a/vendor/golang.org/x/text/cases/context.go +++ b/vendor/golang.org/x/text/cases/context.go @@ -249,7 +249,7 @@ func upper(c *context) bool { return c.copy() } -// isUpper writes the isUppercase version of the current rune to dst. +// isUpper reports whether the current rune is in upper case. func isUpper(c *context) bool { ct := c.caseType() if c.info&hasMappingMask == 0 || ct == cUpper { diff --git a/vendor/golang.org/x/text/cases/map.go b/vendor/golang.org/x/text/cases/map.go index 0f7c6a14b..51a683092 100644 --- a/vendor/golang.org/x/text/cases/map.go +++ b/vendor/golang.org/x/text/cases/map.go @@ -774,7 +774,7 @@ func nlTitle(c *context) bool { // From CLDR: // # Special titlecasing for Dutch initial "ij". // ::Any-Title(); - // # Fix up Ij at the beginning of a "word" (per Any-Title, notUAX #29) + // # Fix up Ij at the beginning of a "word" (per Any-Title, not UAX #29) // [:^WB=ALetter:] [:WB=Extend:]* [[:WB=MidLetter:][:WB=MidNumLet:]]? { Ij } → IJ ; if c.src[c.pSrc] != 'I' && c.src[c.pSrc] != 'i' { return title(c) @@ -794,7 +794,7 @@ func nlTitleSpan(c *context) bool { // From CLDR: // # Special titlecasing for Dutch initial "ij". // ::Any-Title(); - // # Fix up Ij at the beginning of a "word" (per Any-Title, notUAX #29) + // # Fix up Ij at the beginning of a "word" (per Any-Title, not UAX #29) // [:^WB=ALetter:] [:WB=Extend:]* [[:WB=MidLetter:][:WB=MidNumLet:]]? { Ij } → IJ ; if c.src[c.pSrc] != 'I' { return isTitle(c) diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo.go b/vendor/golang.org/x/text/unicode/norm/forminfo.go index f3a234e5f..b3cf5d9bd 100644 --- a/vendor/golang.org/x/text/unicode/norm/forminfo.go +++ b/vendor/golang.org/x/text/unicode/norm/forminfo.go @@ -121,8 +121,12 @@ func (p Properties) BoundaryAfter() bool { // // When all 6 bits are zero, the character is inert, meaning it is never // influenced by normalization. +// +// We set flags to 0x80 (high bit 7 unused in quick check data) to indicate an invalid rune. type qcInfo uint8 +func (p Properties) isInvalid() bool { return p.flags == 0x80 } + func (p Properties) isYesC() bool { return p.flags&0x10 == 0 } func (p Properties) isYesD() bool { return p.flags&0x4 == 0 } @@ -247,6 +251,9 @@ func (f Form) PropertiesString(s string) Properties { // to a Properties. See the comment at the top of the file // for more information on the format. func compInfo(v uint16, sz int) Properties { + if sz == 0 { + return Properties{flags: 0x80, size: 1} + } if v == 0 { return Properties{size: uint8(sz)} } else if v >= 0x8000 { @@ -254,7 +261,7 @@ func compInfo(v uint16, sz int) Properties { size: uint8(sz), ccc: uint8(v), tccc: uint8(v), - flags: qcInfo(v >> 8), + flags: qcInfo(v>>8) & 0x3f, } if p.ccc > 0 || p.combinesBackward() { p.nLead = uint8(p.flags & 0x3) diff --git a/vendor/golang.org/x/text/unicode/norm/iter.go b/vendor/golang.org/x/text/unicode/norm/iter.go index 417c6b268..3cc059224 100644 --- a/vendor/golang.org/x/text/unicode/norm/iter.go +++ b/vendor/golang.org/x/text/unicode/norm/iter.go @@ -376,16 +376,12 @@ func nextComposed(i *Iter) []byte { goto doNorm } prevCC = i.info.tccc - sz := int(i.info.size) - if sz == 0 { - sz = 1 // illegal rune: copy byte-by-byte - } - p := outp + sz + p := outp + int(i.info.size) if p > len(i.buf) { break } outp = p - i.p += sz + i.p += int(i.info.size) if i.p >= i.rb.nsrc { i.setDone() break diff --git a/vendor/golang.org/x/text/unicode/norm/normalize.go b/vendor/golang.org/x/text/unicode/norm/normalize.go index 4747ad07a..60b1511ca 100644 --- a/vendor/golang.org/x/text/unicode/norm/normalize.go +++ b/vendor/golang.org/x/text/unicode/norm/normalize.go @@ -148,7 +148,7 @@ func (f Form) IsNormalString(s string) bool { // patched buffer and whether the decomposition is still in progress. func patchTail(rb *reorderBuffer) bool { info, p := lastRuneStart(&rb.f, rb.out) - if p == -1 || info.size == 0 { + if p == -1 || info.isInvalid() { return true } end := p + int(info.size) @@ -225,7 +225,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte { } fd := &rb.f if doMerge { - var info Properties + info := Properties{flags: 0x80, size: 1} // invalid rune if p < n { info = fd.info(src, p) if !info.BoundaryBefore() || info.nLeadingNonStarters() > 0 { @@ -235,7 +235,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte { p = decomposeSegment(rb, p, true) } } - if info.size == 0 { + if info.isInvalid() { rb.doFlush() // Append incomplete UTF-8 encoding. return src.appendSlice(rb.out, p, n) @@ -314,7 +314,7 @@ func (f *formInfo) quickSpan(src input, i, end int, atEOF bool) (n int, ok bool) continue } info := f.info(src, i) - if info.size == 0 { + if info.isInvalid() { if atEOF { // include incomplete runes return n, true @@ -379,7 +379,7 @@ func (f Form) firstBoundary(src input, nsrc int) int { // CGJ insertion points correctly. Luckily it doesn't have to. for { info := fd.info(src, i) - if info.size == 0 { + if info.isInvalid() { return -1 } if s := ss.next(info); s != ssSuccess { @@ -424,7 +424,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int { } fd := formTable[f] info := fd.info(src, 0) - if info.size == 0 { + if info.isInvalid() { if atEOF { return 1 } @@ -435,7 +435,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int { for i := int(info.size); i < nsrc; i += int(info.size) { info = fd.info(src, i) - if info.size == 0 { + if info.isInvalid() { if atEOF { return i } @@ -465,7 +465,7 @@ func lastBoundary(fd *formInfo, b []byte) int { if p == -1 { return -1 } - if info.size == 0 { // ends with incomplete rune + if info.isInvalid() { // ends with incomplete rune if p == 0 { // starts with incomplete rune return -1 } @@ -504,7 +504,7 @@ func lastBoundary(fd *formInfo, b []byte) int { func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int { // Force one character to be consumed. info := rb.f.info(rb.src, sp) - if info.size == 0 { + if info.isInvalid() { return 0 } if s := rb.ss.next(info); s == ssStarter { @@ -528,7 +528,7 @@ func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int { break } info = rb.f.info(rb.src, sp) - if info.size == 0 { + if info.isInvalid() { if !atEOF { return int(iShortSrc) } diff --git a/vendor/modules.txt b/vendor/modules.txt index 2c60d9282..005d79a73 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -48,7 +48,7 @@ github.com/fatih/color # github.com/gdamore/encoding v1.0.1 ## explicit; go 1.9 github.com/gdamore/encoding -# github.com/gdamore/tcell/v3 v3.4.1-0.20260703153331-243630d2fb59 +# github.com/gdamore/tcell/v3 v3.4.1 ## explicit; go 1.25.0 github.com/gdamore/tcell/v3 github.com/gdamore/tcell/v3/color @@ -175,27 +175,25 @@ github.com/xo/terminfo ## explicit; go 1.20 golang.org/x/exp/constraints golang.org/x/exp/slices -# golang.org/x/mod v0.36.0 +# golang.org/x/mod v0.37.0 ## explicit; go 1.25.0 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/net v0.55.0 -## explicit; go 1.25.0 -# golang.org/x/sync v0.21.0 +# golang.org/x/sync v0.22.0 ## explicit; go 1.25.0 golang.org/x/sync/errgroup golang.org/x/sync/semaphore -# golang.org/x/sys v0.46.0 +# golang.org/x/sys v0.47.0 ## explicit; go 1.25.0 golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.44.0 +# golang.org/x/term v0.45.0 ## explicit; go 1.25.0 golang.org/x/term -# golang.org/x/text v0.38.0 +# golang.org/x/text v0.40.0 ## explicit; go 1.25.0 golang.org/x/text/cases golang.org/x/text/encoding @@ -208,7 +206,7 @@ golang.org/x/text/language golang.org/x/text/runes golang.org/x/text/transform golang.org/x/text/unicode/norm -# golang.org/x/tools v0.45.0 +# golang.org/x/tools v0.47.0 ## explicit; go 1.25.0 golang.org/x/tools/go/ast/astutil # gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c From 46c1fa7db28d1b9399dfb6df2dcce76ab1865755 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 9 Jul 2026 19:11:33 +0200 Subject: [PATCH 194/218] Don't let a leaked subprocess wedge the headless test runner When lazygit exits but leaves behind a subprocess that inherited its stderr pipe and has detached from the pty, cmd.Wait() blocks in awaitGoroutines waiting for that pipe to reach EOF -- which never happens while the straggler is alive. With no WaitDelay set, that wait is unbounded, so a single leaked process hangs the whole test binary until the 10-minute global timeout fires and panics. Worse, the timeout discards whatever lazygit wrote to stderr before exiting (a panic, a -race report), which is exactly the output needed to diagnose the failure. This surfaces under -race, where lazygit runs slow enough to widen the window for a spawned command to still be alive when lazygit quits, and it's a blocker for enabling the race detector on CI. Bound the wait with cmd.WaitDelay so Wait force-closes the pipe and returns ErrWaitDelay instead of hanging, surface the captured stderr as the error (falling back to the wait error when nothing was printed), and kill the child's process group on failure so a straggler can't linger into a later test or pile up across a run. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/integration/clients/go_test.go | 39 +++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/pkg/integration/clients/go_test.go b/pkg/integration/clients/go_test.go index 11f6e754e..d3f15b88a 100644 --- a/pkg/integration/clients/go_test.go +++ b/pkg/integration/clients/go_test.go @@ -11,7 +11,9 @@ import ( "io" "os" "os/exec" + "syscall" "testing" + "time" "github.com/creack/pty" "github.com/jesseduffield/lazycore/pkg/utils" @@ -75,6 +77,17 @@ func runCmdHeadless(cmd *exec.Cmd) (int, error) { stderr := new(bytes.Buffer) cmd.Stderr = stderr + // If lazygit exits but leaves behind a subprocess that inherited its stderr + // pipe, cmd.Wait blocks waiting for that pipe to reach EOF for as long as the + // subprocess stays alive. Unbounded, that hangs the whole test binary until + // its global timeout fires, and the timeout throws away whatever lazygit + // wrote to stderr before exiting (a panic, a -race report) -- the very output + // needed to diagnose the failure. WaitDelay caps the wait: once the process + // has exited, Wait gives the stderr goroutine at most this long to drain, + // then closes the pipe and returns ErrWaitDelay, so the captured stderr + // surfaces as the test error instead of being lost. + cmd.WaitDelay = 5 * time.Second + // these rows and columns are ignored because internally we use tcell's // simulation screen. However we still need the pty for the sake of // running other commands in a pty. @@ -83,12 +96,32 @@ func runCmdHeadless(cmd *exec.Cmd) (int, error) { return -1, err } + // pty.StartWithSize starts lazygit in its own process group, so we can signal + // the whole group at once. Capture the id now, while the process is alive: + // once Wait has reaped it we can no longer look it up. + pgid, pgidErr := syscall.Getpgid(cmd.Process.Pid) + _, _ = io.Copy(io.Discard, f) - if cmd.Wait() != nil { + waitErr := cmd.Wait() + + // On any failure -- including a WaitDelay expiry caused by a leaked + // subprocess -- kill the whole process group so a straggler can't linger and + // wedge a later test or pile up across a CI run. Best effort: usually the + // group is already gone (ESRCH), and a subprocess that called setsid to + // detach into its own group is out of reach, but WaitDelay still unblocks us. + if waitErr != nil && pgidErr == nil { + _ = syscall.Kill(-pgid, syscall.SIGKILL) + } + + if waitErr != nil { _ = f.Close() - // return an error with the stderr output - return cmd.Process.Pid, errors.New(stderr.String()) + // Prefer lazygit's own stderr as the error; fall back to the wait error + // itself (e.g. ErrWaitDelay) when it exited without printing anything. + if stderr.Len() > 0 { + return cmd.Process.Pid, errors.New(stderr.String()) + } + return cmd.Process.Pid, waitErr } return cmd.Process.Pid, f.Close() From 7fce58b09bc7b9bb61cbd8c3950579121a0bb832 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 12:55:36 +0200 Subject: [PATCH 195/218] Scale the integration test watchdog up under the race detector The integration test watchdog fails a test if its recording takes longer than 40 seconds. Under the race detector everything runs several times slower, so legitimately slow tests (e.g. a conflicting interactive rebase) blow that budget and fail even though nothing is actually stuck. Key the timeout off a build-tag constant: the `race` tag is set automatically when the binary is built with -race, so a race build gets a 5x-longer budget while a normal build is unchanged, and the two can't drift apart the way a runtime flag would. The base 40s stays in one place; only the multiplier varies by build. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/test_mode.go | 5 +++-- pkg/gui/test_timeout_norace.go | 5 +++++ pkg/gui/test_timeout_race.go | 10 ++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 pkg/gui/test_timeout_norace.go create mode 100644 pkg/gui/test_timeout_race.go diff --git a/pkg/gui/test_mode.go b/pkg/gui/test_mode.go index d6893c92d..0b24bb8cd 100644 --- a/pkg/gui/test_mode.go +++ b/pkg/gui/test_mode.go @@ -45,9 +45,10 @@ func (gui *Gui) handleTestMode() { }() if os.Getenv(components.WAIT_FOR_DEBUGGER_ENV_VAR) == "" { + timeout := 40 * time.Second * testTimeoutMultiplier go utils.Safe(func() { - time.Sleep(time.Second * 40) - log.Fatal("40 seconds is up, lazygit recording took too long to complete") + time.Sleep(timeout) + log.Fatalf("%v is up, lazygit integration test took too long to complete", timeout) }) } } diff --git a/pkg/gui/test_timeout_norace.go b/pkg/gui/test_timeout_norace.go new file mode 100644 index 000000000..7f924ea71 --- /dev/null +++ b/pkg/gui/test_timeout_norace.go @@ -0,0 +1,5 @@ +//go:build !race + +package gui + +const testTimeoutMultiplier = 1 diff --git a/pkg/gui/test_timeout_race.go b/pkg/gui/test_timeout_race.go new file mode 100644 index 000000000..7d633def3 --- /dev/null +++ b/pkg/gui/test_timeout_race.go @@ -0,0 +1,10 @@ +//go:build race + +package gui + +// The race detector makes everything run several times slower, so the +// recording watchdog needs a correspondingly longer timeout; otherwise it +// fires on tests that are merely slow under -race rather than actually stuck. +// The `race` build tag is set automatically when the binary is built with +// -race, so this can't drift out of sync with the actual build. +const testTimeoutMultiplier = 4 From 334daccfab6e080df95b94678d33e607b106a850 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 15:29:28 +0200 Subject: [PATCH 196/218] Increase integration test timeout to 30 minutes Go's default 10-minute timeout was enough for running integration tests normally (both locally and on CI), but with race detection turned on they can take much longer to run. Increase the timeout unconditionally to 30 minutes; we don't bother making a distinction between race vs. normal, because a longer timeout doesn't hurt (I can't recall having hit the global timeout ever; and we still have the per-test watchdog that kills an individual test after 40s). --- justfile | 2 +- scripts/run_integration_tests.sh | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/justfile b/justfile index 64d9d1ee2..0851179b9 100644 --- a/justfile +++ b/justfile @@ -40,7 +40,7 @@ lint: ./scripts/gofumpt-check.sh ./scripts/golangci-lint-shim.sh run -e2e-test-command := "go test pkg/integration/clients/*.go" +e2e-test-command := "go test -timeout 30m pkg/integration/clients/*.go" # Run integration tests headlessly: no args runs all tests, a test name (or path) runs just that one. Use e2e-cli for a visible UI. e2e *args: diff --git a/scripts/run_integration_tests.sh b/scripts/run_integration_tests.sh index 579e6d77c..1dadeec97 100755 --- a/scripts/run_integration_tests.sh +++ b/scripts/run_integration_tests.sh @@ -19,7 +19,7 @@ if [ -n "$LAZYGIT_GOCOVERDIR" ]; then # hacky. To capture the coverage data for the test runner we pass the test.gocoverdir positional # arg, but if we do that then the GOCOVERDIR env var (which you typically pass to the test binary) will be overwritten by the test runner. So we're passing LAZYGIT_COCOVERDIR instead # and then internally passing that to the test binary as GOCOVERDIR. - go test -cover -coverpkg=github.com/jesseduffield/lazygit/pkg/... pkg/integration/clients/*.go -args -test.gocoverdir="/tmp/code_coverage" + go test -timeout 30m -cover -coverpkg=github.com/jesseduffield/lazygit/pkg/... pkg/integration/clients/*.go -args -test.gocoverdir="/tmp/code_coverage" EXITCODE=$? # We're merging the coverage data for the sake of having fewer artefacts to upload. @@ -29,7 +29,7 @@ if [ -n "$LAZYGIT_GOCOVERDIR" ]; then rm -rf /tmp/code_coverage mv /tmp/code_coverage_merged /tmp/code_coverage else - go test pkg/integration/clients/*.go + go test -timeout 30m pkg/integration/clients/*.go EXITCODE=$? fi From 840a66e7333ae412003b33cd9ff3799a251e92f9 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 13:09:40 +0200 Subject: [PATCH 197/218] Run the integration tests under the race detector on CI Add one extra integration-tests job that runs the whole suite under the race detector. A `race` matrix dimension (default false) plus an include entry adds a single git-latest job with LAZYGIT_RACE_DETECTOR set; races live in lazygit's own Go code rather than in git, so one git version is enough, and using latest skips the git-build steps. The race job skips coverage collection: it's redundant with the non-race latest job and would only slow the -race build down further. --- .github/workflows/ci.yml | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e7538b0d..d14778483 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,8 +53,16 @@ jobs: - 2.38.2 # first version that supports the rebase.updateRefs config - 2.44.0 - latest # We rely on github to have the latest version installed on their VMs + race: + - false + # Additionally run the whole suite once under the race detector. Data + # races live in lazygit's own Go code rather than in git, so a single + # git version is enough; use the latest to skip the git-build steps. + include: + - git-version: latest + race: true runs-on: ubuntu-latest - name: "Integration Tests - git ${{matrix.git-version}}" + name: "Integration Tests - git ${{matrix.git-version}}${{ matrix.race && ' (race)' || '' }}" env: GOFLAGS: -mod=vendor steps: @@ -92,12 +100,20 @@ jobs: run: git --version - name: Test code env: - # See https://go.dev/blog/integration-test-coverage - LAZYGIT_GOCOVERDIR: /tmp/code_coverage + # See https://go.dev/blog/integration-test-coverage. The race variant + # skips coverage: it's redundant with the non-race latest job and + # would only slow the -race build down further. Leaving the dir unset + # makes run_integration_tests.sh take its non-coverage path. + LAZYGIT_GOCOVERDIR: ${{ !matrix.race && '/tmp/code_coverage' || '' }} + # Only set for the race variant. The race detector needs cgo; it's on + # by default on the Linux runner, but we set it explicitly to be safe. + LAZYGIT_RACE_DETECTOR: ${{ matrix.race && '1' || '' }} + CGO_ENABLED: ${{ matrix.race && '1' || '' }} run: | mkdir -p /tmp/code_coverage ./scripts/run_integration_tests.sh - name: Upload code coverage artifacts + if: ${{ !matrix.race }} uses: actions/upload-artifact@v7 with: name: coverage-integration-${{ matrix.git-version }}-${{ github.run_id }} From 03a914c04c713df8b7dbb504f2154185047675cb Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 17:28:19 +0200 Subject: [PATCH 198/218] Dump goroutine stacks when the test watchdog fires The watchdog only log.Fatal'd with a message, so a hung test told us that it timed out but not where it was stuck -- useless for diagnosing an intermittent deadlock under the race detector. Dump all goroutine stacks to stderr first (the harness surfaces this process's stderr on failure), turning a bare timeout into an actionable stack trace. Co-Authored-By: Claude Opus 4.8 (1M context) --- pkg/gui/test_mode.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/gui/test_mode.go b/pkg/gui/test_mode.go index 0b24bb8cd..2644e989b 100644 --- a/pkg/gui/test_mode.go +++ b/pkg/gui/test_mode.go @@ -3,6 +3,7 @@ package gui import ( "log" "os" + "runtime/pprof" "time" "github.com/jesseduffield/lazygit/pkg/gocui" @@ -48,6 +49,10 @@ func (gui *Gui) handleTestMode() { timeout := 40 * time.Second * testTimeoutMultiplier go utils.Safe(func() { time.Sleep(timeout) + // Dump all goroutine stacks before dying, so a hung test shows + // where it got stuck rather than just that it timed out. The + // test harness surfaces this process's stderr on failure. + _ = pprof.Lookup("goroutine").WriteTo(os.Stderr, 2) log.Fatalf("%v is up, lazygit integration test took too long to complete", timeout) }) } From b6b5436d571d377af1e487dee871fad101a46a25 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Fri, 10 Jul 2026 17:28:19 +0200 Subject: [PATCH 199/218] Log per-test durations during integration tests To spot slow or anomalous tests across CI runs, record each test's run duration when LAZYGIT_TEST_TIMING is set (to a file path); run_integration_tests.sh prints them at the end, sorted by slowest first. CI sets it for all integration jobs. The harness appends to a file rather than writing to stdout/stderr because `go test` captures those and only surfaces them with -v, which would drown the signal in every test's verbose logs. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/workflows/ci.yml | 3 +++ pkg/integration/clients/go_test.go | 4 +++- pkg/integration/components/runner.go | 34 ++++++++++++++++++++++++++++ scripts/run_integration_tests.sh | 8 +++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d14778483..c6d2fdf6d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -109,6 +109,9 @@ jobs: # by default on the Linux runner, but we set it explicitly to be safe. LAZYGIT_RACE_DETECTOR: ${{ matrix.race && '1' || '' }} CGO_ENABLED: ${{ matrix.race && '1' || '' }} + # Append each test's duration to this file; run_integration_tests.sh + # prints the slowest at the end, to spot slow/anomalous tests. + LAZYGIT_TEST_TIMING: /tmp/test_timings.txt run: | mkdir -p /tmp/code_coverage ./scripts/run_integration_tests.sh diff --git a/pkg/integration/clients/go_test.go b/pkg/integration/clients/go_test.go index d3f15b88a..4c1faa557 100644 --- a/pkg/integration/clients/go_test.go +++ b/pkg/integration/clients/go_test.go @@ -30,6 +30,7 @@ func TestIntegration(t *testing.T) { parallelTotal := tryConvert(os.Getenv("PARALLEL_TOTAL"), 1) parallelIndex := tryConvert(os.Getenv("PARALLEL_INDEX"), 0) raceDetector := os.Getenv("LAZYGIT_RACE_DETECTOR") != "" + logTimingsPath := os.Getenv("LAZYGIT_TEST_TIMING") // LAZYGIT_GOCOVERDIR is the directory where we write coverage files to. If this directory // is defined, go binaries built with the -cover flag will write coverage files to // to it. @@ -58,7 +59,8 @@ func TestIntegration(t *testing.T) { CodeCoverageDir: codeCoverageDir, InputDelay: 0, // Allow two attempts at each test to get around flakiness - MaxAttempts: 1, + MaxAttempts: 1, + LogTimingsPath: logTimingsPath, }) assert.NoError(t, err) diff --git a/pkg/integration/components/runner.go b/pkg/integration/components/runner.go index 5640c3e70..78cb5439f 100644 --- a/pkg/integration/components/runner.go +++ b/pkg/integration/components/runner.go @@ -5,6 +5,8 @@ import ( "os" "os/exec" "path/filepath" + "sync" + "time" lazycoreUtils "github.com/jesseduffield/lazycore/pkg/utils" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" @@ -24,6 +26,12 @@ type RunTestArgs struct { CodeCoverageDir string InputDelay int MaxAttempts int + // If set, each test's run duration is appended to this file (as + // " "). run_integration_tests.sh prints the slowest at + // the end, so slow or anomalous tests can be spotted across CI runs. We + // write to a file rather than stdout/stderr because `go test` captures + // those and only shows them with -v. Empty disables it. + LogTimingsPath string } // This function lets you run tests either from within `go test` or from a regular binary. @@ -47,6 +55,11 @@ func RunTests(args RunTestArgs) error { return err } + // Start each run with a fresh timings file (see RunTestArgs.LogTimingsPath). + if args.LogTimingsPath != "" { + _ = os.Remove(args.LogTimingsPath) + } + for _, test := range args.Tests { args.TestWrapper(test, func() error { paths := NewPaths( @@ -99,7 +112,11 @@ func runTest( return err } + start := time.Now() pid, err := args.RunCmd(cmd) + if args.LogTimingsPath != "" { + logTestTiming(args.LogTimingsPath, test.Name(), time.Since(start)) + } // Print race detector log regardless of the command's exit status if args.RaceDetector { @@ -112,6 +129,23 @@ func runTest( return err } +// timingsMutex serializes appends to the timings file, since tests run in +// parallel. +var timingsMutex sync.Mutex + +func logTestTiming(path, name string, duration time.Duration) { + timingsMutex.Lock() + defer timingsMutex.Unlock() + + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + + fmt.Fprintf(f, "%.2f %s\n", duration.Seconds(), name) +} + func prepareTestDir( test *IntegrationTest, paths Paths, diff --git a/scripts/run_integration_tests.sh b/scripts/run_integration_tests.sh index 1dadeec97..2bf010f19 100755 --- a/scripts/run_integration_tests.sh +++ b/scripts/run_integration_tests.sh @@ -37,4 +37,12 @@ if test -f ~/.gitconfig.lazygit.bak; then mv ~/.gitconfig.lazygit.bak ~/.gitconfig fi +# If per-test timings were collected (LAZYGIT_TEST_TIMING points at the file the +# harness appends to), print them sorted by slowest first so they show up in the +# CI log. +if [ -n "$LAZYGIT_TEST_TIMING" ] && [ -f "$LAZYGIT_TEST_TIMING" ]; then + echo "Test timings (seconds):" + sort -rn "$LAZYGIT_TEST_TIMING" +fi + exit $EXITCODE From 132f656480671ac83ade3528fcb475422d551ee4 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 22:54:12 +0200 Subject: [PATCH 200/218] Run nested-submodule commands in the parent module's directory explicitly Deleting a nested submodule (and updating its URL) chdir'd the whole process into the parent module, ran its git commands there, and chdir'd back. Only those commands need to run there, and a process-wide chdir leaks the parent module's directory into any command another goroutine spawns during that window (e.g. a background refresh's). Set the directory on the commands themselves instead. Co-Authored-By: Claude Fable 5 --- pkg/commands/git_commands/submodule.go | 62 ++++++++++---------------- 1 file changed, 24 insertions(+), 38 deletions(-) diff --git a/pkg/commands/git_commands/submodule.go b/pkg/commands/git_commands/submodule.go index 3b88e4fbb..3eb081701 100644 --- a/pkg/commands/git_commands/submodule.go +++ b/pkg/commands/git_commands/submodule.go @@ -213,51 +213,51 @@ func (self *SubmoduleCommands) UpdateAll() error { return self.cmd.New(cmdArgs).Run() } +// runInParentModule runs the given command in the submodule's parent module's +// directory when the submodule is nested: its path arguments (and the +// .gitmodules file the config commands touch) are relative to the parent +// module. The directory is set on the command itself rather than by +// temporarily chdir-ing the process there, which would leak the parent +// module's directory into whatever other commands run concurrently (e.g. a +// background refresh's). +func (self *SubmoduleCommands) runInParentModule(submodule *models.SubmoduleConfig, cmdObj *oscommands.CmdObj) error { + if submodule.ParentModule != nil { + cmdObj.SetWd(submodule.ParentModule.FullPath()) + } + return cmdObj.Run() +} + func (self *SubmoduleCommands) Delete(submodule *models.SubmoduleConfig) error { // based on https://gist.github.com/myusuf3/7f645819ded92bda6677 - if submodule.ParentModule != nil { - wd, err := os.Getwd() - if err != nil { - return err - } - - err = os.Chdir(submodule.ParentModule.FullPath()) - if err != nil { - return err - } - - defer func() { _ = os.Chdir(wd) }() - } - - if err := self.cmd.New( + if err := self.runInParentModule(submodule, self.cmd.New( NewGitCmd("submodule"). Arg("deinit", "--force", "--", submodule.Path).ToArgv(), - ).Run(); err != nil { + )); err != nil { if !strings.Contains(err.Error(), "did not match any file(s) known to git") { return err } - if err := self.cmd.New( + if err := self.runInParentModule(submodule, self.cmd.New( NewGitCmd("config"). Arg("--file", ".gitmodules", "--remove-section", "submodule."+submodule.Path). ToArgv(), - ).Run(); err != nil { + )); err != nil { return err } - if err := self.cmd.New( + if err := self.runInParentModule(submodule, self.cmd.New( NewGitCmd("config"). Arg("--remove-section", "submodule."+submodule.Path). ToArgv(), - ).Run(); err != nil { + )); err != nil { return err } } - if err := self.cmd.New( + if err := self.runInParentModule(submodule, self.cmd.New( NewGitCmd("rm").Arg("--force", "-r", submodule.Path).ToArgv(), - ).Run(); err != nil { + )); err != nil { // if the directory isn't there then that's fine self.Log.Error(err) } @@ -282,20 +282,6 @@ func (self *SubmoduleCommands) Add(name string, path string, url string) error { } func (self *SubmoduleCommands) UpdateUrl(submodule *models.SubmoduleConfig, newUrl string) error { - if submodule.ParentModule != nil { - wd, err := os.Getwd() - if err != nil { - return err - } - - err = os.Chdir(submodule.ParentModule.FullPath()) - if err != nil { - return err - } - - defer func() { _ = os.Chdir(wd) }() - } - setUrlCmdStr := NewGitCmd("config"). Arg( "--file", ".gitmodules", "submodule."+submodule.Name+".url", newUrl, @@ -303,14 +289,14 @@ func (self *SubmoduleCommands) UpdateUrl(submodule *models.SubmoduleConfig, newU ToArgv() // the set-url command is only for later git versions so we're doing it manually here - if err := self.cmd.New(setUrlCmdStr).Run(); err != nil { + if err := self.runInParentModule(submodule, self.cmd.New(setUrlCmdStr)); err != nil { return err } syncCmdStr := NewGitCmd("submodule").Arg("sync", "--", submodule.Path). ToArgv() - if err := self.cmd.New(syncCmdStr).Run(); err != nil { + if err := self.runInParentModule(submodule, self.cmd.New(syncCmdStr)); err != nil { return err } From 096a710761ad2210466423ad869306afa741f135 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 20 Jul 2026 12:08:42 +0200 Subject: [PATCH 201/218] Refresh pull requests through the regular refresh after picking a base remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the user picks a base remote in the "select remote repository" prompt, we called setGithubPullRequests directly, bypassing the refresh machinery — which meant hand-rolling the refresh env that call needs (with a comment explaining why), and fetching against the branches captured when the prompt was created. Issue a PULL_REQUESTS-scoped refresh instead: it re-reads branches and remotes (both fast even in large repos), fetches against those fresh values, and gets the refresh machinery's guarantees without any special-casing. The config write is re-read by the refresh from git config, so it is guaranteed to be picked up. The waiting status now covers the config write and the branches/remotes reload, while the GitHub request itself continues as a background task — which is how every other pull-request fetch behaves. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index a7c18aeb8..497eca28a 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1536,7 +1536,7 @@ func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, clearPullRequests() if !self.githubBaseRemotePromptDismissed[self.c.Git().RepoPaths.RepoPath()] { - self.promptForBaseGithubRepo(githubRemotes, branches) + self.promptForBaseGithubRepo(githubRemotes) } return } @@ -1612,7 +1612,7 @@ func getGithubBaseRemote(githubRemotes []githubRemoteInfo, configuredRemoteName return nil } -func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteInfo, branches []*models.Branch) { +func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteInfo) { menuItems := lo.Map(githubRemotes, func(info githubRemoteInfo, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{info.remote.Name, style.FgCyan.Sprint(info.serviceInfo.RepoName)}, @@ -1622,11 +1622,7 @@ func (self *RefreshHelper) promptForBaseGithubRepo(githubRemotes []githubRemoteI self.c.Log.Error(err) } - // This fetch runs on its own worker after the user picked a - // base remote, so it's not part of a performRefresh and has no - // ambient env; build a foreground one now, capturing the - // current generation as the guard baseline. - self.setGithubPullRequests(&info, branches, refreshEnv{generation: self.c.State().GetRepoGeneration()}) + self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.PULL_REQUESTS}}) return nil }) }, From 527124d0e0e41c41edb7829a243f64399f82e807 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 22:14:08 +0200 Subject: [PATCH 202/218] Pin git commands to the repo they were created for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lazygit changes the process working directory when switching repos, but work that is still in flight for the previous repo can keep spawning git commands after the switch — most notably a background refresh. Its model writes are already dropped by the repo generation guard, but its git commands would now run against the new repo. That is wasted work at best; at worst it surfaces spurious error popups (the behind-base- branch computation failing with "no such ref" when the old repo's main branch doesn't exist in the new one) and pollutes caches belonging to the old repo's reusable state (e.g. MainBranches' existing-branches cache), which the user sees when switching back. Give the git command builder the directory of the repo it was created for, and pin every command it produces to that directory. The pinned directory and the process cwd are identical until a switch happens (NewGitCommand chdirs to the worktree path right before creating the builder), so nothing changes in the steady state; the pin only takes effect for commands built through a previous repo's GitCommand instance after a switch, which now keep addressing the repo they were built for. Co-Authored-By: Claude Fable 5 --- pkg/commands/git.go | 2 +- pkg/commands/git_cmd_obj_builder.go | 16 +++++++++++++--- pkg/commands/git_cmd_obj_builder_test.go | 17 +++++++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/pkg/commands/git.go b/pkg/commands/git.go index d9add2790..7ba2dba66 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -90,7 +90,7 @@ func NewGitCommandAux( repoPaths *git_commands.RepoPaths, pagerConfig *config.PagerConfig, ) *GitCommand { - cmd := NewGitCmdObjBuilder(cmn.Log, osCommand.Cmd) + cmd := NewGitCmdObjBuilder(cmn.Log, osCommand.Cmd, repoPaths.WorktreePath()) // here we're doing a bunch of dependency injection for each of our commands structs. // This is admittedly messy, but allows us to test each command struct in isolation, diff --git a/pkg/commands/git_cmd_obj_builder.go b/pkg/commands/git_cmd_obj_builder.go index 20d31c11c..9c3cd50d4 100644 --- a/pkg/commands/git_cmd_obj_builder.go +++ b/pkg/commands/git_cmd_obj_builder.go @@ -11,6 +11,15 @@ import ( type gitCmdObjBuilder struct { innerBuilder *oscommands.CmdObjBuilder + + // The directory of the repo (or worktree) this builder was created for; + // every command we produce runs there, regardless of the process's current + // working directory. The two are the same until the user switches to + // another repo: lazygit chdirs on a switch, but work still in flight for + // the previous repo (e.g. a background refresh spawning commands through + // the old builder) must keep running its commands against the repo it + // started in, not whichever one the process has since moved to. + repoDir string } var _ oscommands.ICmdObjBuilder = &gitCmdObjBuilder{} @@ -21,7 +30,7 @@ var _ oscommands.ICmdObjBuilder = &gitCmdObjBuilder{} // only the foreground files refresh) opt back in via CmdObj.RemoveEnvVar. var defaultEnvVar = git_commands.OptionalLocksEnvVar + "=0" -func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder) *gitCmdObjBuilder { +func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder, repoDir string) *gitCmdObjBuilder { // the price of having a convenient interface where we can say .New(...).Run() is that our builder now depends on our runner, so when we want to wrap the default builder/runner in new functionality we need to jump through some hoops. We could avoid the use of a decorator function here by just exporting the runner field on the default builder but that would be misleading because we don't want anybody using that to run commands (i.e. we want there to be a single API used across the codebase) updatedBuilder := innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner { return &gitCmdObjRunner{ @@ -33,15 +42,16 @@ func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuild return &gitCmdObjBuilder{ innerBuilder: updatedBuilder, + repoDir: repoDir, } } func (self *gitCmdObjBuilder) New(args []string) *oscommands.CmdObj { - return self.innerBuilder.New(args).AddEnvVars(defaultEnvVar) + return self.innerBuilder.New(args).AddEnvVars(defaultEnvVar).SetWd(self.repoDir) } func (self *gitCmdObjBuilder) NewShell(cmdStr string, shellFunctionsFile string) *oscommands.CmdObj { - return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile).AddEnvVars(defaultEnvVar) + return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile).AddEnvVars(defaultEnvVar).SetWd(self.repoDir) } func (self *gitCmdObjBuilder) Quote(str string) string { diff --git a/pkg/commands/git_cmd_obj_builder_test.go b/pkg/commands/git_cmd_obj_builder_test.go index ca7e54cfe..28e21501c 100644 --- a/pkg/commands/git_cmd_obj_builder_test.go +++ b/pkg/commands/git_cmd_obj_builder_test.go @@ -17,8 +17,25 @@ func TestGitCmdObjBuilderDisablesOptionalLocksByDefault(t *testing.T) { builder := NewGitCmdObjBuilder( utils.NewDummyLog(), oscommands.NewDummyCmdObjBuilder(oscommands.NewFakeRunner(t)), + "/path/to/repo", ) assert.Contains(t, builder.New([]string{"git", "status"}).GetEnvVars(), git_commands.OptionalLocksEnvVar+"=0") assert.Contains(t, builder.NewShell("git status", "").GetEnvVars(), git_commands.OptionalLocksEnvVar+"=0") } + +// Every command the builder produces runs in the directory of the repo the +// builder was created for, not in the process's current directory: lazygit +// chdirs when switching repos, and commands built for the previous repo after +// that (e.g. by a background refresh still in flight) must keep addressing the +// repo they were built for. +func TestGitCmdObjBuilderPinsCommandsToRepoDir(t *testing.T) { + builder := NewGitCmdObjBuilder( + utils.NewDummyLog(), + oscommands.NewDummyCmdObjBuilder(oscommands.NewFakeRunner(t)), + "/path/to/repo", + ) + + assert.Equal(t, "/path/to/repo", builder.New([]string{"git", "status"}).GetCmd().Dir) + assert.Equal(t, "/path/to/repo", builder.NewShell("git status", "").GetCmd().Dir) +} From 7c0fa9fe33d8a065c7a33d6f5cfe2dda0a51bd72 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 22:31:48 +0200 Subject: [PATCH 203/218] Run a refresh's git commands through the instance captured at its start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A background refresh's model writes are dropped by the generation guard when the repo is switched mid-flight, but its git commands kept running — and because the refresh read the live git instance at each step, any command issued after the switch ran against the new repo. Now that git commands are pinned to the directory of the instance they were built from, capture the instance once when the refresh starts and run every scope's git work through it, so a switch-crossing refresh keeps addressing the repo it was started for. The instance is captured together with the repo generation, on the UI thread (where repo switches run), so the pair can't straddle a switch: an old instance paired with the new generation would compute data from the old repo and write it into the new repo's model unguarded. This also removes the refresh workers' unsynchronized reads of the live instance pointer, which raced its reassignment on the UI thread when a background refresh crossed a repo switch (foreground refreshes can't cross one: they keep Busy() true, which refuses the switch). Two reads keyed app-state by the live instance's repo path on a worker and now use the captured instance, fixing which repo they file under when crossing a switch: the pull-request cache, and the "user dismissed the base-remote prompt" flag. The base-remote menu's handlers keep reading the live instance: a switch dismisses any open popup, so they can't run against the wrong repo (and the OnPress body runs under a foreground task, which blocks switching anyway). Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 117 +++++++++++------- 1 file changed, 70 insertions(+), 47 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 497eca28a..caf14ed2a 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -7,6 +7,7 @@ import ( "time" "github.com/jesseduffield/generics/set" + "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/hosting_service" "github.com/jesseduffield/lazygit/pkg/commands/models" @@ -97,6 +98,13 @@ type refreshEnv struct { // the repo generation captured when the refresh started generation int + // the git command instance captured when the refresh started. The refresh + // workers run their git commands through this rather than reading the live + // instance: a repo switch mid-refresh replaces the live instance (and the + // process cwd), while this one keeps addressing the repo the refresh was + // started for (its commands are pinned to that repo's directory). + git *commands.GitCommand + // When non-nil, each scope's UI-thread bounce is collected here instead of // being dispatched as it's produced, so they can all be applied in a single // frame once the whole refresh is done (see RefreshOptions.BatchUIUpdates). @@ -167,12 +175,23 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") } - // Capture the repo generation once, here at the start, so every scope's - // bounce is guarded against the same baseline. + // Capture the refresh's baseline once, here at the start: the repo + // generation that every scope's bounce is guarded against, and the git + // command instance the scopes run their commands through. The two are + // captured together on the UI thread so that they can't straddle a repo + // switch (which runs on the UI thread): pairing the old repo's instance + // with the new repo's generation would let a refresh compute data from + // the old repo and write it into the new repo's model unguarded. With a + // consistent pair, a switch-crossing refresh keeps running its commands + // against the repo it started in, and the generation guard drops its + // writes. env := refreshEnv{ background: options.Background, - generation: self.c.State().GetRepoGeneration(), } + self.captureOnUIThread(calledFromWorker, options.Background, func() { + env.generation = self.c.State().GetRepoGeneration() + env.git = self.c.Git() + }) if options.BatchUIUpdates { env.batch = &refreshBounceBatch{} } @@ -226,7 +245,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // of git's state changing externally while (or right after) we are // refreshing; the risk is one potential extra refresh, but capturing the // snapshot at the end would risk missing one, which is worse. - self.updateRefsSnapshotIfRelevant(scopeSet) + self.updateRefsSnapshotIfRelevant(scopeSet, env) wg := sync.WaitGroup{} refresh := func(name string, f func()) { @@ -515,12 +534,12 @@ func (self *RefreshHelper) RefsSnapshotChangedSince(snapshot string) bool { // We check just COMMITS and BRANCHES because the scope-expansion step at the // top of Refresh has already added these whenever REFLOG or BISECT_INFO are // in scope, and whenever a nil scope was passed. -func (self *RefreshHelper) updateRefsSnapshotIfRelevant(scopeSet *set.Set[types.RefreshableView]) { +func (self *RefreshHelper) updateRefsSnapshotIfRelevant(scopeSet *set.Set[types.RefreshableView], env refreshEnv) { if !scopeSet.Includes(types.COMMITS) && !scopeSet.Includes(types.BRANCHES) { return } - snapshot, err := self.c.Git().Status.RefsSnapshot() + snapshot, err := env.git.Status.RefsSnapshot() if err != nil { self.c.Log.Warnf("RefsSnapshot failed during refresh: %v", err) return @@ -704,15 +723,15 @@ func (self *RefreshHelper) refreshCommitsAndCommitFiles(captured capturedCommitS } } -func (self *RefreshHelper) determineCheckedOutRef() models.Ref { - if rebasedBranch := self.c.Git().Status.BranchBeingRebased(); rebasedBranch != "" { +func (self *RefreshHelper) determineCheckedOutRef(env refreshEnv) models.Ref { + if rebasedBranch := env.git.Status.BranchBeingRebased(); rebasedBranch != "" { // During a rebase we're on a detached head, so cannot determine the // branch name in the usual way. We need to read it from the // ".git/rebase-merge/head-name" file instead. return &models.Branch{Name: strings.TrimPrefix(rebasedBranch, "refs/heads/")} } - if bisectInfo := self.c.Git().Bisect.GetInfo(); bisectInfo.Bisecting() && bisectInfo.GetStartHash() != "" { + if bisectInfo := env.git.Bisect.GetInfo(); bisectInfo.Bisecting() && bisectInfo.GetStartHash() != "" { // Likewise, when we're bisecting we're on a detached head as well. In // this case we read the branch name from the ".git/BISECT_START" file. return &models.Branch{Name: bisectInfo.GetStartHash()} @@ -722,7 +741,7 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { // checked out. Note that if we're on a detached head (for reasons other // than rebasing or bisecting, i.e. it was explicitly checked out), then // this will return an empty string. - if branchName, err := self.c.Git().Branch.CurrentBranchName(); err == nil && branchName != "" { + if branchName, err := env.git.Branch.CurrentBranchName(); err == nil && branchName != "" { return &models.Branch{Name: branchName} } @@ -731,9 +750,9 @@ func (self *RefreshHelper) determineCheckedOutRef() models.Ref { } func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, commitSelection types.CommitSelectionBehavior, env refreshEnv) error { - checkedOutRef := self.determineCheckedOutRef() - refName, bisectInfo := self.refForLog() - commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( + checkedOutRef := self.determineCheckedOutRef(env) + refName, bisectInfo := self.refForLog(env) + commits, err := env.git.Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: captured.limitCommits, FilterPath: captured.filterPath, @@ -749,7 +768,7 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState, if err != nil { return err } - workingTreeState := self.c.Git().Status.WorkingTreeState() + workingTreeState := env.git.Status.WorkingTreeState() self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().BisectInfo = bisectInfo @@ -902,7 +921,7 @@ func (self *RefreshHelper) refreshSubCommitsWithLimit(captured capturedSubCommit return nil } - commits, err := self.c.Git().Loaders.CommitLoader.GetCommits( + commits, err := env.git.Loaders.CommitLoader.GetCommits( git_commands.GetCommitsOptions{ Limit: captured.limitCommits, FilterPath: captured.filterPath, @@ -956,7 +975,7 @@ func (self *RefreshHelper) captureCommitFilesState() capturedCommitFilesState { } func (self *RefreshHelper) refreshCommitFilesContext(captured capturedCommitFilesState, env refreshEnv) error { - files, err := self.c.Git().Loaders.CommitFileLoader.GetFilesInDiff(captured.from, captured.to, captured.reverse) + files, err := env.git.Loaders.CommitFileLoader.GetFilesInDiff(captured.from, captured.to, captured.reverse) if err != nil { return err } @@ -975,11 +994,11 @@ func (self *RefreshHelper) captureRebaseCommitState() (hashPool *utils.StringPoo } func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, commits []*models.Commit, env refreshEnv) error { - updatedCommits, err := self.c.Git().Loaders.CommitLoader.MergeRebasingCommits(hashPool, commits) + updatedCommits, err := env.git.Loaders.CommitLoader.MergeRebasingCommits(hashPool, commits) if err != nil { return err } - workingTreeState := self.c.Git().Status.WorkingTreeState() + workingTreeState := env.git.Status.WorkingTreeState() self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Commits = updatedCommits @@ -991,7 +1010,7 @@ func (self *RefreshHelper) refreshRebaseCommits(hashPool *utils.StringPool, comm } func (self *RefreshHelper) refreshTags(env refreshEnv) error { - tags, err := self.c.Git().Loaders.TagLoader.GetTags() + tags, err := env.git.Loaders.TagLoader.GetTags() if err != nil { return err } @@ -1004,8 +1023,8 @@ func (self *RefreshHelper) refreshTags(env refreshEnv) error { return nil } -func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleConfig, error) { - return self.c.Git().Submodule.GetConfigs(nil) +func (self *RefreshHelper) refreshStateSubmoduleConfigs(env refreshEnv) ([]*models.SubmoduleConfig, error) { + return env.git.Submodule.GetConfigs(nil) } // self.refreshStatus is called at the end of this because that's when we can @@ -1013,7 +1032,7 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs() ([]*models.SubmoduleCo func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refreshWorktrees bool, branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, env refreshEnv) []*models.Branch { loadSeq := self.branchLoadSeq.Add(1) - branches, err := self.c.Git().Loaders.BranchLoader.Load( + branches, err := env.git.Loaders.BranchLoader.Load( reflogCommits, captured.mainBranches, captured.oldBranches, @@ -1035,7 +1054,7 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh var worktrees []*models.Worktree if refreshWorktrees { - worktrees = self.loadWorktrees() + worktrees = self.loadWorktrees(env) } self.onUIThreadUnlessRepoChanged(env, func() { @@ -1100,7 +1119,7 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh } func (self *RefreshHelper) refreshFilesAndSubmodules(captured capturedFilesState, env refreshEnv) error { - configs, err := self.refreshStateSubmoduleConfigs() + configs, err := self.refreshStateSubmoduleConfigs(env) if err != nil { return err } @@ -1237,13 +1256,13 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re if len(pathsToStage) > 0 { self.c.LogAction(self.c.Tr.Actions.StageResolvedFiles) - if err := self.c.Git().WorkingTree.StageFiles(pathsToStage, nil); err != nil { + if err := env.git.WorkingTree.StageFiles(pathsToStage, nil); err != nil { return err } } } - files := self.c.Git().Loaders.FileLoader. + files := env.git.Loaders.FileLoader. GetStatusFiles(git_commands.GetStatusFileOptions{ ForceShowUntracked: captured.forceShowUntracked, Background: env.background, @@ -1257,7 +1276,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re } repoState := self.c.State().GetRepoState() - workingTreeState := self.c.Git().Status.WorkingTreeState() + workingTreeState := env.git.Status.WorkingTreeState() if workingTreeState.None() { // No operation is in progress (any more), so forget that we started one. // This also covers an operation that was finished or aborted externally. @@ -1340,7 +1359,7 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en lastReflogCommit = existing[0] } - commits, onlyObtainedNewReflogCommits, err := self.c.Git().Loaders.ReflogCommitLoader. + commits, onlyObtainedNewReflogCommits, err := env.git.Loaders.ReflogCommitLoader. GetReflogCommits(captured.hashPool, lastReflogCommit, filterPath, filterAuthor) if err != nil { return nil, err @@ -1382,7 +1401,7 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en } func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env refreshEnv) ([]*models.Remote, error) { - remotes, err := self.c.Git().Loaders.RemoteLoader.GetRemotes() + remotes, err := env.git.Loaders.RemoteLoader.GetRemotes() if err != nil { return nil, err } @@ -1414,8 +1433,8 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env return remotes, nil } -func (self *RefreshHelper) loadWorktrees() []*models.Worktree { - worktrees, err := self.c.Git().Loaders.Worktrees.GetWorktrees() +func (self *RefreshHelper) loadWorktrees(env refreshEnv) []*models.Worktree { + worktrees, err := env.git.Loaders.Worktrees.GetWorktrees() if err != nil { self.c.Log.Error(err) return []*models.Worktree{} @@ -1424,7 +1443,7 @@ func (self *RefreshHelper) loadWorktrees() []*models.Worktree { } func (self *RefreshHelper) refreshWorktrees(env refreshEnv) { - worktrees := self.loadWorktrees() + worktrees := self.loadWorktrees(env) self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().Worktrees = worktrees @@ -1437,7 +1456,7 @@ func (self *RefreshHelper) refreshWorktrees(env refreshEnv) { } func (self *RefreshHelper) refreshStashEntries(filterPath string, env refreshEnv) { - stashEntries := self.c.Git().Loaders.StashLoader. + stashEntries := env.git.Loaders.StashLoader. GetStashEntries(filterPath) self.onUIThreadUnlessRepoChanged(env, func() { @@ -1449,8 +1468,8 @@ func (self *RefreshHelper) refreshStashEntries(filterPath string, env refreshEnv // never call this on its own, it should only be called from within refreshCommits() func (self *RefreshHelper) refreshStatus(env refreshEnv) { - workingTreeState := self.c.Git().Status.WorkingTreeState() - repoName := self.c.Git().RepoPaths.RepoName() + workingTreeState := env.git.Status.WorkingTreeState() + repoName := env.git.RepoPaths.RepoName() self.onUIThreadUnlessRepoChanged(env, func() { // Read the checked-out branch and the linked worktree name here on the UI @@ -1473,15 +1492,15 @@ func (self *RefreshHelper) refreshStatus(env refreshEnv) { // read to decide that. The caller writes the bisect info to the model (in its // bounce) rather than refForLog doing it, so the model write stays on the UI // thread. -func (self *RefreshHelper) refForLog() (string, *git_commands.BisectInfo) { - bisectInfo := self.c.Git().Bisect.GetInfo() +func (self *RefreshHelper) refForLog(env refreshEnv) (string, *git_commands.BisectInfo) { + bisectInfo := env.git.Bisect.GetInfo() if !bisectInfo.Started() { return "HEAD", bisectInfo } // need to see if our bisect's current commit is reachable from our 'new' ref. - if bisectInfo.Bisecting() && !self.c.Git().Bisect.ReachableFromStart(bisectInfo) { + if bisectInfo.Bisecting() && !env.git.Bisect.ReachableFromStart(bisectInfo) { return bisectInfo.GetNewHash(), bisectInfo } @@ -1525,17 +1544,17 @@ func (self *RefreshHelper) refreshGithubPullRequests(branches []*models.Branch, }) } - githubRemotes := getAuthenticatedGithubRemotes(self.getGithubRemotes(remotes), self.c.Git().GitHub.GetAuthToken) + githubRemotes := getAuthenticatedGithubRemotes(self.getGithubRemotes(remotes, env), env.git.GitHub.GetAuthToken) if len(githubRemotes) == 0 { clearPullRequests() return } - baseInfo := getGithubBaseRemote(githubRemotes, self.c.Git().GitHub.ConfiguredBaseRemoteName()) + baseInfo := getGithubBaseRemote(githubRemotes, env.git.GitHub.ConfiguredBaseRemoteName()) if baseInfo == nil { clearPullRequests() - if !self.githubBaseRemotePromptDismissed[self.c.Git().RepoPaths.RepoPath()] { + if !self.githubBaseRemotePromptDismissed[env.git.RepoPaths.RepoPath()] { self.promptForBaseGithubRepo(githubRemotes) } return @@ -1550,12 +1569,12 @@ type githubRemoteInfo struct { authToken string } -func (self *RefreshHelper) getGithubRemotes(remotes []*models.Remote) []githubRemoteInfo { +func (self *RefreshHelper) getGithubRemotes(remotes []*models.Remote, env refreshEnv) []githubRemoteInfo { return lo.FilterMap(remotes, func(remote *models.Remote, _ int) (githubRemoteInfo, bool) { if len(remote.Urls) == 0 { return githubRemoteInfo{}, false } - serviceInfo, err := self.c.Git().HostingService.GetServiceInfo(remote.Urls[0]) + serviceInfo, err := env.git.HostingService.GetServiceInfo(remote.Urls[0]) if err != nil || serviceInfo.Provider != "github" { return githubRemoteInfo{}, false } @@ -1662,13 +1681,13 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, bra return branch.UpstreamBranch }) - prs, err := self.c.Git().GitHub.FetchRecentPRs(branchNames, &baseInfo.serviceInfo, baseInfo.authToken) + prs, err := env.git.GitHub.FetchRecentPRs(branchNames, &baseInfo.serviceInfo, baseInfo.authToken) if err != nil { self.c.Log.Error("error fetching pull requests from GitHub: " + err.Error()) return } - self.savePullRequestsToCache(prs) + self.savePullRequestsToCache(prs, env) self.onUIThreadUnlessRepoChanged(env, func() { self.c.Model().PullRequests = prs @@ -1680,8 +1699,12 @@ func (self *RefreshHelper) setGithubPullRequests(baseInfo *githubRemoteInfo, bra }) } -func (self *RefreshHelper) savePullRequestsToCache(prs []*models.GithubPullRequest) { - repoPath := self.c.Git().RepoPaths.RepoPath() +func (self *RefreshHelper) savePullRequestsToCache(prs []*models.GithubPullRequest, env refreshEnv) { + // Key the cache by the repo the refresh was started for, not the live one: + // this runs on a worker, and if the user switched repos while the fetch was + // in flight, the live instance would file the old repo's pull requests + // under the new repo's path. + repoPath := env.git.RepoPaths.RepoPath() cached := lo.Map(prs, func(pr *models.GithubPullRequest, _ int) config.CachedPullRequest { return config.CachedPullRequest{ HeadRefName: pr.HeadRefName, From 8e045653bef18ef356d989b17e3eac39b42e463e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 22:34:08 +0200 Subject: [PATCH 204/218] Don't pop up errors from a refresh worker once the repo was switched MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An error returned from a gocui worker is shown to the user in an error popup. For the branch loader's behind-counts worker that used to be the "no such ref" popup when a background refresh crossed a repo switch: the old repo's main branch didn't exist in the new repo. The previous commits fix that scenario properly — the command now runs against the repo the refresh was started for — but a stale worker can still fail legitimately, most plausibly because that repo was deleted after switching away from it (e.g. removing a worktree). Its results are dropped anyway, so log the error instead of alarming the user about a repo they already left. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index caf14ed2a..7ae7b4119 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1039,7 +1039,18 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, refresh loadBehindCounts, func(f func() error) { self.onWorker(env.background, func(_ gocui.Task) error { - return f() + err := f() + if err != nil && self.c.State().GetRepoGeneration() != env.generation { + // An error returned from a worker is shown in a popup. Don't + // do that if the repo was switched while this worker was in + // flight: its results are dropped anyway, and the error + // concerns a repo the user has already left — e.g. failing to + // compute the behind-counts for a worktree that was deleted + // after switching away from it. + self.c.Log.Warnf("dropping error from a stale refresh worker after a repo switch: %v", err) + return nil + } + return err }) }, func() { From ae095f276b0f46041f76ce1d68d29adb6f5ff30e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 19 Jul 2026 22:43:34 +0200 Subject: [PATCH 205/218] Don't refuse a repo switch during a pure refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The refreshes on focus-in, right after a repo switch, and after returning from a subprocess are full foreground refreshes, so their tasks kept Busy() true for as long as the slowest scope took — and any switch attempt in that window was refused with the "can't switch" toast. The focus-in one is particularly annoying: focusing lazygit is often precisely what the user does in order to switch repos, and right after regaining focus is when a refresh takes longest. Blocking the switch bought nothing there. The refusal exists for user operations, whose follow-up work (e.g. a Then callback reading the model) isn't covered by the switch-safety guards; but these refreshes merely reload state, and a refresh by itself is now switch-safe: its git commands run against the repo it was started for, and the generation guard drops its updates when the repo changed. We can't just mark them Background, because that flag also decides whether the files refresh lets git take optional locks to persist its refreshed stat cache — worth doing for an attended refresh, and the focus-in refresh (typically running right after external changes) is the case that profits most. So split the two meanings: a new DontBlockRepoSwitch option dispatches the refresh's tasks as background tasks (excluded from Busy()) while keeping the attended optional-locks behavior. Combining it with Then panics, since Then is not generation-guarded. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refresh_helper.go | 27 +++++++++++++++---- pkg/gui/gui.go | 6 ++--- pkg/gui/types/refresh.go | 15 +++++++++++ 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 7ae7b4119..27f465f69 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -91,10 +91,19 @@ func (self *RefreshHelper) RefreshFromWorker(options types.RefreshOptions) { } type refreshEnv struct { - // whether this is a background refresh (which selects the dispatch variant that - // doesn't count towards lazygit being busy) + // Whether everything this refresh dispatches uses the background task + // variants, which don't count towards lazygit being busy — so the refresh + // doesn't block switching repos. Set for refreshes initiated by a + // background routine, and for foreground ones that opted in via + // RefreshOptions.DontBlockRepoSwitch. background bool + // Whether the refresh was initiated by an unattended background routine + // (RefreshOptions.Background) rather than by user activity. The files + // refresh uses this to decide whether git may take optional locks and + // persist its refreshed stat cache. + backgroundRoutine bool + // the repo generation captured when the refresh started generation int @@ -175,6 +184,13 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr panic("Refresh called from a worker, or RefreshFromWorker called from the UI thread") } + if options.Then != nil && options.DontBlockRepoSwitch { + // Then is not generation-guarded, so if a switch crossed the refresh it + // would run against the newly switched-to repo. A refresh carrying a + // Then must keep blocking switches. + panic("a refresh with a Then callback must not set DontBlockRepoSwitch") + } + // Capture the refresh's baseline once, here at the start: the repo // generation that every scope's bounce is guarded against, and the git // command instance the scopes run their commands through. The two are @@ -186,9 +202,10 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // against the repo it started in, and the generation guard drops its // writes. env := refreshEnv{ - background: options.Background, + background: options.Background || options.DontBlockRepoSwitch, + backgroundRoutine: options.Background, } - self.captureOnUIThread(calledFromWorker, options.Background, func() { + self.captureOnUIThread(calledFromWorker, env.background, func() { env.generation = self.c.State().GetRepoGeneration() env.git = self.c.Git() }) @@ -1276,7 +1293,7 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re files := env.git.Loaders.FileLoader. GetStatusFiles(git_commands.GetStatusFileOptions{ ForceShowUntracked: captured.forceShowUntracked, - Background: env.background, + Background: env.backgroundRoutine, }) conflictFileCount := 0 diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 533c01fbd..8776040e7 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -390,7 +390,7 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context } gui.c.Log.Info("Receiving focus - refreshing") - gui.helpers.Refresh.Refresh(types.RefreshOptions{}) + gui.helpers.Refresh.Refresh(types.RefreshOptions{DontBlockRepoSwitch: true}) return reloadErr } @@ -1031,7 +1031,7 @@ func (gui *Gui) runSubprocessWithSuspenseAndRefresh(subprocess *oscommands.CmdOb return err } - gui.c.Refresh(types.RefreshOptions{}) + gui.c.Refresh(types.RefreshOptions{DontBlockRepoSwitch: true}) return nil } @@ -1108,7 +1108,7 @@ func (gui *Gui) loadNewRepo() error { return err } - gui.c.Refresh(types.RefreshOptions{}) + gui.c.Refresh(types.RefreshOptions{DontBlockRepoSwitch: true}) if err := gui.os.UpdateWindowTitle(); err != nil { return err diff --git a/pkg/gui/types/refresh.go b/pkg/gui/types/refresh.go index 937c3a30e..c733e589e 100644 --- a/pkg/gui/types/refresh.go +++ b/pkg/gui/types/refresh.go @@ -94,4 +94,19 @@ type RefreshOptions struct { // fast. Background refreshes leave the suppression in place: not persisting // the stat-cache is the right trade-off for unattended work. Background bool + + // When true, this foreground refresh does not block switching repos while + // it is in flight. A refresh is switch-safe by construction — its git + // commands run against the repo it was started for, and the generation + // guard drops its model/view updates if the repo changed — but a refresh + // triggered by a user operation still blocks switching (its tasks count + // towards Busy()), because the operation's follow-up work isn't covered + // by those guards. A refresh that merely reloads state (on focus, after a + // repo switch, after returning from a subprocess) has no such follow-up, + // so it opts in here and a repo switch during it is allowed rather than + // refused with a toast. + // + // Must not be combined with Then: Then is not generation-guarded, so it + // would run against the newly switched-to repo. + DontBlockRepoSwitch bool } From e0b8dbf48c0dfd1039f2df743952f4032b5fc21b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 20 Jul 2026 14:24:03 +0200 Subject: [PATCH 206/218] Resolve the refresh's file reads against its repo root MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The refresh workers read a few files at paths relative to the process working directory: the submodule config read of .gitmodules, the files refresh's check for conflict markers, and the submodule stash's existence check. Git commands are pinned to the repo their instance was created for, but these Go file reads still followed the cwd, so a background refresh crossing a repo switch would read the new repo's files while computing data for the old one. Join them with the worktree root of the instance they belong to. (Most git-state file reads — working tree state, rebase todos, bisect info — already resolve against RepoPaths and need no change.) This also fixes the submodule stash's existence check for nested submodules: it stat'ed submodule.Path, which is relative to the parent module, against the repo root — now it uses the submodule's full path, matching the stash command right below it. Co-Authored-By: Claude Fable 5 --- pkg/commands/git_commands/submodule.go | 11 ++++++++--- pkg/gui/controllers/helpers/refresh_helper.go | 7 ++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/pkg/commands/git_commands/submodule.go b/pkg/commands/git_commands/submodule.go index 3eb081701..d8c1208bc 100644 --- a/pkg/commands/git_commands/submodule.go +++ b/pkg/commands/git_commands/submodule.go @@ -28,10 +28,15 @@ func NewSubmoduleCommands(gitCommon *GitCommon) *SubmoduleCommands { } func (self *SubmoduleCommands) GetConfigs(parentModule *models.SubmoduleConfig) ([]*models.SubmoduleConfig, error) { - gitModulesPath := ".gitmodules" + // Resolve the path against the repo this commands object was created for + // rather than the process working directory, so that a read from a + // still-running refresh keeps addressing that repo after the user + // switched to another one. + dir := self.repoPaths.WorktreePath() if parentModule != nil { - gitModulesPath = filepath.Join(parentModule.FullPath(), gitModulesPath) + dir = filepath.Join(dir, parentModule.FullPath()) } + gitModulesPath := filepath.Join(dir, ".gitmodules") file, err := os.Open(gitModulesPath) if err != nil { if os.IsNotExist(err) { @@ -180,7 +185,7 @@ func (self *SubmoduleCommands) ConflictSideLog(path string, side string, otherSi func (self *SubmoduleCommands) Stash(submodule *models.SubmoduleConfig) error { // if the path does not exist then it hasn't yet been initialized so we'll swallow the error // because the intention here is to have no dirty worktree state - if _, err := os.Stat(submodule.Path); os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(self.repoPaths.WorktreePath(), submodule.FullPath())); os.IsNotExist(err) { self.Log.Infof("submodule path %s does not exist, returning", submodule.FullPath()) return nil } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 27f465f69..8ae62d9dd 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1,6 +1,7 @@ package helpers import ( + "path/filepath" "strings" "sync" "sync/atomic" @@ -1273,7 +1274,11 @@ func (self *RefreshHelper) refreshStateFiles(captured capturedFilesState, env re prevConflictFileCount++ } if file.HasInlineMergeConflicts { - hasConflicts, err := mergeconflicts.FileHasConflictMarkers(file.Path) + // Join with the refresh's repo root rather than relying on the + // process working directory, which may already point at another + // repo if the user switched while this refresh was in flight. + hasConflicts, err := mergeconflicts.FileHasConflictMarkers( + filepath.Join(env.git.RepoPaths.WorktreePath(), file.Path)) if err != nil { self.c.Log.Error(err) } else if !hasConflicts { From 568a4276d7580b7285ef9bd21555eebcf160a0f2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 20 Jul 2026 14:34:07 +0200 Subject: [PATCH 207/218] Pin the cached git config's commands to the repo directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cached git config runs its `git config` reads through raw exec.Command calls, outside the pinned git command builder, so they followed the process working directory. A cache miss on a stale instance — one still in use by a refresh that crossed a repo switch — would therefore read the new repo's local config while computing data for the old one. Give the cache a directory, set once by NewGitCommand right after it determines the repo paths (the object is created fresh for every repo switch, so no cross-repo cache invalidation is needed), and run every config command there. Co-Authored-By: Claude Fable 5 --- pkg/commands/git.go | 4 ++++ pkg/commands/git_config/cached_git_config.go | 17 +++++++++++++++++ .../git_config/cached_git_config_test.go | 17 +++++++++++++++++ pkg/commands/git_config/fake_git_config.go | 3 +++ 4 files changed, 41 insertions(+) diff --git a/pkg/commands/git.go b/pkg/commands/git.go index 7ba2dba66..ba6e5a033 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -72,6 +72,10 @@ func NewGitCommand( return nil, utils.WrapError(err) } + // Pin the config reads to the repo directory like all other git commands + // (see NewGitCmdObjBuilder); the config commands run outside that builder. + gitConfig.SetDir(repoPaths.WorktreePath()) + return NewGitCommandAux( cmn, version, diff --git a/pkg/commands/git_config/cached_git_config.go b/pkg/commands/git_config/cached_git_config.go index 256cd325b..17152ef9e 100644 --- a/pkg/commands/git_config/cached_git_config.go +++ b/pkg/commands/git_config/cached_git_config.go @@ -16,11 +16,19 @@ type IGitConfig interface { // this is for when you want to pass 'mykey' and check if the result is truthy GetBool(string) bool + // SetDir pins the config commands to the given repo directory, so that + // they keep reading that repo's local config even if the process working + // directory changes later (i.e. the user switches repos while this + // instance is still in use by in-flight work). Called once, before the + // first read. + SetDir(string) + DropCache() } type CachedGitConfig struct { cache map[string]string + dir string runGitConfigCmd func(*exec.Cmd) (string, error) log *logrus.Entry mutex sync.Mutex @@ -39,6 +47,13 @@ func NewCachedGitConfig(runGitConfigCmd func(*exec.Cmd) (string, error), log *lo } } +func (self *CachedGitConfig) SetDir(dir string) { + self.mutex.Lock() + defer self.mutex.Unlock() + + self.dir = dir +} + func (self *CachedGitConfig) Get(key string) string { self.mutex.Lock() defer self.mutex.Unlock() @@ -69,6 +84,7 @@ func (self *CachedGitConfig) GetGeneral(args string) string { func (self *CachedGitConfig) getGeneralAux(args string) string { cmd := getGitConfigGeneralCmd(args) + cmd.Dir = self.dir value, err := self.runGitConfigCmd(cmd) if err != nil { self.log.Debugf("Error getting git config value for args: %s. Error: %v", args, err.Error()) @@ -79,6 +95,7 @@ func (self *CachedGitConfig) getGeneralAux(args string) string { func (self *CachedGitConfig) getAux(key string) string { cmd := getGitConfigCmd(key) + cmd.Dir = self.dir value, err := self.runGitConfigCmd(cmd) if err != nil { self.log.Debugf("Error getting git config value for key: %s. Error: %v", key, err.Error()) diff --git a/pkg/commands/git_config/cached_git_config_test.go b/pkg/commands/git_config/cached_git_config_test.go index fd884df65..7b92eed1e 100644 --- a/pkg/commands/git_config/cached_git_config_test.go +++ b/pkg/commands/git_config/cached_git_config_test.go @@ -116,3 +116,20 @@ func TestGet(t *testing.T) { assert.Equal(t, "blah", result) assert.Equal(t, 1, count) } + +// The config commands run in the directory set by SetDir rather than in the +// process's current directory: lazygit chdirs when switching repos, and config +// reads issued for the previous repo after that must keep addressing the repo +// they were created for. +func TestSetDirPinsCommandsToDirectory(t *testing.T) { + real := NewCachedGitConfig( + func(cmd *exec.Cmd) (string, error) { + assert.Equal(t, "/path/to/repo", cmd.Dir) + return "blah", nil + }, + utils.NewDummyLog(), + ) + real.SetDir("/path/to/repo") + real.Get("commit.gpgsign") + real.GetGeneral("--local --get-regexp foo") +} diff --git a/pkg/commands/git_config/fake_git_config.go b/pkg/commands/git_config/fake_git_config.go index e82efcd1b..442c18644 100644 --- a/pkg/commands/git_config/fake_git_config.go +++ b/pkg/commands/git_config/fake_git_config.go @@ -28,5 +28,8 @@ func (self *FakeGitConfig) GetBool(key string) bool { return isTruthy(self.Get(key)) } +func (self *FakeGitConfig) SetDir(dir string) { +} + func (self *FakeGitConfig) DropCache() { } From efed9d040721faf57bc8d9b6a1e57f31ba2219c7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 20 Jul 2026 14:39:36 +0200 Subject: [PATCH 208/218] Don't auto-forward branches when the repo was switched during the fetch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PostFetchRefresh's refresh is the only background refresh carrying a Then callback, and Then callbacks are not generation-guarded: when the background fetch's refresh crossed a repo switch, the callback still ran — in the new repo — and auto-forwarded the new repo's branches because the old repo's fetch had completed. That was harmless in practice (the update-ref call compares against the expected old value, and it only does what the next fetch's auto-forward would do anyway), but mutating refs in a repo whose fetch never happened is not an action the user took. Skip the auto-forward when the repo generation changed since the fetch started. The generation is captured by the fetch's callers before the fetch runs, not by PostFetchRefresh itself: the background fetch doesn't block repo switching and is a network call, so by the time PostFetchRefresh runs a switch may already have happened — a capture there (or the one the refresh itself takes) would compare against the new repo's generation and let the auto-forward through. For the manual fetch the capture point makes no difference, since a foreground operation blocks repo switching for its entire duration. This deliberately guards only this call site rather than making Then callbacks generation-guarded in general: a Then is an arbitrary callback, and whether it is safe to skip on a repo switch is a decision for the author of the call site. Co-Authored-By: Claude Fable 5 --- pkg/gui/background.go | 7 ++++++- pkg/gui/controllers/files_controller.go | 3 ++- pkg/gui/controllers/helpers/branches_helper.go | 12 +++++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 1e2db853f..d39dfd84c 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -232,9 +232,14 @@ func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop, retrigge } func (self *BackgroundRoutineMgr) backgroundFetch() (err error) { + // Captured before the fetch, not after: the fetch is a network call during + // which the user may switch repos, and the post-fetch refresh needs to be + // able to tell (see PostFetchRefresh). + fetchGeneration := self.gui.c.State().GetRepoGeneration() + err = self.gui.git.Sync.FetchBackground() - return self.gui.helpers.BranchesHelper.PostFetchRefresh(err, true) + return self.gui.helpers.BranchesHelper.PostFetchRefresh(err, true, fetchGeneration) } func (self *BackgroundRoutineMgr) triggerImmediateFetch() { diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index bf73d4c8b..656da1bf5 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -1527,6 +1527,7 @@ func (self *FilesController) onClickMain(opts gocui.ViewMouseBindingOpts) error } func (self *FilesController) fetch() error { + fetchGeneration := self.c.State().GetRepoGeneration() return self.c.WithWaitingStatus(self.c.Tr.FetchingStatus, func(task gocui.Task) error { self.c.LogAction("Fetch") err := self.c.Git().Sync.Fetch(task) @@ -1535,7 +1536,7 @@ func (self *FilesController) fetch() error { return errors.New(self.c.Tr.PassUnameWrong) } - return self.c.Helpers().BranchesHelper.PostFetchRefresh(err, false) + return self.c.Helpers().BranchesHelper.PostFetchRefresh(err, false, fetchGeneration) }) } diff --git a/pkg/gui/controllers/helpers/branches_helper.go b/pkg/gui/controllers/helpers/branches_helper.go index 83735d87d..e87edb460 100644 --- a/pkg/gui/controllers/helpers/branches_helper.go +++ b/pkg/gui/controllers/helpers/branches_helper.go @@ -392,7 +392,11 @@ func (self *BranchesHelper) deleteRemoteBranches(remoteBranches []*models.Remote return nil } -func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) error { +// fetchGeneration must be the repo generation from when the fetch started, +// captured by the caller before running the fetch: the background fetch +// doesn't block repo switching and is a network call, so the window in which +// the user can switch repos spans the whole fetch, not just this refresh. +func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool, fetchGeneration int) error { scope := []types.RefreshableView{ types.BRANCHES, types.COMMITS, types.REMOTES, types.TAGS, types.PULL_REQUESTS, } @@ -410,6 +414,12 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool) er if fetchErr != nil { return nil } + // Then callbacks are not generation-guarded, so check explicitly: + // if the repo was switched since the fetch started, don't forward + // this repo's branches on the strength of another repo's fetch. + if self.c.State().GetRepoGeneration() != fetchGeneration { + return nil + } err := self.AutoForwardBranches(background) if background && err != nil { // The background poller discards this return value, so surface From 5fc678dde6ea9dad188f95293de75da3be9779bc Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Mon, 20 Jul 2026 15:59:36 +0200 Subject: [PATCH 209/218] Read the gui's per-repo pointers on the UI thread in background routines gui.git, gui.helpers and gui.State are all replaced on a repo switch, which runs on the UI thread. The background fetch and the external- change poller read them from their own goroutines, racing the reassignment. This race can't show up in the integration suite, which doesn't enable the background routines, so no -race run will ever flag it; it can only bite real users who switch repos while a background fetch or poll is in flight. Capture the objects a routine iteration needs in a single blocking UI-thread hop before using them, the same pattern the refresh's input capture uses. For the fetch this has two welcome side effects: the fetch, the post-fetch refresh's generation baseline, and the recorded fetch time now all refer to the same repo (the old comment documented the timestamp's mismatch as a known, unguarded race), and the git instance the fetch runs through is pinned to that repo's directory, so a switch mid-fetch can no longer direct in-flight work at the new repo. Co-Authored-By: Claude Fable 5 --- pkg/gui/background.go | 66 ++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/pkg/gui/background.go b/pkg/gui/background.go index d39dfd84c..180b2d445 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -6,7 +6,9 @@ import ( "sync/atomic" "time" + "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/utils" ) @@ -106,23 +108,35 @@ func (self *BackgroundRoutineMgr) startBackgroundFetch() { self.gui.waitForIntro.Wait() fetch := func(firstTimeOrRetriggered bool) 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. + // Capture what the fetch needs from the gui's per-repo state in a + // single UI-thread hop: gui.git, gui.helpers and gui.State are all + // replaced on a repo switch (which runs on the UI thread), so reading + // them from this background goroutine would race the reassignment. + // Capturing them together also ties the fetch, the post-fetch + // refresh's generation baseline, and the recorded fetch time to the + // same repo. + var git *commands.GitCommand + var appStatusHelper *helpers.AppStatusHelper + var branchesHelper *helpers.BranchesHelper + var fetchGeneration int + if err := self.gui.g.OnUIThreadAndWaitBackground(func() error { + git = self.gui.git + appStatusHelper = self.gui.helpers.AppStatus + branchesHelper = self.gui.helpers.BranchesHelper + fetchGeneration = self.gui.c.State().GetRepoGeneration() self.gui.State.LastBackgroundFetchTime = time.Now() return nil - }) + }); err != nil { + return err + } if self.gui.UserConfig().Gui.ShowBottomLine || firstTimeOrRetriggered { - return self.gui.helpers.AppStatus.WithWaitingStatusImpl(self.gui.Tr.FetchingStatus, func(gocui.Task) error { - return self.backgroundFetch() + return appStatusHelper.WithWaitingStatusImpl(self.gui.Tr.FetchingStatus, func(gocui.Task) error { + return self.backgroundFetch(git, branchesHelper, fetchGeneration) }, nil) } - return self.backgroundFetch() + return self.backgroundFetch(git, branchesHelper, fetchGeneration) } // We want an immediate fetch at startup, and since goEvery starts by @@ -165,7 +179,20 @@ func (self *BackgroundRoutineMgr) startBackgroundExternalChangeDetection() { } func (self *BackgroundRoutineMgr) checkForExternalChanges() { - current, err := self.gui.git.Status.RefsSnapshot() + // Capture the per-repo objects in a UI-thread hop, like the background + // fetch does: gui.git and gui.helpers are replaced on a repo switch, so + // reading them from this background goroutine would race the reassignment. + var git *commands.GitCommand + var refreshHelper *helpers.RefreshHelper + if err := self.gui.g.OnUIThreadAndWaitBackground(func() error { + git = self.gui.git + refreshHelper = self.gui.helpers.Refresh + return nil + }); err != nil { + return + } + + current, err := git.Status.RefsSnapshot() if err != nil { // Transient error (e.g. git process couldn't start). Don't update the // stored snapshot; we'll retry next tick. @@ -173,7 +200,7 @@ func (self *BackgroundRoutineMgr) checkForExternalChanges() { return } - if !self.gui.helpers.Refresh.RefsSnapshotChangedSince(current) { + if !refreshHelper.RefsSnapshotChangedSince(current) { return } @@ -231,15 +258,14 @@ func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop, retrigge }) } -func (self *BackgroundRoutineMgr) backgroundFetch() (err error) { - // Captured before the fetch, not after: the fetch is a network call during - // which the user may switch repos, and the post-fetch refresh needs to be - // able to tell (see PostFetchRefresh). - fetchGeneration := self.gui.c.State().GetRepoGeneration() +// The parameters are captured by the caller before the fetch starts, not read +// here after it: the fetch is a network call during which the user may switch +// repos, and the post-fetch refresh needs to be able to tell (see +// PostFetchRefresh). +func (self *BackgroundRoutineMgr) backgroundFetch(git *commands.GitCommand, branchesHelper *helpers.BranchesHelper, fetchGeneration int) error { + err := git.Sync.FetchBackground() - err = self.gui.git.Sync.FetchBackground() - - return self.gui.helpers.BranchesHelper.PostFetchRefresh(err, true, fetchGeneration) + return branchesHelper.PostFetchRefresh(err, true, fetchGeneration) } func (self *BackgroundRoutineMgr) triggerImmediateFetch() { From 00cef799ce36268cd198f0ae8ed22e6922fb4203 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 13:07:03 +0200 Subject: [PATCH 210/218] Show the inline status again when checking out a newly created remote branch Checking out a remote branch that has no local counterpart creates the local branch, refreshes, and then checks it out. The refresh exists so that CheckoutRef finds the new branch in the model and attaches an inline status to the branch item instead of showing a global waiting status. But since UI-thread refreshes stopped blocking, the checkout started before the refreshed branches had landed in the model, so the lookup failed and we always got the waiting status. Run the checkout from the refresh's Then, which is queued behind the model update. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/helpers/refs_helper.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pkg/gui/controllers/helpers/refs_helper.go b/pkg/gui/controllers/helpers/refs_helper.go index 675c332a0..0fcbeace3 100644 --- a/pkg/gui/controllers/helpers/refs_helper.go +++ b/pkg/gui/controllers/helpers/refs_helper.go @@ -157,12 +157,17 @@ func (self *RefsHelper) CheckoutRemoteBranch(fullBranchName string, localBranchN if err := self.c.Git().Branch.CreateWithUpstream(localBranchName, fullBranchName); err != nil { return err } - // Do a sync refresh to make sure the new branch is visible, - // so that we see an inline status when checking it out + // Refresh the branches and check out from Then, so that the + // new branch is already in the model when CheckoutRef looks + // it up; that's what makes it show an inline status on the + // branch rather than a global waiting status. self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.BRANCHES}, + Then: func() error { + return checkout(localBranchName, true) + }, }) - return checkout(localBranchName, true) + return nil }, }, { From 2e653ceebaa69e3fd8d02843ba65166ac50760f2 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 13:08:56 +0200 Subject: [PATCH 211/218] Update comments that still describe the removed blocking refresh mode A few comments still reasoned in terms of SYNC vs ASYNC refreshes, a distinction that no longer exists: sync vs async is now derived from the calling thread. Restate them in terms of the current mechanisms (RefreshFromWorker blocking its worker, model updates being enqueued on the UI thread) without changing any behavior. Co-Authored-By: Claude Fable 5 --- .../helpers/inline_status_helper.go | 21 ++++++++++--------- pkg/gui/controllers/helpers/refresh_helper.go | 10 ++++----- pkg/gui/controllers/remotes_controller.go | 3 +-- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pkg/gui/controllers/helpers/inline_status_helper.go b/pkg/gui/controllers/helpers/inline_status_helper.go index f2ca7ec17..814a11406 100644 --- a/pkg/gui/controllers/helpers/inline_status_helper.go +++ b/pkg/gui/controllers/helpers/inline_status_helper.go @@ -139,16 +139,17 @@ func (self *InlineStatusHelper) stop(opts InlineStatusOpts) { self.c.State().ClearItemOperation(opts.Item) // Re-render the context to remove the inline status now that the operation - // finished. Any refresh it triggered must be synchronous, not async: by the - // time we get here a synchronous refresh has already updated the model and - // queued its own re-render, and since UI-thread callbacks run in order, the - // render we queue here runs after it and draws the up-to-date model without - // the inline status. An async refresh might not have updated the model yet, - // so this render could briefly show the stale, pre-operation model: when - // pushing a branch, for example, it would flash the old ↑3↓7 ahead/behind - // counts for a moment before the refresh replaced them with a green - // checkmark. (Operations that don't refresh at all are fine too: there's - // nothing stale to show, so this just drops the status.) + // finished. The operation must trigger its refresh via RefreshFromWorker + // before we get here: that call returns only once the refresh's model + // updates have been enqueued on the UI thread, and since UI-thread + // callbacks run in order, the render we queue here runs after them and + // draws the up-to-date model without the inline status. A refresh whose + // model updates aren't enqueued yet by this point would make this render + // briefly show the stale, pre-operation model: when pushing a branch, for + // example, it would flash the old ↑3↓7 ahead/behind counts for a moment + // before the refresh replaced them with a green checkmark. (Operations + // that don't refresh at all are fine too: there's nothing stale to show, + // so this just drops the status.) self.renderContext(opts.ContextKey) } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 8ae62d9dd..a85c58cf2 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -1216,11 +1216,11 @@ func (self *RefreshHelper) onUIThread(background bool, f func() error) { // runs on the UI thread (calledFromWorker is false) fn runs inline; when it runs // on a worker, fn is dispatched to the UI thread and we block for it. // -// The inline case matters for correctness as much as the hop: a SYNC refresh -// initiated on the UI thread parks that thread in a wg.Wait while its scope -// workers run, so a scope worker that tried to hop to the UI thread there would -// deadlock. Capturing before those workers are spawned — inline, on the UI -// thread — avoids that entirely. +// The inline case matters for correctness as much as the hop: OnUIThreadAndWait +// must not be called from the UI thread itself (it would park the thread +// waiting for a callback that only it can run), and capturing inline also +// guarantees the snapshot reflects the state at the moment Refresh was called, +// before the calling handler regains control and can mutate it. func (self *RefreshHelper) captureOnUIThread(calledFromWorker bool, background bool, fn func()) { if !calledFromWorker { fn() diff --git a/pkg/gui/controllers/remotes_controller.go b/pkg/gui/controllers/remotes_controller.go index 76bd16bb1..cd05e5ff9 100644 --- a/pkg/gui/controllers/remotes_controller.go +++ b/pkg/gui/controllers/remotes_controller.go @@ -159,8 +159,7 @@ func (self *RemotesController) addAndCheckoutRemote(remoteName string, remoteUrl // Refresh the remotes so that we can select the new one. The remotes model // update is bounced onto the UI thread, so the selection (which reads // Model.Remotes) has to run in Then; reading it inline here would see the - // previous model. Loading remotes is not expensive, so a sync refresh is - // affordable. + // previous model. self.c.Refresh(types.RefreshOptions{ Scope: []types.RefreshableView{types.REMOTES}, Then: func() error { From 7a902b56cc49dc908e25a76b894fc38cb1923590 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 12:49:36 +0200 Subject: [PATCH 212/218] Add a way for integration tests to press keys in rapid succession MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The test driver waits for lazygit to become idle after every keypress, so tests could never exercise what happens when a key arrives while the previous key's processing is still in flight — for example while the refresh triggered by the previous key hasn't updated the model yet. Real users type faster than that all the time. PressRapidly injects all its keys back to back and waits for idle only once at the end, so the second and later keys are queued before the first one's processing has finished. The next commit uses this to demonstrate a bug in exactly that scenario. Co-Authored-By: Claude Fable 5 --- pkg/gui/gui_driver.go | 26 ++++++++++++++++------- pkg/integration/components/test_driver.go | 10 +++++++++ pkg/integration/components/test_test.go | 4 ++++ pkg/integration/components/view_driver.go | 13 ++++++++++++ pkg/integration/types/types.go | 4 ++++ 5 files changed, 49 insertions(+), 8 deletions(-) diff --git a/pkg/gui/gui_driver.go b/pkg/gui/gui_driver.go index 7bd31d93d..74a8109a7 100644 --- a/pkg/gui/gui_driver.go +++ b/pkg/gui/gui_driver.go @@ -25,17 +25,27 @@ type GuiDriver struct { var _ integrationTypes.GuiDriver = &GuiDriver{} func (self *GuiDriver) PressKey(keyStr string) { + self.PressKeysRapidly(keyStr) +} + +// PressKeysRapidly presses the given keys in immediate succession, waiting for +// lazygit to become idle only after the last one. Keys pressed this way can +// arrive while the previous key's processing is still in flight, like a user +// typing faster than lazygit handles the input. +func (self *GuiDriver) PressKeysRapidly(keyStrs ...string) { self.CheckAllToastsAcknowledged() - key, ok := config.KeyFromLabel(keyStr) - if !ok { - self.Fail("Unrecognized key: " + keyStr) - } + for _, keyStr := range keyStrs { + key, ok := config.KeyFromLabel(keyStr) + if !ok { + self.Fail("Unrecognized key: " + keyStr) + } - self.gui.g.ReplayKeyEvent(gocui.NewTcellKeyEventWrapper( - tcell.NewEventKey(tcell.Key(key.KeyName()), key.Str(), tcell.ModMask(key.Mod())), - 0, - )) + self.gui.g.ReplayKeyEvent(gocui.NewTcellKeyEventWrapper( + tcell.NewEventKey(tcell.Key(key.KeyName()), key.Str(), tcell.ModMask(key.Mod())), + 0, + )) + } self.waitTillIdle() } diff --git a/pkg/integration/components/test_driver.go b/pkg/integration/components/test_driver.go index 376b0f4d6..42ce8ac35 100644 --- a/pkg/integration/components/test_driver.go +++ b/pkg/integration/components/test_driver.go @@ -2,6 +2,7 @@ package components import ( "fmt" + "strings" "time" "github.com/jesseduffield/lazygit/pkg/config" @@ -42,6 +43,15 @@ func (self *TestDriver) pressFast(keyStr string) { self.Wait(self.inputDelay / 5) } +// presses the keys in immediate succession, without waiting for lazygit to +// become idle in between, to simulate a user typing faster than lazygit +// processes the input +func (self *TestDriver) pressRapidly(keyStrs []string) { + self.SetCaption(fmt.Sprintf("Pressing %s", strings.Join(keyStrs, ", "))) + self.gui.PressKeysRapidly(keyStrs...) + self.Wait(self.inputDelay) +} + func (self *TestDriver) click(x, y int) { self.SetCaption(fmt.Sprintf("Clicking %d, %d", x, y)) self.gui.Click(x, y) diff --git a/pkg/integration/components/test_test.go b/pkg/integration/components/test_test.go index e7fd0b66a..8fd4417ea 100644 --- a/pkg/integration/components/test_test.go +++ b/pkg/integration/components/test_test.go @@ -30,6 +30,10 @@ func (self *fakeGuiDriver) PressKey(key string) { self.pressedKeys = append(self.pressedKeys, key) } +func (self *fakeGuiDriver) PressKeysRapidly(keys ...string) { + self.pressedKeys = append(self.pressedKeys, keys...) +} + func (self *fakeGuiDriver) Click(x, y int) { self.clickedCoordinates = append(self.clickedCoordinates, coordinate{x: x, y: y}) } diff --git a/pkg/integration/components/view_driver.go b/pkg/integration/components/view_driver.go index df4b9d7d8..920c610be 100644 --- a/pkg/integration/components/view_driver.go +++ b/pkg/integration/components/view_driver.go @@ -454,6 +454,19 @@ func (self *ViewDriver) PressFast(key config.Keybinding) *ViewDriver { return self } +// Presses the given keys in immediate succession, without waiting for lazygit +// to become idle in between (Press waits after every key). Use this to +// simulate a user typing faster than lazygit processes the input. +func (self *ViewDriver) PressRapidly(keys ...config.Keybinding) *ViewDriver { + self.IsFocused() + + self.t.pressRapidly(lo.Map(keys, func(key config.Keybinding, _ int) string { + return key[0] + })) + + return self +} + func (self *ViewDriver) Click(x, y int) *ViewDriver { offsetX, offsetY, _, _ := self.getView().Dimensions() diff --git a/pkg/integration/types/types.go b/pkg/integration/types/types.go index 34ce499cc..12009315a 100644 --- a/pkg/integration/types/types.go +++ b/pkg/integration/types/types.go @@ -23,6 +23,10 @@ type IntegrationTest interface { // this is the interface through which our integration tests interact with the lazygit gui type GuiDriver interface { PressKey(string) + // Like PressKey, but presses several keys in immediate succession, waiting + // for lazygit to become idle only after the last one. Use it to simulate a + // user typing faster than lazygit processes the input. + PressKeysRapidly(...string) Click(int, int) // Simulate the terminal window regaining focus (which triggers a reload of // changed config files) From 963db76ab62700ddd32ddfd14e0e16efe30601be Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 12:54:24 +0200 Subject: [PATCH 213/218] Add test showing that a rapid second keypress acts on a stale staging panel Pressing space twice in quick succession in the staging panel is supposed to stage two hunks: the refresh triggered by the first press rebuilds the panel's diff and moves the selection to the next stageable hunk, and the second press stages that. Since we made UI-thread refreshes non-blocking, the second press is handled as soon as it arrives, while that refresh is still in flight. It then reads the stale pre-refresh diff, builds the first hunk's patch again, and git apply fails with 'patch does not apply' because those lines are already in the index. The test documents this currently broken behavior; the fix comes next. Co-Authored-By: Claude Fable 5 --- .../stage_hunks_with_rapid_keypresses.go | 69 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 2 files changed, 70 insertions(+) create mode 100644 pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go diff --git a/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go b/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go new file mode 100644 index 000000000..74dbb4b6f --- /dev/null +++ b/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go @@ -0,0 +1,69 @@ +package staging + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +// The second space is pressed before the refresh triggered by the first one +// has updated the staging panel. That refresh is what moves the selection to +// the next hunk, so the second press must not be handled until it has landed; +// handling it earlier would try to stage the first hunk a second time. +var StageHunksWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Stage two hunks with two space presses in rapid succession", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) { + config.GetUserConfig().Gui.UseHunkModeInStagingView = true + }, + SetupRepo: func(shell *Shell) { + // Use 7 context lines between the two change blocks so that git creates + // two separate hunks. + shell.CreateFileAndAdd("file1", "1\n2\na\nb\nc\nd\ne\nf\ng\n3\n4\n") + shell.Commit("one") + + shell.UpdateFile("file1", "1b\n2b\na\nb\nc\nd\ne\nf\ng\n3b\n4b\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("file1").IsSelected(), + ). + PressEnter() + + t.Views().Staging(). + IsFocused(). + PressRapidly(keys.Universal.Select, keys.Universal.Select) + + /* EXPECTED: + t.Views().StagingSecondary(). + IsFocused(). + ContainsLines( + Contains("+1b"), + Contains("+2b"), + ). + ContainsLines( + Contains("+3b"), + Contains("+4b"), + ) + ACTUAL: */ + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Contains("patch does not apply")). + Confirm() + + t.Views().Staging(). + IsFocused(). + ContainsLines( + Contains("+3b"), + Contains("+4b"), + ) + + t.Views().StagingSecondary(). + ContainsLines( + Contains("+1b"), + Contains("+2b"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 8213d5159..2189d3506 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -403,6 +403,7 @@ var tests = []*components.IntegrationTest{ staging.SelectNextLineAfterStagingInTwoHunkDiff, staging.SelectNextLineAfterStagingIsolatedAddedLine, staging.StageHunks, + staging.StageHunksWithRapidKeypresses, staging.StageLines, staging.StagePartialBlockOfChangesFirstLines, staging.StagePartialBlockOfChangesLastLines, From b96b8a97534d513dd774d2826782ee833b2cfa36 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 13:02:36 +0200 Subject: [PATCH 214/218] Add RefreshBlockingInput to buffer keypresses until a refresh has landed A refresh from the UI thread returns immediately and applies its model and view updates as queued UI-thread callbacks. A key pressed before those have run is handled against the stale, pre-refresh state. For most keys that's harmless, but some handlers turn that state into git commands: pressing space twice in quick succession in the staging panel builds the second patch from the already-applied diff and fails with 'patch does not apply', because the refresh after the first press is what moves the selection to the next stageable hunk. Notably, this is not just a regression of the recent change that made UI-thread refreshes non-blocking; the window was merely much narrower before. A blocking refresh parked the UI thread while the scopes' bounces were queued, and the event loop drains pending keyboard input with priority over queued user events, so a key pressed during the blocked window still beat the queued state updates. The guarantee that the next keypress sees post-refresh state had already ended when the scopes' state updates moved from worker-side mutex-guarded writes to UI-thread bounces. Fix it with the input-blocking mechanism we already use for commit surgery, exposed as a new RefreshBlockingInput entry point: it begins blocking events synchronously in the calling handler, and ends the block from a callback that the finishing step queues behind the refresh's own updates. Keys pressed while the refresh is in flight are buffered and replayed, in order, against the fully refreshed state; since a replayed key's handler re-enters this same path, a burst of keypresses applies sequentially, each one seeing the previous one's refresh. Unlike the old blocking refreshes, this doesn't freeze the UI thread: rendering, spinners, resizing, and mouse scrolling keep working while input is withheld. Blocking input is opt-in per call site rather than the default for all UI-thread refreshes, because most refreshes (the focus-in and startup refreshes, say) don't produce state that the next keypress depends on, and blocking on them would delay typing for no reason. It should also be limited to quick, narrow-scoped refreshes: a full refresh, or any scope that pulls in COMMITS, can take very long in large repos and should usually not hold up input. The staging panel's stage/discard/edit-hunk refreshes use it now. --- pkg/gui/controllers/helpers/refresh_helper.go | 32 +++++++++++++++++-- pkg/gui/controllers/staging_controller.go | 9 ++++-- pkg/gui/gui_common.go | 4 +++ pkg/gui/types/common.go | 11 +++++++ .../stage_hunks_with_rapid_keypresses.go | 19 ----------- 5 files changed, 51 insertions(+), 24 deletions(-) diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index a85c58cf2..cf097b67e 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -81,14 +81,20 @@ func NewRefreshHelper( } func (self *RefreshHelper) Refresh(options types.RefreshOptions) { - self.performRefresh(options, false) + self.performRefresh(options, false, false) +} + +// RefreshBlockingInput is Refresh for handlers whose next keypress may depend +// on the state the refresh produces. See IGuiCommon.RefreshBlockingInput. +func (self *RefreshHelper) RefreshBlockingInput(options types.RefreshOptions) { + self.performRefresh(options, false, true) } // RefreshFromWorker is Refresh for callers already running on a worker // goroutine (e.g. inside a WithWaitingStatus handler) rather than the UI // thread. See IGuiCommon.RefreshFromWorker. func (self *RefreshHelper) RefreshFromWorker(options types.RefreshOptions) { - self.performRefresh(options, true) + self.performRefresh(options, true, false) } type refreshEnv struct { @@ -159,7 +165,7 @@ func (self *refreshBounceBatch) close() []func() { return self.funcs } -func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool) { +func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFromWorker bool, blockInput bool) { startTime := time.Now() // A refresh from a worker blocks that worker until it's done; one from the @@ -192,6 +198,17 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr panic("a refresh with a Then callback must not set DontBlockRepoSwitch") } + // A RefreshBlockingInput caller wants keyboard input withheld until the + // refreshed state is in place (see IGuiCommon.RefreshBlockingInput). Begin + // the block synchronously here in the calling handler, so that no keypress + // can slip through before it; the finishing step ends it from a callback + // queued behind the refresh's own updates (see waitAndFinalize). Demos + // take the blocking inline path below and need none of this. + blockInputUntilDone := blockInput && !self.c.InDemo() + if blockInputUntilDone { + self.c.GocuiGui().BeginBlockingEvents() + } + // Capture the refresh's baseline once, here at the start: the repo // generation that every scope's bounce is guarded against, and the git // command instance the scopes run their commands through. The two are @@ -498,6 +515,15 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr self.onUIThread(env.background, options.Then) } + if blockInputUntilDone { + // Queued after the scopes' model bounces and Then, so by the time + // this runs — and the keys buffered during the refresh replay — + // the refreshed state is in place. + self.c.OnUIThread(func() error { + return self.c.GocuiGui().EndBlockingEvents() + }) + } + self.c.Log.Infof("Refresh took %s", time.Since(startTime)) } diff --git a/pkg/gui/controllers/staging_controller.go b/pkg/gui/controllers/staging_controller.go index 8d876acda..505a07fc4 100644 --- a/pkg/gui/controllers/staging_controller.go +++ b/pkg/gui/controllers/staging_controller.go @@ -229,7 +229,10 @@ func (self *StagingController) applySelectionAndRefresh(reverse bool) error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) + // Block input until the refresh has landed: it rebuilds the staging panel + // and moves the selection to the next stageable change, and a quick second + // keypress must act on that, not on the stale pre-refresh diff. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) return nil } @@ -284,7 +287,9 @@ func (self *StagingController) EditHunkAndRefresh() error { return err } - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) + // Block input like applySelectionAndRefresh does; the refresh rebuilds the + // staging panel from the post-edit diff. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES, types.STAGING}}) return nil } diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index 80b2b9ded..e7b14ba04 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -30,6 +30,10 @@ func (self *guiCommon) Refresh(opts types.RefreshOptions) { self.gui.helpers.Refresh.Refresh(opts) } +func (self *guiCommon) RefreshBlockingInput(opts types.RefreshOptions) { + self.gui.helpers.Refresh.RefreshBlockingInput(opts) +} + func (self *guiCommon) RefreshFromWorker(opts types.RefreshOptions) { self.gui.helpers.Refresh.RefreshFromWorker(opts) } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 6d11e29db..87bd9ef50 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -29,6 +29,17 @@ type IGuiCommon interface { LogCommand(cmdStr string, isCommandLine bool) // we call this when we want to refetch some models and render the result. Internally calls PostRefreshUpdate Refresh(RefreshOptions) + // Like Refresh, but withholds keyboard input until the refreshed state is + // in place: keys pressed while the refresh is in flight are buffered and + // replayed once its model and view updates have run, instead of being + // handled against the stale, pre-refresh state. Use it when the very next + // keypress may depend on what the refresh produces — e.g. staging a hunk, + // where the refresh moves the selection to the next stageable hunk that + // the next press is meant to stage. Keep it to quick, narrow-scoped + // refreshes: one that includes COMMITS (or refreshes everything) can take + // very long in large repos and should usually not block input unless + // there's a very good reason (switching repos is one such example). + RefreshBlockingInput(RefreshOptions) // Like Refresh, but for callers running on a worker goroutine (e.g. inside // a WithWaitingStatus handler) rather than the UI thread. The refresh // captures the model/context state it needs on the UI thread before doing diff --git a/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go b/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go index 74dbb4b6f..5b41073e2 100644 --- a/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go +++ b/pkg/integration/tests/staging/stage_hunks_with_rapid_keypresses.go @@ -36,7 +36,6 @@ var StageHunksWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ IsFocused(). PressRapidly(keys.Universal.Select, keys.Universal.Select) - /* EXPECTED: t.Views().StagingSecondary(). IsFocused(). ContainsLines( @@ -47,23 +46,5 @@ var StageHunksWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ Contains("+3b"), Contains("+4b"), ) - ACTUAL: */ - t.ExpectPopup().Alert(). - Title(Equals("Error")). - Content(Contains("patch does not apply")). - Confirm() - - t.Views().Staging(). - IsFocused(). - ContainsLines( - Contains("+3b"), - Contains("+4b"), - ) - - t.Views().StagingSecondary(). - ContainsLines( - Contains("+1b"), - Contains("+2b"), - ) }, }) From 200042a57cc9637d2ae756e9aa0a07673faf52a7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 19:29:47 +0200 Subject: [PATCH 215/218] Add test showing that rapidly moving a rebase todo twice moves the wrong todo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Moving a todo up or down rewrites the todo file and advances the selection synchronously, but the commits model is only rebuilt by the refresh, which finishes in the background. A second keypress arriving before that reads the pre-move model at the advanced selection index — that's the todo the first move swapped with, so the second press moves that one back instead of moving the selected todo further. Two rapid presses (e.g. from holding the key down) thus amount to a net no-op. The two presses also spawn two racing refreshes whose model updates can land in either order, so the todo list can even end up disagreeing with the todo file. That's why the test continues the rebase and asserts the resulting commit order instead of the displayed list: the rebase replays the file, which is deterministic. The test documents this currently broken behavior; the fix comes next. Co-Authored-By: Claude Fable 5 --- .../move_todo_down_with_rapid_keypresses.go | 68 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 2 files changed, 69 insertions(+) create mode 100644 pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go diff --git a/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go b/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go new file mode 100644 index 000000000..548d924f4 --- /dev/null +++ b/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go @@ -0,0 +1,68 @@ +package interactive_rebase + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +// The second keypress arrives before the refresh triggered by the first one +// has rebuilt the commits model. The handler reads the selected todo from the +// model at the already-advanced selection index, so with the stale, pre-move +// model it grabs the todo the first move swapped with and moves that one back +// down — turning the two presses into a net no-op instead of moving the +// selected todo down two slots. This is what happens when holding down the +// move-down key to move a todo several slots. +// +// We continue the rebase and assert the resulting commit order rather than +// asserting the todo list, because the two presses also spawn two racing +// refreshes whose updates can land in either order, so what the todo list +// shows in the broken state is not deterministic (it can even disagree with +// the todo file). The rebase replays what's in the file. +var MoveTodoDownWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Move a todo down two slots with two keypresses in rapid succession", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateNCommits(4) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("commit-04").IsSelected(), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), + ). + NavigateToLine(Contains("commit-01")). + Press(keys.Universal.Edit). + Lines( + Contains("--- Pending rebase todos ---"), + Contains("commit-04"), + Contains("commit-03"), + Contains("commit-02"), + Contains("--- Commits ---"), + Contains("commit-01").IsSelected(), + ). + NavigateToLine(Contains("commit-04")). + PressRapidly(keys.Commits.MoveDownCommit, keys.Commits.MoveDownCommit). + Tap(func() { + t.Common().ContinueRebase() + }). + /* EXPECTED: + Lines( + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-04"), + Contains("commit-01"), + ) + ACTUAL: */ + Lines( + Contains("commit-04"), + Contains("commit-03"), + Contains("commit-02"), + Contains("commit-01"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 2189d3506..1bb06741f 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -310,6 +310,7 @@ var tests = []*components.IntegrationTest{ interactive_rebase.Move, interactive_rebase.MoveAcrossBranchBoundaryOutsideRebase, interactive_rebase.MoveInRebase, + interactive_rebase.MoveTodoDownWithRapidKeypresses, interactive_rebase.MoveUpdateRefTodo, interactive_rebase.MoveWithCustomCommentChar, interactive_rebase.OutsideRebaseRangeSelect, From 055184f99772dc360b4dacb23edf0113dfadb86d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 19:31:36 +0200 Subject: [PATCH 216/218] Block input while the refresh after moving a rebase todo is in flight Moving a todo rewrites the todo file and advances the selection synchronously, but the commits model is only rebuilt by the refresh. A second press arriving before that grabs the swapped-with todo from the stale model at the advanced index and moves it back, so holding the key to move a todo several slots misbehaved. Use RefreshBlockingInput so the second press is buffered and replayed once the moved todo list is in place. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/local_commits_controller.go | 8 ++++++-- .../move_todo_down_with_rapid_keypresses.go | 8 -------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 2da502b79..708f8fc28 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -741,7 +741,10 @@ func (self *LocalCommitsController) moveDown(selectedCommits []*models.Commit, s self.context().MoveSelection(1) self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) - self.c.Refresh(types.RefreshOptions{ + // Block input until the refresh has landed: a quick second press must + // read the moved todo from the refreshed model, not grab whatever the + // advanced selection index points at in the stale one. + self.c.RefreshBlockingInput(types.RefreshOptions{ Scope: []types.RefreshableView{types.REBASE_COMMITS}, CommitSelection: types.KeepCommitSelectionIndex, }) @@ -777,7 +780,8 @@ func (self *LocalCommitsController) moveUp(selectedCommits []*models.Commit, sta self.context().MoveSelection(-1) self.context().HandleFocus(types.OnFocusOpts{ScrollSelectionIntoView: true}) - self.c.Refresh(types.RefreshOptions{ + // Block input for the same reason as in moveDown. + self.c.RefreshBlockingInput(types.RefreshOptions{ Scope: []types.RefreshableView{types.REBASE_COMMITS}, CommitSelection: types.KeepCommitSelectionIndex, }) diff --git a/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go b/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go index 548d924f4..16e58e18e 100644 --- a/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go +++ b/pkg/integration/tests/interactive_rebase/move_todo_down_with_rapid_keypresses.go @@ -50,19 +50,11 @@ var MoveTodoDownWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ Tap(func() { t.Common().ContinueRebase() }). - /* EXPECTED: Lines( Contains("commit-03"), Contains("commit-02"), Contains("commit-04"), Contains("commit-01"), ) - ACTUAL: */ - Lines( - Contains("commit-04"), - Contains("commit-03"), - Contains("commit-02"), - Contains("commit-01"), - ) }, }) From fc975f32a8d84ab1083a1e526dcdedcd961974fd Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 19:33:39 +0200 Subject: [PATCH 217/218] Block input while the refresh after a stash operation is in flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Popping or dropping a stash shifts the indices of the entries below it, and renaming re-creates the stash at the top, shifting all the others. The stash model is only rebuilt by the refresh, which finishes in the background, so acting on the next entry in quick succession — pressing the key, confirming the popup, and pressing again right away — reads the stale pre-operation indices and targets the wrong stash. Note that the confirmation popup is no protection here: the race starts when the confirm handler runs, and the next keypress can easily beat the refresh. Use RefreshBlockingInput so a quick follow-up keypress is buffered and replayed once the refreshed stash list is in place. Co-Authored-By: Claude Fable 5 --- pkg/gui/controllers/stash_controller.go | 30 ++++++++++++++++--------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index a2b7e9e97..d01fc8dbf 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -170,13 +170,16 @@ func (self *StashController) handleStashDrop(stashEntries []*models.StashEntry) Prompt: self.c.Tr.SureDropStashEntry, HandleConfirm: func() error { self.c.LogAction(self.c.Tr.Actions.DropStash) - // Refresh once at the end rather than after each drop: an async - // refresh from the UI thread finishes in the background, so firing - // one per iteration lets the workers race and an earlier, stale - // result can land last. The indices are captured up front and we - // drop highest-first, so the remaining lower indices stay valid - // without an intervening refresh. - defer self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) + // Refresh once at the end rather than after each drop: a refresh + // from the UI thread finishes in the background, so firing one per + // iteration lets the workers race and an earlier, stale result can + // land last. The indices are captured up front and we drop + // highest-first, so the remaining lower indices stay valid without + // an intervening refresh. Block input until the refresh has + // landed, so that dropping the next entry in quick succession + // (confirming and pressing the key again right away) sees the + // refreshed list and not the stale, pre-drop indices. + defer self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) for i := len(stashEntries) - 1; i >= 0; i-- { self.c.LogCommand(fmt.Sprintf(self.c.Tr.Log.DroppingStash, stashEntries[i].Hash), false) if err := self.c.Git().Stash.Drop(stashEntries[i].Index); err != nil { @@ -192,7 +195,11 @@ func (self *StashController) handleStashDrop(stashEntries []*models.StashEntry) } func (self *StashController) postStashRefresh() { - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH, types.FILES}}) + // Block input until the refresh has landed: popping shifts the indices of + // the remaining stash entries, and acting on the next entry in quick + // succession (confirming the popup and pressing the key again right away) + // must see the refreshed list, or it would target the wrong stash. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH, types.FILES}}) } func (self *StashController) handleNewBranchOffStashEntry(stashEntry *models.StashEntry) error { @@ -214,12 +221,15 @@ func (self *StashController) handleRenameStashEntry(stashEntry *models.StashEntr self.c.LogAction(self.c.Tr.Actions.RenameStash) err := self.c.Git().Stash.Rename(stashEntry.Index, response) if err != nil { - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) return err } self.context().SetSelection(0) // Select the renamed stash self.context().FocusLine(true) - self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) + // Renaming re-creates the stash at the top, shifting the other + // entries' indices; block input so that a quick next action sees + // the refreshed list rather than the stale indices. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.STASH}}) return nil }, AllowEmptyInput: true, From 975da9b8a9bd8186ca353e9cddc4bd4cd83c4ecd Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 21 Jul 2026 20:38:41 +0200 Subject: [PATCH 218/218] Block input and batch UI updates when switching repos On startup we don't want to block input during the initial refresh (it should be possible to press, say, `4` to jump to the commits panel right after startup without a delay), and we also want panels to show their contents as soon as possible; it doesn't matter so much that it's not in sync, we go from empty to populated here. However, when switching repos it can be confusing that some panels that are slow to update still show the old repo's data while others already show the new one's data, so update the UI only when everything is ready, and also block input to prevent accidentally trying to act on the old, stale data. --- pkg/gui/gui.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 8776040e7..912d46567 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -1103,12 +1103,31 @@ func (gui *Gui) runSubprocess(cmdObj *oscommands.CmdObj) error { return err } +var isFirstRefreshAfterStartup = true + func (gui *Gui) loadNewRepo() error { if err := gui.updateRecentRepoList(); err != nil { return err } - gui.c.Refresh(types.RefreshOptions{DontBlockRepoSwitch: true}) + // On startup we don't want to block input during the initial refresh (it + // should be possible to press, say, `4` to jump to the commits panel right + // after startup without a delay), and we also want panels to show their + // contents as soon as possible; it doesn't matter so much that it's not in + // sync, we go from empty to populated here. However, when switching repos + // it can be confusing that some panels that are slow to update still show + // the old repo's data while others already show the new one's data, so + // update the UI only when everything is ready, and also block input to + // prevent accidentally trying to act on the old, stale data. + options := types.RefreshOptions{DontBlockRepoSwitch: true} + refresh := gui.c.Refresh + if isFirstRefreshAfterStartup { + isFirstRefreshAfterStartup = false + } else { + options.BatchUIUpdates = true + refresh = gui.c.RefreshBlockingInput + } + refresh(options) if err := gui.os.UpdateWindowTitle(); err != nil { return err