feat: edit working-checkout comparisons with normal editor actions
This commit is contained in:
Generated
+7
@@ -1342,6 +1342,12 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "similar"
|
||||||
|
version = "2.7.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "siphasher"
|
name = "siphasher"
|
||||||
version = "1.0.4"
|
version = "1.0.4"
|
||||||
@@ -1839,6 +1845,7 @@ dependencies = [
|
|||||||
"ratatui",
|
"ratatui",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"similar",
|
||||||
"tree-sitter",
|
"tree-sitter",
|
||||||
"tree-sitter-bash",
|
"tree-sitter-bash",
|
||||||
"tree-sitter-c",
|
"tree-sitter-c",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ ignore = "0.4"
|
|||||||
ratatui = { version = "0.30", default-features = false, features = ["crossterm_0_29", "layout-cache", "underline-color", "unstable-backend-writer"] }
|
ratatui = { version = "0.30", default-features = false, features = ["crossterm_0_29", "layout-cache", "underline-color", "unstable-backend-writer"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
similar = { version = "2", default-features = false }
|
||||||
tree-sitter = "0.27.1"
|
tree-sitter = "0.27.1"
|
||||||
tree-sitter-bash = "0.25.1"
|
tree-sitter-bash = "0.25.1"
|
||||||
tree-sitter-c = "0.24.2"
|
tree-sitter-c = "0.24.2"
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ Vamp starts in Normal mode. Press `i`, type text, then Esc to return to Normal.
|
|||||||
| Paste in Normal | `p`/`P` after/before the caret or row for linewise fragments; system clipboard by default |
|
| Paste in Normal | `p`/`P` after/before the caret or row for linewise fragments; system clipboard by default |
|
||||||
| Command palette | Ctrl+p; type to filter, arrows select, Enter accepts, Esc cancels |
|
| Command palette | Ctrl+p; type to filter, arrows select, Enter accepts, Esc cancels |
|
||||||
| Floating/docked explorer in Normal or Visual | Space then `o` / Space then `e` |
|
| Floating/docked explorer in Normal or Visual | Space then `o` / Space then `e` |
|
||||||
| Repository diff in Normal | `:diff`; select Before then After, Tab changes category, type to search |
|
| Repository diff in Normal | `:diff`; choose Before then After, Tab changes category, type to search; Working checkout After is editable; `:diff.close` exits |
|
||||||
|
|
||||||
Space is the default leader: press its suffix keys in order, not simultaneously. The [editing guide](docs/editing.md) contains the complete key table and behavior reference.
|
Space is the default leader: press its suffix keys in order, not simultaneously. The [editing guide](docs/editing.md) contains the complete key table and behavior reference.
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ Normal `dd` and `cc` delete/change complete rows, with leading counts. Bind `con
|
|||||||
| Normal | `edit`, `buffers`, `buffer`, `buffer_next`, `buffer_previous`, `buffer_delete`, `buffer_force_delete` |
|
| Normal | `edit`, `buffers`, `buffer`, `buffer_next`, `buffer_previous`, `buffer_delete`, `buffer_force_delete` |
|
||||||
| Normal | `follow_link` |
|
| Normal | `follow_link` |
|
||||||
| Normal | `diff` |
|
| Normal | `diff` |
|
||||||
|
| Normal, Insert, Visual, Command, Search | `diff.close` |
|
||||||
| Normal | `jump_back`, `jump_forward` |
|
| Normal | `jump_back`, `jump_forward` |
|
||||||
| Normal | `lsp.definition`, `lsp.diagnostics`, `lsp.hover` |
|
| Normal | `lsp.definition`, `lsp.diagnostics`, `lsp.hover` |
|
||||||
| Insert | `lsp.completion`, `snippet.next`, `snippet.previous` |
|
| Insert | `lsp.completion`, `snippet.next`, `snippet.previous` |
|
||||||
@@ -139,9 +140,13 @@ config.bind "ctrl+f", config.core.right, mode: config.modes.tree
|
|||||||
config.bind "ctrl+h", nil, mode: config.modes.tree
|
config.bind "ctrl+h", nil, mode: config.modes.tree
|
||||||
```
|
```
|
||||||
|
|
||||||
The diff's right-docked changed-file explorer uses these same tree and selection contexts, including remaps and disabled keys. Enter opens the selected file's diff rather than an editable buffer; its catalog comes from the comparison, not a disk scan.
|
The diff's changed-file explorer and floating picker use these same tree and selection contexts, including remaps and disabled keys. Enter opens the selected file's comparison; Working checkout After reuses its editable buffer. The catalog contains only changed paths, with A/M/D/R status markers, rather than a disk scan.
|
||||||
|
|
||||||
In the diff view, Ctrl+e is reserved for hiding/showing the changed-file explorer and takes precedence over tree/selection remaps. Its query, selection, and expansion state survive hiding; the panes use the reclaimed width.
|
Ordinary `config.core.file_picker` and `config.core.file_explorer` bindings work inside comparisons. Ctrl+w closes a focused picker/explorer, retaining its query, selection, and expansion state; the panes use the reclaimed width. Ctrl+e has no reserved diff behavior. Close the comparison explicitly with `:diff.close`, its palette action, or the generated action value below. `config.core.diff` remains the opening action and also exposes its immutable `close` child; Escape never closes a comparison.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
config.bind "leader d q", config.core.diff.close
|
||||||
|
```
|
||||||
|
|
||||||
Ctrl+h is **not** a Backspace alias or default deletion key in any mode. Raw Ctrl+h (0x08) and Backspace (DEL/0x7f) are distinct, as are CSI-u events. In the tree it navigates in NORMAL and INSERT without deleting query text; it never deletes file-buffer Insert text by default. Explicit `config.core.backspace` bindings remain available if desired.
|
Ctrl+h is **not** a Backspace alias or default deletion key in any mode. Raw Ctrl+h (0x08) and Backspace (DEL/0x7f) are distinct, as are CSI-u events. In the tree it navigates in NORMAL and INSERT without deleting query text; it never deletes file-buffer Insert text by default. Explicit `config.core.backspace` bindings remain available if desired.
|
||||||
|
|
||||||
|
|||||||
+7
-7
@@ -197,7 +197,7 @@ The project root is the working directory captured at startup. Scanning uses the
|
|||||||
|
|
||||||
Run `:diff` in Normal mode, choose **Before**, then **After**, and press Enter to compare. The command palette also exposes **Diff**; there is no default keybinding. Repository discovery starts at the active file's directory, or the startup project root for an unnamed buffer, and prefers jj over Git.
|
Run `:diff` in Normal mode, choose **Before**, then **After**, and press Enter to compare. The command palette also exposes **Diff**; there is no default keybinding. Repository discovery starts at the active file's directory, or the startup project root for an unnamed buffer, and prefers jj over Git.
|
||||||
|
|
||||||
The floating selector has **Revisions / Bookmarks** tabs for jj, or **Commits / Branches / Tags** for Git. Type to filter by revision/change ID, commit ID, reference name, or description. **Working checkout** stays first in every category, even when it does not match the query. It compares files on disk, including eligible untracked files; it neither saves nor includes unsaved editor text.
|
The floating selector has **Revisions / Bookmarks** tabs for jj, or **Commits / Branches / Tags** for Git. Type to filter by revision/change ID, commit ID, reference name, or description. **Working checkout** stays first in every category, even when it does not match the query. As Before it is a disk snapshot, including eligible untracked files. As After it includes unsaved regular-text buffers and enables live editing; opening a comparison never saves them.
|
||||||
|
|
||||||
| Selector input | Effect |
|
| Selector input | Effect |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -205,27 +205,27 @@ The floating selector has **Revisions / Bookmarks** tabs for jj, or **Commits /
|
|||||||
| Up / Down, Ctrl+k / Ctrl+j | Previous / next entry |
|
| Up / Down, Ctrl+k / Ctrl+j | Previous / next entry |
|
||||||
| Backspace / Ctrl+u | Remove a query grapheme / clear query |
|
| Backspace / Ctrl+u | Remove a query grapheme / clear query |
|
||||||
| Enter | Choose the entry |
|
| Enter | Choose the entry |
|
||||||
| Esc | After → return to Before; Before → close |
|
| Esc | Cancel loading; After → return to Before; Before → clear query without closing |
|
||||||
|
|
||||||
Remote references such as `some-bookmark@origin` appear from remote advertisements, including refs never fetched locally. Selecting one retrieves missing content into a temporary comparison repository. **Load history from origin** (or another configured remote) in Revisions/Commits imports searchable remote history without advancing the selection stage. These operations may require network access and the repository's existing credentials; errors stay in the selector. They do not update active refs, snapshot jj's working copy, or change the checkout.
|
Remote references such as `some-bookmark@origin` appear from remote advertisements, including refs never fetched locally. Selecting one retrieves missing content into a temporary comparison repository. **Load history from origin** (or another configured remote) in Revisions/Commits imports searchable remote history without advancing the selection stage. These operations may require network access and the repository's existing credentials; errors stay in the selector. They do not update active refs, snapshot jj's working copy, or change the checkout.
|
||||||
|
|
||||||
The read-only comparison has Before on the left, After on the right, and the changed-file explorer **docked on the right**. The explorer reuses the normal compact directory tree, filtering, and configurable `tree`/`selection` navigation. Its catalog contains only changed paths, including removed and historical files; it does not scan the working directory. Use h/j/k/l or control/arrow navigation, Enter to toggle a folder or open a file, `i` to filter, Ctrl+u to clear, and Ctrl+t to switch Tree/List. Opening a file focuses Before.
|
The comparison has Before on the left, After on the right, and the changed-file explorer **docked on the right**. Before and historical/remote After snapshots are read-only. Selecting **Working checkout** as After binds eligible regular UTF-8 files to normal editor buffers, reusing already-open dirty buffers and their undo history. Focus After to use native editing, selections, search, completion, undo/redo, and `:w`. Removed files, binary files, symlinks, and submodules remain read-only. Closing the diff keeps its buffers and unsaved edits.
|
||||||
|
|
||||||
**Ctrl+e** hides/shows the explorer in the diff view. Hiding reclaims its entire width for the split panes without losing the filter, selected row, folder expansion, displayed file, or pane scroll offsets. Hiding from Files moves focus to Before; showing restores Files focus. While hidden, Tab/Shift+Tab cycles only between Before and After. Ctrl+e is a reserved diff-view control and takes precedence over tree/selection remaps.
|
Use the ordinary **file-picker/file-explorer actions and bindings**: Space `o` opens a floating picker, Space `e` opens/focuses the docked explorer, and Ctrl+w closes the focused picker/explorer and reclaims its width. Remapped bindings work too; Ctrl+e is no longer reserved by the diff. The changed-path catalog retains A/M/D/R markers and the normal compact tree, filtering, folder expansion, and configurable `tree`/`selection` navigation. It includes removed and historical paths without scanning the working directory. Enter toggles a folder or opens the selected comparison file and focuses Before. While the explorer is hidden, Tab/Shift+Tab cycles only between the two text panes.
|
||||||
|
|
||||||
File rows show colored **A** (added, green), **M** (modified, yellow), **D** (removed, red), or **R** (renamed, cyan) markers in Tree and List views, including filtered results. Rename rows show the new name followed by `← old/path`; directories have no file-status marker. Ordinary file exploration remains unannotated.
|
File rows show colored **A** (added, green), **M** (modified, yellow), **D** (removed, red), or **R** (renamed, cyan) markers in Tree and List views, including filtered results. Rename rows show the new name followed by `← old/path`; directories have no file-status marker. Ordinary file exploration remains unannotated.
|
||||||
|
|
||||||
Text panes show change excerpts with **10 unchanged lines above and below** each change, preserving original file line numbers. Overlapping or touching excerpts merge; omitted stretches show an unchanged-line count in both panes. Files with only metadata changes show their notice or “No text changes” rather than unrelated source.
|
Text panes show change excerpts with **10 unchanged lines above and below** each change, preserving original file line numbers. Overlapping or touching excerpts merge; omitted stretches show an unchanged-line count in both panes. Files with only metadata changes show their notice or “No text changes” rather than unrelated source.
|
||||||
|
|
||||||
With a text pane focused, **`[` expands above** and **`]` expands below** the excerpt at the top of the viewport, revealing up to **15 lines** per keypress. A hidden-line marker targets the following excerpt, or the preceding excerpt at the end of the file. Expansion clamps at file boundaries and merges excerpts when they meet. Existing visible source stays anchored; expanding above a leading/interior marker brings the newly revealed context into view. Opening a file resets its excerpts to the configured initial context.
|
In **Normal mode** with a text pane focused, **`[` expands above** and **`]` expands below** the excerpt at the top of the viewport, revealing up to **15 lines** per keypress. In editable After's Insert mode these keys insert literal text. A hidden-line marker targets the following excerpt, or the preceding excerpt at the end of the file. Expansion clamps at file boundaries and merges excerpts when they meet. Existing visible source stays anchored; expanding above a leading/interior marker brings the newly revealed context into view. Opening a file resets its excerpts to the configured initial context. Live edits recompute changes while retaining expanded context; the caret stays visible even when the last text change is reverted.
|
||||||
|
|
||||||
Configure these counts in Ruby with `config.diff_context_lines = 10` (nonnegative; `0` shows changes only) and `config.diff_expand_lines = 15` (positive).
|
Configure these counts in Ruby with `config.diff_context_lines = 10` (nonnegative; `0` shows changes only) and `config.diff_expand_lines = 15` (positive).
|
||||||
|
|
||||||
Changed text rows use muted red backgrounds in Before and muted green backgrounds in After, including blank tails and real empty lines. Foreground colors use the editor's bundled Tree-sitter syntax highlighting, parsed independently for each snapshot and its path (including the old path for renames). Unknown languages retain the normal foreground; historical snapshots do not borrow live-buffer LSP tokens.
|
Changed text rows use muted red backgrounds in Before and muted green backgrounds in After, including blank tails and real empty lines. Foreground colors use the editor's bundled Tree-sitter syntax highlighting, parsed independently for each snapshot and its path (including the old path for renames). Editable After also uses its live buffer's semantic highlighting, selections, and diagnostics. Unknown languages retain the normal foreground; historical snapshots do not borrow live-buffer LSP tokens.
|
||||||
|
|
||||||
Missing counterparts use adjacent muted `╱` diagonals (U+2571, box drawings light diagonal) on the normal terminal background, one per column. Unlike the text slash `/`, this glyph is designed to reach cell corners so diagonals can join end to end across successive rows. Pixel-perfect joins depend on the terminal's font and line-spacing rendering. Actual empty source lines retain their normal/change background and are not hatched.
|
Missing counterparts use adjacent muted `╱` diagonals (U+2571, box drawings light diagonal) on the normal terminal background, one per column. Unlike the text slash `/`, this glyph is designed to reach cell corners so diagonals can join end to end across successive rows. Pixel-perfect joins depend on the terminal's font and line-spacing rendering. Actual empty source lines retain their normal/change background and are not hatched.
|
||||||
|
|
||||||
Tab/Shift+Tab cycles focus between Files, Before, and After. In text panes, Up/Down or Ctrl+j/k scrolls both panes together; Left/Right or Ctrl+h/l scrolls the focused pane horizontally. Home/End goes to the first/last tree row or displayed excerpt/hidden-line row. Wheel input over a text pane scrolls both panes; over Files it navigates visible tree rows without opening them. Esc first leaves filtering when the tree is focused; otherwise it closes the diff and preserves the editor's buffers, cursors, unsaved text, and undo history. Typing and pasted text cannot edit either snapshot.
|
In Normal mode, Tab/Shift+Tab cycles focus between Files, Before, and After. Read-only text panes use Up/Down or Ctrl+j/k for shared vertical scrolling, Left/Right or Ctrl+h/l for independent horizontal scrolling, and Home/End for the first/last displayed row; editable After uses normal buffer motions. Wheel input over text panes scrolls both panes without moving the editable caret; over Files it navigates visible tree rows without opening them. Escape cancels modes, prompts, or filtering, or returns picker focus to Before; **it never closes the diff**. Use **`:diff.close`**, the palette's **Close diff** action, or bind **`config.core.diff.close`** to leave the comparison explicitly. The dotted command is intentional; there is no `:diffclose` alias.
|
||||||
|
|
||||||
Binary data, missing final newlines, permission/type changes, symlink targets, and submodule pointers have explicit notices. Symlinks are not followed and submodule contents are not traversed. jj conflicts use jj's file-content projection and carry conflict notices; ordinary files remain readable. Identical-content moves are shown as renames; modified moves appear as an added and removed file.
|
Binary data, missing final newlines, permission/type changes, symlink targets, and submodule pointers have explicit notices. Symlinks are not followed and submodule contents are not traversed. jj conflicts use jj's file-content projection and carry conflict notices; ordinary files remain readable. Identical-content moves are shown as renames; modified moves appear as an added and removed file.
|
||||||
|
|
||||||
|
|||||||
+529
-150
@@ -1,6 +1,9 @@
|
|||||||
use crate::editor::Input;
|
use crate::editor::Input;
|
||||||
use crate::files::{FilePicker, FileView};
|
use crate::files::{FilePicker, FilePresentation, FileView};
|
||||||
use std::path::PathBuf;
|
use std::{
|
||||||
|
collections::BTreeSet,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
use unicode_width::UnicodeWidthStr;
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
@@ -77,6 +80,8 @@ pub struct ChangedFile {
|
|||||||
pub status: FileStatus,
|
pub status: FileStatus,
|
||||||
pub before: Vec<String>,
|
pub before: Vec<String>,
|
||||||
pub after: Vec<String>,
|
pub after: Vec<String>,
|
||||||
|
pub before_eof: bool,
|
||||||
|
pub after_eof: bool,
|
||||||
pub hunks: Vec<Hunk>,
|
pub hunks: Vec<Hunk>,
|
||||||
pub notice: Option<String>,
|
pub notice: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -85,12 +90,18 @@ pub struct Comparison {
|
|||||||
pub before: String,
|
pub before: String,
|
||||||
pub after: String,
|
pub after: String,
|
||||||
pub files: Vec<ChangedFile>,
|
pub files: Vec<ChangedFile>,
|
||||||
|
pub root: PathBuf,
|
||||||
|
pub editable_paths: BTreeSet<PathBuf>,
|
||||||
}
|
}
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Operation {
|
pub enum Operation {
|
||||||
Discover,
|
Discover,
|
||||||
FetchRemote(String),
|
FetchRemote(String),
|
||||||
Compare { before: Revision, after: Revision },
|
Compare {
|
||||||
|
before: Revision,
|
||||||
|
after: Revision,
|
||||||
|
buffers: Box<[(PathBuf, String)]>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Outcome {
|
pub enum Outcome {
|
||||||
@@ -164,6 +175,10 @@ pub struct DiffState {
|
|||||||
pub rows: Vec<AlignedRow>,
|
pub rows: Vec<AlignedRow>,
|
||||||
pub display_rows: Vec<DisplayRow>,
|
pub display_rows: Vec<DisplayRow>,
|
||||||
excerpt_ranges: Vec<(usize, usize)>,
|
excerpt_ranges: Vec<(usize, usize)>,
|
||||||
|
pub live_buffer: Option<usize>,
|
||||||
|
pub live_revision: Option<u64>,
|
||||||
|
pub follow_caret: bool,
|
||||||
|
live_files: BTreeSet<usize>,
|
||||||
context_lines: usize,
|
context_lines: usize,
|
||||||
expand_lines: usize,
|
expand_lines: usize,
|
||||||
pending: Option<Operation>,
|
pending: Option<Operation>,
|
||||||
@@ -199,6 +214,10 @@ impl DiffState {
|
|||||||
rows: Vec::new(),
|
rows: Vec::new(),
|
||||||
display_rows: Vec::new(),
|
display_rows: Vec::new(),
|
||||||
excerpt_ranges: Vec::new(),
|
excerpt_ranges: Vec::new(),
|
||||||
|
live_buffer: None,
|
||||||
|
live_revision: None,
|
||||||
|
follow_caret: false,
|
||||||
|
live_files: BTreeSet::new(),
|
||||||
context_lines: 10,
|
context_lines: 10,
|
||||||
expand_lines: 15,
|
expand_lines: 15,
|
||||||
pending: Some(Operation::Discover),
|
pending: Some(Operation::Discover),
|
||||||
@@ -261,9 +280,17 @@ impl DiffState {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
}
|
}
|
||||||
Ok(Outcome::Comparison(comparison)) if expected == Some(RequestKind::Comparison) => {
|
Ok(Outcome::Comparison(comparison)) if expected == Some(RequestKind::Comparison) => {
|
||||||
|
self.live_files.clear();
|
||||||
|
self.live_buffer = None;
|
||||||
|
self.live_revision = None;
|
||||||
|
self.follow_caret = false;
|
||||||
let mut files = FilePicker::from_paths(
|
let mut files = FilePicker::from_paths(
|
||||||
PathBuf::new(),
|
comparison.root.clone(),
|
||||||
comparison.files.iter().map(|file| file.path.clone()),
|
comparison
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, file)| (index, file.path.clone())),
|
||||||
);
|
);
|
||||||
if let Some(file) = comparison.files.first() {
|
if let Some(file) = comparison.files.first() {
|
||||||
files.reveal_path(&file.path);
|
files.reveal_path(&file.path);
|
||||||
@@ -351,8 +378,8 @@ impl DiffState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns true only when the modal should close. All other inputs are consumed.
|
/// Handles modal input; closing is an explicit editor action.
|
||||||
pub(crate) fn handle(&mut self, input: Input) -> bool {
|
pub(crate) fn handle(&mut self, input: Input) {
|
||||||
if input == Input::Escape {
|
if input == Input::Escape {
|
||||||
if self.phase == Phase::View
|
if self.phase == Phase::View
|
||||||
&& self.focus == Focus::Files
|
&& self.focus == Focus::Files
|
||||||
@@ -361,28 +388,40 @@ impl DiffState {
|
|||||||
&& files.view == FileView::Tree
|
&& files.view == FileView::Tree
|
||||||
{
|
{
|
||||||
files.finish_search();
|
files.finish_search();
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
if self.phase != Phase::After {
|
if self.phase == Phase::View {
|
||||||
return true;
|
if self.focus == Focus::Files
|
||||||
|
&& let Some(files) = &mut self.files
|
||||||
|
{
|
||||||
|
files.focused = false;
|
||||||
|
self.files_visible = files.presentation == FilePresentation::Docked;
|
||||||
|
self.focus = Focus::Before;
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
self.pending = None;
|
self.pending = None;
|
||||||
self.request_kind = None;
|
self.request_kind = None;
|
||||||
self.loading = false;
|
self.loading = false;
|
||||||
|
self.error = None;
|
||||||
|
if self.phase == Phase::Before {
|
||||||
|
self.query.clear();
|
||||||
|
self.refilter();
|
||||||
|
return;
|
||||||
|
}
|
||||||
self.phase = Phase::Before;
|
self.phase = Phase::Before;
|
||||||
self.after = None;
|
self.after = None;
|
||||||
self.error = None;
|
|
||||||
if let Some(position) = self.before_position.take() {
|
if let Some(position) = self.before_position.take() {
|
||||||
self.category = position.category;
|
self.category = position.category;
|
||||||
self.query = position.query;
|
self.query = position.query;
|
||||||
self.refilter();
|
self.refilter();
|
||||||
self.select_target(&position.selected);
|
self.select_target(&position.selected);
|
||||||
}
|
}
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
if self.phase == Phase::View {
|
if self.phase == Phase::View {
|
||||||
self.handle_view(input);
|
self.handle_view(input);
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
match input {
|
match input {
|
||||||
Input::Char('\t') | Input::BackTab => {
|
Input::Char('\t') | Input::BackTab => {
|
||||||
@@ -417,7 +456,6 @@ impl DiffState {
|
|||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn choose(&mut self) {
|
fn choose(&mut self) {
|
||||||
@@ -448,23 +486,12 @@ impl DiffState {
|
|||||||
self.queue(Operation::Compare {
|
self.queue(Operation::Compare {
|
||||||
before: before.clone(),
|
before: before.clone(),
|
||||||
after: revision,
|
after: revision,
|
||||||
|
buffers: Box::new([]),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_view(&mut self, input: Input) {
|
fn handle_view(&mut self, input: Input) {
|
||||||
if input == Input::Ctrl('e') {
|
|
||||||
self.files_visible = !self.files_visible;
|
|
||||||
if self.files_visible {
|
|
||||||
self.focus = Focus::Files;
|
|
||||||
} else if self.focus == Focus::Files {
|
|
||||||
self.focus = Focus::Before;
|
|
||||||
}
|
|
||||||
if let Some(files) = &mut self.files {
|
|
||||||
files.focused = self.files_visible && self.focus == Focus::Files;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if self.focus == Focus::Files {
|
if self.focus == Focus::Files {
|
||||||
let files = self.files.as_mut().expect("comparison file picker");
|
let files = self.files.as_mut().expect("comparison file picker");
|
||||||
match input {
|
match input {
|
||||||
@@ -500,14 +527,12 @@ impl DiffState {
|
|||||||
}
|
}
|
||||||
Input::Enter => {
|
Input::Enter => {
|
||||||
if let Some(path) = files.accept()
|
if let Some(path) = files.accept()
|
||||||
&& let Some(index) = self.comparison.as_ref().and_then(|comparison| {
|
&& self.select_file(&path)
|
||||||
comparison.files.iter().position(|file| file.path == path)
|
|
||||||
})
|
|
||||||
{
|
{
|
||||||
self.file = index;
|
|
||||||
self.focus = Focus::Before;
|
self.focus = Focus::Before;
|
||||||
self.files.as_mut().expect("comparison picker").focused = false;
|
let files = self.files.as_mut().expect("comparison picker");
|
||||||
self.align_file();
|
files.focused = false;
|
||||||
|
self.files_visible = files.presentation == FilePresentation::Docked;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -566,14 +591,213 @@ impl DiffState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn after_editable(&self) -> bool {
|
||||||
|
self.phase == Phase::View
|
||||||
|
&& self
|
||||||
|
.after
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|revision| revision.target == RevisionTarget::Working)
|
||||||
|
&& self.comparison.as_ref().is_some_and(|comparison| {
|
||||||
|
comparison
|
||||||
|
.files
|
||||||
|
.get(self.file)
|
||||||
|
.is_some_and(|file| comparison.editable_paths.contains(&file.path))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn select_file(&mut self, path: &Path) -> bool {
|
||||||
|
let Some(index) = self.comparison.as_ref().and_then(|comparison| {
|
||||||
|
let relative = path.strip_prefix(&comparison.root).unwrap_or(path);
|
||||||
|
comparison
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.position(|file| file.path == relative)
|
||||||
|
}) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
self.file = index;
|
||||||
|
self.live_buffer = None;
|
||||||
|
self.live_revision = None;
|
||||||
|
self.follow_caret = false;
|
||||||
|
self.align_file();
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn after_display_row(&self, source_row: usize) -> Option<usize> {
|
||||||
|
self.display_rows.iter().position(|display| {
|
||||||
|
matches!(*display, DisplayRow::Line(index) if self.rows[index].after == Some(source_row))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reveal_after(&mut self, caret_row: usize) {
|
||||||
|
let Some(index) = self
|
||||||
|
.rows
|
||||||
|
.iter()
|
||||||
|
.position(|row| row.after == Some(caret_row))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if self.after_display_row(caret_row).is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let anchor = self.display_rows.get(self.top).copied();
|
||||||
|
self.excerpt_ranges.push((
|
||||||
|
index.saturating_sub(self.context_lines),
|
||||||
|
index
|
||||||
|
.saturating_add(self.context_lines)
|
||||||
|
.saturating_add(1)
|
||||||
|
.min(self.rows.len()),
|
||||||
|
));
|
||||||
|
self.excerpt_ranges.sort_unstable();
|
||||||
|
self.rebuild_display_rows();
|
||||||
|
self.restore_top(anchor);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_top(&mut self, anchor: Option<DisplayRow>) {
|
||||||
|
if let Some(anchor) = anchor {
|
||||||
|
let index = match anchor {
|
||||||
|
DisplayRow::Line(index) => index,
|
||||||
|
DisplayRow::Fold { start, .. } => start,
|
||||||
|
};
|
||||||
|
self.top = self
|
||||||
|
.display_rows
|
||||||
|
.iter()
|
||||||
|
.position(|row| match *row {
|
||||||
|
DisplayRow::Line(row) => row == index,
|
||||||
|
DisplayRow::Fold { start, end } => start <= index && index < end,
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_after(&mut self, lines: &[String], revision: u64, caret_row: usize) {
|
||||||
|
if !self.after_editable() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.live_revision == Some(revision) {
|
||||||
|
self.reveal_after(caret_row);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let file = &self.comparison.as_ref().unwrap().files[self.file];
|
||||||
|
let was_live = self.live_files.contains(&self.file);
|
||||||
|
let mut old = file.after.iter().map(String::as_str).collect::<Vec<_>>();
|
||||||
|
if !was_live && (file.after_eof || old.is_empty()) {
|
||||||
|
old.push("");
|
||||||
|
}
|
||||||
|
let new = lines.iter().map(String::as_str).collect::<Vec<_>>();
|
||||||
|
let ops = similar::capture_diff_slices(similar::Algorithm::Myers, &old, &new);
|
||||||
|
let mut mapping = vec![new.len().saturating_sub(1); old.len()];
|
||||||
|
for op in &ops {
|
||||||
|
let (_, old_range, new_range) = op.as_tag_tuple();
|
||||||
|
for offset in 0..old_range.len() {
|
||||||
|
mapping[old_range.start + offset] = (new_range.start
|
||||||
|
+ offset.min(new_range.len().saturating_sub(1)))
|
||||||
|
.min(new.len().saturating_sub(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let map_after = |index: usize| mapping.get(index).copied().unwrap_or(0);
|
||||||
|
let mut before_visible = BTreeSet::new();
|
||||||
|
let mut after_visible = BTreeSet::new();
|
||||||
|
for &(start, end) in &self.excerpt_ranges {
|
||||||
|
for row in &self.rows[start..end] {
|
||||||
|
before_visible.extend(row.before);
|
||||||
|
after_visible.extend(row.after.map(map_after));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let top_before = self
|
||||||
|
.display_rows
|
||||||
|
.get(self.top)
|
||||||
|
.and_then(|display| match *display {
|
||||||
|
DisplayRow::Line(index) => self.rows[index].before,
|
||||||
|
DisplayRow::Fold { start, .. } => self.rows[start].before,
|
||||||
|
});
|
||||||
|
let top_after = self
|
||||||
|
.display_rows
|
||||||
|
.get(self.top)
|
||||||
|
.and_then(|display| match *display {
|
||||||
|
DisplayRow::Line(index) => self.rows[index].after,
|
||||||
|
DisplayRow::Fold { start, .. } => self.rows[start].after,
|
||||||
|
})
|
||||||
|
.map(map_after);
|
||||||
|
let was_changed = file_is_changed(file);
|
||||||
|
let file = &mut self.comparison.as_mut().unwrap().files[self.file];
|
||||||
|
file.after.resize_with(lines.len(), String::new);
|
||||||
|
for (target, line) in file.after.iter_mut().zip(lines) {
|
||||||
|
target.clone_from(line);
|
||||||
|
}
|
||||||
|
file.after_eof = lines.len() > 1 && lines.last().is_some_and(String::is_empty);
|
||||||
|
file.hunks = line_hunks(
|
||||||
|
&file.before,
|
||||||
|
file.before_eof,
|
||||||
|
live_content(lines, file.after_eof),
|
||||||
|
file.after_eof,
|
||||||
|
);
|
||||||
|
update_eof_notice(file);
|
||||||
|
let changed = file_is_changed(file);
|
||||||
|
self.live_files.insert(self.file);
|
||||||
|
self.live_revision = Some(revision);
|
||||||
|
let left_before = self.left_before;
|
||||||
|
let left_after = self.left_after;
|
||||||
|
self.rebuild_file(false);
|
||||||
|
self.left_before = left_before.min(self.max_before);
|
||||||
|
self.left_after = left_after.min(self.max_after);
|
||||||
|
for (index, row) in self.rows.iter().enumerate() {
|
||||||
|
if row
|
||||||
|
.before
|
||||||
|
.is_some_and(|index| before_visible.contains(&index))
|
||||||
|
|| row
|
||||||
|
.after
|
||||||
|
.is_some_and(|index| after_visible.contains(&index))
|
||||||
|
{
|
||||||
|
self.excerpt_ranges.push((index, index + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.excerpt_ranges.sort_unstable();
|
||||||
|
self.rebuild_display_rows();
|
||||||
|
if let Some(row) = top_after {
|
||||||
|
self.top = self.after_display_row(row).unwrap_or(0);
|
||||||
|
} else if let Some(source) = top_before
|
||||||
|
&& let Some(index) = self.rows.iter().position(|row| row.before == Some(source))
|
||||||
|
{
|
||||||
|
self.restore_top(Some(DisplayRow::Line(index)));
|
||||||
|
}
|
||||||
|
self.reveal_after(caret_row);
|
||||||
|
if was_changed != changed {
|
||||||
|
self.refresh_files();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_files(&mut self) {
|
||||||
|
let Some(comparison) = &self.comparison else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let paths = comparison
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, file)| file_is_changed(file))
|
||||||
|
.map(|(index, file)| (index, file.path.clone()));
|
||||||
|
if let Some(files) = &mut self.files {
|
||||||
|
files.replace_paths(paths);
|
||||||
|
} else {
|
||||||
|
self.files = Some(FilePicker::from_paths(comparison.root.clone(), paths));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn align_file(&mut self) {
|
fn align_file(&mut self) {
|
||||||
|
self.rebuild_file(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rebuild_file(&mut self, reset: bool) {
|
||||||
self.rows.clear();
|
self.rows.clear();
|
||||||
self.display_rows.clear();
|
self.display_rows.clear();
|
||||||
self.excerpt_ranges.clear();
|
self.excerpt_ranges.clear();
|
||||||
self.top = 0;
|
if reset {
|
||||||
self.left_before = 0;
|
self.top = 0;
|
||||||
self.left_after = 0;
|
self.left_before = 0;
|
||||||
self.max_before = 0;
|
self.left_after = 0;
|
||||||
|
self.max_before = 0;
|
||||||
|
}
|
||||||
self.max_after = 0;
|
self.max_after = 0;
|
||||||
let Some(file) = self
|
let Some(file) = self
|
||||||
.comparison
|
.comparison
|
||||||
@@ -598,15 +822,22 @@ impl DiffState {
|
|||||||
.max()
|
.max()
|
||||||
.unwrap_or(0)
|
.unwrap_or(0)
|
||||||
};
|
};
|
||||||
self.max_before = width(&file.before);
|
if reset {
|
||||||
|
self.max_before = width(&file.before);
|
||||||
|
}
|
||||||
self.max_after = width(&file.after);
|
self.max_after = width(&file.after);
|
||||||
|
let after_len = if self.live_files.contains(&self.file) {
|
||||||
|
live_content(&file.after, file.after_eof).len()
|
||||||
|
} else {
|
||||||
|
file.after.len()
|
||||||
|
};
|
||||||
self.rows.reserve(file.before.len().max(file.after.len()));
|
self.rows.reserve(file.before.len().max(file.after.len()));
|
||||||
let mut before = 0;
|
let mut before = 0;
|
||||||
let mut after = 0;
|
let mut after = 0;
|
||||||
for hunk in &file.hunks {
|
for hunk in &file.hunks {
|
||||||
// Clamp invalid ranges rather than indexing historical text unchecked.
|
// Clamp invalid ranges rather than indexing historical text unchecked.
|
||||||
let start_before = hunk.before_start.min(file.before.len()).max(before);
|
let start_before = hunk.before_start.min(file.before.len()).max(before);
|
||||||
let start_after = hunk.after_start.min(file.after.len()).max(after);
|
let start_after = hunk.after_start.min(after_len).max(after);
|
||||||
append_rows(
|
append_rows(
|
||||||
&mut self.rows,
|
&mut self.rows,
|
||||||
before,
|
before,
|
||||||
@@ -620,7 +851,7 @@ impl DiffState {
|
|||||||
let end_before = before
|
let end_before = before
|
||||||
.saturating_add(hunk.before_len)
|
.saturating_add(hunk.before_len)
|
||||||
.min(file.before.len());
|
.min(file.before.len());
|
||||||
let end_after = after.saturating_add(hunk.after_len).min(file.after.len());
|
let end_after = after.saturating_add(hunk.after_len).min(after_len);
|
||||||
append_rows(&mut self.rows, before, end_before, after, end_after, true);
|
append_rows(&mut self.rows, before, end_before, after, end_after, true);
|
||||||
before = end_before;
|
before = end_before;
|
||||||
after = end_after;
|
after = end_after;
|
||||||
@@ -630,9 +861,16 @@ impl DiffState {
|
|||||||
before,
|
before,
|
||||||
file.before.len(),
|
file.before.len(),
|
||||||
after,
|
after,
|
||||||
file.after.len(),
|
after_len,
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
if after_len < file.after.len() {
|
||||||
|
self.rows.push(AlignedRow {
|
||||||
|
before: None,
|
||||||
|
after: Some(after_len),
|
||||||
|
kind: RowKind::Equal,
|
||||||
|
});
|
||||||
|
}
|
||||||
self.reset_excerpts();
|
self.reset_excerpts();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -781,6 +1019,89 @@ fn append_rows(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn live_content(lines: &[String], eof: bool) -> &[String] {
|
||||||
|
if eof || (lines.len() == 1 && lines[0].is_empty()) {
|
||||||
|
&lines[..lines.len().saturating_sub(1)]
|
||||||
|
} else {
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn line_hunks(
|
||||||
|
before: &[String],
|
||||||
|
before_eof: bool,
|
||||||
|
after: &[String],
|
||||||
|
after_eof: bool,
|
||||||
|
) -> Vec<Hunk> {
|
||||||
|
fn tokens(lines: &[String], eof: bool) -> Vec<(&str, bool)> {
|
||||||
|
lines
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, line)| (line.as_str(), index + 1 < lines.len() || eof))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
let before = tokens(before, before_eof);
|
||||||
|
let after = tokens(after, after_eof);
|
||||||
|
similar::capture_diff_slices(similar::Algorithm::Myers, &before, &after)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|op| {
|
||||||
|
let (tag, before, after) = op.as_tag_tuple();
|
||||||
|
(tag != similar::DiffTag::Equal).then_some(Hunk {
|
||||||
|
before_start: before.start,
|
||||||
|
before_len: before.len(),
|
||||||
|
after_start: after.start,
|
||||||
|
after_len: after.len(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_is_changed(file: &ChangedFile) -> bool {
|
||||||
|
file.status != FileStatus::Modified
|
||||||
|
|| !file.hunks.is_empty()
|
||||||
|
|| file.notice.as_ref().is_some_and(|notice| {
|
||||||
|
notice
|
||||||
|
.split("; ")
|
||||||
|
.any(|part| !part.starts_with("EOF newline:"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_eof_notice(file: &mut ChangedFile) {
|
||||||
|
let mut notices = file
|
||||||
|
.notice
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or("")
|
||||||
|
.split("; ")
|
||||||
|
.filter(|part| !part.is_empty() && !part.starts_with("EOF newline:"))
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let before_empty = file.before.is_empty();
|
||||||
|
let after_empty = live_content(&file.after, file.after_eof).is_empty();
|
||||||
|
if (!before_empty && !file.before_eof) || (!after_empty && !file.after_eof) {
|
||||||
|
let label = |absent, empty, eof| {
|
||||||
|
if absent {
|
||||||
|
"absent"
|
||||||
|
} else if empty {
|
||||||
|
"empty file"
|
||||||
|
} else if eof {
|
||||||
|
"present"
|
||||||
|
} else {
|
||||||
|
"missing"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
notices.push(format!(
|
||||||
|
"EOF newline: Before {}, After {}",
|
||||||
|
label(
|
||||||
|
file.status == FileStatus::Added,
|
||||||
|
before_empty,
|
||||||
|
file.before_eof
|
||||||
|
),
|
||||||
|
label(false, after_empty, file.after_eof)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
file.notice = (!notices.is_empty()).then(|| notices.join("; "));
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -1079,7 +1400,7 @@ mod tests {
|
|||||||
editor.handle(Input::Enter);
|
editor.handle(Input::Enter);
|
||||||
let (id, operation) = editor.take_diff_request().unwrap();
|
let (id, operation) = editor.take_diff_request().unwrap();
|
||||||
match operation {
|
match operation {
|
||||||
Operation::Compare { before, after } => {
|
Operation::Compare { before, after, .. } => {
|
||||||
assert_eq!(before.target, RevisionTarget::Commit("abcdef123".into()));
|
assert_eq!(before.target, RevisionTarget::Commit("abcdef123".into()));
|
||||||
assert_eq!(after.target, RevisionTarget::Working);
|
assert_eq!(after.target, RevisionTarget::Working);
|
||||||
}
|
}
|
||||||
@@ -1092,6 +1413,8 @@ mod tests {
|
|||||||
Comparison {
|
Comparison {
|
||||||
before: "abcdef123".into(),
|
before: "abcdef123".into(),
|
||||||
after: "Working checkout".into(),
|
after: "Working checkout".into(),
|
||||||
|
root: PathBuf::new(),
|
||||||
|
editable_paths: BTreeSet::new(),
|
||||||
files: vec![
|
files: vec![
|
||||||
ChangedFile {
|
ChangedFile {
|
||||||
path: "renamed.txt".into(),
|
path: "renamed.txt".into(),
|
||||||
@@ -1111,6 +1434,8 @@ mod tests {
|
|||||||
"tail".into(),
|
"tail".into(),
|
||||||
"end".into(),
|
"end".into(),
|
||||||
],
|
],
|
||||||
|
before_eof: false,
|
||||||
|
after_eof: false,
|
||||||
hunks: vec![
|
hunks: vec![
|
||||||
Hunk {
|
Hunk {
|
||||||
before_start: 1,
|
before_start: 1,
|
||||||
@@ -1133,6 +1458,8 @@ mod tests {
|
|||||||
status: FileStatus::Added,
|
status: FileStatus::Added,
|
||||||
before: vec![],
|
before: vec![],
|
||||||
after: vec!["a".into(), "b".into()],
|
after: vec!["a".into(), "b".into()],
|
||||||
|
before_eof: false,
|
||||||
|
after_eof: false,
|
||||||
hunks: vec![Hunk {
|
hunks: vec![Hunk {
|
||||||
before_start: 0,
|
before_start: 0,
|
||||||
before_len: 0,
|
before_len: 0,
|
||||||
@@ -1147,6 +1474,8 @@ mod tests {
|
|||||||
status: FileStatus::Removed,
|
status: FileStatus::Removed,
|
||||||
before: vec![],
|
before: vec![],
|
||||||
after: vec![],
|
after: vec![],
|
||||||
|
before_eof: false,
|
||||||
|
after_eof: false,
|
||||||
hunks: vec![],
|
hunks: vec![],
|
||||||
notice: Some("Binary file".into()),
|
notice: Some("Binary file".into()),
|
||||||
},
|
},
|
||||||
@@ -1261,6 +1590,9 @@ mod tests {
|
|||||||
assert_eq!(editor.diff().unwrap().phase, Phase::After);
|
assert_eq!(editor.diff().unwrap().phase, Phase::After);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert_eq!(editor.diff().unwrap().phase, Phase::Before);
|
||||||
|
assert!(editor.diff().unwrap().query.is_empty());
|
||||||
|
editor.execute("diff.close");
|
||||||
assert!(editor.diff().is_none());
|
assert!(editor.diff().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1362,129 +1694,55 @@ mod tests {
|
|||||||
assert_eq!(editor.carets(), carets);
|
assert_eq!(editor.carets(), carets);
|
||||||
assert_eq!(editor.text_revision(), revision);
|
assert_eq!(editor.text_revision(), revision);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert!(editor.diff().is_some());
|
||||||
|
editor.execute("diff.close");
|
||||||
assert!(editor.diff().is_none());
|
assert!(editor.diff().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn explorer_toggle_preserves_filtered_tree_review_and_source_state() {
|
fn explorer_actions_preserve_review_and_ctrl_e_uses_normal_bindings() {
|
||||||
let mut editor = editor();
|
let mut editor = editor();
|
||||||
editor
|
|
||||||
.apply(vec![Effect::Replace("unsaved source".into())])
|
|
||||||
.unwrap();
|
|
||||||
let original = editor.context().text;
|
|
||||||
let carets = editor.carets();
|
|
||||||
let revision = editor.text_revision();
|
|
||||||
open(&mut editor);
|
open(&mut editor);
|
||||||
let id = choose_pair(&mut editor);
|
let id = choose_pair(&mut editor);
|
||||||
let mut changes = comparison();
|
editor.apply_diff_result(id, Ok(Outcome::Comparison(comparison())));
|
||||||
changes.files[0].path = "src/deep/renamed.txt".into();
|
|
||||||
changes.files[1].path = "src/deep/added.txt".into();
|
|
||||||
editor.apply_diff_result(id, Ok(Outcome::Comparison(changes)));
|
|
||||||
editor.handle(Input::Char('\t'));
|
|
||||||
editor.handle(Input::Down);
|
|
||||||
editor.handle(Input::Right);
|
|
||||||
editor.handle(Input::Char('\t'));
|
|
||||||
editor.handle(Input::Right);
|
|
||||||
editor.handle(Input::Char('\t'));
|
|
||||||
editor.handle(Input::Char('i'));
|
|
||||||
text(&mut editor, "src");
|
|
||||||
editor.handle(Input::Down);
|
|
||||||
let snapshot = |state: &DiffState| {
|
|
||||||
let files = state.files.as_ref().unwrap();
|
|
||||||
(
|
|
||||||
files.query.clone(),
|
|
||||||
files.selected,
|
|
||||||
files.view,
|
|
||||||
files.searching,
|
|
||||||
files
|
|
||||||
.entries()
|
|
||||||
.map(|row| (row.path.to_owned(), row.expanded))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let tree = snapshot(editor.diff().unwrap());
|
|
||||||
let rows = editor
|
|
||||||
.diff()
|
|
||||||
.unwrap()
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.map(|row| (row.before, row.after, row.kind))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
editor
|
editor
|
||||||
.bind("tree", "ctrl+e", Some("core.down".into()))
|
.bind("tree", "ctrl+e", Some("core.down".into()))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
editor
|
|
||||||
.bind("selection", "ctrl+e", Some("core.up".into()))
|
|
||||||
.unwrap();
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
editor.handle(Input::Ctrl('e'));
|
||||||
let state = editor.diff().unwrap();
|
assert!(editor.diff().unwrap().files_visible);
|
||||||
assert!(!state.files_visible);
|
|
||||||
assert_eq!(state.focus, Focus::Before);
|
|
||||||
assert!(!state.files.as_ref().unwrap().focused);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
(state.file, state.top, state.left_before, state.left_after),
|
editor
|
||||||
(0, 1, 1, 1)
|
.diff()
|
||||||
|
.unwrap()
|
||||||
|
.files
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.entries()
|
||||||
|
.nth(editor.diff().unwrap().files.as_ref().unwrap().selected)
|
||||||
|
.unwrap()
|
||||||
|
.path,
|
||||||
|
Path::new("added.txt")
|
||||||
);
|
);
|
||||||
assert_eq!(snapshot(state), tree);
|
editor.handle(Input::Ctrl('w'));
|
||||||
for (input, focus) in [
|
assert!(editor.diff().is_some());
|
||||||
(Input::Char('\t'), Focus::After),
|
assert!(!editor.diff().unwrap().files_visible);
|
||||||
(Input::Char('\t'), Focus::Before),
|
text(&mut editor, " e");
|
||||||
(Input::BackTab, Focus::After),
|
assert!(editor.diff().unwrap().files_visible);
|
||||||
(Input::BackTab, Focus::Before),
|
|
||||||
] {
|
|
||||||
editor.handle(input);
|
|
||||||
let state = editor.diff().unwrap();
|
|
||||||
assert_eq!(state.focus, focus);
|
|
||||||
assert!(!state.files.as_ref().unwrap().focused);
|
|
||||||
}
|
|
||||||
for input in [
|
|
||||||
Input::Char('z'),
|
|
||||||
Input::Ctrl('t'),
|
|
||||||
Input::Backspace,
|
|
||||||
Input::Delete,
|
|
||||||
Input::Paste("not source".into()),
|
|
||||||
Input::Enter,
|
|
||||||
] {
|
|
||||||
editor.handle(input);
|
|
||||||
}
|
|
||||||
assert_eq!(snapshot(editor.diff().unwrap()), tree);
|
|
||||||
editor.handle(Input::Down);
|
|
||||||
assert_eq!(editor.diff().unwrap().top, 2);
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
let state = editor.diff().unwrap();
|
|
||||||
assert!(state.files_visible && state.files.as_ref().unwrap().focused);
|
|
||||||
assert_eq!(state.focus, Focus::Files);
|
|
||||||
assert_eq!(snapshot(state), tree);
|
|
||||||
assert_eq!(
|
|
||||||
(state.file, state.top, state.left_before, state.left_after),
|
|
||||||
(0, 2, 1, 1)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
state
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.map(|row| (row.before, row.after, row.kind))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
rows
|
|
||||||
);
|
|
||||||
editor.handle(Input::Char('\t'));
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
assert_eq!(editor.diff().unwrap().focus, Focus::Before);
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
editor.handle(Input::BackTab);
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
assert_eq!(editor.diff().unwrap().focus, Focus::After);
|
|
||||||
assert!(!editor.diff().unwrap().files.as_ref().unwrap().focused);
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
assert_eq!(editor.diff().unwrap().focus, Focus::Files);
|
assert_eq!(editor.diff().unwrap().focus, Focus::Files);
|
||||||
assert_eq!(snapshot(editor.diff().unwrap()), tree);
|
assert_eq!(
|
||||||
assert_eq!(editor.context().text, original);
|
editor.diff().unwrap().files.as_ref().unwrap().presentation,
|
||||||
assert_eq!(editor.carets(), carets);
|
crate::files::FilePresentation::Docked
|
||||||
assert_eq!(editor.text_revision(), revision);
|
);
|
||||||
|
editor.handle(Input::Ctrl('w'));
|
||||||
|
text(&mut editor, " o");
|
||||||
|
assert_eq!(
|
||||||
|
editor.diff().unwrap().files.as_ref().unwrap().presentation,
|
||||||
|
crate::files::FilePresentation::Floating
|
||||||
|
);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
assert!(!editor.diff().unwrap().files.as_ref().unwrap().searching);
|
|
||||||
editor.handle(Input::Ctrl('e'));
|
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert!(editor.diff().is_some());
|
||||||
|
editor.execute("diff.close");
|
||||||
assert!(editor.diff().is_none());
|
assert!(editor.diff().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1584,7 +1842,7 @@ mod tests {
|
|||||||
let first = choose_pair(&mut editor);
|
let first = choose_pair(&mut editor);
|
||||||
assert!(editor.apply_diff_result(first, Ok(Outcome::Comparison(comparison()))));
|
assert!(editor.apply_diff_result(first, Ok(Outcome::Comparison(comparison()))));
|
||||||
assert_eq!(editor.diff().unwrap().comparison_id, Some(first));
|
assert_eq!(editor.diff().unwrap().comparison_id, Some(first));
|
||||||
editor.handle(Input::Escape);
|
editor.execute("diff.close");
|
||||||
open(&mut editor);
|
open(&mut editor);
|
||||||
assert_eq!(editor.diff().unwrap().comparison_id, None);
|
assert_eq!(editor.diff().unwrap().comparison_id, None);
|
||||||
let second = choose_pair(&mut editor);
|
let second = choose_pair(&mut editor);
|
||||||
@@ -1628,7 +1886,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn native_and_ex_diff_preserve_dirty_buffers_carets_and_undo_and_gate_all_edits() {
|
fn immutable_diff_and_selectors_preserve_dirty_buffers_carets_and_undo() {
|
||||||
let mut editor = editor();
|
let mut editor = editor();
|
||||||
editor
|
editor
|
||||||
.apply(vec![Effect::Replace("original\\nsecond".into())])
|
.apply(vec![Effect::Replace("original\\nsecond".into())])
|
||||||
@@ -1671,6 +1929,8 @@ mod tests {
|
|||||||
buffers
|
buffers
|
||||||
);
|
);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert!(editor.diff().is_some());
|
||||||
|
editor.execute("diff.close");
|
||||||
assert_eq!(editor.mode(), Mode::Normal);
|
assert_eq!(editor.mode(), Mode::Normal);
|
||||||
open(&mut editor);
|
open(&mut editor);
|
||||||
let id = choose_pair(&mut editor);
|
let id = choose_pair(&mut editor);
|
||||||
@@ -1690,6 +1950,8 @@ mod tests {
|
|||||||
assert_eq!(editor.carets(), carets);
|
assert_eq!(editor.carets(), carets);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert!(editor.diff().is_some());
|
||||||
|
editor.execute("diff.close");
|
||||||
editor.handle(Input::Char('u'));
|
editor.handle(Input::Char('u'));
|
||||||
assert_eq!(editor.context().text, "original\\nsecond");
|
assert_eq!(editor.context().text, "original\\nsecond");
|
||||||
}
|
}
|
||||||
@@ -1724,6 +1986,8 @@ mod tests {
|
|||||||
before: "Working".into(),
|
before: "Working".into(),
|
||||||
after: "Working".into(),
|
after: "Working".into(),
|
||||||
files: vec![],
|
files: vec![],
|
||||||
|
root: PathBuf::new(),
|
||||||
|
editable_paths: BTreeSet::new(),
|
||||||
}))
|
}))
|
||||||
));
|
));
|
||||||
assert_eq!(editor.diff().unwrap().phase, Phase::View);
|
assert_eq!(editor.diff().unwrap().phase, Phase::View);
|
||||||
@@ -1734,6 +1998,121 @@ mod tests {
|
|||||||
assert_eq!(editor.diff().unwrap().top, 0);
|
assert_eq!(editor.diff().unwrap().top, 0);
|
||||||
assert_eq!(editor.diff().unwrap().file, 0);
|
assert_eq!(editor.diff().unwrap().file, 0);
|
||||||
editor.handle(Input::Escape);
|
editor.handle(Input::Escape);
|
||||||
|
assert!(editor.diff().is_some());
|
||||||
|
editor.execute("diff.close");
|
||||||
assert!(editor.diff().is_none());
|
assert!(editor.diff().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn live_state(before: Vec<String>, after: Vec<String>, eof: bool) -> DiffState {
|
||||||
|
let mut state = DiffState::new();
|
||||||
|
state.phase = Phase::View;
|
||||||
|
state.focus = Focus::After;
|
||||||
|
state.after = Some(revision(
|
||||||
|
RevisionTarget::Working,
|
||||||
|
"Working",
|
||||||
|
"",
|
||||||
|
Category::Commits,
|
||||||
|
));
|
||||||
|
state.comparison = Some(Comparison {
|
||||||
|
root: PathBuf::new(),
|
||||||
|
before: "base".into(),
|
||||||
|
after: "Working".into(),
|
||||||
|
editable_paths: BTreeSet::from([PathBuf::from("file")]),
|
||||||
|
files: vec![ChangedFile {
|
||||||
|
path: "file".into(),
|
||||||
|
old_path: None,
|
||||||
|
status: FileStatus::Modified,
|
||||||
|
hunks: line_hunks(&before, eof, &after, eof),
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
before_eof: eof,
|
||||||
|
after_eof: eof,
|
||||||
|
notice: None,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
state.files = Some(FilePicker::from_paths(
|
||||||
|
PathBuf::new(),
|
||||||
|
[(0, PathBuf::from("file"))],
|
||||||
|
));
|
||||||
|
state.align_file();
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn live_reflow_keeps_separate_hunks_expansion_and_caret_after_revert() {
|
||||||
|
let base = (0..100)
|
||||||
|
.map(|row| format!("line {row}"))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let mut changed = base.clone();
|
||||||
|
changed[30] = "first change".into();
|
||||||
|
changed[70] = "second change".into();
|
||||||
|
let mut state = live_state(base.clone(), changed.clone(), true);
|
||||||
|
state.set_context_options(2, 5);
|
||||||
|
changed.push(String::new());
|
||||||
|
state.refresh_after(&changed, 1, 30);
|
||||||
|
assert_eq!(state.comparison.as_ref().unwrap().files[0].hunks.len(), 2);
|
||||||
|
assert!(
|
||||||
|
state
|
||||||
|
.rows
|
||||||
|
.last()
|
||||||
|
.is_some_and(|row| row.after == Some(100) && row.kind == RowKind::Equal)
|
||||||
|
);
|
||||||
|
state.top = state.after_display_row(30).unwrap();
|
||||||
|
state.handle(Input::Char('['));
|
||||||
|
assert!(state.after_display_row(23).is_some());
|
||||||
|
changed.insert(10, "inserted outside excerpts".into());
|
||||||
|
state.refresh_after(&changed, 2, 31);
|
||||||
|
assert!(state.after_display_row(24).is_some());
|
||||||
|
assert_eq!(state.comparison.as_ref().unwrap().files[0].hunks.len(), 3);
|
||||||
|
assert!(
|
||||||
|
state.display_rows.iter().any(
|
||||||
|
|row| matches!(row, DisplayRow::Fold { start, end } if *start < 60 && *end > 40)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
let mut reverted = base;
|
||||||
|
reverted.push(String::new());
|
||||||
|
state.refresh_after(&reverted, 3, 90);
|
||||||
|
assert!(state.comparison.as_ref().unwrap().files[0].hunks.is_empty());
|
||||||
|
assert!(state.rows.iter().all(|row| row.kind == RowKind::Equal));
|
||||||
|
assert!(state.after_display_row(90).is_some());
|
||||||
|
assert_eq!(state.files.as_ref().unwrap().entries().len(), 0);
|
||||||
|
assert_eq!(state.file, 0);
|
||||||
|
reverted[50] = "changed again".into();
|
||||||
|
state.refresh_after(&reverted, 4, 50);
|
||||||
|
assert_eq!(state.files.as_ref().unwrap().entries().len(), 1);
|
||||||
|
assert!(state.after_display_row(50).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn live_empty_and_eof_rows_match_buffer_without_false_eof_highlights() {
|
||||||
|
let mut state = live_state(vec!["same".into()], vec!["changed".into()], true);
|
||||||
|
state.refresh_after(&["same".into(), "".into()], 1, 1);
|
||||||
|
assert!(state.comparison.as_ref().unwrap().files[0].hunks.is_empty());
|
||||||
|
assert_eq!(state.rows.len(), 2);
|
||||||
|
assert!(state.rows.iter().all(|row| row.kind == RowKind::Equal));
|
||||||
|
assert!(state.after_display_row(1).is_some());
|
||||||
|
state.refresh_after(&["same".into()], 2, 0);
|
||||||
|
assert_eq!(state.rows[0].kind, RowKind::Changed);
|
||||||
|
assert!(
|
||||||
|
state.comparison.as_ref().unwrap().files[0]
|
||||||
|
.notice
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("After missing")
|
||||||
|
);
|
||||||
|
state.refresh_after(&["".into()], 3, 0);
|
||||||
|
assert!(state.after_display_row(0).is_some());
|
||||||
|
assert_eq!(state.comparison.as_ref().unwrap().files[0].after, [""]);
|
||||||
|
let mut empty = live_state(vec![], vec!["text".into()], false);
|
||||||
|
empty.refresh_after(&["".into()], 1, 0);
|
||||||
|
assert!(empty.comparison.as_ref().unwrap().files[0].hunks.is_empty());
|
||||||
|
assert_eq!(empty.rows.len(), 1);
|
||||||
|
assert_eq!(empty.rows[0].kind, RowKind::Equal);
|
||||||
|
assert_eq!(empty.after_display_row(0), Some(0));
|
||||||
|
empty.after.as_mut().unwrap().target = RevisionTarget::Commit("historic".into());
|
||||||
|
empty.refresh_after(&["must not apply".into()], 2, 0);
|
||||||
|
assert_eq!(empty.comparison.as_ref().unwrap().files[0].after, [""]);
|
||||||
|
empty.handle(Input::Escape);
|
||||||
|
assert_eq!(empty.phase, Phase::View);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+719
-55
File diff suppressed because it is too large
Load Diff
+67
-58
@@ -165,10 +165,10 @@ impl FilePicker {
|
|||||||
Ok(Self::from_nodes(root, nodes, presentation, view, warning))
|
Ok(Self::from_nodes(root, nodes, presentation, view, warning))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the changed-path catalog without consulting the working tree.
|
/// Builds a changed-path catalog, retaining each path's comparison index.
|
||||||
pub fn from_paths(root: PathBuf, paths: impl IntoIterator<Item = PathBuf>) -> Self {
|
pub fn from_paths(root: PathBuf, paths: impl IntoIterator<Item = (usize, PathBuf)>) -> Self {
|
||||||
let mut catalog = HashMap::new();
|
let mut catalog = HashMap::new();
|
||||||
for (index, path) in paths.into_iter().enumerate() {
|
for (index, path) in paths {
|
||||||
for parent in path
|
for parent in path
|
||||||
.ancestors()
|
.ancestors()
|
||||||
.skip(1)
|
.skip(1)
|
||||||
@@ -719,63 +719,69 @@ impl FilePicker {
|
|||||||
|
|
||||||
pub(crate) fn refresh(&mut self) {
|
pub(crate) fn refresh(&mut self) {
|
||||||
match Self::scan(self.root.clone(), self.presentation, self.view) {
|
match Self::scan(self.root.clone(), self.presentation, self.view) {
|
||||||
Ok(mut replacement) => {
|
Ok(replacement) => self.replace_catalog(replacement),
|
||||||
let by_path: HashMap<_, _> = replacement
|
|
||||||
.nodes
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, node)| (node.path.clone(), index))
|
|
||||||
.collect();
|
|
||||||
let surviving = |node: usize| {
|
|
||||||
let mut path = self.nodes[node].path.as_path();
|
|
||||||
loop {
|
|
||||||
if let Some(&node) = by_path.get(path) {
|
|
||||||
return Some(node);
|
|
||||||
}
|
|
||||||
path = path.parent()?;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
replacement.expanded = self
|
|
||||||
.expanded
|
|
||||||
.iter()
|
|
||||||
.filter_map(|&node| {
|
|
||||||
by_path
|
|
||||||
.get(&self.nodes[node].path)
|
|
||||||
.copied()
|
|
||||||
.filter(|&node| replacement.nodes[node].is_dir)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
replacement.filter_collapsed = self
|
|
||||||
.filter_collapsed
|
|
||||||
.iter()
|
|
||||||
.filter_map(|&node| {
|
|
||||||
by_path
|
|
||||||
.get(&self.nodes[node].path)
|
|
||||||
.copied()
|
|
||||||
.filter(|&node| replacement.nodes[node].is_dir)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
replacement.saved_selection =
|
|
||||||
self.saved_selection.map(|node| node.and_then(surviving));
|
|
||||||
replacement.filtered_selection =
|
|
||||||
self.filtered_selection.map(|node| node.and_then(surviving));
|
|
||||||
replacement.query = self.query.clone();
|
|
||||||
replacement.focused = self.focused;
|
|
||||||
replacement.view = self.view;
|
|
||||||
replacement.searching = self.searching;
|
|
||||||
replacement.tree_searching = self.tree_searching;
|
|
||||||
let selected = self
|
|
||||||
.selected_node()
|
|
||||||
.or(self.filtered_selection[self.view.index()])
|
|
||||||
.or(self.saved_selection[self.view.index()])
|
|
||||||
.and_then(surviving);
|
|
||||||
replacement.project(selected, false);
|
|
||||||
replacement.remember_selection(false);
|
|
||||||
*self = replacement;
|
|
||||||
}
|
|
||||||
Err(error) => self.error = Some(format!("Refresh failed: {error}")),
|
Err(error) => self.error = Some(format!("Refresh failed: {error}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn replace_paths(&mut self, paths: impl IntoIterator<Item = (usize, PathBuf)>) {
|
||||||
|
self.replace_catalog(Self::from_paths(self.root.clone(), paths));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_catalog(&mut self, mut replacement: Self) {
|
||||||
|
replacement.presentation = self.presentation;
|
||||||
|
let by_path: HashMap<_, _> = replacement
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, node)| (node.path.clone(), index))
|
||||||
|
.collect();
|
||||||
|
let surviving = |node: usize| {
|
||||||
|
let mut path = self.nodes[node].path.as_path();
|
||||||
|
loop {
|
||||||
|
if let Some(&node) = by_path.get(path) {
|
||||||
|
return Some(node);
|
||||||
|
}
|
||||||
|
path = path.parent()?;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
replacement.expanded = self
|
||||||
|
.expanded
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&node| {
|
||||||
|
by_path
|
||||||
|
.get(&self.nodes[node].path)
|
||||||
|
.copied()
|
||||||
|
.filter(|&node| replacement.nodes[node].is_dir)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
replacement.filter_collapsed = self
|
||||||
|
.filter_collapsed
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&node| {
|
||||||
|
by_path
|
||||||
|
.get(&self.nodes[node].path)
|
||||||
|
.copied()
|
||||||
|
.filter(|&node| replacement.nodes[node].is_dir)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
replacement.saved_selection = self.saved_selection.map(|node| node.and_then(surviving));
|
||||||
|
replacement.filtered_selection =
|
||||||
|
self.filtered_selection.map(|node| node.and_then(surviving));
|
||||||
|
replacement.query = self.query.clone();
|
||||||
|
replacement.focused = self.focused;
|
||||||
|
replacement.view = self.view;
|
||||||
|
replacement.searching = self.searching;
|
||||||
|
replacement.tree_searching = self.tree_searching;
|
||||||
|
let selected = self
|
||||||
|
.selected_node()
|
||||||
|
.or(self.filtered_selection[self.view.index()])
|
||||||
|
.or(self.saved_selection[self.view.index()])
|
||||||
|
.and_then(surviving);
|
||||||
|
replacement.project(selected, false);
|
||||||
|
replacement.remember_selection(false);
|
||||||
|
*self = replacement;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -786,7 +792,10 @@ mod tests {
|
|||||||
fn virtual_catalog_compacts_and_retains_file_directory_collisions() {
|
fn virtual_catalog_compacts_and_retains_file_directory_collisions() {
|
||||||
let mut picker = FilePicker::from_paths(
|
let mut picker = FilePicker::from_paths(
|
||||||
PathBuf::new(),
|
PathBuf::new(),
|
||||||
["x", "x/y", "src/deep/deleted.rs", "src/deep/deleted.rs"].map(PathBuf::from),
|
["x", "x/y", "src/deep/deleted.rs", "src/deep/deleted.rs"]
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
picker
|
picker
|
||||||
|
|||||||
+5
-3
@@ -40,10 +40,12 @@ Commands: :w [PATH], :q, :q!, :wq [PATH], :plugins, :PLUGIN [ARGS]
|
|||||||
Buffers: :edit PATH, :buffers, :buffer N, :bnext, :bprev, :bdelete[!] [N]
|
Buffers: :edit PATH, :buffers, :buffer N, :bnext, :bprev, :bdelete[!] [N]
|
||||||
:q refuses any dirty buffer; :wq saves active and quits only if all are clean
|
:q refuses any dirty buffer; :wq saves active and quits only if all are clean
|
||||||
Markdown links: :follow_link (primary caret; local files only)
|
Markdown links: :follow_link (primary caret; local files only)
|
||||||
Diff: :diff (Normal); choose Before then After; Working checkout means disk, not unsaved buffers
|
Diff: :diff (Normal); choose Before then After; Working checkout After edits live unsaved buffers
|
||||||
Tab/Shift+Tab categories/focus; type to search IDs/refs; arrows navigate/scroll; Esc back/close
|
Before and historical/remote After stay read-only; Tab/Shift+Tab categories/Normal focus
|
||||||
|
Type to search IDs/refs; Normal [/] expands excerpts; Insert brackets remain literal text
|
||||||
|
:diff.close exits explicitly; Esc cancels modes/prompts/filtering without closing the diff
|
||||||
Remote refs/history load into temporary comparison repos without changing active refs/checkout
|
Remote refs/history load into temporary comparison repos without changing active refs/checkout
|
||||||
Changed-file tree: Ctrl+e hides/shows; A added, M modified, D removed, R renamed (old path shown)
|
Changed files: normal picker/explorer bindings, Ctrl+w close; A/M/D/R status and rename paths
|
||||||
|
|
||||||
Ruby config: $XDG_CONFIG_HOME/vamp/config.rb or ~/.config/vamp/config.rb
|
Ruby config: $XDG_CONFIG_HOME/vamp/config.rb or ~/.config/vamp/config.rb
|
||||||
Set VAMP_RUBY to choose the Ruby executable.
|
Set VAMP_RUBY to choose the Ruby executable.
|
||||||
|
|||||||
+87
-68
@@ -1,7 +1,7 @@
|
|||||||
//! Read-only active-repository discovery and isolated revision comparison.
|
//! Read-only active-repository discovery and isolated revision comparison.
|
||||||
use crate::diff::{
|
use crate::diff::{
|
||||||
Catalog, Category, ChangedFile, Comparison, FileStatus, Hunk, RepoKind, Revision,
|
Catalog, Category, ChangedFile, Comparison, FileStatus, RepoKind, Revision, RevisionTarget,
|
||||||
RevisionTarget,
|
line_hunks,
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
@@ -934,7 +934,7 @@ impl Repository {
|
|||||||
}
|
}
|
||||||
Ok(snapshot)
|
Ok(snapshot)
|
||||||
}
|
}
|
||||||
fn working_snapshot(&self) -> Result<Snapshot, String> {
|
fn working_snapshot(&self, buffers: &[(PathBuf, String)]) -> Result<Snapshot, String> {
|
||||||
let mut tracked = BTreeSet::new();
|
let mut tracked = BTreeSet::new();
|
||||||
let mut submodules = BTreeSet::new();
|
let mut submodules = BTreeSet::new();
|
||||||
if self.kind == RepoKind::Git {
|
if self.kind == RepoKind::Git {
|
||||||
@@ -1017,6 +1017,32 @@ impl Repository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let overlays: BTreeMap<_, _> = buffers
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(path, text)| {
|
||||||
|
let relative = path.strip_prefix(&self.root).ok()?;
|
||||||
|
if safe_path(relative).is_err()
|
||||||
|
|| !path.is_absolute()
|
||||||
|
|| text.as_bytes().contains(&0)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Reject symlinks in every component, not just the final file.
|
||||||
|
let mut full = self.root.clone();
|
||||||
|
for component in relative.components() {
|
||||||
|
full.push(component);
|
||||||
|
let metadata = fs::symlink_metadata(&full).ok()?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs::symlink_metadata(&full)
|
||||||
|
.ok()?
|
||||||
|
.is_file()
|
||||||
|
.then_some((relative.to_path_buf(), text))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
paths.extend(overlays.keys().cloned());
|
||||||
let mut total = 0;
|
let mut total = 0;
|
||||||
let mut snapshot = BTreeMap::new();
|
let mut snapshot = BTreeMap::new();
|
||||||
for path in paths {
|
for path in paths {
|
||||||
@@ -1110,6 +1136,20 @@ impl Repository {
|
|||||||
path.display()
|
path.display()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
let bytes = if !bytes.contains(&0)
|
||||||
|
&& std::str::from_utf8(&bytes).is_ok()
|
||||||
|
&& let Some(text) = overlays.get(&path)
|
||||||
|
{
|
||||||
|
if text.len() > FILE_LIMIT {
|
||||||
|
return Err(format!(
|
||||||
|
"{} exceeds the 16 MiB comparison file limit",
|
||||||
|
path.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
text.as_bytes().to_vec()
|
||||||
|
} else {
|
||||||
|
bytes
|
||||||
|
};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
let executable = {
|
let executable = {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
@@ -1146,16 +1186,24 @@ impl Repository {
|
|||||||
}
|
}
|
||||||
fn snapshot(&mut self, target: &RevisionTarget) -> Result<Snapshot, String> {
|
fn snapshot(&mut self, target: &RevisionTarget) -> Result<Snapshot, String> {
|
||||||
if *target == RevisionTarget::Working {
|
if *target == RevisionTarget::Working {
|
||||||
self.working_snapshot()
|
self.working_snapshot(&[])
|
||||||
} else {
|
} else {
|
||||||
let (store, id) = self.resolve(target)?;
|
let (store, id) = self.resolve(target)?;
|
||||||
self.commit_snapshot(&store, &id)
|
self.commit_snapshot(&store, &id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn compare(&mut self, before: &Revision, after: &Revision) -> Result<Comparison, String> {
|
pub fn compare(
|
||||||
|
&mut self,
|
||||||
|
before: &Revision,
|
||||||
|
after: &Revision,
|
||||||
|
buffers: &[(PathBuf, String)],
|
||||||
|
) -> Result<Comparison, String> {
|
||||||
let left = self.snapshot(&before.target)?;
|
let left = self.snapshot(&before.target)?;
|
||||||
let right = if before.target == after.target {
|
let working_after = after.target == RevisionTarget::Working;
|
||||||
|
let right = if before.target == after.target && (!working_after || buffers.is_empty()) {
|
||||||
None
|
None
|
||||||
|
} else if working_after {
|
||||||
|
Some(self.working_snapshot(buffers)?)
|
||||||
} else {
|
} else {
|
||||||
Some(self.snapshot(&after.target)?)
|
Some(self.snapshot(&after.target)?)
|
||||||
};
|
};
|
||||||
@@ -1199,15 +1247,36 @@ impl Repository {
|
|||||||
removed.insert(j);
|
removed.insert(j);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let files = files
|
let files: Vec<_> = files
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter_map(|(i, f)| (!removed.contains(&i)).then_some(f))
|
.filter_map(|(i, f)| (!removed.contains(&i)).then_some(f))
|
||||||
.collect();
|
.collect();
|
||||||
|
let editable_paths = if working_after {
|
||||||
|
files
|
||||||
|
.iter()
|
||||||
|
.filter(|file| {
|
||||||
|
right.get(&file.path).is_some_and(|data| {
|
||||||
|
matches!(data.mode.as_str(), "100644" | "100755")
|
||||||
|
&& !data.bytes.contains(&0)
|
||||||
|
&& std::str::from_utf8(&data.bytes).is_ok()
|
||||||
|
&& file
|
||||||
|
.notice
|
||||||
|
.as_deref()
|
||||||
|
.is_none_or(|notice| !notice.contains("Binary or non-UTF-8"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(|file| file.path.clone())
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
BTreeSet::new()
|
||||||
|
};
|
||||||
Ok(Comparison {
|
Ok(Comparison {
|
||||||
before: before.label.clone(),
|
before: before.label.clone(),
|
||||||
after: after.label.clone(),
|
after: after.label.clone(),
|
||||||
files,
|
files,
|
||||||
|
root: self.root.clone(),
|
||||||
|
editable_paths,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn changed_file(
|
fn changed_file(
|
||||||
@@ -1253,38 +1322,15 @@ impl Repository {
|
|||||||
eof_label(after)
|
eof_label(after)
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let before_path = self.temporary.0.join("before");
|
let before_lines = lines(a);
|
||||||
let after_path = self.temporary.0.join("after");
|
let after_lines = lines(b);
|
||||||
fs::write(&before_path, a).map_err(|e| e.to_string())?;
|
let hunks = line_hunks(
|
||||||
fs::write(&after_path, b).map_err(|e| e.to_string())?;
|
&before_lines,
|
||||||
let mut cmd = Command::new("git");
|
a.ends_with(b"\n"),
|
||||||
cmd.args([
|
&after_lines,
|
||||||
"--no-pager",
|
b.ends_with(b"\n"),
|
||||||
"diff",
|
);
|
||||||
"--no-index",
|
(before_lines, after_lines, hunks)
|
||||||
"--no-color",
|
|
||||||
"--no-ext-diff",
|
|
||||||
"--no-textconv",
|
|
||||||
"--text",
|
|
||||||
"--unified=0",
|
|
||||||
"--",
|
|
||||||
])
|
|
||||||
.arg(&before_path)
|
|
||||||
.arg(&after_path)
|
|
||||||
.current_dir(&self.temporary.0);
|
|
||||||
let output = run(cmd, vec![], &self.cancelled)?;
|
|
||||||
if !matches!(output.code, Some(0 | 1)) {
|
|
||||||
return Err(format!(
|
|
||||||
"Cannot calculate diff hunks: {}",
|
|
||||||
String::from_utf8_lossy(&output.stderr)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let patch = text(output.stdout)?;
|
|
||||||
let mut hunks = vec![];
|
|
||||||
for line in patch.lines().filter(|l| l.starts_with("@@ ")) {
|
|
||||||
hunks.push(parse_hunk(line)?);
|
|
||||||
}
|
|
||||||
(lines(a), lines(b), hunks)
|
|
||||||
};
|
};
|
||||||
notices.dedup();
|
notices.dedup();
|
||||||
Ok(ChangedFile {
|
Ok(ChangedFile {
|
||||||
@@ -1293,6 +1339,8 @@ impl Repository {
|
|||||||
status,
|
status,
|
||||||
before: before_lines,
|
before: before_lines,
|
||||||
after: after_lines,
|
after: after_lines,
|
||||||
|
before_eof: a.ends_with(b"\n"),
|
||||||
|
after_eof: b.ends_with(b"\n"),
|
||||||
hunks,
|
hunks,
|
||||||
notice: if notices.is_empty() {
|
notice: if notices.is_empty() {
|
||||||
None
|
None
|
||||||
@@ -1318,35 +1366,6 @@ fn eof_label(file: Option<&FileData>) -> &'static str {
|
|||||||
Some(_) => "missing",
|
Some(_) => "missing",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn parse_hunk(line: &str) -> Result<Hunk, String> {
|
|
||||||
fn range(value: &str) -> Result<(usize, usize), String> {
|
|
||||||
let (start, len) = value[1..].split_once(',').unwrap_or((&value[1..], "1"));
|
|
||||||
let start: usize = start.parse().map_err(|_| "Invalid diff hunk start")?;
|
|
||||||
let len: usize = len.parse().map_err(|_| "Invalid diff hunk length")?;
|
|
||||||
Ok((
|
|
||||||
if len == 0 {
|
|
||||||
start
|
|
||||||
} else {
|
|
||||||
start
|
|
||||||
.checked_sub(1)
|
|
||||||
.ok_or("Invalid nonempty diff hunk start")?
|
|
||||||
},
|
|
||||||
len,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
let mut fields = line.split_whitespace();
|
|
||||||
if fields.next() != Some("@@") {
|
|
||||||
return Err("Invalid diff hunk header".into());
|
|
||||||
}
|
|
||||||
let (before_start, before_len) = range(fields.next().ok_or("Missing Before hunk range")?)?;
|
|
||||||
let (after_start, after_len) = range(fields.next().ok_or("Missing After hunk range")?)?;
|
|
||||||
Ok(Hunk {
|
|
||||||
before_start,
|
|
||||||
before_len,
|
|
||||||
after_start,
|
|
||||||
after_len,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(test, unix))]
|
#[cfg(all(test, unix))]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|||||||
+14
@@ -933,8 +933,19 @@ end
|
|||||||
config.bind "V", config.core.buffer_previous
|
config.bind "V", config.core.buffer_previous
|
||||||
config.bind "D", config.core.buffer_delete
|
config.bind "D", config.core.buffer_delete
|
||||||
config.bind "Z", config.core.buffer_force_delete
|
config.bind "Z", config.core.buffer_force_delete
|
||||||
|
config.bind "R", config.core.diff
|
||||||
|
config.bind "T", config.core.diff.close
|
||||||
|
raise "mutable diff actions" unless config.core.frozen? && config.core.diff.frozen? &&
|
||||||
|
config.core.diff.close.frozen? && config.core.diff.name.frozen? &&
|
||||||
|
config.core.diff.close.name.frozen?
|
||||||
end"#,
|
end"#,
|
||||||
);
|
);
|
||||||
|
let mut review = EditorSession::open(None, vec!["text".into()], Some(&config)).unwrap();
|
||||||
|
review.handle(Input::Char('R'));
|
||||||
|
review.handle(Input::Escape);
|
||||||
|
assert!(review.editor().diff().is_some());
|
||||||
|
review.handle(Input::Char('T'));
|
||||||
|
assert!(review.editor().diff().is_none());
|
||||||
for (key, dirty, quit, saved) in [
|
for (key, dirty, quit, saved) in [
|
||||||
('Q', false, true, false),
|
('Q', false, true, false),
|
||||||
('Q', true, false, false),
|
('Q', true, false, false),
|
||||||
@@ -1047,6 +1058,9 @@ end
|
|||||||
"config.core.lsp",
|
"config.core.lsp",
|
||||||
"config.core.lsp.hover.tap { |action| action.name = 'core.delete' }",
|
"config.core.lsp.hover.tap { |action| action.name = 'core.delete' }",
|
||||||
"config.core.lsp.tap { |namespace| namespace.define_singleton_method(:bogus) { namespace.hover } }.bogus",
|
"config.core.lsp.tap { |namespace| namespace.define_singleton_method(:bogus) { namespace.hover } }.bogus",
|
||||||
|
"config.core.diff.tap { |action| action.name = 'core.delete' }",
|
||||||
|
"config.core.diff.tap { |action| action.define_singleton_method(:bogus) { action.close } }.bogus",
|
||||||
|
"config.core.diff.close.tap { |action| action.name = 'core.delete' }",
|
||||||
] {
|
] {
|
||||||
let invalid = fixture.file(
|
let invalid = fixture.file(
|
||||||
"invalid_action.rb",
|
"invalid_action.rb",
|
||||||
|
|||||||
+12
-11
@@ -59,13 +59,13 @@ module Vamp
|
|||||||
Core = Module.new
|
Core = Module.new
|
||||||
|
|
||||||
# @param entries [Array<Hash{String => String, nil}>] action name and optional Ex alias descriptors
|
# @param entries [Array<Hash{String => String, nil}>] action name and optional Ex alias descriptors
|
||||||
# @return [Array<Module>] frozen action namespaces
|
# @return [Array<Module, Vamp::Action>] frozen action namespaces and leaves
|
||||||
def self.install_actions(entries)
|
def self.install_actions(entries)
|
||||||
raise TypeError, "core action catalog must be an Array" unless entries.is_a?(Array)
|
raise TypeError, "core action catalog must be an Array" unless entries.is_a?(Array)
|
||||||
|
|
||||||
namespaces = [Core]
|
namespaces = [Core]
|
||||||
aliases = {}
|
aliases = {}
|
||||||
entries.each do |entry|
|
entries.sort_by { |entry| entry.fetch("name").count(".") }.each do |entry|
|
||||||
raise TypeError, "core action descriptor must be a Hash" unless entry.is_a?(Hash)
|
raise TypeError, "core action descriptor must be a Hash" unless entry.is_a?(Hash)
|
||||||
|
|
||||||
install_action(entry.fetch("name"), namespaces)
|
install_action(entry.fetch("name"), namespaces)
|
||||||
@@ -139,7 +139,7 @@ module Vamp
|
|||||||
end
|
end
|
||||||
|
|
||||||
# @param name [String]
|
# @param name [String]
|
||||||
# @param namespaces [Array<Module>]
|
# @param namespaces [Array<Module, Vamp::Action>]
|
||||||
# @return [Symbol] the installed action method name
|
# @return [Symbol] the installed action method name
|
||||||
def self.install_action(name, namespaces)
|
def self.install_action(name, namespaces)
|
||||||
name = action_name(name)
|
name = action_name(name)
|
||||||
@@ -147,7 +147,8 @@ module Vamp
|
|||||||
namespace = parts[0...-1].reduce(Core) { |parent, part| action_namespace(parent, part, namespaces, name) }
|
namespace = parts[0...-1].reduce(Core) { |parent, part| action_namespace(parent, part, namespaces, name) }
|
||||||
leaf = parts.last
|
leaf = parts.last
|
||||||
available_action!(namespace, leaf, name)
|
available_action!(namespace, leaf, name)
|
||||||
action = Action.send(:new, name.freeze).freeze
|
action = Action.send(:new, name.freeze)
|
||||||
|
namespaces << action
|
||||||
namespace.define_singleton_method(leaf) { action }
|
namespace.define_singleton_method(leaf) { action }
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -160,23 +161,23 @@ module Vamp
|
|||||||
name
|
name
|
||||||
end
|
end
|
||||||
|
|
||||||
# @param parent [Module]
|
# @param parent [Module, Vamp::Action]
|
||||||
# @param part [String]
|
# @param part [String]
|
||||||
# @param namespaces [Array<Module>]
|
# @param namespaces [Array<Module, Vamp::Action>]
|
||||||
# @param name [String]
|
# @param name [String]
|
||||||
# @return [Module]
|
# @return [Module, Vamp::Action]
|
||||||
def self.action_namespace(parent, part, namespaces, name)
|
def self.action_namespace(parent, part, namespaces, name)
|
||||||
return new_action_namespace(parent, part, namespaces) unless parent.singleton_methods(false).include?(part.to_sym)
|
return new_action_namespace(parent, part, namespaces) unless parent.singleton_methods(false).include?(part.to_sym)
|
||||||
|
|
||||||
child = parent.public_send(part)
|
child = parent.public_send(part)
|
||||||
raise ArgumentError, "conflicting core action namespace: #{name}" unless child.is_a?(Module)
|
raise ArgumentError, "conflicting core action namespace: #{name}" unless child.is_a?(Module) || child.is_a?(Action)
|
||||||
|
|
||||||
child
|
child
|
||||||
end
|
end
|
||||||
|
|
||||||
# @param parent [Module]
|
# @param parent [Module, Vamp::Action]
|
||||||
# @param part [String]
|
# @param part [String]
|
||||||
# @param namespaces [Array<Module>]
|
# @param namespaces [Array<Module, Vamp::Action>]
|
||||||
# @return [Module]
|
# @return [Module]
|
||||||
def self.new_action_namespace(parent, part, namespaces)
|
def self.new_action_namespace(parent, part, namespaces)
|
||||||
child = Module.new
|
child = Module.new
|
||||||
@@ -185,7 +186,7 @@ module Vamp
|
|||||||
child
|
child
|
||||||
end
|
end
|
||||||
|
|
||||||
# @param namespace [Module]
|
# @param namespace [Module, Vamp::Action]
|
||||||
# @param leaf [String]
|
# @param leaf [String]
|
||||||
# @param name [String]
|
# @param name [String]
|
||||||
# @return [nil]
|
# @return [nil]
|
||||||
|
|||||||
+151
-10
@@ -11,7 +11,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
diff::{Operation as DiffOperation, Outcome as DiffOutcome},
|
diff::{Focus, Operation as DiffOperation, Outcome as DiffOutcome},
|
||||||
editor::{Cursor, Editor, Effect, Input, Invocation, Mode},
|
editor::{Cursor, Editor, Effect, Input, Invocation, Mode},
|
||||||
lsp::Lsp,
|
lsp::Lsp,
|
||||||
plugin::{
|
plugin::{
|
||||||
@@ -71,8 +71,12 @@ impl DiffWorker {
|
|||||||
DiffOperation::FetchRemote(remote) => {
|
DiffOperation::FetchRemote(remote) => {
|
||||||
repository.fetch_remote(&remote).map(DiffOutcome::Catalog)
|
repository.fetch_remote(&remote).map(DiffOutcome::Catalog)
|
||||||
}
|
}
|
||||||
DiffOperation::Compare { before, after } => repository
|
DiffOperation::Compare {
|
||||||
.compare(&before, &after)
|
before,
|
||||||
|
after,
|
||||||
|
buffers,
|
||||||
|
} => repository
|
||||||
|
.compare(&before, &after, &buffers)
|
||||||
.map(DiffOutcome::Comparison),
|
.map(DiffOutcome::Comparison),
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
@@ -254,6 +258,10 @@ impl EditorSession {
|
|||||||
&self.editor
|
&self.editor
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn scroll_diff(&mut self, focus: Focus, down: bool) {
|
||||||
|
self.editor.scroll_diff(focus, down);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn handle(&mut self, input: Input) {
|
pub fn handle(&mut self, input: Input) {
|
||||||
self.cancel_pending_popup_request();
|
self.cancel_pending_popup_request();
|
||||||
let invocation = self.editor.handle(input);
|
let invocation = self.editor.handle(input);
|
||||||
@@ -386,6 +394,7 @@ impl EditorSession {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let context = self.editor.context();
|
let context = self.editor.context();
|
||||||
|
let read_only = self.editor.diff().is_some() && !self.editor.diff_editing();
|
||||||
let result = match self.plugins.get_mut(&invocation.plugin) {
|
let result = match self.plugins.get_mut(&invocation.plugin) {
|
||||||
Some(plugin) if plugin.is_async() => {
|
Some(plugin) if plugin.is_async() => {
|
||||||
let requests = self.requests.entry(invocation.plugin.clone()).or_default();
|
let requests = self.requests.entry(invocation.plugin.clone()).or_default();
|
||||||
@@ -402,7 +411,18 @@ impl EditorSession {
|
|||||||
}
|
}
|
||||||
Some(plugin) => plugin
|
Some(plugin) => plugin
|
||||||
.invoke(&invocation.command, &invocation.args, &context)
|
.invoke(&invocation.command, &invocation.args, &context)
|
||||||
.and_then(|effects| self.editor.apply(effects)),
|
.and_then(|effects| {
|
||||||
|
if read_only
|
||||||
|
&& effects
|
||||||
|
.iter()
|
||||||
|
.any(|effect| matches!(effect, Effect::Insert(_) | Effect::Replace(_)))
|
||||||
|
{
|
||||||
|
self.editor.set_message("Diff pane is read-only");
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
self.editor.apply(effects)
|
||||||
|
}
|
||||||
|
}),
|
||||||
None => Err("plugin host is unavailable".into()),
|
None => Err("plugin host is unavailable".into()),
|
||||||
};
|
};
|
||||||
if let Err(error) = result {
|
if let Err(error) = result {
|
||||||
@@ -555,7 +575,7 @@ impl EditorSession {
|
|||||||
request_id: Option<u64>,
|
request_id: Option<u64>,
|
||||||
source: InvocationSource,
|
source: InvocationSource,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
if self.editor.diff().is_some() {
|
if self.editor.diff().is_some() && !self.editor.diff_editing() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
self.editor.buffer_id() == source.buffer_id
|
self.editor.buffer_id() == source.buffer_id
|
||||||
@@ -791,6 +811,7 @@ impl EditorSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.editor.refresh_live_diff();
|
||||||
Ok(changed)
|
Ok(changed)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -807,10 +828,7 @@ impl EditorSession {
|
|||||||
let Some(source) = source else {
|
let Some(source) = source else {
|
||||||
return Err("plugin response has an unknown invocation ID".into());
|
return Err("plugin response has an unknown invocation ID".into());
|
||||||
};
|
};
|
||||||
if !self.source_is_current(source)
|
if !self.source_is_current(source) || self.editor.buffer_id() != source.buffer_id {
|
||||||
|| self.editor.buffer_id() != source.buffer_id
|
|
||||||
|| self.editor.diff().is_some()
|
|
||||||
{
|
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
if effects
|
if effects
|
||||||
@@ -826,6 +844,9 @@ impl EditorSession {
|
|||||||
}
|
}
|
||||||
return Ok(changed);
|
return Ok(changed);
|
||||||
}
|
}
|
||||||
|
if self.editor.diff().is_some() && !self.editor.diff_editing() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
let changed = !effects.is_empty();
|
let changed = !effects.is_empty();
|
||||||
self.editor.apply(effects)?;
|
self.editor.apply(effects)?;
|
||||||
Ok(changed)
|
Ok(changed)
|
||||||
@@ -3314,11 +3335,131 @@ end
|
|||||||
});
|
});
|
||||||
assert_eq!(session.editor().context().text, "original");
|
assert_eq!(session.editor().context().text, "original");
|
||||||
assert_eq!(fs::read_to_string(&source).unwrap(), "original");
|
assert_eq!(fs::read_to_string(&source).unwrap(), "original");
|
||||||
session.handle(Input::Escape);
|
session.execute("diff.close");
|
||||||
session.execute("ping");
|
session.execute("ping");
|
||||||
drain_until(&mut session, |session| {
|
drain_until(&mut session, |session| {
|
||||||
session.editor().message() == "still alive"
|
session.editor().message() == "still alive"
|
||||||
});
|
});
|
||||||
assert_eq!(session.editor().context().text, "original");
|
assert_eq!(session.editor().context().text, "original");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_responses_edit_only_current_bound_working_after_and_refresh_projection() {
|
||||||
|
use crate::diff::{
|
||||||
|
Catalog, Category, ChangedFile, Comparison, FileStatus, RepoKind, Revision,
|
||||||
|
RevisionTarget,
|
||||||
|
};
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
fixture.file("buffer.txt", "base");
|
||||||
|
let mut session = fixture.open("");
|
||||||
|
session.editor.execute("diff");
|
||||||
|
let (id, _) = session.editor.take_diff_request().unwrap();
|
||||||
|
let revision = |target, label: &str| Revision {
|
||||||
|
target,
|
||||||
|
label: label.into(),
|
||||||
|
description: String::new(),
|
||||||
|
category: Category::Commits,
|
||||||
|
};
|
||||||
|
session.editor.apply_diff_result(
|
||||||
|
id,
|
||||||
|
Ok(DiffOutcome::Catalog(Catalog {
|
||||||
|
kind: RepoKind::Git,
|
||||||
|
notice: None,
|
||||||
|
entries: vec![
|
||||||
|
revision(RevisionTarget::Commit("base".into()), "base"),
|
||||||
|
revision(RevisionTarget::Working, "Working"),
|
||||||
|
],
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
for input in [Input::Down, Input::Enter, Input::Enter] {
|
||||||
|
session.editor.handle(input);
|
||||||
|
}
|
||||||
|
let (id, _) = session.editor.take_diff_request().unwrap();
|
||||||
|
session.editor.apply_diff_result(
|
||||||
|
id,
|
||||||
|
Ok(DiffOutcome::Comparison(Comparison {
|
||||||
|
root: fixture.0.canonicalize().unwrap(),
|
||||||
|
before: "base".into(),
|
||||||
|
after: "Working".into(),
|
||||||
|
editable_paths: [PathBuf::from("buffer.txt")].into_iter().collect(),
|
||||||
|
files: vec![ChangedFile {
|
||||||
|
path: PathBuf::from("buffer.txt"),
|
||||||
|
old_path: None,
|
||||||
|
status: FileStatus::Modified,
|
||||||
|
before: vec!["base".into()],
|
||||||
|
after: vec!["base".into()],
|
||||||
|
before_eof: false,
|
||||||
|
after_eof: false,
|
||||||
|
hunks: Vec::new(),
|
||||||
|
notice: None,
|
||||||
|
}],
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
session.editor.handle(Input::BackTab);
|
||||||
|
let source = InvocationSource {
|
||||||
|
buffer_id: session.editor.buffer_id(),
|
||||||
|
revision: session.editor.text_revision(),
|
||||||
|
};
|
||||||
|
session
|
||||||
|
.requests
|
||||||
|
.entry("fixture".into())
|
||||||
|
.or_default()
|
||||||
|
.pending
|
||||||
|
.insert(1, source);
|
||||||
|
assert!(
|
||||||
|
session
|
||||||
|
.apply_response("fixture", 1, vec![Effect::Insert("accepted".into())])
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(session.editor.lines(), ["acceptedbase"]);
|
||||||
|
let diff = session.editor.diff().unwrap();
|
||||||
|
assert_eq!(diff.live_revision, Some(session.editor.text_revision()));
|
||||||
|
assert_eq!(
|
||||||
|
diff.comparison.as_ref().unwrap().files[0].after,
|
||||||
|
session.editor.lines()
|
||||||
|
);
|
||||||
|
|
||||||
|
session
|
||||||
|
.requests
|
||||||
|
.get_mut("fixture")
|
||||||
|
.unwrap()
|
||||||
|
.pending
|
||||||
|
.insert(2, source);
|
||||||
|
assert!(
|
||||||
|
!session
|
||||||
|
.apply_response("fixture", 2, vec![Effect::Insert("stale".into())])
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
let current = InvocationSource {
|
||||||
|
buffer_id: session.editor.buffer_id(),
|
||||||
|
revision: session.editor.text_revision(),
|
||||||
|
};
|
||||||
|
session.editor.scroll_diff(Focus::Before, false);
|
||||||
|
session
|
||||||
|
.requests
|
||||||
|
.get_mut("fixture")
|
||||||
|
.unwrap()
|
||||||
|
.pending
|
||||||
|
.insert(3, current);
|
||||||
|
assert!(
|
||||||
|
!session
|
||||||
|
.apply_response("fixture", 3, vec![Effect::Insert("readonly".into())])
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(session.editor.lines(), ["acceptedbase"]);
|
||||||
|
session
|
||||||
|
.requests
|
||||||
|
.get_mut("fixture")
|
||||||
|
.unwrap()
|
||||||
|
.pending
|
||||||
|
.insert(4, current);
|
||||||
|
assert!(
|
||||||
|
session
|
||||||
|
.apply_response("fixture", 4, vec![Effect::Message("allowed".into())])
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(session.editor.message(), "allowed");
|
||||||
|
session.editor.execute("diff.close");
|
||||||
|
assert!(session.editor.dirty());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+512
-251
File diff suppressed because it is too large
Load Diff
+35
-16
@@ -76,7 +76,7 @@ fn type_query(session: &mut EditorSession, text: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn typed_diff_compares_disk_not_unsaved_buffers_and_preserves_undo() {
|
fn typed_diff_edits_unsaved_working_after_and_preserves_undo_on_explicit_close() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
fixture.git(&["init", "-q"]);
|
fixture.git(&["init", "-q"]);
|
||||||
let source = fixture.0.join("repo/buffer.rs");
|
let source = fixture.0.join("repo/buffer.rs");
|
||||||
@@ -128,7 +128,12 @@ fn typed_diff_compares_disk_not_unsaved_buffers_and_preserves_undo() {
|
|||||||
let file = &comparison.files[0];
|
let file = &comparison.files[0];
|
||||||
assert_eq!(file.path, Path::new("buffer.rs"));
|
assert_eq!(file.path, Path::new("buffer.rs"));
|
||||||
assert_eq!(file.before, ["before"]);
|
assert_eq!(file.before, ["before"]);
|
||||||
assert_eq!(file.after, ["after"]);
|
assert_eq!(file.after, ["uafter", ""]);
|
||||||
|
session.handle(Input::Char('\t'));
|
||||||
|
assert_eq!(
|
||||||
|
session.editor().diff().unwrap().focus,
|
||||||
|
vamp::diff::Focus::Before
|
||||||
|
);
|
||||||
for input in [
|
for input in [
|
||||||
Input::Char('i'),
|
Input::Char('i'),
|
||||||
Input::Char('x'),
|
Input::Char('x'),
|
||||||
@@ -137,27 +142,41 @@ fn typed_diff_compares_disk_not_unsaved_buffers_and_preserves_undo() {
|
|||||||
session.handle(input);
|
session.handle(input);
|
||||||
}
|
}
|
||||||
session.handle(Input::Escape);
|
session.handle(Input::Escape);
|
||||||
assert!(
|
assert!(session.editor().diff().is_some());
|
||||||
!session
|
|
||||||
.editor()
|
|
||||||
.diff()
|
|
||||||
.unwrap()
|
|
||||||
.files
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.searching
|
|
||||||
);
|
|
||||||
session.handle(Input::Escape);
|
|
||||||
assert!(session.editor().diff().is_none());
|
|
||||||
assert_eq!(session.editor().context().text, "uafter\n");
|
assert_eq!(session.editor().context().text, "uafter\n");
|
||||||
assert!(session.editor().dirty());
|
|
||||||
assert_eq!(session.editor().cursor(), cursor);
|
assert_eq!(session.editor().cursor(), cursor);
|
||||||
assert_eq!(fs::read_to_string(&source).unwrap(), "after\n");
|
assert_eq!(fs::read_to_string(&source).unwrap(), "after\n");
|
||||||
|
|
||||||
|
session.handle(Input::Char('\t'));
|
||||||
|
assert_eq!(
|
||||||
|
session.editor().diff().unwrap().focus,
|
||||||
|
vamp::diff::Focus::After
|
||||||
|
);
|
||||||
|
for input in [Input::Char('i'), Input::Char('x'), Input::Escape] {
|
||||||
|
session.handle(input);
|
||||||
|
}
|
||||||
|
assert_eq!(session.editor().context().text, "xuafter\n");
|
||||||
|
assert!(session.editor().diff().is_some());
|
||||||
|
session.handle(Input::Char('u'));
|
||||||
|
assert_eq!(session.editor().context().text, "uafter\n");
|
||||||
|
session.handle(Input::Char('U'));
|
||||||
|
assert_eq!(session.editor().context().text, "xuafter\n");
|
||||||
|
session.execute("w");
|
||||||
|
assert_eq!(fs::read_to_string(&source).unwrap(), "xuafter\n");
|
||||||
|
assert!(!session.editor().dirty());
|
||||||
|
session.handle(Input::Char('u'));
|
||||||
|
assert_eq!(session.editor().context().text, "uafter\n");
|
||||||
|
assert!(session.editor().dirty());
|
||||||
|
|
||||||
|
session.execute("diff.close");
|
||||||
|
assert!(session.editor().diff().is_none());
|
||||||
|
assert_eq!(session.editor().context().text, "uafter\n");
|
||||||
session.handle(Input::Char('u'));
|
session.handle(Input::Char('u'));
|
||||||
assert_eq!(session.editor().context().text, "after\n");
|
assert_eq!(session.editor().context().text, "after\n");
|
||||||
|
assert_eq!(fs::read_to_string(&source).unwrap(), "xuafter\n");
|
||||||
session.execute(":diff");
|
session.execute(":diff");
|
||||||
assert!(session.editor().diff().is_some());
|
assert!(session.editor().diff().is_some());
|
||||||
session.handle(Input::Escape);
|
session.execute("diff.close");
|
||||||
session.poll();
|
session.poll();
|
||||||
assert!(session.editor().diff().is_none());
|
assert!(session.editor().diff().is_none());
|
||||||
assert_eq!(fixture.git(&["rev-parse", "HEAD"]), base);
|
assert_eq!(fixture.git(&["rev-parse", "HEAD"]), base);
|
||||||
|
|||||||
+123
-15
@@ -237,9 +237,15 @@ fn git_working_reads_disk_and_handles_ranges_ignored_files_binary_links_and_odd_
|
|||||||
&& r.category == Category::Tags
|
&& r.category == Category::Tags
|
||||||
&& r.target == RevisionTarget::Commit(id.clone())));
|
&& r.target == RevisionTarget::Commit(id.clone())));
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(&revision(&id, RepoKind::Git), &working(RepoKind::Git))
|
.compare(&revision(&id, RepoKind::Git), &working(RepoKind::Git), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let text = changed(&comparison, Path::new("text"));
|
let text = changed(&comparison, Path::new("text"));
|
||||||
|
assert_eq!(comparison.root, fs::canonicalize(&root).unwrap());
|
||||||
|
assert!(comparison.editable_paths.contains(Path::new("text")));
|
||||||
|
assert!(comparison.editable_paths.contains(Path::new("empty-added")));
|
||||||
|
for path in ["binary", "link", "removed", "type-switch"] {
|
||||||
|
assert!(!comparison.editable_paths.contains(Path::new(path)));
|
||||||
|
}
|
||||||
assert_eq!(text.after, ["one", "two", "three"]);
|
assert_eq!(text.after, ["one", "two", "three"]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
(
|
(
|
||||||
@@ -338,15 +344,16 @@ fn git_working_reads_disk_and_handles_ranges_ignored_files_binary_links_and_odd_
|
|||||||
assert_eq!(moved.before, moved.after);
|
assert_eq!(moved.before, moved.after);
|
||||||
assert!(moved.hunks.is_empty());
|
assert!(moved.hunks.is_empty());
|
||||||
let reverse = repository
|
let reverse = repository
|
||||||
.compare(&working(RepoKind::Git), &revision(&id, RepoKind::Git))
|
.compare(&working(RepoKind::Git), &revision(&id, RepoKind::Git), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
assert!(reverse.editable_paths.is_empty());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
changed(&reverse, Path::new("added")).status,
|
changed(&reverse, Path::new("added")).status,
|
||||||
FileStatus::Removed
|
FileStatus::Removed
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
repository
|
repository
|
||||||
.compare(&working(RepoKind::Git), &working(RepoKind::Git))
|
.compare(&working(RepoKind::Git), &working(RepoKind::Git), &[])
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.files
|
.files
|
||||||
.is_empty()
|
.is_empty()
|
||||||
@@ -433,17 +440,22 @@ fn git_remote_refs_and_annotated_tags_are_discovered_before_fetch_and_history_st
|
|||||||
.success()
|
.success()
|
||||||
);
|
);
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(&revision(&local, RepoKind::Git), &remote)
|
.compare(
|
||||||
|
&revision(&local, RepoKind::Git),
|
||||||
|
&remote,
|
||||||
|
&[(active.join("file"), "unsaved local text\n".into())],
|
||||||
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
assert!(comparison.editable_paths.is_empty());
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).before, ["local"]);
|
assert_eq!(changed(&comparison, Path::new("file")).before, ["local"]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
changed(&comparison, Path::new("file")).after,
|
changed(&comparison, Path::new("file")).after,
|
||||||
["remote tip"]
|
["remote tip"]
|
||||||
);
|
);
|
||||||
let comparison = repository.compare(&tag, &remote).unwrap();
|
let comparison = repository.compare(&tag, &remote, &[]).unwrap();
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).before, ["ancestor"]);
|
assert_eq!(changed(&comparison, Path::new("file")).before, ["ancestor"]);
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(&remote, &working(RepoKind::Git))
|
.compare(&remote, &working(RepoKind::Git), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).after, ["local"]);
|
assert_eq!(changed(&comparison, Path::new("file")).after, ["local"]);
|
||||||
let loaded = repository.fetch_remote("origin").unwrap();
|
let loaded = repository.fetch_remote("origin").unwrap();
|
||||||
@@ -457,7 +469,7 @@ fn git_remote_refs_and_annotated_tags_are_discovered_before_fetch_and_history_st
|
|||||||
assert_eq!(historic.label, ancestor);
|
assert_eq!(historic.label, ancestor);
|
||||||
assert_eq!(historic.description, "remote ancestor needle");
|
assert_eq!(historic.description, "remote ancestor needle");
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(historic, &revision(&local, RepoKind::Git))
|
.compare(historic, &revision(&local, RepoKind::Git), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).before, ["ancestor"]);
|
assert_eq!(changed(&comparison, Path::new("file")).before, ["ancestor"]);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -530,7 +542,7 @@ fn jj_catalog_and_working_comparisons_prefer_jj_and_never_snapshot_or_merge_oper
|
|||||||
.any(|r| r.label == "baseline" && r.category == Category::Bookmarks)
|
.any(|r| r.label == "baseline" && r.category == Category::Bookmarks)
|
||||||
);
|
);
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(baseline, &working(RepoKind::Jujutsu))
|
.compare(baseline, &working(RepoKind::Jujutsu), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).after, ["disk"]);
|
assert_eq!(changed(&comparison, Path::new("file")).after, ["disk"]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -652,7 +664,7 @@ fn jj_private_fetch_discovers_never_fetched_bookmark_and_searchable_remote_chang
|
|||||||
.any(|r| r.target == RevisionTarget::Commit(ancestor.clone()))
|
.any(|r| r.target == RevisionTarget::Commit(ancestor.clone()))
|
||||||
);
|
);
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(&remote, &working(RepoKind::Jujutsu))
|
.compare(&remote, &working(RepoKind::Jujutsu), &[])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
changed(&comparison, Path::new("file")).before,
|
changed(&comparison, Path::new("file")).before,
|
||||||
@@ -670,7 +682,7 @@ fn jj_private_fetch_discovers_never_fetched_bookmark_and_searchable_remote_chang
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(historic.label.contains(&ancestor) && historic.label.contains(&change));
|
assert!(historic.label.contains(&ancestor) && historic.label.contains(&change));
|
||||||
assert_eq!(historic.description, "remote historic needle");
|
assert_eq!(historic.description, "remote historic needle");
|
||||||
let comparison = repository.compare(historic, &remote).unwrap();
|
let comparison = repository.compare(historic, &remote, &[]).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
changed(&comparison, Path::new("file")).before,
|
changed(&comparison, Path::new("file")).before,
|
||||||
["remote ancestor"]
|
["remote ancestor"]
|
||||||
@@ -733,7 +745,11 @@ fn errors_are_explicit_and_do_not_modify_active_repository() {
|
|||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
repository
|
repository
|
||||||
.compare(&revision("--bad", RepoKind::Git), &working(RepoKind::Git))
|
.compare(
|
||||||
|
&revision("--bad", RepoKind::Git),
|
||||||
|
&working(RepoKind::Git),
|
||||||
|
&[]
|
||||||
|
)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("Invalid immutable commit")
|
.contains("Invalid immutable commit")
|
||||||
);
|
);
|
||||||
@@ -741,7 +757,8 @@ fn errors_are_explicit_and_do_not_modify_active_repository() {
|
|||||||
repository
|
repository
|
||||||
.compare(
|
.compare(
|
||||||
&revision(&"f".repeat(40), RepoKind::Git),
|
&revision(&"f".repeat(40), RepoKind::Git),
|
||||||
&working(RepoKind::Git)
|
&working(RepoKind::Git),
|
||||||
|
&[],
|
||||||
)
|
)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("unavailable")
|
.contains("unavailable")
|
||||||
@@ -752,7 +769,7 @@ fn errors_are_explicit_and_do_not_modify_active_repository() {
|
|||||||
};
|
};
|
||||||
assert!(
|
assert!(
|
||||||
repository
|
repository
|
||||||
.compare(&loader, &revision(&id, RepoKind::Git))
|
.compare(&loader, &revision(&id, RepoKind::Git), &[])
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("history loader")
|
.contains("history loader")
|
||||||
);
|
);
|
||||||
@@ -792,7 +809,11 @@ fn unchanged_submodules_are_not_false_changes_and_changed_pointers_are_explicit(
|
|||||||
let mut repository = open(&root);
|
let mut repository = open(&root);
|
||||||
assert!(
|
assert!(
|
||||||
repository
|
repository
|
||||||
.compare(&revision(&baseline, RepoKind::Git), &working(RepoKind::Git))
|
.compare(
|
||||||
|
&revision(&baseline, RepoKind::Git),
|
||||||
|
&working(RepoKind::Git),
|
||||||
|
&[]
|
||||||
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.files
|
.files
|
||||||
.is_empty()
|
.is_empty()
|
||||||
@@ -804,7 +825,11 @@ fn unchanged_submodules_are_not_false_changes_and_changed_pointers_are_explicit(
|
|||||||
git(&root.join("nested"), &["checkout", "--detach", &second]);
|
git(&root.join("nested"), &["checkout", "--detach", &second]);
|
||||||
let state = disk_state(&root);
|
let state = disk_state(&root);
|
||||||
let comparison = repository
|
let comparison = repository
|
||||||
.compare(&revision(&baseline, RepoKind::Git), &working(RepoKind::Git))
|
.compare(
|
||||||
|
&revision(&baseline, RepoKind::Git),
|
||||||
|
&working(RepoKind::Git),
|
||||||
|
&[],
|
||||||
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let submodule = changed(&comparison, Path::new("nested"));
|
let submodule = changed(&comparison, Path::new("nested"));
|
||||||
assert_eq!(submodule.status, FileStatus::Modified);
|
assert_eq!(submodule.status, FileStatus::Modified);
|
||||||
@@ -876,6 +901,7 @@ fn multiple_remotes_retain_tag_only_history_even_when_tag_names_collide() {
|
|||||||
.compare(
|
.compare(
|
||||||
&revision(&ids[0], RepoKind::Git),
|
&revision(&ids[0], RepoKind::Git),
|
||||||
&revision(&ids[1], RepoKind::Git),
|
&revision(&ids[1], RepoKind::Git),
|
||||||
|
&[],
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(changed(&comparison, Path::new("file")).before, ["one"]);
|
assert_eq!(changed(&comparison, Path::new("file")).before, ["one"]);
|
||||||
@@ -989,6 +1015,7 @@ fn jj_conflicted_revisions_show_cli_projection_and_keep_ordinary_files_navigable
|
|||||||
.compare(
|
.compare(
|
||||||
&revision(&base, RepoKind::Jujutsu),
|
&revision(&base, RepoKind::Jujutsu),
|
||||||
&revision(&merged, RepoKind::Jujutsu),
|
&revision(&merged, RepoKind::Jujutsu),
|
||||||
|
&[],
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let conflict = changed(&comparison, Path::new("conflict"));
|
let conflict = changed(&comparison, Path::new("conflict"));
|
||||||
@@ -1009,6 +1036,7 @@ fn jj_conflicted_revisions_show_cli_projection_and_keep_ordinary_files_navigable
|
|||||||
.compare(
|
.compare(
|
||||||
&revision(&merged, RepoKind::Jujutsu),
|
&revision(&merged, RepoKind::Jujutsu),
|
||||||
&working(RepoKind::Jujutsu),
|
&working(RepoKind::Jujutsu),
|
||||||
|
&[],
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
@@ -1020,3 +1048,83 @@ fn jj_conflicted_revisions_show_cli_projection_and_keep_ordinary_files_navigable
|
|||||||
);
|
);
|
||||||
assert_eq!(disk_state(&root), state);
|
assert_eq!(disk_state(&root), state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsaved_overlays_are_working_after_only_and_cannot_follow_nonregular_paths() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let root = fs::canonicalize(fixture.dir("overlay")).unwrap();
|
||||||
|
init_git(&root);
|
||||||
|
fs::create_dir(root.join("sub")).unwrap();
|
||||||
|
fs::write(root.join("file"), "base\n").unwrap();
|
||||||
|
fs::write(root.join("sub/file"), "nested\n").unwrap();
|
||||||
|
fs::write(root.join("binary"), b"\0binary").unwrap();
|
||||||
|
git(&root, &["add", "."]);
|
||||||
|
git(&root, &["commit", "-m", "base"]);
|
||||||
|
let id = git(&root, &["rev-parse", "HEAD"]);
|
||||||
|
let outside = fixture.dir("outside");
|
||||||
|
fs::write(outside.join("file"), "outside\n").unwrap();
|
||||||
|
symlink(&outside, root.join("linked")).unwrap();
|
||||||
|
symlink("file", root.join("link")).unwrap();
|
||||||
|
let state = disk_state(&root);
|
||||||
|
let buffers = vec![
|
||||||
|
(root.join("file"), "unsaved\n".into()),
|
||||||
|
(root.join("binary"), "not binary\n".into()),
|
||||||
|
(root.join("missing"), "not on disk\n".into()),
|
||||||
|
(root.join("link"), "not a regular file\n".into()),
|
||||||
|
(root.join("linked/file"), "outside via link\n".into()),
|
||||||
|
(outside.join("file"), "outside\n".into()),
|
||||||
|
(root.join("sub/../../outside/file"), "escaped\n".into()),
|
||||||
|
(root.join(".git/config"), "metadata\n".into()),
|
||||||
|
];
|
||||||
|
let mut repository = open(&root.join("sub"));
|
||||||
|
let base = revision(&id, RepoKind::Git);
|
||||||
|
let checkout = working(RepoKind::Git);
|
||||||
|
let comparison = repository.compare(&base, &checkout, &buffers).unwrap();
|
||||||
|
assert_eq!(comparison.root, fs::canonicalize(&root).unwrap());
|
||||||
|
assert_eq!(changed(&comparison, Path::new("file")).after, ["unsaved"]);
|
||||||
|
assert!(comparison.editable_paths.contains(Path::new("file")));
|
||||||
|
for path in [
|
||||||
|
"binary",
|
||||||
|
"missing",
|
||||||
|
"link",
|
||||||
|
"linked",
|
||||||
|
"linked/file",
|
||||||
|
".git/config",
|
||||||
|
] {
|
||||||
|
assert!(!comparison.editable_paths.contains(Path::new(path)));
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!comparison
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.any(|file| file.path == Path::new("binary")
|
||||||
|
|| file.path == Path::new("missing")
|
||||||
|
|| file.path == Path::new("linked/file"))
|
||||||
|
);
|
||||||
|
let immutable = repository.compare(&checkout, &base, &buffers).unwrap();
|
||||||
|
assert!(immutable.editable_paths.is_empty());
|
||||||
|
assert!(
|
||||||
|
!immutable
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.any(|file| file.path == Path::new("file"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
repository
|
||||||
|
.compare(&base, &base, &buffers)
|
||||||
|
.unwrap()
|
||||||
|
.files
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
let same_checkout = repository.compare(&checkout, &checkout, &buffers).unwrap();
|
||||||
|
assert_eq!(changed(&same_checkout, Path::new("file")).before, ["base"]);
|
||||||
|
assert_eq!(
|
||||||
|
changed(&same_checkout, Path::new("file")).after,
|
||||||
|
["unsaved"]
|
||||||
|
);
|
||||||
|
assert_eq!(disk_state(&root), state);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(outside.join("file")).unwrap(),
|
||||||
|
"outside\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user