Merge branch 'master' into f/open-in-terminal

This commit is contained in:
Ramon Vermeulen 2026-07-28 09:51:58 +02:00 committed by GitHub
commit 15e33291bc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 775 additions and 215 deletions

View file

@ -30,5 +30,6 @@ There are other forms of contributions to a project besides source code that are
- 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.
- Run a master build! This is probably the most valuable way to help me. Test the latest master not just by occasionally trying it, but by actually using it for your daily work; report any issues that you find. This will help prevent having to release hotfix updates for regressions that are only noticed by users updating to a new release.
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.

View file

@ -66,17 +66,17 @@ These can be used in lazygit by using the `externalDiffCommand` config; in the c
```yaml
git:
pagers:
- externalDiffCommand: difft --color=always
- externalDiffCommand: difft --color=always --context={{diffContext}}
```
The `colorArg` option is not used in this case.
The `colorArg` option is not used in this case. You can include the `{{diffContext}}` template variable to pass lazygit's current diff context size (the value controlled by the `{`/`}` keybindings) to the diff tool.
You can add whatever extra arguments you prefer for your difftool; for instance
```yaml
git:
pagers:
- externalDiffCommand: difft --color=always --display=inline --syntax-highlight=off
- externalDiffCommand: difft --color=always --context={{diffContext}} --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`:
@ -84,7 +84,7 @@ This can also be used for normal git diffs with custom parameters, such as `--co
```sh
#!/bin/sh
git diff --color-words --no-index --color=always --no-ext-diff "$2" "$5"
git diff --color-words --no-index --color=always --no-ext-diff --unified=$LAZYGIT_DIFF_CONTEXT "$2" "$5"
```
And then use it in your git config like so:
@ -92,7 +92,7 @@ And then use it in your git config like so:
```yaml
git:
pagers:
- externalDiffCommand: ~/bin/color-words.sh
- externalDiffCommand: LAZYGIT_DIFF_CONTEXT={{diffContext}} ~/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

View file

@ -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,
@ -90,7 +94,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,

View file

@ -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 {

View file

@ -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)
}

View file

