mirror of
https://github.com/jesseduffield/lazygit.git
synced 2026-10-02 03:56:45 -04:00
Compare commits
156
Commits
@@ -1,7 +0,0 @@
|
||||
[codespell]
|
||||
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
|
||||
skip = .git*,go.sum,*.lock,.codespellrc,vendor,translations,Keybindings_*.md,./pkg/gocui
|
||||
check-hidden = true
|
||||
# camel-cased
|
||||
ignore-regex = (\b[A-Za-z][a-z]*[A-Z]\S+\b|\.edn\b|\S+…|\\nd\b)
|
||||
ignore-words-list = fomrat,inbetween
|
||||
@@ -1,25 +0,0 @@
|
||||
# Codespell configuration is within .codespellrc
|
||||
---
|
||||
name: Codespell
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
branches: [master]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
codespell:
|
||||
name: Check for spelling errors
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
- name: Annotate locations with typos
|
||||
uses: codespell-project/codespell-problem-matcher@9ba2c57125d4908eade4308f32c4ff814c184633 # v1.2.0
|
||||
- name: Codespell
|
||||
uses: codespell-project/actions-codespell@8f01853be192eb0f849a5c7d721450e7a467c579 # v2.2
|
||||
@@ -0,0 +1,142 @@
|
||||
// author_colors_repo creates a git repository for checking that the colors
|
||||
// lazygit gives to authors are readable.
|
||||
//
|
||||
// If gui.authorColors names no color for an author, lazygit derives one from a
|
||||
// hash of their name. The authors of an ordinary repository rarely land near the
|
||||
// edges of the range that this color is picked from. Every commit in the
|
||||
// repository created here is by an author at one of those edges: the lowest or
|
||||
// highest lightness, combined with the lowest or highest saturation, at twelve
|
||||
// hues around the color wheel. The commit subject says which edge it is.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// go run ./cmd/author_colors_repo <path>
|
||||
//
|
||||
// Then open the repository with lazygit in each terminal theme you want to check.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/presentation/authors"
|
||||
)
|
||||
|
||||
type extreme int
|
||||
|
||||
const (
|
||||
lowest extreme = iota
|
||||
highest
|
||||
)
|
||||
|
||||
func (self extreme) String() string {
|
||||
if self == lowest {
|
||||
return "min"
|
||||
}
|
||||
return "max"
|
||||
}
|
||||
|
||||
func (self extreme) matches(fraction float64) bool {
|
||||
if self == lowest {
|
||||
return fraction < 0.01
|
||||
}
|
||||
return fraction >= 0.99
|
||||
}
|
||||
|
||||
const (
|
||||
numHues = 12
|
||||
|
||||
// Small enough that the windows of neighbouring hues don't overlap
|
||||
hueTolerance = 0.02
|
||||
)
|
||||
|
||||
type commit struct {
|
||||
author string
|
||||
subject string
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
log.Fatalf("usage: %s <path>", os.Args[0])
|
||||
}
|
||||
path := os.Args[1]
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
log.Fatalf("%s already exists", path)
|
||||
}
|
||||
|
||||
extremes := []extreme{lowest, highest}
|
||||
commits := make([]commit, 0, len(extremes)*len(extremes)*numHues)
|
||||
for _, lightness := range extremes {
|
||||
for _, saturation := range extremes {
|
||||
for i := range numHues {
|
||||
hue := float64(i) / numHues
|
||||
author, actualHue := findAuthor(lightness, saturation, hue)
|
||||
subject := fmt.Sprintf("lightness %s, saturation %s, hue %.0f°", lightness, saturation, actualHue*360)
|
||||
commits = append(commits, commit{author: author, subject: subject})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := runGit("", nil, "init", "-q", path); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Commit in reverse, so that the commits panel lists them in the order above
|
||||
startTime := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
for i := range commits {
|
||||
c := commits[len(commits)-1-i]
|
||||
date := fmt.Sprintf("%d +0000", startTime.Add(time.Duration(i)*time.Hour).Unix())
|
||||
env := []string{
|
||||
"GIT_AUTHOR_NAME=" + c.author,
|
||||
"GIT_AUTHOR_EMAIL=author@example.com",
|
||||
"GIT_AUTHOR_DATE=" + date,
|
||||
"GIT_COMMITTER_NAME=" + c.author,
|
||||
"GIT_COMMITTER_EMAIL=author@example.com",
|
||||
"GIT_COMMITTER_DATE=" + date,
|
||||
}
|
||||
if err := runGit(path, env, "commit", "-q", "--allow-empty", "-m", c.subject); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Created %s with %d commits\n", path, len(commits))
|
||||
}
|
||||
|
||||
// findAuthor returns the first name of the form "L<lightness> S<saturation> <n>"
|
||||
// whose color lies at the given extremes of lightness and saturation, and close
|
||||
// to the given hue. It also returns the hue that the name lands on.
|
||||
//
|
||||
// Every name of this form has the same initials, so the color is the only
|
||||
// thing that differs between authors in the commits panel.
|
||||
func findAuthor(lightness extreme, saturation extreme, hue float64) (string, float64) {
|
||||
for n := 1; ; n++ {
|
||||
name := fmt.Sprintf("L%s S%s %d", lightness, saturation, n)
|
||||
h, s, l := authors.ColorPosition(name)
|
||||
if lightness.matches(l) && saturation.matches(s) && hueDistance(h, hue) <= hueTolerance {
|
||||
return name, h
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hueDistance is the distance between two hues on the color wheel, where each
|
||||
// hue is a fraction of a full turn.
|
||||
func hueDistance(a float64, b float64) float64 {
|
||||
d := math.Abs(a - b)
|
||||
return math.Min(d, 1-d)
|
||||
}
|
||||
|
||||
func runGit(dir string, env []string, args ...string) error {
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
// Keep the user's git config out of it, so that hooks, commit signing and
|
||||
// the like don't apply, and every run creates the same commits
|
||||
cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1")
|
||||
cmd.Env = append(cmd.Env, env...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
+87
-22
@@ -37,12 +37,6 @@ This is only meant as a reference for what config options exist, and what their
|
||||
```yaml
|
||||
# Config relating to the Lazygit UI
|
||||
gui:
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-author-color
|
||||
authorColors: {}
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color
|
||||
branchColorPatterns: {}
|
||||
|
||||
# Custom icons for filenames and file extensions
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-files-icon--color
|
||||
customIcons:
|
||||
@@ -169,6 +163,14 @@ gui:
|
||||
# Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
|
||||
shortTimeFormat: 3:04PM
|
||||
|
||||
# Whether the terminal has a dark or a light background. This decides whether
|
||||
# 'darkTheme' or 'lightTheme' applies, and the colors of authors are picked to
|
||||
# stand out against it.
|
||||
# One of: 'auto' (default) | 'dark' | 'light'
|
||||
# With 'auto', lazygit asks the terminal, and assumes a dark background if the
|
||||
# terminal doesn't tell.
|
||||
colorScheme: auto
|
||||
|
||||
# Config relating to colors and styles.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes
|
||||
theme:
|
||||
@@ -190,14 +192,22 @@ gui:
|
||||
optionsTextColor:
|
||||
- blue
|
||||
|
||||
# Color and attributes of the text of the selected line. The attributes are
|
||||
# added to those of the text, and a color replaces the colors of the text.
|
||||
# Set it to 'default' to leave the text as it is, e.g. if you don't want the
|
||||
# selected line in bold.
|
||||
selectedLineFgColor:
|
||||
- bold
|
||||
|
||||
# Background color of selected line.
|
||||
# Default: 'blue' if the terminal has a dark background, or a suitable RGB blue
|
||||
# computed from the background color if it is light.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line
|
||||
selectedLineBgColor:
|
||||
- blue
|
||||
selectedLineBgColor: []
|
||||
|
||||
# Background color of selected line when view doesn't have focus.
|
||||
inactiveViewSelectedLineBgColor:
|
||||
- bold
|
||||
# Default: a suitable RGB grey computed from the terminal's background color.
|
||||
inactiveViewSelectedLineBgColor: []
|
||||
|
||||
# Foreground color of copied commit
|
||||
cherryPickedCommitFgColor:
|
||||
@@ -223,6 +233,22 @@ gui:
|
||||
defaultFgColor:
|
||||
- default
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-author-color
|
||||
authorColors: {}
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color
|
||||
branchColorPatterns: {}
|
||||
|
||||
# Colors and styles that override those in 'theme' when the terminal has a dark
|
||||
# background. It has the same fields as 'theme'.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#themes-for-dark-and-light-backgrounds
|
||||
darkTheme: {}
|
||||
|
||||
# Colors and styles that override those in 'theme' when the terminal has a light
|
||||
# background. It has the same fields as 'theme'.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#themes-for-dark-and-light-backgrounds
|
||||
lightTheme: {}
|
||||
|
||||
# Config relating to the commit length indicator
|
||||
commitLength:
|
||||
# If true, show an indicator of commit message length
|
||||
@@ -443,7 +469,9 @@ git:
|
||||
# If not "none", lazygit will automatically fast-forward local branches to match
|
||||
# their upstream after fetching. Applies to branches that are not the currently
|
||||
# checked out branch, and only to those that are strictly behind their upstream
|
||||
# (as opposed to diverged).
|
||||
# (as opposed to diverged). A branch that is checked out in another worktree is
|
||||
# fast-forwarded there, unless that worktree has changes to tracked files or is
|
||||
# in the middle of a rebase or bisect.
|
||||
# Possible values: 'none' | 'onlyMainBranches' | 'allBranches'
|
||||
autoForwardBranches: onlyMainBranches
|
||||
|
||||
@@ -999,6 +1027,7 @@ The available attributes are:
|
||||
|
||||
- bold
|
||||
- default
|
||||
- dim # faint text; not supported by every terminal
|
||||
- reverse # useful for high-contrast
|
||||
- underline
|
||||
- strikethrough
|
||||
@@ -1023,28 +1052,61 @@ gui:
|
||||
- reverse
|
||||
```
|
||||
|
||||
The text of the selected line is bold by default. If you don't want that, set `selectedLineFgColor` to `default`:
|
||||
|
||||
```yaml
|
||||
gui:
|
||||
theme:
|
||||
selectedLineFgColor:
|
||||
- default
|
||||
```
|
||||
|
||||
## Themes for dark and light backgrounds
|
||||
|
||||
The colors in `gui.theme` apply whether your terminal has a dark or a light background. If you want different colors for the two, set them in `gui.darkTheme` or `gui.lightTheme`. These have the same fields as `gui.theme`, and a field that you set in them overrides the one in `gui.theme`:
|
||||
|
||||
```yaml
|
||||
gui:
|
||||
theme:
|
||||
activeBorderColor:
|
||||
- green
|
||||
- bold
|
||||
lightTheme:
|
||||
activeBorderColor:
|
||||
- blue
|
||||
- bold
|
||||
```
|
||||
|
||||
For `authorColors` and `branchColorPatterns`, each entry overrides the one with the same key in `gui.theme`, and the other entries of `gui.theme` still apply. Branch color patterns of `gui.darkTheme` or `gui.lightTheme` come before those of `gui.theme`.
|
||||
|
||||
Lazygit asks the terminal whether its background is dark or light. If your terminal doesn't tell, lazygit assumes a dark background; set `gui.colorScheme` to `light` if yours is light.
|
||||
|
||||
## Custom Author Color
|
||||
|
||||
Lazygit will assign a random color for every commit author in the commits pane by default.
|
||||
|
||||
These colors are picked to be readable against the background of your terminal, and lazygit asks the terminal whether its background is dark or light. If your terminal doesn't tell, lazygit assumes a dark background; set `gui.colorScheme` to `light` if yours is light.
|
||||
|
||||
You can customize the color in case you're not happy with the randomly assigned one:
|
||||
|
||||
```yaml
|
||||
gui:
|
||||
authorColors:
|
||||
'John Smith': 'red' # use red for John Smith
|
||||
'Alan Smithee': '#00ff00' # use green for Alan Smithee
|
||||
theme:
|
||||
authorColors:
|
||||
'John Smith': 'red' # use red for John Smith
|
||||
'Alan Smithee': '#00ff00' # use green for Alan Smithee
|
||||
```
|
||||
|
||||
You can use wildcard to set a unified color in case your are lazy to customize the color for every author or you just want a single color for all/other authors:
|
||||
|
||||
```yaml
|
||||
gui:
|
||||
authorColors:
|
||||
# use red for John Smith
|
||||
'John Smith': 'red'
|
||||
# use blue for other authors
|
||||
'*': '#0000ff'
|
||||
theme:
|
||||
authorColors:
|
||||
# use red for John Smith
|
||||
'John Smith': 'red'
|
||||
# use blue for other authors
|
||||
'*': '#0000ff'
|
||||
```
|
||||
|
||||
## Custom Branch Color
|
||||
@@ -1053,13 +1115,16 @@ You can customize the color of branches based on branch patterns (regular expres
|
||||
|
||||
```yaml
|
||||
gui:
|
||||
branchColorPatterns:
|
||||
'^docs/': '#11aaff' # use a light blue for branches beginning with 'docs/'
|
||||
'ISSUE-\d+': '#ff5733' # use a bright orange for branches containing 'ISSUE-<some-number>'
|
||||
theme:
|
||||
branchColorPatterns:
|
||||
'^docs/': '#11aaff' # use a light blue for branches beginning with 'docs/'
|
||||
'ISSUE-\d+': '#ff5733' # use a bright orange for branches containing 'ISSUE-<some-number>'
|
||||
```
|
||||
|
||||
Note that the regular expressions are not implicitly anchored to the beginning/end of the branch name. If you want to do that, add leading `^` and/or trailing `$` as needed.
|
||||
|
||||
If several patterns match a branch, the first one wins.
|
||||
|
||||
## Custom Files Icon & Color
|
||||
|
||||
You can customize the icon and color of files based on filenames or extensions:
|
||||
|
||||
@@ -23,22 +23,29 @@ Fields only for `extDiff`:
|
||||
|
||||
- **command** The command line to use for the `diff.external` git config. If left empty, it uses the global value of git's `diff.external` config; this can be useful if you also want to use it for diffs on the command line, and it also has the advantage that you can configure it per file type in `.gitattributes`; see https://git-scm.com/docs/gitattributes#_defining_an_external_diff_driver.
|
||||
|
||||
You can include the `{{diffContext}}` template variable to pass lazygit's current diff context size (the value controlled by the `{`/`}` keybindings) to the diff tool.
|
||||
|
||||
Fields only for `rawGit`:
|
||||
|
||||
- **args** The additional arguments to use in the `git diff` or `git show` call (e.g. `--color-words`), as an array of strings.
|
||||
|
||||
The `command` of a `stdinFilter` or `extDiff` renderer is a [Go template](https://pkg.go.dev/text/template) with these variables:
|
||||
|
||||
- `{{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}}`.
|
||||
- `{{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.
|
||||
|
||||
Here's an example for a multi-renderer setup:
|
||||
|
||||
```yaml
|
||||
git:
|
||||
diffRenderers:
|
||||
- command: delta --dark --paging=never
|
||||
- command: delta --{{colorScheme}} --paging=never
|
||||
- command: ydiff -p cat
|
||||
colorArg: never
|
||||
- type: extDiff
|
||||
command: difft --color=always --context={{diffContext}}
|
||||
command: difft --color=always --background={{colorScheme}} --context={{diffContext}}
|
||||
- type: rawGit
|
||||
args: [--color-words]
|
||||
name: color-words
|
||||
@@ -51,12 +58,14 @@ git:
|
||||
```yaml
|
||||
git:
|
||||
diffRenderers:
|
||||
- command: delta --dark --paging=never
|
||||
- command: delta --{{colorScheme}} --paging=never
|
||||
```
|
||||
|
||||

|
||||
|
||||
A cool feature of delta is --hyperlinks, which renders clickable links for the line numbers in the left margin, and lazygit supports these. To use them, set the `command:` field to `delta --dark --paging=never --line-numbers --hyperlinks --hyperlinks-file-link-format="lazygit-edit://{path}:{line}"`; this allows you to click on an underlined line number in the diff to jump right to that same line in your editor.
|
||||
`--{{colorScheme}}` passes `--dark` or `--light` to delta, so that it matches the background of your terminal.
|
||||
|
||||
A cool feature of delta is --hyperlinks, which renders clickable links for the line numbers in the left margin, and lazygit supports these. To use them, set the `command:` field to `delta --{{colorScheme}} --paging=never --line-numbers --hyperlinks --hyperlinks-file-link-format="lazygit-edit://{path}:{line}"`; this allows you to click on an underlined line number in the diff to jump right to that same line in your editor.
|
||||
|
||||
Note that delta's `--navigate` option doesn't work in lazygit, for technical reasons.
|
||||
|
||||
|
||||
@@ -16,3 +16,36 @@ branches properly stacked onto it.
|
||||
Lazygit visualizes the individual branch heads in the stack by marking them with a
|
||||
cyan asterisk (or a cyan branch symbol if you are using [nerd
|
||||
fonts](Config.md#display-nerd-fonts-icons)).
|
||||
|
||||
When you push the topmost branch of the stack with `P`, and the branches below
|
||||
it have commits that haven't been pushed yet, lazygit offers to push them along
|
||||
with it. After rebasing the stack this saves you from checking out and
|
||||
force-pushing every branch one by one; you are asked to confirm the force push
|
||||
once for all of them. Only branches that already have an upstream are included.
|
||||
Each of them is pushed to where `git push` would push it if it were checked out,
|
||||
so your push configuration applies to them as usual.
|
||||
|
||||
When somebody else rebases the stack and force-pushes it, all your branches
|
||||
show up as diverged, for example `↓5↑3`, even though the commits they are ahead
|
||||
by are only the old versions of the ones that are now on the remote. Lazygit
|
||||
tells this apart from a branch that carries work of your own, and shows the
|
||||
divergence dimmed for such a branch. Pressing `f` on it resets it to its
|
||||
upstream instead of refusing, so you don't have to check the branch out and pull
|
||||
it. Lazygit only does this when every commit of the branch was on its remote
|
||||
branch at some point. It finds that out from the reflog of the remote-tracking
|
||||
branch. Reflogs are enabled by default, except in a bare repository; if you work
|
||||
in one with linked worktrees, set `core.logAllRefUpdates` to true there to make
|
||||
this work.
|
||||
|
||||
`f` works on a [range selection](Range_Select.md) too, so you can select the
|
||||
whole stack and bring all of it back in sync at once. If any of the selected
|
||||
branches can't be updated, none of them is, so that you don't end up with half
|
||||
of the stack updated.
|
||||
|
||||
Alternatively, check out the topmost branch of the stack and pull it with `p`.
|
||||
If branches below it can be updated this way, or are simply behind their
|
||||
upstream, lazygit offers to update them along with it. Lazygit decides this
|
||||
from the last fetch, so a branch whose changes on the remote haven't been
|
||||
fetched yet isn't offered; with auto-fetch turned off, pull a second time after
|
||||
the first pull has fetched them. Branches that are checked out in another
|
||||
worktree are left alone. The topmost branch itself is pulled as usual.
|
||||
|
||||
@@ -10,8 +10,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` <pgup>, K, <ctrl+u> (fn+up/shift+k) `` | Scroll up main window | |
|
||||
| `` <pgdown>, J, <ctrl+d> (fn+down/shift+j) `` | Scroll down main window | |
|
||||
| `` @ `` | View command log options | View options for the command log e.g. show/hide the command log and focus the command log. |
|
||||
| `` P `` | Push | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` p `` | Pull | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` P `` | Push | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have commits to push, you are offered to push those too. |
|
||||
| `` p `` | Pull | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have changed on the remote, you are offered to update those too. |
|
||||
| `` ) `` | Increase rename similarity threshold | Increase the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` ( `` | Decrease rename similarity threshold | Decrease the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` } `` | Increase diff context size | Increase the amount of the context shown around changes in the diff view.<br><br>The default can be changed in the config file with the key 'git.diffContextSize'. |
|
||||
@@ -189,7 +189,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` d `` | Delete | View delete options for local/remote branch. |
|
||||
| `` r `` | Rebase | Rebase the checked-out branch onto the selected branch. |
|
||||
| `` M `` | Merge | View options for merging the selected item into the current branch (regular merge, squash merge) |
|
||||
| `` f `` | Fast-forward | Fast-forward selected branch from its upstream. |
|
||||
| `` f `` | Fast-forward | Fast-forward selected branch from its upstream. If the branch has diverged from its upstream because the upstream branch was rewritten, and it has no commits of its own, it is reset to its upstream instead. This needs reflogs to be enabled; a bare repository doesn't keep them by default (core.logAllRefUpdates). |
|
||||
| `` T `` | New tag | |
|
||||
| `` s `` | Sort order | |
|
||||
| `` g `` | Reset | |
|
||||
|
||||
@@ -10,8 +10,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` <pgup>, K, <ctrl+u> (fn+up/shift+k) `` | 메인 패널을 위로 스크롤 | |
|
||||
| `` <pgdown>, J, <ctrl+d> (fn+down/shift+j) `` | 메인 패널을 아래로로 스크롤 | |
|
||||
| `` @ `` | 명령어 로그 메뉴 열기 | View options for the command log e.g. show/hide the command log and focus the command log. |
|
||||
| `` P `` | 푸시 | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` p `` | 업데이트 | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` P `` | 푸시 | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have commits to push, you are offered to push those too. |
|
||||
| `` p `` | 업데이트 | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have changed on the remote, you are offered to update those too. |
|
||||
| `` ) `` | Increase rename similarity threshold | Increase the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` ( `` | Decrease rename similarity threshold | Decrease the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` } `` | Diff 보기의 변경 사항 주위에 표시되는 컨텍스트의 크기를 늘리기 | Increase the amount of the context shown around changes in the diff view.<br><br>The default can be changed in the config file with the key 'git.diffContextSize'. |
|
||||
@@ -223,7 +223,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` d `` | 삭제 | View delete options for local/remote branch. |
|
||||
| `` r `` | 체크아웃된 브랜치를 이 브랜치에 리베이스 | Rebase the checked-out branch onto the selected branch. |
|
||||
| `` M `` | 현재 브랜치에 병합 | View options for merging the selected item into the current branch (regular merge, squash merge) |
|
||||
| `` f `` | Fast-forward this branch from its upstream | Fast-forward selected branch from its upstream. |
|
||||
| `` f `` | Fast-forward this branch from its upstream | Fast-forward selected branch from its upstream. If the branch has diverged from its upstream because the upstream branch was rewritten, and it has no commits of its own, it is reset to its upstream instead. This needs reflogs to be enabled; a bare repository doesn't keep them by default (core.logAllRefUpdates). |
|
||||
| `` T `` | 태그를 생성 | |
|
||||
| `` s `` | Sort order | |
|
||||
| `` g `` | View reset options | |
|
||||
|
||||
@@ -113,7 +113,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` d `` | Verwijderen | View delete options for local/remote branch. |
|
||||
| `` r `` | Rebase branch | Rebase de uitgecheckte branch bovenop de geselecteerde branch. |
|
||||
| `` M `` | Merge in met huidige checked out branch | View options for merging the selected item into the current branch (regular merge, squash merge) |
|
||||
| `` f `` | Fast-forward deze branch vanaf zijn upstream | Fast-forward selected branch from its upstream. |
|
||||
| `` f `` | Fast-forward deze branch vanaf zijn upstream | Fast-forward selected branch from its upstream. If the branch has diverged from its upstream because the upstream branch was rewritten, and it has no commits of its own, it is reset to its upstream instead. This needs reflogs to be enabled; a bare repository doesn't keep them by default (core.logAllRefUpdates). |
|
||||
| `` T `` | Creëer tag | |
|
||||
| `` s `` | Sort order | |
|
||||
| `` g `` | Bekijk reset opties | |
|
||||
|
||||
@@ -10,8 +10,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` <pgup>, K, <ctrl+u> (fn+up/shift+k) `` | Прокрутить вверх главную панель | |
|
||||
| `` <pgdown>, J, <ctrl+d> (fn+down/shift+j) `` | Прокрутить вниз главную панель | |
|
||||
| `` @ `` | Открыть меню журнала команд | View options for the command log e.g. show/hide the command log and focus the command log. |
|
||||
| `` P `` | Отправить изменения | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` p `` | Получить и слить изменения | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. |
|
||||
| `` P `` | Отправить изменения | Push the current branch to its upstream branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have commits to push, you are offered to push those too. |
|
||||
| `` p `` | Получить и слить изменения | Pull changes from the remote for the current branch. If no upstream is configured, you will be prompted to configure an upstream branch. If other branches are stacked below the current one and have changed on the remote, you are offered to update those too. |
|
||||
| `` ) `` | Increase rename similarity threshold | Increase the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` ( `` | Decrease rename similarity threshold | Decrease the similarity threshold for a deletion and addition pair to be treated as a rename.<br><br>The default can be changed in the config file with the key 'git.renameSimilarityThreshold'. |
|
||||
| `` } `` | Увеличить размер контекста, отображаемого вокруг изменений в просмотрщике сравнении | Increase the amount of the context shown around changes in the diff view.<br><br>The default can be changed in the config file with the key 'git.diffContextSize'. |
|
||||
@@ -223,7 +223,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
| `` d `` | Delete | View delete options for local/remote branch. |
|
||||
| `` r `` | Перебазировать переключённую ветку на эту ветку | Rebase the checked-out branch onto the selected branch. |
|
||||
| `` M `` | Слияние с текущей переключённой веткой | View options for merging the selected item into the current branch (regular merge, squash merge) |
|
||||
| `` f `` | Перемотать эту ветку вперёд из её upstream-ветки | Fast-forward selected branch from its upstream. |
|
||||
| `` f `` | Перемотать эту ветку вперёд из её upstream-ветки | Fast-forward selected branch from its upstream. If the branch has diverged from its upstream because the upstream branch was rewritten, and it has no commits of its own, it is reset to its upstream instead. This needs reflogs to be enabled; a bare repository doesn't keep them by default (core.logAllRefUpdates). |
|
||||
| `` T `` | Создать тег | |
|
||||
| `` s `` | Порядок сортировки | |
|
||||
| `` g `` | Просмотреть параметры сброса | |
|
||||
|
||||
+2
-2
@@ -145,11 +145,11 @@ func NewGitCommandAux(
|
||||
gitHubCommands := git_commands.NewGitHubCommands(gitCommon)
|
||||
hostingServiceCommands := git_commands.NewHostingServiceCommand(gitCommon)
|
||||
|
||||
branchLoader := git_commands.NewBranchLoader(cmn, gitCommon, cmd, branchCommands.CurrentBranchInfo, configCommands)
|
||||
branchLoader := git_commands.NewBranchLoader(cmn, gitCommon, cmd, branchCommands.CurrentBranchInfo, branchCommands.HasLocalOnlyCommits, configCommands)
|
||||
commitFileLoader := git_commands.NewCommitFileLoader(cmn, cmd)
|
||||
commitLoader := git_commands.NewCommitLoader(cmn, cmd, statusCommands.WorkingTreeState, gitCommon)
|
||||
reflogCommitLoader := git_commands.NewReflogCommitLoader(cmn, cmd)
|
||||
remoteLoader := git_commands.NewRemoteLoader(cmn, cmd)
|
||||
remoteLoader := git_commands.NewRemoteLoader(gitCommon)
|
||||
worktreeLoader := git_commands.NewWorktreeLoader(gitCommon)
|
||||
stashLoader := git_commands.NewStashLoader(cmn, cmd)
|
||||
tagLoader := git_commands.NewTagLoader(cmn, cmd)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// Holds parsed values from a single %(ahead-behind:<base>) field.
|
||||
type aheadBehind struct {
|
||||
ahead, behind int
|
||||
valid bool
|
||||
}
|
||||
|
||||
type branchAheadBehind struct {
|
||||
refName string
|
||||
aheadBehinds []aheadBehind
|
||||
}
|
||||
|
||||
// Parses output produced by:
|
||||
//
|
||||
// git for-each-ref --format='%(refname)\x00%(ahead-behind:<base1>)\x00...' refs/heads
|
||||
//
|
||||
// Lines whose NUL-split column count doesn't match (1 + numBases) are dropped.
|
||||
// Blank lines are ignored.
|
||||
// Individual malformed ahead-behind fields produce {valid: false} entries, so
|
||||
// that the entries of a line stay aligned with the bases.
|
||||
func parseAheadBehindForEachRefOutput(
|
||||
output string,
|
||||
numBases int, // number of %(ahead-behind:...) tokens
|
||||
) []branchAheadBehind {
|
||||
if output == "" {
|
||||
return nil
|
||||
}
|
||||
lines := strings.Split(output, "\n")
|
||||
result := make([]branchAheadBehind, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
cols := strings.Split(line, "\x00")
|
||||
if len(cols) != numBases+1 {
|
||||
continue
|
||||
}
|
||||
refName := cols[0]
|
||||
aheadBehinds := lo.Map(cols[1:], func(col string, _ int) aheadBehind {
|
||||
return parseAheadBehindField(col)
|
||||
})
|
||||
entry := branchAheadBehind{
|
||||
refName: refName,
|
||||
aheadBehinds: aheadBehinds,
|
||||
}
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func parseAheadBehindField(s string) aheadBehind {
|
||||
parts := strings.Fields(s)
|
||||
if len(parts) != 2 {
|
||||
return aheadBehind{}
|
||||
}
|
||||
ahead, err1 := strconv.Atoi(parts[0])
|
||||
behind, err2 := strconv.Atoi(parts[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return aheadBehind{}
|
||||
}
|
||||
return aheadBehind{ahead: ahead, behind: behind, valid: true}
|
||||
}
|
||||
|
||||
// Picks the "closest" base by smallest ahead value (commits the branch
|
||||
// has that the base doesn't = roughly "since fork point") and returns
|
||||
// its behind value.
|
||||
// Ties are broken by index order
|
||||
func selectBehindForBranch(aheadBehinds []aheadBehind) int {
|
||||
validOnes := lo.Filter(aheadBehinds, func(ab aheadBehind, _ int) bool {
|
||||
return ab.valid
|
||||
})
|
||||
return lo.MinBy(validOnes, func(a, b aheadBehind) bool {
|
||||
return a.ahead < b.ahead
|
||||
}).behind
|
||||
}
|
||||
|
||||
// Builds a for-each-ref command that reports, for each ref matched by one of
|
||||
// refPatterns, how far it is ahead and behind each of the bases. A base is a
|
||||
// ref name or a commit hash. The output format is:
|
||||
//
|
||||
// <refname>\x00<ahead> <behind>\x00<ahead> <behind>...\n
|
||||
//
|
||||
// with one ahead-behind field per base, in the same order as bases.
|
||||
//
|
||||
// Requires git >= 2.41 (when %(ahead-behind:...) was added).
|
||||
func buildAheadBehindForEachRefArgs(bases []string, refPatterns []string) []string {
|
||||
formatParts := make([]string, 0, 1+len(bases))
|
||||
formatParts = append(formatParts, "%(refname)")
|
||||
for _, base := range bases {
|
||||
formatParts = append(formatParts, "%(ahead-behind:"+base+")")
|
||||
}
|
||||
format := strings.Join(formatParts, "%00")
|
||||
|
||||
return NewGitCmd("for-each-ref").
|
||||
Arg("--format=" + format).
|
||||
Arg(refPatterns...).
|
||||
ToArgv()
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseAheadBehindForEachRefOutput(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
input string
|
||||
numBases int
|
||||
expected []branchAheadBehind
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single branch single base",
|
||||
input: "refs/heads/feat\x002 5\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{{ahead: 2, behind: 5, valid: true}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "multiple branches multiple bases",
|
||||
input: "refs/heads/feat\x002 5\x0010 1\n" +
|
||||
"refs/heads/main\x000 0\x000 0\n",
|
||||
numBases: 2,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 2, behind: 5, valid: true},
|
||||
{ahead: 10, behind: 1, valid: true},
|
||||
},
|
||||
},
|
||||
{
|
||||
refName: "refs/heads/main",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 0, behind: 0, valid: true},
|
||||
{ahead: 0, behind: 0, valid: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "empty ahead-behind field for unreachable base",
|
||||
input: "refs/heads/feat\x00\x002 5\n",
|
||||
numBases: 2,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{},
|
||||
{ahead: 2, behind: 5, valid: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "ref name containing slashes and dashes",
|
||||
input: "refs/heads/feat/foo-bar\x001 2\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat/foo-bar",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2, valid: true}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "trailing newline and blank lines are ignored",
|
||||
input: "refs/heads/feat\x001 2\n\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2, valid: true}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "line with wrong column count is skipped",
|
||||
input: "refs/heads/good\x001 2\n" +
|
||||
"refs/heads/bad\n" +
|
||||
"refs/heads/also_good\x003 4\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/good",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2, valid: true}},
|
||||
},
|
||||
{
|
||||
refName: "refs/heads/also_good",
|
||||
aheadBehinds: []aheadBehind{{ahead: 3, behind: 4, valid: true}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "malformed ahead-behind field becomes invalid but line is kept",
|
||||
input: "refs/heads/feat\x00not_a_number\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "empty input",
|
||||
input: "",
|
||||
numBases: 1,
|
||||
expected: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := parseAheadBehindForEachRefOutput(s.input, s.numBases)
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectBehindForBranch(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
aheadBehinds []aheadBehind
|
||||
expected int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single base, valid value",
|
||||
aheadBehinds: []aheadBehind{{ahead: 3, behind: 7, valid: true}},
|
||||
expected: 7,
|
||||
},
|
||||
{
|
||||
testName: "multi-base, clear winner by ahead",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 50, behind: 10, valid: true}, // master
|
||||
{ahead: 5, behind: 2, valid: true}, // develop ← smallest ahead
|
||||
},
|
||||
expected: 2,
|
||||
},
|
||||
{
|
||||
testName: "develop forked from master case (ancestor-of-each-other)",
|
||||
// feat-x has 5 commits since fork from develop.
|
||||
// develop is 50 commits ahead of master.
|
||||
// ahead vs master = 5 + 50 = 55; behind vs master = 0
|
||||
// ahead vs develop = 5; behind vs develop = 5
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 55, behind: 0, valid: true}, // master
|
||||
{ahead: 5, behind: 5, valid: true}, // develop ← smallest ahead
|
||||
},
|
||||
expected: 5,
|
||||
},
|
||||
{
|
||||
testName: "tie on ahead - first base wins (config order)",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 5, behind: 10, valid: true}, // first
|
||||
{ahead: 5, behind: 99, valid: true}, // second, same ahead
|
||||
},
|
||||
expected: 10,
|
||||
},
|
||||
{
|
||||
testName: "first base invalid, second valid",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{},
|
||||
{ahead: 3, behind: 8, valid: true},
|
||||
},
|
||||
expected: 8,
|
||||
},
|
||||
{
|
||||
testName: "all invalid - returns 0",
|
||||
aheadBehinds: []aheadBehind{{}, {}},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
testName: "empty - returns 0",
|
||||
aheadBehinds: nil,
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := selectBehindForBranch(s.aheadBehinds)
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAheadBehindForEachRefArgs(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
bases []string
|
||||
refPatterns []string
|
||||
expected []string
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single base",
|
||||
bases: []string{"refs/heads/master"},
|
||||
refPatterns: []string{"refs/heads"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/master)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "two bases",
|
||||
bases: []string{"refs/heads/master", "refs/remotes/origin/develop"},
|
||||
refPatterns: []string{"refs/heads"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/master)%00%(ahead-behind:refs/remotes/origin/develop)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "four bases",
|
||||
bases: []string{"refs/heads/a", "refs/heads/b", "refs/heads/c", "refs/heads/d"},
|
||||
refPatterns: []string{"refs/heads"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/a)%00%(ahead-behind:refs/heads/b)%00%(ahead-behind:refs/heads/c)%00%(ahead-behind:refs/heads/d)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "commit hashes as bases, individual refs as patterns",
|
||||
bases: []string{"1234567", "89abcde"},
|
||||
refPatterns: []string{"refs/heads/a", "refs/remotes/origin/b"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:1234567)%00%(ahead-behind:89abcde)",
|
||||
"refs/heads/a",
|
||||
"refs/remotes/origin/b",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := buildAheadBehindForEachRefArgs(s.bases, s.refPatterns)
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -285,11 +285,26 @@ func (self *BranchCommands) Merge(branchName string, variant MergeVariant) error
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
// Returns whether refName can be fast-forward merged into the current branch
|
||||
func (self *BranchCommands) CanDoFastForwardMerge(refName string) bool {
|
||||
// Fast-forwards the branch that is checked out in the given worktree to the
|
||||
// given ref. Fails if that can't be done without a merge commit. Pass empty
|
||||
// strings for the worktree to use the current one.
|
||||
func (self *BranchCommands) FastForwardMerge(refName string, worktreeGitDir string, worktreePath string) error {
|
||||
cmdArgs := NewGitCmd("merge").
|
||||
Arg("--ff-only").
|
||||
Arg(refName).
|
||||
GitDirIf(worktreeGitDir != "", worktreeGitDir).
|
||||
WorktreePathIf(worktreePath != "", worktreePath).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
// Returns whether the first ref is an ancestor of the second one, which also
|
||||
// means that the second one can be fast-forward merged into the first one
|
||||
func (self *BranchCommands) IsAncestor(ancestorRefName string, refName string) bool {
|
||||
cmdArgs := NewGitCmd("merge-base").
|
||||
Arg("--is-ancestor").
|
||||
Arg("HEAD", refName).
|
||||
Arg(ancestorRefName, refName).
|
||||
ToArgv()
|
||||
err := self.cmd.New(cmdArgs).DontLog().Run()
|
||||
return err == nil
|
||||
@@ -353,9 +368,85 @@ func (self *BranchCommands) IsBranchMerged(branch *models.Branch, mainBranches *
|
||||
return stdout == "", nil
|
||||
}
|
||||
|
||||
func (self *BranchCommands) UpdateBranchRefs(updateCommands string) error {
|
||||
// Returns whether the given branch has commits of its own, meaning commits
|
||||
// that its remote branch never contained. Those are the commits that would be
|
||||
// lost if we reset the branch to its upstream.
|
||||
//
|
||||
// A branch that has diverged from its upstream doesn't necessarily have any
|
||||
// commits of its own. If somebody else rewrote the remote branch and
|
||||
// force-pushed it, our branch is still at the commits it had before, and all
|
||||
// of those were on the remote branch at some point. The reflog of the
|
||||
// remote-tracking branch records the values it had before it was rewritten, so
|
||||
// a commit that was ever on the remote branch is contained in one of them.
|
||||
func (self *BranchCommands) HasLocalOnlyCommits(branch *models.Branch) (bool, error) {
|
||||
upstreamValues := append(
|
||||
[]string{branch.FullUpstreamRefName()},
|
||||
self.previousUpstreamValues(branch.FullUpstreamRefName())...,
|
||||
)
|
||||
|
||||
cmdArgs := NewGitCmd("rev-list").
|
||||
Arg("--max-count=1").
|
||||
// A value that the remote-tracking branch had long ago might not be
|
||||
// available any more, e.g. in a partial clone. Skip it rather than
|
||||
// failing; it only means we exclude fewer commits.
|
||||
Arg("--ignore-missing").
|
||||
Arg(branch.FullRefName()).
|
||||
Arg(lo.Map(upstreamValues, func(value string, _ int) string {
|
||||
return "^" + value
|
||||
})...).
|
||||
Arg("--").
|
||||
ToArgv()
|
||||
|
||||
stdout, _, err := self.cmd.New(cmdArgs).DontLog().RunWithOutputs()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return stdout != "", nil
|
||||
}
|
||||
|
||||
// Returns the values that the given remote-tracking branch had before its
|
||||
// current one, as far back as its reflog goes. Returns nothing if the reflog
|
||||
// is unavailable, for example because core.logAllRefUpdates is false; a branch
|
||||
// that is strictly behind its upstream is recognized without it.
|
||||
func (self *BranchCommands) previousUpstreamValues(upstreamRef string) []string {
|
||||
cmdArgs := NewGitCmd("reflog").
|
||||
Arg("show").
|
||||
Arg("--format=%H").
|
||||
Arg(upstreamRef).
|
||||
ToArgv()
|
||||
|
||||
stdout, _, err := self.cmd.New(cmdArgs).DontLog().RunWithOutputs()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Each entry holds the value that the ref was updated to.
|
||||
values := utils.SplitLines(stdout)
|
||||
|
||||
// The value it had before the oldest entry is that entry's old value, and
|
||||
// the only way to name it is <ref>@{<number of entries>}. It doesn't exist
|
||||
// if the oldest entry is the one that created the ref, and asking for it
|
||||
// then is an error rather than an empty result.
|
||||
cmdArgs = NewGitCmd("rev-parse").
|
||||
Arg("-q", "--verify").
|
||||
Arg(fmt.Sprintf("%s@{%d}", upstreamRef, len(values))).
|
||||
ToArgv()
|
||||
|
||||
if stdout, _, err := self.cmd.New(cmdArgs).DontLog().RunWithOutputs(); err == nil {
|
||||
values = append(values, strings.TrimSpace(stdout))
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
// Moves branches by writing refs directly. The reflog message is what
|
||||
// `git reflog <branch>` shows for the update; it is the only hint about who
|
||||
// moved the branch, as no git command shows up in the reflog for this.
|
||||
func (self *BranchCommands) UpdateBranchRefs(updateCommands string, reflogMessage string) error {
|
||||
cmdArgs := NewGitCmd("update-ref").
|
||||
Arg("--stdin").
|
||||
Arg("-m", reflogMessage).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).SetStdin(updateCommands).Run()
|
||||
|
||||
@@ -44,6 +44,7 @@ type BranchLoader struct {
|
||||
*GitCommon
|
||||
cmd oscommands.ICmdObjBuilder
|
||||
getCurrentBranchInfo func() (BranchInfo, error)
|
||||
hasLocalOnlyCommits func(*models.Branch) (bool, error)
|
||||
config BranchLoaderConfigCommands
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ func NewBranchLoader(
|
||||
gitCommon *GitCommon,
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
getCurrentBranchInfo func() (BranchInfo, error),
|
||||
hasLocalOnlyCommits func(*models.Branch) (bool, error),
|
||||
config BranchLoaderConfigCommands,
|
||||
) *BranchLoader {
|
||||
return &BranchLoader{
|
||||
@@ -59,6 +61,7 @@ func NewBranchLoader(
|
||||
GitCommon: gitCommon,
|
||||
cmd: cmd,
|
||||
getCurrentBranchInfo: getCurrentBranchInfo,
|
||||
hasLocalOnlyCommits: hasLocalOnlyCommits,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
@@ -67,13 +70,21 @@ func NewBranchLoader(
|
||||
func (self *BranchLoader) Load(reflogCommits []*models.Commit,
|
||||
mainBranches *MainBranches,
|
||||
oldBranches []*models.Branch,
|
||||
loadBehindCounts bool,
|
||||
loadExtraInfo bool,
|
||||
onWorker func(func() error),
|
||||
renderFunc func(),
|
||||
) ([]*models.Branch, error) {
|
||||
branches := self.obtainBranches()
|
||||
branches, tips := self.obtainBranches()
|
||||
|
||||
if self.UserConfig().Git.LocalBranchSortOrder == "recency" {
|
||||
switch self.UserConfig().Git.LocalBranchSortOrder {
|
||||
case "date":
|
||||
if err := sortRefsWithEqualDatesByAncestry(
|
||||
self.cmd, self.version, branches, (*models.Branch).FullRefName, tips,
|
||||
); err != nil {
|
||||
self.Log.Errorf("Failed to sort branches by ancestry: %v", err)
|
||||
}
|
||||
|
||||
case "recency":
|
||||
reflogBranches := self.obtainReflogBranches(reflogCommits)
|
||||
// loop through reflog branches. If there is a match, merge them, then remove it from the branches and keep it in the reflog branches
|
||||
branchesWithRecency := make([]*models.Branch, 0)
|
||||
@@ -127,24 +138,63 @@ func (self *BranchLoader) Load(reflogCommits []*models.Commit,
|
||||
branch.UpstreamBranch = match.Merge
|
||||
}
|
||||
|
||||
// If the branch already existed, take over its BehindBaseBranch value
|
||||
// to reduce flicker
|
||||
// If the branch already existed, take over the values that are
|
||||
// determined in the background, to reduce flicker
|
||||
if oldBranch, found := lo.Find(oldBranches, func(b *models.Branch) bool {
|
||||
return b.Name == branch.Name
|
||||
}); found {
|
||||
branch.BehindBaseBranch.Store(oldBranch.BehindBaseBranch.Load())
|
||||
branch.UpstreamRewritten.Store(oldBranch.UpstreamRewritten.Load())
|
||||
}
|
||||
}
|
||||
|
||||
if loadBehindCounts && self.UserConfig().Gui.ShowDivergenceFromBaseBranch != "none" {
|
||||
if loadExtraInfo {
|
||||
if self.UserConfig().Gui.ShowDivergenceFromBaseBranch != "none" {
|
||||
onWorker(func() error {
|
||||
return self.GetBehindBaseBranchValuesForAllBranches(branches, mainBranches, renderFunc)
|
||||
})
|
||||
}
|
||||
|
||||
onWorker(func() error {
|
||||
return self.GetBehindBaseBranchValuesForAllBranches(branches, mainBranches, renderFunc)
|
||||
return self.checkForRewrittenUpstreams(branches, renderFunc)
|
||||
})
|
||||
}
|
||||
|
||||
return branches, nil
|
||||
}
|
||||
|
||||
// For each branch that has diverged from its upstream, determines whether the
|
||||
// divergence comes from the upstream branch having been rewritten, and stores
|
||||
// the answer in the branch. A branch that we can't determine it for keeps the
|
||||
// answer "no", so that we don't offer anything we aren't sure about.
|
||||
func (self *BranchLoader) checkForRewrittenUpstreams(branches []*models.Branch, renderFunc func()) error {
|
||||
t := time.Now()
|
||||
errg := errgroup.Group{}
|
||||
|
||||
for _, branch := range branches {
|
||||
if !branch.IsAheadForPull() || !branch.IsBehindForPull() {
|
||||
branch.UpstreamRewritten.Store(false)
|
||||
continue
|
||||
}
|
||||
|
||||
errg.Go(func() error {
|
||||
hasLocalOnlyCommits, err := self.hasLocalOnlyCommits(branch)
|
||||
if err != nil {
|
||||
// Not worth bothering the user about; it only means that we
|
||||
// don't show this branch differently.
|
||||
self.Log.Errorf("Failed to check whether branch %s has commits of its own: %v", branch.Name, err)
|
||||
}
|
||||
branch.UpstreamRewritten.Store(err == nil && !hasLocalOnlyCommits)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
err := errg.Wait()
|
||||
self.Log.Debugf("time to check for rewritten upstreams for all branches: %s", time.Since(t))
|
||||
renderFunc()
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *BranchLoader) GetBehindBaseBranchValuesForAllBranches(
|
||||
branches []*models.Branch,
|
||||
mainBranches *MainBranches,
|
||||
@@ -206,94 +256,6 @@ func (self *BranchLoader) getBehindBaseBranchValuesLegacy(
|
||||
return err
|
||||
}
|
||||
|
||||
// Holds parsed values from a single %(ahead-behind:<base>) field.
|
||||
type aheadBehind struct {
|
||||
ahead, behind int
|
||||
}
|
||||
|
||||
type branchAheadBehind struct {
|
||||
refName string
|
||||
aheadBehinds []aheadBehind
|
||||
}
|
||||
|
||||
// Parses output produced by:
|
||||
//
|
||||
// git for-each-ref --format='%(refname)\x00%(ahead-behind:<base1>)\x00...' refs/heads
|
||||
//
|
||||
// Lines whose NUL-split column count doesn't match (1 + numBases) are dropped.
|
||||
// Blank lines are ignored.
|
||||
// Individual malformed ahead-behind fields produce {valid: false} entries
|
||||
func parseAheadBehindForEachRefOutput(
|
||||
output string,
|
||||
numBases int, // number of %(ahead-behind:...) tokens
|
||||
) []branchAheadBehind {
|
||||
if output == "" {
|
||||
return nil
|
||||
}
|
||||
lines := strings.Split(output, "\n")
|
||||
result := make([]branchAheadBehind, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
cols := strings.Split(line, "\x00")
|
||||
if len(cols) != numBases+1 {
|
||||
continue
|
||||
}
|
||||
refName := cols[0]
|
||||
aheadBehinds := lo.FilterMap(cols[1:], func(col string, _ int) (aheadBehind, bool) {
|
||||
return parseAheadBehindField(col)
|
||||
})
|
||||
entry := branchAheadBehind{
|
||||
refName: refName,
|
||||
aheadBehinds: aheadBehinds,
|
||||
}
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func parseAheadBehindField(s string) (aheadBehind, bool) {
|
||||
parts := strings.Fields(s)
|
||||
if len(parts) != 2 {
|
||||
return aheadBehind{}, false
|
||||
}
|
||||
ahead, err1 := strconv.Atoi(parts[0])
|
||||
behind, err2 := strconv.Atoi(parts[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return aheadBehind{}, false
|
||||
}
|
||||
return aheadBehind{ahead: ahead, behind: behind}, true
|
||||
}
|
||||
|
||||
// Picks the "closest" base by smallest ahead value (commits the branch
|
||||
// has that the base doesn't = roughly "since fork point") and returns
|
||||
// its behind value.
|
||||
// Ties are broken by index order
|
||||
func selectBehindForBranch(aheadBehinds []aheadBehind) int {
|
||||
return lo.MinBy(aheadBehinds, func(a, b aheadBehind) bool {
|
||||
return a.ahead < b.ahead
|
||||
}).behind
|
||||
}
|
||||
|
||||
// The output format is:
|
||||
//
|
||||
// <refname>\x00<ahead> <behind>\x00<ahead> <behind>...\n
|
||||
//
|
||||
// with one ahead-behind field per base, in the same order as mainBranchRefs.
|
||||
//
|
||||
// Requires git >= 2.41 (when %(ahead-behind:...) was added).
|
||||
func buildAheadBehindForEachRefArgs(mainBranchRefs []string) []string {
|
||||
formatParts := make([]string, 0, 1+len(mainBranchRefs))
|
||||
formatParts = append(formatParts, "%(refname)")
|
||||
for _, ref := range mainBranchRefs {
|
||||
formatParts = append(formatParts, "%(ahead-behind:"+ref+")")
|
||||
}
|
||||
format := strings.Join(formatParts, "%00")
|
||||
|
||||
return NewGitCmd("for-each-ref").
|
||||
Arg("--format=" + format).
|
||||
Arg("refs/heads").
|
||||
ToArgv()
|
||||
}
|
||||
|
||||
func (self *BranchLoader) getBehindBaseBranchValuesFast(
|
||||
branches []*models.Branch,
|
||||
mainBranchRefs []string,
|
||||
@@ -302,7 +264,7 @@ func (self *BranchLoader) getBehindBaseBranchValuesFast(
|
||||
t := time.Now()
|
||||
|
||||
output, err := self.cmd.New(
|
||||
buildAheadBehindForEachRefArgs(mainBranchRefs),
|
||||
buildAheadBehindForEachRefArgs(mainBranchRefs, []string{"refs/heads"}),
|
||||
).DontLog().RunWithOutput()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -362,7 +324,9 @@ func (self *BranchLoader) GetBaseBranch(branch *models.Branch, mainBranches *Mai
|
||||
return split[0], nil
|
||||
}
|
||||
|
||||
func (self *BranchLoader) obtainBranches() []*models.Branch {
|
||||
// Returns the branches, along with the tip of each of them, keyed by full ref
|
||||
// name
|
||||
func (self *BranchLoader) obtainBranches() ([]*models.Branch, map[string]refTip) {
|
||||
output, err := self.getRawBranches()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -371,7 +335,8 @@ func (self *BranchLoader) obtainBranches() []*models.Branch {
|
||||
trimmedOutput := strings.TrimSpace(output)
|
||||
outputLines := strings.Split(trimmedOutput, "\n")
|
||||
|
||||
return lo.FilterMap(outputLines, func(line string, _ int) (*models.Branch, bool) {
|
||||
tips := make(map[string]refTip, len(outputLines))
|
||||
branches := lo.FilterMap(outputLines, func(line string, _ int) (*models.Branch, bool) {
|
||||
if line == "" {
|
||||
return nil, false
|
||||
}
|
||||
@@ -385,8 +350,12 @@ func (self *BranchLoader) obtainBranches() []*models.Branch {
|
||||
}
|
||||
|
||||
storeCommitDateAsRecency := self.UserConfig().Git.LocalBranchSortOrder != "recency"
|
||||
return obtainBranch(split, storeCommitDateAsRecency), true
|
||||
branch, tip := obtainBranch(split, storeCommitDateAsRecency)
|
||||
tips[branch.FullRefName()] = tip
|
||||
return branch, true
|
||||
})
|
||||
|
||||
return branches, tips
|
||||
}
|
||||
|
||||
func (self *BranchLoader) getRawBranches() (string, error) {
|
||||
@@ -422,25 +391,28 @@ var branchFields = []string{
|
||||
"upstream:short",
|
||||
"upstream:track",
|
||||
"push:track",
|
||||
"push",
|
||||
"subject",
|
||||
"objectname",
|
||||
"committerdate:unix",
|
||||
}
|
||||
|
||||
// Obtain branch information from parsed line output of getRawBranches()
|
||||
func obtainBranch(split []string, storeCommitDateAsRecency bool) *models.Branch {
|
||||
func obtainBranch(split []string, storeCommitDateAsRecency bool) (*models.Branch, refTip) {
|
||||
headMarker := split[0]
|
||||
fullName := split[1]
|
||||
upstreamName := split[2]
|
||||
track := split[3]
|
||||
pushTrack := split[4]
|
||||
subject := split[5]
|
||||
commitHash := split[6]
|
||||
commitDate := split[7]
|
||||
pushRef := split[5]
|
||||
subject := split[6]
|
||||
commitHash := split[7]
|
||||
commitDate := split[8]
|
||||
|
||||
name := strings.TrimPrefix(fullName, "heads/")
|
||||
aheadForPull, behindForPull, gone := parseUpstreamInfo(upstreamName, track)
|
||||
aheadForPush, behindForPush, _ := parseUpstreamInfo(upstreamName, pushTrack)
|
||||
pushRemote, pushBranch := parsePushDestination(pushRef)
|
||||
|
||||
recency := ""
|
||||
if storeCommitDateAsRecency {
|
||||
@@ -449,18 +421,22 @@ func obtainBranch(split []string, storeCommitDateAsRecency bool) *models.Branch
|
||||
}
|
||||
}
|
||||
|
||||
return &models.Branch{
|
||||
branch := &models.Branch{
|
||||
Name: name,
|
||||
Recency: recency,
|
||||
AheadForPull: aheadForPull,
|
||||
BehindForPull: behindForPull,
|
||||
AheadForPush: aheadForPush,
|
||||
BehindForPush: behindForPush,
|
||||
PushRemote: pushRemote,
|
||||
PushBranch: pushBranch,
|
||||
UpstreamGone: gone,
|
||||
Head: headMarker == "*",
|
||||
Subject: subject,
|
||||
CommitHash: commitHash,
|
||||
}
|
||||
|
||||
return branch, refTip{hash: commitHash, committerDate: commitDate}
|
||||
}
|
||||
|
||||
func parseUpstreamInfo(upstreamName string, track string) (string, string, bool) {
|
||||
@@ -481,6 +457,25 @@ func parseUpstreamInfo(upstreamName string, track string) (string, string, bool)
|
||||
return ahead, behind, false
|
||||
}
|
||||
|
||||
// Splits the remote-tracking ref that the %(push) field names, e.g.
|
||||
// refs/remotes/origin/main, into the remote and the remote branch. Returns
|
||||
// empty strings if the field is empty because git has no push destination for
|
||||
// the branch, or if the ref isn't under refs/remotes/.
|
||||
func parsePushDestination(pushRef string) (string, string) {
|
||||
remoteAndBranch, ok := strings.CutPrefix(pushRef, "refs/remotes/")
|
||||
if !ok {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// Remote names can't contain slashes, so the first one ends the remote name
|
||||
remote, branch, ok := strings.Cut(remoteAndBranch, "/")
|
||||
if !ok {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
return remote, branch
|
||||
}
|
||||
|
||||
func parseDifference(track string, regexStr string) string {
|
||||
re := regexp.MustCompile(regexStr)
|
||||
match := re.FindStringSubmatch(track)
|
||||
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/sasha-s/go-deadlock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -26,7 +28,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "TrimHeads",
|
||||
input: []string{"", "heads/a_branch", "", "", "", "subject", "123", timeStamp},
|
||||
input: []string{"", "heads/a_branch", "", "", "", "", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -41,7 +43,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testName: "NoUpstream",
|
||||
input: []string{"", "a_branch", "", "", "", "subject", "123", timeStamp},
|
||||
input: []string{"", "a_branch", "", "", "", "", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -56,7 +58,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testName: "IsHead",
|
||||
input: []string{"*", "a_branch", "", "", "", "subject", "123", timeStamp},
|
||||
input: []string{"*", "a_branch", "", "", "", "", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -71,7 +73,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testName: "IsBehindAndAhead",
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "[behind 2, ahead 3]", "[behind 2, ahead 3]", "subject", "123", timeStamp},
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "[behind 2, ahead 3]", "[behind 2, ahead 3]", "refs/remotes/a_remote/a_branch", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -79,6 +81,40 @@ func TestObtainBranch(t *testing.T) {
|
||||
BehindForPull: "2",
|
||||
AheadForPush: "3",
|
||||
BehindForPush: "2",
|
||||
PushRemote: "a_remote",
|
||||
PushBranch: "a_branch",
|
||||
Head: false,
|
||||
Subject: "subject",
|
||||
CommitHash: "123",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "PushDestinationDiffersFromUpstream",
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "[ahead 3]", "[ahead 5]", "refs/remotes/my_fork/feature/a_branch", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
AheadForPull: "3",
|
||||
BehindForPull: "0",
|
||||
AheadForPush: "5",
|
||||
BehindForPush: "0",
|
||||
PushRemote: "my_fork",
|
||||
PushBranch: "feature/a_branch",
|
||||
Head: false,
|
||||
Subject: "subject",
|
||||
CommitHash: "123",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "PushDestinationNotARemoteTrackingRef",
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "", "", "refs/published/a_branch", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
AheadForPull: "0",
|
||||
BehindForPull: "0",
|
||||
AheadForPush: "0",
|
||||
BehindForPush: "0",
|
||||
Head: false,
|
||||
Subject: "subject",
|
||||
CommitHash: "123",
|
||||
@@ -86,7 +122,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testName: "RemoteBranchIsGone",
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "[gone]", "[gone]", "subject", "123", timeStamp},
|
||||
input: []string{"", "a_branch", "a_remote/a_branch", "[gone]", "[gone]", "refs/remotes/a_remote/a_branch", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: false,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -95,6 +131,8 @@ func TestObtainBranch(t *testing.T) {
|
||||
BehindForPull: "?",
|
||||
AheadForPush: "?",
|
||||
BehindForPush: "?",
|
||||
PushRemote: "a_remote",
|
||||
PushBranch: "a_branch",
|
||||
Head: false,
|
||||
Subject: "subject",
|
||||
CommitHash: "123",
|
||||
@@ -102,7 +140,7 @@ func TestObtainBranch(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testName: "WithCommitDateAsRecency",
|
||||
input: []string{"", "a_branch", "", "", "", "subject", "123", timeStamp},
|
||||
input: []string{"", "a_branch", "", "", "", "", "subject", "123", timeStamp},
|
||||
storeCommitDateAsRecency: true,
|
||||
expectedBranch: &models.Branch{
|
||||
Name: "a_branch",
|
||||
@@ -120,245 +158,9 @@ func TestObtainBranch(t *testing.T) {
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
branch := obtainBranch(s.input, s.storeCommitDateAsRecency)
|
||||
branch, tip := obtainBranch(s.input, s.storeCommitDateAsRecency)
|
||||
assert.EqualValues(t, s.expectedBranch, branch)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAheadBehindForEachRefOutput(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
input string
|
||||
numBases int
|
||||
expected []branchAheadBehind
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single branch single base",
|
||||
input: "refs/heads/feat\x002 5\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{{ahead: 2, behind: 5}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "multiple branches multiple bases",
|
||||
input: "refs/heads/feat\x002 5\x0010 1\n" +
|
||||
"refs/heads/main\x000 0\x000 0\n",
|
||||
numBases: 2,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 2, behind: 5},
|
||||
{ahead: 10, behind: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
refName: "refs/heads/main",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 0, behind: 0},
|
||||
{ahead: 0, behind: 0},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "empty ahead-behind field for unreachable base",
|
||||
input: "refs/heads/feat\x00\x002 5\n",
|
||||
numBases: 2,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 2, behind: 5},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "ref name containing slashes and dashes",
|
||||
input: "refs/heads/feat/foo-bar\x001 2\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat/foo-bar",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "trailing newline and blank lines are ignored",
|
||||
input: "refs/heads/feat\x001 2\n\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "line with wrong column count is skipped",
|
||||
input: "refs/heads/good\x001 2\n" +
|
||||
"refs/heads/bad\n" +
|
||||
"refs/heads/also_good\x003 4\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/good",
|
||||
aheadBehinds: []aheadBehind{{ahead: 1, behind: 2}},
|
||||
},
|
||||
{
|
||||
refName: "refs/heads/also_good",
|
||||
aheadBehinds: []aheadBehind{{ahead: 3, behind: 4}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "malformed ahead-behind field becomes invalid but line is kept",
|
||||
input: "refs/heads/feat\x00not_a_number\n",
|
||||
numBases: 1,
|
||||
expected: []branchAheadBehind{
|
||||
{
|
||||
refName: "refs/heads/feat",
|
||||
aheadBehinds: []aheadBehind{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "empty input",
|
||||
input: "",
|
||||
numBases: 1,
|
||||
expected: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := parseAheadBehindForEachRefOutput(s.input, s.numBases)
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectBehindForBranch(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
aheadBehinds []aheadBehind
|
||||
expected int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single base, valid value",
|
||||
aheadBehinds: []aheadBehind{{ahead: 3, behind: 7}},
|
||||
expected: 7,
|
||||
},
|
||||
{
|
||||
testName: "multi-base, clear winner by ahead",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 50, behind: 10}, // master
|
||||
{ahead: 5, behind: 2}, // develop ← smallest ahead
|
||||
},
|
||||
expected: 2,
|
||||
},
|
||||
{
|
||||
testName: "develop forked from master case (ancestor-of-each-other)",
|
||||
// feat-x has 5 commits since fork from develop.
|
||||
// develop is 50 commits ahead of master.
|
||||
// ahead vs master = 5 + 50 = 55; behind vs master = 0
|
||||
// ahead vs develop = 5; behind vs develop = 5
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 55, behind: 0}, // master
|
||||
{ahead: 5, behind: 5}, // develop ← smallest ahead
|
||||
},
|
||||
expected: 5,
|
||||
},
|
||||
{
|
||||
testName: "tie on ahead - first base wins (config order)",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 5, behind: 10}, // first
|
||||
{ahead: 5, behind: 99}, // second, same ahead
|
||||
},
|
||||
expected: 10,
|
||||
},
|
||||
{
|
||||
testName: "first base invalid, second valid",
|
||||
aheadBehinds: []aheadBehind{
|
||||
{ahead: 3, behind: 8},
|
||||
},
|
||||
expected: 8,
|
||||
},
|
||||
{
|
||||
testName: "all invalid - returns 0",
|
||||
aheadBehinds: []aheadBehind{},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
testName: "empty - returns 0",
|
||||
aheadBehinds: nil,
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := selectBehindForBranch(s.aheadBehinds)
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAheadBehindForEachRefArgs(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
mainBranchRefs []string
|
||||
expected []string
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "single base",
|
||||
mainBranchRefs: []string{"refs/heads/master"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/master)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "two bases",
|
||||
mainBranchRefs: []string{"refs/heads/master", "refs/remotes/origin/develop"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/master)%00%(ahead-behind:refs/remotes/origin/develop)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "four bases",
|
||||
mainBranchRefs: []string{"refs/heads/a", "refs/heads/b", "refs/heads/c", "refs/heads/d"},
|
||||
expected: []string{
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:refs/heads/a)%00%(ahead-behind:refs/heads/b)%00%(ahead-behind:refs/heads/c)%00%(ahead-behind:refs/heads/d)",
|
||||
"refs/heads",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := buildAheadBehindForEachRefArgs(s.mainBranchRefs)
|
||||
assert.Equal(t, s.expected, result)
|
||||
assert.Equal(t, refTip{hash: "123", committerDate: timeStamp}, tip)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -491,3 +293,62 @@ func TestGetBehindBaseBranchValuesForAllBranches_LegacyPath(t *testing.T) {
|
||||
|
||||
runner.CheckForMissingCalls()
|
||||
}
|
||||
|
||||
func TestCheckForRewrittenUpstreams(t *testing.T) {
|
||||
branch := func(name string, ahead string, behind string) *models.Branch {
|
||||
return &models.Branch{
|
||||
Name: name,
|
||||
UpstreamRemote: "origin",
|
||||
UpstreamBranch: name,
|
||||
AheadForPull: ahead,
|
||||
BehindForPull: behind,
|
||||
}
|
||||
}
|
||||
|
||||
notDiverged := branch("not-diverged", "0", "2")
|
||||
rewritten := branch("rewritten", "3", "5")
|
||||
ownCommits := branch("own-commits", "3", "5")
|
||||
failing := branch("failing", "1", "1")
|
||||
|
||||
// A branch that is no longer diverged must lose the value it had before
|
||||
notDiverged.UpstreamRewritten.Store(true)
|
||||
|
||||
branches := []*models.Branch{notDiverged, rewritten, ownCommits, failing}
|
||||
|
||||
var mutex deadlock.Mutex
|
||||
queried := []string{}
|
||||
hasLocalOnlyCommits := func(branch *models.Branch) (bool, error) {
|
||||
mutex.Lock()
|
||||
queried = append(queried, branch.Name)
|
||||
mutex.Unlock()
|
||||
|
||||
switch branch.Name {
|
||||
case "own-commits":
|
||||
return true, nil
|
||||
case "failing":
|
||||
return false, errors.New("error")
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
gitCommon := buildGitCommon(commonDeps{})
|
||||
loader := &BranchLoader{
|
||||
Common: gitCommon.Common,
|
||||
GitCommon: gitCommon,
|
||||
cmd: gitCommon.cmd,
|
||||
hasLocalOnlyCommits: hasLocalOnlyCommits,
|
||||
}
|
||||
|
||||
rendered := false
|
||||
err := loader.checkForRewrittenUpstreams(branches, func() { rendered = true })
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, rendered, "renderFunc should have been called")
|
||||
|
||||
assert.ElementsMatch(t, []string{"rewritten", "own-commits", "failing"}, queried,
|
||||
"only diverged branches should be looked at")
|
||||
assert.False(t, notDiverged.UpstreamRewritten.Load())
|
||||
assert.True(t, rewritten.UpstreamRewritten.Load())
|
||||
assert.False(t, ownCommits.UpstreamRewritten.Load())
|
||||
assert.False(t, failing.UpstreamRewritten.Load(), "a failed check should not claim anything")
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -317,3 +318,111 @@ func TestBranchCurrentBranchInfo(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchHasLocalOnlyCommits(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
runner *oscommands.FakeCmdObjRunner
|
||||
test func(bool, error)
|
||||
}
|
||||
|
||||
branch := &models.Branch{
|
||||
Name: "branch",
|
||||
UpstreamRemote: "origin",
|
||||
UpstreamBranch: "branch",
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
"branch is strictly behind its upstream, and there are no reflogs",
|
||||
oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reflog", "show", "--format=%H", "refs/remotes/origin/branch"}, "", nil).
|
||||
ExpectGitArgs([]string{"rev-parse", "-q", "--verify", "refs/remotes/origin/branch@{0}"}, "", errors.New("error")).
|
||||
ExpectGitArgs([]string{
|
||||
"rev-list", "--max-count=1", "--ignore-missing", "refs/heads/branch",
|
||||
"^refs/remotes/origin/branch", "--",
|
||||
}, "", nil),
|
||||
func(hasLocalOnlyCommits bool, err error) {
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, hasLocalOnlyCommits)
|
||||
},
|
||||
},
|
||||
{
|
||||
"the upstream branch was rewritten, so all our commits were on it before",
|
||||
oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reflog", "show", "--format=%H", "refs/remotes/origin/branch"},
|
||||
"1111111111111111111111111111111111111111\n2222222222222222222222222222222222222222\n", nil).
|
||||
ExpectGitArgs([]string{"rev-parse", "-q", "--verify", "refs/remotes/origin/branch@{2}"},
|
||||
"3333333333333333333333333333333333333333\n", nil).
|
||||
ExpectGitArgs([]string{
|
||||
"rev-list", "--max-count=1", "--ignore-missing", "refs/heads/branch",
|
||||
"^refs/remotes/origin/branch",
|
||||
"^1111111111111111111111111111111111111111",
|
||||
"^2222222222222222222222222222222222222222",
|
||||
"^3333333333333333333333333333333333333333",
|
||||
"--",
|
||||
}, "", nil),
|
||||
func(hasLocalOnlyCommits bool, err error) {
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, hasLocalOnlyCommits)
|
||||
},
|
||||
},
|
||||
{
|
||||
"the oldest reflog entry is the one that created the ref",
|
||||
oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reflog", "show", "--format=%H", "refs/remotes/origin/branch"},
|
||||
"1111111111111111111111111111111111111111\n", nil).
|
||||
ExpectGitArgs([]string{"rev-parse", "-q", "--verify", "refs/remotes/origin/branch@{1}"}, "", errors.New("error")).
|
||||
ExpectGitArgs([]string{
|
||||
"rev-list", "--max-count=1", "--ignore-missing", "refs/heads/branch",
|
||||
"^refs/remotes/origin/branch",
|
||||
"^1111111111111111111111111111111111111111",
|
||||
"--",
|
||||
}, "", nil),
|
||||
func(hasLocalOnlyCommits bool, err error) {
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, hasLocalOnlyCommits)
|
||||
},
|
||||
},
|
||||
{
|
||||
"the branch has a commit that was never on the upstream branch",
|
||||
oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reflog", "show", "--format=%H", "refs/remotes/origin/branch"},
|
||||
"1111111111111111111111111111111111111111\n", nil).
|
||||
ExpectGitArgs([]string{"rev-parse", "-q", "--verify", "refs/remotes/origin/branch@{1}"},
|
||||
"2222222222222222222222222222222222222222\n", nil).
|
||||
ExpectGitArgs([]string{
|
||||
"rev-list", "--max-count=1", "--ignore-missing", "refs/heads/branch",
|
||||
"^refs/remotes/origin/branch",
|
||||
"^1111111111111111111111111111111111111111",
|
||||
"^2222222222222222222222222222222222222222",
|
||||
"--",
|
||||
}, "4444444444444444444444444444444444444444\n", nil),
|
||||
func(hasLocalOnlyCommits bool, err error) {
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, hasLocalOnlyCommits)
|
||||
},
|
||||
},
|
||||
{
|
||||
"bubbles up an error from rev-list",
|
||||
oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reflog", "show", "--format=%H", "refs/remotes/origin/branch"}, "", nil).
|
||||
ExpectGitArgs([]string{"rev-parse", "-q", "--verify", "refs/remotes/origin/branch@{0}"}, "", errors.New("error")).
|
||||
ExpectGitArgs([]string{
|
||||
"rev-list", "--max-count=1", "--ignore-missing", "refs/heads/branch",
|
||||
"^refs/remotes/origin/branch", "--",
|
||||
}, "", errors.New("error")),
|
||||
func(hasLocalOnlyCommits bool, err error) {
|
||||
assert.Error(t, err)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
instance := buildBranchCommands(commonDeps{runner: s.runner})
|
||||
s.test(instance.HasLocalOnlyCommits(branch))
|
||||
s.runner.CheckForMissingCalls()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +312,7 @@ func TestCommitShowCmdObj(t *testing.T) {
|
||||
similarityThreshold: 50,
|
||||
ignoreWhitespace: false,
|
||||
diffRendererConfig: &config.DiffRendererConfig{Type: "extDiff", Command: "difft --color=always"},
|
||||
expected: []string{"-C", "/path/to/worktree", "-c", "diff.external=difft --color=always", "-c", "diff.noprefix=false", "show", "--ext-diff", "--unified=3", "--find-renames=50%", "--submodule", "--color=always", "--stat", "--decorate", "-p", "1234567890", "--"},
|
||||
expected: []string{"-C", "/path/to/worktree", "-c", "diff.noprefix=false", "show", "--ext-diff", "--unified=3", "--find-renames=50%", "--submodule", "--color=always", "--stat", "--decorate", "-p", "1234567890", "--"},
|
||||
},
|
||||
{
|
||||
testName: "Show diff using git's external diff config",
|
||||
|
||||
@@ -19,12 +19,12 @@ import (
|
||||
// that opts back in is the foreground files refresh; see FileLoader.gitStatus.
|
||||
const OptionalLocksEnvVar = "GIT_OPTIONAL_LOCKS"
|
||||
|
||||
// forOtherRepo prepares a command that operates on a repo other than the one
|
||||
// ForOtherRepo prepares a command that operates on a repo other than the one
|
||||
// we have open — a submodule, or another worktree. GIT_DIR and GIT_WORK_TREE
|
||||
// say where our repo is, and every command we run inherits them, so a command
|
||||
// pointed at a different repo would be resolved against ours instead: `git -C
|
||||
// <submodule> log` would silently log the superproject's commits.
|
||||
func forOtherRepo(cmdObj *oscommands.CmdObj) *oscommands.CmdObj {
|
||||
func ForOtherRepo(cmdObj *oscommands.CmdObj) *oscommands.CmdObj {
|
||||
return cmdObj.RemoveEnvVar(env.GitDirEnvVar).RemoveEnvVar(env.GitWorkTreeEnvVar)
|
||||
}
|
||||
|
||||
@@ -125,11 +125,9 @@ func (self *GitCommandBuilder) GitDirIf(condition bool, path string) *GitCommand
|
||||
|
||||
func (self *GitCommandBuilder) AddCommonDiffArgs(diffRendererConfigManager *config.DiffRendererConfigManager, userConfig *config.UserConfig, forUI bool) *GitCommandBuilder {
|
||||
contextSize := userConfig.Git.DiffContextSize
|
||||
extDiffCmd := diffRendererConfigManager.GetExternalDiffCommand(contextSize)
|
||||
useExtDiff := forUI && diffRendererConfigManager.GetDiffRendererType() == config.DiffRendererType_ExtDiff
|
||||
|
||||
return self.
|
||||
ConfigIf(forUI && extDiffCmd != "", "diff.external="+extDiffCmd).
|
||||
ArgIfElse(useExtDiff, "--ext-diff", "--no-ext-diff").
|
||||
Arg(fmt.Sprintf("--unified=%d", contextSize)).
|
||||
ArgIf(forUI && userConfig.Git.IgnoreWhitespaceInDiffView, "--ignore-all-space").
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/jesseduffield/generics/set"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// The tip commit of a ref, as far as sorting refs by ancestry needs it. The
|
||||
// date is the raw %(committerdate:unix) field, and is only ever compared for
|
||||
// equality.
|
||||
type refTip struct {
|
||||
hash string
|
||||
committerDate string
|
||||
}
|
||||
|
||||
// Determining ancestry costs one %(ahead-behind:<tip>) field per tip, and git
|
||||
// evaluates each of those for every tip we ask about, so the work grows with
|
||||
// the square of the number of tips. Branches whose tips came out of one rebase
|
||||
// are nowhere near this many, so leave the refs in the order git returned them
|
||||
// once the tips add up to more than this.
|
||||
const maxTipsForAncestrySorting = 100
|
||||
|
||||
// Sorts each group of refs that share a committer date so that a ref comes
|
||||
// before the refs it is descended from. Refs that are not descended from one
|
||||
// another keep the order they came in.
|
||||
//
|
||||
// git sorts refs with equal committer dates by name, and a stack of branches
|
||||
// that gets rebased in one go ends up with the same committer date on all of
|
||||
// its tips. Without this, such a stack appears in alphabetical order.
|
||||
//
|
||||
// refs must be sorted by committer date already, and tips must have an entry
|
||||
// for each of them.
|
||||
func sortRefsWithEqualDatesByAncestry[T any](
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
version *GitVersion,
|
||||
refs []T,
|
||||
fullRefName func(T) string,
|
||||
tips map[string]refTip,
|
||||
) error {
|
||||
// %(ahead-behind:...) was added in git 2.41
|
||||
if !version.IsAtLeast(2, 41, 0) {
|
||||
return nil
|
||||
}
|
||||
|
||||
groups := lo.Filter(groupRefsWithEqualDates(refs, fullRefName, tips),
|
||||
func(group []T, _ int) bool {
|
||||
return pointAtMoreThanOneCommit(group, fullRefName, tips)
|
||||
})
|
||||
if len(groups) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ancestry is a property of the tip commits, so ask git about each of them
|
||||
// once, however many refs point at it. A repository with several remotes
|
||||
// has the same branches under each of them, and they all share a date.
|
||||
tipHashes := []string{}
|
||||
refNames := []string{}
|
||||
seenTips := set.New[string]()
|
||||
for _, ref := range lo.Flatten(groups) {
|
||||
refName := fullRefName(ref)
|
||||
if hash := tips[refName].hash; !seenTips.Includes(hash) {
|
||||
seenTips.Add(hash)
|
||||
tipHashes = append(tipHashes, hash)
|
||||
refNames = append(refNames, refName)
|
||||
}
|
||||
}
|
||||
if len(tipHashes) > maxTipsForAncestrySorting {
|
||||
return nil
|
||||
}
|
||||
|
||||
containedTips, err := loadContainedTips(cmd, tipHashes, refNames)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, group := range groups {
|
||||
sortGroupByAncestry(group, fullRefName, tips, containedTips)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Refs that all point at the same commit have no order to be put in, so
|
||||
// there is nothing to ask git about them
|
||||
func pointAtMoreThanOneCommit[T any](
|
||||
refs []T,
|
||||
fullRefName func(T) string,
|
||||
tips map[string]refTip,
|
||||
) bool {
|
||||
firstHash := tips[fullRefName(refs[0])].hash
|
||||
return lo.SomeBy(refs, func(ref T) bool {
|
||||
return tips[fullRefName(ref)].hash != firstHash
|
||||
})
|
||||
}
|
||||
|
||||
// Returns the runs of consecutive refs that share a committer date, for runs of
|
||||
// more than one ref. The returned slices share their backing array with refs,
|
||||
// so sorting a run sorts that part of refs.
|
||||
func groupRefsWithEqualDates[T any](
|
||||
refs []T,
|
||||
fullRefName func(T) string,
|
||||
tips map[string]refTip,
|
||||
) [][]T {
|
||||
committerDate := func(ref T) string {
|
||||
return tips[fullRefName(ref)].committerDate
|
||||
}
|
||||
|
||||
groups := [][]T{}
|
||||
start := 0
|
||||
for i := 1; i <= len(refs); i++ {
|
||||
if i < len(refs) && committerDate(refs[i]) == committerDate(refs[start]) {
|
||||
continue
|
||||
}
|
||||
if i-start > 1 {
|
||||
groups = append(groups, refs[start:i])
|
||||
}
|
||||
start = i
|
||||
}
|
||||
|
||||
return groups
|
||||
}
|
||||
|
||||
// For each of the given tips, which of the tips its history contains. Keyed by
|
||||
// tip hash, with an entry for every tip passed in. refNames names, for each
|
||||
// tip, a ref that points at it; git reports the values by ref name.
|
||||
func loadContainedTips(
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
tipHashes []string,
|
||||
refNames []string,
|
||||
) (map[string]*set.Set[string], error) {
|
||||
output, err := cmd.New(
|
||||
buildAheadBehindForEachRefArgs(tipHashes, refNames),
|
||||
).DontLog().RunWithOutput()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
containedTips := make(map[string]*set.Set[string], len(tipHashes))
|
||||
for _, hash := range tipHashes {
|
||||
containedTips[hash] = set.New[string]()
|
||||
}
|
||||
tipByRefName := make(map[string]string, len(refNames))
|
||||
for i, refName := range refNames {
|
||||
tipByRefName[refName] = tipHashes[i]
|
||||
}
|
||||
|
||||
for _, entry := range parseAheadBehindForEachRefOutput(output, len(tipHashes)) {
|
||||
hash, ok := tipByRefName[entry.refName]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
contained := containedTips[hash]
|
||||
for i, ab := range entry.aheadBehinds {
|
||||
// The tip's history contains the other tip if it has commits the
|
||||
// other one doesn't have, and the other one has none it doesn't
|
||||
// have.
|
||||
if ab.valid && ab.ahead > 0 && ab.behind == 0 {
|
||||
contained.Add(tipHashes[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return containedTips, nil
|
||||
}
|
||||
|
||||
func sortGroupByAncestry[T any](
|
||||
group []T,
|
||||
fullRefName func(T) string,
|
||||
tips map[string]refTip,
|
||||
containedTips map[string]*set.Set[string],
|
||||
) {
|
||||
hashes := lo.Map(group, func(ref T, _ int) string {
|
||||
return tips[fullRefName(ref)].hash
|
||||
})
|
||||
contained := lo.Map(hashes, func(hash string, _ int) *set.Set[string] {
|
||||
if contained, ok := containedTips[hash]; ok {
|
||||
return contained
|
||||
}
|
||||
return set.New[string]()
|
||||
})
|
||||
isDescendedFrom := func(descendant int, ancestor int) bool {
|
||||
return contained[descendant].Includes(hashes[ancestor])
|
||||
}
|
||||
|
||||
// Indices into group, holding the refs we haven't placed yet
|
||||
remaining := lo.Range(len(group))
|
||||
// A ref can only go in once every ref that is descended from it is in
|
||||
canBePlaced := func(i int) bool {
|
||||
return !lo.SomeBy(remaining, func(j int) bool {
|
||||
return isDescendedFrom(j, i)
|
||||
})
|
||||
}
|
||||
|
||||
sorted := make([]T, 0, len(group))
|
||||
lastPlaced := -1
|
||||
for len(remaining) > 0 {
|
||||
next := -1
|
||||
if lastPlaced != -1 {
|
||||
// Walk from the ref we placed last down to the refs it is based on,
|
||||
// so that the branches of a stack come out as one run even when an
|
||||
// unrelated branch sorts into the middle of them by name
|
||||
next = slices.IndexFunc(remaining, func(i int) bool {
|
||||
return isDescendedFrom(lastPlaced, i) && canBePlaced(i)
|
||||
})
|
||||
}
|
||||
if next == -1 {
|
||||
next = slices.IndexFunc(remaining, canBePlaced)
|
||||
}
|
||||
if next == -1 {
|
||||
// Commits can't descend from each other in a circle; only take the
|
||||
// first ref so that we don't spin if the values ever say otherwise.
|
||||
next = 0
|
||||
}
|
||||
lastPlaced = remaining[next]
|
||||
sorted = append(sorted, group[lastPlaced])
|
||||
remaining = slices.Delete(remaining, next, next+1)
|
||||
}
|
||||
|
||||
copy(group, sorted)
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/samber/lo"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// A branch as the tests below describe it: a name, the hash of its tip, and the
|
||||
// committer date of its tip
|
||||
type testRef struct {
|
||||
name string
|
||||
hash string
|
||||
date string
|
||||
}
|
||||
|
||||
func buildTestRefs(refs []testRef) ([]*models.Branch, map[string]refTip) {
|
||||
branches := lo.Map(refs, func(ref testRef, _ int) *models.Branch {
|
||||
return &models.Branch{Name: ref.name, CommitHash: ref.hash}
|
||||
})
|
||||
tips := make(map[string]refTip, len(refs))
|
||||
for _, ref := range refs {
|
||||
tips["refs/heads/"+ref.name] = refTip{hash: ref.hash, committerDate: ref.date}
|
||||
}
|
||||
return branches, tips
|
||||
}
|
||||
|
||||
func branchNames(branches []*models.Branch) []string {
|
||||
return lo.Map(branches, func(branch *models.Branch, _ int) string {
|
||||
return branch.Name
|
||||
})
|
||||
}
|
||||
|
||||
func TestGroupRefsWithEqualDates(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
refs []testRef
|
||||
expected [][]string
|
||||
}{
|
||||
{
|
||||
testName: "no refs",
|
||||
refs: []testRef{},
|
||||
expected: [][]string{},
|
||||
},
|
||||
{
|
||||
testName: "all dates distinct",
|
||||
refs: []testRef{
|
||||
{name: "a", hash: "1", date: "300"},
|
||||
{name: "b", hash: "2", date: "200"},
|
||||
{name: "c", hash: "3", date: "100"},
|
||||
},
|
||||
expected: [][]string{},
|
||||
},
|
||||
{
|
||||
testName: "all dates equal",
|
||||
refs: []testRef{
|
||||
{name: "a", hash: "1", date: "100"},
|
||||
{name: "b", hash: "2", date: "100"},
|
||||
{name: "c", hash: "3", date: "100"},
|
||||
},
|
||||
expected: [][]string{{"a", "b", "c"}},
|
||||
},
|
||||
{
|
||||
testName: "two groups, with a lone ref between and after them",
|
||||
refs: []testRef{
|
||||
{name: "a", hash: "1", date: "300"},
|
||||
{name: "b", hash: "2", date: "300"},
|
||||
{name: "c", hash: "3", date: "200"},
|
||||
{name: "d", hash: "4", date: "100"},
|
||||
{name: "e", hash: "5", date: "100"},
|
||||
{name: "f", hash: "6", date: "50"},
|
||||
},
|
||||
expected: [][]string{{"a", "b"}, {"d", "e"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
branches, tips := buildTestRefs(s.refs)
|
||||
groups := groupRefsWithEqualDates(branches, (*models.Branch).FullRefName, tips)
|
||||
assert.Equal(t, s.expected, lo.Map(groups,
|
||||
func(group []*models.Branch, _ int) []string {
|
||||
return branchNames(group)
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortRefsWithEqualDatesByAncestry(t *testing.T) {
|
||||
// A stack of three branches, all committed within the same second, as git
|
||||
// returns them: sorted by name. bottom is the base of middle, which is the
|
||||
// base of top.
|
||||
stack := []testRef{
|
||||
{name: "middle", hash: "m", date: "100"},
|
||||
{name: "top", hash: "t", date: "100"},
|
||||
{name: "bottom", hash: "b", date: "100"},
|
||||
}
|
||||
|
||||
// One %(ahead-behind:<hash>) field per tip, in the order the tips appear in
|
||||
// the branch list
|
||||
stackOutput := "refs/heads/middle\x000 0\x000 1\x001 0\n" +
|
||||
"refs/heads/top\x001 0\x000 0\x002 0\n" +
|
||||
"refs/heads/bottom\x000 1\x000 2\x000 0\n"
|
||||
|
||||
stackArgs := []string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:m)%00%(ahead-behind:t)%00%(ahead-behind:b)",
|
||||
"refs/heads/middle", "refs/heads/top", "refs/heads/bottom",
|
||||
}
|
||||
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
refs []testRef
|
||||
gitVersion *GitVersion
|
||||
expectedArgs []string
|
||||
output string
|
||||
outputErr error
|
||||
expectedOrder []string
|
||||
expectedErr string
|
||||
}{
|
||||
{
|
||||
testName: "a stack of branches is sorted from the top down",
|
||||
refs: stack,
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: stackArgs,
|
||||
output: stackOutput,
|
||||
expectedOrder: []string{"top", "middle", "bottom"},
|
||||
},
|
||||
{
|
||||
testName: "git too old for %(ahead-behind:...), so nothing to do",
|
||||
refs: stack,
|
||||
gitVersion: &GitVersion{2, 40, 0, ""},
|
||||
expectedOrder: []string{"middle", "top", "bottom"},
|
||||
},
|
||||
{
|
||||
testName: "no two refs share a date, so nothing to do",
|
||||
refs: []testRef{
|
||||
{name: "middle", hash: "m", date: "300"},
|
||||
{name: "top", hash: "t", date: "200"},
|
||||
{name: "bottom", hash: "b", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedOrder: []string{"middle", "top", "bottom"},
|
||||
},
|
||||
{
|
||||
testName: "the command fails",
|
||||
refs: stack,
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: stackArgs,
|
||||
outputErr: errors.New("fatal: failed to find 'm'"),
|
||||
expectedOrder: []string{"middle", "top", "bottom"},
|
||||
expectedErr: "fatal: failed to find 'm'",
|
||||
},
|
||||
{
|
||||
testName: "a branch unrelated to the stack is placed by name",
|
||||
refs: []testRef{
|
||||
{name: "middle", hash: "m", date: "100"},
|
||||
{name: "other", hash: "o", date: "100"},
|
||||
{name: "top", hash: "t", date: "100"},
|
||||
{name: "bottom", hash: "b", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: []string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:m)%00%(ahead-behind:o)%00%(ahead-behind:t)%00%(ahead-behind:b)",
|
||||
"refs/heads/middle", "refs/heads/other", "refs/heads/top", "refs/heads/bottom",
|
||||
},
|
||||
output: "refs/heads/middle\x000 0\x002 1\x000 1\x001 0\n" +
|
||||
"refs/heads/other\x001 2\x000 0\x001 3\x001 1\n" +
|
||||
"refs/heads/top\x001 0\x003 1\x000 0\x002 0\n" +
|
||||
"refs/heads/bottom\x000 1\x001 1\x000 2\x000 0\n",
|
||||
expectedOrder: []string{"other", "top", "middle", "bottom"},
|
||||
},
|
||||
{
|
||||
testName: "a stack stays together when a branch sorts into the middle of it",
|
||||
refs: []testRef{
|
||||
{name: "add-tests", hash: "t", date: "100"},
|
||||
{name: "cleanup", hash: "c", date: "100"},
|
||||
{name: "fix-parser", hash: "p", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: []string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:t)%00%(ahead-behind:c)%00%(ahead-behind:p)",
|
||||
"refs/heads/add-tests", "refs/heads/cleanup", "refs/heads/fix-parser",
|
||||
},
|
||||
// add-tests is based on fix-parser, and cleanup is on a line of its
|
||||
// own, but its name sorts between the two
|
||||
output: "refs/heads/add-tests\x000 0\x002 1\x001 0\n" +
|
||||
"refs/heads/cleanup\x001 2\x000 0\x001 1\n" +
|
||||
"refs/heads/fix-parser\x000 1\x001 1\x000 0\n",
|
||||
expectedOrder: []string{"add-tests", "fix-parser", "cleanup"},
|
||||
},
|
||||
{
|
||||
testName: "each group is sorted on its own",
|
||||
refs: []testRef{
|
||||
{name: "middle", hash: "m", date: "200"},
|
||||
{name: "top", hash: "t", date: "200"},
|
||||
{name: "lone", hash: "l", date: "150"},
|
||||
{name: "base", hash: "a", date: "100"},
|
||||
{name: "derived", hash: "d", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: []string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:m)%00%(ahead-behind:t)%00%(ahead-behind:a)%00%(ahead-behind:d)",
|
||||
"refs/heads/middle", "refs/heads/top", "refs/heads/base", "refs/heads/derived",
|
||||
},
|
||||
output: "refs/heads/middle\x000 0\x000 1\x002 0\x001 0\n" +
|
||||
"refs/heads/top\x001 0\x000 0\x003 0\x002 0\n" +
|
||||
"refs/heads/base\x000 2\x000 3\x000 0\x000 1\n" +
|
||||
"refs/heads/derived\x000 1\x000 2\x001 0\x000 0\n",
|
||||
expectedOrder: []string{"top", "middle", "lone", "derived", "base"},
|
||||
},
|
||||
{
|
||||
testName: "a group whose branches are all on one commit is left alone",
|
||||
refs: []testRef{
|
||||
{name: "a", hash: "x", date: "100"},
|
||||
{name: "b", hash: "x", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedOrder: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
testName: "branches on the same commit are asked about once",
|
||||
refs: []testRef{
|
||||
{name: "mirror-1", hash: "s", date: "100"},
|
||||
{name: "mirror-2", hash: "s", date: "100"},
|
||||
{name: "stack-bottom", hash: "u", date: "100"},
|
||||
{name: "stack-top", hash: "t", date: "100"},
|
||||
},
|
||||
gitVersion: &GitVersion{2, 41, 0, ""},
|
||||
expectedArgs: []string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:s)%00%(ahead-behind:u)%00%(ahead-behind:t)",
|
||||
"refs/heads/mirror-1", "refs/heads/stack-bottom", "refs/heads/stack-top",
|
||||
},
|
||||
output: "refs/heads/mirror-1\x000 0\x001 1\x001 2\n" +
|
||||
"refs/heads/stack-bottom\x001 1\x000 0\x000 1\n" +
|
||||
"refs/heads/stack-top\x002 1\x001 0\x000 0\n",
|
||||
expectedOrder: []string{"mirror-1", "mirror-2", "stack-top", "stack-bottom"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
runner := oscommands.NewFakeRunner(t)
|
||||
if s.expectedArgs != nil {
|
||||
runner.ExpectGitArgs(s.expectedArgs, s.output, s.outputErr)
|
||||
}
|
||||
gitCommon := buildGitCommon(commonDeps{runner: runner, gitVersion: s.gitVersion})
|
||||
|
||||
branches, tips := buildTestRefs(s.refs)
|
||||
err := sortRefsWithEqualDatesByAncestry(gitCommon.cmd, gitCommon.version,
|
||||
branches, (*models.Branch).FullRefName, tips)
|
||||
|
||||
if s.expectedErr == "" {
|
||||
assert.NoError(t, err)
|
||||
} else {
|
||||
assert.ErrorContains(t, err, s.expectedErr)
|
||||
}
|
||||
assert.Equal(t, s.expectedOrder, branchNames(branches))
|
||||
runner.CheckForMissingCalls()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortRefsWithEqualDatesByAncestry_TooManyTips(t *testing.T) {
|
||||
refs := lo.Map(lo.Range(maxTipsForAncestrySorting+1), func(i int, _ int) testRef {
|
||||
return testRef{
|
||||
name: fmt.Sprintf("branch-%03d", i),
|
||||
hash: fmt.Sprintf("hash-%03d", i),
|
||||
date: "100",
|
||||
}
|
||||
})
|
||||
|
||||
// The runner fails the test if the command runs at all
|
||||
runner := oscommands.NewFakeRunner(t)
|
||||
gitCommon := buildGitCommon(commonDeps{runner: runner, gitVersion: &GitVersion{2, 41, 0, ""}})
|
||||
|
||||
branches, tips := buildTestRefs(refs)
|
||||
err := sortRefsWithEqualDatesByAncestry(gitCommon.cmd, gitCommon.version,
|
||||
branches, (*models.Branch).FullRefName, tips)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, lo.Map(refs, func(ref testRef, _ int) string { return ref.name }),
|
||||
branchNames(branches))
|
||||
runner.CheckForMissingCalls()
|
||||
}
|
||||
|
||||
// A repository with many remotes has the same branches under each of them, so
|
||||
// a group can hold far more refs than the commits they point at
|
||||
func TestSortRefsWithEqualDatesByAncestry_ManyRefsOnTwoTips(t *testing.T) {
|
||||
refs := lo.Map(lo.Range(4*maxTipsForAncestrySorting), func(i int, _ int) testRef {
|
||||
return testRef{
|
||||
name: fmt.Sprintf("branch-%03d", i),
|
||||
hash: lo.Ternary(i%2 == 0, "bottom", "top"),
|
||||
date: "100",
|
||||
}
|
||||
})
|
||||
|
||||
runner := oscommands.NewFakeRunner(t).ExpectGitArgs([]string{
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(ahead-behind:bottom)%00%(ahead-behind:top)",
|
||||
"refs/heads/branch-000", "refs/heads/branch-001",
|
||||
},
|
||||
"refs/heads/branch-000\x000 0\x000 1\n"+
|
||||
"refs/heads/branch-001\x001 0\x000 0\n", nil)
|
||||
gitCommon := buildGitCommon(commonDeps{runner: runner, gitVersion: &GitVersion{2, 41, 0, ""}})
|
||||
|
||||
branches, tips := buildTestRefs(refs)
|
||||
err := sortRefsWithEqualDatesByAncestry(gitCommon.cmd, gitCommon.version,
|
||||
branches, (*models.Branch).FullRefName, tips)
|
||||
|
||||
assert.NoError(t, err)
|
||||
// the branches on the top commit first, each half still ordered by name
|
||||
expected := append(
|
||||
lo.FilterMap(refs, func(ref testRef, _ int) (string, bool) {
|
||||
return ref.name, ref.hash == "top"
|
||||
}),
|
||||
lo.FilterMap(refs, func(ref testRef, _ int) (string, bool) {
|
||||
return ref.name, ref.hash == "bottom"
|
||||
})...)
|
||||
assert.Equal(t, expected, branchNames(branches))
|
||||
runner.CheckForMissingCalls()
|
||||
}
|
||||
@@ -59,9 +59,10 @@ func (self *RemoteCommands) DeleteRemoteBranch(task gocui.Task, remoteName strin
|
||||
return self.cmd.New(cmdArgs).PromptOnCredentialRequest(task).Run()
|
||||
}
|
||||
|
||||
func (self *RemoteCommands) DeleteRemoteTag(task gocui.Task, remoteName string, tagName string) error {
|
||||
func (self *RemoteCommands) DeleteRemoteTag(task gocui.Task, remoteName string, tagNames []string) error {
|
||||
cmdArgs := NewGitCmd("push").
|
||||
Arg(remoteName, "--delete", "refs/tags/"+tagName).
|
||||
Arg(remoteName, "--delete").
|
||||
Arg(lo.Map(tagNames, func(t string, _ int) string { return "refs/tags/" + t })...).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).PromptOnCredentialRequest(task).Run()
|
||||
|
||||
@@ -5,53 +5,25 @@ import (
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type RemoteLoader struct {
|
||||
*common.Common
|
||||
cmd oscommands.ICmdObjBuilder
|
||||
*GitCommon
|
||||
}
|
||||
|
||||
func NewRemoteLoader(
|
||||
common *common.Common,
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
) *RemoteLoader {
|
||||
return &RemoteLoader{
|
||||
Common: common,
|
||||
cmd: cmd,
|
||||
}
|
||||
func NewRemoteLoader(gitCommon *GitCommon) *RemoteLoader {
|
||||
return &RemoteLoader{GitCommon: gitCommon}
|
||||
}
|
||||
|
||||
func (self *RemoteLoader) GetRemotes() ([]*models.Remote, error) {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
|
||||
var remoteBranchesByRemoteName map[string][]*models.RemoteBranch
|
||||
var remoteBranchesErr error
|
||||
go utils.Safe(func() {
|
||||
defer wg.Done()
|
||||
|
||||
remoteBranchesByRemoteName, remoteBranchesErr = self.getRemoteBranchesByRemoteName()
|
||||
})
|
||||
|
||||
// GetRemotes returns the repo's remotes, without their branches; those are
|
||||
// loaded separately with GetRemoteBranchesByRemoteName, which takes a lot longer
|
||||
// in a repo with many remote branches.
|
||||
func (self *RemoteLoader) GetRemotes() []*models.Remote {
|
||||
remotes := self.getRemotesFromConfig()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if remoteBranchesErr != nil {
|
||||
return nil, remoteBranchesErr
|
||||
}
|
||||
|
||||
for _, remote := range remotes {
|
||||
remote.Branches = remoteBranchesByRemoteName[remote.Name]
|
||||
}
|
||||
|
||||
// now lets sort our remotes by name alphabetically
|
||||
slices.SortFunc(remotes, func(a, b *models.Remote) int {
|
||||
// we want origin at the top because we'll be most likely to want it
|
||||
@@ -64,7 +36,7 @@ func (self *RemoteLoader) GetRemotes() ([]*models.Remote, error) {
|
||||
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
|
||||
})
|
||||
|
||||
return remotes, nil
|
||||
return remotes
|
||||
}
|
||||
|
||||
func (self *RemoteLoader) getRemotesFromConfig() []*models.Remote {
|
||||
@@ -111,29 +83,47 @@ func (self *RemoteLoader) getRemotesFromConfig() []*models.Remote {
|
||||
return slices.Collect(maps.Values(remotesByName))
|
||||
}
|
||||
|
||||
func (self *RemoteLoader) getRemoteBranchesByRemoteName() (map[string][]*models.RemoteBranch, error) {
|
||||
remoteBranchesByRemoteName := make(map[string][]*models.RemoteBranch)
|
||||
// GetRemoteBranchesByRemoteName returns all remote branches, keyed by the name
|
||||
// of the remote they belong to.
|
||||
func (self *RemoteLoader) GetRemoteBranchesByRemoteName() (map[string][]*models.RemoteBranch, error) {
|
||||
remoteBranches, err := self.getRemoteBranches()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var sortOrder string
|
||||
switch strings.ToLower(self.UserConfig().Git.RemoteBranchSortOrder) {
|
||||
case "alphabetical":
|
||||
sortOrder = "refname"
|
||||
case "date":
|
||||
return lo.GroupBy(remoteBranches, func(branch *models.RemoteBranch) string {
|
||||
return branch.RemoteName
|
||||
}), nil
|
||||
}
|
||||
|
||||
// Returns all remote branches, sorted the way the config asks for
|
||||
func (self *RemoteLoader) getRemoteBranches() ([]*models.RemoteBranch, error) {
|
||||
sortByDate := strings.ToLower(self.UserConfig().Git.RemoteBranchSortOrder) == "date"
|
||||
sortOrder := "refname"
|
||||
if sortByDate {
|
||||
sortOrder = "-committerdate"
|
||||
default:
|
||||
sortOrder = "refname"
|
||||
}
|
||||
|
||||
// Asking for the tip of a branch makes git read its commit, so only do it
|
||||
// when we are going to sort by ancestry below
|
||||
format := "%(refname)"
|
||||
if sortByDate {
|
||||
format += "%00%(objectname)%00%(committerdate:unix)"
|
||||
}
|
||||
|
||||
cmdArgs := NewGitCmd("for-each-ref").
|
||||
Arg(fmt.Sprintf("--sort=%s", sortOrder)).
|
||||
Arg("--format=%(refname)").
|
||||
Arg(fmt.Sprintf("--format=%s", format)).
|
||||
Arg("refs/remotes").
|
||||
ToArgv()
|
||||
|
||||
remoteBranches := []*models.RemoteBranch{}
|
||||
tips := map[string]refTip{}
|
||||
err := self.cmd.New(cmdArgs).DontLog().RunAndProcessLines(func(line string) (bool, error) {
|
||||
line = strings.TrimSpace(line)
|
||||
fields := strings.Split(strings.TrimSpace(line), "\x00")
|
||||
refName := fields[0]
|
||||
|
||||
split := strings.SplitN(line, "/", 4)
|
||||
split := strings.SplitN(refName, "/", 4)
|
||||
if len(split) != 4 {
|
||||
return false, nil
|
||||
}
|
||||
@@ -144,21 +134,27 @@ func (self *RemoteLoader) getRemoteBranchesByRemoteName() (map[string][]*models.
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_, ok := remoteBranchesByRemoteName[remoteName]
|
||||
if !ok {
|
||||
remoteBranchesByRemoteName[remoteName] = []*models.RemoteBranch{}
|
||||
}
|
||||
|
||||
remoteBranchesByRemoteName[remoteName] = append(remoteBranchesByRemoteName[remoteName],
|
||||
remoteBranches = append(remoteBranches,
|
||||
&models.RemoteBranch{
|
||||
Name: name,
|
||||
RemoteName: remoteName,
|
||||
})
|
||||
if len(fields) == 3 {
|
||||
tips[refName] = refTip{hash: fields[1], committerDate: fields[2]}
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return remoteBranchesByRemoteName, nil
|
||||
if sortByDate {
|
||||
if err := sortRefsWithEqualDatesByAncestry(
|
||||
self.cmd, self.version, remoteBranches, (*models.RemoteBranch).FullRefName, tips,
|
||||
); err != nil {
|
||||
self.Log.Errorf("Failed to sort remote branches by ancestry: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return remoteBranches, nil
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -95,8 +94,7 @@ func TestGetRemotesFromConfig(t *testing.T) {
|
||||
for _, scenario := range scenarios {
|
||||
t.Run(scenario.testName, func(t *testing.T) {
|
||||
loader := &RemoteLoader{
|
||||
Common: common.NewDummyCommon(),
|
||||
cmd: oscommands.NewDummyCmdObjBuilder(scenario.runner),
|
||||
GitCommon: buildGitCommon(commonDeps{runner: scenario.runner}),
|
||||
}
|
||||
|
||||
// map iteration order is non-deterministic, so compare unordered
|
||||
|
||||
@@ -271,13 +271,13 @@ func callGitRevParseWithDir(
|
||||
return runGitRevParse(newGitRevParseCmd(cmd, dir, gitRevArgs...))
|
||||
}
|
||||
|
||||
// Asks git about a repo that isn't the one we have open; see forOtherRepo.
|
||||
// Asks git about a repo that isn't the one we have open; see ForOtherRepo.
|
||||
func callGitRevParseInOtherRepo(
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
dir string,
|
||||
gitRevArgs ...string,
|
||||
) (string, error) {
|
||||
return runGitRevParse(forOtherRepo(newGitRevParseCmd(cmd, dir, gitRevArgs...)))
|
||||
return runGitRevParse(ForOtherRepo(newGitRevParseCmd(cmd, dir, gitRevArgs...)))
|
||||
}
|
||||
|
||||
func newGitRevParseCmd(
|
||||
|
||||
@@ -139,7 +139,7 @@ func TestStashStashEntryCmdObj(t *testing.T) {
|
||||
similarityThreshold: 50,
|
||||
ignoreWhitespace: false,
|
||||
diffRendererConfig: &config.DiffRendererConfig{Type: "extDiff", Command: "difft --color=always"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "-c", "diff.external=difft --color=always", "stash", "show", "--ext-diff", "--unified=3", "--find-renames=50%", "-p", "--stat", "-u", "--color=always", "refs/stash@{5}"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "--ext-diff", "--unified=3", "--find-renames=50%", "-p", "--stat", "-u", "--color=always", "refs/stash@{5}"},
|
||||
},
|
||||
{
|
||||
testName: "Show diff using git's external diff config",
|
||||
|
||||
@@ -157,7 +157,7 @@ func (self *SubmoduleCommands) GetCommitSummary(path string, sha string) (string
|
||||
Config("log.showsignature=false").
|
||||
ToArgv()
|
||||
|
||||
summary, err := forOtherRepo(self.cmd.New(cmdArgs)).DontLog().RunWithOutput()
|
||||
summary, err := ForOtherRepo(self.cmd.New(cmdArgs)).DontLog().RunWithOutput()
|
||||
return strings.TrimSpace(summary), err
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ func (self *SubmoduleCommands) GetCommitSummary(path string, sha string) (string
|
||||
// caller then stages the submodule to record the resolution.
|
||||
func (self *SubmoduleCommands) CheckoutConflictCommit(path string, sha string) error {
|
||||
cmdArgs := NewGitCmd("checkout").Dir(path).Arg(sha).ToArgv()
|
||||
return forOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
return ForOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
}
|
||||
|
||||
// ConflictSideLog returns a oneline log, run inside the submodule, of the commits
|
||||
@@ -179,7 +179,7 @@ func (self *SubmoduleCommands) ConflictSideLog(path string, side string, otherSi
|
||||
Arg("--oneline", "--color=always", otherSide+".."+side).
|
||||
ToArgv()
|
||||
|
||||
return forOtherRepo(self.cmd.New(cmdArgs)).DontLog().RunWithOutput()
|
||||
return ForOtherRepo(self.cmd.New(cmdArgs)).DontLog().RunWithOutput()
|
||||
}
|
||||
|
||||
func (self *SubmoduleCommands) Stash(submodule *models.SubmoduleConfig) error {
|
||||
@@ -195,7 +195,7 @@ func (self *SubmoduleCommands) Stash(submodule *models.SubmoduleConfig) error {
|
||||
Arg("--include-untracked").
|
||||
ToArgv()
|
||||
|
||||
return forOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
return ForOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
}
|
||||
|
||||
func (self *SubmoduleCommands) Reset(submodule *models.SubmoduleConfig) error {
|
||||
@@ -229,7 +229,7 @@ func (self *SubmoduleCommands) UpdateAll() error {
|
||||
// need not be.
|
||||
func (self *SubmoduleCommands) runInParentModule(submodule *models.SubmoduleConfig, cmdObj *oscommands.CmdObj) error {
|
||||
if submodule.ParentModule != nil {
|
||||
forOtherRepo(cmdObj.SetWd(submodule.ParentModule.FullPath()))
|
||||
ForOtherRepo(cmdObj.SetWd(submodule.ParentModule.FullPath()))
|
||||
}
|
||||
return cmdObj.Run()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type SyncCommands struct {
|
||||
@@ -18,18 +19,21 @@ func NewSyncCommands(gitCommon *GitCommon) *SyncCommands {
|
||||
}
|
||||
}
|
||||
|
||||
// Push pushes to a branch
|
||||
type PushOpts struct {
|
||||
Force bool
|
||||
ForceWithLease bool
|
||||
CurrentBranch string
|
||||
UpstreamRemote string
|
||||
UpstreamBranch string
|
||||
SetUpstream bool
|
||||
// The remote to push to. If empty, git picks it from its configuration,
|
||||
// and Refspecs must be empty too.
|
||||
Remote string
|
||||
// What to push, each in the form "refs/heads/<local branch>:<remote ref>".
|
||||
// If empty, git decides what to push based on push.default and
|
||||
// remote.<name>.push.
|
||||
Refspecs []string
|
||||
}
|
||||
|
||||
func (self *SyncCommands) PushCmdObj(task gocui.Task, opts PushOpts) (*oscommands.CmdObj, error) {
|
||||
if opts.UpstreamBranch != "" && opts.UpstreamRemote == "" {
|
||||
if len(opts.Refspecs) > 0 && opts.Remote == "" {
|
||||
return nil, errors.New(self.Tr.MustSpecifyOriginError)
|
||||
}
|
||||
|
||||
@@ -37,8 +41,8 @@ func (self *SyncCommands) PushCmdObj(task gocui.Task, opts PushOpts) (*oscommand
|
||||
ArgIf(opts.Force, "--force").
|
||||
ArgIf(opts.ForceWithLease, "--force-with-lease").
|
||||
ArgIf(opts.SetUpstream, "--set-upstream").
|
||||
ArgIf(opts.UpstreamRemote != "", opts.UpstreamRemote).
|
||||
ArgIf(opts.UpstreamBranch != "", fmt.Sprintf("refs/heads/%s:%s", opts.CurrentBranch, opts.UpstreamBranch)).
|
||||
ArgIf(opts.Remote != "", opts.Remote).
|
||||
Arg(opts.Refspecs...).
|
||||
ToArgv()
|
||||
|
||||
cmdObj := self.cmd.New(cmdArgs).PromptOnCredentialRequest(task)
|
||||
@@ -110,15 +114,25 @@ func (self *SyncCommands) Pull(task gocui.Task, opts PullOptions) error {
|
||||
return self.cmd.New(cmdArgs).AddEnvVars("GIT_SEQUENCE_EDITOR=:").PromptOnCredentialRequest(task).Run()
|
||||
}
|
||||
|
||||
func (self *SyncCommands) FastForward(
|
||||
// Fetches the given branches of the given remote, updating their
|
||||
// remote-tracking branches. Local branches are left alone, including the ones
|
||||
// that track them.
|
||||
func (self *SyncCommands) FetchRemoteBranches(
|
||||
task gocui.Task,
|
||||
branchName string,
|
||||
remoteName string,
|
||||
remoteBranchName string,
|
||||
remoteBranchNames []string,
|
||||
) error {
|
||||
// The explicit destinations and the leading + make sure that the
|
||||
// remote-tracking branches are updated even when the remote branches were
|
||||
// rewritten, whatever the remote's fetch refspec says
|
||||
refspecs := lo.Map(remoteBranchNames, func(remoteBranchName string, _ int) string {
|
||||
return fmt.Sprintf("+refs/heads/%s:refs/remotes/%s/%s",
|
||||
remoteBranchName, remoteName, remoteBranchName)
|
||||
})
|
||||
|
||||
cmdArgs := self.fetchCommandBuilder(false).
|
||||
Arg(remoteName).
|
||||
Arg("refs/heads/" + remoteBranchName + ":" + branchName).
|
||||
Arg(refspecs...).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).PromptOnCredentialRequest(task).Run()
|
||||
|
||||
@@ -41,12 +41,11 @@ func TestSyncPush(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Push with force disabled, upstream supplied",
|
||||
testName: "Push with force disabled, refspec supplied",
|
||||
opts: PushOpts{
|
||||
ForceWithLease: false,
|
||||
CurrentBranch: "master",
|
||||
UpstreamRemote: "origin",
|
||||
UpstreamBranch: "master",
|
||||
Remote: "origin",
|
||||
Refspecs: []string{"refs/heads/master:master"},
|
||||
},
|
||||
test: func(cmdObj *oscommands.CmdObj, err error) {
|
||||
assert.Equal(t, cmdObj.Args(), []string{"git", "push", "origin", "refs/heads/master:master"})
|
||||
@@ -57,9 +56,8 @@ func TestSyncPush(t *testing.T) {
|
||||
testName: "Push with force disabled, setting upstream",
|
||||
opts: PushOpts{
|
||||
ForceWithLease: false,
|
||||
CurrentBranch: "master-local",
|
||||
UpstreamRemote: "origin",
|
||||
UpstreamBranch: "master",
|
||||
Remote: "origin",
|
||||
Refspecs: []string{"refs/heads/master-local:master"},
|
||||
SetUpstream: true,
|
||||
},
|
||||
test: func(cmdObj *oscommands.CmdObj, err error) {
|
||||
@@ -71,9 +69,8 @@ func TestSyncPush(t *testing.T) {
|
||||
testName: "Push with force-with-lease enabled, setting upstream",
|
||||
opts: PushOpts{
|
||||
ForceWithLease: true,
|
||||
CurrentBranch: "master",
|
||||
UpstreamRemote: "origin",
|
||||
UpstreamBranch: "master",
|
||||
Remote: "origin",
|
||||
Refspecs: []string{"refs/heads/master:master"},
|
||||
SetUpstream: true,
|
||||
},
|
||||
test: func(cmdObj *oscommands.CmdObj, err error) {
|
||||
@@ -82,11 +79,23 @@ func TestSyncPush(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Push with remote branch but no origin",
|
||||
testName: "Push several refspecs",
|
||||
opts: PushOpts{
|
||||
ForceWithLease: true,
|
||||
UpstreamRemote: "",
|
||||
UpstreamBranch: "master",
|
||||
Remote: "origin",
|
||||
Refspecs: []string{"refs/heads/a:refs/heads/a", "refs/heads/b:refs/heads/b"},
|
||||
},
|
||||
test: func(cmdObj *oscommands.CmdObj, err error) {
|
||||
assert.Equal(t, cmdObj.Args(), []string{"git", "push", "--force-with-lease", "origin", "refs/heads/a:refs/heads/a", "refs/heads/b:refs/heads/b"})
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Push with refspec but no remote",
|
||||
opts: PushOpts{
|
||||
ForceWithLease: true,
|
||||
Remote: "",
|
||||
Refspecs: []string{"refs/heads/master:master"},
|
||||
SetUpstream: true,
|
||||
},
|
||||
test: func(cmdObj *oscommands.CmdObj, err error) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type TagCommands struct {
|
||||
@@ -46,15 +47,16 @@ func (self *TagCommands) HasTag(tagName string) bool {
|
||||
return self.cmd.New(cmdArgs).DontLog().Run() == nil
|
||||
}
|
||||
|
||||
func (self *TagCommands) LocalDelete(tagName string) error {
|
||||
cmdArgs := NewGitCmd("tag").Arg("-d", tagName).
|
||||
func (self *TagCommands) LocalDelete(tagNames []string) error {
|
||||
cmdArgs := NewGitCmd("tag").Arg("-d").Arg(tagNames...).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
func (self *TagCommands) Push(task gocui.Task, remoteName string, tagName string) error {
|
||||
cmdArgs := NewGitCmd("push").Arg(remoteName, "tag", tagName).
|
||||
func (self *TagCommands) Push(task gocui.Task, remoteName string, tagNames []string) error {
|
||||
cmdArgs := NewGitCmd("push").Arg(remoteName).
|
||||
Arg(lo.FlatMap(tagNames, func(t string, _ int) []string { return []string{"tag", t} })...).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).PromptOnCredentialRequest(task).Run()
|
||||
|
||||
@@ -524,6 +524,42 @@ func (self *WorkingTreeCommands) ResetSoft(ref string) error {
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
// ResetKeep runs `git reset --keep` in the given worktree, which moves the
|
||||
// checked out branch to the given ref while keeping local modifications. It
|
||||
// fails rather than overwriting a file that differs between the two commits.
|
||||
// Pass empty strings for the worktree to use the current one.
|
||||
func (self *WorkingTreeCommands) ResetKeep(ref string, worktreeGitDir string, worktreePath string) error {
|
||||
cmdArgs := NewGitCmd("reset").Arg("--keep", ref).
|
||||
GitDirIf(worktreeGitDir != "", worktreeGitDir).
|
||||
WorktreePathIf(worktreePath != "", worktreePath).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
// Returns whether the given worktree has changes to tracked files, either in
|
||||
// its working tree or in its index. Untracked files don't count, and neither do
|
||||
// submodules. A submodule that is checked out at a different commit than the
|
||||
// one recorded, or that has changes of its own, doesn't get in the way of
|
||||
// moving the branch, because moving it leaves the submodules alone. Pass empty
|
||||
// strings for the worktree to use the current one.
|
||||
func (self *WorkingTreeCommands) HasChangesToTrackedFiles(worktreeGitDir string, worktreePath string) (bool, error) {
|
||||
cmdArgs := NewGitCmd("status").
|
||||
Arg("--porcelain").
|
||||
Arg("--untracked-files=no").
|
||||
Arg("--ignore-submodules").
|
||||
GitDirIf(worktreeGitDir != "", worktreeGitDir).
|
||||
WorktreePathIf(worktreePath != "", worktreePath).
|
||||
ToArgv()
|
||||
|
||||
stdout, _, err := self.cmd.New(cmdArgs).DontLog().RunWithOutputs()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return stdout != "", nil
|
||||
}
|
||||
|
||||
func (self *WorkingTreeCommands) ResetMixed(ref string) error {
|
||||
cmdArgs := NewGitCmd("reset").Arg("--mixed", ref).
|
||||
ToArgv()
|
||||
|
||||
@@ -51,7 +51,7 @@ func (self *WorktreeCommands) Delete(worktreePath string, force bool) error {
|
||||
func (self *WorktreeCommands) Detach(worktreePath string) error {
|
||||
cmdArgs := NewGitCmd("checkout").Arg("--detach").GitDir(filepath.Join(worktreePath, ".git")).ToArgv()
|
||||
|
||||
return forOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
return ForOtherRepo(self.cmd.New(cmdArgs)).Run()
|
||||
}
|
||||
|
||||
func WorktreeForBranch(branch *models.Branch, worktrees []*models.Worktree) (*models.Worktree, bool) {
|
||||
|
||||
@@ -140,12 +140,14 @@ func (self *WorktreeLoader) GetWorktrees() ([]*models.Worktree, error) {
|
||||
rebasedBranch, ok := self.rebasedBranch(worktree)
|
||||
if ok {
|
||||
worktree.Branch = rebasedBranch
|
||||
worktree.IsRebasingOrBisecting = true
|
||||
continue
|
||||
}
|
||||
|
||||
bisectedBranch, ok := self.bisectedBranch(worktree)
|
||||
if ok {
|
||||
worktree.Branch = bisectedBranch
|
||||
worktree.IsRebasingOrBisecting = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,13 @@ type Branch struct {
|
||||
// 'git@github.com:tiwood/lazygit.git'
|
||||
UpstreamRemote string
|
||||
UpstreamBranch string
|
||||
// The remote and the remote branch that `git push` would push this branch
|
||||
// to, as git determines them from push.default, remote.pushDefault and
|
||||
// branch.<name>.pushRemote. In a triangular workflow these differ from the
|
||||
// upstream. Both are empty if git has no push destination for the branch,
|
||||
// e.g. because push.default is "upstream" and the branch has no upstream.
|
||||
PushRemote string
|
||||
PushBranch string
|
||||
// subject line in commit message
|
||||
Subject string
|
||||
// commit hash
|
||||
@@ -40,6 +47,13 @@ type Branch struct {
|
||||
// determined yet, or up to date with base branch. (We don't need to
|
||||
// distinguish the two, as we don't draw anything in both cases.)
|
||||
BehindBaseBranch atomic.Int32
|
||||
|
||||
// Whether the branch has diverged from its upstream because the upstream
|
||||
// branch was rewritten, and not because the branch has commits of its own.
|
||||
// Such a branch can be reset to its upstream without losing anything.
|
||||
// False for branches that haven't diverged, and for those we haven't
|
||||
// determined it for yet.
|
||||
UpstreamRewritten atomic.Bool
|
||||
}
|
||||
|
||||
func (b *Branch) FullRefName() string {
|
||||
@@ -119,6 +133,13 @@ func (b *Branch) IsBehindForPush() bool {
|
||||
return b.RemoteBranchStoredLocally() && b.BehindForPush != "0"
|
||||
}
|
||||
|
||||
// Whether the branch has commits that its push destination doesn't have. False
|
||||
// if the remote branch it would be pushed to isn't stored locally, in which
|
||||
// case the count is "?".
|
||||
func (b *Branch) IsAheadForPush() bool {
|
||||
return b.RemoteBranchStoredLocally() && b.AheadForPush != "0" && b.AheadForPush != "?"
|
||||
}
|
||||
|
||||
// for when we're in a detached head state
|
||||
func (b *Branch) IsRealBranch() bool {
|
||||
return b.AheadForPull != "" && b.BehindForPull != ""
|
||||
|
||||
@@ -19,6 +19,9 @@ type Worktree struct {
|
||||
// * the worktree is mid-rebase on the branch
|
||||
// * the worktree is mid-bisect on the branch
|
||||
Branch string
|
||||
// If true, the worktree is mid-rebase or mid-bisect on Branch, so its HEAD
|
||||
// is detached rather than pointing at the branch
|
||||
IsRebasingOrBisecting bool
|
||||
// The HEAD sha of the worktree. Always populated (even when Branch is set).
|
||||
// Used for display when Branch is empty (detached HEAD state).
|
||||
Head string
|
||||
|
||||
@@ -108,6 +108,14 @@ func (self *CmdObj) GetEnvVars() []string {
|
||||
return self.cmd.Env
|
||||
}
|
||||
|
||||
// SetEnviron replaces the command's whole environment, for a command that has
|
||||
// to run in the same one as another command rather than in this process's.
|
||||
func (self *CmdObj) SetEnviron(env []string) *CmdObj {
|
||||
self.cmd.Env = env
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
// sets the working directory
|
||||
func (self *CmdObj) SetWd(wd string) *CmdObj {
|
||||
self.cmd.Dir = wd
|
||||
|
||||
@@ -33,6 +33,16 @@ func (self *CmdObjBuilder) New(args []string) *CmdObj {
|
||||
return cmdObj
|
||||
}
|
||||
|
||||
// NewFromCmd wraps a command that has already been built, for a caller that
|
||||
// holds an *exec.Cmd and needs it as a CmdObj. The command itself is shared,
|
||||
// not copied, so whatever was set on it still applies.
|
||||
func (self *CmdObjBuilder) NewFromCmd(cmd *exec.Cmd) *CmdObj {
|
||||
return &CmdObj{
|
||||
cmd: cmd,
|
||||
runner: self.runner,
|
||||
}
|
||||
}
|
||||
|
||||
// A command with explicit environment from env
|
||||
func (self *CmdObjBuilder) NewWithEnviron(args []string, env []string) *CmdObj {
|
||||
cmd := exec.Command(args[0], args[1:]...)
|
||||
|
||||
@@ -4,12 +4,10 @@ import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/samber/lo"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
@@ -203,61 +201,25 @@ func (c *OSCommand) FileExists(path string) (bool, error) {
|
||||
|
||||
// PipeCommands runs a heap of commands and pipes their inputs/outputs together like A | B | C
|
||||
func (c *OSCommand) PipeCommands(cmdObjs ...*CmdObj) error {
|
||||
cmds := lo.Map(cmdObjs, func(cmdObj *CmdObj, _ int) *exec.Cmd {
|
||||
return cmdObj.GetCmd()
|
||||
})
|
||||
c.logPipeline(cmdObjs)
|
||||
|
||||
logCmdStr := strings.Join(
|
||||
lo.Map(cmdObjs, func(cmdObj *CmdObj, _ int) string {
|
||||
return cmdObj.ToString()
|
||||
}),
|
||||
" | ",
|
||||
)
|
||||
|
||||
c.LogCommand(logCmdStr, true)
|
||||
|
||||
for i := range len(cmds) - 1 {
|
||||
stdout, err := cmds[i].StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmds[i+1].Stdin = stdout
|
||||
cmds, parentEnds, err := wirePipeline(cmdObjs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// keeping this here in case I adapt this code for some other purpose in the future
|
||||
// cmds[len(cmds)-1].Stdout = os.Stdout
|
||||
|
||||
stderrs := make([]bytes.Buffer, len(cmds))
|
||||
for i := range cmds {
|
||||
cmds[i].Stderr = &stderrs[i]
|
||||
}
|
||||
|
||||
// Start every command before waiting for any of them: waiting for a command
|
||||
// closes our end of the pipe that feeds the next one, and a command that
|
||||
// hasn't been started by then would inherit a closed stdin.
|
||||
started := 0
|
||||
var startErr error
|
||||
for _, cmd := range cmds {
|
||||
if err := cmd.Start(); err != nil {
|
||||
startErr = err
|
||||
break
|
||||
}
|
||||
|
||||
started++
|
||||
}
|
||||
started, startErr := startPipeline(cmds, parentEnds)
|
||||
|
||||
finalErrors := []string{}
|
||||
|
||||
if startErr != nil {
|
||||
c.Log.Error(startErr)
|
||||
finalErrors = append(finalErrors, startErr.Error())
|
||||
|
||||
// Without the rest of the pipeline to drain them, the commands we did
|
||||
// start could block forever writing to a full pipe.
|
||||
for _, cmd := range cmds[:started] {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
|
||||
for i, cmd := range cmds[:started] {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package oscommands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// Pipeline is a chain of running commands, each one's output feeding the next
|
||||
// one's input, with the last one's output going somewhere the caller reads. Its
|
||||
// method set is the one a render task expects of a command (see tasks.Cmd), so
|
||||
// a pipeline can render a view just as a single command can.
|
||||
type Pipeline struct {
|
||||
cmds []*exec.Cmd
|
||||
cmdStr string
|
||||
}
|
||||
|
||||
// StartPipeline starts the given commands wired A | B | C and returns the
|
||||
// pipeline together with the reader for its output.
|
||||
//
|
||||
// Every command's stderr goes to that same output, so whatever a command
|
||||
// complains about is part of what the caller reads. A diff renderer's error
|
||||
// message belongs on screen with the diff it failed to render.
|
||||
//
|
||||
// Closing the reader is how a pipeline is brought down. The last command's next
|
||||
// write fails, so it exits, and the failure travels back up the chain as each
|
||||
// command in turn writes into a pipe whose reader is gone.
|
||||
func (c *OSCommand) StartPipeline(cmdObjs ...*CmdObj) (*Pipeline, io.ReadCloser, error) {
|
||||
c.logPipeline(cmdObjs)
|
||||
|
||||
cmds, parentEnds, err := wirePipeline(cmdObjs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
closeAll(parentEnds)
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, cmd := range cmds {
|
||||
cmd.Stderr = writer
|
||||
}
|
||||
cmds[len(cmds)-1].Stdout = writer
|
||||
parentEnds = append(parentEnds, writer)
|
||||
|
||||
started, err := startPipeline(cmds, parentEnds)
|
||||
if err != nil {
|
||||
for _, cmd := range cmds[:started] {
|
||||
_ = cmd.Wait()
|
||||
}
|
||||
_ = reader.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return &Pipeline{cmds: cmds, cmdStr: pipelineString(cmdObjs)}, reader, nil
|
||||
}
|
||||
|
||||
func (self *Pipeline) String() string {
|
||||
return self.cmdStr
|
||||
}
|
||||
|
||||
// Wait waits for every command to exit and reports the failure nearest the end
|
||||
// of the pipeline. A command that fails leaves the ones before it writing into
|
||||
// a pipe nobody reads, so their own broken-pipe failures are consequences of it
|
||||
// rather than the cause worth reporting, while a command that fails early
|
||||
// leaves the ones after it with nothing to read and no reason to fail at all.
|
||||
func (self *Pipeline) Wait() error {
|
||||
var lastErr error
|
||||
for _, cmd := range self.cmds {
|
||||
if err := cmd.Wait(); err != nil {
|
||||
lastErr = fmt.Errorf("%s: %w", cmd.String(), err)
|
||||
}
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// Terminate asks every command to stop, without waiting for any of them. On
|
||||
// platforms where that does nothing, the pipeline comes down when its output
|
||||
// reader is closed; see StartPipeline.
|
||||
func (self *Pipeline) Terminate() error {
|
||||
var firstErr error
|
||||
for _, cmd := range self.cmds {
|
||||
if err := TerminateProcessGracefully(cmd.Process); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// logPipeline enters a chain of commands into the command log, unless the first
|
||||
// command was marked not to be logged; it speaks for the pipeline. A render runs
|
||||
// its pipeline again on every selection change, so a caller has to be able to
|
||||
// keep it out of the log.
|
||||
func (c *OSCommand) logPipeline(cmdObjs []*CmdObj) {
|
||||
if cmdObjs[0].ShouldLog() {
|
||||
c.LogCommand(pipelineString(cmdObjs), true)
|
||||
}
|
||||
}
|
||||
|
||||
// pipelineString names a chain of commands the way a shell would write it.
|
||||
func pipelineString(cmdObjs []*CmdObj) string {
|
||||
return strings.Join(
|
||||
lo.Map(cmdObjs, func(cmdObj *CmdObj, _ int) string {
|
||||
return cmdObj.ToString()
|
||||
}),
|
||||
" | ",
|
||||
)
|
||||
}
|
||||
|
||||
// wirePipeline connects each command's output to the next one's input, like
|
||||
// A | B | C, and returns the commands along with the parent's ends of those
|
||||
// pipes. The last command's output is left for the caller to direct.
|
||||
//
|
||||
// The parent's ends have to be closed once the commands are running.
|
||||
// startPipeline does that; see there for why it matters.
|
||||
func wirePipeline(cmdObjs []*CmdObj) ([]*exec.Cmd, []io.Closer, error) {
|
||||
cmds := lo.Map(cmdObjs, func(cmdObj *CmdObj, _ int) *exec.Cmd {
|
||||
return cmdObj.GetCmd()
|
||||
})
|
||||
|
||||
parentEnds := []io.Closer{}
|
||||
for i := range len(cmds) - 1 {
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
closeAll(parentEnds)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
cmds[i].Stdout = writer
|
||||
cmds[i+1].Stdin = reader
|
||||
parentEnds = append(parentEnds, reader, writer)
|
||||
}
|
||||
|
||||
return cmds, parentEnds, nil
|
||||
}
|
||||
|
||||
// startPipeline starts every command and reports how many it got going. Every
|
||||
// one is started before any of them is waited for: waiting closes our end of
|
||||
// the pipe that feeds the next command, and one that hasn't been started by
|
||||
// then would inherit a closed stdin.
|
||||
//
|
||||
// Once they are all running, each of them holds its own ends of the pipes it
|
||||
// reads and writes, and the parent lets go of its copies. Both directions
|
||||
// matter. While the parent holds the read end of a link, a command writing
|
||||
// into it never learns that the command meant to read it is gone, and keeps
|
||||
// running after the pipeline has been brought down. While the parent holds the
|
||||
// write end, the command reading it never reaches the end of its input.
|
||||
//
|
||||
// When a command fails to start, the ones already running are killed, since
|
||||
// without the rest of the pipeline to drain them they could block forever
|
||||
// writing to a full pipe. They still have to be reaped, so the count covers
|
||||
// them too.
|
||||
func startPipeline(cmds []*exec.Cmd, parentEnds []io.Closer) (int, error) {
|
||||
defer closeAll(parentEnds)
|
||||
|
||||
for i, cmd := range cmds {
|
||||
if err := cmd.Start(); err != nil {
|
||||
for _, started := range cmds[:i] {
|
||||
_ = started.Process.Kill()
|
||||
}
|
||||
|
||||
return i, err
|
||||
}
|
||||
}
|
||||
|
||||
return len(cmds), nil
|
||||
}
|
||||
|
||||
func closeAll(closers []io.Closer) {
|
||||
for _, closer := range closers {
|
||||
_ = closer.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package oscommands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// The pipeline tests need programs to run, and the test binary is the one
|
||||
// program every platform we test on is sure to have. pipelineMember builds a
|
||||
// command that re-runs this binary in the role a member of the pipeline is to
|
||||
// play; the roles are in TestPipelineMember.
|
||||
const pipelineRoleEnvVar = "LAZYGIT_TEST_PIPELINE_ROLE"
|
||||
|
||||
func pipelineMember(role string) *CmdObj {
|
||||
return NewDummyOSCommand().Cmd.
|
||||
New([]string{os.Args[0], "-test.run=^TestPipelineMember$"}).
|
||||
AddEnvVars(pipelineRoleEnvVar + "=" + role)
|
||||
}
|
||||
|
||||
// TestPipelineMember is the program the pipeline tests run, not a test of its
|
||||
// own. It exits before the testing package reports anything, so that its output
|
||||
// is what the role wrote and nothing else.
|
||||
//
|
||||
// For the same reason it exits with syscall.Exit, which skips the exit hooks
|
||||
// that os.Exit runs. In a binary built with -cover, one of these hooks writes
|
||||
// coverage data to $GOCOVERDIR and prints an error to stderr if that fails. On
|
||||
// Windows it fails now and then if two members of a pipeline exit at the same
|
||||
// time, because both of them replace the same file in that directory.
|
||||
func TestPipelineMember(t *testing.T) {
|
||||
switch os.Getenv(pipelineRoleEnvVar) {
|
||||
case "":
|
||||
t.Skip("not a test; the pipeline tests run this binary in a role")
|
||||
case "count":
|
||||
for i := 1; i <= 3; i++ {
|
||||
fmt.Printf("line %d\n", i)
|
||||
}
|
||||
case "upcase":
|
||||
input, _ := io.ReadAll(os.Stdin)
|
||||
fmt.Print(strings.ToUpper(string(input)))
|
||||
case "copy":
|
||||
_, _ = io.Copy(os.Stdout, os.Stdin)
|
||||
case "complain":
|
||||
fmt.Fprintln(os.Stderr, "something went wrong")
|
||||
syscall.Exit(3)
|
||||
case "flood":
|
||||
// A failed write means the reader is gone, and there is no point
|
||||
// writing to nobody. On platforms that raise a signal for it instead,
|
||||
// this process is already dead by the time the write returns.
|
||||
for i := 1; ; i++ {
|
||||
if _, err := fmt.Printf("line %d\n", i); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
syscall.Exit(0)
|
||||
}
|
||||
|
||||
func TestStartPipelineStreamsTheOutputOfTheLastCommand(t *testing.T) {
|
||||
pipeline, reader, err := NewDummyOSCommand().StartPipeline(
|
||||
pipelineMember("count"),
|
||||
pipelineMember("upcase"),
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
|
||||
output, err := io.ReadAll(reader)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "LINE 1\nLINE 2\nLINE 3\n", string(output))
|
||||
|
||||
assert.NoError(t, pipeline.Wait())
|
||||
assert.NoError(t, reader.Close())
|
||||
}
|
||||
|
||||
func TestStartPipelineReadsWhatTheCommandsComplainAbout(t *testing.T) {
|
||||
pipeline, reader, err := NewDummyOSCommand().StartPipeline(
|
||||
pipelineMember("count"),
|
||||
pipelineMember("complain"),
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
|
||||
output, err := io.ReadAll(reader)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "something went wrong\n", string(output))
|
||||
|
||||
// The failure of the command nearest the output is the one reported, even
|
||||
// though the one feeding it was left writing into a pipe nobody reads.
|
||||
assert.ErrorContains(t, pipeline.Wait(), "exit status 3")
|
||||
|
||||
assert.NoError(t, reader.Close())
|
||||
}
|
||||
|
||||
func TestClosingAPipelinesOutputBringsItDown(t *testing.T) {
|
||||
pipeline, reader, err := NewDummyOSCommand().StartPipeline(
|
||||
pipelineMember("flood"),
|
||||
pipelineMember("copy"),
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Read some output first, so that both commands are past their startup and
|
||||
// really running when the reader goes.
|
||||
buf := make([]byte, len("line 1\n"))
|
||||
_, err = io.ReadFull(reader, buf)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "line 1\n", string(buf))
|
||||
|
||||
assert.NoError(t, reader.Close())
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- pipeline.Wait() }()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the pipeline was still running long after its output was closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartPipelineReportsACommandItCannotStart(t *testing.T) {
|
||||
osCommand := NewDummyOSCommand()
|
||||
|
||||
_, _, err := osCommand.StartPipeline(
|
||||
pipelineMember("count"),
|
||||
osCommand.Cmd.New([]string{"lazygit-no-such-command"}),
|
||||
)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestPipeCommandsReturnsWhenALaterCommandDiesEarly(t *testing.T) {
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- NewDummyOSCommand().PipeCommands(
|
||||
pipelineMember("flood"),
|
||||
pipelineMember("complain"),
|
||||
)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
assert.ErrorContains(t, err, "something went wrong")
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("PipeCommands was still waiting for a command whose output nothing reads")
|
||||
}
|
||||
}
|
||||
@@ -144,9 +144,7 @@ func TerminateLivePtys() {
|
||||
// graceful signal worth waiting on — git and the common diff tools leave it
|
||||
// to the default handler, which calls ExitProcess at whatever instruction
|
||||
// the process happens to execute — so clients that got the event are
|
||||
// already dying. Killing at an arbitrary point cannot leak a stale
|
||||
// index.lock, because pty-rendered commands don't take that lock (see
|
||||
// withPtyGitConfig in pkg/gui/pty.go).
|
||||
// already dying.
|
||||
//
|
||||
// The pseudoconsole close gets its own goroutine because the kill must not
|
||||
// wait for it: on builds where ClosePseudoConsole blocks until the console
|
||||
|
||||
@@ -16,6 +16,11 @@ type Hunk struct {
|
||||
newStart int
|
||||
// the context at the end of the header line (' func (f *CommitFile) Description() string {' in the above example)
|
||||
headerContext string
|
||||
// the lengths declared in the header line ('2' and '3' in the above example),
|
||||
// kept so that we can check the parsed body against them (see
|
||||
// Patch.IsWellFormed). Only set by Parse.
|
||||
declaredOldLength int
|
||||
declaredNewLength int
|
||||
// the body of the hunk, excluding the header line
|
||||
bodyLines []*PatchLine
|
||||
}
|
||||
|
||||
+26
-11
@@ -7,7 +7,9 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
|
||||
var hunkHeaderRegexp = regexp.MustCompile(`(?m)^@@ -(\d+)[^\+]+\+(\d+)[^@]+@@(.*)$`)
|
||||
// Captures, in order: the old start, the old length (omitted by git when it is
|
||||
// 1), the new start, the new length (likewise), and the trailing context.
|
||||
var hunkHeaderRegexp = regexp.MustCompile(`(?m)^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$`)
|
||||
|
||||
func Parse(patchStr string) *Patch {
|
||||
// ignore trailing newline.
|
||||
@@ -19,13 +21,15 @@ func Parse(patchStr string) *Patch {
|
||||
var currentHunk *Hunk
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "@@") {
|
||||
oldStart, newStart, headerContext := headerInfo(line)
|
||||
oldStart, oldLength, newStart, newLength, headerContext := headerInfo(line)
|
||||
|
||||
currentHunk = &Hunk{
|
||||
oldStart: oldStart,
|
||||
newStart: newStart,
|
||||
headerContext: headerContext,
|
||||
bodyLines: []*PatchLine{},
|
||||
oldStart: oldStart,
|
||||
newStart: newStart,
|
||||
declaredOldLength: oldLength,
|
||||
declaredNewLength: newLength,
|
||||
headerContext: headerContext,
|
||||
bodyLines: []*PatchLine{},
|
||||
}
|
||||
hunks = append(hunks, currentHunk)
|
||||
} else if currentHunk != nil {
|
||||
@@ -41,14 +45,25 @@ func Parse(patchStr string) *Patch {
|
||||
}
|
||||
}
|
||||
|
||||
func headerInfo(header string) (int, int, string) {
|
||||
func headerInfo(header string) (oldStart int, oldLength int, newStart int, newLength int, headerContext string) {
|
||||
match := hunkHeaderRegexp.FindStringSubmatch(header)
|
||||
|
||||
oldStart := utils.MustConvertToInt(match[1])
|
||||
newStart := utils.MustConvertToInt(match[2])
|
||||
headerContext := match[3]
|
||||
oldStart = utils.MustConvertToInt(match[1])
|
||||
oldLength = declaredLength(match[2])
|
||||
newStart = utils.MustConvertToInt(match[3])
|
||||
newLength = declaredLength(match[4])
|
||||
headerContext = match[5]
|
||||
|
||||
return oldStart, newStart, headerContext
|
||||
return oldStart, oldLength, newStart, newLength, headerContext
|
||||
}
|
||||
|
||||
// declaredLength parses a length capture of a hunk header, which git omits when
|
||||
// it is 1 (e.g. "@@ -0,0 +1 @@").
|
||||
func declaredLength(match string) int {
|
||||
if match == "" {
|
||||
return 1
|
||||
}
|
||||
return utils.MustConvertToInt(match)
|
||||
}
|
||||
|
||||
func newHunkLine(line string) *PatchLine {
|
||||
|
||||
@@ -79,6 +79,44 @@ func (self *Patch) HunkEndIdx(hunkIndex int) int {
|
||||
return self.HunkStartIdx(hunkIndex) + self.hunks[hunkIndex].lineCount() - 1
|
||||
}
|
||||
|
||||
// IsWellFormed reports whether every hunk's body matches the lengths declared in
|
||||
// its header. A faithful unified diff always satisfies this; a rendering that
|
||||
// restructured the diff body does not — a diff renderer that puts line numbers in
|
||||
// a gutter, say, shifts the +/- marker off the start of each line, so every body
|
||||
// line reads as context and the computed lengths no longer match the header. That
|
||||
// makes this the test for whether a rendered diff can be parsed as a unified diff
|
||||
// at all, rather than trusting a mis-parse. Only meaningful for patches produced
|
||||
// by Parse, which is where the declared lengths come from.
|
||||
func (self *Patch) IsWellFormed() bool {
|
||||
return self.isWellFormed(false)
|
||||
}
|
||||
|
||||
// IsWellFormedSoFar is IsWellFormed for a patch parsed from a diff we have only the
|
||||
// beginning of. Its last hunk holds the first lines of a body that hasn't all arrived,
|
||||
// so every hunk but the last has to match its header exactly, as before, while the last
|
||||
// one only has to fit within what its header declares.
|
||||
//
|
||||
// The check exists to tell a faithful rendering from a restructured one, and it still
|
||||
// does that. A rendering that moves the +/- marker off the start of the line makes us
|
||||
// read a change as context, and a context line counts towards both lengths, so such a
|
||||
// hunk comes out longer than its header declares rather than shorter.
|
||||
func (self *Patch) IsWellFormedSoFar() bool {
|
||||
return self.isWellFormed(true)
|
||||
}
|
||||
|
||||
func (self *Patch) isWellFormed(lastHunkMayBeIncomplete bool) bool {
|
||||
for i, hunk := range self.hunks {
|
||||
if lastHunkMayBeIncomplete && i == len(self.hunks)-1 {
|
||||
return hunk.oldLength() <= hunk.declaredOldLength &&
|
||||
hunk.newLength() <= hunk.declaredNewLength
|
||||
}
|
||||
if hunk.oldLength() != hunk.declaredOldLength || hunk.newLength() != hunk.declaredNewLength {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Patch) ContainsChanges() bool {
|
||||
return lo.SomeBy(self.hunks, func(hunk *Hunk) bool {
|
||||
return hunk.containsChanges()
|
||||
@@ -114,6 +152,37 @@ func (self *Patch) LineNumberOfLine(idx int) int {
|
||||
return hunk.newStart + offset
|
||||
}
|
||||
|
||||
// Takes a line index in the patch and returns the line number in the old file.
|
||||
// This is the old-file counterpart of LineNumberOfLine; for a deletion it gives
|
||||
// the line's position in the old file (additions get the position they sit at).
|
||||
// If the line is a header line, returns 1.
|
||||
// If the line is a hunk header line, returns the first old-file line number in that hunk.
|
||||
// If the line is out of range below, returns the last old-file line number in the last hunk.
|
||||
func (self *Patch) OldLineNumberOfLine(idx int) int {
|
||||
if idx < len(self.header) || len(self.hunks) == 0 {
|
||||
return 1
|
||||
}
|
||||
|
||||
hunkIdx := self.HunkContainingLine(idx)
|
||||
// cursor out of range, return last file line number
|
||||
if hunkIdx == -1 {
|
||||
lastHunk := self.hunks[len(self.hunks)-1]
|
||||
return lastHunk.oldStart + lastHunk.oldLength() - 1
|
||||
}
|
||||
|
||||
hunk := self.hunks[hunkIdx]
|
||||
hunkStartIdx := self.HunkStartIdx(hunkIdx)
|
||||
idxInHunk := idx - hunkStartIdx
|
||||
|
||||
if idxInHunk == 0 {
|
||||
return hunk.oldStart
|
||||
}
|
||||
|
||||
lines := hunk.bodyLines[:idxInHunk-1]
|
||||
offset := nLinesWithKind(lines, []PatchLineKind{DELETION, CONTEXT})
|
||||
return hunk.oldStart + offset
|
||||
}
|
||||
|
||||
// Returns hunk index containing the line at the given patch line index
|
||||
func (self *Patch) HunkContainingLine(idx int) int {
|
||||
for hunkIdx, hunk := range self.hunks {
|
||||
|
||||
@@ -120,6 +120,20 @@ index 9320895..6d79956 100644
|
||||
lemon
|
||||
`
|
||||
|
||||
// Two deletions with no line between them: they share a new-file line number
|
||||
// (both sit at the same new-file position), so only their old-file line numbers
|
||||
// tell them apart.
|
||||
const consecutiveDeletions = `diff --git a/filename b/filename
|
||||
index 9320895..6d79956 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,4 +1,2 @@
|
||||
apple
|
||||
-grape
|
||||
-pear
|
||||
lemon
|
||||
`
|
||||
|
||||
const newFile = `diff --git a/newfile b/newfile
|
||||
new file mode 100644
|
||||
index 0000000..4e680cc
|
||||
@@ -682,6 +696,148 @@ func TestLineNumberOfLine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWellFormed(t *testing.T) {
|
||||
// The body of a diff as rendered with the +/- markers moved out of the text
|
||||
// and into a gutter: every body line now reads as context, so the lengths no
|
||||
// longer match the header.
|
||||
const gutterMangled = `diff --git a/filename b/filename
|
||||
index 9320895..6d79956 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,4 +1,2 @@
|
||||
apple
|
||||
grape
|
||||
pear
|
||||
lemon
|
||||
`
|
||||
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
patchStr string
|
||||
expected bool
|
||||
}{
|
||||
{"simpleDiff", simpleDiff, true},
|
||||
{"renameWithModificationDiff", renameWithModificationDiff, true},
|
||||
{"addNewlineToEndOfFile", addNewlineToEndOfFile, true},
|
||||
{"twoHunks", twoHunks, true},
|
||||
{"consecutiveDeletions", consecutiveDeletions, true},
|
||||
{"newFile", newFile, true},
|
||||
{"deletedFile", deletedFile, true},
|
||||
{"addNewlineToPreviouslyEmptyFile", addNewlineToPreviouslyEmptyFile, true},
|
||||
{"exampleHunk", exampleHunk, true},
|
||||
{"gutterMangled", gutterMangled, false},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, Parse(s.patchStr).IsWellFormed())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWellFormedSoFar(t *testing.T) {
|
||||
// A diff read only as far as the middle of its second hunk.
|
||||
const cutShort = `diff --git a/filename b/filename
|
||||
index e48a11c..b2ab81b 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
-grape
|
||||
+orange
|
||||
...
|
||||
...
|
||||
...
|
||||
@@ -8,6 +8,8 @@ grape
|
||||
...
|
||||
...
|
||||
`
|
||||
|
||||
// The same diff cut short in its first hunk, so that the second is missing
|
||||
// entirely rather than short.
|
||||
const cutShortInTheFirstHunk = `diff --git a/filename b/filename
|
||||
index e48a11c..b2ab81b 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
-grape
|
||||
`
|
||||
|
||||
// A rendering with the +/- markers moved into a gutter, cut short: reading the
|
||||
// changes as context makes the hunk longer than its header declares, not shorter,
|
||||
// so it doesn't pass for a diff we only have the beginning of.
|
||||
const gutterMangledAndCutShort = `diff --git a/filename b/filename
|
||||
index 9320895..6d79956 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,4 +1,2 @@
|
||||
apple
|
||||
grape
|
||||
pear
|
||||
lemon
|
||||
melon
|
||||
`
|
||||
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
patchStr string
|
||||
expected bool
|
||||
}{
|
||||
{"simpleDiff", simpleDiff, true},
|
||||
{"twoHunks", twoHunks, true},
|
||||
{"cutShort", cutShort, true},
|
||||
{"cutShortInTheFirstHunk", cutShortInTheFirstHunk, true},
|
||||
{"gutterMangledAndCutShort", gutterMangledAndCutShort, false},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, Parse(s.patchStr).IsWellFormedSoFar())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldLineNumberOfLine(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
patchStr string
|
||||
indexes []int
|
||||
expecteds []int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "twoChangesInOneHunk",
|
||||
patchStr: twoChangesInOneHunk,
|
||||
indexes: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1000},
|
||||
expecteds: []int{1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 5, 5, 5},
|
||||
},
|
||||
{
|
||||
testName: "consecutiveDeletions",
|
||||
patchStr: consecutiveDeletions,
|
||||
indexes: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 1000},
|
||||
expecteds: []int{1, 1, 1, 1, 1, 1, 2, 3, 4, 4},
|
||||
},
|
||||
{
|
||||
testName: "renameWithModificationDiff",
|
||||
patchStr: renameWithModificationDiff,
|
||||
indexes: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1000},
|
||||
expecteds: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 5, 5},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
for i, idx := range s.indexes {
|
||||
patch := Parse(s.patchStr)
|
||||
result := patch.OldLineNumberOfLine(idx)
|
||||
assert.Equal(t, s.expecteds[i], result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNextStageableLineIndex(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -309,6 +310,13 @@ func computeMigratedConfig(path string, content []byte, changes *ChangesSet) ([]
|
||||
}
|
||||
}
|
||||
|
||||
// This creates gui.branchColorPatterns, so it must run before the move of
|
||||
// that key into gui.theme below.
|
||||
err = migrateBranchColors(&rootNode, changes)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Couldn't migrate config file at `%s`: %w", path, err)
|
||||
}
|
||||
|
||||
pathsToMove := []struct {
|
||||
oldPath []string
|
||||
newPath []string
|
||||
@@ -317,6 +325,14 @@ func computeMigratedConfig(path string, content []byte, changes *ChangesSet) ([]
|
||||
[]string{"keybinding", "worktrees", "viewWorktreeOptions"},
|
||||
[]string{"keybinding", "universal", "newWorktree"},
|
||||
},
|
||||
{
|
||||
[]string{"gui", "authorColors"},
|
||||
[]string{"gui", "theme", "authorColors"},
|
||||
},
|
||||
{
|
||||
[]string{"gui", "branchColorPatterns"},
|
||||
[]string{"gui", "theme", "branchColorPatterns"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, pathToMove := range pathsToMove {
|
||||
@@ -630,6 +646,43 @@ func migratePagersToDiffRenderers(rootNode *yaml.Node, changes *ChangesSet) erro
|
||||
})
|
||||
}
|
||||
|
||||
// The deprecated gui.branchColors matched its keys against the part of a branch
|
||||
// name before the first slash. Turn each key into a pattern that matches the
|
||||
// same branches. If the file has a non-empty gui.branchColorPatterns,
|
||||
// gui.branchColors was ignored, so remove it.
|
||||
func migrateBranchColors(rootNode *yaml.Node, changes *ChangesSet) error {
|
||||
return yaml_utils.TransformNode(rootNode, []string{"gui"}, func(guiNode *yaml.Node) error {
|
||||
branchColorsKeyNode, branchColorsValueNode := yaml_utils.LookupKey(guiNode, "branchColors")
|
||||
if branchColorsKeyNode == nil || branchColorsValueNode.Kind != yaml.MappingNode {
|
||||
return nil
|
||||
}
|
||||
|
||||
patternsKeyNode, patternsValueNode := yaml_utils.LookupKey(guiNode, "branchColorPatterns")
|
||||
if patternsKeyNode != nil {
|
||||
switch {
|
||||
case patternsValueNode.Kind == yaml.MappingNode && len(patternsValueNode.Content) > 0:
|
||||
yaml_utils.RemoveKey(guiNode, "branchColors")
|
||||
changes.Add("Removed 'gui.branchColors'; it had no effect because 'gui.branchColorPatterns' is set")
|
||||
return nil
|
||||
case patternsValueNode.Kind == yaml.MappingNode || patternsValueNode.Tag == "!!null":
|
||||
yaml_utils.RemoveKey(guiNode, "branchColorPatterns")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
branchColorsKeyNode.Value = "branchColorPatterns"
|
||||
for i := 0; i < len(branchColorsValueNode.Content)-1; i += 2 {
|
||||
keyNode := branchColorsValueNode.Content[i]
|
||||
keyNode.Value = "^" + regexp.QuoteMeta(keyNode.Value) + "(/|$)"
|
||||
keyNode.Tag = "!!str"
|
||||
}
|
||||
changes.Add("Converted 'gui.branchColors' to 'gui.branchColorPatterns'")
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func hasNonNullScalarValue(node *yaml.Node) bool {
|
||||
return node != nil && node.Kind == yaml.ScalarNode && node.Tag != "!!null" && node.Value != ""
|
||||
}
|
||||
|
||||
@@ -175,6 +175,32 @@ func TestMigrationOfMovedKeys(t *testing.T) {
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{"Moved 'keybinding.worktrees.viewWorktreeOptions' to 'keybinding.universal.newWorktree'"},
|
||||
},
|
||||
{
|
||||
name: "Move author and branch colors into the theme",
|
||||
input: `gui:
|
||||
authorColors:
|
||||
John Smith: red
|
||||
theme:
|
||||
activeBorderColor:
|
||||
- green
|
||||
branchColorPatterns:
|
||||
^docs/: blue
|
||||
`,
|
||||
expected: `gui:
|
||||
theme:
|
||||
activeBorderColor:
|
||||
- green
|
||||
authorColors:
|
||||
John Smith: red
|
||||
branchColorPatterns:
|
||||
^docs/: blue
|
||||
`,
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{
|
||||
"Moved 'gui.authorColors' to 'gui.theme.authorColors'",
|
||||
"Moved 'gui.branchColorPatterns' to 'gui.theme.branchColorPatterns'",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
@@ -821,3 +847,119 @@ func TestPagerMigration(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchColorsMigration(t *testing.T) {
|
||||
moved := "Moved 'gui.branchColorPatterns' to 'gui.theme.branchColorPatterns'"
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
expectedDidChange bool
|
||||
expectedChanges []string
|
||||
}{
|
||||
{
|
||||
name: "No branchColors",
|
||||
input: "gui:\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" '^docs/': blue\n",
|
||||
expectedDidChange: false,
|
||||
expectedChanges: []string{},
|
||||
},
|
||||
{
|
||||
name: "branchColors is not an object",
|
||||
input: "gui:\n" +
|
||||
" branchColors: 5\n",
|
||||
expectedDidChange: false,
|
||||
expectedChanges: []string{},
|
||||
},
|
||||
{
|
||||
name: "branchColors is converted to patterns",
|
||||
input: "gui:\n" +
|
||||
" scrollHeight: 2\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n" +
|
||||
" v1.x: '#ff0000'\n" +
|
||||
" 123: red\n" +
|
||||
" mouseEvents: false\n",
|
||||
expected: "gui:\n" +
|
||||
" scrollHeight: 2\n" +
|
||||
" mouseEvents: false\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" ^feature(/|$): green\n" +
|
||||
" ^v1\\.x(/|$): '#ff0000'\n" +
|
||||
" ^123(/|$): red\n",
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{"Converted 'gui.branchColors' to 'gui.branchColorPatterns'", moved},
|
||||
},
|
||||
{
|
||||
name: "branchColors is removed if branchColorPatterns is set",
|
||||
input: "gui:\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" '^docs/': blue\n",
|
||||
expected: "gui:\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" '^docs/': blue\n",
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{"Removed 'gui.branchColors'; it had no effect because 'gui.branchColorPatterns' is set", moved},
|
||||
},
|
||||
{
|
||||
name: "branchColors replaces an empty branchColorPatterns",
|
||||
input: "gui:\n" +
|
||||
" branchColorPatterns: {}\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n",
|
||||
expected: "gui:\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" ^feature(/|$): green\n",
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{"Converted 'gui.branchColors' to 'gui.branchColorPatterns'", moved},
|
||||
},
|
||||
{
|
||||
name: "branchColors replaces a null branchColorPatterns",
|
||||
input: "gui:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n",
|
||||
expected: "gui:\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns:\n" +
|
||||
" ^feature(/|$): green\n",
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{"Converted 'gui.branchColors' to 'gui.branchColorPatterns'", moved},
|
||||
},
|
||||
{
|
||||
name: "branchColors is kept if branchColorPatterns is not an object",
|
||||
input: "gui:\n" +
|
||||
" branchColorPatterns: 5\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n",
|
||||
expected: "gui:\n" +
|
||||
" branchColors:\n" +
|
||||
" feature: green\n" +
|
||||
" theme:\n" +
|
||||
" branchColorPatterns: 5\n",
|
||||
expectedDidChange: true,
|
||||
expectedChanges: []string{moved},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
changes := NewChangesSet()
|
||||
actual, didChange, err := computeMigratedConfig("path doesn't matter", []byte(s.input), changes)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, s.expectedDidChange, didChange)
|
||||
if didChange {
|
||||
assert.Equal(t, s.expected, string(actual))
|
||||
}
|
||||
assert.Equal(t, s.expectedChanges, changes.ToSliceFromOldest())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/karimkhaleel/jsonschema"
|
||||
"github.com/samber/lo"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// ColorPatterns assigns colors to the names that match regular expressions.
|
||||
// It's written in YAML as a mapping from pattern to color, and keeps the
|
||||
// patterns in the order in which they are written, so that the first pattern
|
||||
// that matches a name can decide its color.
|
||||
type ColorPatterns []ColorPattern
|
||||
|
||||
type ColorPattern struct {
|
||||
Pattern string
|
||||
Color string
|
||||
}
|
||||
|
||||
// UnmarshalYAML puts the patterns it reads in front of the ones that are there
|
||||
// already, which come from config files that were loaded earlier.
|
||||
func (p *ColorPatterns) UnmarshalYAML(node *yaml.Node) error {
|
||||
// Decoding into a map reports malformed input the same way as for the
|
||||
// other maps in the config.
|
||||
var colors map[string]string
|
||||
if err := node.Decode(&colors); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
patterns := make(ColorPatterns, 0, len(colors))
|
||||
for i := 0; i < len(node.Content)-1; i += 2 {
|
||||
var pattern string
|
||||
if err := node.Content[i].Decode(&pattern); err != nil {
|
||||
return err
|
||||
}
|
||||
patterns = append(patterns, ColorPattern{Pattern: pattern, Color: colors[pattern]})
|
||||
}
|
||||
|
||||
*p = patterns.over(*p)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p ColorPatterns) MarshalYAML() (any, error) {
|
||||
node := &yaml.Node{Kind: yaml.MappingNode}
|
||||
for _, pattern := range p {
|
||||
node.Content = append(node.Content,
|
||||
&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: pattern.Pattern},
|
||||
&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: pattern.Color},
|
||||
)
|
||||
}
|
||||
return node, nil
|
||||
}
|
||||
|
||||
// JSONSchema describes the patterns as the mapping they are written as.
|
||||
func (ColorPatterns) JSONSchema() *jsonschema.Schema {
|
||||
return &jsonschema.Schema{
|
||||
Type: "object",
|
||||
AdditionalProperties: &jsonschema.Schema{Type: "string"},
|
||||
}
|
||||
}
|
||||
|
||||
// over returns p followed by the patterns of lower that p doesn't have.
|
||||
func (p ColorPatterns) over(lower ColorPatterns) ColorPatterns {
|
||||
return slices.Concat(p, lo.Reject(lower, func(l ColorPattern, _ int) bool {
|
||||
return slices.ContainsFunc(p, func(c ColorPattern) bool { return c.Pattern == l.Pattern })
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type colorPatternsConfig struct {
|
||||
Patterns ColorPatterns `yaml:"patterns"`
|
||||
}
|
||||
|
||||
func TestColorPatternsKeepTheirOrder(t *testing.T) {
|
||||
var config colorPatternsConfig
|
||||
err := yaml.Unmarshal([]byte("patterns:\n"+
|
||||
" '^b': red\n"+
|
||||
" '^a': '#00ff00'\n"+
|
||||
" '^c': blue\n"), &config)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, ColorPatterns{
|
||||
{Pattern: "^b", Color: "red"},
|
||||
{Pattern: "^a", Color: "#00ff00"},
|
||||
{Pattern: "^c", Color: "blue"},
|
||||
}, config.Patterns)
|
||||
}
|
||||
|
||||
func TestColorPatternsOfALaterFileComeFirst(t *testing.T) {
|
||||
var config colorPatternsConfig
|
||||
err := yaml.Unmarshal([]byte("patterns:\n"+
|
||||
" '^a': red\n"+
|
||||
" '^b': green\n"), &config)
|
||||
assert.NoError(t, err)
|
||||
err = yaml.Unmarshal([]byte("patterns:\n"+
|
||||
" '^c': blue\n"+
|
||||
" '^b': yellow\n"), &config)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, ColorPatterns{
|
||||
{Pattern: "^c", Color: "blue"},
|
||||
{Pattern: "^b", Color: "yellow"},
|
||||
{Pattern: "^a", Color: "red"},
|
||||
}, config.Patterns)
|
||||
}
|
||||
|
||||
func TestColorPatternsMustBeAMapping(t *testing.T) {
|
||||
var config colorPatternsConfig
|
||||
err := yaml.Unmarshal([]byte("patterns: 5\n"), &config)
|
||||
assert.ErrorContains(t, err, "cannot unmarshal !!int `5` into map[string]string")
|
||||
}
|
||||
|
||||
func TestColorPatternsSurviveMarshalling(t *testing.T) {
|
||||
config := colorPatternsConfig{Patterns: ColorPatterns{
|
||||
{Pattern: "^b", Color: "red"},
|
||||
{Pattern: "^a", Color: "#00ff00"},
|
||||
{Pattern: "true", Color: "blue"},
|
||||
}}
|
||||
content, err := yaml.Marshal(config)
|
||||
assert.NoError(t, err)
|
||||
|
||||
var roundTripped colorPatternsConfig
|
||||
err = yaml.Unmarshal(content, &roundTripped)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, config, roundTripped)
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/i18n"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
@@ -60,18 +61,23 @@ func (self *DiffRendererConfigManager) GetDiffRendererType() DiffRendererType {
|
||||
return currentDiffRendererConfig.getType()
|
||||
}
|
||||
|
||||
func (self *DiffRendererConfigManager) GetStdinFilterCommand(width int) string {
|
||||
// DiffRendererValues are what the command of a diff renderer can refer to.
|
||||
type DiffRendererValues struct {
|
||||
// The width of the view that the diff is rendered into
|
||||
Width int
|
||||
// The number of lines of context around each hunk
|
||||
DiffContext uint64
|
||||
// Whether the terminal has a light background
|
||||
LightBackground bool
|
||||
}
|
||||
|
||||
func (self *DiffRendererConfigManager) GetStdinFilterCommand(values DiffRendererValues) (string, error) {
|
||||
currentDiffRendererConfig := self.currentDiffRendererConfig()
|
||||
if currentDiffRendererConfig == nil || currentDiffRendererConfig.getType() != DiffRendererType_StdinFilter {
|
||||
return ""
|
||||
return "", nil
|
||||
}
|
||||
|
||||
templateValues := map[string]string{
|
||||
"columnWidth": strconv.Itoa(width/2 - 6),
|
||||
}
|
||||
|
||||
commandTemplate := string(currentDiffRendererConfig.Command)
|
||||
return utils.ResolvePlaceholderString(commandTemplate, templateValues)
|
||||
return currentDiffRendererConfig.resolveCommand(values)
|
||||
}
|
||||
|
||||
func (self *DiffRendererConfigManager) GetColorArg() string {
|
||||
@@ -87,17 +93,46 @@ func (self *DiffRendererConfigManager) GetColorArg() string {
|
||||
return colorArg
|
||||
}
|
||||
|
||||
func (self *DiffRendererConfigManager) GetExternalDiffCommand(diffContext uint64) string {
|
||||
func (self *DiffRendererConfigManager) GetExternalDiffCommand(values DiffRendererValues) (string, error) {
|
||||
currentDiffRendererConfig := self.currentDiffRendererConfig()
|
||||
if currentDiffRendererConfig == nil || currentDiffRendererConfig.getType() != DiffRendererType_ExtDiff {
|
||||
return ""
|
||||
return "", nil
|
||||
}
|
||||
|
||||
templateValues := map[string]string{
|
||||
"diffContext": strconv.Itoa(int(diffContext)),
|
||||
return currentDiffRendererConfig.resolveCommand(values)
|
||||
}
|
||||
|
||||
// resolveCommand resolves the renderer's command, which is a Go template with
|
||||
// the values it can refer to as its variables. A variable can be written with
|
||||
// or without the leading dot, as in {{.width}} or {{width}}.
|
||||
func (self *DiffRendererConfig) resolveCommand(values DiffRendererValues) (string, error) {
|
||||
colorScheme := "dark"
|
||||
if values.LightBackground {
|
||||
colorScheme = "light"
|
||||
}
|
||||
variables := map[string]any{
|
||||
"width": values.Width,
|
||||
"colorScheme": colorScheme,
|
||||
}
|
||||
switch self.getType() {
|
||||
case DiffRendererType_StdinFilter:
|
||||
variables["columnWidth"] = values.Width/2 - 6
|
||||
case DiffRendererType_ExtDiff:
|
||||
variables["diffContext"] = values.DiffContext
|
||||
case DiffRendererType_RawGit:
|
||||
// has no command
|
||||
}
|
||||
|
||||
return utils.ResolvePlaceholderString(string(currentDiffRendererConfig.Command), templateValues)
|
||||
funcs := template.FuncMap{}
|
||||
for name, value := range variables {
|
||||
funcs[name] = func() any { return value }
|
||||
}
|
||||
|
||||
command, err := utils.ResolveTemplate(string(self.Command), variables, funcs)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("git.diffRenderers: can't use the command '%s': %w", self.Command, err)
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
func (self *DiffRendererConfigManager) GetRawGitArgs() []string {
|
||||
|
||||
@@ -63,6 +63,158 @@ func TestCurrentDiffRendererName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetStdinFilterCommand(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
diffRendererConfig DiffRendererConfig
|
||||
width int
|
||||
lightBackground bool
|
||||
expected string
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "a command without template variables is passed through",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --paging=never"},
|
||||
width: 120,
|
||||
expected: "delta --paging=never",
|
||||
},
|
||||
{
|
||||
name: "the width the diff is rendered at",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --width={{width}}"},
|
||||
width: 120,
|
||||
expected: "delta --width=120",
|
||||
},
|
||||
{
|
||||
name: "the width of one side of a side-by-side rendering",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "ydiff -p cat -w {{columnWidth}}"},
|
||||
width: 120,
|
||||
expected: "ydiff -p cat -w 54",
|
||||
},
|
||||
{
|
||||
name: "a template variable can also be written with a leading dot",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --width={{.width}}"},
|
||||
width: 120,
|
||||
expected: "delta --width=120",
|
||||
},
|
||||
{
|
||||
name: "the color scheme on a dark background",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --{{colorScheme}}"},
|
||||
width: 120,
|
||||
expected: "delta --dark",
|
||||
},
|
||||
{
|
||||
name: "the color scheme on a light background",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --{{colorScheme}}"},
|
||||
width: 120,
|
||||
lightBackground: true,
|
||||
expected: "delta --light",
|
||||
},
|
||||
{
|
||||
name: "the command can choose between options by the color scheme",
|
||||
diffRendererConfig: DiffRendererConfig{Command: `delta --syntax-theme={{if eq .colorScheme "light"}}GitHub{{else}}Dracula{{end}}`},
|
||||
width: 120,
|
||||
lightBackground: true,
|
||||
expected: "delta --syntax-theme=GitHub",
|
||||
},
|
||||
{
|
||||
name: "the command can use template expressions",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta{{if gt .width 100}} --side-by-side{{end}}"},
|
||||
width: 120,
|
||||
expected: "delta --side-by-side",
|
||||
},
|
||||
{
|
||||
name: "an unknown template variable is an error",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --width={{.widht}}"},
|
||||
width: 120,
|
||||
expectedError: "can't use the command 'delta --width={{.widht}}'",
|
||||
},
|
||||
{
|
||||
name: "an unknown template variable without a leading dot is an error too",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --width={{widht}}"},
|
||||
width: 120,
|
||||
expectedError: "can't use the command 'delta --width={{widht}}'",
|
||||
},
|
||||
{
|
||||
name: "nothing is returned for a renderer of another type",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --width={{width}}"},
|
||||
width: 120,
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
userConfig := &UserConfig{}
|
||||
userConfig.Git.DiffRenderers = []DiffRendererConfig{s.diffRendererConfig}
|
||||
config := NewDiffRendererConfigManager(func() *UserConfig { return userConfig })
|
||||
|
||||
command, err := config.GetStdinFilterCommand(DiffRendererValues{Width: s.width, LightBackground: s.lightBackground})
|
||||
if s.expectedError != "" {
|
||||
assert.ErrorContains(t, err, s.expectedError)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, s.expected, command)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalDiffCommand(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
diffRendererConfig DiffRendererConfig
|
||||
expected string
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "a command without template variables is passed through",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --color=always"},
|
||||
expected: "difft --color=always",
|
||||
},
|
||||
{
|
||||
name: "the width the diff is rendered at",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --width={{width}}"},
|
||||
expected: "difft --width=120",
|
||||
},
|
||||
{
|
||||
name: "the color scheme",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --background={{colorScheme}}"},
|
||||
expected: "difft --background=dark",
|
||||
},
|
||||
{
|
||||
name: "the width alongside the diff context size",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --width={{width}} --context={{diffContext}}"},
|
||||
expected: "difft --width=120 --context=3",
|
||||
},
|
||||
{
|
||||
name: "a variable of stdin filters is an error",
|
||||
diffRendererConfig: DiffRendererConfig{Type: "extDiff", Command: "difft --width={{columnWidth}}"},
|
||||
expectedError: "can't use the command 'difft --width={{columnWidth}}'",
|
||||
},
|
||||
{
|
||||
name: "nothing is returned for a renderer of another type",
|
||||
diffRendererConfig: DiffRendererConfig{Command: "delta --width={{width}}"},
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
userConfig := &UserConfig{}
|
||||
userConfig.Git.DiffRenderers = []DiffRendererConfig{s.diffRendererConfig}
|
||||
config := NewDiffRendererConfigManager(func() *UserConfig { return userConfig })
|
||||
|
||||
command, err := config.GetExternalDiffCommand(DiffRendererValues{Width: 120, DiffContext: 3})
|
||||
if s.expectedError != "" {
|
||||
assert.ErrorContains(t, err, s.expectedError)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, s.expected, command)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentDiffRendererNameWithoutDiffRenderers(t *testing.T) {
|
||||
config := NewDiffRendererConfigManager(func() *UserConfig { return &UserConfig{} })
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// ThemeForBackground returns gui.theme with the overrides for a dark or a light
|
||||
// background applied, and with the defaults for that background in the fields
|
||||
// that neither of them sets. backgroundColor is the terminal's background color
|
||||
// as #rrggbb, or empty if we don't know it.
|
||||
func (c *GuiConfig) ThemeForBackground(lightBackground bool, backgroundColor string) ThemeConfig {
|
||||
override := lo.Ternary(lightBackground, c.LightTheme, c.DarkTheme)
|
||||
return mergeThemes(override, c.Theme, themeDefaults(lightBackground, backgroundColor))
|
||||
}
|
||||
|
||||
// themeDefaults returns the defaults of the theme fields whose default depends
|
||||
// on the terminal's background. GetDefaultConfig leaves these fields empty in
|
||||
// gui.theme, so that a value there comes from the user, and wins over these.
|
||||
//
|
||||
// Most of them are derived from the background color, so that they keep the
|
||||
// same distance from it however dark or light it is. If we don't know the
|
||||
// background color, we assume black or white.
|
||||
func themeDefaults(lightBackground bool, backgroundColor string) ThemeConfig {
|
||||
if len(backgroundColor) != 7 || !utils.IsValidHexValue(backgroundColor) {
|
||||
backgroundColor = lo.Ternary(lightBackground, "#ffffff", "#000000")
|
||||
}
|
||||
|
||||
if lightBackground {
|
||||
return ThemeConfig{
|
||||
// The colors of a light palette are dark enough to read as text on
|
||||
// the background, so none of them works as a background for text.
|
||||
// Some blue mixed into the background keeps the colored text on the
|
||||
// selected line as readable as elsewhere.
|
||||
SelectedLineBgColor: []string{mixHexColors(backgroundColor, "#0064ff", 0.25)},
|
||||
InactiveViewSelectedLineBgColor: []string{mixHexColors(backgroundColor, "#000000", 0.15)},
|
||||
}
|
||||
}
|
||||
|
||||
return ThemeConfig{
|
||||
// Dark palettes make their blue dark enough to work as a background for
|
||||
// text. Unlike a color derived from a dark background, it doesn't turn
|
||||
// into black on terminals with only 8 colors.
|
||||
SelectedLineBgColor: []string{"blue"},
|
||||
InactiveViewSelectedLineBgColor: []string{mixHexColors(backgroundColor, "#ffffff", 0.3)},
|
||||
}
|
||||
}
|
||||
|
||||
// mixHexColors mixes two colors given as #rrggbb. amount is how much of b to
|
||||
// take: 0 gives a, 1 gives b.
|
||||
func mixHexColors(a, b string, amount float64) string {
|
||||
channel := func(color string, i int) float64 {
|
||||
value, _ := strconv.ParseUint(color[1+2*i:3+2*i], 16, 8)
|
||||
return float64(value)
|
||||
}
|
||||
|
||||
result := "#"
|
||||
for i := range 3 {
|
||||
mixed := channel(a, i) + (channel(b, i)-channel(a, i))*amount
|
||||
result += fmt.Sprintf("%02x", int(math.Round(mixed)))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// mergeThemes takes each field from the first of the themes that sets it. For
|
||||
// maps and color patterns it merges the entries instead, and an entry of an
|
||||
// earlier theme wins over one with the same key in a later theme.
|
||||
func mergeThemes(themes ...ThemeConfig) ThemeConfig {
|
||||
var result ThemeConfig
|
||||
resultValue := reflect.ValueOf(&result).Elem()
|
||||
for i := range resultValue.NumField() {
|
||||
values := lo.Map(themes, func(theme ThemeConfig, _ int) any {
|
||||
return reflect.ValueOf(theme).Field(i).Interface()
|
||||
})
|
||||
resultValue.Field(i).Set(reflect.ValueOf(mergeThemeField(values)))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func mergeThemeField(values []any) any {
|
||||
switch values[0].(type) {
|
||||
case []string:
|
||||
return lo.FindOrElse(lo.Map(values, func(v any, _ int) []string { return v.([]string) }), nil,
|
||||
func(v []string) bool { return len(v) > 0 })
|
||||
case map[string]string:
|
||||
merged := map[string]string{}
|
||||
for _, v := range slices.Backward(values) {
|
||||
maps.Copy(merged, v.(map[string]string))
|
||||
}
|
||||
return merged
|
||||
case ColorPatterns:
|
||||
return lo.Reduce(values, func(merged ColorPatterns, v any, _ int) ColorPatterns {
|
||||
return merged.over(v.(ColorPatterns))
|
||||
}, nil)
|
||||
default:
|
||||
panic(fmt.Sprintf("don't know how to merge a theme field of type %T", values[0]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestThemeForBackground(t *testing.T) {
|
||||
gui := GuiConfig{
|
||||
Theme: ThemeConfig{
|
||||
ActiveBorderColor: []string{"green"},
|
||||
InactiveBorderColor: []string{"default"},
|
||||
AuthorColors: map[string]string{"Alice": "red", "Bob": "blue"},
|
||||
BranchColorPatterns: ColorPatterns{
|
||||
{Pattern: "^docs/", Color: "cyan"},
|
||||
{Pattern: "^feature/", Color: "green"},
|
||||
},
|
||||
},
|
||||
DarkTheme: ThemeConfig{
|
||||
ActiveBorderColor: []string{"yellow"},
|
||||
},
|
||||
LightTheme: ThemeConfig{
|
||||
InactiveBorderColor: []string{"#777777"},
|
||||
AuthorColors: map[string]string{"Bob": "#000080"},
|
||||
BranchColorPatterns: ColorPatterns{
|
||||
{Pattern: "ISSUE", Color: "red"},
|
||||
{Pattern: "^docs/", Color: "#008080"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
dark := gui.ThemeForBackground(false, "")
|
||||
assert.Equal(t, []string{"yellow"}, dark.ActiveBorderColor)
|
||||
assert.Equal(t, []string{"default"}, dark.InactiveBorderColor)
|
||||
assert.Equal(t, map[string]string{"Alice": "red", "Bob": "blue"}, dark.AuthorColors)
|
||||
assert.Equal(t, gui.Theme.BranchColorPatterns, dark.BranchColorPatterns)
|
||||
|
||||
light := gui.ThemeForBackground(true, "")
|
||||
assert.Equal(t, []string{"green"}, light.ActiveBorderColor)
|
||||
assert.Equal(t, []string{"#777777"}, light.InactiveBorderColor)
|
||||
assert.Equal(t, map[string]string{"Alice": "red", "Bob": "#000080"}, light.AuthorColors)
|
||||
assert.Equal(t, ColorPatterns{
|
||||
{Pattern: "ISSUE", Color: "red"},
|
||||
{Pattern: "^docs/", Color: "#008080"},
|
||||
{Pattern: "^feature/", Color: "green"},
|
||||
}, light.BranchColorPatterns)
|
||||
|
||||
assert.Equal(t, map[string]string{"Alice": "red", "Bob": "blue"}, gui.Theme.AuthorColors,
|
||||
"merging must leave the themes it merges alone")
|
||||
}
|
||||
|
||||
func TestEveryThemeFieldCanBeOverridden(t *testing.T) {
|
||||
var override ThemeConfig
|
||||
overrideValue := reflect.ValueOf(&override).Elem()
|
||||
for i := range overrideValue.NumField() {
|
||||
field := overrideValue.Field(i)
|
||||
switch field.Interface().(type) {
|
||||
case []string:
|
||||
field.Set(reflect.ValueOf([]string{"#123456"}))
|
||||
case map[string]string:
|
||||
field.Set(reflect.ValueOf(map[string]string{"key": "#123456"}))
|
||||
case ColorPatterns:
|
||||
field.Set(reflect.ValueOf(ColorPatterns{{Pattern: "key", Color: "#123456"}}))
|
||||
default:
|
||||
t.Fatalf("no test value for theme field %s", overrideValue.Type().Field(i).Name)
|
||||
}
|
||||
}
|
||||
|
||||
gui := GetDefaultConfig().Gui
|
||||
gui.DarkTheme = override
|
||||
assert.Equal(t, override, gui.ThemeForBackground(false, ""))
|
||||
}
|
||||
|
||||
func TestThemeForBackgroundFallsBackToTheDefaultsForTheBackground(t *testing.T) {
|
||||
gui := GetDefaultConfig().Gui
|
||||
assert.Equal(t, []string{"#4d4d4d"}, gui.ThemeForBackground(false, "").InactiveViewSelectedLineBgColor)
|
||||
assert.Equal(t, []string{"#d9d9d9"}, gui.ThemeForBackground(true, "").InactiveViewSelectedLineBgColor)
|
||||
|
||||
gui.Theme.InactiveViewSelectedLineBgColor = []string{"bold"}
|
||||
assert.Equal(t, []string{"bold"}, gui.ThemeForBackground(false, "").InactiveViewSelectedLineBgColor)
|
||||
assert.Equal(t, []string{"bold"}, gui.ThemeForBackground(true, "").InactiveViewSelectedLineBgColor)
|
||||
|
||||
gui.LightTheme.InactiveViewSelectedLineBgColor = []string{"white"}
|
||||
assert.Equal(t, []string{"bold"}, gui.ThemeForBackground(false, "").InactiveViewSelectedLineBgColor)
|
||||
assert.Equal(t, []string{"white"}, gui.ThemeForBackground(true, "").InactiveViewSelectedLineBgColor)
|
||||
}
|
||||
|
||||
func TestBackgroundDefaultsAreDerivedFromTheBackgroundColor(t *testing.T) {
|
||||
gui := GetDefaultConfig().Gui
|
||||
assert.Equal(t, []string{"#626262"}, gui.ThemeForBackground(false, "#1e1e1e").InactiveViewSelectedLineBgColor)
|
||||
assert.Equal(t, []string{"#d7d1c1"}, gui.ThemeForBackground(true, "#fdf6e3").InactiveViewSelectedLineBgColor)
|
||||
|
||||
assert.Equal(t, []string{"blue"}, gui.ThemeForBackground(false, "#1e1e1e").SelectedLineBgColor)
|
||||
assert.Equal(t, []string{"#bed2ea"}, gui.ThemeForBackground(true, "#fdf6e3").SelectedLineBgColor)
|
||||
assert.Equal(t, []string{"#bfd8ff"}, gui.ThemeForBackground(true, "").SelectedLineBgColor)
|
||||
}
|
||||
|
||||
// If gui.theme had a default for a field that also has a default for the
|
||||
// terminal's background, the former would always win.
|
||||
func TestFieldsWithBackgroundDefaultsHaveNoDefaultInGuiTheme(t *testing.T) {
|
||||
genericDefaults := setThemeFields(GetDefaultConfig().Gui.Theme)
|
||||
for _, field := range setThemeFields(themeDefaults(false, "")) {
|
||||
assert.NotContains(t, genericDefaults, field)
|
||||
}
|
||||
for _, field := range setThemeFields(themeDefaults(true, "")) {
|
||||
assert.NotContains(t, genericDefaults, field)
|
||||
}
|
||||
}
|
||||
|
||||
// If only one of the backgrounds had a default for a field, the field would
|
||||
// have no value at all with the other.
|
||||
func TestDarkAndLightDefaultsSetTheSameFields(t *testing.T) {
|
||||
assert.Equal(t, setThemeFields(themeDefaults(false, "")), setThemeFields(themeDefaults(true, "")))
|
||||
}
|
||||
|
||||
func setThemeFields(theme ThemeConfig) []string {
|
||||
var fields []string
|
||||
themeValue := reflect.ValueOf(theme)
|
||||
for i := range themeValue.NumField() {
|
||||
if themeValue.Field(i).Len() > 0 {
|
||||
fields = append(fields, themeValue.Type().Field(i).Name)
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
+32
-20
@@ -68,13 +68,6 @@ func (c *RefresherConfig) ExternalChangeCheckIntervalDuration() time.Duration {
|
||||
}
|
||||
|
||||
type GuiConfig struct {
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-author-color
|
||||
AuthorColors map[string]string `yaml:"authorColors"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color
|
||||
// Deprecated: use branchColorPatterns instead
|
||||
BranchColors map[string]string `yaml:"branchColors" jsonschema:"deprecated"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color
|
||||
BranchColorPatterns map[string]string `yaml:"branchColorPatterns"`
|
||||
// Custom icons for filenames and file extensions
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-files-icon--color
|
||||
CustomIcons CustomIconsConfig `yaml:"customIcons"`
|
||||
@@ -141,9 +134,19 @@ type GuiConfig struct {
|
||||
// Format used when displaying time if the time is less than 24 hours ago.
|
||||
// Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
|
||||
ShortTimeFormat string `yaml:"shortTimeFormat"`
|
||||
// Whether the terminal has a dark or a light background. This decides whether 'darkTheme' or 'lightTheme' applies, and the colors of authors are picked to stand out against it.
|
||||
// One of: 'auto' (default) | 'dark' | 'light'
|
||||
// With 'auto', lazygit asks the terminal, and assumes a dark background if the terminal doesn't tell.
|
||||
ColorScheme string `yaml:"colorScheme" jsonschema:"enum=auto,enum=dark,enum=light"`
|
||||
// Config relating to colors and styles.
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes
|
||||
Theme ThemeConfig `yaml:"theme"`
|
||||
// Colors and styles that override those in 'theme' when the terminal has a dark background. It has the same fields as 'theme'.
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#themes-for-dark-and-light-backgrounds
|
||||
DarkTheme ThemeConfig `yaml:"darkTheme"`
|
||||
// Colors and styles that override those in 'theme' when the terminal has a light background. It has the same fields as 'theme'.
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#themes-for-dark-and-light-backgrounds
|
||||
LightTheme ThemeConfig `yaml:"lightTheme"`
|
||||
// Config relating to the commit length indicator
|
||||
CommitLength CommitLengthConfig `yaml:"commitLength"`
|
||||
// If true, show the '5 of 20' footer at the bottom of list views
|
||||
@@ -237,10 +240,15 @@ type ThemeConfig struct {
|
||||
SearchingActiveBorderColor []string `yaml:"searchingActiveBorderColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Color of keybindings help text in the bottom line
|
||||
OptionsTextColor []string `yaml:"optionsTextColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Color and attributes of the text of the selected line. The attributes are added to those of the text, and a color replaces the colors of the text.
|
||||
// Set it to 'default' to leave the text as it is, e.g. if you don't want the selected line in bold.
|
||||
SelectedLineFgColor []string `yaml:"selectedLineFgColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Background color of selected line.
|
||||
// Default: 'blue' if the terminal has a dark background, or a suitable RGB blue computed from the background color if it is light.
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line
|
||||
SelectedLineBgColor []string `yaml:"selectedLineBgColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Background color of selected line when view doesn't have focus.
|
||||
// Default: a suitable RGB grey computed from the terminal's background color.
|
||||
InactiveViewSelectedLineBgColor []string `yaml:"inactiveViewSelectedLineBgColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Foreground color of copied commit
|
||||
CherryPickedCommitFgColor []string `yaml:"cherryPickedCommitFgColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
@@ -254,6 +262,10 @@ type ThemeConfig struct {
|
||||
UnstagedChangesColor []string `yaml:"unstagedChangesColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// Default text color
|
||||
DefaultFgColor []string `yaml:"defaultFgColor" jsonschema:"minItems=1,uniqueItems=true"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-author-color
|
||||
AuthorColors map[string]string `yaml:"authorColors"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-branch-color
|
||||
BranchColorPatterns ColorPatterns `yaml:"branchColorPatterns"`
|
||||
}
|
||||
|
||||
type CommitLengthConfig struct {
|
||||
@@ -316,7 +328,7 @@ type GitConfig struct {
|
||||
AutoRefresh bool `yaml:"autoRefresh"`
|
||||
// If true, poll the repo periodically for external ref changes (commits, branch updates, checkouts made outside lazygit) and refresh when one is detected. Independent of autoRefresh, which only governs the files panel.
|
||||
AutoDetectExternalChanges bool `yaml:"autoDetectExternalChanges"`
|
||||
// If not "none", lazygit will automatically fast-forward local branches to match their upstream after fetching. Applies to branches that are not the currently checked out branch, and only to those that are strictly behind their upstream (as opposed to diverged).
|
||||
// If not "none", lazygit will automatically fast-forward local branches to match their upstream after fetching. Applies to branches that are not the currently checked out branch, and only to those that are strictly behind their upstream (as opposed to diverged). A branch that is checked out in another worktree is fast-forwarded there, unless that worktree has changes to tracked files or is in the middle of a rebase or bisect.
|
||||
// Possible values: 'none' | 'onlyMainBranches' | 'allBranches'
|
||||
AutoForwardBranches string `yaml:"autoForwardBranches" jsonschema:"enum=none,enum=onlyMainBranches,enum=allBranches"`
|
||||
// If true, pass the --all arg to git fetch
|
||||
@@ -881,19 +893,19 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig {
|
||||
Language: "auto",
|
||||
TimeFormat: "02 Jan 06",
|
||||
ShortTimeFormat: time.Kitchen,
|
||||
ColorScheme: "auto",
|
||||
Theme: ThemeConfig{
|
||||
ActiveBorderColor: []string{"green", "bold"},
|
||||
SearchingActiveBorderColor: []string{"cyan", "bold"},
|
||||
InactiveBorderColor: []string{"default"},
|
||||
OptionsTextColor: []string{"blue"},
|
||||
SelectedLineBgColor: []string{"blue"},
|
||||
InactiveViewSelectedLineBgColor: []string{"bold"},
|
||||
CherryPickedCommitBgColor: []string{"cyan"},
|
||||
CherryPickedCommitFgColor: []string{"blue"},
|
||||
MarkedBaseCommitBgColor: []string{"yellow"},
|
||||
MarkedBaseCommitFgColor: []string{"blue"},
|
||||
UnstagedChangesColor: []string{"red"},
|
||||
DefaultFgColor: []string{"default"},
|
||||
ActiveBorderColor: []string{"green", "bold"},
|
||||
SearchingActiveBorderColor: []string{"cyan", "bold"},
|
||||
InactiveBorderColor: []string{"default"},
|
||||
OptionsTextColor: []string{"blue"},
|
||||
SelectedLineFgColor: []string{"bold"},
|
||||
CherryPickedCommitBgColor: []string{"cyan"},
|
||||
CherryPickedCommitFgColor: []string{"blue"},
|
||||
MarkedBaseCommitBgColor: []string{"yellow"},
|
||||
MarkedBaseCommitFgColor: []string{"blue"},
|
||||
UnstagedChangesColor: []string{"red"},
|
||||
DefaultFgColor: []string{"default"},
|
||||
},
|
||||
CommitLength: CommitLengthConfig{Show: true},
|
||||
SkipNoStagedFilesWarning: false,
|
||||
|
||||
@@ -18,6 +18,10 @@ func (config *UserConfig) Validate() error {
|
||||
[]string{"dashboard", "allBranchesLog"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateEnum("gui.colorScheme", config.Gui.ColorScheme,
|
||||
[]string{"auto", "dark", "light"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateEnum("gui.showDivergenceFromBaseBranch", config.Gui.ShowDivergenceFromBaseBranch,
|
||||
[]string{"none", "onlyArrow", "arrowAndNumber"}); err != nil {
|
||||
return err
|
||||
@@ -120,10 +124,16 @@ func validateDiffRenderers(diffRenderers []DiffRendererConfig) error {
|
||||
if len(diffRenderer.Args) > 0 {
|
||||
return errors.New("git.diffRenderers: 'args' cannot be used with diff renderer type 'stdinFilter'.")
|
||||
}
|
||||
if err := validateDiffRendererCommand(diffRenderer); err != nil {
|
||||
return err
|
||||
}
|
||||
case "extDiff":
|
||||
if len(diffRenderer.Args) > 0 {
|
||||
return errors.New("git.diffRenderers: 'args' cannot be used with diff renderer type 'extDiff'.")
|
||||
}
|
||||
if err := validateDiffRendererCommand(diffRenderer); err != nil {
|
||||
return err
|
||||
}
|
||||
case "rawGit":
|
||||
if diffRenderer.Command != "" {
|
||||
return errors.New("git.diffRenderers: 'command' cannot be used with diff renderer type 'rawGit'.")
|
||||
@@ -135,6 +145,14 @@ func validateDiffRenderers(diffRenderers []DiffRendererConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateDiffRendererCommand resolves the command with made-up values, so that
|
||||
// a mistake in it shows up when the config is loaded rather than when a diff
|
||||
// is rendered.
|
||||
func validateDiffRendererCommand(diffRenderer DiffRendererConfig) error {
|
||||
_, err := diffRenderer.resolveCommand(DiffRendererValues{Width: 80, DiffContext: 3})
|
||||
return err
|
||||
}
|
||||
|
||||
func validateEnum(name string, value string, allowedValues []string) error {
|
||||
if slices.Contains(allowedValues, value) {
|
||||
return nil
|
||||
|
||||
@@ -409,9 +409,14 @@ func TestUserConfigValidate_diffRenderers(t *testing.T) {
|
||||
{name: "stdinFilter with explicit type", diffRenderer: DiffRendererConfig{Type: "stdinFilter"}, valid: false},
|
||||
{name: "stdinFilter with type default without command", diffRenderer: DiffRendererConfig{}, valid: false},
|
||||
{name: "stdinFilter with args", diffRenderer: DiffRendererConfig{Type: "stdinFilter", Command: "delta", Args: []string{"-x"}}, valid: false},
|
||||
{name: "stdinFilter with a template", diffRenderer: DiffRendererConfig{Command: "delta --width={{width}}{{if gt .width 100}} --side-by-side{{end}}"}, valid: true},
|
||||
{name: "stdinFilter with an unknown template variable", diffRenderer: DiffRendererConfig{Command: "delta --width={{.widht}}"}, valid: false},
|
||||
{name: "stdinFilter with a broken template", diffRenderer: DiffRendererConfig{Command: "delta {{if .width}}"}, valid: false},
|
||||
{name: "external diff", diffRenderer: DiffRendererConfig{Type: "extDiff", Command: "difft"}, valid: true},
|
||||
{name: "external diff without command", diffRenderer: DiffRendererConfig{Type: "extDiff"}, valid: true},
|
||||
{name: "external diff with args", diffRenderer: DiffRendererConfig{Type: "extDiff", Command: "difft", Args: []string{"-x"}}, valid: false},
|
||||
{name: "external diff with a template", diffRenderer: DiffRendererConfig{Type: "extDiff", Command: "difft --context={{diffContext}}"}, valid: true},
|
||||
{name: "external diff with a variable of stdin filters", diffRenderer: DiffRendererConfig{Type: "extDiff", Command: "difft --width={{columnWidth}}"}, valid: false},
|
||||
{name: "raw git", diffRenderer: DiffRendererConfig{Type: "rawGit"}, valid: true},
|
||||
{name: "raw git with args", diffRenderer: DiffRendererConfig{Type: "rawGit", Args: []string{"-x"}}, valid: true},
|
||||
{name: "raw git with command", diffRenderer: DiffRendererConfig{Type: "rawGit", Command: "delta"}, valid: false},
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
package gocui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gdamore/tcell/v3"
|
||||
"github.com/lucasb-eyer/go-colorful"
|
||||
)
|
||||
|
||||
// ColorScheme says whether the terminal shows light text on a dark background,
|
||||
// or dark text on a light one.
|
||||
type ColorScheme int
|
||||
|
||||
const (
|
||||
ColorSchemeUnknown ColorScheme = iota
|
||||
ColorSchemeDark
|
||||
ColorSchemeLight
|
||||
)
|
||||
|
||||
func (self ColorScheme) String() string {
|
||||
switch self {
|
||||
case ColorSchemeDark:
|
||||
return "dark"
|
||||
case ColorSchemeLight:
|
||||
return "light"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// DetectedColorScheme is what the terminal has told us about its colors.
|
||||
type DetectedColorScheme struct {
|
||||
ColorScheme ColorScheme
|
||||
// The background color that ColorScheme was derived from, as #rrggbb. It is
|
||||
// empty if the terminal didn't tell us its background color; ColorScheme is
|
||||
// then whatever the terminal said about itself, if anything.
|
||||
Background string
|
||||
}
|
||||
|
||||
func (self DetectedColorScheme) String() string {
|
||||
if self.Background != "" {
|
||||
return fmt.Sprintf("%s (background %s)", self.ColorScheme, self.Background)
|
||||
}
|
||||
if self.ColorScheme != ColorSchemeUnknown {
|
||||
return fmt.Sprintf("%s (reported by the terminal)", self.ColorScheme)
|
||||
}
|
||||
return self.ColorScheme.String()
|
||||
}
|
||||
|
||||
const (
|
||||
// Makes the terminal send a color scheme report whenever its colors change
|
||||
enableColorSchemeReports = "\x1b[?2031h"
|
||||
disableColorSchemeReports = "\x1b[?2031l"
|
||||
// Asks for a color scheme report: CSI ? 997 ; 1 n for dark, 2 for light
|
||||
requestColorScheme = "\x1b[?996n"
|
||||
// Asks for the background color: OSC 11 ; rgb:RRRR/GGGG/BBBB, ended by BEL
|
||||
// or ST. Ending the request with BEL makes more terminals reply.
|
||||
requestBackgroundColor = "\x1b]11;?\a"
|
||||
)
|
||||
|
||||
// colorSchemeTty is a tcell.Tty that finds out the terminal's color scheme.
|
||||
//
|
||||
// Some terminals say whether they are dark or light, and can report it again
|
||||
// whenever that changes. What they base this on varies, though: some go by the
|
||||
// terminal's own colors, others by the dark or light mode of the operating
|
||||
// system, whether or not the terminal follows it. So we also ask for the
|
||||
// background color, and when the terminal tells us that, it decides; a color
|
||||
// scheme report is then only a sign that the background may have changed.
|
||||
//
|
||||
// The queries go out when tcell starts the tty, which is before tcell sends its
|
||||
// own queries during Screen.Init and waits for their answer. Terminals answer in
|
||||
// order, so the answers to ours have arrived by the time Init returns, and we
|
||||
// know the color scheme before drawing anything without waiting for it.
|
||||
//
|
||||
// tcell doesn't understand the answers and drops them, so all we need to do is
|
||||
// watch for them in the input as it goes by.
|
||||
type colorSchemeTty struct {
|
||||
tcell.Tty
|
||||
|
||||
// What we send when the tty starts
|
||||
queries string
|
||||
|
||||
// Guards all of the fields below, and serializes our writes to the terminal
|
||||
// with tcell's
|
||||
mutex sync.Mutex
|
||||
|
||||
started bool
|
||||
|
||||
background colorful.Color
|
||||
// Whether the terminal has told us its background color
|
||||
haveBackground bool
|
||||
// Whether we have asked for the background color and are waiting for the
|
||||
// answer
|
||||
backgroundRequested bool
|
||||
// The color scheme that the terminal last reported for itself
|
||||
reported ColorScheme
|
||||
// Whether we have asked for a color scheme report and are waiting for it
|
||||
colorSchemeRequested bool
|
||||
// Closed once no answer that waitForReplies waits for is outstanding
|
||||
repliesArrived chan struct{}
|
||||
|
||||
notified DetectedColorScheme
|
||||
onChange func(DetectedColorScheme)
|
||||
|
||||
// Only used by Read, which tcell never calls concurrently with itself
|
||||
scanner terminalReplyScanner
|
||||
}
|
||||
|
||||
var _ tcell.Tty = &colorSchemeTty{}
|
||||
|
||||
func newColorSchemeTty(tty tcell.Tty) *colorSchemeTty {
|
||||
return &colorSchemeTty{
|
||||
Tty: tty,
|
||||
queries: colorSchemeQueries(
|
||||
os.Getenv("TERM"),
|
||||
os.Getenv("TERM_PROGRAM"),
|
||||
os.Getenv("TCELL_NEGOTIATE"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// colorSchemeQueries returns what to ask the terminal. It leaves out the
|
||||
// terminals that tcell doesn't send its own queries to (see
|
||||
// applyKnownTerminalProfile and the legacy terminals in tScreen.Init), except
|
||||
// for those that are known to answer a request for the background color.
|
||||
func colorSchemeQueries(term string, termProgram string, tcellNegotiate string) string {
|
||||
if tcellNegotiate == "disable" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if term == "st" || strings.HasPrefix(term, "st-") ||
|
||||
strings.HasPrefix(term, "vt") || strings.Contains(term, "ansi") ||
|
||||
term == "linux" || term == "sun" || term == "sun-color" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if termProgram == "Apple_Terminal" || termProgram == "WezTerm" {
|
||||
return requestBackgroundColor
|
||||
}
|
||||
|
||||
return enableColorSchemeReports + requestColorScheme + requestBackgroundColor
|
||||
}
|
||||
|
||||
// subscribe sets a function to call whenever the detected color scheme changes,
|
||||
// and returns the one detected so far. The function is called on the goroutine
|
||||
// that reads from the tty, so it must not block.
|
||||
func (self *colorSchemeTty) subscribe(onChange func(DetectedColorScheme)) DetectedColorScheme {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
self.onChange = onChange
|
||||
self.notified = self.detected()
|
||||
return self.notified
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) Start() error {
|
||||
if err := self.Tty.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
self.started = true
|
||||
self.writeLocked(self.queries)
|
||||
if strings.Contains(self.queries, requestBackgroundColor) {
|
||||
self.backgroundRequested = true
|
||||
}
|
||||
if strings.Contains(self.queries, requestColorScheme) {
|
||||
self.colorSchemeRequested = true
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitForReplies waits until the terminal has answered what we asked it, but
|
||||
// no longer than the timeout. Call it before handing the terminal to another
|
||||
// program, or the answers would reach that program as if they were typed. It
|
||||
// only waits for the answers that the terminal has given before, so a terminal
|
||||
// that doesn't answer at all costs no time.
|
||||
func (self *colorSchemeTty) waitForReplies(timeout time.Duration) {
|
||||
self.mutex.Lock()
|
||||
if !self.awaitingRepliesLocked() {
|
||||
self.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
if self.repliesArrived == nil {
|
||||
self.repliesArrived = make(chan struct{})
|
||||
}
|
||||
repliesArrived := self.repliesArrived
|
||||
self.mutex.Unlock()
|
||||
|
||||
select {
|
||||
case <-repliesArrived:
|
||||
case <-time.After(timeout):
|
||||
}
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) awaitingRepliesLocked() bool {
|
||||
return (self.backgroundRequested && self.haveBackground) ||
|
||||
(self.colorSchemeRequested && self.reported != ColorSchemeUnknown)
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) Stop() error {
|
||||
self.mutex.Lock()
|
||||
// Otherwise, the program we hand the terminal to would receive the reports
|
||||
// as if they were typed
|
||||
if strings.Contains(self.queries, enableColorSchemeReports) {
|
||||
self.writeLocked(disableColorSchemeReports)
|
||||
}
|
||||
self.started = false
|
||||
self.mutex.Unlock()
|
||||
|
||||
return self.Tty.Stop()
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) Write(p []byte) (int, error) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
return self.Tty.Write(p)
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) Read(p []byte) (int, error) {
|
||||
n, err := self.Tty.Read(p)
|
||||
|
||||
for _, reply := range self.scanner.scan(p[:n]) {
|
||||
self.handleReply(reply)
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
|
||||
// onFocusGained asks for the background color again, for the terminals that
|
||||
// tell us their background color but not when it changes. When the operating
|
||||
// system switches between dark and light mode, the user is usually busy
|
||||
// elsewhere, so coming back to the terminal is a good time to check.
|
||||
func (self *colorSchemeTty) onFocusGained() {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
self.requestBackgroundColorLocked()
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) handleReply(reply terminalReply) {
|
||||
self.mutex.Lock()
|
||||
|
||||
if reply.background != nil {
|
||||
self.background = *reply.background
|
||||
self.haveBackground = true
|
||||
self.backgroundRequested = false
|
||||
} else {
|
||||
self.reported = reply.colorScheme
|
||||
self.colorSchemeRequested = false
|
||||
self.requestBackgroundColorLocked()
|
||||
}
|
||||
|
||||
if self.repliesArrived != nil && !self.awaitingRepliesLocked() {
|
||||
close(self.repliesArrived)
|
||||
self.repliesArrived = nil
|
||||
}
|
||||
|
||||
detected := self.detected()
|
||||
onChange := self.onChange
|
||||
changed := detected != self.notified
|
||||
if changed {
|
||||
self.notified = detected
|
||||
}
|
||||
|
||||
self.mutex.Unlock()
|
||||
|
||||
if changed && onChange != nil {
|
||||
onChange(detected)
|
||||
}
|
||||
}
|
||||
|
||||
// requestBackgroundColorLocked asks for the background color, if the terminal
|
||||
// has told us its background color before and isn't about to do it anyway.
|
||||
func (self *colorSchemeTty) requestBackgroundColorLocked() {
|
||||
if !self.started || !self.haveBackground || self.backgroundRequested {
|
||||
return
|
||||
}
|
||||
|
||||
self.writeLocked(requestBackgroundColor)
|
||||
self.backgroundRequested = true
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) detected() DetectedColorScheme {
|
||||
if !self.haveBackground {
|
||||
return DetectedColorScheme{ColorScheme: self.reported}
|
||||
}
|
||||
|
||||
return DetectedColorScheme{
|
||||
ColorScheme: colorSchemeOfBackground(self.background),
|
||||
Background: self.background.Hex(),
|
||||
}
|
||||
}
|
||||
|
||||
func (self *colorSchemeTty) writeLocked(s string) {
|
||||
if s == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// If the terminal is gone, tcell finds out when it next writes or reads
|
||||
_, _ = self.Tty.Write([]byte(s))
|
||||
}
|
||||
|
||||
func colorSchemeOfBackground(background colorful.Color) ColorScheme {
|
||||
lightness, _, _ := background.Lab()
|
||||
if lightness < 0.5 {
|
||||
return ColorSchemeDark
|
||||
}
|
||||
return ColorSchemeLight
|
||||
}
|
||||
|
||||
// terminalReply is one of the answers that colorSchemeTty asks the terminal
|
||||
// for. Exactly one of its fields is set.
|
||||
type terminalReply struct {
|
||||
colorScheme ColorScheme
|
||||
background *colorful.Color
|
||||
}
|
||||
|
||||
type terminalReplyScannerState int
|
||||
|
||||
const (
|
||||
scanningText terminalReplyScannerState = iota
|
||||
scanningEscape
|
||||
scanningCsi
|
||||
scanningOsc
|
||||
scanningOscEscape
|
||||
)
|
||||
|
||||
// No reply we look for is longer than this; we don't look at longer sequences
|
||||
const maxTerminalReplyLength = 64
|
||||
|
||||
// terminalReplyScanner finds the terminal's answers to our color scheme queries
|
||||
// in its input. The input arrives in chunks, which may split an answer anywhere,
|
||||
// so the scanner keeps its state from one chunk to the next.
|
||||
type terminalReplyScanner struct {
|
||||
state terminalReplyScannerState
|
||||
sequence []byte
|
||||
oversized bool
|
||||
}
|
||||
|
||||
func (self *terminalReplyScanner) scan(input []byte) []terminalReply {
|
||||
var replies []terminalReply
|
||||
|
||||
for _, b := range input {
|
||||
switch self.state {
|
||||
case scanningText:
|
||||
if b == '\x1b' {
|
||||
self.state = scanningEscape
|
||||
}
|
||||
|
||||
case scanningEscape:
|
||||
self.scanEscape(b)
|
||||
|
||||
case scanningCsi:
|
||||
switch {
|
||||
case b == '\x1b':
|
||||
self.state = scanningEscape
|
||||
case b >= 0x20 && b <= 0x3f: // parameter and intermediate bytes
|
||||
self.appendToSequence(b)
|
||||
case b >= 0x40 && b <= 0x7e: // final byte
|
||||
self.state = scanningText
|
||||
if b == 'n' && !self.oversized {
|
||||
if colorScheme, ok := parseColorSchemeReport(string(self.sequence)); ok {
|
||||
replies = append(replies, terminalReply{colorScheme: colorScheme})
|
||||
}
|
||||
}
|
||||
default:
|
||||
self.state = scanningText
|
||||
}
|
||||
|
||||
case scanningOsc:
|
||||
switch b {
|
||||
case '\a':
|
||||
self.state = scanningText
|
||||
replies = self.appendOscReply(replies)
|
||||
case '\x1b':
|
||||
self.state = scanningOscEscape
|
||||
default:
|
||||
self.appendToSequence(b)
|
||||
}
|
||||
|
||||
case scanningOscEscape:
|
||||
if b == '\\' {
|
||||
self.state = scanningText
|
||||
replies = self.appendOscReply(replies)
|
||||
} else {
|
||||
// Not a string terminator, so a new escape sequence has begun and
|
||||
// the one before it was cut short
|
||||
self.scanEscape(b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return replies
|
||||
}
|
||||
|
||||
// scanEscape handles the byte after an ESC.
|
||||
func (self *terminalReplyScanner) scanEscape(b byte) {
|
||||
switch b {
|
||||
case '[':
|
||||
self.startSequence(scanningCsi)
|
||||
case ']':
|
||||
self.startSequence(scanningOsc)
|
||||
case '\x1b':
|
||||
self.state = scanningEscape
|
||||
default:
|
||||
self.state = scanningText
|
||||
}
|
||||
}
|
||||
|
||||
func (self *terminalReplyScanner) startSequence(state terminalReplyScannerState) {
|
||||
self.state = state
|
||||
self.sequence = self.sequence[:0]
|
||||
self.oversized = false
|
||||
}
|
||||
|
||||
func (self *terminalReplyScanner) appendToSequence(b byte) {
|
||||
if len(self.sequence) >= maxTerminalReplyLength {
|
||||
self.oversized = true
|
||||
return
|
||||
}
|
||||
self.sequence = append(self.sequence, b)
|
||||
}
|
||||
|
||||
func (self *terminalReplyScanner) appendOscReply(replies []terminalReply) []terminalReply {
|
||||
if self.oversized {
|
||||
return replies
|
||||
}
|
||||
|
||||
if background, ok := parseBackgroundColorReport(string(self.sequence)); ok {
|
||||
replies = append(replies, terminalReply{background: &background})
|
||||
}
|
||||
|
||||
return replies
|
||||
}
|
||||
|
||||
// parseColorSchemeReport parses the parameters of CSI ? 997 ; <n> n
|
||||
func parseColorSchemeReport(params string) (ColorScheme, bool) {
|
||||
switch params {
|
||||
case "?997;1":
|
||||
return ColorSchemeDark, true
|
||||
case "?997;2":
|
||||
return ColorSchemeLight, true
|
||||
default:
|
||||
return ColorSchemeUnknown, false
|
||||
}
|
||||
}
|
||||
|
||||
// parseBackgroundColorReport parses the content of OSC 11 ; rgb:R/G/B, where
|
||||
// each of R, G and B has from one to four hex digits. Some terminals send
|
||||
// rgba:R/G/B/A instead.
|
||||
func parseBackgroundColorReport(content string) (colorful.Color, bool) {
|
||||
spec, ok := strings.CutPrefix(content, "11;")
|
||||
if !ok {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
|
||||
var components []string
|
||||
if rgb, ok := strings.CutPrefix(spec, "rgb:"); ok {
|
||||
components = strings.Split(rgb, "/")
|
||||
if len(components) != 3 {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
} else if rgba, ok := strings.CutPrefix(spec, "rgba:"); ok {
|
||||
components = strings.Split(rgba, "/")
|
||||
if len(components) != 4 {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
} else {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
|
||||
values := [3]float64{}
|
||||
for i := range values {
|
||||
component := components[i]
|
||||
if len(component) < 1 || len(component) > 4 {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
value, err := strconv.ParseUint(component, 16, 16)
|
||||
if err != nil {
|
||||
return colorful.Color{}, false
|
||||
}
|
||||
maxValue := uint64(1)<<(4*len(component)) - 1
|
||||
values[i] = float64(value) / float64(maxValue)
|
||||
}
|
||||
|
||||
return colorful.Color{R: values[0], G: values[1], B: values[2]}, true
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package gocui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gdamore/tcell/v3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func describeReplies(replies []terminalReply) []string {
|
||||
result := []string{}
|
||||
for _, reply := range replies {
|
||||
if reply.background != nil {
|
||||
result = append(result, reply.background.Hex())
|
||||
} else {
|
||||
result = append(result, reply.colorScheme.String())
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestTerminalReplyScanner(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
input string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "dark report",
|
||||
input: "\x1b[?997;1n",
|
||||
expected: []string{"dark"},
|
||||
},
|
||||
{
|
||||
name: "light report",
|
||||
input: "\x1b[?997;2n",
|
||||
expected: []string{"light"},
|
||||
},
|
||||
{
|
||||
name: "background ended by ST",
|
||||
input: "\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\",
|
||||
expected: []string{"#1e1e1e"},
|
||||
},
|
||||
{
|
||||
name: "background ended by BEL",
|
||||
input: "\x1b]11;rgb:ffff/ffff/ffff\a",
|
||||
expected: []string{"#ffffff"},
|
||||
},
|
||||
{
|
||||
name: "background with two hex digits per component",
|
||||
input: "\x1b]11;rgb:fd/f6/e3\a",
|
||||
expected: []string{"#fdf6e3"},
|
||||
},
|
||||
{
|
||||
name: "background with one hex digit per component",
|
||||
input: "\x1b]11;rgb:f/0/f\a",
|
||||
expected: []string{"#ff00ff"},
|
||||
},
|
||||
{
|
||||
name: "background with alpha",
|
||||
input: "\x1b]11;rgba:0000/2b2b/3636/ffff\a",
|
||||
expected: []string{"#002b36"},
|
||||
},
|
||||
{
|
||||
name: "replies among other input",
|
||||
input: "j\x1b[?997;1n\x1b[A\x1b[<0;10;5M\x1b]11;rgb:0000/0000/0000\x1b\\\x1b[?62;22c",
|
||||
expected: []string{"dark", "#000000"},
|
||||
},
|
||||
{
|
||||
name: "other reports",
|
||||
input: "\x1b[?997;3n\x1b[0n\x1b[?996n\x1b]10;rgb:ffff/ffff/ffff\a\x1b]4;1;rgb:ffff/0000/0000\a",
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
name: "malformed backgrounds",
|
||||
input: "\x1b]11;rgb:zz/00/00\a\x1b]11;rgb:10/20\a\x1b]11;rgb:12345/0/0\a\x1b]11;rgb://\a\x1b]11;#ffffff\a",
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
name: "reply after a sequence that was cut short",
|
||||
input: "\x1b]11;rgb:\x1b[?997;2n\x1b[?99\x1b]11;rgb:00/00/00\a",
|
||||
expected: []string{"light", "#000000"},
|
||||
},
|
||||
{
|
||||
name: "reply after an oversized sequence",
|
||||
input: "\x1b]11;" + strings.Repeat("x", 100) + "\a\x1b[?" + strings.Repeat("9", 100) + "n\x1b[?997;1n",
|
||||
expected: []string{"dark"},
|
||||
},
|
||||
{
|
||||
name: "oversized sequence that starts like a reply",
|
||||
input: "\x1b]11;rgb:00/00/00" + strings.Repeat("x", 100) + "\a",
|
||||
expected: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
scanner := terminalReplyScanner{}
|
||||
assert.Equal(t, s.expected, describeReplies(scanner.scan([]byte(s.input))))
|
||||
})
|
||||
|
||||
t.Run(s.name+", split in two", func(t *testing.T) {
|
||||
for i := range len(s.input) {
|
||||
scanner := terminalReplyScanner{}
|
||||
replies := scanner.scan([]byte(s.input[:i]))
|
||||
replies = append(replies, scanner.scan([]byte(s.input[i:]))...)
|
||||
assert.Equal(t, s.expected, describeReplies(replies), "split at %d", i)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(s.name+", byte by byte", func(t *testing.T) {
|
||||
scanner := terminalReplyScanner{}
|
||||
replies := []terminalReply{}
|
||||
for i := range len(s.input) {
|
||||
replies = append(replies, scanner.scan([]byte{s.input[i]})...)
|
||||
}
|
||||
assert.Equal(t, s.expected, describeReplies(replies))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestColorSchemeQueries(t *testing.T) {
|
||||
allQueries := enableColorSchemeReports + requestColorScheme + requestBackgroundColor
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
term string
|
||||
termProgram string
|
||||
tcellNegotiate string
|
||||
expected string
|
||||
}{
|
||||
{name: "xterm", term: "xterm-256color", expected: allQueries},
|
||||
{name: "tmux", term: "tmux-256color", termProgram: "tmux", expected: allQueries},
|
||||
{name: "Terminal.app", term: "xterm-256color", termProgram: "Apple_Terminal", expected: requestBackgroundColor},
|
||||
{name: "WezTerm", term: "xterm-256color", termProgram: "WezTerm", expected: requestBackgroundColor},
|
||||
{name: "st", term: "st-256color", expected: ""},
|
||||
{name: "Linux console", term: "linux", expected: ""},
|
||||
{name: "VT100", term: "vt100", expected: ""},
|
||||
{name: "negotiation disabled", term: "xterm-256color", tcellNegotiate: "disable", expected: ""},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, colorSchemeQueries(s.term, s.termProgram, s.tcellNegotiate))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type fakeTty struct {
|
||||
input string
|
||||
written strings.Builder
|
||||
}
|
||||
|
||||
var _ tcell.Tty = &fakeTty{}
|
||||
|
||||
func (self *fakeTty) Start() error { return nil }
|
||||
func (self *fakeTty) Stop() error { return nil }
|
||||
func (self *fakeTty) Drain() error { return nil }
|
||||
func (self *fakeTty) NotifyResize(chan<- bool) {}
|
||||
func (self *fakeTty) WindowSize() (tcell.WindowSize, error) { return tcell.WindowSize{}, nil }
|
||||
func (self *fakeTty) Close() error { return nil }
|
||||
func (self *fakeTty) Write(p []byte) (int, error) { return self.written.Write(p) }
|
||||
func (self *fakeTty) Read(p []byte) (int, error) {
|
||||
n := copy(p, self.input)
|
||||
self.input = self.input[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (self *fakeTty) takeWritten() string {
|
||||
written := self.written.String()
|
||||
self.written.Reset()
|
||||
return written
|
||||
}
|
||||
|
||||
type colorSchemeTtyTest struct {
|
||||
fake *fakeTty
|
||||
tty *colorSchemeTty
|
||||
notifications []string
|
||||
}
|
||||
|
||||
func newColorSchemeTtyTest(termProgram string) *colorSchemeTtyTest {
|
||||
test := &colorSchemeTtyTest{fake: &fakeTty{}}
|
||||
test.tty = &colorSchemeTty{
|
||||
Tty: test.fake,
|
||||
queries: colorSchemeQueries("xterm-256color", termProgram, ""),
|
||||
}
|
||||
test.tty.subscribe(func(colorScheme DetectedColorScheme) {
|
||||
test.notifications = append(test.notifications, colorScheme.String())
|
||||
})
|
||||
return test
|
||||
}
|
||||
|
||||
// feed has the terminal send input, and has tcell read it
|
||||
func (self *colorSchemeTtyTest) feed(input string) {
|
||||
self.fake.input = input
|
||||
_, _ = self.tty.Read(make([]byte, 128))
|
||||
}
|
||||
|
||||
func (self *colorSchemeTtyTest) takeNotifications() []string {
|
||||
notifications := self.notifications
|
||||
self.notifications = nil
|
||||
return notifications
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyPrefersTheBackground(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
assert.Equal(t, enableColorSchemeReports+requestColorScheme+requestBackgroundColor, test.fake.takeWritten())
|
||||
|
||||
// The terminal says it's light, but its background is dark
|
||||
test.feed("\x1b[?997;2n")
|
||||
assert.Equal(t, []string{"light (reported by the terminal)"}, test.takeNotifications())
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "the background was asked for already")
|
||||
|
||||
test.feed("\x1b]11;rgb:1e1e/1e1e/1e1e\x1b\\\x1b[?62;22c")
|
||||
assert.Equal(t, []string{"dark (background #1e1e1e)"}, test.takeNotifications())
|
||||
assert.Equal(t, "", test.fake.takeWritten())
|
||||
|
||||
// A later report only makes us ask for the background again
|
||||
test.feed("\x1b[?997;2n")
|
||||
assert.Nil(t, test.takeNotifications())
|
||||
assert.Equal(t, requestBackgroundColor, test.fake.takeWritten())
|
||||
|
||||
test.feed("\x1b[?997;2n")
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "the background was asked for already")
|
||||
|
||||
test.feed("\x1b]11;rgb:ffff/ffff/ffff\x1b\\")
|
||||
assert.Equal(t, []string{"light (background #ffffff)"}, test.takeNotifications())
|
||||
|
||||
// The same background again is no change
|
||||
test.feed("\x1b[?997;2n")
|
||||
assert.Equal(t, requestBackgroundColor, test.fake.takeWritten())
|
||||
test.feed("\x1b]11;rgb:ffff/ffff/ffff\x1b\\")
|
||||
assert.Nil(t, test.takeNotifications())
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyWithoutBackground(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
test.fake.takeWritten()
|
||||
|
||||
test.feed("\x1b[?997;1n\x1b[?62;22c")
|
||||
assert.Equal(t, []string{"dark (reported by the terminal)"}, test.takeNotifications())
|
||||
|
||||
test.feed("\x1b[?997;2n")
|
||||
assert.Equal(t, []string{"light (reported by the terminal)"}, test.takeNotifications())
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "a terminal that didn't answer before isn't asked again")
|
||||
|
||||
test.tty.onFocusGained()
|
||||
assert.Equal(t, "", test.fake.takeWritten())
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyAsksAgainOnFocus(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("Apple_Terminal")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
assert.Equal(t, requestBackgroundColor, test.fake.takeWritten())
|
||||
|
||||
test.tty.onFocusGained()
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "the background was asked for already")
|
||||
|
||||
test.feed("\x1b]11;rgb:0000/0000/0000\a")
|
||||
assert.Equal(t, []string{"dark (background #000000)"}, test.takeNotifications())
|
||||
|
||||
test.tty.onFocusGained()
|
||||
assert.Equal(t, requestBackgroundColor, test.fake.takeWritten())
|
||||
test.tty.onFocusGained()
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "the background was asked for already")
|
||||
|
||||
test.feed("\x1b]11;rgb:ffff/ffff/ffff\a")
|
||||
assert.Equal(t, []string{"light (background #ffffff)"}, test.takeNotifications())
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyStopAndStart(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
test.fake.takeWritten()
|
||||
test.feed("\x1b[?997;1n\x1b]11;rgb:0000/0000/0000\a")
|
||||
|
||||
assert.NoError(t, test.tty.Stop())
|
||||
assert.Equal(t, disableColorSchemeReports, test.fake.takeWritten())
|
||||
|
||||
test.tty.onFocusGained()
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "nothing is written to a stopped tty")
|
||||
|
||||
// Anything may have changed while we were stopped, so ask again
|
||||
assert.NoError(t, test.tty.Start())
|
||||
assert.Equal(t, enableColorSchemeReports+requestColorScheme+requestBackgroundColor, test.fake.takeWritten())
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyStopWithoutReports(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("WezTerm")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
test.fake.takeWritten()
|
||||
|
||||
assert.NoError(t, test.tty.Stop())
|
||||
assert.Equal(t, "", test.fake.takeWritten(), "reports were never turned on")
|
||||
}
|
||||
|
||||
func TestColorSchemeOfBackground(t *testing.T) {
|
||||
for background, expected := range map[string]ColorScheme{
|
||||
"rgb:0000/0000/0000": ColorSchemeDark,
|
||||
"rgb:1e/1e/1e": ColorSchemeDark,
|
||||
"rgb:00/2b/36": ColorSchemeDark,
|
||||
"rgb:70/70/70": ColorSchemeDark,
|
||||
"rgb:80/80/80": ColorSchemeLight,
|
||||
"rgb:fd/f6/e3": ColorSchemeLight,
|
||||
"rgb:ff/ff/ff": ColorSchemeLight,
|
||||
} {
|
||||
color, ok := parseBackgroundColorReport("11;" + background)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, expected, colorSchemeOfBackground(color), background)
|
||||
}
|
||||
}
|
||||
|
||||
// startWaiting starts waiting for replies, with a timeout too long to matter
|
||||
func (self *colorSchemeTtyTest) startWaiting() <-chan struct{} {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
self.tty.waitForReplies(time.Minute)
|
||||
close(done)
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
func isClosed(ch <-chan struct{}) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func assertDoneWaiting(t *testing.T, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
assert.Eventually(t, func() bool { return isClosed(done) }, time.Second, time.Millisecond)
|
||||
}
|
||||
|
||||
func assertStillWaiting(t *testing.T, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
assert.Never(t, func() bool { return isClosed(done) }, 50*time.Millisecond, time.Millisecond)
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyWaitsForReplies(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
test.feed("\x1b[?997;1n\x1b]11;rgb:0000/0000/0000\a")
|
||||
assertDoneWaiting(t, test.startWaiting())
|
||||
|
||||
assert.NoError(t, test.tty.Stop())
|
||||
assert.NoError(t, test.tty.Start())
|
||||
|
||||
done := test.startWaiting()
|
||||
assertStillWaiting(t, done)
|
||||
test.feed("\x1b[?997;1n")
|
||||
assertStillWaiting(t, done)
|
||||
test.feed("\x1b]11;rgb:0000/0000/0000\a")
|
||||
assertDoneWaiting(t, done)
|
||||
|
||||
test.tty.onFocusGained()
|
||||
done = test.startWaiting()
|
||||
assertStillWaiting(t, done)
|
||||
test.feed("\x1b]11;rgb:0000/0000/0000\a")
|
||||
assertDoneWaiting(t, done)
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyGivesUpWaiting(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
assert.NoError(t, test.tty.Start())
|
||||
test.feed("\x1b[?997;1n\x1b]11;rgb:0000/0000/0000\a")
|
||||
test.tty.onFocusGained()
|
||||
|
||||
start := time.Now()
|
||||
test.tty.waitForReplies(20 * time.Millisecond)
|
||||
assert.GreaterOrEqual(t, time.Since(start), 20*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestColorSchemeTtyDoesntWaitForRepliesThatNeverCame(t *testing.T) {
|
||||
test := newColorSchemeTtyTest("")
|
||||
|
||||
// The terminal answers nothing
|
||||
assert.NoError(t, test.tty.Start())
|
||||
assertDoneWaiting(t, test.startWaiting())
|
||||
|
||||
// The terminal reports its color scheme, but not its background
|
||||
test.feed("\x1b[?997;1n\x1b[?62;22c")
|
||||
assert.NoError(t, test.tty.Stop())
|
||||
assert.NoError(t, test.tty.Start())
|
||||
|
||||
done := test.startWaiting()
|
||||
assertStillWaiting(t, done)
|
||||
test.feed("\x1b[?997;1n")
|
||||
assertDoneWaiting(t, done)
|
||||
}
|
||||
@@ -41,6 +41,7 @@ func SimpleEditor(v *View, key Key) bool {
|
||||
key.Equals(NewKeyStrMod("d", ModAlt)):
|
||||
v.TextArea.ForwardDeleteWord()
|
||||
case key.Equals(NewKeyName(KeyBackspace)),
|
||||
key.Equals(NewKey(KeyBackspace, "", ModShift)),
|
||||
key.Equals(NewKeyStrMod("h", ModCtrl)):
|
||||
v.TextArea.BackSpaceChar()
|
||||
case key.Equals(NewKeyStrMod("d", ModCtrl)),
|
||||
|
||||
+97
-20
@@ -20,6 +20,25 @@ type escapeInterpreter struct {
|
||||
instruction instruction
|
||||
hyperlink strings.Builder
|
||||
|
||||
// the digits of the OSC number seen so far, while we don't yet know which
|
||||
// OSC this is
|
||||
oscNumber strings.Builder
|
||||
// the payload of an OSC 1717 sequence, in which a diff renderer states
|
||||
// which line of which file it is about to render; accumulated like
|
||||
// hyperlink, and attached to the cells that follow it
|
||||
metadata strings.Builder
|
||||
// whether the payload currently in metadata has reached a cell, so that one
|
||||
// that never does can be recognized and kept as an orphan
|
||||
metadataConsumed bool
|
||||
// OSC 1717 payloads that no cell took, because the next record followed
|
||||
// with nothing rendered in between. A renderer emits records back to back
|
||||
// wherever two diff lines share a rendered line — the deletion and the
|
||||
// addition of a modification collapsed into one column, or a banner
|
||||
// announcing a file and its first hunk at once. The write loop gives these
|
||||
// cells of their own, so that a line keeps every record it was given rather
|
||||
// than only the last.
|
||||
orphanedMetadata []string
|
||||
|
||||
// ConPTY emits cursor-positioning escapes (CUP) to skip over blank
|
||||
// rows rather than emitting LFs for them. To convert those into row
|
||||
// advances the view can act on, we track where in the pseudo-terminal
|
||||
@@ -82,9 +101,9 @@ const (
|
||||
stateParams
|
||||
stateCSIDiscard
|
||||
stateOSC
|
||||
stateOSCWaitForParams
|
||||
stateOSCParams
|
||||
stateOSCHyperlink
|
||||
stateOSCMetadata
|
||||
stateOSCEndEscape
|
||||
stateOSCSkipUnknown
|
||||
|
||||
@@ -427,27 +446,42 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) {
|
||||
}
|
||||
return true, nil
|
||||
case stateOSC:
|
||||
if characterEquals(ch, '8') {
|
||||
ei.state = stateOSCWaitForParams
|
||||
ei.hyperlink.Reset()
|
||||
// Accumulate the OSC number until the ';' that terminates it, then
|
||||
// dispatch on the whole number rather than on a single digit.
|
||||
switch {
|
||||
case len(ch) == 1 && ch[0] >= '0' && ch[0] <= '9':
|
||||
ei.oscNumber.WriteByte(ch[0])
|
||||
return true, nil
|
||||
case characterEquals(ch, ';'):
|
||||
switch ei.oscNumber.String() {
|
||||
case "8":
|
||||
ei.hyperlink.Reset()
|
||||
ei.state = stateOSCParams
|
||||
case "1717":
|
||||
ei.orphanUnconsumedMetadata()
|
||||
ei.state = stateOSCMetadata
|
||||
default:
|
||||
ei.state = stateOSCSkipUnknown
|
||||
}
|
||||
ei.oscNumber.Reset()
|
||||
return true, nil
|
||||
default:
|
||||
// Not an OSC we understand — it has no number, or a character
|
||||
// follows the number where the ';' should be. Rather than
|
||||
// erroring, which would reset state mid-OSC and leak the rest of
|
||||
// the sequence into the view as literal text, skip to its
|
||||
// terminator, which this character may already be.
|
||||
ei.oscNumber.Reset()
|
||||
switch {
|
||||
case characterEquals(ch, 0x07):
|
||||
ei.state = stateNone
|
||||
case characterEquals(ch, 0x1b):
|
||||
ei.state = stateOSCEndEscape
|
||||
default:
|
||||
ei.state = stateOSCSkipUnknown
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
ei.state = stateOSCSkipUnknown
|
||||
return true, nil
|
||||
case stateOSCWaitForParams:
|
||||
if !characterEquals(ch, ';') {
|
||||
// Malformed OSC 8 (expected ';' after '8'). Rather than
|
||||
// erroring — which would reset state mid-OSC and cause the
|
||||
// rest of the sequence to leak as literal text — treat the
|
||||
// whole OSC as one we don't understand and skip to its
|
||||
// terminator.
|
||||
ei.state = stateOSCSkipUnknown
|
||||
return true, nil
|
||||
}
|
||||
|
||||
ei.state = stateOSCParams
|
||||
return true, nil
|
||||
case stateOSCParams:
|
||||
if characterEquals(ch, ';') {
|
||||
ei.state = stateOSCHyperlink
|
||||
@@ -463,6 +497,18 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) {
|
||||
ei.hyperlink.Write(ch)
|
||||
}
|
||||
return true, nil
|
||||
case stateOSCMetadata:
|
||||
switch {
|
||||
case characterEquals(ch, 0x07):
|
||||
ei.dropMetadataIfHandshake()
|
||||
ei.state = stateNone
|
||||
case characterEquals(ch, 0x1b):
|
||||
ei.dropMetadataIfHandshake()
|
||||
ei.state = stateOSCEndEscape
|
||||
default:
|
||||
ei.metadata.Write(ch)
|
||||
}
|
||||
return true, nil
|
||||
case stateOSCEndEscape:
|
||||
ei.state = stateNone
|
||||
return true, nil
|
||||
@@ -478,6 +524,37 @@ func (ei *escapeInterpreter) parseOne(ch []byte) (isEscape bool, err error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// orphanUnconsumedMetadata clears the metadata accumulator for a new OSC 1717
|
||||
// record, keeping the payload it held as an orphan if no cell took it (see
|
||||
// orphanedMetadata).
|
||||
func (ei *escapeInterpreter) orphanUnconsumedMetadata() {
|
||||
if ei.metadata.Len() > 0 && !ei.metadataConsumed {
|
||||
ei.orphanedMetadata = append(ei.orphanedMetadata, ei.metadata.String())
|
||||
}
|
||||
ei.metadata.Reset()
|
||||
ei.metadataConsumed = false
|
||||
}
|
||||
|
||||
// takeOrphanedMetadata hands the accumulated orphaned payloads to the caller and
|
||||
// clears the list.
|
||||
func (ei *escapeInterpreter) takeOrphanedMetadata() []string {
|
||||
result := ei.orphanedMetadata
|
||||
ei.orphanedMetadata = nil
|
||||
return result
|
||||
}
|
||||
|
||||
// dropMetadataIfHandshake discards a just-completed OSC 1717 payload that
|
||||
// carries nothing beyond the version. A diff renderer emits such a record ahead
|
||||
// of everything else to announce that it speaks the protocol, so that a host can
|
||||
// find that out by asking rather than by inspecting a rendering. It says nothing
|
||||
// about any line, so it must not attach to the line that follows it; a per-line
|
||||
// record always has fields, and is kept.
|
||||
func (ei *escapeInterpreter) dropMetadataIfHandshake() {
|
||||
if !strings.Contains(ei.metadata.String(), ";") {
|
||||
ei.metadata.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
func (ei *escapeInterpreter) outputCSI() error {
|
||||
n := len(ei.csiParam)
|
||||
for i := 0; i < n; {
|
||||
|
||||
@@ -167,6 +167,7 @@ func TestParseOneIgnoresUnknownSequences(t *testing.T) {
|
||||
"\x1b[0 q", // intermediate byte after a param
|
||||
"\x1b[1;;m", // malformed SGR: empty middle param
|
||||
"\x1b]8bogus\x07", // OSC 8 missing ';'
|
||||
"\x1b]1337;File=inline=1\x07", // OSC with a number we don't implement
|
||||
"\x1b[" + strings.Repeat("0", 300) + "m", // single param overflows length cap
|
||||
"\x1b[" + strings.Repeat("1;", 25) + "1m", // too many params
|
||||
}
|
||||
|
||||
+50
-2
@@ -227,6 +227,12 @@ type Gui struct {
|
||||
// readable from anywhere, so it's atomic.
|
||||
focused atomic.Bool
|
||||
|
||||
// colorSchemeTty is nil when running headless. colorScheme and
|
||||
// colorSchemeHandler are only touched on the UI thread.
|
||||
colorSchemeTty *colorSchemeTty
|
||||
colorScheme DetectedColorScheme
|
||||
colorSchemeHandler func(DetectedColorScheme) error
|
||||
|
||||
// blockInputCount, when greater than zero, withholds keyboard input from
|
||||
// the handlers: key events are buffered into bufferedKeyEvents and replayed
|
||||
// once the count drops back to zero, while mouse clicks and hover are
|
||||
@@ -317,6 +323,18 @@ func NewGui(opts NewGuiOpts) (*Gui, error) {
|
||||
// never happened.
|
||||
g.focused.Store(true)
|
||||
|
||||
if g.colorSchemeTty != nil {
|
||||
g.colorScheme = g.colorSchemeTty.subscribe(func(colorScheme DetectedColorScheme) {
|
||||
g.UpdateBackground(func(g *Gui) error {
|
||||
g.colorScheme = colorScheme
|
||||
if g.colorSchemeHandler != nil {
|
||||
return g.colorSchemeHandler(colorScheme)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return g, nil
|
||||
}
|
||||
|
||||
@@ -374,6 +392,7 @@ func (g *Gui) WaitUntilIdle() {
|
||||
// initialization and when gocui is not needed anymore.
|
||||
func (g *Gui) Close() {
|
||||
close(g.stop)
|
||||
g.waitForColorSchemeReplies()
|
||||
Screen.Fini()
|
||||
}
|
||||
|
||||
@@ -419,7 +438,7 @@ func (g *Gui) SetView(name string, x0, y0, x1, y1 int, overlaps byte) (*View, er
|
||||
v.y1 = y1
|
||||
|
||||
if sizeChanged {
|
||||
v.ClearViewLines()
|
||||
v.RewrapContent()
|
||||
|
||||
if v.Editable {
|
||||
cursorX, cursorY := v.TextArea.GetCursorXY()
|
||||
@@ -708,6 +727,29 @@ func (g *Gui) SetFocusHandler(handler func(bool) error) {
|
||||
g.focusHandler = handler
|
||||
}
|
||||
|
||||
// DetectedColorScheme returns what the terminal has told us about its colors.
|
||||
// It is known before the first layout, for the terminals that tell us at all.
|
||||
func (g *Gui) DetectedColorScheme() DetectedColorScheme {
|
||||
return g.colorScheme
|
||||
}
|
||||
|
||||
// SetColorSchemeChangeHandler sets a function to call on the UI thread whenever
|
||||
// the terminal's colors change after startup.
|
||||
func (g *Gui) SetColorSchemeChangeHandler(handler func(DetectedColorScheme) error) {
|
||||
g.colorSchemeHandler = handler
|
||||
}
|
||||
|
||||
// Long enough for the round trip of a slow ssh connection
|
||||
const colorSchemeReplyTimeout = 500 * time.Millisecond
|
||||
|
||||
// waitForColorSchemeReplies is for before we give up the terminal. tcell is
|
||||
// still reading the input at that point, so the answers are consumed as usual.
|
||||
func (g *Gui) waitForColorSchemeReplies() {
|
||||
if g.colorSchemeTty != nil {
|
||||
g.colorSchemeTty.waitForReplies(colorSchemeReplyTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gui) SetOpenHyperlinkFunc(openHyperlinkFunc func(string, string) error) {
|
||||
g.openHyperlink = openHyperlinkFunc
|
||||
}
|
||||
@@ -1534,7 +1576,7 @@ func (g *Gui) flush() error {
|
||||
// if GUI's size has changed, we need to redraw all views
|
||||
if maxX != g.maxX || maxY != g.maxY {
|
||||
for _, v := range g.views {
|
||||
v.ClearViewLines()
|
||||
v.RewrapContent()
|
||||
}
|
||||
}
|
||||
g.maxX, g.maxY = maxX, maxY
|
||||
@@ -2043,6 +2085,10 @@ func (g *Gui) onFocus(ev *GocuiEvent) error {
|
||||
}
|
||||
g.focused.Store(ev.Focused)
|
||||
|
||||
if ev.Focused && g.colorSchemeTty != nil {
|
||||
g.colorSchemeTty.onFocusGained()
|
||||
}
|
||||
|
||||
if g.focusHandler != nil {
|
||||
return g.focusHandler(ev.Focused)
|
||||
}
|
||||
@@ -2059,6 +2105,8 @@ func (g *Gui) onFocus(ev *GocuiEvent) error {
|
||||
// after re-engaging.
|
||||
|
||||
func (g *Gui) Suspend() error {
|
||||
g.waitForColorSchemeReplies()
|
||||
|
||||
g.suspendedMutex.Lock()
|
||||
defer g.suspendedMutex.Unlock()
|
||||
|
||||
|
||||
@@ -56,7 +56,13 @@ var runeReplacements = map[rune]string{
|
||||
func (g *Gui) tcellInit(runeReplacements map[rune]string) error {
|
||||
tcell.SetEncodingFallback(tcell.EncodingFallbackASCII)
|
||||
|
||||
s, e := tcell.NewScreen()
|
||||
tty, e := tcell.NewDevTty()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
colorSchemeTty := newColorSchemeTty(tty)
|
||||
|
||||
s, e := tcell.NewTerminfoScreenFromTty(colorSchemeTty)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -68,6 +74,7 @@ func (g *Gui) tcellInit(runeReplacements map[rune]string) error {
|
||||
registerRuneFallbacks(s, runeReplacements)
|
||||
|
||||
g.screen = s
|
||||
g.colorSchemeTty = colorSchemeTty
|
||||
Screen = s
|
||||
return nil
|
||||
}
|
||||
|
||||
+352
-28
@@ -5,6 +5,7 @@
|
||||
package gocui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
@@ -138,6 +139,12 @@ type View struct {
|
||||
// focus.
|
||||
InactiveViewSelBgColor Attribute
|
||||
|
||||
// SelTextColor is applied to the text of the selected line when it is
|
||||
// highlighted, whether the view has the focus or not. Its attributes are
|
||||
// added to those of the text, and if it has a color, that replaces the
|
||||
// color of the text.
|
||||
SelTextColor Attribute
|
||||
|
||||
// If Editable is true, keystrokes will be added to the view's internal
|
||||
// buffer at the cursor position.
|
||||
Editable bool
|
||||
@@ -245,23 +252,138 @@ type pos struct {
|
||||
x, y int
|
||||
}
|
||||
|
||||
// call this in the event of a view resize, or if you want to render new content
|
||||
// without the chance of old content still appearing, or if you want to remove
|
||||
// a line from the existing content
|
||||
// call this if you want to render new content without the chance of old content
|
||||
// still appearing, or if you want to remove a line from the existing content. For
|
||||
// a view whose size has changed, whose content is the same but has to be wrapped
|
||||
// afresh, call RewrapContent instead.
|
||||
func (v *View) clearViewLines() {
|
||||
v.tainted = true
|
||||
v.viewLines = nil
|
||||
v.clearHover()
|
||||
}
|
||||
|
||||
// ClearViewLines is clearViewLines guarded by writeMutex. It's for callers on
|
||||
// the UI thread (the layout pass) that touch a view whose content a task
|
||||
// goroutine may be writing concurrently: viewLines/tainted/hover are all
|
||||
// buffer state that writeMutex protects.
|
||||
func (v *View) ClearViewLines() {
|
||||
// RewrapContent wraps the view's content for the size the view has now, and puts
|
||||
// the positions into that content — the scroll offset, the cursor, a range's
|
||||
// anchor — back on the lines they were on. They are all view lines, which count
|
||||
// the segments each line is wrapped into, so wrapping the content at another
|
||||
// width leaves every one of them pointing at a different line.
|
||||
//
|
||||
// Call it on the UI thread whenever the view's size changes; a task goroutine may
|
||||
// be writing the content concurrently, and all of this is state writeMutex
|
||||
// protects.
|
||||
func (v *View) RewrapContent() {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
v.refreshViewLinesIfNeeded()
|
||||
origin := v.contentPosOf(v.oy)
|
||||
cursor := v.contentPosOf(v.oy + v.cy)
|
||||
anchor := v.contentPosOf(v.rangeSelectStartY)
|
||||
cursorRow := v.cy
|
||||
|
||||
v.clearViewLines()
|
||||
v.refreshViewLinesIfNeeded()
|
||||
|
||||
if !origin.ok {
|
||||
return
|
||||
}
|
||||
|
||||
cursorLine, cursorOk := v.viewLineOf(cursor)
|
||||
if anchorLine, ok := v.viewLineOf(anchor); ok {
|
||||
v.rangeSelectStartY = anchorLine
|
||||
if cursorOk {
|
||||
// A range covers lines of content, not the wrapped segments those
|
||||
// lines are drawn as, so its ends go back on the outermost segments
|
||||
// of their lines: a line that was covered whole stays covered whole.
|
||||
cursorLine = v.viewLineOfRangeEnd(cursor, anchor)
|
||||
v.rangeSelectStartY = v.viewLineOfRangeEnd(anchor, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
// The line the cursor is on keeps the row it was drawn on, so that it doesn't
|
||||
// move under the user; with no cursor on screen the view keeps its own place
|
||||
// in the content instead.
|
||||
if v.Highlight && cursorOk && cursorRow >= 0 && cursorRow < v.InnerHeight() {
|
||||
v.SetOriginY(cursorLine - cursorRow)
|
||||
} else if originLine, ok := v.viewLineOf(origin); ok {
|
||||
v.SetOriginY(originLine)
|
||||
}
|
||||
if cursorOk {
|
||||
v.cy = cursorLine - v.oy
|
||||
}
|
||||
}
|
||||
|
||||
// contentPos is a position in a view's content in terms that survive the content
|
||||
// being wrapped again: which line of it, and which of that line's segments.
|
||||
type contentPos struct {
|
||||
line, segment int
|
||||
ok bool
|
||||
}
|
||||
|
||||
// contentPosOf returns where the given view line sits in the content. Only call
|
||||
// this with a lock on writeMutex, and with the view lines up to date.
|
||||
func (v *View) contentPosOf(viewLine int) contentPos {
|
||||
if viewLine < 0 || viewLine >= len(v.viewLines) {
|
||||
return contentPos{}
|
||||
}
|
||||
return contentPos{
|
||||
line: v.viewLines[viewLine].linesY,
|
||||
segment: v.viewLines[viewLine].linesX,
|
||||
ok: true,
|
||||
}
|
||||
}
|
||||
|
||||
// viewLineOf returns the view line drawing the given position in the content,
|
||||
// on the nearest segment its line still has. Only call this with a lock on
|
||||
// writeMutex, and with the view lines up to date.
|
||||
func (v *View) viewLineOf(pos contentPos) (int, bool) {
|
||||
first, last, ok := v.segmentSpanOf(pos)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return min(first+pos.segment, last), true
|
||||
}
|
||||
|
||||
// viewLineOfRangeEnd returns the view line for one end of a range selection: the
|
||||
// outermost segment of its line, so that the range covers that line whole. other
|
||||
// is the range's other end, which says which way is outward. Both ends have to be
|
||||
// positions whose lines are drawn, which viewLineOf answers.
|
||||
func (v *View) viewLineOfRangeEnd(pos contentPos, other contentPos) int {
|
||||
first, last, _ := v.segmentSpanOf(pos)
|
||||
if pos.line <= other.line {
|
||||
return first
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
// segmentSpanOf returns the first and last view line drawing the given position's
|
||||
// line of the content. ok is false when the position was never taken, or its line
|
||||
// isn't drawn at all.
|
||||
func (v *View) segmentSpanOf(pos contentPos) (int, int, bool) {
|
||||
if !pos.ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
return v.viewLineSpanOfBufferLine(pos.line)
|
||||
}
|
||||
|
||||
// viewLineSpanOfBufferLine returns the first and last view line drawing the given
|
||||
// buffer line, i.e. the first and last segment it is wrapped into. Both are the
|
||||
// same view line when the line doesn't wrap. ok is false when the line isn't drawn
|
||||
// at all. Only call this with a lock on writeMutex, and with the view lines up to
|
||||
// date.
|
||||
func (v *View) viewLineSpanOfBufferLine(bufferLine int) (int, int, bool) {
|
||||
first, last := -1, -1
|
||||
for i, vline := range v.viewLines {
|
||||
if vline.linesY == bufferLine {
|
||||
if first == -1 {
|
||||
first = i
|
||||
}
|
||||
last = i
|
||||
} else if first != -1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return first, last, first != -1
|
||||
}
|
||||
|
||||
type searcher struct {
|
||||
@@ -572,6 +694,23 @@ type lineType struct {
|
||||
// matches the current width; nil means nothing is cached yet.
|
||||
wrappedCells [][]cell
|
||||
wrappedColumns int
|
||||
|
||||
// asWritten is the text of the line as its writer wrote it, escape sequences
|
||||
// left out, kept from the first character on that the cells spell differently:
|
||||
// a tab, which the cells hold as the spaces it fills, or a carriage return,
|
||||
// which they hold as the overwrite it caused. nil while the cells spell the
|
||||
// line as it was written, as they do for most lines.
|
||||
asWritten []byte
|
||||
}
|
||||
|
||||
// textAsWritten returns the line's text as its writer wrote it, escape sequences
|
||||
// left out. A reader that parses a view's content rather than showing it wants
|
||||
// this form; the cells' text is for showing.
|
||||
func (l *lineType) textAsWritten() string {
|
||||
if l.asWritten != nil {
|
||||
return string(l.asWritten)
|
||||
}
|
||||
return l.cells.String()
|
||||
}
|
||||
|
||||
// trailingFillAttributes describes the fg/bg colors that draw() should
|
||||
@@ -588,6 +727,9 @@ type cell struct {
|
||||
width int // number of terminal cells occupied by chr (always 1 or 2)
|
||||
bgColor, fgColor Attribute
|
||||
hyperlink string
|
||||
// the OSC 1717 payload in effect when the cell was written, i.e. what the
|
||||
// diff renderer said about the diff line this cell is part of
|
||||
metadata string
|
||||
}
|
||||
|
||||
type cells []cell
|
||||
@@ -631,7 +773,7 @@ func NewView(name string, x0, y0, x1, y1 int, mode OutputMode) *View {
|
||||
|
||||
v.FgColor, v.BgColor = ColorDefault, ColorDefault
|
||||
v.SelFgColor, v.SelBgColor = ColorDefault, ColorDefault
|
||||
v.InactiveViewSelBgColor = ColorDefault
|
||||
v.InactiveViewSelBgColor, v.SelTextColor = ColorDefault, ColorDefault
|
||||
v.TitleColor, v.FrameColor = ColorDefault, ColorDefault
|
||||
v.buf.ei.screenColMax = v.InnerWidth()
|
||||
return v
|
||||
@@ -722,12 +864,7 @@ func (v *View) setCharacter(x, y int, ch string, fgColor, bgColor Attribute, isW
|
||||
}
|
||||
|
||||
if y >= rangeSelectStart && y <= rangeSelectEnd {
|
||||
// this ensures we use the bright variant of a colour upon highlight
|
||||
fgColorComponent := fgColor & ^AttrAll
|
||||
if fgColorComponent >= AttrIsValidColor && fgColorComponent < AttrIsValidColor+8 {
|
||||
fgColor += 8
|
||||
}
|
||||
fgColor = fgColor | AttrBold
|
||||
fgColor = applySelTextColor(fgColor, v.SelTextColor)
|
||||
if v.HighlightInactive || !isWindowFocused {
|
||||
bgColor = (bgColor & AttrStyleBits) | v.InactiveViewSelBgColor
|
||||
} else {
|
||||
@@ -834,8 +971,7 @@ func (v *View) SetWritePos(x, y int) {
|
||||
y = 0
|
||||
}
|
||||
|
||||
v.buf.wx = x
|
||||
v.buf.wy = y
|
||||
v.buf.seekWrite(x, y)
|
||||
|
||||
// Changing the write position makes a pending newline obsolete
|
||||
v.buf.pendingNewline = false
|
||||
@@ -919,6 +1055,35 @@ func (b *viewBuffer) writeCells(cells []cell) {
|
||||
b.wx += len(cells)
|
||||
}
|
||||
|
||||
// seekWrite moves the write cursor to (x, y). Writing there starts the line over,
|
||||
// so whatever it kept of its text as written is dropped; the text a line keeps is
|
||||
// the text written to it from its start. A carriage return continues a line
|
||||
// instead, and moves the cursor without this (see write).
|
||||
func (b *viewBuffer) seekWrite(x, y int) {
|
||||
b.wx = x
|
||||
b.wy = y
|
||||
if y < len(b.lines) {
|
||||
b.lines[y].asWritten = nil
|
||||
}
|
||||
}
|
||||
|
||||
// startAsWritten begins keeping the current line's text as written (see
|
||||
// lineType.asWritten), at the first character the cells won't spell the same way.
|
||||
// Up to here they spell it exactly, so their text is what was written so far.
|
||||
func (b *viewBuffer) startAsWritten() {
|
||||
if line := &b.lines[b.wy]; line.asWritten == nil {
|
||||
line.asWritten = append([]byte{}, line.cells.String()...)
|
||||
}
|
||||
}
|
||||
|
||||
// noteAsWritten records text the writer wrote to the current line, once the line
|
||||
// keeps its text as written at all.
|
||||
func (b *viewBuffer) noteAsWritten(text []byte) {
|
||||
if line := &b.lines[b.wy]; line.asWritten != nil {
|
||||
line.asWritten = append(line.asWritten, text...)
|
||||
}
|
||||
}
|
||||
|
||||
// Write appends a byte slice into the view's internal buffer. Because
|
||||
// View implements the io.Writer interface, it can be passed as parameter
|
||||
// of functions like fmt.Fprintf, fmt.Fprintln, io.Copy, etc. Clear must
|
||||
@@ -962,14 +1127,30 @@ func (b *viewBuffer) write(v *View, p []byte) {
|
||||
|
||||
finishLine := func() {
|
||||
b.autoRenderHyperlinksInCurrentLine(v)
|
||||
// A record that reached the line's end without covering a cell still
|
||||
// belongs to the line: an orphan (see escapeInterpreter.orphanedMetadata),
|
||||
// or the record of a changed line that is empty, which a renderer emits
|
||||
// with nothing but the newline after it. Give each a cell of its own, so
|
||||
// that the line is still recognizable as the diff line it renders rather
|
||||
// than as nothing at all.
|
||||
for _, payload := range b.ei.takeOrphanedMetadata() {
|
||||
b.writeCells([]cell{{metadata: payload}})
|
||||
}
|
||||
if b.ei.metadata.Len() > 0 && !b.ei.metadataConsumed {
|
||||
b.writeCells([]cell{{metadata: b.ei.metadata.String()}})
|
||||
b.ei.metadataConsumed = true
|
||||
}
|
||||
}
|
||||
|
||||
advanceToNextLine := func() {
|
||||
b.wx = 0
|
||||
b.wy++
|
||||
b.seekWrite(0, b.wy+1)
|
||||
if b.wy >= len(b.lines) {
|
||||
b.lines = append(b.lines, lineType{})
|
||||
}
|
||||
// An OSC 1717 record describes the line it precedes and is never
|
||||
// closed, so it stops applying at the line's end; a renderer emits a
|
||||
// fresh one for each line it has something to say about.
|
||||
b.ei.metadata.Reset()
|
||||
}
|
||||
|
||||
if b.pendingNewline {
|
||||
@@ -999,6 +1180,10 @@ func (b *viewBuffer) write(v *View, p []byte) {
|
||||
b.ei.notifyRowAdvance()
|
||||
case characterEquals(chr, '\r'):
|
||||
finishLine()
|
||||
// The cells will hold what follows as an overwrite of what came
|
||||
// before; the text as written keeps the return itself.
|
||||
b.startAsWritten()
|
||||
b.noteAsWritten(chr)
|
||||
b.wx = 0
|
||||
b.ei.notifyColumnReset()
|
||||
default:
|
||||
@@ -1114,8 +1299,18 @@ func (b *viewBuffer) parseInput(v *View, ch []byte, width int, x int, _ int) (bo
|
||||
truncateLine := false
|
||||
|
||||
isEscape, err := b.ei.parseOne(ch)
|
||||
|
||||
// A record that the next one superseded before any cell took it still
|
||||
// belongs to this line (see escapeInterpreter.orphanedMetadata); give each
|
||||
// a cell of its own, in the order they were emitted, ahead of whatever this
|
||||
// character produces.
|
||||
for _, payload := range b.ei.takeOrphanedMetadata() {
|
||||
cells = append(cells, cell{metadata: payload})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
for _, chr := range b.ei.characters() {
|
||||
characters := b.ei.characters()
|
||||
for _, chr := range characters {
|
||||
c := cell{
|
||||
fgColor: v.FgColor,
|
||||
bgColor: v.BgColor,
|
||||
@@ -1124,6 +1319,7 @@ func (b *viewBuffer) parseInput(v *View, ch []byte, width int, x int, _ int) (bo
|
||||
}
|
||||
cells = append(cells, c)
|
||||
}
|
||||
b.noteAsWritten([]byte(strings.Join(characters, "")))
|
||||
b.ei.reset()
|
||||
} else {
|
||||
repeatCount := 1
|
||||
@@ -1140,7 +1336,7 @@ func (b *viewBuffer) parseInput(v *View, ch []byte, width int, x int, _ int) (bo
|
||||
fg: b.ei.curFgColor,
|
||||
bg: b.ei.curBgColor,
|
||||
}
|
||||
return truncateLine, []cell{}
|
||||
return truncateLine, cells
|
||||
} else if cf, ok := b.ei.instruction.(cursorForward); ok {
|
||||
// emit `n` space cells under the parser-tracked SGR — used
|
||||
// to materialize ConPTY's compressed runs of spaces (which
|
||||
@@ -1149,10 +1345,19 @@ func (b *viewBuffer) parseInput(v *View, ch []byte, width int, x int, _ int) (bo
|
||||
repeatCount = cf.n
|
||||
ch = []byte{' '}
|
||||
width = 1
|
||||
b.noteAsWritten(bytes.Repeat(ch, repeatCount))
|
||||
} else if isEscape {
|
||||
// do not output anything
|
||||
return truncateLine, nil
|
||||
// the escape itself outputs nothing, but any cells carrying an
|
||||
// orphaned record still need writing
|
||||
if len(cells) == 0 {
|
||||
return truncateLine, nil
|
||||
}
|
||||
return truncateLine, cells
|
||||
} else if characterEquals(ch, '\t') {
|
||||
// The cells hold a tab as the spaces it fills; the text as written
|
||||
// keeps the tab itself.
|
||||
b.startAsWritten()
|
||||
b.noteAsWritten(ch)
|
||||
// fill tab-sized space
|
||||
tabWidth := v.TabWidth
|
||||
if tabWidth < 1 {
|
||||
@@ -1161,14 +1366,20 @@ func (b *viewBuffer) parseInput(v *View, ch []byte, width int, x int, _ int) (bo
|
||||
ch = []byte{' '}
|
||||
width = 1
|
||||
repeatCount = tabWidth - (x % tabWidth)
|
||||
} else {
|
||||
b.noteAsWritten(ch)
|
||||
}
|
||||
c := cell{
|
||||
fgColor: b.ei.curFgColor,
|
||||
bgColor: b.ei.curBgColor,
|
||||
hyperlink: b.ei.hyperlink.String(),
|
||||
metadata: b.ei.metadata.String(),
|
||||
chr: string(ch),
|
||||
width: width,
|
||||
}
|
||||
if c.metadata != "" {
|
||||
b.ei.metadataConsumed = true
|
||||
}
|
||||
for range repeatCount {
|
||||
cells = append(cells, c)
|
||||
}
|
||||
@@ -1744,6 +1955,88 @@ func (v *View) BufferLines() []string {
|
||||
return lines
|
||||
}
|
||||
|
||||
// DiffLineContent holds what one line of a rendered diff offers to a reader trying
|
||||
// to recover which line of which file it came from: the line's text, which can be
|
||||
// parsed as a unified diff when the rendering preserves one, and the OSC 1717
|
||||
// records a diff renderer attached to it, which state the answer outright.
|
||||
type DiffLineContent struct {
|
||||
// The line's text as its writer wrote it, escape sequences left out, where
|
||||
// BufferLines gives the text as the cells spell it. The two differ where the
|
||||
// cells can't spell what was written: a tab, which they hold as the spaces it
|
||||
// fills, and a carriage return, which they hold as the overwrite it caused.
|
||||
// git terminates a path containing a space with a tab in a diff header, and a
|
||||
// parser of the diff has to see the tab.
|
||||
Text string
|
||||
// The distinct OSC 1717 payloads carried by the line's cells, in
|
||||
// left-to-right order. A single-column rendering tags every cell of a line
|
||||
// with the same payload, so there is one; a side-by-side rendering tags
|
||||
// each side separately, so a line showing a deletion beside the addition
|
||||
// that replaces it carries both.
|
||||
Metadata []string
|
||||
}
|
||||
|
||||
// DiffLineContents returns the per-line material a diff-line reader works from
|
||||
// (see DiffLineContent), indexed by unwrapped buffer line. Text and records are
|
||||
// snapshotted in a single locked pass, so they stay consistent with each other
|
||||
// and with the buffer they came from even while a re-render rebuilds it.
|
||||
func (v *View) DiffLineContents() []DiffLineContent {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
contents := make([]DiffLineContent, len(v.buf.lines))
|
||||
for i := range v.buf.lines {
|
||||
line := &v.buf.lines[i]
|
||||
var metadata []string
|
||||
for _, c := range line.cells {
|
||||
if c.metadata != "" && !slices.Contains(metadata, c.metadata) {
|
||||
metadata = append(metadata, c.metadata)
|
||||
}
|
||||
}
|
||||
contents[i] = DiffLineContent{Text: line.textAsWritten(), Metadata: metadata}
|
||||
}
|
||||
return contents
|
||||
}
|
||||
|
||||
// BufferLineForViewLine maps a view line index (which counts wrapped lines) to
|
||||
// the index of the corresponding line in the unwrapped internal buffer (as
|
||||
// returned by BufferLines). Several view lines map to the same buffer line when
|
||||
// that line wraps. Returns false if the view line is out of range.
|
||||
func (v *View) BufferLineForViewLine(y int) (int, bool) {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
return v.bufferLineForViewLine(y)
|
||||
}
|
||||
|
||||
// ViewLineForBufferLine maps an unwrapped buffer line index to the index of the
|
||||
// first view line that renders it — the inverse of BufferLineForViewLine, for
|
||||
// turning a line found by examining the buffer into a line to scroll to or
|
||||
// select. Returns false if the buffer line isn't rendered into any view line.
|
||||
func (v *View) ViewLineForBufferLine(bufferLineIdx int) (int, bool) {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
v.refreshViewLinesIfNeeded()
|
||||
|
||||
first, _, ok := v.viewLineSpanOfBufferLine(bufferLineIdx)
|
||||
return first, ok
|
||||
}
|
||||
|
||||
// LastViewLineForBufferLine maps an unwrapped buffer line index to the index of
|
||||
// the last view line that renders it, which for a line that doesn't wrap is the
|
||||
// same as the first. It is where the far end of a range goes: a range is over
|
||||
// buffer lines, so it has to cover the last one of them to its final segment
|
||||
// rather than stopping where that line begins.
|
||||
func (v *View) LastViewLineForBufferLine(bufferLineIdx int) (int, bool) {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
v.refreshViewLinesIfNeeded()
|
||||
|
||||
_, last, ok := v.viewLineSpanOfBufferLine(bufferLineIdx)
|
||||
return last, ok
|
||||
}
|
||||
|
||||
// Buffer returns a string with the contents of the view's internal
|
||||
// buffer.
|
||||
func (v *View) Buffer() string {
|
||||
@@ -1843,6 +2136,15 @@ func indexFunc(r rune) bool {
|
||||
return r == ' ' || r == 0
|
||||
}
|
||||
|
||||
// applySelTextColor adds the attributes of selTextColor to fgColor, and
|
||||
// replaces the color of fgColor with that of selTextColor if it has one.
|
||||
func applySelTextColor(fgColor, selTextColor Attribute) Attribute {
|
||||
if selTextColor&AttrColorBits != ColorDefault {
|
||||
fgColor = fgColor&AttrStyleBits | selTextColor&AttrColorBits
|
||||
}
|
||||
return fgColor | selTextColor&AttrStyleBits
|
||||
}
|
||||
|
||||
// SetHighlight toggles highlighting of separate lines, for custom lists
|
||||
// or multiple selection in views.
|
||||
func (v *View) SetHighlight(y int, on bool) {
|
||||
@@ -1975,11 +2277,12 @@ func (v *View) SelectedLine() string {
|
||||
v.writeMutex.Lock()
|
||||
defer v.writeMutex.Unlock()
|
||||
|
||||
if len(v.buf.lines) == 0 {
|
||||
idx, ok := v.bufferLineForViewLine(v.SelectedLineIdx())
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return v.lineContentAtIdx(v.SelectedLineIdx())
|
||||
return v.lineContentAtIdx(idx)
|
||||
}
|
||||
|
||||
// expected to only be used in tests
|
||||
@@ -1994,8 +2297,17 @@ func (v *View) SelectedLines() []string {
|
||||
startIdx, endIdx := v.SelectedLineRange()
|
||||
|
||||
lines := make([]string, 0, endIdx-startIdx+1)
|
||||
previous := -1
|
||||
for i := startIdx; i <= endIdx; i++ {
|
||||
lines = append(lines, v.lineContentAtIdx(i))
|
||||
// The selection is in view lines, which count the segments a wrapped line
|
||||
// is drawn as; a line the selection covers several segments of is still
|
||||
// the one line it is.
|
||||
idx, ok := v.bufferLineForViewLine(i)
|
||||
if !ok || idx == previous {
|
||||
continue
|
||||
}
|
||||
previous = idx
|
||||
lines = append(lines, v.lineContentAtIdx(idx))
|
||||
}
|
||||
|
||||
return lines
|
||||
@@ -2005,6 +2317,19 @@ func (v *View) lineContentAtIdx(idx int) string {
|
||||
return v.buf.lines[idx].cells.String()
|
||||
}
|
||||
|
||||
// bufferLineForViewLine maps a view line index, which counts the wrapped
|
||||
// segments of the lines it draws, to the index of the line of content it is a
|
||||
// segment of. Only call this with a lock on writeMutex.
|
||||
func (v *View) bufferLineForViewLine(y int) (int, bool) {
|
||||
v.refreshViewLinesIfNeeded()
|
||||
|
||||
if y < 0 || y >= len(v.viewLines) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return v.viewLines[y].linesY, true
|
||||
}
|
||||
|
||||
func (v *View) SelectedPoint() (int, int) {
|
||||
cx, cy := v.Cursor()
|
||||
ox, oy := v.Origin()
|
||||
@@ -2075,8 +2400,7 @@ func (v *View) ClearTextArea() {
|
||||
|
||||
func (v *View) overwriteLines(y int, content string) {
|
||||
// break by newline, then for each line, write it, then add that erase command
|
||||
v.buf.wx = 0
|
||||
v.buf.wy = y
|
||||
v.SetWritePos(0, y)
|
||||
v.clearViewLines()
|
||||
|
||||
lines := strings.ReplaceAll(content, "\n", "\x1b[K\n")
|
||||
|
||||
@@ -113,6 +113,99 @@ func TestWriteString(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverwriteLinesAfterContentEndingInANewline(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 20, 10, OutputNormal)
|
||||
// The trailing newline is held back until more content arrives, so that the
|
||||
// view doesn't end in an empty line.
|
||||
v.writeString("a\nb\n")
|
||||
|
||||
v.OverwriteLines(0, "x")
|
||||
|
||||
assert.Equal(t, []string{"x", "b"}, v.BufferLines())
|
||||
}
|
||||
|
||||
// diffLineTexts returns the Text of each of the given contents.
|
||||
func diffLineTexts(contents []DiffLineContent) []string {
|
||||
return lo.Map(contents, func(c DiffLineContent, _ int) string { return c.Text })
|
||||
}
|
||||
|
||||
func TestDiffLineContentsTextIsTheTextAsWritten(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
stringsToWrite []string
|
||||
expectedShown []string
|
||||
expectedAsWritten []string
|
||||
}{
|
||||
{
|
||||
name: "a line the cells spell as written",
|
||||
stringsToWrite: []string{"abc\n"},
|
||||
expectedShown: []string{"abc"},
|
||||
expectedAsWritten: []string{"abc"},
|
||||
},
|
||||
{
|
||||
name: "a tab is kept rather than the spaces it fills",
|
||||
stringsToWrite: []string{"a\tb\n"},
|
||||
expectedShown: []string{"a b"},
|
||||
expectedAsWritten: []string{"a\tb"},
|
||||
},
|
||||
{
|
||||
name: "a carriage return is kept rather than the overwrite it causes",
|
||||
stringsToWrite: []string{"abc\rde\n"},
|
||||
expectedShown: []string{"dec"},
|
||||
expectedAsWritten: []string{"abc\rde"},
|
||||
},
|
||||
{
|
||||
// git writes a CRLF file's lines as "+foo\r", the color reset, "\n".
|
||||
name: "escape sequences are left out",
|
||||
stringsToWrite: []string{"\x1b[32m+foo\r\x1b[m\n"},
|
||||
expectedShown: []string{"+foo"},
|
||||
expectedAsWritten: []string{"+foo\r"},
|
||||
},
|
||||
{
|
||||
// ConPTY writes a run of spaces as a cursor-forward escape.
|
||||
name: "a cursor-forward escape stands for the spaces it skips",
|
||||
stringsToWrite: []string{"\ta\x1b[2Cb\n"},
|
||||
expectedShown: []string{" a b"},
|
||||
expectedAsWritten: []string{"\ta b"},
|
||||
},
|
||||
{
|
||||
name: "a line written in two parts",
|
||||
stringsToWrite: []string{"a\t", "b\n"},
|
||||
expectedShown: []string{"a b"},
|
||||
expectedAsWritten: []string{"a\tb"},
|
||||
},
|
||||
{
|
||||
name: "only the lines with a tab or a return are kept separately",
|
||||
stringsToWrite: []string{"x\n", "y\tz\n", "w\n"},
|
||||
expectedShown: []string{"x", "y z", "w"},
|
||||
expectedAsWritten: []string{"x", "y\tz", "w"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 20, 10, OutputNormal)
|
||||
for _, s := range test.stringsToWrite {
|
||||
v.writeString(s)
|
||||
}
|
||||
assert.Equal(t, test.expectedShown, v.BufferLines())
|
||||
assert.Equal(t, test.expectedAsWritten, diffLineTexts(v.DiffLineContents()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffLineContentsTextOfAnOverwrittenLine(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 20, 10, OutputNormal)
|
||||
v.writeString("a\tb\nc\td")
|
||||
|
||||
// Overwriting a line starts it over: what it kept of its earlier text goes,
|
||||
// and the line below is left alone.
|
||||
v.OverwriteLines(0, "xy")
|
||||
|
||||
assert.Equal(t, []string{"xy", "c d"}, v.BufferLines())
|
||||
assert.Equal(t, []string{"xy", "c\td"}, diffLineTexts(v.DiffLineContents()))
|
||||
}
|
||||
|
||||
func TestUpdatedCursorAndOrigin(t *testing.T) {
|
||||
tests := []struct {
|
||||
prevOrigin int
|
||||
@@ -158,6 +251,107 @@ func TestAutoRenderingHyperlinks(t *testing.T) {
|
||||
assert.Equal(t, "https://example.com", v.buf.lines[0].cells[0].hyperlink)
|
||||
}
|
||||
|
||||
// osc1717 wraps an OSC 1717 payload in the sequence a diff renderer emits it in:
|
||||
// the ESC ] introducer with the OSC number, and ESC \ as the terminator.
|
||||
func osc1717(payload string) string {
|
||||
return "\x1b]1717;" + payload + "\x1b\\"
|
||||
}
|
||||
|
||||
func TestDiffLineContents(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 80, 10, OutputNormal)
|
||||
|
||||
// A diff renderer prefixes each line it renders with a record naming the
|
||||
// file and the line's position in it: version;type;new-line;old-line;file.
|
||||
v.writeString(strings.Join([]string{
|
||||
osc1717("1;c;1;;foo.txt") + "line1",
|
||||
osc1717("1;d;2;2;foo.txt") + "old2",
|
||||
osc1717("1;a;2;;foo.txt") + "new2",
|
||||
"@@ a hunk header, which carries no record @@",
|
||||
}, "\n"))
|
||||
|
||||
assert.Equal(t, []DiffLineContent{
|
||||
{Text: "line1", Metadata: []string{"1;c;1;;foo.txt"}},
|
||||
{Text: "old2", Metadata: []string{"1;d;2;2;foo.txt"}},
|
||||
{Text: "new2", Metadata: []string{"1;a;2;;foo.txt"}},
|
||||
// The record of the line before doesn't bleed onto this one.
|
||||
{Text: "@@ a hunk header, which carries no record @@"},
|
||||
}, v.DiffLineContents())
|
||||
}
|
||||
|
||||
func TestDiffLineContentsWithSideBySideRecords(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 80, 10, OutputNormal)
|
||||
|
||||
// A side-by-side renderer puts two diff lines on one rendered line, and so
|
||||
// emits a record before each half.
|
||||
v.writeString(strings.Join([]string{
|
||||
osc1717("1;c;1;;foo.txt") + "context " + osc1717("1;c;1;;foo.txt") + "context",
|
||||
osc1717("1;d;2;2;foo.txt") + "old2 " + osc1717("1;a;2;;foo.txt") + "new2",
|
||||
}, "\n"))
|
||||
|
||||
assert.Equal(t, []DiffLineContent{
|
||||
// The two halves of a context line are the same diff line, stated twice.
|
||||
{Text: "context context", Metadata: []string{"1;c;1;;foo.txt"}},
|
||||
{Text: "old2 new2", Metadata: []string{"1;d;2;2;foo.txt", "1;a;2;;foo.txt"}},
|
||||
}, v.DiffLineContents())
|
||||
}
|
||||
|
||||
func TestDiffLineContentsOfWrappedLine(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 10, 10, OutputNormal) // InnerWidth is 9
|
||||
v.Wrap = true
|
||||
|
||||
// A line that gocui wraps is still one buffer line, so its record covers
|
||||
// every view line it is displayed on.
|
||||
v.writeString(osc1717("1;a;1;;foo.txt") + "a line too long to fit")
|
||||
|
||||
assert.Equal(t, []DiffLineContent{
|
||||
{Text: "a line too long to fit", Metadata: []string{"1;a;1;;foo.txt"}},
|
||||
}, v.DiffLineContents())
|
||||
assert.Equal(t, 3, v.ViewLinesHeight())
|
||||
for viewLine := range 3 {
|
||||
bufferLine, ok := v.BufferLineForViewLine(viewLine)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, 0, bufferLine)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiffLineContentsWithRecordsCoveringNoCell(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 80, 10, OutputNormal)
|
||||
|
||||
v.writeString(strings.Join([]string{
|
||||
// A banner announcing a file and its first hunk at once carries both
|
||||
// records back to back.
|
||||
osc1717("1;f;;;foo.txt") + osc1717("1;h;5;;foo.txt") + "foo.txt --- Go",
|
||||
// So does a modification whose deletion and addition are collapsed into
|
||||
// a single rendered line.
|
||||
osc1717("1;d;5;5;foo.txt") + osc1717("1;a;5;;foo.txt") + "595 new content",
|
||||
// A changed line that is empty is rendered as its record and nothing else.
|
||||
osc1717("1;a;6;;foo.txt"),
|
||||
}, "\n") + "\n")
|
||||
|
||||
assert.Equal(t, []DiffLineContent{
|
||||
{Text: "foo.txt --- Go", Metadata: []string{"1;f;;;foo.txt", "1;h;5;;foo.txt"}},
|
||||
{Text: "595 new content", Metadata: []string{"1;d;5;5;foo.txt", "1;a;5;;foo.txt"}},
|
||||
{Text: "", Metadata: []string{"1;a;6;;foo.txt"}},
|
||||
}, v.DiffLineContents())
|
||||
}
|
||||
|
||||
func TestDiffLineContentsSwallowsHandshake(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 80, 10, OutputNormal)
|
||||
|
||||
// A diff renderer announces itself with a version-only record before the
|
||||
// diff. It must leave no trace: no visible bytes, no line of its own, and
|
||||
// above all no record on the line that follows it.
|
||||
v.writeString(osc1717("1") + strings.Join([]string{
|
||||
"diff --git a/foo.txt b/foo.txt",
|
||||
osc1717("1;a;1;;foo.txt") + "added",
|
||||
}, "\n"))
|
||||
|
||||
assert.Equal(t, []DiffLineContent{
|
||||
{Text: "diff --git a/foo.txt b/foo.txt"},
|
||||
{Text: "added", Metadata: []string{"1;a;1;;foo.txt"}},
|
||||
}, v.DiffLineContents())
|
||||
}
|
||||
|
||||
// An async re-render builds into an off-screen buffer and swaps it in once it
|
||||
// has enough to paint, so readers keep seeing the previous render — coherent and
|
||||
// consistent — until the new content appears in one step. See View.offscreen.
|
||||
@@ -204,6 +398,61 @@ func TestViewLinesTruncatedByShorterRender(t *testing.T) {
|
||||
assert.Equal(t, []string{"aaa", "bbb", "ccc"}, v.ViewBufferLines())
|
||||
}
|
||||
|
||||
func TestBufferLineForViewLine(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 10, 10, OutputNormal) // InnerWidth is 9
|
||||
v.Wrap = true
|
||||
|
||||
// Buffer line 0 is short (view line 0); buffer line 1 wraps into three view
|
||||
// lines (1, 2, 3); buffer line 2 is short again (view line 4).
|
||||
v.writeString("short\n" + strings.Repeat("b", 27) + "\nlast")
|
||||
|
||||
for viewLine, wantBufferLine := range []int{0, 1, 1, 1, 2} {
|
||||
bufferLine, ok := v.BufferLineForViewLine(viewLine)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, wantBufferLine, bufferLine)
|
||||
}
|
||||
|
||||
_, ok := v.BufferLineForViewLine(5)
|
||||
assert.False(t, ok)
|
||||
|
||||
_, ok = v.BufferLineForViewLine(-1)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestViewLineForBufferLine(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 10, 10, OutputNormal) // InnerWidth is 9
|
||||
v.Wrap = true
|
||||
|
||||
// A wrapped buffer line maps to the first of the view lines it spans.
|
||||
v.writeString("short\n" + strings.Repeat("b", 27) + "\nlast")
|
||||
|
||||
for bufferLine, wantViewLine := range []int{0, 1, 4} {
|
||||
viewLine, ok := v.ViewLineForBufferLine(bufferLine)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, wantViewLine, viewLine)
|
||||
}
|
||||
|
||||
_, ok := v.ViewLineForBufferLine(3)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLastViewLineForBufferLine(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 10, 10, OutputNormal) // InnerWidth is 9
|
||||
v.Wrap = true
|
||||
|
||||
// A wrapped buffer line maps to the last of the view lines it spans.
|
||||
v.writeString("short\n" + strings.Repeat("b", 27) + "\nlast")
|
||||
|
||||
for bufferLine, wantViewLine := range []int{0, 3, 4} {
|
||||
viewLine, ok := v.LastViewLineForBufferLine(bufferLine)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, wantViewLine, viewLine)
|
||||
}
|
||||
|
||||
_, ok := v.LastViewLineForBufferLine(3)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
// While an async re-render loads, it swaps in only a partially-filled buffer at
|
||||
// its first paint and keeps appending lines afterwards. The scrollbar must keep
|
||||
// using the pre-load height until the load ends, so the thumb doesn't shrink and
|
||||
@@ -780,3 +1029,93 @@ func TestMulticolorWrappedFillUsesLastCellOfEachSegment(t *testing.T) {
|
||||
"trailing cell at (%d, 2) should have green bg", x)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySelTextColor(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
fgColor Attribute
|
||||
selTextColor Attribute
|
||||
expected Attribute
|
||||
}{
|
||||
{
|
||||
name: "adds attributes",
|
||||
fgColor: ColorRed | AttrUnderline,
|
||||
selTextColor: AttrBold,
|
||||
expected: ColorRed | AttrUnderline | AttrBold,
|
||||
},
|
||||
{
|
||||
name: "replaces the color",
|
||||
fgColor: ColorRed | AttrUnderline,
|
||||
selTextColor: ColorWhite | AttrBold,
|
||||
expected: ColorWhite | AttrUnderline | AttrBold,
|
||||
},
|
||||
{
|
||||
name: "replaces an RGB color",
|
||||
fgColor: NewRGBColor(0x12, 0x34, 0x56),
|
||||
selTextColor: ColorBlue,
|
||||
expected: ColorBlue,
|
||||
},
|
||||
{
|
||||
name: "leaves the text alone if default",
|
||||
fgColor: ColorRed | AttrUnderline,
|
||||
selTextColor: ColorDefault,
|
||||
expected: ColorRed | AttrUnderline,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, applySelTextColor(s.fgColor, s.selTextColor))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A view that wraps draws one line of its content as several view lines, and the
|
||||
// cursor and the range anchor count those. What is asked about a selection is
|
||||
// which lines of the content it covers, so those are what it has to be reported
|
||||
// in.
|
||||
func TestSelectedLinesOfWrappedContent(t *testing.T) {
|
||||
v := NewView("name", 0, 0, 11, 10, OutputNormal) // InnerWidth 10
|
||||
v.Wrap = true
|
||||
v.Highlight = true
|
||||
|
||||
// "a line that wraps" takes two view lines, so the four lines of content are
|
||||
// drawn as five: "one", "two", "a line th", "at wraps", "four".
|
||||
v.writeString("one\ntwo\na line that wraps\nfour\n")
|
||||
assert.Equal(t, 5, v.ViewLinesHeight())
|
||||
|
||||
// The cursor on the wrapped line's second half is on that line.
|
||||
v.FocusPoint(0, 3, false)
|
||||
assert.Equal(t, "a line that wraps", v.SelectedLine())
|
||||
|
||||
// A range over both halves of the wrapped line covers one line of content.
|
||||
v.SetRangeSelectStart(2)
|
||||
assert.Equal(t, []string{"a line that wraps"}, v.SelectedLines())
|
||||
}
|
||||
|
||||
// Resizing a view throws away the wrapping of its content and wraps it again for
|
||||
// the new width, which moves every line of it to a different view line. The
|
||||
// positions into the view count view lines, so they all have to come along.
|
||||
func TestResizingAWrappingViewKeepsItsPlaceInTheContent(t *testing.T) {
|
||||
g := &Gui{}
|
||||
v, _ := g.SetView("name", 0, 0, 11, 10, 0) // InnerWidth 10
|
||||
v.Wrap = true
|
||||
v.Highlight = true
|
||||
|
||||
// Two wrapping lines, with a single line between them: eight view lines for
|
||||
// five lines of content.
|
||||
v.writeString("one\na line that wraps\ntwo\nanother wrapping line\nthree\n")
|
||||
assert.Equal(t, 8, v.ViewLinesHeight())
|
||||
|
||||
// A range over the whole of the second wrapping line, which is drawn as view
|
||||
// lines 4 to 6.
|
||||
v.SetRangeSelectStart(4)
|
||||
v.FocusPoint(0, 6, false)
|
||||
assert.Equal(t, []string{"another wrapping line"}, v.SelectedLines())
|
||||
|
||||
// Widen the view so that nothing wraps any more.
|
||||
_, _ = g.SetView("name", 0, 0, 31, 10, 0) // InnerWidth 30
|
||||
assert.Equal(t, 5, v.ViewLinesHeight())
|
||||
|
||||
assert.Equal(t, []string{"another wrapping line"}, v.SelectedLines())
|
||||
}
|
||||
|
||||
@@ -89,6 +89,10 @@ func NewMenuViewModel(c *ContextCommon) *MenuViewModel {
|
||||
})
|
||||
}
|
||||
|
||||
if item.FilterColumns != nil {
|
||||
return item.FilterColumns
|
||||
}
|
||||
|
||||
return item.LabelColumns
|
||||
},
|
||||
)
|
||||
|
||||
@@ -27,13 +27,10 @@ func NewReflogCommitsContext(c *ContextCommon) *ReflogCommitsContext {
|
||||
)
|
||||
|
||||
getDisplayStrings := func(startIdx int, endIdx int) [][]string {
|
||||
commits := viewModel.GetItems()
|
||||
if startIdx >= len(commits) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return presentation.GetReflogCommitListDisplayStrings(
|
||||
commits[startIdx:endIdx],
|
||||
viewModel.GetItems(),
|
||||
startIdx,
|
||||
endIdx,
|
||||
c.State().GetRepoState().GetScreenMode() != types.SCREEN_NORMAL,
|
||||
c.Modes().CherryPicking.SelectedHashSet(),
|
||||
c.Modes().Diffing.Ref,
|
||||
|
||||
@@ -68,6 +68,7 @@ func (gui *Gui) resetHelpersAndControllers() {
|
||||
searchHelper,
|
||||
)
|
||||
diffHelper := helpers.NewDiffHelper(helperCommon)
|
||||
diffLineHelper := helpers.NewDiffLineHelper(helperCommon)
|
||||
cherryPickHelper := helpers.NewCherryPickHelper(
|
||||
helperCommon,
|
||||
rebaseHelper,
|
||||
@@ -110,6 +111,7 @@ func (gui *Gui) resetHelpersAndControllers() {
|
||||
SuspendResume: helpers.NewSuspendResumeHelper(helperCommon),
|
||||
Snake: helpers.NewSnakeHelper(helperCommon),
|
||||
Diff: diffHelper,
|
||||
DiffLine: diffLineHelper,
|
||||
Repos: reposHelper,
|
||||
RecordDirectory: recordDirectoryHelper,
|
||||
Update: helpers.NewUpdateHelper(helperCommon, gui.Updater),
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/presentation"
|
||||
@@ -144,8 +143,8 @@ func (self *BranchesController) GetKeybindings(opts types.KeybindingsOpts) []*ty
|
||||
},
|
||||
{
|
||||
Keys: opts.GetKeys(opts.Config.Branches.FastForward),
|
||||
Handler: self.withItem(self.fastForward),
|
||||
GetDisabledReason: self.require(self.singleItemSelected(self.branchIsReal)),
|
||||
Handler: self.withItems(self.fastForward),
|
||||
GetDisabledReason: self.require(self.itemRangeSelected(self.branchesAreReal)),
|
||||
Description: self.c.Tr.FastForward,
|
||||
Tooltip: self.c.Tr.FastForwardTooltip,
|
||||
},
|
||||
@@ -206,13 +205,13 @@ func (self *BranchesController) GetOnRenderToMain() func() {
|
||||
} else {
|
||||
cmdObj := self.c.Git().Branch.GetGraphCmdObj(branch.FullRefName())
|
||||
|
||||
ptyTask := types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
task = ptyTask
|
||||
rendererTask := types.NewRunDiffRendererTask(cmdObj.GetCmd())
|
||||
task = rendererTask
|
||||
|
||||
pr, ok := self.c.Model().PullRequestsMap[branch.Name]
|
||||
if ok && presentation.ShouldShowPrForBranch(pr, branch.Name, self.c.UserConfig()) {
|
||||
ptyTask.Prefix = presentation.FormatPullRequestHeader(pr, self.c.Tr)
|
||||
ptyTask.Prefix += strings.Repeat("─", self.c.Contexts().Normal.GetView().InnerWidth()) + "\n"
|
||||
rendererTask.Prefix = presentation.FormatPullRequestHeader(pr, self.c.Tr)
|
||||
rendererTask.Prefix += strings.Repeat("─", self.c.Contexts().Normal.GetView().InnerWidth()) + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,54 +654,23 @@ func (self *BranchesController) rebase(branch *models.Branch) error {
|
||||
return self.c.Helpers().MergeAndRebase.RebaseOntoRef(branch.Name)
|
||||
}
|
||||
|
||||
func (self *BranchesController) fastForward(branch *models.Branch) error {
|
||||
if !branch.IsTrackingRemote() {
|
||||
func (self *BranchesController) fastForward(branches []*models.Branch) error {
|
||||
if !lo.EveryBy(branches, func(branch *models.Branch) bool { return branch.IsTrackingRemote() }) {
|
||||
return errors.New(self.c.Tr.FwdNoUpstream)
|
||||
}
|
||||
if !branch.RemoteBranchStoredLocally() {
|
||||
if !lo.EveryBy(branches, func(branch *models.Branch) bool { return branch.RemoteBranchStoredLocally() }) {
|
||||
return errors.New(self.c.Tr.FwdNoLocalUpstream)
|
||||
}
|
||||
if branch.IsAheadForPull() {
|
||||
// A branch that is only ahead has nothing to fast-forward to. One that is
|
||||
// both ahead and behind may still be reset to its upstream, so let the
|
||||
// helper look into it.
|
||||
if lo.SomeBy(branches, func(branch *models.Branch) bool {
|
||||
return branch.IsAheadForPull() && !branch.IsBehindForPull()
|
||||
}) {
|
||||
return errors.New(self.c.Tr.FwdCommitsToPush)
|
||||
}
|
||||
|
||||
action := self.c.Tr.Actions.FastForwardBranch
|
||||
worktree, ok := self.worktreeForBranch(branch)
|
||||
|
||||
return self.c.WithInlineStatus(branch, types.ItemOperationFastForwarding, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
if ok {
|
||||
self.c.LogAction(action)
|
||||
|
||||
worktreeGitDir := ""
|
||||
worktreePath := ""
|
||||
// if it is the current worktree path, no need to specify the path
|
||||
if !worktree.IsCurrent {
|
||||
worktreeGitDir = worktree.GitDir
|
||||
worktreePath = worktree.Path
|
||||
}
|
||||
|
||||
err := self.c.Git().Sync.Pull(
|
||||
task,
|
||||
git_commands.PullOptions{
|
||||
RemoteName: branch.UpstreamRemote,
|
||||
BranchName: branch.UpstreamBranch,
|
||||
FastForwardOnly: true,
|
||||
WorktreeGitDir: worktreeGitDir,
|
||||
WorktreePath: worktreePath,
|
||||
},
|
||||
)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{})
|
||||
return err
|
||||
}
|
||||
|
||||
self.c.LogAction(action)
|
||||
|
||||
err := self.c.Git().Sync.FastForward(
|
||||
task, branch.Name, branch.UpstreamRemote, branch.UpstreamBranch,
|
||||
)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}})
|
||||
return err
|
||||
})
|
||||
return self.c.Helpers().BranchesHelper.FastForwardBranches(branches)
|
||||
}
|
||||
|
||||
func (self *BranchesController) createTag(branch *models.Branch) error {
|
||||
|
||||
@@ -177,7 +177,7 @@ func (self *CommitFilesController) GetOnRenderToMain() func() {
|
||||
|
||||
paths := self.pathsForDiff(node)
|
||||
cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, false)
|
||||
task := types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
task := types.NewRunDiffRendererTask(cmdObj.GetCmd())
|
||||
|
||||
self.c.RenderToMainViews(types.RefreshMainOpts{
|
||||
Pair: self.c.MainViewPairs().Normal,
|
||||
|
||||
@@ -356,7 +356,7 @@ func (self *FilesController) renderNonTextualConflict(node *filetree.FileNode) {
|
||||
prefix += self.c.Tr.MergeConflictCurrentDiff
|
||||
}
|
||||
prefix += "\n\n"
|
||||
self.renderToMainWithTask(types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix))
|
||||
self.renderToMainWithTask(types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) {
|
||||
refreshOpts := types.RefreshMainOpts{
|
||||
Pair: self.c.MainViewPairs().Normal,
|
||||
Main: &types.ViewUpdateOpts{
|
||||
Task: types.NewRunPtyTask(cmdObj.GetCmd()),
|
||||
Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()),
|
||||
SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(),
|
||||
Title: title,
|
||||
},
|
||||
@@ -395,7 +395,7 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) {
|
||||
refreshOpts.Secondary = &types.ViewUpdateOpts{
|
||||
Title: title,
|
||||
SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(),
|
||||
Task: types.NewRunPtyTask(cmdObj.GetCmd()),
|
||||
Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package controllers
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
@@ -185,13 +184,7 @@ func (self *GlobalController) cycleDiffRenderersBackward() error {
|
||||
// onDiffRenderersChanged re-renders the main view so the newly selected diff renderer
|
||||
// takes effect, and shows a toast naming it.
|
||||
func (self *GlobalController) onDiffRenderersChanged() {
|
||||
currentSide := self.c.Context().CurrentSide()
|
||||
currentKey := self.c.Context().Current().GetKey()
|
||||
if currentSide.GetKey() == currentKey ||
|
||||
currentKey == context.NORMAL_MAIN_CONTEXT_KEY ||
|
||||
currentKey == context.NORMAL_SECONDARY_CONTEXT_KEY {
|
||||
currentSide.HandleRenderToMain()
|
||||
}
|
||||
self.c.Helpers().Diff.RenderToMainAgain()
|
||||
|
||||
diffRendererConfigManager := self.c.State().GetDiffRendererConfigManager()
|
||||
current, total := diffRendererConfigManager.CurrentDiffRendererIndex()
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// Returns the branches stacked below the given branch: those whose tip is one
|
||||
// of the given commits of the branch that hasn't been merged into a main
|
||||
// branch yet. The branch itself and the main branches are left out. The
|
||||
// result is in the order in which the tips appear in commits, so the branch
|
||||
// closest to the given one comes first.
|
||||
//
|
||||
// Only the commits passed in are looked at, so a branch whose tip is further
|
||||
// down the history than the loaded commits is not found.
|
||||
func BranchesBelowInStack(
|
||||
commits []*models.Commit,
|
||||
branches []*models.Branch,
|
||||
branch *models.Branch,
|
||||
mainBranches []string,
|
||||
) []*models.Branch {
|
||||
branchesByTip := map[string][]*models.Branch{}
|
||||
for _, other := range branches {
|
||||
if other.Name == branch.Name || lo.Contains(mainBranches, other.Name) {
|
||||
continue
|
||||
}
|
||||
branchesByTip[other.CommitHash] = append(branchesByTip[other.CommitHash], other)
|
||||
}
|
||||
|
||||
result := []*models.Branch{}
|
||||
for _, commit := range commits {
|
||||
if commit.IsTODO() || commit.Status == models.StatusMerged {
|
||||
continue
|
||||
}
|
||||
result = append(result, branchesByTip[commit.Hash()]...)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
"github.com/stefanhaller/git-todo-parser/todo"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestBranchesBelowInStack(t *testing.T) {
|
||||
hashPool := &utils.StringPool{}
|
||||
commit := func(hash string, status models.CommitStatus) *models.Commit {
|
||||
return models.NewCommit(hashPool, models.NewCommitOpts{Hash: hash, Status: status})
|
||||
}
|
||||
todoCommit := func(hash string) *models.Commit {
|
||||
return models.NewCommit(hashPool, models.NewCommitOpts{Hash: hash, Action: todo.Pick, Status: models.StatusRebasing})
|
||||
}
|
||||
branch := func(name string, tip string) *models.Branch {
|
||||
return &models.Branch{Name: name, CommitHash: tip}
|
||||
}
|
||||
|
||||
current := branch("current", "c3")
|
||||
mainBranches := []string{"master", "main"}
|
||||
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
commits []*models.Commit
|
||||
branches []*models.Branch
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
testName: "stack of branches, closest to the current one first",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
commit("c2", models.StatusPushed),
|
||||
commit("c1", models.StatusUnpushed),
|
||||
commit("m1", models.StatusMerged),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("first", "c1"), branch("second", "c2"), branch("master", "m1")},
|
||||
expected: []string{"second", "first"},
|
||||
},
|
||||
{
|
||||
testName: "branch pointing at the same commit as the current one",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
commit("m1", models.StatusMerged),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("twin", "c3")},
|
||||
expected: []string{"twin"},
|
||||
},
|
||||
{
|
||||
testName: "several branches pointing at one commit keep their order",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
commit("c1", models.StatusUnpushed),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("one", "c1"), branch("two", "c1")},
|
||||
expected: []string{"one", "two"},
|
||||
},
|
||||
{
|
||||
testName: "main branches are left out even if their tip isn't merged",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
commit("c1", models.StatusUnpushed),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("main", "c1")},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
testName: "branches whose tip is merged are left out",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
commit("m1", models.StatusMerged),
|
||||
commit("m0", models.StatusMerged),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("old", "m0"), branch("master", "m1")},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
testName: "branches whose tip is not among the commits are left out",
|
||||
commits: []*models.Commit{
|
||||
commit("c3", models.StatusUnpushed),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("sibling", "s1")},
|
||||
expected: []string{},
|
||||
},
|
||||
{
|
||||
testName: "todo commits of a rebase don't count",
|
||||
commits: []*models.Commit{
|
||||
todoCommit("t1"),
|
||||
commit("c3", models.StatusUnpushed),
|
||||
},
|
||||
branches: []*models.Branch{current, branch("other", "t1")},
|
||||
expected: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := BranchesBelowInStack(s.commits, s.branches, current, mainBranches)
|
||||
names := lo.Map(result, func(b *models.Branch, _ int) string { return b.Name })
|
||||
assert.Equal(t, s.expected, names)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
@@ -420,52 +422,287 @@ func (self *BranchesHelper) PostFetchRefresh(fetchErr error, background bool, fe
|
||||
if self.c.State().GetRepoGeneration() != fetchGeneration {
|
||||
return nil
|
||||
}
|
||||
err := self.AutoForwardBranches(background)
|
||||
if background && err != nil {
|
||||
// The background poller discards this return value, so surface
|
||||
// the error in the log rather than as a popup for background work.
|
||||
self.c.Log.Error(err)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
self.AutoForwardBranches(background)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
return fetchErr
|
||||
}
|
||||
|
||||
func (self *BranchesHelper) AutoForwardBranches(background bool) error {
|
||||
if self.c.UserConfig().Git.AutoForwardBranches == "none" {
|
||||
// One of the branches that a fast-forward is about to bring to its upstream
|
||||
type branchToForward struct {
|
||||
branch *models.Branch
|
||||
// the worktree that the branch is checked out in, nil if there is none
|
||||
worktree *models.Worktree
|
||||
// whether the branch has to be reset to its upstream because it has
|
||||
// diverged from it, as opposed to being moved forward
|
||||
reset bool
|
||||
}
|
||||
|
||||
// Updates the given branches to their upstream branches, fetching those first.
|
||||
// A branch that is behind its upstream is moved forward to it; one that has
|
||||
// diverged from it is reset to it, as long as it has no commits of its own. If
|
||||
// any of the branches can't be updated, none of them is.
|
||||
func (self *BranchesHelper) FastForwardBranches(branches []*models.Branch) error {
|
||||
fastForward, err := self.PrepareFastForward(branches)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return self.WithInlineStatusOnBranches(branches, types.ItemOperationFastForwarding, fastForward)
|
||||
}
|
||||
|
||||
// Does the part of FastForwardBranches that looks at the model, and so has to
|
||||
// run on the UI thread. Returns the rest, which is to be run on a worker; this
|
||||
// lets other operations include the fast-forward in their own task.
|
||||
func (self *BranchesHelper) PrepareFastForward(branches []*models.Branch) (func(gocui.Task) error, error) {
|
||||
toForward := lo.Map(branches, func(branch *models.Branch, _ int) *branchToForward {
|
||||
worktree, _ := self.worktreeForBranch(branch)
|
||||
return &branchToForward{branch: branch, worktree: worktree}
|
||||
})
|
||||
anyCheckedOut := lo.SomeBy(toForward, func(f *branchToForward) bool { return f.worktree != nil })
|
||||
|
||||
// Updating that worktree would move its detached HEAD, which belongs to the
|
||||
// rebase or bisect, and leave the branch alone
|
||||
for _, f := range toForward {
|
||||
if f.worktree != nil && f.worktree.IsRebasingOrBisecting {
|
||||
return nil, errors.New(utils.ResolvePlaceholderString(
|
||||
self.c.Tr.FwdBranchRebasingOrBisecting,
|
||||
map[string]string{"branchName": f.branch.Name, "worktreeName": f.worktree.Name},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
return func(task gocui.Task) error {
|
||||
defer func() {
|
||||
if anyCheckedOut {
|
||||
// The files of those worktrees have changed as well
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{})
|
||||
} else {
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}})
|
||||
}
|
||||
}()
|
||||
|
||||
self.c.LogAction(self.c.Tr.Actions.FastForwardBranch)
|
||||
|
||||
if err := self.fetchUpstreamBranches(task, branches); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Look at all the branches before moving any of them, so that one we
|
||||
// have to refuse leaves the others alone too
|
||||
for _, f := range toForward {
|
||||
if err := self.planForwardingBranch(f); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return self.forwardBranches(self.c.Git(), toForward)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Runs f on a worker with all the given branches shown as being in the given
|
||||
// operation while it runs
|
||||
func (self *BranchesHelper) WithInlineStatusOnBranches(branches []*models.Branch, operation types.ItemOperation, f func(gocui.Task) error) error {
|
||||
return WithInlineStatusOnItems(self.c, branches, operation, context.LOCAL_BRANCHES_CONTEXT_KEY, f)
|
||||
}
|
||||
|
||||
func (self *BranchesHelper) fetchUpstreamBranches(task gocui.Task, branches []*models.Branch) error {
|
||||
remotes := lo.Uniq(lo.Map(branches, func(branch *models.Branch, _ int) string {
|
||||
return branch.UpstreamRemote
|
||||
}))
|
||||
|
||||
for _, remote := range remotes {
|
||||
remoteBranches := []string{}
|
||||
for _, branch := range branches {
|
||||
if branch.UpstreamRemote == remote {
|
||||
remoteBranches = append(remoteBranches, branch.UpstreamBranch)
|
||||
}
|
||||
}
|
||||
|
||||
if err := self.c.Git().Sync.FetchRemoteBranches(task, remote, remoteBranches); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Works out whether the branch has to be reset to its upstream, and returns an
|
||||
// error if it can't be brought there at all.
|
||||
func (self *BranchesHelper) planForwardingBranch(f *branchToForward) error {
|
||||
f.reset = !self.c.Git().Branch.IsAncestor(
|
||||
f.branch.FullRefName(), f.branch.FullUpstreamRefName())
|
||||
if !f.reset {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Moving the branch to its upstream means giving up the commits it is
|
||||
// ahead by, so make sure that none of them is ours
|
||||
hasLocalOnlyCommits, err := self.c.Git().Branch.HasLocalOnlyCommits(f.branch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hasLocalOnlyCommits {
|
||||
return errors.New(utils.ResolvePlaceholderString(
|
||||
self.c.Tr.FwdLocalOnlyCommits,
|
||||
map[string]string{"branchName": f.branch.Name},
|
||||
))
|
||||
}
|
||||
|
||||
if f.worktree != nil {
|
||||
// Resetting the branch changes the files of the worktree under the
|
||||
// user's feet, so only do it while they have no changes of their own
|
||||
// there
|
||||
worktreeGitDir, worktreePath := self.worktreeArgs(f.worktree)
|
||||
hasChanges, err := self.c.Git().WorkingTree.HasChangesToTrackedFiles(worktreeGitDir, worktreePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hasChanges {
|
||||
return errors.New(utils.ResolvePlaceholderString(
|
||||
self.c.Tr.FwdUncommittedChanges,
|
||||
map[string]string{"branchName": f.branch.Name},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Keeps going when a branch fails to update, so that it doesn't hold up the
|
||||
// others, and returns the errors of all the failed ones.
|
||||
func (self *BranchesHelper) forwardBranches(git *commands.GitCommand, toForward []*branchToForward) error {
|
||||
var errs []error
|
||||
|
||||
// The branches that aren't checked out anywhere are nothing but refs to
|
||||
// update, so they can all be done in one go
|
||||
updateCommands := ""
|
||||
for _, f := range toForward {
|
||||
if f.worktree == nil {
|
||||
updateCommands += fmt.Sprintf("update %s %s %s\n",
|
||||
f.branch.FullRefName(), f.branch.FullUpstreamRefName(), f.branch.CommitHash)
|
||||
}
|
||||
}
|
||||
|
||||
if updateCommands != "" {
|
||||
self.c.LogCommand(strings.TrimRight(updateCommands, "\n"), false)
|
||||
if err := git.Branch.UpdateBranchRefs(updateCommands, "lazygit: update to upstream branch"); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A branch that is checked out somewhere needs the files of that worktree
|
||||
// to be updated along with it
|
||||
for _, f := range toForward {
|
||||
if f.worktree == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
worktreeGitDir, worktreePath := self.worktreeArgs(f.worktree)
|
||||
|
||||
var err error
|
||||
if f.reset {
|
||||
err = git.WorkingTree.ResetKeep(
|
||||
f.branch.FullUpstreamRefName(), worktreeGitDir, worktreePath)
|
||||
} else {
|
||||
err = git.Branch.FastForwardMerge(
|
||||
f.branch.FullUpstreamRefName(), worktreeGitDir, worktreePath)
|
||||
}
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// Returns the git dir and the path to pass for the given worktree; both are
|
||||
// empty for the current one, which git commands use by default anyway.
|
||||
func (self *BranchesHelper) worktreeArgs(worktree *models.Worktree) (string, string) {
|
||||
if worktree.IsCurrent {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
return worktree.GitDir, worktree.Path
|
||||
}
|
||||
|
||||
// Reads the branches from the model, so it must be called on the UI thread; the
|
||||
// git work happens on a worker.
|
||||
func (self *BranchesHelper) AutoForwardBranches(background bool) {
|
||||
if self.c.UserConfig().Git.AutoForwardBranches == "none" {
|
||||
return
|
||||
}
|
||||
|
||||
branches := self.c.Model().Branches
|
||||
if len(branches) == 0 {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
allBranches := self.c.UserConfig().Git.AutoForwardBranches == "allBranches"
|
||||
updateCommands := ""
|
||||
toForward := []*branchToForward{}
|
||||
// The first branch is the currently checked out branch; skip it
|
||||
for _, branch := range branches[1:] {
|
||||
if branch.RemoteBranchStoredLocally() &&
|
||||
!self.checkedOutByOtherWorktree(branch) &&
|
||||
(allBranches || lo.Contains(self.c.UserConfig().Git.MainBranches, branch.Name)) {
|
||||
isStrictlyBehind := branch.IsBehindForPull() && !branch.IsAheadForPull()
|
||||
if isStrictlyBehind {
|
||||
updateCommands += fmt.Sprintf("update %s %s %s\n", branch.FullRefName(), branch.FullUpstreamRefName(), branch.CommitHash)
|
||||
}
|
||||
if !branch.RemoteBranchStoredLocally() ||
|
||||
!(allBranches || lo.Contains(self.c.UserConfig().Git.MainBranches, branch.Name)) {
|
||||
continue
|
||||
}
|
||||
|
||||
isStrictlyBehind := branch.IsBehindForPull() && !branch.IsAheadForPull()
|
||||
if !isStrictlyBehind {
|
||||
continue
|
||||
}
|
||||
|
||||
// Changing the files of the current worktree without being asked to
|
||||
// would be surprising. A worktree that is mid-rebase or mid-bisect has
|
||||
// its HEAD detached from the branch, so the branch can't be moved
|
||||
// there, and neither can it in a worktree whose directory is missing.
|
||||
worktree, _ := self.worktreeForBranch(branch)
|
||||
if worktree != nil && (worktree.IsCurrent || worktree.IsRebasingOrBisecting || worktree.IsPathMissing) {
|
||||
continue
|
||||
}
|
||||
|
||||
toForward = append(toForward, &branchToForward{branch: branch, worktree: worktree})
|
||||
}
|
||||
|
||||
if updateCommands == "" {
|
||||
return nil
|
||||
if len(toForward) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
self.c.LogAction(self.c.Tr.Actions.AutoForwardBranches)
|
||||
self.c.LogCommand(strings.TrimRight(updateCommands, "\n"), false)
|
||||
err := self.c.Git().Branch.UpdateBranchRefs(updateCommands)
|
||||
// A background worker doesn't block switching repos, so it has to stick
|
||||
// to the git commands of the repo that the branches came from
|
||||
git := self.c.Git()
|
||||
onWorker := lo.Ternary(background, self.c.OnWorkerBackground, self.c.OnWorker)
|
||||
onWorker(func(gocui.Task) error {
|
||||
// Only change the files of another worktree while the user has no
|
||||
// changes of their own there
|
||||
toForward := lo.Filter(toForward, func(f *branchToForward, _ int) bool {
|
||||
if f.worktree == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Background: background})
|
||||
worktreeGitDir, worktreePath := self.worktreeArgs(f.worktree)
|
||||
hasChanges, err := git.WorkingTree.HasChangesToTrackedFiles(worktreeGitDir, worktreePath)
|
||||
if err != nil {
|
||||
self.c.Log.Errorf("Failed to check worktree %s for changes: %v", f.worktree.Name, err)
|
||||
}
|
||||
return err == nil && !hasChanges
|
||||
})
|
||||
if len(toForward) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
self.c.LogAction(self.c.Tr.Actions.AutoForwardBranches)
|
||||
err := self.forwardBranches(git, toForward)
|
||||
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.BRANCHES}, Background: background})
|
||||
|
||||
if background && err != nil {
|
||||
// Surface the error in the log rather than as a popup for background
|
||||
// work
|
||||
self.c.Log.Error(err)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
@@ -118,27 +118,36 @@ func (self *ConfirmationHelper) getPopupPanelDimensionsAux(contentWidth int, con
|
||||
y0 += 1
|
||||
return x0, y0, x0 + panelWidth - 1, y0 + panelHeight - 1
|
||||
}
|
||||
return width/2 - panelWidth/2,
|
||||
height/2 - panelHeight/2 - panelHeight%2,
|
||||
// Currently, X1/Y1 of a gocui view is one less than you would expect based on its
|
||||
// width/height, so we need to subtract 1 here. See
|
||||
// https://github.com/jesseduffield/lazygit/commit/f6f2a52dee8bba3ebd7e3b34b4b7c7d3e3795f3e
|
||||
width/2 + panelWidth/2 - 1,
|
||||
height/2 + panelHeight/2 - 1
|
||||
x0 := (width - panelWidth) / 2
|
||||
y0 := height/2 - panelHeight/2 - panelHeight%2
|
||||
// Currently, X1/Y1 of a gocui view is one less than you would expect based on its
|
||||
// width/height, so we need to subtract 1 here. See
|
||||
// https://github.com/jesseduffield/lazygit/commit/f6f2a52dee8bba3ebd7e3b34b4b7c7d3e3795f3e
|
||||
return x0, y0, x0 + panelWidth - 1, y0 + panelHeight - 1
|
||||
}
|
||||
|
||||
const (
|
||||
// The width a popup panel keeps as long as it fits into the window at all,
|
||||
// even when the panel asks for less.
|
||||
popupPanelMinWidth = 80
|
||||
|
||||
// The margin we try to leave between a popup panel and the sides of the
|
||||
// window, so that the panel doesn't sit flush against them as soon as the
|
||||
// window gets a little narrow.
|
||||
popupPanelMargin = 3
|
||||
)
|
||||
|
||||
// Returns the outer width of the view, including its frame. To decide how to wrap text, subtract 2.
|
||||
// Also, note that X1-X0 of the view is one less than this.
|
||||
func (self *ConfirmationHelper) getPopupPanelWidth(maxWidth int) int {
|
||||
width, _ := self.c.GocuiGui().Size()
|
||||
// we want a minimum width up to a point, then we do it based on ratio, but only up to the given max width
|
||||
panelWidth := min(4*width/7, maxWidth)
|
||||
minWidth := 80
|
||||
if panelWidth < minWidth {
|
||||
panelWidth = min(width-2, minWidth)
|
||||
}
|
||||
func (self *ConfirmationHelper) getPopupPanelWidth(requestedWidth int) int {
|
||||
windowWidth, _ := self.c.GocuiGui().Size()
|
||||
// A panel gets the width it asks for as long as the margin fits beside it.
|
||||
// It gives the margin up before it goes below the minimum width, and a
|
||||
// column on either side is all it leaves in the end.
|
||||
widthWithMargin := windowWidth - 2*popupPanelMargin
|
||||
widthAtMinWidth := min(popupPanelMinWidth, windowWidth-2)
|
||||
|
||||
return panelWidth
|
||||
return min(requestedWidth, max(widthWithMargin, widthAtMinWidth))
|
||||
}
|
||||
|
||||
func (self *ConfirmationHelper) prepareConfirmationPanel(
|
||||
@@ -324,6 +333,10 @@ func (self *ConfirmationHelper) ResizeCurrentPopupPanels() {
|
||||
}
|
||||
}
|
||||
|
||||
// The width a menu grows to when the window is wide enough for it. Its content
|
||||
// is two columns narrower than this, for the frame.
|
||||
const menuMaxWidth = 90
|
||||
|
||||
// The rows that a filter row adds to a menu popup: one for the input, and one
|
||||
// for its bottom border. Its top border is the menu's bottom border.
|
||||
const menuFilterRowHeight = 2
|
||||
@@ -359,7 +372,7 @@ func (self *ConfirmationHelper) resizeMenu(parentPopupContext types.Context) {
|
||||
// resize the window
|
||||
itemCount := menuContext.UnfilteredLen()
|
||||
offset := 3
|
||||
panelWidth := self.getPopupPanelWidth(90)
|
||||
panelWidth := self.getPopupPanelWidth(menuMaxWidth)
|
||||
contentWidth := panelWidth - 2 // minus 2 for the frame
|
||||
promptLinesCount := self.layoutMenuPrompt(contentWidth)
|
||||
// The row is reserved for the whole time the menu is open, even though it only
|
||||
|
||||
@@ -74,11 +74,11 @@ func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Comm
|
||||
}
|
||||
cmdObj := self.c.Git().Diff.DiffCmdObj(args)
|
||||
prefix := style.FgYellow.Sprintf("%s %s-%s\n\n", self.c.Tr.ShowingDiffForRange, from.ShortRefName(), to.ShortRefName())
|
||||
return types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix)
|
||||
return types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix)
|
||||
}
|
||||
|
||||
cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit))
|
||||
return types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
return types.NewRunDiffRendererTask(cmdObj.GetCmd())
|
||||
}
|
||||
|
||||
func (self *DiffHelper) FilterPathsForCommit(commit *models.Commit) []string {
|
||||
@@ -98,6 +98,19 @@ func (self *DiffHelper) ExitDiffMode() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenderToMainAgain renders the current side panel into the main view again, if
|
||||
// that is what the main view shows. This is for when something that the
|
||||
// rendering depends on has changed, such as the diff renderer.
|
||||
func (self *DiffHelper) RenderToMainAgain() {
|
||||
currentSide := self.c.Context().CurrentSide()
|
||||
currentKey := self.c.Context().Current().GetKey()
|
||||
if currentSide.GetKey() == currentKey ||
|
||||
currentKey == context.NORMAL_MAIN_CONTEXT_KEY ||
|
||||
currentKey == context.NORMAL_SECONDARY_CONTEXT_KEY {
|
||||
currentSide.HandleRenderToMain()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *DiffHelper) RenderDiff() {
|
||||
args := self.DiffArgs()
|
||||
cmdObj := self.c.Git().Diff.DiffCmdObj(args)
|
||||
@@ -106,7 +119,7 @@ func (self *DiffHelper) RenderDiff() {
|
||||
self.c.Tr.ShowingGitDiff,
|
||||
"git diff "+strings.Join(args, " "),
|
||||
)
|
||||
task := types.NewRunPtyTaskWithPrefix(cmdObj.GetCmd(), prefix)
|
||||
task := types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix)
|
||||
|
||||
self.c.RenderToMainViews(types.RefreshMainOpts{
|
||||
Pair: self.c.MainViewPairs().Normal,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
)
|
||||
|
||||
type DiffLineHelper struct {
|
||||
c *HelperCommon
|
||||
}
|
||||
|
||||
func NewDiffLineHelper(c *HelperCommon) *DiffLineHelper {
|
||||
return &DiffLineHelper{c: c}
|
||||
}
|
||||
|
||||
// GetDiffLineInfo recovers the identity — file, kind, and old/new line number —
|
||||
// of the diff row at the given (wrapped) view line of the given view. It is the
|
||||
// seam every consumer of a diff row goes through, so that how we recover that
|
||||
// identity can change without them noticing.
|
||||
//
|
||||
// There are two ways, and which one is used is settled for the rendering as a
|
||||
// whole (see renderingStatesDiffLines). A diff renderer that speaks the OSC 1717
|
||||
// protocol states the identity of each line it renders. That is the only way to
|
||||
// recover it from a rendering that doesn't look like a diff any more (columns, or
|
||||
// +/- markers replaced by colour), and a row such a renderer says nothing about
|
||||
// has no identity. Otherwise we parse the view's contents as a unified diff; this
|
||||
// works for the renderings that keep a diff's structure (no renderer, `git diff
|
||||
// --color`, a renderer that only colorizes) and fails for the rest.
|
||||
//
|
||||
// ok is false when the row's identity can't be recovered, in which case the
|
||||
// caller must not act on the line at all.
|
||||
func (self *DiffLineHelper) GetDiffLineInfo(view *gocui.View, viewLineIdx int) (types.DiffLineInfo, bool) {
|
||||
// The cursor and clicks land on a view line, which counts wrapped segments;
|
||||
// the contents are indexed by unwrapped buffer line.
|
||||
bufferLineIdx, ok := view.BufferLineForViewLine(viewLineIdx)
|
||||
if !ok {
|
||||
return types.DiffLineInfo{}, false
|
||||
}
|
||||
|
||||
contents := view.DiffLineContents()
|
||||
if bufferLineIdx >= len(contents) {
|
||||
return types.DiffLineInfo{}, false
|
||||
}
|
||||
|
||||
if renderingStatesDiffLines(contents) {
|
||||
// A row can carry more than one record, when the rendering puts two diff
|
||||
// lines on it; the first one is the row's identity, and the leftmost record
|
||||
// is the one a reader would call the row's own.
|
||||
if metadata := contents[bufferLineIdx].Metadata; len(metadata) > 0 {
|
||||
if parsed, ok := parseDiffLineMetadata(metadata[0]); ok {
|
||||
return self.diffLineInfo(parsed), true
|
||||
}
|
||||
}
|
||||
return types.DiffLineInfo{}, false
|
||||
}
|
||||
|
||||
parsed, ok := parseDiffLineFromBuffer(diffLineTexts(contents), bufferLineIdx)
|
||||
if !ok {
|
||||
return types.DiffLineInfo{}, false
|
||||
}
|
||||
|
||||
return self.diffLineInfo(parsed), true
|
||||
}
|
||||
|
||||
// diffLineInfo turns a parser's result into the absolute-path identity consumers
|
||||
// work with. The path arrives repo-relative from the diff header, but a renderer
|
||||
// states it however it likes, absolute paths included.
|
||||
func (self *DiffLineHelper) diffLineInfo(parsed parsedDiffLine) types.DiffLineInfo {
|
||||
path := parsed.Path
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(self.c.Git().RepoPaths.WorktreePath(), path)
|
||||
}
|
||||
|
||||
return types.DiffLineInfo{
|
||||
Path: path,
|
||||
Type: parsed.Type,
|
||||
NewLine: parsed.NewLine,
|
||||
OldLine: parsed.OldLine,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/patch"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
)
|
||||
|
||||
// diffFilePrefix marks the start of a file's section in a (possibly multi-file)
|
||||
// unified diff.
|
||||
const diffFilePrefix = "diff --git "
|
||||
|
||||
// submodulePrefix opens the line a submodule's section of a diff starts with, which
|
||||
// stands in for the "diff --git" header a file of the repo gets.
|
||||
const submodulePrefix = "Submodule "
|
||||
|
||||
// submoduleSectionPattern matches that line and captures the submodule's path. git
|
||||
// writes one of two kinds: the commit the submodule is checked out at has moved
|
||||
// ("Submodule sub a32f27c..2d9f921:", with "..." in place of ".." where the move is
|
||||
// no fast-forward, " (rewind)" where it goes backwards, and a message in brackets in
|
||||
// place of the colon where the two commits can't both be read), or its working tree
|
||||
// is dirty ("Submodule sub contains untracked content").
|
||||
//
|
||||
// The path is captured greedily: git writes it unquoted, so a path that itself ends
|
||||
// in something reading like a range of commits is told apart by taking the last such
|
||||
// range on the line.
|
||||
var submoduleSectionPattern = regexp.MustCompile(
|
||||
`^Submodule (.+) (?:contains (?:untracked|modified) content|[0-9a-f]+\.{2,3}[0-9a-f]+(?: \(.*\))?:?)$`)
|
||||
|
||||
// parsedDiffLine is what the parser recovers about a row of a rendered diff.
|
||||
// Path is the path as the diff header spells it, i.e. relative to the repo root;
|
||||
// the caller turns it into the absolute path of types.DiffLineInfo.
|
||||
type parsedDiffLine struct {
|
||||
Path string
|
||||
Type types.DiffLineType
|
||||
NewLine int
|
||||
OldLine int
|
||||
}
|
||||
|
||||
// bufferLineParse is the parser's result for one buffer line: the recovered
|
||||
// identity, and whether the line could be resolved at all (false for a line in
|
||||
// an unparseable section, or outside any file section).
|
||||
type bufferLineParse struct {
|
||||
parsed parsedDiffLine
|
||||
ok bool
|
||||
}
|
||||
|
||||
// parseDiffLineFromBuffer recovers the identity of a row of a rendered diff by
|
||||
// parsing the view's decolorized contents.
|
||||
//
|
||||
// bufferLines is the full unwrapped view buffer; targetIdx is the buffer line to
|
||||
// resolve. A commit's diff spans several files, so we isolate the file section
|
||||
// containing targetIdx and parse just that one (see parseFileSection). Use this
|
||||
// for a single line, e.g. the one under the cursor; to resolve every line of a
|
||||
// buffer, use parseAllDiffLinesFromBuffer, which parses each section only once.
|
||||
//
|
||||
// ok is false when the buffer isn't a parseable unified diff at targetIdx,
|
||||
// because the diff renderer restructured it, so that the caller can fall back.
|
||||
func parseDiffLineFromBuffer(bufferLines []string, targetIdx int) (parsedDiffLine, bool) {
|
||||
if targetIdx < 0 || targetIdx >= len(bufferLines) {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
start, end := fileSectionBounds(bufferLines, targetIdx)
|
||||
if start == -1 {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
r := parseFileSection(bufferLines[start:end], end == len(bufferLines))[targetIdx-start]
|
||||
return r.parsed, r.ok
|
||||
}
|
||||
|
||||
// parseAllDiffLinesFromBuffer resolves every line of a (possibly multi-file)
|
||||
// diff buffer in one pass, parsing each file section exactly once. It is the
|
||||
// batch form of parseDiffLineFromBuffer, for callers that scan a whole buffer:
|
||||
// resolving line by line would re-parse a section once per line of it — O(n²) on
|
||||
// a large single-file diff — whereas this is O(n). The result is indexed 1:1
|
||||
// with bufferLines; a line in an unparseable section, or above the first one, is
|
||||
// left ok=false.
|
||||
func parseAllDiffLinesFromBuffer(bufferLines []string) []bufferLineParse {
|
||||
result := make([]bufferLineParse, len(bufferLines))
|
||||
for i := 0; i < len(bufferLines); {
|
||||
if !startsFileSection(bufferLines[i]) {
|
||||
i++ // in no file section; leave it unresolved
|
||||
continue
|
||||
}
|
||||
end := fileSectionEnd(bufferLines, i)
|
||||
copy(result[i:end], parseFileSection(bufferLines[i:end], end == len(bufferLines)))
|
||||
i = end
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// diffLineTexts extracts the text of each rendered row — the material the buffer
|
||||
// parser works on.
|
||||
func diffLineTexts(contents []gocui.DiffLineContent) []string {
|
||||
texts := make([]string, len(contents))
|
||||
for i, content := range contents {
|
||||
texts[i] = content.Text
|
||||
}
|
||||
return texts
|
||||
}
|
||||
|
||||
// renderingStatesDiffLines reports whether the renderer stated, for at least one row
|
||||
// of the rendering, which diff line it shows. The version-only record a renderer
|
||||
// announces the protocol with names no line, and doesn't count.
|
||||
//
|
||||
// The answer settles how the whole rendering is read. A renderer that states its
|
||||
// lines lays the diff out as it likes, so its text is no unified diff and must not be
|
||||
// parsed as one, not even for the rows it says nothing about. Such a row can read
|
||||
// like a diff header when the file being diffed is itself a diff; the parser would
|
||||
// take that for the start of a file section and place every untagged row below it
|
||||
// in a file the diff doesn't have. So the rows a renderer leaves untagged (dividers,
|
||||
// padding) have no identity, as the protocol has it. A rendering without any record
|
||||
// is a diff that describes itself, and is parsed as one.
|
||||
func renderingStatesDiffLines(contents []gocui.DiffLineContent) bool {
|
||||
return slices.ContainsFunc(contents, func(content gocui.DiffLineContent) bool {
|
||||
return slices.ContainsFunc(content.Metadata, func(record string) bool {
|
||||
_, ok := parseDiffLineMetadata(record)
|
||||
return ok
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// fileSectionBounds returns the half-open range [start, end) of the file section
|
||||
// containing targetIdx: the nearest line starting a section at or above it, up to
|
||||
// where that section ends. start is -1 when targetIdx is above the first file
|
||||
// section, or below the end of the last one that begins above it.
|
||||
func fileSectionBounds(bufferLines []string, targetIdx int) (start, end int) {
|
||||
for start = targetIdx; start >= 0; start-- {
|
||||
if !startsFileSection(bufferLines[start]) {
|
||||
continue
|
||||
}
|
||||
if end = fileSectionEnd(bufferLines, start); targetIdx < end {
|
||||
return start, end
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
// fileSectionEnd returns the line the file section beginning at start ends before.
|
||||
//
|
||||
// A file's section runs to the next one, since every line between them is part of
|
||||
// its diff. A submodule's runs only as far as what git writes for it — the line
|
||||
// naming it, and the log of the commits it moved over — because the lines after
|
||||
// that need not belong to any section at all. A diff renderer's output has no
|
||||
// "diff --git" line to stop at, and the rows it puts between one file and the next
|
||||
// belong to neither.
|
||||
func fileSectionEnd(bufferLines []string, start int) int {
|
||||
if submodulePath(bufferLines[start]) != "" {
|
||||
end := start + 1
|
||||
for end < len(bufferLines) && isSubmoduleLogLine(bufferLines[end]) {
|
||||
end++
|
||||
}
|
||||
return end
|
||||
}
|
||||
|
||||
for i := start + 1; i < len(bufferLines); i++ {
|
||||
if startsFileSection(bufferLines[i]) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(bufferLines)
|
||||
}
|
||||
|
||||
// startsFileSection reports whether the line opens a section of a diff: git's header
|
||||
// for a file of the repo, or the line a submodule's section begins with.
|
||||
func startsFileSection(line string) bool {
|
||||
return strings.HasPrefix(line, diffFilePrefix) || submodulePath(line) != ""
|
||||
}
|
||||
|
||||
// isSubmoduleLogLine reports whether the line is one of the commits git lists under
|
||||
// a submodule's header, which it writes as two spaces, the direction the commit was
|
||||
// moved in, and the commit's subject.
|
||||
func isSubmoduleLogLine(line string) bool {
|
||||
return strings.HasPrefix(line, " > ") || strings.HasPrefix(line, " < ")
|
||||
}
|
||||
|
||||
// submodulePath returns the submodule whose section the given line opens, and "" for
|
||||
// every other line.
|
||||
//
|
||||
// A submodule gets no "diff --git" header and no hunks: git states which commits it
|
||||
// moved between and lists them, so that one line is all there is to take the path
|
||||
// from. The prefix is tested first so that the pattern is run over next to no lines
|
||||
// of a diff.
|
||||
func submodulePath(line string) string {
|
||||
if !strings.HasPrefix(line, submodulePrefix) {
|
||||
return ""
|
||||
}
|
||||
if match := submoduleSectionPattern.FindStringSubmatch(line); match != nil {
|
||||
return match[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseFileSection parses one file's diff section (fileLines, starting at the line
|
||||
// that opens it) a single time and returns the identity of each of its
|
||||
// lines, indexed 1:1 with fileLines. patch.Parse's line indices line up with the
|
||||
// section's buffer lines, so the type and the old/new line numbers fall out of
|
||||
// the patch arithmetic. A submodule's section has no hunks at all, so every row of
|
||||
// it comes out as a header of the submodule, which is what they are: what git states
|
||||
// there is which commits it moved between, not lines of a file.
|
||||
//
|
||||
// Every line is left ok=false when the section has no
|
||||
// recoverable path or isn't a well-formed unified diff — the rendering
|
||||
// restructured it, and acting on a mis-parse would land us on the wrong line, so
|
||||
// the caller should fall back.
|
||||
//
|
||||
// endsTheBuffer says the section runs to the end of what we were given. That is
|
||||
// where a diff we have only part of breaks off. A long one is read a screenful
|
||||
// at a time and the rest as the user scrolls, so its last hunk holds fewer lines
|
||||
// than its header declares until the reading is done. Insisting on the whole
|
||||
// hunk there would leave every line of the file unresolved while the diff is the
|
||||
// one on screen, so a section in that position is held to what has arrived.
|
||||
func parseFileSection(fileLines []string, endsTheBuffer bool) []bufferLineParse {
|
||||
result := make([]bufferLineParse, len(fileLines))
|
||||
|
||||
relPath := pathFromDiffHeader(fileLines)
|
||||
if relPath == "" {
|
||||
return result
|
||||
}
|
||||
p := patch.Parse(strings.Join(fileLines, "\n"))
|
||||
isWellFormed := p.IsWellFormed
|
||||
if endsTheBuffer {
|
||||
isWellFormed = p.IsWellFormedSoFar
|
||||
}
|
||||
if !isWellFormed() {
|
||||
return result
|
||||
}
|
||||
patchLines := p.Lines()
|
||||
for i := range fileLines {
|
||||
if i >= len(patchLines) {
|
||||
break
|
||||
}
|
||||
parsed := parsedDiffLine{
|
||||
Path: relPath,
|
||||
Type: diffLineTypeForKind(patchLines[i].Kind),
|
||||
NewLine: p.LineNumberOfLine(i),
|
||||
}
|
||||
if parsed.Type == types.DiffLineDeleted {
|
||||
parsed.OldLine = p.OldLineNumberOfLine(i)
|
||||
}
|
||||
result[i] = bufferLineParse{parsed, true}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func diffLineTypeForKind(kind patch.PatchLineKind) types.DiffLineType {
|
||||
switch kind {
|
||||
case patch.PATCH_HEADER:
|
||||
return types.DiffLineFileHeader
|
||||
case patch.HUNK_HEADER:
|
||||
return types.DiffLineHunkHeader
|
||||
case patch.ADDITION:
|
||||
return types.DiffLineAdded
|
||||
case patch.DELETION:
|
||||
return types.DiffLineDeleted
|
||||
case patch.CONTEXT:
|
||||
return types.DiffLineContext
|
||||
default:
|
||||
return types.DiffLineOther
|
||||
}
|
||||
}
|
||||
|
||||
// pathFromDiffHeader extracts the new-file path of a single diff section. A
|
||||
// submodule's section states its path in the line it opens with. For a file of the
|
||||
// repo the path comes from the "+++ b/<path>" line, falling back to "--- a/<path>"
|
||||
// when the new path is /dev/null (a deleted file), and to the "diff --git" line when
|
||||
// there are no such lines at all (a pure rename, which has no hunks).
|
||||
func pathFromDiffHeader(fileLines []string) string {
|
||||
if path := submodulePath(fileLines[0]); path != "" {
|
||||
return path
|
||||
}
|
||||
|
||||
var oldPath, newPath string
|
||||
for _, line := range fileLines {
|
||||
if strings.HasPrefix(line, "@@") {
|
||||
break // past the header
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(line, "+++ "):
|
||||
newPath = pathFromDiffHeaderField(strings.TrimPrefix(line, "+++ "))
|
||||
case strings.HasPrefix(line, "--- "):
|
||||
oldPath = pathFromDiffHeaderField(strings.TrimPrefix(line, "--- "))
|
||||
}
|
||||
}
|
||||
|
||||
if newPath != "" && newPath != "/dev/null" {
|
||||
return newPath
|
||||
}
|
||||
if oldPath != "" && oldPath != "/dev/null" {
|
||||
return oldPath
|
||||
}
|
||||
return pathFromDiffGitLine(fileLines[0])
|
||||
}
|
||||
|
||||
// pathFromDiffHeaderField decodes one path field of a diff header — the part
|
||||
// after "--- " or "+++ ", or one of the two paths on the "diff --git" line —
|
||||
// into the repo-relative path it names.
|
||||
//
|
||||
// git spells such a field in three ways: plain; terminated by a tab, when the
|
||||
// path contains a space; or C-quoted as a whole, when the path contains
|
||||
// characters git won't print raw — which, with core.quotePath enabled (the
|
||||
// default), includes every non-ASCII byte, so `café` arrives as
|
||||
// `"b/caf\303\251"`. The quoting is Go's string syntax, octal escapes included,
|
||||
// so strconv decodes it for us.
|
||||
//
|
||||
// Returns "" for a quoted field we can't decode: better to resolve nothing than
|
||||
// to point a consumer at a path that doesn't exist.
|
||||
func pathFromDiffHeaderField(field string) string {
|
||||
field = strings.TrimSuffix(field, "\t")
|
||||
|
||||
if strings.HasPrefix(field, `"`) {
|
||||
unquoted, err := strconv.Unquote(field)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
field = unquoted
|
||||
}
|
||||
|
||||
return stripDiffPathPrefix(field)
|
||||
}
|
||||
|
||||
// stripDiffPathPrefix removes the a/ or b/ prefix git puts on the paths in a
|
||||
// diff header. We ask git for these prefixes explicitly (diff.noprefix=false),
|
||||
// so they are always there.
|
||||
func stripDiffPathPrefix(path string) string {
|
||||
if strings.HasPrefix(path, "a/") || strings.HasPrefix(path, "b/") {
|
||||
return path[2:]
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// parseDiffLineMetadata parses the payload of an OSC 1717 record, in which a
|
||||
// diff renderer states which line of which file it is rendering. The v1 payload
|
||||
// is positional and ';'-delimited:
|
||||
//
|
||||
// version;type;new-line;old-line;file
|
||||
//
|
||||
// The file comes last so that it may itself contain a ';'. The old-file line is
|
||||
// empty unless the line is a deletion, the only kind that needs it, and the
|
||||
// new-file line is empty on a file header, the one kind that has no line.
|
||||
//
|
||||
// ok is false for a payload of an unknown version or shape, so that the caller
|
||||
// can fall back to reading the rendered text.
|
||||
func parseDiffLineMetadata(payload string) (parsedDiffLine, bool) {
|
||||
fields := strings.SplitN(payload, ";", 5)
|
||||
if len(fields) < 5 || fields[0] != "1" {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
|
||||
lineType, ok := diffLineTypeFromMetadata(fields[1])
|
||||
if !ok {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
|
||||
newLine := 0
|
||||
if fields[2] != "" {
|
||||
var err error
|
||||
if newLine, err = strconv.Atoi(fields[2]); err != nil {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
} else if lineType != types.DiffLineFileHeader {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
|
||||
oldLine := 0
|
||||
if fields[3] != "" {
|
||||
var err error
|
||||
if oldLine, err = strconv.Atoi(fields[3]); err != nil {
|
||||
return parsedDiffLine{}, false
|
||||
}
|
||||
}
|
||||
|
||||
return parsedDiffLine{Path: fields[4], Type: lineType, NewLine: newLine, OldLine: oldLine}, true
|
||||
}
|
||||
|
||||
func diffLineTypeFromMetadata(typeField string) (types.DiffLineType, bool) {
|
||||
switch typeField {
|
||||
case "c":
|
||||
return types.DiffLineContext, true
|
||||
case "a":
|
||||
return types.DiffLineAdded, true
|
||||
case "d":
|
||||
return types.DiffLineDeleted, true
|
||||
case "f":
|
||||
return types.DiffLineFileHeader, true
|
||||
case "h":
|
||||
return types.DiffLineHunkHeader, true
|
||||
default:
|
||||
return types.DiffLineOther, false
|
||||
}
|
||||
}
|
||||
|
||||
// pathFromDiffGitLine extracts the new-file path from a "diff --git a/X b/X"
|
||||
// line, where the two paths are separated by a space and either may be quoted.
|
||||
// A path containing " b/" (or ` "b/`) would defeat this, but the +++/--- lines
|
||||
// are unambiguous and we only get here when they are absent.
|
||||
func pathFromDiffGitLine(line string) string {
|
||||
rest := strings.TrimPrefix(line, diffFilePrefix)
|
||||
if idx := strings.LastIndex(rest, ` "b/`); idx != -1 {
|
||||
return pathFromDiffHeaderField(rest[idx+1:])
|
||||
}
|
||||
if idx := strings.LastIndex(rest, " b/"); idx != -1 {
|
||||
return pathFromDiffHeaderField(rest[idx+1:])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// A two-file commit diff as it appears (decolorized) in the main view. file1 has
|
||||
// two consecutive deletions (grape, pear) that share a new-file line number;
|
||||
// file2 has two consecutive additions.
|
||||
const twoFileDiff = `diff --git a/file1.go b/file1.go
|
||||
index 1111111..2222222 100644
|
||||
--- a/file1.go
|
||||
+++ b/file1.go
|
||||
@@ -1,4 +1,2 @@
|
||||
apple
|
||||
-grape
|
||||
-pear
|
||||
lemon
|
||||
diff --git a/dir/file2.go b/dir/file2.go
|
||||
index 3333333..4444444 100644
|
||||
--- a/dir/file2.go
|
||||
+++ b/dir/file2.go
|
||||
@@ -10,2 +9,4 @@ func foo() {
|
||||
ctx
|
||||
+added1
|
||||
+added2
|
||||
ctx2`
|
||||
|
||||
func TestParseDiffLineFromBuffer(t *testing.T) {
|
||||
bufferLines := strings.Split(twoFileDiff, "\n")
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
targetIdx int
|
||||
expected parsedDiffLine
|
||||
expectOk bool
|
||||
}{
|
||||
{"file header", 0, parsedDiffLine{Path: "file1.go", Type: types.DiffLineFileHeader, NewLine: 1}, true},
|
||||
{"hunk header", 4, parsedDiffLine{Path: "file1.go", Type: types.DiffLineHunkHeader, NewLine: 1}, true},
|
||||
{"context line", 5, parsedDiffLine{Path: "file1.go", Type: types.DiffLineContext, NewLine: 1}, true},
|
||||
// The two deletions share new-file line 2 but have distinct old-file lines.
|
||||
{"first deletion", 6, parsedDiffLine{Path: "file1.go", Type: types.DiffLineDeleted, NewLine: 2, OldLine: 2}, true},
|
||||
{"second deletion", 7, parsedDiffLine{Path: "file1.go", Type: types.DiffLineDeleted, NewLine: 2, OldLine: 3}, true},
|
||||
// The second file: its path comes from the second "diff --git" section,
|
||||
// and its additions get distinct new-file line numbers.
|
||||
{"first addition", 15, parsedDiffLine{Path: "dir/file2.go", Type: types.DiffLineAdded, NewLine: 10}, true},
|
||||
{"second addition", 16, parsedDiffLine{Path: "dir/file2.go", Type: types.DiffLineAdded, NewLine: 11}, true},
|
||||
{"out of range", 999, parsedDiffLine{}, false},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
result, ok := parseDiffLineFromBuffer(bufferLines, s.targetIdx)
|
||||
assert.Equal(t, s.expectOk, ok)
|
||||
if s.expectOk {
|
||||
assert.Equal(t, s.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferRename(t *testing.T) {
|
||||
// A rename with no content change has no hunks and no +++/--- lines, so the
|
||||
// path has to come from the "diff --git" line; a rename with a content
|
||||
// change has them, and they carry the new path.
|
||||
pureRename := strings.Split(`diff --git a/old.go b/new.go
|
||||
similarity index 100%
|
||||
rename from old.go
|
||||
rename to new.go`, "\n")
|
||||
|
||||
result, ok := parseDiffLineFromBuffer(pureRename, 2)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "new.go", Type: types.DiffLineFileHeader, NewLine: 1}, result)
|
||||
|
||||
renameWithModification := strings.Split(`diff --git a/old.go b/new.go
|
||||
similarity index 62%
|
||||
rename from old.go
|
||||
rename to new.go
|
||||
index 1111111..2222222 100644
|
||||
--- a/old.go
|
||||
+++ b/new.go
|
||||
@@ -1,2 +1,2 @@
|
||||
apple
|
||||
-grape
|
||||
+kiwi`, "\n")
|
||||
|
||||
result, ok = parseDiffLineFromBuffer(renameWithModification, 10)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "new.go", Type: types.DiffLineAdded, NewLine: 2}, result)
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferDeletedFile(t *testing.T) {
|
||||
// The new path is /dev/null, so the identity comes from the old path.
|
||||
deletedFile := strings.Split(`diff --git a/gone.go b/gone.go
|
||||
deleted file mode 100644
|
||||
index 1111111..0000000
|
||||
--- a/gone.go
|
||||
+++ /dev/null
|
||||
@@ -1,2 +0,0 @@
|
||||
-apple
|
||||
-grape`, "\n")
|
||||
|
||||
result, ok := parseDiffLineFromBuffer(deletedFile, 7)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "gone.go", Type: types.DiffLineDeleted, NewLine: 0, OldLine: 2}, result)
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferSubmodule(t *testing.T) {
|
||||
// A submodule has no "diff --git" header and no hunks: git opens its section with
|
||||
// the commits it moved between and lists them below. So the section ends the one
|
||||
// above it, and every row of it belongs to the submodule as a whole.
|
||||
withSubmodule := strings.Split(`diff --git a/file.txt b/file.txt
|
||||
index 1111111..2222222 100644
|
||||
--- a/file.txt
|
||||
+++ b/file.txt
|
||||
@@ -1,2 +1,3 @@
|
||||
hello
|
||||
world
|
||||
+world
|
||||
Submodule modules/xyz a32f27c..2d9f921:
|
||||
> bump the thing`, "\n")
|
||||
|
||||
for _, targetIdx := range []int{8, 9} {
|
||||
result, ok := parseDiffLineFromBuffer(withSubmodule, targetIdx)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t,
|
||||
parsedDiffLine{Path: "modules/xyz", Type: types.DiffLineFileHeader, NewLine: 1},
|
||||
result, "line %d", targetIdx)
|
||||
}
|
||||
|
||||
result, ok := parseDiffLineFromBuffer(withSubmodule, 7)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "file.txt", Type: types.DiffLineAdded, NewLine: 3}, result)
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferSubmoduleInARendering(t *testing.T) {
|
||||
// A diff renderer passes the lines git writes for a submodule through as they
|
||||
// are, while printing nothing below them that a section could end at. The
|
||||
// section has to end where what git writes for the submodule ends all the same:
|
||||
// the rows below belong to the other files of the diff, and can only be placed
|
||||
// by the records the renderer states for them.
|
||||
rendered := strings.Split(`Submodule modules/xyz a32f27c..2d9f921:
|
||||
> bump the thing
|
||||
|
||||
products/a.txt
|
||||
|
||||
one
|
||||
two`, "\n")
|
||||
|
||||
all := parseAllDiffLinesFromBuffer(rendered)
|
||||
assert.Equal(t, "modules/xyz", all[0].parsed.Path)
|
||||
assert.Equal(t, "modules/xyz", all[1].parsed.Path)
|
||||
for i := 2; i < len(rendered); i++ {
|
||||
assert.False(t, all[i].ok, "line %d: %q", i, rendered[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmodulePath(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
line string
|
||||
expected string
|
||||
}{
|
||||
{"moved on", "Submodule modules/xyz a32f27c..2d9f921:", "modules/xyz"},
|
||||
{"moved back", "Submodule modules/xyz 2d9f921..a32f27c (rewind):", "modules/xyz"},
|
||||
{"moved sideways", "Submodule modules/xyz a32f27c...2d9f921:", "modules/xyz"},
|
||||
{"added", "Submodule modules/xyz 0000000...2d9f921 (new submodule)", "modules/xyz"},
|
||||
{"removed", "Submodule modules/xyz a32f27c...0000000 (submodule deleted)", "modules/xyz"},
|
||||
{"commits missing", "Submodule modules/xyz a32f27c...2d9f921 (commits not present)", "modules/xyz"},
|
||||
{"dirty", "Submodule modules/xyz contains modified content", "modules/xyz"},
|
||||
{"with something new in it", "Submodule modules/xyz contains untracked content", "modules/xyz"},
|
||||
// git writes the path unquoted, so one with a space in it, or one ending in
|
||||
// something that reads like a range of commits, is told apart by matching the
|
||||
// last range on the line.
|
||||
{"path with a space", "Submodule my modules/xyz a32f27c..2d9f921:", "my modules/xyz"},
|
||||
{"path reading like a range", "Submodule a32f27c..2d9f921 deadbee..fa1afe1:", "a32f27c..2d9f921"},
|
||||
// A line of a file that reads like one of these is indented by the column the
|
||||
// diff states the line's side in, so it cannot be mistaken for one.
|
||||
{"a line of a file", " Submodule modules/xyz contains modified content", ""},
|
||||
{"something else entirely", "Submodule support was added", ""},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, submodulePath(s.line))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferNotADiff(t *testing.T) {
|
||||
// A rendering with no "diff --git" line can't be parsed, so the caller falls
|
||||
// back rather than acting on the line.
|
||||
bufferLines := []string{"some", "lines", "that", "are not a diff"}
|
||||
_, ok := parseDiffLineFromBuffer(bufferLines, 2)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferGutterMangled(t *testing.T) {
|
||||
// A diff renderer that moves the line numbers into a gutter keeps the diff
|
||||
// and hunk headers but pushes the +/- markers off the start of each body
|
||||
// line, so every line reads as context. The body no longer matches the hunk
|
||||
// header, so we refuse to parse rather than return a confident mis-parse.
|
||||
mangled := strings.Split(`diff --git a/file1.txt b/file1.txt
|
||||
index 1111111..2222222 100644
|
||||
--- a/file1.txt
|
||||
+++ b/file1.txt
|
||||
@@ -1,5 +1,3 @@
|
||||
1 ⋮ 1 │ apple
|
||||
2 ⋮ │-grape
|
||||
3 ⋮ │-pear
|
||||
4 ⋮ 2 │ lemon
|
||||
5 ⋮ 3 │ mango`, "\n")
|
||||
|
||||
_, ok := parseDiffLineFromBuffer(mangled, 6)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferReadInPart(t *testing.T) {
|
||||
lines := strings.Split(twoFileDiff, "\n")
|
||||
|
||||
// A long diff is read a screenful at a time, so the buffer breaks off part way
|
||||
// through a hunk. The lines that did arrive are resolved all the same, since
|
||||
// holding out for the whole hunk would leave the diff on screen with nothing to
|
||||
// act on.
|
||||
cutShort := lines[:len(lines)-1]
|
||||
result, ok := parseDiffLineFromBuffer(cutShort, 15)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "dir/file2.go", Type: types.DiffLineAdded, NewLine: 10}, result)
|
||||
|
||||
// Only the section the buffer breaks off in is read that way. One that another
|
||||
// section follows is all there, so a hunk short of what its header declares means
|
||||
// the rendering restructured the diff, and none of it is resolved.
|
||||
shortFirstSection := append(slices.Clone(lines[:8]), lines[9:]...)
|
||||
_, ok = parseDiffLineFromBuffer(shortFirstSection, 5)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestPathFromDiffHeaderField(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
field string
|
||||
expected string
|
||||
}{
|
||||
{"new side", "b/file.go", "file.go"},
|
||||
{"old side", "a/file.go", "file.go"},
|
||||
{"a missing file", "/dev/null", "/dev/null"},
|
||||
// git terminates the field with a tab when the path has a space in it.
|
||||
{"path with a space", "b/with space.go\t", "with space.go"},
|
||||
// With core.quotePath enabled (the default) every non-ASCII byte is
|
||||
// escaped, and the field is quoted as a whole, prefix included.
|
||||
{"non-ASCII path", `"b/caf\303\251.go"`, "café.go"},
|
||||
{"non-ASCII path with a space", "\"b/caf\\303\\251 x.go\"\t", "café x.go"},
|
||||
{"path with a double quote", `"b/we\"ird.go"`, `we"ird.go`},
|
||||
{"path with a backslash", `"b/back\\slash.go"`, `back\slash.go`},
|
||||
{"path with a tab", `"b/tab\there.go"`, "tab\there.go"},
|
||||
{"undecodable", `"b/unterminated`, ""},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, pathFromDiffHeaderField(s.field))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDiffLineFromBufferQuotedPath(t *testing.T) {
|
||||
// A rename of a file whose name needs quoting, with a content change: the
|
||||
// path is quoted on the "diff --git" line and on both of the +++/--- lines.
|
||||
renamed := []string{
|
||||
`diff --git "a/caf\303\251 old.go" "b/caf\303\251 new.go"`,
|
||||
"similarity index 62%",
|
||||
`rename from "caf\303\251 old.go"`,
|
||||
`rename to "caf\303\251 new.go"`,
|
||||
"index 1111111..2222222 100644",
|
||||
"--- \"a/caf\\303\\251 old.go\"\t",
|
||||
"+++ \"b/caf\\303\\251 new.go\"\t",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
" apple",
|
||||
"-grape",
|
||||
"+kiwi",
|
||||
}
|
||||
|
||||
result, ok := parseDiffLineFromBuffer(renamed, 10)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "café new.go", Type: types.DiffLineAdded, NewLine: 2}, result)
|
||||
|
||||
// The same rename without a content change has no +++/--- lines, so the path
|
||||
// comes from the "diff --git" line, where both paths are quoted.
|
||||
result, ok = parseDiffLineFromBuffer(renamed[:4], 2)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, parsedDiffLine{Path: "café new.go", Type: types.DiffLineFileHeader, NewLine: 1}, result)
|
||||
}
|
||||
|
||||
func TestParseAllDiffLinesFromBuffer(t *testing.T) {
|
||||
// Some decoration above the diff, which belongs to no file section: a commit
|
||||
// message and a diffstat, as `git show` renders them.
|
||||
bufferLines := append(
|
||||
[]string{"commit 1234567", "", " do a thing", "", " file1.go | 2 --", ""},
|
||||
strings.Split(twoFileDiff, "\n")...,
|
||||
)
|
||||
|
||||
all := parseAllDiffLinesFromBuffer(bufferLines)
|
||||
|
||||
// The batch parse resolves each file section once, and has to agree with
|
||||
// resolving the lines one at a time.
|
||||
assert.Len(t, all, len(bufferLines))
|
||||
for i := range bufferLines {
|
||||
parsed, ok := parseDiffLineFromBuffer(bufferLines, i)
|
||||
assert.Equal(t, bufferLineParse{parsed, ok}, all[i], "line %d: %q", i, bufferLines[i])
|
||||
}
|
||||
|
||||
// The lines above the first file section are left unresolved.
|
||||
for i := range 6 {
|
||||
assert.False(t, all[i].ok)
|
||||
}
|
||||
assert.True(t, all[6].ok)
|
||||
}
|
||||
|
||||
func TestParseDiffLineMetadata(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
payload string
|
||||
expected parsedDiffLine
|
||||
expectOk bool
|
||||
}{
|
||||
{"context", "1;c;1;;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineContext, NewLine: 1}, true},
|
||||
{"added", "1;a;3;;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineAdded, NewLine: 3}, true},
|
||||
// A deletion carries both numbers; two consecutive deletions share the
|
||||
// new-file line and differ only in the old-file one.
|
||||
{"first deletion", "1;d;2;2;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineDeleted, NewLine: 2, OldLine: 2}, true},
|
||||
{"second deletion", "1;d;2;3;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineDeleted, NewLine: 2, OldLine: 3}, true},
|
||||
// A whole-file deletion has new-file position 0 and the old path.
|
||||
{"deleted file", "1;d;0;1;gone.txt", parsedDiffLine{Path: "gone.txt", Type: types.DiffLineDeleted, NewLine: 0, OldLine: 1}, true},
|
||||
// The path is the last field, so a ';' within it survives.
|
||||
{"path with semicolon", "1;c;5;;weird;name.txt", parsedDiffLine{Path: "weird;name.txt", Type: types.DiffLineContext, NewLine: 5}, true},
|
||||
// A renderer may state the path absolutely; the parser keeps it verbatim
|
||||
// and leaves resolving it to the caller.
|
||||
{"absolute path", "1;a;7;;/abs/foo.txt", parsedDiffLine{Path: "/abs/foo.txt", Type: types.DiffLineAdded, NewLine: 7}, true},
|
||||
// A file header has no line number; a hunk header carries the new-file
|
||||
// line of the hunk's first line (0 for a whole-file deletion, mirroring
|
||||
// `@@ -1,N +0,0 @@`).
|
||||
{"file header", "1;f;;;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineFileHeader}, true},
|
||||
{"hunk header", "1;h;10;;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineHunkHeader, NewLine: 10}, true},
|
||||
{"hunk header of a deleted file", "1;h;0;;gone.txt", parsedDiffLine{Path: "gone.txt", Type: types.DiffLineHunkHeader, NewLine: 0}, true},
|
||||
// A file header's line number is always empty, but a renderer that fills
|
||||
// it in anyway is taken at its word rather than rejected.
|
||||
{"file header with a line number", "1;f;10;;foo.txt", parsedDiffLine{Path: "foo.txt", Type: types.DiffLineFileHeader, NewLine: 10}, true},
|
||||
|
||||
{"unknown version", "2;c;1;;foo.txt", parsedDiffLine{}, false},
|
||||
{"unknown type", "1;x;1;;foo.txt", parsedDiffLine{}, false},
|
||||
{"too few fields", "1;c;1", parsedDiffLine{}, false},
|
||||
{"non-numeric new-line", "1;c;x;;foo.txt", parsedDiffLine{}, false},
|
||||
{"non-numeric old-line", "1;d;2;y;foo.txt", parsedDiffLine{}, false},
|
||||
// Only a file header may omit the new-file line; on any other kind the
|
||||
// record is malformed, and rejecting it falls the row back to the diff
|
||||
// text rather than acting on a line number we don't have.
|
||||
{"empty new-line on a content line", "1;c;;;foo.txt", parsedDiffLine{}, false},
|
||||
{"empty new-line on a hunk header", "1;h;;;foo.txt", parsedDiffLine{}, false},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
result, ok := parseDiffLineMetadata(s.payload)
|
||||
assert.Equal(t, s.expectOk, ok)
|
||||
if s.expectOk {
|
||||
assert.Equal(t, s.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderingStatesDiffLines(t *testing.T) {
|
||||
row := func(text string, records ...string) gocui.DiffLineContent {
|
||||
return gocui.DiffLineContent{Text: text, Metadata: records}
|
||||
}
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
contents []gocui.DiffLineContent
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "a rendering without records is read as a diff",
|
||||
contents: []gocui.DiffLineContent{row("diff --git a/foo.txt b/foo.txt"), row("+one")},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "a record on any row makes the records the source",
|
||||
contents: []gocui.DiffLineContent{row("foo.txt"), row("one", "1;c;1;;foo.txt"), row("")},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
// A renderer announces the protocol with a record that names no line; a
|
||||
// rendering with nothing but that one says nothing about its rows.
|
||||
name: "the version-only handshake record doesn't count",
|
||||
contents: []gocui.DiffLineContent{row("foo.txt", "1"), row("one")},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "records of a version we don't understand don't count",
|
||||
contents: []gocui.DiffLineContent{row("one", "2;c;1;;foo.txt")},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "an empty rendering states nothing",
|
||||
contents: nil,
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
assert.Equal(t, s.expected, renderingStatesDiffLines(s.contents))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ type Helpers struct {
|
||||
Snake *SnakeHelper
|
||||
// lives in context package because our contexts need it to render to main
|
||||
Diff *DiffHelper
|
||||
DiffLine *DiffLineHelper
|
||||
Repos *ReposHelper
|
||||
RecordDirectory *RecordDirectoryHelper
|
||||
Update *UpdateHelper
|
||||
@@ -76,6 +77,7 @@ func NewStubHelpers() *Helpers {
|
||||
Commits: &CommitsHelper{},
|
||||
Snake: &SnakeHelper{},
|
||||
Diff: &DiffHelper{},
|
||||
DiffLine: &DiffLineHelper{},
|
||||
Repos: &ReposHelper{},
|
||||
RecordDirectory: &RecordDirectoryHelper{},
|
||||
Update: &UpdateHelper{},
|
||||
|
||||
@@ -94,6 +94,23 @@ func (self *InlineStatusHelper) WithInlineStatus(opts InlineStatusOpts, f func(g
|
||||
}
|
||||
}
|
||||
|
||||
// Runs f on a worker with all the given items shown as being in the given
|
||||
// operation while it runs
|
||||
func WithInlineStatusOnItems[T types.HasUrn](c *HelperCommon, items []T, operation types.ItemOperation, contextKey types.ContextKey, f func(gocui.Task) error) error {
|
||||
return c.WithInlineStatus(items[0], operation, contextKey, func(task gocui.Task) error {
|
||||
for _, item := range items[1:] {
|
||||
c.State().SetItemOperation(item, operation)
|
||||
}
|
||||
defer func() {
|
||||
for _, item := range items[1:] {
|
||||
c.State().ClearItemOperation(item)
|
||||
}
|
||||
}()
|
||||
|
||||
return f(task)
|
||||
})
|
||||
}
|
||||
|
||||
func (self *InlineStatusHelper) start(opts InlineStatusOpts) {
|
||||
self.c.State().SetItemOperation(opts.Item, opts.Operation)
|
||||
|
||||
|
||||
@@ -525,7 +525,7 @@ func (self *MergeAndRebaseHelper) MergeRefIntoCheckedOutBranch(refName string) e
|
||||
}
|
||||
|
||||
wantFastForward, wantNonFastForward := self.fastForwardMergeUserPreference()
|
||||
canFastForward := self.c.Git().Branch.CanDoFastForwardMerge(refName)
|
||||
canFastForward := self.c.Git().Branch.IsAncestor("HEAD", refName)
|
||||
|
||||
var firstRegularMergeItem *types.MenuItem
|
||||
var secondRegularMergeItem *types.MenuItem
|
||||
|
||||
@@ -348,6 +348,39 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr
|
||||
// branchesAndRemotesWg gives the fetch the happens-before to read them.
|
||||
var loadedBranches []*models.Branch
|
||||
var loadedRemotes []*models.Remote
|
||||
|
||||
// The branches view also shows a pull request icon against a branch, and
|
||||
// those icons come from the remotes, so the branches refresh waits for the
|
||||
// remotes as well, for the same reason it waits for the worktrees. Only the
|
||||
// remotes themselves are waited for, not their branches, which are loaded
|
||||
// afterwards (see refreshRemotes). The remotes scope has to be started before
|
||||
// the branches scope for that wait to be safe. One of the early returns below
|
||||
// would otherwise leave the branches refresh waiting for a scope that never
|
||||
// started.
|
||||
remotesWg := sync.WaitGroup{}
|
||||
waitForRemotes := func() { remotesWg.Wait() }
|
||||
if scopeSet.Includes(types.REMOTES) {
|
||||
// Capture the previously-selected remote on the UI thread; the worker
|
||||
// needs it to keep the remote-branches selection valid, and reading
|
||||
// the Remotes context off the UI thread races its render.
|
||||
var prevSelectedRemote *models.Remote
|
||||
if !self.captureOnUIThread(calledFromWorker, env.background, func() {
|
||||
prevSelectedRemote = self.c.Contexts().Remotes.GetSelected()
|
||||
}) {
|
||||
return
|
||||
}
|
||||
remotesWg.Add(1)
|
||||
remotesLoaded := sync.OnceFunc(remotesWg.Done)
|
||||
branchesAndRemotesWg.Add(1)
|
||||
refresh("remotes", func() {
|
||||
// Signal again on the way out, so that a future early return in
|
||||
// refreshRemotes can't leave the branches refresh waiting for ever.
|
||||
defer remotesLoaded()
|
||||
defer branchesAndRemotesWg.Done()
|
||||
loadedRemotes = self.refreshRemotes(prevSelectedRemote, remotesLoaded, env)
|
||||
})
|
||||
}
|
||||
|
||||
if scopeSet.Includes(types.COMMITS) {
|
||||
// Capture the refresh's inputs (model, contexts, modes) on the UI
|
||||
// thread, before the git work is dispatched to a worker, so the worker
|
||||
@@ -390,7 +423,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr
|
||||
if self.c.UserConfig().Git.LocalBranchSortOrder == "recency" {
|
||||
branchesAndRemotesWg.Add(1)
|
||||
refresh("reflog and branches", func() {
|
||||
loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, waitForWorktrees, options.BranchSelection, options.SelectTopReflogCommit, env)
|
||||
loadedBranches = self.refreshReflogAndBranches(capturedReflog, capturedBranches, waitForWorktrees, waitForRemotes, options.BranchSelection, options.SelectTopReflogCommit, env)
|
||||
branchesAndRemotesWg.Done()
|
||||
})
|
||||
} else {
|
||||
@@ -399,7 +432,7 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr
|
||||
// Not a recency sort, so branches doesn't depend on the reflog
|
||||
// being fresh; it runs concurrently with the reflog refresh
|
||||
// below and uses the reflog we captured up front, as it always has.
|
||||
loadedBranches = self.refreshBranches(capturedBranches, waitForWorktrees, options.BranchSelection, true, capturedReflog.reflogCommits, env)
|
||||
loadedBranches = self.refreshBranches(capturedBranches, waitForWorktrees, waitForRemotes, options.BranchSelection, true, capturedReflog.reflogCommits, env)
|
||||
branchesAndRemotesWg.Done()
|
||||
})
|
||||
refresh("reflog", func() {
|
||||
@@ -458,23 +491,6 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr
|
||||
refresh("tags", func() { _ = self.refreshTags(env) })
|
||||
}
|
||||
|
||||
if scopeSet.Includes(types.REMOTES) {
|
||||
// Capture the previously-selected remote on the UI thread; the worker
|
||||
// needs it to keep the remote-branches selection valid, and reading
|
||||
// the Remotes context off the UI thread races its render.
|
||||
var prevSelectedRemote *models.Remote
|
||||
if !self.captureOnUIThread(calledFromWorker, env.background, func() {
|
||||
prevSelectedRemote = self.c.Contexts().Remotes.GetSelected()
|
||||
}) {
|
||||
return
|
||||
}
|
||||
branchesAndRemotesWg.Add(1)
|
||||
refresh("remotes", func() {
|
||||
loadedRemotes, _ = self.refreshRemotes(prevSelectedRemote, env)
|
||||
branchesAndRemotesWg.Done()
|
||||
})
|
||||
}
|
||||
|
||||
if scopeSet.Includes(types.PULL_REQUESTS) {
|
||||
// Fetching pull requests talks to the GitHub API over the network; on
|
||||
// a bad connection that request can stall for a long time. It runs no
|
||||
@@ -726,19 +742,19 @@ func (self *RefreshHelper) captureBranchState() capturedBranchState {
|
||||
}
|
||||
}
|
||||
|
||||
func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflogState, capturedBranches capturedBranchState, waitForWorktrees func(), branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, env refreshEnv) []*models.Branch {
|
||||
func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflogState, capturedBranches capturedBranchState, waitForWorktrees func(), waitForRemotes func(), branchSelection types.BranchSelectionBehavior, selectTopReflogCommit bool, env refreshEnv) []*models.Branch {
|
||||
switch self.c.State().GetRepoState().GetStartupStage() {
|
||||
case types.INITIAL:
|
||||
// Return the immediate (non-recency) load's branches; the recency-sorted
|
||||
// reload below runs on its own worker after we return. Both hold the same
|
||||
// set of branches, which is all the caller (the PR fetch) needs.
|
||||
branches := self.refreshBranches(capturedBranches, waitForWorktrees, branchSelection, false, capturedReflog.reflogCommits, env)
|
||||
branches := self.refreshBranches(capturedBranches, waitForWorktrees, waitForRemotes, branchSelection, false, capturedReflog.reflogCommits, env)
|
||||
|
||||
self.onWorker(env.background, func(_ gocui.Task) error {
|
||||
reflogCommits, _ := self.refreshReflogCommits(capturedReflog, env, false)
|
||||
// The load above already waited for the worktrees, so this one has
|
||||
// nothing left to wait for.
|
||||
self.refreshBranches(capturedBranches, func() {}, types.SelectCheckedOutBranch, true, reflogCommits, env)
|
||||
// The load above already waited for the worktrees and the remotes, so
|
||||
// this one has nothing left to wait for.
|
||||
self.refreshBranches(capturedBranches, func() {}, func() {}, types.SelectCheckedOutBranch, true, reflogCommits, env)
|
||||
self.c.State().GetRepoState().SetStartupStage(types.COMPLETE)
|
||||
return nil
|
||||
})
|
||||
@@ -747,7 +763,7 @@ func (self *RefreshHelper) refreshReflogAndBranches(capturedReflog capturedReflo
|
||||
|
||||
case types.COMPLETE:
|
||||
reflogCommits, _ := self.refreshReflogCommits(capturedReflog, env, selectTopReflogCommit)
|
||||
return self.refreshBranches(capturedBranches, waitForWorktrees, branchSelection, true, reflogCommits, env)
|
||||
return self.refreshBranches(capturedBranches, waitForWorktrees, waitForRemotes, branchSelection, true, reflogCommits, env)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1134,14 +1150,14 @@ func (self *RefreshHelper) refreshStateSubmoduleConfigs(env refreshEnv) ([]*mode
|
||||
|
||||
// self.refreshStatus is called at the end of this because that's when we can
|
||||
// be sure there is a State.Model.Branches array to pick the current branch from
|
||||
func (self *RefreshHelper) refreshBranches(captured capturedBranchState, waitForWorktrees func(), branchSelection types.BranchSelectionBehavior, loadBehindCounts bool, reflogCommits []*models.Commit, env refreshEnv) []*models.Branch {
|
||||
func (self *RefreshHelper) refreshBranches(captured capturedBranchState, waitForWorktrees func(), waitForRemotes func(), branchSelection types.BranchSelectionBehavior, loadExtraInfo bool, reflogCommits []*models.Commit, env refreshEnv) []*models.Branch {
|
||||
loadSeq := self.branchLoadSeq.Add(1)
|
||||
|
||||
branches, err := env.git.Loaders.BranchLoader.Load(
|
||||
reflogCommits,
|
||||
captured.mainBranches,
|
||||
captured.oldBranches,
|
||||
loadBehindCounts,
|
||||
loadExtraInfo,
|
||||
func(f func() error) {
|
||||
self.onWorker(env.background, func(_ gocui.Task) error {
|
||||
err := f()
|
||||
@@ -1168,9 +1184,11 @@ func (self *RefreshHelper) refreshBranches(captured capturedBranchState, waitFor
|
||||
self.c.Log.Error(err)
|
||||
}
|
||||
|
||||
// Render only once the refreshed worktrees are in the model; the branches
|
||||
// view shows them against the branches (see performRefresh).
|
||||
// Render only once the refreshed worktrees and remotes are in the model. The
|
||||
// branches view shows the worktrees against the branches, and the pull
|
||||
// request icons come from the remotes (see performRefresh).
|
||||
waitForWorktrees()
|
||||
waitForRemotes()
|
||||
|
||||
self.onUIThreadUnlessRepoChanged(env, func() {
|
||||
// Drop this write if a branch load that started later has already applied
|
||||
@@ -1544,14 +1562,16 @@ func (self *RefreshHelper) refreshReflogCommits(captured capturedReflogState, en
|
||||
return reflogCommits, nil
|
||||
}
|
||||
|
||||
func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env refreshEnv) ([]*models.Remote, error) {
|
||||
remotes, err := env.git.Loaders.RemoteLoader.GetRemotes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, remotesLoaded func(), env refreshEnv) []*models.Remote {
|
||||
remotes := env.git.Loaders.RemoteLoader.GetRemotes()
|
||||
|
||||
// Put the remotes in the model before loading their branches below. The map
|
||||
// from branches to pull requests is built from the remotes' URLs (see
|
||||
// GenerateGithubPullRequestMap), and loading the remote branches takes much
|
||||
// longer than loading the remotes themselves. If the map had to wait for the
|
||||
// branches, the pull request icons would show up long after the branch list.
|
||||
self.onUIThreadUnlessRepoChanged(env, func() {
|
||||
self.c.Model().Remotes = remotes
|
||||
self.c.Model().Remotes = remotesWithCarriedOverBranches(remotes, self.c.Model().Remotes)
|
||||
|
||||
hadPrs := len(self.c.Model().PullRequestsMap) != 0
|
||||
self.rebuildPullRequestsMap()
|
||||
@@ -1559,11 +1579,35 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env
|
||||
// if we didn't have PRs in the map before but now we do, we need to redraw the branches view
|
||||
self.refreshView(self.c.Contexts().Branches, env)
|
||||
}
|
||||
})
|
||||
|
||||
// Tell the branches refresh that the remotes write is queued, so that it can
|
||||
// queue its own write behind ours and render the icons with the branches.
|
||||
remotesLoaded()
|
||||
|
||||
self.refreshView(self.c.Contexts().Remotes, env)
|
||||
|
||||
remoteBranchesByRemoteName, err := env.git.Loaders.RemoteLoader.GetRemoteBranchesByRemoteName()
|
||||
if err != nil {
|
||||
// The remotes themselves are in the model already; log the failure and
|
||||
// leave them there without their branches.
|
||||
self.c.Log.Error(err)
|
||||
return remotes
|
||||
}
|
||||
|
||||
remotesWithBranches := lo.Map(remotes, func(remote *models.Remote, _ int) *models.Remote {
|
||||
withBranches := *remote
|
||||
withBranches.Branches = remoteBranchesByRemoteName[remote.Name]
|
||||
return &withBranches
|
||||
})
|
||||
|
||||
self.onUIThreadUnlessRepoChanged(env, func() {
|
||||
self.c.Model().Remotes = remotesWithBranches
|
||||
|
||||
// we need to ensure our selected remote branches aren't now outdated
|
||||
if prevSelectedRemote != nil && self.c.Model().RemoteBranches != nil {
|
||||
// find remote now
|
||||
for _, remote := range remotes {
|
||||
for _, remote := range remotesWithBranches {
|
||||
if remote.Name == prevSelectedRemote.Name {
|
||||
self.c.Model().RemoteBranches = remote.Branches
|
||||
break
|
||||
@@ -1574,7 +1618,25 @@ func (self *RefreshHelper) refreshRemotes(prevSelectedRemote *models.Remote, env
|
||||
|
||||
self.refreshView(self.c.Contexts().Remotes, env)
|
||||
self.refreshView(self.c.Contexts().RemoteBranches, env)
|
||||
return remotes, nil
|
||||
return remotesWithBranches
|
||||
}
|
||||
|
||||
// remotesWithCarriedOverBranches returns copies of the freshly loaded remotes,
|
||||
// each carrying the branches of the remote of the same name in the model. Those
|
||||
// branches are the ones the views are showing right now, so carrying them over
|
||||
// keeps the remote branches, and the branch counts in the remotes view, in place
|
||||
// until the fresh ones are loaded. The copies also leave the remotes we were
|
||||
// given untouched, so that the caller can go on reading them off the UI thread.
|
||||
func remotesWithCarriedOverBranches(remotes []*models.Remote, modelRemotes []*models.Remote) []*models.Remote {
|
||||
return lo.Map(remotes, func(remote *models.Remote, _ int) *models.Remote {
|
||||
copied := *remote
|
||||
if previous, found := lo.Find(modelRemotes, func(modelRemote *models.Remote) bool {
|
||||
return modelRemote.Name == remote.Name
|
||||
}); found {
|
||||
copied.Branches = previous.Branches
|
||||
}
|
||||
return &copied
|
||||
})
|
||||
}
|
||||
|
||||
func (self *RefreshHelper) loadWorktrees(env refreshEnv) []*models.Worktree {
|
||||
|
||||
@@ -2,7 +2,6 @@ package helpers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -11,6 +10,7 @@ import (
|
||||
appTypes "github.com/jesseduffield/lazygit/pkg/app/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/direnv"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/env"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
@@ -62,46 +62,252 @@ func (self *ReposHelper) EnterSubmodule(submodule *models.SubmoduleConfig) error
|
||||
return self.switchTo(submodule.FullPath(), self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT)
|
||||
}
|
||||
|
||||
// What a repo has checked out. Exactly one of the two fields is set.
|
||||
type headInfo struct {
|
||||
// The name of the checked-out branch.
|
||||
branch string
|
||||
// The commit HEAD is detached at.
|
||||
hash string
|
||||
}
|
||||
|
||||
// gitDirOfRepo returns the directory that holds the git data of the repo at
|
||||
// repoPath, and whether it could be found. An ordinary repo keeps that data in
|
||||
// a .git directory; a worktree and a submodule have a .git file naming the
|
||||
// directory instead.
|
||||
func gitDirOfRepo(repoPath string) (string, bool) {
|
||||
gitDirPath := filepath.Join(repoPath, ".git")
|
||||
|
||||
stat, err := os.Stat(gitDirPath)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if stat.IsDir() {
|
||||
return gitDirPath, true
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(gitDirPath)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
gitDir, ok := strings.CutPrefix(strings.TrimSpace(string(content)), "gitdir: ")
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
// A relative name is relative to the repo. Git writes one for a submodule,
|
||||
// and for a worktree created with --relative-paths.
|
||||
if !filepath.IsAbs(gitDir) {
|
||||
gitDir = filepath.Join(repoPath, gitDir)
|
||||
}
|
||||
return gitDir, true
|
||||
}
|
||||
|
||||
// The branch git names in the HEAD file of a repo that keeps its refs in a
|
||||
// reftable. The refs live in a binary table there, and the name in HEAD
|
||||
// resolves nowhere, so that a reader of the file gets an error instead of a
|
||||
// stale answer.
|
||||
const reftablePlaceholderBranch = ".invalid"
|
||||
|
||||
// readHeadInfo reads the HEAD file of the repo at repoPath to find out what it
|
||||
// has checked out, and reports whether that worked.
|
||||
func readHeadInfo(repoPath string) (headInfo, bool) {
|
||||
gitDir, ok := gitDirOfRepo(repoPath)
|
||||
if !ok {
|
||||
return headInfo{}, false
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(filepath.Join(gitDir, "HEAD"))
|
||||
if err != nil {
|
||||
return headInfo{}, false
|
||||
}
|
||||
|
||||
head := strings.TrimSpace(string(content))
|
||||
if branch, ok := strings.CutPrefix(head, "ref: refs/heads/"); ok {
|
||||
if branch == reftablePlaceholderBranch {
|
||||
return headInfo{}, false
|
||||
}
|
||||
return headInfo{branch: branch}, true
|
||||
}
|
||||
return headInfo{hash: head}, true
|
||||
}
|
||||
|
||||
// askGitForHeadInfo asks git what the repo at repoPath has checked out. This
|
||||
// costs a process, so only the repos that readHeadInfo can't answer for go
|
||||
// through here.
|
||||
func (self *ReposHelper) askGitForHeadInfo(repoPath string) (headInfo, bool) {
|
||||
// symbolic-ref names the branch even when it has no commit yet, and
|
||||
// rev-parse resolves HEAD when it is detached. Neither can do the other's
|
||||
// job, so ask for the branch first and only then for the commit.
|
||||
if branch, ok := self.askGit(repoPath, "symbolic-ref", "--short", "--quiet", "HEAD"); ok {
|
||||
return headInfo{branch: branch}, true
|
||||
}
|
||||
if hash, ok := self.askGit(repoPath, "rev-parse", "HEAD"); ok {
|
||||
return headInfo{hash: hash}, true
|
||||
}
|
||||
return headInfo{}, false
|
||||
}
|
||||
|
||||
// askGit runs a git command against the repo at repoPath and returns the one
|
||||
// line it writes, or false if it fails or writes nothing.
|
||||
func (self *ReposHelper) askGit(repoPath string, subcommand string, args ...string) (string, bool) {
|
||||
cmdObj := self.c.OS().Cmd.New(git_commands.NewGitCmd(subcommand).
|
||||
Dir(repoPath).
|
||||
Arg(args...).
|
||||
ToArgv()).DontLog()
|
||||
stdout, _, err := git_commands.ForOtherRepo(cmdObj).RunWithOutputs()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
output := strings.TrimSpace(stdout)
|
||||
return output, output != ""
|
||||
}
|
||||
|
||||
func (self *ReposHelper) getCurrentBranch(path string) string {
|
||||
readHeadFile := func(path string) (string, error) {
|
||||
headFile, err := os.ReadFile(filepath.Join(path, "HEAD"))
|
||||
if err == nil {
|
||||
content := strings.TrimSpace(string(headFile))
|
||||
refsPrefix := "ref: refs/heads/"
|
||||
var branchDisplay string
|
||||
if bareName, ok := strings.CutPrefix(content, refsPrefix); ok {
|
||||
// is a branch
|
||||
branchDisplay = bareName
|
||||
} else {
|
||||
// detached HEAD state, displaying short hash
|
||||
branchDisplay = utils.ShortHash(content)
|
||||
}
|
||||
return branchDisplay, nil
|
||||
}
|
||||
return "", err
|
||||
head, ok := readHeadInfo(path)
|
||||
if !ok {
|
||||
head, ok = self.askGitForHeadInfo(path)
|
||||
}
|
||||
if !ok {
|
||||
return self.c.Tr.BranchUnknown
|
||||
}
|
||||
if head.branch != "" {
|
||||
return head.branch
|
||||
}
|
||||
return utils.ResolvePlaceholderString(self.c.Tr.HeadDetachedAt,
|
||||
map[string]string{"hash": utils.ShortHash(head.hash)})
|
||||
}
|
||||
|
||||
// The most that the name and the branch column of the recent repos menu are
|
||||
// allowed to take up. Each column is padded to the width of its widest entry,
|
||||
// so without a limit one long entry pushes the columns after it off the right
|
||||
// edge of the menu for every entry.
|
||||
const (
|
||||
recentReposNameMaxWidth = 30
|
||||
recentReposBranchMaxWidth = 30
|
||||
)
|
||||
|
||||
// One entry of the recent repos menu.
|
||||
type recentRepoEntry struct {
|
||||
// What the entry stands for
|
||||
path string
|
||||
branchName string
|
||||
|
||||
// The text of its three columns
|
||||
nameColumn string
|
||||
branchColumn string
|
||||
dirColumn string
|
||||
}
|
||||
|
||||
func newRecentRepoEntry(path string, branchName string) recentRepoEntry {
|
||||
// The icon is part of the column, so it counts towards the column's width.
|
||||
branchColumn := branchName
|
||||
if icons.IsIconEnabled() {
|
||||
branchColumn = icons.BRANCH_ICON + " " + branchName
|
||||
}
|
||||
|
||||
gitDirPath := filepath.Join(path, ".git")
|
||||
return recentRepoEntry{
|
||||
path: path,
|
||||
branchName: branchName,
|
||||
nameColumn: filepath.Base(path),
|
||||
branchColumn: branchColumn,
|
||||
// The last segment of the path is already in the first column, so the
|
||||
// directory that contains the repo is enough to tell repos with the
|
||||
// same name apart.
|
||||
dirColumn: utils.ContractTilde(filepath.Dir(path)),
|
||||
}
|
||||
}
|
||||
|
||||
if gitDir, err := os.Stat(gitDirPath); err == nil {
|
||||
if gitDir.IsDir() {
|
||||
// ordinary repo
|
||||
if branch, err := readHeadFile(gitDirPath); err == nil {
|
||||
return branch
|
||||
}
|
||||
} else {
|
||||
// worktree
|
||||
if worktreeGitDir, err := os.ReadFile(gitDirPath); err == nil {
|
||||
content := strings.TrimSpace(string(worktreeGitDir))
|
||||
worktreePath := strings.TrimPrefix(content, "gitdir: ")
|
||||
if branch, err := readHeadFile(worktreePath); err == nil {
|
||||
return branch
|
||||
}
|
||||
}
|
||||
}
|
||||
// How wide the columns of the recent repos menu are allowed to get.
|
||||
type recentRepoColumnWidths struct {
|
||||
name int
|
||||
branch int
|
||||
dir int
|
||||
}
|
||||
|
||||
// Gives the name and the branch column as much as their entries need, up to
|
||||
// their respective maximum, and the rest of the row to the directory column.
|
||||
// Measuring the entries first matters because most users don't have names that
|
||||
// long; truncating the directories as if they did would cut them short for no
|
||||
// reason.
|
||||
func (self *ReposHelper) fitRecentRepoColumns(entries []recentRepoEntry) recentRepoColumnWidths {
|
||||
// The menu appends a Cancel entry, whose label sits in the first column.
|
||||
nameWidth := utils.StringWidth(self.c.Tr.Cancel)
|
||||
branchWidth := 0
|
||||
for _, entry := range entries {
|
||||
nameWidth = max(nameWidth, utils.StringWidth(entry.nameColumn))
|
||||
branchWidth = max(branchWidth, utils.StringWidth(entry.branchColumn))
|
||||
}
|
||||
|
||||
return self.c.Tr.BranchUnknown
|
||||
nameWidth = min(nameWidth, recentReposNameMaxWidth)
|
||||
branchWidth = min(branchWidth, recentReposBranchMaxWidth)
|
||||
|
||||
return recentRepoColumnWidths{
|
||||
name: nameWidth,
|
||||
branch: branchWidth,
|
||||
// The menu's frame takes up two columns, and two more separate the
|
||||
// three columns from each other. What's left is the room a whole row
|
||||
// has in a menu that is as wide as it gets.
|
||||
dir: menuMaxWidth - 2 - 2 - nameWidth - branchWidth,
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ReposHelper) recentRepoMenuItem(entry recentRepoEntry, widths recentRepoColumnWidths) *types.MenuItem {
|
||||
displayedName := utils.TruncateWithEllipsis(entry.nameColumn, widths.name)
|
||||
displayedBranch := utils.TruncateWithEllipsis(entry.branchColumn, widths.branch)
|
||||
// The beginning and the end of a directory are both worth seeing, so it
|
||||
// loses its middle rather than its end when it doesn't fit.
|
||||
displayedDir := utils.TruncateWithEllipsisInMiddle(entry.dirColumn, widths.dir)
|
||||
|
||||
// Spell out whatever the columns show in truncated form
|
||||
type tooltipField struct {
|
||||
label string
|
||||
value string
|
||||
}
|
||||
fields := []tooltipField{}
|
||||
addTooltipField := func(label string, value string) {
|
||||
fields = append(fields, tooltipField{label: label, value: value})
|
||||
}
|
||||
|
||||
if displayedName != entry.nameColumn {
|
||||
addTooltipField(self.c.Tr.RecentReposRepoLabel, entry.nameColumn)
|
||||
}
|
||||
if displayedBranch != entry.branchColumn {
|
||||
addTooltipField(self.c.Tr.RecentReposBranchLabel, entry.branchName)
|
||||
}
|
||||
if displayedDir != entry.dirColumn {
|
||||
addTooltipField(self.c.Tr.RecentReposPathLabel, entry.dirColumn)
|
||||
}
|
||||
|
||||
// Line the values up behind the widest of the labels that are there
|
||||
labelWidth := utils.MaxFn(fields, func(field tooltipField) int {
|
||||
return utils.StringWidth(field.label)
|
||||
})
|
||||
tooltipLines := lo.Map(fields, func(field tooltipField, _ int) string {
|
||||
return utils.WithPadding(field.label, labelWidth, utils.AlignLeft) + " " + field.value
|
||||
})
|
||||
|
||||
return &types.MenuItem{
|
||||
LabelColumns: []string{
|
||||
displayedName,
|
||||
style.FgCyan.Sprint(displayedBranch),
|
||||
style.FgMagenta.Sprint(displayedDir),
|
||||
},
|
||||
// Filtering matches the full text, including the parts that the columns
|
||||
// above truncate or leave out.
|
||||
FilterColumns: []string{entry.nameColumn, entry.branchName, entry.path},
|
||||
Tooltip: strings.Join(tooltipLines, "\n"),
|
||||
OnPress: func() error {
|
||||
// Check before clearing the stack, so a refused switch doesn't
|
||||
// forget the submodule breadcrumb (which would leave escape
|
||||
// unable to return to the parent repo).
|
||||
if self.switchRefusedBecauseBusy() {
|
||||
return nil
|
||||
}
|
||||
// if we were in a submodule, we want to forget about that stack of repos
|
||||
// so that hitting escape in the new repo does nothing
|
||||
self.c.State().GetRepoPathStack().Clear()
|
||||
return self.switchTo(entry.path, self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ReposHelper) CreateRecentReposMenu() error {
|
||||
@@ -112,45 +318,27 @@ func (self *ReposHelper) CreateRecentReposMenu() error {
|
||||
recentRepoPaths = self.c.GetAppState().RecentRepos[1:]
|
||||
}
|
||||
|
||||
currentBranches := sync.Map{}
|
||||
currentBranches := make([]string, len(recentRepoPaths))
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(len(recentRepoPaths))
|
||||
|
||||
for _, path := range recentRepoPaths {
|
||||
go func(path string) {
|
||||
for i, path := range recentRepoPaths {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
currentBranches.Store(path, self.getCurrentBranch(path))
|
||||
}(path)
|
||||
currentBranches[i] = self.getCurrentBranch(path)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
menuItems := lo.Map(recentRepoPaths, func(path string, _ int) *types.MenuItem {
|
||||
branchName, _ := currentBranches.Load(path)
|
||||
if icons.IsIconEnabled() {
|
||||
branchName = icons.BRANCH_ICON + " " + fmt.Sprintf("%v", branchName)
|
||||
}
|
||||
entries := lo.Map(recentRepoPaths, func(path string, i int) recentRepoEntry {
|
||||
return newRecentRepoEntry(path, currentBranches[i])
|
||||
})
|
||||
|
||||
return &types.MenuItem{
|
||||
LabelColumns: []string{
|
||||
filepath.Base(path),
|
||||
style.FgCyan.Sprint(branchName),
|
||||
style.FgMagenta.Sprint(path),
|
||||
},
|
||||
OnPress: func() error {
|
||||
// Check before clearing the stack, so a refused switch doesn't
|
||||
// forget the submodule breadcrumb (which would leave escape
|
||||
// unable to return to the parent repo).
|
||||
if self.switchRefusedBecauseBusy() {
|
||||
return nil
|
||||
}
|
||||
// if we were in a submodule, we want to forget about that stack of repos
|
||||
// so that hitting escape in the new repo does nothing
|
||||
self.c.State().GetRepoPathStack().Clear()
|
||||
return self.switchTo(path, self.c.Tr.ErrRepositoryMovedOrDeleted, context.NO_CONTEXT)
|
||||
},
|
||||
}
|
||||
columnWidths := self.fitRecentRepoColumns(entries)
|
||||
menuItems := lo.Map(entries, func(entry recentRepoEntry, _ int) *types.MenuItem {
|
||||
return self.recentRepoMenuItem(entry, columnWidths)
|
||||
})
|
||||
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestReadHeadInfo(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
// The files to lay out below a temporary root directory, by their path
|
||||
// relative to it. "$root" in a file's content is replaced with the
|
||||
// root's path, so that a scenario can write an absolute path.
|
||||
files map[string]string
|
||||
// The repo to read, relative to the root. The directory is created
|
||||
// whether or not the scenario puts any files in it.
|
||||
repoPath string
|
||||
expected headInfo
|
||||
expectedOk bool
|
||||
}{
|
||||
{
|
||||
name: "ordinary repo on a branch",
|
||||
files: map[string]string{"repo/.git/HEAD": "ref: refs/heads/mybranch\n"},
|
||||
repoPath: "repo",
|
||||
expected: headInfo{branch: "mybranch"},
|
||||
expectedOk: true,
|
||||
},
|
||||
{
|
||||
name: "ordinary repo at a detached head",
|
||||
files: map[string]string{"repo/.git/HEAD": "d85cc9d2f5d0dc0b8f0e4d8e5b2ba0d1e7c8a3f6\n"},
|
||||
repoPath: "repo",
|
||||
expected: headInfo{hash: "d85cc9d2f5d0dc0b8f0e4d8e5b2ba0d1e7c8a3f6"},
|
||||
expectedOk: true,
|
||||
},
|
||||
{
|
||||
name: "worktree whose .git file names the git dir absolutely",
|
||||
files: map[string]string{
|
||||
"repo/.git/worktrees/wt/HEAD": "ref: refs/heads/mybranch\n",
|
||||
"wt/.git": "gitdir: $root/repo/.git/worktrees/wt\n",
|
||||
},
|
||||
repoPath: "wt",
|
||||
expected: headInfo{branch: "mybranch"},
|
||||
expectedOk: true,
|
||||
},
|
||||
{
|
||||
name: "worktree whose .git file names the git dir relatively",
|
||||
files: map[string]string{
|
||||
"repo/.git/worktrees/wt/HEAD": "ref: refs/heads/mybranch\n",
|
||||
"wt/.git": "gitdir: ../repo/.git/worktrees/wt\n",
|
||||
},
|
||||
repoPath: "wt",
|
||||
expected: headInfo{branch: "mybranch"},
|
||||
expectedOk: true,
|
||||
},
|
||||
{
|
||||
name: "submodule, whose .git file always names the git dir relatively",
|
||||
files: map[string]string{
|
||||
"repo/.git/modules/sub/HEAD": "ref: refs/heads/mybranch\n",
|
||||
"repo/sub/.git": "gitdir: ../.git/modules/sub\n",
|
||||
},
|
||||
repoPath: "repo/sub",
|
||||
expected: headInfo{branch: "mybranch"},
|
||||
expectedOk: true,
|
||||
},
|
||||
{
|
||||
name: "repo that keeps its refs in a reftable, so HEAD holds a placeholder",
|
||||
files: map[string]string{
|
||||
"repo/.git/HEAD": "ref: refs/heads/.invalid\n",
|
||||
},
|
||||
repoPath: "repo",
|
||||
expectedOk: false,
|
||||
},
|
||||
{
|
||||
name: "directory without a .git entry",
|
||||
repoPath: "notarepo",
|
||||
expectedOk: false,
|
||||
},
|
||||
{
|
||||
name: ".git file that doesn't name a git dir",
|
||||
files: map[string]string{"repo/.git": "not what git writes\n"},
|
||||
repoPath: "repo",
|
||||
expectedOk: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for path, content := range s.files {
|
||||
fullPath := filepath.Join(root, filepath.FromSlash(path))
|
||||
assert.NoError(t, os.MkdirAll(filepath.Dir(fullPath), 0o700))
|
||||
content = strings.ReplaceAll(content, "$root", root)
|
||||
assert.NoError(t, os.WriteFile(fullPath, []byte(content), 0o600))
|
||||
}
|
||||
repoPath := filepath.Join(root, filepath.FromSlash(s.repoPath))
|
||||
assert.NoError(t, os.MkdirAll(repoPath, 0o700))
|
||||
|
||||
head, ok := readHeadInfo(repoPath)
|
||||
|
||||
assert.Equal(t, s.expectedOk, ok)
|
||||
assert.Equal(t, s.expected, head)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func (self *ReflogCommitsController) GetOnRenderToMain() func() {
|
||||
} else {
|
||||
cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit))
|
||||
|
||||
task = types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
task = types.NewRunDiffRendererTask(cmdObj.GetCmd())
|
||||
}
|
||||
|
||||
self.c.RenderToMainViews(types.RefreshMainOpts{
|
||||
|
||||
@@ -93,7 +93,7 @@ func (self *StashController) GetOnRenderToMain() func() {
|
||||
task = types.NewRenderStringTask(self.c.Tr.NoStashEntries)
|
||||
} else {
|
||||
prefix := style.FgYellow.Sprintf("%s\n\n", stashEntry.Description())
|
||||
task = types.NewRunPtyTaskWithPrefix(
|
||||
task = types.NewRunDiffRendererTaskWithPrefix(
|
||||
self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index).GetCmd(),
|
||||
prefix,
|
||||
)
|
||||
|
||||
@@ -146,7 +146,7 @@ func (self *StatusController) editConfig() error {
|
||||
|
||||
func (self *StatusController) showAllBranchLogs() {
|
||||
cmdObj := self.c.Git().Branch.AllBranchesLogCmdObj()
|
||||
task := types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
task := types.NewRunDiffRendererTask(cmdObj.GetCmd())
|
||||
|
||||
title := self.c.Tr.LogTitle
|
||||
if i, n := self.c.Git().Branch.GetAllBranchesLogIdxAndCount(); n > 1 {
|
||||
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/style"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type SyncController struct {
|
||||
@@ -87,18 +89,140 @@ func (self *SyncController) branchCheckedOut(f func(*models.Branch) error) func(
|
||||
}
|
||||
|
||||
func (self *SyncController) push(currentBranch *models.Branch) error {
|
||||
// if we are behind our upstream branch we'll ask if the user wants to force push
|
||||
if currentBranch.IsTrackingRemote() {
|
||||
opts := pushOpts{remoteBranchStoredLocally: currentBranch.RemoteBranchStoredLocally()}
|
||||
branchesBelow := self.unpushedBranchesBelow(currentBranch)
|
||||
if len(branchesBelow) == 0 {
|
||||
return self.pushCurrentBranch(currentBranch)
|
||||
}
|
||||
|
||||
branchName := map[string]string{"branchName": currentBranch.Name}
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
Title: self.c.Tr.Push,
|
||||
Prompt: self.branchesBelowPrompt(currentBranch, branchesBelow),
|
||||
Items: []*types.MenuItem{
|
||||
{
|
||||
Label: utils.ResolvePlaceholderString(self.c.Tr.PushBranchAndBranchesBelow, branchName),
|
||||
OnPress: func() error {
|
||||
return self.pushWithBranchesBelow(currentBranch, branchesBelow)
|
||||
},
|
||||
},
|
||||
{
|
||||
Label: utils.ResolvePlaceholderString(self.c.Tr.PushOnlyCurrentBranch, branchName),
|
||||
OnPress: func() error {
|
||||
return self.pushCurrentBranch(currentBranch)
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (self *SyncController) pushCurrentBranch(currentBranch *models.Branch) error {
|
||||
return self.resolvePushOfCurrentBranch(currentBranch, func(opts pushOpts) error {
|
||||
// if we are behind our upstream branch we'll ask if the user wants to force push
|
||||
if currentBranch.IsBehindForPush() {
|
||||
return self.requestToForcePush(currentBranch, opts)
|
||||
}
|
||||
|
||||
return self.pushAux(currentBranch, opts)
|
||||
})
|
||||
}
|
||||
|
||||
// The branches stacked below the current one that have commits to push
|
||||
func (self *SyncController) unpushedBranchesBelow(currentBranch *models.Branch) []*models.Branch {
|
||||
branchesBelow := helpers.BranchesBelowInStack(
|
||||
self.c.Model().Commits, self.c.Model().Branches, currentBranch, self.c.UserConfig().Git.MainBranches)
|
||||
|
||||
return lo.Filter(branchesBelow, func(branch *models.Branch, _ int) bool {
|
||||
// Pushing a branch whose remote branch was deleted would recreate it.
|
||||
// A branch that is only behind its remote branch has nothing to push,
|
||||
// and force-pushing it would move the remote branch back to an older
|
||||
// commit.
|
||||
return branch.PushRemote != "" && !branch.UpstreamGone && branch.IsAheadForPush()
|
||||
})
|
||||
}
|
||||
|
||||
func (self *SyncController) branchesBelowPrompt(currentBranch *models.Branch, branchesBelow []*models.Branch) string {
|
||||
intro := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.BranchesBelowHaveCommitsToPush,
|
||||
map[string]string{"branchName": currentBranch.Name},
|
||||
)
|
||||
lines := lo.Map(branchesBelow, func(branch *models.Branch, _ int) string {
|
||||
divergence := "↑" + branch.AheadForPush
|
||||
if branch.IsBehindForPush() {
|
||||
divergence = "↓" + branch.BehindForPush + divergence
|
||||
}
|
||||
return fmt.Sprintf("%s %s", branch.Name, style.FgYellow.Sprint(divergence))
|
||||
})
|
||||
|
||||
return intro + "\n\n " + strings.Join(lines, "\n ")
|
||||
}
|
||||
|
||||
// Pushes the current branch and the branches stacked below it, after asking
|
||||
// for confirmation if any of them has to be force-pushed
|
||||
func (self *SyncController) pushWithBranchesBelow(currentBranch *models.Branch, branchesBelow []*models.Branch) error {
|
||||
if currentBranch.RemoteBranchStoredLocally() && currentBranch.PushRemote != "" {
|
||||
// We know where the current branch goes and whether it needs to be
|
||||
// forced, so it is pushed like the branches below it, in the same
|
||||
// command as those that go to the same remote
|
||||
branches := append([]*models.Branch{currentBranch}, branchesBelow...)
|
||||
return self.confirmForcePushIfNeeded(branches, func(forceWithLease bool) error {
|
||||
return self.pushBranchesAux(currentBranch, branchesBelow, forceWithLease)
|
||||
})
|
||||
}
|
||||
|
||||
// The current branch has no upstream yet, or its remote branch isn't
|
||||
// stored locally. Push it the way it is pushed on its own, and the branches
|
||||
// below it after it.
|
||||
return self.resolvePushOfCurrentBranch(currentBranch, func(opts pushOpts) error {
|
||||
return self.confirmForcePushIfNeeded(branchesBelow, func(forceWithLease bool) error {
|
||||
opts.branchesBelow = branchesBelow
|
||||
opts.forceWithLeaseBelow = forceWithLease
|
||||
return self.pushAux(currentBranch, opts)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Calls push right away if none of the branches has diverged from its remote
|
||||
// branch, and after the user confirmed force-pushing otherwise
|
||||
func (self *SyncController) confirmForcePushIfNeeded(branches []*models.Branch, push func(forceWithLease bool) error) error {
|
||||
diverged := lo.Filter(branches, func(branch *models.Branch, _ int) bool {
|
||||
return branch.IsBehindForPush()
|
||||
})
|
||||
if len(diverged) == 0 {
|
||||
return push(false)
|
||||
}
|
||||
|
||||
if self.c.UserConfig().Git.DisableForcePushing {
|
||||
return errors.New(self.c.Tr.ForcePushBranchesDisabled)
|
||||
}
|
||||
|
||||
self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.ForcePush,
|
||||
Prompt: utils.ResolvePlaceholderString(
|
||||
self.c.Tr.ForcePushBranchesPrompt,
|
||||
map[string]string{
|
||||
"branches": " " + strings.Join(lo.Map(diverged, func(branch *models.Branch, _ int) string { return branch.Name }), "\n "),
|
||||
"cancelKey": self.c.UserConfig().Keybinding.Universal.Return.String(),
|
||||
"confirmKey": self.c.UserConfig().Keybinding.Universal.Confirm.String(),
|
||||
},
|
||||
),
|
||||
HandleConfirm: func() error {
|
||||
return push(true)
|
||||
},
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Works out where the current branch is pushed to: to its upstream, to a
|
||||
// branch of the same name if push.default is "current", or to an upstream the
|
||||
// user enters in a prompt. Calls onResolved with the options for that push.
|
||||
func (self *SyncController) resolvePushOfCurrentBranch(currentBranch *models.Branch, onResolved func(pushOpts) error) error {
|
||||
if currentBranch.IsTrackingRemote() {
|
||||
return onResolved(pushOpts{remoteBranchStoredLocally: currentBranch.RemoteBranchStoredLocally()})
|
||||
}
|
||||
|
||||
if self.c.Git().Config.GetPushToCurrent() {
|
||||
return self.pushAux(currentBranch, pushOpts{setUpstream: true})
|
||||
return onResolved(pushOpts{setUpstream: true})
|
||||
}
|
||||
|
||||
return self.c.Helpers().Upstream.PromptForUpstreamWithInitialContent(currentBranch, func(upstream string) error {
|
||||
@@ -107,7 +231,7 @@ func (self *SyncController) push(currentBranch *models.Branch) error {
|
||||
return err
|
||||
}
|
||||
|
||||
return self.pushAux(currentBranch, pushOpts{
|
||||
return onResolved(pushOpts{
|
||||
setUpstream: true,
|
||||
upstreamRemote: upstreamRemote,
|
||||
upstreamBranch: upstreamBranch,
|
||||
@@ -116,7 +240,36 @@ func (self *SyncController) push(currentBranch *models.Branch) error {
|
||||
}
|
||||
|
||||
func (self *SyncController) pull(currentBranch *models.Branch) error {
|
||||
action := self.c.Tr.Actions.Pull
|
||||
branchesBelow := self.updatableBranchesBelow(currentBranch)
|
||||
if len(branchesBelow) == 0 {
|
||||
return self.pullCurrentBranch(currentBranch, nil)
|
||||
}
|
||||
|
||||
branchName := map[string]string{"branchName": currentBranch.Name}
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
Title: self.c.Tr.Pull,
|
||||
Prompt: self.branchesBelowToUpdatePrompt(currentBranch, branchesBelow),
|
||||
Items: []*types.MenuItem{
|
||||
{
|
||||
Label: utils.ResolvePlaceholderString(self.c.Tr.PullBranchAndBranchesBelow, branchName),
|
||||
OnPress: func() error {
|
||||
return self.pullCurrentBranch(currentBranch, branchesBelow)
|
||||
},
|
||||
},
|
||||
{
|
||||
Label: utils.ResolvePlaceholderString(self.c.Tr.PullOnlyCurrentBranch, branchName),
|
||||
OnPress: func() error {
|
||||
return self.pullCurrentBranch(currentBranch, nil)
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Pulls the current branch, after updating the given branches stacked below it
|
||||
// to their upstream branches
|
||||
func (self *SyncController) pullCurrentBranch(currentBranch *models.Branch, branchesBelow []*models.Branch) error {
|
||||
opts := PullFilesOptions{Action: self.c.Tr.Actions.Pull, BranchesBelow: branchesBelow}
|
||||
|
||||
// if we have no upstream branch we need to set that first
|
||||
if !currentBranch.IsTrackingRemote() {
|
||||
@@ -125,11 +278,46 @@ func (self *SyncController) pull(currentBranch *models.Branch) error {
|
||||
return err
|
||||
}
|
||||
|
||||
return self.PullAux(currentBranch, PullFilesOptions{Action: action})
|
||||
return self.PullAux(currentBranch, opts)
|
||||
})
|
||||
}
|
||||
|
||||
return self.PullAux(currentBranch, PullFilesOptions{Action: action})
|
||||
return self.PullAux(currentBranch, opts)
|
||||
}
|
||||
|
||||
// The branches stacked below the current one that can be updated to their
|
||||
// upstream branches without losing anything: those that are behind them, and
|
||||
// those that diverged from them only because they were rewritten
|
||||
func (self *SyncController) updatableBranchesBelow(currentBranch *models.Branch) []*models.Branch {
|
||||
branchesBelow := helpers.BranchesBelowInStack(
|
||||
self.c.Model().Commits, self.c.Model().Branches, currentBranch, self.c.UserConfig().Git.MainBranches)
|
||||
|
||||
return lo.Filter(branchesBelow, func(branch *models.Branch, _ int) bool {
|
||||
// Updating a branch that is checked out in another worktree changes
|
||||
// the files there, which is more than pulling the current branch
|
||||
// should do
|
||||
if git_commands.CheckedOutByOtherWorktree(branch, self.c.Model().Worktrees) {
|
||||
return false
|
||||
}
|
||||
|
||||
return branch.IsBehindForPull() && (!branch.IsAheadForPull() || branch.UpstreamRewritten.Load())
|
||||
})
|
||||
}
|
||||
|
||||
func (self *SyncController) branchesBelowToUpdatePrompt(currentBranch *models.Branch, branchesBelow []*models.Branch) string {
|
||||
intro := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.BranchesBelowHaveChangedOnRemote,
|
||||
map[string]string{"branchName": currentBranch.Name},
|
||||
)
|
||||
lines := lo.Map(branchesBelow, func(branch *models.Branch, _ int) string {
|
||||
divergence := "↓" + branch.BehindForPull
|
||||
if branch.IsAheadForPull() {
|
||||
divergence += "↑" + branch.AheadForPull
|
||||
}
|
||||
return fmt.Sprintf("%s %s", branch.Name, style.FgYellow.Sprint(divergence))
|
||||
})
|
||||
|
||||
return intro + "\n\n " + strings.Join(lines, "\n ")
|
||||
}
|
||||
|
||||
func (self *SyncController) setCurrentBranchUpstream(upstream string) error {
|
||||
@@ -155,10 +343,35 @@ type PullFilesOptions struct {
|
||||
UpstreamBranch string
|
||||
FastForwardOnly bool
|
||||
Action string
|
||||
|
||||
// Branches stacked below the current one, updated to their upstream
|
||||
// branches before the current one is pulled
|
||||
BranchesBelow []*models.Branch
|
||||
}
|
||||
|
||||
func (self *SyncController) PullAux(currentBranch *models.Branch, opts PullFilesOptions) error {
|
||||
return self.c.WithInlineStatus(currentBranch, types.ItemOperationPulling, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
var updateBranchesBelow func(gocui.Task) error
|
||||
if len(opts.BranchesBelow) > 0 {
|
||||
var err error
|
||||
updateBranchesBelow, err = self.c.Helpers().BranchesHelper.PrepareFastForward(opts.BranchesBelow)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
branches := append([]*models.Branch{currentBranch}, opts.BranchesBelow...)
|
||||
return self.c.Helpers().BranchesHelper.WithInlineStatusOnBranches(branches, types.ItemOperationPulling, func(task gocui.Task) error {
|
||||
// Update the branches below first. If one of them pointed into the
|
||||
// commits that a rebasing pull rebases, the pull would move it when
|
||||
// rebase.updateRefs is set, and updating it afterwards would fail. If
|
||||
// updating them fails, the current branch isn't pulled either; the
|
||||
// user can still choose to pull only the current branch.
|
||||
if updateBranchesBelow != nil {
|
||||
if err := updateBranchesBelow(task); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return self.pullWithLock(task, opts)
|
||||
})
|
||||
}
|
||||
@@ -190,20 +403,28 @@ type pushOpts struct {
|
||||
// the server rejected. If this is true, we don't offer to force-push if the
|
||||
// server rejected, but rather ask the user to fetch.
|
||||
remoteBranchStoredLocally bool
|
||||
|
||||
// Branches stacked below the current one, pushed after it with one command
|
||||
// per remote, with --force-with-lease if forceWithLeaseBelow is set. The
|
||||
// force options above apply to the current branch's own push only.
|
||||
branchesBelow []*models.Branch
|
||||
forceWithLeaseBelow bool
|
||||
}
|
||||
|
||||
func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts) error {
|
||||
return self.c.WithInlineStatus(currentBranch, types.ItemOperationPushing, context.LOCAL_BRANCHES_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.Push)
|
||||
return self.withPushingStatus(currentBranch, opts.branchesBelow, func(task gocui.Task) error {
|
||||
refspecs := []string{}
|
||||
if opts.upstreamBranch != "" {
|
||||
refspecs = append(refspecs, fmt.Sprintf("refs/heads/%s:%s", currentBranch.Name, opts.upstreamBranch))
|
||||
}
|
||||
err := self.c.Git().Sync.Push(
|
||||
task,
|
||||
git_commands.PushOpts{
|
||||
Force: opts.force,
|
||||
ForceWithLease: opts.forceWithLease,
|
||||
CurrentBranch: currentBranch.Name,
|
||||
UpstreamRemote: opts.upstreamRemote,
|
||||
UpstreamBranch: opts.upstreamBranch,
|
||||
SetUpstream: opts.setUpstream,
|
||||
Remote: opts.upstreamRemote,
|
||||
Refspecs: refspecs,
|
||||
})
|
||||
if err != nil {
|
||||
if !opts.force && !opts.forceWithLease && strings.Contains(err.Error(), "Updates were rejected") {
|
||||
@@ -229,11 +450,54 @@ func (self *SyncController) pushAux(currentBranch *models.Branch, opts pushOpts)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
err = self.pushBranches(task, opts.branchesBelow, opts.forceWithLeaseBelow)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{})
|
||||
return nil
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Pushes the current branch along with the branches stacked below it, all of
|
||||
// them with explicit refspecs
|
||||
func (self *SyncController) pushBranchesAux(currentBranch *models.Branch, branchesBelow []*models.Branch, forceWithLease bool) error {
|
||||
return self.withPushingStatus(currentBranch, branchesBelow, func(task gocui.Task) error {
|
||||
branches := append([]*models.Branch{currentBranch}, branchesBelow...)
|
||||
err := self.pushBranches(task, branches, forceWithLease)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{})
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Runs f as a push of the current branch, showing it and the other branches
|
||||
// as being pushed while it runs
|
||||
func (self *SyncController) withPushingStatus(currentBranch *models.Branch, otherBranches []*models.Branch, f func(gocui.Task) error) error {
|
||||
branches := append([]*models.Branch{currentBranch}, otherBranches...)
|
||||
return self.c.Helpers().BranchesHelper.WithInlineStatusOnBranches(branches, types.ItemOperationPushing, func(task gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.Push)
|
||||
return f(task)
|
||||
})
|
||||
}
|
||||
|
||||
// Pushes the branches to their push destinations, one command per remote
|
||||
func (self *SyncController) pushBranches(task gocui.Task, branches []*models.Branch, forceWithLease bool) error {
|
||||
remotes := lo.Uniq(lo.Map(branches, func(branch *models.Branch, _ int) string { return branch.PushRemote }))
|
||||
for _, remote := range remotes {
|
||||
refspecs := lo.FilterMap(branches, func(branch *models.Branch, _ int) (string, bool) {
|
||||
return fmt.Sprintf("refs/heads/%s:refs/heads/%s", branch.Name, branch.PushBranch), branch.PushRemote == remote
|
||||
})
|
||||
err := self.c.Git().Sync.Push(task, git_commands.PushOpts{
|
||||
ForceWithLease: forceWithLease,
|
||||
Remote: remote,
|
||||
Refspecs: refspecs,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *SyncController) requestToForcePush(currentBranch *models.Branch, opts pushOpts) error {
|
||||
forcePushDisabled := self.c.UserConfig().Git.DisableForcePushing
|
||||
if forcePushDisabled {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/style"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
@@ -61,17 +62,17 @@ func (self *TagsController) GetKeybindings(opts types.KeybindingsOpts) []*types.
|
||||
},
|
||||
{
|
||||
Keys: opts.GetKeys(opts.Config.Universal.Remove),
|
||||
Handler: self.withItem(self.delete),
|
||||
Handler: self.withItems(self.delete),
|
||||
Description: self.c.Tr.Delete,
|
||||
GetDisabledReason: self.require(self.singleItemSelected()),
|
||||
GetDisabledReason: self.require(self.itemsSelected()),
|
||||
Tooltip: self.c.Tr.TagDeleteTooltip,
|
||||
OpensMenu: true,
|
||||
DisplayOnScreen: true,
|
||||
},
|
||||
{
|
||||
Keys: opts.GetKeys(opts.Config.Branches.PushTag),
|
||||
Handler: self.withItem(self.push),
|
||||
GetDisabledReason: self.require(self.singleItemSelected()),
|
||||
Handler: self.withItems(self.push),
|
||||
GetDisabledReason: self.require(self.itemsSelected()),
|
||||
Description: self.c.Tr.PushTag,
|
||||
Tooltip: self.c.Tr.PushTagTooltip,
|
||||
DisplayOnScreen: true,
|
||||
@@ -164,54 +165,104 @@ func (self *TagsController) checkout(tag *models.Tag) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *TagsController) localDelete(tag *models.Tag) error {
|
||||
func (self *TagsController) localDelete(tags []*models.Tag) error {
|
||||
return self.c.WithWaitingStatus(self.c.Tr.DeletingStatus, func(gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag)
|
||||
err := self.c.Git().Tag.LocalDelete(tag.Name)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}})
|
||||
err := self.c.Git().Tag.LocalDelete(tagNames(tags))
|
||||
self.refreshAfterLocalDelete()
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (self *TagsController) remoteDelete(tag *models.Tag) error {
|
||||
title := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.SelectRemoteTagUpstream,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
func (self *TagsController) remoteDelete(tags []*models.Tag) error {
|
||||
confirmPromptTemplate := lo.Ternary(len(tags) > 1, self.c.Tr.DeleteRemoteTagsPrompt, self.c.Tr.DeleteRemoteTagPrompt)
|
||||
return self.confirmRemoteDelete(tags, confirmPromptTemplate, func(task gocui.Task, upstream string) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag)
|
||||
if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tagNames(tags)); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.Toast(lo.Ternary(len(tags) > 1, self.c.Tr.RemoteTagsDeletedMessage, self.c.Tr.RemoteTagDeletedMessage))
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}})
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (self *TagsController) localAndRemoteDelete(tags []*models.Tag) error {
|
||||
confirmPromptTemplate := lo.Ternary(len(tags) > 1, self.c.Tr.DeleteLocalAndRemoteTagsPrompt, self.c.Tr.DeleteLocalAndRemoteTagPrompt)
|
||||
return self.confirmRemoteDelete(tags, confirmPromptTemplate, func(task gocui.Task, upstream string) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag)
|
||||
if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tagNames(tags)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag)
|
||||
if err := self.c.Git().Tag.LocalDelete(tagNames(tags)); err != nil {
|
||||
return err
|
||||
}
|
||||
self.refreshAfterLocalDelete()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Refreshes after deleting local tags. If the tags were a range selection,
|
||||
// this also collapses it to its first line; otherwise it would select the tags
|
||||
// that moved up into the place of the deleted ones. Collapsing it in the Then
|
||||
// of a batched refresh draws the shorter list and the new selection in the
|
||||
// same frame.
|
||||
func (self *TagsController) refreshAfterLocalDelete() {
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{
|
||||
Scope: []types.RefreshableView{types.COMMITS, types.TAGS},
|
||||
BatchUIUpdates: true,
|
||||
Then: func() error {
|
||||
if self.context().IsSelectingRange() {
|
||||
self.context().CollapseRangeSelectionToTop()
|
||||
self.c.PostRefreshUpdate(self.context())
|
||||
}
|
||||
return nil
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Asks for the remote to delete the tags from and for a confirmation, and then
|
||||
// runs deleteTags on a worker with the tags shown as being deleted.
|
||||
// confirmPromptTemplate can use the placeholder upstream, and tagName if there
|
||||
// is only one tag.
|
||||
func (self *TagsController) confirmRemoteDelete(
|
||||
tags []*models.Tag,
|
||||
confirmPromptTemplate string,
|
||||
deleteTags func(task gocui.Task, upstream string) error,
|
||||
) error {
|
||||
var title string
|
||||
if len(tags) == 1 {
|
||||
title = utils.ResolvePlaceholderString(
|
||||
self.c.Tr.SelectRemoteTagUpstream,
|
||||
map[string]string{
|
||||
"tagName": tags[0].Name,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
title = self.c.Tr.SelectRemoteTagsUpstream
|
||||
}
|
||||
|
||||
self.c.Prompt(types.PromptOpts{
|
||||
Title: title,
|
||||
InitialContent: "origin",
|
||||
FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(),
|
||||
HandleConfirm: func(upstream string) error {
|
||||
confirmTitle := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteTagTitle,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
},
|
||||
)
|
||||
confirmPrompt := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteRemoteTagPrompt,
|
||||
confirmPromptTemplate,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
"tagName": tags[0].Name,
|
||||
"upstream": upstream,
|
||||
},
|
||||
)
|
||||
|
||||
self.c.Confirm(types.ConfirmOpts{
|
||||
Title: confirmTitle,
|
||||
Title: self.deleteTagsTitle(tags),
|
||||
Prompt: confirmPrompt,
|
||||
HandleConfirm: func() error {
|
||||
return self.c.WithInlineStatus(tag, types.ItemOperationDeleting, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag)
|
||||
if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tag.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.Toast(self.c.Tr.RemoteTagDeletedMessage)
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}})
|
||||
return nil
|
||||
return helpers.WithInlineStatusOnItems(self.c.HelperCommon, tags, types.ItemOperationDeleting, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
return deleteTags(task, upstream)
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -223,116 +274,73 @@ func (self *TagsController) remoteDelete(tag *models.Tag) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *TagsController) localAndRemoteDelete(tag *models.Tag) error {
|
||||
title := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.SelectRemoteTagUpstream,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
},
|
||||
)
|
||||
|
||||
self.c.Prompt(types.PromptOpts{
|
||||
Title: title,
|
||||
InitialContent: "origin",
|
||||
FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(),
|
||||
HandleConfirm: func(upstream string) error {
|
||||
confirmTitle := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteTagTitle,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
},
|
||||
)
|
||||
confirmPrompt := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteLocalAndRemoteTagPrompt,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
"upstream": upstream,
|
||||
},
|
||||
)
|
||||
|
||||
self.c.Confirm(types.ConfirmOpts{
|
||||
Title: confirmTitle,
|
||||
Prompt: confirmPrompt,
|
||||
HandleConfirm: func() error {
|
||||
return self.c.WithInlineStatus(tag, types.ItemOperationDeleting, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteRemoteTag)
|
||||
if err := self.c.Git().Remote.DeleteRemoteTag(task, upstream, tag.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.c.LogAction(self.c.Tr.Actions.DeleteLocalTag)
|
||||
if err := self.c.Git().Tag.LocalDelete(tag.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.RefreshFromWorker(types.RefreshOptions{Scope: []types.RefreshableView{types.COMMITS, types.TAGS}})
|
||||
return nil
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *TagsController) delete(tag *models.Tag) error {
|
||||
menuTitle := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteTagTitle,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
},
|
||||
)
|
||||
|
||||
func (self *TagsController) delete(tags []*models.Tag) error {
|
||||
menuItems := []*types.MenuItem{
|
||||
{
|
||||
Label: self.c.Tr.DeleteLocalTag,
|
||||
Label: lo.Ternary(len(tags) > 1, self.c.Tr.DeleteLocalTags, self.c.Tr.DeleteLocalTag),
|
||||
Keys: menuKey('c'),
|
||||
OnPress: func() error {
|
||||
return self.localDelete(tag)
|
||||
return self.localDelete(tags)
|
||||
},
|
||||
},
|
||||
{
|
||||
Label: self.c.Tr.DeleteRemoteTag,
|
||||
Label: lo.Ternary(len(tags) > 1, self.c.Tr.DeleteRemoteTags, self.c.Tr.DeleteRemoteTag),
|
||||
Keys: menuKey('r'),
|
||||
OpensMenu: true,
|
||||
OnPress: func() error {
|
||||
return self.remoteDelete(tag)
|
||||
return self.remoteDelete(tags)
|
||||
},
|
||||
},
|
||||
{
|
||||
Label: self.c.Tr.DeleteLocalAndRemoteTag,
|
||||
Label: lo.Ternary(len(tags) > 1, self.c.Tr.DeleteLocalAndRemoteTags, self.c.Tr.DeleteLocalAndRemoteTag),
|
||||
Keys: menuKey('b'),
|
||||
OpensMenu: true,
|
||||
OnPress: func() error {
|
||||
return self.localAndRemoteDelete(tag)
|
||||
return self.localAndRemoteDelete(tags)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
Title: menuTitle,
|
||||
Title: self.deleteTagsTitle(tags),
|
||||
Items: menuItems,
|
||||
})
|
||||
}
|
||||
|
||||
func (self *TagsController) push(tag *models.Tag) error {
|
||||
title := utils.ResolvePlaceholderString(
|
||||
self.c.Tr.PushTagTitle,
|
||||
func (self *TagsController) deleteTagsTitle(tags []*models.Tag) string {
|
||||
if len(tags) > 1 {
|
||||
return self.c.Tr.DeleteTagsTitle
|
||||
}
|
||||
|
||||
return utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DeleteTagTitle,
|
||||
map[string]string{
|
||||
"tagName": tag.Name,
|
||||
"tagName": tags[0].Name,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (self *TagsController) push(tags []*models.Tag) error {
|
||||
var title string
|
||||
if len(tags) == 1 {
|
||||
title = utils.ResolvePlaceholderString(
|
||||
self.c.Tr.PushTagTitle,
|
||||
map[string]string{
|
||||
"tagName": tags[0].Name,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
title = self.c.Tr.PushTagsTitle
|
||||
}
|
||||
|
||||
self.c.Prompt(types.PromptOpts{
|
||||
Title: title,
|
||||
InitialContent: "origin",
|
||||
FindSuggestionsFunc: self.c.Helpers().Suggestions.GetRemoteSuggestionsFunc(),
|
||||
HandleConfirm: func(response string) error {
|
||||
return self.c.WithInlineStatus(tag, types.ItemOperationPushing, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
return helpers.WithInlineStatusOnItems(self.c.HelperCommon, tags, types.ItemOperationPushing, context.TAGS_CONTEXT_KEY, func(task gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.PushTag)
|
||||
return self.c.Git().Tag.Push(task, response, tag.Name)
|
||||
return self.c.Git().Tag.Push(task, response, tagNames(tags))
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -354,3 +362,7 @@ func (self *TagsController) create() error {
|
||||
func (self *TagsController) context() *context.TagsContext {
|
||||
return self.c.Contexts().Tags
|
||||
}
|
||||
|
||||
func tagNames(tags []*models.Tag) []string {
|
||||
return lo.Map(tags, func(tag *models.Tag, _ int) string { return tag.Name })
|
||||
}
|
||||
|
||||
@@ -98,22 +98,22 @@ func (self *FileTreeViewModel) GetSelectedPath() string {
|
||||
}
|
||||
|
||||
func (self *FileTreeViewModel) SetTree() {
|
||||
newFiles := self.GetAllFiles()
|
||||
selectedNode := self.GetSelected()
|
||||
|
||||
// for when you stage the old file of a rename and the new file is in a collapsed dir
|
||||
for _, file := range newFiles {
|
||||
if selectedNode != nil && selectedNode.path != "" && file.PreviousPath == selectedNode.path {
|
||||
self.ExpandToPath(file.Path)
|
||||
}
|
||||
}
|
||||
|
||||
prevNodes := self.GetAllItems()
|
||||
prevSelectedLineIdx := self.GetSelectedLineIdx()
|
||||
|
||||
self.IFileTree.SetTree()
|
||||
|
||||
if selectedNode != nil {
|
||||
// If the selected file has become the old half of a rename, e.g. because
|
||||
// its deletion was staged, make sure the rename is visible so that the
|
||||
// selection can move to it.
|
||||
for _, node := range self.GetRoot().GetLeaves() {
|
||||
if node.File.PreviousPath == selectedNode.GetPath() {
|
||||
self.ExpandToPath(node.GetInternalPath())
|
||||
}
|
||||
}
|
||||
|
||||
newNodes := self.GetAllItems()
|
||||
newIdx := self.findNewSelectedIdx(prevNodes[prevSelectedLineIdx:], newNodes)
|
||||
if newIdx != -1 && newIdx != prevSelectedLineIdx {
|
||||
@@ -131,7 +131,16 @@ func (self *FileTreeViewModel) SetTree() {
|
||||
// nodes until we find one that exists in the new set of nodes, then move the cursor
|
||||
// to that.
|
||||
// prevNodes starts from our previously selected node because we don't need to consider anything above that
|
||||
//
|
||||
// A compressed directory node stands for every directory that was squished
|
||||
// into it, so it matches any new node that stands for at least one of the same
|
||||
// directories. When a compressed directory splits into several nodes because
|
||||
// a file appeared in another of its subdirectories, the topmost of these nodes
|
||||
// comes first in currNodes and takes over the selection; this keeps the cursor
|
||||
// on the same line.
|
||||
func (self *FileTreeViewModel) findNewSelectedIdx(prevNodes []*FileNode, currNodes []*FileNode) int {
|
||||
// Paths are compared as the user sees them, without the "./" prefix of the
|
||||
// root item, so that they line up with the names of a rename.
|
||||
getPaths := func(node *FileNode) []string {
|
||||
if node == nil {
|
||||
return nil
|
||||
@@ -139,7 +148,7 @@ func (self *FileTreeViewModel) findNewSelectedIdx(prevNodes []*FileNode, currNod
|
||||
if node.File != nil && node.File.IsRename() {
|
||||
return node.File.Names()
|
||||
}
|
||||
return []string{node.path}
|
||||
return node.GetPaths()
|
||||
}
|
||||
|
||||
for _, prevNode := range prevNodes {
|
||||
@@ -150,7 +159,7 @@ func (self *FileTreeViewModel) findNewSelectedIdx(prevNodes []*FileNode, currNod
|
||||
|
||||
// If you started off with a rename selected, and now it's broken in two, we want you to jump to the new file, not the old file.
|
||||
// This is because the new should be in the same position as the rename was meaning less cursor jumping
|
||||
foundOldFileInRename := prevNode.File != nil && prevNode.File.IsRename() && node.path == prevNode.File.PreviousPath
|
||||
foundOldFileInRename := prevNode.File != nil && prevNode.File.IsRename() && node.GetPath() == prevNode.File.PreviousPath
|
||||
foundNode := utils.StringArraysOverlap(paths, selectedPaths) && !foundOldFileInRename
|
||||
if foundNode {
|
||||
return idx
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/samber/lo"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -30,3 +32,174 @@ func TestSetStatusFilterPreservingSelection(t *testing.T) {
|
||||
assert.Equal(t, "file3", viewModel.GetSelectedPath())
|
||||
assert.False(t, viewModel.IsSelectingRange())
|
||||
}
|
||||
|
||||
func TestSetTreeSelectsNewFileWhenSelectedRenameSplits(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
showRootItem bool
|
||||
expectedPath string
|
||||
}{
|
||||
{
|
||||
name: "with root item",
|
||||
showRootItem: true,
|
||||
expectedPath: "dir/new.go",
|
||||
},
|
||||
{
|
||||
name: "without root item",
|
||||
showRootItem: false,
|
||||
expectedPath: "dir/new.go",
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
userConfig := config.GetDefaultConfig()
|
||||
userConfig.Gui.ShowRootItemInFileTree = s.showRootItem
|
||||
cmn := common.NewDummyCommonWithUserConfigAndAppState(userConfig, nil)
|
||||
|
||||
files := []*models.File{
|
||||
{Path: "dir/new.go", PreviousPath: "dir/old.go"},
|
||||
{Path: "other.go"},
|
||||
}
|
||||
viewModel := NewFileTreeViewModel(func() []*models.File { return files }, cmn, true)
|
||||
viewModel.SetTree()
|
||||
idx, found := viewModel.GetIndexForPath(InternalTreePathForFilePath("dir/new.go", s.showRootItem))
|
||||
assert.True(t, found)
|
||||
viewModel.SetSelection(idx)
|
||||
|
||||
// the rename is split into its two halves, e.g. because it was unstaged
|
||||
files = []*models.File{
|
||||
{Path: "dir/new.go"},
|
||||
{Path: "dir/old.go"},
|
||||
{Path: "other.go"},
|
||||
}
|
||||
viewModel.SetTree()
|
||||
|
||||
assert.Equal(t, s.expectedPath, viewModel.GetSelectedPath())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTreeFollowsRenameIntoCollapsedDir(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
showRootItem bool
|
||||
expectedPath string
|
||||
}{
|
||||
{
|
||||
name: "with root item",
|
||||
showRootItem: true,
|
||||
expectedPath: "a/new.go",
|
||||
},
|
||||
{
|
||||
name: "without root item",
|
||||
showRootItem: false,
|
||||
expectedPath: "a/new.go",
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
userConfig := config.GetDefaultConfig()
|
||||
userConfig.Gui.ShowRootItemInFileTree = s.showRootItem
|
||||
cmn := common.NewDummyCommonWithUserConfigAndAppState(userConfig, nil)
|
||||
|
||||
files := []*models.File{
|
||||
{Path: "a/b.go"},
|
||||
{Path: "a/new.go"},
|
||||
{Path: "old.go"},
|
||||
}
|
||||
viewModel := NewFileTreeViewModel(func() []*models.File { return files }, cmn, true)
|
||||
viewModel.SetTree()
|
||||
viewModel.ToggleCollapsed(InternalTreePathForFilePath("a", s.showRootItem))
|
||||
idx, found := viewModel.GetIndexForPath(InternalTreePathForFilePath("old.go", s.showRootItem))
|
||||
assert.True(t, found)
|
||||
viewModel.SetSelection(idx)
|
||||
|
||||
// staging the deletion of old.go turns it into the old half of a rename
|
||||
files = []*models.File{
|
||||
{Path: "a/b.go"},
|
||||
{Path: "a/new.go", PreviousPath: "old.go"},
|
||||
}
|
||||
viewModel.SetTree()
|
||||
|
||||
assert.Equal(t, s.expectedPath, viewModel.GetSelectedPath())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTreeKeepsSelectionAcrossCompressionChanges(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
filesBefore []string
|
||||
selectedPath string
|
||||
filesAfter []string
|
||||
expectedPath string
|
||||
}{
|
||||
{
|
||||
name: "compressed root directory splits",
|
||||
filesBefore: []string{"pkg/gui/controllers/helpers/refresh_helper.go"},
|
||||
selectedPath: "pkg/gui/controllers/helpers",
|
||||
filesAfter: []string{
|
||||
"pkg/gui/context/base_context.go",
|
||||
"pkg/gui/controllers/helpers/refresh_helper.go",
|
||||
},
|
||||
expectedPath: "pkg/gui",
|
||||
},
|
||||
{
|
||||
name: "compressed subdirectory splits",
|
||||
filesBefore: []string{"a/b/c/file1", "file2"},
|
||||
selectedPath: "a/b/c",
|
||||
filesAfter: []string{"a/b/c/file1", "a/b/d/file3", "file2"},
|
||||
expectedPath: "a/b",
|
||||
},
|
||||
{
|
||||
name: "file inside a compressed directory that splits",
|
||||
filesBefore: []string{"pkg/gui/controllers/helpers/refresh_helper.go"},
|
||||
selectedPath: "pkg/gui/controllers/helpers/refresh_helper.go",
|
||||
filesAfter: []string{
|
||||
"pkg/gui/context/base_context.go",
|
||||
"pkg/gui/controllers/helpers/refresh_helper.go",
|
||||
},
|
||||
expectedPath: "pkg/gui/controllers/helpers/refresh_helper.go",
|
||||
},
|
||||
{
|
||||
name: "directories merge into one compressed node",
|
||||
filesBefore: []string{
|
||||
"pkg/gui/context/base_context.go",
|
||||
"pkg/gui/controllers/helpers/refresh_helper.go",
|
||||
},
|
||||
selectedPath: "pkg/gui",
|
||||
filesAfter: []string{"pkg/gui/controllers/helpers/refresh_helper.go"},
|
||||
expectedPath: "pkg/gui/controllers/helpers",
|
||||
},
|
||||
}
|
||||
|
||||
toFiles := func(paths []string) []*models.File {
|
||||
return lo.Map(paths, func(path string, _ int) *models.File {
|
||||
return &models.File{Path: path}
|
||||
})
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
files := toFiles(s.filesBefore)
|
||||
cmn := common.NewDummyCommon()
|
||||
viewModel := NewFileTreeViewModel(
|
||||
func() []*models.File { return files },
|
||||
cmn,
|
||||
true,
|
||||
)
|
||||
viewModel.SetTree()
|
||||
showRootItem := cmn.UserConfig().Gui.ShowRootItemInFileTree
|
||||
idx, found := viewModel.GetIndexForPath(InternalTreePathForFilePath(s.selectedPath, showRootItem))
|
||||
assert.True(t, found)
|
||||
viewModel.SetSelection(idx)
|
||||
|
||||
files = toFiles(s.filesAfter)
|
||||
viewModel.SetTree()
|
||||
|
||||
assert.Equal(t, s.expectedPath, viewModel.GetSelectedPath())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,20 @@ func (self *Node[T]) GetInternalPath() string {
|
||||
return self.path
|
||||
}
|
||||
|
||||
// This returns the logical paths of all the directories that this node stands
|
||||
// for, from the user's point of view like GetPath. For most nodes that's just
|
||||
// its own path. A compressed node (see CompressionLevel) also stands for the
|
||||
// directories that were squished into it, so for "a/b/c" with a
|
||||
// CompressionLevel of 2 this returns "a/b/c", "a/b" and "a".
|
||||
func (self *Node[T]) GetPaths() []string {
|
||||
splitPath := split(self.path)
|
||||
paths := make([]string, 0, self.CompressionLevel+1)
|
||||
for i := 0; i <= self.CompressionLevel; i++ {
|
||||
paths = append(paths, strings.TrimPrefix(join(splitPath[:len(splitPath)-i]), "./"))
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
func (self *Node[T]) Sort(cmp func(a, b *Node[T]) int) {
|
||||
self.SortChildren(cmp)
|
||||
|
||||
|
||||
+53
-13
@@ -494,7 +494,7 @@ func (gui *Gui) onUserConfigLoaded() error {
|
||||
gui.previousLanguageConfig = userConfig.Gui.Language
|
||||
}
|
||||
|
||||
gui.setColorScheme()
|
||||
gui.applyTheme()
|
||||
gui.configureViewProperties()
|
||||
|
||||
gui.g.SearchEscapeKeys = config.GetValidatedKeyBindingKeys(userConfig.Keybinding.Universal.Return)
|
||||
@@ -517,7 +517,6 @@ func (gui *Gui) onUserConfigLoaded() error {
|
||||
// sake of backwards compatibility. We're making use of short circuiting here
|
||||
gui.ShowExtrasWindow = userConfig.Gui.ShowCommandLog && !gui.c.GetAppState().HideCommandLog
|
||||
|
||||
authors.SetCustomAuthors(userConfig.Gui.AuthorColors)
|
||||
if userConfig.Gui.NerdFontsVersion != "" {
|
||||
icons.SetNerdFontsVersion(userConfig.Gui.NerdFontsVersion)
|
||||
} else if userConfig.Gui.ShowIcons {
|
||||
@@ -526,13 +525,6 @@ func (gui *Gui) onUserConfigLoaded() error {
|
||||
icons.SetNerdFontsVersion("")
|
||||
}
|
||||
|
||||
if len(userConfig.Gui.BranchColorPatterns) > 0 {
|
||||
presentation.SetCustomBranches(userConfig.Gui.BranchColorPatterns, true)
|
||||
} else {
|
||||
// Fall back to the deprecated branchColors config
|
||||
presentation.SetCustomBranches(userConfig.Gui.BranchColors, false)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -942,6 +934,19 @@ func (gui *Gui) Run(startArgs appTypes.StartArgs) error {
|
||||
|
||||
g.ErrorHandler = gui.PopupHandler.ErrorHandler
|
||||
|
||||
gui.c.Log.Infof("Terminal color scheme: %s", g.DetectedColorScheme())
|
||||
g.SetColorSchemeChangeHandler(func(colorScheme gocui.DetectedColorScheme) error {
|
||||
gui.c.Log.Infof("Terminal color scheme changed: %s", colorScheme)
|
||||
gui.applyTheme()
|
||||
gui.configureViewProperties()
|
||||
for _, context := range gui.c.Context().AllList() {
|
||||
context.HandleRender()
|
||||
}
|
||||
gui.helpers.Refresh.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.STATUS}})
|
||||
gui.helpers.Diff.RenderToMainAgain()
|
||||
return nil
|
||||
})
|
||||
|
||||
gui.g.ShouldHandleMouseEvent = func(view *gocui.View, key gocui.KeyName) bool {
|
||||
if gui.helpers.Confirmation.IsPopupPanelFocused() && gui.currentViewName() != view.Name() &&
|
||||
!gocui.IsMouseScrollKey(key) {
|
||||
@@ -1244,15 +1249,50 @@ func (gui *Gui) showBreakingChangesMessage() {
|
||||
}
|
||||
}
|
||||
|
||||
// setColorScheme sets the color scheme for the app based on the user config
|
||||
func (gui *Gui) setColorScheme() {
|
||||
userConfig := gui.UserConfig()
|
||||
theme.UpdateTheme(userConfig.Gui.Theme)
|
||||
// applyTheme sets the colors of the app from the theme in the user config,
|
||||
// with the overrides for the terminal's background applied
|
||||
func (gui *Gui) applyTheme() {
|
||||
themeConfig := gui.UserConfig().Gui.ThemeForBackground(gui.terminalHasLightBackground(), gui.terminalBackgroundColor())
|
||||
theme.UpdateTheme(themeConfig)
|
||||
authors.SetCustomAuthors(themeConfig.AuthorColors)
|
||||
presentation.SetCustomBranches(themeConfig.BranchColorPatterns)
|
||||
|
||||
gui.g.FgColor = theme.InactiveBorderColor
|
||||
gui.g.SelFgColor = theme.ActiveBorderColor
|
||||
gui.g.FrameColor = theme.InactiveBorderColor
|
||||
gui.g.SelFrameColor = theme.ActiveBorderColor
|
||||
|
||||
gui.applyTerminalBackground()
|
||||
}
|
||||
|
||||
// applyTerminalBackground tells the colors that depend on the terminal's
|
||||
// background whether it is light.
|
||||
func (gui *Gui) applyTerminalBackground() {
|
||||
authors.SetLightBackground(gui.terminalHasLightBackground())
|
||||
}
|
||||
|
||||
// terminalHasLightBackground goes by gui.colorScheme, or by what the terminal
|
||||
// tells us if that is 'auto'.
|
||||
func (gui *Gui) terminalHasLightBackground() bool {
|
||||
switch gui.UserConfig().Gui.ColorScheme {
|
||||
case "dark":
|
||||
return false
|
||||
case "light":
|
||||
return true
|
||||
default:
|
||||
return gui.g.DetectedColorScheme().ColorScheme == gocui.ColorSchemeLight
|
||||
}
|
||||
}
|
||||
|
||||
// terminalBackgroundColor returns the background color that the terminal told
|
||||
// us, as #rrggbb. It returns "" if the terminal didn't tell us, or if
|
||||
// gui.colorScheme disagrees with it about whether the background is light.
|
||||
func (gui *Gui) terminalBackgroundColor() string {
|
||||
detected := gui.g.DetectedColorScheme()
|
||||
if (detected.ColorScheme == gocui.ColorSchemeLight) != gui.terminalHasLightBackground() {
|
||||
return ""
|
||||
}
|
||||
return detected.Background
|
||||
}
|
||||
|
||||
func (gui *Gui) onUIThread(f func() error) {
|
||||
|
||||
@@ -20,8 +20,8 @@ func (gui *Gui) runTaskForView(view *gocui.View, task types.UpdateTask) error {
|
||||
case *types.RunCommandTask:
|
||||
return gui.newCmdTask(view, v.Cmd, v.Prefix)
|
||||
|
||||
case *types.RunPtyTask:
|
||||
return gui.newPtyTask(view, v.Cmd, v.Prefix)
|
||||
case *types.RunDiffRendererTask:
|
||||
return gui.newRenderTask(view, v.Cmd, v.Prefix)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/jesseduffield/lazygit/pkg/gocui"
|
||||
"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
|
||||
// of running the command (see runRender) needs to know about it.
|
||||
type renderSpec struct {
|
||||
view *gocui.View
|
||||
cmd *exec.Cmd
|
||||
// The width the renderer lays its rendering out to, and the width the view
|
||||
// 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.
|
||||
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 string) 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.
|
||||
// The variable names the protocol versions we understand, and a renderer
|
||||
// that doesn't understand it ignores it, so we can set it always. It has to
|
||||
// be set before the plain path below, since on that path git renders the
|
||||
// diff itself, and git speaks the protocol too, for its word-diff formats,
|
||||
// whose markup we could not otherwise resolve.
|
||||
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)
|
||||
}
|
||||
|
||||
// Mark the view as loading synchronously now, before the layout pass: the
|
||||
// actual task is created in afterLayout (below), which runs after layout, so
|
||||
// without this the next layout pass would clamp the scroll position to the
|
||||
// not-yet-loaded content.
|
||||
gui.getManager(view).StartLoading()
|
||||
// Hold the scrollbar at its current height while the re-render loads, so the
|
||||
// thumb doesn't shrink and snap back when the first partial paint swaps in
|
||||
// (see the matching call in newCmdTask).
|
||||
view.FreezeScrollbarHeight()
|
||||
|
||||
// Run the render after layout so that it gets the correct size
|
||||
gui.afterLayout(func() error {
|
||||
// The layout may have changed the size of the view, so only now is the
|
||||
// width to render at known, and with it the renderer command.
|
||||
width := view.InnerWidth()
|
||||
diffRendererConfigManager := gui.stateAccessor.GetDiffRendererConfigManager()
|
||||
values := config.DiffRendererValues{
|
||||
Width: width,
|
||||
DiffContext: gui.c.UserConfig().Git.DiffContextSize,
|
||||
LightBackground: gui.terminalHasLightBackground(),
|
||||
}
|
||||
stdinFilter, stdinFilterErr := diffRendererConfigManager.GetStdinFilterCommand(values)
|
||||
externalDiff, externalDiffErr := diffRendererConfigManager.GetExternalDiffCommand(values)
|
||||
if err := errors.Join(stdinFilterErr, externalDiffErr); err != nil {
|
||||
// The commands are checked with made-up values when the config is
|
||||
// loaded, so only one that fails for some values and not for others
|
||||
// gets here. Git's own diff is shown instead.
|
||||
gui.c.ErrorToast(err.Error())
|
||||
}
|
||||
|
||||
cmdStr := strings.Join(cmd.Args, " ")
|
||||
|
||||
// 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")
|
||||
|
||||
// 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
|
||||
// the command's arguments were settled before it. An empty command
|
||||
// means the user wants git's own diff.external config to apply, so
|
||||
// leave the variable unset in that case; git takes it being set at all
|
||||
// as an instruction, however little it says.
|
||||
if externalDiff != "" {
|
||||
cmd.Env = append(cmd.Env, "GIT_EXTERNAL_DIFF="+externalDiff)
|
||||
}
|
||||
|
||||
spec := renderSpec{
|
||||
view: view,
|
||||
cmd: cmd,
|
||||
width: width,
|
||||
stdinFilter: stdinFilter,
|
||||
}
|
||||
run := gui.ptyRender
|
||||
if rendersThroughAPipe() {
|
||||
run = gui.pipedRender
|
||||
}
|
||||
return gui.newTaskForRender(spec, prefix, cmdStr, run)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// The start and onClose functions a render hands to its task: how to get the
|
||||
// command running and the output reader for it, and how to tear it down again
|
||||
// once the task is stopped.
|
||||
type (
|
||||
startRender func() (tasks.Cmd, io.Reader)
|
||||
onCloseRender func()
|
||||
)
|
||||
|
||||
// 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.
|
||||
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. 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(spec renderSpec, prefix string, key string, run runRender) error {
|
||||
setColumnsEnvVar(spec.cmd, spec.width)
|
||||
|
||||
start, onClose := run(spec)
|
||||
|
||||
manager := gui.getManager(spec.view)
|
||||
linesToRead := gui.linesToReadFromCmdTask(spec.view)
|
||||
return manager.NewTask(manager.NewCmdTask(start, prefix, 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) != ""
|
||||
}
|
||||
|
||||
// pipedRender feeds the diff renderer the command's output through a pipe.
|
||||
//
|
||||
// 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
|
||||
// own business, named in the environment and run by git per file, so with one
|
||||
// the command runs alone.
|
||||
func (gui *Gui) pipedRender(spec renderSpec) (startRender, onCloseRender) {
|
||||
if spec.stdinFilter == "" {
|
||||
return gui.plainRender(spec)
|
||||
}
|
||||
|
||||
view := spec.view
|
||||
cmd := spec.cmd
|
||||
|
||||
var pipe io.ReadCloser
|
||||
start := func() (tasks.Cmd, io.Reader) {
|
||||
// See the matching call in ptyRender 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(),
|
||||
)
|
||||
if err != nil {
|
||||
gui.c.Log.Error(err)
|
||||
// The command has been started and stopped again by now, so it
|
||||
// can't be run a second time without the renderer. Show what went
|
||||
// wrong where the diff would have been.
|
||||
return tasks.ExecCmd{Cmd: cmd}, strings.NewReader(err.Error())
|
||||
}
|
||||
pipe = reader
|
||||
return pipeline, reader
|
||||
}
|
||||
|
||||
onClose := func() {
|
||||
// Closing the reader brings the pipeline down. The renderer's next write
|
||||
// fails, so it exits, and git's write into the pipe the renderer was
|
||||
// reading fails in turn.
|
||||
if pipe != nil {
|
||||
pipe.Close()
|
||||
pipe = nil
|
||||
}
|
||||
}
|
||||
|
||||
return start, onClose
|
||||
}
|
||||
|
||||
// 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.
|
||||
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_")
|
||||
}
|
||||
@@ -21,7 +21,17 @@ type authorNameCacheKey struct {
|
||||
var (
|
||||
authorInitialCache = make(map[string]string)
|
||||
authorNameCache = make(map[authorNameCacheKey]string)
|
||||
authorStyleCache = make(map[string]*style.TextStyle)
|
||||
|
||||
// The styles from gui.authorColors
|
||||
customAuthorStyles = make(map[string]*style.TextStyle)
|
||||
// The styles derived from the names of the other authors
|
||||
authorStyleCache = make(map[string]*style.TextStyle)
|
||||
|
||||
// Whether the terminal has a light background, for the derived styles to
|
||||
// stand out against
|
||||
lightBackground bool
|
||||
|
||||
colorsVersion int
|
||||
)
|
||||
|
||||
const authorNameWildcard = "*"
|
||||
@@ -74,12 +84,16 @@ func AuthorWithLength(authorName string, length int) string {
|
||||
}
|
||||
|
||||
func AuthorStyle(authorName string) *style.TextStyle {
|
||||
if value, ok := authorStyleCache[authorName]; ok {
|
||||
if value, ok := customAuthorStyles[authorName]; ok {
|
||||
return value
|
||||
}
|
||||
|
||||
// use the unified style whatever the author name is
|
||||
if value, ok := authorStyleCache[authorNameWildcard]; ok {
|
||||
if value, ok := customAuthorStyles[authorNameWildcard]; ok {
|
||||
return value
|
||||
}
|
||||
|
||||
if value, ok := authorStyleCache[authorName]; ok {
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -91,12 +105,42 @@ func AuthorStyle(authorName string) *style.TextStyle {
|
||||
}
|
||||
|
||||
func trueColorStyle(str string) style.TextStyle {
|
||||
hash := md5.Sum([]byte(str))
|
||||
c := colorful.Hsl(randFloat(hash[0:4])*360.0, 0.6+0.4*randFloat(hash[4:8]), 0.4+randFloat(hash[8:12])*0.2)
|
||||
c := colorAtPosition(ColorPosition(str))
|
||||
|
||||
return style.New().SetFg(style.NewRGBColor(color.RGB(uint8(c.R*255), uint8(c.G*255), uint8(c.B*255))))
|
||||
}
|
||||
|
||||
// To check the colors at the edges of the ranges below, run
|
||||
// `go run ./cmd/author_colors_repo <path>` and open the repository it creates.
|
||||
func colorAtPosition(hue, saturation, lightness float64) colorful.Color {
|
||||
// The lightness of an HSLuv color is how bright it looks, so every author
|
||||
// comes out about equally readable whichever hue their name lands on. Plain
|
||||
// HSL spreads them instead. At one and the same lightness, it gives a
|
||||
// glaring yellow and a blue that all but disappears.
|
||||
//
|
||||
// There is one lightness range for a dark background and one for a light
|
||||
// background. Each keeps every author above a contrast ratio of 4.5:1
|
||||
// against common backgrounds of its kind, such as #1e1e1e and #fdf6e3.
|
||||
//
|
||||
// Saturation in HSLuv is a fraction of the most colorful a hue can get at
|
||||
// that lightness, and pale colors are hard to tell apart, so keep it near
|
||||
// the top of its range.
|
||||
minLightness := 0.57
|
||||
if lightBackground {
|
||||
minLightness = 0.31
|
||||
}
|
||||
|
||||
return colorful.HSLuv(hue*360.0, 0.8+0.2*saturation, minLightness+0.15*lightness)
|
||||
}
|
||||
|
||||
// ColorPosition says where an author's color lies within the range of hues,
|
||||
// saturations and lightnesses that colorAtPosition picks from. Each is a
|
||||
// fraction from 0 up to 1, derived from a hash of the author's name.
|
||||
func ColorPosition(authorName string) (hue, saturation, lightness float64) {
|
||||
hash := md5.Sum([]byte(authorName))
|
||||
return randFloat(hash[0:4]), randFloat(hash[4:8]), randFloat(hash[8:12])
|
||||
}
|
||||
|
||||
func randFloat(hash []byte) float64 {
|
||||
return float64(randInt(hash, 100)) / 100
|
||||
}
|
||||
@@ -128,5 +172,32 @@ func getInitials(authorName string) string {
|
||||
}
|
||||
|
||||
func SetCustomAuthors(customAuthorColors map[string]string) {
|
||||
authorStyleCache = utils.SetCustomColors(customAuthorColors)
|
||||
customAuthorStyles = utils.SetCustomColors(customAuthorColors)
|
||||
colorsChanged()
|
||||
}
|
||||
|
||||
// SetLightBackground says whether the terminal has a light background, for the
|
||||
// colors of authors to stand out against.
|
||||
func SetLightBackground(light bool) {
|
||||
if light == lightBackground {
|
||||
return
|
||||
}
|
||||
|
||||
lightBackground = light
|
||||
authorStyleCache = make(map[string]*style.TextStyle)
|
||||
colorsChanged()
|
||||
}
|
||||
|
||||
// colorsChanged drops what was rendered with the previous colors of authors.
|
||||
func colorsChanged() {
|
||||
authorInitialCache = make(map[string]string)
|
||||
authorNameCache = make(map[authorNameCacheKey]string)
|
||||
colorsVersion++
|
||||
}
|
||||
|
||||
// ColorsVersion changes whenever the colors of authors change, so that
|
||||
// whatever keeps the styles of authors around can tell when they are out of
|
||||
// date.
|
||||
func ColorsVersion() int {
|
||||
return colorsVersion
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user