mirror of
https://github.com/jesseduffield/lazygit.git
synced 2026-10-04 13:06:51 -04:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5e3cc200e | ||
|
|
8e4efddbf7 | ||
|
|
82c54ed3d2 | ||
|
|
bd62b519de | ||
|
|
04e0a9bb45 | ||
|
|
2b4ac986a2 | ||
|
|
caedf57484 | ||
|
|
046b0d9daa | ||
|
|
e3c5e07b20 | ||
|
|
e4e16fa38e | ||
|
|
b7e029adc7 | ||
|
|
08d679c3a8 | ||
|
|
2947b56134 | ||
|
|
659d668e16 | ||
|
|
7bbcec965b | ||
|
|
24de156592 | ||
|
|
8d3cce4a49 | ||
|
|
95757ceb3b | ||
|
|
2087a02f01 | ||
|
|
6ffe98abac | ||
|
|
046cb942c2 | ||
|
|
fc2f8b7b20 | ||
|
|
298dae23e8 | ||
|
|
a02b54e1b7 | ||
|
|
0af4e5a843 | ||
|
|
e0503b9922 | ||
|
|
ef239c04fb | ||
|
|
d508badd62 | ||
|
|
e7d0116312 | ||
|
|
85fdb700ba | ||
|
|
7513d77567 | ||
|
|
c757063264 | ||
|
|
b24955063c | ||
|
|
605bc026a1 | ||
|
|
c6930e0538 | ||
|
|
3a59aba46d | ||
|
|
213ae8dd07 | ||
|
|
4780953cef | ||
|
|
11bc8b87fa | ||
|
|
3bfbc9d255 | ||
|
|
8121a0cc74 | ||
|
|
4adca84d68 | ||
|
|
b7c61aa883 | ||
|
|
40f6767cfc | ||
|
|
776d8f4d2e | ||
|
|
4b67a45a16 | ||
|
|
a82d952f48 | ||
|
|
549ce09f71 | ||
|
|
cef804f27a | ||
|
|
60f902f026 | ||
|
|
7ce3165afa | ||
|
|
c28e25524a | ||
|
|
73c7dc9c5d | ||
|
|
b542579db3 | ||
|
|
e6274af015 | ||
|
|
4f57bf22c9 | ||
|
|
8dbd7d44ff | ||
|
|
4b4dccfd7d | ||
|
|
81ea3107ed | ||
|
|
5c8bc790ff | ||
|
|
b5d612e6d6 | ||
|
|
dea279920c | ||
|
|
5834440767 | ||
|
|
55fb3ef4e6 | ||
|
|
f314cb3763 | ||
|
|
516e963392 | ||
|
|
804a134aa5 | ||
|
|
82fc6fb111 | ||
|
|
0bda93d4c3 | ||
|
|
6735bf4c89 | ||
|
|
4bd1322941 | ||
|
|
45cf993982 | ||
|
|
e4659145e8 | ||
|
|
bf6e9a1bd3 | ||
|
|
a68cd6af9c | ||
|
|
4ca012dbfb | ||
|
|
6bd1c1d068 | ||
|
|
5d692e8961 | ||
|
|
9cc33c479b | ||
|
|
c79e360584 | ||
|
|
f76cc27956 | ||
|
|
5a50bfd179 | ||
|
|
c36333af3d | ||
|
|
4d78d76a44 | ||
|
|
d08a9849c3 | ||
|
|
3791b5057a | ||
|
|
dfe5c805c4 | ||
|
|
e94ff63bc5 | ||
|
|
723504a290 | ||
|
|
40a29fd622 | ||
|
|
648748781d | ||
|
|
63e8b8c01c | ||
|
|
ed47529604 | ||
|
|
ff5d0155db | ||
|
|
48acf3818f | ||
|
|
de3e4838ad | ||
|
|
6af8f278d0 | ||
|
|
e3c6887e5d | ||
|
|
c34e0deca7 | ||
|
|
75b2c50a55 | ||
|
|
af7c71d1ee | ||
|
|
161bb684fa | ||
|
|
a624e0457f | ||
|
|
f2aa7e7e28 | ||
|
|
75aa339b4e | ||
|
|
45d45d2397 | ||
|
|
f7e8b2dd71 | ||
|
|
8b5d59c238 | ||
|
|
f82f4f6dbc | ||
|
|
ff3c5d331e | ||
|
|
adef3bd4ca | ||
|
|
33f9f81c8c | ||
|
|
f6fafc65ee | ||
|
|
9c645088bf | ||
|
|
dd1bf629b8 | ||
|
|
c80a94aa7a | ||
|
|
6c0b805137 | ||
|
|
8a69d994c0 | ||
|
|
037e957282 | ||
|
|
db011d8e34 | ||
|
|
752526c880 | ||
|
|
c63fed2074 | ||
|
|
1b52a0d83f | ||
|
|
909a3b6791 | ||
|
|
558ceb64c7 | ||
|
|
1034962c7e | ||
|
|
eabe7f462a | ||
|
|
22c10479d5 | ||
|
|
f0572238cb | ||
|
|
78f3a7a478 | ||
|
|
90772e1eaa | ||
|
|
526c9dea9b | ||
|
|
c244c8f231 | ||
|
|
bfde06d049 | ||
|
|
6b8abb7887 | ||
|
|
2b6a109e38 | ||
|
|
71a30155dc | ||
|
|
6ee20840b2 | ||
|
|
56424eb1aa | ||
|
|
38c7030b0f | ||
|
|
31b8524fe6 | ||
|
|
0ae34aeeb7 | ||
|
|
e1c376ef54 | ||
|
|
c13f550d63 | ||
|
|
06351c1adf | ||
|
|
0b55eaca1d | ||
|
|
ee8c31880c | ||
|
|
daf8176dd7 | ||
|
|
76109a4c44 | ||
|
|
082d342bf8 | ||
|
|
39c56553b3 | ||
|
|
c5cd217a65 | ||
|
|
9e2a3a87dd | ||
|
|
ac580ae6a0 | ||
|
|
9e1e20fef2 | ||
|
|
4b49bd406f | ||
|
|
7351907474 | ||
|
|
a349e886ce | ||
|
|
dd61c49a15 | ||
|
|
1c3db24e44 | ||
|
|
15962e489d | ||
|
|
ac9515d8c7 | ||
|
|
72a92d748f | ||
|
|
36c2b00336 | ||
|
|
67b08ac239 | ||
|
|
67b8ef449c | ||
|
|
bb856ad7c6 | ||
|
|
b54b8ae746 | ||
|
|
65bd0ab431 | ||
|
|
93b9e1bd19 | ||
|
|
a51f64814c | ||
|
|
b5e325b0a4 | ||
|
|
88c76868ba | ||
|
|
e471567b5d | ||
|
|
13ee0f0a5d | ||
|
|
76a1b501f2 | ||
|
|
7201a91b69 | ||
|
|
31d796ee75 | ||
|
|
0ac869a415 | ||
|
|
9da9143aed | ||
|
|
b0383ba73a | ||
|
|
a3096e720c | ||
|
|
c599aaed51 | ||
|
|
f999bbce7c | ||
|
|
bff076c70a | ||
|
|
979c3d6278 | ||
|
|
1fc8823825 | ||
|
|
eeb9c02836 | ||
|
|
4d39668743 | ||
|
|
627cc285f7 | ||
|
|
bee338f93b | ||
|
|
01bf7f21e6 | ||
|
|
c517d1e0a2 | ||
|
|
8cad8cda8f | ||
|
|
6b81e6adca | ||
|
|
b499eba1a8 | ||
|
|
97daec7228 | ||
|
|
ff2a799200 | ||
|
|
31fcec16d9 | ||
|
|
0d395e4051 | ||
|
|
09178a1276 | ||
|
|
b66aa42ee5 | ||
|
|
3cfdae4116 | ||
|
|
d7956c481d | ||
|
|
7a3291a1f7 | ||
|
|
08c2b46d04 | ||
|
|
1c48842277 | ||
|
|
010f6d7f6e | ||
|
|
39c20bc634 | ||
|
|
823d95a8c6 | ||
|
|
225cd3cc60 | ||
|
|
91d62da577 | ||
|
|
9f71ed6c41 | ||
|
|
984eb95cb7 | ||
|
|
1da762c295 | ||
|
|
e357c00d4d | ||
|
|
1be6c522d8 | ||
|
|
8af59c3e6e | ||
|
|
c713d19383 | ||
|
|
4f7324bad0 | ||
|
|
aed3d56840 | ||
|
|
3745ba506b | ||
|
|
5e2254395a | ||
|
|
b243f30f48 | ||
|
|
e57843d947 | ||
|
|
5bb6198219 | ||
|
|
bbaeab68e1 | ||
|
|
946c1dff99 | ||
|
|
d838965a41 | ||
|
|
469938ee9b | ||
|
|
f7af2b991d | ||
|
|
75c3ab8a4a | ||
|
|
7bd0c779c7 | ||
|
|
bc7873144e |
@@ -46,36 +46,6 @@ jobs:
|
||||
# we're passing -short so that we skip the integration tests, which will be run in parallel below
|
||||
run: |
|
||||
go test ./... -short
|
||||
integration-tests-old:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
parallelism: [5]
|
||||
index: [0,1,2,3,4]
|
||||
name: "Integration Tests (Old pattern) (${{ matrix.index }}/${{ matrix.parallelism }})"
|
||||
env:
|
||||
GOFLAGS: -mod=vendor
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: 1.18.x
|
||||
- name: Cache build
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: |
|
||||
~/.cache/go-build
|
||||
~/go/pkg/mod
|
||||
key: ${{runner.os}}-go-${{hashFiles('**/go.sum')}}-test
|
||||
restore-keys: |
|
||||
${{runner.os}}-go-
|
||||
- name: Test code
|
||||
# for file.allow thing see https://vielmetti.typepad.com/logbook/2022/10/git-security-fixes-lead-to-fatal-transport-file-not-allowed-error-in-ci-systems-cve-2022-39253.html
|
||||
run: |
|
||||
git config --global protocol.file.allow always && PARALLEL_TOTAL=${{ matrix.parallelism }} PARALLEL_INDEX=${{ matrix.index }} go test pkg/integration/deprecated/*.go
|
||||
integration-tests:
|
||||
runs-on: ubuntu-latest
|
||||
name: "Integration Tests"
|
||||
@@ -98,8 +68,9 @@ jobs:
|
||||
restore-keys: |
|
||||
${{runner.os}}-go-
|
||||
- name: Test code
|
||||
# LONG_WAIT_BEFORE_FAIL means that for a given test assertion, we'll wait longer before failing
|
||||
run: |
|
||||
go test pkg/integration/clients/*.go
|
||||
LONG_WAIT_BEFORE_FAIL=true go test pkg/integration/clients/*.go
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
@@ -164,6 +135,10 @@ jobs:
|
||||
# ensure our vendor directory matches up with our go modules
|
||||
run: |
|
||||
go mod vendor && git diff --exit-code || (echo "Unexpected change to vendor directory. Run 'go mod vendor' locally and commit the changes" && exit 1)
|
||||
- name: Check Integration Tests List
|
||||
# ensure our tests list matches up with our generator's output
|
||||
run: |
|
||||
go generate pkg/integration/tests/tests.go && git diff --exit-code || (echo "Unexpected change to tests list. Run 'go generate pkg/integration/tests/tests.go' locally and commit the changes" && exit 1)
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
|
||||
@@ -20,12 +20,12 @@ jobs:
|
||||
run: echo "UUID_APP_TAG=$(uuidgen)" >> $GITHUB_ENV
|
||||
- name: Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: registry.uffizzi.com/${{ env.UUID_APP_TAG }}
|
||||
tags: type=raw,value=60d
|
||||
- name: Build and Push Image to registry.uffizzi.com ephemeral registry
|
||||
uses: docker/build-push-action@v2
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
@@ -60,17 +60,11 @@ jobs:
|
||||
name: preview-spec
|
||||
path: docker-compose.rendered.yml
|
||||
retention-days: 2
|
||||
- name: Serialize PR Event to File
|
||||
run: |
|
||||
cat << EOF > event.json
|
||||
${{ toJSON(github.event) }}
|
||||
|
||||
EOF
|
||||
- name: Upload PR Event as Artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: preview-spec
|
||||
path: event.json
|
||||
path: ${{ github.event_path }}
|
||||
retention-days: 2
|
||||
|
||||
delete-preview:
|
||||
@@ -79,11 +73,9 @@ jobs:
|
||||
if: ${{ github.event.action == 'closed' }}
|
||||
steps:
|
||||
# If this PR is closing, we will not render a compose file nor pass it to the next workflow.
|
||||
- name: Serialize PR Event to File
|
||||
run: echo '${{ toJSON(github.event) }}' > event.json
|
||||
- name: Upload PR Event as Artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: preview-spec
|
||||
path: event.json
|
||||
path: ${{ github.event_path }}
|
||||
retention-days: 2
|
||||
|
||||
@@ -7,11 +7,11 @@ on:
|
||||
types:
|
||||
- completed
|
||||
|
||||
|
||||
jobs:
|
||||
cache-compose-file:
|
||||
name: Cache Compose File
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
outputs:
|
||||
compose-file-cache-key: ${{ env.COMPOSE_FILE_HASH }}
|
||||
pr-number: ${{ env.PR_NUMBER }}
|
||||
@@ -29,6 +29,9 @@ jobs:
|
||||
let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
|
||||
return artifact.name == "preview-spec"
|
||||
})[0];
|
||||
if (matchArtifact === undefined) {
|
||||
throw TypeError('Build Artifact not found!');
|
||||
}
|
||||
let download = await github.rest.actions.downloadArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
@@ -39,16 +42,18 @@ jobs:
|
||||
fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/preview-spec.zip`, Buffer.from(download.data));
|
||||
- name: 'Unzip artifact'
|
||||
run: unzip preview-spec.zip
|
||||
|
||||
- name: Read Event into ENV
|
||||
run: |
|
||||
echo 'EVENT_JSON<<EOF' >> $GITHUB_ENV
|
||||
cat event.json >> $GITHUB_ENV
|
||||
echo 'EOF' >> $GITHUB_ENV
|
||||
echo -e '\nEOF' >> $GITHUB_ENV
|
||||
- name: Hash Rendered Compose File
|
||||
id: hash
|
||||
# If the previous workflow was triggered by a PR close event, we will not have a compose file artifact.
|
||||
if: ${{ fromJSON(env.EVENT_JSON).action != 'closed' }}
|
||||
run: echo "COMPOSE_FILE_HASH=$(md5sum docker-compose.rendered.yml | awk '{ print $1 }')" >> $GITHUB_ENV
|
||||
|
||||
- name: Cache Rendered Compose File
|
||||
if: ${{ fromJSON(env.EVENT_JSON).action != 'closed' }}
|
||||
uses: actions/cache@v3
|
||||
@@ -70,7 +75,8 @@ jobs:
|
||||
name: Use Remote Workflow to Preview on Uffizzi
|
||||
needs:
|
||||
- cache-compose-file
|
||||
uses: UffizziCloud/preview-action/.github/workflows/reusable.yaml@v2.6.1
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
uses: UffizziCloud/preview-action/.github/workflows/reusable.yaml@v2
|
||||
with:
|
||||
# If this workflow was triggered by a PR close event, cache-key will be an empty string
|
||||
# and this reusable workflow will delete the preview deployment.
|
||||
@@ -81,4 +87,4 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
id-token: write
|
||||
id-token: write
|
||||
|
||||
+1
-8
@@ -35,14 +35,7 @@ lazygit.exe
|
||||
|
||||
test/git_server/data
|
||||
|
||||
# we'll scrap these lines once we've fully moved over to the new integration test approach
|
||||
test/integration/*/actual/
|
||||
test/integration/*/used_config/
|
||||
# these sample hooks waste too much space
|
||||
test/integration/*/expected/**/hooks/
|
||||
test/integration/*/expected_remote/**/hooks/
|
||||
|
||||
test/integration_new/**
|
||||
test/results/**
|
||||
|
||||
oryxBuildBinary
|
||||
__debug_bin
|
||||
|
||||
Vendored
+2
-2
@@ -7,7 +7,7 @@
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "main.go",
|
||||
"args": ["--debug", "--use-config-file=.vscode/debugger_config.yml"],
|
||||
"args": ["--debug", "--use-config-file=${workspaceFolder}/.vscode/debugger_config.yml"],
|
||||
"console": "integratedTerminal",
|
||||
"presentation": {
|
||||
"hidden": true
|
||||
@@ -19,7 +19,7 @@
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "main.go",
|
||||
"args": ["--logs", "--use-config-file=.vscode/debugger_config.yml"],
|
||||
"args": ["--logs", "--use-config-file=${workspaceFolder}/.vscode/debugger_config.yml"],
|
||||
"console": "integratedTerminal",
|
||||
"presentation": {
|
||||
"hidden": true
|
||||
|
||||
Vendored
+16
-4
@@ -24,7 +24,7 @@
|
||||
{
|
||||
"label": "Run current file integration test",
|
||||
"type": "shell",
|
||||
"command": "go run cmd/integration_test/main.go cli ${relativeFile}",
|
||||
"command": "go generate pkg/integration/tests/tests.go && go run cmd/integration_test/main.go cli ${relativeFile}",
|
||||
"problemMatcher": [],
|
||||
"group": {
|
||||
"kind": "test",
|
||||
@@ -37,7 +37,7 @@
|
||||
{
|
||||
"label": "Run current file integration test (slow)",
|
||||
"type": "shell",
|
||||
"command": "go run cmd/integration_test/main.go cli --slow ${relativeFile}",
|
||||
"command": "go generate pkg/integration/tests/tests.go && go run cmd/integration_test/main.go cli --slow ${relativeFile}",
|
||||
"problemMatcher": [],
|
||||
"group": {
|
||||
"kind": "test",
|
||||
@@ -49,7 +49,7 @@
|
||||
{
|
||||
"label": "Run current file integration test (sandbox)",
|
||||
"type": "shell",
|
||||
"command": "go run cmd/integration_test/main.go cli --sandbox ${relativeFile}",
|
||||
"command": "go generate pkg/integration/tests/tests.go && go run cmd/integration_test/main.go cli --sandbox ${relativeFile}",
|
||||
"problemMatcher": [],
|
||||
"group": {
|
||||
"kind": "test",
|
||||
@@ -69,6 +69,18 @@
|
||||
"presentation": {
|
||||
"focus": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Sync tests list",
|
||||
"type": "shell",
|
||||
"command": "go generate pkg/integration/tests/tests.go",
|
||||
"problemMatcher": [],
|
||||
"group": {
|
||||
"kind": "test",
|
||||
},
|
||||
"presentation": {
|
||||
"focus": true
|
||||
}
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -17,11 +17,6 @@ Usage:
|
||||
If you pass no test names, it runs all tests
|
||||
Accepted environment variables:
|
||||
KEY_PRESS_DELAY (e.g. 200): the number of milliseconds to wait between keypresses
|
||||
MODE:
|
||||
* ask (default): if a snapshot test fails, asks if you want to update the snapshot
|
||||
* check: if a snapshot test fails, exits with an error
|
||||
* update: if a snapshot test fails, updates the snapshot
|
||||
* sandbox: uses the test's setup step to run the test in a sandbox where you can do whatever you want
|
||||
|
||||
TUI mode:
|
||||
> go run cmd/integration_test/main.go tui
|
||||
|
||||
+32
-38
@@ -9,7 +9,7 @@ Default path for the config file:
|
||||
For old installations (slightly embarrassing: I didn't realise at the time that you didn't need to supply a vendor name to the path so I just used my name):
|
||||
|
||||
- Linux: `~/.config/jesseduffield/lazygit/config.yml`
|
||||
- MacOS: `~/Library/Application Support/jesseduffield/lazygit/config.yml`
|
||||
- MacOS: `~/Library/Application\ Support/jesseduffield/lazygit/config.yml`
|
||||
- Windows: `%APPDATA%\jesseduffield\lazygit\config.yml`
|
||||
|
||||
If you want to change the config directory:
|
||||
@@ -63,6 +63,7 @@ gui:
|
||||
commandLogSize: 8
|
||||
splitDiff: 'auto' # one of 'auto' | 'always'
|
||||
skipRewordInEditorWarning: false # for skipping the confirmation before launching the reword editor
|
||||
border: 'single' # one of 'single' | 'double' | 'rounded' | 'hidden'
|
||||
git:
|
||||
paging:
|
||||
colorArg: always
|
||||
@@ -95,9 +96,12 @@ git:
|
||||
parseEmoji: false
|
||||
diffContextSize: 3 # how many lines of context are shown around a change in diffs
|
||||
os:
|
||||
editCommand: '' # see 'Configuring File Editing' section
|
||||
editCommandTemplate: ''
|
||||
openCommand: ''
|
||||
editPreset: '' # see 'Configuring File Editing' section
|
||||
edit: ''
|
||||
editAtLine: ''
|
||||
editAtLineAndWait: ''
|
||||
open: ''
|
||||
openLink: ''
|
||||
refresher:
|
||||
refreshInterval: 10 # File/submodule refresh interval in seconds. Auto-refresh can be disabled via option 'git.autoRefresh'.
|
||||
fetchInterval: 60 # Re-fetch interval in seconds. Auto-fetch can be disabled via option 'git.autoFetch'.
|
||||
@@ -115,8 +119,6 @@ keybinding:
|
||||
quit: 'q'
|
||||
quit-alt1: '<c-c>' # alternative/alias of quit
|
||||
return: '<esc>' # return to previous menu, will quit if there's nowhere to return
|
||||
# When set to a printable character, this will work for returning from non-prompt panels
|
||||
return-alt1: null
|
||||
quitWithoutChangingDirectory: 'Q'
|
||||
togglePanel: '<tab>' # goto the next panel
|
||||
prevItem: '<up>' # go one line up
|
||||
@@ -136,13 +138,12 @@ keybinding:
|
||||
jumpToBlock: ['1', '2', '3', '4', '5'] # goto the Nth block / panel
|
||||
nextMatch: 'n'
|
||||
prevMatch: 'N'
|
||||
optionMenu: 'x' # show help menu
|
||||
optionMenu: null # show help menu
|
||||
optionMenu-alt1: '?' # show help menu
|
||||
select: '<space>'
|
||||
goInto: '<enter>'
|
||||
openRecentRepos: '<c-r>'
|
||||
confirm: '<enter>'
|
||||
confirm-alt1: 'y'
|
||||
remove: 'd'
|
||||
new: 'n'
|
||||
edit: 'e'
|
||||
@@ -203,6 +204,7 @@ keybinding:
|
||||
mergeIntoCurrentBranch: 'M'
|
||||
viewGitFlowOptions: 'i'
|
||||
fastForward: 'f' # fast-forward this branch from its upstream
|
||||
createTag: 'T'
|
||||
pushTag: 'P'
|
||||
setUpstream: 'u' # set as upstream of checked-out branch
|
||||
fetchRemote: 'f'
|
||||
@@ -269,40 +271,41 @@ os:
|
||||
|
||||
### Configuring File Editing
|
||||
|
||||
Lazygit will edit a file with the first set editor in the following:
|
||||
There are two commands for opening files, `o` for "open" and `e` for "edit". `o`
|
||||
acts as if the file was double-clicked in the Finder/Explorer, so it also works
|
||||
for non-text files, whereas `e` opens the file in an editor. `e` can also jump
|
||||
to the right line in the file if you invoke it from the staging panel, for
|
||||
example.
|
||||
|
||||
1. config.yaml
|
||||
To tell lazygit which editor to use for the `e` command, the easiest way to do
|
||||
that is to provide an editPreset config, e.g.
|
||||
|
||||
```yaml
|
||||
os:
|
||||
editCommand: 'vim' # as an example
|
||||
editPreset: 'vscode'
|
||||
```
|
||||
|
||||
2. \$(git config core.editor)
|
||||
3. \$GIT_EDITOR
|
||||
4. \$VISUAL
|
||||
5. \$EDITOR
|
||||
6. \$(which vi)
|
||||
Supported presets are `vim`, `emacs`, `nano`, `vscode`, `sublime`, `bbedit`, and
|
||||
`xcode`. In many cases lazygit will be able to guess the right preset from your
|
||||
$(git config core.editor), or an environment variable such as $VISUAL or $EDITOR.
|
||||
|
||||
Lazygit will log an error if none of these options are set.
|
||||
|
||||
You can specify the current line number when you're in the patch explorer.
|
||||
If for some reason you are not happy with the default commands from a preset, or
|
||||
there simply is no preset for your editor, you can customize the commands by
|
||||
setting the `edit`, `editAtLine`, and `editAtLineAndWait` options, e.g.:
|
||||
|
||||
```yaml
|
||||
os:
|
||||
editCommand: 'vim'
|
||||
editCommandTemplate: '{{editor}} +{{line}} -- {{filename}}'
|
||||
edit: 'myeditor {{filename}}'
|
||||
editAtLine: 'myeditor --line={{line}} {{filename}}'
|
||||
editAtLineAndWait: 'myeditor --block --line={{line}} {{filename}}'
|
||||
editInTerminal: true
|
||||
```
|
||||
|
||||
or
|
||||
The `editInTerminal` option is used to decide whether lazygit needs to suspend
|
||||
itself to the background before calling the editor.
|
||||
|
||||
```yaml
|
||||
os:
|
||||
editCommand: 'code'
|
||||
editCommandTemplate: '{{editor}} --goto -- {{filename}}:{{line}}'
|
||||
```
|
||||
|
||||
`{{editor}}` in `editCommandTemplate` is replaced with the value of `editCommand`.
|
||||
Contributions of new editor presets are welcome; see the `getPreset` function in
|
||||
[`editor_presets.go`](https://github.com/jesseduffield/lazygit/blob/master/pkg/config/editor_presets.go).
|
||||
|
||||
### Overriding default config file location
|
||||
|
||||
@@ -318,15 +321,6 @@ or
|
||||
LG_CONFIG_FILE="$HOME/.base_lg_conf,$HOME/.light_theme_lg_conf" lazygit
|
||||
```
|
||||
|
||||
### Recommended Config Values
|
||||
|
||||
for users of VSCode
|
||||
|
||||
```yaml
|
||||
os:
|
||||
openCommand: 'code -rg {{filename}}'
|
||||
```
|
||||
|
||||
## Color Attributes
|
||||
|
||||
For color attributes you can choose an array of attributes (with max one color attribute)
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: view merge/rebase options
|
||||
<kbd>ctrl+p</kbd>: view custom patch options
|
||||
<kbd>R</kbd>: refresh
|
||||
<kbd>x</kbd>: open menu
|
||||
<kbd>?</kbd>: open menu
|
||||
<kbd>+</kbd>: next screen mode (normal/half/fullscreen)
|
||||
<kbd>_</kbd>: prev screen mode
|
||||
<kbd>ctrl+s</kbd>: view filter-by-path options
|
||||
<kbd>W</kbd>: open diff menu
|
||||
<kbd>ctrl+e</kbd>: open diff menu
|
||||
<kbd>@</kbd>: open command log menu
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>}</kbd>: Increase the size of the context shown around changes in the diff view
|
||||
<kbd>{</kbd>: Decrease the size of the context shown around changes in the diff view
|
||||
<kbd>:</kbd>: execute custom command
|
||||
@@ -92,7 +93,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: copy the file name to the clipboard
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>d</kbd>: view 'discard changes' options
|
||||
<kbd>space</kbd>: toggle staged
|
||||
<kbd>ctrl+b</kbd>: Filter files (staged/unstaged)
|
||||
@@ -131,6 +131,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: rebase checked-out branch onto this branch
|
||||
<kbd>M</kbd>: merge into currently checked out branch
|
||||
<kbd>f</kbd>: fast-forward this branch from its upstream
|
||||
<kbd>T</kbd>: create tag
|
||||
<kbd>g</kbd>: view reset options
|
||||
<kbd>R</kbd>: rename branch
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -142,8 +143,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: edit file
|
||||
<kbd>o</kbd>: open file
|
||||
<kbd>◄</kbd>: select previous conflict
|
||||
<kbd>►</kbd>: select next conflict
|
||||
<kbd>◀</kbd>: select previous conflict
|
||||
<kbd>▶</kbd>: select next conflict
|
||||
<kbd>▲</kbd>: select previous hunk
|
||||
<kbd>▼</kbd>: select next hunk
|
||||
<kbd>z</kbd>: undo
|
||||
@@ -163,8 +164,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Main Panel (Patch Building)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: select previous hunk
|
||||
<kbd>►</kbd>: select next hunk
|
||||
<kbd>◀</kbd>: select previous hunk
|
||||
<kbd>▶</kbd>: select next hunk
|
||||
<kbd>v</kbd>: toggle drag select
|
||||
<kbd>V</kbd>: toggle drag select
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -178,8 +179,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Main Panel (Staging)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: select previous hunk
|
||||
<kbd>►</kbd>: select next hunk
|
||||
<kbd>◀</kbd>: select previous hunk
|
||||
<kbd>▶</kbd>: select next hunk
|
||||
<kbd>v</kbd>: toggle drag select
|
||||
<kbd>V</kbd>: toggle drag select
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -214,6 +215,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Remote Branches
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: copy branch name to clipboard
|
||||
<kbd>space</kbd>: checkout
|
||||
<kbd>n</kbd>: new branch
|
||||
<kbd>M</kbd>: merge into currently checked out branch
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: view merge/rebase options
|
||||
<kbd>ctrl+p</kbd>: view custom patch options
|
||||
<kbd>R</kbd>: リフレッシュ
|
||||
<kbd>x</kbd>: メニューを開く
|
||||
<kbd>?</kbd>: メニューを開く
|
||||
<kbd>+</kbd>: 次のスクリーンモード (normal/half/fullscreen)
|
||||
<kbd>_</kbd>: 前のスクリーンモード
|
||||
<kbd>ctrl+s</kbd>: view filter-by-path options
|
||||
<kbd>W</kbd>: 差分メニューを開く
|
||||
<kbd>ctrl+e</kbd>: 差分メニューを開く
|
||||
<kbd>@</kbd>: コマンドログメニューを開く
|
||||
<kbd>ctrl+w</kbd>: 空白文字の差分の表示有無を切り替え
|
||||
<kbd>}</kbd>: Increase the size of the context shown around changes in the diff view
|
||||
<kbd>{</kbd>: Decrease the size of the context shown around changes in the diff view
|
||||
<kbd>:</kbd>: カスタムコマンドを実行
|
||||
@@ -152,7 +153,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: ファイル名をクリップボードにコピー
|
||||
<kbd>ctrl+w</kbd>: 空白文字の差分の表示有無を切り替え
|
||||
<kbd>d</kbd>: view 'discard changes' options
|
||||
<kbd>space</kbd>: ステージ/アンステージ
|
||||
<kbd>ctrl+b</kbd>: ファイルをフィルタ (ステージ/アンステージ)
|
||||
@@ -191,6 +191,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: rebase checked-out branch onto this branch
|
||||
<kbd>M</kbd>: 現在のブランチにマージ
|
||||
<kbd>f</kbd>: fast-forward this branch from its upstream
|
||||
<kbd>T</kbd>: タグを作成
|
||||
<kbd>g</kbd>: view reset options
|
||||
<kbd>R</kbd>: ブランチ名を変更
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -202,8 +203,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: ファイルを編集
|
||||
<kbd>o</kbd>: ファイルを開く
|
||||
<kbd>◄</kbd>: 前のコンフリクトを選択
|
||||
<kbd>►</kbd>: 次のコンフリクトを選択
|
||||
<kbd>◀</kbd>: 前のコンフリクトを選択
|
||||
<kbd>▶</kbd>: 次のコンフリクトを選択
|
||||
<kbd>▲</kbd>: 前のhunkを選択
|
||||
<kbd>▼</kbd>: 次のhunkを選択
|
||||
<kbd>z</kbd>: アンドゥ
|
||||
@@ -223,8 +224,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## メインパネル (Patch Building)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 前のhunkを選択
|
||||
<kbd>►</kbd>: 次のhunkを選択
|
||||
<kbd>◀</kbd>: 前のhunkを選択
|
||||
<kbd>▶</kbd>: 次のhunkを選択
|
||||
<kbd>v</kbd>: 範囲選択を切り替え
|
||||
<kbd>V</kbd>: 範囲選択を切り替え
|
||||
<kbd>a</kbd>: hunk選択を切り替え
|
||||
@@ -238,8 +239,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## メインパネル (Staging)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 前のhunkを選択
|
||||
<kbd>►</kbd>: 次のhunkを選択
|
||||
<kbd>◀</kbd>: 前のhunkを選択
|
||||
<kbd>▶</kbd>: 次のhunkを選択
|
||||
<kbd>v</kbd>: 範囲選択を切り替え
|
||||
<kbd>V</kbd>: 範囲選択を切り替え
|
||||
<kbd>a</kbd>: hunk選択を切り替え
|
||||
@@ -268,6 +269,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## リモートブランチ
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: ブランチ名をクリップボードにコピー
|
||||
<kbd>space</kbd>: チェックアウト
|
||||
<kbd>n</kbd>: 新しいブランチを作成
|
||||
<kbd>M</kbd>: 現在のブランチにマージ
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: view merge/rebase options
|
||||
<kbd>ctrl+p</kbd>: 커스텀 Patch 옵션 보기
|
||||
<kbd>R</kbd>: 새로고침
|
||||
<kbd>x</kbd>: 매뉴 열기
|
||||
<kbd>?</kbd>: 매뉴 열기
|
||||
<kbd>+</kbd>: 다음 스크린 모드 (normal/half/fullscreen)
|
||||
<kbd>_</kbd>: 이전 스크린 모드
|
||||
<kbd>ctrl+s</kbd>: view filter-by-path options
|
||||
<kbd>W</kbd>: Diff 메뉴 열기
|
||||
<kbd>ctrl+e</kbd>: Diff 메뉴 열기
|
||||
<kbd>@</kbd>: 명령어 로그 메뉴 열기
|
||||
<kbd>ctrl+w</kbd>: 공백문자를 Diff 뷰에서 표시 여부 전환
|
||||
<kbd>}</kbd>: diff 보기의 변경 사항 주위에 표시되는 컨텍스트의 크기를 늘리기
|
||||
<kbd>{</kbd>: diff 보기의 변경 사항 주위에 표시되는 컨텍스트 크기 줄이기
|
||||
<kbd>:</kbd>: execute custom command
|
||||
@@ -87,8 +88,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: 파일 편집
|
||||
<kbd>o</kbd>: 파일 닫기
|
||||
<kbd>◄</kbd>: 이전 충돌을 선택
|
||||
<kbd>►</kbd>: 다음 충돌을 선택
|
||||
<kbd>◀</kbd>: 이전 충돌을 선택
|
||||
<kbd>▶</kbd>: 다음 충돌을 선택
|
||||
<kbd>▲</kbd>: 이전 hunk를 선택
|
||||
<kbd>▼</kbd>: 다음 hunk를 선택
|
||||
<kbd>z</kbd>: 되돌리기
|
||||
@@ -108,8 +109,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 메인 패널 (Patch Building)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 이전 hunk를 선택
|
||||
<kbd>►</kbd>: 다음 hunk를 선택
|
||||
<kbd>◀</kbd>: 이전 hunk를 선택
|
||||
<kbd>▶</kbd>: 다음 hunk를 선택
|
||||
<kbd>v</kbd>: 드래그 선택 전환
|
||||
<kbd>V</kbd>: 드래그 선택 전환
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -123,8 +124,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 메인 패널 (Staging)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 이전 hunk를 선택
|
||||
<kbd>►</kbd>: 다음 hunk를 선택
|
||||
<kbd>◀</kbd>: 이전 hunk를 선택
|
||||
<kbd>▶</kbd>: 다음 hunk를 선택
|
||||
<kbd>v</kbd>: 드래그 선택 전환
|
||||
<kbd>V</kbd>: 드래그 선택 전환
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -157,6 +158,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: 체크아웃된 브랜치를 이 브랜치에 리베이스
|
||||
<kbd>M</kbd>: 현재 브랜치에 병합
|
||||
<kbd>f</kbd>: fast-forward this branch from its upstream
|
||||
<kbd>T</kbd>: 태그를 생성
|
||||
<kbd>g</kbd>: view reset options
|
||||
<kbd>R</kbd>: 브랜치 이름 변경
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -198,6 +200,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 원격 브랜치
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: 브랜치명을 클립보드에 복사
|
||||
<kbd>space</kbd>: 체크아웃
|
||||
<kbd>n</kbd>: 새 브랜치 생성
|
||||
<kbd>M</kbd>: 현재 브랜치에 병합
|
||||
@@ -271,7 +274,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: 파일명을 클립보드에 복사
|
||||
<kbd>ctrl+w</kbd>: 공백문자를 Diff 뷰에서 표시 여부 전환
|
||||
<kbd>d</kbd>: view 'discard changes' options
|
||||
<kbd>space</kbd>: Staged 전환
|
||||
<kbd>ctrl+b</kbd>: 파일을 필터하기 (Staged/unstaged)
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: bekijk merge/rebase opties
|
||||
<kbd>ctrl+p</kbd>: bekijk aangepaste patch opties
|
||||
<kbd>R</kbd>: verversen
|
||||
<kbd>x</kbd>: open menu
|
||||
<kbd>?</kbd>: open menu
|
||||
<kbd>+</kbd>: volgende scherm modus (normaal/half/groot)
|
||||
<kbd>_</kbd>: vorige scherm modus
|
||||
<kbd>ctrl+s</kbd>: bekijk scoping opties
|
||||
<kbd>W</kbd>: open diff menu
|
||||
<kbd>ctrl+e</kbd>: open diff menu
|
||||
<kbd>@</kbd>: open command log menu
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>}</kbd>: Increase the size of the context shown around changes in the diff view
|
||||
<kbd>{</kbd>: Decrease the size of the context shown around changes in the diff view
|
||||
<kbd>:</kbd>: voer aangepaste commando uit
|
||||
@@ -45,7 +46,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: kopieer de bestandsnaam naar het klembord
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>d</kbd>: bekijk 'veranderingen ongedaan maken' opties
|
||||
<kbd>space</kbd>: toggle staged
|
||||
<kbd>ctrl+b</kbd>: Filter files (staged/unstaged)
|
||||
@@ -84,6 +84,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: rebase branch
|
||||
<kbd>M</kbd>: merge in met huidige checked out branch
|
||||
<kbd>f</kbd>: fast-forward deze branch vanaf zijn upstream
|
||||
<kbd>T</kbd>: creëer tag
|
||||
<kbd>g</kbd>: bekijk reset opties
|
||||
<kbd>R</kbd>: hernoem branch
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -142,8 +143,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: verander bestand
|
||||
<kbd>o</kbd>: open bestand
|
||||
<kbd>◄</kbd>: selecteer voorgaand conflict
|
||||
<kbd>►</kbd>: selecteer volgende conflict
|
||||
<kbd>◀</kbd>: selecteer voorgaand conflict
|
||||
<kbd>▶</kbd>: selecteer volgende conflict
|
||||
<kbd>▲</kbd>: selecteer bovenste hunk
|
||||
<kbd>▼</kbd>: selecteer onderste hunk
|
||||
<kbd>z</kbd>: ongedaan maken
|
||||
@@ -163,8 +164,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Patch Bouwen
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: selecteer de vorige hunk
|
||||
<kbd>►</kbd>: selecteer de volgende hunk
|
||||
<kbd>◀</kbd>: selecteer de vorige hunk
|
||||
<kbd>▶</kbd>: selecteer de volgende hunk
|
||||
<kbd>v</kbd>: toggle drag selecteer
|
||||
<kbd>V</kbd>: toggle drag selecteer
|
||||
<kbd>a</kbd>: toggle selecteer hunk
|
||||
@@ -193,6 +194,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Remote Branches
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: kopieer branch name naar klembord
|
||||
<kbd>space</kbd>: uitchecken
|
||||
<kbd>n</kbd>: nieuwe branch
|
||||
<kbd>M</kbd>: merge in met huidige checked out branch
|
||||
@@ -216,8 +218,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Staging
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: selecteer de vorige hunk
|
||||
<kbd>►</kbd>: selecteer de volgende hunk
|
||||
<kbd>◀</kbd>: selecteer de vorige hunk
|
||||
<kbd>▶</kbd>: selecteer de volgende hunk
|
||||
<kbd>v</kbd>: toggle drag selecteer
|
||||
<kbd>V</kbd>: toggle drag selecteer
|
||||
<kbd>a</kbd>: toggle selecteer hunk
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: widok scalenia/opcje zmiany bazy
|
||||
<kbd>ctrl+p</kbd>: view custom patch options
|
||||
<kbd>R</kbd>: odśwież
|
||||
<kbd>x</kbd>: open menu
|
||||
<kbd>?</kbd>: open menu
|
||||
<kbd>+</kbd>: next screen mode (normal/half/fullscreen)
|
||||
<kbd>_</kbd>: prev screen mode
|
||||
<kbd>ctrl+s</kbd>: view filter-by-path options
|
||||
<kbd>W</kbd>: open diff menu
|
||||
<kbd>ctrl+e</kbd>: open diff menu
|
||||
<kbd>@</kbd>: open command log menu
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>}</kbd>: Increase the size of the context shown around changes in the diff view
|
||||
<kbd>{</kbd>: Decrease the size of the context shown around changes in the diff view
|
||||
<kbd>:</kbd>: wykonaj własną komendę
|
||||
@@ -90,6 +91,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: zmiana bazy gałęzi
|
||||
<kbd>M</kbd>: scal do obecnej gałęzi
|
||||
<kbd>f</kbd>: fast-forward this branch from its upstream
|
||||
<kbd>T</kbd>: create tag
|
||||
<kbd>g</kbd>: wyświetl opcje resetu
|
||||
<kbd>R</kbd>: rename branch
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -99,8 +101,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Main Panel (Patch Building)
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: poprzedni kawałek
|
||||
<kbd>►</kbd>: następny kawałek
|
||||
<kbd>◀</kbd>: poprzedni kawałek
|
||||
<kbd>▶</kbd>: następny kawałek
|
||||
<kbd>v</kbd>: toggle drag select
|
||||
<kbd>V</kbd>: toggle drag select
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -115,7 +117,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: copy the file name to the clipboard
|
||||
<kbd>ctrl+w</kbd>: Toggle whether or not whitespace changes are shown in the diff view
|
||||
<kbd>d</kbd>: pokaż opcje porzucania zmian
|
||||
<kbd>space</kbd>: przełącz stan poczekalni
|
||||
<kbd>ctrl+b</kbd>: Filter files (staged/unstaged)
|
||||
@@ -155,8 +156,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Poczekalnia
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: poprzedni kawałek
|
||||
<kbd>►</kbd>: następny kawałek
|
||||
<kbd>◀</kbd>: poprzedni kawałek
|
||||
<kbd>▶</kbd>: następny kawałek
|
||||
<kbd>v</kbd>: toggle drag select
|
||||
<kbd>V</kbd>: toggle drag select
|
||||
<kbd>a</kbd>: toggle select hunk
|
||||
@@ -191,6 +192,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## Remote Branches
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: copy branch name to clipboard
|
||||
<kbd>space</kbd>: przełącz
|
||||
<kbd>n</kbd>: nowa gałąź
|
||||
<kbd>M</kbd>: scal do obecnej gałęzi
|
||||
@@ -216,8 +218,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: edytuj plik
|
||||
<kbd>o</kbd>: otwórz plik
|
||||
<kbd>◄</kbd>: poprzedni konflikt
|
||||
<kbd>►</kbd>: następny konflikt
|
||||
<kbd>◀</kbd>: poprzedni konflikt
|
||||
<kbd>▶</kbd>: następny konflikt
|
||||
<kbd>▲</kbd>: wybierz poprzedni kawałek
|
||||
<kbd>▼</kbd>: wybierz następny kawałek
|
||||
<kbd>z</kbd>: cofnij
|
||||
|
||||
@@ -11,13 +11,14 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>m</kbd>: 查看 合并/变基 选项
|
||||
<kbd>ctrl+p</kbd>: 查看自定义补丁选项
|
||||
<kbd>R</kbd>: 刷新
|
||||
<kbd>x</kbd>: 打开菜单
|
||||
<kbd>?</kbd>: 打开菜单
|
||||
<kbd>+</kbd>: 下一屏模式(正常/半屏/全屏)
|
||||
<kbd>_</kbd>: 上一屏模式
|
||||
<kbd>ctrl+s</kbd>: 查看按路径过滤选项
|
||||
<kbd>W</kbd>: 打开 diff 菜单
|
||||
<kbd>ctrl+e</kbd>: 打开 diff 菜单
|
||||
<kbd>@</kbd>: 打开命令日志菜单
|
||||
<kbd>ctrl+w</kbd>: 切换是否在差异视图中显示空白字符差异
|
||||
<kbd>}</kbd>: 扩大差异视图中显示的上下文范围
|
||||
<kbd>{</kbd>: 缩小差异视图中显示的上下文范围
|
||||
<kbd>:</kbd>: 执行自定义命令
|
||||
@@ -72,6 +73,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<kbd>r</kbd>: 将已检出的分支变基到该分支
|
||||
<kbd>M</kbd>: 合并到当前检出的分支
|
||||
<kbd>f</kbd>: 从上游快进此分支
|
||||
<kbd>T</kbd>: 创建标签
|
||||
<kbd>g</kbd>: 查看重置选项
|
||||
<kbd>R</kbd>: 重命名分支
|
||||
<kbd>u</kbd>: set/unset upstream
|
||||
@@ -157,7 +159,6 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: 将文件名复制到剪贴板
|
||||
<kbd>ctrl+w</kbd>: 切换是否在差异视图中显示空白字符差异
|
||||
<kbd>d</kbd>: 查看'放弃更改'选项
|
||||
<kbd>space</kbd>: 切换暂存状态
|
||||
<kbd>ctrl+b</kbd>: Filter files (staged/unstaged)
|
||||
@@ -183,8 +184,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 构建补丁中
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 选择上一个区块
|
||||
<kbd>►</kbd>: 选择下一个区块
|
||||
<kbd>◀</kbd>: 选择上一个区块
|
||||
<kbd>▶</kbd>: 选择下一个区块
|
||||
<kbd>v</kbd>: 切换拖动选择
|
||||
<kbd>V</kbd>: 切换拖动选择
|
||||
<kbd>a</kbd>: 切换选择区块
|
||||
@@ -211,8 +212,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
<pre>
|
||||
<kbd>e</kbd>: 编辑文件
|
||||
<kbd>o</kbd>: 打开文件
|
||||
<kbd>◄</kbd>: 选择上一个冲突
|
||||
<kbd>►</kbd>: 选择下一个冲突
|
||||
<kbd>◀</kbd>: 选择上一个冲突
|
||||
<kbd>▶</kbd>: 选择下一个冲突
|
||||
<kbd>▲</kbd>: 选择顶部块
|
||||
<kbd>▼</kbd>: 选择底部块
|
||||
<kbd>z</kbd>: 撤销
|
||||
@@ -225,8 +226,8 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 正在暂存
|
||||
|
||||
<pre>
|
||||
<kbd>◄</kbd>: 选择上一个区块
|
||||
<kbd>►</kbd>: 选择下一个区块
|
||||
<kbd>◀</kbd>: 选择上一个区块
|
||||
<kbd>▶</kbd>: 选择下一个区块
|
||||
<kbd>v</kbd>: 切换拖动选择
|
||||
<kbd>V</kbd>: 切换拖动选择
|
||||
<kbd>a</kbd>: 切换选择区块
|
||||
@@ -274,6 +275,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct
|
||||
## 远程分支
|
||||
|
||||
<pre>
|
||||
<kbd>ctrl+o</kbd>: 将分支名称复制到剪贴板
|
||||
<kbd>space</kbd>: 检出
|
||||
<kbd>n</kbd>: 新分支
|
||||
<kbd>M</kbd>: 合并到当前检出的分支
|
||||
|
||||
@@ -11,14 +11,14 @@ require (
|
||||
github.com/creack/pty v1.1.11
|
||||
github.com/fsmiamoto/git-todo-parser v0.0.2
|
||||
github.com/fsnotify/fsnotify v1.4.7
|
||||
github.com/gdamore/tcell/v2 v2.5.4
|
||||
github.com/gdamore/tcell/v2 v2.6.0
|
||||
github.com/go-errors/errors v1.4.2
|
||||
github.com/gookit/color v1.4.2
|
||||
github.com/imdario/mergo v0.3.11
|
||||
github.com/integrii/flaggy v1.4.0
|
||||
github.com/jesseduffield/generics v0.0.0-20220320043834-727e535cbe68
|
||||
github.com/jesseduffield/go-git/v5 v5.1.2-0.20221018185014-fdd53fef665d
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230105224502-214a0df08da7
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230324073941-36f2e87458fa
|
||||
github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10
|
||||
github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5
|
||||
github.com/jesseduffield/minimal/gitignore v0.3.3-0.20211018110810-9cde264e6b1e
|
||||
@@ -62,14 +62,14 @@ require (
|
||||
github.com/onsi/ginkgo v1.10.3 // indirect
|
||||
github.com/onsi/gomega v1.7.1 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
|
||||
github.com/rivo/uniseg v0.4.3 // indirect
|
||||
github.com/rivo/uniseg v0.4.4 // indirect
|
||||
github.com/sergi/go-diff v1.1.0 // indirect
|
||||
github.com/xanzy/ssh-agent v0.2.1 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
|
||||
golang.org/x/exp v0.0.0-20220318154914-8dddf5d87bd8 // indirect
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect
|
||||
golang.org/x/sys v0.3.0 // indirect
|
||||
golang.org/x/term v0.3.0 // indirect
|
||||
golang.org/x/text v0.5.0 // indirect
|
||||
golang.org/x/sys v0.6.0 // indirect
|
||||
golang.org/x/term v0.6.0 // indirect
|
||||
golang.org/x/text v0.8.0 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
)
|
||||
|
||||
@@ -35,8 +35,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
|
||||
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
|
||||
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
|
||||
github.com/gdamore/tcell/v2 v2.4.0/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU=
|
||||
github.com/gdamore/tcell/v2 v2.5.4 h1:TGU4tSjD3sCL788vFNeJnTdzpNKIw1H5dgLnJRQVv/k=
|
||||
github.com/gdamore/tcell/v2 v2.5.4/go.mod h1:dZgRy5v4iMobMEcWNYBtREnDZAT9DYmfqIkrgEMxLyw=
|
||||
github.com/gdamore/tcell/v2 v2.6.0 h1:OKbluoP9VYmJwZwq/iLb4BxwKcwGthaa1YNBJIyCySg=
|
||||
github.com/gdamore/tcell/v2 v2.6.0/go.mod h1:be9omFATkdr0D9qewWW3d+MEvl5dha+Etb5y65J2H8Y=
|
||||
github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0=
|
||||
github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
|
||||
github.com/go-errors/errors v1.0.2/go.mod h1:psDX2osz5VnTOnFWbDeWwS7yejl+uV3FEWEp4lssFEs=
|
||||
@@ -72,8 +72,8 @@ github.com/jesseduffield/generics v0.0.0-20220320043834-727e535cbe68 h1:EQP2Tv8T
|
||||
github.com/jesseduffield/generics v0.0.0-20220320043834-727e535cbe68/go.mod h1:+LLj9/WUPAP8LqCchs7P+7X0R98HiFujVFANdNaxhGk=
|
||||
github.com/jesseduffield/go-git/v5 v5.1.2-0.20221018185014-fdd53fef665d h1:bO+OmbreIv91rCe8NmscRwhFSqkDJtzWCPV4Y+SQuXE=
|
||||
github.com/jesseduffield/go-git/v5 v5.1.2-0.20221018185014-fdd53fef665d/go.mod h1:nGNEErzf+NRznT+N2SWqmHnDnF9aLgANB1CUNEan09o=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230105224502-214a0df08da7 h1:a7T87NGCrmFhzWBWvaaPQppjbY9/w0Vl4hoB7RnFaug=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230105224502-214a0df08da7/go.mod h1:znJuCDnF2Ph40YZSlBwdX/4GEofnIoWLGdT4mK5zRAU=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230324073941-36f2e87458fa h1:E9G1mj94rMal1YLaABwdxLUUgKq+xGbElFjHRNaDJUg=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20230324073941-36f2e87458fa/go.mod h1:znJuCDnF2Ph40YZSlBwdX/4GEofnIoWLGdT4mK5zRAU=
|
||||
github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10 h1:jmpr7KpX2+2GRiE91zTgfq49QvgiqB0nbmlwZ8UnOx0=
|
||||
github.com/jesseduffield/kill v0.0.0-20220618033138-bfbe04675d10/go.mod h1:aA97kHeNA+sj2Hbki0pvLslmE4CbDyhBeSSTUUnOuVo=
|
||||
github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5 h1:CDuQmfOjAtb1Gms6a1p5L2P8RhbLUq5t8aL7PiQd2uY=
|
||||
@@ -136,8 +136,9 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
|
||||
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
|
||||
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
|
||||
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
|
||||
github.com/samber/lo v1.31.0 h1:Sfa+/064Tdo4SvlohQUQzBhgSer9v/coGvKQI/XLWAM=
|
||||
@@ -205,19 +206,22 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.3.0 h1:qoo4akIqOcDME5bhc/NgxUdovd6BSS2uMsVjB56q1xI=
|
||||
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
|
||||
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
|
||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
|
||||
+1
-1
@@ -123,7 +123,7 @@ func (app *App) validateGitVersion() (*git_commands.GitVersion, error) {
|
||||
return nil, minVersionError
|
||||
}
|
||||
|
||||
if version.IsOlderThan(2, 0, 0) {
|
||||
if version.IsOlderThan(2, 20, 0) {
|
||||
return nil, minVersionError
|
||||
}
|
||||
|
||||
|
||||
+9
-4
@@ -117,9 +117,14 @@ func NewGitCommandAux(
|
||||
workingTreeCommands := git_commands.NewWorkingTreeCommands(gitCommon, submoduleCommands, fileLoader)
|
||||
rebaseCommands := git_commands.NewRebaseCommands(gitCommon, commitCommands, workingTreeCommands)
|
||||
stashCommands := git_commands.NewStashCommands(gitCommon, fileLoader, workingTreeCommands)
|
||||
// TODO: have patch manager take workingTreeCommands in its entirety
|
||||
patchManager := patch.NewPatchManager(cmn.Log, workingTreeCommands.ApplyPatch, workingTreeCommands.ShowFileDiff)
|
||||
patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchManager)
|
||||
// TODO: have patch builder take workingTreeCommands in its entirety
|
||||
patchBuilder := patch.NewPatchBuilder(cmn.Log, workingTreeCommands.ApplyPatch,
|
||||
func(from string, to string, reverse bool, filename string, plain bool) (string, error) {
|
||||
// TODO: make patch builder take Gui.IgnoreWhitespaceInDiffView into
|
||||
// account. For now we just pass false.
|
||||
return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, plain, false)
|
||||
})
|
||||
patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchBuilder)
|
||||
bisectCommands := git_commands.NewBisectCommands(gitCommon)
|
||||
|
||||
branchLoader := git_commands.NewBranchLoader(cmn, branchCommands.GetRawBranches, branchCommands.CurrentBranchInfo, configCommands)
|
||||
@@ -128,7 +133,7 @@ func NewGitCommandAux(
|
||||
reflogCommitLoader := git_commands.NewReflogCommitLoader(cmn, cmd)
|
||||
remoteLoader := git_commands.NewRemoteLoader(cmn, cmd, repo.Remotes)
|
||||
stashLoader := git_commands.NewStashLoader(cmn, cmd)
|
||||
tagLoader := git_commands.NewTagLoader(cmn, version, cmd)
|
||||
tagLoader := git_commands.NewTagLoader(cmn, cmd)
|
||||
|
||||
return &GitCommand{
|
||||
Branch: branchCommands,
|
||||
|
||||
@@ -149,14 +149,19 @@ func (self *CommitCommands) AmendHeadCmdObj() oscommands.ICmdObj {
|
||||
return self.cmd.New("git commit --amend --no-edit --allow-empty")
|
||||
}
|
||||
|
||||
func (self *CommitCommands) ShowCmdObj(sha string, filterPath string) oscommands.ICmdObj {
|
||||
func (self *CommitCommands) ShowCmdObj(sha string, filterPath string, ignoreWhitespace bool) oscommands.ICmdObj {
|
||||
contextSize := self.UserConfig.Git.DiffContextSize
|
||||
filterPathArg := ""
|
||||
if filterPath != "" {
|
||||
filterPathArg = fmt.Sprintf(" -- %s", self.cmd.Quote(filterPath))
|
||||
}
|
||||
ignoreWhitespaceArg := ""
|
||||
if ignoreWhitespace {
|
||||
ignoreWhitespaceArg = " --ignore-all-space"
|
||||
}
|
||||
|
||||
cmdStr := fmt.Sprintf("git show --submodule --color=%s --unified=%d --no-renames --stat -p %s %s", self.UserConfig.Git.Paging.ColorArg, contextSize, sha, filterPathArg)
|
||||
cmdStr := fmt.Sprintf("git show --submodule --color=%s --unified=%d --stat -p %s%s%s",
|
||||
self.UserConfig.Git.Paging.ColorArg, contextSize, sha, ignoreWhitespaceArg, filterPathArg)
|
||||
return self.cmd.New(cmdStr).DontLog()
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/types/enums"
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/style"
|
||||
)
|
||||
|
||||
// context:
|
||||
@@ -68,10 +67,6 @@ type GetCommitsOptions struct {
|
||||
func (self *CommitLoader) GetCommits(opts GetCommitsOptions) ([]*models.Commit, error) {
|
||||
commits := []*models.Commit{}
|
||||
var rebasingCommits []*models.Commit
|
||||
rebaseMode, err := self.getRebaseMode()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts.IncludeRebaseCommits && opts.FilterPath == "" {
|
||||
var err error
|
||||
@@ -106,12 +101,6 @@ func (self *CommitLoader) GetCommits(opts GetCommitsOptions) ([]*models.Commit,
|
||||
return commits, nil
|
||||
}
|
||||
|
||||
if rebaseMode != enums.REBASE_MODE_NONE {
|
||||
currentCommit := commits[len(rebasingCommits)]
|
||||
youAreHere := style.FgYellow.Sprintf("<-- %s ---", self.Tr.YouAreHere)
|
||||
currentCommit.Name = fmt.Sprintf("%s %s", youAreHere, currentCommit.Name)
|
||||
}
|
||||
|
||||
commits, err = self.setCommitMergedStatuses(opts.RefName, commits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -124,7 +113,7 @@ func (self *CommitLoader) MergeRebasingCommits(commits []*models.Commit) ([]*mod
|
||||
// chances are we have as many commits as last time so we'll set the capacity to be the old length
|
||||
result := make([]*models.Commit, 0, len(commits))
|
||||
for i, commit := range commits {
|
||||
if commit.Status != "rebasing" { // removing the existing rebase commits so we can add the refreshed ones
|
||||
if !commit.IsTODO() { // removing the existing rebase commits so we can add the refreshed ones
|
||||
result = append(result, commits[i:]...)
|
||||
break
|
||||
}
|
||||
@@ -401,7 +390,9 @@ func ignoringWarnings(commandOutput string) string {
|
||||
func (self *CommitLoader) getFirstPushedCommit(refName string) (string, error) {
|
||||
output, err := self.cmd.
|
||||
New(
|
||||
fmt.Sprintf("git merge-base %s %s@{u}", self.cmd.Quote(refName), self.cmd.Quote(refName)),
|
||||
fmt.Sprintf("git merge-base %s %s@{u}",
|
||||
self.cmd.Quote(refName),
|
||||
self.cmd.Quote(strings.TrimPrefix(refName, "refs/heads/"))),
|
||||
).
|
||||
DontLog().
|
||||
RunWithOutput()
|
||||
@@ -419,9 +410,11 @@ func (self *CommitLoader) getLogCmd(opts GetCommitsOptions) oscommands.ICmdObj {
|
||||
limitFlag = " -300"
|
||||
}
|
||||
|
||||
followFlag := ""
|
||||
filterFlag := ""
|
||||
if opts.FilterPath != "" {
|
||||
filterFlag = fmt.Sprintf(" --follow -- %s", self.cmd.Quote(opts.FilterPath))
|
||||
followFlag = " --follow"
|
||||
filterFlag = fmt.Sprintf(" %s", self.cmd.Quote(opts.FilterPath))
|
||||
}
|
||||
|
||||
config := self.UserConfig.Git.Log
|
||||
@@ -437,13 +430,14 @@ func (self *CommitLoader) getLogCmd(opts GetCommitsOptions) oscommands.ICmdObj {
|
||||
|
||||
return self.cmd.New(
|
||||
fmt.Sprintf(
|
||||
"git -c log.showSignature=false log %s%s%s --oneline %s%s --abbrev=%d%s",
|
||||
"git log %s%s%s --oneline %s%s --abbrev=%d%s --no-show-signature --%s",
|
||||
self.cmd.Quote(opts.RefName),
|
||||
orderFlag,
|
||||
allFlag,
|
||||
prettyFormat,
|
||||
limitFlag,
|
||||
40,
|
||||
followFlag,
|
||||
filterFlag,
|
||||
),
|
||||
).DontLog()
|
||||
|
||||
@@ -42,7 +42,20 @@ func TestGetCommits(t *testing.T) {
|
||||
opts: GetCommitsOptions{RefName: "HEAD", IncludeRebaseCommits: false},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git merge-base "HEAD" "HEAD"@{u}`, "b21997d6b4cbdf84b149d8e6a2c4d06a8e9ec164", nil).
|
||||
Expect(`git -c log.showSignature=false log "HEAD" --topo-order --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40`, "", nil),
|
||||
Expect(`git log "HEAD" --topo-order --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40 --no-show-signature --`, "", nil),
|
||||
|
||||
expectedCommits: []*models.Commit{},
|
||||
expectedError: nil,
|
||||
},
|
||||
{
|
||||
testName: "should use proper upstream name for branch",
|
||||
logOrder: "topo-order",
|
||||
rebaseMode: enums.REBASE_MODE_NONE,
|
||||
currentBranchName: "mybranch",
|
||||
opts: GetCommitsOptions{RefName: "refs/heads/mybranch", IncludeRebaseCommits: false},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git merge-base "refs/heads/mybranch" "mybranch"@{u}`, "b21997d6b4cbdf84b149d8e6a2c4d06a8e9ec164", nil).
|
||||
Expect(`git log "refs/heads/mybranch" --topo-order --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40 --no-show-signature --`, "", nil),
|
||||
|
||||
expectedCommits: []*models.Commit{},
|
||||
expectedError: nil,
|
||||
@@ -57,7 +70,7 @@ func TestGetCommits(t *testing.T) {
|
||||
// here it's seeing which commits are yet to be pushed
|
||||
Expect(`git merge-base "HEAD" "HEAD"@{u}`, "b21997d6b4cbdf84b149d8e6a2c4d06a8e9ec164", nil).
|
||||
// here it's actually getting all the commits in a formatted form, one per line
|
||||
Expect(`git -c log.showSignature=false log "HEAD" --topo-order --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40`, commitsOutput, nil).
|
||||
Expect(`git log "HEAD" --topo-order --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40 --no-show-signature --`, commitsOutput, nil).
|
||||
// here it's seeing where our branch diverged from the master branch so that we can mark that commit and parent commits as 'merged'
|
||||
Expect(`git merge-base "HEAD" "master"`, "26c07b1ab33860a1a7591a0638f9925ccf497ffa", nil),
|
||||
|
||||
@@ -185,7 +198,20 @@ func TestGetCommits(t *testing.T) {
|
||||
opts: GetCommitsOptions{RefName: "HEAD", IncludeRebaseCommits: false},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git merge-base "HEAD" "HEAD"@{u}`, "b21997d6b4cbdf84b149d8e6a2c4d06a8e9ec164", nil).
|
||||
Expect(`git -c log.showSignature=false log "HEAD" --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40`, "", nil),
|
||||
Expect(`git log "HEAD" --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40 --no-show-signature --`, "", nil),
|
||||
|
||||
expectedCommits: []*models.Commit{},
|
||||
expectedError: nil,
|
||||
},
|
||||
{
|
||||
testName: "should set filter path",
|
||||
logOrder: "default",
|
||||
rebaseMode: enums.REBASE_MODE_NONE,
|
||||
currentBranchName: "master",
|
||||
opts: GetCommitsOptions{RefName: "HEAD", FilterPath: "src"},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git merge-base "HEAD" "HEAD"@{u}`, "b21997d6b4cbdf84b149d8e6a2c4d06a8e9ec164", nil).
|
||||
Expect(`git log "HEAD" --oneline --pretty=format:"%H%x00%at%x00%aN%x00%ae%x00%d%x00%p%x00%s" --abbrev=40 --follow --no-show-signature -- "src"`, "", nil),
|
||||
|
||||
expectedCommits: []*models.Commit{},
|
||||
expectedError: nil,
|
||||
|
||||
@@ -177,30 +177,41 @@ func TestCommitCreateFixupCommit(t *testing.T) {
|
||||
|
||||
func TestCommitShowCmdObj(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
filterPath string
|
||||
contextSize int
|
||||
expected string
|
||||
testName string
|
||||
filterPath string
|
||||
contextSize int
|
||||
ignoreWhitespace bool
|
||||
expected string
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "Default case without filter path",
|
||||
filterPath: "",
|
||||
contextSize: 3,
|
||||
expected: "git show --submodule --color=always --unified=3 --no-renames --stat -p 1234567890 ",
|
||||
testName: "Default case without filter path",
|
||||
filterPath: "",
|
||||
contextSize: 3,
|
||||
ignoreWhitespace: false,
|
||||
expected: "git show --submodule --color=always --unified=3 --stat -p 1234567890",
|
||||
},
|
||||
{
|
||||
testName: "Default case with filter path",
|
||||
filterPath: "file.txt",
|
||||
contextSize: 3,
|
||||
expected: `git show --submodule --color=always --unified=3 --no-renames --stat -p 1234567890 -- "file.txt"`,
|
||||
testName: "Default case with filter path",
|
||||
filterPath: "file.txt",
|
||||
contextSize: 3,
|
||||
ignoreWhitespace: false,
|
||||
expected: `git show --submodule --color=always --unified=3 --stat -p 1234567890 -- "file.txt"`,
|
||||
},
|
||||
{
|
||||
testName: "Show diff with custom context size",
|
||||
filterPath: "",
|
||||
contextSize: 77,
|
||||
expected: "git show --submodule --color=always --unified=77 --no-renames --stat -p 1234567890 ",
|
||||
testName: "Show diff with custom context size",
|
||||
filterPath: "",
|
||||
contextSize: 77,
|
||||
ignoreWhitespace: false,
|
||||
expected: "git show --submodule --color=always --unified=77 --stat -p 1234567890",
|
||||
},
|
||||
{
|
||||
testName: "Show diff, ignoring whitespace",
|
||||
filterPath: "",
|
||||
contextSize: 77,
|
||||
ignoreWhitespace: true,
|
||||
expected: "git show --submodule --color=always --unified=77 --stat -p 1234567890 --ignore-all-space",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -212,7 +223,7 @@ func TestCommitShowCmdObj(t *testing.T) {
|
||||
|
||||
instance := buildCommitCommands(commonDeps{userConfig: userConfig})
|
||||
|
||||
cmdStr := instance.ShowCmdObj("1234567890", s.filterPath).ToString()
|
||||
cmdStr := instance.ShowCmdObj("1234567890", s.filterPath, s.ignoreWhitespace).ToString()
|
||||
assert.Equal(t, s.expected, cmdStr)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ package git_commands
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
|
||||
@@ -27,7 +29,7 @@ func (self *FileCommands) Cat(fileName string) (string, error) {
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
func (self *FileCommands) GetEditor() (string, error) {
|
||||
func (self *FileCommands) GetEditCmdStrLegacy(filename string, lineNumber int) (string, error) {
|
||||
editor := self.UserConfig.OS.EditCommand
|
||||
|
||||
if editor == "" {
|
||||
@@ -50,14 +52,6 @@ func (self *FileCommands) GetEditor() (string, error) {
|
||||
if editor == "" {
|
||||
return "", errors.New("No editor defined in config file, $GIT_EDITOR, $VISUAL, $EDITOR, or git config")
|
||||
}
|
||||
return editor, nil
|
||||
}
|
||||
|
||||
func (self *FileCommands) GetEditCmdStr(filename string, lineNumber int) (string, error) {
|
||||
editor, err := self.GetEditor()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
templateValues := map[string]string{
|
||||
"editor": editor,
|
||||
@@ -80,3 +74,82 @@ func (self *FileCommands) GetEditCmdStr(filename string, lineNumber int) (string
|
||||
}
|
||||
return utils.ResolvePlaceholderString(editCmdTemplate, templateValues), nil
|
||||
}
|
||||
|
||||
func (self *FileCommands) GetEditCmdStr(filename string) (string, bool) {
|
||||
// Legacy support for old config; to be removed at some point
|
||||
if self.UserConfig.OS.Edit == "" && self.UserConfig.OS.EditCommandTemplate != "" {
|
||||
if cmdStr, err := self.GetEditCmdStrLegacy(filename, 1); err == nil {
|
||||
return cmdStr, true
|
||||
}
|
||||
}
|
||||
|
||||
template, editInTerminal := config.GetEditTemplate(&self.UserConfig.OS, self.guessDefaultEditor)
|
||||
|
||||
templateValues := map[string]string{
|
||||
"filename": self.cmd.Quote(filename),
|
||||
}
|
||||
|
||||
cmdStr := utils.ResolvePlaceholderString(template, templateValues)
|
||||
return cmdStr, editInTerminal
|
||||
}
|
||||
|
||||
func (self *FileCommands) GetEditAtLineCmdStr(filename string, lineNumber int) (string, bool) {
|
||||
// Legacy support for old config; to be removed at some point
|
||||
if self.UserConfig.OS.EditAtLine == "" && self.UserConfig.OS.EditCommandTemplate != "" {
|
||||
if cmdStr, err := self.GetEditCmdStrLegacy(filename, lineNumber); err == nil {
|
||||
return cmdStr, true
|
||||
}
|
||||
}
|
||||
|
||||
template, editInTerminal := config.GetEditAtLineTemplate(&self.UserConfig.OS, self.guessDefaultEditor)
|
||||
|
||||
templateValues := map[string]string{
|
||||
"filename": self.cmd.Quote(filename),
|
||||
"line": strconv.Itoa(lineNumber),
|
||||
}
|
||||
|
||||
cmdStr := utils.ResolvePlaceholderString(template, templateValues)
|
||||
return cmdStr, editInTerminal
|
||||
}
|
||||
|
||||
func (self *FileCommands) GetEditAtLineAndWaitCmdStr(filename string, lineNumber int) string {
|
||||
// Legacy support for old config; to be removed at some point
|
||||
if self.UserConfig.OS.EditAtLineAndWait == "" && self.UserConfig.OS.EditCommandTemplate != "" {
|
||||
if cmdStr, err := self.GetEditCmdStrLegacy(filename, lineNumber); err == nil {
|
||||
return cmdStr
|
||||
}
|
||||
}
|
||||
|
||||
template := config.GetEditAtLineAndWaitTemplate(&self.UserConfig.OS, self.guessDefaultEditor)
|
||||
|
||||
templateValues := map[string]string{
|
||||
"filename": self.cmd.Quote(filename),
|
||||
"line": strconv.Itoa(lineNumber),
|
||||
}
|
||||
|
||||
cmdStr := utils.ResolvePlaceholderString(template, templateValues)
|
||||
return cmdStr
|
||||
}
|
||||
|
||||
func (self *FileCommands) guessDefaultEditor() string {
|
||||
// Try to query a few places where editors get configured
|
||||
editor := self.config.GetCoreEditor()
|
||||
if editor == "" {
|
||||
editor = self.os.Getenv("GIT_EDITOR")
|
||||
}
|
||||
if editor == "" {
|
||||
editor = self.os.Getenv("VISUAL")
|
||||
}
|
||||
if editor == "" {
|
||||
editor = self.os.Getenv("EDITOR")
|
||||
}
|
||||
|
||||
if editor != "" {
|
||||
// At this point, it might be more than just the name of the editor;
|
||||
// e.g. it might be "code -w" or "vim -u myvim.rc". So assume that
|
||||
// everything up to the first space is the editor name.
|
||||
editor = strings.Split(editor, " ")[0]
|
||||
}
|
||||
|
||||
return editor
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestEditFileCmdStr(t *testing.T) {
|
||||
func TestEditFileCmdStrLegacy(t *testing.T) {
|
||||
type scenario struct {
|
||||
filename string
|
||||
configEditCommand string
|
||||
@@ -172,7 +172,206 @@ func TestEditFileCmdStr(t *testing.T) {
|
||||
getenv: s.getenv,
|
||||
})
|
||||
|
||||
s.test(instance.GetEditCmdStr(s.filename, 1))
|
||||
s.test(instance.GetEditCmdStrLegacy(s.filename, 1))
|
||||
s.runner.CheckForMissingCalls()
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditFileCmd(t *testing.T) {
|
||||
type scenario struct {
|
||||
filename string
|
||||
osConfig config.OSConfig
|
||||
expectedCmdStr string
|
||||
expectedEditInTerminal bool
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
filename: "test",
|
||||
osConfig: config.OSConfig{},
|
||||
expectedCmdStr: `vim -- "test"`,
|
||||
expectedEditInTerminal: true,
|
||||
},
|
||||
{
|
||||
filename: "test",
|
||||
osConfig: config.OSConfig{
|
||||
Edit: "nano {{filename}}",
|
||||
},
|
||||
expectedCmdStr: `nano "test"`,
|
||||
expectedEditInTerminal: true,
|
||||
},
|
||||
{
|
||||
filename: "file/with space",
|
||||
osConfig: config.OSConfig{
|
||||
EditPreset: "sublime",
|
||||
},
|
||||
expectedCmdStr: `subl -- "file/with space"`,
|
||||
expectedEditInTerminal: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
userConfig := config.GetDefaultConfig()
|
||||
userConfig.OS = s.osConfig
|
||||
|
||||
instance := buildFileCommands(commonDeps{
|
||||
userConfig: userConfig,
|
||||
})
|
||||
|
||||
cmdStr, editInTerminal := instance.GetEditCmdStr(s.filename)
|
||||
assert.Equal(t, s.expectedCmdStr, cmdStr)
|
||||
assert.Equal(t, s.expectedEditInTerminal, editInTerminal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditFileAtLineCmd(t *testing.T) {
|
||||
type scenario struct {
|
||||
filename string
|
||||
lineNumber int
|
||||
osConfig config.OSConfig
|
||||
expectedCmdStr string
|
||||
expectedEditInTerminal bool
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
filename: "test",
|
||||
lineNumber: 42,
|
||||
osConfig: config.OSConfig{},
|
||||
expectedCmdStr: `vim +42 -- "test"`,
|
||||
expectedEditInTerminal: true,
|
||||
},
|
||||
{
|
||||
filename: "test",
|
||||
lineNumber: 35,
|
||||
osConfig: config.OSConfig{
|
||||
EditAtLine: "nano +{{line}} {{filename}}",
|
||||
},
|
||||
expectedCmdStr: `nano +35 "test"`,
|
||||
expectedEditInTerminal: true,
|
||||
},
|
||||
{
|
||||
filename: "file/with space",
|
||||
lineNumber: 12,
|
||||
osConfig: config.OSConfig{
|
||||
EditPreset: "sublime",
|
||||
},
|
||||
expectedCmdStr: `subl -- "file/with space":12`,
|
||||
expectedEditInTerminal: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
userConfig := config.GetDefaultConfig()
|
||||
userConfig.OS = s.osConfig
|
||||
|
||||
instance := buildFileCommands(commonDeps{
|
||||
userConfig: userConfig,
|
||||
})
|
||||
|
||||
cmdStr, editInTerminal := instance.GetEditAtLineCmdStr(s.filename, s.lineNumber)
|
||||
assert.Equal(t, s.expectedCmdStr, cmdStr)
|
||||
assert.Equal(t, s.expectedEditInTerminal, editInTerminal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditFileAtLineAndWaitCmd(t *testing.T) {
|
||||
type scenario struct {
|
||||
filename string
|
||||
lineNumber int
|
||||
osConfig config.OSConfig
|
||||
expectedCmdStr string
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
filename: "test",
|
||||
lineNumber: 42,
|
||||
osConfig: config.OSConfig{},
|
||||
expectedCmdStr: `vim +42 -- "test"`,
|
||||
},
|
||||
{
|
||||
filename: "file/with space",
|
||||
lineNumber: 12,
|
||||
osConfig: config.OSConfig{
|
||||
EditPreset: "sublime",
|
||||
},
|
||||
expectedCmdStr: `subl --wait -- "file/with space":12`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
userConfig := config.GetDefaultConfig()
|
||||
userConfig.OS = s.osConfig
|
||||
|
||||
instance := buildFileCommands(commonDeps{
|
||||
userConfig: userConfig,
|
||||
})
|
||||
|
||||
cmdStr := instance.GetEditAtLineAndWaitCmdStr(s.filename, s.lineNumber)
|
||||
assert.Equal(t, s.expectedCmdStr, cmdStr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuessDefaultEditor(t *testing.T) {
|
||||
type scenario struct {
|
||||
gitConfigMockResponses map[string]string
|
||||
getenv func(string) string
|
||||
expectedResult string
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
gitConfigMockResponses: nil,
|
||||
getenv: func(env string) string {
|
||||
return ""
|
||||
},
|
||||
expectedResult: "",
|
||||
},
|
||||
{
|
||||
gitConfigMockResponses: map[string]string{"core.editor": "nano"},
|
||||
getenv: func(env string) string {
|
||||
return ""
|
||||
},
|
||||
expectedResult: "nano",
|
||||
},
|
||||
{
|
||||
gitConfigMockResponses: map[string]string{"core.editor": "code -w"},
|
||||
getenv: func(env string) string {
|
||||
return ""
|
||||
},
|
||||
expectedResult: "code",
|
||||
},
|
||||
{
|
||||
gitConfigMockResponses: nil,
|
||||
getenv: func(env string) string {
|
||||
if env == "VISUAL" {
|
||||
return "emacs"
|
||||
}
|
||||
|
||||
return ""
|
||||
},
|
||||
expectedResult: "emacs",
|
||||
},
|
||||
{
|
||||
gitConfigMockResponses: nil,
|
||||
getenv: func(env string) string {
|
||||
if env == "EDITOR" {
|
||||
return "bbedit -w"
|
||||
}
|
||||
|
||||
return ""
|
||||
},
|
||||
expectedResult: "bbedit",
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
instance := buildFileCommands(commonDeps{
|
||||
gitConfig: git_config.NewFakeGitConfig(s.gitConfigMockResponses),
|
||||
getenv: s.getenv,
|
||||
})
|
||||
|
||||
assert.Equal(t, s.expectedResult, instance.guessDefaultEditor())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ type PatchCommands struct {
|
||||
status *StatusCommands
|
||||
stash *StashCommands
|
||||
|
||||
PatchManager *patch.PatchManager
|
||||
PatchBuilder *patch.PatchBuilder
|
||||
}
|
||||
|
||||
func NewPatchCommands(
|
||||
@@ -25,7 +25,7 @@ func NewPatchCommands(
|
||||
commit *CommitCommands,
|
||||
status *StatusCommands,
|
||||
stash *StashCommands,
|
||||
patchManager *patch.PatchManager,
|
||||
patchBuilder *patch.PatchBuilder,
|
||||
) *PatchCommands {
|
||||
return &PatchCommands{
|
||||
GitCommon: gitCommon,
|
||||
@@ -33,7 +33,7 @@ func NewPatchCommands(
|
||||
commit: commit,
|
||||
status: status,
|
||||
stash: stash,
|
||||
PatchManager: patchManager,
|
||||
PatchBuilder: patchBuilder,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +44,8 @@ func (self *PatchCommands) DeletePatchesFromCommit(commits []*models.Commit, com
|
||||
}
|
||||
|
||||
// apply each patch in reverse
|
||||
if err := self.PatchManager.ApplyPatches(true); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.PatchBuilder.ApplyPatches(true); err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -57,7 +55,7 @@ func (self *PatchCommands) DeletePatchesFromCommit(commits []*models.Commit, com
|
||||
}
|
||||
|
||||
self.rebase.onSuccessfulContinue = func() error {
|
||||
self.PatchManager.Reset()
|
||||
self.PatchBuilder.Reset()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -72,10 +70,9 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
}
|
||||
|
||||
// apply each patch forward
|
||||
if err := self.PatchManager.ApplyPatches(false); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.PatchBuilder.ApplyPatches(false); err != nil {
|
||||
// Don't abort the rebase here; this might cause conflicts, so give
|
||||
// the user a chance to resolve them
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -85,7 +82,7 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
}
|
||||
|
||||
self.rebase.onSuccessfulContinue = func() error {
|
||||
self.PatchManager.Reset()
|
||||
self.PatchBuilder.Reset()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -120,10 +117,8 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
}
|
||||
|
||||
// apply each patch in reverse
|
||||
if err := self.PatchManager.ApplyPatches(true); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.PatchBuilder.ApplyPatches(true); err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -132,6 +127,12 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
return err
|
||||
}
|
||||
|
||||
patch, err := self.diffHeadAgainstCommit(commits[sourceCommitIdx])
|
||||
if err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
if self.rebase.onSuccessfulContinue != nil {
|
||||
return errors.New("You are midway through another rebase operation. Please abort to start again")
|
||||
}
|
||||
@@ -139,10 +140,9 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
self.rebase.onSuccessfulContinue = func() error {
|
||||
// now we should be up to the destination, so let's apply forward these patches to that.
|
||||
// ideally we would ensure we're on the right commit but I'm not sure if that check is necessary
|
||||
if err := self.PatchManager.ApplyPatches(false); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.rebase.workingTree.ApplyPatch(patch, "index", "3way"); err != nil {
|
||||
// Don't abort the rebase here; this might cause conflicts, so give
|
||||
// the user a chance to resolve them
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
|
||||
}
|
||||
|
||||
self.rebase.onSuccessfulContinue = func() error {
|
||||
self.PatchManager.Reset()
|
||||
self.PatchBuilder.Reset()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -173,11 +173,9 @@ func (self *PatchCommands) MovePatchIntoIndex(commits []*models.Commit, commitId
|
||||
return err
|
||||
}
|
||||
|
||||
if err := self.PatchManager.ApplyPatches(true); err != nil {
|
||||
if err := self.PatchBuilder.ApplyPatches(true); err != nil {
|
||||
if self.status.WorkingTreeState() == enums.REBASE_MODE_REBASING {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = self.rebase.AbortRebase()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -187,17 +185,21 @@ func (self *PatchCommands) MovePatchIntoIndex(commits []*models.Commit, commitId
|
||||
return err
|
||||
}
|
||||
|
||||
patch, err := self.diffHeadAgainstCommit(commits[commitIdx])
|
||||
if err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
if self.rebase.onSuccessfulContinue != nil {
|
||||
return errors.New("You are midway through another rebase operation. Please abort to start again")
|
||||
}
|
||||
|
||||
self.rebase.onSuccessfulContinue = func() error {
|
||||
// add patches to index
|
||||
if err := self.PatchManager.ApplyPatches(false); err != nil {
|
||||
if err := self.rebase.workingTree.ApplyPatch(patch, "index", "3way"); err != nil {
|
||||
if self.status.WorkingTreeState() == enums.REBASE_MODE_REBASING {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = self.rebase.AbortRebase()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -208,7 +210,7 @@ func (self *PatchCommands) MovePatchIntoIndex(commits []*models.Commit, commitId
|
||||
}
|
||||
}
|
||||
|
||||
self.PatchManager.Reset()
|
||||
self.PatchBuilder.Reset()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -220,10 +222,8 @@ func (self *PatchCommands) PullPatchIntoNewCommit(commits []*models.Commit, comm
|
||||
return err
|
||||
}
|
||||
|
||||
if err := self.PatchManager.ApplyPatches(true); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.PatchBuilder.ApplyPatches(true); err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -232,18 +232,20 @@ func (self *PatchCommands) PullPatchIntoNewCommit(commits []*models.Commit, comm
|
||||
return err
|
||||
}
|
||||
|
||||
// add patches to index
|
||||
if err := self.PatchManager.ApplyPatches(false); err != nil {
|
||||
if err := self.rebase.AbortRebase(); err != nil {
|
||||
return err
|
||||
}
|
||||
patch, err := self.diffHeadAgainstCommit(commits[commitIdx])
|
||||
if err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := self.rebase.workingTree.ApplyPatch(patch, "index", "3way"); err != nil {
|
||||
_ = self.rebase.AbortRebase()
|
||||
return err
|
||||
}
|
||||
|
||||
head_message, _ := self.commit.GetHeadCommitMessage()
|
||||
new_message := fmt.Sprintf("Split from \"%s\"", head_message)
|
||||
err := self.commit.CommitCmdObj(new_message).Run()
|
||||
if err != nil {
|
||||
if err := self.commit.CommitCmdObj(new_message).Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -251,6 +253,15 @@ func (self *PatchCommands) PullPatchIntoNewCommit(commits []*models.Commit, comm
|
||||
return errors.New("You are midway through another rebase operation. Please abort to start again")
|
||||
}
|
||||
|
||||
self.PatchManager.Reset()
|
||||
self.PatchBuilder.Reset()
|
||||
return self.rebase.ContinueRebase()
|
||||
}
|
||||
|
||||
// We have just applied a patch in reverse to discard it from a commit; if we
|
||||
// now try to apply the patch again to move it to a later commit, or to the
|
||||
// index, then this would conflict "with itself" in case the patch contained
|
||||
// only some lines of a range of adjacent added lines. To solve this, we
|
||||
// get the diff of HEAD and the original commit and then apply that.
|
||||
func (self *PatchCommands) diffHeadAgainstCommit(commit *models.Commit) (string, error) {
|
||||
return self.cmd.New(fmt.Sprintf("git diff HEAD..%s", commit.Sha)).RunWithOutput()
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func NewRebaseCommands(
|
||||
}
|
||||
|
||||
func (self *RebaseCommands) RewordCommit(commits []*models.Commit, index int, message string) error {
|
||||
if index == 0 {
|
||||
if models.IsHeadCommit(commits, index) {
|
||||
// we've selected the top commit so no rebase is required
|
||||
return self.commit.RewordLastCommit(message)
|
||||
}
|
||||
@@ -95,17 +95,15 @@ func (self *RebaseCommands) GenericAmend(commits []*models.Commit, index int, f
|
||||
}
|
||||
|
||||
func (self *RebaseCommands) MoveCommitDown(commits []*models.Commit, index int) error {
|
||||
// we must ensure that we have at least two commits after the selected one
|
||||
if len(commits) <= index+2 {
|
||||
// assuming they aren't picking the bottom commit
|
||||
return errors.New(self.Tr.NoRoom)
|
||||
}
|
||||
|
||||
orderedCommits := append(commits[0:index], commits[index+1], commits[index])
|
||||
// not appending to original slice so that we don't mutate it
|
||||
orderedCommits := append([]*models.Commit{}, commits[0:index]...)
|
||||
orderedCommits = append(orderedCommits, commits[index+1], commits[index])
|
||||
|
||||
todoLines := self.BuildTodoLinesSingleAction(orderedCommits, "pick")
|
||||
|
||||
return self.PrepareInteractiveRebaseCommand(commits[index+2].Sha, todoLines, true).Run()
|
||||
baseShaOrRoot := getBaseShaOrRoot(commits, index+2)
|
||||
|
||||
return self.PrepareInteractiveRebaseCommand(baseShaOrRoot, todoLines, true).Run()
|
||||
}
|
||||
|
||||
func (self *RebaseCommands) InteractiveRebase(commits []*models.Commit, index int, action string) error {
|
||||
@@ -117,10 +115,20 @@ func (self *RebaseCommands) InteractiveRebase(commits []*models.Commit, index in
|
||||
return self.PrepareInteractiveRebaseCommand(sha, todo, true).Run()
|
||||
}
|
||||
|
||||
func (self *RebaseCommands) InteractiveRebaseBreakAfter(commits []*models.Commit, index int) error {
|
||||
todo, sha, err := self.BuildSingleActionTodo(commits, index-1, "pick")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
todo = append(todo, TodoLine{Action: "break", Commit: nil})
|
||||
return self.PrepareInteractiveRebaseCommand(sha, todo, true).Run()
|
||||
}
|
||||
|
||||
// PrepareInteractiveRebaseCommand returns the cmd for an interactive rebase
|
||||
// we tell git to run lazygit to edit the todo list, and we pass the client
|
||||
// lazygit a todo string to write to the todo file
|
||||
func (self *RebaseCommands) PrepareInteractiveRebaseCommand(baseSha string, todoLines []TodoLine, overrideEditor bool) oscommands.ICmdObj {
|
||||
func (self *RebaseCommands) PrepareInteractiveRebaseCommand(baseShaOrRoot string, todoLines []TodoLine, overrideEditor bool) oscommands.ICmdObj {
|
||||
todo := self.buildTodo(todoLines)
|
||||
ex := oscommands.GetLazygitPath()
|
||||
|
||||
@@ -129,7 +137,7 @@ func (self *RebaseCommands) PrepareInteractiveRebaseCommand(baseSha string, todo
|
||||
debug = "TRUE"
|
||||
}
|
||||
|
||||
cmdStr := fmt.Sprintf("git rebase --interactive --autostash --keep-empty %s", baseSha)
|
||||
cmdStr := fmt.Sprintf("git rebase --interactive --autostash --keep-empty --empty=keep --no-autosquash %s", baseShaOrRoot)
|
||||
self.Log.WithField("command", cmdStr).Debug("RunCommand")
|
||||
|
||||
cmdObj := self.cmd.New(cmdStr)
|
||||
@@ -162,16 +170,8 @@ func (self *RebaseCommands) PrepareInteractiveRebaseCommand(baseSha string, todo
|
||||
func (self *RebaseCommands) BuildSingleActionTodo(commits []*models.Commit, actionIndex int, action string) ([]TodoLine, string, error) {
|
||||
baseIndex := actionIndex + 1
|
||||
|
||||
if len(commits) <= baseIndex {
|
||||
return nil, "", errors.New(self.Tr.CannotRebaseOntoFirstCommit)
|
||||
}
|
||||
|
||||
if action == "squash" || action == "fixup" {
|
||||
baseIndex++
|
||||
|
||||
if len(commits) <= baseIndex {
|
||||
return nil, "", errors.New(self.Tr.CannotSquashOntoSecondCommit)
|
||||
}
|
||||
}
|
||||
|
||||
todoLines := self.BuildTodoLines(commits[0:baseIndex], func(commit *models.Commit, i int) string {
|
||||
@@ -187,16 +187,18 @@ func (self *RebaseCommands) BuildSingleActionTodo(commits []*models.Commit, acti
|
||||
}
|
||||
})
|
||||
|
||||
return todoLines, commits[baseIndex].Sha, nil
|
||||
baseShaOrRoot := getBaseShaOrRoot(commits, baseIndex)
|
||||
|
||||
return todoLines, baseShaOrRoot, nil
|
||||
}
|
||||
|
||||
// AmendTo amends the given commit with whatever files are staged
|
||||
func (self *RebaseCommands) AmendTo(sha string) error {
|
||||
if err := self.commit.CreateFixupCommit(sha); err != nil {
|
||||
func (self *RebaseCommands) AmendTo(commit *models.Commit) error {
|
||||
if err := self.commit.CreateFixupCommit(commit.Sha); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return self.SquashAllAboveFixupCommits(sha)
|
||||
return self.SquashAllAboveFixupCommits(commit)
|
||||
}
|
||||
|
||||
// EditRebaseTodo sets the action at a given index in the git-rebase-todo file
|
||||
@@ -251,12 +253,17 @@ func (self *RebaseCommands) MoveTodoDown(index int) error {
|
||||
}
|
||||
|
||||
// SquashAllAboveFixupCommits squashes all fixup! commits above the given one
|
||||
func (self *RebaseCommands) SquashAllAboveFixupCommits(sha string) error {
|
||||
func (self *RebaseCommands) SquashAllAboveFixupCommits(commit *models.Commit) error {
|
||||
shaOrRoot := commit.Sha + "^"
|
||||
if commit.IsFirstCommit() {
|
||||
shaOrRoot = "--root"
|
||||
}
|
||||
|
||||
return self.runSkipEditorCommand(
|
||||
self.cmd.New(
|
||||
fmt.Sprintf(
|
||||
"git rebase --interactive --rebase-merges --autostash --autosquash %s^",
|
||||
sha,
|
||||
"git rebase --interactive --rebase-merges --autostash --autosquash %s",
|
||||
shaOrRoot,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -332,6 +339,7 @@ func (self *RebaseCommands) runSkipEditorCommand(cmdObj oscommands.ICmdObj) erro
|
||||
AddEnvVars(
|
||||
daemon.DaemonKindEnvKey+"="+string(daemon.ExitImmediately),
|
||||
"GIT_EDITOR="+lazyGitPath,
|
||||
"GIT_SEQUENCE_EDITOR="+lazyGitPath,
|
||||
"EDITOR="+lazyGitPath,
|
||||
"VISUAL="+lazyGitPath,
|
||||
).
|
||||
@@ -399,5 +407,23 @@ type TodoLine struct {
|
||||
}
|
||||
|
||||
func (self *TodoLine) ToString() string {
|
||||
return self.Action + " " + self.Commit.Sha + " " + self.Commit.Name + "\n"
|
||||
if self.Action == "break" {
|
||||
return self.Action + "\n"
|
||||
} else {
|
||||
return self.Action + " " + self.Commit.Sha + " " + self.Commit.Name + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
// we can't start an interactive rebase from the first commit without passing the
|
||||
// '--root' arg
|
||||
func getBaseShaOrRoot(commits []*models.Commit, index int) string {
|
||||
// We assume that the commits slice contains the initial commit of the repo.
|
||||
// Technically this assumption could prove false, but it's unlikely you'll
|
||||
// be starting a rebase from 300 commits ago (which is the original commit limit
|
||||
// at time of writing)
|
||||
if index < len(commits) {
|
||||
return commits[index].Sha
|
||||
} else {
|
||||
return "--root"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestRebaseRebaseBranch(t *testing.T) {
|
||||
testName: "successful rebase",
|
||||
arg: "master",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git rebase --interactive --autostash --keep-empty master`, "", nil),
|
||||
Expect(`git rebase --interactive --autostash --keep-empty --empty=keep --no-autosquash master`, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -35,7 +35,7 @@ func TestRebaseRebaseBranch(t *testing.T) {
|
||||
testName: "unsuccessful rebase",
|
||||
arg: "master",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git rebase --interactive --autostash --keep-empty master`, "", errors.New("error")),
|
||||
Expect(`git rebase --interactive --autostash --keep-empty --empty=keep --no-autosquash master`, "", errors.New("error")),
|
||||
test: func(err error) {
|
||||
assert.Error(t, err)
|
||||
},
|
||||
@@ -62,6 +62,7 @@ func TestRebaseSkipEditorCommand(t *testing.T) {
|
||||
`^VISUAL=.*$`,
|
||||
`^EDITOR=.*$`,
|
||||
`^GIT_EDITOR=.*$`,
|
||||
`^GIT_SEQUENCE_EDITOR=.*$`,
|
||||
"^" + daemon.DaemonKindEnvKey + "=" + string(daemon.ExitImmediately) + "$",
|
||||
} {
|
||||
regexStr := regexStr
|
||||
@@ -124,7 +125,7 @@ func TestRebaseDiscardOldFileChanges(t *testing.T) {
|
||||
commitIndex: 0,
|
||||
fileName: "test999.txt",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git rebase --interactive --autostash --keep-empty abcdef`, "", nil).
|
||||
Expect(`git rebase --interactive --autostash --keep-empty --empty=keep --no-autosquash abcdef`, "", nil).
|
||||
Expect(`git cat-file -e HEAD^:"test999.txt"`, "", nil).
|
||||
Expect(`git checkout HEAD^ -- "test999.txt"`, "", nil).
|
||||
Expect(`git commit --amend --no-edit --allow-empty`, "", nil).
|
||||
|
||||
@@ -14,12 +14,20 @@ func NewTagCommands(gitCommon *GitCommon) *TagCommands {
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TagCommands) CreateLightweight(tagName string, commitSha string) error {
|
||||
return self.cmd.New(fmt.Sprintf("git tag -- %s %s", self.cmd.Quote(tagName), commitSha)).Run()
|
||||
func (self *TagCommands) CreateLightweight(tagName string, ref string) error {
|
||||
if len(ref) > 0 {
|
||||
return self.cmd.New(fmt.Sprintf("git tag -- %s %s", self.cmd.Quote(tagName), self.cmd.Quote(ref))).Run()
|
||||
} else {
|
||||
return self.cmd.New(fmt.Sprintf("git tag -- %s", self.cmd.Quote(tagName))).Run()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TagCommands) CreateAnnotated(tagName, commitSha, msg string) error {
|
||||
return self.cmd.New(fmt.Sprintf("git tag %s %s -m %s", tagName, commitSha, self.cmd.Quote(msg))).Run()
|
||||
func (self *TagCommands) CreateAnnotated(tagName, ref, msg string) error {
|
||||
if len(ref) > 0 {
|
||||
return self.cmd.New(fmt.Sprintf("git tag %s %s -m %s", self.cmd.Quote(tagName), self.cmd.Quote(ref), self.cmd.Quote(msg))).Run()
|
||||
} else {
|
||||
return self.cmd.New(fmt.Sprintf("git tag %s -m %s", self.cmd.Quote(tagName), self.cmd.Quote(msg))).Run()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TagCommands) Delete(tagName string) error {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/jesseduffield/generics/slices"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
@@ -12,40 +12,42 @@ import (
|
||||
|
||||
type TagLoader struct {
|
||||
*common.Common
|
||||
version *GitVersion
|
||||
cmd oscommands.ICmdObjBuilder
|
||||
cmd oscommands.ICmdObjBuilder
|
||||
}
|
||||
|
||||
func NewTagLoader(
|
||||
common *common.Common,
|
||||
version *GitVersion,
|
||||
cmd oscommands.ICmdObjBuilder,
|
||||
) *TagLoader {
|
||||
return &TagLoader{
|
||||
Common: common,
|
||||
version: version,
|
||||
cmd: cmd,
|
||||
Common: common,
|
||||
cmd: cmd,
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TagLoader) GetTags() ([]*models.Tag, error) {
|
||||
// get remote branches, sorted by creation date (descending)
|
||||
// see: https://git-scm.com/docs/git-tag#Documentation/git-tag.txt---sortltkeygt
|
||||
sortKey := "-creatordate"
|
||||
if self.version.IsOlderThan(2, 7, 0) {
|
||||
sortKey = "-v:refname"
|
||||
}
|
||||
|
||||
tagsOutput, err := self.cmd.New(fmt.Sprintf(`git tag --list --sort=%s`, sortKey)).DontLog().RunWithOutput()
|
||||
tagsOutput, err := self.cmd.New(`git tag --list -n --sort=-creatordate`).DontLog().RunWithOutput()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
split := utils.SplitLines(tagsOutput)
|
||||
|
||||
tags := slices.Map(split, func(tagName string) *models.Tag {
|
||||
lineRegex := regexp.MustCompile(`^([^\s]+)(\s+)?(.*)$`)
|
||||
|
||||
tags := slices.Map(split, func(line string) *models.Tag {
|
||||
matches := lineRegex.FindStringSubmatch(line)
|
||||
tagName := matches[1]
|
||||
message := ""
|
||||
if len(matches) > 3 {
|
||||
message = matches[3]
|
||||
}
|
||||
|
||||
return &models.Tag{
|
||||
Name: tagName,
|
||||
Name: tagName,
|
||||
Message: message,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -9,18 +9,14 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const tagsOutput = `v0.34
|
||||
v0.33
|
||||
v0.32.2
|
||||
v0.32.1
|
||||
v0.32
|
||||
testtag
|
||||
const tagsOutput = `tag1 this is my message
|
||||
tag2
|
||||
tag3 this is my other message
|
||||
`
|
||||
|
||||
func TestGetTags(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
gitVersion *GitVersion
|
||||
runner *oscommands.FakeCmdObjRunner
|
||||
expectedTags []*models.Tag
|
||||
expectedError error
|
||||
@@ -28,48 +24,20 @@ func TestGetTags(t *testing.T) {
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "should return no tags if there are none",
|
||||
gitVersion: &GitVersion{2, 7, 0, ""},
|
||||
testName: "should return no tags if there are none",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git tag --list --sort=-creatordate`, "", nil),
|
||||
Expect(`git tag --list -n --sort=-creatordate`, "", nil),
|
||||
expectedTags: []*models.Tag{},
|
||||
expectedError: nil,
|
||||
},
|
||||
{
|
||||
testName: "should return no tags if there are none (< 2.7.0)",
|
||||
gitVersion: &GitVersion{2, 6, 7, ""},
|
||||
testName: "should return tags if present",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git tag --list --sort=-v:refname`, "", nil),
|
||||
expectedTags: []*models.Tag{},
|
||||
expectedError: nil,
|
||||
},
|
||||
{
|
||||
testName: "should return tags if present",
|
||||
gitVersion: &GitVersion{2, 7, 0, ""},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git tag --list --sort=-creatordate`, tagsOutput, nil),
|
||||
Expect(`git tag --list -n --sort=-creatordate`, tagsOutput, nil),
|
||||
expectedTags: []*models.Tag{
|
||||
{Name: "v0.34"},
|
||||
{Name: "v0.33"},
|
||||
{Name: "v0.32.2"},
|
||||
{Name: "v0.32.1"},
|
||||
{Name: "v0.32"},
|
||||
{Name: "testtag"},
|
||||
},
|
||||
expectedError: nil,
|
||||
},
|
||||
{
|
||||
testName: "should return tags if present (< 2.7.0)",
|
||||
gitVersion: &GitVersion{2, 6, 7, ""},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git tag --list --sort=-v:refname`, tagsOutput, nil),
|
||||
expectedTags: []*models.Tag{
|
||||
{Name: "v0.34"},
|
||||
{Name: "v0.33"},
|
||||
{Name: "v0.32.2"},
|
||||
{Name: "v0.32.1"},
|
||||
{Name: "v0.32"},
|
||||
{Name: "testtag"},
|
||||
{Name: "tag1", Message: "this is my message"},
|
||||
{Name: "tag2", Message: ""},
|
||||
{Name: "tag3", Message: "this is my other message"},
|
||||
},
|
||||
expectedError: nil,
|
||||
},
|
||||
@@ -78,11 +46,10 @@ func TestGetTags(t *testing.T) {
|
||||
for _, scenario := range scenarios {
|
||||
scenario := scenario
|
||||
t.Run(scenario.testName, func(t *testing.T) {
|
||||
loader := NewTagLoader(
|
||||
utils.NewDummyCommon(),
|
||||
scenario.gitVersion,
|
||||
oscommands.NewDummyCmdObjBuilder(scenario.runner),
|
||||
)
|
||||
loader := &TagLoader{
|
||||
Common: utils.NewDummyCommon(),
|
||||
cmd: oscommands.NewDummyCmdObjBuilder(scenario.runner),
|
||||
}
|
||||
|
||||
tags, err := loader.GetTags()
|
||||
|
||||
|
||||
@@ -287,11 +287,15 @@ func (self *WorkingTreeCommands) SaveTemporaryPatch(patch string) (string, error
|
||||
|
||||
// ShowFileDiff get the diff of specified from and to. Typically this will be used for a single commit so it'll be 123abc^..123abc
|
||||
// but when we're in diff mode it could be any 'from' to any 'to'. The reverse flag is also here thanks to diff mode.
|
||||
func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, plain bool) (string, error) {
|
||||
return self.ShowFileDiffCmdObj(from, to, reverse, fileName, plain).RunWithOutput()
|
||||
func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, plain bool,
|
||||
ignoreWhitespace bool,
|
||||
) (string, error) {
|
||||
return self.ShowFileDiffCmdObj(from, to, reverse, fileName, plain, ignoreWhitespace).RunWithOutput()
|
||||
}
|
||||
|
||||
func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reverse bool, fileName string, plain bool) oscommands.ICmdObj {
|
||||
func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reverse bool, fileName string, plain bool,
|
||||
ignoreWhitespace bool,
|
||||
) oscommands.ICmdObj {
|
||||
colorArg := self.UserConfig.Git.Paging.ColorArg
|
||||
contextSize := self.UserConfig.Git.DiffContextSize
|
||||
if plain {
|
||||
@@ -303,11 +307,16 @@ func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reve
|
||||
reverseFlag = " -R"
|
||||
}
|
||||
|
||||
ignoreWhitespaceFlag := ""
|
||||
if ignoreWhitespace {
|
||||
ignoreWhitespaceFlag = " --ignore-all-space"
|
||||
}
|
||||
|
||||
return self.cmd.
|
||||
New(
|
||||
fmt.Sprintf(
|
||||
"git diff --submodule --no-ext-diff --unified=%d --no-renames --color=%s%s%s%s -- %s",
|
||||
contextSize, colorArg, pad(from), pad(to), reverseFlag, self.cmd.Quote(fileName)),
|
||||
"git diff --submodule --no-ext-diff --unified=%d --no-renames --color=%s%s%s%s%s -- %s",
|
||||
contextSize, colorArg, pad(from), pad(to), reverseFlag, ignoreWhitespaceFlag, self.cmd.Quote(fileName)),
|
||||
).
|
||||
DontLog()
|
||||
}
|
||||
|
||||
@@ -323,38 +323,52 @@ func TestWorkingTreeDiff(t *testing.T) {
|
||||
|
||||
func TestWorkingTreeShowFileDiff(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
from string
|
||||
to string
|
||||
reverse bool
|
||||
plain bool
|
||||
contextSize int
|
||||
runner *oscommands.FakeCmdObjRunner
|
||||
testName string
|
||||
from string
|
||||
to string
|
||||
reverse bool
|
||||
plain bool
|
||||
ignoreWhitespace bool
|
||||
contextSize int
|
||||
runner *oscommands.FakeCmdObjRunner
|
||||
}
|
||||
|
||||
const expectedResult = "pretend this is an actual git diff"
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "Default case",
|
||||
from: "1234567890",
|
||||
to: "0987654321",
|
||||
reverse: false,
|
||||
plain: false,
|
||||
contextSize: 3,
|
||||
testName: "Default case",
|
||||
from: "1234567890",
|
||||
to: "0987654321",
|
||||
reverse: false,
|
||||
plain: false,
|
||||
ignoreWhitespace: false,
|
||||
contextSize: 3,
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git diff --submodule --no-ext-diff --unified=3 --no-renames --color=always 1234567890 0987654321 -- "test.txt"`, expectedResult, nil),
|
||||
},
|
||||
{
|
||||
testName: "Show diff with custom context size",
|
||||
from: "1234567890",
|
||||
to: "0987654321",
|
||||
reverse: false,
|
||||
plain: false,
|
||||
contextSize: 123,
|
||||
testName: "Show diff with custom context size",
|
||||
from: "1234567890",
|
||||
to: "0987654321",
|
||||
reverse: false,
|
||||
plain: false,
|
||||
ignoreWhitespace: false,
|
||||
contextSize: 123,
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git diff --submodule --no-ext-diff --unified=123 --no-renames --color=always 1234567890 0987654321 -- "test.txt"`, expectedResult, nil),
|
||||
},
|
||||
{
|
||||
testName: "Default case (ignore whitespace)",
|
||||
from: "1234567890",
|
||||
to: "0987654321",
|
||||
reverse: false,
|
||||
plain: false,
|
||||
ignoreWhitespace: true,
|
||||
contextSize: 3,
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
Expect(`git diff --submodule --no-ext-diff --unified=3 --no-renames --color=always 1234567890 0987654321 --ignore-all-space -- "test.txt"`, expectedResult, nil),
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
@@ -365,7 +379,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) {
|
||||
|
||||
instance := buildWorkingTreeCommands(commonDeps{runner: s.runner, userConfig: userConfig})
|
||||
|
||||
result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, "test.txt", s.plain)
|
||||
result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, "test.txt", s.plain, s.ignoreWhitespace)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expectedResult, result)
|
||||
s.runner.CheckForMissingCalls()
|
||||
|
||||
@@ -4,7 +4,7 @@ package hosting_service
|
||||
// at regoio.herokuapp.com
|
||||
var defaultUrlRegexStrings = []string{
|
||||
`^(?:https?|ssh)://[^/]+/(?P<owner>.*)/(?P<repo>.*?)(?:\.git)?$`,
|
||||
`^git@.*:(?P<owner>.*)/(?P<repo>.*?)(?:\.git)?$`,
|
||||
`^.*?@.*:(?P<owner>.*)/(?P<repo>.*?)(?:\.git)?$`,
|
||||
}
|
||||
var defaultRepoURLTemplate = "https://{{.webDomain}}/{{.owner}}/{{.repo}}"
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ package hosting_service
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/fakes"
|
||||
"github.com/jesseduffield/lazygit/pkg/i18n"
|
||||
"github.com/jesseduffield/lazygit/pkg/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -86,6 +86,16 @@ func TestGetPullRequestURL(t *testing.T) {
|
||||
assert.Equal(t, "https://github.com/peter/calculator/compare/feature%2Foperations...feature%2Fsum-operation?expand=1", url)
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Opens a link to new pull request on github with specific target branch (different git username)",
|
||||
from: "feature/sum-operation",
|
||||
to: "feature/operations",
|
||||
remoteUrl: "ssh://org-12345@github.com:peter/calculator.git",
|
||||
test: func(url string, err error) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://github.com/peter/calculator/compare/feature%2Foperations...feature%2Fsum-operation?expand=1", url)
|
||||
},
|
||||
},
|
||||
{
|
||||
testName: "Opens a link to new pull request on github with https remote url with specific target branch",
|
||||
from: "feature/sum-operation",
|
||||
@@ -328,7 +338,7 @@ func TestGetPullRequestURL(t *testing.T) {
|
||||
s := s
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
tr := i18n.EnglishTranslationSet()
|
||||
log := &test.FakeFieldLogger{}
|
||||
log := &fakes.FakeFieldLogger{}
|
||||
hostingServiceMgr := NewHostingServiceMgr(log, &tr, s.remoteUrl, s.configServiceDomains)
|
||||
s.test(hostingServiceMgr.GetPullRequestURL(s.from, s.to))
|
||||
log.AssertErrors(t, s.expectedLoggedErrors)
|
||||
|
||||
@@ -65,3 +65,7 @@ func (c *Commit) IsMerge() bool {
|
||||
func (c *Commit) IsTODO() bool {
|
||||
return c.Action != ""
|
||||
}
|
||||
|
||||
func IsHeadCommit(commits []*Commit, index int) bool {
|
||||
return !commits[index].IsTODO() && (index == 0 || commits[index-1].IsTODO())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ package models
|
||||
// Tag : A git tag
|
||||
type Tag struct {
|
||||
Name string
|
||||
// this is either the first line of the message of an annotated tag, or the
|
||||
// first line of a commit message for a lightweight tag
|
||||
Message string
|
||||
}
|
||||
|
||||
func (t *Tag) FullRefName() string {
|
||||
@@ -22,5 +25,5 @@ func (t *Tag) ID() string {
|
||||
}
|
||||
|
||||
func (t *Tag) Description() string {
|
||||
return "tag " + t.Name
|
||||
return t.Message
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func (self *CmdObjBuilder) NewFromArgs(args []string) ICmdObj {
|
||||
}
|
||||
|
||||
func (self *CmdObjBuilder) NewShell(commandStr string) ICmdObj {
|
||||
quotedCommand := ""
|
||||
var quotedCommand string
|
||||
// Windows does not seem to like quotes around the command
|
||||
if self.platform.OS == "windows" {
|
||||
quotedCommand = strings.NewReplacer(
|
||||
|
||||
@@ -323,6 +323,23 @@ func (self *cmdObjRunner) processOutput(reader io.Reader, writer io.Writer, prom
|
||||
// having a function that returns a function because we need to maintain some state inbetween calls hence the closure
|
||||
func (self *cmdObjRunner) getCheckForCredentialRequestFunc() func([]byte) (CredentialType, bool) {
|
||||
var ttyText strings.Builder
|
||||
prompts := map[string]CredentialType{
|
||||
`Password:`: Password,
|
||||
`.+'s password:`: Password,
|
||||
`Password\s*for\s*'.+':`: Password,
|
||||
`Username\s*for\s*'.+':`: Username,
|
||||
`Enter\s*passphrase\s*for\s*key\s*'.+':`: Passphrase,
|
||||
`Enter\s*PIN\s*for\s*.+\s*key\s*.+:`: PIN,
|
||||
}
|
||||
|
||||
compiledPrompts := map[*regexp.Regexp]CredentialType{}
|
||||
for pattern, askFor := range prompts {
|
||||
compiledPattern := regexp.MustCompile(pattern)
|
||||
compiledPrompts[compiledPattern] = askFor
|
||||
}
|
||||
|
||||
newlineRegex := regexp.MustCompile("\n")
|
||||
|
||||
// this function takes each word of output from the command and builds up a string to see if we're being asked for a password
|
||||
return func(newBytes []byte) (CredentialType, bool) {
|
||||
_, err := ttyText.Write(newBytes)
|
||||
@@ -330,22 +347,18 @@ func (self *cmdObjRunner) getCheckForCredentialRequestFunc() func([]byte) (Crede
|
||||
self.log.Error(err)
|
||||
}
|
||||
|
||||
prompts := map[string]CredentialType{
|
||||
`Password:`: Password,
|
||||
`.+'s password:`: Password,
|
||||
`Password\s*for\s*'.+':`: Password,
|
||||
`Username\s*for\s*'.+':`: Username,
|
||||
`Enter\s*passphrase\s*for\s*key\s*'.+':`: Passphrase,
|
||||
`Enter\s*PIN\s*for\s*.+\s*key\s*.+:`: PIN,
|
||||
}
|
||||
|
||||
for pattern, askFor := range prompts {
|
||||
if match, _ := regexp.MatchString(pattern, ttyText.String()); match {
|
||||
for pattern, askFor := range compiledPrompts {
|
||||
if match := pattern.Match([]byte(ttyText.String())); match {
|
||||
ttyText.Reset()
|
||||
return askFor, true
|
||||
}
|
||||
}
|
||||
|
||||
if indices := newlineRegex.FindIndex([]byte(ttyText.String())); indices != nil {
|
||||
newText := []byte(ttyText.String()[indices[1]:])
|
||||
ttyText.Reset()
|
||||
ttyText.Write(newText)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package oscommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
|
||||
func getRunner() *cmdObjRunner {
|
||||
log := utils.NewDummyLog()
|
||||
return &cmdObjRunner{
|
||||
log: log,
|
||||
guiIO: NewNullGuiIO(log),
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessOutput(t *testing.T) {
|
||||
defaultPromptUserForCredential := func(ct CredentialType) string {
|
||||
switch ct {
|
||||
case Password:
|
||||
return "password"
|
||||
case Username:
|
||||
return "username"
|
||||
case Passphrase:
|
||||
return "passphrase"
|
||||
case PIN:
|
||||
return "pin"
|
||||
default:
|
||||
panic("unexpected credential type")
|
||||
}
|
||||
}
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
promptUserForCredential func(CredentialType) string
|
||||
output string
|
||||
expectedToWrite string
|
||||
}{
|
||||
{
|
||||
name: "no output",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "",
|
||||
expectedToWrite: "",
|
||||
},
|
||||
{
|
||||
name: "password prompt",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Password:",
|
||||
expectedToWrite: "password",
|
||||
},
|
||||
{
|
||||
name: "password prompt 2",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Bill's password:",
|
||||
expectedToWrite: "password",
|
||||
},
|
||||
{
|
||||
name: "password prompt 3",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Password for 'Bill':",
|
||||
expectedToWrite: "password",
|
||||
},
|
||||
{
|
||||
name: "username prompt",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Username for 'Bill':",
|
||||
expectedToWrite: "username",
|
||||
},
|
||||
{
|
||||
name: "passphrase prompt",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Enter passphrase for key '123':",
|
||||
expectedToWrite: "passphrase",
|
||||
},
|
||||
{
|
||||
name: "pin prompt",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Enter PIN for key '123':",
|
||||
expectedToWrite: "pin",
|
||||
},
|
||||
{
|
||||
name: "username and password prompt",
|
||||
promptUserForCredential: defaultPromptUserForCredential,
|
||||
output: "Password:\nUsername for 'Alice':\n",
|
||||
expectedToWrite: "passwordusername",
|
||||
},
|
||||
{
|
||||
name: "user submits empty credential",
|
||||
promptUserForCredential: func(ct CredentialType) string { return "" },
|
||||
output: "Password:\n",
|
||||
expectedToWrite: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, scenario := range scenarios {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
runner := getRunner()
|
||||
reader := strings.NewReader(scenario.output)
|
||||
writer := &strings.Builder{}
|
||||
|
||||
runner.processOutput(reader, writer, scenario.promptUserForCredential)
|
||||
|
||||
if writer.String() != scenario.expectedToWrite {
|
||||
t.Errorf("expected to write '%s' but got '%s'", scenario.expectedToWrite, writer.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -78,21 +78,30 @@ func FileType(path string) string {
|
||||
}
|
||||
|
||||
func (c *OSCommand) OpenFile(filename string) error {
|
||||
return c.OpenFileAtLine(filename, 1)
|
||||
}
|
||||
|
||||
func (c *OSCommand) OpenFileAtLine(filename string, lineNumber int) error {
|
||||
commandTemplate := c.UserConfig.OS.OpenCommand
|
||||
commandTemplate := c.UserConfig.OS.Open
|
||||
if commandTemplate == "" {
|
||||
// Legacy support
|
||||
commandTemplate = c.UserConfig.OS.OpenCommand
|
||||
}
|
||||
if commandTemplate == "" {
|
||||
commandTemplate = config.GetPlatformDefaultConfig().Open
|
||||
}
|
||||
templateValues := map[string]string{
|
||||
"filename": c.Quote(filename),
|
||||
"line": fmt.Sprintf("%d", lineNumber),
|
||||
}
|
||||
command := utils.ResolvePlaceholderString(commandTemplate, templateValues)
|
||||
return c.Cmd.NewShell(command).Run()
|
||||
}
|
||||
|
||||
func (c *OSCommand) OpenLink(link string) error {
|
||||
commandTemplate := c.UserConfig.OS.OpenLinkCommand
|
||||
commandTemplate := c.UserConfig.OS.OpenLink
|
||||
if commandTemplate == "" {
|
||||
// Legacy support
|
||||
commandTemplate = c.UserConfig.OS.OpenLinkCommand
|
||||
}
|
||||
if commandTemplate == "" {
|
||||
commandTemplate = config.GetPlatformDefaultConfig().OpenLink
|
||||
}
|
||||
templateValues := map[string]string{
|
||||
"link": c.Quote(link),
|
||||
}
|
||||
|
||||
+2
-2
@@ -75,7 +75,7 @@ func TestOSCommandOpenFileDarwin(t *testing.T) {
|
||||
for _, s := range scenarios {
|
||||
oSCmd := NewDummyOSCommandWithRunner(s.runner)
|
||||
oSCmd.Platform.OS = "darwin"
|
||||
oSCmd.UserConfig.OS.OpenCommand = "open {{filename}}"
|
||||
oSCmd.UserConfig.OS.Open = "open {{filename}}"
|
||||
|
||||
s.test(oSCmd.OpenFile(s.filename))
|
||||
}
|
||||
@@ -135,7 +135,7 @@ func TestOSCommandOpenFileLinux(t *testing.T) {
|
||||
for _, s := range scenarios {
|
||||
oSCmd := NewDummyOSCommandWithRunner(s.runner)
|
||||
oSCmd.Platform.OS = "linux"
|
||||
oSCmd.UserConfig.OS.OpenCommand = `xdg-open {{filename}} > /dev/null`
|
||||
oSCmd.UserConfig.OS.Open = `xdg-open {{filename}} > /dev/null`
|
||||
|
||||
s.test(oSCmd.OpenFile(s.filename))
|
||||
}
|
||||
+8
-5
@@ -6,6 +6,7 @@ package oscommands
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/cli/safeexec"
|
||||
"github.com/go-errors/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -19,11 +20,13 @@ func TestOSCommandOpenFileWindows(t *testing.T) {
|
||||
test func(error)
|
||||
}
|
||||
|
||||
fullCmdPath, _ := safeexec.LookPath("cmd")
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
filename: "test",
|
||||
runner: NewFakeRunner(t).
|
||||
ExpectArgs([]string{"cmd", "/c", "start", "", "test"}, "", errors.New("error")),
|
||||
ExpectArgs([]string{fullCmdPath, "/c", "start", "", "test"}, "", errors.New("error")),
|
||||
test: func(err error) {
|
||||
assert.Error(t, err)
|
||||
},
|
||||
@@ -31,7 +34,7 @@ func TestOSCommandOpenFileWindows(t *testing.T) {
|
||||
{
|
||||
filename: "test",
|
||||
runner: NewFakeRunner(t).
|
||||
ExpectArgs([]string{"cmd", "/c", "start", "", "test"}, "", nil),
|
||||
ExpectArgs([]string{fullCmdPath, "/c", "start", "", "test"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -39,7 +42,7 @@ func TestOSCommandOpenFileWindows(t *testing.T) {
|
||||
{
|
||||
filename: "filename with spaces",
|
||||
runner: NewFakeRunner(t).
|
||||
ExpectArgs([]string{"cmd", "/c", "start", "", "filename with spaces"}, "", nil),
|
||||
ExpectArgs([]string{fullCmdPath, "/c", "start", "", "filename with spaces"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -47,7 +50,7 @@ func TestOSCommandOpenFileWindows(t *testing.T) {
|
||||
{
|
||||
filename: "let's_test_with_single_quote",
|
||||
runner: NewFakeRunner(t).
|
||||
ExpectArgs([]string{"cmd", "/c", "start", "", "let's_test_with_single_quote"}, "", nil),
|
||||
ExpectArgs([]string{fullCmdPath, "/c", "start", "", "let's_test_with_single_quote"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -55,7 +58,7 @@ func TestOSCommandOpenFileWindows(t *testing.T) {
|
||||
{
|
||||
filename: "$USER.txt",
|
||||
runner: NewFakeRunner(t).
|
||||
ExpectArgs([]string{"cmd", "/c", "start", "", "$USER.txt"}, "", nil),
|
||||
ExpectArgs([]string{fullCmdPath, "/c", "start", "", "$USER.txt"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -0,0 +1,169 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/generics/set"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/style"
|
||||
"github.com/jesseduffield/lazygit/pkg/theme"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type patchPresenter struct {
|
||||
patch *Patch
|
||||
// if true, all following fields are ignored
|
||||
plain bool
|
||||
|
||||
isFocused bool
|
||||
// first line index for selected cursor range
|
||||
firstLineIndex int
|
||||
// last line index for selected cursor range
|
||||
lastLineIndex int
|
||||
// line indices for tagged lines (e.g. lines added to a custom patch)
|
||||
incLineIndices *set.Set[int]
|
||||
}
|
||||
|
||||
// formats the patch as a plain string
|
||||
func formatPlain(patch *Patch) string {
|
||||
presenter := &patchPresenter{
|
||||
patch: patch,
|
||||
plain: true,
|
||||
incLineIndices: set.New[int](),
|
||||
}
|
||||
return presenter.format()
|
||||
}
|
||||
|
||||
func formatRangePlain(patch *Patch, startIdx int, endIdx int) string {
|
||||
lines := patch.Lines()[startIdx : endIdx+1]
|
||||
return strings.Join(
|
||||
lo.Map(lines, func(line *PatchLine, _ int) string {
|
||||
return line.Content + "\n"
|
||||
}),
|
||||
"",
|
||||
)
|
||||
}
|
||||
|
||||
type FormatViewOpts struct {
|
||||
IsFocused bool
|
||||
// first line index for selected cursor range
|
||||
FirstLineIndex int
|
||||
// last line index for selected cursor range
|
||||
LastLineIndex int
|
||||
// line indices for tagged lines (e.g. lines added to a custom patch)
|
||||
IncLineIndices *set.Set[int]
|
||||
}
|
||||
|
||||
// formats the patch for rendering within a view, meaning it's coloured and
|
||||
// highlights selected items
|
||||
func formatView(patch *Patch, opts FormatViewOpts) string {
|
||||
includedLineIndices := opts.IncLineIndices
|
||||
if includedLineIndices == nil {
|
||||
includedLineIndices = set.New[int]()
|
||||
}
|
||||
presenter := &patchPresenter{
|
||||
patch: patch,
|
||||
plain: false,
|
||||
isFocused: opts.IsFocused,
|
||||
firstLineIndex: opts.FirstLineIndex,
|
||||
lastLineIndex: opts.LastLineIndex,
|
||||
incLineIndices: includedLineIndices,
|
||||
}
|
||||
return presenter.format()
|
||||
}
|
||||
|
||||
func (self *patchPresenter) format() string {
|
||||
// if we have no changes in our patch (i.e. no additions or deletions) then
|
||||
// the patch is effectively empty and we can return an empty string
|
||||
if !self.patch.ContainsChanges() {
|
||||
return ""
|
||||
}
|
||||
|
||||
stringBuilder := &strings.Builder{}
|
||||
lineIdx := 0
|
||||
appendLine := func(line string) {
|
||||
_, _ = stringBuilder.WriteString(line + "\n")
|
||||
|
||||
lineIdx++
|
||||
}
|
||||
appendFormattedLine := func(line string, style style.TextStyle) {
|
||||
formattedLine := self.formatLine(
|
||||
line,
|
||||
style,
|
||||
lineIdx,
|
||||
)
|
||||
|
||||
appendLine(formattedLine)
|
||||
}
|
||||
|
||||
for _, line := range self.patch.header {
|
||||
appendFormattedLine(line, theme.DefaultTextColor.SetBold())
|
||||
}
|
||||
|
||||
for _, hunk := range self.patch.hunks {
|
||||
appendLine(
|
||||
self.formatLine(
|
||||
hunk.formatHeaderStart(),
|
||||
style.FgCyan,
|
||||
lineIdx,
|
||||
) +
|
||||
// we're splitting the line into two parts: the diff header and the context
|
||||
// We explicitly pass 'included' as false here so that we're only tagging the
|
||||
// first half of the line as included if the line is indeed included.
|
||||
self.formatLineAux(
|
||||
hunk.headerContext,
|
||||
theme.DefaultTextColor,
|
||||
lineIdx,
|
||||
false,
|
||||
),
|
||||
)
|
||||
|
||||
for _, line := range hunk.bodyLines {
|
||||
appendFormattedLine(line.Content, self.patchLineStyle(line))
|
||||
}
|
||||
}
|
||||
|
||||
return stringBuilder.String()
|
||||
}
|
||||
|
||||
func (self *patchPresenter) patchLineStyle(patchLine *PatchLine) style.TextStyle {
|
||||
switch patchLine.Kind {
|
||||
case ADDITION:
|
||||
return style.FgGreen
|
||||
case DELETION:
|
||||
return style.FgRed
|
||||
default:
|
||||
return theme.DefaultTextColor
|
||||
}
|
||||
}
|
||||
|
||||
func (self *patchPresenter) formatLine(str string, textStyle style.TextStyle, index int) string {
|
||||
included := self.incLineIndices.Includes(index)
|
||||
|
||||
return self.formatLineAux(str, textStyle, index, included)
|
||||
}
|
||||
|
||||
// 'selected' means you've got it highlighted with your cursor
|
||||
// 'included' means the line has been included in the patch (only applicable when
|
||||
// building a patch)
|
||||
func (self *patchPresenter) formatLineAux(str string, textStyle style.TextStyle, index int, included bool) string {
|
||||
if self.plain {
|
||||
return str
|
||||
}
|
||||
|
||||
selected := self.isFocused && index >= self.firstLineIndex && index <= self.lastLineIndex
|
||||
|
||||
if selected {
|
||||
textStyle = textStyle.MergeStyle(theme.SelectedRangeBgColor)
|
||||
}
|
||||
|
||||
firstCharStyle := textStyle
|
||||
if included {
|
||||
firstCharStyle = firstCharStyle.MergeStyle(style.BgGreen)
|
||||
}
|
||||
|
||||
if len(str) < 2 {
|
||||
return firstCharStyle.Sprint(str)
|
||||
}
|
||||
|
||||
return firstCharStyle.Sprint(str[:1]) + textStyle.Sprint(str[1:])
|
||||
}
|
||||
+49
-125
@@ -1,143 +1,67 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
import "fmt"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
// Example hunk:
|
||||
// @@ -16,2 +14,3 @@ func (f *CommitFile) Description() string {
|
||||
// return f.Name
|
||||
// -}
|
||||
// +
|
||||
// +// test
|
||||
|
||||
type PatchHunk struct {
|
||||
FirstLineIdx int
|
||||
oldStart int
|
||||
newStart int
|
||||
heading string
|
||||
bodyLines []string
|
||||
type Hunk struct {
|
||||
// the line number of the first line in the old file ('16' in the above example)
|
||||
oldStart int
|
||||
// the line number of the first line in the new file ('14' in the above example)
|
||||
newStart int
|
||||
// the context at the end of the header line (' func (f *CommitFile) Description() string {' in the above example)
|
||||
headerContext string
|
||||
// the body of the hunk, excluding the header line
|
||||
bodyLines []*PatchLine
|
||||
}
|
||||
|
||||
func (hunk *PatchHunk) LastLineIdx() int {
|
||||
return hunk.FirstLineIdx + len(hunk.bodyLines)
|
||||
// Returns the number of lines in the hunk in the original file ('2' in the above example)
|
||||
func (self *Hunk) oldLength() int {
|
||||
return nLinesWithKind(self.bodyLines, []PatchLineKind{CONTEXT, DELETION})
|
||||
}
|
||||
|
||||
func newHunk(lines []string, firstLineIdx int) *PatchHunk {
|
||||
header := lines[0]
|
||||
bodyLines := lines[1:]
|
||||
|
||||
oldStart, newStart, heading := headerInfo(header)
|
||||
|
||||
return &PatchHunk{
|
||||
oldStart: oldStart,
|
||||
newStart: newStart,
|
||||
heading: heading,
|
||||
FirstLineIdx: firstLineIdx,
|
||||
bodyLines: bodyLines,
|
||||
}
|
||||
// Returns the number of lines in the hunk in the new file ('3' in the above example)
|
||||
func (self *Hunk) newLength() int {
|
||||
return nLinesWithKind(self.bodyLines, []PatchLineKind{CONTEXT, ADDITION})
|
||||
}
|
||||
|
||||
func headerInfo(header string) (int, int, string) {
|
||||
match := hunkHeaderRegexp.FindStringSubmatch(header)
|
||||
|
||||
oldStart := utils.MustConvertToInt(match[1])
|
||||
newStart := utils.MustConvertToInt(match[2])
|
||||
heading := match[3]
|
||||
|
||||
return oldStart, newStart, heading
|
||||
// Returns true if the hunk contains any changes (i.e. if it's not just a context hunk).
|
||||
// We'll end up with a context hunk if we're transforming a patch and one of the hunks
|
||||
// has no selected lines.
|
||||
func (self *Hunk) containsChanges() bool {
|
||||
return nLinesWithKind(self.bodyLines, []PatchLineKind{ADDITION, DELETION}) > 0
|
||||
}
|
||||
|
||||
func (hunk *PatchHunk) updatedLines(lineIndices []int, reverse bool) []string {
|
||||
skippedNewlineMessageIndex := -1
|
||||
newLines := []string{}
|
||||
// Returns the number of lines in the hunk, including the header line
|
||||
func (self *Hunk) lineCount() int {
|
||||
return len(self.bodyLines) + 1
|
||||
}
|
||||
|
||||
lineIdx := hunk.FirstLineIdx
|
||||
for _, line := range hunk.bodyLines {
|
||||
lineIdx++ // incrementing at the start to skip the header line
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
isLineSelected := lo.Contains(lineIndices, lineIdx)
|
||||
// Returns all lines in the hunk, including the header line
|
||||
func (self *Hunk) allLines() []*PatchLine {
|
||||
lines := []*PatchLine{{Content: self.formatHeaderLine(), Kind: HUNK_HEADER}}
|
||||
lines = append(lines, self.bodyLines...)
|
||||
return lines
|
||||
}
|
||||
|
||||
firstChar, content := line[:1], line[1:]
|
||||
transformedFirstChar := transformedFirstChar(firstChar, reverse, isLineSelected)
|
||||
// Returns the header line, including the unified diff header and the context
|
||||
func (self *Hunk) formatHeaderLine() string {
|
||||
return fmt.Sprintf("%s%s", self.formatHeaderStart(), self.headerContext)
|
||||
}
|
||||
|
||||
if isLineSelected || (transformedFirstChar == "\\" && skippedNewlineMessageIndex != lineIdx) || transformedFirstChar == " " {
|
||||
newLines = append(newLines, transformedFirstChar+content)
|
||||
continue
|
||||
}
|
||||
|
||||
if transformedFirstChar == "+" {
|
||||
// we don't want to include the 'newline at end of file' line if it involves an addition we're not including
|
||||
skippedNewlineMessageIndex = lineIdx + 1
|
||||
}
|
||||
// Returns the first part of the header line i.e. the unified diff part (excluding any context)
|
||||
func (self *Hunk) formatHeaderStart() string {
|
||||
newLengthDisplay := ""
|
||||
newLength := self.newLength()
|
||||
// if the new length is 1, it's omitted
|
||||
if newLength != 1 {
|
||||
newLengthDisplay = fmt.Sprintf(",%d", newLength)
|
||||
}
|
||||
|
||||
return newLines
|
||||
}
|
||||
|
||||
func transformedFirstChar(firstChar string, reverse bool, isLineSelected bool) string {
|
||||
if reverse {
|
||||
if !isLineSelected && firstChar == "+" {
|
||||
return " "
|
||||
} else if firstChar == "-" {
|
||||
return "+"
|
||||
} else if firstChar == "+" {
|
||||
return "-"
|
||||
} else {
|
||||
return firstChar
|
||||
}
|
||||
}
|
||||
|
||||
if !isLineSelected && firstChar == "-" {
|
||||
return " "
|
||||
}
|
||||
|
||||
return firstChar
|
||||
}
|
||||
|
||||
func (hunk *PatchHunk) formatHeader(oldStart int, oldLength int, newStart int, newLength int, heading string) string {
|
||||
return fmt.Sprintf("@@ -%d,%d +%d,%d @@%s\n", oldStart, oldLength, newStart, newLength, heading)
|
||||
}
|
||||
|
||||
func (hunk *PatchHunk) formatWithChanges(lineIndices []int, reverse bool, startOffset int) (int, string) {
|
||||
bodyLines := hunk.updatedLines(lineIndices, reverse)
|
||||
startOffset, header, ok := hunk.updatedHeader(bodyLines, startOffset, reverse)
|
||||
if !ok {
|
||||
return startOffset, ""
|
||||
}
|
||||
return startOffset, header + strings.Join(bodyLines, "")
|
||||
}
|
||||
|
||||
func (hunk *PatchHunk) updatedHeader(newBodyLines []string, startOffset int, reverse bool) (int, string, bool) {
|
||||
changeCount := nLinesWithPrefix(newBodyLines, []string{"+", "-"})
|
||||
oldLength := nLinesWithPrefix(newBodyLines, []string{" ", "-"})
|
||||
newLength := nLinesWithPrefix(newBodyLines, []string{"+", " "})
|
||||
|
||||
if changeCount == 0 {
|
||||
// if nothing has changed we just return nothing
|
||||
return startOffset, "", false
|
||||
}
|
||||
|
||||
var oldStart int
|
||||
if reverse {
|
||||
oldStart = hunk.newStart
|
||||
} else {
|
||||
oldStart = hunk.oldStart
|
||||
}
|
||||
|
||||
var newStartOffset int
|
||||
// if the hunk went from zero to positive length, we need to increment the starting point by one
|
||||
// if the hunk went from positive to zero length, we need to decrement the starting point by one
|
||||
if oldLength == 0 {
|
||||
newStartOffset = 1
|
||||
} else if newLength == 0 {
|
||||
newStartOffset = -1
|
||||
} else {
|
||||
newStartOffset = 0
|
||||
}
|
||||
|
||||
newStart := oldStart + startOffset + newStartOffset
|
||||
|
||||
newStartOffset = startOffset + newLength - oldLength
|
||||
formattedHeader := hunk.formatHeader(oldStart, oldLength, newStart, newLength, hunk.heading)
|
||||
return newStartOffset, formattedHeader, true
|
||||
return fmt.Sprintf("@@ -%d,%d +%d%s @@", self.oldStart, self.oldLength(), self.newStart, newLengthDisplay)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
|
||||
var hunkHeaderRegexp = regexp.MustCompile(`(?m)^@@ -(\d+)[^\+]+\+(\d+)[^@]+@@(.*)$`)
|
||||
|
||||
func Parse(patchStr string) *Patch {
|
||||
// ignore trailing newline.
|
||||
lines := strings.Split(strings.TrimSuffix(patchStr, "\n"), "\n")
|
||||
|
||||
hunks := []*Hunk{}
|
||||
patchHeader := []string{}
|
||||
|
||||
var currentHunk *Hunk
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "@@") {
|
||||
oldStart, newStart, headerContext := headerInfo(line)
|
||||
|
||||
currentHunk = &Hunk{
|
||||
oldStart: oldStart,
|
||||
newStart: newStart,
|
||||
headerContext: headerContext,
|
||||
bodyLines: []*PatchLine{},
|
||||
}
|
||||
hunks = append(hunks, currentHunk)
|
||||
} else if currentHunk != nil {
|
||||
currentHunk.bodyLines = append(currentHunk.bodyLines, newHunkLine(line))
|
||||
} else {
|
||||
patchHeader = append(patchHeader, line)
|
||||
}
|
||||
}
|
||||
|
||||
return &Patch{
|
||||
hunks: hunks,
|
||||
header: patchHeader,
|
||||
}
|
||||
}
|
||||
|
||||
func headerInfo(header string) (int, int, string) {
|
||||
match := hunkHeaderRegexp.FindStringSubmatch(header)
|
||||
|
||||
oldStart := utils.MustConvertToInt(match[1])
|
||||
newStart := utils.MustConvertToInt(match[2])
|
||||
headerContext := match[3]
|
||||
|
||||
return oldStart, newStart, headerContext
|
||||
}
|
||||
|
||||
func newHunkLine(line string) *PatchLine {
|
||||
if line == "" {
|
||||
return &PatchLine{
|
||||
Kind: CONTEXT,
|
||||
Content: "",
|
||||
}
|
||||
}
|
||||
|
||||
firstChar := line[:1]
|
||||
|
||||
kind := parseFirstChar(firstChar)
|
||||
|
||||
return &PatchLine{
|
||||
Kind: kind,
|
||||
Content: line,
|
||||
}
|
||||
}
|
||||
|
||||
func parseFirstChar(firstChar string) PatchLineKind {
|
||||
switch firstChar {
|
||||
case " ":
|
||||
return CONTEXT
|
||||
case "+":
|
||||
return ADDITION
|
||||
case "-":
|
||||
return DELETION
|
||||
case "\\":
|
||||
return NEWLINE_MESSAGE
|
||||
}
|
||||
|
||||
return CONTEXT
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
type Patch struct {
|
||||
// header of the patch (split on newlines) e.g.
|
||||
// diff --git a/filename b/filename
|
||||
// index dcd3485..1ba5540 100644
|
||||
// --- a/filename
|
||||
// +++ b/filename
|
||||
header []string
|
||||
// hunks of the patch
|
||||
hunks []*Hunk
|
||||
}
|
||||
|
||||
// Returns a new patch with the specified transformation applied (e.g.
|
||||
// only selecting a subset of changes).
|
||||
// Leaves the original patch unchanged.
|
||||
func (self *Patch) Transform(opts TransformOpts) *Patch {
|
||||
return transform(self, opts)
|
||||
}
|
||||
|
||||
// Returns the patch as a plain string
|
||||
func (self *Patch) FormatPlain() string {
|
||||
return formatPlain(self)
|
||||
}
|
||||
|
||||
// Returns a range of lines from the patch as a plain string (range is inclusive)
|
||||
func (self *Patch) FormatRangePlain(startIdx int, endIdx int) string {
|
||||
return formatRangePlain(self, startIdx, endIdx)
|
||||
}
|
||||
|
||||
// Returns the patch as a string with ANSI color codes for displaying in a view
|
||||
func (self *Patch) FormatView(opts FormatViewOpts) string {
|
||||
return formatView(self, opts)
|
||||
}
|
||||
|
||||
// Returns the lines of the patch
|
||||
func (self *Patch) Lines() []*PatchLine {
|
||||
lines := []*PatchLine{}
|
||||
for _, line := range self.header {
|
||||
lines = append(lines, &PatchLine{Content: line, Kind: PATCH_HEADER})
|
||||
}
|
||||
|
||||
for _, hunk := range self.hunks {
|
||||
lines = append(lines, hunk.allLines()...)
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
// Returns the patch line index of the first line in the given hunk
|
||||
func (self *Patch) HunkStartIdx(hunkIndex int) int {
|
||||
hunkIndex = utils.Clamp(hunkIndex, 0, len(self.hunks)-1)
|
||||
|
||||
result := len(self.header)
|
||||
for i := 0; i < hunkIndex; i++ {
|
||||
result += self.hunks[i].lineCount()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Returns the patch line index of the last line in the given hunk
|
||||
func (self *Patch) HunkEndIdx(hunkIndex int) int {
|
||||
hunkIndex = utils.Clamp(hunkIndex, 0, len(self.hunks)-1)
|
||||
|
||||
return self.HunkStartIdx(hunkIndex) + self.hunks[hunkIndex].lineCount() - 1
|
||||
}
|
||||
|
||||
func (self *Patch) ContainsChanges() bool {
|
||||
return lo.SomeBy(self.hunks, func(hunk *Hunk) bool {
|
||||
return hunk.containsChanges()
|
||||
})
|
||||
}
|
||||
|
||||
// Takes a line index in the patch and returns the line number in the new file.
|
||||
// If the line is a header line, returns 1.
|
||||
// If the line is a hunk header line, returns the first file line number in that hunk.
|
||||
// If the line is out of range below, returns the last file line number in the last hunk.
|
||||
func (self *Patch) LineNumberOfLine(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.newStart + lastHunk.newLength() - 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{ADDITION, 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 {
|
||||
hunkStartIdx := self.HunkStartIdx(hunkIdx)
|
||||
if idx >= hunkStartIdx && idx < hunkStartIdx+hunk.lineCount() {
|
||||
return hunkIdx
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Returns the patch line index of the next change (i.e. addition or deletion).
|
||||
func (self *Patch) GetNextChangeIdx(idx int) int {
|
||||
idx = utils.Clamp(idx, 0, self.LineCount()-1)
|
||||
|
||||
lines := self.Lines()
|
||||
|
||||
for i, line := range lines[idx:] {
|
||||
if line.isChange() {
|
||||
return i + idx
|
||||
}
|
||||
}
|
||||
|
||||
// there are no changes from the cursor onwards so we'll instead
|
||||
// return the index of the last change
|
||||
for i := len(lines) - 1; i >= 0; i-- {
|
||||
line := lines[i]
|
||||
if line.isChange() {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
// should not be possible
|
||||
return 0
|
||||
}
|
||||
|
||||
// Returns the length of the patch in lines
|
||||
func (self *Patch) LineCount() int {
|
||||
count := len(self.header)
|
||||
for _, hunk := range self.hunks {
|
||||
count += hunk.lineCount()
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -33,8 +33,8 @@ type (
|
||||
loadFileDiffFunc func(from string, to string, reverse bool, filename string, plain bool) (string, error)
|
||||
)
|
||||
|
||||
// PatchManager manages the building of a patch for a commit to be applied to another commit (or the working tree, or removed from the current commit). We also support building patches from things like stashes, for which there is less flexibility
|
||||
type PatchManager struct {
|
||||
// PatchBuilder manages the building of a patch for a commit to be applied to another commit (or the working tree, or removed from the current commit). We also support building patches from things like stashes, for which there is less flexibility
|
||||
type PatchBuilder struct {
|
||||
// To is the commit sha if we're dealing with files of a commit, or a stash ref for a stash
|
||||
To string
|
||||
From string
|
||||
@@ -53,17 +53,16 @@ type PatchManager struct {
|
||||
loadFileDiff loadFileDiffFunc
|
||||
}
|
||||
|
||||
// NewPatchManager returns a new PatchManager
|
||||
func NewPatchManager(log *logrus.Entry, applyPatch applyPatchFunc, loadFileDiff loadFileDiffFunc) *PatchManager {
|
||||
return &PatchManager{
|
||||
// NewPatchBuilder returns a new PatchBuilder
|
||||
func NewPatchBuilder(log *logrus.Entry, applyPatch applyPatchFunc, loadFileDiff loadFileDiffFunc) *PatchBuilder {
|
||||
return &PatchBuilder{
|
||||
Log: log,
|
||||
applyPatch: applyPatch,
|
||||
loadFileDiff: loadFileDiff,
|
||||
}
|
||||
}
|
||||
|
||||
// NewPatchManager returns a new PatchManager
|
||||
func (p *PatchManager) Start(from, to string, reverse bool, canRebase bool) {
|
||||
func (p *PatchBuilder) Start(from, to string, reverse bool, canRebase bool) {
|
||||
p.To = to
|
||||
p.From = from
|
||||
p.reverse = reverse
|
||||
@@ -71,7 +70,7 @@ func (p *PatchManager) Start(from, to string, reverse bool, canRebase bool) {
|
||||
p.fileInfoMap = map[string]*fileInfo{}
|
||||
}
|
||||
|
||||
func (p *PatchManager) addFileWhole(info *fileInfo) {
|
||||
func (p *PatchBuilder) addFileWhole(info *fileInfo) {
|
||||
info.mode = WHOLE
|
||||
lineCount := len(strings.Split(info.diff, "\n"))
|
||||
// add every line index
|
||||
@@ -82,12 +81,12 @@ func (p *PatchManager) addFileWhole(info *fileInfo) {
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PatchManager) removeFile(info *fileInfo) {
|
||||
func (p *PatchBuilder) removeFile(info *fileInfo) {
|
||||
info.mode = UNSELECTED
|
||||
info.includedLineIndices = nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) AddFileWhole(filename string) error {
|
||||
func (p *PatchBuilder) AddFileWhole(filename string) error {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -98,7 +97,7 @@ func (p *PatchManager) AddFileWhole(filename string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) RemoveFile(filename string) error {
|
||||
func (p *PatchBuilder) RemoveFile(filename string) error {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -117,7 +116,7 @@ func getIndicesForRange(first, last int) []int {
|
||||
return indices
|
||||
}
|
||||
|
||||
func (p *PatchManager) getFileInfo(filename string) (*fileInfo, error) {
|
||||
func (p *PatchBuilder) getFileInfo(filename string) (*fileInfo, error) {
|
||||
info, ok := p.fileInfoMap[filename]
|
||||
if ok {
|
||||
return info, nil
|
||||
@@ -137,7 +136,7 @@ func (p *PatchManager) getFileInfo(filename string) (*fileInfo, error) {
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) AddFileLineRange(filename string, firstLineIdx, lastLineIdx int) error {
|
||||
func (p *PatchBuilder) AddFileLineRange(filename string, firstLineIdx, lastLineIdx int) error {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -148,7 +147,7 @@ func (p *PatchManager) AddFileLineRange(filename string, firstLineIdx, lastLineI
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) RemoveFileLineRange(filename string, firstLineIdx, lastLineIdx int) error {
|
||||
func (p *PatchBuilder) RemoveFileLineRange(filename string, firstLineIdx, lastLineIdx int) error {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -162,44 +161,46 @@ func (p *PatchManager) RemoveFileLineRange(filename string, firstLineIdx, lastLi
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) renderPlainPatchForFile(filename string, reverse bool, keepOriginalHeader bool) string {
|
||||
func (p *PatchBuilder) RenderPatchForFile(filename string, plain bool, reverse bool) string {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
p.Log.Error(err)
|
||||
return ""
|
||||
}
|
||||
|
||||
switch info.mode {
|
||||
case WHOLE:
|
||||
// use the whole diff
|
||||
// the reverse flag is only for part patches so we're ignoring it here
|
||||
return info.diff
|
||||
case PART:
|
||||
// generate a new diff with just the selected lines
|
||||
return ModifiedPatchForLines(p.Log, filename, info.diff, info.includedLineIndices, reverse, keepOriginalHeader)
|
||||
default:
|
||||
if info.mode == UNSELECTED {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PatchManager) RenderPatchForFile(filename string, plain bool, reverse bool, keepOriginalHeader bool) string {
|
||||
patch := p.renderPlainPatchForFile(filename, reverse, keepOriginalHeader)
|
||||
if plain {
|
||||
return patch
|
||||
if info.mode == WHOLE && plain {
|
||||
// Use the whole diff (spares us parsing it and then formatting it).
|
||||
// TODO: see if this is actually noticeably faster.
|
||||
// The reverse flag is only for part patches so we're ignoring it here.
|
||||
return info.diff
|
||||
}
|
||||
parser := NewPatchParser(p.Log, patch)
|
||||
|
||||
// not passing included lines because we don't want to see them in the secondary panel
|
||||
return parser.Render(false, -1, -1, nil)
|
||||
patch := Parse(info.diff).
|
||||
Transform(TransformOpts{
|
||||
Reverse: reverse,
|
||||
IncludedLineIndices: info.includedLineIndices,
|
||||
})
|
||||
|
||||
if plain {
|
||||
return patch.FormatPlain()
|
||||
} else {
|
||||
return patch.FormatView(FormatViewOpts{
|
||||
IsFocused: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PatchManager) renderEachFilePatch(plain bool) []string {
|
||||
func (p *PatchBuilder) renderEachFilePatch(plain bool) []string {
|
||||
// sort files by name then iterate through and render each patch
|
||||
filenames := maps.Keys(p.fileInfoMap)
|
||||
|
||||
sort.Strings(filenames)
|
||||
patches := slices.Map(filenames, func(filename string) string {
|
||||
return p.RenderPatchForFile(filename, plain, false, true)
|
||||
return p.RenderPatchForFile(filename, plain, false)
|
||||
})
|
||||
output := slices.Filter(patches, func(patch string) bool {
|
||||
return patch != ""
|
||||
@@ -208,17 +209,11 @@ func (p *PatchManager) renderEachFilePatch(plain bool) []string {
|
||||
return output
|
||||
}
|
||||
|
||||
func (p *PatchManager) RenderAggregatedPatchColored(plain bool) string {
|
||||
result := ""
|
||||
for _, patch := range p.renderEachFilePatch(plain) {
|
||||
if patch != "" {
|
||||
result += patch + "\n"
|
||||
}
|
||||
}
|
||||
return result
|
||||
func (p *PatchBuilder) RenderAggregatedPatch(plain bool) string {
|
||||
return strings.Join(p.renderEachFilePatch(plain), "")
|
||||
}
|
||||
|
||||
func (p *PatchManager) GetFileStatus(filename string, parent string) PatchStatus {
|
||||
func (p *PatchBuilder) GetFileStatus(filename string, parent string) PatchStatus {
|
||||
if parent != p.To {
|
||||
return UNSELECTED
|
||||
}
|
||||
@@ -231,7 +226,7 @@ func (p *PatchManager) GetFileStatus(filename string, parent string) PatchStatus
|
||||
return info.mode
|
||||
}
|
||||
|
||||
func (p *PatchManager) GetFileIncLineIndices(filename string) ([]int, error) {
|
||||
func (p *PatchBuilder) GetFileIncLineIndices(filename string) ([]int, error) {
|
||||
info, err := p.getFileInfo(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -239,56 +234,36 @@ func (p *PatchManager) GetFileIncLineIndices(filename string) ([]int, error) {
|
||||
return info.includedLineIndices, nil
|
||||
}
|
||||
|
||||
func (p *PatchManager) ApplyPatches(reverse bool) error {
|
||||
// for whole patches we'll apply the patch in reverse
|
||||
// but for part patches we'll apply a reverse patch forwards
|
||||
func (p *PatchBuilder) ApplyPatches(reverse bool) error {
|
||||
patch := ""
|
||||
|
||||
applyFlags := []string{"index", "3way"}
|
||||
if reverse {
|
||||
applyFlags = append(applyFlags, "reverse")
|
||||
}
|
||||
|
||||
for filename, info := range p.fileInfoMap {
|
||||
if info.mode == UNSELECTED {
|
||||
continue
|
||||
}
|
||||
|
||||
applyFlags := []string{"index", "3way"}
|
||||
reverseOnGenerate := false
|
||||
if reverse {
|
||||
if info.mode == WHOLE {
|
||||
applyFlags = append(applyFlags, "reverse")
|
||||
} else {
|
||||
reverseOnGenerate = true
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
// first run we try with the original header, then without
|
||||
for _, keepOriginalHeader := range []bool{true, false} {
|
||||
patch := p.RenderPatchForFile(filename, true, reverseOnGenerate, keepOriginalHeader)
|
||||
if patch == "" {
|
||||
continue
|
||||
}
|
||||
if err = p.applyPatch(patch, applyFlags...); err != nil {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
patch += p.RenderPatchForFile(filename, true, reverse)
|
||||
}
|
||||
|
||||
return nil
|
||||
return p.applyPatch(patch, applyFlags...)
|
||||
}
|
||||
|
||||
// clears the patch
|
||||
func (p *PatchManager) Reset() {
|
||||
func (p *PatchBuilder) Reset() {
|
||||
p.To = ""
|
||||
p.fileInfoMap = map[string]*fileInfo{}
|
||||
}
|
||||
|
||||
func (p *PatchManager) Active() bool {
|
||||
func (p *PatchBuilder) Active() bool {
|
||||
return p.To != ""
|
||||
}
|
||||
|
||||
func (p *PatchManager) IsEmpty() bool {
|
||||
func (p *PatchBuilder) IsEmpty() bool {
|
||||
for _, fileInfo := range p.fileInfoMap {
|
||||
if fileInfo.mode == WHOLE || (fileInfo.mode == PART && len(fileInfo.includedLineIndices) > 0) {
|
||||
return false
|
||||
@@ -299,6 +274,16 @@ func (p *PatchManager) IsEmpty() bool {
|
||||
}
|
||||
|
||||
// if any of these things change we'll need to reset and start a new patch
|
||||
func (p *PatchManager) NewPatchRequired(from string, to string, reverse bool) bool {
|
||||
func (p *PatchBuilder) NewPatchRequired(from string, to string, reverse bool) bool {
|
||||
return from != p.From || to != p.To || reverse != p.reverse
|
||||
}
|
||||
|
||||
func (p *PatchBuilder) AllFilesInPatch() []string {
|
||||
files := make([]string, 0, len(p.fileInfoMap))
|
||||
|
||||
for filename := range p.fileInfoMap {
|
||||
files = append(files, filename)
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package patch
|
||||
|
||||
import "github.com/samber/lo"
|
||||
|
||||
type PatchLineKind int
|
||||
|
||||
const (
|
||||
PATCH_HEADER PatchLineKind = iota
|
||||
HUNK_HEADER
|
||||
ADDITION
|
||||
DELETION
|
||||
CONTEXT
|
||||
NEWLINE_MESSAGE
|
||||
)
|
||||
|
||||
type PatchLine struct {
|
||||
Kind PatchLineKind
|
||||
Content string // something like '+ hello' (note the first character is not removed)
|
||||
}
|
||||
|
||||
func (self *PatchLine) isChange() bool {
|
||||
return self.Kind == ADDITION || self.Kind == DELETION
|
||||
}
|
||||
|
||||
// Returns the number of lines in the given slice that have one of the given kinds
|
||||
func nLinesWithKind(lines []*PatchLine, kinds []PatchLineKind) int {
|
||||
return lo.CountBy(lines, func(line *PatchLine) bool {
|
||||
return lo.Contains(kinds, line.Kind)
|
||||
})
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
hunkHeaderRegexp = regexp.MustCompile(`(?m)^@@ -(\d+)[^\+]+\+(\d+)[^@]+@@(.*)$`)
|
||||
patchHeaderRegexp = regexp.MustCompile(`(?ms)(^diff.*?)^@@`)
|
||||
)
|
||||
|
||||
func GetHeaderFromDiff(diff string) string {
|
||||
match := patchHeaderRegexp.FindStringSubmatch(diff)
|
||||
if len(match) <= 1 {
|
||||
return ""
|
||||
}
|
||||
return match[1]
|
||||
}
|
||||
|
||||
func GetHunksFromDiff(diff string) []*PatchHunk {
|
||||
hunks := []*PatchHunk{}
|
||||
firstLineIdx := -1
|
||||
var hunkLines []string //nolint:prealloc
|
||||
pastDiffHeader := false
|
||||
|
||||
for lineIdx, line := range strings.SplitAfter(diff, "\n") {
|
||||
isHunkHeader := strings.HasPrefix(line, "@@ -")
|
||||
|
||||
if isHunkHeader {
|
||||
if pastDiffHeader { // we need to persist the current hunk
|
||||
hunks = append(hunks, newHunk(hunkLines, firstLineIdx))
|
||||
}
|
||||
pastDiffHeader = true
|
||||
firstLineIdx = lineIdx
|
||||
hunkLines = []string{line}
|
||||
continue
|
||||
}
|
||||
|
||||
if !pastDiffHeader { // skip through the stuff that precedes the first hunk
|
||||
continue
|
||||
}
|
||||
|
||||
hunkLines = append(hunkLines, line)
|
||||
}
|
||||
|
||||
if pastDiffHeader {
|
||||
hunks = append(hunks, newHunk(hunkLines, firstLineIdx))
|
||||
}
|
||||
|
||||
return hunks
|
||||
}
|
||||
|
||||
type PatchModifier struct {
|
||||
Log *logrus.Entry
|
||||
filename string
|
||||
hunks []*PatchHunk
|
||||
header string
|
||||
}
|
||||
|
||||
func NewPatchModifier(log *logrus.Entry, filename string, diffText string) *PatchModifier {
|
||||
return &PatchModifier{
|
||||
Log: log,
|
||||
filename: filename,
|
||||
hunks: GetHunksFromDiff(diffText),
|
||||
header: GetHeaderFromDiff(diffText),
|
||||
}
|
||||
}
|
||||
|
||||
func (d *PatchModifier) ModifiedPatchForLines(lineIndices []int, reverse bool, keepOriginalHeader bool) string {
|
||||
// step one is getting only those hunks which we care about
|
||||
hunksInRange := []*PatchHunk{}
|
||||
outer:
|
||||
for _, hunk := range d.hunks {
|
||||
// if there is any line in our lineIndices array that the hunk contains, we append it
|
||||
for _, lineIdx := range lineIndices {
|
||||
if lineIdx >= hunk.FirstLineIdx && lineIdx <= hunk.LastLineIdx() {
|
||||
hunksInRange = append(hunksInRange, hunk)
|
||||
continue outer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// step 2 is collecting all the hunks with new headers
|
||||
startOffset := 0
|
||||
formattedHunks := ""
|
||||
var formattedHunk string
|
||||
for _, hunk := range hunksInRange {
|
||||
startOffset, formattedHunk = hunk.formatWithChanges(lineIndices, reverse, startOffset)
|
||||
formattedHunks += formattedHunk
|
||||
}
|
||||
|
||||
if formattedHunks == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
var fileHeader string
|
||||
// for staging/unstaging lines we don't want the original header because
|
||||
// it makes git confused e.g. when dealing with deleted/added files
|
||||
// but with building and applying patches the original header gives git
|
||||
// information it needs to cleanly apply patches
|
||||
if keepOriginalHeader {
|
||||
fileHeader = d.header
|
||||
} else {
|
||||
fileHeader = fmt.Sprintf("--- a/%s\n+++ b/%s\n", d.filename, d.filename)
|
||||
}
|
||||
|
||||
return fileHeader + formattedHunks
|
||||
}
|
||||
|
||||
func (d *PatchModifier) ModifiedPatchForRange(firstLineIdx int, lastLineIdx int, reverse bool, keepOriginalHeader bool) string {
|
||||
// generate array of consecutive line indices from our range
|
||||
selectedLines := []int{}
|
||||
for i := firstLineIdx; i <= lastLineIdx; i++ {
|
||||
selectedLines = append(selectedLines, i)
|
||||
}
|
||||
return d.ModifiedPatchForLines(selectedLines, reverse, keepOriginalHeader)
|
||||
}
|
||||
|
||||
func (d *PatchModifier) OriginalPatchLength() int {
|
||||
if len(d.hunks) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return d.hunks[len(d.hunks)-1].LastLineIdx()
|
||||
}
|
||||
|
||||
func ModifiedPatchForRange(log *logrus.Entry, filename string, diffText string, firstLineIdx int, lastLineIdx int, reverse bool, keepOriginalHeader bool) string {
|
||||
p := NewPatchModifier(log, filename, diffText)
|
||||
return p.ModifiedPatchForRange(firstLineIdx, lastLineIdx, reverse, keepOriginalHeader)
|
||||
}
|
||||
|
||||
func ModifiedPatchForLines(log *logrus.Entry, filename string, diffText string, includedLineIndices []int, reverse bool, keepOriginalHeader bool) string {
|
||||
p := NewPatchModifier(log, filename, diffText)
|
||||
return p.ModifiedPatchForLines(includedLineIndices, reverse, keepOriginalHeader)
|
||||
}
|
||||
|
||||
// I want to know, given a hunk, what line a given index is on
|
||||
func (hunk *PatchHunk) LineNumberOfLine(idx int) int {
|
||||
n := idx - hunk.FirstLineIdx - 1
|
||||
if n < 0 {
|
||||
n = 0
|
||||
} else if n >= len(hunk.bodyLines) {
|
||||
n = len(hunk.bodyLines) - 1
|
||||
}
|
||||
|
||||
lines := hunk.bodyLines[0:n]
|
||||
|
||||
offset := nLinesWithPrefix(lines, []string{"+", " "})
|
||||
|
||||
return hunk.newStart + offset
|
||||
}
|
||||
|
||||
func nLinesWithPrefix(lines []string, chars []string) int {
|
||||
result := 0
|
||||
for _, line := range lines {
|
||||
for _, char := range chars {
|
||||
if line[:1] == char {
|
||||
result++
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/generics/slices"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/style"
|
||||
"github.com/jesseduffield/lazygit/pkg/theme"
|
||||
"github.com/samber/lo"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type PatchLineKind int
|
||||
|
||||
const (
|
||||
PATCH_HEADER PatchLineKind = iota
|
||||
COMMIT_SHA
|
||||
COMMIT_DESCRIPTION
|
||||
HUNK_HEADER
|
||||
ADDITION
|
||||
DELETION
|
||||
CONTEXT
|
||||
NEWLINE_MESSAGE
|
||||
)
|
||||
|
||||
// the job of this file is to parse a diff, find out where the hunks begin and end, which lines are stageable, and how to find the next hunk from the current position or the next stageable line from the current position.
|
||||
|
||||
type PatchLine struct {
|
||||
Kind PatchLineKind
|
||||
Content string // something like '+ hello' (note the first character is not removed)
|
||||
}
|
||||
|
||||
type PatchParser struct {
|
||||
Log *logrus.Entry
|
||||
PatchLines []*PatchLine
|
||||
PatchHunks []*PatchHunk
|
||||
HunkStarts []int
|
||||
StageableLines []int // rename to mention we're talking about indexes
|
||||
}
|
||||
|
||||
// NewPatchParser builds a new branch list builder
|
||||
func NewPatchParser(log *logrus.Entry, patch string) *PatchParser {
|
||||
hunkStarts, stageableLines, patchLines := parsePatch(patch)
|
||||
|
||||
patchHunks := GetHunksFromDiff(patch)
|
||||
|
||||
return &PatchParser{
|
||||
Log: log,
|
||||
HunkStarts: hunkStarts, // deprecated
|
||||
StageableLines: stageableLines,
|
||||
PatchLines: patchLines,
|
||||
PatchHunks: patchHunks,
|
||||
}
|
||||
}
|
||||
|
||||
// GetHunkContainingLine takes a line index and an offset and finds the hunk
|
||||
// which contains the line index, then returns the hunk considering the offset.
|
||||
// e.g. if the offset is 1 it will return the next hunk.
|
||||
func (p *PatchParser) GetHunkContainingLine(lineIndex int, offset int) *PatchHunk {
|
||||
if len(p.PatchHunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for index, hunk := range p.PatchHunks {
|
||||
if lineIndex >= hunk.FirstLineIdx && lineIndex <= hunk.LastLineIdx() {
|
||||
resultIndex := index + offset
|
||||
if resultIndex < 0 {
|
||||
resultIndex = 0
|
||||
} else if resultIndex > len(p.PatchHunks)-1 {
|
||||
resultIndex = len(p.PatchHunks) - 1
|
||||
}
|
||||
return p.PatchHunks[resultIndex]
|
||||
}
|
||||
}
|
||||
|
||||
// if your cursor is past the last hunk, select the last hunk
|
||||
if lineIndex > p.PatchHunks[len(p.PatchHunks)-1].LastLineIdx() {
|
||||
return p.PatchHunks[len(p.PatchHunks)-1]
|
||||
}
|
||||
|
||||
// otherwise select the first
|
||||
return p.PatchHunks[0]
|
||||
}
|
||||
|
||||
// selected means you've got it highlighted with your cursor
|
||||
// included means the line has been included in the patch (only applicable when
|
||||
// building a patch)
|
||||
func (l *PatchLine) render(selected bool, included bool) string {
|
||||
content := l.Content
|
||||
if len(content) == 0 {
|
||||
content = " " // using the space so that we can still highlight if necessary
|
||||
}
|
||||
|
||||
// for hunk headers we need to start off cyan and then use white for the message
|
||||
if l.Kind == HUNK_HEADER {
|
||||
re := regexp.MustCompile("(@@.*?@@)(.*)")
|
||||
match := re.FindStringSubmatch(content)
|
||||
return coloredString(style.FgCyan, match[1], selected, included) + coloredString(theme.DefaultTextColor, match[2], selected, false)
|
||||
}
|
||||
|
||||
var textStyle style.TextStyle
|
||||
switch l.Kind {
|
||||
case PATCH_HEADER:
|
||||
textStyle = textStyle.SetBold()
|
||||
case ADDITION:
|
||||
textStyle = style.FgGreen
|
||||
case DELETION:
|
||||
textStyle = style.FgRed
|
||||
case COMMIT_SHA:
|
||||
textStyle = style.FgYellow
|
||||
default:
|
||||
textStyle = theme.DefaultTextColor
|
||||
}
|
||||
|
||||
return coloredString(textStyle, content, selected, included)
|
||||
}
|
||||
|
||||
func coloredString(textStyle style.TextStyle, str string, selected bool, included bool) string {
|
||||
if selected {
|
||||
textStyle = textStyle.MergeStyle(theme.SelectedRangeBgColor)
|
||||
}
|
||||
|
||||
firstCharStyle := textStyle
|
||||
if included {
|
||||
firstCharStyle = firstCharStyle.MergeStyle(style.BgGreen)
|
||||
}
|
||||
|
||||
if len(str) < 2 {
|
||||
return firstCharStyle.Sprint(str)
|
||||
}
|
||||
|
||||
return firstCharStyle.Sprint(str[:1]) + textStyle.Sprint(str[1:])
|
||||
}
|
||||
|
||||
func parsePatch(patch string) ([]int, []int, []*PatchLine) {
|
||||
lines := strings.Split(patch, "\n")
|
||||
hunkStarts := []int{}
|
||||
stageableLines := []int{}
|
||||
pastFirstHunkHeader := false
|
||||
pastCommitDescription := true
|
||||
patchLines := make([]*PatchLine, len(lines))
|
||||
var lineKind PatchLineKind
|
||||
var firstChar string
|
||||
for index, line := range lines {
|
||||
firstChar = " "
|
||||
if len(line) > 0 {
|
||||
firstChar = line[:1]
|
||||
}
|
||||
if index == 0 && strings.HasPrefix(line, "commit") {
|
||||
lineKind = COMMIT_SHA
|
||||
pastCommitDescription = false
|
||||
} else if !pastCommitDescription {
|
||||
if strings.HasPrefix(line, "diff") || strings.HasPrefix(line, "---") {
|
||||
pastCommitDescription = true
|
||||
lineKind = PATCH_HEADER
|
||||
} else {
|
||||
lineKind = COMMIT_DESCRIPTION
|
||||
}
|
||||
} else if firstChar == "@" {
|
||||
pastFirstHunkHeader = true
|
||||
hunkStarts = append(hunkStarts, index)
|
||||
lineKind = HUNK_HEADER
|
||||
} else if pastFirstHunkHeader {
|
||||
switch firstChar {
|
||||
case "-":
|
||||
lineKind = DELETION
|
||||
stageableLines = append(stageableLines, index)
|
||||
case "+":
|
||||
lineKind = ADDITION
|
||||
stageableLines = append(stageableLines, index)
|
||||
case "\\":
|
||||
lineKind = NEWLINE_MESSAGE
|
||||
case " ":
|
||||
lineKind = CONTEXT
|
||||
}
|
||||
} else {
|
||||
lineKind = PATCH_HEADER
|
||||
}
|
||||
patchLines[index] = &PatchLine{Kind: lineKind, Content: line}
|
||||
}
|
||||
return hunkStarts, stageableLines, patchLines
|
||||
}
|
||||
|
||||
// Render returns the coloured string of the diff with any selected lines highlighted
|
||||
func (p *PatchParser) Render(isFocused bool, firstLineIndex int, lastLineIndex int, incLineIndices []int) string {
|
||||
contentToDisplay := slices.Some(p.PatchLines, func(line *PatchLine) bool {
|
||||
return line.Content != ""
|
||||
})
|
||||
if !contentToDisplay {
|
||||
return ""
|
||||
}
|
||||
|
||||
renderedLines := slices.MapWithIndex(p.PatchLines, func(patchLine *PatchLine, index int) string {
|
||||
selected := isFocused && index >= firstLineIndex && index <= lastLineIndex
|
||||
included := lo.Contains(incLineIndices, index)
|
||||
return patchLine.render(selected, included)
|
||||
})
|
||||
|
||||
result := strings.Join(renderedLines, "\n")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// RenderLinesPlain returns the non-coloured string of diff part from firstLineIndex to
|
||||
// lastLineIndex
|
||||
func (p *PatchParser) RenderLinesPlain(firstLineIndex, lastLineIndex int) string {
|
||||
return renderLinesPlain(p.PatchLines[firstLineIndex : lastLineIndex+1])
|
||||
}
|
||||
|
||||
func renderLinesPlain(lines []*PatchLine) string {
|
||||
renderedLines := slices.Map(lines, func(line *PatchLine) string {
|
||||
return line.Content + "\n"
|
||||
})
|
||||
|
||||
return strings.Join(renderedLines, "")
|
||||
}
|
||||
|
||||
// GetNextStageableLineIndex takes a line index and returns the line index of the next stageable line
|
||||
// note this will actually include the current index if it is stageable
|
||||
func (p *PatchParser) GetNextStageableLineIndex(currentIndex int) int {
|
||||
for _, lineIndex := range p.StageableLines {
|
||||
if lineIndex >= currentIndex {
|
||||
return lineIndex
|
||||
}
|
||||
}
|
||||
return p.StageableLines[len(p.StageableLines)-1]
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package patch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -69,6 +67,20 @@ index e48a11c..b2ab81b 100644
|
||||
...
|
||||
`
|
||||
|
||||
const twoChangesInOneHunk = `diff --git a/filename b/filename
|
||||
index 9320895..6d79956 100644
|
||||
--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
-grape
|
||||
+kiwi
|
||||
orange
|
||||
-pear
|
||||
+banana
|
||||
lemon
|
||||
`
|
||||
|
||||
const newFile = `diff --git a/newfile b/newfile
|
||||
new file mode 100644
|
||||
index 0000000..4e680cc
|
||||
@@ -98,8 +110,7 @@ const exampleHunk = `@@ -1,5 +1,5 @@
|
||||
...
|
||||
`
|
||||
|
||||
// TestModifyPatchForRange is a function.
|
||||
func TestModifyPatchForRange(t *testing.T) {
|
||||
func TestTransform(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
filename string
|
||||
@@ -116,7 +127,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: -1,
|
||||
lastLineIndex: -1,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: "",
|
||||
},
|
||||
@@ -125,7 +135,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 5,
|
||||
lastLineIndex: 5,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: "",
|
||||
},
|
||||
@@ -134,7 +143,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 0,
|
||||
lastLineIndex: 11,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -152,7 +160,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 6,
|
||||
lastLineIndex: 6,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -169,7 +176,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 7,
|
||||
lastLineIndex: 7,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -187,7 +193,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -198,59 +203,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "whole range reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 0,
|
||||
lastLineIndex: 11,
|
||||
reverse: true,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
+orange
|
||||
-grape
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "removal reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 6,
|
||||
lastLineIndex: 6,
|
||||
reverse: true,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,6 @@
|
||||
apple
|
||||
+orange
|
||||
grape
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "removal reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 7,
|
||||
lastLineIndex: 7,
|
||||
reverse: true,
|
||||
diffText: simpleDiff,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,4 @@
|
||||
apple
|
||||
-grape
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -258,7 +210,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: addNewlineToEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -272,37 +223,21 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "add newline to end of file, addition only",
|
||||
testName: "add newline to end of file, reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 8,
|
||||
lastLineIndex: 8,
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: true,
|
||||
diffText: addNewlineToEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -60,4 +60,5 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
+last line
|
||||
\ No newline at end of file
|
||||
last line
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "add newline to end of file, removal only",
|
||||
filename: "filename",
|
||||
firstLineIndex: 10,
|
||||
lastLineIndex: 10,
|
||||
reverse: true,
|
||||
diffText: addNewlineToEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -60,4 +60,3 @@ grape
|
||||
@@ -60,4 +60,4 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
-last line
|
||||
\ No newline at end of file
|
||||
+last line
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -310,7 +245,24 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -60,4 +60,4 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
-last line
|
||||
+last line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "remove newline from end of file, reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: true,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -328,7 +280,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 8,
|
||||
lastLineIndex: 8,
|
||||
reverse: false,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -337,6 +288,24 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
...
|
||||
...
|
||||
-last line
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "remove newline from end of file, removal only, reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 8,
|
||||
lastLineIndex: 8,
|
||||
reverse: true,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -60,5 +60,4 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
-last line
|
||||
last line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -344,7 +313,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 9,
|
||||
lastLineIndex: 9,
|
||||
reverse: false,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -355,6 +323,23 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
last line
|
||||
+last line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "remove newline from end of file, addition only, reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 9,
|
||||
lastLineIndex: 9,
|
||||
reverse: true,
|
||||
diffText: removeNewlinefromEndOfFile,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -60,3 +60,4 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
+last line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -362,7 +347,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: twoHunks,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -389,7 +373,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "filename",
|
||||
firstLineIndex: 7,
|
||||
lastLineIndex: 15,
|
||||
reverse: false,
|
||||
diffText: twoHunks,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -408,32 +391,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "staging part of both hunks, reversed",
|
||||
filename: "filename",
|
||||
firstLineIndex: 7,
|
||||
lastLineIndex: 15,
|
||||
reverse: true,
|
||||
diffText: twoHunks,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,4 @@
|
||||
apple
|
||||
-orange
|
||||
...
|
||||
...
|
||||
...
|
||||
@@ -8,8 +7,7 @@ grape
|
||||
...
|
||||
...
|
||||
...
|
||||
-pear
|
||||
lemon
|
||||
...
|
||||
...
|
||||
...
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -441,7 +398,6 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "newfile",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: newFile,
|
||||
expected: `--- a/newfile
|
||||
+++ b/newfile
|
||||
@@ -456,28 +412,12 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "newfile",
|
||||
firstLineIndex: 6,
|
||||
lastLineIndex: 7,
|
||||
reverse: false,
|
||||
diffText: newFile,
|
||||
expected: `--- a/newfile
|
||||
+++ b/newfile
|
||||
@@ -0,0 +1,2 @@
|
||||
+apple
|
||||
+orange
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "adding a new file, reversed",
|
||||
filename: "newfile",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: true,
|
||||
diffText: newFile,
|
||||
expected: `--- a/newfile
|
||||
+++ b/newfile
|
||||
@@ -1,3 +0,0 @@
|
||||
-apple
|
||||
-orange
|
||||
-grape
|
||||
`,
|
||||
},
|
||||
{
|
||||
@@ -485,11 +425,10 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "newfile",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: false,
|
||||
diffText: addNewlineToPreviouslyEmptyFile,
|
||||
expected: `--- a/newfile
|
||||
+++ b/newfile
|
||||
@@ -0,0 +1,1 @@
|
||||
@@ -0,0 +1 @@
|
||||
+new line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
@@ -499,13 +438,49 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
filename: "newfile",
|
||||
firstLineIndex: -100,
|
||||
lastLineIndex: 100,
|
||||
reverse: true,
|
||||
diffText: addNewlineToPreviouslyEmptyFile,
|
||||
reverse: true,
|
||||
expected: `--- a/newfile
|
||||
+++ b/newfile
|
||||
@@ -1,1 +0,0 @@
|
||||
-new line
|
||||
@@ -0,0 +1 @@
|
||||
+new line
|
||||
\ No newline at end of file
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "adding part of a hunk",
|
||||
filename: "filename",
|
||||
firstLineIndex: 6,
|
||||
lastLineIndex: 7,
|
||||
reverse: false,
|
||||
diffText: twoChangesInOneHunk,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
-grape
|
||||
+kiwi
|
||||
orange
|
||||
pear
|
||||
lemon
|
||||
`,
|
||||
},
|
||||
{
|
||||
testName: "adding part of a hunk, reverse",
|
||||
filename: "filename",
|
||||
firstLineIndex: 6,
|
||||
lastLineIndex: 7,
|
||||
reverse: true,
|
||||
diffText: twoChangesInOneHunk,
|
||||
expected: `--- a/filename
|
||||
+++ b/filename
|
||||
@@ -1,5 +1,5 @@
|
||||
apple
|
||||
-grape
|
||||
+kiwi
|
||||
orange
|
||||
banana
|
||||
lemon
|
||||
`,
|
||||
},
|
||||
}
|
||||
@@ -513,37 +488,128 @@ func TestModifyPatchForRange(t *testing.T) {
|
||||
for _, s := range scenarios {
|
||||
s := s
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := ModifiedPatchForRange(nil, s.filename, s.diffText, s.firstLineIndex, s.lastLineIndex, s.reverse, false)
|
||||
if !assert.Equal(t, s.expected, result) {
|
||||
fmt.Println(result)
|
||||
}
|
||||
lineIndices := ExpandRange(s.firstLineIndex, s.lastLineIndex)
|
||||
|
||||
result := Parse(s.diffText).
|
||||
Transform(TransformOpts{
|
||||
Reverse: s.reverse,
|
||||
FileNameOverride: s.filename,
|
||||
IncludedLineIndices: lineIndices,
|
||||
}).
|
||||
FormatPlain()
|
||||
|
||||
assert.Equal(t, s.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLineNumberOfLine(t *testing.T) {
|
||||
type scenario struct {
|
||||
func TestParseAndFormatPlain(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
testName string
|
||||
hunk *PatchHunk
|
||||
idx int
|
||||
expected int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
patchStr string
|
||||
}{
|
||||
{
|
||||
testName: "nothing selected",
|
||||
hunk: newHunk(strings.SplitAfter(exampleHunk, "\n"), 10),
|
||||
idx: 15,
|
||||
expected: 3,
|
||||
testName: "simpleDiff",
|
||||
patchStr: simpleDiff,
|
||||
},
|
||||
{
|
||||
testName: "addNewlineToEndOfFile",
|
||||
patchStr: addNewlineToEndOfFile,
|
||||
},
|
||||
{
|
||||
testName: "removeNewlinefromEndOfFile",
|
||||
patchStr: removeNewlinefromEndOfFile,
|
||||
},
|
||||
{
|
||||
testName: "twoHunks",
|
||||
patchStr: twoHunks,
|
||||
},
|
||||
{
|
||||
testName: "twoChangesInOneHunk",
|
||||
patchStr: twoChangesInOneHunk,
|
||||
},
|
||||
{
|
||||
testName: "newFile",
|
||||
patchStr: newFile,
|
||||
},
|
||||
{
|
||||
testName: "addNewlineToPreviouslyEmptyFile",
|
||||
patchStr: addNewlineToPreviouslyEmptyFile,
|
||||
},
|
||||
{
|
||||
testName: "exampleHunk",
|
||||
patchStr: exampleHunk,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
s := s
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
result := s.hunk.LineNumberOfLine(s.idx)
|
||||
if !assert.Equal(t, s.expected, result) {
|
||||
fmt.Println(result)
|
||||
// here we parse the patch, then format it, and ensure the result
|
||||
// matches the original patch. Note that unified diffs allow omitting
|
||||
// the new length in a hunk header if the value is 1, and currently we always
|
||||
// omit the new length in such cases.
|
||||
patch := Parse(s.patchStr)
|
||||
result := formatPlain(patch)
|
||||
assert.Equal(t, s.patchStr, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLineNumberOfLine(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
patchStr string
|
||||
indexes []int
|
||||
expecteds []int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "twoHunks",
|
||||
patchStr: twoHunks,
|
||||
// this is really more of a characteristic test than anything.
|
||||
indexes: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 1000},
|
||||
expecteds: []int{1, 1, 1, 1, 1, 1, 2, 2, 3, 4, 5, 8, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 15, 15, 15},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
s := s
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
for i, idx := range s.indexes {
|
||||
patch := Parse(s.patchStr)
|
||||
result := patch.LineNumberOfLine(idx)
|
||||
assert.Equal(t, s.expecteds[i], result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNextStageableLineIndex(t *testing.T) {
|
||||
type scenario struct {
|
||||
testName string
|
||||
patchStr string
|
||||
indexes []int
|
||||
expecteds []int
|
||||
}
|
||||
|
||||
scenarios := []scenario{
|
||||
{
|
||||
testName: "twoHunks",
|
||||
patchStr: twoHunks,
|
||||
indexes: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 1000},
|
||||
expecteds: []int{6, 6, 6, 6, 6, 6, 6, 7, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
s := s
|
||||
t.Run(s.testName, func(t *testing.T) {
|
||||
for i, idx := range s.indexes {
|
||||
patch := Parse(s.patchStr)
|
||||
result := patch.GetNextChangeIdx(idx)
|
||||
assert.Equal(t, s.expecteds[i], result)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package patch
|
||||
|
||||
import "github.com/samber/lo"
|
||||
|
||||
type patchTransformer struct {
|
||||
patch *Patch
|
||||
opts TransformOpts
|
||||
}
|
||||
|
||||
type TransformOpts struct {
|
||||
// Create a patch that will applied in reverse with `git apply --reverse`.
|
||||
// This affects how unselected lines are treated when only parts of a hunk
|
||||
// are selected: usually, for unselected lines we change '-' lines to
|
||||
// context lines and remove '+' lines, but when Reverse is true we need to
|
||||
// turn '+' lines into context lines and remove '-' lines.
|
||||
Reverse bool
|
||||
|
||||
// If set, we will replace the original header with one referring to this file name.
|
||||
// For staging/unstaging lines we don't want the original header because
|
||||
// it makes git confused e.g. when dealing with deleted/added files
|
||||
// but with building and applying patches the original header gives git
|
||||
// information it needs to cleanly apply patches
|
||||
FileNameOverride string
|
||||
|
||||
// The indices of lines that should be included in the patch.
|
||||
IncludedLineIndices []int
|
||||
}
|
||||
|
||||
func transform(patch *Patch, opts TransformOpts) *Patch {
|
||||
transformer := &patchTransformer{
|
||||
patch: patch,
|
||||
opts: opts,
|
||||
}
|
||||
|
||||
return transformer.transform()
|
||||
}
|
||||
|
||||
// helper function that takes a start and end index and returns a slice of all
|
||||
// indexes inbetween (inclusive)
|
||||
func ExpandRange(start int, end int) []int {
|
||||
expanded := []int{}
|
||||
for i := start; i <= end; i++ {
|
||||
expanded = append(expanded, i)
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transform() *Patch {
|
||||
header := self.transformHeader()
|
||||
hunks := self.transformHunks()
|
||||
|
||||
return &Patch{
|
||||
header: header,
|
||||
hunks: hunks,
|
||||
}
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transformHeader() []string {
|
||||
if self.opts.FileNameOverride != "" {
|
||||
return []string{
|
||||
"--- a/" + self.opts.FileNameOverride,
|
||||
"+++ b/" + self.opts.FileNameOverride,
|
||||
}
|
||||
} else {
|
||||
return self.patch.header
|
||||
}
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transformHunks() []*Hunk {
|
||||
newHunks := make([]*Hunk, 0, len(self.patch.hunks))
|
||||
|
||||
startOffset := 0
|
||||
var formattedHunk *Hunk
|
||||
for i, hunk := range self.patch.hunks {
|
||||
startOffset, formattedHunk = self.transformHunk(
|
||||
hunk,
|
||||
startOffset,
|
||||
self.patch.HunkStartIdx(i),
|
||||
)
|
||||
if formattedHunk.containsChanges() {
|
||||
newHunks = append(newHunks, formattedHunk)
|
||||
}
|
||||
}
|
||||
|
||||
return newHunks
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transformHunk(hunk *Hunk, startOffset int, firstLineIdx int) (int, *Hunk) {
|
||||
newLines := self.transformHunkLines(hunk, firstLineIdx)
|
||||
newNewStart, newStartOffset := self.transformHunkHeader(newLines, hunk.oldStart, startOffset)
|
||||
|
||||
newHunk := &Hunk{
|
||||
bodyLines: newLines,
|
||||
oldStart: hunk.oldStart,
|
||||
newStart: newNewStart,
|
||||
headerContext: hunk.headerContext,
|
||||
}
|
||||
|
||||
return newStartOffset, newHunk
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transformHunkLines(hunk *Hunk, firstLineIdx int) []*PatchLine {
|
||||
skippedNewlineMessageIndex := -1
|
||||
newLines := []*PatchLine{}
|
||||
|
||||
for i, line := range hunk.bodyLines {
|
||||
lineIdx := i + firstLineIdx + 1 // plus one for header line
|
||||
if line.Content == "" {
|
||||
break
|
||||
}
|
||||
isLineSelected := lo.Contains(self.opts.IncludedLineIndices, lineIdx)
|
||||
|
||||
if isLineSelected || (line.Kind == NEWLINE_MESSAGE && skippedNewlineMessageIndex != lineIdx) || line.Kind == CONTEXT {
|
||||
newLines = append(newLines, line)
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.Kind == DELETION && !self.opts.Reverse) || (line.Kind == ADDITION && self.opts.Reverse) {
|
||||
content := " " + line.Content[1:]
|
||||
newLines = append(newLines, &PatchLine{
|
||||
Kind: CONTEXT,
|
||||
Content: content,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if line.Kind == ADDITION {
|
||||
// we don't want to include the 'newline at end of file' line if it involves an addition we're not including
|
||||
skippedNewlineMessageIndex = lineIdx + 1
|
||||
}
|
||||
}
|
||||
|
||||
return newLines
|
||||
}
|
||||
|
||||
func (self *patchTransformer) transformHunkHeader(newBodyLines []*PatchLine, oldStart int, startOffset int) (int, int) {
|
||||
oldLength := nLinesWithKind(newBodyLines, []PatchLineKind{CONTEXT, DELETION})
|
||||
newLength := nLinesWithKind(newBodyLines, []PatchLineKind{CONTEXT, ADDITION})
|
||||
|
||||
var newStartOffset int
|
||||
// if the hunk went from zero to positive length, we need to increment the starting point by one
|
||||
// if the hunk went from positive to zero length, we need to decrement the starting point by one
|
||||
if oldLength == 0 {
|
||||
newStartOffset = 1
|
||||
} else if newLength == 0 {
|
||||
newStartOffset = -1
|
||||
} else {
|
||||
newStartOffset = 0
|
||||
}
|
||||
|
||||
newStart := oldStart + startOffset + newStartOffset
|
||||
|
||||
newStartOffset = startOffset + newLength - oldLength
|
||||
|
||||
return newStart, newStartOffset
|
||||
}
|
||||
@@ -6,9 +6,7 @@ package config
|
||||
// GetPlatformDefaultConfig gets the defaults for the platform
|
||||
func GetPlatformDefaultConfig() OSConfig {
|
||||
return OSConfig{
|
||||
EditCommand: ``,
|
||||
EditCommandTemplate: "",
|
||||
OpenCommand: "open -- {{filename}}",
|
||||
OpenLinkCommand: "open {{link}}",
|
||||
Open: "open -- {{filename}}",
|
||||
OpenLink: "open {{link}}",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -10,21 +11,31 @@ func isWSL() bool {
|
||||
return err == nil && strings.Contains(string(data), "microsoft")
|
||||
}
|
||||
|
||||
func isContainer() bool {
|
||||
data, err := ioutil.ReadFile("/proc/1/cgroup")
|
||||
|
||||
if strings.Contains(string(data), "docker") ||
|
||||
strings.Contains(string(data), "/lxc/") ||
|
||||
[]string{string(data)}[0] != "systemd" &&
|
||||
[]string{string(data)}[0] != "init" ||
|
||||
os.Getenv("container") != "" {
|
||||
return err == nil && true
|
||||
}
|
||||
|
||||
return err == nil && false
|
||||
}
|
||||
|
||||
// GetPlatformDefaultConfig gets the defaults for the platform
|
||||
func GetPlatformDefaultConfig() OSConfig {
|
||||
if isWSL() {
|
||||
if isWSL() && !isContainer() {
|
||||
return OSConfig{
|
||||
EditCommand: ``,
|
||||
EditCommandTemplate: "",
|
||||
OpenCommand: `powershell.exe start explorer.exe {{filename}} >/dev/null`,
|
||||
OpenLinkCommand: `powershell.exe start {{link}} >/dev/null`,
|
||||
Open: `powershell.exe start explorer.exe {{filename}} >/dev/null`,
|
||||
OpenLink: `powershell.exe start {{link}} >/dev/null`,
|
||||
}
|
||||
}
|
||||
|
||||
return OSConfig{
|
||||
EditCommand: ``,
|
||||
EditCommandTemplate: "",
|
||||
OpenCommand: `xdg-open {{filename}} >/dev/null`,
|
||||
OpenLinkCommand: `xdg-open {{link}} >/dev/null`,
|
||||
Open: `xdg-open {{filename}} >/dev/null`,
|
||||
OpenLink: `xdg-open {{link}} >/dev/null`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,7 @@ package config
|
||||
// GetPlatformDefaultConfig gets the defaults for the platform
|
||||
func GetPlatformDefaultConfig() OSConfig {
|
||||
return OSConfig{
|
||||
EditCommand: ``,
|
||||
EditCommandTemplate: "",
|
||||
OpenCommand: `start "" {{filename}}`,
|
||||
OpenLinkCommand: `start "" {{link}}`,
|
||||
Open: `start "" {{filename}}`,
|
||||
OpenLink: `start "" {{link}}`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package config
|
||||
|
||||
func GetEditTemplate(osConfig *OSConfig, guessDefaultEditor func() string) (string, bool) {
|
||||
preset := getPreset(osConfig, guessDefaultEditor)
|
||||
template := osConfig.Edit
|
||||
if template == "" {
|
||||
template = preset.editTemplate
|
||||
}
|
||||
|
||||
return template, getEditInTerminal(osConfig, preset)
|
||||
}
|
||||
|
||||
func GetEditAtLineTemplate(osConfig *OSConfig, guessDefaultEditor func() string) (string, bool) {
|
||||
preset := getPreset(osConfig, guessDefaultEditor)
|
||||
template := osConfig.EditAtLine
|
||||
if template == "" {
|
||||
template = preset.editAtLineTemplate
|
||||
}
|
||||
return template, getEditInTerminal(osConfig, preset)
|
||||
}
|
||||
|
||||
func GetEditAtLineAndWaitTemplate(osConfig *OSConfig, guessDefaultEditor func() string) string {
|
||||
preset := getPreset(osConfig, guessDefaultEditor)
|
||||
template := osConfig.EditAtLineAndWait
|
||||
if template == "" {
|
||||
template = preset.editAtLineAndWaitTemplate
|
||||
}
|
||||
return template
|
||||
}
|
||||
|
||||
type editPreset struct {
|
||||
editTemplate string
|
||||
editAtLineTemplate string
|
||||
editAtLineAndWaitTemplate string
|
||||
editInTerminal bool
|
||||
}
|
||||
|
||||
func getPreset(osConfig *OSConfig, guessDefaultEditor func() string) *editPreset {
|
||||
presets := map[string]*editPreset{
|
||||
"vi": standardTerminalEditorPreset("vi"),
|
||||
"vim": standardTerminalEditorPreset("vim"),
|
||||
"nvim": standardTerminalEditorPreset("nvim"),
|
||||
"emacs": standardTerminalEditorPreset("emacs"),
|
||||
"nano": standardTerminalEditorPreset("nano"),
|
||||
"vscode": {
|
||||
editTemplate: "code --reuse-window -- {{filename}}",
|
||||
editAtLineTemplate: "code --reuse-window --goto -- {{filename}}:{{line}}",
|
||||
editAtLineAndWaitTemplate: "code --reuse-window --goto --wait -- {{filename}}:{{line}}",
|
||||
editInTerminal: false,
|
||||
},
|
||||
"sublime": {
|
||||
editTemplate: "subl -- {{filename}}",
|
||||
editAtLineTemplate: "subl -- {{filename}}:{{line}}",
|
||||
editAtLineAndWaitTemplate: "subl --wait -- {{filename}}:{{line}}",
|
||||
editInTerminal: false,
|
||||
},
|
||||
"bbedit": {
|
||||
editTemplate: "bbedit -- {{filename}}",
|
||||
editAtLineTemplate: "bbedit +{{line}} -- {{filename}}",
|
||||
editAtLineAndWaitTemplate: "bbedit +{{line}} --wait -- {{filename}}",
|
||||
editInTerminal: false,
|
||||
},
|
||||
"xcode": {
|
||||
editTemplate: "xed -- {{filename}}",
|
||||
editAtLineTemplate: "xed --line {{line}} -- {{filename}}",
|
||||
editAtLineAndWaitTemplate: "xed --line {{line}} --wait -- {{filename}}",
|
||||
editInTerminal: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Some of our presets have a different name than the editor they are using.
|
||||
editorToPreset := map[string]string{
|
||||
"code": "vscode",
|
||||
"subl": "sublime",
|
||||
"xed": "xcode",
|
||||
}
|
||||
|
||||
presetName := osConfig.EditPreset
|
||||
if presetName == "" {
|
||||
defaultEditor := guessDefaultEditor()
|
||||
if presets[defaultEditor] != nil {
|
||||
presetName = defaultEditor
|
||||
} else if p := editorToPreset[defaultEditor]; p != "" {
|
||||
presetName = p
|
||||
}
|
||||
}
|
||||
|
||||
if presetName == "" || presets[presetName] == nil {
|
||||
presetName = "vim"
|
||||
}
|
||||
|
||||
return presets[presetName]
|
||||
}
|
||||
|
||||
func standardTerminalEditorPreset(editor string) *editPreset {
|
||||
return &editPreset{
|
||||
editTemplate: editor + " -- {{filename}}",
|
||||
editAtLineTemplate: editor + " +{{line}} -- {{filename}}",
|
||||
editAtLineAndWaitTemplate: editor + " +{{line}} -- {{filename}}",
|
||||
editInTerminal: true,
|
||||
}
|
||||
}
|
||||
|
||||
func getEditInTerminal(osConfig *OSConfig, preset *editPreset) bool {
|
||||
if osConfig.EditInTerminal != nil {
|
||||
return *osConfig.EditInTerminal
|
||||
}
|
||||
return preset.editInTerminal
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetEditTemplate(t *testing.T) {
|
||||
trueVal := true
|
||||
|
||||
scenarios := []struct {
|
||||
name string
|
||||
osConfig *OSConfig
|
||||
guessDefaultEditor func() string
|
||||
expectedEditTemplate string
|
||||
expectedEditAtLineTemplate string
|
||||
expectedEditAtLineAndWaitTemplate string
|
||||
expectedEditInTerminal bool
|
||||
}{
|
||||
{
|
||||
"Default template is vim",
|
||||
&OSConfig{},
|
||||
func() string { return "" },
|
||||
"vim -- {{filename}}",
|
||||
"vim +{{line}} -- {{filename}}",
|
||||
"vim +{{line}} -- {{filename}}",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Setting a preset",
|
||||
&OSConfig{
|
||||
EditPreset: "vscode",
|
||||
},
|
||||
func() string { return "" },
|
||||
"code --reuse-window -- {{filename}}",
|
||||
"code --reuse-window --goto -- {{filename}}:{{line}}",
|
||||
"code --reuse-window --goto --wait -- {{filename}}:{{line}}",
|
||||
false,
|
||||
},
|
||||
{
|
||||
"Setting a preset wins over guessed editor",
|
||||
&OSConfig{
|
||||
EditPreset: "vscode",
|
||||
},
|
||||
func() string { return "nano" },
|
||||
"code --reuse-window -- {{filename}}",
|
||||
"code --reuse-window --goto -- {{filename}}:{{line}}",
|
||||
"code --reuse-window --goto --wait -- {{filename}}:{{line}}",
|
||||
false,
|
||||
},
|
||||
{
|
||||
"Overriding a preset with explicit config (edit)",
|
||||
&OSConfig{
|
||||
EditPreset: "vscode",
|
||||
Edit: "myeditor {{filename}}",
|
||||
EditInTerminal: &trueVal,
|
||||
},
|
||||
func() string { return "" },
|
||||
"myeditor {{filename}}",
|
||||
"code --reuse-window --goto -- {{filename}}:{{line}}",
|
||||
"code --reuse-window --goto --wait -- {{filename}}:{{line}}",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Overriding a preset with explicit config (edit at line)",
|
||||
&OSConfig{
|
||||
EditPreset: "vscode",
|
||||
EditAtLine: "myeditor --line={{line}} {{filename}}",
|
||||
EditInTerminal: &trueVal,
|
||||
},
|
||||
func() string { return "" },
|
||||
"code --reuse-window -- {{filename}}",
|
||||
"myeditor --line={{line}} {{filename}}",
|
||||
"code --reuse-window --goto --wait -- {{filename}}:{{line}}",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Overriding a preset with explicit config (edit at line and wait)",
|
||||
&OSConfig{
|
||||
EditPreset: "vscode",
|
||||
EditAtLineAndWait: "myeditor --line={{line}} -w {{filename}}",
|
||||
EditInTerminal: &trueVal,
|
||||
},
|
||||
func() string { return "" },
|
||||
"code --reuse-window -- {{filename}}",
|
||||
"code --reuse-window --goto -- {{filename}}:{{line}}",
|
||||
"myeditor --line={{line}} -w {{filename}}",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Unknown preset name",
|
||||
&OSConfig{
|
||||
EditPreset: "thisPresetDoesNotExist",
|
||||
},
|
||||
func() string { return "" },
|
||||
"vim -- {{filename}}",
|
||||
"vim +{{line}} -- {{filename}}",
|
||||
"vim +{{line}} -- {{filename}}",
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Guessing a preset from guessed editor",
|
||||
&OSConfig{},
|
||||
func() string { return "emacs" },
|
||||
"emacs -- {{filename}}",
|
||||
"emacs +{{line}} -- {{filename}}",
|
||||
"emacs +{{line}} -- {{filename}}",
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
template, editInTerminal := GetEditTemplate(s.osConfig, s.guessDefaultEditor)
|
||||
assert.Equal(t, s.expectedEditTemplate, template)
|
||||
assert.Equal(t, s.expectedEditInTerminal, editInTerminal)
|
||||
|
||||
template, editInTerminal = GetEditAtLineTemplate(s.osConfig, s.guessDefaultEditor)
|
||||
assert.Equal(t, s.expectedEditAtLineTemplate, template)
|
||||
assert.Equal(t, s.expectedEditInTerminal, editInTerminal)
|
||||
|
||||
template = GetEditAtLineAndWaitTemplate(s.osConfig, s.guessDefaultEditor)
|
||||
assert.Equal(t, s.expectedEditAtLineAndWaitTemplate, template)
|
||||
})
|
||||
}
|
||||
}
|
||||
+52
-14
@@ -52,6 +52,7 @@ type GuiConfig struct {
|
||||
SplitDiff string `yaml:"splitDiff"`
|
||||
SkipRewordInEditorWarning bool `yaml:"skipRewordInEditorWarning"`
|
||||
WindowSize string `yaml:"windowSize"`
|
||||
Border string `yaml:"border"`
|
||||
}
|
||||
|
||||
type ThemeConfig struct {
|
||||
@@ -137,7 +138,6 @@ type KeybindingUniversalConfig struct {
|
||||
Quit string `yaml:"quit"`
|
||||
QuitAlt1 string `yaml:"quit-alt1"`
|
||||
Return string `yaml:"return"`
|
||||
ReturnAlt1 string `yaml:"return-alt1"`
|
||||
QuitWithoutChangingDirectory string `yaml:"quitWithoutChangingDirectory"`
|
||||
TogglePanel string `yaml:"togglePanel"`
|
||||
PrevItem string `yaml:"prevItem"`
|
||||
@@ -165,7 +165,6 @@ type KeybindingUniversalConfig struct {
|
||||
Select string `yaml:"select"`
|
||||
GoInto string `yaml:"goInto"`
|
||||
Confirm string `yaml:"confirm"`
|
||||
ConfirmAlt1 string `yaml:"confirm-alt1"`
|
||||
Remove string `yaml:"remove"`
|
||||
New string `yaml:"new"`
|
||||
Edit string `yaml:"edit"`
|
||||
@@ -178,8 +177,8 @@ type KeybindingUniversalConfig struct {
|
||||
ScrollDownMainAlt2 string `yaml:"scrollDownMain-alt2"`
|
||||
ExecuteCustomCommand string `yaml:"executeCustomCommand"`
|
||||
CreateRebaseOptionsMenu string `yaml:"createRebaseOptionsMenu"`
|
||||
PushFiles string `yaml:"pushFiles"`
|
||||
PullFiles string `yaml:"pullFiles"`
|
||||
Push string `yaml:"pushFiles"` // 'Files' appended for legacy reasons
|
||||
Pull string `yaml:"pullFiles"` // 'Files' appended for legacy reasons
|
||||
Refresh string `yaml:"refresh"`
|
||||
CreatePatchOptionsMenu string `yaml:"createPatchOptionsMenu"`
|
||||
NextTab string `yaml:"nextTab"`
|
||||
@@ -235,6 +234,7 @@ type KeybindingBranchesConfig struct {
|
||||
MergeIntoCurrentBranch string `yaml:"mergeIntoCurrentBranch"`
|
||||
ViewGitFlowOptions string `yaml:"viewGitFlowOptions"`
|
||||
FastForward string `yaml:"fastForward"`
|
||||
CreateTag string `yaml:"createTag"`
|
||||
PushTag string `yaml:"pushTag"`
|
||||
SetUpstream string `yaml:"setUpstream"`
|
||||
FetchRemote string `yaml:"fetchRemote"`
|
||||
@@ -257,7 +257,7 @@ type KeybindingCommitsConfig struct {
|
||||
CherryPickCopy string `yaml:"cherryPickCopy"`
|
||||
CherryPickCopyRange string `yaml:"cherryPickCopyRange"`
|
||||
PasteCommits string `yaml:"pasteCommits"`
|
||||
TagCommit string `yaml:"tagCommit"`
|
||||
CreateTag string `yaml:"tagCommit"`
|
||||
CheckoutCommit string `yaml:"checkoutCommit"`
|
||||
ResetCherryPick string `yaml:"resetCherryPick"`
|
||||
CopyCommitAttributeToClipboard string `yaml:"copyCommitAttributeToClipboard"`
|
||||
@@ -291,16 +291,54 @@ type KeybindingSubmodulesConfig struct {
|
||||
|
||||
// OSConfig contains config on the level of the os
|
||||
type OSConfig struct {
|
||||
// EditCommand is the command for editing a file
|
||||
// Command for editing a file. Should contain "{{filename}}".
|
||||
Edit string `yaml:"edit,omitempty"`
|
||||
|
||||
// Command for editing a file at a given line number. Should contain
|
||||
// "{{filename}}", and may optionally contain "{{line}}".
|
||||
EditAtLine string `yaml:"editAtLine,omitempty"`
|
||||
|
||||
// Same as EditAtLine, except that the command needs to wait until the
|
||||
// window is closed.
|
||||
EditAtLineAndWait string `yaml:"editAtLineAndWait,omitempty"`
|
||||
|
||||
// Whether the given edit commands use the terminal. Used to decide whether
|
||||
// lazygit needs to suspend to the background before calling the editor.
|
||||
// Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
EditInTerminal *bool `yaml:"editInTerminal,omitempty"`
|
||||
|
||||
// A built-in preset that sets all of the above settings. Supported presets
|
||||
// are defined in the getPreset function in editor_presets.go.
|
||||
EditPreset string `yaml:"editPreset,omitempty"`
|
||||
|
||||
// Command for opening a file, as if the file is double-clicked. Should
|
||||
// contain "{{filename}}", but doesn't support "{{line}}".
|
||||
Open string `yaml:"open,omitempty"`
|
||||
|
||||
// Command for opening a link. Should contain "{{link}}".
|
||||
OpenLink string `yaml:"openLink,omitempty"`
|
||||
|
||||
// --------
|
||||
|
||||
// The following configs are all deprecated and kept for backward
|
||||
// compatibility. They will be removed in the future.
|
||||
|
||||
// EditCommand is the command for editing a file.
|
||||
// Deprecated: use Edit instead. Note that semantics are different:
|
||||
// EditCommand is just the command itself, whereas Edit contains a
|
||||
// "{{filename}}" variable.
|
||||
EditCommand string `yaml:"editCommand,omitempty"`
|
||||
|
||||
// EditCommandTemplate is the command template for editing a file
|
||||
// Deprecated: use EditAtLine instead.
|
||||
EditCommandTemplate string `yaml:"editCommandTemplate,omitempty"`
|
||||
|
||||
// OpenCommand is the command for opening a file
|
||||
// Deprecated: use Open instead.
|
||||
OpenCommand string `yaml:"openCommand,omitempty"`
|
||||
|
||||
// OpenCommand is the command for opening a link
|
||||
// OpenLinkCommand is the command for opening a link
|
||||
// Deprecated: use OpenLink instead.
|
||||
OpenLinkCommand string `yaml:"openLinkCommand,omitempty"`
|
||||
}
|
||||
|
||||
@@ -381,6 +419,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
CommandLogSize: 8,
|
||||
SplitDiff: "auto",
|
||||
SkipRewordInEditorWarning: false,
|
||||
Border: "single",
|
||||
},
|
||||
Git: GitConfig{
|
||||
Paging: PagingConfig{
|
||||
@@ -426,7 +465,6 @@ func GetDefaultConfig() *UserConfig {
|
||||
Quit: "q",
|
||||
QuitAlt1: "<c-c>",
|
||||
Return: "<esc>",
|
||||
ReturnAlt1: "",
|
||||
QuitWithoutChangingDirectory: "Q",
|
||||
TogglePanel: "<tab>",
|
||||
PrevItem: "<up>",
|
||||
@@ -449,12 +487,11 @@ func GetDefaultConfig() *UserConfig {
|
||||
NextMatch: "n",
|
||||
PrevMatch: "N",
|
||||
StartSearch: "/",
|
||||
OptionMenu: "x",
|
||||
OptionMenu: "",
|
||||
OptionMenuAlt1: "?",
|
||||
Select: "<space>",
|
||||
GoInto: "<enter>",
|
||||
Confirm: "<enter>",
|
||||
ConfirmAlt1: "y",
|
||||
Remove: "d",
|
||||
New: "n",
|
||||
Edit: "e",
|
||||
@@ -468,8 +505,8 @@ func GetDefaultConfig() *UserConfig {
|
||||
ScrollDownMainAlt2: "<c-d>",
|
||||
ExecuteCustomCommand: ":",
|
||||
CreateRebaseOptionsMenu: "m",
|
||||
PushFiles: "P",
|
||||
PullFiles: "p",
|
||||
Push: "P",
|
||||
Pull: "p",
|
||||
Refresh: "R",
|
||||
CreatePatchOptionsMenu: "<c-p>",
|
||||
NextTab: "]",
|
||||
@@ -521,6 +558,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
MergeIntoCurrentBranch: "M",
|
||||
ViewGitFlowOptions: "i",
|
||||
FastForward: "f",
|
||||
CreateTag: "T",
|
||||
PushTag: "P",
|
||||
SetUpstream: "u",
|
||||
FetchRemote: "f",
|
||||
@@ -542,7 +580,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
CherryPickCopy: "c",
|
||||
CherryPickCopyRange: "C",
|
||||
PasteCommits: "v",
|
||||
TagCommit: "T",
|
||||
CreateTag: "T",
|
||||
CheckoutCommit: "<space>",
|
||||
ResetCherryPick: "<c-R>",
|
||||
CopyCommitAttributeToClipboard: "y",
|
||||
@@ -570,7 +608,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
BulkMenu: "b",
|
||||
},
|
||||
},
|
||||
OS: GetPlatformDefaultConfig(),
|
||||
OS: OSConfig{},
|
||||
DisableStartupPopups: false,
|
||||
CustomCommands: []CustomCommand(nil),
|
||||
Services: map[string]string(nil),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package test
|
||||
package fakes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -79,7 +79,7 @@ func (gui *Gui) getRandomTip() string {
|
||||
// keybindings and lazygit-specific advice
|
||||
fmt.Sprintf(
|
||||
"To force push, press '%s' and then if the push is rejected you will be asked if you want to force push",
|
||||
formattedKey(config.Universal.PushFiles),
|
||||
formattedKey(config.Universal.Push),
|
||||
),
|
||||
fmt.Sprintf(
|
||||
"To filter commits by path, press '%s'",
|
||||
@@ -191,7 +191,7 @@ func (gui *Gui) getRandomTip() string {
|
||||
),
|
||||
}
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
randomIndex := rand.Intn(len(tips))
|
||||
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
randomIndex := rnd.Intn(len(tips))
|
||||
return tips[randomIndex]
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ func (gui *Gui) commitFilesRenderToMain() error {
|
||||
to := ref.RefName()
|
||||
from, reverse := gui.State.Modes.Diffing.GetFromAndReverseArgsForDiff(ref.ParentRefName())
|
||||
|
||||
cmdObj := gui.git.WorkingTree.ShowFileDiffCmdObj(from, to, reverse, node.GetPath(), false)
|
||||
cmdObj := gui.git.WorkingTree.ShowFileDiffCmdObj(from, to, reverse, node.GetPath(), false,
|
||||
gui.IgnoreWhitespaceInDiffView)
|
||||
task := types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
|
||||
pair := gui.c.MainViewPairs().Normal
|
||||
|
||||
@@ -35,7 +35,8 @@ func (gui *Gui) branchCommitsRenderToMain() error {
|
||||
if commit == nil {
|
||||
task = types.NewRenderStringTask(gui.c.Tr.NoCommitsThisBranch)
|
||||
} else {
|
||||
cmdObj := gui.git.Commit.ShowCmdObj(commit.Sha, gui.State.Modes.Filtering.GetPath())
|
||||
cmdObj := gui.git.Commit.ShowCmdObj(commit.Sha, gui.State.Modes.Filtering.GetPath(),
|
||||
gui.IgnoreWhitespaceInDiffView)
|
||||
task = types.NewRunPtyTask(cmdObj.GetCmd())
|
||||
}
|
||||
|
||||
@@ -50,8 +51,8 @@ func (gui *Gui) branchCommitsRenderToMain() error {
|
||||
}
|
||||
|
||||
func (gui *Gui) secondaryPatchPanelUpdateOpts() *types.ViewUpdateOpts {
|
||||
if gui.git.Patch.PatchManager.Active() {
|
||||
patch := gui.git.Patch.PatchManager.RenderAggregatedPatchColored(false)
|
||||
if gui.git.Patch.PatchBuilder.Active() {
|
||||
patch := gui.git.Patch.PatchBuilder.RenderAggregatedPatch(false)
|
||||
|
||||
return &types.ViewUpdateOpts{
|
||||
Task: types.NewRenderStringWithoutScrollTask(patch),
|
||||
|
||||
@@ -241,11 +241,6 @@ func (gui *Gui) setKeyBindings(cancel context.CancelFunc, opts types.CreatePopup
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.Confirm),
|
||||
Handler: onConfirm,
|
||||
},
|
||||
{
|
||||
ViewName: "confirmation",
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.ConfirmAlt1),
|
||||
Handler: onConfirm,
|
||||
},
|
||||
{
|
||||
ViewName: "confirmation",
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.Return),
|
||||
@@ -266,11 +261,6 @@ func (gui *Gui) setKeyBindings(cancel context.CancelFunc, opts types.CreatePopup
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.Confirm),
|
||||
Handler: onSuggestionConfirm,
|
||||
},
|
||||
{
|
||||
ViewName: "suggestions",
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.ConfirmAlt1),
|
||||
Handler: onSuggestionConfirm,
|
||||
},
|
||||
{
|
||||
ViewName: "suggestions",
|
||||
Key: keybindings.GetKey(keybindingConfig.Universal.Return),
|
||||
@@ -295,10 +285,8 @@ func (gui *Gui) setKeyBindings(cancel context.CancelFunc, opts types.CreatePopup
|
||||
func (gui *Gui) clearConfirmationViewKeyBindings() {
|
||||
keybindingConfig := gui.c.UserConfig.Keybinding
|
||||
_ = gui.g.DeleteKeybinding("confirmation", keybindings.GetKey(keybindingConfig.Universal.Confirm), gocui.ModNone)
|
||||
_ = gui.g.DeleteKeybinding("confirmation", keybindings.GetKey(keybindingConfig.Universal.ConfirmAlt1), gocui.ModNone)
|
||||
_ = gui.g.DeleteKeybinding("confirmation", keybindings.GetKey(keybindingConfig.Universal.Return), gocui.ModNone)
|
||||
_ = gui.g.DeleteKeybinding("suggestions", keybindings.GetKey(keybindingConfig.Universal.Confirm), gocui.ModNone)
|
||||
_ = gui.g.DeleteKeybinding("suggestions", keybindings.GetKey(keybindingConfig.Universal.ConfirmAlt1), gocui.ModNone)
|
||||
_ = gui.g.DeleteKeybinding("suggestions", keybindings.GetKey(keybindingConfig.Universal.Return), gocui.ModNone)
|
||||
}
|
||||
|
||||
|
||||
+21
-6
@@ -52,7 +52,7 @@ func (gui *Gui) pushContext(c types.Context, opts types.OnFocusOpts) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
contextsToDeactivate := gui.pushToContextStack(c)
|
||||
contextsToDeactivate, contextToActivate := gui.pushToContextStack(c)
|
||||
|
||||
for _, contextToDeactivate := range contextsToDeactivate {
|
||||
if err := gui.deactivateContext(contextToDeactivate, types.OnFocusLostOpts{NewContextKey: c.GetKey()}); err != nil {
|
||||
@@ -60,16 +60,28 @@ func (gui *Gui) pushContext(c types.Context, opts types.OnFocusOpts) error {
|
||||
}
|
||||
}
|
||||
|
||||
return gui.activateContext(c, opts)
|
||||
if contextToActivate == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return gui.activateContext(contextToActivate, opts)
|
||||
}
|
||||
|
||||
// Adjusts the context stack based on the context that's being pushed and returns contexts to deactivate
|
||||
func (gui *Gui) pushToContextStack(c types.Context) []types.Context {
|
||||
// Adjusts the context stack based on the context that's being pushed and
|
||||
// returns (contexts to deactivate, context to activate)
|
||||
func (gui *Gui) pushToContextStack(c types.Context) ([]types.Context, types.Context) {
|
||||
contextsToDeactivate := []types.Context{}
|
||||
|
||||
gui.State.ContextManager.Lock()
|
||||
defer gui.State.ContextManager.Unlock()
|
||||
|
||||
if len(gui.State.ContextManager.ContextStack) > 0 &&
|
||||
c == gui.State.ContextManager.ContextStack[len(gui.State.ContextManager.ContextStack)-1] {
|
||||
// Context being pushed is already on top of the stack: nothing to
|
||||
// deactivate or activate
|
||||
return contextsToDeactivate, nil
|
||||
}
|
||||
|
||||
if len(gui.State.ContextManager.ContextStack) == 0 {
|
||||
gui.State.ContextManager.ContextStack = append(gui.State.ContextManager.ContextStack, c)
|
||||
} else if c.GetKind() == types.SIDE_CONTEXT {
|
||||
@@ -78,12 +90,15 @@ func (gui *Gui) pushToContextStack(c types.Context) []types.Context {
|
||||
gui.State.ContextManager.ContextStack = []types.Context{c}
|
||||
} else if c.GetKind() == types.MAIN_CONTEXT {
|
||||
// if we're switching to a main context, remove all other main contexts in the stack
|
||||
contextsToKeep := []types.Context{}
|
||||
for _, stackContext := range gui.State.ContextManager.ContextStack {
|
||||
if stackContext.GetKind() == types.MAIN_CONTEXT {
|
||||
contextsToDeactivate = append(contextsToDeactivate, stackContext)
|
||||
} else {
|
||||
contextsToKeep = append(contextsToKeep, stackContext)
|
||||
}
|
||||
}
|
||||
gui.State.ContextManager.ContextStack = []types.Context{c}
|
||||
gui.State.ContextManager.ContextStack = append(contextsToKeep, c)
|
||||
} else {
|
||||
topContext := gui.currentContextWithoutLock()
|
||||
|
||||
@@ -105,7 +120,7 @@ func (gui *Gui) pushToContextStack(c types.Context) []types.Context {
|
||||
}
|
||||
}
|
||||
|
||||
return contextsToDeactivate
|
||||
return contextsToDeactivate, c
|
||||
}
|
||||
|
||||
func (gui *Gui) popContext() error {
|
||||
|
||||
@@ -20,6 +20,7 @@ type BaseContext struct {
|
||||
focusable bool
|
||||
transient bool
|
||||
hasControlledBounds bool
|
||||
highlightOnFocus bool
|
||||
|
||||
*ParentContextMgr
|
||||
}
|
||||
@@ -34,6 +35,7 @@ type NewBaseContextOpts struct {
|
||||
Focusable bool
|
||||
Transient bool
|
||||
HasUncontrolledBounds bool // negating for the sake of making false the default
|
||||
HighlightOnFocus bool
|
||||
|
||||
OnGetOptionsMap func() map[string]string
|
||||
}
|
||||
@@ -52,6 +54,7 @@ func NewBaseContext(opts NewBaseContextOpts) *BaseContext {
|
||||
focusable: opts.Focusable,
|
||||
transient: opts.Transient,
|
||||
hasControlledBounds: hasControlledBounds,
|
||||
highlightOnFocus: opts.HighlightOnFocus,
|
||||
ParentContextMgr: &ParentContextMgr{},
|
||||
viewTrait: viewTrait,
|
||||
}
|
||||
|
||||
@@ -42,12 +42,13 @@ func NewMergeConflictsContext(
|
||||
mutex: &deadlock.Mutex{},
|
||||
Context: NewSimpleContext(
|
||||
NewBaseContext(NewBaseContextOpts{
|
||||
Kind: types.MAIN_CONTEXT,
|
||||
View: view,
|
||||
WindowName: "main",
|
||||
Key: MERGE_CONFLICTS_CONTEXT_KEY,
|
||||
OnGetOptionsMap: getOptionsMap,
|
||||
Focusable: true,
|
||||
Kind: types.MAIN_CONTEXT,
|
||||
View: view,
|
||||
WindowName: "main",
|
||||
Key: MERGE_CONFLICTS_CONTEXT_KEY,
|
||||
OnGetOptionsMap: getOptionsMap,
|
||||
Focusable: true,
|
||||
HighlightOnFocus: true,
|
||||
}),
|
||||
opts,
|
||||
),
|
||||
@@ -77,7 +78,7 @@ func (self *MergeConflictsContext) IsUserScrolling() bool {
|
||||
|
||||
func (self *MergeConflictsContext) RenderAndFocus(isFocused bool) error {
|
||||
self.setContent(isFocused)
|
||||
self.focusSelection()
|
||||
self.FocusSelection()
|
||||
|
||||
self.c.Render()
|
||||
|
||||
@@ -104,9 +105,9 @@ func (self *MergeConflictsContext) setContent(isFocused bool) {
|
||||
self.GetView().SetContent(self.GetContentToRender(isFocused))
|
||||
}
|
||||
|
||||
func (self *MergeConflictsContext) focusSelection() {
|
||||
func (self *MergeConflictsContext) FocusSelection() {
|
||||
if !self.IsUserScrolling() {
|
||||
_ = self.GetView().SetOrigin(self.GetView().OriginX(), self.GetOriginY())
|
||||
_ = self.GetView().SetOriginY(self.GetOriginY())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,11 +37,12 @@ func NewPatchExplorerContext(
|
||||
mutex: &deadlock.Mutex{},
|
||||
getIncludedLineIndices: getIncludedLineIndices,
|
||||
SimpleContext: NewSimpleContext(NewBaseContext(NewBaseContextOpts{
|
||||
View: view,
|
||||
WindowName: windowName,
|
||||
Key: key,
|
||||
Kind: types.MAIN_CONTEXT,
|
||||
Focusable: true,
|
||||
View: view,
|
||||
WindowName: windowName,
|
||||
Key: key,
|
||||
Kind: types.MAIN_CONTEXT,
|
||||
Focusable: true,
|
||||
HighlightOnFocus: true,
|
||||
}), ContextCallbackOpts{
|
||||
OnFocus: onFocus,
|
||||
OnFocusLost: onFocusLost,
|
||||
@@ -68,7 +69,7 @@ func (self *PatchExplorerContext) GetIncludedLineIndices() []int {
|
||||
func (self *PatchExplorerContext) RenderAndFocus(isFocused bool) error {
|
||||
self.setContent(isFocused)
|
||||
|
||||
self.focusSelection()
|
||||
self.FocusSelection()
|
||||
self.c.Render()
|
||||
|
||||
return nil
|
||||
@@ -83,7 +84,7 @@ func (self *PatchExplorerContext) Render(isFocused bool) error {
|
||||
}
|
||||
|
||||
func (self *PatchExplorerContext) Focus() error {
|
||||
self.focusSelection()
|
||||
self.FocusSelection()
|
||||
self.c.Render()
|
||||
|
||||
return nil
|
||||
@@ -93,19 +94,18 @@ func (self *PatchExplorerContext) setContent(isFocused bool) {
|
||||
self.GetView().SetContent(self.GetContentToRender(isFocused))
|
||||
}
|
||||
|
||||
func (self *PatchExplorerContext) focusSelection() {
|
||||
func (self *PatchExplorerContext) FocusSelection() {
|
||||
view := self.GetView()
|
||||
state := self.GetState()
|
||||
_, viewHeight := view.Size()
|
||||
bufferHeight := viewHeight - 1
|
||||
_, origin := view.Origin()
|
||||
|
||||
selectedLineIdx := state.GetSelectedLineIdx()
|
||||
newOriginY := state.CalculateOrigin(origin, bufferHeight)
|
||||
|
||||
newOrigin := state.CalculateOrigin(origin, bufferHeight)
|
||||
_ = view.SetOriginY(newOriginY)
|
||||
|
||||
_ = view.SetOriginY(newOrigin)
|
||||
_ = view.SetCursor(0, selectedLineIdx-newOrigin)
|
||||
view.SetCursorY(state.GetSelectedLineIdx() - newOriginY)
|
||||
}
|
||||
|
||||
func (self *PatchExplorerContext) GetContentToRender(isFocused bool) string {
|
||||
|
||||
@@ -50,6 +50,10 @@ func NewDisplayContext(key types.ContextKey, view *gocui.View, windowName string
|
||||
}
|
||||
|
||||
func (self *SimpleContext) HandleFocus(opts types.OnFocusOpts) error {
|
||||
if self.highlightOnFocus {
|
||||
self.GetViewTrait().SetHighlight(true)
|
||||
}
|
||||
|
||||
if self.OnFocus != nil {
|
||||
if err := self.OnFocus(opts); err != nil {
|
||||
return err
|
||||
|
||||
@@ -30,7 +30,8 @@ func NewSubCommitsContext(
|
||||
) *SubCommitsContext {
|
||||
viewModel := &SubCommitsViewModel{
|
||||
BasicViewModel: NewBasicViewModel(getModel),
|
||||
refName: "",
|
||||
ref: nil,
|
||||
limitCommits: true,
|
||||
}
|
||||
|
||||
return &SubCommitsContext{
|
||||
@@ -60,12 +61,18 @@ func NewSubCommitsContext(
|
||||
|
||||
type SubCommitsViewModel struct {
|
||||
// name of the ref that the sub-commits are shown for
|
||||
refName string
|
||||
ref types.Ref
|
||||
*BasicViewModel[*models.Commit]
|
||||
|
||||
limitCommits bool
|
||||
}
|
||||
|
||||
func (self *SubCommitsViewModel) SetRefName(refName string) {
|
||||
self.refName = refName
|
||||
func (self *SubCommitsViewModel) SetRef(ref types.Ref) {
|
||||
self.ref = ref
|
||||
}
|
||||
|
||||
func (self *SubCommitsViewModel) GetRef() types.Ref {
|
||||
return self.ref
|
||||
}
|
||||
|
||||
func (self *SubCommitsContext) GetSelectedItemId() string {
|
||||
@@ -94,5 +101,13 @@ func (self *SubCommitsContext) GetCommits() []*models.Commit {
|
||||
}
|
||||
|
||||
func (self *SubCommitsContext) Title() string {
|
||||
return fmt.Sprintf(self.c.Tr.SubCommitsDynamicTitle, utils.TruncateWithEllipsis(self.refName, 50))
|
||||
return fmt.Sprintf(self.c.Tr.SubCommitsDynamicTitle, utils.TruncateWithEllipsis(self.ref.RefName(), 50))
|
||||
}
|
||||
|
||||
func (self *SubCommitsContext) SetLimitCommits(value bool) {
|
||||
self.limitCommits = value
|
||||
}
|
||||
|
||||
func (self *SubCommitsContext) GetLimitCommits() bool {
|
||||
return self.limitCommits
|
||||
}
|
||||
|
||||
@@ -150,15 +150,15 @@ func (gui *Gui) contextTree() *context.ContextTree {
|
||||
func(opts types.OnFocusLostOpts) error {
|
||||
gui.Views.PatchBuilding.Wrap = true
|
||||
|
||||
if gui.git.Patch.PatchManager.IsEmpty() {
|
||||
gui.git.Patch.PatchManager.Reset()
|
||||
if gui.git.Patch.PatchBuilder.IsEmpty() {
|
||||
gui.git.Patch.PatchBuilder.Reset()
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
func() []int {
|
||||
filename := gui.State.Contexts.CommitFiles.GetSelectedPath()
|
||||
includedLineIndices, err := gui.git.Patch.PatchManager.GetFileIncLineIndices(filename)
|
||||
includedLineIndices, err := gui.git.Patch.PatchBuilder.GetFileIncLineIndices(filename)
|
||||
if err != nil {
|
||||
gui.Log.Error(err)
|
||||
return nil
|
||||
|
||||
+14
-3
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/modes/cherrypicking"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/services/custom_commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/snake"
|
||||
)
|
||||
|
||||
@@ -29,6 +30,7 @@ func (gui *Gui) resetControllers() {
|
||||
getSavedCommitMessage := func() string {
|
||||
return gui.State.savedCommitMessage
|
||||
}
|
||||
gpgHelper := helpers.NewGpgHelper(helperCommon, gui.os, gui.git)
|
||||
gui.helpers = &helpers.Helpers{
|
||||
Refs: refsHelper,
|
||||
Host: helpers.NewHostHelper(helperCommon, gui.git),
|
||||
@@ -38,7 +40,7 @@ func (gui *Gui) resetControllers() {
|
||||
Files: helpers.NewFilesHelper(helperCommon, gui.git, osCommand),
|
||||
WorkingTree: helpers.NewWorkingTreeHelper(helperCommon, gui.git, gui.State.Contexts, refsHelper, model, setCommitMessage, getSavedCommitMessage),
|
||||
Tags: helpers.NewTagsHelper(helperCommon, gui.git),
|
||||
GPG: helpers.NewGpgHelper(helperCommon, gui.os, gui.git),
|
||||
GPG: gpgHelper,
|
||||
MergeAndRebase: rebaseHelper,
|
||||
MergeConflicts: helpers.NewMergeConflictsHelper(helperCommon, gui.State.Contexts, gui.git),
|
||||
CherryPick: helpers.NewCherryPickHelper(
|
||||
@@ -48,7 +50,8 @@ func (gui *Gui) resetControllers() {
|
||||
func() *cherrypicking.CherryPicking { return gui.State.Modes.CherryPicking },
|
||||
rebaseHelper,
|
||||
),
|
||||
Upstream: helpers.NewUpstreamHelper(helperCommon, model, suggestionsHelper.GetRemoteBranchesSuggestionsFunc),
|
||||
Upstream: helpers.NewUpstreamHelper(helperCommon, model, suggestionsHelper.GetRemoteBranchesSuggestionsFunc),
|
||||
AmendHelper: helpers.NewAmendHelper(helperCommon, gui.git, gpgHelper),
|
||||
}
|
||||
|
||||
gui.CustomCommandsClient = custom_commands.NewClient(
|
||||
@@ -92,6 +95,9 @@ func (gui *Gui) resetControllers() {
|
||||
|
||||
onCommitSuccess := func() {
|
||||
gui.State.savedCommitMessage = ""
|
||||
_ = gui.c.Refresh(types.RefreshOptions{
|
||||
Scope: []types.RefreshableView{types.STAGING},
|
||||
})
|
||||
}
|
||||
|
||||
commitMessageController := controllers.NewCommitMessageController(
|
||||
@@ -133,7 +139,12 @@ func (gui *Gui) resetControllers() {
|
||||
patchBuildingController := controllers.NewPatchBuildingController(common)
|
||||
snakeController := controllers.NewSnakeController(common, func() *snake.Game { return gui.snakeGame })
|
||||
|
||||
setSubCommits := func(commits []*models.Commit) { gui.State.Model.SubCommits = commits }
|
||||
setSubCommits := func(commits []*models.Commit) {
|
||||
gui.Mutexes.SubCommitsMutex.Lock()
|
||||
defer gui.Mutexes.SubCommitsMutex.Unlock()
|
||||
|
||||
gui.State.Model.SubCommits = commits
|
||||
}
|
||||
|
||||
for _, context := range []controllers.CanSwitchToSubCommits{
|
||||
gui.State.Contexts.Branches,
|
||||
|
||||
@@ -86,6 +86,11 @@ func (self *BranchesController) GetKeybindings(opts types.KeybindingsOpts) []*ty
|
||||
Handler: self.checkSelectedAndReal(self.fastForward),
|
||||
Description: self.c.Tr.FastForward,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Branches.CreateTag),
|
||||
Handler: self.checkSelected(self.createTag),
|
||||
Description: self.c.Tr.LcCreateTag,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Commits.ViewResetOptions),
|
||||
Handler: self.checkSelected(self.createResetMenu),
|
||||
@@ -363,6 +368,10 @@ func (self *BranchesController) fastForward(branch *models.Branch) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (self *BranchesController) createTag(branch *models.Branch) error {
|
||||
return self.helpers.Tags.CreateTagMenu(branch.FullRefName(), func() {})
|
||||
}
|
||||
|
||||
func (self *BranchesController) createResetMenu(selectedBranch *models.Branch) error {
|
||||
return self.helpers.Refs.CreateGitResetMenu(selectedBranch.Name)
|
||||
}
|
||||
|
||||
@@ -157,8 +157,8 @@ func (self *CommitFilesController) edit(node *filetree.CommitFileNode) error {
|
||||
func (self *CommitFilesController) toggleForPatch(node *filetree.CommitFileNode) error {
|
||||
toggle := func() error {
|
||||
return self.c.WithWaitingStatus(self.c.Tr.LcUpdatingPatch, func() error {
|
||||
if !self.git.Patch.PatchManager.Active() {
|
||||
if err := self.startPatchManager(); err != nil {
|
||||
if !self.git.Patch.PatchBuilder.Active() {
|
||||
if err := self.startPatchBuilder(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -166,34 +166,34 @@ func (self *CommitFilesController) toggleForPatch(node *filetree.CommitFileNode)
|
||||
// if there is any file that hasn't been fully added we'll fully add everything,
|
||||
// otherwise we'll remove everything
|
||||
adding := node.SomeFile(func(file *models.CommitFile) bool {
|
||||
return self.git.Patch.PatchManager.GetFileStatus(file.Name, self.context().GetRef().RefName()) != patch.WHOLE
|
||||
return self.git.Patch.PatchBuilder.GetFileStatus(file.Name, self.context().GetRef().RefName()) != patch.WHOLE
|
||||
})
|
||||
|
||||
err := node.ForEachFile(func(file *models.CommitFile) error {
|
||||
if adding {
|
||||
return self.git.Patch.PatchManager.AddFileWhole(file.Name)
|
||||
return self.git.Patch.PatchBuilder.AddFileWhole(file.Name)
|
||||
} else {
|
||||
return self.git.Patch.PatchManager.RemoveFile(file.Name)
|
||||
return self.git.Patch.PatchBuilder.RemoveFile(file.Name)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
|
||||
if self.git.Patch.PatchManager.IsEmpty() {
|
||||
self.git.Patch.PatchManager.Reset()
|
||||
if self.git.Patch.PatchBuilder.IsEmpty() {
|
||||
self.git.Patch.PatchBuilder.Reset()
|
||||
}
|
||||
|
||||
return self.c.PostRefreshUpdate(self.context())
|
||||
})
|
||||
}
|
||||
|
||||
if self.git.Patch.PatchManager.Active() && self.git.Patch.PatchManager.To != self.context().GetRef().RefName() {
|
||||
if self.git.Patch.PatchBuilder.Active() && self.git.Patch.PatchBuilder.To != self.context().GetRef().RefName() {
|
||||
return self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.DiscardPatch,
|
||||
Prompt: self.c.Tr.DiscardPatchConfirm,
|
||||
HandleConfirm: func() error {
|
||||
self.git.Patch.PatchManager.Reset()
|
||||
self.git.Patch.PatchBuilder.Reset()
|
||||
return toggle()
|
||||
},
|
||||
})
|
||||
@@ -207,7 +207,7 @@ func (self *CommitFilesController) toggleAllForPatch(_ *filetree.CommitFileNode)
|
||||
return self.toggleForPatch(root)
|
||||
}
|
||||
|
||||
func (self *CommitFilesController) startPatchManager() error {
|
||||
func (self *CommitFilesController) startPatchBuilder() error {
|
||||
commitFilesContext := self.context()
|
||||
|
||||
canRebase := commitFilesContext.GetCanRebase()
|
||||
@@ -215,7 +215,7 @@ func (self *CommitFilesController) startPatchManager() error {
|
||||
to := ref.RefName()
|
||||
from, reverse := self.modes.Diffing.GetFromAndReverseArgsForDiff(ref.ParentRefName())
|
||||
|
||||
self.git.Patch.PatchManager.Start(from, to, reverse, canRebase)
|
||||
self.git.Patch.PatchBuilder.Start(from, to, reverse, canRebase)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -229,8 +229,8 @@ func (self *CommitFilesController) enterCommitFile(node *filetree.CommitFileNode
|
||||
}
|
||||
|
||||
enterTheFile := func() error {
|
||||
if !self.git.Patch.PatchManager.Active() {
|
||||
if err := self.startPatchManager(); err != nil {
|
||||
if !self.git.Patch.PatchBuilder.Active() {
|
||||
if err := self.startPatchBuilder(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -238,12 +238,12 @@ func (self *CommitFilesController) enterCommitFile(node *filetree.CommitFileNode
|
||||
return self.c.PushContext(self.contexts.CustomPatchBuilder, opts)
|
||||
}
|
||||
|
||||
if self.git.Patch.PatchManager.Active() && self.git.Patch.PatchManager.To != self.context().GetRef().RefName() {
|
||||
if self.git.Patch.PatchBuilder.Active() && self.git.Patch.PatchBuilder.To != self.context().GetRef().RefName() {
|
||||
return self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.DiscardPatch,
|
||||
Prompt: self.c.Tr.DiscardPatchConfirm,
|
||||
HandleConfirm: func() error {
|
||||
self.git.Patch.PatchManager.Reset()
|
||||
self.git.Patch.PatchBuilder.Reset()
|
||||
return enterTheFile()
|
||||
},
|
||||
})
|
||||
|
||||
@@ -101,7 +101,7 @@ func (self *ContextLinesController) applyChange() error {
|
||||
}
|
||||
|
||||
func (self *ContextLinesController) checkCanChangeContext() error {
|
||||
if self.git.Patch.PatchManager.Active() {
|
||||
if self.git.Patch.PatchBuilder.Active() {
|
||||
return errors.New(self.c.Tr.CantChangeContextSizeError)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
type FilesController struct {
|
||||
baseController
|
||||
baseController // nolint: unused
|
||||
*controllerCommon
|
||||
|
||||
enterSubmodule func(submodule *models.SubmoduleConfig) error
|
||||
@@ -567,15 +567,7 @@ func (self *FilesController) handleAmendCommitPress() error {
|
||||
return self.c.ErrorMsg(self.c.Tr.NoCommitToAmend)
|
||||
}
|
||||
|
||||
return self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.AmendLastCommitTitle,
|
||||
Prompt: self.c.Tr.SureToAmend,
|
||||
HandleConfirm: func() error {
|
||||
cmdObj := self.git.Commit.AmendHeadCmdObj()
|
||||
self.c.LogAction(self.c.Tr.Actions.AmendCommit)
|
||||
return self.helpers.GPG.WithGpgHandling(cmdObj, self.c.Tr.AmendingStatus, nil)
|
||||
},
|
||||
})
|
||||
return self.helpers.AmendHelper.AmendHead()
|
||||
}
|
||||
|
||||
func (self *FilesController) handleStatusFilterPressed() error {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/filetree"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
)
|
||||
|
||||
// splitting this action out into its own file because it's self-contained
|
||||
@@ -51,7 +52,13 @@ func (self *FilesRemoveController) remove(node *filetree.FileNode) error {
|
||||
}
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}})
|
||||
},
|
||||
Key: 'd',
|
||||
Key: 'x',
|
||||
Tooltip: utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DiscardAllTooltip,
|
||||
map[string]string{
|
||||
"path": node.GetPath(),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -67,6 +74,12 @@ func (self *FilesRemoveController) remove(node *filetree.FileNode) error {
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}})
|
||||
},
|
||||
Key: 'u',
|
||||
Tooltip: utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DiscardUnstagedTooltip,
|
||||
map[string]string{
|
||||
"path": node.GetPath(),
|
||||
},
|
||||
),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -95,7 +108,13 @@ func (self *FilesRemoveController) remove(node *filetree.FileNode) error {
|
||||
}
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}})
|
||||
},
|
||||
Key: 'd',
|
||||
Key: 'x',
|
||||
Tooltip: utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DiscardAllTooltip,
|
||||
map[string]string{
|
||||
"path": node.GetPath(),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -111,6 +130,12 @@ func (self *FilesRemoveController) remove(node *filetree.FileNode) error {
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}})
|
||||
},
|
||||
Key: 'u',
|
||||
Tooltip: utils.ResolvePlaceholderString(
|
||||
self.c.Tr.DiscardUnstagedTooltip,
|
||||
map[string]string{
|
||||
"path": node.GetPath(),
|
||||
},
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/generics/slices"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
@@ -37,10 +39,12 @@ func (self *GlobalController) customCommand() error {
|
||||
Title: self.c.Tr.CustomCommand,
|
||||
FindSuggestionsFunc: self.GetCustomCommandsHistorySuggestionsFunc(),
|
||||
HandleConfirm: func(command string) error {
|
||||
self.c.GetAppState().CustomCommandsHistory = utils.Limit(
|
||||
lo.Uniq(append(self.c.GetAppState().CustomCommandsHistory, command)),
|
||||
1000,
|
||||
)
|
||||
if self.shouldSaveCommand(command) {
|
||||
self.c.GetAppState().CustomCommandsHistory = utils.Limit(
|
||||
lo.Uniq(append(self.c.GetAppState().CustomCommandsHistory, command)),
|
||||
1000,
|
||||
)
|
||||
}
|
||||
|
||||
err := self.c.SaveAppState()
|
||||
if err != nil {
|
||||
@@ -55,6 +59,12 @@ func (self *GlobalController) customCommand() error {
|
||||
})
|
||||
}
|
||||
|
||||
// this mimics the shell functionality `ignorespace`
|
||||
// which doesn't save a command to history if it starts with a space
|
||||
func (self *GlobalController) shouldSaveCommand(command string) bool {
|
||||
return !strings.HasPrefix(command, " ")
|
||||
}
|
||||
|
||||
func (self *GlobalController) GetCustomCommandsHistorySuggestionsFunc() func(string) []*types.Suggestion {
|
||||
// reversing so that we display the latest command first
|
||||
history := slices.Reverse(self.c.GetAppState().CustomCommandsHistory)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/commands"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
)
|
||||
|
||||
type AmendHelper struct {
|
||||
c *types.HelperCommon
|
||||
git *commands.GitCommand
|
||||
gpg *GpgHelper
|
||||
}
|
||||
|
||||
func NewAmendHelper(
|
||||
c *types.HelperCommon,
|
||||
git *commands.GitCommand,
|
||||
gpg *GpgHelper,
|
||||
) *AmendHelper {
|
||||
return &AmendHelper{
|
||||
c: c,
|
||||
git: git,
|
||||
gpg: gpg,
|
||||
}
|
||||
}
|
||||
|
||||
func (self *AmendHelper) AmendHead() error {
|
||||
return self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.AmendLastCommitTitle,
|
||||
Prompt: self.c.Tr.SureToAmend,
|
||||
HandleConfirm: func() error {
|
||||
cmdObj := self.git.Commit.AmendHeadCmdObj()
|
||||
self.c.LogAction(self.c.Tr.Actions.AmendCommit)
|
||||
return self.gpg.WithGpgHandling(cmdObj, self.c.Tr.AmendingStatus, nil)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -10,7 +10,6 @@ type IFilesHelper interface {
|
||||
EditFile(filename string) error
|
||||
EditFileAtLine(filename string, lineNumber int) error
|
||||
OpenFile(filename string) error
|
||||
OpenFileAtLine(filename string, lineNumber int) error
|
||||
}
|
||||
|
||||
type FilesHelper struct {
|
||||
@@ -34,42 +33,37 @@ func NewFilesHelper(
|
||||
var _ IFilesHelper = &FilesHelper{}
|
||||
|
||||
func (self *FilesHelper) EditFile(filename string) error {
|
||||
editor, err := self.git.File.GetEditor()
|
||||
if err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
editCmd := ""
|
||||
switch editor {
|
||||
case "code":
|
||||
editCmd = editor + " -r --goto -- " + filename
|
||||
default:
|
||||
editCmd = editor + " -- " + filename
|
||||
}
|
||||
self.c.LogAction(self.c.Tr.Actions.EditFile)
|
||||
return self.c.RunSubprocessAndRefresh(
|
||||
self.os.Cmd.NewShell(editCmd),
|
||||
)
|
||||
cmdStr, editInTerminal := self.git.File.GetEditCmdStr(filename)
|
||||
return self.callEditor(cmdStr, editInTerminal)
|
||||
}
|
||||
|
||||
func (self *FilesHelper) EditFileAtLine(filename string, lineNumber int) error {
|
||||
cmdStr, err := self.git.File.GetEditCmdStr(filename, lineNumber)
|
||||
if err != nil {
|
||||
return self.c.Error(err)
|
||||
cmdStr, editInTerminal := self.git.File.GetEditAtLineCmdStr(filename, lineNumber)
|
||||
return self.callEditor(cmdStr, editInTerminal)
|
||||
}
|
||||
|
||||
func (self *FilesHelper) EditFileAtLineAndWait(filename string, lineNumber int) error {
|
||||
cmdStr := self.git.File.GetEditAtLineAndWaitCmdStr(filename, lineNumber)
|
||||
|
||||
// Always suspend, regardless of the value of the editInTerminal config,
|
||||
// since we want to prevent interacting with the UI until the editor
|
||||
// returns, even if the editor doesn't use the terminal
|
||||
return self.callEditor(cmdStr, true)
|
||||
}
|
||||
|
||||
func (self *FilesHelper) callEditor(cmdStr string, editInTerminal bool) error {
|
||||
if editInTerminal {
|
||||
return self.c.RunSubprocessAndRefresh(
|
||||
self.os.Cmd.NewShell(cmdStr),
|
||||
)
|
||||
}
|
||||
|
||||
self.c.LogAction(self.c.Tr.Actions.EditFile)
|
||||
return self.c.RunSubprocessAndRefresh(
|
||||
self.os.Cmd.NewShell(cmdStr),
|
||||
)
|
||||
return self.os.Cmd.NewShell(cmdStr).Run()
|
||||
}
|
||||
|
||||
func (self *FilesHelper) OpenFile(filename string) error {
|
||||
return self.OpenFileAtLine(filename, 1)
|
||||
}
|
||||
|
||||
func (self *FilesHelper) OpenFileAtLine(filename string, lineNumber int) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.OpenFile)
|
||||
if err := self.os.OpenFileAtLine(filename, lineNumber); err != nil {
|
||||
if err := self.os.OpenFile(filename); err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -14,6 +14,7 @@ type Helpers struct {
|
||||
PatchBuilding *PatchBuildingHelper
|
||||
GPG *GpgHelper
|
||||
Upstream *UpstreamHelper
|
||||
AmendHelper *AmendHelper
|
||||
}
|
||||
|
||||
func NewStubHelpers() *Helpers {
|
||||
@@ -31,5 +32,6 @@ func NewStubHelpers() *Helpers {
|
||||
PatchBuilding: &PatchBuildingHelper{},
|
||||
GPG: &GpgHelper{},
|
||||
Upstream: &UpstreamHelper{},
|
||||
AmendHelper: &AmendHelper{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,6 +119,7 @@ var conflictStrings = []string{
|
||||
"When you have resolved this problem",
|
||||
"fix conflicts",
|
||||
"Resolve all conflicts manually",
|
||||
"Merge conflict in file",
|
||||
}
|
||||
|
||||
func isMergeConflictErr(errStr string) bool {
|
||||
|
||||
@@ -38,12 +38,12 @@ func (self *PatchBuildingHelper) ValidateNormalWorkingTreeState() (bool, error)
|
||||
|
||||
// takes us from the patch building panel back to the commit files panel
|
||||
func (self *PatchBuildingHelper) Escape() error {
|
||||
return self.c.PushContext(self.contexts.CommitFiles)
|
||||
return self.c.PopContext()
|
||||
}
|
||||
|
||||
// kills the custom patch and returns us back to the commit files panel if needed
|
||||
func (self *PatchBuildingHelper) Reset() error {
|
||||
self.git.Patch.PatchManager.Reset()
|
||||
self.git.Patch.PatchBuilder.Reset()
|
||||
|
||||
if self.c.CurrentStaticContext().GetKind() != types.SIDE_CONTEXT {
|
||||
if err := self.Escape(); err != nil {
|
||||
|
||||
@@ -21,20 +21,20 @@ func NewTagsHelper(c *types.HelperCommon, git *commands.GitCommand) *TagsHelper
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TagsHelper) CreateTagMenu(commitSha string, onCreate func()) error {
|
||||
func (self *TagsHelper) CreateTagMenu(ref string, onCreate func()) error {
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
Title: self.c.Tr.TagMenuTitle,
|
||||
Items: []*types.MenuItem{
|
||||
{
|
||||
Label: self.c.Tr.LcLightweightTag,
|
||||
OnPress: func() error {
|
||||
return self.handleCreateLightweightTag(commitSha, onCreate)
|
||||
return self.handleCreateLightweightTag(ref, onCreate)
|
||||
},
|
||||
},
|
||||
{
|
||||
Label: self.c.Tr.LcAnnotatedTag,
|
||||
OnPress: func() error {
|
||||
return self.handleCreateAnnotatedTag(commitSha, onCreate)
|
||||
return self.handleCreateAnnotatedTag(ref, onCreate)
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -48,7 +48,7 @@ func (self *TagsHelper) afterTagCreate(onCreate func()) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (self *TagsHelper) handleCreateAnnotatedTag(commitSha string, onCreate func()) error {
|
||||
func (self *TagsHelper) handleCreateAnnotatedTag(ref string, onCreate func()) error {
|
||||
return self.c.Prompt(types.PromptOpts{
|
||||
Title: self.c.Tr.TagNameTitle,
|
||||
HandleConfirm: func(tagName string) error {
|
||||
@@ -56,7 +56,7 @@ func (self *TagsHelper) handleCreateAnnotatedTag(commitSha string, onCreate func
|
||||
Title: self.c.Tr.TagMessageTitle,
|
||||
HandleConfirm: func(msg string) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.CreateAnnotatedTag)
|
||||
if err := self.git.Tag.CreateAnnotated(tagName, commitSha, msg); err != nil {
|
||||
if err := self.git.Tag.CreateAnnotated(tagName, ref, msg); err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
return self.afterTagCreate(onCreate)
|
||||
@@ -66,12 +66,12 @@ func (self *TagsHelper) handleCreateAnnotatedTag(commitSha string, onCreate func
|
||||
})
|
||||
}
|
||||
|
||||
func (self *TagsHelper) handleCreateLightweightTag(commitSha string, onCreate func()) error {
|
||||
func (self *TagsHelper) handleCreateLightweightTag(ref string, onCreate func()) error {
|
||||
return self.c.Prompt(types.PromptOpts{
|
||||
Title: self.c.Tr.TagNameTitle,
|
||||
HandleConfirm: func(tagName string) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.CreateLightweightTag)
|
||||
if err := self.git.Tag.CreateLightweight(tagName, commitSha); err != nil {
|
||||
if err := self.git.Tag.CreateLightweight(tagName, ref); err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
return self.afterTagCreate(onCreate)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/models"
|
||||
"github.com/jesseduffield/lazygit/pkg/commands/types/enums"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/context"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/utils"
|
||||
@@ -132,7 +133,7 @@ func (self *LocalCommitsController) GetKeybindings(opts types.KeybindingsOpts) [
|
||||
Description: self.c.Tr.LcRevertCommit,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Commits.TagCommit),
|
||||
Key: opts.GetKey(opts.Config.Commits.CreateTag),
|
||||
Handler: self.checkSelected(self.createTag),
|
||||
Description: self.c.Tr.LcTagCommit,
|
||||
},
|
||||
@@ -148,8 +149,8 @@ func (self *LocalCommitsController) GetKeybindings(opts types.KeybindingsOpts) [
|
||||
}
|
||||
|
||||
func (self *LocalCommitsController) squashDown(commit *models.Commit) error {
|
||||
if len(self.model.Commits) <= 1 {
|
||||
return self.c.ErrorMsg(self.c.Tr.YouNoCommitsToSquash)
|
||||
if self.context().GetSelectedLineIdx() >= len(self.model.Commits)-1 {
|
||||
return self.c.ErrorMsg(self.c.Tr.CannotSquashOrFixupFirstCommit)
|
||||
}
|
||||
|
||||
applied, err := self.handleMidRebaseCommand("squash", commit)
|
||||
@@ -173,8 +174,8 @@ func (self *LocalCommitsController) squashDown(commit *models.Commit) error {
|
||||
}
|
||||
|
||||
func (self *LocalCommitsController) fixup(commit *models.Commit) error {
|
||||
if len(self.model.Commits) <= 1 {
|
||||
return self.c.ErrorMsg(self.c.Tr.YouNoCommitsToSquash)
|
||||
if self.context().GetSelectedLineIdx() >= len(self.model.Commits)-1 {
|
||||
return self.c.ErrorMsg(self.c.Tr.CannotSquashOrFixupFirstCommit)
|
||||
}
|
||||
|
||||
applied, err := self.handleMidRebaseCommand("fixup", commit)
|
||||
@@ -229,7 +230,7 @@ func (self *LocalCommitsController) reword(commit *models.Commit) error {
|
||||
func (self *LocalCommitsController) doRewordEditor() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.RewordCommit)
|
||||
|
||||
if self.context().GetSelectedLineIdx() == 0 {
|
||||
if self.isHeadCommit() {
|
||||
return self.c.RunSubprocessAndRefresh(self.os.Cmd.New("git commit --allow-empty --amend --only"))
|
||||
}
|
||||
|
||||
@@ -298,7 +299,8 @@ func (self *LocalCommitsController) edit(commit *models.Commit) error {
|
||||
|
||||
return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.EditCommit)
|
||||
return self.interactiveRebase("edit")
|
||||
err := self.git.Rebase.InteractiveRebaseBreakAfter(self.model.Commits, self.context().GetSelectedLineIdx())
|
||||
return self.helpers.MergeAndRebase.CheckMergeOrRebase(err)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -325,7 +327,15 @@ func (self *LocalCommitsController) interactiveRebase(action string) error {
|
||||
// commit meaning you are trying to edit the todo file rather than actually
|
||||
// begin a rebase. It then updates the todo file with that action
|
||||
func (self *LocalCommitsController) handleMidRebaseCommand(action string, commit *models.Commit) (bool, error) {
|
||||
if commit.Status != "rebasing" {
|
||||
if !commit.IsTODO() {
|
||||
if self.git.Status.WorkingTreeState() != enums.REBASE_MODE_NONE {
|
||||
// If we are in a rebase, the only action that is allowed for
|
||||
// non-todo commits is rewording the current head commit
|
||||
if !(action == "reword" && self.isHeadCommit()) {
|
||||
return true, self.c.ErrorMsg(self.c.Tr.AlreadyRebasing)
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -357,8 +367,14 @@ func (self *LocalCommitsController) handleMidRebaseCommand(action string, commit
|
||||
func (self *LocalCommitsController) moveDown(commit *models.Commit) error {
|
||||
index := self.context().GetSelectedLineIdx()
|
||||
commits := self.model.Commits
|
||||
if commit.Status == "rebasing" {
|
||||
if commits[index+1].Status != "rebasing" {
|
||||
|
||||
// can't move past the initial commit
|
||||
if index >= len(commits)-1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if commit.IsTODO() {
|
||||
if !commits[index+1].IsTODO() {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -376,6 +392,10 @@ func (self *LocalCommitsController) moveDown(commit *models.Commit) error {
|
||||
})
|
||||
}
|
||||
|
||||
if self.git.Status.WorkingTreeState() != enums.REBASE_MODE_NONE {
|
||||
return self.c.ErrorMsg(self.c.Tr.AlreadyRebasing)
|
||||
}
|
||||
|
||||
return self.c.WithWaitingStatus(self.c.Tr.MovingStatus, func() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.MoveCommitDown)
|
||||
err := self.git.Rebase.MoveCommitDown(self.model.Commits, index)
|
||||
@@ -392,7 +412,7 @@ func (self *LocalCommitsController) moveUp(commit *models.Commit) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if commit.Status == "rebasing" {
|
||||
if commit.IsTODO() {
|
||||
// logging directly here because MoveTodoDown doesn't have enough information
|
||||
// to provide a useful log
|
||||
self.c.LogAction(self.c.Tr.Actions.MoveCommitUp)
|
||||
@@ -410,6 +430,10 @@ func (self *LocalCommitsController) moveUp(commit *models.Commit) error {
|
||||
})
|
||||
}
|
||||
|
||||
if self.git.Status.WorkingTreeState() != enums.REBASE_MODE_NONE {
|
||||
return self.c.ErrorMsg(self.c.Tr.AlreadyRebasing)
|
||||
}
|
||||
|
||||
return self.c.WithWaitingStatus(self.c.Tr.MovingStatus, func() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.MoveCommitUp)
|
||||
err := self.git.Rebase.MoveCommitDown(self.model.Commits, index-1)
|
||||
@@ -421,13 +445,24 @@ func (self *LocalCommitsController) moveUp(commit *models.Commit) error {
|
||||
}
|
||||
|
||||
func (self *LocalCommitsController) amendTo(commit *models.Commit) error {
|
||||
if self.isHeadCommit() {
|
||||
if err := self.helpers.AmendHelper.AmendHead(); err != nil {
|
||||
return err
|
||||
}
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC})
|
||||
}
|
||||
|
||||
if self.git.Status.WorkingTreeState() != enums.REBASE_MODE_NONE {
|
||||
return self.c.ErrorMsg(self.c.Tr.AlreadyRebasing)
|
||||
}
|
||||
|
||||
return self.c.Confirm(types.ConfirmOpts{
|
||||
Title: self.c.Tr.AmendCommitTitle,
|
||||
Prompt: self.c.Tr.AmendCommitPrompt,
|
||||
HandleConfirm: func() error {
|
||||
return self.c.WithWaitingStatus(self.c.Tr.AmendingStatus, func() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.AmendCommit)
|
||||
err := self.git.Rebase.AmendTo(commit.Sha)
|
||||
err := self.git.Rebase.AmendTo(commit)
|
||||
return self.helpers.MergeAndRebase.CheckMergeOrRebase(err)
|
||||
})
|
||||
},
|
||||
@@ -570,7 +605,7 @@ func (self *LocalCommitsController) squashAllAboveFixupCommits(commit *models.Co
|
||||
HandleConfirm: func() error {
|
||||
return self.c.WithWaitingStatus(self.c.Tr.SquashingStatus, func() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.SquashAllAboveFixupCommits)
|
||||
err := self.git.Rebase.SquashAllAboveFixupCommits(commit.Sha)
|
||||
err := self.git.Rebase.SquashAllAboveFixupCommits(commit)
|
||||
return self.helpers.MergeAndRebase.CheckMergeOrRebase(err)
|
||||
})
|
||||
},
|
||||
@@ -721,3 +756,7 @@ func (self *LocalCommitsController) context() *context.LocalCommitsContext {
|
||||
func (self *LocalCommitsController) paste() error {
|
||||
return self.helpers.CherryPick.Paste()
|
||||
}
|
||||
|
||||
func (self *LocalCommitsController) isHeadCommit() bool {
|
||||
return models.IsHeadCommit(self.model.Commits, self.context().GetSelectedLineIdx())
|
||||
}
|
||||
|
||||
@@ -31,10 +31,6 @@ func (self *MenuController) GetKeybindings(opts types.KeybindingsOpts) []*types.
|
||||
Key: opts.GetKey(opts.Config.Universal.Confirm),
|
||||
Handler: self.press,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.ConfirmAlt1),
|
||||
Handler: self.press,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.Return),
|
||||
Handler: self.close,
|
||||
|
||||
@@ -157,7 +157,7 @@ func (self *MergeConflictsController) context() *context.MergeConflictsContext {
|
||||
}
|
||||
|
||||
func (self *MergeConflictsController) Escape() error {
|
||||
return self.c.PushContext(self.contexts.Files)
|
||||
return self.c.PopContext()
|
||||
}
|
||||
|
||||
func (self *MergeConflictsController) HandleEditFile() error {
|
||||
@@ -166,8 +166,7 @@ func (self *MergeConflictsController) HandleEditFile() error {
|
||||
}
|
||||
|
||||
func (self *MergeConflictsController) HandleOpenFile() error {
|
||||
lineNumber := self.context().GetState().GetSelectedLine()
|
||||
return self.helpers.Files.OpenFileAtLine(self.context().GetState().GetPath(), lineNumber)
|
||||
return self.helpers.Files.OpenFile(self.context().GetState().GetPath())
|
||||
}
|
||||
|
||||
func (self *MergeConflictsController) HandleScrollLeft() error {
|
||||
|
||||
@@ -69,8 +69,7 @@ func (self *PatchBuildingController) OpenFile() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
lineNumber := self.context().GetState().CurrentLineNumber()
|
||||
return self.helpers.Files.OpenFileAtLine(path, lineNumber)
|
||||
return self.helpers.Files.OpenFile(path)
|
||||
}
|
||||
|
||||
func (self *PatchBuildingController) EditFile() error {
|
||||
@@ -101,7 +100,7 @@ func (self *PatchBuildingController) toggleSelection() error {
|
||||
self.context().GetMutex().Lock()
|
||||
defer self.context().GetMutex().Unlock()
|
||||
|
||||
toggleFunc := self.git.Patch.PatchManager.AddFileLineRange
|
||||
toggleFunc := self.git.Patch.PatchBuilder.AddFileLineRange
|
||||
filename := self.contexts.CommitFiles.GetSelectedPath()
|
||||
if filename == "" {
|
||||
return nil
|
||||
@@ -109,13 +108,13 @@ func (self *PatchBuildingController) toggleSelection() error {
|
||||
|
||||
state := self.context().GetState()
|
||||
|
||||
includedLineIndices, err := self.git.Patch.PatchManager.GetFileIncLineIndices(filename)
|
||||
includedLineIndices, err := self.git.Patch.PatchBuilder.GetFileIncLineIndices(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
currentLineIsStaged := lo.Contains(includedLineIndices, state.GetSelectedLineIdx())
|
||||
if currentLineIsStaged {
|
||||
toggleFunc = self.git.Patch.PatchManager.RemoveFileLineRange
|
||||
toggleFunc = self.git.Patch.PatchBuilder.RemoveFileLineRange
|
||||
}
|
||||
|
||||
// add range of lines to those set for the file
|
||||
|
||||
@@ -109,8 +109,7 @@ func (self *StagingController) OpenFile() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
lineNumber := self.context.GetState().CurrentLineNumber()
|
||||
return self.helpers.Files.OpenFileAtLine(path, lineNumber)
|
||||
return self.helpers.Files.OpenFile(path)
|
||||
}
|
||||
|
||||
func (self *StagingController) EditFile() error {
|
||||
@@ -128,7 +127,7 @@ func (self *StagingController) EditFile() error {
|
||||
}
|
||||
|
||||
func (self *StagingController) Escape() error {
|
||||
return self.c.PushContext(self.contexts.Files)
|
||||
return self.c.PopContext()
|
||||
}
|
||||
|
||||
func (self *StagingController) TogglePanel() error {
|
||||
@@ -176,26 +175,37 @@ func (self *StagingController) applySelection(reverse bool) error {
|
||||
}
|
||||
|
||||
firstLineIdx, lastLineIdx := state.SelectedRange()
|
||||
patch := patch.ModifiedPatchForRange(self.c.Log, path, state.GetDiff(), firstLineIdx, lastLineIdx, reverse, false)
|
||||
patchToApply := patch.
|
||||
Parse(state.GetDiff()).
|
||||
Transform(patch.TransformOpts{
|
||||
Reverse: reverse,
|
||||
IncludedLineIndices: patch.ExpandRange(firstLineIdx, lastLineIdx),
|
||||
FileNameOverride: path,
|
||||
}).
|
||||
FormatPlain()
|
||||
|
||||
if patch == "" {
|
||||
if patchToApply == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// apply the patch then refresh this panel
|
||||
// create a new temp file with the patch, then call git apply with that patch
|
||||
applyFlags := []string{}
|
||||
if reverse {
|
||||
applyFlags = append(applyFlags, "reverse")
|
||||
}
|
||||
if !reverse || self.staged {
|
||||
applyFlags = append(applyFlags, "cached")
|
||||
}
|
||||
self.c.LogAction(self.c.Tr.Actions.ApplyPatch)
|
||||
err := self.git.WorkingTree.ApplyPatch(patch, applyFlags...)
|
||||
err := self.git.WorkingTree.ApplyPatch(patchToApply, applyFlags...)
|
||||
if err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
|
||||
if state.SelectingRange() {
|
||||
state.SetLineSelectMode()
|
||||
firstLine, _ := state.SelectedRange()
|
||||
state.SelectLine(firstLine)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -219,18 +229,24 @@ func (self *StagingController) editHunk() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
hunk := state.CurrentHunk()
|
||||
patchText := patch.ModifiedPatchForRange(
|
||||
self.c.Log, path, state.GetDiff(), hunk.FirstLineIdx, hunk.LastLineIdx(), self.staged, false,
|
||||
)
|
||||
hunkStartIdx, hunkEndIdx := state.CurrentHunkBounds()
|
||||
patchText := patch.
|
||||
Parse(state.GetDiff()).
|
||||
Transform(patch.TransformOpts{
|
||||
Reverse: self.staged,
|
||||
IncludedLineIndices: patch.ExpandRange(hunkStartIdx, hunkEndIdx),
|
||||
FileNameOverride: path,
|
||||
}).
|
||||
FormatPlain()
|
||||
|
||||
patchFilepath, err := self.git.WorkingTree.SaveTemporaryPatch(patchText)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lineOffset := 3
|
||||
lineIdxInHunk := state.GetSelectedLineIdx() - hunk.FirstLineIdx
|
||||
if err := self.helpers.Files.EditFileAtLine(patchFilepath, lineIdxInHunk+lineOffset); err != nil {
|
||||
lineIdxInHunk := state.GetSelectedLineIdx() - hunkStartIdx
|
||||
if err := self.helpers.Files.EditFileAtLineAndWait(patchFilepath, lineIdxInHunk+lineOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -242,10 +258,19 @@ func (self *StagingController) editHunk() error {
|
||||
self.c.LogAction(self.c.Tr.Actions.ApplyPatch)
|
||||
|
||||
lineCount := strings.Count(editedPatchText, "\n") + 1
|
||||
newPatchText := patch.ModifiedPatchForRange(
|
||||
self.c.Log, path, editedPatchText, 0, lineCount, false, false,
|
||||
)
|
||||
if err := self.git.WorkingTree.ApplyPatch(newPatchText, "cached"); err != nil {
|
||||
newPatchText := patch.
|
||||
Parse(editedPatchText).
|
||||
Transform(patch.TransformOpts{
|
||||
IncludedLineIndices: patch.ExpandRange(0, lineCount),
|
||||
FileNameOverride: path,
|
||||
}).
|
||||
FormatPlain()
|
||||
|
||||
applyFlags := []string{"cached"}
|
||||
if self.staged {
|
||||
applyFlags = append(applyFlags, "reverse")
|
||||
}
|
||||
if err := self.git.WorkingTree.ApplyPatch(newPatchText, applyFlags...); err != nil {
|
||||
return self.c.Error(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,8 @@ func (self *SwitchToSubCommitsController) viewCommits() error {
|
||||
self.contexts.SubCommits.SetParentContext(self.context)
|
||||
self.contexts.SubCommits.SetWindowName(self.context.GetWindowName())
|
||||
self.contexts.SubCommits.SetTitleRef(ref.Description())
|
||||
self.contexts.SubCommits.SetRefName(ref.RefName())
|
||||
self.contexts.SubCommits.SetRef(ref)
|
||||
self.contexts.SubCommits.SetLimitCommits(true)
|
||||
|
||||
err = self.c.PostRefreshUpdate(self.contexts.SubCommits)
|
||||
if err != nil {
|
||||
|
||||
@@ -28,12 +28,12 @@ func NewSyncController(
|
||||
func (self *SyncController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {
|
||||
bindings := []*types.Binding{
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.PushFiles),
|
||||
Key: opts.GetKey(opts.Config.Universal.Push),
|
||||
Handler: opts.Guards.NoPopupPanel(self.HandlePush),
|
||||
Description: self.c.Tr.LcPush,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.PullFiles),
|
||||
Key: opts.GetKey(opts.Config.Universal.Pull),
|
||||
Handler: opts.Guards.NoPopupPanel(self.HandlePull),
|
||||
Description: self.c.Tr.LcPull,
|
||||
},
|
||||
|
||||
@@ -195,17 +195,17 @@ func (self *UndoController) parseReflogForActions(onUserAction func(counter int,
|
||||
counter++
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^\[lazygit redo\]`); ok {
|
||||
counter--
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase -i \(abort\)|^rebase -i \(finish\)`); ok {
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(abort\)|^rebase (-i )?\(finish\)`); ok {
|
||||
rebaseFinishCommitSha = reflogCommit.Sha
|
||||
} else if ok, match := utils.FindStringSubmatch(reflogCommit.Name, `^checkout: moving from ([\S]+) to ([\S]+)`); ok {
|
||||
action = &reflogAction{kind: CHECKOUT, from: match[1], to: match[2]}
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^commit|^reset: moving to|^pull`); ok {
|
||||
action = &reflogAction{kind: COMMIT, from: prevCommitSha, to: reflogCommit.Sha}
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase -i \(start\)`); ok {
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok {
|
||||
// if we're here then we must be currently inside an interactive rebase
|
||||
action = &reflogAction{kind: CURRENT_REBASE, from: prevCommitSha}
|
||||
}
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase -i \(start\)`); ok {
|
||||
} else if ok, _ := utils.FindStringSubmatch(reflogCommit.Name, `^rebase (-i )?\(start\)`); ok {
|
||||
action = &reflogAction{kind: REBASE, from: prevCommitSha, to: rebaseFinishCommitSha}
|
||||
rebaseFinishCommitSha = ""
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func (self *FilesController) createResetMenu() error {
|
||||
|
||||
return self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.FILES}})
|
||||
},
|
||||
Key: 'D',
|
||||
Key: 'x',
|
||||
Tooltip: self.c.Tr.NukeDescription,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func (gui *Gui) handleCreatePatchOptionsMenu() error {
|
||||
if !gui.git.Patch.PatchManager.Active() {
|
||||
if !gui.git.Patch.PatchBuilder.Active() {
|
||||
return gui.c.ErrorMsg(gui.c.Tr.NoPatchError)
|
||||
}
|
||||
|
||||
@@ -30,10 +30,10 @@ func (gui *Gui) handleCreatePatchOptionsMenu() error {
|
||||
},
|
||||
}
|
||||
|
||||
if gui.git.Patch.PatchManager.CanRebase && gui.git.Status.WorkingTreeState() == enums.REBASE_MODE_NONE {
|
||||
if gui.git.Patch.PatchBuilder.CanRebase && gui.git.Status.WorkingTreeState() == enums.REBASE_MODE_NONE {
|
||||
menuItems = append(menuItems, []*types.MenuItem{
|
||||
{
|
||||
Label: fmt.Sprintf("remove patch from original commit (%s)", gui.git.Patch.PatchManager.To),
|
||||
Label: fmt.Sprintf("remove patch from original commit (%s)", gui.git.Patch.PatchBuilder.To),
|
||||
OnPress: gui.handleDeletePatchFromCommit,
|
||||
Key: 'd',
|
||||
},
|
||||
@@ -51,7 +51,7 @@ func (gui *Gui) handleCreatePatchOptionsMenu() error {
|
||||
|
||||
if gui.currentContext().GetKey() == gui.State.Contexts.LocalCommits.GetKey() {
|
||||
selectedCommit := gui.getSelectedLocalCommit()
|
||||
if selectedCommit != nil && gui.git.Patch.PatchManager.To != selectedCommit.Sha {
|
||||
if selectedCommit != nil && gui.git.Patch.PatchBuilder.To != selectedCommit.Sha {
|
||||
// adding this option to index 1
|
||||
menuItems = append(
|
||||
menuItems[:1],
|
||||
@@ -82,7 +82,7 @@ func (gui *Gui) handleCreatePatchOptionsMenu() error {
|
||||
|
||||
func (gui *Gui) getPatchCommitIndex() int {
|
||||
for index, commit := range gui.State.Model.Commits {
|
||||
if commit.Sha == gui.git.Patch.PatchManager.To {
|
||||
if commit.Sha == gui.git.Patch.PatchBuilder.To {
|
||||
return index
|
||||
}
|
||||
}
|
||||
@@ -195,14 +195,14 @@ func (gui *Gui) handleApplyPatch(reverse bool) error {
|
||||
action = "Apply patch in reverse"
|
||||
}
|
||||
gui.c.LogAction(action)
|
||||
if err := gui.git.Patch.PatchManager.ApplyPatches(reverse); err != nil {
|
||||
if err := gui.git.Patch.PatchBuilder.ApplyPatches(reverse); err != nil {
|
||||
return gui.c.Error(err)
|
||||
}
|
||||
return gui.c.Refresh(types.RefreshOptions{Mode: types.ASYNC})
|
||||
}
|
||||
|
||||
func (gui *Gui) copyPatchToClipboard() error {
|
||||
patch := gui.git.Patch.PatchManager.RenderAggregatedPatchColored(true)
|
||||
patch := gui.git.Patch.PatchBuilder.RenderAggregatedPatch(true)
|
||||
|
||||
gui.c.LogAction(gui.c.Tr.Actions.CopyPatchToClipboard)
|
||||
if err := gui.os.CopyToClipboard(patch); err != nil {
|
||||
|
||||
@@ -95,6 +95,10 @@ func (gui *Gui) diffStr() string {
|
||||
output += " -R"
|
||||
}
|
||||
|
||||
if gui.IgnoreWhitespaceInDiffView {
|
||||
output += " --ignore-all-space"
|
||||
}
|
||||
|
||||
file := gui.currentlySelectedFilename()
|
||||
if file != "" {
|
||||
output += " -- " + file
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
package gui
|
||||
|
||||
const UNKNOWN_VIEW_ERROR_MSG = "unknown view"
|
||||
+43
-26
@@ -3,7 +3,6 @@ package gui
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -64,9 +63,9 @@ type ContextManager struct {
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewContextManager(initialContext types.Context) ContextManager {
|
||||
func NewContextManager() ContextManager {
|
||||
return ContextManager{
|
||||
ContextStack: []types.Context{initialContext},
|
||||
ContextStack: []types.Context{},
|
||||
RWMutex: sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
@@ -299,11 +298,15 @@ func (gui *Gui) resetState(startArgs appTypes.StartArgs, reuseState bool) {
|
||||
},
|
||||
ScreenMode: initialScreenMode,
|
||||
// TODO: put contexts in the context manager
|
||||
ContextManager: NewContextManager(initialContext),
|
||||
ContextManager: NewContextManager(),
|
||||
Contexts: contextTree,
|
||||
WindowViewNameMap: initialWindowViewNameMap,
|
||||
}
|
||||
|
||||
if err := gui.c.PushContext(initialContext); err != nil {
|
||||
gui.c.Log.Error(err)
|
||||
}
|
||||
|
||||
gui.RepoStateMap[Repo(currentDir)] = gui.State
|
||||
}
|
||||
|
||||
@@ -380,6 +383,7 @@ func NewGui(
|
||||
RefreshingStatusMutex: &deadlock.Mutex{},
|
||||
SyncMutex: &deadlock.Mutex{},
|
||||
LocalCommitsMutex: &deadlock.Mutex{},
|
||||
SubCommitsMutex: &deadlock.Mutex{},
|
||||
SubprocessMutex: &deadlock.Mutex{},
|
||||
PopupMutex: &deadlock.Mutex{},
|
||||
PtyMutex: &deadlock.Mutex{},
|
||||
@@ -435,17 +439,9 @@ var RuneReplacements = map[rune]string{
|
||||
}
|
||||
|
||||
func (gui *Gui) initGocui(headless bool, test integrationTypes.IntegrationTest) (*gocui.Gui, error) {
|
||||
recordEvents := RecordingEvents()
|
||||
playMode := gocui.NORMAL
|
||||
if recordEvents {
|
||||
playMode = gocui.RECORDING
|
||||
} else if Replaying() {
|
||||
playMode = gocui.REPLAYING
|
||||
} else if test != nil && os.Getenv(components.SANDBOX_ENV_VAR) != "true" {
|
||||
playMode = gocui.REPLAYING_NEW
|
||||
}
|
||||
playRecording := test != nil && os.Getenv(components.SANDBOX_ENV_VAR) != "true"
|
||||
|
||||
g, err := gocui.NewGui(gocui.OutputTrue, OverlappingEdges, playMode, headless, RuneReplacements)
|
||||
g, err := gocui.NewGui(gocui.OutputTrue, OverlappingEdges, playRecording, headless, RuneReplacements)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -499,6 +495,8 @@ func (gui *Gui) Run(startArgs appTypes.StartArgs) error {
|
||||
return err
|
||||
}
|
||||
|
||||
defer gui.checkForDeprecatedEditConfigs()
|
||||
|
||||
gui.g = g
|
||||
defer gui.g.Close()
|
||||
|
||||
@@ -576,10 +574,6 @@ func (gui *Gui) RunAndHandleError(startArgs appTypes.StartArgs) error {
|
||||
}
|
||||
}
|
||||
|
||||
if err := SaveRecording(gui.g.Recording); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
@@ -591,6 +585,37 @@ func (gui *Gui) RunAndHandleError(startArgs appTypes.StartArgs) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (gui *Gui) checkForDeprecatedEditConfigs() {
|
||||
osConfig := &gui.UserConfig.OS
|
||||
deprecatedConfigs := []struct {
|
||||
config string
|
||||
oldName string
|
||||
newName string
|
||||
}{
|
||||
{osConfig.EditCommand, "EditCommand", "Edit"},
|
||||
{osConfig.EditCommandTemplate, "EditCommandTemplate", "Edit,EditAtLine"},
|
||||
{osConfig.OpenCommand, "OpenCommand", "Open"},
|
||||
{osConfig.OpenLinkCommand, "OpenLinkCommand", "OpenLink"},
|
||||
}
|
||||
deprecatedConfigStrings := []string{}
|
||||
|
||||
for _, dc := range deprecatedConfigs {
|
||||
if dc.config != "" {
|
||||
deprecatedConfigStrings = append(deprecatedConfigStrings, fmt.Sprintf(" OS.%s -> OS.%s", dc.oldName, dc.newName))
|
||||
}
|
||||
}
|
||||
if len(deprecatedConfigStrings) != 0 {
|
||||
warningMessage := utils.ResolvePlaceholderString(
|
||||
gui.c.Tr.DeprecatedEditConfigWarning,
|
||||
map[string]string{
|
||||
"configs": strings.Join(deprecatedConfigStrings, "\n"),
|
||||
},
|
||||
)
|
||||
|
||||
os.Stdout.Write([]byte(warningMessage))
|
||||
}
|
||||
}
|
||||
|
||||
// returns whether command exited without error or not
|
||||
func (gui *Gui) runSubprocessWithSuspenseAndRefresh(subprocess oscommands.ICmdObj) error {
|
||||
_, err := gui.runSubprocessWithSuspense(subprocess)
|
||||
@@ -610,14 +635,6 @@ func (gui *Gui) runSubprocessWithSuspense(subprocess oscommands.ICmdObj) (bool,
|
||||
gui.Mutexes.SubprocessMutex.Lock()
|
||||
defer gui.Mutexes.SubprocessMutex.Unlock()
|
||||
|
||||
if Replaying() {
|
||||
// we do not yet support running subprocesses within integration tests. So if
|
||||
// we're replaying an integration test and we're inside this method, something
|
||||
// has gone wrong, so we should fail
|
||||
|
||||
log.Fatal("opening subprocesses not yet supported in integration tests. Chances are that this test is running too fast and a subprocess is accidentally opened")
|
||||
}
|
||||
|
||||
if err := gui.g.Suspend(); err != nil {
|
||||
return false, gui.c.Error(err)
|
||||
}
|
||||
|
||||
+18
-1
@@ -49,11 +49,28 @@ func (self *GuiDriver) CurrentContext() types.Context {
|
||||
return self.gui.c.CurrentContext()
|
||||
}
|
||||
|
||||
func (self *GuiDriver) ContextForView(viewName string) types.Context {
|
||||
context, ok := self.gui.contextForView(viewName)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
func (self *GuiDriver) Fail(message string) {
|
||||
currentView := self.gui.g.CurrentView()
|
||||
fullMessage := fmt.Sprintf(
|
||||
"%s\nFinal Lazygit state:\n%s\nUpon failure, focused view was '%s'.\nLog:\n%s", message,
|
||||
self.gui.g.Snapshot(),
|
||||
currentView.Name(),
|
||||
strings.Join(self.gui.CmdLog, "\n"),
|
||||
)
|
||||
|
||||
self.gui.g.Close()
|
||||
// need to give the gui time to close
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
panic(fmt.Sprintf("%s\nLog:\n%s", message, strings.Join(self.gui.CmdLog, "\n")))
|
||||
panic(fullMessage)
|
||||
}
|
||||
|
||||
// logs to the normal place that you log to i.e. viewable with `lazygit --logs`
|
||||
|
||||
+15
-13
@@ -74,12 +74,6 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: self.handleTopLevelReturn,
|
||||
},
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.ReturnAlt1),
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: self.handleTopLevelReturn,
|
||||
},
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.OpenRecentRepos),
|
||||
@@ -145,17 +139,19 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
Description: self.c.Tr.LcRefresh,
|
||||
},
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.OptionMenu),
|
||||
Handler: self.handleCreateOptionsMenu,
|
||||
Description: self.c.Tr.LcOpenMenu,
|
||||
OpensMenu: true,
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.OptionMenu),
|
||||
Handler: self.handleCreateOptionsMenu,
|
||||
OpensMenu: true,
|
||||
},
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.OptionMenuAlt1),
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: self.handleCreateOptionsMenu,
|
||||
// we have the description on the alt key and not the main key for legacy reasons
|
||||
// (the original main key was 'x' but we've reassigned that to other purposes)
|
||||
Description: self.c.Tr.LcOpenMenu,
|
||||
Handler: self.handleCreateOptionsMenu,
|
||||
},
|
||||
{
|
||||
ViewName: "status",
|
||||
@@ -211,6 +207,12 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
Handler: self.handleCopySelectedSideContextItemToClipboard,
|
||||
Description: self.c.Tr.LcCopyBranchNameToClipboard,
|
||||
},
|
||||
{
|
||||
ViewName: "remoteBranches",
|
||||
Key: opts.GetKey(opts.Config.Universal.CopyToClipboard),
|
||||
Handler: self.handleCopySelectedSideContextItemToClipboard,
|
||||
Description: self.c.Tr.LcCopyBranchNameToClipboard,
|
||||
},
|
||||
{
|
||||
ViewName: "commits",
|
||||
Key: opts.GetKey(opts.Config.Universal.CopyToClipboard),
|
||||
@@ -356,7 +358,7 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
Description: self.c.Tr.LcCopySubmoduleNameToClipboard,
|
||||
},
|
||||
{
|
||||
ViewName: "files",
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.ToggleWhitespaceInDiffView),
|
||||
Handler: self.toggleWhitespaceInDiffView,
|
||||
Description: self.c.Tr.ToggleWhitespaceInDiffView,
|
||||
|
||||
@@ -32,8 +32,8 @@ var keyMapReversed = map[gocui.Key]string{
|
||||
gocui.KeyPgdn: "pgdown",
|
||||
gocui.KeyArrowUp: "▲",
|
||||
gocui.KeyArrowDown: "▼",
|
||||
gocui.KeyArrowLeft: "◄",
|
||||
gocui.KeyArrowRight: "►",
|
||||
gocui.KeyArrowLeft: "◀",
|
||||
gocui.KeyArrowRight: "▶",
|
||||
gocui.KeyTab: "tab", // ctrl+i
|
||||
gocui.KeyBacktab: "shift+tab",
|
||||
gocui.KeyEnter: "enter", // ctrl+m
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user