@ -243,7 +243,7 @@ func (self *CommitCommands) AmendHeadCmdObj() *oscommands.CmdObj {
func (self *CommitCommands) ShowCmdObj(hash string, filterPaths []string) *oscommands.CmdObj {
contextSize := self.UserConfig().Git.DiffContextSize
extDiffCmd := self.pagerConfig.GetExternalDiffCommand()
extDiffCmd := self.pagerConfig.GetExternalDiffCommand(contextSize)
useExtDiffGitConfig := self.pagerConfig.GetUseExternalDiffGitConfig()
cmdArgs := NewGitCmd("show").
Config("diff.noprefix=false").

View file

@ -19,7 +19,8 @@ func NewDiffCommands(gitCommon *GitCommon) *DiffCommands {
// This is for generating diffs to be shown in the UI (e.g. rendering a range
// diff to the main view). It uses a custom pager if one is configured.
func (self *DiffCommands) DiffCmdObj(diffArgs []string) *oscommands.CmdObj {
extDiffCmd := self.pagerConfig.GetExternalDiffCommand()
contextSize := self.UserConfig().Git.DiffContextSize
extDiffCmd := self.pagerConfig.GetExternalDiffCommand(contextSize)
useExtDiff := extDiffCmd != ""
useExtDiffGitConfig := self.pagerConfig.GetUseExternalDiffGitConfig()
ignoreWhitespace := self.UserConfig().Git.IgnoreWhitespaceInDiffView
@ -32,7 +33,7 @@ func (self *DiffCommands) DiffCmdObj(diffArgs []string) *oscommands.CmdObj {
Arg("--submodule").
Arg(fmt.Sprintf("--color=%s", self.pagerConfig.GetColorArg())).
ArgIf(ignoreWhitespace, "--ignore-all-space").
Arg(fmt.Sprintf("--unified=%d", self.UserConfig().Git.DiffContextSize)).
Arg(fmt.Sprintf("--unified=%d", contextSize)).
Arg(diffArgs...).
Dir(self.repoPaths.worktreePath).
ToArgv(),

View file

@ -81,7 +81,8 @@ func (self *StashCommands) Hash(index int) (string, error) {
}
func (self *StashCommands) ShowStashEntryCmdObj(index int) *oscommands.CmdObj {
extDiffCmd := self.pagerConfig.GetExternalDiffCommand()
contextSize := self.UserConfig().Git.DiffContextSize
extDiffCmd := self.pagerConfig.GetExternalDiffCommand(contextSize)
useExtDiffGitConfig := self.pagerConfig.GetUseExternalDiffGitConfig()
// "-u" is the same as "--include-untracked", but the latter fails in older git versions for some reason
@ -92,7 +93,7 @@ func (self *StashCommands) ShowStashEntryCmdObj(index int) *oscommands.CmdObj {
ConfigIf(extDiffCmd != "", "diff.external="+extDiffCmd).
ArgIfElse(extDiffCmd != "" || useExtDiffGitConfig, "--ext-diff", "--no-ext-diff").
Arg(fmt.Sprintf("--color=%s", self.pagerConfig.GetColorArg())).
Arg(fmt.Sprintf("--unified=%d", self.UserConfig().Git.DiffContextSize)).
Arg(fmt.Sprintf("--unified=%d", contextSize)).
ArgIf(self.UserConfig().Git.IgnoreWhitespaceInDiffView, "--ignore-all-space").
Arg(fmt.Sprintf("--find-renames=%d%%", self.UserConfig().Git.RenameSimilarityThreshold)).
Arg(fmt.Sprintf("refs/stash@{%d}", index)).

View file

@ -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
}
@ -213,51 +218,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 +287,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 +294,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
}

View file

@ -401,7 +401,7 @@ func (self *WorkingTreeCommands) WorktreeFileDiffCmdObj(node models.IFile, plain
contextSize := self.UserConfig().Git.DiffContextSize
prevPath := node.GetPreviousPath()
noIndex := !node.GetIsTracked() && !node.GetHasStagedChanges() && !cached && node.GetIsFile()
extDiffCmd := self.pagerConfig.GetExternalDiffCommand()
extDiffCmd := self.pagerConfig.GetExternalDiffCommand(contextSize)
useExtDiff := extDiffCmd != "" && !plain
useExtDiffGitConfig := self.pagerConfig.GetUseExternalDiffGitConfig() && !plain
@ -450,7 +450,7 @@ func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reve
colorArg = "never"
}
extDiffCmd := self.pagerConfig.GetExternalDiffCommand()
extDiffCmd := self.pagerConfig.GetExternalDiffCommand(contextSize)
useExtDiff := extDiffCmd != "" && !plain
useExtDiffGitConfig := self.pagerConfig.GetUseExternalDiffGitConfig() && !plain

View file

@ -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())

View file

@ -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")
}

View file

@ -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() {
}

View file

@ -36,7 +36,16 @@ func (p *winPty) Resize(cols, rows uint16) error {
// there is nothing left to resize.
return nil
}
return windows.ResizePseudoConsole(p.hpc, windows.Coord{X: int16(cols), Y: int16(rows)})
return windows.ResizePseudoConsole(p.hpc, clampPtySize(cols, rows))
}
// clampPtySize clamps a requested pty size to the minimum that ConPTY
// accepts: CreatePseudoConsole and ResizePseudoConsole reject zero
// dimensions with E_INVALIDARG, but callers legitimately request them — the
// pty is sized after the main view, which is zero-sized while hidden, e.g.
// in full-screen mode with a side panel focused.
func clampPtySize(cols, rows uint16) windows.Coord {
return windows.Coord{X: int16(max(cols, 1)), Y: int16(max(rows, 1))}
}
// closeHpc closes the pseudoconsole exactly once. Safe to call from multiple
@ -140,7 +149,7 @@ func StartPty(cmd *exec.Cmd, cols, rows uint16) (sp StartedPty, err error) {
// 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)}
size := clampPtySize(cols, rows)
if err = windows.CreatePseudoConsole(size, inRead, outWrite, 0, &hpc); err != nil {
_ = windows.CloseHandle(inRead)
_ = windows.CloseHandle(outWrite)

View file

@ -0,0 +1,25 @@
package oscommands
import (
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
)
// The requested size can legitimately be zero: the pty inherits the main
// view's dimensions, and that view is zero-sized while hidden, e.g. in
// full-screen mode with a side panel focused.
func TestStartPtyWithZeroSize(t *testing.T) {
// The command deliberately produces no output: go test runs with
// redirected std handles, which CreateProcess duplicates into the child
// in place of handles to the attached pseudoconsole, so command output
// would bypass the pty and pollute the test log.
sp, err := StartPty(exec.Command("cmd", "/c", "exit 0"), 0, 0)
assert.NoError(t, err)
if err == nil {
_ = sp.Wait()
_ = sp.Pty.Close()
}
}

View file

@ -58,12 +58,17 @@ func (self *PagerConfig) GetColorArg() string {
return colorArg
}
func (self *PagerConfig) GetExternalDiffCommand() string {
func (self *PagerConfig) GetExternalDiffCommand(diffContext uint64) string {
currentPagerConfig := self.currentPagerConfig()
if currentPagerConfig == nil {
return ""
}
return currentPagerConfig.ExternalDiffCommand
templateValues := map[string]string{
"diffContext": strconv.Itoa(int(diffContext)),
}
return utils.ResolvePlaceholderString(currentPagerConfig.ExternalDiffCommand, templateValues)
}
func (self *PagerConfig) GetUseExternalDiffGitConfig() bool {

View file

@ -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,10 +258,14 @@ func (self *BackgroundRoutineMgr) goEvery(interval time.Duration, stop, retrigge
})
}
func (self *BackgroundRoutineMgr) backgroundFetch() (err error) {
err = self.gui.git.Sync.FetchBackground()
// 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()
return self.gui.helpers.BranchesHelper.PostFetchRefresh(err, true)
return branchesHelper.PostFetchRefresh(err, true, fetchGeneration)
}
func (self *BackgroundRoutineMgr) triggerImmediateFetch() {

View file

@ -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)
})
}

View file

@ -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

View file

@ -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)
}

