mirror of
https://github.com/jesseduffield/lazygit.git
synced 2026-09-29 10:36:45 -04:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b571f9e6b | ||
|
|
df17896de5 | ||
|
|
22512d55a8 | ||
|
|
e799976b8a | ||
|
|
f93948cb23 | ||
|
|
0df5e08828 | ||
|
|
7238e41251 | ||
|
|
9ad50028f8 | ||
|
|
a7b0ccf059 | ||
|
|
d39f883b4e | ||
|
|
a01ca19bb3 | ||
|
|
4e38a941de | ||
|
|
471f72e607 | ||
|
|
49f2f818c6 | ||
|
|
f5cd02b54f | ||
|
|
fd01ca3acf | ||
|
|
4845ce1e0f | ||
|
|
0cc6e39f0f | ||
|
|
e90aeb62e5 | ||
|
|
17ab91e668 | ||
|
|
964278255b | ||
|
|
56695078c3 | ||
|
|
96934d5a1d | ||
|
|
f05f81d713 | ||
|
|
9d0740427e | ||
|
|
e62aeb99ed | ||
|
|
fcf48c4f08 | ||
|
|
2ceecad381 | ||
|
|
3b85307f67 | ||
|
|
30e9bf8a75 | ||
|
|
62c6ba7d57 | ||
|
|
72b9e8328d | ||
|
|
38ab7ebefb | ||
|
|
4b30bc6dd3 | ||
|
|
626ca18a23 | ||
|
|
87c3e75811 | ||
|
|
1e05055fff | ||
|
|
0ef3832e59 | ||
|
|
b766ff9c83 | ||
|
|
b2fd6128f6 | ||
|
|
a81f9ea97c | ||
|
|
101bbb0ac5 | ||
|
|
3e11e34181 | ||
|
|
daf1fd3419 | ||
|
|
54d0ebeff0 | ||
|
|
af9699e59a | ||
|
|
d92c6d116b | ||
|
|
343a3e466a | ||
|
|
16f5348790 | ||
|
|
5979b40546 | ||
|
|
a5f78d3222 | ||
|
|
f3791e6ab6 | ||
|
|
130801dbf6 | ||
|
|
67bb7f62c5 | ||
|
|
52b1c42d38 | ||
|
|
11616190ee | ||
|
|
e5137b86cf | ||
|
|
ac3824bd7c | ||
|
|
56c9d5abeb | ||
|
|
c9196812a2 | ||
|
|
caca62b89e | ||
|
|
e15e4951ab | ||
|
|
e3944c1707 | ||
|
|
0d155e1478 | ||
|
|
2fa4ee2cac | ||
|
|
a7bfeca9c0 | ||
|
|
ab23539c0c | ||
|
|
01eece3737 | ||
|
|
57220ba478 |
@@ -1,35 +0,0 @@
|
||||
name: Continuous Delivery
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
- name: Unshallow repo
|
||||
run: git fetch --prune --unshallow
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.22.x
|
||||
- name: Run goreleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: v1.17.2
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_API_TOKEN}}
|
||||
homebrew:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Bump Homebrew formula
|
||||
uses: dawidd6/action-homebrew-bump-formula@v3
|
||||
with:
|
||||
token: ${{secrets.GITHUB_API_TOKEN}}
|
||||
formula: lazygit
|
||||
@@ -1,24 +1,44 @@
|
||||
name: Automated Release
|
||||
name: Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 2:00 AM UTC on the first Saturday of every month
|
||||
- cron: '0 2 * * 6'
|
||||
workflow_dispatch: # Allow manual triggering of the workflow
|
||||
- cron: '0 2 1-7 * 6'
|
||||
# Allow manual triggering of the workflow
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version_bump:
|
||||
description: 'Version bump type'
|
||||
type: choice
|
||||
required: true
|
||||
default: 'patch'
|
||||
options:
|
||||
- minor
|
||||
- patch
|
||||
ignore_blocks:
|
||||
description: 'Ignore blocking PRs/issues'
|
||||
type: boolean
|
||||
required: true
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
check-and-release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get Latest Tag
|
||||
run: |
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1) || echo "v0.0.0")
|
||||
|
||||
if ! [[ $latest_tag =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Error: Tag format is invalid. Expected format: vX.X.X"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Latest tag: $latest_tag"
|
||||
echo "latest_tag=$latest_tag" >> $GITHUB_ENV
|
||||
|
||||
@@ -30,6 +50,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Check for Blocking Issues/PRs
|
||||
if: ${{ !inputs.ignore_blocks }}
|
||||
id: check_blocks
|
||||
run: |
|
||||
gh auth setup-git
|
||||
@@ -61,17 +82,56 @@ jobs:
|
||||
run: |
|
||||
echo "Latest tag: ${{ env.latest_tag }}"
|
||||
IFS='.' read -r major minor patch <<< "${{ env.latest_tag }}"
|
||||
new_minor=$((minor + 1))
|
||||
new_tag="$major.$new_minor.0"
|
||||
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
if [[ "${{ inputs.version_bump }}" == "patch" ]]; then
|
||||
patch=$((patch + 1))
|
||||
else
|
||||
minor=$((minor + 1))
|
||||
patch=0
|
||||
fi
|
||||
else
|
||||
# Default behavior for scheduled runs
|
||||
minor=$((minor + 1))
|
||||
patch=0
|
||||
fi
|
||||
|
||||
new_tag="$major.$minor.$patch"
|
||||
|
||||
if ! [[ $new_tag =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Error: New tag's format is invalid. Expected format: vX.X.X"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "New tag: $new_tag"
|
||||
echo "new_tag=$new_tag" >> $GITHUB_ENV
|
||||
|
||||
# This will trigger a deploy via .github/workflows/cd.yml
|
||||
- name: Push New Tag
|
||||
- name: Create and Push Tag
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag ${{ env.new_tag }}
|
||||
git push origin ${{ env.new_tag }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_API_TOKEN }}
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.22.x
|
||||
|
||||
- name: Run goreleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: v1.17.2
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_API_TOKEN}}
|
||||
|
||||
- name: Bump Homebrew formula
|
||||
uses: dawidd6/action-homebrew-bump-formula@v3
|
||||
with:
|
||||
token: ${{secrets.GITHUB_API_TOKEN}}
|
||||
formula: lazygit
|
||||
tag: ${{env.new_tag}}
|
||||
|
||||
Vendored
+9
@@ -26,6 +26,15 @@
|
||||
],
|
||||
"console": "integratedTerminal",
|
||||
},
|
||||
{
|
||||
"name": "JSON Schema generator",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}/pkg/jsonschema/generator.go",
|
||||
"cwd": "${workspaceFolder}/pkg/jsonschema",
|
||||
"console": "integratedTerminal",
|
||||
},
|
||||
{
|
||||
"name": "Attach to a running Lazygit",
|
||||
"type": "go",
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
<br>
|
||||
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=lazygit_20231023">
|
||||
<div>
|
||||
<img src="../assets/warp.png" width="230" alt="Warp">
|
||||
<img src="../assets/warp.png" width="330" alt="Warp">
|
||||
</div>
|
||||
<b>Warp is a modern, Rust-based terminal with AI built in so you and your team can build great software, faster.</b>
|
||||
<b>Warp, the intelligent terminal</b>
|
||||
<br>
|
||||
<b>Available for MacOS and Linux</b>
|
||||
<br>
|
||||
<div>
|
||||
<sup>Visit warp.dev to learn more.</sup>
|
||||
</div>
|
||||
|
||||
+28
-16
@@ -47,6 +47,10 @@ gui:
|
||||
# One of: 'margin' (default) | 'jump'
|
||||
scrollOffBehavior: margin
|
||||
|
||||
# The number of spaces per tab; used for everything that's shown in the main view, but probably mostly relevant for diffs.
|
||||
# Note that when using a pager, the pager has its own tab width setting, so you need to pass it separately in the pager command.
|
||||
tabWidth: 4
|
||||
|
||||
# If true, capture mouse events.
|
||||
# When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS.
|
||||
mouseEvents: true
|
||||
@@ -166,7 +170,7 @@ gui:
|
||||
showListFooter: true
|
||||
|
||||
# If true, display the files in the file views as a tree. If false, display the files as a flat list.
|
||||
# This can be toggled from within Lazygit with the '~' key, but that will not change the default.
|
||||
# This can be toggled from within Lazygit with the '`' key, but that will not change the default.
|
||||
showFileTree: true
|
||||
|
||||
# If true, show the number of lines changed per file in the Files view
|
||||
@@ -341,14 +345,6 @@ git:
|
||||
# If true, do not allow force pushes
|
||||
disableForcePushing: false
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix
|
||||
commitPrefix:
|
||||
# pattern to match on. E.g. for 'feature/AB-123' to match on the AB-123 use "^\\w+\\/(\\w+-\\w+).*"
|
||||
pattern: ""
|
||||
|
||||
# Replace directive. E.g. for 'feature/AB-123' to start the commit message with 'AB-123 ' use "[$1] "
|
||||
replace: ""
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix
|
||||
branchPrefix: ""
|
||||
|
||||
@@ -415,6 +411,9 @@ os:
|
||||
# window is closed.
|
||||
editAtLineAndWait: ""
|
||||
|
||||
# Whether lazygit suspends until an edit process returns
|
||||
editInTerminal: false
|
||||
|
||||
# For opening a directory in an editor
|
||||
openDirInEditor: ""
|
||||
|
||||
@@ -922,27 +921,40 @@ Where:
|
||||
## Predefined commit message prefix
|
||||
|
||||
In situations where certain naming pattern is used for branches and commits, pattern can be used to populate commit message with prefix that is parsed from the branch name.
|
||||
If you define multiple naming patterns, they will be attempted in order until one matches.
|
||||
|
||||
Example:
|
||||
Example hitting first match:
|
||||
|
||||
- Branch name: feature/AB-123
|
||||
- Commit message: [AB-123] Adding feature
|
||||
- Generated commit message prefix: [AB-123]
|
||||
|
||||
Example hitting second match:
|
||||
|
||||
- Branch name: CD-456_fix_problem
|
||||
- Generated commit message prefix: (CD-456)
|
||||
|
||||
```yaml
|
||||
git:
|
||||
commitPrefix:
|
||||
pattern: "^\\w+\\/(\\w+-\\w+).*"
|
||||
replace: '[$1] '
|
||||
- pattern: "^\\w+\\/(\\w+-\\w+).*"
|
||||
replace: '[$1] '
|
||||
- pattern: "^([^_]+)_.*" # Take all text prior to the first underscore
|
||||
replace: '($1) '
|
||||
```
|
||||
|
||||
If you want repository-specific prefixes, you can map them with `commitPrefixes`. If you have both `commitPrefixes` defined and an entry in `commitPrefixes` for the current repo, the `commitPrefixes` entry is given higher precedence. Repository folder names must be an exact match.
|
||||
If you want repository-specific prefixes, you can map them with `commitPrefixes`. If you have both entries in `commitPrefix` defined and an repository match in `commitPrefixes` for the current repo, the `commitPrefixes` entries will be attempted first. Repository folder names must be an exact match.
|
||||
|
||||
```yaml
|
||||
git:
|
||||
commitPrefixes:
|
||||
my_project: # This is repository folder name
|
||||
pattern: "^\\w+\\/(\\w+-\\w+).*"
|
||||
replace: '[$1] '
|
||||
- pattern: "^\\w+\\/(\\w+-\\w+).*"
|
||||
replace: '[$1] '
|
||||
commitPrefix:
|
||||
- pattern: "^(\\w+)-.*" # A more general match for any leading word
|
||||
replace : '[$1] '
|
||||
- pattern: ".*" # The final fallthrough regex that copies over the whole branch name
|
||||
replace : '[$0] '
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Custom Command Keybindings
|
||||
|
||||
You can add custom command keybindings in your config.yml (accessible by pressing 'o' on the status panel from within lazygit) like so:
|
||||
You can add custom command keybindings in your config.yml (accessible by pressing 'e' on the status panel from within lazygit) like so:
|
||||
|
||||
```yml
|
||||
customCommands:
|
||||
@@ -324,6 +324,27 @@ We don't support accessing all elements of a range selection yet. We might add t
|
||||
|
||||
If your custom keybinding collides with an inbuilt keybinding that is defined for the same context, only the custom keybinding will be executed. This also applies to the global context. However, one caveat is that if you have a custom keybinding defined on the global context for some key, and there is an in-built keybinding defined for the same key and for a specific context (say the 'files' context), then the in-built keybinding will take precedence. See how to change in-built keybindings [here](https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#keybindings)
|
||||
|
||||
## Menus of custom commands
|
||||
|
||||
For custom commands that are not used very frequently it may be preferable to hide them in a menu; you can assign a key to open the menu, and the commands will appear inside. This has the advantage that you don't have to come up with individual unique keybindings for all those commands that you don't use often; the keybindings for the commands in the menu only need to be unique within the menu. Here is an example:
|
||||
|
||||
```yml
|
||||
customCommands:
|
||||
- key: X
|
||||
description: "Copy/paste commits across repos"
|
||||
commandMenu:
|
||||
- key: c
|
||||
command: 'git format-patch --stdout {{.SelectedCommitRange.From}}^..{{.SelectedCommitRange.To}} | pbcopy'
|
||||
context: commits, subCommits
|
||||
description: "Copy selected commits to clipboard"
|
||||
- key: v
|
||||
command: 'pbpaste | git am'
|
||||
context: "commits"
|
||||
description: "Paste selected commits from clipboard"
|
||||
```
|
||||
|
||||
If you use the commandMenu property, none of the other properties except key and description can be used.
|
||||
|
||||
## Debugging
|
||||
|
||||
If you want to verify that your command actually does what you expect, you can wrap it in an 'echo' call and set `showOutput: true` so that it doesn't actually execute the command but you can see how the placeholders were resolved.
|
||||
|
||||
@@ -20,11 +20,15 @@
|
||||
| `<pgup>` | Pgup |
|
||||
| `<pgdown>` | Pgdn |
|
||||
| `<up>` | ArrowUp |
|
||||
| `<s-up>` | ShiftArrowUp |
|
||||
| `<down>` | ArrowDown |
|
||||
| `<s-down>` | ShiftArrowDown |
|
||||
| `<left>` | ArrowLeft |
|
||||
| `<right>` | ArrowRight |
|
||||
| `<tab>` | Tab |
|
||||
| `<backtab>` | Backtab |
|
||||
| `<enter>` | Enter |
|
||||
| `<a-enter>` | AltEnter |
|
||||
| `<esc>` | Esc |
|
||||
| `<backspace>` | Backspace |
|
||||
| `<c-space>` | CtrlSpace |
|
||||
|
||||
@@ -56,6 +56,7 @@ _Legend: `<c-b>` means ctrl+b, `<a-b>` means alt+b, `B` means shift+b_
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | Copy path to clipboard | |
|
||||
| `` y `` | Copy to clipboard | |
|
||||
| `` c `` | Checkout | Checkout file. This replaces the file in your working tree with the version from the selected commit. |
|
||||
| `` d `` | Remove | Discard this commit's changes to this file. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes this file. |
|
||||
| `` o `` | Open file | Open file in default application. |
|
||||
|
||||
@@ -134,6 +134,7 @@ If you would instead like to start an interactive rebase from the selected commi
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | ファイル名をクリップボードにコピー | |
|
||||
| `` y `` | Copy to clipboard | |
|
||||
| `` c `` | チェックアウト | Checkout file. This replaces the file in your working tree with the version from the selected commit. |
|
||||
| `` d `` | Remove | Discard this commit's changes to this file. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes this file. |
|
||||
| `` o `` | ファイルを開く | Open file in default application. |
|
||||
|
||||
@@ -299,6 +299,7 @@ If you would instead like to start an interactive rebase from the selected commi
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | 파일명을 클립보드에 복사 | |
|
||||
| `` y `` | 클립보드에 복사 | |
|
||||
| `` c `` | 체크아웃 | Checkout file |
|
||||
| `` d `` | Remove | Discard this commit's changes to this file |
|
||||
| `` o `` | 파일 닫기 | Open file in default application. |
|
||||
|
||||
@@ -129,6 +129,7 @@ _Legend: `<c-b>` means ctrl+b, `<a-b>` means alt+b, `B` means shift+b_
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | Kopieer de bestandsnaam naar het klembord | |
|
||||
| `` y `` | Copy to clipboard | |
|
||||
| `` c `` | Uitchecken | Bestand uitchecken |
|
||||
| `` d `` | Remove | Uitsluit deze commit zijn veranderingen aan dit bestand |
|
||||
| `` o `` | Open bestand | Open file in default application. |
|
||||
|
||||
@@ -238,6 +238,7 @@ Jeśli chcesz zamiast tego rozpocząć interaktywny rebase od wybranego commita,
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | Kopiuj ścieżkę do schowka | |
|
||||
| `` y `` | Kopiuj do schowka | |
|
||||
| `` c `` | Przełącz | Przełącz plik. Zastępuje plik w twoim drzewie roboczym wersją z wybranego commita. |
|
||||
| `` d `` | Usuń | Odrzuć zmiany w tym pliku z tego commita. Uruchamia interaktywny rebase w tle, więc możesz otrzymać konflikt scalania, jeśli późniejszy commit również zmienia ten plik. |
|
||||
| `` o `` | Otwórz plik | Otwórz plik w domyślnej aplikacji. |
|
||||
|
||||
@@ -135,6 +135,7 @@ Veja a documentação:
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | Copy path to clipboard | |
|
||||
| `` y `` | Copy to clipboard | |
|
||||
| `` c `` | Verificar | Checkout file. This replaces the file in your working tree with the version from the selected commit. |
|
||||
| `` d `` | Remove | Discard this commit's changes to this file. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes this file. |
|
||||
| `` o `` | Abrir arquivo | Abrir arquivo no aplicativo padrão. |
|
||||
|
||||
@@ -261,6 +261,7 @@ If you would instead like to start an interactive rebase from the selected commi
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | Скопировать название файла в буфер обмена | |
|
||||
| `` y `` | Copy to clipboard | |
|
||||
| `` c `` | Переключить | Переключить файл |
|
||||
| `` d `` | Remove | Отменить изменения коммита в этом файле |
|
||||
| `` o `` | Открыть файл | Open file in default application. |
|
||||
|
||||
@@ -186,6 +186,7 @@ _图例:`<c-b>` 意味着ctrl+b, `<a-b>意味着Alt+b, `B` 意味着shift+b_
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | 将文件名复制到剪贴板 | |
|
||||
| `` y `` | 复制到剪贴板 | |
|
||||
| `` c `` | 检出 | 检出文件 |
|
||||
| `` d `` | 删除 | 放弃对此文件的提交变更 |
|
||||
| `` o `` | 打开文件 | 使用默认程序打开该文件 |
|
||||
|
||||
@@ -210,6 +210,7 @@ If you would instead like to start an interactive rebase from the selected commi
|
||||
| Key | Action | Info |
|
||||
|-----|--------|-------------|
|
||||
| `` <c-o> `` | 複製檔案名稱到剪貼簿 | |
|
||||
| `` y `` | 複製到剪貼簿 | |
|
||||
| `` c `` | 檢出 | 檢出檔案 |
|
||||
| `` d `` | Remove | Discard this commit's changes to this file. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes this file. |
|
||||
| `` o `` | 開啟檔案 | 使用預設軟體開啟 |
|
||||
|
||||
@@ -11,12 +11,11 @@ require (
|
||||
github.com/gdamore/tcell/v2 v2.8.1
|
||||
github.com/go-errors/errors v1.5.1
|
||||
github.com/gookit/color v1.4.2
|
||||
github.com/iancoleman/orderedmap v0.3.0
|
||||
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.20250210123912-aba68ae65951
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20250220081214-b376cb0857ac
|
||||
github.com/jesseduffield/kill v0.0.0-20250101124109-e216ddbe133a
|
||||
github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5
|
||||
github.com/jesseduffield/minimal/gitignore v0.3.3-0.20211018110810-9cde264e6b1e
|
||||
|
||||
@@ -171,8 +171,6 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
|
||||
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/iancoleman/orderedmap v0.3.0 h1:5cbR2grmZR/DiVt+VJopEhtVs9YGInGIxAoMJn+Ichc=
|
||||
github.com/iancoleman/orderedmap v0.3.0/go.mod h1:XuLcCUkdL5owUCQeF2Ue9uuw1EptkJDkXXS7VoV7XGE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
|
||||
@@ -188,8 +186,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.20250210123912-aba68ae65951 h1:7/3M0yosAM9/aLAjTfzSJWhsWjT860ZVe4T76RPwE2k=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20250210123912-aba68ae65951/go.mod h1:sLIyZ2J42R6idGdtemZzsiR3xY5EF0KsvYEGh3dQv3s=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20250220081214-b376cb0857ac h1:vUNTiVEB9Bz16pTJ5kNgb/1HhnWdSA1P0GfFLUJeITI=
|
||||
github.com/jesseduffield/gocui v0.3.1-0.20250220081214-b376cb0857ac/go.mod h1:sLIyZ2J42R6idGdtemZzsiR3xY5EF0KsvYEGh3dQv3s=
|
||||
github.com/jesseduffield/kill v0.0.0-20250101124109-e216ddbe133a h1:UDeJ3EBk04bXDLOPvuqM3on8HvyJfISw0+UMqW+0a4g=
|
||||
github.com/jesseduffield/kill v0.0.0-20250101124109-e216ddbe133a/go.mod h1:FSWDLKT0NQpntbDd1H3lbz51fhCVlMzy/J0S6nM727Q=
|
||||
github.com/jesseduffield/lazycore v0.0.0-20221012050358-03d2e40243c5 h1:CDuQmfOjAtb1Gms6a1p5L2P8RhbLUq5t8aL7PiQd2uY=
|
||||
|
||||
@@ -149,7 +149,7 @@ func TestRebaseDiscardOldFileChanges(t *testing.T) {
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"rebase", "--interactive", "--autostash", "--keep-empty", "--no-autosquash", "--rebase-merges", "abcdef"}, "", nil).
|
||||
ExpectGitArgs([]string{"cat-file", "-e", "HEAD^:test999.txt"}, "", nil).
|
||||
ExpectGitArgs([]string{"checkout", "HEAD^", "--", "test999.txt"}, "", nil).
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "HEAD^", "--", "test999.txt"}, "", nil).
|
||||
ExpectGitArgs([]string{"commit", "--amend", "--no-edit", "--allow-empty"}, "", nil).
|
||||
ExpectGitArgs([]string{"rebase", "--continue"}, "", nil),
|
||||
test: func(err error) {
|
||||
|
||||
@@ -81,9 +81,11 @@ func (self *StashCommands) Hash(index int) (string, error) {
|
||||
}
|
||||
|
||||
func (self *StashCommands) ShowStashEntryCmdObj(index int) oscommands.ICmdObj {
|
||||
// "-u" is the same as "--include-untracked", but the latter fails in older git versions for some reason
|
||||
cmdArgs := NewGitCmd("stash").Arg("show").
|
||||
Arg("-p").
|
||||
Arg("--stat").
|
||||
Arg("-u").
|
||||
Arg(fmt.Sprintf("--color=%s", self.UserConfig().Git.Paging.ColorArg)).
|
||||
Arg(fmt.Sprintf("--unified=%d", self.AppState.DiffContextSize)).
|
||||
ArgIf(self.AppState.IgnoreWhitespaceInDiffView, "--ignore-all-space").
|
||||
|
||||
@@ -113,7 +113,7 @@ func TestStashStashEntryCmdObj(t *testing.T) {
|
||||
contextSize: 3,
|
||||
similarityThreshold: 50,
|
||||
ignoreWhitespace: false,
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "--color=always", "--unified=3", "--find-renames=50%", "stash@{5}"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "-u", "--color=always", "--unified=3", "--find-renames=50%", "stash@{5}"},
|
||||
},
|
||||
{
|
||||
testName: "Show diff with custom context size",
|
||||
@@ -121,7 +121,7 @@ func TestStashStashEntryCmdObj(t *testing.T) {
|
||||
contextSize: 77,
|
||||
similarityThreshold: 50,
|
||||
ignoreWhitespace: false,
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "--color=always", "--unified=77", "--find-renames=50%", "stash@{5}"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "-u", "--color=always", "--unified=77", "--find-renames=50%", "stash@{5}"},
|
||||
},
|
||||
{
|
||||
testName: "Show diff with custom similarity threshold",
|
||||
@@ -129,7 +129,7 @@ func TestStashStashEntryCmdObj(t *testing.T) {
|
||||
contextSize: 3,
|
||||
similarityThreshold: 33,
|
||||
ignoreWhitespace: false,
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "--color=always", "--unified=3", "--find-renames=33%", "stash@{5}"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "-u", "--color=always", "--unified=3", "--find-renames=33%", "stash@{5}"},
|
||||
},
|
||||
{
|
||||
testName: "Default case",
|
||||
@@ -137,7 +137,7 @@ func TestStashStashEntryCmdObj(t *testing.T) {
|
||||
contextSize: 3,
|
||||
similarityThreshold: 50,
|
||||
ignoreWhitespace: true,
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "--color=always", "--unified=3", "--ignore-all-space", "--find-renames=50%", "stash@{5}"},
|
||||
expected: []string{"git", "-C", "/path/to/worktree", "stash", "show", "-p", "--stat", "-u", "--color=always", "--unified=3", "--ignore-all-space", "--find-renames=50%", "stash@{5}"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,10 @@ func (self *WorkingTreeCommands) BeforeAndAfterFileForRename(file *models.File)
|
||||
return beforeFile, afterFile, nil
|
||||
}
|
||||
|
||||
func newCheckoutCommand() *GitCommandBuilder {
|
||||
return NewGitCmd("checkout").Config(fmt.Sprintf("core.hooksPath=%s", os.DevNull))
|
||||
}
|
||||
|
||||
// DiscardAllFileChanges directly
|
||||
func (self *WorkingTreeCommands) DiscardAllFileChanges(file *models.File) error {
|
||||
if file.IsRename() {
|
||||
@@ -130,7 +134,7 @@ func (self *WorkingTreeCommands) DiscardAllFileChanges(file *models.File) error
|
||||
|
||||
if file.ShortStatus == "AA" {
|
||||
if err := self.cmd.New(
|
||||
NewGitCmd("checkout").Arg("--ours", "--", file.Name).ToArgv(),
|
||||
newCheckoutCommand().Arg("--ours", "--", file.Name).ToArgv(),
|
||||
).Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,7 +193,7 @@ func (self *WorkingTreeCommands) DiscardUnstagedDirChanges(node IFileNode) error
|
||||
return err
|
||||
}
|
||||
|
||||
cmdArgs := NewGitCmd("checkout").Arg("--", node.GetPath()).ToArgv()
|
||||
cmdArgs := newCheckoutCommand().Arg("--", node.GetPath()).ToArgv()
|
||||
if err := self.cmd.New(cmdArgs).Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -222,7 +226,7 @@ func (self *WorkingTreeCommands) RemoveUntrackedDirFiles(node IFileNode) error {
|
||||
}
|
||||
|
||||
func (self *WorkingTreeCommands) DiscardUnstagedFileChanges(file *models.File) error {
|
||||
cmdArgs := NewGitCmd("checkout").Arg("--", file.Name).ToArgv()
|
||||
cmdArgs := newCheckoutCommand().Arg("--", file.Name).ToArgv()
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
}
|
||||
|
||||
@@ -315,7 +319,7 @@ func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reve
|
||||
|
||||
// CheckoutFile checks out the file for the given commit
|
||||
func (self *WorkingTreeCommands) CheckoutFile(commitHash, fileName string) error {
|
||||
cmdArgs := NewGitCmd("checkout").Arg(commitHash, "--", fileName).
|
||||
cmdArgs := newCheckoutCommand().Arg(commitHash, "--", fileName).
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
@@ -323,7 +327,7 @@ func (self *WorkingTreeCommands) CheckoutFile(commitHash, fileName string) error
|
||||
|
||||
// DiscardAnyUnstagedFileChanges discards any unstaged file changes via `git checkout -- .`
|
||||
func (self *WorkingTreeCommands) DiscardAnyUnstagedFileChanges() error {
|
||||
cmdArgs := NewGitCmd("checkout").Arg("--", ".").
|
||||
cmdArgs := newCheckoutCommand().Arg("--", ".").
|
||||
ToArgv()
|
||||
|
||||
return self.cmd.New(cmdArgs).Run()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package git_commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
@@ -10,6 +12,8 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var disableHooksFlag = fmt.Sprintf("core.hooksPath=%s", os.DevNull)
|
||||
|
||||
func TestWorkingTreeStageFile(t *testing.T) {
|
||||
runner := oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"add", "--", "test.txt"}, "", nil)
|
||||
@@ -113,7 +117,7 @@ func TestWorkingTreeDiscardAllFileChanges(t *testing.T) {
|
||||
},
|
||||
removeFile: func(string) error { return nil },
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "--", "test"}, "", errors.New("error")),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "test"}, "", errors.New("error")),
|
||||
expectedError: "error",
|
||||
},
|
||||
{
|
||||
@@ -125,7 +129,7 @@ func TestWorkingTreeDiscardAllFileChanges(t *testing.T) {
|
||||
},
|
||||
removeFile: func(string) error { return nil },
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "--", "test"}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "test"}, "", nil),
|
||||
expectedError: "",
|
||||
},
|
||||
{
|
||||
@@ -138,7 +142,7 @@ func TestWorkingTreeDiscardAllFileChanges(t *testing.T) {
|
||||
removeFile: func(string) error { return nil },
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reset", "--", "test"}, "", nil).
|
||||
ExpectGitArgs([]string{"checkout", "--", "test"}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "test"}, "", nil),
|
||||
expectedError: "",
|
||||
},
|
||||
{
|
||||
@@ -151,7 +155,7 @@ func TestWorkingTreeDiscardAllFileChanges(t *testing.T) {
|
||||
removeFile: func(string) error { return nil },
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"reset", "--", "test"}, "", nil).
|
||||
ExpectGitArgs([]string{"checkout", "--", "test"}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "test"}, "", nil),
|
||||
expectedError: "",
|
||||
},
|
||||
{
|
||||
@@ -428,7 +432,7 @@ func TestWorkingTreeCheckoutFile(t *testing.T) {
|
||||
commitHash: "11af912",
|
||||
fileName: "test999.txt",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "11af912", "--", "test999.txt"}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "11af912", "--", "test999.txt"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -438,7 +442,7 @@ func TestWorkingTreeCheckoutFile(t *testing.T) {
|
||||
commitHash: "11af912",
|
||||
fileName: "test999.txt",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "11af912", "--", "test999.txt"}, "", errors.New("error")),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "11af912", "--", "test999.txt"}, "", errors.New("error")),
|
||||
test: func(err error) {
|
||||
assert.Error(t, err)
|
||||
},
|
||||
@@ -468,7 +472,7 @@ func TestWorkingTreeDiscardUnstagedFileChanges(t *testing.T) {
|
||||
testName: "valid case",
|
||||
file: &models.File{Name: "test.txt"},
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "--", "test.txt"}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "test.txt"}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
@@ -495,7 +499,7 @@ func TestWorkingTreeDiscardAnyUnstagedFileChanges(t *testing.T) {
|
||||
{
|
||||
testName: "valid case",
|
||||
runner: oscommands.NewFakeRunner(t).
|
||||
ExpectGitArgs([]string{"checkout", "--", "."}, "", nil),
|
||||
ExpectGitArgs([]string{"-c", disableHooksFlag, "checkout", "--", "."}, "", nil),
|
||||
test: func(err error) {
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
|
||||
+101
-27
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -217,32 +218,11 @@ func loadUserConfig(configFiles []*ConfigFile, base *UserConfig) (*UserConfig, e
|
||||
// from one container to another, or changing the type of a key (e.g. from bool
|
||||
// to an enum).
|
||||
func migrateUserConfig(path string, content []byte) ([]byte, error) {
|
||||
changedContent := content
|
||||
|
||||
pathsToReplace := []struct {
|
||||
oldPath []string
|
||||
newName string
|
||||
}{
|
||||
{[]string{"gui", "skipUnstageLineWarning"}, "skipDiscardChangeWarning"},
|
||||
{[]string{"keybinding", "universal", "executeCustomCommand"}, "executeShellCommand"},
|
||||
{[]string{"gui", "windowSize"}, "screenMode"},
|
||||
}
|
||||
|
||||
var err error
|
||||
for _, pathToReplace := range pathsToReplace {
|
||||
changedContent, err = yaml_utils.RenameYamlKey(changedContent, pathToReplace.oldPath, pathToReplace.newName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s` for key %s: %s", path, strings.Join(pathToReplace.oldPath, "."), err)
|
||||
}
|
||||
}
|
||||
|
||||
changedContent, err = changeNullKeybindingsToDisabled(changedContent)
|
||||
changedContent, err := computeMigratedConfig(path, content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s`: %s", path, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add more migrations here...
|
||||
|
||||
// Write config back if changed
|
||||
if string(changedContent) != string(content) {
|
||||
fmt.Println("Provided user config is deprecated but auto-fixable. Attempting to write fixed version back to file...")
|
||||
@@ -256,14 +236,108 @@ func migrateUserConfig(path string, content []byte) ([]byte, error) {
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func changeNullKeybindingsToDisabled(changedContent []byte) ([]byte, error) {
|
||||
return yaml_utils.Walk(changedContent, func(node *yaml.Node, path string) bool {
|
||||
// A pure function helper for testing purposes
|
||||
func computeMigratedConfig(path string, content []byte) ([]byte, error) {
|
||||
var err error
|
||||
var rootNode yaml.Node
|
||||
err = yaml.Unmarshal(content, &rootNode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse YAML: %w", err)
|
||||
}
|
||||
var originalCopy yaml.Node
|
||||
err = yaml.Unmarshal(content, &originalCopy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse YAML, but only the second time!?!? How did that happen: %w", err)
|
||||
}
|
||||
|
||||
pathsToReplace := []struct {
|
||||
oldPath []string
|
||||
newName string
|
||||
}{
|
||||
{[]string{"gui", "skipUnstageLineWarning"}, "skipDiscardChangeWarning"},
|
||||
{[]string{"keybinding", "universal", "executeCustomCommand"}, "executeShellCommand"},
|
||||
{[]string{"gui", "windowSize"}, "screenMode"},
|
||||
}
|
||||
|
||||
for _, pathToReplace := range pathsToReplace {
|
||||
err := yaml_utils.RenameYamlKey(&rootNode, pathToReplace.oldPath, pathToReplace.newName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s` for key %s: %s", path, strings.Join(pathToReplace.oldPath, "."), err)
|
||||
}
|
||||
}
|
||||
|
||||
err = changeNullKeybindingsToDisabled(&rootNode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s`: %s", path, err)
|
||||
}
|
||||
|
||||
err = changeElementToSequence(&rootNode, []string{"git", "commitPrefix"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s`: %s", path, err)
|
||||
}
|
||||
|
||||
err = changeCommitPrefixesMap(&rootNode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Couldn't migrate config file at `%s`: %s", path, err)
|
||||
}
|
||||
|
||||
// Add more migrations here...
|
||||
|
||||
if !reflect.DeepEqual(rootNode, originalCopy) {
|
||||
newContent, err := yaml_utils.YamlMarshal(&rootNode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to remarsal!\n %w", err)
|
||||
}
|
||||
return newContent, nil
|
||||
} else {
|
||||
return content, nil
|
||||
}
|
||||
}
|
||||
|
||||
func changeNullKeybindingsToDisabled(rootNode *yaml.Node) error {
|
||||
return yaml_utils.Walk(rootNode, func(node *yaml.Node, path string) {
|
||||
if strings.HasPrefix(path, "keybinding.") && node.Kind == yaml.ScalarNode && node.Tag == "!!null" {
|
||||
node.Value = "<disabled>"
|
||||
node.Tag = "!!str"
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func changeElementToSequence(rootNode *yaml.Node, path []string) error {
|
||||
return yaml_utils.TransformNode(rootNode, path, func(node *yaml.Node) error {
|
||||
if node.Kind == yaml.MappingNode {
|
||||
nodeContentCopy := node.Content
|
||||
node.Kind = yaml.SequenceNode
|
||||
node.Value = ""
|
||||
node.Tag = "!!seq"
|
||||
node.Content = []*yaml.Node{{
|
||||
Kind: yaml.MappingNode,
|
||||
Content: nodeContentCopy,
|
||||
}}
|
||||
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func changeCommitPrefixesMap(rootNode *yaml.Node) error {
|
||||
return yaml_utils.TransformNode(rootNode, []string{"git", "commitPrefixes"}, func(prefixesNode *yaml.Node) error {
|
||||
if prefixesNode.Kind == yaml.MappingNode {
|
||||
for _, contentNode := range prefixesNode.Content {
|
||||
if contentNode.Kind == yaml.MappingNode {
|
||||
nodeContentCopy := contentNode.Content
|
||||
contentNode.Kind = yaml.SequenceNode
|
||||
contentNode.Value = ""
|
||||
contentNode.Tag = "!!seq"
|
||||
contentNode.Content = []*yaml.Node{{
|
||||
Kind: yaml.MappingNode,
|
||||
Content: nodeContentCopy,
|
||||
}}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCommitPrefixMigrations(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Empty String",
|
||||
input: "",
|
||||
expected: "",
|
||||
}, {
|
||||
name: "Single CommitPrefix Rename",
|
||||
input: `git:
|
||||
commitPrefix:
|
||||
pattern: "^\\w+-\\w+.*"
|
||||
replace: '[JIRA $0] '
|
||||
`,
|
||||
expected: `git:
|
||||
commitPrefix:
|
||||
- pattern: "^\\w+-\\w+.*"
|
||||
replace: '[JIRA $0] '
|
||||
`,
|
||||
}, {
|
||||
name: "Complicated CommitPrefixes Rename",
|
||||
input: `git:
|
||||
commitPrefixes:
|
||||
foo:
|
||||
pattern: "^\\w+-\\w+.*"
|
||||
replace: '[OTHER $0] '
|
||||
CrazyName!@#$^*&)_-)[[}{f{[]:
|
||||
pattern: "^foo.bar*"
|
||||
replace: '[FUN $0] '
|
||||
`,
|
||||
expected: `git:
|
||||
commitPrefixes:
|
||||
foo:
|
||||
- pattern: "^\\w+-\\w+.*"
|
||||
replace: '[OTHER $0] '
|
||||
CrazyName!@#$^*&)_-)[[}{f{[]:
|
||||
- pattern: "^foo.bar*"
|
||||
replace: '[FUN $0] '
|
||||
`,
|
||||
}, {
|
||||
name: "Incomplete Configuration",
|
||||
input: "git:",
|
||||
expected: "git:",
|
||||
}, {
|
||||
// This test intentionally uses non-standard indentation to test that the migration
|
||||
// does not change the input.
|
||||
name: "No changes made when already migrated",
|
||||
input: `
|
||||
git:
|
||||
commitPrefix:
|
||||
- pattern: "Hello World"
|
||||
replace: "Goodbye"
|
||||
commitPrefixes:
|
||||
foo:
|
||||
- pattern: "^\\w+-\\w+.*"
|
||||
replace: '[JIRA $0] '`,
|
||||
expected: `
|
||||
git:
|
||||
commitPrefix:
|
||||
- pattern: "Hello World"
|
||||
replace: "Goodbye"
|
||||
commitPrefixes:
|
||||
foo:
|
||||
- pattern: "^\\w+-\\w+.*"
|
||||
replace: '[JIRA $0] '`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, func(t *testing.T) {
|
||||
actual, err := computeMigratedConfig("path doesn't matter", []byte(s.input))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, s.expected, string(actual))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var largeConfiguration = []byte(`
|
||||
# Config relating to the Lazygit UI
|
||||
gui:
|
||||
# The number of lines you scroll by when scrolling the main window
|
||||
scrollHeight: 2
|
||||
|
||||
# If true, allow scrolling past the bottom of the content in the main window
|
||||
scrollPastBottom: true
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#scroll-off-margin
|
||||
scrollOffMargin: 2
|
||||
|
||||
# One of: 'margin' (default) | 'jump'
|
||||
scrollOffBehavior: margin
|
||||
|
||||
# The number of spaces per tab; used for everything that's shown in the main view, but probably mostly relevant for diffs.
|
||||
# Note that when using a pager, the pager has its own tab width setting, so you need to pass it separately in the pager command.
|
||||
tabWidth: 4
|
||||
|
||||
# If true, capture mouse events.
|
||||
# When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS.
|
||||
mouseEvents: true
|
||||
|
||||
# If true, do not show a warning when discarding changes in the staging view.
|
||||
skipDiscardChangeWarning: false
|
||||
|
||||
# If true, do not show warning when applying/popping the stash
|
||||
skipStashWarning: false
|
||||
|
||||
# If true, do not show a warning when attempting to commit without any staged files; instead stage all unstaged files.
|
||||
skipNoStagedFilesWarning: false
|
||||
|
||||
# If true, do not show a warning when rewording a commit via an external editor
|
||||
skipRewordInEditorWarning: false
|
||||
|
||||
# Fraction of the total screen width to use for the left side section. You may want to pick a small number (e.g. 0.2) if you're using a narrow screen, so that you can see more of the main section.
|
||||
# Number from 0 to 1.0.
|
||||
sidePanelWidth: 0.3333
|
||||
|
||||
# If true, increase the height of the focused side window; creating an accordion effect.
|
||||
expandFocusedSidePanel: false
|
||||
|
||||
# The weight of the expanded side panel, relative to the other panels. 2 means
|
||||
# twice as tall as the other panels. Only relevant if expandFocusedSidePanel is true.
|
||||
expandedSidePanelWeight: 2
|
||||
|
||||
# Sometimes the main window is split in two (e.g. when the selected file has both staged and unstaged changes). This setting controls how the two sections are split.
|
||||
# Options are:
|
||||
# - 'horizontal': split the window horizontally
|
||||
# - 'vertical': split the window vertically
|
||||
# - 'flexible': (default) split the window horizontally if the window is wide enough, otherwise split vertically
|
||||
mainPanelSplitMode: flexible
|
||||
|
||||
# How the window is split when in half screen mode (i.e. after hitting '+' once).
|
||||
# Possible values:
|
||||
# - 'left': split the window horizontally (side panel on the left, main view on the right)
|
||||
# - 'top': split the window vertically (side panel on top, main view below)
|
||||
enlargedSideViewLocation: left
|
||||
|
||||
# If true, wrap lines in the staging view to the width of the view. This
|
||||
# makes it much easier to work with diffs that have long lines, e.g.
|
||||
# paragraphs of markdown text.
|
||||
wrapLinesInStagingView: true
|
||||
|
||||
# One of 'auto' (default) | 'en' | 'zh-CN' | 'zh-TW' | 'pl' | 'nl' | 'ja' | 'ko' | 'ru'
|
||||
language: auto
|
||||
|
||||
# Format used when displaying time e.g. commit time.
|
||||
# Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
|
||||
timeFormat: 02 Jan 06
|
||||
|
||||
# Format used when displaying time if the time is less than 24 hours ago.
|
||||
# Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
|
||||
shortTimeFormat: 3:04PM
|
||||
|
||||
# Config relating to colors and styles.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes
|
||||
theme:
|
||||
# Border color of focused window
|
||||
activeBorderColor:
|
||||
- green
|
||||
- bold
|
||||
|
||||
# Border color of non-focused windows
|
||||
inactiveBorderColor:
|
||||
- default
|
||||
|
||||
# Border color of focused window when searching in that window
|
||||
searchingActiveBorderColor:
|
||||
- cyan
|
||||
- bold
|
||||
|
||||
# Color of keybindings help text in the bottom line
|
||||
optionsTextColor:
|
||||
- blue
|
||||
|
||||
# Background color of selected line.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line
|
||||
selectedLineBgColor:
|
||||
- blue
|
||||
|
||||
# Background color of selected line when view doesn't have focus.
|
||||
inactiveViewSelectedLineBgColor:
|
||||
- bold
|
||||
|
||||
# Foreground color of copied commit
|
||||
cherryPickedCommitFgColor:
|
||||
- blue
|
||||
|
||||
# Background color of copied commit
|
||||
cherryPickedCommitBgColor:
|
||||
- cyan
|
||||
|
||||
# Foreground color of marked base commit (for rebase)
|
||||
markedBaseCommitFgColor:
|
||||
- blue
|
||||
|
||||
# Background color of marked base commit (for rebase)
|
||||
markedBaseCommitBgColor:
|
||||
- yellow
|
||||
|
||||
# Color for file with unstaged changes
|
||||
unstagedChangesColor:
|
||||
- red
|
||||
|
||||
# Default text color
|
||||
defaultFgColor:
|
||||
- default
|
||||
|
||||
# Config relating to the commit length indicator
|
||||
commitLength:
|
||||
# If true, show an indicator of commit message length
|
||||
show: true
|
||||
|
||||
# If true, show the '5 of 20' footer at the bottom of list views
|
||||
showListFooter: true
|
||||
|
||||
# If true, display the files in the file views as a tree. If false, display the files as a flat list.
|
||||
# This can be toggled from within Lazygit with the '' key, but that will not change the default.
|
||||
showFileTree: true
|
||||
|
||||
# If true, show the number of lines changed per file in the Files view
|
||||
showNumstatInFilesView: false
|
||||
|
||||
# If true, show a random tip in the command log when Lazygit starts
|
||||
showRandomTip: true
|
||||
|
||||
# If true, show the command log
|
||||
showCommandLog: true
|
||||
|
||||
# If true, show the bottom line that contains keybinding info and useful buttons. If false, this line will be hidden except to display a loader for an in-progress action.
|
||||
showBottomLine: true
|
||||
|
||||
# If true, show jump-to-window keybindings in window titles.
|
||||
showPanelJumps: true
|
||||
|
||||
# Deprecated: use nerdFontsVersion instead
|
||||
showIcons: false
|
||||
|
||||
# Nerd fonts version to use.
|
||||
# One of: '2' | '3' | empty string (default)
|
||||
# If empty, do not show icons.
|
||||
nerdFontsVersion: ""
|
||||
|
||||
# If true (default), file icons are shown in the file views. Only relevant if NerdFontsVersion is not empty.
|
||||
showFileIcons: true
|
||||
|
||||
# Length of author name in (non-expanded) commits view. 2 means show initials only.
|
||||
commitAuthorShortLength: 2
|
||||
|
||||
# Length of author name in expanded commits view. 2 means show initials only.
|
||||
commitAuthorLongLength: 17
|
||||
|
||||
# Length of commit hash in commits view. 0 shows '*' if NF icons aren't on.
|
||||
commitHashLength: 8
|
||||
|
||||
# If true, show commit hashes alongside branch names in the branches view.
|
||||
showBranchCommitHash: false
|
||||
|
||||
# Whether to show the divergence from the base branch in the branches view.
|
||||
# One of: 'none' | 'onlyArrow' | 'arrowAndNumber'
|
||||
showDivergenceFromBaseBranch: none
|
||||
|
||||
# Height of the command log view
|
||||
commandLogSize: 8
|
||||
|
||||
# Whether to split the main window when viewing file changes.
|
||||
# One of: 'auto' | 'always'
|
||||
# If 'auto', only split the main window when a file has both staged and unstaged changes
|
||||
splitDiff: auto
|
||||
|
||||
# Default size for focused window. Can be changed from within Lazygit with '+' and '_' (but this won't change the default).
|
||||
# One of: 'normal' (default) | 'half' | 'full'
|
||||
screenMode: normal
|
||||
|
||||
# Window border style.
|
||||
# One of 'rounded' (default) | 'single' | 'double' | 'hidden'
|
||||
border: rounded
|
||||
|
||||
# If true, show a seriously epic explosion animation when nuking the working tree.
|
||||
animateExplosion: true
|
||||
|
||||
# Whether to stack UI components on top of each other.
|
||||
# One of 'auto' (default) | 'always' | 'never'
|
||||
portraitMode: auto
|
||||
|
||||
# How things are filtered when typing '/'.
|
||||
# One of 'substring' (default) | 'fuzzy'
|
||||
filterMode: substring
|
||||
|
||||
# Config relating to the spinner.
|
||||
spinner:
|
||||
# The frames of the spinner animation.
|
||||
frames:
|
||||
- '|'
|
||||
- /
|
||||
- '-'
|
||||
- \
|
||||
|
||||
# The "speed" of the spinner in milliseconds.
|
||||
rate: 50
|
||||
|
||||
# Status panel view.
|
||||
# One of 'dashboard' (default) | 'allBranchesLog'
|
||||
statusPanelView: dashboard
|
||||
|
||||
# If true, jump to the Files panel after popping a stash
|
||||
switchToFilesAfterStashPop: true
|
||||
|
||||
# If true, jump to the Files panel after applying a stash
|
||||
switchToFilesAfterStashApply: true
|
||||
|
||||
# If true, when using the panel jump keys (default 1 through 5) and target panel is already active, go to next tab instead
|
||||
switchTabsWithPanelJumpKeys: false
|
||||
|
||||
# Config relating to git
|
||||
git:
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md
|
||||
paging:
|
||||
# Value of the --color arg in the git diff command. Some pagers want this to be set to 'always' and some want it set to 'never'
|
||||
colorArg: always
|
||||
|
||||
# e.g.
|
||||
# diff-so-fancy
|
||||
# delta --dark --paging=never
|
||||
# ydiff -p cat -s --wrap --width={{columnWidth}}
|
||||
pager: ""
|
||||
|
||||
useConfig: false
|
||||
|
||||
# e.g. 'difft --color=always'
|
||||
externalDiffCommand: ""
|
||||
|
||||
# Config relating to committing
|
||||
commit:
|
||||
# If true, pass '--signoff' flag when committing
|
||||
signOff: false
|
||||
|
||||
# Automatic WYSIWYG wrapping of the commit message as you type
|
||||
autoWrapCommitMessage: true
|
||||
|
||||
# If autoWrapCommitMessage is true, the width to wrap to
|
||||
autoWrapWidth: 72
|
||||
|
||||
# Config relating to merging
|
||||
merging:
|
||||
# If true, run merges in a subprocess so that if a commit message is required, Lazygit will not hang
|
||||
# Only applicable to unix users.
|
||||
manualCommit: false
|
||||
|
||||
# Extra args passed to , e.g. --no-ff
|
||||
args: ""
|
||||
|
||||
# The commit message to use for a squash merge commit. Can contain "{{selectedRef}}" and "{{currentBranch}}" placeholders.
|
||||
squashMergeMessage: Squash merge {{selectedRef}} into {{currentBranch}}
|
||||
|
||||
# list of branches that are considered 'main' branches, used when displaying commits
|
||||
mainBranches:
|
||||
- master
|
||||
- main
|
||||
|
||||
# Prefix to use when skipping hooks. E.g. if set to 'WIP', then pre-commit hooks will be skipped when the commit message starts with 'WIP'
|
||||
skipHookPrefix: WIP
|
||||
|
||||
# If true, periodically fetch from remote
|
||||
autoFetch: true
|
||||
|
||||
# If true, periodically refresh files and submodules
|
||||
autoRefresh: true
|
||||
|
||||
# If true, pass the --all arg to git fetch
|
||||
fetchAll: true
|
||||
|
||||
# If true, lazygit will automatically stage files that used to have merge
|
||||
# conflicts but no longer do; and it will also ask you if you want to
|
||||
# continue a merge or rebase if you've resolved all conflicts. If false, it
|
||||
# won't do either of these things.
|
||||
autoStageResolvedConflicts: true
|
||||
|
||||
# Command used when displaying the current branch git log in the main window
|
||||
branchLogCmd: git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --
|
||||
|
||||
# Command used to display git log of all branches in the main window.
|
||||
# Deprecated: Use allBranchesLogCmds instead.
|
||||
allBranchesLogCmd: git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium
|
||||
|
||||
# If true, do not spawn a separate process when using GPG
|
||||
overrideGpg: false
|
||||
|
||||
# If true, do not allow force pushes
|
||||
disableForcePushing: false
|
||||
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix
|
||||
branchPrefix: ""
|
||||
|
||||
# If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀
|
||||
# (This should really be under 'gui', not 'git')
|
||||
parseEmoji: false
|
||||
|
||||
# Config for showing the log in the commits view
|
||||
log:
|
||||
# One of: 'date-order' | 'author-date-order' | 'topo-order' | 'default'
|
||||
# 'topo-order' makes it easier to read the git log graph, but commits may not
|
||||
# appear chronologically. See https://git-scm.com/docs/
|
||||
#
|
||||
# Deprecated: Configure this with Log menu -> Commit sort order (<c-l> in the commits window by default).
|
||||
order: topo-order
|
||||
|
||||
# This determines whether the git graph is rendered in the commits panel
|
||||
# One of 'always' | 'never' | 'when-maximised'
|
||||
#
|
||||
# Deprecated: Configure this with Log menu -> Show git graph (<c-l> in the commits window by default).
|
||||
showGraph: always
|
||||
|
||||
# displays the whole git graph by default in the commits view (equivalent to passing the --all argument to git log)
|
||||
showWholeGraph: false
|
||||
|
||||
# When copying commit hashes to the clipboard, truncate them to this
|
||||
# length. Set to 40 to disable truncation.
|
||||
truncateCopiedCommitHashesTo: 12
|
||||
|
||||
# Periodic update checks
|
||||
update:
|
||||
# One of: 'prompt' (default) | 'background' | 'never'
|
||||
method: prompt
|
||||
|
||||
# Period in days between update checks
|
||||
days: 14
|
||||
|
||||
# Background refreshes
|
||||
refresher:
|
||||
# File/submodule refresh interval in seconds.
|
||||
# Auto-refresh can be disabled via option 'git.autoRefresh'.
|
||||
refreshInterval: 10
|
||||
|
||||
# Re-fetch interval in seconds.
|
||||
# Auto-fetch can be disabled via option 'git.autoFetch'.
|
||||
fetchInterval: 60
|
||||
|
||||
# If true, show a confirmation popup before quitting Lazygit
|
||||
confirmOnQuit: false
|
||||
|
||||
# If true, exit Lazygit when the user presses escape in a context where there is nothing to cancel/close
|
||||
quitOnTopLevelReturn: false
|
||||
|
||||
# Config relating to things outside of Lazygit like how files are opened, copying to clipboard, etc
|
||||
os:
|
||||
# Command for editing a file. Should contain "{{filename}}".
|
||||
edit: ""
|
||||
|
||||
# Command for editing a file at a given line number. Should contain
|
||||
# "{{filename}}", and may optionally contain "{{line}}".
|
||||
editAtLine: ""
|
||||
|
||||
# Same as EditAtLine, except that the command needs to wait until the
|
||||
# window is closed.
|
||||
editAtLineAndWait: ""
|
||||
|
||||
# Whether lazygit suspends until an edit process returns
|
||||
editInTerminal: false
|
||||
|
||||
# For opening a directory in an editor
|
||||
openDirInEditor: ""
|
||||
|
||||
# A built-in preset that sets all of the above settings. Supported presets
|
||||
# are defined in the getPreset function in editor_presets.go.
|
||||
editPreset: ""
|
||||
|
||||
# Command for opening a file, as if the file is double-clicked. Should
|
||||
# contain "{{filename}}", but doesn't support "{{line}}".
|
||||
open: ""
|
||||
|
||||
# Command for opening a link. Should contain "{{link}}".
|
||||
openLink: ""
|
||||
|
||||
# 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: ""
|
||||
|
||||
# EditCommandTemplate is the command template for editing a file
|
||||
# Deprecated: use EditAtLine instead.
|
||||
editCommandTemplate: ""
|
||||
|
||||
# OpenCommand is the command for opening a file
|
||||
# Deprecated: use Open instead.
|
||||
openCommand: ""
|
||||
|
||||
# OpenLinkCommand is the command for opening a link
|
||||
# Deprecated: use OpenLink instead.
|
||||
openLinkCommand: ""
|
||||
|
||||
# CopyToClipboardCmd is the command for copying to clipboard.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard
|
||||
copyToClipboardCmd: ""
|
||||
|
||||
# ReadFromClipboardCmd is the command for reading the clipboard.
|
||||
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard
|
||||
readFromClipboardCmd: ""
|
||||
|
||||
# If true, don't display introductory popups upon opening Lazygit.
|
||||
disableStartupPopups: false
|
||||
|
||||
# What to do when opening Lazygit outside of a git repo.
|
||||
# - 'prompt': (default) ask whether to initialize a new repo or open in the most recent repo
|
||||
# - 'create': initialize a new repo
|
||||
# - 'skip': open most recent repo
|
||||
# - 'quit': exit Lazygit
|
||||
notARepository: prompt
|
||||
|
||||
# If true, display a confirmation when subprocess terminates. This allows you to view the output of the subprocess before returning to Lazygit.
|
||||
promptToReturnFromSubprocess: true
|
||||
|
||||
# Keybindings
|
||||
keybinding:
|
||||
universal:
|
||||
quit: q
|
||||
quit-alt1: <c-c>
|
||||
return: <esc>
|
||||
quitWithoutChangingDirectory: Q
|
||||
togglePanel: <tab>
|
||||
prevItem: <up>
|
||||
nextItem: <down>
|
||||
prevItem-alt: k
|
||||
nextItem-alt: j
|
||||
prevPage: ','
|
||||
nextPage: .
|
||||
scrollLeft: H
|
||||
scrollRight: L
|
||||
gotoTop: <
|
||||
gotoBottom: '>'
|
||||
toggleRangeSelect: v
|
||||
rangeSelectDown: <s-down>
|
||||
rangeSelectUp: <s-up>
|
||||
prevBlock: <left>
|
||||
nextBlock: <right>
|
||||
prevBlock-alt: h
|
||||
nextBlock-alt: l
|
||||
nextBlock-alt2: <tab>
|
||||
prevBlock-alt2: <backtab>
|
||||
jumpToBlock:
|
||||
- "1"
|
||||
- "2"
|
||||
- "3"
|
||||
- "4"
|
||||
- "5"
|
||||
nextMatch: "n"
|
||||
prevMatch: "N"
|
||||
startSearch: /
|
||||
optionMenu: <disabled>
|
||||
optionMenu-alt1: '?'
|
||||
select: <space>
|
||||
goInto: <enter>
|
||||
confirm: <enter>
|
||||
confirmInEditor: <a-enter>
|
||||
remove: d
|
||||
new: "n"
|
||||
edit: e
|
||||
openFile: o
|
||||
scrollUpMain: <pgup>
|
||||
scrollDownMain: <pgdown>
|
||||
scrollUpMain-alt1: K
|
||||
scrollDownMain-alt1: J
|
||||
scrollUpMain-alt2: <c-u>
|
||||
scrollDownMain-alt2: <c-d>
|
||||
executeShellCommand: ':'
|
||||
createRebaseOptionsMenu: m
|
||||
|
||||
# 'Files' appended for legacy reasons
|
||||
pushFiles: P
|
||||
|
||||
# 'Files' appended for legacy reasons
|
||||
pullFiles: p
|
||||
refresh: R
|
||||
createPatchOptionsMenu: <c-p>
|
||||
nextTab: ']'
|
||||
prevTab: '['
|
||||
nextScreenMode: +
|
||||
prevScreenMode: _
|
||||
undo: z
|
||||
redo: <c-z>
|
||||
filteringMenu: <c-s>
|
||||
diffingMenu: W
|
||||
diffingMenu-alt: <c-e>
|
||||
copyToClipboard: <c-o>
|
||||
openRecentRepos: <c-r>
|
||||
submitEditorText: <enter>
|
||||
extrasMenu: '@'
|
||||
toggleWhitespaceInDiffView: <c-w>
|
||||
increaseContextInDiffView: '}'
|
||||
decreaseContextInDiffView: '{'
|
||||
increaseRenameSimilarityThreshold: )
|
||||
decreaseRenameSimilarityThreshold: (
|
||||
openDiffTool: <c-t>
|
||||
status:
|
||||
checkForUpdate: u
|
||||
recentRepos: <enter>
|
||||
allBranchesLogGraph: a
|
||||
files:
|
||||
commitChanges: c
|
||||
commitChangesWithoutHook: w
|
||||
amendLastCommit: A
|
||||
commitChangesWithEditor: C
|
||||
findBaseCommitForFixup: <c-f>
|
||||
confirmDiscard: x
|
||||
ignoreFile: i
|
||||
refreshFiles: r
|
||||
stashAllChanges: s
|
||||
viewStashOptions: S
|
||||
toggleStagedAll: a
|
||||
viewResetOptions: D
|
||||
fetch: f
|
||||
openMergeTool: M
|
||||
openStatusFilter: <c-b>
|
||||
copyFileInfoToClipboard: "y"
|
||||
collapseAll: '-'
|
||||
expandAll: =
|
||||
branches:
|
||||
createPullRequest: o
|
||||
viewPullRequestOptions: O
|
||||
copyPullRequestURL: <c-y>
|
||||
checkoutBranchByName: c
|
||||
forceCheckoutBranch: F
|
||||
rebaseBranch: r
|
||||
renameBranch: R
|
||||
mergeIntoCurrentBranch: M
|
||||
viewGitFlowOptions: i
|
||||
fastForward: f
|
||||
createTag: T
|
||||
pushTag: P
|
||||
setUpstream: u
|
||||
fetchRemote: f
|
||||
sortOrder: s
|
||||
worktrees:
|
||||
viewWorktreeOptions: w
|
||||
commits:
|
||||
squashDown: s
|
||||
renameCommit: r
|
||||
renameCommitWithEditor: R
|
||||
viewResetOptions: g
|
||||
markCommitAsFixup: f
|
||||
createFixupCommit: F
|
||||
squashAboveCommits: S
|
||||
moveDownCommit: <c-j>
|
||||
moveUpCommit: <c-k>
|
||||
amendToCommit: A
|
||||
resetCommitAuthor: a
|
||||
pickCommit: p
|
||||
revertCommit: t
|
||||
cherryPickCopy: C
|
||||
pasteCommits: V
|
||||
markCommitAsBaseForRebase: B
|
||||
tagCommit: T
|
||||
checkoutCommit: <space>
|
||||
resetCherryPick: <c-R>
|
||||
copyCommitAttributeToClipboard: "y"
|
||||
openLogMenu: <c-l>
|
||||
openInBrowser: o
|
||||
viewBisectOptions: b
|
||||
startInteractiveRebase: i
|
||||
amendAttribute:
|
||||
resetAuthor: a
|
||||
setAuthor: A
|
||||
addCoAuthor: c
|
||||
stash:
|
||||
popStash: g
|
||||
renameStash: r
|
||||
commitFiles:
|
||||
checkoutCommitFile: c
|
||||
main:
|
||||
toggleSelectHunk: a
|
||||
pickBothHunks: b
|
||||
editSelectHunk: E
|
||||
submodules:
|
||||
init: i
|
||||
update: u
|
||||
bulkMenu: b
|
||||
commitMessage:
|
||||
commitMenu: <c-o>
|
||||
`)
|
||||
|
||||
func BenchmarkMigrationOnLargeConfiguration(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = computeMigratedConfig("path doesn't matter", largeConfiguration)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jesseduffield/gocui"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// NOTE: if you make changes to this table, be sure to update
|
||||
// docs/keybindings/Custom_Keybindings.md as well
|
||||
|
||||
var LabelByKey = map[gocui.Key]string{
|
||||
gocui.KeyF1: "<f1>",
|
||||
gocui.KeyF2: "<f2>",
|
||||
gocui.KeyF3: "<f3>",
|
||||
gocui.KeyF4: "<f4>",
|
||||
gocui.KeyF5: "<f5>",
|
||||
gocui.KeyF6: "<f6>",
|
||||
gocui.KeyF7: "<f7>",
|
||||
gocui.KeyF8: "<f8>",
|
||||
gocui.KeyF9: "<f9>",
|
||||
gocui.KeyF10: "<f10>",
|
||||
gocui.KeyF11: "<f11>",
|
||||
gocui.KeyF12: "<f12>",
|
||||
gocui.KeyInsert: "<insert>",
|
||||
gocui.KeyDelete: "<delete>",
|
||||
gocui.KeyHome: "<home>",
|
||||
gocui.KeyEnd: "<end>",
|
||||
gocui.KeyPgup: "<pgup>",
|
||||
gocui.KeyPgdn: "<pgdown>",
|
||||
gocui.KeyArrowUp: "<up>",
|
||||
gocui.KeyShiftArrowUp: "<s-up>",
|
||||
gocui.KeyArrowDown: "<down>",
|
||||
gocui.KeyShiftArrowDown: "<s-down>",
|
||||
gocui.KeyArrowLeft: "<left>",
|
||||
gocui.KeyArrowRight: "<right>",
|
||||
gocui.KeyTab: "<tab>", // <c-i>
|
||||
gocui.KeyBacktab: "<backtab>",
|
||||
gocui.KeyEnter: "<enter>", // <c-m>
|
||||
gocui.KeyAltEnter: "<a-enter>",
|
||||
gocui.KeyEsc: "<esc>", // <c-[>, <c-3>
|
||||
gocui.KeyBackspace: "<backspace>", // <c-h>
|
||||
gocui.KeyCtrlSpace: "<c-space>", // <c-~>, <c-2>
|
||||
gocui.KeyCtrlSlash: "<c-/>", // <c-_>
|
||||
gocui.KeySpace: "<space>",
|
||||
gocui.KeyCtrlA: "<c-a>",
|
||||
gocui.KeyCtrlB: "<c-b>",
|
||||
gocui.KeyCtrlC: "<c-c>",
|
||||
gocui.KeyCtrlD: "<c-d>",
|
||||
gocui.KeyCtrlE: "<c-e>",
|
||||
gocui.KeyCtrlF: "<c-f>",
|
||||
gocui.KeyCtrlG: "<c-g>",
|
||||
gocui.KeyCtrlJ: "<c-j>",
|
||||
gocui.KeyCtrlK: "<c-k>",
|
||||
gocui.KeyCtrlL: "<c-l>",
|
||||
gocui.KeyCtrlN: "<c-n>",
|
||||
gocui.KeyCtrlO: "<c-o>",
|
||||
gocui.KeyCtrlP: "<c-p>",
|
||||
gocui.KeyCtrlQ: "<c-q>",
|
||||
gocui.KeyCtrlR: "<c-r>",
|
||||
gocui.KeyCtrlS: "<c-s>",
|
||||
gocui.KeyCtrlT: "<c-t>",
|
||||
gocui.KeyCtrlU: "<c-u>",
|
||||
gocui.KeyCtrlV: "<c-v>",
|
||||
gocui.KeyCtrlW: "<c-w>",
|
||||
gocui.KeyCtrlX: "<c-x>",
|
||||
gocui.KeyCtrlY: "<c-y>",
|
||||
gocui.KeyCtrlZ: "<c-z>",
|
||||
gocui.KeyCtrl4: "<c-4>", // <c-\>
|
||||
gocui.KeyCtrl5: "<c-5>", // <c-]>
|
||||
gocui.KeyCtrl6: "<c-6>",
|
||||
gocui.KeyCtrl8: "<c-8>",
|
||||
gocui.MouseWheelUp: "mouse wheel up",
|
||||
gocui.MouseWheelDown: "mouse wheel down",
|
||||
}
|
||||
|
||||
var KeyByLabel = lo.Invert(LabelByKey)
|
||||
|
||||
func isValidKeybindingKey(key string) bool {
|
||||
runeCount := utf8.RuneCountInString(key)
|
||||
if key == "<disabled>" {
|
||||
return true
|
||||
}
|
||||
|
||||
if runeCount > 1 {
|
||||
_, ok := KeyByLabel[strings.ToLower(key)]
|
||||
return ok
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
+29
-10
@@ -64,6 +64,9 @@ type GuiConfig struct {
|
||||
ScrollOffMargin int `yaml:"scrollOffMargin"`
|
||||
// One of: 'margin' (default) | 'jump'
|
||||
ScrollOffBehavior string `yaml:"scrollOffBehavior"`
|
||||
// The number of spaces per tab; used for everything that's shown in the main view, but probably mostly relevant for diffs.
|
||||
// Note that when using a pager, the pager has its own tab width setting, so you need to pass it separately in the pager command.
|
||||
TabWidth int `yaml:"tabWidth" jsonschema:"minimum=1"`
|
||||
// If true, capture mouse events.
|
||||
// When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS.
|
||||
MouseEvents bool `yaml:"mouseEvents"`
|
||||
@@ -114,7 +117,7 @@ type GuiConfig struct {
|
||||
// If true, show the '5 of 20' footer at the bottom of list views
|
||||
ShowListFooter bool `yaml:"showListFooter"`
|
||||
// If true, display the files in the file views as a tree. If false, display the files as a flat list.
|
||||
// This can be toggled from within Lazygit with the '~' key, but that will not change the default.
|
||||
// This can be toggled from within Lazygit with the '`' key, but that will not change the default.
|
||||
ShowFileTree bool `yaml:"showFileTree"`
|
||||
// If true, show the number of lines changed per file in the Files view
|
||||
ShowNumstatInFilesView bool `yaml:"showNumstatInFilesView"`
|
||||
@@ -256,9 +259,9 @@ type GitConfig struct {
|
||||
// If true, do not allow force pushes
|
||||
DisableForcePushing bool `yaml:"disableForcePushing"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix
|
||||
CommitPrefix *CommitPrefixConfig `yaml:"commitPrefix"`
|
||||
CommitPrefix []CommitPrefixConfig `yaml:"commitPrefix"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix
|
||||
CommitPrefixes map[string]CommitPrefixConfig `yaml:"commitPrefixes"`
|
||||
CommitPrefixes map[string][]CommitPrefixConfig `yaml:"commitPrefixes"`
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix
|
||||
BranchPrefix string `yaml:"branchPrefix"`
|
||||
// If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀
|
||||
@@ -554,8 +557,8 @@ type OSConfig struct {
|
||||
EditAtLineAndWait string `yaml:"editAtLineAndWait,omitempty"`
|
||||
|
||||
// Whether lazygit suspends until an edit process returns
|
||||
// Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
// We're naming this `editInTerminal` for backwards compatibility
|
||||
// [dev] Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
// [dev] We're naming this `editInTerminal` for backwards compatibility
|
||||
SuspendOnEdit *bool `yaml:"editInTerminal,omitempty"`
|
||||
|
||||
// For opening a directory in an editor
|
||||
@@ -611,12 +614,16 @@ type CustomCommandAfterHook struct {
|
||||
type CustomCommand struct {
|
||||
// The key to trigger the command. Use a single letter or one of the values from https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Custom_Keybindings.md
|
||||
Key string `yaml:"key"`
|
||||
// Instead of defining a single custom command, create a menu of custom commands. Useful for grouping related commands together under a single keybinding, and for keeping them out of the global keybindings menu.
|
||||
// When using this, all other fields except Key and Description are ignored and must be empty.
|
||||
CommandMenu []CustomCommand `yaml:"commandMenu"`
|
||||
// The context in which to listen for the key. Valid values are: status, files, worktrees, localBranches, remotes, remoteBranches, tags, commits, reflogCommits, subCommits, commitFiles, stash, and global. Multiple contexts separated by comma are allowed; most useful for "commits, subCommits" or "files, commitFiles".
|
||||
Context string `yaml:"context" jsonschema:"example=status,example=files,example=worktrees,example=localBranches,example=remotes,example=remoteBranches,example=tags,example=commits,example=reflogCommits,example=subCommits,example=commitFiles,example=stash,example=global"`
|
||||
// The command to run (using Go template syntax for placeholder values)
|
||||
Command string `yaml:"command" jsonschema:"example=git fetch {{.Form.Remote}} {{.Form.Branch}} && git checkout FETCH_HEAD"`
|
||||
// If true, run the command in a subprocess (e.g. if the command requires user input)
|
||||
Subprocess bool `yaml:"subprocess"`
|
||||
// [dev] Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
Subprocess *bool `yaml:"subprocess"`
|
||||
// A list of prompts that will request user input before running the final command
|
||||
Prompts []CustomCommandPrompt `yaml:"prompts"`
|
||||
// Text to display while waiting for command to finish
|
||||
@@ -624,13 +631,24 @@ type CustomCommand struct {
|
||||
// Label for the custom command when displayed in the keybindings menu
|
||||
Description string `yaml:"description"`
|
||||
// If true, stream the command's output to the Command Log panel
|
||||
Stream bool `yaml:"stream"`
|
||||
// [dev] Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
Stream *bool `yaml:"stream"`
|
||||
// If true, show the command's output in a popup within Lazygit
|
||||
ShowOutput bool `yaml:"showOutput"`
|
||||
// [dev] Pointer to bool so that we can distinguish unset (nil) from false.
|
||||
ShowOutput *bool `yaml:"showOutput"`
|
||||
// The title to display in the popup panel if showOutput is true. If left unset, the command will be used as the title.
|
||||
OutputTitle string `yaml:"outputTitle"`
|
||||
// Actions to take after the command has completed
|
||||
After CustomCommandAfterHook `yaml:"after"`
|
||||
// [dev] Pointer so that we can tell whether it appears in the config file
|
||||
After *CustomCommandAfterHook `yaml:"after"`
|
||||
}
|
||||
|
||||
func (c *CustomCommand) GetDescription() string {
|
||||
if c.Description != "" {
|
||||
return c.Description
|
||||
}
|
||||
|
||||
return c.Command
|
||||
}
|
||||
|
||||
type CustomCommandPrompt struct {
|
||||
@@ -693,6 +711,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
ScrollPastBottom: true,
|
||||
ScrollOffMargin: 2,
|
||||
ScrollOffBehavior: "margin",
|
||||
TabWidth: 4,
|
||||
MouseEvents: true,
|
||||
SkipDiscardChangeWarning: false,
|
||||
SkipStashWarning: false,
|
||||
@@ -784,7 +803,7 @@ func GetDefaultConfig() *UserConfig {
|
||||
BranchLogCmd: "git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --",
|
||||
AllBranchesLogCmd: "git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium",
|
||||
DisableForcePushing: false,
|
||||
CommitPrefixes: map[string]CommitPrefixConfig(nil),
|
||||
CommitPrefixes: map[string][]CommitPrefixConfig(nil),
|
||||
BranchPrefix: "",
|
||||
ParseEmoji: false,
|
||||
TruncateCopiedCommitHashesTo: 12,
|
||||
|
||||
@@ -2,8 +2,12 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazygit/pkg/constants"
|
||||
)
|
||||
|
||||
func (config *UserConfig) Validate() error {
|
||||
@@ -15,6 +19,12 @@ func (config *UserConfig) Validate() error {
|
||||
[]string{"none", "onlyArrow", "arrowAndNumber"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateKeybindings(config.Keybinding); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCustomCommands(config.CustomCommands); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -25,3 +35,84 @@ func validateEnum(name string, value string, allowedValues []string) error {
|
||||
allowedValuesStr := strings.Join(allowedValues, ", ")
|
||||
return fmt.Errorf("Unexpected value '%s' for '%s'. Allowed values: %s", value, name, allowedValuesStr)
|
||||
}
|
||||
|
||||
func validateKeybindingsRecurse(path string, node any) error {
|
||||
value := reflect.ValueOf(node)
|
||||
if value.Kind() == reflect.Struct {
|
||||
for _, field := range reflect.VisibleFields(reflect.TypeOf(node)) {
|
||||
var newPath string
|
||||
if len(path) == 0 {
|
||||
newPath = field.Name
|
||||
} else {
|
||||
newPath = fmt.Sprintf("%s.%s", path, field.Name)
|
||||
}
|
||||
if err := validateKeybindingsRecurse(newPath,
|
||||
value.FieldByName(field.Name).Interface()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if value.Kind() == reflect.Slice {
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
if err := validateKeybindingsRecurse(
|
||||
fmt.Sprintf("%s[%d]", path, i), value.Index(i).Interface()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if value.Kind() == reflect.String {
|
||||
key := node.(string)
|
||||
if !isValidKeybindingKey(key) {
|
||||
return fmt.Errorf("Unrecognized key '%s' for keybinding '%s'. For permitted values see %s",
|
||||
key, path, constants.Links.Docs.CustomKeybindings)
|
||||
}
|
||||
} else {
|
||||
log.Fatalf("Unexpected type for property '%s': %s", path, value.Kind())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateKeybindings(keybindingConfig KeybindingConfig) error {
|
||||
if err := validateKeybindingsRecurse("", keybindingConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(keybindingConfig.Universal.JumpToBlock) != 5 {
|
||||
return fmt.Errorf("keybinding.universal.jumpToBlock must have 5 elements; found %d.",
|
||||
len(keybindingConfig.Universal.JumpToBlock))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCustomCommandKey(key string) error {
|
||||
if !isValidKeybindingKey(key) {
|
||||
return fmt.Errorf("Unrecognized key '%s' for custom command. For permitted values see %s",
|
||||
key, constants.Links.Docs.CustomKeybindings)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCustomCommands(customCommands []CustomCommand) error {
|
||||
for _, customCommand := range customCommands {
|
||||
if err := validateCustomCommandKey(customCommand.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(customCommand.CommandMenu) > 0 &&
|
||||
(len(customCommand.Context) > 0 ||
|
||||
len(customCommand.Command) > 0 ||
|
||||
customCommand.Subprocess != nil ||
|
||||
len(customCommand.Prompts) > 0 ||
|
||||
len(customCommand.LoadingText) > 0 ||
|
||||
customCommand.Stream != nil ||
|
||||
customCommand.ShowOutput != nil ||
|
||||
len(customCommand.OutputTitle) > 0 ||
|
||||
customCommand.After != nil) {
|
||||
commandRef := ""
|
||||
if len(customCommand.Key) > 0 {
|
||||
commandRef = fmt.Sprintf(" with key '%s'", customCommand.Key)
|
||||
}
|
||||
return fmt.Errorf("Error with custom command%s: it is not allowed to use both commandMenu and any of the other fields except key and description.", commandRef)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -29,6 +30,102 @@ func TestUserConfigValidate_enums(t *testing.T) {
|
||||
{value: "invalid_value", valid: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Keybindings",
|
||||
setup: func(config *UserConfig, value string) {
|
||||
config.Keybinding.Universal.Quit = value
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: true},
|
||||
{value: "<disabled>", valid: true},
|
||||
{value: "q", valid: true},
|
||||
{value: "<c-c>", valid: true},
|
||||
{value: "invalid_value", valid: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "JumpToBlock keybinding",
|
||||
setup: func(config *UserConfig, value string) {
|
||||
config.Keybinding.Universal.JumpToBlock = strings.Split(value, ",")
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: false},
|
||||
{value: "1,2,3", valid: false},
|
||||
{value: "1,2,3,4,5", valid: true},
|
||||
{value: "1,2,3,4,invalid", valid: false},
|
||||
{value: "1,2,3,4,5,6", valid: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Custom command keybinding",
|
||||
setup: func(config *UserConfig, value string) {
|
||||
config.CustomCommands = []CustomCommand{
|
||||
{
|
||||
Key: value,
|
||||
Command: "echo 'hello'",
|
||||
},
|
||||
}
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: true},
|
||||
{value: "<disabled>", valid: true},
|
||||
{value: "q", valid: true},
|
||||
{value: "<c-c>", valid: true},
|
||||
{value: "invalid_value", valid: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Custom command sub menu",
|
||||
setup: func(config *UserConfig, _ string) {
|
||||
config.CustomCommands = []CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Description: "My Custom Commands",
|
||||
CommandMenu: []CustomCommand{
|
||||
{Key: "1", Command: "echo 'hello'", Context: "global"},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: true},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Custom command sub menu",
|
||||
setup: func(config *UserConfig, _ string) {
|
||||
config.CustomCommands = []CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Context: "global",
|
||||
CommandMenu: []CustomCommand{
|
||||
{Key: "1", Command: "echo 'hello'", Context: "global"},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Custom command sub menu",
|
||||
setup: func(config *UserConfig, _ string) {
|
||||
falseVal := false
|
||||
config.CustomCommands = []CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Subprocess: &falseVal,
|
||||
CommandMenu: []CustomCommand{
|
||||
{Key: "1", Command: "echo 'hello'", Context: "global"},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
testCases: []testCase{
|
||||
{value: "", valid: false},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
|
||||
@@ -122,7 +122,24 @@ func (self *BasicCommitsController) GetKeybindings(opts types.KeybindingsOpts) [
|
||||
return bindings
|
||||
}
|
||||
|
||||
func (self *BasicCommitsController) getCommitMessageBody(hash string) string {
|
||||
commitMessageBody, err := self.c.Git().Commit.GetCommitMessage(hash)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
_, body := self.c.Helpers().Commits.SplitCommitMessageAndDescription(commitMessageBody)
|
||||
return body
|
||||
}
|
||||
|
||||
func (self *BasicCommitsController) copyCommitAttribute(commit *models.Commit) error {
|
||||
commitMessageBody := self.getCommitMessageBody(commit.Hash)
|
||||
var commitMessageBodyDisabled *types.DisabledReason
|
||||
if commitMessageBody == "" {
|
||||
commitMessageBodyDisabled = &types.DisabledReason{
|
||||
Text: self.c.Tr.CommitHasNoMessageBody,
|
||||
}
|
||||
}
|
||||
|
||||
items := []*types.MenuItem{
|
||||
{
|
||||
Label: self.c.Tr.CommitHash,
|
||||
@@ -144,6 +161,14 @@ func (self *BasicCommitsController) copyCommitAttribute(commit *models.Commit) e
|
||||
},
|
||||
Key: 'm',
|
||||
},
|
||||
{
|
||||
Label: self.c.Tr.CommitMessageBody,
|
||||
DisabledReason: commitMessageBodyDisabled,
|
||||
OnPress: func() error {
|
||||
return self.copyCommitMessageBodyToClipboard(commitMessageBody)
|
||||
},
|
||||
Key: 'b',
|
||||
},
|
||||
{
|
||||
Label: self.c.Tr.CommitURL,
|
||||
OnPress: func() error {
|
||||
@@ -259,6 +284,16 @@ func (self *BasicCommitsController) copyCommitMessageToClipboard(commit *models.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *BasicCommitsController) copyCommitMessageBodyToClipboard(commitMessageBody string) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.CopyCommitMessageBodyToClipboard)
|
||||
if err := self.c.OS().CopyToClipboard(commitMessageBody); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.c.Toast(self.c.Tr.CommitMessageBodyCopiedToClipboard)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *BasicCommitsController) copyCommitSubjectToClipboard(commit *models.Commit) error {
|
||||
message, err := self.c.Git().Commit.GetCommitSubject(commit.Hash)
|
||||
if err != nil {
|
||||
|
||||
@@ -41,6 +41,12 @@ func NewCommitFilesController(
|
||||
|
||||
func (self *CommitFilesController) GetKeybindings(opts types.KeybindingsOpts) []*types.Binding {
|
||||
bindings := []*types.Binding{
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Files.CopyFileInfoToClipboard),
|
||||
Handler: self.openCopyMenu,
|
||||
Description: self.c.Tr.CopyToClipboardMenu,
|
||||
OpensMenu: true,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.CommitFiles.CheckoutCommitFile),
|
||||
Handler: self.withItem(self.checkout),
|
||||
@@ -181,6 +187,77 @@ func (self *CommitFilesController) onClickMain(opts gocui.ViewMouseBindingOpts)
|
||||
return self.enterCommitFile(node, types.OnFocusOpts{ClickedWindowName: "main", ClickedViewLineIdx: opts.Y})
|
||||
}
|
||||
|
||||
func (self *CommitFilesController) copyDiffToClipboard(path string, toastMessage string) error {
|
||||
from, to := self.context().GetFromAndToForDiff()
|
||||
from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from)
|
||||
|
||||
cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, path, true)
|
||||
diff, err := cmdObj.RunWithOutput()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := self.c.OS().CopyToClipboard(diff); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.Toast(toastMessage)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *CommitFilesController) openCopyMenu() error {
|
||||
node := self.context().GetSelected()
|
||||
|
||||
copyNameItem := &types.MenuItem{
|
||||
Label: self.c.Tr.CopyFileName,
|
||||
OnPress: func() error {
|
||||
if err := self.c.OS().CopyToClipboard(node.Name()); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.Toast(self.c.Tr.FileNameCopiedToast)
|
||||
return nil
|
||||
},
|
||||
DisabledReason: self.require(self.singleItemSelected())(),
|
||||
Key: 'n',
|
||||
}
|
||||
copyPathItem := &types.MenuItem{
|
||||
Label: self.c.Tr.CopyFilePath,
|
||||
OnPress: func() error {
|
||||
if err := self.c.OS().CopyToClipboard(node.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
self.c.Toast(self.c.Tr.FilePathCopiedToast)
|
||||
return nil
|
||||
},
|
||||
DisabledReason: self.require(self.singleItemSelected())(),
|
||||
Key: 'p',
|
||||
}
|
||||
copyFileDiffItem := &types.MenuItem{
|
||||
Label: self.c.Tr.CopySelectedDiff,
|
||||
OnPress: func() error {
|
||||
return self.copyDiffToClipboard(node.GetPath(), self.c.Tr.FileDiffCopiedToast)
|
||||
},
|
||||
DisabledReason: self.require(self.singleItemSelected())(),
|
||||
Key: 's',
|
||||
}
|
||||
copyAllDiff := &types.MenuItem{
|
||||
Label: self.c.Tr.CopyAllFilesDiff,
|
||||
OnPress: func() error {
|
||||
return self.copyDiffToClipboard(".", self.c.Tr.AllFilesDiffCopiedToast)
|
||||
},
|
||||
DisabledReason: self.require(self.itemsSelected())(),
|
||||
Key: 'a',
|
||||
}
|
||||
|
||||
return self.c.Menu(types.CreateMenuOptions{
|
||||
Title: self.c.Tr.CopyToClipboardMenu,
|
||||
Items: []*types.MenuItem{
|
||||
copyNameItem,
|
||||
copyPathItem,
|
||||
copyFileDiffItem,
|
||||
copyAllDiff,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (self *CommitFilesController) checkout(node *filetree.CommitFileNode) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.CheckoutFile)
|
||||
if err := self.c.Git().WorkingTree.CheckoutFile(self.context().GetRef().RefName(), node.GetPath()); err != nil {
|
||||
|
||||
@@ -36,25 +36,25 @@ func (self *GlobalController) GetKeybindings(opts types.KeybindingsOpts) []*type
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.CreateRebaseOptionsMenu),
|
||||
Handler: self.c.Helpers().MergeAndRebase.CreateRebaseOptionsMenu,
|
||||
Handler: opts.Guards.NoPopupPanel(self.c.Helpers().MergeAndRebase.CreateRebaseOptionsMenu),
|
||||
Description: self.c.Tr.ViewMergeRebaseOptions,
|
||||
Tooltip: self.c.Tr.ViewMergeRebaseOptionsTooltip,
|
||||
OpensMenu: true,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.Refresh),
|
||||
Handler: self.refresh,
|
||||
Handler: opts.Guards.NoPopupPanel(self.refresh),
|
||||
Description: self.c.Tr.Refresh,
|
||||
Tooltip: self.c.Tr.RefreshTooltip,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.NextScreenMode),
|
||||
Handler: self.nextScreenMode,
|
||||
Handler: opts.Guards.NoPopupPanel(self.nextScreenMode),
|
||||
Description: self.c.Tr.NextScreenMode,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.PrevScreenMode),
|
||||
Handler: self.prevScreenMode,
|
||||
Handler: opts.Guards.NoPopupPanel(self.prevScreenMode),
|
||||
Description: self.c.Tr.PrevScreenMode,
|
||||
},
|
||||
{
|
||||
@@ -78,21 +78,21 @@ func (self *GlobalController) GetKeybindings(opts types.KeybindingsOpts) []*type
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.FilteringMenu),
|
||||
Handler: self.createFilteringMenu,
|
||||
Handler: opts.Guards.NoPopupPanel(self.createFilteringMenu),
|
||||
Description: self.c.Tr.OpenFilteringMenu,
|
||||
Tooltip: self.c.Tr.OpenFilteringMenuTooltip,
|
||||
OpensMenu: true,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.DiffingMenu),
|
||||
Handler: self.createDiffingMenu,
|
||||
Handler: opts.Guards.NoPopupPanel(self.createDiffingMenu),
|
||||
Description: self.c.Tr.ViewDiffingOptions,
|
||||
Tooltip: self.c.Tr.ViewDiffingOptionsTooltip,
|
||||
OpensMenu: true,
|
||||
},
|
||||
{
|
||||
Key: opts.GetKey(opts.Config.Universal.DiffingMenuAlt),
|
||||
Handler: self.createDiffingMenu,
|
||||
Handler: opts.Guards.NoPopupPanel(self.createDiffingMenu),
|
||||
Description: self.c.Tr.ViewDiffingOptions,
|
||||
Tooltip: self.c.Tr.ViewDiffingOptionsTooltip,
|
||||
OpensMenu: true,
|
||||
|
||||
@@ -56,8 +56,8 @@ func (self *ConfirmationHelper) DeactivateConfirmationPrompt() {
|
||||
self.clearConfirmationViewKeyBindings()
|
||||
}
|
||||
|
||||
func getMessageHeight(wrap bool, editable bool, message string, width int) int {
|
||||
wrappedLines, _, _ := utils.WrapViewLinesToWidth(wrap, editable, message, width)
|
||||
func getMessageHeight(wrap bool, editable bool, message string, width int, tabWidth int) int {
|
||||
wrappedLines, _, _ := utils.WrapViewLinesToWidth(wrap, editable, message, width, tabWidth)
|
||||
return len(wrappedLines)
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ func (self *ConfirmationHelper) resizeMenu(parentPopupContext types.Context) {
|
||||
if selectedItem != nil {
|
||||
tooltip = self.TooltipForMenuItem(selectedItem)
|
||||
}
|
||||
tooltipHeight := getMessageHeight(true, false, tooltip, contentWidth) + 2 // plus 2 for the frame
|
||||
tooltipHeight := getMessageHeight(true, false, tooltip, contentWidth, self.c.Views().Menu.TabWidth) + 2 // plus 2 for the frame
|
||||
_, _ = self.c.GocuiGui().SetView(self.c.Views().Tooltip.Name(), x0, tooltipTop, x1, tooltipTop+tooltipHeight-1, 0)
|
||||
}
|
||||
|
||||
@@ -276,7 +276,7 @@ func (self *ConfirmationHelper) layoutMenuPrompt(contentWidth int) int {
|
||||
var promptLines []string
|
||||
prompt := self.c.Contexts().Menu.GetPrompt()
|
||||
if len(prompt) > 0 {
|
||||
promptLines, _, _ = utils.WrapViewLinesToWidth(true, false, prompt, contentWidth)
|
||||
promptLines, _, _ = utils.WrapViewLinesToWidth(true, false, prompt, contentWidth, self.c.Views().Menu.TabWidth)
|
||||
promptLines = append(promptLines, "")
|
||||
}
|
||||
self.c.Contexts().Menu.SetPromptLines(promptLines)
|
||||
@@ -305,17 +305,18 @@ func (self *ConfirmationHelper) resizeConfirmationPanel(parentPopupContext types
|
||||
}
|
||||
panelWidth := self.getPopupPanelWidth()
|
||||
contentWidth := panelWidth - 2 // minus 2 for the frame
|
||||
prompt := self.c.Views().Confirmation.Buffer()
|
||||
confirmationView := self.c.Views().Confirmation
|
||||
prompt := confirmationView.Buffer()
|
||||
wrap := true
|
||||
editable := self.c.Views().Confirmation.Editable
|
||||
editable := confirmationView.Editable
|
||||
if editable {
|
||||
prompt = self.c.Views().Confirmation.TextArea.GetContent()
|
||||
prompt = confirmationView.TextArea.GetContent()
|
||||
wrap = false
|
||||
}
|
||||
panelHeight := getMessageHeight(wrap, editable, prompt, contentWidth) + suggestionsViewHeight
|
||||
panelHeight := getMessageHeight(wrap, editable, prompt, contentWidth, confirmationView.TabWidth) + suggestionsViewHeight
|
||||
x0, y0, x1, y1 := self.getPopupPanelDimensionsAux(panelWidth, panelHeight, parentPopupContext)
|
||||
confirmationViewBottom := y1 - suggestionsViewHeight
|
||||
_, _ = self.c.GocuiGui().SetView(self.c.Views().Confirmation.Name(), x0, y0, x1, confirmationViewBottom, 0)
|
||||
_, _ = self.c.GocuiGui().SetView(confirmationView.Name(), x0, y0, x1, confirmationViewBottom, 0)
|
||||
|
||||
suggestionsViewTop := confirmationViewBottom + 1
|
||||
_, _ = self.c.GocuiGui().SetView(self.c.Views().Suggestions.Name(), x0, suggestionsViewTop, x1, suggestionsViewTop+suggestionsViewHeight, 0)
|
||||
@@ -325,7 +326,7 @@ func (self *ConfirmationHelper) ResizeCommitMessagePanels(parentPopupContext typ
|
||||
panelWidth := self.getPopupPanelWidth()
|
||||
content := self.c.Views().CommitDescription.TextArea.GetContent()
|
||||
summaryViewHeight := 3
|
||||
panelHeight := getMessageHeight(false, true, content, panelWidth)
|
||||
panelHeight := getMessageHeight(false, true, content, panelWidth, self.c.Views().CommitDescription.TabWidth)
|
||||
minHeight := 7
|
||||
if panelHeight < minHeight {
|
||||
panelHeight = minHeight
|
||||
|
||||
@@ -490,9 +490,9 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele
|
||||
self.refreshView(self.c.Contexts().Worktrees)
|
||||
}
|
||||
|
||||
self.refreshView(self.c.Contexts().Branches)
|
||||
|
||||
if !keepBranchSelectionIndex && prevSelectedBranch != nil {
|
||||
self.searchHelper.ReApplyFilter(self.c.Contexts().Branches)
|
||||
|
||||
_, idx, found := lo.FindIndexOf(self.c.Contexts().Branches.GetItems(),
|
||||
func(b *models.Branch) bool { return b.Name == prevSelectedBranch.Name })
|
||||
if found {
|
||||
@@ -500,6 +500,8 @@ func (self *RefreshHelper) refreshBranches(refreshWorktrees bool, keepBranchSele
|
||||
}
|
||||
}
|
||||
|
||||
self.refreshView(self.c.Contexts().Branches)
|
||||
|
||||
// Need to re-render the commits view because the visualization of local
|
||||
// branch heads might have changed
|
||||
self.c.Mutexes().LocalCommitsMutex.Lock()
|
||||
|
||||
@@ -2,6 +2,7 @@ package helpers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazycore/pkg/boxlayout"
|
||||
@@ -237,14 +238,14 @@ func mainSectionChildren(args WindowArrangementArgs) []*boxlayout.Box {
|
||||
}
|
||||
|
||||
func getMidSectionWeights(args WindowArrangementArgs) (int, int) {
|
||||
// we originally specified this as a ratio i.e. .20 would correspond to a weight of 1 against 4
|
||||
sidePanelWidthRatio := args.UserConfig.Gui.SidePanelWidth
|
||||
// we could make this better by creating ratios like 2:3 rather than always 1:something
|
||||
mainSectionWeight := int(1/sidePanelWidthRatio) - 1
|
||||
sideSectionWeight := 1
|
||||
// Using 120 so that the default of 0.3333 will remain consistent with previous behavior
|
||||
const maxColumnCount = 120
|
||||
mainSectionWeight := int(math.Round(maxColumnCount * (1 - sidePanelWidthRatio)))
|
||||
sideSectionWeight := int(math.Round(maxColumnCount * sidePanelWidthRatio))
|
||||
|
||||
if splitMainPanelSideBySide(args) {
|
||||
mainSectionWeight = 5 // need to shrink side panel to make way for main panels if side-by-side
|
||||
mainSectionWeight = sideSectionWeight * 5 // need to shrink side panel to make way for main panels if side-by-side
|
||||
}
|
||||
|
||||
if args.CurrentWindow == "main" || args.CurrentWindow == "secondary" {
|
||||
@@ -254,9 +255,9 @@ func getMidSectionWeights(args WindowArrangementArgs) (int, int) {
|
||||
} else {
|
||||
if args.ScreenMode == types.SCREEN_HALF {
|
||||
if args.UserConfig.Gui.EnlargedSideViewLocation == "top" {
|
||||
mainSectionWeight = 2
|
||||
mainSectionWeight = sideSectionWeight * 2
|
||||
} else {
|
||||
mainSectionWeight = 1
|
||||
mainSectionWeight = sideSectionWeight
|
||||
}
|
||||
} else if args.ScreenMode == types.SCREEN_FULL {
|
||||
mainSectionWeight = 0
|
||||
|
||||
@@ -202,6 +202,86 @@ func TestGetWindowDimensions(t *testing.T) {
|
||||
B: information
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "0.5 SidePanelWidth",
|
||||
mutateArgs: func(args *WindowArrangementArgs) {
|
||||
args.UserConfig.Gui.SidePanelWidth = 0.5
|
||||
},
|
||||
expected: `
|
||||
╭status──────────────────────────────╮╭main───────────────────────────────╮
|
||||
│ ││ │
|
||||
╰────────────────────────────────────╯│ │
|
||||
╭files───────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰────────────────────────────────────╯│ │
|
||||
╭branches────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰────────────────────────────────────╯│ │
|
||||
╭commits─────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰────────────────────────────────────╯│ │
|
||||
╭stash───────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
╰────────────────────────────────────╯╰───────────────────────────────────╯
|
||||
<options──────────────────────────────────────────────────────>A<B────────>
|
||||
A: statusSpacer1
|
||||
B: information
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "0.8 SidePanelWidth",
|
||||
mutateArgs: func(args *WindowArrangementArgs) {
|
||||
args.UserConfig.Gui.SidePanelWidth = 0.8
|
||||
},
|
||||
expected: `
|
||||
╭status────────────────────────────────────────────────────╮╭main─────────╮
|
||||
│ ││ │
|
||||
╰──────────────────────────────────────────────────────────╯│ │
|
||||
╭files─────────────────────────────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰──────────────────────────────────────────────────────────╯│ │
|
||||
╭branches──────────────────────────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰──────────────────────────────────────────────────────────╯│ │
|
||||
╭commits───────────────────────────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
│ ││ │
|
||||
╰──────────────────────────────────────────────────────────╯│ │
|
||||
╭stash─────────────────────────────────────────────────────╮│ │
|
||||
│ ││ │
|
||||
╰──────────────────────────────────────────────────────────╯╰─────────────╯
|
||||
<options──────────────────────────────────────────────────────>A<B────────>
|
||||
A: statusSpacer1
|
||||
B: information
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "half screen mode, enlargedSideViewLocation left",
|
||||
mutateArgs: func(args *WindowArrangementArgs) {
|
||||
|
||||
@@ -152,8 +152,8 @@ func (self *WorkingTreeHelper) HandleCommitPress() error {
|
||||
message := self.c.Contexts().CommitMessage.GetPreservedMessageAndLogError()
|
||||
|
||||
if message == "" {
|
||||
commitPrefixConfig := self.commitPrefixConfigForRepo()
|
||||
if commitPrefixConfig != nil {
|
||||
commitPrefixConfigs := self.commitPrefixConfigsForRepo()
|
||||
for _, commitPrefixConfig := range commitPrefixConfigs {
|
||||
prefixPattern := commitPrefixConfig.Pattern
|
||||
prefixReplace := commitPrefixConfig.Replace
|
||||
branchName := self.refHelper.GetCheckedOutRef().Name
|
||||
@@ -165,6 +165,7 @@ func (self *WorkingTreeHelper) HandleCommitPress() error {
|
||||
if rgx.MatchString(branchName) {
|
||||
prefix := rgx.ReplaceAllString(branchName, prefixReplace)
|
||||
message = prefix
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,11 +229,11 @@ func (self *WorkingTreeHelper) prepareFilesForCommit() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *WorkingTreeHelper) commitPrefixConfigForRepo() *config.CommitPrefixConfig {
|
||||
func (self *WorkingTreeHelper) commitPrefixConfigsForRepo() []config.CommitPrefixConfig {
|
||||
cfg, ok := self.c.UserConfig().Git.CommitPrefixes[self.c.Git().RepoPaths.RepoName()]
|
||||
if ok {
|
||||
return &cfg
|
||||
return append(cfg, self.c.UserConfig().Git.CommitPrefix...)
|
||||
} else {
|
||||
return self.c.UserConfig().Git.CommitPrefix
|
||||
}
|
||||
|
||||
return self.c.UserConfig().Git.CommitPrefix
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func (self *JumpToSideWindowController) GetKeybindings(opts types.KeybindingsOpt
|
||||
// by default the keys are 1, 2, 3, etc
|
||||
Key: opts.GetKey(opts.Config.Universal.JumpToBlock[index]),
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: self.goToSideWindow(window),
|
||||
Handler: opts.Guards.NoPopupPanel(self.goToSideWindow(window)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+8
-1
@@ -1012,9 +1012,16 @@ func (gui *Gui) showIntroPopupMessage() {
|
||||
return err
|
||||
}
|
||||
|
||||
introMessage := utils.ResolvePlaceholderString(
|
||||
gui.c.Tr.IntroPopupMessage,
|
||||
map[string]string{
|
||||
"confirmationKey": gui.c.UserConfig().Keybinding.Universal.Confirm,
|
||||
},
|
||||
)
|
||||
|
||||
gui.c.Confirm(types.ConfirmOpts{
|
||||
Title: "",
|
||||
Prompt: gui.c.Tr.IntroPopupMessage,
|
||||
Prompt: introMessage,
|
||||
HandleConfirm: onConfirm,
|
||||
HandleClose: onConfirm,
|
||||
})
|
||||
|
||||
@@ -83,7 +83,7 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.OpenRecentRepos),
|
||||
Handler: self.helpers.Repos.CreateRecentReposMenu,
|
||||
Handler: opts.Guards.NoPopupPanel(self.helpers.Repos.CreateRecentReposMenu),
|
||||
Description: self.c.Tr.SwitchRepo,
|
||||
},
|
||||
{
|
||||
@@ -195,7 +195,7 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.ExtrasMenu),
|
||||
Handler: self.handleCreateExtrasMenuPanel,
|
||||
Handler: opts.Guards.NoPopupPanel(self.handleCreateExtrasMenuPanel),
|
||||
Description: self.c.Tr.OpenCommandLogMenu,
|
||||
Tooltip: self.c.Tr.OpenCommandLogMenuTooltip,
|
||||
OpensMenu: true,
|
||||
@@ -330,14 +330,14 @@ func (self *Gui) GetInitialKeybindings() ([]*types.Binding, []*gocui.ViewMouseBi
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.NextTab),
|
||||
Handler: self.handleNextTab,
|
||||
Handler: opts.Guards.NoPopupPanel(self.handleNextTab),
|
||||
Description: self.c.Tr.NextTab,
|
||||
Tag: "navigation",
|
||||
},
|
||||
{
|
||||
ViewName: "",
|
||||
Key: opts.GetKey(opts.Config.Universal.PrevTab),
|
||||
Handler: self.handlePrevTab,
|
||||
Handler: opts.Guards.NoPopupPanel(self.handlePrevTab),
|
||||
Description: self.c.Tr.PrevTab,
|
||||
Tag: "navigation",
|
||||
},
|
||||
|
||||
@@ -7,78 +7,11 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jesseduffield/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/jesseduffield/lazygit/pkg/constants"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
var labelByKey = map[gocui.Key]string{
|
||||
gocui.KeyF1: "<f1>",
|
||||
gocui.KeyF2: "<f2>",
|
||||
gocui.KeyF3: "<f3>",
|
||||
gocui.KeyF4: "<f4>",
|
||||
gocui.KeyF5: "<f5>",
|
||||
gocui.KeyF6: "<f6>",
|
||||
gocui.KeyF7: "<f7>",
|
||||
gocui.KeyF8: "<f8>",
|
||||
gocui.KeyF9: "<f9>",
|
||||
gocui.KeyF10: "<f10>",
|
||||
gocui.KeyF11: "<f11>",
|
||||
gocui.KeyF12: "<f12>",
|
||||
gocui.KeyInsert: "<insert>",
|
||||
gocui.KeyDelete: "<delete>",
|
||||
gocui.KeyHome: "<home>",
|
||||
gocui.KeyEnd: "<end>",
|
||||
gocui.KeyPgup: "<pgup>",
|
||||
gocui.KeyPgdn: "<pgdown>",
|
||||
gocui.KeyArrowUp: "<up>",
|
||||
gocui.KeyShiftArrowUp: "<s-up>",
|
||||
gocui.KeyArrowDown: "<down>",
|
||||
gocui.KeyShiftArrowDown: "<s-down>",
|
||||
gocui.KeyArrowLeft: "<left>",
|
||||
gocui.KeyArrowRight: "<right>",
|
||||
gocui.KeyTab: "<tab>", // <c-i>
|
||||
gocui.KeyBacktab: "<backtab>",
|
||||
gocui.KeyEnter: "<enter>", // <c-m>
|
||||
gocui.KeyAltEnter: "<a-enter>",
|
||||
gocui.KeyEsc: "<esc>", // <c-[>, <c-3>
|
||||
gocui.KeyBackspace: "<backspace>", // <c-h>
|
||||
gocui.KeyCtrlSpace: "<c-space>", // <c-~>, <c-2>
|
||||
gocui.KeyCtrlSlash: "<c-/>", // <c-_>
|
||||
gocui.KeySpace: "<space>",
|
||||
gocui.KeyCtrlA: "<c-a>",
|
||||
gocui.KeyCtrlB: "<c-b>",
|
||||
gocui.KeyCtrlC: "<c-c>",
|
||||
gocui.KeyCtrlD: "<c-d>",
|
||||
gocui.KeyCtrlE: "<c-e>",
|
||||
gocui.KeyCtrlF: "<c-f>",
|
||||
gocui.KeyCtrlG: "<c-g>",
|
||||
gocui.KeyCtrlJ: "<c-j>",
|
||||
gocui.KeyCtrlK: "<c-k>",
|
||||
gocui.KeyCtrlL: "<c-l>",
|
||||
gocui.KeyCtrlN: "<c-n>",
|
||||
gocui.KeyCtrlO: "<c-o>",
|
||||
gocui.KeyCtrlP: "<c-p>",
|
||||
gocui.KeyCtrlQ: "<c-q>",
|
||||
gocui.KeyCtrlR: "<c-r>",
|
||||
gocui.KeyCtrlS: "<c-s>",
|
||||
gocui.KeyCtrlT: "<c-t>",
|
||||
gocui.KeyCtrlU: "<c-u>",
|
||||
gocui.KeyCtrlV: "<c-v>",
|
||||
gocui.KeyCtrlW: "<c-w>",
|
||||
gocui.KeyCtrlX: "<c-x>",
|
||||
gocui.KeyCtrlY: "<c-y>",
|
||||
gocui.KeyCtrlZ: "<c-z>",
|
||||
gocui.KeyCtrl4: "<c-4>", // <c-\>
|
||||
gocui.KeyCtrl5: "<c-5>", // <c-]>
|
||||
gocui.KeyCtrl6: "<c-6>",
|
||||
gocui.KeyCtrl8: "<c-8>",
|
||||
gocui.MouseWheelUp: "mouse wheel up",
|
||||
gocui.MouseWheelDown: "mouse wheel down",
|
||||
}
|
||||
|
||||
var keyByLabel = lo.Invert(labelByKey)
|
||||
|
||||
func Label(name string) string {
|
||||
return LabelFromKey(GetKey(name))
|
||||
}
|
||||
@@ -90,7 +23,7 @@ func LabelFromKey(key types.Key) string {
|
||||
case rune:
|
||||
keyInt = int(key)
|
||||
case gocui.Key:
|
||||
value, ok := labelByKey[key]
|
||||
value, ok := config.LabelByKey[key]
|
||||
if ok {
|
||||
return value
|
||||
}
|
||||
@@ -105,7 +38,7 @@ func GetKey(key string) types.Key {
|
||||
if key == "<disabled>" {
|
||||
return nil
|
||||
} else if runeCount > 1 {
|
||||
binding, ok := keyByLabel[strings.ToLower(key)]
|
||||
binding, ok := config.KeyByLabel[strings.ToLower(key)]
|
||||
if !ok {
|
||||
log.Fatalf("Unrecognized key %s for keybinding. For permitted values see %s", strings.ToLower(key), constants.Links.Docs.CustomKeybindings)
|
||||
} else {
|
||||
|
||||
@@ -323,6 +323,6 @@ func (s *State) CalculateOrigin(currentOrigin int, bufferHeight int, numLines in
|
||||
|
||||
func wrapPatchLines(diff string, view *gocui.View) ([]int, []int) {
|
||||
_, viewLineIndices, patchLineIndices := utils.WrapViewLinesToWidth(
|
||||
view.Wrap, view.Editable, strings.TrimSuffix(diff, "\n"), view.InnerWidth())
|
||||
view.Wrap, view.Editable, strings.TrimSuffix(diff, "\n"), view.InnerWidth(), view.TabWidth)
|
||||
return viewLineIndices, patchLineIndices
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
package custom_commands
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/common"
|
||||
"github.com/jesseduffield/gocui"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/keybindings"
|
||||
"github.com/jesseduffield/lazygit/pkg/gui/types"
|
||||
"github.com/jesseduffield/lazygit/pkg/i18n"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
// Client is the entry point to this package. It returns a list of keybindings based on the config's user-defined custom commands.
|
||||
// See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Command_Keybindings.md for more info.
|
||||
type Client struct {
|
||||
c *common.Common
|
||||
c *helpers.HelperCommon
|
||||
handlerCreator *HandlerCreator
|
||||
keybindingCreator *KeybindingCreator
|
||||
}
|
||||
@@ -28,7 +32,7 @@ func NewClient(
|
||||
keybindingCreator := NewKeybindingCreator(c)
|
||||
|
||||
return &Client{
|
||||
c: c.Common,
|
||||
c: c,
|
||||
keybindingCreator: keybindingCreator,
|
||||
handlerCreator: handlerCreator,
|
||||
}
|
||||
@@ -37,13 +41,81 @@ func NewClient(
|
||||
func (self *Client) GetCustomCommandKeybindings() ([]*types.Binding, error) {
|
||||
bindings := []*types.Binding{}
|
||||
for _, customCommand := range self.c.UserConfig().CustomCommands {
|
||||
handler := self.handlerCreator.call(customCommand)
|
||||
compoundBindings, err := self.keybindingCreator.call(customCommand, handler)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(customCommand.CommandMenu) > 0 {
|
||||
handler := func() error {
|
||||
return self.showCustomCommandsMenu(customCommand)
|
||||
}
|
||||
bindings = append(bindings, &types.Binding{
|
||||
ViewName: "", // custom commands menus are global; we filter the commands inside by context
|
||||
Key: keybindings.GetKey(customCommand.Key),
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: handler,
|
||||
Description: getCustomCommandsMenuDescription(customCommand, self.c.Tr),
|
||||
OpensMenu: true,
|
||||
})
|
||||
} else {
|
||||
handler := self.handlerCreator.call(customCommand)
|
||||
compoundBindings, err := self.keybindingCreator.call(customCommand, handler)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bindings = append(bindings, compoundBindings...)
|
||||
}
|
||||
bindings = append(bindings, compoundBindings...)
|
||||
}
|
||||
|
||||
return bindings, nil
|
||||
}
|
||||
|
||||
func (self *Client) showCustomCommandsMenu(customCommand config.CustomCommand) error {
|
||||
menuItems := make([]*types.MenuItem, 0, len(customCommand.CommandMenu))
|
||||
for _, subCommand := range customCommand.CommandMenu {
|
||||
if len(subCommand.CommandMenu) > 0 {
|
||||
handler := func() error {
|
||||
return self.showCustomCommandsMenu(subCommand)
|
||||
}
|
||||
menuItems = append(menuItems, &types.MenuItem{
|
||||
Label: subCommand.GetDescription(),
|
||||
Key: keybindings.GetKey(subCommand.Key),
|
||||
OnPress: handler,
|
||||
OpensMenu: true,
|
||||
})
|
||||
} else {
|
||||
if subCommand.Context != "" && subCommand.Context != "global" {
|
||||
viewNames, err := self.keybindingCreator.getViewNamesAndContexts(subCommand)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
currentView := self.c.GocuiGui().CurrentView()
|
||||
enabled := currentView != nil && lo.Contains(viewNames, currentView.Name())
|
||||
if !enabled {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
menuItems = append(menuItems, &types.MenuItem{
|
||||
Label: subCommand.GetDescription(),
|
||||
Key: keybindings.GetKey(subCommand.Key),
|
||||
OnPress: self.handlerCreator.call(subCommand),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(menuItems) == 0 {
|
||||
menuItems = append(menuItems, &types.MenuItem{
|
||||
Label: self.c.Tr.NoApplicableCommandsInThisContext,
|
||||
OnPress: func() error { return nil },
|
||||
})
|
||||
}
|
||||
|
||||
title := getCustomCommandsMenuDescription(customCommand, self.c.Tr)
|
||||
return self.c.Menu(types.CreateMenuOptions{Title: title, Items: menuItems, HideCancel: true})
|
||||
}
|
||||
|
||||
func getCustomCommandsMenuDescription(customCommand config.CustomCommand, tr *i18n.TranslationSet) string {
|
||||
if customCommand.Description != "" {
|
||||
return customCommand.Description
|
||||
}
|
||||
|
||||
return tr.CustomCommands
|
||||
}
|
||||
|
||||
@@ -261,7 +261,7 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses
|
||||
|
||||
cmdObj := self.c.OS().Cmd.NewShell(cmdStr)
|
||||
|
||||
if customCommand.Subprocess {
|
||||
if customCommand.Subprocess != nil && *customCommand.Subprocess {
|
||||
return self.c.RunSubprocessAndRefresh(cmdObj)
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses
|
||||
return self.c.WithWaitingStatus(loadingText, func(gocui.Task) error {
|
||||
self.c.LogAction(self.c.Tr.Actions.CustomCommand)
|
||||
|
||||
if customCommand.Stream {
|
||||
if customCommand.Stream != nil && *customCommand.Stream {
|
||||
cmdObj.StreamOutput()
|
||||
}
|
||||
output, err := cmdObj.RunWithOutput()
|
||||
@@ -283,14 +283,14 @@ func (self *HandlerCreator) finalHandler(customCommand config.CustomCommand, ses
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if customCommand.After.CheckForConflicts {
|
||||
if customCommand.After != nil && customCommand.After.CheckForConflicts {
|
||||
return self.mergeAndRebaseHelper.CheckForConflicts(err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if customCommand.ShowOutput {
|
||||
if customCommand.ShowOutput != nil && *customCommand.ShowOutput {
|
||||
if strings.TrimSpace(output) == "" {
|
||||
output = self.c.Tr.EmptyOutput
|
||||
}
|
||||
|
||||
@@ -34,18 +34,13 @@ func (self *KeybindingCreator) call(customCommand config.CustomCommand, handler
|
||||
return nil, err
|
||||
}
|
||||
|
||||
description := customCommand.Description
|
||||
if description == "" {
|
||||
description = customCommand.Command
|
||||
}
|
||||
|
||||
return lo.Map(viewNames, func(viewName string, _ int) *types.Binding {
|
||||
return &types.Binding{
|
||||
ViewName: viewName,
|
||||
Key: keybindings.GetKey(customCommand.Key),
|
||||
Modifier: gocui.ModNone,
|
||||
Handler: handler,
|
||||
Description: description,
|
||||
Description: customCommand.GetDescription(),
|
||||
}
|
||||
}), nil
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
// compatibility. We already did this for Commit.Sha, which was renamed to Hash.
|
||||
|
||||
type Commit struct {
|
||||
Hash string // deprecated: use Sha
|
||||
Sha string
|
||||
Hash string
|
||||
Sha string // deprecated: use Hash
|
||||
Name string
|
||||
Status models.CommitStatus
|
||||
Action todo.TodoCommand
|
||||
|
||||
@@ -203,6 +203,7 @@ func (gui *Gui) configureViewProperties() {
|
||||
|
||||
for _, view := range []*gocui.View{gui.Views.Main, gui.Views.Secondary, gui.Views.Staging, gui.Views.StagingSecondary, gui.Views.PatchBuilding, gui.Views.PatchBuildingSecondary, gui.Views.MergeConflicts} {
|
||||
view.CanScrollPastBottom = gui.c.UserConfig().Gui.ScrollPastBottom
|
||||
view.TabWidth = gui.c.UserConfig().Gui.TabWidth
|
||||
}
|
||||
|
||||
gui.Views.CommitDescription.FgColor = theme.GocuiDefaultTextColor
|
||||
|
||||
+58
-44
@@ -621,6 +621,7 @@ type TranslationSet struct {
|
||||
PasteCommitMessageFromClipboard string
|
||||
SurePasteCommitMessage string
|
||||
CommitMessage string
|
||||
CommitMessageBody string
|
||||
CommitSubject string
|
||||
CommitAuthor string
|
||||
CommitTags string
|
||||
@@ -685,10 +686,12 @@ type TranslationSet struct {
|
||||
CommitDiffCopiedToClipboard string
|
||||
CommitURLCopiedToClipboard string
|
||||
CommitMessageCopiedToClipboard string
|
||||
CommitMessageBodyCopiedToClipboard string
|
||||
CommitSubjectCopiedToClipboard string
|
||||
CommitAuthorCopiedToClipboard string
|
||||
CommitTagsCopiedToClipboard string
|
||||
CommitHasNoTags string
|
||||
CommitHasNoMessageBody string
|
||||
PatchCopiedToClipboard string
|
||||
CopiedToClipboard string
|
||||
ErrCannotEditDirectory string
|
||||
@@ -840,6 +843,8 @@ type TranslationSet struct {
|
||||
RangeSelectNotSupportedForSubmodules string
|
||||
OldCherryPickKeyWarning string
|
||||
CommandDoesNotSupportOpeningInEditor string
|
||||
CustomCommands string
|
||||
NoApplicableCommandsInThisContext string
|
||||
Actions Actions
|
||||
Bisect Bisect
|
||||
Log Log
|
||||
@@ -914,6 +919,7 @@ type Actions struct {
|
||||
MoveCommitUp string
|
||||
MoveCommitDown string
|
||||
CopyCommitMessageToClipboard string
|
||||
CopyCommitMessageBodyToClipboard string
|
||||
CopyCommitSubjectToClipboard string
|
||||
CopyCommitDiffToClipboard string
|
||||
CopyCommitHashToClipboard string
|
||||
@@ -1015,6 +1021,8 @@ Thanks for using lazygit! Seriously you rock. Three things to share with you:
|
||||
You can also sponsor me and tell me what to work on by clicking the donate
|
||||
button at the bottom right.
|
||||
Or even just star the repo to share the love!
|
||||
|
||||
Press {{confirmationKey}} to get started.
|
||||
`
|
||||
|
||||
const englishDeprecatedEditConfigWarning = `
|
||||
@@ -1432,7 +1440,7 @@ func EnglishTranslationSet() *TranslationSet {
|
||||
DiscardOldFileChangeTooltip: "Discard this commit's changes to this file. This runs an interactive rebase in the background, so you may get a merge conflict if a later commit also changes this file.",
|
||||
DiscardFileChangesTitle: "Discard file changes",
|
||||
DiscardFileChangesPrompt: "Are you sure you want to remove changes to the selected file(s) from this commit?\n\nThis action will start a rebase, reverting these file changes. Be aware that if subsequent commits depend on these changes, you may need to resolve conflicts.\nNote: This will also reset any active custom patches.",
|
||||
DisabledForGPG: "Feature not available for users using GPG",
|
||||
DisabledForGPG: "Feature not available for users using GPG.\n\nIf you are using a passphrase agent (e.g. gpg-agent) so that you don't have to type your passphrase when signing, you can enable this feature by adding\n\ngit:\n overrideGpg: true\n\nto your lazygit config file.",
|
||||
CreateRepo: "Not in a git repository. Create a new git repository? (y/n): ",
|
||||
BareRepo: "You've attempted to open Lazygit in a bare repo but Lazygit does not yet support bare repos. Open most recent repo? (y/n) ",
|
||||
InitialBranch: "Branch name? (leave empty for git's default): ",
|
||||
@@ -1653,7 +1661,8 @@ func EnglishTranslationSet() *TranslationSet {
|
||||
CopyCommitMessageToClipboard: "Copy commit message to clipboard",
|
||||
PasteCommitMessageFromClipboard: "Paste commit message from clipboard",
|
||||
SurePasteCommitMessage: "Pasting will overwrite the current commit message, continue?",
|
||||
CommitMessage: "Commit message",
|
||||
CommitMessage: "Commit message (subject and body)",
|
||||
CommitMessageBody: "Commit message body",
|
||||
CommitSubject: "Commit subject",
|
||||
CommitAuthor: "Commit author",
|
||||
CommitTags: "Commit tags",
|
||||
@@ -1717,10 +1726,12 @@ func EnglishTranslationSet() *TranslationSet {
|
||||
CommitDiffCopiedToClipboard: "Commit diff copied to clipboard",
|
||||
CommitURLCopiedToClipboard: "Commit URL copied to clipboard",
|
||||
CommitMessageCopiedToClipboard: "Commit message copied to clipboard",
|
||||
CommitMessageBodyCopiedToClipboard: "Commit message body copied to clipboard",
|
||||
CommitSubjectCopiedToClipboard: "Commit subject copied to clipboard",
|
||||
CommitAuthorCopiedToClipboard: "Commit author copied to clipboard",
|
||||
CommitTagsCopiedToClipboard: "Commit tags copied to clipboard",
|
||||
CommitHasNoTags: "Commit has no tags",
|
||||
CommitHasNoMessageBody: "Commit has no message body",
|
||||
PatchCopiedToClipboard: "Patch copied to clipboard",
|
||||
CopiedToClipboard: "copied to clipboard",
|
||||
ErrCannotEditDirectory: "Cannot edit directories: you can only edit individual files",
|
||||
@@ -1870,51 +1881,54 @@ func EnglishTranslationSet() *TranslationSet {
|
||||
RangeSelectNotSupportedForSubmodules: "Range select not supported for submodules",
|
||||
OldCherryPickKeyWarning: "The 'c' key is no longer the default key for copying commits to cherry pick. Please use `{{.copy}}` instead (and `{{.paste}}` to paste). The reason for this change is that the 'v' key for selecting a range of lines when staging is now also used for selecting a range of lines in any list view, meaning that we needed to find a new key for pasting commits, and if we're going to now use `{{.paste}}` for pasting commits, we may as well use `{{.copy}}` for copying them. If you want to configure the keybindings to get the old behaviour, set the following in your config:\n\nkeybinding:\n universal:\n toggleRangeSelect: <something other than v>\n commits:\n cherryPickCopy: 'c'\n pasteCommits: 'v'",
|
||||
CommandDoesNotSupportOpeningInEditor: "This command doesn't support switching to the editor",
|
||||
CustomCommands: "Custom commands",
|
||||
NoApplicableCommandsInThisContext: "(No applicable commands in this context)",
|
||||
|
||||
Actions: Actions{
|
||||
// TODO: combine this with the original keybinding descriptions (those are all in lowercase atm)
|
||||
CheckoutCommit: "Checkout commit",
|
||||
CheckoutBranchAtCommit: "Checkout branch '%s'",
|
||||
CheckoutCommitAsDetachedHead: "Checkout commit %s as detached head",
|
||||
CheckoutTag: "Checkout tag",
|
||||
CheckoutBranch: "Checkout branch",
|
||||
ForceCheckoutBranch: "Force checkout branch",
|
||||
CheckoutBranchOrCommit: "Checkout branch or commit",
|
||||
DeleteLocalBranch: "Delete local branch",
|
||||
Merge: "Merge",
|
||||
SquashMerge: "Squash merge",
|
||||
RebaseBranch: "Rebase branch",
|
||||
RenameBranch: "Rename branch",
|
||||
CreateBranch: "Create branch",
|
||||
CherryPick: "(Cherry-pick) paste commits",
|
||||
CheckoutFile: "Checkout file",
|
||||
DiscardOldFileChange: "Discard old file change",
|
||||
SquashCommitDown: "Squash commit down",
|
||||
FixupCommit: "Fixup commit",
|
||||
RewordCommit: "Reword commit",
|
||||
DropCommit: "Drop commit",
|
||||
EditCommit: "Edit commit",
|
||||
AmendCommit: "Amend commit",
|
||||
ResetCommitAuthor: "Reset commit author",
|
||||
SetCommitAuthor: "Set commit author",
|
||||
AddCommitCoAuthor: "Add commit co-author",
|
||||
RevertCommit: "Revert commit",
|
||||
CreateFixupCommit: "Create fixup commit",
|
||||
SquashAllAboveFixupCommits: "Squash all above fixup commits",
|
||||
CreateLightweightTag: "Create lightweight tag",
|
||||
CreateAnnotatedTag: "Create annotated tag",
|
||||
CopyCommitMessageToClipboard: "Copy commit message to clipboard",
|
||||
CopyCommitSubjectToClipboard: "Copy commit subject to clipboard",
|
||||
CopyCommitTagsToClipboard: "Copy commit tags to clipboard",
|
||||
CopyCommitDiffToClipboard: "Copy commit diff to clipboard",
|
||||
CopyCommitHashToClipboard: "Copy full commit hash to clipboard",
|
||||
CopyCommitURLToClipboard: "Copy commit URL to clipboard",
|
||||
CopyCommitAuthorToClipboard: "Copy commit author to clipboard",
|
||||
CopyCommitAttributeToClipboard: "Copy to clipboard",
|
||||
CopyPatchToClipboard: "Copy patch to clipboard",
|
||||
MoveCommitUp: "Move commit up",
|
||||
MoveCommitDown: "Move commit down",
|
||||
CustomCommand: "Custom command",
|
||||
CheckoutCommit: "Checkout commit",
|
||||
CheckoutBranchAtCommit: "Checkout branch '%s'",
|
||||
CheckoutCommitAsDetachedHead: "Checkout commit %s as detached head",
|
||||
CheckoutTag: "Checkout tag",
|
||||
CheckoutBranch: "Checkout branch",
|
||||
ForceCheckoutBranch: "Force checkout branch",
|
||||
CheckoutBranchOrCommit: "Checkout branch or commit",
|
||||
DeleteLocalBranch: "Delete local branch",
|
||||
Merge: "Merge",
|
||||
SquashMerge: "Squash merge",
|
||||
RebaseBranch: "Rebase branch",
|
||||
RenameBranch: "Rename branch",
|
||||
CreateBranch: "Create branch",
|
||||
CherryPick: "(Cherry-pick) paste commits",
|
||||
CheckoutFile: "Checkout file",
|
||||
DiscardOldFileChange: "Discard old file change",
|
||||
SquashCommitDown: "Squash commit down",
|
||||
FixupCommit: "Fixup commit",
|
||||
RewordCommit: "Reword commit",
|
||||
DropCommit: "Drop commit",
|
||||
EditCommit: "Edit commit",
|
||||
AmendCommit: "Amend commit",
|
||||
ResetCommitAuthor: "Reset commit author",
|
||||
SetCommitAuthor: "Set commit author",
|
||||
AddCommitCoAuthor: "Add commit co-author",
|
||||
RevertCommit: "Revert commit",
|
||||
CreateFixupCommit: "Create fixup commit",
|
||||
SquashAllAboveFixupCommits: "Squash all above fixup commits",
|
||||
CreateLightweightTag: "Create lightweight tag",
|
||||
CreateAnnotatedTag: "Create annotated tag",
|
||||
CopyCommitMessageToClipboard: "Copy commit message to clipboard",
|
||||
CopyCommitMessageBodyToClipboard: "Copy commit message body to clipboard",
|
||||
CopyCommitSubjectToClipboard: "Copy commit subject to clipboard",
|
||||
CopyCommitTagsToClipboard: "Copy commit tags to clipboard",
|
||||
CopyCommitDiffToClipboard: "Copy commit diff to clipboard",
|
||||
CopyCommitHashToClipboard: "Copy full commit hash to clipboard",
|
||||
CopyCommitURLToClipboard: "Copy commit URL to clipboard",
|
||||
CopyCommitAuthorToClipboard: "Copy commit author to clipboard",
|
||||
CopyCommitAttributeToClipboard: "Copy to clipboard",
|
||||
CopyPatchToClipboard: "Copy patch to clipboard",
|
||||
MoveCommitUp: "Move commit up",
|
||||
MoveCommitDown: "Move commit down",
|
||||
CustomCommand: "Custom command",
|
||||
|
||||
// TODO: remove
|
||||
DiscardAllChangesInDirectory: "Discard all changes in directory",
|
||||
|
||||
@@ -174,6 +174,10 @@ func (self *Shell) EmptyCommit(message string) *Shell {
|
||||
return self.RunCommand([]string{"git", "commit", "--allow-empty", "-m", message})
|
||||
}
|
||||
|
||||
func (self *Shell) EmptyCommitWithBody(subject string, body string) *Shell {
|
||||
return self.RunCommand([]string{"git", "commit", "--allow-empty", "-m", subject, "-m", body})
|
||||
}
|
||||
|
||||
func (self *Shell) EmptyCommitDaysAgo(message string, daysAgo int) *Shell {
|
||||
return self.RunCommand([]string{"git", "commit", "--allow-empty", "--date", fmt.Sprintf("%d days ago", daysAgo), "-m", message})
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ var CommitWipWithPrefix = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().Git.CommitPrefixes = map[string]config.CommitPrefixConfig{"repo": {Pattern: "^\\w+\\/(\\w+-\\w+).*", Replace: "[$1]: "}}
|
||||
cfg.GetUserConfig().Git.CommitPrefixes = map[string][]config.CommitPrefixConfig{"repo": {{Pattern: "^\\w+\\/(\\w+-\\w+).*", Replace: "[$1]: "}}}
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.NewBranch("feature/TEST-002")
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package commit
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
var CommitWithFallthroughPrefix = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "Commit with multiple CommitPrefixConfig",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().Git.CommitPrefix = []config.CommitPrefixConfig{
|
||||
{Pattern: "^doesntmatch-(\\w+).*", Replace: "[BAD $1]: "},
|
||||
{Pattern: "^\\w+\\/(\\w+-\\w+).*", Replace: "[GOOD $1]: "},
|
||||
}
|
||||
cfg.GetUserConfig().Git.CommitPrefixes = map[string][]config.CommitPrefixConfig{
|
||||
"DifferentProject": {{Pattern: "^otherthatdoesn'tmatch-(\\w+).*", Replace: "[BAD $1]: "}},
|
||||
}
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.NewBranch("feature/TEST-001")
|
||||
shell.CreateFile("test-commit-prefix", "This is foo bar")
|
||||
},
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Commits().
|
||||
IsEmpty()
|
||||
|
||||
t.Views().Files().
|
||||
IsFocused().
|
||||
PressPrimaryAction().
|
||||
Press(keys.Files.CommitChanges)
|
||||
|
||||
t.ExpectPopup().CommitMessagePanel().
|
||||
Title(Equals("Commit summary")).
|
||||
InitialText(Equals("[GOOD TEST-001]: ")).
|
||||
Type("my commit message").
|
||||
Cancel()
|
||||
|
||||
t.Views().Files().
|
||||
IsFocused().
|
||||
Press(keys.Files.CommitChanges)
|
||||
|
||||
t.ExpectPopup().CommitMessagePanel().
|
||||
Title(Equals("Commit summary")).
|
||||
InitialText(Equals("[GOOD TEST-001]: my commit message")).
|
||||
Type(". Added something else").
|
||||
Confirm()
|
||||
|
||||
t.Views().Commits().Focus()
|
||||
t.Views().Main().Content(Contains("[GOOD TEST-001]: my commit message. Added something else"))
|
||||
},
|
||||
})
|
||||
@@ -10,7 +10,7 @@ var CommitWithGlobalPrefix = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().Git.CommitPrefix = &config.CommitPrefixConfig{Pattern: "^\\w+\\/(\\w+-\\w+).*", Replace: "[$1]: "}
|
||||
cfg.GetUserConfig().Git.CommitPrefix = []config.CommitPrefixConfig{{Pattern: "^\\w+\\/(\\w+-\\w+).*", Replace: "[$1]: "}}
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.NewBranch("feature/TEST-001")
|
||||
|
||||
@@ -10,10 +10,10 @@ var CommitWithNonMatchingBranchName = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().Git.CommitPrefix = &config.CommitPrefixConfig{
|
||||
cfg.GetUserConfig().Git.CommitPrefix = []config.CommitPrefixConfig{{
|
||||
Pattern: "^\\w+\\/(\\w+-\\w+).*",
|
||||
Replace: "[$1]: ",
|
||||
}
|
||||
}}
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.NewBranch("branchnomatch")
|
||||
|
||||
@@ -10,11 +10,11 @@ var CommitWithPrefix = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().Git.CommitPrefixes = map[string]config.CommitPrefixConfig{
|
||||
"repo": {
|
||||
cfg.GetUserConfig().Git.CommitPrefixes = map[string][]config.CommitPrefixConfig{
|
||||
"repo": {{
|
||||
Pattern: `^\w+/(\w+-\w+).*`,
|
||||
Replace: "[$1]: ",
|
||||
},
|
||||
}},
|
||||
}
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
|
||||
@@ -12,8 +12,7 @@ var CopyAuthorToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
// Include delimiters around the text so that we can assert on the entire content
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo /{{text}}/ > clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
|
||||
SetupRepo: func(shell *Shell) {
|
||||
@@ -36,13 +35,6 @@ var CopyAuthorToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.ExpectToast(Equals("Commit author copied to clipboard"))
|
||||
|
||||
t.Views().Files().
|
||||
Focus().
|
||||
Press(keys.Files.RefreshFiles).
|
||||
Lines(
|
||||
Contains("clipboard").IsSelected(),
|
||||
)
|
||||
|
||||
t.Views().Main().Content(Contains("/John Doe <john@doe.com>/"))
|
||||
t.FileSystem().FileContent("clipboard", Equals("John Doe <john@doe.com>"))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package commit
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
// We're emulating the clipboard by writing to a file called clipboard
|
||||
|
||||
var CopyMessageBodyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "Copy a commit message body to the clipboard",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.EmptyCommitWithBody("My Subject", "My awesome commit message body")
|
||||
},
|
||||
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Commits().
|
||||
Focus().
|
||||
Lines(
|
||||
Contains("My Subject").IsSelected(),
|
||||
).
|
||||
Press(keys.Commits.CopyCommitAttributeToClipboard)
|
||||
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Commit message body")).
|
||||
Confirm()
|
||||
|
||||
t.ExpectToast(Equals("Commit message body copied to clipboard"))
|
||||
|
||||
t.FileSystem().FileContent("clipboard", Equals("My awesome commit message body"))
|
||||
},
|
||||
})
|
||||
@@ -12,8 +12,7 @@ var CopyTagToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
// Include delimiters around the text so that we can assert on the entire content
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo _{{text}}_ > clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
|
||||
SetupRepo: func(shell *Shell) {
|
||||
@@ -38,14 +37,6 @@ var CopyTagToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.ExpectToast(Equals("Commit tags copied to clipboard"))
|
||||
|
||||
t.Views().Files().
|
||||
Focus().
|
||||
Press(keys.Files.RefreshFiles).
|
||||
Lines(
|
||||
Contains("clipboard").IsSelected(),
|
||||
)
|
||||
|
||||
t.Views().Main().Content(Contains("+_tag2"))
|
||||
t.Views().Main().Content(Contains("+tag1_"))
|
||||
t.FileSystem().FileContent("clipboard", Equals("tag2\ntag1"))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package commit
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
var DisableCopyCommitMessageBody = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "Disables copy commit message body when there is no body",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {},
|
||||
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.EmptyCommit("commit")
|
||||
},
|
||||
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Commits().
|
||||
Focus().
|
||||
Lines(
|
||||
Contains("commit").IsSelected(),
|
||||
).
|
||||
Press(keys.Commits.CopyCommitAttributeToClipboard)
|
||||
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Commit message body")).
|
||||
Confirm()
|
||||
|
||||
t.ExpectToast(Equals("Disabled: Commit has no message body"))
|
||||
},
|
||||
})
|
||||
@@ -10,7 +10,7 @@ var PasteCommitMessage = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo {{text}} > ../clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > ../clipboard"
|
||||
config.GetUserConfig().OS.ReadFromClipboardCmd = "cat ../clipboard"
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
@@ -26,7 +26,7 @@ var PasteCommitMessage = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Press(keys.Commits.CopyCommitAttributeToClipboard)
|
||||
|
||||
t.ExpectPopup().Menu().Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Commit message")).Confirm()
|
||||
Select(Contains("Commit message (subject and body)")).Confirm()
|
||||
|
||||
t.ExpectToast(Equals("Commit message copied to clipboard"))
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ var PasteCommitMessageOverExisting = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo {{text}} > ../clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > ../clipboard"
|
||||
config.GetUserConfig().OS.ReadFromClipboardCmd = "cat ../clipboard"
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
@@ -26,7 +26,7 @@ var PasteCommitMessageOverExisting = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Press(keys.Commits.CopyCommitAttributeToClipboard)
|
||||
|
||||
t.ExpectPopup().Menu().Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Commit message")).Confirm()
|
||||
Select(Contains("Commit message (subject and body)")).Confirm()
|
||||
|
||||
t.ExpectToast(Equals("Commit message copied to clipboard"))
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ var CheckForConflicts = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Key: "m",
|
||||
Context: "localBranches",
|
||||
Command: "git merge {{ .SelectedLocalBranch.Name | quote }}",
|
||||
After: config.CustomCommandAfterHook{
|
||||
After: &config.CustomCommandAfterHook{
|
||||
CheckForConflicts: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package custom_commands
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
var CustomCommandsSubmenu = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "Using custom commands from a custom commands menu",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupRepo: func(shell *Shell) {},
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
|
||||
{
|
||||
Key: "x",
|
||||
Description: "My Custom Commands",
|
||||
CommandMenu: []config.CustomCommand{
|
||||
{
|
||||
Key: "1",
|
||||
Context: "global",
|
||||
Command: "touch myfile-global",
|
||||
},
|
||||
{
|
||||
Key: "2",
|
||||
Context: "files",
|
||||
Command: "touch myfile-files",
|
||||
},
|
||||
{
|
||||
Key: "3",
|
||||
Context: "commits",
|
||||
Command: "touch myfile-commits",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Files().
|
||||
Focus().
|
||||
IsEmpty().
|
||||
Press("x").
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("My Custom Commands")).
|
||||
Lines(
|
||||
Contains("1 touch myfile-global"),
|
||||
Contains("2 touch myfile-files"),
|
||||
).
|
||||
Select(Contains("touch myfile-files")).Confirm()
|
||||
}).
|
||||
Lines(
|
||||
Contains("myfile-files"),
|
||||
)
|
||||
|
||||
t.Views().Commits().
|
||||
Focus().
|
||||
Press("x").
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("My Custom Commands")).
|
||||
Lines(
|
||||
Contains("1 touch myfile-global"),
|
||||
Contains("3 touch myfile-commits"),
|
||||
)
|
||||
t.GlobalPress("3")
|
||||
})
|
||||
|
||||
t.Views().Files().
|
||||
Lines(
|
||||
Contains("myfile-commits"),
|
||||
Contains("myfile-files"),
|
||||
)
|
||||
},
|
||||
})
|
||||
@@ -15,10 +15,9 @@ var GlobalContext = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Context: "global",
|
||||
Command: "touch myfile",
|
||||
ShowOutput: false,
|
||||
Key: "X",
|
||||
Context: "global",
|
||||
Command: "touch myfile",
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -15,10 +15,9 @@ var MultipleContexts = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Context: "commits, reflogCommits",
|
||||
Command: "touch myfile",
|
||||
ShowOutput: false,
|
||||
Key: "X",
|
||||
Context: "commits, reflogCommits",
|
||||
Command: "touch myfile",
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -15,18 +15,19 @@ var ShowOutputInPanel = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
shell.EmptyCommit("my change")
|
||||
},
|
||||
SetupConfig: func(cfg *config.AppConfig) {
|
||||
trueVal := true
|
||||
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
|
||||
{
|
||||
Key: "X",
|
||||
Context: "commits",
|
||||
Command: "printf '%s' '{{ .SelectedLocalCommit.Name }}'",
|
||||
ShowOutput: true,
|
||||
ShowOutput: &trueVal,
|
||||
},
|
||||
{
|
||||
Key: "Y",
|
||||
Context: "commits",
|
||||
Command: "printf '%s' '{{ .SelectedLocalCommit.Name }}'",
|
||||
ShowOutput: true,
|
||||
ShowOutput: &trueVal,
|
||||
OutputTitle: "Subject of commit {{ .SelectedLocalCommit.Hash }}",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package diff
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
// note: this is required to simulate the clipboard during CI
|
||||
func expectClipboard(t *TestDriver, matcher *TextMatcher) {
|
||||
defer t.Shell().DeleteFile("clipboard")
|
||||
|
||||
t.FileSystem().FileContent("clipboard", matcher)
|
||||
}
|
||||
|
||||
var CopyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "The copy menu allows to copy name and diff of selected/all files",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.CreateDir("dir")
|
||||
shell.CreateFileAndAdd("dir/file1", "1st line\n")
|
||||
shell.Commit("1")
|
||||
shell.CreateFileAndAdd("dir/file1", "1st line\n2nd line\n")
|
||||
shell.CreateFileAndAdd("dir/file2", "file2\n")
|
||||
shell.Commit("2")
|
||||
},
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Commits().
|
||||
Focus().
|
||||
Lines(
|
||||
Contains("2").IsSelected(),
|
||||
Contains("1"),
|
||||
).
|
||||
PressEnter()
|
||||
|
||||
t.Views().CommitFiles().
|
||||
IsFocused().
|
||||
Lines(
|
||||
Contains("dir").IsSelected(),
|
||||
Contains("file1"),
|
||||
Contains("file2"),
|
||||
).
|
||||
NavigateToLine(Contains("file1")).
|
||||
Press(keys.Files.CopyFileInfoToClipboard).
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("File name")).
|
||||
Confirm().
|
||||
Tap(func() {
|
||||
t.ExpectToast(Equals("File name copied to clipboard"))
|
||||
expectClipboard(t, Equals("file1"))
|
||||
})
|
||||
}).
|
||||
Press(keys.Files.CopyFileInfoToClipboard).
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Path")).
|
||||
Confirm().
|
||||
Tap(func() {
|
||||
t.ExpectToast(Equals("File path copied to clipboard"))
|
||||
expectClipboard(t, Equals("dir/file1"))
|
||||
})
|
||||
}).
|
||||
Press(keys.Files.CopyFileInfoToClipboard).
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Diff of selected file")).
|
||||
Confirm().
|
||||
Tap(func() {
|
||||
t.ExpectToast(Equals("File diff copied to clipboard"))
|
||||
expectClipboard(t,
|
||||
Contains("diff --git a/dir/file1 b/dir/file1").Contains("+2nd line").DoesNotContain("+1st line").
|
||||
DoesNotContain("diff --git a/dir/file2 b/dir/file2").DoesNotContain("+file2"))
|
||||
})
|
||||
}).
|
||||
Press(keys.Files.CopyFileInfoToClipboard).
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Diff of all files")).
|
||||
Confirm().
|
||||
Tap(func() {
|
||||
t.ExpectToast(Equals("All files diff copied to clipboard"))
|
||||
expectClipboard(t,
|
||||
Contains("diff --git a/dir/file1 b/dir/file1").Contains("+2nd line").DoesNotContain("+1st line").
|
||||
Contains("diff --git a/dir/file2 b/dir/file2").Contains("+file2"))
|
||||
})
|
||||
})
|
||||
|
||||
t.Views().Commits().
|
||||
Focus().
|
||||
// Select both commits
|
||||
Press(keys.Universal.RangeSelectDown).
|
||||
PressEnter()
|
||||
|
||||
t.Views().CommitFiles().
|
||||
IsFocused().
|
||||
Lines(
|
||||
Contains("dir").IsSelected(),
|
||||
Contains("file1"),
|
||||
Contains("file2"),
|
||||
).
|
||||
NavigateToLine(Contains("file1")).
|
||||
Press(keys.Files.CopyFileInfoToClipboard).
|
||||
Tap(func() {
|
||||
t.ExpectPopup().Menu().
|
||||
Title(Equals("Copy to clipboard")).
|
||||
Select(Contains("Diff of selected file")).
|
||||
Confirm().
|
||||
Tap(func() {
|
||||
t.ExpectToast(Equals("File diff copied to clipboard"))
|
||||
expectClipboard(t,
|
||||
Contains("diff --git a/dir/file1 b/dir/file1").Contains("+1st line").Contains("+2nd line"))
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -17,7 +17,7 @@ var CopyMenu = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo {{text}} > clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {},
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
@@ -100,7 +100,7 @@ var CopyMenu = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.ExpectToast(Equals("File name copied to clipboard"))
|
||||
|
||||
expectClipboard(t, Contains("unstaged_file"))
|
||||
expectClipboard(t, Equals("1-unstaged_file"))
|
||||
})
|
||||
|
||||
// Copy file path
|
||||
@@ -114,7 +114,7 @@ var CopyMenu = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.ExpectToast(Equals("File path copied to clipboard"))
|
||||
|
||||
expectClipboard(t, Contains("dir/1-unstaged_file"))
|
||||
expectClipboard(t, Equals("dir/1-unstaged_file"))
|
||||
})
|
||||
|
||||
// Selected path diff on a single (unstaged) file
|
||||
|
||||
@@ -12,7 +12,7 @@ var CopyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo {{text}} > clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
|
||||
SetupRepo: func(shell *Shell) {
|
||||
@@ -34,13 +34,6 @@ var CopyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.GlobalPress(keys.Files.RefreshFiles)
|
||||
|
||||
// Expect to see the clipboard file with contents
|
||||
t.Views().Files().
|
||||
IsFocused().
|
||||
Lines(
|
||||
Contains("clipboard").IsSelected(),
|
||||
)
|
||||
|
||||
t.Views().Main().Content(Contains("branch-a"))
|
||||
t.FileSystem().FileContent("clipboard", Equals("branch-a"))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -10,8 +10,7 @@ var CopyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {
|
||||
// Include delimiters around the text so that we can assert on the entire content
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "echo _{{text}}_ > clipboard"
|
||||
config.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard"
|
||||
},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.EmptyCommit("one")
|
||||
@@ -27,13 +26,6 @@ var CopyToClipboard = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
|
||||
t.ExpectToast(Equals("'super.l000ongtag' copied to clipboard"))
|
||||
|
||||
t.Views().Files().
|
||||
Focus().
|
||||
Press(keys.Files.RefreshFiles).
|
||||
Lines(
|
||||
Contains("clipboard").IsSelected(),
|
||||
)
|
||||
|
||||
t.Views().Main().Content(Contains("super.l000ongtag"))
|
||||
t.FileSystem().FileContent("clipboard", Equals("super.l000ongtag"))
|
||||
},
|
||||
})
|
||||
|
||||
@@ -93,14 +93,17 @@ var tests = []*components.IntegrationTest{
|
||||
commit.CommitMultiline,
|
||||
commit.CommitSwitchToEditor,
|
||||
commit.CommitWipWithPrefix,
|
||||
commit.CommitWithFallthroughPrefix,
|
||||
commit.CommitWithGlobalPrefix,
|
||||
commit.CommitWithNonMatchingBranchName,
|
||||
commit.CommitWithPrefix,
|
||||
commit.CopyAuthorToClipboard,
|
||||
commit.CopyMessageBodyToClipboard,
|
||||
commit.CopyTagToClipboard,
|
||||
commit.CreateAmendCommit,
|
||||
commit.CreateFixupCommitInBranchStack,
|
||||
commit.CreateTag,
|
||||
commit.DisableCopyCommitMessageBody,
|
||||
commit.DiscardOldFileChanges,
|
||||
commit.FindBaseCommitForFixup,
|
||||
commit.FindBaseCommitForFixupDisregardMainBranch,
|
||||
@@ -137,6 +140,7 @@ var tests = []*components.IntegrationTest{
|
||||
custom_commands.AccessCommitProperties,
|
||||
custom_commands.BasicCommand,
|
||||
custom_commands.CheckForConflicts,
|
||||
custom_commands.CustomCommandsSubmenu,
|
||||
custom_commands.FormPrompts,
|
||||
custom_commands.GlobalContext,
|
||||
custom_commands.MenuFromCommand,
|
||||
@@ -164,6 +168,7 @@ var tests = []*components.IntegrationTest{
|
||||
demo.StageLines,
|
||||
demo.Undo,
|
||||
demo.WorktreeCreateFromBranches,
|
||||
diff.CopyToClipboard,
|
||||
diff.Diff,
|
||||
diff.DiffAndApplyPatch,
|
||||
diff.DiffCommits,
|
||||
@@ -367,7 +372,6 @@ var tests = []*components.IntegrationTest{
|
||||
tag.Reset,
|
||||
ui.Accordion,
|
||||
ui.DisableSwitchTabWithPanelJumpKeys,
|
||||
ui.DoublePopup,
|
||||
ui.EmptyMenu,
|
||||
ui.KeybindingSuggestionsWhenSwitchingRepos,
|
||||
ui.ModeSpecificKeybindingSuggestions,
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
. "github.com/jesseduffield/lazygit/pkg/integration/components"
|
||||
)
|
||||
|
||||
var DoublePopup = NewIntegrationTest(NewIntegrationTestArgs{
|
||||
Description: "Open a popup from within another popup and assert you can escape back to the side panels",
|
||||
ExtraCmdArgs: []string{},
|
||||
Skip: false,
|
||||
SetupConfig: func(config *config.AppConfig) {},
|
||||
SetupRepo: func(shell *Shell) {
|
||||
shell.EmptyCommit("one")
|
||||
},
|
||||
Run: func(t *TestDriver, keys config.KeybindingConfig) {
|
||||
t.Views().Branches().
|
||||
Focus().
|
||||
// arbitrarily bringing up a popup
|
||||
PressPrimaryAction()
|
||||
|
||||
t.ExpectPopup().Alert().
|
||||
Title(Contains("Error")).
|
||||
Content(Contains("You have already checked out this branch"))
|
||||
|
||||
t.GlobalPress(keys.Universal.OpenRecentRepos)
|
||||
|
||||
t.ExpectPopup().Menu().Title(Contains("Recent repositories")).Cancel()
|
||||
|
||||
t.Views().Branches().IsFocused()
|
||||
|
||||
t.Views().Files().Focus()
|
||||
},
|
||||
})
|
||||
+72
-11
@@ -7,41 +7,87 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/jesseduffield/lazycore/pkg/utils"
|
||||
"github.com/jesseduffield/lazygit/pkg/config"
|
||||
"github.com/karimkhaleel/jsonschema"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func GetSchemaDir() string {
|
||||
return utils.GetLazyRootDirectory() + "/schema"
|
||||
}
|
||||
|
||||
func GenerateSchema() {
|
||||
func GenerateSchema() *jsonschema.Schema {
|
||||
schema := customReflect(&config.UserConfig{})
|
||||
obj, _ := json.MarshalIndent(schema, "", " ")
|
||||
obj = append(obj, '\n')
|
||||
|
||||
if err := os.WriteFile(GetSchemaDir()+"/config.json", obj, 0o644); err != nil {
|
||||
fmt.Println("Error writing to file:", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
return schema
|
||||
}
|
||||
|
||||
func getSubSchema(rootSchema, parentSchema *jsonschema.Schema, key string) *jsonschema.Schema {
|
||||
subSchema, found := parentSchema.Properties.Get(key)
|
||||
if !found {
|
||||
panic(fmt.Sprintf("Failed to find subSchema at %s on parent", key))
|
||||
}
|
||||
|
||||
// This means the schema is defined on the rootSchema's Definitions
|
||||
if subSchema.Ref != "" {
|
||||
key, _ = strings.CutPrefix(subSchema.Ref, "#/$defs/")
|
||||
refSchema, ok := rootSchema.Definitions[key]
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("Failed to find #/$defs/%s", key))
|
||||
}
|
||||
refSchema.Description = subSchema.Description
|
||||
return refSchema
|
||||
}
|
||||
|
||||
return subSchema
|
||||
}
|
||||
|
||||
func customReflect(v *config.UserConfig) *jsonschema.Schema {
|
||||
defaultConfig := config.GetDefaultConfig()
|
||||
r := &jsonschema.Reflector{FieldNameTag: "yaml", RequiredFromJSONSchemaTags: true, DoNotReference: true}
|
||||
r := &jsonschema.Reflector{FieldNameTag: "yaml", RequiredFromJSONSchemaTags: true}
|
||||
if err := r.AddGoComments("github.com/jesseduffield/lazygit/pkg/config", "../config"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
filterOutDevComments(r)
|
||||
schema := r.Reflect(v)
|
||||
defaultConfig := config.GetDefaultConfig()
|
||||
userConfigSchema := schema.Definitions["UserConfig"]
|
||||
|
||||
setDefaultVals(defaultConfig, schema)
|
||||
defaultValue := reflect.ValueOf(defaultConfig).Elem()
|
||||
|
||||
yamlToFieldNames := lo.Invert(userConfigSchema.OriginalPropertiesMapping)
|
||||
|
||||
for pair := userConfigSchema.Properties.Oldest(); pair != nil; pair = pair.Next() {
|
||||
yamlName := pair.Key
|
||||
fieldName := yamlToFieldNames[yamlName]
|
||||
|
||||
subSchema := getSubSchema(schema, userConfigSchema, yamlName)
|
||||
|
||||
setDefaultVals(schema, subSchema, defaultValue.FieldByName(fieldName).Interface())
|
||||
}
|
||||
|
||||
return schema
|
||||
}
|
||||
|
||||
func setDefaultVals(defaults any, schema *jsonschema.Schema) {
|
||||
func filterOutDevComments(r *jsonschema.Reflector) {
|
||||
for k, v := range r.CommentMap {
|
||||
commentLines := strings.Split(v, "\n")
|
||||
filteredCommentLines := lo.Filter(commentLines, func(line string, _ int) bool {
|
||||
return !strings.Contains(line, "[dev]")
|
||||
})
|
||||
r.CommentMap[k] = strings.Join(filteredCommentLines, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func setDefaultVals(rootSchema, schema *jsonschema.Schema, defaults any) {
|
||||
t := reflect.TypeOf(defaults)
|
||||
v := reflect.ValueOf(defaults)
|
||||
|
||||
@@ -50,6 +96,24 @@ func setDefaultVals(defaults any, schema *jsonschema.Schema) {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
k := t.Kind()
|
||||
_ = k
|
||||
|
||||
switch t.Kind() {
|
||||
case reflect.Bool:
|
||||
schema.Default = v.Bool()
|
||||
case reflect.Int:
|
||||
schema.Default = v.Int()
|
||||
case reflect.String:
|
||||
schema.Default = v.String()
|
||||
default:
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
if t.Kind() != reflect.Struct {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
value := v.Field(i).Interface()
|
||||
parentKey := t.Field(i).Name
|
||||
@@ -59,13 +123,10 @@ func setDefaultVals(defaults any, schema *jsonschema.Schema) {
|
||||
continue
|
||||
}
|
||||
|
||||
subSchema, ok := schema.Properties.Get(key)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
subSchema := getSubSchema(rootSchema, schema, key)
|
||||
|
||||
if isStruct(value) {
|
||||
setDefaultVals(value, subSchema)
|
||||
setDefaultVals(rootSchema, subSchema, value)
|
||||
} else if !isZeroValue(value) {
|
||||
subSchema.Default = value
|
||||
}
|
||||
|
||||
@@ -2,14 +2,13 @@ package jsonschema
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/iancoleman/orderedmap"
|
||||
"github.com/jesseduffield/lazycore/pkg/utils"
|
||||
"github.com/karimkhaleel/jsonschema"
|
||||
"github.com/samber/lo"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -106,16 +105,7 @@ func (n *Node) MarshalYAML() (interface{}, error) {
|
||||
setComment(&keyNode, n.Description)
|
||||
}
|
||||
|
||||
if n.Default != nil {
|
||||
valueNode := yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
}
|
||||
err := valueNode.Encode(n.Default)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node.Content = append(node.Content, &keyNode, &valueNode)
|
||||
} else if len(n.Children) > 0 {
|
||||
if len(n.Children) > 0 {
|
||||
childrenNode := yaml.Node{
|
||||
Kind: yaml.MappingNode,
|
||||
}
|
||||
@@ -136,62 +126,20 @@ func (n *Node) MarshalYAML() (interface{}, error) {
|
||||
childrenNode.Content = append(childrenNode.Content, childYaml.(*yaml.Node).Content...)
|
||||
}
|
||||
node.Content = append(node.Content, &keyNode, &childrenNode)
|
||||
} else {
|
||||
valueNode := yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
}
|
||||
err := valueNode.Encode(n.Default)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node.Content = append(node.Content, &keyNode, &valueNode)
|
||||
}
|
||||
|
||||
return &node, nil
|
||||
}
|
||||
|
||||
func getDescription(v *orderedmap.OrderedMap) string {
|
||||
description, ok := v.Get("description")
|
||||
if !ok {
|
||||
description = ""
|
||||
}
|
||||
return description.(string)
|
||||
}
|
||||
|
||||
func getDefault(v *orderedmap.OrderedMap) (error, any) {
|
||||
defaultValue, ok := v.Get("default")
|
||||
if ok {
|
||||
return nil, defaultValue
|
||||
}
|
||||
|
||||
dataType, ok := v.Get("type")
|
||||
if ok {
|
||||
dataTypeString := dataType.(string)
|
||||
if dataTypeString == "string" {
|
||||
return nil, ""
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("Failed to get default value"), nil
|
||||
}
|
||||
|
||||
func parseNode(parent *Node, name string, value *orderedmap.OrderedMap) {
|
||||
description := getDescription(value)
|
||||
err, defaultValue := getDefault(value)
|
||||
if err == nil {
|
||||
leaf := &Node{Name: name, Description: description, Default: defaultValue}
|
||||
parent.Children = append(parent.Children, leaf)
|
||||
}
|
||||
|
||||
properties, ok := value.Get("properties")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
orderedProperties := properties.(orderedmap.OrderedMap)
|
||||
|
||||
node := &Node{Name: name, Description: description}
|
||||
parent.Children = append(parent.Children, node)
|
||||
|
||||
keys := orderedProperties.Keys()
|
||||
for _, name := range keys {
|
||||
value, _ := orderedProperties.Get(name)
|
||||
typedValue := value.(orderedmap.OrderedMap)
|
||||
parseNode(node, name, &typedValue)
|
||||
}
|
||||
}
|
||||
|
||||
func writeToConfigDocs(config []byte) error {
|
||||
configPath := utils.GetLazyRootDirectory() + "/docs/Config.md"
|
||||
markdown, err := os.ReadFile(configPath)
|
||||
@@ -222,31 +170,12 @@ func writeToConfigDocs(config []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateConfigDocs() {
|
||||
content, err := os.ReadFile(GetSchemaDir() + "/config.json")
|
||||
if err != nil {
|
||||
panic("Error reading config.json")
|
||||
func GenerateConfigDocs(schema *jsonschema.Schema) {
|
||||
rootNode := &Node{
|
||||
Children: make([]*Node, 0),
|
||||
}
|
||||
|
||||
schema := orderedmap.New()
|
||||
|
||||
err = json.Unmarshal(content, &schema)
|
||||
if err != nil {
|
||||
panic("Failed to unmarshal config.json")
|
||||
}
|
||||
|
||||
root, ok := schema.Get("properties")
|
||||
if !ok {
|
||||
panic("properties key not found in schema")
|
||||
}
|
||||
orderedRoot := root.(orderedmap.OrderedMap)
|
||||
|
||||
rootNode := Node{}
|
||||
for _, name := range orderedRoot.Keys() {
|
||||
value, _ := orderedRoot.Get(name)
|
||||
typedValue := value.(orderedmap.OrderedMap)
|
||||
parseNode(&rootNode, name, &typedValue)
|
||||
}
|
||||
recurseOverSchema(schema, schema.Definitions["UserConfig"], rootNode)
|
||||
|
||||
var buffer bytes.Buffer
|
||||
encoder := yaml.NewEncoder(&buffer)
|
||||
@@ -262,8 +191,51 @@ func GenerateConfigDocs() {
|
||||
|
||||
config := prepareMarshalledConfig(buffer)
|
||||
|
||||
err = writeToConfigDocs(config)
|
||||
err := writeToConfigDocs(config)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func recurseOverSchema(rootSchema, schema *jsonschema.Schema, parent *Node) {
|
||||
if schema == nil || schema.Properties == nil || schema.Properties.Len() == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for pair := schema.Properties.Oldest(); pair != nil; pair = pair.Next() {
|
||||
subSchema := getSubSchema(rootSchema, schema, pair.Key)
|
||||
|
||||
// Skip empty objects
|
||||
if subSchema.Type == "object" && subSchema.Properties == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip empty arrays
|
||||
if isZeroValue(subSchema.Default) && subSchema.Type == "array" {
|
||||
continue
|
||||
}
|
||||
|
||||
node := Node{
|
||||
Name: pair.Key,
|
||||
Description: subSchema.Description,
|
||||
Default: getZeroValue(subSchema.Default, subSchema.Type),
|
||||
}
|
||||
parent.Children = append(parent.Children, &node)
|
||||
recurseOverSchema(rootSchema, subSchema, &node)
|
||||
}
|
||||
}
|
||||
|
||||
func getZeroValue(val any, t string) any {
|
||||
if !isZeroValue(val) {
|
||||
return val
|
||||
}
|
||||
|
||||
switch t {
|
||||
case "string":
|
||||
return ""
|
||||
case "boolean":
|
||||
return false
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,6 @@ import (
|
||||
|
||||
func main() {
|
||||
fmt.Printf("Generating jsonschema in %s...\n", jsonschema.GetSchemaDir())
|
||||
jsonschema.GenerateSchema()
|
||||
jsonschema.GenerateConfigDocs()
|
||||
schema := jsonschema.GenerateSchema()
|
||||
jsonschema.GenerateConfigDocs(schema)
|
||||
}
|
||||
|
||||
+7
-3
@@ -109,7 +109,7 @@ func ScanLinesAndTruncateWhenLongerThanBuffer(maxBufferSize int) func(data []byt
|
||||
// - the line indices of the original lines, indexed by the wrapped line indices
|
||||
// If wrap is false, the text is returned as is.
|
||||
// This code needs to behave the same as `gocui.lineWrap` does.
|
||||
func WrapViewLinesToWidth(wrap bool, editable bool, text string, width int) ([]string, []int, []int) {
|
||||
func WrapViewLinesToWidth(wrap bool, editable bool, text string, width int, tabWidth int) ([]string, []int, []int) {
|
||||
if !editable {
|
||||
text = strings.TrimSuffix(text, "\n")
|
||||
}
|
||||
@@ -126,14 +126,18 @@ func WrapViewLinesToWidth(wrap bool, editable bool, text string, width int) ([]s
|
||||
wrappedLineIndices := make([]int, 0, len(lines))
|
||||
originalLineIndices := make([]int, 0, len(lines))
|
||||
|
||||
if tabWidth < 1 {
|
||||
tabWidth = 4
|
||||
}
|
||||
|
||||
for originalLineIdx, line := range lines {
|
||||
wrappedLineIndices = append(wrappedLineIndices, len(wrappedLines))
|
||||
|
||||
// convert tabs to spaces
|
||||
for i := 0; i < len(line); i++ {
|
||||
if line[i] == '\t' {
|
||||
numSpaces := 4 - (i % 4)
|
||||
line = line[:i] + " "[:numSpaces] + line[i+1:]
|
||||
numSpaces := tabWidth - (i % tabWidth)
|
||||
line = line[:i] + strings.Repeat(" ", numSpaces) + line[i+1:]
|
||||
i += numSpaces - 1
|
||||
}
|
||||
}
|
||||
|
||||
+22
-5
@@ -173,6 +173,7 @@ func TestWrapViewLinesToWidth(t *testing.T) {
|
||||
editable bool
|
||||
text string
|
||||
width int
|
||||
tabWidth int
|
||||
expectedWrappedLines []string
|
||||
expectedWrappedLinesIndices []int
|
||||
expectedOriginalLinesIndices []int
|
||||
@@ -353,14 +354,25 @@ func TestWrapViewLinesToWidth(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Tabs",
|
||||
wrap: true,
|
||||
text: "\ta\tbb\tccc\tdddd\teeeee",
|
||||
width: 50,
|
||||
name: "Tabs, width 4",
|
||||
wrap: true,
|
||||
text: "\ta\tbb\tccc\tdddd\teeeee",
|
||||
width: 50,
|
||||
tabWidth: 4,
|
||||
expectedWrappedLines: []string{
|
||||
" a bb ccc dddd eeeee",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Tabs, width 8",
|
||||
wrap: true,
|
||||
text: "\ta\tbb\tccc\tdddddddd\teeeee",
|
||||
width: 100,
|
||||
tabWidth: 8,
|
||||
expectedWrappedLines: []string{
|
||||
" a bb ccc dddddddd eeeee",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Multiple lines",
|
||||
wrap: true,
|
||||
@@ -425,7 +437,11 @@ func TestWrapViewLinesToWidth(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
wrappedLines, wrappedLinesIndices, originalLinesIndices := WrapViewLinesToWidth(tt.wrap, tt.editable, tt.text, tt.width)
|
||||
tabWidth := tt.tabWidth
|
||||
if tabWidth == 0 {
|
||||
tabWidth = 4
|
||||
}
|
||||
wrappedLines, wrappedLinesIndices, originalLinesIndices := WrapViewLinesToWidth(tt.wrap, tt.editable, tt.text, tt.width, tabWidth)
|
||||
assert.Equal(t, tt.expectedWrappedLines, wrappedLines)
|
||||
if tt.expectedWrappedLinesIndices != nil {
|
||||
assert.Equal(t, tt.expectedWrappedLinesIndices, wrappedLinesIndices)
|
||||
@@ -436,6 +452,7 @@ func TestWrapViewLinesToWidth(t *testing.T) {
|
||||
|
||||
// As a sanity check, also test that gocui's line wrapping behaves the same way
|
||||
view := gocui.NewView("", 0, 0, tt.width+1, 1000, gocui.OutputNormal)
|
||||
view.TabWidth = tabWidth
|
||||
assert.Equal(t, tt.width, view.InnerWidth())
|
||||
view.Wrap = tt.wrap
|
||||
view.Editable = tt.editable
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package yaml_utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
@@ -34,7 +35,7 @@ func UpdateYamlValue(yamlBytes []byte, path []string, value string) ([]byte, err
|
||||
}
|
||||
|
||||
// Convert the updated YAML node back to YAML bytes.
|
||||
updatedYAMLBytes, err := yaml.Marshal(body)
|
||||
updatedYAMLBytes, err := YamlMarshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert YAML node to bytes: %w", err)
|
||||
}
|
||||
@@ -99,98 +100,101 @@ func lookupKey(node *yaml.Node, key string) (*yaml.Node, *yaml.Node) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// takes a yaml document in bytes, a path to a key, and a new name for the key.
|
||||
// Will rename the key to the new name if it exists, and do nothing otherwise.
|
||||
func RenameYamlKey(yamlBytes []byte, path []string, newKey string) ([]byte, error) {
|
||||
// Parse the YAML file.
|
||||
var node yaml.Node
|
||||
err := yaml.Unmarshal(yamlBytes, &node)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse YAML: %w", err)
|
||||
}
|
||||
|
||||
// Walks a yaml document from the root node to the specified path, and then applies the transformation to that node.
|
||||
// If the requested path is not defined in the document, no changes are made to the document.
|
||||
func TransformNode(rootNode *yaml.Node, path []string, transform func(node *yaml.Node) error) error {
|
||||
// Empty document: nothing to do.
|
||||
if len(node.Content) == 0 {
|
||||
return yamlBytes, nil
|
||||
if len(rootNode.Content) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
body := node.Content[0]
|
||||
body := rootNode.Content[0]
|
||||
|
||||
if didRename, err := renameYamlKey(body, path, newKey); err != nil || !didRename {
|
||||
return yamlBytes, err
|
||||
if err := transformNode(body, path, transform); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Convert the updated YAML node back to YAML bytes.
|
||||
updatedYAMLBytes, err := yaml.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert YAML node to bytes: %w", err)
|
||||
}
|
||||
|
||||
return updatedYAMLBytes, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recursive function to rename the YAML key.
|
||||
func renameYamlKey(node *yaml.Node, path []string, newKey string) (bool, error) {
|
||||
if node.Kind != yaml.MappingNode {
|
||||
return false, errors.New("yaml node in path is not a dictionary")
|
||||
// A recursive function to walk down the tree. See TransformNode for more details.
|
||||
func transformNode(node *yaml.Node, path []string, transform func(node *yaml.Node) error) error {
|
||||
if len(path) == 0 {
|
||||
return transform(node)
|
||||
}
|
||||
|
||||
keyNode, valueNode := lookupKey(node, path[0])
|
||||
if keyNode == nil {
|
||||
return false, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
return transformNode(valueNode, path[1:], transform)
|
||||
}
|
||||
|
||||
// Takes the root node of a yaml document, a path to a key, and a new name for the key.
|
||||
// Will rename the key to the new name if it exists, and do nothing otherwise.
|
||||
func RenameYamlKey(rootNode *yaml.Node, path []string, newKey string) error {
|
||||
// Empty document: nothing to do.
|
||||
if len(rootNode.Content) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
body := rootNode.Content[0]
|
||||
|
||||
if err := renameYamlKey(body, path, newKey); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recursive function to rename the YAML key.
|
||||
func renameYamlKey(node *yaml.Node, path []string, newKey string) error {
|
||||
if node.Kind != yaml.MappingNode {
|
||||
return errors.New("yaml node in path is not a dictionary")
|
||||
}
|
||||
|
||||
keyNode, valueNode := lookupKey(node, path[0])
|
||||
if keyNode == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// end of path reached: rename key
|
||||
if len(path) == 1 {
|
||||
// Check that new key doesn't exist yet
|
||||
if newKeyNode, _ := lookupKey(node, newKey); newKeyNode != nil {
|
||||
return false, fmt.Errorf("new key `%s' already exists", newKey)
|
||||
return fmt.Errorf("new key `%s' already exists", newKey)
|
||||
}
|
||||
|
||||
keyNode.Value = newKey
|
||||
return true, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
return renameYamlKey(valueNode, path[1:], newKey)
|
||||
}
|
||||
|
||||
// Traverses a yaml document, calling the callback function for each node. The
|
||||
// callback is allowed to modify the node in place, in which case it should
|
||||
// return true. The function returns the original yaml document if none of the
|
||||
// callbacks returned true, and the modified document otherwise.
|
||||
func Walk(yamlBytes []byte, callback func(node *yaml.Node, path string) bool) ([]byte, error) {
|
||||
// Parse the YAML file.
|
||||
var node yaml.Node
|
||||
err := yaml.Unmarshal(yamlBytes, &node)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse YAML: %w", err)
|
||||
}
|
||||
|
||||
// callback is expected to modify the node in place
|
||||
func Walk(rootNode *yaml.Node, callback func(node *yaml.Node, path string)) error {
|
||||
// Empty document: nothing to do.
|
||||
if len(node.Content) == 0 {
|
||||
return yamlBytes, nil
|
||||
if len(rootNode.Content) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
body := node.Content[0]
|
||||
body := rootNode.Content[0]
|
||||
|
||||
if didChange, err := walk(body, "", callback); err != nil || !didChange {
|
||||
return yamlBytes, err
|
||||
if err := walk(body, "", callback); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Convert the updated YAML node back to YAML bytes.
|
||||
updatedYAMLBytes, err := yaml.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert YAML node to bytes: %w", err)
|
||||
}
|
||||
|
||||
return updatedYAMLBytes, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func walk(node *yaml.Node, path string, callback func(*yaml.Node, string) bool) (bool, error) {
|
||||
didChange := callback(node, path)
|
||||
func walk(node *yaml.Node, path string, callback func(*yaml.Node, string)) error {
|
||||
callback(node, path)
|
||||
switch node.Kind {
|
||||
case yaml.DocumentNode:
|
||||
return false, errors.New("Unexpected document node in the middle of a yaml tree")
|
||||
return errors.New("Unexpected document node in the middle of a yaml tree")
|
||||
case yaml.MappingNode:
|
||||
for i := 0; i < len(node.Content); i += 2 {
|
||||
name := node.Content[i].Value
|
||||
@@ -201,26 +205,33 @@ func walk(node *yaml.Node, path string, callback func(*yaml.Node, string) bool)
|
||||
} else {
|
||||
childPath = fmt.Sprintf("%s.%s", path, name)
|
||||
}
|
||||
didChangeChild, err := walk(childNode, childPath, callback)
|
||||
err := walk(childNode, childPath, callback)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
didChange = didChange || didChangeChild
|
||||
}
|
||||
case yaml.SequenceNode:
|
||||
for i := 0; i < len(node.Content); i++ {
|
||||
childPath := fmt.Sprintf("%s[%d]", path, i)
|
||||
didChangeChild, err := walk(node.Content[i], childPath, callback)
|
||||
err := walk(node.Content[i], childPath, callback)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
didChange = didChange || didChangeChild
|
||||
}
|
||||
case yaml.ScalarNode:
|
||||
// nothing to do
|
||||
case yaml.AliasNode:
|
||||
return false, errors.New("Alias nodes are not supported")
|
||||
return errors.New("Alias nodes are not supported")
|
||||
}
|
||||
|
||||
return didChange, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func YamlMarshal(node *yaml.Node) ([]byte, error) {
|
||||
var buffer bytes.Buffer
|
||||
encoder := yaml.NewEncoder(&buffer)
|
||||
encoder.SetIndent(2)
|
||||
|
||||
err := encoder.Encode(node)
|
||||
return buffer.Bytes(), err
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package yaml_utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -49,12 +50,11 @@ func TestUpdateYamlValue(t *testing.T) {
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
name: "nested update",
|
||||
in: "foo:\n bar: baz\n",
|
||||
path: []string{"foo", "bar"},
|
||||
value: "qux",
|
||||
// indentation is not preserved. See https://github.com/go-yaml/yaml/issues/899
|
||||
expectedOut: "foo:\n bar: qux\n",
|
||||
name: "nested update",
|
||||
in: "foo:\n bar: baz\n",
|
||||
path: []string{"foo", "bar"},
|
||||
value: "qux",
|
||||
expectedOut: "foo:\n bar: qux\n",
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
@@ -62,7 +62,7 @@ func TestUpdateYamlValue(t *testing.T) {
|
||||
in: "",
|
||||
path: []string{"foo", "bar", "baz"},
|
||||
value: "qux",
|
||||
expectedOut: "foo:\n bar:\n baz: qux\n",
|
||||
expectedOut: "foo:\n bar:\n baz: qux\n",
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
@@ -133,21 +133,19 @@ func TestRenameYamlKey(t *testing.T) {
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
name: "rename key, nested",
|
||||
in: "foo:\n bar: 5\n",
|
||||
path: []string{"foo", "bar"},
|
||||
newKey: "baz",
|
||||
// indentation is not preserved. See https://github.com/go-yaml/yaml/issues/899
|
||||
expectedOut: "foo:\n baz: 5\n",
|
||||
name: "rename key, nested",
|
||||
in: "foo:\n bar: 5\n",
|
||||
path: []string{"foo", "bar"},
|
||||
newKey: "baz",
|
||||
expectedOut: "foo:\n baz: 5\n",
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
name: "rename non-scalar key",
|
||||
in: "foo:\n bar: 5\n",
|
||||
path: []string{"foo"},
|
||||
newKey: "qux",
|
||||
// indentation is not preserved. See https://github.com/go-yaml/yaml/issues/899
|
||||
expectedOut: "qux:\n bar: 5\n",
|
||||
name: "rename non-scalar key",
|
||||
in: "foo:\n bar: 5\n",
|
||||
path: []string{"foo"},
|
||||
newKey: "qux",
|
||||
expectedOut: "qux:\n bar: 5\n",
|
||||
expectedErr: "",
|
||||
},
|
||||
{
|
||||
@@ -188,14 +186,16 @@ func TestRenameYamlKey(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
out, actualErr := RenameYamlKey([]byte(test.in), test.path, test.newKey)
|
||||
node := unmarshalForTest(t, test.in)
|
||||
actualErr := RenameYamlKey(&node, test.path, test.newKey)
|
||||
if test.expectedErr == "" {
|
||||
assert.NoError(t, actualErr)
|
||||
} else {
|
||||
assert.EqualError(t, actualErr, test.expectedErr)
|
||||
}
|
||||
out := marshalForTest(t, &node)
|
||||
|
||||
assert.Equal(t, test.expectedOut, string(out))
|
||||
assert.Equal(t, test.expectedOut, out)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -240,10 +240,10 @@ func TestWalk_paths(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
node := unmarshalForTest(t, test.document)
|
||||
paths := []string{}
|
||||
_, err := Walk([]byte(test.document), func(node *yaml.Node, path string) bool {
|
||||
err := Walk(&node, func(node *yaml.Node, path string) {
|
||||
paths = append(paths, path)
|
||||
return true
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
@@ -256,61 +256,154 @@ func TestWalk_inPlaceChanges(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
callback func(node *yaml.Node, path string) bool
|
||||
callback func(node *yaml.Node, path string)
|
||||
expectedOut string
|
||||
}{
|
||||
{
|
||||
name: "no change",
|
||||
in: "x: 5",
|
||||
callback: func(node *yaml.Node, path string) bool { return false },
|
||||
expectedOut: "x: 5",
|
||||
name: "no change",
|
||||
in: "x: 5",
|
||||
callback: func(node *yaml.Node, path string) {},
|
||||
},
|
||||
{
|
||||
name: "change value",
|
||||
in: "x: 5\ny: 3",
|
||||
callback: func(node *yaml.Node, path string) bool {
|
||||
callback: func(node *yaml.Node, path string) {
|
||||
if path == "x" {
|
||||
node.Value = "7"
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
expectedOut: "x: 7\ny: 3\n",
|
||||
},
|
||||
{
|
||||
name: "change nested value",
|
||||
in: "x:\n y: 5",
|
||||
callback: func(node *yaml.Node, path string) bool {
|
||||
callback: func(node *yaml.Node, path string) {
|
||||
if path == "x.y" {
|
||||
node.Value = "7"
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
// indentation is not preserved. See https://github.com/go-yaml/yaml/issues/899
|
||||
expectedOut: "x:\n y: 7\n",
|
||||
expectedOut: "x:\n y: 7\n",
|
||||
},
|
||||
{
|
||||
name: "change array value",
|
||||
in: "x:\n - y: 5",
|
||||
callback: func(node *yaml.Node, path string) bool {
|
||||
callback: func(node *yaml.Node, path string) {
|
||||
if path == "x[0].y" {
|
||||
node.Value = "7"
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
// indentation is not preserved. See https://github.com/go-yaml/yaml/issues/899
|
||||
expectedOut: "x:\n - y: 7\n",
|
||||
expectedOut: "x:\n - y: 7\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
result, err := Walk([]byte(test.in), test.callback)
|
||||
|
||||
node := unmarshalForTest(t, test.in)
|
||||
err := Walk(&node, test.callback)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, test.expectedOut, string(result))
|
||||
if test.expectedOut == "" {
|
||||
unmodifiedOriginal := unmarshalForTest(t, test.in)
|
||||
assert.Equal(t, unmodifiedOriginal, node)
|
||||
} else {
|
||||
result := marshalForTest(t, &node)
|
||||
assert.Equal(t, test.expectedOut, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransformNode(t *testing.T) {
|
||||
transformIntValueToString := func(node *yaml.Node) error {
|
||||
if node.Kind == yaml.ScalarNode {
|
||||
if node.ShortTag() == "!!int" {
|
||||
node.Tag = "!!str"
|
||||
return nil
|
||||
} else if node.ShortTag() == "!!str" {
|
||||
// We have already transformed it,
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("Node was of bad type")
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("Node was not a scalar")
|
||||
}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
path []string
|
||||
transform func(node *yaml.Node) error
|
||||
expectedOut string
|
||||
}{
|
||||
{
|
||||
name: "Path not present",
|
||||
in: "foo: 1",
|
||||
path: []string{"bar"},
|
||||
transform: transformIntValueToString,
|
||||
},
|
||||
{
|
||||
name: "Part of path present",
|
||||
in: `
|
||||
foo:
|
||||
bar: 2`,
|
||||
path: []string{"foo", "baz"},
|
||||
transform: transformIntValueToString,
|
||||
},
|
||||
{
|
||||
name: "Successfully Transforms to string",
|
||||
in: `
|
||||
foo:
|
||||
bar: 2`,
|
||||
path: []string{"foo", "bar"},
|
||||
transform: transformIntValueToString,
|
||||
expectedOut: `foo:
|
||||
bar: "2"
|
||||
`, // Note the trailing newline changes because of how it re-marshalls
|
||||
},
|
||||
{
|
||||
name: "Does nothing when already transformed",
|
||||
in: `
|
||||
foo:
|
||||
bar: "2"`,
|
||||
path: []string{"foo", "bar"},
|
||||
transform: transformIntValueToString,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
node := unmarshalForTest(t, test.in)
|
||||
err := TransformNode(&node, test.path, test.transform)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.expectedOut == "" {
|
||||
unmodifiedOriginal := unmarshalForTest(t, test.in)
|
||||
assert.Equal(t, unmodifiedOriginal, node)
|
||||
} else {
|
||||
result := marshalForTest(t, &node)
|
||||
assert.Equal(t, test.expectedOut, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func unmarshalForTest(t *testing.T, input string) yaml.Node {
|
||||
t.Helper()
|
||||
var node yaml.Node
|
||||
err := yaml.Unmarshal([]byte(input), &node)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
func marshalForTest(t *testing.T, node *yaml.Node) string {
|
||||
t.Helper()
|
||||
result, err := YamlMarshal(node)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
+1430
-1317
File diff suppressed because it is too large
Load Diff
-21
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 Ian Coleman
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, Subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or Substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
-266
@@ -1,266 +0,0 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type Pair struct {
|
||||
key string
|
||||
value interface{}
|
||||
}
|
||||
|
||||
func (kv *Pair) Key() string {
|
||||
return kv.key
|
||||
}
|
||||
|
||||
func (kv *Pair) Value() interface{} {
|
||||
return kv.value
|
||||
}
|
||||
|
||||
type ByPair struct {
|
||||
Pairs []*Pair
|
||||
LessFunc func(a *Pair, j *Pair) bool
|
||||
}
|
||||
|
||||
func (a ByPair) Len() int { return len(a.Pairs) }
|
||||
func (a ByPair) Swap(i, j int) { a.Pairs[i], a.Pairs[j] = a.Pairs[j], a.Pairs[i] }
|
||||
func (a ByPair) Less(i, j int) bool { return a.LessFunc(a.Pairs[i], a.Pairs[j]) }
|
||||
|
||||
type OrderedMap struct {
|
||||
keys []string
|
||||
values map[string]interface{}
|
||||
escapeHTML bool
|
||||
}
|
||||
|
||||
func New() *OrderedMap {
|
||||
o := OrderedMap{}
|
||||
o.keys = []string{}
|
||||
o.values = map[string]interface{}{}
|
||||
o.escapeHTML = true
|
||||
return &o
|
||||
}
|
||||
|
||||
func (o *OrderedMap) SetEscapeHTML(on bool) {
|
||||
o.escapeHTML = on
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Get(key string) (interface{}, bool) {
|
||||
val, exists := o.values[key]
|
||||
return val, exists
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Set(key string, value interface{}) {
|
||||
_, exists := o.values[key]
|
||||
if !exists {
|
||||
o.keys = append(o.keys, key)
|
||||
}
|
||||
o.values[key] = value
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Delete(key string) {
|
||||
// check key is in use
|
||||
_, ok := o.values[key]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// remove from keys
|
||||
for i, k := range o.keys {
|
||||
if k == key {
|
||||
o.keys = append(o.keys[:i], o.keys[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
// remove from values
|
||||
delete(o.values, key)
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Keys() []string {
|
||||
return o.keys
|
||||
}
|
||||
|
||||
func (o *OrderedMap) Values() map[string]interface{} {
|
||||
return o.values
|
||||
}
|
||||
|
||||
// SortKeys Sort the map keys using your sort func
|
||||
func (o *OrderedMap) SortKeys(sortFunc func(keys []string)) {
|
||||
sortFunc(o.keys)
|
||||
}
|
||||
|
||||
// Sort Sort the map using your sort func
|
||||
func (o *OrderedMap) Sort(lessFunc func(a *Pair, b *Pair) bool) {
|
||||
pairs := make([]*Pair, len(o.keys))
|
||||
for i, key := range o.keys {
|
||||
pairs[i] = &Pair{key, o.values[key]}
|
||||
}
|
||||
|
||||
sort.Sort(ByPair{pairs, lessFunc})
|
||||
|
||||
for i, pair := range pairs {
|
||||
o.keys[i] = pair.key
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OrderedMap) UnmarshalJSON(b []byte) error {
|
||||
if o.values == nil {
|
||||
o.values = map[string]interface{}{}
|
||||
}
|
||||
err := json.Unmarshal(b, &o.values)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
if _, err = dec.Token(); err != nil { // skip '{'
|
||||
return err
|
||||
}
|
||||
o.keys = make([]string, 0, len(o.values))
|
||||
return decodeOrderedMap(dec, o)
|
||||
}
|
||||
|
||||
func decodeOrderedMap(dec *json.Decoder, o *OrderedMap) error {
|
||||
hasKey := make(map[string]bool, len(o.values))
|
||||
for {
|
||||
token, err := dec.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if delim, ok := token.(json.Delim); ok && delim == '}' {
|
||||
return nil
|
||||
}
|
||||
key := token.(string)
|
||||
if hasKey[key] {
|
||||
// duplicate key
|
||||
for j, k := range o.keys {
|
||||
if k == key {
|
||||
copy(o.keys[j:], o.keys[j+1:])
|
||||
break
|
||||
}
|
||||
}
|
||||
o.keys[len(o.keys)-1] = key
|
||||
} else {
|
||||
hasKey[key] = true
|
||||
o.keys = append(o.keys, key)
|
||||
}
|
||||
|
||||
token, err = dec.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if delim, ok := token.(json.Delim); ok {
|
||||
switch delim {
|
||||
case '{':
|
||||
if values, ok := o.values[key].(map[string]interface{}); ok {
|
||||
newMap := OrderedMap{
|
||||
keys: make([]string, 0, len(values)),
|
||||
values: values,
|
||||
escapeHTML: o.escapeHTML,
|
||||
}
|
||||
if err = decodeOrderedMap(dec, &newMap); err != nil {
|
||||
return err
|
||||
}
|
||||
o.values[key] = newMap
|
||||
} else if oldMap, ok := o.values[key].(OrderedMap); ok {
|
||||
newMap := OrderedMap{
|
||||
keys: make([]string, 0, len(oldMap.values)),
|
||||
values: oldMap.values,
|
||||
escapeHTML: o.escapeHTML,
|
||||
}
|
||||
if err = decodeOrderedMap(dec, &newMap); err != nil {
|
||||
return err
|
||||
}
|
||||
o.values[key] = newMap
|
||||
} else if err = decodeOrderedMap(dec, &OrderedMap{}); err != nil {
|
||||
return err
|
||||
}
|
||||
case '[':
|
||||
if values, ok := o.values[key].([]interface{}); ok {
|
||||
if err = decodeSlice(dec, values, o.escapeHTML); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err = decodeSlice(dec, []interface{}{}, o.escapeHTML); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func decodeSlice(dec *json.Decoder, s []interface{}, escapeHTML bool) error {
|
||||
for index := 0; ; index++ {
|
||||
token, err := dec.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if delim, ok := token.(json.Delim); ok {
|
||||
switch delim {
|
||||
case '{':
|
||||
if index < len(s) {
|
||||
if values, ok := s[index].(map[string]interface{}); ok {
|
||||
newMap := OrderedMap{
|
||||
keys: make([]string, 0, len(values)),
|
||||
values: values,
|
||||
escapeHTML: escapeHTML,
|
||||
}
|
||||
if err = decodeOrderedMap(dec, &newMap); err != nil {
|
||||
return err
|
||||
}
|
||||
s[index] = newMap
|
||||
} else if oldMap, ok := s[index].(OrderedMap); ok {
|
||||
newMap := OrderedMap{
|
||||
keys: make([]string, 0, len(oldMap.values)),
|
||||
values: oldMap.values,
|
||||
escapeHTML: escapeHTML,
|
||||
}
|
||||
if err = decodeOrderedMap(dec, &newMap); err != nil {
|
||||
return err
|
||||
}
|
||||
s[index] = newMap
|
||||
} else if err = decodeOrderedMap(dec, &OrderedMap{}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err = decodeOrderedMap(dec, &OrderedMap{}); err != nil {
|
||||
return err
|
||||
}
|
||||
case '[':
|
||||
if index < len(s) {
|
||||
if values, ok := s[index].([]interface{}); ok {
|
||||
if err = decodeSlice(dec, values, escapeHTML); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err = decodeSlice(dec, []interface{}{}, escapeHTML); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err = decodeSlice(dec, []interface{}{}, escapeHTML); err != nil {
|
||||
return err
|
||||
}
|
||||
case ']':
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (o OrderedMap) MarshalJSON() ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
encoder := json.NewEncoder(&buf)
|
||||
encoder.SetEscapeHTML(o.escapeHTML)
|
||||
for i, k := range o.keys {
|
||||
if i > 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
// add key
|
||||
if err := encoder.Encode(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf.WriteByte(':')
|
||||
// add value
|
||||
if err := encoder.Encode(o.values[k]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
# orderedmap
|
||||
|
||||
[](https://travis-ci.com/iancoleman/orderedmap)
|
||||
|
||||
A golang data type equivalent to python's collections.OrderedDict
|
||||
|
||||
Retains order of keys in maps
|
||||
|
||||
Can be JSON serialized / deserialized
|
||||
|
||||
# Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/iancoleman/orderedmap"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
// use New() instead of o := map[string]interface{}{}
|
||||
o := orderedmap.New()
|
||||
|
||||
// use SetEscapeHTML() to whether escape problematic HTML characters or not, defaults is true
|
||||
o.SetEscapeHTML(false)
|
||||
|
||||
// use Set instead of o["a"] = 1
|
||||
o.Set("a", 1)
|
||||
|
||||
// add some value with special characters
|
||||
o.Set("b", "\\.<>[]{}_-")
|
||||
|
||||
// use Get instead of i, ok := o["a"]
|
||||
val, ok := o.Get("a")
|
||||
|
||||
// use Keys instead of for k, v := range o
|
||||
keys := o.Keys()
|
||||
for _, k := range keys {
|
||||
v, _ := o.Get(k)
|
||||
}
|
||||
|
||||
// use o.Delete instead of delete(o, key)
|
||||
o.Delete("a")
|
||||
|
||||
// serialize to a json string using encoding/json
|
||||
bytes, err := json.Marshal(o)
|
||||
prettyBytes, err := json.MarshalIndent(o, "", " ")
|
||||
|
||||
// deserialize a json string using encoding/json
|
||||
// all maps (including nested maps) will be parsed as orderedmaps
|
||||
s := `{"a": 1}`
|
||||
err := json.Unmarshal([]byte(s), &o)
|
||||
|
||||
// sort the keys
|
||||
o.SortKeys(sort.Strings)
|
||||
|
||||
// sort by Pair
|
||||
o.Sort(func(a *orderedmap.Pair, b *orderedmap.Pair) bool {
|
||||
return a.Value().(float64) < b.Value().(float64)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
# Caveats
|
||||
|
||||
* OrderedMap only takes strings for the key, as per [the JSON spec](http://json.org/).
|
||||
|
||||
# Tests
|
||||
|
||||
```
|
||||
go test
|
||||
```
|
||||
|
||||
# Alternatives
|
||||
|
||||
None of the alternatives offer JSON serialization.
|
||||
|
||||
* [cevaris/ordered_map](https://github.com/cevaris/ordered_map)
|
||||
* [mantyr/iterator](https://github.com/mantyr/iterator)
|
||||
+9
-2
@@ -195,6 +195,9 @@ type View struct {
|
||||
// if true, the view will underline hyperlinks only when the cursor is on
|
||||
// them; otherwise, they will always be underlined
|
||||
UnderlineHyperLinksOnlyOnHover bool
|
||||
|
||||
// number of spaces per \t character, defaults to 4
|
||||
TabWidth int
|
||||
}
|
||||
|
||||
type pos struct {
|
||||
@@ -424,6 +427,7 @@ func NewView(name string, x0, y0, x1, y1 int, mode OutputMode) *View {
|
||||
searcher: &searcher{},
|
||||
TextArea: &TextArea{},
|
||||
rangeSelectStartY: -1,
|
||||
TabWidth: 4,
|
||||
}
|
||||
|
||||
v.FgColor, v.BgColor = ColorDefault, ColorDefault
|
||||
@@ -923,9 +927,12 @@ func (v *View) parseInput(ch rune, x int, _ int) (bool, []cell) {
|
||||
return truncateLine, nil
|
||||
} else if ch == '\t' {
|
||||
// fill tab-sized space
|
||||
const tabStop = 4
|
||||
tabWidth := v.TabWidth
|
||||
if tabWidth < 1 {
|
||||
tabWidth = 4
|
||||
}
|
||||
ch = ' '
|
||||
repeatCount = tabStop - (x % tabStop)
|
||||
repeatCount = tabWidth - (x % tabWidth)
|
||||
}
|
||||
c := cell{
|
||||
fgColor: v.ei.curFgColor,
|
||||
|
||||
Vendored
+1
-4
@@ -109,9 +109,6 @@ github.com/gobwas/glob/util/strings
|
||||
# github.com/gookit/color v1.4.2
|
||||
## explicit; go 1.12
|
||||
github.com/gookit/color
|
||||
# github.com/iancoleman/orderedmap v0.3.0
|
||||
## explicit; go 1.16
|
||||
github.com/iancoleman/orderedmap
|
||||
# github.com/imdario/mergo v0.3.11
|
||||
## explicit; go 1.13
|
||||
github.com/imdario/mergo
|
||||
@@ -171,7 +168,7 @@ github.com/jesseduffield/go-git/v5/utils/merkletrie/filesystem
|
||||
github.com/jesseduffield/go-git/v5/utils/merkletrie/index
|
||||
github.com/jesseduffield/go-git/v5/utils/merkletrie/internal/frame
|
||||
github.com/jesseduffield/go-git/v5/utils/merkletrie/noder
|
||||
# github.com/jesseduffield/gocui v0.3.1-0.20250210123912-aba68ae65951
|
||||
# github.com/jesseduffield/gocui v0.3.1-0.20250220081214-b376cb0857ac
|
||||
## explicit; go 1.12
|
||||
github.com/jesseduffield/gocui
|
||||
# github.com/jesseduffield/kill v0.0.0-20250101124109-e216ddbe133a
|
||||
|
||||
Reference in New Issue
Block a user