diff --git a/docs-master/Config.md b/docs-master/Config.md index d8de794be..73fc0d8a5 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -421,7 +421,7 @@ git: # # e.g. # # diff-so-fancy # # delta --dark --paging=never - # # ydiff -p cat + # # ydiff -p cat --color=always # # difft --color=always # command: "" # diff --git a/docs-master/Custom_DiffRenderers.md b/docs-master/Custom_DiffRenderers.md index 05e806d40..2d8efe73b 100644 --- a/docs-master/Custom_DiffRenderers.md +++ b/docs-master/Custom_DiffRenderers.md @@ -2,7 +2,7 @@ Custom diff renderers are useful for showing a better rendering of a diff than git's builtin raw diff, and using one is strongly recommended (I personally prefer delta myself, but that's a matter of personal preference). There are three types of diff renderers that lazygit supports: -- **stdin filters**, e.g. [delta](#delta) and [diff-so-fancy](#diff-so-fancy). They take git's raw output as stdin and produce something nicer on stdout, and they are hooked up using git's GIT_PAGER mechanism. (These used to be called "custom pagers" in earlier lazygit versions.) +- **stdin filters**, e.g. [delta](#delta) and [diff-so-fancy](#diff-so-fancy). They take git's raw output as stdin and produce something nicer on stdout; lazygit pipes git's output into them. (These used to be called "custom pagers" in earlier lazygit versions.) - **external diff programs**, e.g. difftastic; these are called using git's `--ext-diff` flag, and they take over diff generation from git completely rather than post-processing git's output. - **git's raw output using custom arguments**; mainly useful for `--color-words` (or `--word-diff` if you are color blind). @@ -15,7 +15,7 @@ Fields that are shared by all renderer types: Fields only for `stdinFilter`: -- **command** The command line to use for `GIT_PAGER`. +- **command** The command line that git's output is piped into. - **colorArg** whether you want the `--color=always` arg in your `git diff` command. Some diff renderers want it set to `always`, others want it set to `never`. The default is `always`, since that's what most renderers need. @@ -31,18 +31,23 @@ The `command` of a `stdinFilter` or `extDiff` renderer is a [Go template](https: - `{{width}}`: the width of the view that the diff is rendered into. - `{{colorScheme}}`: `dark` or `light`, depending on whether the terminal has a dark or a light background. Lazygit asks the terminal about this; if yours doesn't tell, set `gui.colorScheme`. -- `{{columnWidth}}` (only for `stdinFilter`): the width of one side of a side-by-side rendering, e.g. for `ydiff -p cat -s -w {{columnWidth}}`. +- `{{columnWidth}}` (only for `stdinFilter`): the width of one side of a side-by-side rendering, e.g. for `ydiff -p cat --color=always -s -w {{columnWidth}}`. - `{{diffContext}}` (only for `extDiff`): lazygit's current diff context size, the value controlled by the `{`/`}` keybindings. A variable can also be written with a leading dot, as in `{{.width}}`. The command can use template expressions too; for example, `delta --paging=never {{if gt .width 160}}--side-by-side{{end}}` shows the diff side by side only when there is room for it, or `delta --syntax-theme={{if eq .colorScheme "light"}}Github{{else}}Dracula{{end}}` picks a different syntax theme based on the background. +A diff renderer doesn't run in a terminal; its output reaches lazygit through a pipe. So: + +- A renderer that uses colors only when it writes to a terminal has to be told to use them anyway, for example with `--color=always` for difftastic or ydiff. +- A renderer can't ask a terminal how wide it should lay itself out. Lazygit sets the `COLUMNS` environment variable to the width of the view, which difftastic, diff-so-fancy and recent versions of delta read. For a renderer that doesn't, pass the width with `{{width}}`, for example `delta --width={{width}}`. + Here's an example for a multi-renderer setup: ```yaml git: diffRenderers: - command: delta --{{colorScheme}} --paging=never - - command: ydiff -p cat + - command: ydiff -p cat --color=always colorArg: never - type: extDiff command: difft --color=always --background={{colorScheme}} --context={{diffContext}} @@ -87,7 +92,7 @@ gui: git: diffRenderers: - colorArg: never - command: ydiff -p cat + command: ydiff -p cat --color=always ``` ![](https://i.imgur.com/vaa8z0H.png) diff --git a/pkg/commands/git_commands/commit.go b/pkg/commands/git_commands/commit.go index 3d61a3e11..68546f492 100644 --- a/pkg/commands/git_commands/commit.go +++ b/pkg/commands/git_commands/commit.go @@ -6,6 +6,7 @@ import ( "github.com/go-errors/errors" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/samber/lo" ) var ErrInvalidCommitIndex = errors.New("invalid commit index") @@ -155,13 +156,39 @@ func (self *CommitCommands) signoffFlag() string { } func (self *CommitCommands) GetCommitMessage(commitHash string) (string, error) { + messages, err := self.GetCommitMessages([]string{commitHash}) + if err != nil { + return "", err + } + + return messages[0], nil +} + +// GetCommitMessages returns the messages of the given commits, in the order in +// which the hashes were passed in. +func (self *CommitCommands) GetCommitMessages(commitHashes []string) ([]string, error) { cmdArgs := NewGitCmd("log"). - Arg("--format=%B", "--max-count=1", commitHash). + Arg("--no-walk=unsorted", "--format=%B%x00"). + Arg(commitHashes...). Config("log.showsignature=false"). ToArgv() - message, err := self.cmd.New(cmdArgs).DontLog().RunWithOutput() - return strings.ReplaceAll(strings.TrimSpace(message), "\r\n", "\n"), err + output, err := self.cmd.New(cmdArgs).DontLog().RunWithOutput() + if err != nil { + return nil, err + } + + // The messages are NUL-terminated, so the split gives us one more element + // than we asked for (holding the newline that git prints after the last + // message). + messages := strings.Split(output, "\x00") + if len(messages) <= len(commitHashes) { + return nil, errors.New("unexpected output from git log") + } + + return lo.Map(messages[:len(commitHashes)], func(message string, _ int) string { + return strings.ReplaceAll(strings.TrimSpace(message), "\r\n", "\n") + }), nil } func (self *CommitCommands) GetCommitSubject(commitHash string) (string, error) { diff --git a/pkg/commands/git_commands/commit_test.go b/pkg/commands/git_commands/commit_test.go index 81f6e1d8f..34690b006 100644 --- a/pkg/commands/git_commands/commit_test.go +++ b/pkg/commands/git_commands/commit_test.go @@ -378,7 +378,7 @@ func TestGetCommitMsg(t *testing.T) { for _, s := range scenarios { t.Run(s.testName, func(t *testing.T) { instance := buildCommitCommands(commonDeps{ - runner: oscommands.NewFakeRunner(t).ExpectGitArgs([]string{"-c", "log.showsignature=false", "log", "--format=%B", "--max-count=1", "deadbeef"}, s.input, nil), + runner: oscommands.NewFakeRunner(t).ExpectGitArgs([]string{"-c", "log.showsignature=false", "log", "--no-walk=unsorted", "--format=%B%x00", "deadbeef"}, s.input+"\x00\n", nil), }) output, err := instance.GetCommitMessage("deadbeef") @@ -390,6 +390,21 @@ func TestGetCommitMsg(t *testing.T) { } } +func TestGetCommitMessages(t *testing.T) { + instance := buildCommitCommands(commonDeps{ + runner: oscommands.NewFakeRunner(t).ExpectGitArgs( + []string{"-c", "log.showsignature=false", "log", "--no-walk=unsorted", "--format=%B%x00", "deadbeef", "1234567"}, + "first subject\n\nfirst body\n\x00\nsecond subject\n\x00\n", + nil, + ), + }) + + output, err := instance.GetCommitMessages([]string{"deadbeef", "1234567"}) + + assert.NoError(t, err) + assert.Equal(t, []string{"first subject\n\nfirst body", "second subject"}, output) +} + func TestGetCommitMessageFromHistory(t *testing.T) { type scenario struct { testName string @@ -406,7 +421,7 @@ func TestGetCommitMessageFromHistory(t *testing.T) { }, { "Default case to retrieve a commit in history", - oscommands.NewFakeRunner(t).ExpectGitArgs([]string{"log", "-1", "--skip=2", "--pretty=%H"}, "hash3 \n", nil).ExpectGitArgs([]string{"-c", "log.showsignature=false", "log", "--format=%B", "--max-count=1", "hash3"}, `use generics to DRY up context code`, nil), + oscommands.NewFakeRunner(t).ExpectGitArgs([]string{"log", "-1", "--skip=2", "--pretty=%H"}, "hash3 \n", nil).ExpectGitArgs([]string{"-c", "log.showsignature=false", "log", "--no-walk=unsorted", "--format=%B%x00", "hash3"}, "use generics to DRY up context code\x00\n", nil), func(output string, err error) { assert.NoError(t, err) assert.Equal(t, "use generics to DRY up context code", output) diff --git a/pkg/commands/git_commands/deps_test.go b/pkg/commands/git_commands/deps_test.go index b378df47d..f514be35c 100644 --- a/pkg/commands/git_commands/deps_test.go +++ b/pkg/commands/git_commands/deps_test.go @@ -120,6 +120,11 @@ func buildSubmoduleCommands(deps commonDeps) *SubmoduleCommands { return NewSubmoduleCommands(gitCommon) } +func buildDiffCommands(deps commonDeps) *DiffCommands { + gitCommon := buildGitCommon(deps) + return NewDiffCommands(gitCommon) +} + func buildCommitCommands(deps commonDeps) *CommitCommands { gitCommon := buildGitCommon(deps) return NewCommitCommands(gitCommon) diff --git a/pkg/commands/git_commands/diff.go b/pkg/commands/git_commands/diff.go index 471af511d..ddfa489ca 100644 --- a/pkg/commands/git_commands/diff.go +++ b/pkg/commands/git_commands/diff.go @@ -2,11 +2,15 @@ package git_commands import ( "fmt" + "io" "os" + "path/filepath" + "slices" "strings" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/config" + "github.com/jesseduffield/lazygit/pkg/utils" "github.com/mgutz/str" ) @@ -208,6 +212,171 @@ func (self *DiffCommands) getDiffCmdObj(worktreePath string, staged bool, additi ).DontLog() } +// NamedText is a text to be diffed by a TextDiffer, along with the name to show +// for it in the diff. The name doubles as the name of the temporary file holding +// the text, so it has to be usable as a file name. +type NamedText struct { + Name string + Content string +} + +// A TextDiffer diffs two texts with the configured diff renderer, in the same way +// as every other diff we show. It holds everything it takes from the +// configuration, so that it can render a diff on any goroutine. +type TextDiffer struct { + diffCommands *DiffCommands + + // The git command that diffs the two texts, up to the names of the files + // holding them + args []string + rawGit bool + stdinFilter string + externalDiff string + width int +} + +// NewTextDiffer resolves what a TextDiffer takes from the configuration. values +// are what the renderer's command is resolved with. values.Width is the width of +// the view the diff is going to be shown in; a diff renderer lays its output out +// to it. +// +// It has to be called on the UI thread, since that is where the user switches +// diff renderers and has the config reloaded. +func (self *DiffCommands) NewTextDiffer(values config.DiffRendererValues) (*TextDiffer, error) { + manager := self.diffRendererConfigManager + stdinFilter, err := manager.GetStdinFilterCommand(values) + if err != nil { + return nil, err + } + externalDiff, err := manager.GetExternalDiffCommand(values) + if err != nil { + return nil, err + } + + return &TextDiffer{ + diffCommands: self, + args: NewGitCmd("diff"). + // git heads a hunk with the nearest line above it that starts with + // a letter, for the name of the function the hunk is in. In a text, + // that is just a line out of context. A pattern that never matches + // leaves it out; "default" is the driver of a file that no + // attribute gives one. + Config("diff.default.xfuncname=x^"). + AddCommonDiffArgs(manager, self.UserConfig(), DiffModeRendered). + Arg("--no-index", "--no-prefix"). + Arg(fmt.Sprintf("--color=%s", DiffModeRendered.colorArg(manager))). + ToArgv(), + rawGit: manager.GetDiffRendererType() == config.DiffRendererType_RawGit, + stdinFilter: stdinFilter, + externalDiff: externalDiff, + width: values.Width, + }, nil +} + +// RenderedDiff returns a diff of the two given texts. +// +// git can only diff files, so the texts are written to temporary files named +// after them. Under a diff renderer those names are what the diff calls the two +// sides; under git's own diff they go away with the rest of the header. +func (self *TextDiffer) RenderedDiff(before NamedText, after NamedText) (string, error) { + dir, err := os.MkdirTemp(self.diffCommands.os.GetTempDir(), "textdiff-") + if err != nil { + return "", err + } + defer os.RemoveAll(dir) + + for _, text := range []NamedText{before, after} { + content := text.Content + // End the file with a newline, or git says that it doesn't, which tells + // a reader of the diff nothing about the two texts. + if content != "" && !strings.HasSuffix(content, "\n") { + content += "\n" + } + if err := self.diffCommands.os.CreateFileWithContent(filepath.Join(dir, text.Name), content); err != nil { + return "", err + } + } + + cmdObj := self.diffCommands.cmd.New( + append(slices.Clone(self.args), "--", before.Name, after.Name), + ).SetWd(dir).DontLog() + + // --no-index implies --exit-code, so git exits with a non-zero status + // whenever the two texts differ; that is only an error if it left us with + // nothing to show. + if self.rawGit { + // git renders the diff itself here, and needs none of what a renderer is + // told below. + output, err := cmdObj.RunWithOutput() + if output == "" && err != nil { + return "", err + } + + return stripDiffHeaders(output), nil + } + + oscommands.SetDumbTerminalEnv(cmdObj.GetCmd()) + // A renderer has no terminal to ask how wide it is (see runThroughAPipe). + cmdObj.AddEnvVars(fmt.Sprintf("COLUMNS=%d", self.width)) + // An empty command means that git's own diff.external config applies, and + // git consults that only while the variable is unset. + if self.externalDiff != "" { + cmdObj.AddEnvVars("GIT_EXTERNAL_DIFF=" + self.externalDiff) + } + + output, err := self.runThroughAPipe(cmdObj) + if output == "" && err != nil { + return "", err + } + + return output, nil +} + +// runThroughAPipe feeds the output of cmdObj to the stdin filter through a pipe +// and returns what the filter wrote. git only runs a stdin filter itself when it +// thinks it is talking to a terminal, so here the filter is a command of our +// own. An external diff renderer is run by git, so with one the command runs +// alone. +// +// The commands start without a controlling terminal, like those of the main +// view's renders. A renderer that found lazygit's terminal would lay itself out +// to the width of the whole window rather than to the width it is told in +// COLUMNS. +func (self *TextDiffer) runThroughAPipe(cmdObj *oscommands.CmdObj) (string, error) { + oscommands.DetachFromTerminal(cmdObj.GetCmd()) + if self.stdinFilter == "" { + return cmdObj.RunWithOutput() + } + + // The filter runs in a plain shell, with git's environment, since that is + // how git would have run it. + filter := self.diffCommands.cmd.NewShell(self.stdinFilter, "").SetEnviron(cmdObj.GetCmd().Env).DontLog() + oscommands.DetachFromTerminal(filter.GetCmd()) + pipeline, reader, err := self.diffCommands.os.StartPipeline(cmdObj, filter) + if err != nil { + return "", err + } + defer reader.Close() + + // The output ends once every command in the pipeline has exited, and Wait + // says how they did. + output, _ := io.ReadAll(reader) + return string(output), pipeline.Wait() +} + +// Strips the file header and the first hunk header from a diff. For a diff of +// two temporary files these say nothing that a reader could make sense of. +func stripDiffHeaders(diff string) string { + lines := strings.SplitAfter(diff, "\n") + for i, line := range lines { + if strings.HasPrefix(utils.Decolorise(line), "@@ ") { + return strings.Join(lines[i+1:], "") + } + } + + return diff +} + type DiffToolCmdOptions struct { // The path to show a diff for. Pass "." for the entire repo. Filepath string diff --git a/pkg/commands/git_commands/diff_inputs.go b/pkg/commands/git_commands/diff_inputs.go new file mode 100644 index 000000000..0cad71948 --- /dev/null +++ b/pkg/commands/git_commands/diff_inputs.go @@ -0,0 +1,114 @@ +package git_commands + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/spf13/afero" +) + +// DiffInputs is what the diffs of some files of the working tree are made from, as far +// as it can be told without reading the files: each file's entries in the index, the +// commit HEAD is at for the staged side of the diffs, and the type, permissions, size +// and modification time of each file in the working tree for the unstaged side. +// +// Taken again later and compared, it tells whether the files' diffs may have changed in +// between. Some changes alter the inputs without changing a diff: HEAD moving to a +// commit with the same version of a file, or a file written with the content it has. +// And a rewrite of a file that keeps its size and modification time goes unnoticed. +type DiffInputs struct { + // The commit HEAD is at, if taken for the staged side; "" in a repo without commits. + head string + + // Each file's entries in the index, as `git ls-files -s` prints them, by repo-relative + // path; "" for a file that has none. + indexEntries map[string]string + + // What a stat of each file in the working tree says, by repo-relative path, if taken + // for the unstaged side; "" for a file that doesn't exist. + files map[string]string +} + +// GetDiffInputs takes the DiffInputs of the files at the given repo-relative paths, for +// the staged side of their diffs, the unstaged side, or both. +func (self *WorkingTreeCommands) GetDiffInputs(paths []string, stagedSide bool, unstagedSide bool) (*DiffInputs, error) { + inputs := &DiffInputs{indexEntries: map[string]string{}} + + for _, path := range paths { + inputs.indexEntries[path] = "" + } + for _, batch := range pathsPerCommandLine(paths) { + output, err := self.cmd.New( + NewGitCmd("ls-files").Arg("-s", "-z", "--").Arg(batch...).Dir(self.repoPaths.worktreePath).ToArgv(), + ).DontLog().RunWithOutput() + if err != nil { + return nil, err + } + // An entry is " \t"; a file with a merge conflict has + // one for each stage. + for entry := range strings.SplitSeq(output, "\x00") { + if _, path, ok := strings.Cut(entry, "\t"); ok { + inputs.indexEntries[path] += entry + "\n" + } + } + } + + if stagedSide { + // In a repo without commits there is no HEAD to verify, and git prints nothing. + // That is a state like any other, so the error is no reason to fail. + head, _ := self.cmd.New(NewGitCmd("rev-parse").Arg("--verify", "--quiet", "HEAD").ToArgv()). + DontLog().RunWithOutput() + inputs.head = strings.TrimSpace(head) + } + + if unstagedSide { + inputs.files = map[string]string{} + for _, path := range paths { + inputs.files[path] = self.statWorkingTreeFile(filepath.Join(self.repoPaths.worktreePath, path)) + } + } + + return inputs, nil +} + +// statWorkingTreeFile describes a file of the working tree by what a stat of it says, +// without following a symlink: git diffs a symlink as the path it points to. It is "" +// for a file that doesn't exist. +func (self *WorkingTreeCommands) statWorkingTreeFile(path string) string { + var info os.FileInfo + var err error + if lstater, ok := self.Fs.(afero.Lstater); ok { + info, _, err = lstater.LstatIfPossible(path) + } else { + info, err = self.Fs.Stat(path) + } + if err != nil { + return "" + } + return fmt.Sprintf("%v %d %d", info.Mode(), info.Size(), info.ModTime().UnixNano()) +} + +// SameFor reports whether the inputs of the diffs of the files at the given +// repo-relative paths, on the given side, are the same in both. +func (self *DiffInputs) SameFor(other *DiffInputs, paths []string, stagedSide bool) bool { + for _, path := range paths { + if self.indexEntries[path] != other.indexEntries[path] { + return false + } + if !stagedSide && self.files[path] != other.files[path] { + return false + } + } + return !stagedSide || self.head == other.head +} + +// Paths returns the repo-relative paths of the files whose inputs were taken. +func (self *DiffInputs) Paths() []string { + paths := make([]string, 0, len(self.indexEntries)) + for path := range self.indexEntries { + paths = append(paths, path) + } + return paths +} diff --git a/pkg/commands/git_commands/diff_inputs_test.go b/pkg/commands/git_commands/diff_inputs_test.go new file mode 100644 index 000000000..c54f83e45 --- /dev/null +++ b/pkg/commands/git_commands/diff_inputs_test.go @@ -0,0 +1,122 @@ +package git_commands + +import ( + "errors" + "testing" + "time" + + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" +) + +func TestGetDiffInputs(t *testing.T) { + lsFilesArgs := []string{"-C", "/repo", "ls-files", "-s", "-z", "--", "file1", "conflicted", "untracked"} + lsFilesOutput := "100644 1111111111111111111111111111111111111111 0\tfile1\x00" + + "100644 2222222222222222222222222222222222222222 1\tconflicted\x00" + + "100644 3333333333333333333333333333333333333333 2\tconflicted\x00" + revParseArgs := []string{"rev-parse", "--verify", "--quiet", "HEAD"} + + fs := afero.NewMemMapFs() + assert.NoError(t, afero.WriteFile(fs, "/repo/file1", []byte("one\n"), 0o644)) + assert.NoError(t, afero.WriteFile(fs, "/repo/untracked", []byte("two\n"), 0o644)) + modTime := time.Unix(1700000000, 123456789) + assert.NoError(t, fs.Chtimes("/repo/file1", modTime, modTime)) + assert.NoError(t, fs.Chtimes("/repo/untracked", modTime, modTime)) + + runner := oscommands.NewFakeRunner(t). + ExpectGitArgs(lsFilesArgs, lsFilesOutput, nil). + ExpectGitArgs(revParseArgs, "abcdef\n", nil) + instance := buildWorkingTreeCommands(commonDeps{runner: runner, fs: fs, repoPaths: MockRepoPaths("/repo")}) + + inputs, err := instance.GetDiffInputs([]string{"file1", "conflicted", "untracked"}, true, true) + assert.NoError(t, err) + runner.CheckForMissingCalls() + + assert.Equal(t, &DiffInputs{ + head: "abcdef", + indexEntries: map[string]string{ + "file1": "100644 1111111111111111111111111111111111111111 0\tfile1\n", + "conflicted": "100644 2222222222222222222222222222222222222222 1\tconflicted\n" + + "100644 3333333333333333333333333333333333333333 2\tconflicted\n", + "untracked": "", + }, + files: map[string]string{ + "file1": "-rw-r--r-- 4 1700000000123456789", + "conflicted": "", + "untracked": "-rw-r--r-- 4 1700000000123456789", + }, + }, inputs) + assert.ElementsMatch(t, []string{"file1", "conflicted", "untracked"}, inputs.Paths()) +} + +func TestGetDiffInputsOneSide(t *testing.T) { + lsFilesArgs := []string{"-C", "/repo", "ls-files", "-s", "-z", "--", "file1"} + revParseArgs := []string{"rev-parse", "--verify", "--quiet", "HEAD"} + + // The unstaged side doesn't need HEAD. + runner := oscommands.NewFakeRunner(t). + ExpectGitArgs(lsFilesArgs, "", nil) + instance := buildWorkingTreeCommands(commonDeps{runner: runner, fs: afero.NewMemMapFs(), repoPaths: MockRepoPaths("/repo")}) + inputs, err := instance.GetDiffInputs([]string{"file1"}, false, true) + assert.NoError(t, err) + runner.CheckForMissingCalls() + assert.Equal(t, &DiffInputs{indexEntries: map[string]string{"file1": ""}, files: map[string]string{"file1": ""}}, inputs) + + // The staged side doesn't need the working tree. In a repo without commits, there is + // no HEAD. + runner = oscommands.NewFakeRunner(t). + ExpectGitArgs(lsFilesArgs, "", nil). + ExpectGitArgs(revParseArgs, "", errors.New("exit status 1")) + instance = buildWorkingTreeCommands(commonDeps{runner: runner, fs: afero.NewMemMapFs(), repoPaths: MockRepoPaths("/repo")}) + inputs, err = instance.GetDiffInputs([]string{"file1"}, true, false) + assert.NoError(t, err) + runner.CheckForMissingCalls() + assert.Equal(t, &DiffInputs{indexEntries: map[string]string{"file1": ""}}, inputs) + + // A failure to read the index is one. + runner = oscommands.NewFakeRunner(t). + ExpectGitArgs(lsFilesArgs, "", errors.New("fatal")) + instance = buildWorkingTreeCommands(commonDeps{runner: runner, fs: afero.NewMemMapFs(), repoPaths: MockRepoPaths("/repo")}) + _, err = instance.GetDiffInputs([]string{"file1"}, true, true) + assert.Error(t, err) +} + +func TestDiffInputsSameFor(t *testing.T) { + inputs := func(head string, entry string, file string) *DiffInputs { + return &DiffInputs{ + head: head, + indexEntries: map[string]string{"file1": entry, "file2": "100644 2222 0\tfile2\n"}, + files: map[string]string{"file1": file, "file2": "-rw-r--r-- 2 2"}, + } + } + base := inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1") + paths := []string{"file1"} + + scenarios := []struct { + testName string + other *DiffInputs + stagedSide bool + expected bool + }{ + {"same, unstaged side", inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1"), false, true}, + {"same, staged side", inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1"), true, true}, + {"index entry changed, unstaged side", inputs("abc", "100644 9999 0\tfile1\n", "-rw-r--r-- 1 1"), false, false}, + {"index entry changed, staged side", inputs("abc", "100644 9999 0\tfile1\n", "-rw-r--r-- 1 1"), true, false}, + {"file changed, unstaged side", inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 2"), false, false}, + {"file changed, staged side", inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 2"), true, true}, + {"HEAD moved, unstaged side", inputs("def", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1"), false, true}, + {"HEAD moved, staged side", inputs("def", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1"), true, false}, + } + + for _, s := range scenarios { + t.Run(s.testName, func(t *testing.T) { + assert.Equal(t, s.expected, base.SameFor(s.other, paths, s.stagedSide)) + }) + } + + // Only the files asked about count. + other := inputs("abc", "100644 1111 0\tfile1\n", "-rw-r--r-- 1 1") + other.indexEntries["file2"] = "100644 9999 0\tfile2\n" + assert.True(t, base.SameFor(other, paths, false)) +} diff --git a/pkg/commands/git_commands/diff_test.go b/pkg/commands/git_commands/diff_test.go new file mode 100644 index 000000000..14e413060 --- /dev/null +++ b/pkg/commands/git_commands/diff_test.go @@ -0,0 +1,128 @@ +package git_commands + +import ( + "os" + "path/filepath" + "testing" + + "github.com/go-errors/errors" + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/jesseduffield/lazygit/pkg/config" + "github.com/stretchr/testify/assert" +) + +func TestTextDifferRenderedDiff(t *testing.T) { + var args []string + var dir string + var beforeContent, afterContent string + + // The two texts are diffed as files in a temporary directory that is removed + // again afterwards, so read them here, while they are still there. + runner := oscommands.NewFakeRunner(t).ExpectFunc("text diff", + func(cmdObj *oscommands.CmdObj) bool { + args = cmdObj.GetCmd().Args + dir = cmdObj.GetCmd().Dir + before, _ := os.ReadFile(filepath.Join(dir, "old message")) + after, _ := os.ReadFile(filepath.Join(dir, "new message")) + beforeContent, afterContent = string(before), string(after) + return true + }, + "\x1b[1mdiff --git old message new message\x1b[m\n"+ + "\x1b[1mindex 9ebe4a6..ec3885a 100644\x1b[m\n"+ + "\x1b[1m--- old message\x1b[m\n"+ + "\x1b[1m+++ new message\x1b[m\n"+ + "\x1b[36m@@ -1,3 +1,3 @@\x1b[m\n"+ + "-Fix the widget\n"+ + "+Fix the widget on startup\n", + // --no-index implies --exit-code + errors.New("exit status 1")) + + instance := buildDiffCommands(commonDeps{runner: runner}) + + differ, err := instance.NewTextDiffer(config.DiffRendererValues{Width: 80, DiffContext: 3}) + assert.NoError(t, err) + output, err := differ.RenderedDiff( + NamedText{Name: "old message", Content: "Fix the widget\n"}, + NamedText{Name: "new message", Content: "Fix the widget on startup\n"}) + + assert.NoError(t, err) + assert.Equal(t, "-Fix the widget\n+Fix the widget on startup\n", output) + + assert.Equal(t, []string{ + "git", "-c", "diff.default.xfuncname=x^", "diff", "--no-ext-diff", "--unified=3", "--find-renames=50%", + "--no-index", "--no-prefix", "--color=always", "--", "old message", "new message", + }, args) + assert.Equal(t, "Fix the widget\n", beforeContent) + assert.Equal(t, "Fix the widget on startup\n", afterContent) + + assert.NoDirExists(t, dir) +} + +func TestTextDifferPassesOnTheRenderersGitArgs(t *testing.T) { + userConfig := config.GetDefaultConfig() + userConfig.Git.DiffRenderers = []config.DiffRendererConfig{ + {Type: "rawGit", Args: []string{"--color-words"}}, + } + + var args []string + runner := oscommands.NewFakeRunner(t).ExpectFunc("text diff", + func(cmdObj *oscommands.CmdObj) bool { + args = cmdObj.GetCmd().Args + return true + }, "", nil) + + instance := buildDiffCommands(commonDeps{runner: runner, userConfig: userConfig}) + + differ, err := instance.NewTextDiffer(config.DiffRendererValues{Width: 80, DiffContext: 3}) + assert.NoError(t, err) + _, err = differ.RenderedDiff( + NamedText{Name: "old message", Content: "one"}, + NamedText{Name: "new message", Content: "two"}) + + assert.NoError(t, err) + assert.Contains(t, args, "--color-words") +} + +func TestStripDiffHeaders(t *testing.T) { + scenarios := []struct { + name string + diff string + expectedOutput string + }{ + { + name: "colored diff", + diff: "\x1b[1mdiff --git old message new message\x1b[m\n" + + "\x1b[1mindex 9ebe4a6..ec3885a 100644\x1b[m\n" + + "\x1b[1m--- old message\x1b[m\n" + + "\x1b[1m+++ new message\x1b[m\n" + + "\x1b[36m@@ -1,3 +1,3 @@\x1b[m\n" + + "one \x1b[32mtwo\x1b[m\n", + expectedOutput: "one \x1b[32mtwo\x1b[m\n", + }, + { + name: "uncolored diff with several hunks", + diff: "diff --git old message new message\n" + + "index 9ebe4a6..ec3885a 100644\n" + + "--- old message\n" + + "+++ new message\n" + + "@@ -1,3 +1,3 @@\n" + + "one two\n" + + "@@ -20,3 +20,3 @@\n" + + "three four\n", + expectedOutput: "one two\n" + + "@@ -20,3 +20,3 @@\n" + + "three four\n", + }, + { + name: "empty diff", + diff: "", + expectedOutput: "", + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + assert.Equal(t, s.expectedOutput, stripDiffHeaders(s.diff)) + }) + } +} diff --git a/pkg/commands/git_commands/git_command_builder.go b/pkg/commands/git_commands/git_command_builder.go index fbc204f7a..7b26d0a58 100644 --- a/pkg/commands/git_commands/git_command_builder.go +++ b/pkg/commands/git_commands/git_command_builder.go @@ -187,11 +187,25 @@ func (self *GitCommandBuilder) ToString() string { } // runGitCmdOnPaths runs `git -- `, splitting into -// multiple calls if needed to stay under the OS command-line length limit. -// Windows CreateProcess has a ~32 KB limit; we use 30 KB as a safe threshold. +// multiple calls if needed (see pathsPerCommandLine). func runGitCmdOnPaths(subcommand string, paths []string, cmd oscommands.ICmdObjBuilder) error { + for _, batch := range pathsPerCommandLine(paths) { + if err := cmd.New(NewGitCmd(subcommand).Arg("--"). + Arg(batch...). + ToArgv()).Run(); err != nil { + return err + } + } + return nil +} + +// pathsPerCommandLine splits paths into batches that each stay under the OS +// command-line length limit when passed as arguments. Windows CreateProcess has a +// ~32 KB limit; we use 30 KB as a safe threshold. +func pathsPerCommandLine(paths []string) [][]string { const maxArgBytes = 30_000 + batches := [][]string{} start := 0 for start < len(paths) { end := start @@ -203,12 +217,8 @@ func runGitCmdOnPaths(subcommand string, paths []string, cmd oscommands.ICmdObjB } end++ } - if err := cmd.New(NewGitCmd(subcommand).Arg("--"). - Arg(paths[start:end]...). - ToArgv()).Run(); err != nil { - return err - } + batches = append(batches, paths[start:end]) start = end } - return nil + return batches } diff --git a/pkg/commands/oscommands/os.go b/pkg/commands/oscommands/os.go index 1a6921c55..b84b9cc37 100644 --- a/pkg/commands/oscommands/os.go +++ b/pkg/commands/oscommands/os.go @@ -4,6 +4,7 @@ import ( "bytes" "io" "os" + "os/exec" "path/filepath" "strings" @@ -13,6 +14,7 @@ import ( "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/utils" + "github.com/samber/lo" ) // OSCommand holds all the os commands @@ -333,3 +335,29 @@ func GetLazygitPath() string { } return `"` + filepath.ToSlash(ex) + `"` } + +// SetDumbTerminalEnv tells diff renderers that we're in a very simple terminal +// that they should not expect to have much capabilities. +// Moving the cursor, clearing the screen, or querying for colors are among such +// "advanced" capabilities. +// Context: https://github.com/jesseduffield/lazygit/issues/3419 +func SetDumbTerminalEnv(cmd *exec.Cmd) { + cmd.Env = append(removeExistingTermEnvVars(cmd.Env), "TERM=dumb") +} + +func removeExistingTermEnvVars(env []string) []string { + return lo.Filter(env, func(envVar string, _ int) bool { + return !isTermEnvVar(envVar) + }) +} + +// Terminals set a variety of different environment variables +// to identify themselves to processes. This list should catch the most common among them. +func isTermEnvVar(envVar string) bool { + return strings.HasPrefix(envVar, "TERM=") || + strings.HasPrefix(envVar, "TERM_PROGRAM=") || + strings.HasPrefix(envVar, "TERM_PROGRAM_VERSION=") || + strings.HasPrefix(envVar, "TERMINAL_EMULATOR=") || + strings.HasPrefix(envVar, "TERMINAL_NAME=") || + strings.HasPrefix(envVar, "TERMINAL_VERSION_") +} diff --git a/pkg/commands/oscommands/os_default_platform.go b/pkg/commands/oscommands/os_default_platform.go index 09f9f1d6d..521c638b8 100644 --- a/pkg/commands/oscommands/os_default_platform.go +++ b/pkg/commands/oscommands/os_default_platform.go @@ -45,6 +45,16 @@ 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) {} +// DetachFromTerminal has cmd start in a session of its own, which has no +// controlling terminal. A command that asks its terminal something, such as how +// wide it is, then finds no terminal rather than lazygit's. +func DetachFromTerminal(cmd *exec.Cmd) { + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.Setsid = true +} + func TerminateProcessGracefully(proc *os.Process) error { if proc == nil { return nil diff --git a/pkg/commands/oscommands/os_windows.go b/pkg/commands/oscommands/os_windows.go index d0252f5b1..006a927b9 100644 --- a/pkg/commands/oscommands/os_windows.go +++ b/pkg/commands/oscommands/os_windows.go @@ -41,6 +41,10 @@ func (c *OSCommand) UpdateWindowTitle() error { return c.Cmd.NewShell(argString, c.UserConfig().OS.ShellFunctionsFile).Run() } +// DetachFromTerminal does nothing on Windows; see the version for the other +// platforms. +func DetachFromTerminal(cmd *exec.Cmd) {} + func TerminateProcessGracefully(proc *os.Process) error { // Signals other than SIGKILL are not supported on Windows return nil diff --git a/pkg/commands/oscommands/pty.go b/pkg/commands/oscommands/pty.go index a4a369633..7e0ea3587 100644 --- a/pkg/commands/oscommands/pty.go +++ b/pkg/commands/oscommands/pty.go @@ -10,7 +10,6 @@ import ( // ConPTY on Windows. type Pty interface { io.ReadWriteCloser - Resize(cols, rows uint16) error } // StartedPty is the result of StartPty. diff --git a/pkg/commands/oscommands/pty_unix.go b/pkg/commands/oscommands/pty_unix.go index cd3962a8e..0c0f46200 100644 --- a/pkg/commands/oscommands/pty_unix.go +++ b/pkg/commands/oscommands/pty_unix.go @@ -17,10 +17,6 @@ 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 { diff --git a/pkg/commands/oscommands/pty_windows.go b/pkg/commands/oscommands/pty_windows.go index 54fd9da78..6b1385dba 100644 --- a/pkg/commands/oscommands/pty_windows.go +++ b/pkg/commands/oscommands/pty_windows.go @@ -25,11 +25,8 @@ type winPty struct { inWrite *os.File outRead *os.File - // 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 guards hpcClosed, which gates ClosePseudoConsole: it must run exactly + // once, and more than one goroutine may get to it (see closeHpc). mu sync.Mutex hpcClosed bool } @@ -37,17 +34,6 @@ type winPty struct { 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, 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 @@ -119,12 +105,9 @@ func TerminateLivePtys() { // 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 -// diff renderer 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. +// it, a client that keeps running keeps the host — and with it +// ClosePseudoConsole — alive arbitrarily long. None of this may happen on the +// caller's thread, which would be held up for that long. // // Within the teardown, the pipe ends must be closed before the // pseudoconsole, and without holding p.mu: closing the pseudoconsole flushes diff --git a/pkg/commands/patch/file_versions.go b/pkg/commands/patch/file_versions.go new file mode 100644 index 000000000..c0f754fad --- /dev/null +++ b/pkg/commands/patch/file_versions.go @@ -0,0 +1,75 @@ +package patch + +import "strings" + +// FileVersions names the two versions of a file that a diff of it is between, as the +// diff's header states them: the id of the blob each version is stored as, abbreviated +// the way git wrote it, and the mode of each. git writes an id of zeros for a version +// that doesn't exist, the old one of an added file or the new one of a deleted one, and +// that version has no mode. +// +// With the same diff options, two diffs of a file between the same versions are the +// same diff, line for line. So the versions tell whether a diff read now is still the +// one read earlier, however the file, the index or HEAD changed in between. +type FileVersions struct { + OldBlob string + NewBlob string + OldMode string + NewMode string +} + +// FileVersions returns the versions of the file the patch is a diff of. +func (self *Patch) FileVersions() FileVersions { + return ParseFileVersions(self.header) +} + +// ParseFileVersions reads the versions of a file from the header of its diff, given as +// the lines of the diff from its start; it stops at the first hunk. A header without +// an index line names no blobs. git leaves the index line out where the content +// doesn't change: a rename or copy of the file as it is, or a change of its mode alone. +func ParseFileVersions(lines []string) FileVersions { + versions := FileVersions{} + for _, line := range lines { + if strings.HasPrefix(line, "@@") { + break + } + switch { + case strings.HasPrefix(line, "index "): + // The mode is on the index line only if both versions have the same one. + blobs, mode, _ := strings.Cut(strings.TrimPrefix(line, "index "), " ") + versions.OldBlob, versions.NewBlob, _ = strings.Cut(blobs, "..") + if mode != "" { + versions.OldMode = mode + versions.NewMode = mode + } + case strings.HasPrefix(line, "old mode "): + versions.OldMode = strings.TrimPrefix(line, "old mode ") + case strings.HasPrefix(line, "new mode "): + versions.NewMode = strings.TrimPrefix(line, "new mode ") + case strings.HasPrefix(line, "deleted file mode "): + versions.OldMode = strings.TrimPrefix(line, "deleted file mode ") + case strings.HasPrefix(line, "new file mode "): + versions.NewMode = strings.TrimPrefix(line, "new file mode ") + } + } + return versions +} + +// Same reports whether two diffs are between the same versions of their file. +func (self FileVersions) Same(other FileVersions) bool { + return sameBlob(self.OldBlob, other.OldBlob) && + sameBlob(self.NewBlob, other.NewBlob) && + self.OldMode == other.OldMode && + self.NewMode == other.NewMode +} + +// sameBlob reports whether two abbreviated ids name the same blob. How many digits git +// abbreviates an id to depends on how many objects the repo has, so two diffs of the +// same blob can spell its id with different lengths; the shorter one is then a prefix +// of the longer one. An id that is missing matches only another missing one. +func sameBlob(a string, b string) bool { + if a == "" || b == "" { + return a == b + } + return strings.HasPrefix(a, b) || strings.HasPrefix(b, a) +} diff --git a/pkg/commands/patch/file_versions_test.go b/pkg/commands/patch/file_versions_test.go new file mode 100644 index 000000000..14b996bb7 --- /dev/null +++ b/pkg/commands/patch/file_versions_test.go @@ -0,0 +1,159 @@ +package patch + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseFileVersions(t *testing.T) { + scenarios := []struct { + testName string + diff string + expected FileVersions + }{ + { + testName: "modified file", + diff: `diff --git a/file1 b/file1 +index 9f439a7..20141c9 100644 +--- a/file1 ++++ b/file1 +@@ -1,3 +1,4 @@ + one ++index 1234567..89abcde 100755 + two + three +`, + expected: FileVersions{OldBlob: "9f439a7", NewBlob: "20141c9", OldMode: "100644", NewMode: "100644"}, + }, + { + testName: "added file", + diff: `diff --git a/file1 b/file1 +new file mode 100644 +index 0000000..3e75765 +--- /dev/null ++++ b/file1 +@@ -0,0 +1 @@ ++new +`, + expected: FileVersions{OldBlob: "0000000", NewBlob: "3e75765", NewMode: "100644"}, + }, + { + testName: "deleted file", + diff: `diff --git a/file1 b/file1 +deleted file mode 100644 +index 3e75765..0000000 +--- a/file1 ++++ /dev/null +@@ -1 +0,0 @@ +-new +`, + expected: FileVersions{OldBlob: "3e75765", NewBlob: "0000000", OldMode: "100644"}, + }, + { + testName: "changed mode and content", + diff: `diff --git a/file1 b/file1 +old mode 100644 +new mode 100755 +index 9f439a7..20141c9 +--- a/file1 ++++ b/file1 +@@ -1 +1 @@ +-one ++ONE +`, + expected: FileVersions{OldBlob: "9f439a7", NewBlob: "20141c9", OldMode: "100644", NewMode: "100755"}, + }, + { + testName: "renamed file with changes", + diff: `diff --git a/file1 b/file2 +similarity index 80% +rename from file1 +rename to file2 +index 9f439a7..20141c9 100644 +--- a/file1 ++++ b/file2 +@@ -1 +1 @@ +-one ++ONE +`, + expected: FileVersions{OldBlob: "9f439a7", NewBlob: "20141c9", OldMode: "100644", NewMode: "100644"}, + }, + { + testName: "changed mode only", + diff: `diff --git a/file1 b/file1 +old mode 100644 +new mode 100755 +`, + expected: FileVersions{OldMode: "100644", NewMode: "100755"}, + }, + { + testName: "no header", + diff: "", + expected: FileVersions{}, + }, + } + + for _, s := range scenarios { + t.Run(s.testName, func(t *testing.T) { + assert.Equal(t, s.expected, ParseFileVersions(strings.Split(s.diff, "\n"))) + assert.Equal(t, s.expected, Parse(s.diff).FileVersions()) + }) + } +} + +func TestFileVersionsSame(t *testing.T) { + versions := FileVersions{OldBlob: "9f439a7", NewBlob: "20141c9", OldMode: "100644", NewMode: "100644"} + + scenarios := []struct { + testName string + other FileVersions + expected bool + }{ + { + testName: "equal", + other: versions, + expected: true, + }, + { + testName: "ids abbreviated to more digits", + other: FileVersions{OldBlob: "9f439a739f", NewBlob: "20141c9eb2", OldMode: "100644", NewMode: "100644"}, + expected: true, + }, + { + testName: "different new blob", + other: FileVersions{OldBlob: "9f439a7", NewBlob: "3e75765", OldMode: "100644", NewMode: "100644"}, + expected: false, + }, + { + testName: "different old blob", + other: FileVersions{OldBlob: "3e75765", NewBlob: "20141c9", OldMode: "100644", NewMode: "100644"}, + expected: false, + }, + { + testName: "different mode", + other: FileVersions{OldBlob: "9f439a7", NewBlob: "20141c9", OldMode: "100644", NewMode: "100755"}, + expected: false, + }, + { + testName: "no blobs", + other: FileVersions{OldMode: "100644", NewMode: "100644"}, + expected: false, + }, + { + testName: "nothing at all", + other: FileVersions{}, + expected: false, + }, + } + + for _, s := range scenarios { + t.Run(s.testName, func(t *testing.T) { + assert.Equal(t, s.expected, versions.Same(s.other)) + assert.Equal(t, s.expected, s.other.Same(versions)) + }) + } + + assert.True(t, FileVersions{}.Same(FileVersions{})) +} diff --git a/pkg/config/diff_renderer_config_manager.go b/pkg/config/diff_renderer_config_manager.go index 8c6517dc8..44983c746 100644 --- a/pkg/config/diff_renderer_config_manager.go +++ b/pkg/config/diff_renderer_config_manager.go @@ -143,6 +143,24 @@ func (self *DiffRendererConfigManager) GetRawGitArgs() []string { return currentDiffRendererConfig.Args } +// Signature is what identifies the current diff renderer, so that something we +// remembered about what it produced can be dropped once it no longer describes +// the renderer we have. The values a command is resolved with are no part of +// its identity, so the command's template stands for it. +func (self *DiffRendererConfigManager) Signature() string { + currentDiffRendererConfig := self.currentDiffRendererConfig() + if currentDiffRendererConfig == nil { + return "" + } + + return fmt.Sprintf("%d\x00%s\x00%s\x00%s\x00%s", + self.diffRendererIndex, + currentDiffRendererConfig.Type, + currentDiffRendererConfig.ColorArg, + currentDiffRendererConfig.Command, + strings.Join(currentDiffRendererConfig.Args, "\x00")) +} + func (self *DiffRendererConfigManager) CycleDiffRenderers() { self.diffRendererIndex = (self.diffRendererIndex + 1) % len(self.getUserConfig().Git.DiffRenderers) } diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index 095509e07..f86174651 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -310,7 +310,7 @@ type GitConfig struct { // # e.g. // # diff-so-fancy // # delta --dark --paging=never - // # ydiff -p cat + // # ydiff -p cat --color=always // # difft --color=always // command: "" // @@ -384,7 +384,7 @@ func (DiffRendererCommandType) JSONSchemaExtend(schema *jsonschema.Schema) { schema.Examples = []any{ "delta --dark --paging=never", "diff-so-fancy", - "ydiff -p cat", + "ydiff -p cat --color=always", "difft --color=always", } } @@ -401,7 +401,7 @@ type DiffRendererConfig struct { // e.g. // diff-so-fancy // delta --dark --paging=never - // ydiff -p cat + // ydiff -p cat --color=always // difft --color=always Command DiffRendererCommandType `yaml:"command"` // Extra arguments (array of strings) passed to the git command. Only applicable if the type is 'rawGit'. diff --git a/pkg/gocui/view.go b/pkg/gocui/view.go index fd6b67ce9..e3c763ce3 100644 --- a/pkg/gocui/view.go +++ b/pkg/gocui/view.go @@ -47,6 +47,10 @@ type viewBuffer struct { // set pendingNewline to true. If more text is written, we write the newline // then. This avoids an extra blank line at the end of the view. pendingNewline bool + + // What the render that produced the content attached to it (see + // BeginOffscreenRender), or nil. + tag any } // A View is a window. It maintains its own internal buffer and cursor @@ -1643,6 +1647,7 @@ func (v *View) Read(p []byte) (n int, err error) { func (v *View) clear() { v.rewind() v.buf.lines = nil + v.buf.tag = nil v.clearViewLines() // Abandon any in-progress off-screen render: a synchronous SetContent/Clear // is taking over the displayed buffer, so writes must go there, not into a @@ -1694,6 +1699,7 @@ func (v *View) CopyContent(from *View) { // and stays shared, so the cost is proportional to the number of rows, not // their contents. v.buf.lines = slices.Clone(from.buf.lines) + v.buf.tag = from.buf.tag v.viewLines = slices.Clone(from.viewLines) v.SetOriginX(from.ox) v.SetOriginY(from.oy) @@ -1717,6 +1723,7 @@ func (v *View) Reset() { v.rewind() v.buf.lines = nil + v.buf.tag = nil // As in clear(): abandon any in-progress off-screen render so writes after a // reset go to the displayed buffer. v.offscreen = nil @@ -1727,7 +1734,11 @@ func (v *View) Reset() { // displayed buffer — what every reader sees — is left as it was. This is how an // async re-render avoids exposing a half-written buffer: it accumulates // off-screen and swaps in once it has read enough to paint. -func (v *View) BeginOffscreenRender() { +// +// tag is what the render knows about the content it produces that the content +// doesn't say itself, or nil. ContentTag returns it for as long as that content is +// displayed, so a reader can't get it from one render and the content from another. +func (v *View) BeginOffscreenRender(tag any) { v.writeMutex.Lock() defer v.writeMutex.Unlock() @@ -1737,7 +1748,17 @@ func (v *View) BeginOffscreenRender() { // needs it too — otherwise it counts no soft wraps and cursor-positioning // escapes land on the wrong rows. ei.screenColMax = v.buf.ei.screenColMax - v.offscreen = &viewBuffer{ei: ei} + v.offscreen = &viewBuffer{ei: ei, tag: tag} +} + +// ContentTag returns what the render of the displayed content attached to it (see +// BeginOffscreenRender), or nil if it attached nothing, or if the content didn't come +// from such a render. +func (v *View) ContentTag() any { + v.writeMutex.Lock() + defer v.writeMutex.Unlock() + + return v.buf.tag } // SwapInOffscreenRender promotes the off-screen buffer (see BeginOffscreenRender) diff --git a/pkg/gocui/view_test.go b/pkg/gocui/view_test.go index 364d7dedc..ecb96d62a 100644 --- a/pkg/gocui/view_test.go +++ b/pkg/gocui/view_test.go @@ -396,7 +396,7 @@ func TestOffscreenRender(t *testing.T) { assert.Equal(t, []string{"a", "b", "c"}, v.ViewBufferLines()) // Render new, longer content off-screen. - v.BeginOffscreenRender() + v.BeginOffscreenRender(nil) v.writeString("w\nx\ny\nz") // The displayed buffer is untouched: readers still see the previous render. @@ -411,6 +411,39 @@ func TestOffscreenRender(t *testing.T) { assert.Equal(t, []string{"w", "x", "y", "z", "more"}, v.ViewBufferLines()) } +// What a render attaches to its content is there for as long as the content is +// displayed, and only then. +func TestContentTag(t *testing.T) { + v := NewView("name", 0, 0, 80, 10, OutputNormal) + + v.writeString("a") + assert.Nil(t, v.ContentTag()) + + // While the new content is built off-screen, the displayed content keeps the tag it + // has, which is none. + v.BeginOffscreenRender("tag") + v.writeString("b") + assert.Nil(t, v.ContentTag()) + + // The tag comes with the content, and stays while more of it arrives. + v.SwapInOffscreenRender() + assert.Equal(t, "tag", v.ContentTag()) + v.writeString("\nc") + assert.Equal(t, "tag", v.ContentTag()) + + // Content copied from another view is that view's render, tag and all. + other := NewView("other", 0, 0, 80, 10, OutputNormal) + other.CopyContent(v) + assert.Equal(t, "tag", other.ContentTag()) + + // Content that replaces it without such a render has none. + v.SetContent("d") + assert.Nil(t, v.ContentTag()) + + other.Reset() + assert.Nil(t, other.ContentTag()) +} + // When a render produces fewer view lines than the previous one, // refreshViewLinesIfNeeded must truncate viewLines to the new content rather // than leaving the previous render's entries in the tail: with the off-screen @@ -425,7 +458,7 @@ func TestViewLinesTruncatedByShorterRender(t *testing.T) { assert.Equal(t, 6, v.ViewLinesHeight()) // Re-render with three short, unwrapped lines: only 3 view lines remain. - v.BeginOffscreenRender() + v.BeginOffscreenRender(nil) v.writeString("aaa\nbbb\nccc") v.SwapInOffscreenRender() assert.Equal(t, 3, v.ViewLinesHeight()) @@ -524,7 +557,7 @@ func TestScrollbarHeightHeldWhileLoading(t *testing.T) { v.FreezeScrollbarHeight() // The off-screen render swaps in only a screenful at its first paint. - v.BeginOffscreenRender() + v.BeginOffscreenRender(nil) v.writeString(strings.Repeat("y\n", 30)) v.SwapInOffscreenRender() @@ -689,7 +722,7 @@ func TestWriteCursorPositionEscapeInOffscreenRender(t *testing.T) { v := NewView("name", 0, 0, 30, 30, OutputNormal) v.SetContentWidth(5) - v.BeginOffscreenRender() + v.BeginOffscreenRender(nil) // Seven characters soft-wrap once on a 5-column screen, putting ConPTY on // row 2; CUP to row 3 should then skip no rows at all. v.writeString("aaaaaaa\x1b[3;1Hb\n") diff --git a/pkg/gui/controllers/commit_diff_actions.go b/pkg/gui/controllers/commit_diff_actions.go index b5adae259..41c66aeef 100644 --- a/pkg/gui/controllers/commit_diff_actions.go +++ b/pkg/gui/controllers/commit_diff_actions.go @@ -52,16 +52,16 @@ func NewCommitDiffActions( // The patch's own diff is handed out whole: it is only ever as big as the patch, and it // names its files under the trees the patch was materialized into rather than under the // paths asked for. -func (self *CommitDiffActions) PlainDiff(pane types.DiffPaneContext, paths []string) string { +func (self *CommitDiffActions) PlainDiff(pane types.DiffPaneContext, paths []string) (string, error) { if self.showsCustomPatch(pane) { - return self.customPatchDiff() + return self.customPatchDiff(), nil } target := self.target() if target == nil { - return "" + return "", nil } - return self.c.Helpers().Diff.PlainDiffBetweenRefs(target.from, target.to, paths) + return self.c.Helpers().Diff.PlainDiffBetweenRefs(target.from, target.to, paths), nil } // customPatchDiff is the diff the custom patch is previewed as, as git writes it — the diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index 3037943c5..7ab9548e9 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -5,6 +5,7 @@ import ( "fmt" "path/filepath" "strings" + "sync" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" @@ -445,10 +446,18 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { paths := self.pathsForDiff(node) refreshOpts := types.RefreshMainOpts{Pair: self.c.MainViewPairs().Normal} + // A diff renderer that states its rows shows none of git's headers, so what the diff + // is made from is taken along with it, to tell whether it is still the current one + // when the user acts on it. + var contentTag func() any + if self.c.Helpers().DiffLine.MayRenderStatedRows(mode) { + contentTag = self.diffInputsTag(node, showStaged, showUnstaged) + } + if showUnstaged { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, mode, false, paths) refreshOpts.Main = &types.ViewUpdateOpts{ - Task: types.NewMainViewDiffTask(cmdObj.GetCmd(), mode), + Task: types.NewMainViewDiffTaskWithContentTag(cmdObj.GetCmd(), contentTag, mode), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Title: self.c.Tr.UnstagedChanges, NothingToActOn: !node.GetHasUnstagedChanges(), @@ -458,7 +467,7 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { if showStaged { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, mode, true, paths) refreshOpts.Secondary = &types.ViewUpdateOpts{ - Task: types.NewMainViewDiffTask(cmdObj.GetCmd(), mode), + Task: types.NewMainViewDiffTaskWithContentTag(cmdObj.GetCmd(), contentTag, mode), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Title: self.c.Tr.StagedChanges, NothingToActOn: !node.GetHasStagedChanges(), @@ -468,6 +477,30 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { self.c.RenderToMainViews(refreshOpts) } +// diffInputsTag returns the content tag for a render of the node's diff: the inputs of +// the diffs of its files (see git_commands.DiffInputs), for the sides the panes show. +// The renders of both panes share them, taken once, before whichever of their commands +// starts first. +func (self *FilesController) diffInputsTag(node *filetree.FileNode, stagedSide bool, unstagedSide bool) func() any { + paths := []string{} + _ = node.ForEachFile(func(file *models.File) error { + paths = append(paths, file.Names()...) + return nil + }) + + // A repo switch replaces the git commands, so they are captured here, on the UI + // thread, rather than read where the renders run. + workingTree := self.c.Git().WorkingTree + return sync.OnceValue(func() any { + inputs, err := workingTree.GetDiffInputs(paths, stagedSide, unstagedSide) + if err != nil { + self.c.Log.Error(err) + return nil + } + return inputs + }) +} + func (self *FilesController) GetFocusedMainViewDiffSource() types.FocusedMainViewDiffSource { return self.diffActions } diff --git a/pkg/gui/controllers/helpers/diff_helper.go b/pkg/gui/controllers/helpers/diff_helper.go index d855282ea..08bb5d6d0 100644 --- a/pkg/gui/controllers/helpers/diff_helper.go +++ b/pkg/gui/controllers/helpers/diff_helper.go @@ -2,12 +2,14 @@ package helpers import ( "errors" + "fmt" "path/filepath" "strings" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/patch" + "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/modes/diffing" "github.com/jesseduffield/lazygit/pkg/gui/style" @@ -20,13 +22,21 @@ type DiffHelper struct { c *HelperCommon diffLineHelper *DiffLineHelper filesHelper *FilesHelper + + // Diffs of the messages of "amend!" commits, keyed by everything that + // shapes them: the two commits, the diff renderer, and the values its + // command was resolved with. An empty diff means that the commit doesn't + // change the message. Only accessed on the UI thread, so a diff produced + // on a render's goroutine is stored by way of OnUIThread. + commitMessageDiffs map[string]string } func NewDiffHelper(c *HelperCommon, diffLineHelper *DiffLineHelper, filesHelper *FilesHelper) *DiffHelper { return &DiffHelper{ - c: c, - diffLineHelper: diffLineHelper, - filesHelper: filesHelper, + c: c, + diffLineHelper: diffLineHelper, + filesHelper: filesHelper, + commitMessageDiffs: make(map[string]string), } } @@ -59,7 +69,13 @@ func (self *DiffHelper) DiffArgs() []string { // and the refRange for a range selection. If the refRange is nil (meaning that // either there's no range, or it can't be diffed for some reason), then we want // to fall back to rendering the diff for the single commit. -func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Commit, refRange *types.RefRange) types.UpdateTask { +// In addition, we need to pass the list of all commits; this is needed for +// showing the commit message diff for "amend!" commits. +func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff( + commits []*models.Commit, + commit *models.Commit, + refRange *types.RefRange, +) types.UpdateTask { mode := self.diffLineHelper.MainViewDiffMode() if refRange != nil { @@ -87,7 +103,110 @@ func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Comm } cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit), mode) - return types.NewMainViewDiffTask(cmdObj.GetCmd(), mode) + return types.NewMainViewDiffTaskWithPrefix(cmdObj.GetCmd(), self.commitMessageDiffPrefix(commits, commit), mode) +} + +// For an "amend!" commit, returns a prefix with a diff of the commit message it +// sets against the message it replaces, to be shown above the commit's own diff. +// Returns nil for any other commit. The prefix is empty for an "amend!" commit +// that only changes the contents of the commit it applies to. +func (self *DiffHelper) commitMessageDiffPrefix(commits []*models.Commit, commit *models.Commit) types.Prefix { + previousCommit, ok := findCommitWithPreviousMessage(commits, commit) + if !ok { + return nil + } + + header := style.FgYellow.Sprintf("%s\n", utils.ResolvePlaceholderString( + self.c.Tr.CommitMessageChanges, + map[string]string{"hash": previousCommit.ShortHash()}, + )) + + return func(width int) func() string { + produceDiff := self.commitMessageDiff(previousCommit.Hash(), commit.Hash(), width) + return func() string { + diff := produceDiff() + if diff == "" { + return "" + } + + return header + diff + strings.Repeat("─", width) + "\n" + } + } +} + +// The names the two messages are diffed under. A diff renderer shows them as the +// names of the files being diffed, so they are what tells the reader which side +// is which. They are not translated because they end up as file names, and git +// mangles paths outside of ASCII when it states them in a diff. +const ( + oldMessageName = "old message" + newMessageName = "new message" +) + +// commitMessageDiff returns the function that produces the diff of the messages +// of the two commits, laid out to the given width. It is called on the UI +// thread, and the function it returns on the render's own goroutine (see +// types.Prefix). +func (self *DiffHelper) commitMessageDiff(previousHash string, hash string, width int) func() string { + values := config.DiffRendererValues{ + Width: width, + DiffContext: self.c.UserConfig().Git.DiffContextSize, + LightBackground: self.c.TerminalHasLightBackground(), + } + + // The diff renderer lays the diff out, and lays it out according to the + // values its command is resolved with, so both belong in the key along with + // the two messages. + key := fmt.Sprintf("%s\x00%s\x00%+v\x00%s", + hash, + previousHash, + values, + self.c.State().GetDiffRendererConfigManager().Signature()) + if diff, ok := self.commitMessageDiffs[key]; ok { + return func() string { return diff } + } + + differ, err := self.c.Git().Diff.NewTextDiffer(values) + if err != nil { + self.c.Log.Error(err) + return func() string { return "" } + } + commitCommands := self.c.Git().Commit + + return func() string { + diff, err := renderCommitMessageDiff(commitCommands, differ, previousHash, hash) + if err != nil { + self.c.Log.Error(err) + return "" + } + + self.c.OnUIThread(func() error { + self.commitMessageDiffs[key] = diff + return nil + }) + return diff + } +} + +// renderCommitMessageDiff returns the diff of the messages of the two commits, or +// an empty string if they are the same. +func renderCommitMessageDiff( + commitCommands *git_commands.CommitCommands, differ *git_commands.TextDiffer, previousHash string, hash string, +) (string, error) { + messages, err := commitCommands.GetCommitMessages([]string{previousHash, hash}) + if err != nil { + return "", err + } + + before := messageAfterAmending(messages[0]) + after := messageAfterAmending(messages[1]) + if before == after { + return "", nil + } + + return differ.RenderedDiff( + git_commands.NamedText{Name: oldMessageName, Content: before}, + git_commands.NamedText{Name: newMessageName, Content: after}) } // PlainDiffBetweenRefs returns the diff of the given files between two refs as git diff --git a/pkg/gui/controllers/helpers/diff_line_parser.go b/pkg/gui/controllers/helpers/diff_line_parser.go index 667946a7c..fcf47d9ae 100644 --- a/pkg/gui/controllers/helpers/diff_line_parser.go +++ b/pkg/gui/controllers/helpers/diff_line_parser.go @@ -95,6 +95,32 @@ func parseAllDiffLinesFromBuffer(bufferLines []string) []bufferLineParse { return result } +// fileVersionsOfSections reads the versions of each file that a (possibly multi-file) +// diff shows, from the header of the file's section (see patch.FileVersions), by the +// path the section names, relative to the repo root. +// +// A section whose header has no index line is left out. git writes one for every +// section that has lines to select, so a section without one either has none (a +// submodule, a rename without a content change, a change of the mode alone), or comes +// from a diff renderer that left the line out. Either way the versions can't be read. +func fileVersionsOfSections(lines []string) map[string]patch.FileVersions { + versions := map[string]patch.FileVersions{} + for i := 0; i < len(lines); { + if !startsFileSection(lines[i]) { + i++ + continue + } + end := fileSectionEnd(lines, i) + path := pathFromDiffHeader(lines[i:end]) + sectionVersions := patch.ParseFileVersions(lines[i:end]) + if path != "" && sectionVersions.OldBlob != "" { + versions[path] = sectionVersions + } + i = end + } + return versions +} + // diffLineTexts extracts the text of each rendered row — the material the buffer // parser works on. func diffLineTexts(contents []gocui.DiffLineContent) []string { diff --git a/pkg/gui/controllers/helpers/diff_line_parser_test.go b/pkg/gui/controllers/helpers/diff_line_parser_test.go index 55553e0f3..130090321 100644 --- a/pkg/gui/controllers/helpers/diff_line_parser_test.go +++ b/pkg/gui/controllers/helpers/diff_line_parser_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/stretchr/testify/assert" @@ -388,6 +389,36 @@ func TestParseAllDiffLinesFromBuffer(t *testing.T) { assert.True(t, all[6].ok) } +func TestFileVersionsOfSections(t *testing.T) { + // Decoration above the diff, a submodule's section, a change of a file's mode alone, + // and a deleted file, whose path comes from its "---" line. The submodule and the + // mode change have no index line. + bufferLines := append( + []string{"commit 1234567", "", " do a thing", ""}, + strings.Split(twoFileDiff+` +Submodule sub a32f27c..2d9f921: + > a commit of the submodule +diff --git a/script.sh b/script.sh +old mode 100644 +new mode 100755 +diff --git a/gone.go b/gone.go +deleted file mode 100644 +index 5555555..0000000 +--- a/gone.go ++++ /dev/null +@@ -1 +0,0 @@ +-gone`, "\n")..., + ) + + assert.Equal(t, + map[string]patch.FileVersions{ + "file1.go": {OldBlob: "1111111", NewBlob: "2222222", OldMode: "100644", NewMode: "100644"}, + "dir/file2.go": {OldBlob: "3333333", NewBlob: "4444444", OldMode: "100644", NewMode: "100644"}, + "gone.go": {OldBlob: "5555555", NewBlob: "0000000", OldMode: "100644"}, + }, + fileVersionsOfSections(bufferLines)) +} + func TestParseDiffLineMetadata(t *testing.T) { scenarios := []struct { name string diff --git a/pkg/gui/controllers/helpers/diff_line_plain_text.go b/pkg/gui/controllers/helpers/diff_line_plain_text.go index f62144ec1..00b77f834 100644 --- a/pkg/gui/controllers/helpers/diff_line_plain_text.go +++ b/pkg/gui/controllers/helpers/diff_line_plain_text.go @@ -35,10 +35,11 @@ import ( // plainDiff fetches the diff of the given repo-relative files, and is asked only for // the files the selection touches, so that copying three lines of a commit's diff // doesn't fetch the whole of it. fromDiff is "" when no selected row could be found in -// the diff, e.g. because the selection covers nothing but a renderer's decoration. +// the diff, e.g. because the selection covers nothing but a renderer's decoration. If +// plainDiff fails, so does this. func (self *DiffLineHelper) PlainDiffOfSelection( - view *gocui.View, first int, last int, plainDiff func(paths []string) string, -) (aboveDiff string, fromDiff string) { + view *gocui.View, first int, last int, plainDiff func(paths []string) (string, error), +) (aboveDiff string, fromDiff string, err error) { worktreePath := self.c.Git().RepoPaths.WorktreePath() aboveDiff = self.textAboveDiff(view, first, last) @@ -68,10 +69,14 @@ func (self *DiffLineHelper) PlainDiffOfSelection( relPaths := repoRelativePaths(worktreePath, paths) if len(relPaths) == 0 { - return aboveDiff, "" + return aboveDiff, "", nil } - diffLines := strings.Split(strings.TrimSuffix(plainDiff(relPaths), "\n"), "\n") + diff, err := plainDiff(relPaths) + if err != nil { + return "", "", err + } + diffLines := strings.Split(strings.TrimSuffix(diff, "\n"), "\n") toDiffLineInfo := diffLineInfoConverterIn(worktreePath) runs := map[string][2]int{} for i, parsed := range parseAllDiffLinesFromBuffer(diffLines) { @@ -101,7 +106,7 @@ func (self *DiffLineHelper) PlainDiffOfSelection( text.WriteString("\n") } } - return aboveDiff, text.String() + return aboveDiff, text.String(), nil } // textAboveDiff returns the text of the selected rows that sit above the diff, as they diff --git a/pkg/gui/controllers/helpers/diff_line_queries.go b/pkg/gui/controllers/helpers/diff_line_queries.go index e56591a25..b50b55538 100644 --- a/pkg/gui/controllers/helpers/diff_line_queries.go +++ b/pkg/gui/controllers/helpers/diff_line_queries.go @@ -4,6 +4,7 @@ import ( "path/filepath" "strings" + "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/samber/lo" @@ -37,6 +38,39 @@ func (self *DiffLineHelper) DiffLinesInBufferRange(view *gocui.View, first int, return self.inRepoTerms(view, infos) } +// FileVersionsOnScreen returns the versions of each file whose diff view shows, as the +// header of the file's diff states them (see patch.FileVersions), by the file's absolute +// path. A file is left out if its header shows no index line (see +// fileVersionsOfSections). ok is false for a rendering whose rows a diff renderer +// stated (see renderingStatesDiffLines): its text is the renderer's picture of the +// diff, which shows no header to read them from. +func (self *DiffLineHelper) FileVersionsOnScreen(view *gocui.View) (versions map[string]patch.FileVersions, ok bool) { + contents := view.DiffLineContents() + if renderingStatesDiffLines(contents) { + return nil, false + } + return self.absoluteFileVersions(fileVersionsOfSections(diffLineTexts(contents))), true +} + +// FileVersionsInDiff returns the versions of each file of a diff given as git's text, +// as FileVersionsOnScreen does for a view. A file the diff doesn't have, or has without +// an index line, is left out. +func (self *DiffLineHelper) FileVersionsInDiff(diff string) map[string]patch.FileVersions { + return self.absoluteFileVersions(fileVersionsOfSections(strings.Split(diff, "\n"))) +} + +// absoluteFileVersions keys versions by the absolute paths of their files, as a diff +// line's identity names them, rather than by the repo-relative ones the diff names +// them by. +func (self *DiffLineHelper) absoluteFileVersions( + versions map[string]patch.FileVersions, +) map[string]patch.FileVersions { + worktreePath := self.c.Git().RepoPaths.WorktreePath() + return lo.MapKeys(versions, func(_ patch.FileVersions, path string) string { + return filepath.Join(worktreePath, path) + }) +} + // ChangeLineOrdinals says, for each of the given change lines, which of its file's // changes it is in the given diff — its place among them, counted from the top of the // file — keyed by file. Lines the diff doesn't have are left out. diff --git a/pkg/gui/controllers/helpers/diff_line_raw_fallback.go b/pkg/gui/controllers/helpers/diff_line_raw_fallback.go index ee5d41ab2..8edcdf4b9 100644 --- a/pkg/gui/controllers/helpers/diff_line_raw_fallback.go +++ b/pkg/gui/controllers/helpers/diff_line_raw_fallback.go @@ -33,6 +33,19 @@ func (self *DiffLineHelper) MainViewDiffMode() git_commands.DiffMode { return git_commands.DiffModeRendered } +// MayRenderStatedRows reports whether a diff rendered in the given mode may reach the +// main view as a rendering whose rows the diff renderer states (see +// renderingStatesDiffLines). Such a rendering shows none of git's headers. It doesn't +// ask the renderer, so as not to hold up a render with that; until the renderer has +// been asked about (see diffRendererEmitsMetadata), any renderer but git's own may. +func (self *DiffLineHelper) MayRenderStatedRows(mode git_commands.DiffMode) bool { + if mode != git_commands.DiffModeRendered || !self.diffNeedsMetadata() { + return false + } + verdict, ok := self.rememberedRendererVerdict() + return verdict || !ok +} + // DiffRowsCanBePlaced reports whether the rows of the diff the main view is about to be // given can be placed in the file they show. git's own diff describes itself, whether it // is what the user configured or what MainViewDiffMode is about to substitute for a @@ -101,13 +114,22 @@ func (self *DiffLineHelper) diffNeedsMetadata() bool { // once and remembered until the renderer changes — the user cycling to another one, or a // changed config being reloaded. func (self *DiffLineHelper) diffRendererEmitsMetadata() bool { - signature := self.diffRendererSignature() - if self.rendererEmitsMetadata == nil || signature != self.rendererSignature { - verdict := self.c.Git().Diff.ProbeDiffRendererEmitsMetadata() - self.rendererEmitsMetadata = &verdict - self.rendererSignature = signature + if verdict, ok := self.rememberedRendererVerdict(); ok { + return verdict } - return *self.rendererEmitsMetadata + verdict := self.c.Git().Diff.ProbeDiffRendererEmitsMetadata() + self.rendererEmitsMetadata = &verdict + self.rendererSignature = self.diffRendererSignature() + return verdict +} + +// rememberedRendererVerdict returns what the probe said about the current diff +// renderer. ok is false if it hasn't been asked about this one. +func (self *DiffLineHelper) rememberedRendererVerdict() (verdict bool, ok bool) { + if self.rendererEmitsMetadata == nil || self.rendererSignature != self.diffRendererSignature() { + return false, false + } + return *self.rendererEmitsMetadata, true } // diffRendererSignature identifies the current diff renderer, so that the remembered diff --git a/pkg/gui/controllers/helpers/fixup_helper.go b/pkg/gui/controllers/helpers/fixup_helper.go index 2e3250a3d..9538a8991 100644 --- a/pkg/gui/controllers/helpers/fixup_helper.go +++ b/pkg/gui/controllers/helpers/fixup_helper.go @@ -409,3 +409,62 @@ func IsFixupCommit(subject string) (string, bool) { return subject, false } + +// Check whether the given subject line is the subject of an "amend!" commit, +// i.e. of a commit that replaces the message of the commit it applies to, and +// return the subject of that commit if so. Note that a commit with a subject +// like "fixup! amend! Bla" is not an "amend!" commit; only the outermost +// prefix decides what happens to the message. +func isAmendCommit(subject string) (string, bool) { + if !strings.HasPrefix(subject, "amend! ") { + return subject, false + } + + return IsFixupCommit(subject) +} + +// For an "amend!" commit, find the commit that holds the message it replaces. +// This is the nearest "amend!" commit below it that applies to the same commit, +// or, if there is none, the commit it applies to itself. Returns false if the +// given commit isn't an "amend!" commit, or if the commit it applies to isn't +// in the given list. +func findCommitWithPreviousMessage(commits []*models.Commit, commit *models.Commit) (*models.Commit, bool) { + baseSubject, isAmend := isAmendCommit(commit.Name) + if !isAmend { + return nil, false + } + + _, index, ok := lo.FindIndexOf(commits, func(c *models.Commit) bool { + return c.Hash() == commit.Hash() + }) + if !ok { + return nil, false + } + + for _, previousCommit := range commits[index+1:] { + if previousCommit.Name == baseSubject { + return previousCommit, true + } + if subject, isAmend := isAmendCommit(previousCommit.Name); isAmend && subject == baseSubject { + return previousCommit, true + } + } + + return nil, false +} + +// Return the message that the given commit leaves on the commit it applies to: +// for an "amend!" commit this is its message without the "amend! " +// line at the top, and for any other commit it is simply its own message. +func messageAfterAmending(message string) string { + subject, body, found := strings.Cut(message, "\n") + if !found { + return message + } + + if _, isAmend := isAmendCommit(subject); !isAmend { + return message + } + + return strings.TrimLeft(body, "\n") +} diff --git a/pkg/gui/controllers/helpers/fixup_helper_test.go b/pkg/gui/controllers/helpers/fixup_helper_test.go index 466e90087..543260dd9 100644 --- a/pkg/gui/controllers/helpers/fixup_helper_test.go +++ b/pkg/gui/controllers/helpers/fixup_helper_test.go @@ -205,6 +205,187 @@ func TestFixupHelper_IsFixupCommit(t *testing.T) { } } +func TestFixupHelper_findCommitWithPreviousMessage(t *testing.T) { + hashPool := &utils.StringPool{} + + type commitDesc struct { + Hash string + Name string + } + + scenarios := []struct { + name string + commits []commitDesc + index int + expectedHash string + }{ + { + name: "not an amend commit", + commits: []commitDesc{ + {"abc123", "Some feature"}, + }, + index: 0, + expectedHash: "", + }, + { + name: "fixup commits don't change the message", + commits: []commitDesc{ + {"abc123", "fixup! Some feature"}, + {"def456", "Some feature"}, + }, + index: 0, + expectedHash: "", + }, + { + name: "a fixup of an amend commit doesn't change the message either", + commits: []commitDesc{ + {"abc123", "fixup! amend! Some feature"}, + {"def456", "amend! Some feature"}, + {"ghi789", "Some feature"}, + }, + index: 0, + expectedHash: "", + }, + { + name: "base commit right below the amend commit", + commits: []commitDesc{ + {"abc123", "amend! Some feature"}, + {"def456", "Some feature"}, + }, + index: 0, + expectedHash: "def456", + }, + { + name: "base commit further down the list", + commits: []commitDesc{ + {"abc123", "amend! Some feature"}, + {"def456", "Unrelated commit"}, + {"ghi789", "Some feature"}, + }, + index: 0, + expectedHash: "ghi789", + }, + { + name: "amend commit in the middle of the list", + commits: []commitDesc{ + {"abc123", "Unrelated commit"}, + {"def456", "amend! Some feature"}, + {"ghi789", "Some feature"}, + }, + index: 1, + expectedHash: "ghi789", + }, + { + name: "the nearest earlier amend commit holds the message", + commits: []commitDesc{ + {"abc123", "amend! Some feature"}, + {"def456", "amend! Some feature"}, + {"ghi789", "Some feature"}, + }, + index: 0, + expectedHash: "def456", + }, + { + name: "fixup and squash commits in between are skipped", + commits: []commitDesc{ + {"abc123", "amend! Some feature"}, + {"def456", "fixup! Some feature"}, + {"ghi789", "squash! Some feature"}, + {"jkl012", "amend! Some feature"}, + {"mno345", "Some feature"}, + }, + index: 0, + expectedHash: "jkl012", + }, + { + name: "amend commit with several prefixes applies to the innermost subject", + commits: []commitDesc{ + {"abc123", "amend! amend! Some feature"}, + {"def456", "amend! Some feature"}, + {"ghi789", "Some feature"}, + }, + index: 0, + expectedHash: "def456", + }, + { + name: "base commit is not in the list", + commits: []commitDesc{ + {"abc123", "amend! Some feature"}, + {"def456", "Unrelated commit"}, + }, + index: 0, + expectedHash: "", + }, + { + name: "base commit is above the amend commit", + commits: []commitDesc{ + {"abc123", "Some feature"}, + {"def456", "amend! Some feature"}, + }, + index: 1, + expectedHash: "", + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + commits := lo.Map(s.commits, func(desc commitDesc, _ int) *models.Commit { + return models.NewCommit(hashPool, models.NewCommitOpts{Hash: desc.Hash, Name: desc.Name}) + }) + + result, ok := findCommitWithPreviousMessage(commits, commits[s.index]) + + if s.expectedHash == "" { + assert.False(t, ok) + assert.Nil(t, result) + } else { + assert.True(t, ok) + assert.Equal(t, s.expectedHash, result.Hash()) + } + }) + } +} + +func TestFixupHelper_messageAfterAmending(t *testing.T) { + scenarios := []struct { + name string + message string + expectedMessage string + }{ + { + name: "subject only", + message: "Some feature", + expectedMessage: "Some feature", + }, + { + name: "subject and body", + message: "Some feature\n\nSome description", + expectedMessage: "Some feature\n\nSome description", + }, + { + name: "amend commit", + message: "amend! Some feature\n\nA better subject\n\nSome description", + expectedMessage: "A better subject\n\nSome description", + }, + { + name: "amend commit without a replacement message", + message: "amend! Some feature", + expectedMessage: "amend! Some feature", + }, + { + name: "fixup commit", + message: "fixup! amend! Some feature\n\nSome description", + expectedMessage: "fixup! amend! Some feature\n\nSome description", + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + assert.Equal(t, s.expectedMessage, messageAfterAmending(s.message)) + }) + } +} + func TestFixupHelper_removeFixupCommits(t *testing.T) { hashPool := &utils.StringPool{} diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index a00589a76..9e0c23de3 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -729,7 +729,8 @@ func (self *LocalCommitsController) GetOnRenderToMain() func() { task = types.NewRenderStringTask(string(patch)) } else { refRange := self.context().GetSelectedRefRangeForDiffFiles() - task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff(commit, refRange) + task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff( + self.c.Model().Commits, commit, refRange) } self.c.RenderToMainViews(types.RefreshMainOpts{ diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 1ff6c52bb..5fc1b06c3 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -487,7 +487,10 @@ func (self *MainViewController) pullRequestDescription(description string) func( // The rows above the diff (a commit's message, git's summary of it) belong to no file, // so they are copied as they stand on screen. func (self *MainViewController) copySelection() error { - text := self.textOfSelection() + text, err := self.textOfSelection() + if err != nil { + return err + } if text == "" { self.c.ErrorToast(self.c.Tr.SelectionNotFoundInDiffToast) return nil @@ -503,25 +506,28 @@ func (self *MainViewController) copySelection() error { // textOfSelection is what copying the selection puts on the clipboard. It is "" when // none of the selected rows could be placed in the diff, which is what a rendering's -// own decoration comes to. -func (self *MainViewController) textOfSelection() string { +// own decoration comes to. It fails if the panel can't hand out the diff behind it. +func (self *MainViewController) textOfSelection() (string, error) { source := self.diffSource() if source == nil { - return "" + return "", nil } view := self.context.GetView() first, last, ok := view.SelectedBufferLineRange() if !ok { - return "" + return "", nil + } + aboveDiff, fromDiff, err := self.c.Helpers().DiffLine.PlainDiffOfSelection(view, first, last, + func(paths []string) (string, error) { return source.PlainDiff(self.context, paths) }) + if err != nil { + return "", err } - aboveDiff, fromDiff := self.c.Helpers().DiffLine.PlainDiffOfSelection(view, first, last, - func(paths []string) string { return source.PlainDiff(self.context, paths) }) if aboveDiff == "" { // Only text that is all diff has a +/- column to lose: a line of a commit message // may begin with a '-' without being a deletion of anything. fromDiff = dropDiffPrefix(fromDiff) } - return aboveDiff + fromDiff + return aboveDiff + fromDiff, nil } // diffSelectState returns this pane's diff selection mode state. diff --git a/pkg/gui/controllers/sub_commits_controller.go b/pkg/gui/controllers/sub_commits_controller.go index dca7f5af8..04001ce4f 100644 --- a/pkg/gui/controllers/sub_commits_controller.go +++ b/pkg/gui/controllers/sub_commits_controller.go @@ -46,7 +46,8 @@ func (self *SubCommitsController) GetOnRenderToMain() func() { task = types.NewRenderStringTask("No commits") } else { refRange := self.context().GetSelectedRefRangeForDiffFiles() - task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff(commit, refRange) + task = self.c.Helpers().Diff.GetUpdateTaskForRenderingCommitsDiff( + self.c.Model().SubCommits, commit, refRange) } self.c.RenderToMainViews(types.RefreshMainOpts{ diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 6739d80a2..82d78a03b 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -1,7 +1,9 @@ package controllers import ( + "errors" "fmt" + "path/filepath" "strings" "github.com/jesseduffield/generics/set" @@ -10,6 +12,7 @@ import ( "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/jesseduffield/lazygit/pkg/utils" "github.com/samber/lo" ) @@ -31,18 +34,34 @@ func (self *WorkingTreeDiffActions) context() *context.WorkingTreeContext { } // PlainDiff hands out the working tree's diff for the given files, taken from the -// side of the index that the asking pane shows. -func (self *WorkingTreeDiffActions) PlainDiff(pane types.DiffPaneContext, paths []string) string { +// side of the index that the asking pane shows. It fails if the diff of one of the +// files is no longer the one the pane shows (see shownDiff). +func (self *WorkingTreeDiffActions) PlainDiff(pane types.DiffPaneContext, paths []string) (string, error) { node := self.context().GetSelected() if node == nil { - return "" + return "", nil } + shown := self.shownDiffs(pane) + onStagedSide := self.showsStagedSide(pane) // An error means there is no diff to be had, which for our purposes is the same as // an empty one. diff, _ := self.c.Git().WorkingTree. - WorktreeFileDiffCmdObj(node, git_commands.DiffModePlain, self.showsStagedSide(pane), paths). + WorktreeFileDiffCmdObj(node, git_commands.DiffModePlain, onStagedSide, paths). RunWithOutput() - return diff + + versions := self.c.Helpers().DiffLine.FileVersionsInDiff(diff) + worktreePath := self.c.Git().RepoPaths.WorktreePath() + for _, path := range paths { + absolutePath := filepath.Join(worktreePath, path) + filePaths := []string{path} + if file := self.fileForDiffLinePath(absolutePath); file != nil { + filePaths = file.Names() + } + if err := self.checkShown(shown[absolutePath], filePaths, onStagedSide, versions[absolutePath]); err != nil { + return "", err + } + } + return diff, nil } // showsStagedSide reports whether the given main pane is the one showing the staged @@ -94,7 +113,21 @@ func (self *WorkingTreeDiffActions) DiscardSelection(pane types.DiffPaneContext, // how destructive that is. On the staged side it goes to the index; this is the // same as unstaging, so nothing is lost. On the unstaged side it goes to the // working tree, where the change is gone for good, so we ask first. - return self.c.ConfirmIf(!onStagedSide && !self.c.UserConfig().Gui.SkipDiscardChangeWarning, + askFirst := !onStagedSide && !self.c.UserConfig().Gui.SkipDiscardChangeWarning + + // Building the patch reads the diff again and fails if it changed since it was + // shown. That happens once the user has confirmed, since the diff can change while + // they decide; checking before asking as well spares them confirming a discard + // that won't happen. + if askFirst { + for _, fileLines := range linesByFile { + if _, err := self.readFileDiff(fileLines, onStagedSide); err != nil { + return err + } + } + } + + return self.c.ConfirmIf(askFirst, types.ConfirmOpts{ Title: self.c.Tr.DiscardChangeTitle, Prompt: self.c.Tr.DiscardChangePrompt, @@ -132,7 +165,10 @@ func (self *WorkingTreeDiffActions) EditHunk( } file := linesByFile[0].file - parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, onStagedSide)) + parsedPatch, err := self.readFileDiff(linesByFile[0], onStagedSide) + if err != nil { + return err + } lineIndices := patch.ChangeLineIndicesForLines(parsedPatch, []patch.LineIdentity{linesByFile[0].lines[0].PatchLineIdentity()}) if len(lineIndices) == 0 { @@ -203,6 +239,83 @@ func (self *WorkingTreeDiffActions) PatchInclusion() func(types.DiffLineInfo) bo type fileDiffLines struct { file *models.File lines []types.DiffLineInfo + + // What the pane showed of the file's diff when the lines were selected. + shown shownDiff +} + +// shownDiff is what a pane showed of a file's diff at one moment, to tell whether a +// diff of the file read later is still that diff. The selected lines are looked up in +// the diff read later by where they sit in the file, and in a different diff that +// place can hold a different line. The diff changes whenever the file, the index or +// HEAD is changed outside of lazygit and lazygit hasn't refreshed since. +type shownDiff struct { + // The versions of the file the diff is between, as the header of the diff on screen + // states them; nil if the screen shows no header to read them from (see + // DiffLineHelper.FileVersionsOnScreen). + versions *patch.FileVersions + + // What the diff on screen was made from, as its render took it before running git + // (see FilesController.diffInputsTag); nil if it took nothing. A diff renderer that + // states its rows shows no header, and this is what is left to tell by. + inputs *git_commands.DiffInputs +} + +// shownDiffs reads what the pane shows of the diff of each of its files, by the file's +// absolute path. +func (self *WorkingTreeDiffActions) shownDiffs(pane types.DiffPaneContext) map[string]shownDiff { + shown := map[string]shownDiff{} + view := pane.GetView() + + if inputs, ok := view.ContentTag().(*git_commands.DiffInputs); ok { + worktreePath := self.c.Git().RepoPaths.WorktreePath() + for _, path := range inputs.Paths() { + shown[filepath.Join(worktreePath, path)] = shownDiff{inputs: inputs} + } + } + + // The versions on screen are the diff itself, so they win where there are both. + versions, _ := self.c.Helpers().DiffLine.FileVersionsOnScreen(view) + for path, fileVersions := range versions { + shown[path] = shownDiff{versions: &fileVersions} + } + return shown +} + +// checkShown fails if a diff of a file, just read from the given side of the index and +// between the given versions, isn't the diff that was shown. paths are the file's +// paths in the repo: the one it has, and the one it was renamed from, if any (see +// models.File.Names). With nothing to tell by, any diff passes. +// +// The inputs of the diff are taken after the diff was read, so that a change in +// between counts as a change. +func (self *WorkingTreeDiffActions) checkShown( + shown shownDiff, paths []string, onStagedSide bool, versions patch.FileVersions, +) error { + same := true + switch { + case shown.versions != nil: + same = shown.versions.Same(versions) + case shown.inputs != nil: + current, err := self.c.Git().WorkingTree.GetDiffInputs(paths, onStagedSide, !onStagedSide) + if err != nil { + return err + } + same = shown.inputs.SameFor(current, paths, onStagedSide) + } + if !same { + return self.diffChangedError(paths[0]) + } + return nil +} + +// diffChangedError reports that the diff of the file at the given path in the repo is +// no longer the one on screen. It has the files panel refreshed, so that the diff on +// screen is the current one when the user looks at it again. +func (self *WorkingTreeDiffActions) diffChangedError(path string) error { + self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) + return errors.New(utils.ResolvePlaceholderString(self.c.Tr.DiffChangedSinceShown, + map[string]string{"path": path})) } // diffLineSelection resolves what the user has selected in a pane of the focused main @@ -215,18 +328,22 @@ type fileDiffLines struct { // grouped by the file they belong to, in the order the diff shows the files. If a line // belongs to no file of the files panel, the diff and the panel disagree. Acting on the // other lines would do only part of what the user asked for, so this fails instead. +// +// With each file's lines goes what the pane shows of the file's diff, read at the same +// moment as the lines. func (self *WorkingTreeDiffActions) diffLineSelection( pane types.DiffPaneContext, firstBufferLine int, lastBufferLine int, ) (linesByFile []fileDiffLines, onStagedSide bool, err error) { infos := self.c.Helpers().DiffLine.ChangeLinesInBufferRange(pane.GetView(), firstBufferLine, lastBufferLine) infosByPath := lo.GroupBy(infos, func(info types.DiffLineInfo) string { return info.Path }) paths := lo.Uniq(lo.Map(infos, func(info types.DiffLineInfo, _ int) string { return info.Path })) + shown := self.shownDiffs(pane) for _, path := range paths { file := self.fileForDiffLinePath(path) if file == nil { return nil, false, diffLinesFileNotFoundError(self.c, path) } - linesByFile = append(linesByFile, fileDiffLines{file: file, lines: infosByPath[path]}) + linesByFile = append(linesByFile, fileDiffLines{file: file, lines: infosByPath[path], shown: shown[path]}) } return linesByFile, self.showsStagedSide(pane), nil } @@ -244,7 +361,7 @@ func (self *WorkingTreeDiffActions) applyDiffLineSelection( // patch is built before any is applied. patches := make([]diffLinesPatch, 0, len(linesByFile)) for _, fileLines := range linesByFile { - p, err := self.buildDiffLinesPatch(fileLines.file, fileLines.lines, onStagedSide, opts) + p, err := self.buildDiffLinesPatch(fileLines, onStagedSide, opts) if err != nil { return err } @@ -329,16 +446,19 @@ type diffLinesPatch struct { // caller uses this to tell whether the side acted on still has anything of this file // in it once we are done. // -// It fails if none of the lines are in the diff. The diff on screen is then not the -// one it read; either the file changed since the diff was shown, or we read the -// lines wrongly. +// It fails if the diff it reads is no longer the one on screen (see readFileDiff), and +// if none of the lines are in it. func (self *WorkingTreeDiffActions) buildDiffLinesPatch( - file *models.File, infos []types.DiffLineInfo, sourceCached bool, opts git_commands.ApplyPatchOpts, + fileLines fileDiffLines, sourceCached bool, opts git_commands.ApplyPatchOpts, ) (diffLinesPatch, error) { - parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, sourceCached)) + file := fileLines.file + parsedPatch, err := self.readFileDiff(fileLines, sourceCached) + if err != nil { + return diffLinesPatch{}, err + } patchLineIndices := patch.ChangeLineIndicesForLines(parsedPatch, - lo.Map(infos, func(info types.DiffLineInfo, _ int) patch.LineIdentity { + lo.Map(fileLines.lines, func(info types.DiffLineInfo, _ int) patch.LineIdentity { return info.PatchLineIdentity() })) if len(patchLineIndices) == 0 { @@ -367,6 +487,18 @@ func (self *WorkingTreeDiffActions) buildDiffLinesPatch( return diffLinesPatch{file: file, patch: patchToApply, changesLeft: changesLeft}, nil } +// readFileDiff reads the diff of the file the given lines belong to, from the side of +// the index they were selected on: the diff to look them up in. It fails if this is no +// longer the diff that was on screen when they were selected (see shownDiff). +func (self *WorkingTreeDiffActions) readFileDiff(fileLines fileDiffLines, onStagedSide bool) (*patch.Patch, error) { + parsedPatch := patch.Parse( + self.c.Git().WorkingTree.WorktreeFileDiff(fileLines.file, git_commands.DiffModePlain, onStagedSide)) + if err := self.checkShown(fileLines.shown, fileLines.file.Names(), onStagedSide, parsedPatch.FileVersions()); err != nil { + return nil, err + } + return parsedPatch, nil +} + // applyDiffLinesPatch applies what buildDiffLinesPatch built, as opts says. func (self *WorkingTreeDiffActions) applyDiffLinesPatch(p diffLinesPatch, opts git_commands.ApplyPatchOpts) error { if p.wholeFile { diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 319bac2c6..c98b02722 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -90,11 +90,7 @@ type Gui struct { // holds a mapping of the main section's view names to the writers that link the // files named in the diffstat of what is rendered into them diffStatLinkWriterMap map[string]*helpers.DiffStatLinkWriter - // 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]oscommands.Pty - stopChan chan struct{} + stopChan chan struct{} // when lazygit is opened outside a git directory we want to open to the most // recent repo with the recent repos popup showing @@ -235,8 +231,6 @@ func (self *StateAccessor) ClearItemOperation(item types.HasUrn) { // things have changed type PrevLayout struct { Information string - MainWidth int - MainHeight int } type GuiRepoState struct { @@ -804,7 +798,6 @@ func NewGui( statusManager: status.NewStatusManager(), viewBufferManagerMap: map[string]*tasks.ViewBufferManager{}, diffStatLinkWriterMap: map[string]*helpers.DiffStatLinkWriter{}, - viewPtmxMap: map[string]oscommands.Pty{}, showRecentRepos: showRecentRepos, RepoPathStack: &utils.Stack[types.RepoLocation]{}, RepoStateMap: map[Repo]*GuiRepoState{}, diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index 6fdaa503d..65c08e132 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -227,6 +227,10 @@ func (self *guiCommon) InDemo() bool { return self.gui.integrationTest != nil && self.gui.integrationTest.IsDemo() } +func (self *guiCommon) TerminalHasLightBackground() bool { + return self.gui.terminalHasLightBackground() +} + func (self *guiCommon) WithInlineStatus(item types.HasUrn, operation types.ItemOperation, contextKey types.ContextKey, f func(gocui.Task) error) error { self.gui.helpers.InlineStatus.WithInlineStatus(helpers.InlineStatusOpts{Item: item, Operation: operation, ContextKey: contextKey}, f) return nil diff --git a/pkg/gui/layout.go b/pkg/gui/layout.go index 41fb19d64..d0af14b5e 100644 --- a/pkg/gui/layout.go +++ b/pkg/gui/layout.go @@ -204,15 +204,6 @@ func (gui *Gui) layout(g *gocui.Gui) error { gui.State.ViewsSetup = true } - mainViewWidth, mainViewHeight := gui.Views.Main.Size() - if mainViewWidth != gui.PrevLayout.MainWidth || mainViewHeight != gui.PrevLayout.MainHeight { - gui.PrevLayout.MainWidth = mainViewWidth - gui.PrevLayout.MainHeight = mainViewHeight - if err := gui.onResize(); err != nil { - return err - } - } - for _, context := range contextsToRerender { context.HandleRender() } diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index abab6fcc8..030c52884 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -21,10 +21,10 @@ func (gui *Gui) runTaskForView(view *gocui.View, task types.UpdateTask) error { return gui.newStringTaskWithScroll(view, v.Str, v.OriginX, v.OriginY) case *types.RunCommandTask: - return gui.newCmdTask(view, v.Cmd, v.Prefix) + return gui.newCmdTask(view, v.Cmd, v.Prefix, v.ContentTag) case *types.RunDiffRendererTask: - return gui.newRenderTask(view, v.Cmd, v.Prefix) + return gui.newRenderTask(view, v.Cmd, v.Prefix, v.ContentTag) } return nil diff --git a/pkg/gui/main_view_render.go b/pkg/gui/main_view_render.go index 04dd5120a..b12df8757 100644 --- a/pkg/gui/main_view_render.go +++ b/pkg/gui/main_view_render.go @@ -4,16 +4,14 @@ import ( "errors" "fmt" "io" - "os" "os/exec" - "runtime" "strings" + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/types" "github.com/jesseduffield/lazygit/pkg/tasks" - "github.com/samber/lo" ) // renderSpec describes a render of a command's output into a view: what a way @@ -25,18 +23,17 @@ type renderSpec struct { // counts its own wrapping against. Read after the layout pass, which // settles it. width int - // The configured stdin filter, empty unless one is configured. How git gets - // to run it depends on the way the render runs. An external diff renderer - // is named to git in the environment before the render is set up, whichever - // way it runs, so it doesn't appear here; nothing else is a command of its - // own. + // The configured stdin filter, empty unless one is configured. It runs as a + // command of our own that git's output is piped into (see pipedRender). An + // external diff renderer is named to git in the environment before the render + // is set up, so it doesn't appear here; nothing else is a command of its own. stdinFilter string } // newRenderTask renders cmd's output into view, through the diff renderer the // user has configured. The renderer lays its rendering out to the width of the // view, which only the layout settles, so the task is created after it. -func (gui *Gui) newRenderTask(view *gocui.View, cmd *exec.Cmd, prefix types.Prefix) error { +func (gui *Gui) newRenderTask(view *gocui.View, cmd *exec.Cmd, prefix types.Prefix, contentTag func() any) error { // Ask whatever renders the diff to state, in an OSC 1717 record per line, // which line of which file it is rendering. This lets us act on the line the // user is pointing at even when the rendering no longer looks like a diff. @@ -48,8 +45,8 @@ func (gui *Gui) newRenderTask(view *gocui.View, cmd *exec.Cmd, prefix types.Pref cmd.Env = append(cmd.Env, "OSC1717=V1") if gui.stateAccessor.GetDiffRendererConfigManager().GetDiffRendererType() == config.DiffRendererType_RawGit { - // If we're not using a custom diff renderer, then we don't need to use a pty - return gui.newCmdTask(view, cmd, prefix) + // Git renders its own diff, without anything that the rest of this sets up. + return gui.newCmdTask(view, cmd, prefix, contentTag) } // The key the render is remembered under says which diff it is of, so that a @@ -96,12 +93,7 @@ func (gui *Gui) newRenderTask(view *gocui.View, cmd *exec.Cmd, prefix types.Pref gui.c.ErrorToast(err.Error()) } - // This communicates to diff renderers that we're in a very simple - // terminal that they should not expect to have much capabilities. - // Moving the cursor, clearing the screen, or querying for colors are among such "advanced" capabilities. - // Context: https://github.com/jesseduffield/lazygit/issues/3419 - cmd.Env = removeExistingTermEnvVars(cmd.Env) - cmd.Env = append(cmd.Env, "TERM=dumb") + oscommands.SetDumbTerminalEnv(cmd) // An external diff command is named to git here, in the environment, // because the width it renders at is only known after the layout, and @@ -119,11 +111,7 @@ func (gui *Gui) newRenderTask(view *gocui.View, cmd *exec.Cmd, prefix types.Pref width: width, stdinFilter: stdinFilter, } - run := gui.ptyRender - if rendersThroughAPipe() { - run = gui.pipedRender - } - return gui.newTaskForRender(reservation, spec, prefix, cmdStr, run) + return gui.newTaskForRender(reservation, spec, prefix, contentTag, cmdStr, gui.pipedRender) }) return nil @@ -149,15 +137,17 @@ type ( ) // runRender is a way of running a render's command and getting at its output: -// plainly, in a pty, or through a pipe with the stdin filter as a command of our -// own. It returns the functions the task drives the command by. +// plainly, or through a pipe with the stdin filter as a command of our own. It +// returns the functions the task drives the command by. type runRender func(spec renderSpec) (startRender, onCloseRender) // newTaskForRender creates the task that reads the render's output into its // view, running the command the given way. The task takes the place that the // reservation holds among the view's tasks. key names what is rendered, so that // a re-render of the same content can be told from a render of other content. -func (gui *Gui) newTaskForRender(reservation tasks.TaskReservation, spec renderSpec, prefix types.Prefix, key string, run runRender) error { +func (gui *Gui) newTaskForRender( + reservation tasks.TaskReservation, spec renderSpec, prefix types.Prefix, contentTag func() any, key string, run runRender, +) error { setColumnsEnvVar(spec.cmd, spec.width) start, onClose := run(spec) @@ -171,31 +161,19 @@ func (gui *Gui) newTaskForRender(reservation tasks.TaskReservation, spec renderS manager := gui.getManager(spec.view) linesToRead := gui.linesToReadFromCmdTask(spec.view) - return manager.NewReservedTask(reservation, manager.NewCmdTask(start, producePrefix, linesToRead, onClose), key) -} - -// renderWithoutPtyEnvVar makes a render take the piped path on a platform that -// would otherwise use a pty, so that tests can exercise it anywhere. -const renderWithoutPtyEnvVar = "LAZYGIT_RENDER_WITHOUT_PTY" - -// rendersThroughAPipe reports whether a render feeds the diff renderer the -// command's output through a pipe rather than running it in a pty. -// -// On Windows it has to. ConPTY doesn't pass a command's output through; it -// parses it into a screen buffer and re-encodes that for the terminal side, -// and it hands a sequence it can't represent there the moment it parses it, -// separately from the text around it. So what a renderer writes is not what -// lazygit reads. A pipe carries the bytes as the renderer wrote them. -// -// Everywhere else the pty is kept, since a renderer can read the width it -// should lay out to off it, and a configuration that doesn't name a width would -// otherwise render at whatever width the renderer falls back to. -func rendersThroughAPipe() bool { - return runtime.GOOS == "windows" || os.Getenv(renderWithoutPtyEnvVar) != "" + return manager.NewReservedTask(reservation, + manager.NewCmdTask(start, producePrefix, contentTag, linesToRead, onClose), key) } // pipedRender feeds the diff renderer the command's output through a pipe. // +// The renderer doesn't run in a terminal. A pty would carry its output more +// slowly, and on Windows not as the renderer wrote it: ConPTY parses a command's +// output into a screen buffer and re-encodes that for the terminal side, and it +// hands a sequence it can't represent there over separately from the text around +// it. A renderer learns the width to lay itself out to from COLUMNS (see +// setColumnsEnvVar), or from its command line. +// // A stdin filter becomes a command of our own here, because git only invokes // the one named by GIT_PAGER when it thinks it is talking to a terminal, so // with a pipe the filter would never run. An external diff renderer is git's @@ -211,17 +189,18 @@ func (gui *Gui) pipedRender(spec renderSpec) (startRender, onCloseRender) { var pipe io.ReadCloser start := func() (tasks.Cmd, io.Reader) { - // See the matching call in ptyRender for why this happens here. + // See the matching call in plainRender for why this happens here. view.SetContentWidth(spec.width) // The filter runs in a plain shell, without lazygit's shell functions // sourced, since that is the shell git would have run it in. It is // handed git's environment for the same reason: as git's child it // would have inherited exactly that. - pipeline, reader, err := gui.os.StartPipeline( - gui.os.Cmd.NewFromCmd(cmd).DontLog(), - gui.os.Cmd.NewShell(spec.stdinFilter, "").SetEnviron(cmd.Env).DontLog(), - ) + filter := gui.os.Cmd.NewShell(spec.stdinFilter, "").SetEnviron(cmd.Env).DontLog() + // See the matching call in startCmdWithPipe. + oscommands.DetachFromTerminal(cmd) + oscommands.DetachFromTerminal(filter.GetCmd()) + pipeline, reader, err := gui.os.StartPipeline(gui.os.Cmd.NewFromCmd(cmd).DontLog(), filter) if err != nil { gui.c.Log.Error(err) // The command has been started and stopped again by now, so it @@ -249,25 +228,8 @@ func (gui *Gui) pipedRender(spec renderSpec) (startRender, onCloseRender) { // setColumnsEnvVar tells a command how wide the view its output goes into is. // git reads COLUMNS in preference to the size of the terminal it is talking to, // and lays the diffstat graph out to it; a diff renderer with no terminal to -// ask may read it too (difftastic and diff-so-fancy do, delta does not). A -// command told nothing renders for 80 columns. +// ask may read it too (difftastic, diff-so-fancy and recent versions of delta +// do). A command told nothing renders for 80 columns. func setColumnsEnvVar(cmd *exec.Cmd, width int) { cmd.Env = append(cmd.Env, fmt.Sprintf("COLUMNS=%d", width)) } - -func removeExistingTermEnvVars(env []string) []string { - return lo.Filter(env, func(envVar string, _ int) bool { - return !isTermEnvVar(envVar) - }) -} - -// Terminals set a variety of different environment variables -// to identify themselves to processes. This list should catch the most common among them. -func isTermEnvVar(envVar string) bool { - return strings.HasPrefix(envVar, "TERM=") || - strings.HasPrefix(envVar, "TERM_PROGRAM=") || - strings.HasPrefix(envVar, "TERM_PROGRAM_VERSION=") || - strings.HasPrefix(envVar, "TERMINAL_EMULATOR=") || - strings.HasPrefix(envVar, "TERMINAL_NAME=") || - strings.HasPrefix(envVar, "TERMINAL_VERSION_") -} diff --git a/pkg/gui/pty.go b/pkg/gui/pty.go deleted file mode 100644 index bbc570ed6..000000000 --- a/pkg/gui/pty.go +++ /dev/null @@ -1,106 +0,0 @@ -package gui - -import ( - "io" - "os" - "os/exec" - - "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" -) - -func (gui *Gui) desiredPtySize(view *gocui.View) (cols, rows uint16) { - return uint16(gui.renderWidth(view)), uint16(view.InnerHeight()) -} - -func (gui *Gui) onResize() error { - gui.Mutexes.PtyMutex.Lock() - defer gui.Mutexes.PtyMutex.Unlock() - - 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) - cols, rows := gui.desiredPtySize(view) - if err := p.Resize(cols, rows); err != nil { - return utils.WrapError(err) - } - } - - 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) Terminate() error { return oscommands.TerminateProcessGracefully(p.process) } - -// ptyRender runs the command in a pseudo-terminal. git invokes the stdin filter -// named by GIT_PAGER only when it talks to a terminal, and a renderer reads the -// width it lays out to off it. -// -// Must be called on the UI thread: it reads the view's dimensions, which the -// layout writes. -func (gui *Gui) ptyRender(spec renderSpec) (startRender, onCloseRender) { - view := spec.view - cmd := spec.cmd - - // git runs the stdin filter itself, as the pager it is told about here. - // Named even when there is none, so that git doesn't reach for the user's - // core.pager instead. - cmd.Env = append(cmd.Env, "GIT_PAGER="+spec.stdinFilter) - - cols, rows := gui.desiredPtySize(view) - - var p oscommands.Pty - var fallbackPipe io.ReadCloser - start := func() (tasks.Cmd, io.Reader) { - // The pty (and diff renderer) 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(spec.width) - - sp, err := oscommands.StartPty(cmd, cols, rows) - if err != nil { - gui.c.Log.Error(err) - // Fall back to running the command without a pty: the diff renderer is - // lost, but the command's output still renders. - execCmd, pipe := startCmdWithPipe(cmd, gui.c.Log) - fallbackPipe = pipe - return execCmd, pipe - } - p = sp.Pty - - gui.Mutexes.PtyMutex.Lock() - gui.viewPtmxMap[view.Name()] = p - gui.Mutexes.PtyMutex.Unlock() - - return ptyCmd{cmd: cmd, process: sp.Process, wait: sp.Wait}, p - } - - onClose := func() { - gui.Mutexes.PtyMutex.Lock() - if p != nil { - p.Close() - } - if fallbackPipe != nil { - fallbackPipe.Close() - fallbackPipe = nil - } - delete(gui.viewPtmxMap, view.Name()) - gui.Mutexes.PtyMutex.Unlock() - } - - return start, onClose -} diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 114c27705..80203eb68 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -5,6 +5,7 @@ import ( "os/exec" "strings" + "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -12,7 +13,7 @@ import ( "github.com/sirupsen/logrus" ) -func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix types.Prefix) error { +func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix types.Prefix, contentTag func() any) error { cmdStr := strings.Join(cmd.Args, " ") gui.c.Log.WithField( "command", @@ -46,7 +47,7 @@ func (gui *Gui) newCmdTask(view *gocui.View, cmd *exec.Cmd, prefix types.Prefix) } spec := renderSpec{view: view, cmd: cmd, width: gui.renderWidth(view)} - return gui.newTaskForRender(reservation, spec, prefix, cmdStr, gui.plainRender) + return gui.newTaskForRender(reservation, spec, prefix, contentTag, cmdStr, gui.plainRender) }) return nil @@ -90,6 +91,11 @@ func startCmdWithPipe(cmd *exec.Cmd, log *logrus.Entry) (tasks.Cmd, io.ReadClose return tasks.ExecCmd{Cmd: cmd}, io.NopCloser(strings.NewReader("")) } cmd.Stderr = cmd.Stdout + // A render's command writes to the view, not to lazygit's terminal. A diff + // renderer that found that terminal would lay itself out to the width of the + // whole window rather than to the width of the view, which it is told in + // COLUMNS. + oscommands.DetachFromTerminal(cmd) if err := cmd.Start(); err != nil { log.Error(err) diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 2d2ec134b..5301a3694 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -160,6 +160,10 @@ type IGuiCommon interface { // Returns true if we're in a demo recording/playback InDemo() bool + + // Returns true if the terminal has a light background, going by + // gui.colorScheme, or by what the terminal tells us if that is 'auto' + TerminalHasLightBackground() bool } type IModeMgr interface { @@ -400,7 +404,6 @@ type Model struct { type Mutexes struct { SubprocessMutex deadlock.Mutex - PtyMutex deadlock.Mutex } // A long-running operation associated with an item. For example, we'll show diff --git a/pkg/gui/types/context.go b/pkg/gui/types/context.go index 46a111a42..ceb074bdc 100644 --- a/pkg/gui/types/context.go +++ b/pkg/gui/types/context.go @@ -286,8 +286,10 @@ type DiffPaneContext interface { // of a commit's diff can be had without fetching the whole thing. pane says which of // the two main panes is asking, since a panel can show a different diff in each — the // files panel shows the unstaged changes in one and the staged ones in the other. +// +// It fails, with an error to show to the user, when there is no diff to hand out. type FocusedMainViewDiffSource interface { - PlainDiff(pane DiffPaneContext, paths []string) string + PlainDiff(pane DiffPaneContext, paths []string) (string, error) } // FocusedMainViewActions describes what a side panel does when the user acts on a diff --git a/pkg/gui/types/rendering.go b/pkg/gui/types/rendering.go index 7e07e4386..4e6cb2642 100644 --- a/pkg/gui/types/rendering.go +++ b/pkg/gui/types/rendering.go @@ -114,6 +114,11 @@ type RunCommandTask struct { Cmd *exec.Cmd Prefix Prefix + // ContentTag, unless nil, produces what the render attaches to the content it + // renders (see gocui.View.BeginOffscreenRender). It is called on the render's own + // goroutine before the command starts. + ContentTag func() any + // contentIsDiff marks output that is a panel's own diff; see ContentIsDiff. contentIsDiff bool } @@ -132,6 +137,9 @@ type RunDiffRendererTask struct { Cmd *exec.Cmd Prefix Prefix + // ContentTag is as for RunCommandTask. + ContentTag func() any + // contentIsDiff marks output that is a panel's own diff; see ContentIsDiff. contentIsDiff bool } @@ -158,12 +166,24 @@ func NewMainViewDiffTask(cmd *exec.Cmd, mode git_commands.DiffMode) UpdateTask { } func NewMainViewDiffTaskWithPrefix(cmd *exec.Cmd, prefix Prefix, mode git_commands.DiffMode) UpdateTask { + return newMainViewDiffTask(cmd, prefix, nil, mode) +} + +// NewMainViewDiffTaskWithContentTag is NewMainViewDiffTask for a render that attaches +// what contentTag produces to its content (see RunCommandTask.ContentTag). +func NewMainViewDiffTaskWithContentTag(cmd *exec.Cmd, contentTag func() any, mode git_commands.DiffMode) UpdateTask { + return newMainViewDiffTask(cmd, nil, contentTag, mode) +} + +func newMainViewDiffTask(cmd *exec.Cmd, prefix Prefix, contentTag func() any, mode git_commands.DiffMode) UpdateTask { if mode == git_commands.DiffModeRaw { task := NewRunCommandTaskWithPrefix(cmd, prefix) + task.ContentTag = contentTag task.contentIsDiff = true return task } task := NewRunDiffRendererTaskWithPrefix(cmd, prefix) + task.ContentTag = contentTag task.contentIsDiff = true return task } diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index 8a992ed2f..f77335f33 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -759,6 +759,7 @@ type TranslationSet struct { OpenCommandLogMenuTooltip string ShowingGitDiff string ShowingDiffForRange string + CommitMessageChanges string CommitDiff string CopyCommitHashToClipboard string CommitHash string @@ -783,6 +784,7 @@ type TranslationSet struct { SelectionNotFoundInDiffToast string DiffLinesFileNotFound string DiffLinesNotFound string + DiffChangedSinceShown string CommitNotInCommitsPanel string NoFilesStagedTitle string NoFilesStagedPrompt string @@ -1992,6 +1994,7 @@ func EnglishTranslationSet() *TranslationSet { OpenCommandLogMenuTooltip: "View options for the command log e.g. show/hide the command log and focus the command log.", ShowingGitDiff: "Showing output for:", ShowingDiffForRange: "Showing diff for range", + CommitMessageChanges: "Commit message changes compared to {{.hash}}:", CommitDiff: "Commit diff", CopyCommitHashToClipboard: "Copy abbreviated commit hash to clipboard", CommitHash: "Commit hash", @@ -2015,6 +2018,7 @@ func EnglishTranslationSet() *TranslationSet { SelectionNotFoundInDiffToast: "Nothing in the selection could be found in the diff", DiffLinesFileNotFound: "Can't find the file '{{.path}}' that the selected lines belong to", DiffLinesNotFound: "Can't find the selected lines in the diff of '{{.path}}'", + DiffChangedSinceShown: "The diff of '{{.path}}' has changed since it was shown. Check the updated diff and select the lines again.", CommitNotInCommitsPanel: "Can't find commit {{.hash}} in the commits panel", CommitPrefixPatternError: "Error in commitPrefix pattern", NoFilesStagedTitle: "No files staged", diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff.go b/pkg/integration/tests/commit/show_amend_commit_message_diff.go new file mode 100644 index 000000000..1694ef532 --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff.go @@ -0,0 +1,74 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ShowAmendCommitMessageDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Show a diff of the commit message when selecting an amend! commit", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell. + EmptyCommitWithBody("Fix the widget", + "The frobnicator was not initialised properly at all."). + EmptyCommitWithBody("amend! Fix the widget", + "Fix the widget on startup\n\nThe frobnicator was not initialised at all."). + EmptyCommitWithBody("amend! Fix the widget", + "Fix the widget on startup\n\nThe frobnicator was not properly initialised at all.") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // git's default colors for added and removed lines + green := "#008000" + red := "#800000" + + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("amend! Fix the widget"), + Contains("Fix the widget"), + ) + + // The message of the topmost amend! commit is compared with the message + // of the amend! commit below it, not with the one of the commit they + // both apply to. + t.Views().Main(). + TopLines( + Contains("Commit message changes compared to"), + Equals(" Fix the widget on startup"), + Equals(" "), + Equals("-The frobnicator was not initialised at all."), + Equals("+The frobnicator was not properly initialised at all."), + Contains("───"), + ). + ContainsColoredText(green, "+The frobnicator was not properly initialised at all."). + ContainsColoredText(red, "-The frobnicator was not initialised at all.") + + t.Views().Commits(). + SelectNextItem() + + // The other amend! commit is compared with the commit it applies to. + t.Views().Main(). + TopLines( + Contains("Commit message changes compared to"), + Equals("-Fix the widget"), + Equals("+Fix the widget on startup"), + Equals(" "), + Equals("-The frobnicator was not initialised properly at all."), + Equals("+The frobnicator was not initialised at all."), + Contains("───"), + ) + + t.Views().Commits(). + SelectNextItem() + + // The commit that they both apply to gets no such header. + t.Views().Main(). + TopLines( + Contains("commit "), + ) + }, +}) diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff_beside_the_patch_marks.go b/pkg/integration/tests/commit/show_amend_commit_message_diff_beside_the_patch_marks.go new file mode 100644 index 000000000..0d841bd14 --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff_beside_the_patch_marks.go @@ -0,0 +1,43 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ShowAmendCommitMessageDiffBesideThePatchMarks = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The commit message diff of an amend! commit is laid out to the width that the custom patch's marks leave the diff below it", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file", "one\n") + shell.Commit("Fix the widget") + shell.UpdateFileAndAdd("file", "one\ntwo\n") + shell.Commit("amend! Fix the widget\n\nFix the widget on startup") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("Fix the widget"), + ). + Press(keys.Universal.FocusMainView) + + // The rule below the message diff is as wide as the diff is laid out to, + // so it only fits on one line beside the marks if the message diff was + // laid out to the width they leave. + t.Views().Main(). + IsFocused(). + PressPrimaryAction(). + MarkedLines( + Contains("+two"), + ). + ContainsViewLines( + Equals("+Fix the widget on startup"), + MatchesRegexp("^─+$"), + Contains("commit "), + ) + }, +}) diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff_in_a_split_main_view.go b/pkg/integration/tests/commit/show_amend_commit_message_diff_in_a_split_main_view.go new file mode 100644 index 000000000..a49c1d827 --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff_in_a_split_main_view.go @@ -0,0 +1,47 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ShowAmendCommitMessageDiffInASplitMainView = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The commit message diff of an amend! commit is laid out to the width of the main view once building a custom patch splits it", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + // The pane showing the custom patch goes beside the diff, so the diff + // gets narrower when the patch is started. + cfg.GetUserConfig().Gui.MainPanelSplitMode = "horizontal" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file", "one\n") + shell.Commit("Fix the widget") + shell.UpdateFileAndAdd("file", "one\ntwo\n") + shell.Commit("amend! Fix the widget\n\nFix the widget on startup") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("Fix the widget"), + ). + Press(keys.Universal.FocusMainView) + + // The rule below the message diff is as wide as the diff is laid out to, + // so it only fits on one line if the message diff was laid out to the + // width of the split view. + t.Views().Main(). + IsFocused(). + PressPrimaryAction(). + MarkedLines( + Contains("+two"), + ). + ContainsViewLines( + Equals("+Fix the widget on startup"), + MatchesRegexp("^─+$"), + Contains("commit "), + ) + }, +}) diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff_through_a_pipe.go b/pkg/integration/tests/commit/show_amend_commit_message_diff_through_a_pipe.go new file mode 100644 index 000000000..a6cefcc66 --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff_through_a_pipe.go @@ -0,0 +1,44 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ShowAmendCommitMessageDiffThroughAPipe = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Show the commit message diff of an amend! commit through a diff renderer that is fed through a pipe", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + // Says so if it is writing into a pipe, then passes the diff through. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Command: `[ -t 1 ] || echo "rendered into a pipe"; cat`}, + } + }, + SetupRepo: func(shell *Shell) { + shell. + EmptyCommitWithBody("Fix the widget", + "The frobnicator was not initialised."). + EmptyCommitWithBody("amend! Fix the widget", + "Fix the widget on startup\n\nThe frobnicator was not initialised.") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("Fix the widget"), + ) + + t.Views().Main(). + TopLines( + Contains("Commit message changes compared to"), + Equals("rendered into a pipe"), + Equals("diff --git old message new message"), + ). + ContainsLines( + Equals("-Fix the widget"), + Equals("+Fix the widget on startup"), + ) + }, +}) diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff_with_renderer.go b/pkg/integration/tests/commit/show_amend_commit_message_diff_with_renderer.go new file mode 100644 index 000000000..ee501ffe7 --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff_with_renderer.go @@ -0,0 +1,48 @@ +package commit + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ShowAmendCommitMessageDiffWithRenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Show the commit message diff of an amend! commit through a diff renderer", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + // cat does nothing to the diff, but it is a diff renderer as far as + // lazygit is concerned, so the diff takes the same route through it as + // it would for a real one. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{{Command: "cat"}} + }, + SetupRepo: func(shell *Shell) { + shell. + EmptyCommitWithBody("Fix the widget", + "The frobnicator was not initialised."). + EmptyCommitWithBody("amend! Fix the widget", + "Fix the widget on startup\n\nThe frobnicator was not initialised.") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("Fix the widget"), + ) + + // A diff renderer states the two sides of the diff in its own way, so + // unlike for git's own diff, the header naming them is kept. + t.Views().Main(). + TopLines( + Contains("Commit message changes compared to"), + Equals("diff --git old message new message"), + ). + ContainsLines( + Contains("--- old message"), + Contains("+++ new message"), + Contains("@@"), + Equals("-Fix the widget"), + Equals("+Fix the widget on startup"), + ) + }, +}) diff --git a/pkg/integration/tests/commit/show_amend_commit_message_diff_with_several_hunks.go b/pkg/integration/tests/commit/show_amend_commit_message_diff_with_several_hunks.go new file mode 100644 index 000000000..07ddec24b --- /dev/null +++ b/pkg/integration/tests/commit/show_amend_commit_message_diff_with_several_hunks.go @@ -0,0 +1,60 @@ +package commit + +import ( + "strings" + + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +const showAmendCommitMessageDiffWithSeveralHunksBody = `The frobnicator was not initialised. + +It has to be initialised before the widget +draws itself for the first time, or the +widget shows garbage until it is resized. + +This only showed on startup, so nobody +noticed it for a long time. + +Fixes #123.` + +var ShowAmendCommitMessageDiffWithSeveralHunks = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The hunks of the commit message diff of an amend! commit are not headed by a line of the message", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) {}, + SetupRepo: func(shell *Shell) { + shell. + EmptyCommitWithBody("Fix the widget", showAmendCommitMessageDiffWithSeveralHunksBody). + EmptyCommitWithBody("amend! Fix the widget", + "Fix the widget on startup\n\n"+ + strings.Replace(showAmendCommitMessageDiffWithSeveralHunksBody, "#123", "#124", 1)) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("amend! Fix the widget").IsSelected(), + Contains("Fix the widget"), + ) + + // git would head the second hunk with the last line above it that + // starts with a letter, as if it named the function the hunk is in. + t.Views().Main(). + TopLines( + Contains("Commit message changes compared to"), + Equals("-Fix the widget"), + Equals("+Fix the widget on startup"), + Equals(" "), + Equals(" The frobnicator was not initialised."), + Equals(" "), + Equals("@@ -9,4 +9,4 @@"), + Equals(" This only showed on startup, so nobody"), + Equals(" noticed it for a long time."), + Equals(" "), + Equals("-Fixes #123."), + Equals("+Fixes #124."), + Contains("───"), + ) + }, +}) diff --git a/pkg/integration/tests/diff/render_through_a_pipe.go b/pkg/integration/tests/diff/render_through_a_pipe.go index 0fc42b1cf..4b336e3f3 100644 --- a/pkg/integration/tests/diff/render_through_a_pipe.go +++ b/pkg/integration/tests/diff/render_through_a_pipe.go @@ -6,13 +6,9 @@ import ( ) var RenderThroughAPipe = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "A stdin filter renders the diff when it is fed through a pipe rather than run in a pty", + Description: "A stdin filter renders the diff that it is fed through a pipe", ExtraCmdArgs: []string{}, Skip: false, - // This is how a render works on Windows, where a pty can't carry a - // renderer's output faithfully. Ask for it here so that the path is - // covered on the platforms the integration tests do run on. - ExtraEnvVars: map[string]string{"LAZYGIT_RENDER_WITHOUT_PTY": "1"}, SetupConfig: func(cfg *config.AppConfig) { // Reports the width it was given, then passes the diff through. git // only runs a filter of its own when it talks to a terminal, so the diff --git a/pkg/integration/tests/diff/render_through_a_pipe_without_a_terminal.go b/pkg/integration/tests/diff/render_through_a_pipe_without_a_terminal.go new file mode 100644 index 000000000..f586e5c37 --- /dev/null +++ b/pkg/integration/tests/diff/render_through_a_pipe_without_a_terminal.go @@ -0,0 +1,37 @@ +package diff + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RenderThroughAPipeWithoutATerminal = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "A diff renderer fed through a pipe has no terminal to ask for its size", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + // Reports the size of the terminal it can reach, the way a renderer that + // lays itself out to the terminal's width (difftastic does) finds its width, + // then passes the diff through. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Command: `echo "terminal: $(stty size /dev/null || echo none)"; cat`}, + } + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\n") + shell.Commit("one") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Commits(). + Focus(). + Lines( + Contains("one").IsSelected(), + ) + + // The terminal it would find is lazygit's own, which is as wide as the whole + // window rather than the view. With none, it falls back to the COLUMNS it is + // given. + t.Views().Main(). + Content(Contains("terminal: none")) + }, +}) diff --git a/pkg/integration/tests/main_view/copy_from_a_stale_diff.go b/pkg/integration/tests/main_view/copy_from_a_stale_diff.go new file mode 100644 index 000000000..0148add37 --- /dev/null +++ b/pkg/integration/tests/main_view/copy_from_a_stale_diff.go @@ -0,0 +1,49 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var CopyFromAStaleDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Copying lines of a diff that changed since it was shown copies nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + // Emulate the clipboard by writing to a file. + cfg.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + Press(keys.Universal.CopyToClipboard) + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + }, +}) diff --git a/pkg/integration/tests/main_view/copy_from_a_stale_diff_under_a_renderer.go b/pkg/integration/tests/main_view/copy_from_a_stale_diff_under_a_renderer.go new file mode 100644 index 000000000..7642567a1 --- /dev/null +++ b/pkg/integration/tests/main_view/copy_from_a_stale_diff_under_a_renderer.go @@ -0,0 +1,51 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var CopyFromAStaleDiffUnderARenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Copying lines of a renderer's diff whose file changed since it was shown copies nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{shared.RecordsDiffRenderer} + // Emulate the clipboard by writing to a file. + cfg.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + Press(keys.Universal.CopyToClipboard) + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + }, +}) diff --git a/pkg/integration/tests/main_view/discard_from_a_diff_that_changes_during_the_prompt.go b/pkg/integration/tests/main_view/discard_from_a_diff_that_changes_during_the_prompt.go new file mode 100644 index 000000000..611f96d71 --- /dev/null +++ b/pkg/integration/tests/main_view/discard_from_a_diff_that_changes_during_the_prompt.go @@ -0,0 +1,57 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var DiscardFromADiffThatChangesDuringThePrompt = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Discarding a line of a diff that changes while the confirmation is open discards nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ). + Press(keys.Universal.Remove) + + t.ExpectPopup().Confirmation(). + Title(Equals("Discard change")). + Content(Contains("Are you sure you want to discard this change")) + + // Another line takes the place of the selected one outside of lazygit while the + // user is being asked. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.ExpectPopup().Confirmation(). + Title(Equals("Discard change")). + Content(Contains("Are you sure you want to discard this change")). + Confirm() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.FileSystem().FileContent("file1", + Equals("one\nOTHER\ntwo\nthree\n")) + }, +}) diff --git a/pkg/integration/tests/main_view/discard_from_a_stale_diff.go b/pkg/integration/tests/main_view/discard_from_a_stale_diff.go new file mode 100644 index 000000000..84d844bb3 --- /dev/null +++ b/pkg/integration/tests/main_view/discard_from_a_stale_diff.go @@ -0,0 +1,50 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var DiscardFromAStaleDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Discarding a line of a diff that changed since it was shown discards nothing and shows an error before asking", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + Press(keys.Universal.Remove) + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.FileSystem().FileContent("file1", + Equals("one\nOTHER\ntwo\nthree\n")) + }, +}) diff --git a/pkg/integration/tests/main_view/edit_hunk_of_a_stale_diff.go b/pkg/integration/tests/main_view/edit_hunk_of_a_stale_diff.go new file mode 100644 index 000000000..91a61458c --- /dev/null +++ b/pkg/integration/tests/main_view/edit_hunk_of_a_stale_diff.go @@ -0,0 +1,56 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var EditHunkOfAStaleDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Editing the hunk of a diff that changed since it was shown opens no editor and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + // Stand in for the editor: keep a copy of the patch it was given, outside the + // repo so that the files panel keeps saying what the test is about, and hand it + // back as it is, so that it is staged. + cfg.GetUserConfig().OS.EditAtLineAndWait = "cp {{filename}} ../edited-patch" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + Press(keys.Main.EditSelectHunk) + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains(" M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/report_lines_missing_from_a_file_changed_since.go b/pkg/integration/tests/main_view/report_lines_missing_from_a_file_changed_since.go index b10618189..1dd89bc1f 100644 --- a/pkg/integration/tests/main_view/report_lines_missing_from_a_file_changed_since.go +++ b/pkg/integration/tests/main_view/report_lines_missing_from_a_file_changed_since.go @@ -41,7 +41,7 @@ var ReportLinesMissingFromAFileChangedSince = NewIntegrationTest(NewIntegrationT t.ExpectPopup().Alert(). Title(Equals("Error")). - Content(Equals("Can't find the selected lines in the diff of 'file1'")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). Confirm() }, }) diff --git a/pkg/integration/tests/main_view/report_lines_missing_from_the_working_tree_diff.go b/pkg/integration/tests/main_view/report_lines_missing_from_the_working_tree_diff.go new file mode 100644 index 000000000..b4b997434 --- /dev/null +++ b/pkg/integration/tests/main_view/report_lines_missing_from_the_working_tree_diff.go @@ -0,0 +1,52 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var ReportLinesMissingFromTheWorkingTreeDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging lines that the diff puts where the file's diff has none shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + // A renderer that announces the metadata protocol and passes the diff through, + // except that its hunk header puts the hunk ten lines further down. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Command: `printf '\033]1717;1\007'; sed 's#@@ -1,3 +1,4 @@#@@ -11,3 +11,4 @@#'`}, + } + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("Can't find the selected lines in the diff of 'file1'")). + Confirm() + + // Nothing was staged. + t.Views().Files(). + Lines( + Contains(" M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_after_changes_that_leave_the_diff_alone.go b/pkg/integration/tests/main_view/stage_after_changes_that_leave_the_diff_alone.go new file mode 100644 index 000000000..1f23a40e3 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_after_changes_that_leave_the_diff_alone.go @@ -0,0 +1,59 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageAfterChangesThatLeaveTheDiffAlone = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging a line still works after changes outside of lazygit that leave the file's diff as it was", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.CreateFileAndAdd("file2", "a\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + shell.UpdateFile("file2", "b\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Equals("▼ /").IsSelected(), + Contains(" M file1"), + Contains(" M file2"), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Outside of lazygit, and with nothing refreshing the diff: the file is written + // with the content it has, the index is rewritten for another file, and HEAD + // moves to a commit of that other file. + t.Shell(). + UpdateFile("file1", "one\nADD1\ntwo\nthree\n"). + GitAdd("file2"). + Commit("two") + + t.Views().Main(). + PressPrimaryAction() + + t.Views().Files(). + Lines( + Contains("M file1"), + ) + t.Views().Secondary(). + ContainsLines( + Contains("+ADD1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_from_a_refreshed_diff_under_a_renderer.go b/pkg/integration/tests/main_view/stage_from_a_refreshed_diff_under_a_renderer.go new file mode 100644 index 000000000..c0afe7d56 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_from_a_refreshed_diff_under_a_renderer.go @@ -0,0 +1,67 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var StageFromARefreshedDiffUnderARenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging a line of a renderer's diff works once the diff has been rendered again after a change, and after the index changed for another file", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{shared.RecordsDiffRenderer} + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.CreateFileAndAdd("file2", "a\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + shell.UpdateFile("file2", "b\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Equals("▼ /").IsSelected(), + Contains(" M file1"), + Contains(" M file2"), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // The file changes outside of lazygit, and the diff is rendered again. What it was + // made from goes with the diff now on screen. + t.Shell().UpdateFile("file1", "one\nADD1\ntwo\nthree\nEND\n") + t.GlobalPress(keys.Universal.Refresh) + t.Views().Main(). + IsFocused(). + ContainsLines( + Contains("+END"), + ). + SelectedLines( + Contains("+ADD1"), + ) + + // The index is rewritten for the other file, which leaves this file's diff alone. + t.Shell().GitAdd("file2") + + t.Views().Main(). + PressPrimaryAction() + + t.Views().Files(). + Lines( + Equals("▼ /"), + Contains("MM file1"), + Contains("M file2"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_from_a_stale_diff.go b/pkg/integration/tests/main_view/stage_from_a_stale_diff.go new file mode 100644 index 000000000..00d96fca7 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_from_a_stale_diff.go @@ -0,0 +1,52 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageFromAStaleDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging a line of a diff that changed since it was shown stages nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains(" M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_from_a_stale_diff_under_a_renderer.go b/pkg/integration/tests/main_view/stage_from_a_stale_diff_under_a_renderer.go new file mode 100644 index 000000000..18281f4bd --- /dev/null +++ b/pkg/integration/tests/main_view/stage_from_a_stale_diff_under_a_renderer.go @@ -0,0 +1,54 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var StageFromAStaleDiffUnderARenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging a line of a renderer's diff whose file changed since it was shown stages nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{shared.RecordsDiffRenderer} + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains(" M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one outside of lazygit, and + // nothing has refreshed the diff since. + t.Shell().UpdateFile("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Main(). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains(" M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved.go b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved.go new file mode 100644 index 000000000..53418e2c6 --- /dev/null +++ b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved.go @@ -0,0 +1,55 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var UnstageFromADiffWhoseHeadMoved = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Unstaging a line of the staged diff after HEAD moved since it was shown unstages nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\nTWO\nthree\n") + shell.Commit("one") + shell.UpdateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("two") + + shell.UpdateFileAndAdd("file1", "one\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("-two"), + ) + + // HEAD moves back to the commit with the other line outside of lazygit, without + // touching the index, and nothing has refreshed the diff since. The staged diff + // now deletes the other line, at the same place. + t.Shell().RunCommand([]string{"git", "reset", "--soft", "HEAD~"}) + + t.Views().Secondary(). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains("M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved_under_a_renderer.go b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved_under_a_renderer.go new file mode 100644 index 000000000..ed2a73e0e --- /dev/null +++ b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_head_moved_under_a_renderer.go @@ -0,0 +1,57 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var UnstageFromADiffWhoseHeadMovedUnderARenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Unstaging a line of a renderer's staged diff after HEAD moved since it was shown unstages nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{shared.RecordsDiffRenderer} + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\nTWO\nthree\n") + shell.Commit("one") + shell.UpdateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("two") + + shell.UpdateFileAndAdd("file1", "one\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("-two"), + ) + + // HEAD moves back to the commit with the other line outside of lazygit, without + // touching the index, and nothing has refreshed the diff since. The staged diff + // now deletes the other line, at the same place. + t.Shell().RunCommand([]string{"git", "reset", "--soft", "HEAD~"}) + + t.Views().Secondary(). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains("M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/unstage_from_a_diff_whose_index_changed_under_a_renderer.go b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_index_changed_under_a_renderer.go new file mode 100644 index 000000000..5ae94e0a7 --- /dev/null +++ b/pkg/integration/tests/main_view/unstage_from_a_diff_whose_index_changed_under_a_renderer.go @@ -0,0 +1,54 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" + "github.com/jesseduffield/lazygit/pkg/integration/tests/shared" +) + +var UnstageFromADiffWhoseIndexChangedUnderARenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Unstaging a line of a renderer's staged diff after the index changed since it was shown unstages nothing and shows an error", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInDiffView = false + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{shared.RecordsDiffRenderer} + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFileAndAdd("file1", "one\nADD1\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ) + + // Another line takes the place of the selected one in the index outside of + // lazygit, and nothing has refreshed the diff since. + t.Shell().UpdateFileAndAdd("file1", "one\nOTHER\ntwo\nthree\n") + + t.Views().Secondary(). + PressPrimaryAction() + + t.ExpectPopup().Alert(). + Title(Equals("Error")). + Content(Equals("The diff of 'file1' has changed since it was shown. Check the updated diff and select the lines again.")). + Confirm() + + t.Views().Files(). + Lines( + Contains("M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/shared/diff_renderers.go b/pkg/integration/tests/shared/diff_renderers.go new file mode 100644 index 000000000..4856b483d --- /dev/null +++ b/pkg/integration/tests/shared/diff_renderers.go @@ -0,0 +1,23 @@ +package shared + +import "github.com/jesseduffield/lazygit/pkg/config" + +// RecordsDiffRenderer stands in for a diff renderer that states each row it renders in +// an OSC 1717 record, as delta and diff-so-fancy do. It passes the diff through as it +// is, but since it states its rows, lazygit places them by the records alone and reads +// nothing out of the text, the diff's header included. It reads the diff's +/- column, +// so it wants its input uncoloured. +var RecordsDiffRenderer = config.DiffRendererConfig{ + Command: `printf '\033]1717;1\007'; awk ' + /^diff --git / { file = $0; sub(/^.* b\//, "", file); inHunk = 0 } + /^@@ / { + split($2, o, ","); split($3, n, ","); old = -o[1]; new = n[1] + 0; inHunk = 1 + printf "\033]1717;1;h;%d;;%s\007%s\n", new, file, $0; next + } + !inHunk { printf "\033]1717;1;f;;;%s\007%s\n", file, $0; next } + /^\+/ { printf "\033]1717;1;a;%d;;%s\007%s\n", new, file, $0; new++; next } + /^-/ { printf "\033]1717;1;d;%d;%d;%s\007%s\n", new, old, file, $0; old++; next } + /^ / { printf "\033]1717;1;c;%d;;%s\007%s\n", new, file, $0; new++; old++; next } + { print }'`, + ColorArg: "never", +} diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 7286c20a8..180a6981e 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -208,6 +208,12 @@ var tests = []*components.IntegrationTest{ commit.SearchScrollsToAMatchOffTheEdge, commit.SetAuthor, commit.SetAuthorRange, + commit.ShowAmendCommitMessageDiff, + commit.ShowAmendCommitMessageDiffBesideThePatchMarks, + commit.ShowAmendCommitMessageDiffInASplitMainView, + commit.ShowAmendCommitMessageDiffThroughAPipe, + commit.ShowAmendCommitMessageDiffWithRenderer, + commit.ShowAmendCommitMessageDiffWithSeveralHunks, commit.StageRangeOfLines, commit.Staged, commit.StagedWithoutHooks, @@ -282,6 +288,7 @@ var tests = []*components.IntegrationTest{ diff.IgnoreWhitespace, diff.RenameSimilarityThresholdChange, diff.RenderThroughAPipe, + diff.RenderThroughAPipeWithoutATerminal, diff.StatFollowsAScreenModeChange, diff.StatUsesTheViewWidth, file.ClickArrowToCollapse, @@ -442,6 +449,8 @@ var tests = []*components.IntegrationTest{ main_view.ClickAFileInTheDiffStat, main_view.ClickSelectsDiffLine, main_view.CommitFromMainView, + main_view.CopyFromAStaleDiff, + main_view.CopyFromAStaleDiffUnderARenderer, main_view.CopyRowsThatAreNoDiffLine, main_view.CopySelectedDiffLines, main_view.CustomPatchGoesThroughTheDiffRenderer, @@ -451,6 +460,8 @@ var tests = []*components.IntegrationTest{ main_view.DiscardAllChanges, main_view.DiscardDiffLines, main_view.DiscardFromACommitOnlyWhereItCanBeRewritten, + main_view.DiscardFromADiffThatChangesDuringThePrompt, + main_view.DiscardFromAStaleDiff, main_view.DiscardLineFromAddedFileInCommit, main_view.DiscardLinesFromACommit, main_view.DragRangeWithAutoscroll, @@ -458,6 +469,7 @@ var tests = []*components.IntegrationTest{ main_view.EditClickedDiffLine, main_view.EditHistoricalDiffLine, main_view.EditHunkInFocusedDiff, + main_view.EditHunkOfAStaleDiff, main_view.EditSelectedDiffLine, main_view.EnterAndDoubleClickFocusFileDiff, main_view.EscapeDismissesSelection, @@ -532,6 +544,7 @@ var tests = []*components.IntegrationTest{ main_view.RenderTheDiffBesideThePatchMarks, main_view.ReportLinesMissingFromACommitsDiff, main_view.ReportLinesMissingFromAFileChangedSince, + main_view.ReportLinesMissingFromTheWorkingTreeDiff, main_view.ReportLinesOfAFileMissingFromTheCommitsDiff, main_view.ReportLinesOfAFileMissingFromTheFilesPanel, main_view.ResetAPatchBuiltFromACommitsDiff, @@ -561,12 +574,16 @@ var tests = []*components.IntegrationTest{ main_view.SelectionOverTheCustomPatch, main_view.ShowAnotherLongDiffAfterScrollingFarDown, main_view.ShowTheTabSwitchedToLast, + main_view.StageAfterChangesThatLeaveTheDiffAlone, main_view.StageDeletedFile, main_view.StageDiffLines, main_view.StageDiffLinesOfAPathWithASpace, main_view.StageDiffLinesWithCustomPrefixes, main_view.StageDiffLinesWithMnemonicPrefixes, main_view.StageDiffLinesWithNoPrefixes, + main_view.StageFromARefreshedDiffUnderARenderer, + main_view.StageFromAStaleDiff, + main_view.StageFromAStaleDiffUnderARenderer, main_view.StageHunksWithRapidKeypresses, main_view.StagePartialBlockOfChangesFirstLines, main_view.StagePartialBlockOfChangesLastLines, @@ -576,6 +593,9 @@ var tests = []*components.IntegrationTest{ main_view.StageUnderUnsupportedDiffRenderer, main_view.StartPatchFromAnotherCommit, main_view.UnstageDiffLines, + main_view.UnstageFromADiffWhoseHeadMoved, + main_view.UnstageFromADiffWhoseHeadMovedUnderARenderer, + main_view.UnstageFromADiffWhoseIndexChangedUnderARenderer, main_view.WrapOnlyTheDiff, misc.ConfirmOnQuit, misc.CopyConfirmationMessageToClipboard, diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 5b70d2ca6..2c5a6664f 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -18,10 +18,9 @@ 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). +// Cmd abstracts over a started external process, or a chain of them. *exec.Cmd +// satisfies the bulk of it via ExecCmd, and oscommands.Pipeline satisfies it for +// a chain. type Cmd interface { Wait() error String() string @@ -133,7 +132,8 @@ type ViewBufferManager struct { // disturbing what's displayed. swapInRender then promotes it to the display // in one step. Together they keep the view showing the previous render until // the new one has read enough to paint, instead of revealing it line by line. - beginRender func() + // beginRender is given what the task attaches to its content (see NewCmdTask). + beginRender func(tag any) swapInRender func() // see docs/dev/Busy.md @@ -341,7 +341,7 @@ func NewViewBufferManager( refreshView func(), onEndOfInput func(), resetOrigin func(), - beginRender func(), + beginRender func(tag any), swapInRender func(), newGocuiTask func() gocui.Task, onUIThread func(f func()) error, @@ -466,10 +466,13 @@ func answerReadRequests(requests []LinesToRead) { } // NewCmdTask returns a task that renders the output of the command that start -// starts. prefix, unless nil, produces the text shown above that output. It is -// called on the task's goroutine before the command starts, so a prefix that -// takes a while to produce holds up only this task. -func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix func() string, linesToRead LinesToRead, onDoneFn func()) func(TaskOpts) error { +// starts. prefix, unless nil, produces the text shown above that output. tag, +// unless nil, produces what the task attaches to the content it renders (see +// gocui.View.BeginOffscreenRender). Both are called on the task's goroutine before +// the command starts, so one that takes a while holds up only this task. +func (self *ViewBufferManager) NewCmdTask( + start func() (Cmd, io.Reader), prefix func() string, tag func() any, linesToRead LinesToRead, onDoneFn func(), +) func(TaskOpts) error { return func(opts TaskOpts) error { var onDoneOnce sync.Once var onFirstPageShownOnce sync.Once @@ -530,6 +533,17 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix } } + var tagValue any + if tag != nil { + tagValue = tag() + + // Likewise for its tag. + if stopped() { + onDone() + return nil + } + } + startTime := time.Now() cmd, r := start() timeToStart := time.Since(startTime) @@ -557,7 +571,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix 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 + // close the task's output pipe to make the command terminate onDone() } }) @@ -757,7 +771,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix // Build the new content off-screen, leaving the previous render // displayed until we swap in below; this is what keeps an async // re-render from showing a half-loaded buffer. - self.beginRender() + self.beginRender(tagValue) if prefixText != "" { writeToView([]byte(prefixText)) } diff --git a/pkg/tasks/tasks_test.go b/pkg/tasks/tasks_test.go index 76bfa6aa7..a469ff07c 100644 --- a/pkg/tasks/tasks_test.go +++ b/pkg/tasks/tasks_test.go @@ -42,7 +42,7 @@ func TestNewCmdTaskInstantStop(t *testing.T) { refreshView, onEndOfInput, resetOrigin, - beginRender, + func(any) { beginRender() }, swapInRender, newTask, // no UI thread in the test; run the view mutations inline @@ -60,7 +60,7 @@ func TestNewCmdTaskInstantStop(t *testing.T) { return ExecCmd{Cmd: cmd}, reader } - fn := manager.NewCmdTask(start, func() string { return "prefix\n" }, LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) + fn := manager.NewCmdTask(start, func() string { return "prefix\n" }, nil, LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) _ = fn(TaskOpts{Stop: stop, InitialContentLoaded: func() { task.Done() }}) @@ -108,6 +108,7 @@ func TestNewCmdTask(t *testing.T) { return task } + var renderTag any manager := NewViewBufferManager( utils.NewDummyLog(), writer, @@ -115,7 +116,10 @@ func TestNewCmdTask(t *testing.T) { refreshView, onEndOfInput, resetOrigin, - beginRender, + func(tag any) { + renderTag = tag + beginRender() + }, swapInRender, newTask, // no UI thread in the test; run the view mutations inline @@ -131,7 +135,8 @@ func TestNewCmdTask(t *testing.T) { return ExecCmd{Cmd: cmd}, reader } - fn := manager.NewCmdTask(start, func() string { return "prefix\n" }, LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) + fn := manager.NewCmdTask(start, func() string { return "prefix\n" }, func() any { return "tag" }, + LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) wg := sync.WaitGroup{} wg.Go(func() { time.Sleep(100 * time.Millisecond) @@ -164,6 +169,9 @@ func TestNewCmdTask(t *testing.T) { t.Errorf("expected task status to be 'done', got '%s'", task.FormatStatus()) } + // The render was given what the task attaches to its content. + assert.Equal(t, "tag", renderTag) + expectedContent := "prefix\ntest\n" actualContent := writer.String() if actualContent != expectedContent { @@ -179,7 +187,7 @@ func TestNewCmdTaskStoppedWhileProducingItsPrefix(t *testing.T) { writer := bytes.NewBuffer(nil) manager := NewViewBufferManager( - utils.NewDummyLog(), writer, noop, noop, noop, noop, noop, noop, + utils.NewDummyLog(), writer, noop, noop, noop, noop, func(any) { noop() }, noop, func() gocui.Task { return task }, func(f func()) error { f(); return nil }, ) @@ -196,7 +204,7 @@ func TestNewCmdTaskStoppedWhileProducingItsPrefix(t *testing.T) { } onDone, getOnDoneCallCount := getCounter() - fn := manager.NewCmdTask(start, prefix, LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) + fn := manager.NewCmdTask(start, prefix, nil, LinesToRead{Total: 20, InitialRefreshAfter: -1}, onDone) _ = fn(TaskOpts{Stop: stop, InitialContentLoaded: func() { task.Done() }}) assert.False(t, started) @@ -258,7 +266,7 @@ func TestNewCmdTaskQueuedReadAtEndOfInput(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return task }, // no UI thread in the test; run the view mutations inline @@ -277,7 +285,7 @@ func TestNewCmdTaskQueuedReadAtEndOfInput(t *testing.T) { // The initial request asks for far more lines than the reader has, so the // task reaches EOF while that request is still the one being served. - fn := manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: -1}, func() {}) + fn := manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: -1}, func() {}) thenCalled := false wg := sync.WaitGroup{} @@ -312,7 +320,7 @@ func TestResetOriginSurvivesTaskReplacement(t *testing.T) { func() {}, func() {}, resetOrigin, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -326,7 +334,7 @@ func TestResetOriginSurvivesTaskReplacement(t *testing.T) { } // The first-paint point is far beyond what any of these readers yield, so // only reaching EOF paints. - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) } runTaskToCompletion := func(key string) { done := make(chan struct{}) @@ -369,7 +377,7 @@ func TestLoadingIndicatorOnlyTakesOverForNewContent(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -381,7 +389,7 @@ func TestLoadingIndicatorOnlyTakesOverForNewContent(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, reader } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) } // Starts a task whose command produces nothing at all, so that it is still // waiting for its first line when the loading indicator falls due. Returns @@ -442,7 +450,7 @@ func TestNewCmdTaskRestore(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput resetOrigin, - func() {}, // beginRender + func(any) {}, // beginRender func() { swapped = true }, // swapInRender func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -467,7 +475,7 @@ func TestNewCmdTaskRestore(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, &BlankLineReader{totalLinesToYield: 50} } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 30}, func() { close(done) }), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 30}, func() { close(done) }), "cmd") <-done assert.Equal(t, 1, applyCount, "Apply should run exactly once") @@ -500,7 +508,7 @@ func TestNewCmdTaskRestoreThatFindsNothing(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput resetOrigin, - func() {}, // beginRender + func(any) {}, // beginRender func() { swappedAtLines = linesWritten() }, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -520,7 +528,7 @@ func TestNewCmdTaskRestoreThatFindsNothing(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, &BlankLineReader{totalLinesToYield: 50} } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 30}, func() { close(done) }), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 30}, func() { close(done) }), "cmd") <-done assert.Equal(t, 1, applyCount, "Apply should still run, to swap the render in") @@ -542,7 +550,7 @@ func TestRestoreSurvivesTaskReplacement(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -562,7 +570,7 @@ func TestRestoreSurvivesTaskReplacement(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, reader } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), "cmd") } // The task the restore was installed for stalls before it can paint. @@ -597,8 +605,8 @@ func TestKeepScrollPositionForNextTask(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput resetOrigin, - func() {}, // beginRender - func() {}, // swapInRender + func(any) {}, // beginRender + func() {}, // swapInRender func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline func(f func()) error { f(); return nil }, @@ -609,7 +617,7 @@ func TestKeepScrollPositionForNextTask(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, reader } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, onDone), key) } runTaskToCompletion := func(key string) { done := make(chan struct{}) @@ -656,8 +664,8 @@ func TestForgetRenderedContent(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput resetOrigin, - func() {}, // beginRender - func() {}, // swapInRender + func(any) {}, // beginRender + func() {}, // swapInRender func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline func(f func()) error { f(); return nil }, @@ -670,7 +678,7 @@ func TestForgetRenderedContent(t *testing.T) { } done := make(chan struct{}) _ = manager.NewTask( - manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, func() { close(done) }), key) + manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, func() { close(done) }), key) <-done } @@ -704,7 +712,7 @@ func TestOnlyARenderInPlaceReadsTheLinesAboveTheView(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput func() {}, // resetOrigin - writer.Reset, + func(any) { writer.Reset() }, func() { linesWrittenAtFirstPaint = linesWritten() }, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -726,7 +734,7 @@ func TestOnlyARenderInPlaceReadsTheLinesAboveTheView(t *testing.T) { LinesAboveView: 100, Then: func() { close(served) }, } - _ = manager.NewTask(manager.NewCmdTask(start, nil, linesToRead, nil), key) + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, linesToRead, nil), key) <-served } @@ -809,7 +817,7 @@ func TestNewCmdTaskRefresh(t *testing.T) { refreshView, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, newTask, // no UI thread in the test; run the view mutations inline @@ -825,7 +833,7 @@ func TestNewCmdTaskRefresh(t *testing.T) { return ExecCmd{Cmd: cmd}, &reader } - fn := manager.NewCmdTask(start, nil, s.linesToRead, func() {}) + fn := manager.NewCmdTask(start, nil, nil, s.linesToRead, func() {}) wg := sync.WaitGroup{} wg.Go(func() { time.Sleep(100 * time.Millisecond) @@ -859,7 +867,7 @@ func TestReadToEndWaitingWhenARerenderReplacesTheTask(t *testing.T) { func() {}, // refreshView func() {}, // onEndOfInput func() {}, // resetOrigin - writer.Reset, + func(any) { writer.Reset() }, func() { firstPaint <- struct{}{} }, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -873,7 +881,7 @@ func TestReadToEndWaitingWhenARerenderReplacesTheTask(t *testing.T) { return ExecCmd{Cmd: exec.Command("blah")}, reader } linesToRead := LinesToRead{Total: 1, InitialRefreshAfter: 1} - _ = manager.NewTask(manager.NewCmdTask(start, nil, linesToRead, nil), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, linesToRead, nil), "cmd") } var mutex sync.Mutex @@ -912,7 +920,7 @@ func TestReadToEndWaitingWhenARerenderReplacesTheTask(t *testing.T) { func TestReadRequestsLeftToAMessageAreAnsweredOnceItIsShown(t *testing.T) { noop := func() {} manager := NewViewBufferManager( - utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, noop, noop, + utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, func(any) { noop() }, noop, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline func(f func()) error { f(); return nil }, @@ -925,7 +933,7 @@ func TestReadRequestsLeftToAMessageAreAnsweredOnceItIsShown(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, &stalled } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 1, InitialRefreshAfter: 1}, nil), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 1, InitialRefreshAfter: 1}, nil), "cmd") <-stalled.blocked var messageShown atomic.Bool @@ -951,7 +959,7 @@ func TestReadToEndWaitsForATaskAskedForButNotCreatedYet(t *testing.T) { linesWritten := func() int { return strings.Count(writer.String(), "\n") } noop := func() {} manager := NewViewBufferManager( - utils.NewDummyLog(), writer, noop, noop, noop, noop, writer.Reset, noop, + utils.NewDummyLog(), writer, noop, noop, noop, noop, func(any) { writer.Reset() }, noop, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline func(f func()) error { f(); return nil }, @@ -963,7 +971,7 @@ func TestReadToEndWaitsForATaskAskedForButNotCreatedYet(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, &BlankLineReader{totalLinesToYield: lines} } - return manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 1}, onDone) + return manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 1}, onDone) } done := make(chan struct{}) @@ -983,7 +991,7 @@ func TestReadToEndWaitsForATaskAskedForButNotCreatedYet(t *testing.T) { func TestCloseAnswersWaitingReadRequests(t *testing.T) { noop := func() {} manager := NewViewBufferManager( - utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, noop, noop, + utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, func(any) { noop() }, noop, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline func(f func()) error { f(); return nil }, @@ -995,7 +1003,7 @@ func TestCloseAnswersWaitingReadRequests(t *testing.T) { // not actually starting this because it's not necessary return ExecCmd{Cmd: exec.Command("blah")}, &stalled } - _ = manager.NewTask(manager.NewCmdTask(start, nil, LinesToRead{Total: 1, InitialRefreshAfter: 1}, nil), "cmd") + _ = manager.NewTask(manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 1, InitialRefreshAfter: 1}, nil), "cmd") <-stalled.blocked answered := atomic.Int32{} @@ -1015,7 +1023,7 @@ func TestReadToEndHoldsItsTaskUntilThenReturns(t *testing.T) { task := gocui.NewFakeTask() manager := NewViewBufferManager( - utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, noop, noop, + utils.NewDummyLog(), bytes.NewBuffer(nil), noop, noop, noop, noop, func(any) { noop() }, noop, func() gocui.Task { return task }, func(f func()) error { f(); return nil }, ) @@ -1052,7 +1060,7 @@ func TestReservedTaskDoesntReplaceATaskAskedForLater(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { tasksDone.Add(1) @@ -1095,7 +1103,7 @@ func TestMessageEndsTheLoadingOfTheTaskItReplaces(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -1115,7 +1123,7 @@ func TestMessageEndsTheLoadingOfTheTaskItReplaces(t *testing.T) { reservation := manager.ReserveTask() manager.StartLoading() - _ = manager.NewReservedTask(reservation, manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, nil), "cmd") + _ = manager.NewReservedTask(reservation, manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, nil), "cmd") <-stalled.blocked assert.True(t, manager.IsLoading()) @@ -1133,7 +1141,7 @@ func TestEarlierTaskEndingLeavesALaterTaskLoading(t *testing.T) { func() {}, func() {}, func() {}, - func() {}, + func(any) {}, func() {}, func() gocui.Task { return gocui.NewFakeTask() }, // no UI thread in the test; run the view mutations inline @@ -1154,7 +1162,7 @@ func TestEarlierTaskEndingLeavesALaterTaskLoading(t *testing.T) { reservation := manager.ReserveTask() manager.StartLoading() _ = manager.NewReservedTask(reservation, - manager.NewCmdTask(start, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, func() { close(earlierDone) }), "earlier") + manager.NewCmdTask(start, nil, nil, LinesToRead{Total: 100, InitialRefreshAfter: 50}, func() { close(earlierDone) }), "earlier") <-stalled.blocked // The later task is asked for, but not created yet, as for a render whose task diff --git a/schema-master/config.json b/schema-master/config.json index f956217ca..7fa89a274 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -346,11 +346,11 @@ }, "command": { "type": "string", - "description": "The command to use for rendering diffs. This is either a stdinFilter or an external diff command, depending on the type field; not applicable if the type is 'rawGit'.\ne.g.\ndiff-so-fancy\ndelta --dark --paging=never\nydiff -p cat\ndifft --color=always", + "description": "The command to use for rendering diffs. This is either a stdinFilter or an external diff command, depending on the type field; not applicable if the type is 'rawGit'.\ne.g.\ndiff-so-fancy\ndelta --dark --paging=never\nydiff -p cat --color=always\ndifft --color=always", "examples": [ "delta --dark --paging=never", "diff-so-fancy", - "ydiff -p cat", + "ydiff -p cat --color=always", "difft --color=always" ] }, @@ -372,7 +372,7 @@ "$ref": "#/$defs/DiffRendererConfig" }, "type": "array", - "description": "Array of diff renderers. Each entry has the following format:\n\n # The type of diff renderer. One of: 'stdinFilter' (default) | 'extDiff'\n # | 'rawGit'\n type: \"stdinFilter\"\n\n # A name for the diff renderer, shown in the notification when cycling\n # renderers. If not set, the name is derived from the first word of the\n # renderer command.\n name: \"\"\n\n # Value of the --color arg in the git diff command. Only used for type\n # 'stdinFilter'. Some renderers want this to be set to 'always' and some\n # want it set to 'never'.\n colorArg: \"always\"\n\n # The command to use for rendering diffs. This is either a stdinFilter or\n # an external diff command, depending on the type field; not applicable if\n # the type is 'rawGit'.\n # e.g.\n # diff-so-fancy\n # delta --dark --paging=never\n # ydiff -p cat\n # difft --color=always\n command: \"\"\n\n # Extra arguments (array of strings) passed to the git command. Only\n # applicable if the type is 'rawGit'.\n args: []\n\nSee https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_DiffRenderers.md for more information." + "description": "Array of diff renderers. Each entry has the following format:\n\n # The type of diff renderer. One of: 'stdinFilter' (default) | 'extDiff'\n # | 'rawGit'\n type: \"stdinFilter\"\n\n # A name for the diff renderer, shown in the notification when cycling\n # renderers. If not set, the name is derived from the first word of the\n # renderer command.\n name: \"\"\n\n # Value of the --color arg in the git diff command. Only used for type\n # 'stdinFilter'. Some renderers want this to be set to 'always' and some\n # want it set to 'never'.\n colorArg: \"always\"\n\n # The command to use for rendering diffs. This is either a stdinFilter or\n # an external diff command, depending on the type field; not applicable if\n # the type is 'rawGit'.\n # e.g.\n # diff-so-fancy\n # delta --dark --paging=never\n # ydiff -p cat --color=always\n # difft --color=always\n command: \"\"\n\n # Extra arguments (array of strings) passed to the git command. Only\n # applicable if the type is 'rawGit'.\n args: []\n\nSee https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_DiffRenderers.md for more information." }, "commit": { "$ref": "#/$defs/CommitConfig",