View file

@ -1,12 +1,14 @@
package helpers
import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"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"
@ -79,24 +81,46 @@ 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 {
// 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
// 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).
@ -141,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
@ -167,12 +191,42 @@ 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.
env := refreshEnv{
background: options.Background,
generation: self.c.State().GetRepoGeneration(),
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")
}
// 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
// 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 || options.DontBlockRepoSwitch,
backgroundRoutine: options.Background,
}
self.captureOnUIThread(calledFromWorker, env.background, func() {
env.generation = self.c.State().GetRepoGeneration()
env.git = self.c.Git()
})
if options.BatchUIUpdates {
env.batch = &refreshBounceBatch{}
}
@ -226,7 +280,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()) {
@ -268,7 +322,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr
var capturedReflog capturedReflogState
var capturedBranches capturedBranchState
self.captureOnUIThread(calledFromWorker, env.background, func() {
capturedCommits = self.captureCommitsState(options.CommitSelection)
capturedCommits = self.captureCommitsState()
capturedReflog = self.captureReflogState()
capturedBranches = self.captureBranchState()
})
@ -461,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))
}
@ -515,12 +578,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
@ -641,7 +704,6 @@ func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflo
// 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
@ -653,17 +715,12 @@ type capturedCommitState struct {
// 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)
}
// The selection is captured later, when applying the refresh, so user input
// received while the git work is in flight is not overwritten.
func (self *RefreshHelper) captureCommitsState() capturedCommitState {
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(),
@ -704,15 +761,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 +779,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 +788,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,9 +806,15 @@ 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() {
var selectionRange *localCommitSelectionRange
if commitSelection == types.KeepCommitSelectionByHash {
selectedIdx, rangeStartIdx, rangeSelectMode := self.c.Contexts().LocalCommits.GetSelectionRangeAndMode()
selectionRange = captureLocalCommitSelectionRange(self.c.Model().Commits, selectedIdx, rangeStartIdx, rangeSelectMode)
}
self.c.Model().BisectInfo = bisectInfo
self.c.Model().Commits = commits
self.RefreshAuthors(commits)
@ -770,10 +833,10 @@ func (self *RefreshHelper) refreshCommitsWithLimit(captured capturedCommitState,
scrollSelectionIntoView = true
}
case types.KeepCommitSelectionByHash:
if captured.selectionRange != nil {
selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, captured.selectionRange)
if selectionRange != nil {
selectedIdx, rangeStartIdx, didMove, found := findLocalCommitSelectionRange(commits, selectionRange)
if found {
self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, captured.selectionRange.mode)
self.c.Contexts().LocalCommits.SetSelectionRangeAndMode(selectedIdx, rangeStartIdx, selectionRange.mode)
scrollSelectionIntoView = didMove
}
}
@ -902,7 +965,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 +1019,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 +1038,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 +1054,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 +1067,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,14 +1076,25 @@ 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,
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() {
@ -1035,7 +1109,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 +1174,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
}
@ -1168,11 +1242,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()
@ -1226,7 +1300,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 {
@ -1237,16 +1315,16 @@ 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,
Background: env.backgroundRoutine,
})
conflictFileCount := 0
@ -1257,7 +1335,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 +1418,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 +1460,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 +1492,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 +1502,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 +1515,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 +1527,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 +1551,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,18 +1603,18 @@ 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()] {
self.promptForBaseGithubRepo(githubRemotes, branches)
if !self.githubBaseRemotePromptDismissed[env.git.RepoPaths.RepoPath()] {
self.promptForBaseGithubRepo(githubRemotes)
}
return
}
@ -1550,12 +1628,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
}
@ -1612,7 +1690,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 +1700,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
})
},
@ -1666,13 +1740,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
@ -1684,8 +1758,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,

View file

@ -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
},
},
{

View file

@ -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,
})

View file

@ -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 {

View file

@ -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
}

View file

@ -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,

View file

@ -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
}
@ -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{})
// 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

View file

@ -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)
}

View file

@ -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()
}
@ -67,6 +77,25 @@ func (self *GuiDriver) FocusIn() {
self.waitTillIdle()
}
func (self *GuiDriver) FocusInAndClick(x, y int) {
self.CheckAllToastsAcknowledged()
self.gui.g.ReplayFocusEvent(gocui.NewTcellFocusEventWrapper(
tcell.NewEventFocus(true),
0,
))
self.gui.g.ReplayMouseEvent(gocui.NewTcellMouseEventWrapper(
tcell.NewEventMouse(x, y, tcell.ButtonPrimary, 0),
0,
))
self.waitTillIdle()
self.gui.g.ReplayMouseEvent(gocui.NewTcellMouseEventWrapper(
tcell.NewEventMouse(x, y, tcell.ButtonNone, 0),
0,
))
self.waitTillIdle()
}
func (self *GuiDriver) PretendMergeOrRebaseStartedInLazygit() {
self.gui.onUIThread(func() error {
self.gui.State.SetMergeOrRebaseStartedInLazygit(true)

View file

@ -58,6 +58,7 @@ func (p ptyCmd) GetProcess() *os.Process { return p.process }
// command.
func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error {
width := view.InnerWidth()
diffContext := gui.UserConfig().Git.DiffContextSize
// LAZYGIT_COLUMNS is documented in docs/Custom_Pagers.md for pager
// scripts that can't query the terminal width directly. We set it on
@ -65,7 +66,7 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
cmd.Env = append(cmd.Env, fmt.Sprintf("LAZYGIT_COLUMNS=%d", width))
pager := gui.stateAccessor.GetPagerConfig().GetPagerCommand(width)
externalDiffCommand := gui.stateAccessor.GetPagerConfig().GetExternalDiffCommand()
externalDiffCommand := gui.stateAccessor.GetPagerConfig().GetExternalDiffCommand(diffContext)
useExtDiffGitConfig := gui.stateAccessor.GetPagerConfig().GetUseExternalDiffGitConfig()
if pager == "" && externalDiffCommand == "" && !useExtDiffGitConfig {
@ -99,6 +100,7 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
cols, rows := gui.desiredPtySize(view)
var p oscommands.Pty
var fallbackPipe io.ReadCloser
start := func() (tasks.Cmd, io.Reader) {
// 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
@ -108,7 +110,11 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
sp, err := oscommands.StartPty(cmd, cols, rows)
if err != nil {
gui.c.Log.Error(err)
return tasks.ExecCmd{Cmd: cmd}, nil
// Fall back to running the command without a pty: the pager is
// lost, but the command's output still renders.
execCmd, pipe := startCmdWithPipe(cmd, gui.c.Log)
fallbackPipe = pipe
return execCmd, pipe
}
p = sp.Pty
@ -124,6 +130,10 @@ func (gui *Gui) newPtyTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
if p != nil {
p.Close()
}
if fallbackPipe != nil {
fallbackPipe.Close()
fallbackPipe = nil
}
delete(gui.viewPtmxMap, view.Name())
gui.Mutexes.PtyMutex.Unlock()
}

View file

@ -7,6 +7,7 @@ import (
"github.com/jesseduffield/lazygit/pkg/gocui"
"github.com/jesseduffield/lazygit/pkg/tasks"
"github.com/sirupsen/logrus"
)
func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error {
@ -29,19 +30,9 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
start := func() (tasks.Cmd, io.Reader) {
view.SetContentWidth(contentWidth)
var err error
r, err = cmd.StdoutPipe()
if err != nil {
gui.c.Log.Error(err)
r = nil
}
cmd.Stderr = cmd.Stdout
if err := cmd.Start(); err != nil {
gui.c.Log.Error(err)
}
return tasks.ExecCmd{Cmd: cmd}, r
execCmd, pipe := startCmdWithPipe(cmd, gui.c.Log)
r = pipe
return execCmd, pipe
}
onClose := func() {
@ -59,6 +50,27 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix string) error
return nil
}
// startCmdWithPipe starts cmd with its stdout and stderr going to a single
// pipe, and returns the command along with the pipe's read end, in the shape
// that NewCmdTask expects from its start func. It never returns a nil reader,
// because NewCmdTask's scanner panics on one: when the pipe can't be created
// the command isn't started at all, and an empty reader is returned so that
// the task shuts down cleanly with the error in the log.
func startCmdWithPipe(cmd *exec.Cmd, log *logrus.Entry) (tasks.Cmd, io.ReadCloser) {
r, err := cmd.StdoutPipe()
if err != nil {
log.Error(err)
return tasks.ExecCmd{Cmd: cmd}, io.NopCloser(strings.NewReader(""))
}
cmd.Stderr = cmd.Stdout
if err := cmd.Start(); err != nil {
log.Error(err)
}
return tasks.ExecCmd{Cmd: cmd}, r
}
func (gui *Gui) newStringTask(view *gocui.View, str string) error {
// using str so that if rendering the exact same thing we don't reset the origin
return gui.newStringTaskWithKey(view, str, str)

View file

@ -0,0 +1,24 @@
package gui
import (
"bytes"
"os/exec"
"testing"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/stretchr/testify/assert"
)
func TestStartCmdWithPipeWhenPipeCannotBeCreated(t *testing.T) {
cmd := exec.Command("non-existent-command")
// Assigning stdout up front makes cmd.StdoutPipe fail. This happens in
// practice on the Unix pty fallback path: a failed pty start can leave
// the tty assigned to the command's stdout.
cmd.Stdout = &bytes.Buffer{}
_, r := startCmdWithPipe(cmd, utils.NewDummyLog())
// NewCmdTask's scanner panics on a nil reader, so startCmdWithPipe must
// not return one even when it can't create the pipe.
assert.NotNil(t, r)
}

View file

@ -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

View file

@ -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
}

View file

@ -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)
@ -63,6 +73,12 @@ func (self *TestDriver) FocusIn() {
self.Wait(self.inputDelay)
}
func (self *TestDriver) focusInAndClick(x, y int) {
self.SetCaption(fmt.Sprintf("Focusing window and clicking %d, %d", x, y))
self.gui.FocusInAndClick(x, y)
self.Wait(self.inputDelay)
}
func (self *TestDriver) typeContent(content string) {
for _, char := range content {
self.pressFast(string(char))

View file

@ -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})
}
@ -37,6 +41,10 @@ func (self *fakeGuiDriver) Click(x, y int) {
func (self *fakeGuiDriver) FocusIn() {
}
func (self *fakeGuiDriver) FocusInAndClick(x, y int) {
self.clickedCoordinates = append(self.clickedCoordinates, coordinate{x: x, y: y})
}
func (self *fakeGuiDriver) Keys() config.KeybindingConfig {
return config.KeybindingConfig{}
}

View file

@ -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()
@ -462,6 +475,14 @@ func (self *ViewDriver) Click(x, y int) *ViewDriver {
return self
}
func (self *ViewDriver) FocusInAndClick(x, y int) *ViewDriver {
offsetX, offsetY, _, _ := self.getView().Dimensions()
self.t.focusInAndClick(offsetX+1+x, offsetY+1+y)
return self
}
// i.e. pressing down arrow
func (self *ViewDriver) SelectNextItem() *ViewDriver {
return self.PressFast(self.t.keys.Universal.NextItem)

View file

@ -0,0 +1,26 @@
package commit
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var KeepClickedCommitSelectedAfterFocusIn = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Keep a clicked commit selected when focus-in immediately precedes the click",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(2)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Focus().
Lines(
Contains("commit-02").IsSelected(),
Contains("commit-01"),
).
FocusInAndClick(1, 1).
SelectedLine(Contains("commit-01"))
},
})

View file

@ -0,0 +1,60 @@
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()
}).
Lines(
Contains("commit-03"),
Contains("commit-02"),
Contains("commit-04"),
Contains("commit-01"),
)
},
})

View file

@ -0,0 +1,50 @@
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)
t.Views().StagingSecondary().
IsFocused().
ContainsLines(
Contains("+1b"),
Contains("+2b"),
).
ContainsLines(
Contains("+3b"),
Contains("+4b"),
)
},
})

View file

@ -140,6 +140,7 @@ var tests = []*components.IntegrationTest{
commit.Highlight,
commit.History,
commit.HistoryComplex,
commit.KeepClickedCommitSelectedAfterFocusIn,
commit.KeepSelectedCommitAfterExternalCommit,
commit.NewBranch,
commit.PasteCommitMessage,
@ -310,6 +311,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,
@ -403,6 +405,7 @@ var tests = []*components.IntegrationTest{
staging.SelectNextLineAfterStagingInTwoHunkDiff,
staging.SelectNextLineAfterStagingIsolatedAddedLine,
staging.StageHunks,
staging.StageHunksWithRapidKeypresses,
staging.StageLines,
staging.StagePartialBlockOfChangesFirstLines,
staging.StagePartialBlockOfChangesLastLines,

View file

@ -23,10 +23,17 @@ 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)
FocusIn()
// Simulate a terminal dispatching focus-in immediately followed by a click,
// without waiting for the focus refresh to finish in between.
FocusInAndClick(int, int)
Keys() config.KeybindingConfig
CurrentContext() types.Context
ContextForView(viewName string) types.Context