Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 9876a69e60 fix(run): pass plain Windows paths to Tomcat 2026-11-01 03:16:39 +08:00
l0ng-ai f48cd85d0b fix(editor): support custom folding in block comments (#606)
Native folding matched comment node names case-sensitively and stripped delimiters character by character, so XML comments were skipped and the `<` in editor-fold tags was consumed. The frontend hardcoded its own comment prefixes. Both now strip the configured comment tokens from the language definitions, so region and editor-fold markers work in block comment languages (XML, HTML, Vue, SVG, CSS and others), and Navigate > Custom Folding lists them. Languages without a bundled grammar get a fallback for own-line markers. Rust and frontend tests share one fixture over 22 language configurations.

Fixes #583
2026-11-01 02:28:07 +08:00
l0ng-ai 9e35cfc064 feat(vcs): compare folder selections with revisions across repositories (#602)
Compare with Branch or Revision only handled one file, so reviewing a folder meant opening each file. Folders, the project root and multiple selections now open a changes tree against the chosen revision, with per-file diffs on demand. A single file keeps its direct diff.

Each path resolves against its own repository through the root registry. In a multi-repo workspace the picker offers shared revisions such as "main in 3 repositories" as well as per-repository ones, results are grouped by repository, and content outside any repository or a repository missing the revision is stated in the result. Listing is cancellable and off the UI thread, includes worktree and untracked changes, and a rename leaving the selection shows as a delete. Show Diff on folders reuses the same tree.

Verified on macOS, and against a remote host over the server protocol. A remote window, Windows and Linux were not run.

Fixes #567
2026-11-01 01:43:15 +08:00
l0ng-ai 0a71f6be88 feat(editor): paste copied files as Markdown links (#599)
Pasting files copied in the project view into a Markdown document now inserts `[](relative/path)`, one link per line, encoded the same way as Markdown images. Other editors and terminals keep inserting the raw path, copied images keep their ![](...) route, and remote windows keep raw paths because the clipboard holds client paths. A context-menu Paste that the native command rejects falls back to reading the clipboard.

Fixes #573
2026-11-01 01:41:58 +08:00
l0ng-ai b3c3150489 fix(remote): run commands on the main thread after authorization (#600)
Authorization for a remote window resumes on a Tokio worker, so the generated handler ran synchronous commands there, including ones reaching AppKit such as the clipboard check, while local windows run them on the main thread. The handler is now dispatched back to the main thread after authorization, and the request is rejected if dispatch fails.

Two app aborts seen in remote windows unwound through this task. The abort was not reproduced and its throw site is unconfirmed. Logging confirmed the thread change. An audit found no remote-only blocking path in the synchronous commands that move to the main thread.
2026-11-01 01:31:01 +08:00
l0ng-ai 1d937d52e5 fix(i18n): remove stale remote import entries from the zh catalog (#590)
The remote import change left two zh entries whose source text is not in the scanned source, which failed textCatalog.test.ts on main.
2026-11-01 00:16:00 +08:00
l0ng-ai 5f57ce962e fix(project): import local files into remote project trees (#587)
Pasting or dropping OS files into a remote project tree sent a client-local source path to the server, so nothing was copied. Local-source imports are now carried separately from project copies and uploaded over the session SFTP channel: streamed in bounded chunks, created exclusively, cancellable across all selected paths under one task, with partial files removed on failure. Symlinks and Unix file modes are preserved, and special files are skipped and reported. Project-internal paste keeps working when the OS clipboard is briefly unavailable.

Native drop positions were assumed to be physical pixels, which shifted the target far from the pointer on Retina displays and with IDE zoom. A shared helper converts them to CSS coordinates for the project tree, the editor and Markdown drop handling, and the agent composer. Composer image drops are now read on the client in remote windows.

Verified on macOS against a live SSH host. Windows and Linux were not run: the Windows conversion is unchanged, the Linux one changed. Copy out from a remote tree to the local machine still needs a download workflow.
2026-11-01 00:14:56 +08:00
arookieofcтаa-rookie-of-C-language 95b45c095d fix(project): paste copied files into editors and terminals as paths (#576)
Copying files in the project view wrote only the file list to the OS clipboard, so pasting into an editor did nothing. The copy now also writes the newline-separated paths as text, which other applications can paste.

WKWebView hides that text when file URLs are present and delivers a paste event with only Files, so the IDE editor and terminal still received nothing. A shared helper now reads the OS file list when a paste has files but no text, and inserts the paths. It covers Cmd+V and context-menu Paste in the editor, the terminal and embedded terminals. Markdown image paste runs first and keeps its behaviour.

Verified on macOS. The Windows clipboard change was tested by the contributor at the clipboard level only.

Refs #573

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-01 00:13:18 +08:00
l0ng-ai 9dc736de09 fix(java): explain recovery for unimported launch modules (#585)
Java launch preparation forwarded jdtls project-lookup failures unchanged, so a Maven module missing from the parent build or a wrongly inferred module showed a raw jdtls error in every Run and Debug entry point. Launch preparation now names the selected module and explains how to recover: wait for import, check the run configuration and the parent build, or open the folder as a project.

Covers the "does not belong to any Java project", "references non-existing project" and "not a Java project" responses. Cancellation, missing server, crash, timeout and build errors keep their existing handling. Import membership and module inference are unchanged.

Refs #197
2026-10-31 23:56:19 +08:00
arookieofcтаa-rookie-of-C-language 369c63979d fix(project): keep the tree viewport when expanding shifts rows above (#579)
The tree followed the lead row by index, so expanding or collapsing a folder above the selection shifted the index and scrolled back to the selected row. It now scrolls when the lead changes. A lead whose row has not loaded yet is kept pending and scrolled to once when the row appears, so preselected rows and async loads still come into view.

Covers keyboard navigation, speed search, Select Opened File and autoscroll from source, which all still scroll to the new lead.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-10-31 23:44:34 +08:00
iGinkтаiGink 347e3525d2 feat(editor): close editor tabs with Shift+click (#581)
Add Shift+left-click as a way to close editor tabs. The tab strip gets a closeOnShiftClick option, enabled for the editor area only, so tool window tabs such as Run and Terminal still select on Shift+click. Keyboard activation with Shift held still selects, non-closable tabs still select, and Shift+click does not start a tab drag.

Co-authored-by: iGink <[email protected]>
2026-10-31 23:38:44 +08:00
l0ng-ai 5280c9e584 fix(agent): report Claude Code turns that fail instead of ending them as ready (#582)
Prompts are sent with the origin `human` and their results echo it, but
`belongs` treated any result with an origin as another turn's. The result
was ignored and the turn ended on `command_lifecycle`, which dropped the
failure the turn had recorded. A signed-out Claude Code showed an empty
reply and a Ready task, with no error.

Only origins other than `human` now mark a result as foreign, so failures,
usage limits and the `max_tokens` and `refusal` stop reasons reach the task.
A turn ended by `command_lifecycle` also keeps its recorded failure.
2026-10-31 23:14:37 +08:00
75 змінених файлів з 3397 додано та 291 видалено

No files matched your search

+7 -2
Переглянути файл
@@ -915,7 +915,11 @@ impl Session {
} else {
"end_turn"
};
finished = st.turn.take().map(|t| (t, TurnEnd::Stop(stop)));
finished = st.turn.take().map(|mut t| {
// Claude Code reports a turn that failed as cancelled here.
let failure = t.failure.take().filter(|_| !t.cancelled);
(t, failure.unwrap_or(TurnEnd::Stop(stop)))
});
}
}
"assistant" if msg.get("parent_tool_use_id").is_none_or(Value::is_null) => {
@@ -1139,7 +1143,8 @@ where
/// Whether `result` ends `turn`: it answers the turn's last message, or (stopped) any of
/// its messages, or names none (the CLI's own error before the turn began).
fn belongs(turn: &Turn, result: &Value) -> bool {
if result.get("origin").is_some_and(|o| !o.is_null()) {
// Prompts are sent with the origin `human`, and their results echo it.
if result.get("origin").is_some_and(|o| !o.is_null() && o.get("kind").and_then(Value::as_str) != Some("human")) {
return false;
}
let mut uuids = strings(result.get("user_message_uuids"));
+45
Переглянути файл
@@ -738,6 +738,50 @@ async fn a_stop_ahead_of_its_prompt_cancels_it() {
assert!(cli.sent.lock()[0].iter().all(|m| m["type"] != "user"), "nothing was sent");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_turn_reports_its_failure() {
let text = "Failed to authenticate: OAuth session expired and could not be refreshed";
let lifecycle = |uuid: &str, state: &str| {
Frame::Cli(json!({ "type": "command_lifecycle", "command_uuid": uuid, "state": state }))
};
let result = |uuid: &str| {
Frame::Cli(json!({
"type": "result", "subtype": "success", "is_error": true, "result": text, "stop_reason": "stop_sequence",
"terminal_reason": "api_error", "origin": { "kind": "human" }, "user_message_uuids": [uuid],
}))
};
// As Claude Code sends it, and with the turn's end ahead of its result.
for lifecycle_first in [false, true] {
let mut process = load_fixture("simple").remove(0);
process.truncate(6);
let Some(Frame::Shim(prompt)) = process.last() else { panic!("the fixture's prompt") };
let uuid = prompt["uuid"].as_str().unwrap().to_owned();
process.push(Frame::Cli(json!({
"type": "assistant", "error": "authentication_failed", "parent_tool_use_id": null,
"message": { "id": "m", "model": "<synthetic>", "content": [{ "type": "text", "text": text }] },
})));
if lifecycle_first {
process.extend([lifecycle(&uuid, "cancelled"), result(&uuid)]);
} else {
process.extend([result(&uuid), lifecycle(&uuid, "cancelled")]);
}
let cli = Arc::new(Replay {
processes: Mutex::new(VecDeque::from([process])),
sent: Arc::default(),
launched: Mutex::default(),
errors: Arc::default(),
});
let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let h =
Harness::connect(cli.clone(), dir.path().into(), dir.path().join("p"), cwd.path().into(), Vec::new()).await;
let s = h.new_session().await;
let Err(RpcError::Server { message, .. }) = h.prompt(&s, "hi").await else {
panic!("the turn should fail (lifecycle first: {lifecycle_first})");
};
assert_eq!(message, format!("Claude Code authentication failed: {text}"));
}
}
/// Fork and undo against the real CLI, across connections, in a symlinked directory
/// (macOS `/tmp`).
#[tokio::test(flavor = "multi_thread")]
@@ -829,6 +873,7 @@ fn which_result_ends_a_turn() {
assert!(!belongs(&t, &json!({"user_message_uuids": ["a"]})), "a steer superseded it");
assert!(belongs(&t, &json!({"subtype": "error_during_execution"})), "names no message");
assert!(!belongs(&t, &json!({"origin": {"kind": "task-notification"}})), "Claude Code's own turn");
assert!(belongs(&t, &json!({"origin": {"kind": "human"}, "user_message_uuids": ["b"]})), "the prompt's own result");
assert!(belongs(&turn(&["a", "b"], true), &json!({"user_message_uuids": ["a"]})));
}
+55 -9
Переглянути файл
@@ -1,6 +1,8 @@
//! The file list on the OS clipboard: what Explorer copies when the user
//! copies files, so the project view can paste them, and what the project view
//! writes so Explorer can paste the files it copied (IDEA does both).
//! writes so Explorer can paste the files it copied (IDEA does both). The
//! written list comes with the paths as text, so a paste into an editor
//! inserts them instead of doing nothing.
//!
//! Windows keeps it as `CF_HDROP`: a `DROPFILES` header and a double-NUL
//! terminated list of absolute paths, wide when `fWide` is set. The data is set
@@ -111,6 +113,8 @@ mod imp {
/// `CF_HDROP`, the clipboard format holding a file list.
const CF_HDROP: u32 = 15;
/// `CF_UNICODETEXT`, so an editor paste of copied files inserts the paths.
const CF_UNICODETEXT: u32 = 13;
/// An `HGLOBAL` or a `HANDLE`: both are opaque pointers here.
type Handle = *mut c_void;
@@ -182,12 +186,37 @@ mod imp {
paths
}
/// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
/// byte size. Null when the allocation failed.
fn global_text(text: &str) -> (Handle, usize) {
let mut units: Vec<u16> = text.encode_utf16().collect();
units.push(0);
let bytes = units.len() * 2;
unsafe {
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes);
if memory.is_null() {
return (ptr::null_mut(), 0);
}
let data = GlobalLock(memory);
if data.is_null() {
GlobalFree(memory);
return (ptr::null_mut(), 0);
}
ptr::copy_nonoverlapping(units.as_ptr() as *const u8, data as *mut u8, bytes);
GlobalUnlock(memory);
(memory, bytes)
}
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
}
// SAFETY: the block is allocated, filled, handed to the clipboard and
// The paths as text, newline-separated, so pasting into an editor
// inserts them (IDEA writes the list and the text together).
let text = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\r\n");
// SAFETY: the blocks are allocated, filled, handed to the clipboard and
// freed only on the paths where the clipboard did not take ownership.
unsafe {
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
@@ -205,17 +234,27 @@ mod imp {
GlobalFree(memory);
return false;
}
// Replacing the list also drops the text the user copied before.
// Replacing the list also drops the text the user copied before;
// the paths' own text is set back with it.
if EmptyClipboard() == 0 {
CloseClipboard();
GlobalFree(memory);
return false;
}
let taken = !SetClipboardData(CF_HDROP, memory).is_null();
CloseClipboard();
let mut taken = !SetClipboardData(CF_HDROP, memory).is_null();
if !taken {
GlobalFree(memory);
}
let (text_memory, _) = global_text(&text);
if !text_memory.is_null() {
// The text alone still pastes somewhere useful.
let text_taken = !SetClipboardData(CF_UNICODETEXT, text_memory).is_null();
taken |= text_taken;
if !text_taken {
GlobalFree(text_memory);
}
}
CloseClipboard();
taken
}
}
@@ -227,9 +266,10 @@ mod imp {
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSURL};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
/// `NSURL` as the one class to read, limited to file URLs: a web link the
@@ -285,9 +325,15 @@ mod imp {
let writers: Vec<&ProtocolObject<dyn NSPasteboardWriting>> =
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
let board = NSPasteboard::generalPasteboard();
// Replacing the list also drops the text the user copied before.
// Replacing the list also drops the text the user copied before;
// the paths' own text is set back with it, so an editor paste
// inserts them (IDEA writes the list and the text together).
board.clearContents();
board.writeObjects(&NSArray::from_slice(&writers))
board.writeObjects(&NSArray::from_slice(&writers));
let text = NSString::from_str(
&paths.iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"),
);
board.setString_forType(&text, unsafe { NSPasteboardTypeString })
})
}
}
+39
Переглянути файл
@@ -746,6 +746,33 @@ pub async fn vcs_remove_worktree(
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force))).await
}
pub async fn vcs_compare_scope(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<CompareScope> {
let project = host.project(window)?;
blocking(move || Ok(project.repos().compare_scope(&paths))).await
}
pub async fn vcs_compare_paths(
host: &Host,
window: &str,
paths: Vec<PathBuf>,
revision: String,
repositories: Option<Vec<PathBuf>>,
request: RequestId,
) -> IdeResult<CompareResult> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel)
})
.await;
host.end_request(request);
result
}
/// Compare with Local: tracked files that differ between `rev` and the working tree.
pub async fn vcs_diff_with_worktree(
host: &Host,
@@ -1040,6 +1067,18 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_remove_worktree", |c| async move {
vcs_remove_worktree(&c.host, &c.window, c.arg("repo")?, c.arg("path")?, c.arg("force")?).await
});
d.add("vcs_compare_scope", |c| async move { vcs_compare_scope(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_compare_paths", |c| async move {
vcs_compare_paths(
&c.host,
&c.window,
c.arg("paths")?,
c.arg("revision")?,
c.arg("repositories")?,
c.arg("request")?,
)
.await
});
d.add("vcs_diff_with_worktree", |c| async move {
vcs_diff_with_worktree(&c.host, &c.window, c.arg("repo")?, c.arg("rev")?).await
});
+2
Переглянути файл
@@ -276,6 +276,8 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "vcs_remotes"
| "vcs_worktrees"
| "vcs_diff_with_worktree"
| "vcs_compare_scope"
| "vcs_compare_paths"
| "vcs_diff_revisions"
| "vcs_merge_base"
| "vcs_shelves"
+2 -1
Переглянути файл
@@ -209,8 +209,9 @@ impl SyntaxCache {
|m| &mut m.folding,
|| {
self.with_tree(doc, lang, version, text, |g, tree, text| {
Some(folding::folding(g.spec, g.kinds(), tree, text))
Some(folding::folding(g.spec, g.kinds(), tree, text, self.syntax.comment_tokens(lang)))
})
.or_else(|| Some(self.syntax.custom_folding(lang, text)))
},
)
}
+73 -12
Переглянути файл
@@ -2,7 +2,7 @@
//! comment runs, import runs and `region` / `endregion` marker comments.
use super::grammars::Spec;
use crate::{FoldKind, FoldRange};
use crate::{FoldKind, FoldRange, LanguageConfig};
use tree_sitter::{Language, Node, Tree, TreeCursor};
const PAIRS: &[(&str, &str)] = &[("{", "}"), ("[", "]"), ("(", ")"), ("#{", "}"), ("${", "}"), ("@{", "}")];
@@ -85,7 +85,25 @@ impl KindTable {
}
}
pub(crate) fn folding(spec: &Spec, kinds: &KindTable, tree: &Tree, text: &str) -> Vec<FoldRange> {
#[derive(Default)]
pub(super) struct CommentTokens {
line: Option<String>,
block: Option<(String, String)>,
}
impl From<&LanguageConfig> for CommentTokens {
fn from(config: &LanguageConfig) -> Self {
Self { line: config.line_comment.clone(), block: config.block_comment.clone() }
}
}
pub(super) fn folding(
spec: &Spec,
kinds: &KindTable,
tree: &Tree,
text: &str,
tokens: &CommentTokens,
) -> Vec<FoldRange> {
let mut out: Vec<FoldRange> = Vec::new();
let mut comments: Vec<Comment> = Vec::new();
let mut cursor = tree.walk();
@@ -96,7 +114,7 @@ pub(crate) fn folding(spec: &Spec, kinds: &KindTable, tree: &Tree, text: &str) -
start_row: start,
end_row: last_content_row(&node, text),
own_line: own_line(text, node.start_byte(), node.start_position().column),
marker: region_marker(text.get(node.start_byte()..node.end_byte()).unwrap_or_default()),
marker: region_marker(text.get(node.start_byte()..node.end_byte()).unwrap_or_default(), tokens),
});
return true;
}
@@ -185,7 +203,7 @@ fn visit(cursor: &mut TreeCursor, mut f: impl FnMut(Node) -> bool) {
}
pub(crate) fn is_comment(kind: &str) -> bool {
kind.contains("comment")
kind.contains("comment") || kind == "Comment"
}
/// Row of the closing token when `node` is delimited by a matching bracket pair.
@@ -220,21 +238,64 @@ fn own_line(text: &str, byte: usize, column: usize) -> bool {
}
/// `Some(true)` for a region start marker, `Some(false)` for an end marker.
fn region_marker(comment: &str) -> Option<bool> {
let body = comment
.trim_start_matches(['/', '*', '#', '-', ';', '%', '!', '<', ' ', '\t'])
.trim_start_matches("--")
.trim_start();
let lower = body.get(..body.len().min(32))?.to_ascii_lowercase();
if lower.starts_with("endregion") || lower.starts_with("#endregion") || lower.starts_with("</editor-fold") {
/// Strip whole configured delimiters, preserving the `<` in editor-fold tags.
pub(super) fn region_marker(comment: &str, tokens: &CommentTokens) -> Option<bool> {
let comment = comment.trim();
let body = if let Some((open, close)) = &tokens.block
&& let Some(body) = comment.strip_prefix(open.as_str())
{
let body = body.trim_end().strip_suffix(close.as_str())?;
if open == "/*" { body.trim_start_matches('*') } else { body }
} else if let Some(open) = &tokens.line
&& let Some(body) = comment.strip_prefix(open.as_str())
{
match open.as_str() {
"//" => body.trim_start_matches('/'),
";" => body.trim_start_matches(';'),
_ => body,
}
} else {
return None;
};
let body = body.trim();
if body.contains(['\n', '\r']) {
return None;
}
let lower = body.to_ascii_lowercase();
let region = lower.strip_prefix('#').unwrap_or(&lower);
let boundary = |tail: &str| !tail.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_');
if region.strip_prefix("endregion").is_some_and(boundary)
|| lower
.strip_prefix("</editor-fold")
.and_then(|tail| tail.strip_suffix('>'))
.is_some_and(|tail| tail.trim().is_empty())
{
Some(false)
} else if lower.starts_with("region") || lower.starts_with("#region") || lower.starts_with("<editor-fold") {
} else if region.strip_prefix("region").is_some_and(boundary)
|| lower.strip_prefix("<editor-fold").is_some_and(|tail| boundary(tail) && tail.contains('>'))
{
Some(true)
} else {
None
}
}
/// Languages without a bundled grammar still support own-line custom markers.
pub(super) fn custom_folding(text: &str, tokens: &CommentTokens) -> Vec<FoldRange> {
let comments: Vec<_> = text
.lines()
.enumerate()
.filter_map(|(row, line)| {
let marker = region_marker(line, tokens)?;
Some(Comment { start_row: row, end_row: row, own_line: true, marker: Some(marker) })
})
.collect();
let mut out = Vec::new();
comment_folds(&comments, &mut out);
out.sort_by_key(|f| f.start_line);
out
}
fn comment_folds(comments: &[Comment], out: &mut Vec<FoldRange>) {
let mut regions: Vec<usize> = Vec::new();
let mut run: Option<(usize, usize)> = None;
+24 -3
Переглянути файл
@@ -32,6 +32,7 @@ pub struct Syntax {
grammars: Vec<Grammar>,
/// Language id (and grammar name) -> index into `grammars`.
by_lang: HashMap<String, usize>,
comments: HashMap<String, folding::CommentTokens>,
}
pub(crate) struct Grammar {
@@ -107,7 +108,14 @@ impl Syntax {
}
}
}
Self { grammars, by_lang }
let mut comments = HashMap::new();
for cfg in languages {
comments.insert(cfg.id.as_str().to_owned(), folding::CommentTokens::from(cfg));
if let Some(name) = &cfg.tree_sitter {
comments.entry(name.clone()).or_insert_with(|| folding::CommentTokens::from(cfg));
}
}
Self { grammars, by_lang, comments }
}
/// Names of the bundled grammars (valid values for `tree-sitter = "..."`).
@@ -161,8 +169,21 @@ impl Syntax {
}
pub fn folding(&self, lang: &LanguageId, text: &str) -> Vec<FoldRange> {
self.analyze(lang, text, |g, tree, text| Some(folding::folding(g.spec, g.kinds(), tree, text)))
.unwrap_or_default()
let tokens = self.comment_tokens(lang);
self.analyze(lang, text, |g, tree, text| Some(folding::folding(g.spec, g.kinds(), tree, text, tokens)))
.unwrap_or_else(|| self.custom_folding(lang, text))
}
fn comment_tokens(&self, lang: &LanguageId) -> &folding::CommentTokens {
static EMPTY: OnceLock<folding::CommentTokens> = OnceLock::new();
self.comments.get(lang.as_str()).unwrap_or_else(|| EMPTY.get_or_init(Default::default))
}
fn custom_folding(&self, lang: &LanguageId, text: &str) -> Vec<FoldRange> {
if text.len() > MAX_PARSE_BYTES {
return Vec::new();
}
folding::custom_folding(text, self.comment_tokens(lang))
}
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
+79
Переглянути файл
@@ -969,6 +969,85 @@ fn g() {}
);
}
#[test]
fn folding_xml_custom_regions() {
for (start, end) in [
("<!--region要折叠的内容-->", "<!-- endregion -->"),
("<!--region name-->", "<!--endregion-->"),
("<!-- <editor-fold desc=\"Head\"> -->", "<!-- </editor-fold> -->"),
] {
let text = format!("<project>\n {start}\n <name>demo</name>\n {end}\n</project>\n");
assert!(folds("xml", &text).contains(&(1, 3, FoldKind::Region)), "{text}");
}
}
#[test]
fn folding_custom_regions_use_configured_comment_tokens() {
let fixture: serde_json::Value =
serde_json::from_str(include_str!("../../../../fixtures/folding/regions.json")).unwrap();
let registry = LanguageRegistry::load(None).unwrap();
let cache = SyntaxCache::new(std::sync::Arc::new(Syntax::new()));
for language in fixture["languages"].as_array().unwrap() {
let id = language.as_str().unwrap();
let cfg = registry.get(&lang(id)).unwrap();
let mut tokens = Vec::new();
if let Some(line) = &cfg.line_comment {
tokens.push((line.as_str(), ""));
}
if let Some((open, close)) = &cfg.block_comment {
tokens.push((open.as_str(), close.as_str()));
}
for (open, close) in tokens {
for space in ["", " ", " "] {
// Word delimiters require a separator in the language itself.
if space.is_empty() && open.ends_with(|c: char| c.is_ascii_alphanumeric()) {
continue;
}
let wrap = |body: &str| format!(" {open}{space}{body}{space}{close}");
for marker in fixture["markers"].as_array().unwrap() {
let start = wrap(marker["start"].as_str().unwrap());
let end = wrap(marker["end"].as_str().unwrap());
let tokens = folding::CommentTokens::from(&cfg);
assert_eq!(folding::region_marker(&start, &tokens), Some(true), "{id}: {start}");
assert_eq!(folding::region_marker(&end, &tokens), Some(false), "{id}: {end}");
// Ruby block delimiters must occupy separate lines; Haskell
// interprets `--` followed immediately by a symbol as an operator.
if (id == "ruby" && open == "=begin") || (id == "haskell" && space.is_empty()) {
continue;
}
let text = format!("{start}\n\n{end}\n");
let expected = vec![(0, 2, FoldKind::Region)];
assert_eq!(folds(id, &text), expected, "{id}: {text}");
let doc = ide_core::DocId::next();
cache.open(doc, &lang(id), 0);
let actual = cache.folding(doc, &lang(id), 0, &text);
assert_eq!(cache.folding(doc, &lang(id), 0, &text), actual);
cache.close(doc);
assert_eq!(
actual.iter().map(|f| (f.start_line, f.end_line, f.kind)).collect::<Vec<_>>(),
expected,
"cached {id}: {text}"
);
let nested = format!("{end}\n\n{start}\n{start}\n\n{end}\n{end}\n{start}\n");
assert_eq!(
folds(id, &nested),
vec![(2, 6, FoldKind::Region), (3, 5, FoldKind::Region)],
"nested {id}: {nested}"
);
}
for invalid in fixture["invalid"].as_array().unwrap() {
let start = wrap(invalid.as_str().unwrap());
assert_eq!(
folding::region_marker(&start, &folding::CommentTokens::from(&cfg)),
None,
"invalid {id}: {start}"
);
}
}
}
}
}
#[test]
fn folding_python_bodies_start_at_header() {
let src = "import os\nimport sys\n\nclass A:\n def f(self):\n return [\n 1,\n ]\n\n\ndef g():\n pass\n";
+61
Переглянути файл
@@ -0,0 +1,61 @@
//! Imports from the client filesystem into a remote project, without deployment mappings.
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_ssh::RemoteFs;
use std::path::Path;
/// Copies entries, preserving symlinks and empty folders. Reports skipped special files.
pub async fn import_local(fs: &RemoteFs, from: &Path, to: &str, cancel: &CancellationToken) -> IdeResult<Vec<String>> {
let mut skipped = Vec::new();
import_entry(fs, from, to, cancel, &mut skipped).await?;
Ok(skipped)
}
async fn import_entry(
fs: &RemoteFs,
from: &Path,
to: &str,
cancel: &CancellationToken,
skipped: &mut Vec<String>,
) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if fs.stat(to).await?.is_some() {
return Err(IdeError::new(ide_core::error::ErrorKind::AlreadyExists, format!("{to} already exists")));
}
let meta = tokio::fs::symlink_metadata(from).await?;
if meta.is_symlink() {
let result = async {
let target = tokio::fs::read_link(from).await?;
let target = target.to_str().ok_or_else(|| IdeError::invalid("Link target is not valid UTF-8"))?;
fs.symlink(target, to).await
}
.await;
if let Err(e) = result {
skipped.push(format!("{}: {e}", from.display()));
}
return Ok(());
}
if !meta.is_file() && !meta.is_dir() {
skipped.push(format!("{}: skipped special file", from.display()));
return Ok(());
}
if meta.is_file() {
return fs.upload_new(from, to, cancel).await;
}
fs.create_dir(to).await?;
let result = async {
let mut entries = tokio::fs::read_dir(from).await?;
while let Some(entry) = entries.next_entry().await? {
let name = entry.file_name();
let name = name.to_str().ok_or_else(|| IdeError::invalid("File name is not valid UTF-8"))?;
Box::pin(import_entry(fs, &entry.path(), &ide_ssh::sftp::join(to, name), cancel, skipped)).await?;
}
Ok(())
}
.await;
if result.is_err() {
let _ = fs.remove(to).await;
}
result
}
+1
Переглянути файл
@@ -2,6 +2,7 @@
//! configurations on run targets ([`target`]).
pub mod deploy;
pub mod import;
pub mod mapping;
pub mod service;
pub mod target;
+69
Переглянути файл
@@ -58,6 +58,75 @@ fn no_progress() -> impl FnMut(&str, usize, usize) + Send {
|_, _, _| {}
}
#[tokio::test]
async fn client_imports_preserve_conflicts_and_report_failure_over_sftp_and_local() {
let env = env().await;
for sftp in [false, true] {
let fs = if sftp { RemoteFs::new(env.session.sftp().await.unwrap()) } else { RemoteFs::Local };
let base =
if sftp { "/imports".to_owned() } else { env.server_root.join("local").to_string_lossy().into_owned() };
fs.mkdir_all(&base).await.unwrap();
let to = ide_ssh::sftp::join(&base, "copy");
let cancel = CancellationToken::new();
std::fs::create_dir_all(env.project.join("empty")).unwrap();
ide_remote::import::import_local(&fs, &env.project, &to, &cancel).await.unwrap();
assert_eq!(fs.read(&format!("{to}/src/main.py")).await.unwrap(), b"print('hi')\n");
assert!(fs.stat(&format!("{to}/empty")).await.unwrap().unwrap().is_dir);
let err = ide_remote::import::import_local(&fs, &env.project, &to, &cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::AlreadyExists);
let file = format!("{to}/README.md");
assert!(fs.upload_new(&env.project.join("src/main.py"), &file, &cancel).await.is_err());
assert_eq!(fs.read(&file).await.unwrap(), b"# demo\n");
let missing =
ide_remote::import::import_local(&fs, &env.project.join("missing"), &format!("{base}/missing"), &cancel)
.await
.unwrap_err();
assert_eq!(missing.kind, ide_core::error::ErrorKind::NotFound);
cancel.cancel();
let err = ide_remote::import::import_local(&fs, &env.project, &format!("{base}/cancelled"), &cancel)
.await
.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(fs.stat(&format!("{base}/cancelled")).await.unwrap().is_none());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let source = env.project.join("links-tree");
std::fs::create_dir_all(&source).unwrap();
std::fs::write(source.join("run.sh"), "#!/bin/sh\necho imported\n").unwrap();
std::fs::set_permissions(source.join("run.sh"), std::fs::Permissions::from_mode(0o751)).unwrap();
std::os::unix::fs::symlink("run.sh", source.join("link")).unwrap();
std::os::unix::fs::symlink("missing", source.join("dangling")).unwrap();
std::os::unix::fs::symlink(".", source.join("cycle")).unwrap();
let socket = std::os::unix::net::UnixListener::bind(source.join("socket")).unwrap();
let dest = format!("{base}/links");
let skipped =
ide_remote::import::import_local(&fs, &source, &dest, &CancellationToken::new()).await.unwrap();
assert_eq!(skipped, vec![format!("{}: skipped special file", source.join("socket").display())]);
let on_disk = if sftp { env.server_root.join("imports/links") } else { std::path::PathBuf::from(&dest) };
for (name, target) in [("link", "run.sh"), ("dangling", "missing"), ("cycle", ".")] {
assert_eq!(std::fs::read_link(on_disk.join(name)).unwrap(), std::path::PathBuf::from(target));
}
assert_eq!(std::fs::metadata(on_disk.join("run.sh")).unwrap().permissions().mode() & 0o777, 0o751);
assert_eq!(fs.read(&format!("{dest}/run.sh")).await.unwrap(), b"#!/bin/sh\necho imported\n");
assert!(!on_disk.join("socket").exists());
let skipped = ide_remote::import::import_local(
&fs,
&source.join("socket"),
&format!("{base}/socket"),
&CancellationToken::new(),
)
.await
.unwrap();
assert_eq!(skipped.len(), 1);
assert!(fs.stat(&format!("{base}/socket")).await.unwrap().is_none());
drop(socket);
std::fs::remove_dir_all(source).unwrap();
}
fs.close().await;
}
}
#[tokio::test]
async fn uploads_compares_syncs_and_downloads() {
let env = env().await;
+2 -2
Переглянути файл
@@ -687,9 +687,9 @@ fn detect_go(root: &Path, out: &mut Vec<RunConfig>) {
let mut seen = HashSet::new();
for member in crate::go::work_modules(&work) {
let dir = root.join(member);
let dir = dir.canonicalize().unwrap_or(dir);
let dir = dunce::canonicalize(&dir).unwrap_or(dir);
if dir.join("go.mod").is_file() && seen.insert(dir.clone()) {
let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let rel = dir.strip_prefix(&canonical_root).unwrap_or(&dir).to_path_buf();
detect_go_module(&dir, (!rel.as_os_str().is_empty()).then_some(rel), out);
}
+1 -1
Переглянути файл
@@ -494,7 +494,7 @@ mod tests {
fn pathing_jar_runs_with_a_local_jdk() {
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from).or_else(|| {
let java = crate::which::find_executable("java", &std::env::var_os("PATH").unwrap_or_default())?;
std::fs::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
dunce::canonicalize(java).ok()?.parent()?.parent().map(Path::to_path_buf)
}) else {
return;
};
+42 -13
Переглянути файл
@@ -228,8 +228,7 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
.filter(|v| !v.trim().is_empty())
.ok_or_else(|| invalid("Choose a WAR file or exploded directory"))?;
let path = root.join(value);
let path = path
.canonicalize()
let path = dunce::canonicalize(&path)
.map_err(|e| invalid(format!("Invalid Tomcat deployment: {} ({e})", path.display())))?;
if (kind == "war" && (!path.is_file() || !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("war"))))
|| (kind == "directory" && !path.is_dir())
@@ -264,13 +263,14 @@ pub fn script_command(home: &Path, windows: bool, verb: &str) -> (String, Vec<St
}
pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<()> {
let home = root
.join(config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?)
.canonicalize()?;
// Batch scripts and their environment variables require ordinary Windows paths.
let home = dunce::canonicalize(root.join(
config.extras.params.get("tomcatHome").ok_or_else(|| invalid("Choose a Tomcat installation directory"))?,
))?;
validate_home(&home)?;
let base = base_dir(cache, &config.id);
fs::create_dir_all(&base)?;
let base = base.canonicalize()?;
let base = dunce::canonicalize(&base)?;
let doc = deployment(root, &base, config, false)?;
let context = effective_context(config, &doc);
let context = context_name(&context)?;
@@ -304,7 +304,7 @@ pub fn prepare(root: &Path, cache: &Path, config: &mut RunConfig) -> IdeResult<(
config.env.insert("CATALINA_HOME".into(), home.to_string_lossy().into_owned());
config.env.insert("CATALINA_BASE".into(), base.to_string_lossy().into_owned());
if let Some(jre) = config.extras.params.get("jre").filter(|s| !s.trim().is_empty()) {
let jre = root.join(jre).canonicalize()?;
let jre = dunce::canonicalize(root.join(jre))?;
config.env.insert("JAVA_HOME".into(), jre.to_string_lossy().into_owned());
config.env.insert("JRE_HOME".into(), jre.to_string_lossy().into_owned());
} else if let Some(java) = config.env.get("JAVA_HOME").cloned() {
@@ -432,7 +432,7 @@ mod tests {
assert_eq!(fs::read_to_string(dest.join("WEB-INF/classes/App.class")).unwrap(), "class2");
c.extras.params.insert("deployment".into(), "war".into());
c.extras.params.insert("deploymentPath".into(), "web app.war".into());
assert_eq!(deployment(tmp.path(), &base, &c, false).unwrap(), war.canonicalize().unwrap());
assert_eq!(deployment(tmp.path(), &base, &c, false).unwrap(), dunce::canonicalize(&war).unwrap());
fs::create_dir_all(tmp.path().join("WebContent")).unwrap();
c.extras.params.insert("deployment".into(), "directory".into());
c.extras.params.insert("deploymentPath".into(), "WebContent".into());
@@ -463,11 +463,22 @@ mod tests {
#[test]
fn prepares_isolated_base_and_jdwp_only_for_run() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("Tomcat Home");
check_prepared_paths(tmp.path());
}
#[cfg(windows)]
#[test]
fn prepares_plain_windows_paths_from_verbatim_root() {
let tmp = tempfile::tempdir().unwrap();
let root = PathBuf::from(format!(r"\\?\{}", dunce::canonicalize(tmp.path()).unwrap().display()));
check_prepared_paths(&root);
}
fn check_prepared_paths(root: &Path) {
let home = root.join("Tomcat Home");
fs::create_dir_all(home.join("bin")).unwrap();
fs::create_dir_all(home.join("conf")).unwrap();
fs::create_dir_all(tmp.path().join("WebRoot")).unwrap();
fs::create_dir_all(root.join("WebRoot")).unwrap();
fs::write(home.join("bin/catalina.sh"), "").unwrap();
fs::write(home.join("bin/catalina.bat"), "").unwrap();
archive(
&home.join("lib/catalina.jar"),
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
@@ -486,17 +497,35 @@ mod tests {
c.extras.params.insert(k.into(), v.into());
}
c.env.insert("JAVA_HOME".into(), "/jdk with spaces".into());
prepare(tmp.path(), &tmp.path().join("cache"), &mut c).unwrap();
let cache = root.join("cache");
prepare(root, &cache, &mut c).unwrap();
assert_eq!(fs::read_to_string(home.join("conf/server.xml")).unwrap(), server);
let base = PathBuf::from(&c.env["CATALINA_BASE"]);
assert!(base.join("conf/Catalina/localhost/app.xml").is_file());
let context = base.join("conf/Catalina/localhost/app.xml");
let doc = dunce::canonicalize(root.join("WebRoot")).unwrap();
assert_eq!(fs::read_to_string(&context).unwrap(), context_xml(&doc, false));
assert_eq!(c.env["CATALINA_HOME"], dunce::canonicalize(&home).unwrap().to_string_lossy());
assert_eq!(base, dunce::canonicalize(base_dir(&cache, &c.id)).unwrap());
assert!(c.env["CATALINA_OPTS"].contains("suspend=n,address=127.0.0.1:0"));
assert!(c.env["CATALINA_OPTS"].contains("-Xmx256m"));
assert!(!c.env.get("JAVA_OPTS").is_some_and(|s| s.contains("jdwp")));
assert_eq!(c.env["JRE_HOME"], "/jdk with spaces");
let stop = c.extras.stop_command.unwrap();
let stop = c.extras.stop_command.as_ref().unwrap();
assert!(stop.contains("stop"));
let script = if cfg!(windows) { "catalina.bat" } else { "catalina.sh" };
assert!(stop.contains(script));
fs::create_dir_all(root.join("JDK Home")).unwrap();
c.extras.params.insert("jre".into(), "JDK Home".into());
prepare(root, &cache, &mut c).unwrap();
let jre = dunce::canonicalize(root.join("JDK Home")).unwrap();
for key in ["JAVA_HOME", "JRE_HOME"] {
assert_eq!(c.env[key], jre.to_string_lossy());
}
assert!(!c.command.contains(r"\\?\"));
assert!(c.args.iter().all(|arg| !arg.contains(r"\\?\")));
assert!(!c.extras.stop_command.as_ref().unwrap().contains(r"\\?\"));
assert!(c.env.values().all(|value| !value.contains(r"\\?\")));
assert!(!fs::read_to_string(context).unwrap().contains(r"\\?\"));
}
}
+15
Переглянути файл
@@ -608,6 +608,21 @@ fn go_work_members_define_configs_including_deep_and_quoted_directories() {
assert!(configs.iter().any(|c| c.id == "go:test:module with spaces"));
}
#[test]
fn go_work_external_member_has_a_plain_absolute_working_directory() {
let dir = project(&[
("workspace/go.work", "go 1.22\nuse ../external\n"),
("external/go.mod", "module example.com/external\ngo 1.22\n"),
("external/main.go", "package main\nfunc main() {}"),
]);
let configs = detect(&dir.path().join("workspace"));
let run = configs.iter().find(|c| c.kind == "go" && !c.is_test).unwrap();
let cwd = run.cwd.as_deref().unwrap();
assert_eq!(cwd, dunce::canonicalize(dir.path().join("external")).unwrap());
assert!(cwd.is_absolute());
assert!(!cwd.to_string_lossy().starts_with(r"\\?\"));
}
#[test]
fn go_work_parser_ignores_other_directives_comments_and_malformed_groups() {
use ide_run::go::work_modules;
+67 -1
Переглянути файл
@@ -1,6 +1,6 @@
//! Filesystem operations shared by deployment and remote development bootstrap.
use crate::sftp::{RemoteEntry, SftpFs};
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use russh_sftp::client::SftpSession;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -115,6 +115,50 @@ impl RemoteFs {
}
}
/// Exclusive creation keeps imports from overwriting a concurrent copy.
pub async fn upload_new(&self, local: &Path, remote: &str, cancel: &CancellationToken) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match self {
Self::Sftp(fs) => fs.upload_new(local, remote, cancel).await,
Self::Local => {
let mut input = tokio::fs::File::open(local).await?;
let mut output = tokio::fs::OpenOptions::new().write(true).create_new(true).open(remote).await?;
let result = async {
copy_stream(&mut input, &mut output, cancel).await?;
#[cfg(unix)]
output.set_permissions(input.metadata().await?.permissions()).await?;
Ok(())
}
.await;
drop(output);
if result.is_err() {
let _ = tokio::fs::remove_file(remote).await;
}
result
}
}
}
/// Creates the link itself, preserving a relative or dangling target.
pub async fn symlink(&self, target: &str, link: &str) -> IdeResult<()> {
match self {
Self::Sftp(fs) => fs.symlink(target, link).await,
#[cfg(unix)]
Self::Local => Ok(tokio::fs::symlink(target, link).await?),
#[cfg(not(unix))]
Self::Local => Err(IdeError::invalid("Cannot create a symbolic link on this client")),
}
}
pub async fn create_dir(&self, path: &str) -> IdeResult<()> {
match self {
Self::Sftp(fs) => fs.create_dir(path).await,
Self::Local => Ok(tokio::fs::create_dir(path).await?),
}
}
pub async fn download(&self, remote: &str, local: &Path) -> IdeResult<()> {
match self {
Self::Sftp(fs) => fs.download(remote, local).await,
@@ -199,6 +243,28 @@ impl RemoteFs {
}
}
pub(crate) async fn copy_stream(
input: &mut (impl tokio::io::AsyncRead + Unpin),
output: &mut (impl tokio::io::AsyncWrite + Unpin),
cancel: &CancellationToken,
) -> IdeResult<()> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
tokio::select! {
biased;
_ = cancel.cancelled() => Err(IdeError::cancelled()),
result = async {
let mut buf = vec![0; 64 * 1024];
loop {
let len = input.read(&mut buf).await?;
if len == 0 { break; }
output.write_all(&buf[..len]).await?;
}
output.flush().await?;
Ok(())
} => result,
}
}
/// Copies without holding the file in memory: deployments can include large archives.
async fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
if let Some(parent) = to.parent() {
+41 -2
Переглянути файл
@@ -1,9 +1,9 @@
//! Remote files over SFTP. Remote paths are POSIX strings.
use ide_core::{IdeError, IdeResult, error::ErrorKind};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use russh_sftp::client::SftpSession;
use russh_sftp::client::error::Error as SftpError;
use russh_sftp::protocol::{FileAttributes, StatusCode};
use russh_sftp::protocol::{FileAttributes, OpenFlags, StatusCode};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
@@ -168,6 +168,45 @@ impl SftpFs {
self.write(remote, &data, mtime).await
}
/// Imports a local file without replacing an existing remote entry.
pub async fn upload_new(&self, local: &Path, remote: &str, cancel: &CancellationToken) -> IdeResult<()> {
let mut input = tokio::fs::File::open(local).await?;
let mut output = self
.sftp
.open_with_flags(remote, OpenFlags::WRITE | OpenFlags::CREATE | OpenFlags::EXCLUDE)
.await
.map_err(|e| err(remote, e))?;
let result = crate::filesystem::copy_stream(&mut input, &mut output, cancel).await;
let closed = output.shutdown().await.map_err(IdeError::from);
drop(output);
let result = async {
result.and(closed)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = input.metadata().await?.permissions().mode() & 0o7777;
self.sftp
.set_metadata(remote, FileAttributes { permissions: Some(mode), ..FileAttributes::empty() })
.await
.map_err(|e| err(remote, e))?;
}
Ok(())
}
.await;
if result.is_err() {
let _ = self.sftp.remove_file(remote).await;
}
result
}
pub async fn symlink(&self, target: &str, link: &str) -> IdeResult<()> {
self.sftp.symlink(target, link).await.map_err(|e| err(link, e))
}
pub async fn create_dir(&self, path: &str) -> IdeResult<()> {
self.sftp.create_dir(path).await.map_err(|e| err(path, e))
}
pub async fn download(&self, remote: &str, local: &Path) -> IdeResult<()> {
let data = self.read(remote).await?;
if let Some(dir) = local.parent() {
+12
Переглянути файл
@@ -164,6 +164,7 @@ impl russh_sftp::server::Handler for Sftp {
.read(pflags.contains(OpenFlags::READ))
.write(pflags.contains(OpenFlags::WRITE))
.create(pflags.contains(OpenFlags::CREATE))
.create_new(pflags.contains(OpenFlags::EXCLUDE))
.truncate(pflags.contains(OpenFlags::TRUNCATE))
.open(path)
.map_err(code)?;
@@ -213,6 +214,11 @@ impl russh_sftp::server::Handler for Sftp {
}
async fn setstat(&mut self, id: u32, path: String, attrs: FileAttributes) -> Result<Status, Self::Error> {
#[cfg(unix)]
if let Some(mode) = attrs.permissions {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(self.local(&path), std::fs::Permissions::from_mode(mode)).map_err(code)?;
}
if let Some(t) = attrs.mtime {
let time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.into());
let f = std::fs::File::options().write(true).open(self.local(&path)).map_err(code)?;
@@ -255,6 +261,12 @@ impl russh_sftp::server::Handler for Sftp {
Ok(ok(id))
}
#[cfg(unix)]
async fn symlink(&mut self, id: u32, target: String, link: String) -> Result<Status, Self::Error> {
std::os::unix::fs::symlink(target, self.local(&link)).map_err(code)?;
Ok(ok(id))
}
async fn rename(&mut self, id: u32, oldpath: String, newpath: String) -> Result<Status, Self::Error> {
std::fs::rename(self.local(&oldpath), self.local(&newpath)).map_err(code)?;
Ok(ok(id))
+49
Переглянути файл
@@ -348,6 +348,55 @@ fn run_raw_env_once(
Ok(Output { stdout: out.stdout, stderr: out.stderr, code: out.status.code() })
}
/// Captures binary/NUL-delimited read output while allowing cancellation to kill git.
pub(crate) fn run_cancellable(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
let out = run_cancellable_raw(root, args, cancel)?;
if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) }
}
/// Cancellable capture preserving exit codes for commands with documented non-error states.
pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = command(root)?;
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let mut session = CommandSession::start(&mut cmd);
let mut child = cmd.spawn().map_err(spawn_error)?;
let capture = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut bytes = Vec::new();
pipe.read_to_end(&mut bytes).map(|_| bytes)
})
};
let stdout = capture(Box::new(child.stdout.take().expect("piped stdout")));
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
let status = loop {
if cancel.is_cancelled() {
kill(&mut child);
let _ = child.wait();
let _ = stdout.join();
let _ = stderr.join();
return Err(IdeError::cancelled());
}
if let Some(status) = child.try_wait()? {
break status;
}
std::thread::sleep(Duration::from_millis(20));
};
let join = |thread: std::thread::JoinHandle<std::io::Result<Vec<u8>>>| {
thread.join().map_err(|_| IdeError::internal("git output reader panicked"))?.map_err(IdeError::from)
};
let out = Output { stdout: join(stdout)?, stderr: join(stderr)?, code: status.code() };
session.finish(status.success(), &String::from_utf8_lossy(&out.stderr));
Ok(out)
}
/// Runs git and maps a non-zero exit status to an error carrying git's message.
pub(crate) fn run(root: &Path, args: &[&str], stdin: Option<&[u8]>) -> IdeResult<Output> {
let out = run_raw(root, args, stdin)?;
+521
Переглянути файл
@@ -0,0 +1,521 @@
//! Selection-scoped revision → working-tree comparison over the existing root registry.
use crate::{ChangeKind, Repos, cli, ops};
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CompareScope {
pub repositories: Vec<IpcPath>,
/// Selected content outside registered repositories; workspace parents expand to their skipped children.
pub skipped_paths: Vec<IpcPath>,
pub single_file: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WorkingTreeChange {
pub path: String,
pub kind: ChangeKind,
pub old_path: Option<String>,
pub added: u32,
pub removed: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RepositoryComparison {
pub root: IpcPath,
/// Resolved commit, so opening a diff later uses the same left side as the listing.
pub revision: Option<String>,
pub files: Vec<WorkingTreeChange>,
pub error: Option<String>,
/// The requested revision does not resolve to a commit in this repository.
#[serde(default)]
pub missing_revision: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CompareResult {
pub repositories: Vec<RepositoryComparison>,
pub skipped_paths: Vec<IpcPath>,
}
fn normalized(path: &Path) -> PathBuf {
dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn comparison_children(path: &Path) -> Vec<PathBuf> {
std::fs::read_dir(path)
.into_iter()
.flatten()
.flatten()
.filter(|entry| entry.file_name() != ".git" && entry.file_name() != ".openidea")
.map(|entry| entry.path())
.collect()
}
impl Repos {
pub fn compare_scope(&self, paths: &[PathBuf]) -> CompareScope {
let paths: Vec<_> = paths.iter().map(|p| normalized(p)).collect();
let repositories = self
.all()
.iter()
.filter(|r| {
let root = normalized(r.root());
paths.iter().any(|p| {
root.starts_with(p)
|| self.at_root(p).or_else(|| self.for_path(p)).is_some_and(|owner| owner.root() == r.root())
})
})
.map(|r| IpcPath(r.root().to_path_buf()))
.collect();
let mut skipped = std::collections::BTreeSet::new();
for path in &paths {
if self.at_root(path).or_else(|| self.for_path(path)).is_some() {
continue;
}
if self.all().iter().any(|r| r.root().starts_with(path)) {
for child in comparison_children(path) {
if self.has_outside_content(&child) {
skipped.insert(child);
}
}
} else {
skipped.insert(path.clone());
}
}
let skipped_paths = skipped
.into_iter()
.map(|mut path| {
if path.is_dir() {
path.push("");
}
IpcPath(path)
})
.collect();
CompareScope { repositories, skipped_paths, single_file: paths.len() == 1 && !paths[0].is_dir() }
}
fn has_outside_content(&self, path: &Path) -> bool {
if self.at_root(path).or_else(|| self.for_path(path)).is_some() {
return false;
}
!self.all().iter().any(|r| r.root().starts_with(path))
|| comparison_children(path).iter().any(|child| self.has_outside_content(child))
}
pub fn compare_paths(
&self,
paths: &[PathBuf],
revision: &str,
repositories: Option<&[PathBuf]>,
cancel: &CancellationToken,
) -> IdeResult<CompareResult> {
if revision.trim().is_empty() || revision.starts_with('-') {
return Err(IdeError::invalid("invalid revision"));
}
let scope = self.compare_scope(paths);
let paths: Vec<_> = paths.iter().map(|p| normalized(p)).collect();
let mut result = CompareResult { repositories: Vec::new(), skipped_paths: scope.skipped_paths };
for root in scope.repositories {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if repositories.is_some_and(|roots| !roots.iter().any(|r| normalized(r) == normalized(&root.0))) {
continue;
}
let repo = self.at_root(&root.0).expect("scope comes from registry");
let _scope =
crate::ExecutionScope::enter(repo.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
let mut missing_revision = false;
let mut compare = || -> IdeResult<(String, Vec<WorkingTreeChange>)> {
// Worktree comparisons must not run repository-defined clean/process filters
// in Restricted Mode. External diff and textconv are disabled below as well.
let mut overrides = Vec::new();
if !crate::execution_allowed() {
let config = cli::run_cancellable(repo.root(), &["config", "--null", "--list"], cancel)?;
for record in config.stdout_str().split('\0') {
let key = record.split('\n').next().unwrap_or_default();
if key.starts_with("filter.")
&& (key.ends_with(".clean") || key.ends_with(".process") || key.ends_with(".required"))
{
overrides.push("-c".to_owned());
overrides.push(format!("{key}={}", if key.ends_with(".required") { "false" } else { "" }));
}
}
}
let run = |args: &[&str]| {
let mut full: Vec<&str> = overrides.iter().map(String::as_str).collect();
full.extend_from_slice(args);
cli::run_cancellable(repo.root(), &full, cancel)
};
// --quiet documents exit 1 for an unresolved revision; other failures keep their diagnostics.
let resolve_args =
["rev-parse", "--verify", "--quiet", "--end-of-options", &format!("{revision}^{{commit}}")];
let resolved = cli::run_cancellable_raw(repo.root(), &resolve_args, cancel)?;
if resolved.code != Some(0) {
missing_revision = resolved.code == Some(1);
return Err(cli::failure(&resolve_args, &resolved.stderr, &resolved.stdout, resolved.code));
}
let resolved = resolved.stdout_str().trim().to_owned();
// Disable textconv/external diff; these are also safe in untrusted projects.
let names =
run(&["diff", "--name-status", "-z", "-M", "--no-ext-diff", "--no-textconv", &resolved, "--"])?;
let stats = run(&[
"diff",
"--numstat",
"-z",
"--no-renames",
"--no-ext-diff",
"--no-textconv",
&resolved,
"--",
])?;
let stats: std::collections::HashMap<_, _> = ops::parse_numstat(&stats.stdout_str())
.into_iter()
.map(|(path, added, removed)| (path, (added, removed)))
.collect();
let mut files = Vec::new();
let contains = |rel: &str| {
let absolute = repo.root().join(rel);
// Nested clones contribute their own files, never the enclosing repo's entries.
let own = self.at_root(&absolute).or_else(|| self.for_path(&absolute));
own.is_some_and(|r| r.root() == repo.root()) && paths.iter().any(|p| absolute.starts_with(p))
};
for mut file in ops::parse_name_status(&names.stdout_str()) {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let new_in = contains(&file.path);
let old_in = file.old_path.as_deref().is_some_and(contains);
if !new_in && !old_in {
continue;
}
let original = file.path.clone();
if file.old_path.is_some() && new_in != old_in {
if old_in {
file.path = file.old_path.take().unwrap();
file.kind = ChangeKind::Deleted;
} else {
file.old_path = None;
file.kind = ChangeKind::Added;
}
}
let count = |path: &str| stats.get(path).copied().unwrap_or_default();
let (added, removed) = match &file.old_path {
Some(old) => (count(&original).0, count(old).1),
None => count(&file.path),
};
files.push(WorkingTreeChange {
path: file.path,
kind: file.kind,
old_path: file.old_path,
added,
removed,
});
}
if files.iter().any(|f| f.kind == ChangeKind::Renamed) {
let renamed =
run(&["diff", "--numstat", "-z", "-M", "--no-ext-diff", "--no-textconv", &resolved, "--"])?;
let indexes: std::collections::HashMap<_, _> = files
.iter()
.enumerate()
.filter(|(_, f)| f.kind == ChangeKind::Renamed)
.map(|(index, f)| (f.path.clone(), index))
.collect();
let mut records =
renamed.stdout_str().split('\0').map(str::to_owned).collect::<Vec<_>>().into_iter();
while let Some(record) = records.next() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let fields: Vec<_> = record.splitn(3, '\t').collect();
if fields.len() == 3 && fields[2].is_empty() {
let _old = records.next();
if let Some(path) = records.next()
&& let Some(index) = indexes.get(&path)
{
let file = &mut files[*index];
file.added = fields[0].parse().unwrap_or(0);
file.removed = fields[1].parse().unwrap_or(0);
}
}
}
}
let untracked = run(&["ls-files", "--others", "--exclude-standard", "-z"])?;
for path in untracked.stdout_str().split('\0').filter(|p| !p.is_empty() && contains(p)) {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let absolute = repo.root().join(path);
// Match the existing diff viewer's large/binary-file policy without loading large files for counts.
let added = if std::fs::metadata(&absolute).is_ok_and(|m| m.len() <= 10 * 1024 * 1024) {
let bytes = std::fs::read(&absolute).unwrap_or_default();
if bytes.contains(&0) {
0
} else {
(bytes.iter().filter(|b| **b == b'\n').count()
+ usize::from(!bytes.is_empty() && bytes.last() != Some(&b'\n')))
as u32
}
} else {
0
};
files.push(WorkingTreeChange {
path: path.to_owned(),
kind: ChangeKind::Untracked,
old_path: None,
added,
removed: 0,
});
}
files.sort_by(|a, b| a.path.cmp(&b.path));
Ok((resolved, files))
};
let comparison = match compare() {
Ok((revision, files)) => {
RepositoryComparison { root, revision: Some(revision), files, error: None, missing_revision: false }
}
Err(_) if cancel.is_cancelled() => return Err(IdeError::cancelled()),
Err(e) => RepositoryComparison {
root,
revision: None,
files: Vec::new(),
error: (!missing_revision).then_some(e.message),
missing_revision,
},
};
result.repositories.push(comparison);
}
Ok(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn git(root: &Path, args: &[&str]) {
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
}
fn write(root: &Path, path: &str, text: &str) {
let path = root.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn init(root: &Path, branch: &str) {
std::fs::create_dir_all(root).unwrap();
git(root, &["init", "-q", "-b", branch]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
write(root, "src/文件 name.txt", "old\n");
write(root, "src/move.txt", "move\n");
write(root, "other/stable.txt", "stable\n");
git(root, &["add", "."]);
git(root, &["commit", "-qm", "initial"]);
}
#[test]
fn subtree_union_worktree_untracked_and_rename_boundaries() {
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root, "main");
git(&root, &["switch", "-qc", "feature"]);
git(&root, &["mv", "src/move.txt", "other/moved.txt"]);
git(&root, &["commit", "-qm", "move out"]);
write(&root, "src/文件 name.txt", "old\nnew\n");
write(&root, "src/untracked space 中文.txt", "new\nfile\n");
write(&root, "other/stable.txt", "changed\n");
let repos = Repos::discover(&root, &|_| false).unwrap();
let cancel = CancellationToken::new();
let result = repos.compare_paths(&[root.join("src")], "main", None, &cancel).unwrap();
assert_eq!(result.repositories.len(), 1);
let files = &result.repositories[0].files;
assert_eq!(files.len(), 3, "{files:?}");
let moved = files.iter().find(|f| f.path == "src/move.txt").unwrap();
assert_eq!(moved.kind, ChangeKind::Deleted);
assert_eq!((moved.added, moved.removed), (0, 1));
assert!(moved.old_path.is_none());
let changed = files.iter().find(|f| f.path == "src/文件 name.txt").unwrap();
assert_eq!((changed.added, changed.removed), (1, 0));
let untracked = files.iter().find(|f| f.path == "src/untracked space 中文.txt").unwrap();
assert_eq!((untracked.kind, untracked.added), (ChangeKind::Untracked, 2));
let union = repos
.compare_paths(&[root.join("src"), root.join("other"), root.join("src")], "main", None, &cancel)
.unwrap();
assert_eq!(union.repositories[0].files.len(), 4);
let rename = union.repositories[0].files.iter().find(|f| f.path == "other/moved.txt").unwrap();
assert_eq!(rename.kind, ChangeKind::Renamed);
assert_eq!(rename.old_path.as_deref(), Some("src/move.txt"));
assert_eq!((rename.added, rename.removed), (0, 0));
let into = repos.compare_paths(&[root.join("other")], "main", None, &cancel).unwrap();
assert_eq!(
into.repositories[0].files.iter().find(|f| f.path == "other/moved.txt").unwrap().kind,
ChangeKind::Added
);
}
#[test]
fn workspace_roots_missing_revision_loose_paths_and_empty_results() {
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
for name in ["client", "server", "admin"] {
init(&root.join(name), if name == "admin" { "trunk" } else { "main" });
}
write(&root, "loose/readme.txt", "not git\n");
write(&root.join("client"), "src/new.txt", "client\n");
write(&root.join("server"), "src/文件 name.txt", "server\n");
let repos = Repos::discover(&root, &|_| false).unwrap();
let scope = repos.compare_scope(std::slice::from_ref(&root));
assert_eq!(scope.repositories.len(), 3);
assert_eq!(scope.skipped_paths, [IpcPath(root.join("loose"))]);
assert!(!scope.single_file);
assert!(repos.compare_scope(&[root.join("client/src/文件 name.txt")]).single_file);
let cancel = CancellationToken::new();
let result = repos.compare_paths(&[root.clone(), root.join("loose")], "main", None, &cancel).unwrap();
assert_eq!(result.repositories.len(), 3);
assert_eq!(result.repositories.iter().filter(|r| r.missing_revision).count(), 1);
assert!(result.repositories[0].missing_revision, "admin lacks main");
assert!(result.repositories[0].error.is_none());
assert_eq!(result.repositories[1].files.len(), 1);
assert_eq!(result.repositories[2].files.len(), 1);
assert_eq!(result.skipped_paths, [IpcPath(root.join("loose"))]);
let filtered =
repos.compare_paths(std::slice::from_ref(&root), "main", Some(&[root.join("server")]), &cancel).unwrap();
assert_eq!(filtered.repositories.len(), 1);
assert_eq!(filtered.repositories[0].root.0, root.join("server"));
let empty = repos.compare_paths(&[root.join("server/other")], "main", None, &cancel).unwrap();
assert!(empty.repositories[0].files.is_empty());
let loose = repos.compare_paths(&[root.join("loose")], "main", None, &cancel).unwrap();
assert!(loose.repositories.is_empty());
assert_eq!(loose.skipped_paths, [IpcPath(root.join("loose"))]);
cancel.cancel();
assert!(repos.compare_paths(&[root], "main", None, &cancel).is_err());
}
#[test]
fn nested_repositories_are_not_reported_twice_and_binary_counts_are_zero() {
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root, "main");
init(&root.join("nested"), "main");
write(&root.join("nested"), "src/new.txt", "nested\n");
std::fs::write(root.join("src/image.bin"), [0, 1, 2]).unwrap();
let repos = Repos::discover(&root, &|_| false).unwrap();
let result = repos.compare_paths(std::slice::from_ref(&root), "main", None, &CancellationToken::new()).unwrap();
assert_eq!(result.repositories.len(), 2);
assert_eq!(result.repositories[0].files.len(), 1);
assert_eq!(result.repositories[0].files[0].added, 0);
assert_eq!(result.repositories[1].files.len(), 1);
let nested = repos.compare_paths(&[root.join("nested")], "main", None, &CancellationToken::new()).unwrap();
assert_eq!(nested.repositories.len(), 1);
assert_eq!(nested.repositories.iter().map(|r| r.files.len()).sum::<usize>(), 1);
}
#[test]
fn skipped_children_only_report_content_outside_repositories() {
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root.join("services/server"), "main");
init(&root.join("client"), "main");
write(&root, ".openidea/state.json", "{}");
write(&root, ".git/config", "ignored metadata");
let repos = Repos::discover(&root, &|_| false).unwrap();
assert!(repos.compare_scope(std::slice::from_ref(&root)).skipped_paths.is_empty());
write(&root, "services/notes.txt", "loose nested content");
write(&root, "loose/readme.txt", "loose");
write(&root, "readme.txt", "loose file");
let scope = repos.compare_scope(&[root.clone(), root.join("loose")]);
assert_eq!(
scope.skipped_paths,
[IpcPath(root.join("loose")), IpcPath(root.join("readme.txt")), IpcPath(root.join("services")),]
);
assert!(scope.skipped_paths[0].0.to_string_lossy().ends_with(std::path::MAIN_SEPARATOR));
}
#[test]
fn missing_revision_is_typed_and_other_errors_keep_only_the_message() {
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root, "main");
let repos = Repos::discover(&root, &|_| false).unwrap();
let cancel = CancellationToken::new();
let result = repos.compare_paths(std::slice::from_ref(&root), "missing-revision", None, &cancel).unwrap();
assert!(result.repositories[0].missing_revision);
assert!(result.repositories[0].error.is_none());
std::fs::write(root.join(".git/config"), "[broken").unwrap();
let result = repos.compare_paths(&[root], "main", None, &cancel).unwrap();
assert!(!result.repositories[0].missing_revision);
let error = result.repositories[0].error.as_deref().unwrap();
assert!(error.contains("bad config"), "{error}");
assert!(!error.starts_with("Internal:"), "{error}");
}
#[cfg(unix)]
#[test]
fn untracked_read_and_metadata_failures_leave_files_with_zero_counts() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root, "main");
// Reading a directory fails after successful metadata; a dangling link fails metadata.
symlink(root.join("src"), root.join("unreadable")).unwrap();
symlink(root.join("vanished"), root.join("missing")).unwrap();
write(&root, "new.txt", "still counted\n");
let repos = Repos::discover(&root, &|_| false).unwrap();
let result = repos.compare_paths(&[root], "main", None, &CancellationToken::new()).unwrap();
let repo = &result.repositories[0];
assert!(repo.error.is_none(), "{repo:?}");
assert_eq!(repo.files.len(), 3);
for name in ["unreadable", "missing"] {
let file = repo.files.iter().find(|f| f.path == name).unwrap();
assert_eq!((file.kind, file.added, file.removed), (ChangeKind::Untracked, 0, 0));
}
assert_eq!(repo.files.iter().find(|f| f.path == "new.txt").unwrap().added, 1);
}
#[cfg(unix)]
#[test]
fn restricted_comparison_does_not_execute_repository_commands() {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let root = normalized(temp.path());
init(&root, "main");
let script = root.join(".git/marker.sh");
let marker = root.join(".git/executed");
std::fs::write(&script, "#!/bin/sh\ntouch .git/executed\n").unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let script = script.to_str().unwrap();
for key in [
"core.fsmonitor",
"filter.marker.clean",
"filter.marker.process",
"diff.marker.command",
"diff.marker.textconv",
] {
git(&root, &["config", key, script]);
}
git(&root, &["config", "filter.marker.required", "true"]);
write(&root, ".gitattributes", "*.txt filter=marker diff=marker\n");
write(&root, "src/文件 name.txt", "changed\n");
write(&root, "new.txt", "untracked\n");
let repos = Repos::discover(&root, &|_| false).unwrap();
for repo in repos.all() {
repo.set_execution_allowed(false);
}
let result = repos.compare_paths(std::slice::from_ref(&root), "main", None, &CancellationToken::new()).unwrap();
assert!(result.repositories[0].error.is_none(), "{result:?}");
assert_eq!(result.repositories[0].files.len(), 3);
assert!(!marker.exists(), "Restricted Mode executed a repository command");
// Prove the fixture's fsmonitor hook is active when the shared wrapper is bypassed.
git(&root, &["ls-files"]);
assert!(marker.exists(), "control invocation did not run fsmonitor");
}
}
+2
Переглянути файл
@@ -453,6 +453,7 @@ pub struct ChangelistState {
mod blame;
pub mod changelists;
mod cli;
mod compare;
mod diff;
mod history;
mod ignore;
@@ -464,6 +465,7 @@ mod refs;
mod remotes;
mod repo;
mod roots;
pub use compare::{CompareResult, CompareScope, RepositoryComparison, WorkingTreeChange};
pub mod shelf;
mod status;
pub use index_writes::is_own_index_write;
+8
Переглянути файл
@@ -1555,6 +1555,14 @@ fn restricted_reads_ignore_executable_repository_configuration() {
assert!(!repo.log(&LogQuery::default()).unwrap().is_empty());
repo.merge_versions(&f.path("a.txt"), encoding_rs::UTF_8).unwrap();
assert!(!f.path("execution.marker").exists());
let repos = ide_vcs::Repos::discover(&f.dir, &|_| false).unwrap();
for r in repos.all() {
r.set_execution_allowed(false);
}
let compared =
repos.compare_paths(std::slice::from_ref(&f.dir), "HEAD", None, &ide_core::CancellationToken::new()).unwrap();
assert!(compared.repositories.iter().all(|r| r.error.is_none()));
assert!(!f.path("execution.marker").exists());
// Positive control: the same filter really executes without restriction.
f.git(&["-c", "core.fsmonitor=false", "diff", "--no-ext-diff", "--no-textconv"]);
assert!(f.path("execution.marker").exists());
+74
Переглянути файл
@@ -0,0 +1,74 @@
{
"languages": [
"xml",
"html",
"vue",
"svelte",
"css",
"java",
"rust",
"typescript",
"python",
"csharp",
"sql",
"clojure",
"erlang",
"bat",
"ocaml",
"fsharp",
"haskell",
"lua",
"cmake",
"powershell",
"julia",
"ruby"
],
"markers": [
{
"start": "region Name",
"end": "endregion",
"name": "Name"
},
{
"start": "region要折叠的内容",
"end": "endregion",
"name": "要折叠的内容"
},
{
"start": "#region \"Quoted name\"",
"end": "#endregion",
"name": "Quoted name"
},
{
"start": "REGION Mixed case",
"end": "ENDREGION",
"name": "Mixed case"
},
{
"start": "region",
"end": "endregion",
"name": ""
},
{
"start": "<editor-fold desc=\"Head 内容\">",
"end": "</editor-fold>",
"name": "Head 内容"
},
{
"start": "<editor-fold>",
"end": "</editor-fold>",
"name": ""
}
],
"invalid": [
"regional Name",
"regions.push(x)",
"endregionFoo",
"<editor-folder>",
"</editor-folder>",
"the region below",
"region_name",
"<editor-fold",
"</editor-fold"
]
}
+3
Переглянути файл
@@ -271,6 +271,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_add_worktree,
vcs::vcs_remove_worktree,
vcs::vcs_diff_with_worktree,
vcs::vcs_compare_scope,
vcs::vcs_compare_paths,
vcs::vcs_diff_revisions,
vcs::vcs_merge_base,
vcs::vcs_create_patch,
@@ -477,6 +479,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
crate::remote_dev::remote_current,
crate::remote_dev::remote_disconnect,
crate::remote_dev::remote_invoke,
crate::remote_dev::remote_import_local,
env::env_reload,
db::db_test,
db::db_connected,
+23
Переглянути файл
@@ -680,3 +680,26 @@ pub async fn vcs_shelf_import(
) -> IdeResult<()> {
ide_host::ops::vcs::vcs_shelf_import(&state.host, window.label(), name, patch).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_compare_scope(
window: Window,
state: State<'_, AppState>,
paths: Vec<PathBuf>,
) -> IdeResult<ide_vcs::CompareScope> {
ide_host::ops::vcs::vcs_compare_scope(&state.host, window.label(), paths).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_compare_paths(
window: Window,
state: State<'_, AppState>,
paths: Vec<PathBuf>,
revision: String,
repositories: Option<Vec<PathBuf>>,
request: RequestId,
) -> IdeResult<ide_vcs::CompareResult> {
ide_host::ops::vcs::vcs_compare_paths(&state.host, window.label(), paths, revision, repositories, request).await
}
+10 -1
Переглянути файл
@@ -95,10 +95,19 @@ pub fn run() {
let label = label.to_owned();
let command = request.message.command().to_owned();
let invoke = invoke.clone();
let app = webview.app_handle().clone();
tauri::async_runtime::spawn(async move {
match connection.authorize_command(&label, &command).await {
Ok(()) => {
invoke(request);
let resolver = request.resolver.clone();
// Sync commands must run on the main thread, as they do in local windows.
if let Err(error) = app.run_on_main_thread(move || {
invoke(request);
}) {
resolver.reject(ide_core::IdeError::internal(format!(
"failed to dispatch command on the main thread: {error}"
)));
}
}
Err(error) => request.resolver.reject(error),
}
+25
Переглянути файл
@@ -468,6 +468,31 @@ pub async fn remote_invoke(
Ok(result.to_string())
}
/// A client OS file belongs to this machine even when its destination is remote.
#[tauri::command]
#[specta::specta]
pub async fn remote_import_local(
window: Window,
state: State<'_, AppState>,
from: std::path::PathBuf,
to: String,
request: ide_core::RequestId,
) -> IdeResult<Vec<String>> {
let label = AppState::owner_window(window.label());
let c = state.remote_dev.get(label).ok_or_else(|| IdeError::unavailable("Remote project is disconnected"))?;
c.authorize_command(label, "fs_copy").await?;
let cancel = state.host.begin_request(request);
let result = async {
let fs = ide_ssh::RemoteFs::new(c._session.sftp().await?);
let result = ide_remote::import::import_local(&fs, &from, &to, &cancel).await;
fs.close().await;
result
}
.await;
state.host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
+34
Переглянути файл
@@ -509,6 +509,8 @@ export const commands = {
vcsRemoveWorktree: (repo: string | null, path: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remove_worktree", { repo, path, force })),
/** Compare with Local: tracked files that differ between `rev` and the working tree. */
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
vcsCompareScope: (paths: string[]) => typedError<CompareScope, IdeError>(__TAURI_INVOKE("vcs_compare_scope", { paths })),
vcsComparePaths: (paths: string[], revision: string, repositories: string[] | null, request: RequestId) => typedError<CompareResult, IdeError>(__TAURI_INVOKE("vcs_compare_paths", { paths, revision, repositories, request })),
/** Files that differ between two revisions (the "N files updated" of Update Project). */
vcsDiffRevisions: (repo: string | null, from: string, to: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_revisions", { repo, from, to })),
/** The best common ancestor of `a` and `b` (`git merge-base`), if any. */
@@ -1016,6 +1018,8 @@ export const commands = {
* `on_channel` tagged with the id.
*/
remoteInvoke: (cmd: string, args: string, onChannel: Channel<ChannelFrame>) => typedError<string, IdeError>(__TAURI_INVOKE("remote_invoke", { cmd, args, onChannel })),
/** A client OS file belongs to this machine even when its destination is remote. */
remoteImportLocal: (from: string, to: string, request: RequestId) => typedError<string[], IdeError>(__TAURI_INVOKE("remote_import_local", { from, to, request })),
/**
* Reload Environment: new child processes get the login shell's current environment
* (and the project's `remoteEnv` on a remote host); running ones keep theirs.
@@ -1886,6 +1890,18 @@ export type CommitSettings = {
wrapAtMargin?: boolean,
};
export type CompareResult = {
repositories: RepositoryComparison[],
skippedPaths: IpcPath[],
};
export type CompareScope = {
repositories: IpcPath[],
/** Selected content outside registered repositories; workspace parents expand to their skipped children. */
skippedPaths: IpcPath[],
singleFile: boolean,
};
export type CompletionItem = {
label: string,
/** e.g. `(req: CreateOrderRequest)` shown right after the label. */
@@ -5123,6 +5139,16 @@ export type ReplaceTarget = {
only?: Pos[] | null,
};
export type RepositoryComparison = {
root: IpcPath,
/** Resolved commit, so opening a diff later uses the same left side as the listing. */
revision: string | null,
files: WorkingTreeChange[],
error: string | null,
/** The requested revision does not resolve to a commit in this repository. */
missingRevision?: boolean,
};
/** A cancellable, streaming backend request issued by the UI. */
export type RequestId = number;
@@ -6292,6 +6318,14 @@ export type WindowTab = {
current: boolean,
};
export type WorkingTreeChange = {
path: string,
kind: ChangeKind,
oldPath: string | null,
added: number,
removed: number,
};
export type Workspace = Workspace_Serialize | Workspace_Deserialize;
/** Edits to many files, applied atomically from the user's point of view. */
+1 -1
Переглянути файл
@@ -337,7 +337,7 @@ function showContextInfo(view: EditorView) {
/** Navigate › Custom Folding (⌥⌘.): the file's custom regions; picking one moves the caret to it. */
function showCustomRegions(view: EditorView) {
const regions = customRegions(view.state.doc);
const regions = customRegions(view.state);
if (!regions.length) return void executeAction("editor.showHint", { text: "No custom folding regions in this file" });
const head = view.state.selection.main.head;
openPopup({
+32 -2
Переглянути файл
@@ -22,6 +22,9 @@ import {
type TextChange,
} from "@/platform/ipc";
import { EditorState } from "@codemirror/state";
import { customRegions } from "./cm/regions";
export type LanguageInfo = LanguageInfo_Serialize;
export interface DocPatchedEvent {
@@ -129,6 +132,8 @@ const EXT_LANG: Record<string, string> = {
cmd: "bat",
sql: "sql",
xml: "xml",
svg: "xml",
vue: "vue",
};
const MEM_LANGUAGES: LanguageInfo[] = [
@@ -240,6 +245,15 @@ const MEM_LANGUAGES: LanguageInfo[] = [
blockComment: null,
indent: { tabSize: 4, insertSpaces: true },
},
...["xml", "html", "vue", "css"].map((id): LanguageInfo => ({
id,
name: id.toUpperCase(),
extensions: id === "xml" ? ["xml", "svg"] : [id],
uiMode: id === "xml" ? "XML" : id === "css" ? "CSS" : id === "vue" ? "Vue" : "HTML",
lineComment: null,
blockComment: id === "css" ? ["/*", "*/"] : ["<!--", "-->"],
indent: { tabSize: 2, insertSpaces: true },
})),
{
id: "plaintext",
name: "Plain Text",
@@ -507,8 +521,24 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
},
async folding(doc) {
const d = get(doc);
const out: FoldRange[] = [];
const seen = new Set<number>();
const info = MEM_LANGUAGES.find((language) => language.id === d.language);
const state = EditorState.create({
doc: d.text,
extensions: EditorState.languageData.of(() => [
{
commentTokens: {
line: info?.lineComment ?? undefined,
block: info?.blockComment && { open: info.blockComment[0], close: info.blockComment[1] },
},
},
]),
});
const out: FoldRange[] = customRegions(state).map((region) => ({
start_line: region.startLine - 1,
end_line: region.endLine - 1,
kind: "region",
}));
const seen = new Set(out.map((fold) => fold.start_line));
const stack: number[] = [];
d.text.split("\n").forEach((line, i) => {
for (const ch of line) {
+206
Переглянути файл
@@ -0,0 +1,206 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { clipboardDocumentPath, clipboardFilesExtension, pasteEditorClipboard } from "./clipboard";
import { markdownImages } from "./markdownImages";
vi.mock("@/platform/remote", () => ({ isRemoteWindow: vi.fn(() => false) }));
const views: EditorView[] = [];
beforeEach(() => {
vi.stubGlobal("__TAURI_INTERNALS__", {});
Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) });
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: vi.fn(() => false) });
});
afterEach(() => {
views.splice(0).forEach((view) => view.destroy());
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
for (const route of ["event", "menu", "menu unsupported", "menu rejected"]) {
it.each([
{ name: "file", paths: ["/p/docs/file.txt"], expected: "[](file.txt)" },
{ name: "folder", paths: ["/p/docs/folder"], expected: "[](folder)" },
{ name: "several", paths: ["/p/docs/a.txt", "/p/folder"], expected: "[](a.txt)\n[](../folder)" },
{
name: "spaces, Chinese, and delimiters",
paths: ["/p/docs/中文/a (1)#!'*.txt"],
expected: "[](%E4%B8%AD%E6%96%87/a%20%281%29%23%21%27%2A.txt)",
},
{ name: "parent relative", paths: ["/p/file.txt"], expected: "[](../file.txt)" },
{
name: "Windows separators",
path: "C:\\p\\docs\\a.md",
paths: ["C:\\p\\folder\\a b.txt"],
expected: "[](../folder/a%20b.txt)",
},
{ name: "no document path", path: "", paths: ["/p/file.txt"], expected: "/p/file.txt" },
{ name: "non-Markdown", path: "/p/a.ts", paths: ["/p/file.txt"], expected: "/p/file.txt" },
{
name: "remote window with client file paths",
remote: true,
path: "/home/dev/a.md",
paths: ["/Users/me/file.txt", "/Users/me/中文 文件夹"],
expected: "/Users/me/file.txt\n/Users/me/中文 文件夹",
},
{
name: "remote window with matching text flavor",
remote: true,
path: "/home/dev/a.md",
text: "C:\\Users\\me\\file.txt",
paths: ["C:/Users/me/file.txt"],
expected: "C:\\Users\\me\\file.txt",
},
{ name: "alternate extension", path: "/p/docs/a.MDX", paths: ["/p/docs/file"], expected: "[](file)" },
{ name: "empty list", paths: [], expected: "" },
{ name: "text path", text: "/p/file.txt", paths: ["/stale"], expected: "/p/file.txt" },
{ name: "plain text", text: "plain text 你好", paths: [], expected: "plain text 你好" },
{
name: "file list with matching text flavor",
text: "C:\\p\\a.txt\r\nC:\\p\\folder",
path: "C:/p/docs/a.md",
paths: ["C:/p/a.txt", "C:/p/folder"],
expected: "[](../a.txt)\n[](../folder)",
},
])(`${route}: Markdown $name`, async ({ path = "/p/docs/a.md", paths, text = "", expected, remote = false }) => {
vi.mocked(isRemoteWindow).mockReturnValue(remote);
const list = vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: paths });
const view = new EditorView({
extensions: [clipboardDocumentPath.of(path), clipboardFilesExtension],
parent: document.body,
});
views.push(view);
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text, files: [], types: ["Files"] },
});
if (route === "event") {
view.contentDOM.dispatchEvent(event);
} else {
if (route === "menu") {
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
vi.mocked(document.execCommand).mockImplementation(() => {
view.contentDOM.dispatchEvent(event);
return true;
});
}
if (route === "menu rejected") vi.mocked(document.queryCommandSupported).mockReturnValue(true);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => text } });
await pasteEditorClipboard(view);
}
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(expected));
expect(list).toHaveBeenCalledTimes(remote && text ? 0 : 1);
if (route === "menu rejected" && /\.(md|mdx)$/i.test(path)) {
expect(document.execCommand).toHaveBeenCalledExactlyOnceWith("paste");
}
});
it.each([
{ name: "text present", text: "plain", paths: ["/stale"], expected: "plain", calls: 0 },
{ name: "files plus list", text: "", paths: ["/a b", "/中文"], expected: "/a b\n/中文", calls: 1 },
{ name: "files without list", text: "", paths: [], expected: "", calls: 1 },
{ name: "backend error", text: "", paths: null, expected: "", calls: 1 },
])(`${route}: $name`, async ({ text, paths, expected, calls }) => {
const list = vi.spyOn(commands, "clipboardFileList");
if (paths) list.mockResolvedValue({ status: "ok", data: paths });
else list.mockRejectedValue(new Error("busy"));
const view = new EditorView({ extensions: [clipboardFilesExtension], parent: document.body });
views.push(view);
if (route === "event") {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text, files: [], types: ["Files"] },
});
view.contentDOM.dispatchEvent(event);
} else {
if (route === "menu rejected") vi.mocked(document.queryCommandSupported).mockReturnValue(true);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => text } });
await pasteEditorClipboard(view);
}
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(expected));
expect(list).toHaveBeenCalledTimes(calls);
});
}
it("does not fall back while a successful native paste is still pending", async () => {
const readText = vi.fn(async () => "fallback");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText } });
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
vi.mocked(document.execCommand).mockReturnValue(true);
const view = new EditorView({
extensions: [clipboardDocumentPath.of("/p/a.md"), clipboardFilesExtension],
parent: document.body,
});
views.push(view);
await pasteEditorClipboard(view);
expect(view.state.doc.toString()).toBe("");
expect(readText).not.toHaveBeenCalled();
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => "native text", files: [], types: ["text/plain"] },
});
view.contentDOM.dispatchEvent(event);
expect(view.state.doc.toString()).toBe("native text");
});
it.each([
["event", true],
["event", false],
["menu", true],
["menu", false],
])("%s: keeps copied PNG and screenshot Markdown image handling (file: %s)", async (route, hasFile) => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
}
},
);
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({
status: "ok",
data: hasFile ? ["/source/image.png"] : [],
});
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const view = new EditorView({
extensions: [
clipboardDocumentPath.of("/p/a.md"),
clipboardFilesExtension,
markdownImages({ path: "/p/a.md", folder: "assets", pattern: "image-{timestamp}" }),
],
parent: document.body,
});
views.push(view);
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => "", files: [new File(["png"], "image.png", { type: "image/png" })], types: ["Files"] },
});
if (route === "menu") {
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
vi.mocked(document.execCommand).mockImplementation(() => {
view.contentDOM.dispatchEvent(event);
return true;
});
await pasteEditorClipboard(view);
expect(document.execCommand).toHaveBeenCalledWith("paste");
} else view.contentDOM.dispatchEvent(event);
await vi.waitFor(() => expect(view.state.doc.toString()).toMatch(/^!\[\]\(assets\/image.*\.png\)$/));
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
});
it("does not insert into a read-only editor", async () => {
const list = vi.spyOn(commands, "clipboardFileList");
const view = new EditorView({ extensions: [clipboardFilesExtension, EditorState.readOnly.of(true)] });
views.push(view);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "text" } });
await pasteEditorClipboard(view);
expect(view.state.doc.toString()).toBe("");
expect(list).not.toHaveBeenCalled();
});
+46
Переглянути файл
@@ -0,0 +1,46 @@
import { Facet, Prec } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
import { isRemoteWindow } from "@/platform/remote";
import { isMarkdown, relativeImagePath } from "./markdownImages";
export const clipboardDocumentPath = Facet.define<string, string>({ combine: (paths) => paths[0] ?? "" });
function clipboardFileFormatter(view: EditorView): ((paths: string[]) => string) | undefined {
const path = view.state.facet(clipboardDocumentPath);
return isMarkdown(path) && !isRemoteWindow()
? (paths) => paths.map((target) => `[](${relativeImagePath(path, target)})`).join("\n")
: undefined;
}
export function pasteEditorText(view: EditorView, text: string) {
if (!text || !view.dom.isConnected || view.state.readOnly) return;
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
view.focus();
}
export async function pasteEditorClipboard(view: EditorView) {
if (!view.dom.isConnected || view.state.readOnly) return;
try {
// Successful native paste preserves image blobs and may complete after execCommand returns.
if (isMarkdown(view.state.facet(clipboardDocumentPath)) && document.queryCommandSupported("paste")) {
view.focus();
if (document.execCommand("paste")) return;
}
pasteEditorText(view, await readClipboardText(undefined, clipboardFileFormatter(view)));
} catch {
if (!view.dom.isConnected || view.state.readOnly) return;
view.focus();
document.execCommand("paste");
}
}
// Markdown image handlers get first refusal, including copied image files.
export const clipboardFilesExtension = Prec.lowest(
EditorView.domEventHandlers({
paste(event, view) {
if (view.state.readOnly) return false;
return pasteClipboardFiles(event, (text) => pasteEditorText(view, text), clipboardFileFormatter(view));
},
}),
);
+4 -1
Переглянути файл
@@ -78,7 +78,10 @@ describe("foldsFromRanges", () => {
});
it("folds a custom region from its start marker through its end marker", () => {
const s = EditorState.create({ doc: "class A {\n //region Fields\n int a;\n //endregion\n}\n" });
const s = EditorState.create({
doc: "class A {\n //region Fields\n int a;\n //endregion\n}\n",
extensions: EditorState.languageData.of(() => [{ commentTokens: { line: "//" } }]),
});
const [f] = foldsFromRanges(s, [fold(1, 3)]);
expect(f).toMatchObject({ from: s.doc.line(2).from + 2, to: s.doc.line(4).to, custom: true });
});
+2 -2
Переглянути файл
@@ -24,7 +24,7 @@ import {
} from "@codemirror/language";
import type { FoldRange } from "@/platform/ipc";
import { enclosingCodeBlock } from "./caretCommands";
import { regionMarker, regionNameAt } from "./regions";
import { regionMarkerAt, regionNameAt } from "./regions";
export interface BackendFold {
/** Offset where the fold starts (end of the header line). */
@@ -58,7 +58,7 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
if (r.start_line + 1 > lines || r.end_line + 1 > lines || r.end_line <= r.start_line) continue;
const first = state.doc.line(r.start_line + 1);
const end = state.doc.line(r.end_line + 1);
if (regionMarker(first.text)?.start) {
if (regionMarkerAt(state, first)?.start) {
const from = first.from + /^\s*/.exec(first.text)![0].length;
if (end.to > from) out.push({ from, to: end.to, kind: r.kind, custom: true });
continue;
+94 -35
Переглянути файл
@@ -1,48 +1,107 @@
import { describe, expect, it } from "vitest";
import { EditorState, Text } from "@codemirror/state";
import { customRegions, regionMarker, regionNameAt } from "./regions";
import { EditorState } from "@codemirror/state";
import fixture from "../../../../fixtures/folding/regions.json";
import { createMemoryBackend } from "../backend";
import { commentTokens } from "./languages";
import { foldsFromRanges } from "./folding";
import { customRegions, regionMarker, regionNameAt, type RegionCommentTokens } from "./regions";
const definitions = import.meta.glob<string>("../../../../languages/*.toml", {
query: "?raw",
import: "default",
eager: true,
});
function language(id: string) {
const source = definitions[`../../../../languages/${id}.toml`]!;
const lineComment = /^line-comment = (".*")$/m.exec(source)?.[1];
const blockComment = /^block-comment = (\[.*\])$/m.exec(source)?.[1];
return {
id,
name: id,
extensions: [],
uiMode: null,
indent: null,
lineComment: lineComment ? (JSON.parse(lineComment) as string) : null,
blockComment: blockComment ? (JSON.parse(blockComment) as [string, string]) : null,
};
}
const make = (doc: string, id = "java") => EditorState.create({ doc, extensions: commentTokens(language(id)) });
// The native folding suite consumes this same marker contract and the TOML tokens.
describe.each(fixture.languages)("custom regions in %s", (id) => {
const info = language(id);
const tokens: RegionCommentTokens = {
line: info.lineComment ?? undefined,
block: info.blockComment ? { open: info.blockComment[0], close: info.blockComment[1] } : undefined,
};
const delimiters: [string, string][] = [];
if (tokens.line) delimiters.push([tokens.line, ""]);
if (tokens.block) delimiters.push([tokens.block.open, tokens.block.close]);
it.each(delimiters)("uses %s … %s with optional spaces", (open, close) => {
for (const space of ["", " ", " "]) {
if (!space && /[a-z0-9]$/i.test(open)) continue;
const wrap = (body: string) => ` ${open}${space}${body}${space}${close}`;
for (const marker of fixture.markers) {
const start = wrap(marker.start);
const end = wrap(marker.end);
expect(regionMarker(start, tokens)).toEqual({ start: true, name: marker.name });
expect(regionMarker(end, tokens)).toEqual({ start: false });
const state = make(`${start}\n\n${end}\n`, id);
expect(customRegions(state)).toEqual([{ name: marker.name, startLine: 1, endLine: 3 }]);
expect(regionNameAt(state, 2)).toBe(marker.name || null);
expect(regionNameAt(state, 5)).toBeNull();
const [fold] = foldsFromRanges(state, [{ start_line: 0, end_line: 2, kind: "region" }]);
expect(fold).toMatchObject({ from: 2, to: state.doc.line(3).to, custom: true });
const nested = make(`${end}\n\n${start}\n${start}\n\n${end}\n${end}\n${start}\n`, id);
expect(customRegions(nested)).toEqual([
{ name: marker.name, startLine: 3, endLine: 7 },
{ name: marker.name, startLine: 4, endLine: 6 },
]);
}
for (const invalid of fixture.invalid) expect(regionMarker(wrap(invalid), tokens)).toBeNull();
}
});
});
describe("regionMarker", () => {
it.each([
["//region Accessors", "Accessors"],
[" // region Accessors", "Accessors"],
["#region Setup", "Setup"],
["# region Setup", "Setup"],
["//#region Setup", "Setup"],
['// <editor-fold desc="Getters">', "Getters"],
['<!-- <editor-fold desc="Head"> -->', "Head"],
["/* region Block */", "Block"],
["//region", ""],
])("start %s", (line, name) => {
expect(regionMarker(line)).toEqual({ start: true, name });
it.each(["///region Docs", "/**region Docs*/", "// #region Docs"])("preserves %s", (text) => {
expect(regionMarker(text, { line: "//", block: { open: "/*", close: "*/" } })).toEqual({
start: true,
name: "Docs",
});
});
it.each(["//endregion", "# endregion", "#endregion", "// </editor-fold>", "<!-- </editor-fold> -->"])(
"end %s",
(line) => {
expect(regionMarker(line)).toEqual({ start: false });
it.each(["const region = 1;", "region Name", "//region Wrong language", "<!--region Missing close"])(
"rejects %s in XML",
(text) => {
expect(regionMarker(text, { block: { open: "<!--", close: "-->" } })).toBeNull();
},
);
it.each(["const region = 1;", "// the region below", "regions.push(x)"])("not a marker: %s", (line) => {
expect(regionMarker(line)).toBeNull();
it("preserves C# region directives and their names", () => {
const state = make('#region "Fields"\nint a;\n#endregion', "csharp");
expect(customRegions(state)).toEqual([{ name: "Fields", startLine: 1, endLine: 3 }]);
expect(regionNameAt(state, 0)).toBe("Fields");
expect(foldsFromRanges(state, [{ start_line: 0, end_line: 2, kind: "region" }])[0]?.custom).toBe(true);
});
it("does not list plain text as a region without comment tokens", () => {
expect(customRegions(EditorState.create({ doc: "region Name\n\nendregion" }))).toEqual([]);
});
});
describe("customRegions", () => {
it("matches nested markers and drops unclosed ones", () => {
const doc = Text.of(["//region A", "//region B", "x", "//endregion", "//endregion", "//region C"]);
expect(customRegions(doc)).toEqual([
{ name: "A", startLine: 1, endLine: 5 },
{ name: "B", startLine: 2, endLine: 4 },
]);
});
});
describe("regionNameAt", () => {
it("names a fold starting at a start marker", () => {
const state = EditorState.create({ doc: " //region Fields\nint a;\n//endregion" });
expect(regionNameAt(state, 2)).toBe("Fields");
expect(regionNameAt(state, 5)).toBeNull();
describe("memory backend custom folding", () => {
it.each(["xml", "svg", "html", "vue", "css", "java", "py", "ts"])("folds %s markers", async (extension) => {
const path = `/project/file.${extension}`;
const css = extension === "css";
const line = extension === "py" ? "#" : ["java", "ts"].includes(extension) ? "//" : null;
const open = line ?? (css ? "/*" : "<!--");
const close = line ? "" : css ? "*/" : "-->";
const backend = createMemoryBackend({ [path]: `${open}region Name${close}\ncontent\n${open}endregion${close}\n` });
const doc = await backend.open(path);
expect(await backend.folding(doc.id)).toEqual([{ start_line: 0, end_line: 2, kind: "region" }]);
});
});
+39 -11
Переглянути файл
@@ -1,30 +1,51 @@
/**
* Custom folding regions: `//region Name` … `//endregion`, `#region` (C#, Python…),
* `<editor-fold desc="Name">` … `</editor-fold>`, in any line comment style.
* `<editor-fold desc="Name">` … `</editor-fold>`, in the language’s configured line or block comments.
* The backend folds them; this names their placeholders and lists them for
* Navigate › Custom Folding (⌥⌘.).
*/
import type { EditorState, Text } from "@codemirror/state";
import type { EditorState, Line } from "@codemirror/state";
export type RegionMarker = { start: true; name: string } | { start: false };
const COMMENT_START = /^\s*(?:\/\/+|\/\*+|#|--|;+|%|<!--|')?\s*/;
export interface RegionCommentTokens {
line?: string;
block?: { open: string; close: string };
}
const START = /^#?region\b\s*(.*)$/i;
const END = /^(?:#?endregion\b|<\/editor-fold\s*>)/i;
const END = /^(?:#?endregion\b|<\/editor-fold\s*>$)/i;
const FOLD = /^<editor-fold\b([^>]*)>/i;
const DESC = /\bdesc\s*=\s*"([^"]*)"/i;
/** The region marker on a line of text, if it is one. */
export function regionMarker(line: string): RegionMarker | null {
export function regionMarker(line: string, tokens: RegionCommentTokens): RegionMarker | null {
if (!/region|editor-fold/i.test(line)) return null;
const body = line.replace(COMMENT_START, "").trimEnd();
const text = line.trim();
let body: string;
if (/^#(?:end)?region\b/i.test(text)) {
body = text;
} else if (tokens.block && text.startsWith(tokens.block.open)) {
body = text.slice(tokens.block.open.length).trimEnd();
if (!body.endsWith(tokens.block.close)) return null;
body = body.slice(0, -tokens.block.close.length);
if (tokens.block.open === "/*") body = body.replace(/^\*+/, "");
} else if (tokens.line && text.startsWith(tokens.line)) {
body = text.slice(tokens.line.length);
if (tokens.line === "//") body = body.replace(/^\/+/, "");
if (tokens.line === ";") body = body.replace(/^;+/, "");
} else {
return null;
}
body = body.trim();
if (/[\r\n]/.test(body)) return null;
if (END.test(body)) return { start: false };
const fold = FOLD.exec(body);
if (fold) return { start: true, name: DESC.exec(fold[1]!)?.[1]?.trim() ?? "" };
const region = START.exec(body);
if (!region) return null;
const name = region[1]!
.replace(/\s*(?:\*\/|-->)\s*$/, "")
.trim()
.replace(/^"(.*)"$/, "$1")
.trim();
return { start: true, name };
@@ -37,12 +58,19 @@ export interface CustomRegion {
endLine: number;
}
/** Every matched region of `doc`, in document order of their start markers. */
export function customRegions(doc: Text): CustomRegion[] {
/** The marker using the configured comment syntax at this line. */
export function regionMarkerAt(state: EditorState, line: Line): RegionMarker | null {
const tokens = state.languageDataAt<RegionCommentTokens>("commentTokens", line.from)[0] ?? {};
return regionMarker(line.text, tokens);
}
/** Every matched region, in document order of its start marker. */
export function customRegions(state: EditorState): CustomRegion[] {
const doc = state.doc;
const out: CustomRegion[] = [];
const open: { name: string; line: number; index: number }[] = [];
for (let n = 1; n <= doc.lines; n++) {
const m = regionMarker(doc.line(n).text);
const m = regionMarkerAt(state, doc.line(n));
if (!m) continue;
if (m.start) {
open.push({ name: m.name, line: n, index: out.length });
@@ -59,6 +87,6 @@ export function customRegions(doc: Text): CustomRegion[] {
export function regionNameAt(state: EditorState, pos: number): string | null {
const line = state.doc.lineAt(pos);
if (state.sliceDoc(line.from, pos).trim()) return null;
const m = regionMarker(line.text);
const m = regionMarkerAt(state, line);
return m?.start && m.name ? m.name : null;
}
+3
Переглянути файл
@@ -51,6 +51,7 @@ import { editorBaseKeymap } from "./baseKeymap";
import { occurrenceSearch } from "./editing";
import { gutterLineDrag } from "./gutterDrag";
import { overwriteField } from "./overwrite";
import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard";
import { clipboardHistoryExtension } from "../clipboardHistory";
import type { LanguageInfo } from "../backend";
import { tx } from "@/platform/i18n";
@@ -336,6 +337,8 @@ export function baseExtensions(o: SetupOptions): Extension {
overwriteField,
gutterLineDrag,
clipboardHistoryExtension,
clipboardDocumentPath.of(o.ctx.path),
clipboardFilesExtension,
indentOnInput(),
syntaxHighlighting(openideaHighlightStyle),
syntaxHighlightField,
+2 -12
Переглянути файл
@@ -3,6 +3,7 @@
* status, navigation history, autosave. The React views and actions talk to
* this singleton; other features use the EditorService and editor/api.
*/
import { pasteEditorClipboard } from "./cm/clipboard";
import { EditorSelection } from "@codemirror/state";
import { create } from "zustand";
import { setContext } from "@/platform/context";
@@ -641,18 +642,7 @@ export class EditorController implements SlotHost {
icon: "paste",
shortcut: "⌘V",
disabled: view.state.readOnly,
run: () => {
void navigator.clipboard
?.readText()
.then((text) => {
view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true });
view.focus();
})
.catch(() => {
view.focus();
document.execCommand("paste");
});
},
run: () => void pasteEditorClipboard(view),
},
{ kind: "separator" },
{
+1
Переглянути файл
@@ -279,6 +279,7 @@ function PaneView({ paneId }: { paneId: string }) {
onSelect={(id) => ctrl.activate(paneId, id)}
onClose={(id) => void ctrl.closeTab(paneId, id)}
onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)}
closeOnShiftClick
onDoubleClick={(id) => {
// IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
+4 -3
Переглянути файл
@@ -7,6 +7,8 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEve
import clsx from "clsx";
import type { AgentCommand, AgentConfigOption, AgentImage } from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { nativeDropPoint } from "@/platform/nativeDrop";
import { invokeLocal } from "@/platform/tauriCore";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions";
@@ -221,13 +223,12 @@ export function Composer(props: ComposerProps) {
const p = event.payload;
if (p.type !== "drop" || !p.paths.length) return;
const box = boxRef.current?.getBoundingClientRect();
const ratio = window.devicePixelRatio || 1;
const [x, y] = [p.position.x / ratio, p.position.y / ratio];
const { x, y } = nativeDropPoint(p.position);
if (!box || x < box.left || x > box.right || y < box.top || y > box.bottom) return;
const refs: FileRef[] = [];
for (const path of p.paths) {
if (IMAGE_EXTENSIONS.test(path)) {
void call(commands.fsReadImage(path)).then((url) => {
void invokeLocal<string>("fs_read_image", { path }).then((url) => {
const image = imageFromDataUrl(url, basename(path));
if (image) addImages([image]);
});
+24
Переглянути файл
@@ -118,6 +118,30 @@ it("still reports a real resolve failure in the preparation console", async () =
expect(ipc.debugStart).not.toHaveBeenCalled();
});
it.each([
"jdtls: Given URI does not belong to any Java project.",
"jdtls: Launch configuration 1793460461218 references non-existing project parent.",
])("explains how to import a module when Debug fails with %s", async (message) => {
const starting = executeAction("debug.startConfig", { ...config, module: "web" });
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
respond({ status: "error", error: { kind: "protocol", message } });
await starting;
expect(notify).toHaveBeenLastCalledWith(
expect.objectContaining({
title: "Cannot start debugging",
body: expect.stringContaining("Java module 'web' is not imported."),
}),
);
expect(
Object.values(useDebug.getState().console)
.flat()
.map((line) => line.text)
.join("\n"),
).toContain("open its folder as a project");
expect(ipc.javaDebugServer).not.toHaveBeenCalled();
expect(ipc.debugStart).not.toHaveBeenCalled();
});
it("keeps progress and the originating configuration when DAP takes over", async () => {
const starting = executeAction("debug.startConfig", config);
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
+2 -3
Переглянути файл
@@ -23,6 +23,7 @@ import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { tx, useTxTemplate } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { nativeDropPoint } from "@/platform/nativeDrop";
import type { RootFolder } from "@/platform/languageSettings";
import { useDetectedRoots, useEffectiveRoots } from "@/platform/projectRoots";
import { macStroke, strokeOf } from "@/platform/keymap";
@@ -550,9 +551,7 @@ export function ProjectView() {
.onDragDropEvent((event) => {
const p = event.payload;
if (p.type === "leave") return setDropTarget(null);
const ratio = window.devicePixelRatio || 1;
const x = p.position.x / ratio,
y = p.position.y / ratio;
const { x, y } = nativeDropPoint(p.position);
const target = folderAt(containerRef.current, x, y);
if (p.type === "drop") {
setDropTarget(null);
+1 -6
Переглянути файл
@@ -18,12 +18,7 @@ export interface OsClipboard {
const native: OsClipboard = {
async files() {
if (!isTauri()) return [];
try {
return await call(commands.clipboardFileList());
} catch {
// A clipboard another app holds for a moment is not an error worth showing.
return [];
}
return call(commands.clipboardFileList());
},
async hasFiles() {
+12
Переглянути файл
@@ -44,6 +44,7 @@ const OTHER_ACTIONS = [
"vcs.addToVcs",
"vcs.annotate",
"vcs.showDiff",
"vcs.compareWithBranch",
"vcs.rollback",
"vcs.push",
];
@@ -129,6 +130,17 @@ describe("project view context menu", () => {
}
});
it("offers branch comparison for files, folders, their union and the project root", () => {
for (const nodes of [
[node("/p/a.py")],
[node("/p/src", true)],
[node("/p/src", true), node("/p/lib", true)],
[node("/p", true, true)],
]) {
expect(sub(contextMenuItems(nodes), "Git")).toContain("Compare with Branch…");
}
});
it("offers Show History for files, directories, multi-selection and the project root", () => {
const dispose = registerActions([{ id: "vcs.showHistory", title: "Show History", run: () => undefined }]);
try {
+3 -1
Переглянути файл
@@ -335,7 +335,9 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
singleFile && act("vcs.annotate", singleFile.path, "Annotate with Git Blame"),
act("vcs.showDiff", arg, "Show Diff"),
singleFile && act("vcs.compareWithBranch", { path: singleFile.path }, "Compare with Branch…"),
nodes.length > 0 &&
nodes.every((n) => !n.placeholder) &&
act("vcs.compareWithBranch", arg, "Compare with Branch…"),
nodes.length > 0 && nodes.every((n) => !n.placeholder) && act("vcs.showHistory", arg, "Show History"),
act("vcs.rollback", arg, "Rollback…"),
{ kind: "separator" },
+77
Переглянути файл
@@ -0,0 +1,77 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commands } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { useTasks } from "@/workbench/tasks";
import { beginLocalImport, tauriFs } from "./fs";
vi.mock("@/platform/tauriCore", async (original) => ({
...(await original<typeof import("@/platform/tauriCore")>()),
invokeLocal: vi.fn(async () => undefined),
}));
beforeEach(() => {
useTasks.setState({ tasks: [] });
useRemote.setState({
session: { sshConfig: "s", root: "/remote", host: "host", commands: ["fs_copy", "cancel_request"] },
});
});
afterEach(() => {
vi.restoreAllMocks();
useRemote.setState({ session: null });
useTasks.setState({ tasks: [] });
});
describe("client file routing", () => {
it("uploads OS files locally and cancels the client request rather than a remote one", async () => {
let finish!: (r: { status: "ok"; data: string[] }) => void;
const upload = vi.spyOn(commands, "remoteImportLocal").mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const copy = vi.spyOn(commands, "fsCopy");
const work = tauriFs.importLocal("/client/a", "/remote/a");
const task = useTasks.getState().tasks[0]!;
const request = upload.mock.calls[0]![2];
task.cancel!();
expect(invokeLocal).toHaveBeenCalledWith("cancel_request", { id: request });
finish({ status: "ok", data: [] });
await work;
expect(upload).toHaveBeenCalledWith("/client/a", "/remote/a", request);
expect(copy).not.toHaveBeenCalled();
expect(useTasks.getState().tasks[0]?.done).toBe(true);
});
it("surfaces a disconnected upload and finishes its task", async () => {
vi.spyOn(commands, "remoteImportLocal").mockResolvedValue({
status: "error",
error: { kind: "unavailable", message: "Remote project is disconnected" },
});
await expect(tauriFs.importLocal("/client/a", "/remote/a")).rejects.toThrow("Remote project is disconnected");
expect(useTasks.getState().tasks[0]?.done).toBe(true);
});
it("shares one task across paths and prevents starting another after Cancel", async () => {
const upload = vi.spyOn(commands, "remoteImportLocal").mockResolvedValue({ status: "ok", data: [] });
const batch = beginLocalImport();
await tauriFs.importLocal("/client/a", "/remote/a", batch);
await tauriFs.importLocal("/client/b", "/remote/b", batch);
expect(useTasks.getState().tasks).toHaveLength(1);
expect(useTasks.getState().tasks[0]?.done).toBe(false);
useTasks.getState().tasks[0]!.cancel!();
await expect(tauriFs.importLocal("/client/c", "/remote/c", batch)).rejects.toMatchObject({ kind: "cancelled" });
expect(upload).toHaveBeenCalledTimes(2);
batch.finish();
expect(useTasks.getState().tasks[0]?.done).toBe(true);
});
it("uses project copy for a local destination", async () => {
useRemote.setState({ session: null });
const copy = vi.spyOn(commands, "fsCopy").mockResolvedValue({ status: "ok", data: null });
const upload = vi.spyOn(commands, "remoteImportLocal");
await tauriFs.importLocal("/client/a", "/project/a");
expect(copy).toHaveBeenCalledWith("/client/a", "/project/a");
expect(upload).not.toHaveBeenCalled();
});
});
+64 -1
Переглянути файл
@@ -4,7 +4,11 @@
*/
import type { FileEntry } from "@/bindings";
import { notifyFileOperation } from "@/platform/fileOps";
import { call, commands, emitLocalIdeEvent, isTauri, IpcError } from "@/platform/ipc";
import { call, commands, emitLocalIdeEvent, isTauri, IpcError, nextRequestId } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { tx } from "@/platform/i18n";
import { upsertTask } from "@/workbench/tasks";
import { isInside, joinPath, nameOf, parentOf } from "./paths";
export interface ProjectFs {
@@ -15,6 +19,7 @@ export interface ProjectFs {
/** Moves to the trash when possible. */
delete(path: string): Promise<void>;
copy(from: string, to: string): Promise<void>;
importLocal(from: string, to: string, upload?: LocalImport): Promise<string[]>;
}
export const tauriFs: ProjectFs = {
@@ -33,8 +38,61 @@ export const tauriFs: ProjectFs = {
await call(commands.fsCopy(from, to));
notifyFileOperation({ kind: "created", paths: [to] });
},
importLocal: async (from, to, upload) => {
if (!isRemoteWindow()) {
await tauriFs.copy(from, to);
return [];
}
const batch = upload ?? beginLocalImport();
try {
const request = batch.start(from);
const skipped = await call(commands.remoteImportLocal(from, to, request));
notifyFileOperation({ kind: "created", paths: [to] });
return skipped;
} finally {
if (!upload) batch.finish();
}
},
};
interface LocalImport {
readonly cancelled: boolean;
start(from: string): number;
finish(): void;
}
/** One task spans every selected path; cancellation also stops paths not started yet. */
export function beginLocalImport(): LocalImport {
let cancelled = false;
let request = nextRequestId();
const task = {
id: `file-import-${request}`,
title: tx("Uploading files"),
message: null as string | null,
fraction: null,
cancel: () => {
cancelled = true;
void invokeLocal("cancel_request", { id: request }).catch(() => {});
},
};
upsertTask({ ...task, done: false });
return {
get cancelled() {
return cancelled;
},
start(from) {
if (cancelled) throw new IpcError({ kind: "cancelled", message: "Cancelled" });
request = nextRequestId();
task.message = nameOf(from);
upsertTask({ ...task, done: false });
return request;
},
finish() {
upsertTask({ ...task, done: true });
},
};
}
type MemNode = { kind: "file"; size: number } | { kind: "dir" };
const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) => new IpcError({ kind, message });
@@ -138,6 +196,11 @@ export class MemoryFs implements ProjectFs {
}
this.emit({ created: [to] });
}
async importLocal(from: string, to: string): Promise<string[]> {
await this.copy(from, to);
return [];
}
}
/** Sample project for plain-browser development (matches the design mock). */
+115 -2
Переглянути файл
@@ -1,6 +1,16 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ProjectNode } from "./model";
import { selectionAfterDelete } from "./operations";
import { importExternal, paste, selectionAfterDelete, transfer } from "./operations";
import { IpcError } from "@/platform/ipc";
import { pendingFileRefactorDialog } from "./FileRefactorDialogs";
import { useRemote } from "@/platform/remote";
import { provideNotificationService } from "@/workbench/contributions";
import { MemoryFs, setProjectFsForTests } from "./fs";
import { initProjectTree, loadDir, setClipboard } from "./store";
import { setOsClipboardForTests } from "./clipboard";
let fs: MemoryFs;
const notify = vi.fn();
const node = (path: string, dir = false): ProjectNode => ({
key: path,
@@ -31,3 +41,106 @@ describe("selectionAfterDelete", () => {
expect(selectionAfterDelete(rows, ["/elsewhere"])).toBeNull();
});
});
// Local OS paths and remote project paths may be identical strings.
describe("OS file imports", () => {
beforeEach(async () => {
fs = new MemoryFs({ "/p/target": null, "/p/local.txt": "client" }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "p");
await loadDir("/p");
useRemote.setState({ session: { sshConfig: "ssh", root: "/p", host: "host", commands: ["fs_copy"] } });
provideNotificationService({ notify });
notify.mockClear();
});
afterEach(() => {
useRemote.setState({ session: null });
setProjectFsForTests(null);
setOsClipboardForTests(null);
});
it.each(["paste", "drop"])(
"%s imports a client path under the remote root and keeps conflict names",
async (entry) => {
setOsClipboardForTests({
files: async () => ["/p/local.txt"],
hasFiles: async () => true,
setFiles: async () => {},
});
const imported = vi.spyOn(fs, "importLocal");
for (let i = 0; i < 2; i++) {
if (entry === "paste") await paste("/p/target");
else await importExternal(["/p/local.txt"], "/p/target");
}
expect(imported.mock.calls).toEqual([
["/p/local.txt", "/p/target/local.txt", expect.anything()],
["/p/local.txt", "/p/target/local copy.txt", expect.anything()],
]);
expect(notify).not.toHaveBeenCalled();
},
);
it("reports upload failure and continues with the next file", async () => {
const imported = vi.spyOn(fs, "importLocal").mockRejectedValueOnce(new Error("SSH disconnected"));
await importExternal(["/missing.txt", "/p/local.txt"], "/p/target");
expect(imported).toHaveBeenCalledTimes(2);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Some items could not be copied", body: "missing.txt: SSH disconnected" }),
);
expect(fs.nodes.has("/p/target/local.txt")).toBe(true);
});
it("reports a clipboard read failure", async () => {
setOsClipboardForTests({
files: async () => {
throw new Error("clipboard unavailable");
},
hasFiles: async () => true,
setFiles: async () => {},
});
await paste("/p/target");
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Cannot access the clipboard", body: "clipboard unavailable" }),
);
});
it.each([false, true])("falls back to internal clipboard (cut=%s) when another app holds it", async (cut) => {
setOsClipboardForTests({
files: async () => {
throw new Error("busy");
},
hasFiles: async () => false,
setFiles: async () => {},
});
setClipboard({ paths: ["/p/local.txt"], cut });
await paste("/p/target");
expect(pendingFileRefactorDialog()).toEqual(
expect.objectContaining({ kind: cut ? "move" : "copy", paths: ["/p/local.txt"] }),
);
expect(notify).not.toHaveBeenCalled();
});
it("stops a multi-path import quietly on cancellation", async () => {
const imported = vi
.spyOn(fs, "importLocal")
.mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await importExternal(["/p/local.txt", "/p/another.txt"], "/p/target");
expect(imported).toHaveBeenCalledTimes(1);
expect(notify).not.toHaveBeenCalled();
});
it("reports skipped entries while keeping the imported folder", async () => {
vi.spyOn(fs, "importLocal").mockResolvedValueOnce(["bundle/pipe: skipped special file"]);
expect(await transfer(["/bundle"], "/p/target", "copy", undefined, "local")).toBe("/p/target/bundle");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ body: "bundle/pipe: skipped special file" }));
});
it("keeps internal remote copies on the project filesystem", async () => {
const imported = vi.spyOn(fs, "importLocal");
const copied = vi.spyOn(fs, "copy");
await transfer(["/p/local.txt"], "/p/target", "copy");
expect(copied).toHaveBeenCalledWith("/p/local.txt", "/p/target/local.txt");
expect(imported).not.toHaveBeenCalled();
});
});
+51 -21
Переглянути файл
@@ -10,7 +10,8 @@ import { ask, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
import { runFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { projectFs } from "./fs";
import { beginLocalImport, projectFs } from "./fs";
import { isCancelled } from "@/platform/ipc";
import type { ProjectNode } from "./model";
import {
isInside,
@@ -38,6 +39,7 @@ import {
useProjectTree,
} from "./store";
import { tx } from "@/platform/i18n";
import { isRemoteWindow } from "@/platform/remote";
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
const mutable = (n: ProjectNode) => !n.root && !n.placeholder && !n.readOnly;
@@ -500,11 +502,22 @@ export function canPaste(): boolean {
export async function paste(target = targetFolder()) {
const { clipboard } = get();
if (!target || isReadOnlyPath(target)) return;
const external = await osClipboard().files();
let external: string[] = [];
try {
external = await osClipboard().files();
} catch (e) {
if (!clipboard?.paths.length) {
fail("Cannot access the clipboard", e);
return;
}
}
// The last copy is the one the user expects to paste, so another app's files
// win over ours — unless they are the copy we handed to the OS ourselves.
if (external.length && !sameFiles(external, clipboard?.paths)) return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) return;
if (!clipboard?.paths.length) {
notifications().notify({ level: "info", title: "No files on the clipboard" });
return;
}
const isDir = (p: string) =>
get().listings.has(p) || currentModel().byKey.get(currentModel().keyOfPath.get(p) ?? p)?.dir === true;
const single = clipboard.paths.length === 1 && isDir(clipboard.paths[0]!);
@@ -519,7 +532,7 @@ export async function paste(target = targetFolder()) {
/** Pasting from Explorer copies, whatever the source: never a move or a refactoring. */
async function pasteFromOsClipboard(paths: string[], target: string) {
osHasFiles = true;
await transfer(paths, target, "copy");
await transfer(paths, target, "copy", undefined, "local");
}
/** The same files, as the clipboard keeps them (`/`-separated, any order). */
@@ -559,6 +572,7 @@ export async function transfer(
target: string,
mode: "move" | "copy",
name?: string,
source: "project" | "local" = "project",
): Promise<string | boolean> {
if (mode === "move") return moveInto(paths, target);
const { root } = get();
@@ -571,23 +585,38 @@ export async function transfer(
const errors: string[] = [];
let first: string | null = null;
const newName = name;
for (const src of paths) {
const name = nameOf(src);
if (isSameOrInside(target, src) && target !== parentOf(src) && src !== target) {
errors.push(`${name}: cannot copy a folder into itself`);
continue;
}
const srcIsDir =
get().listings.has(src) || currentModel().byKey.get(currentModel().keyOfPath.get(src) ?? src)?.dir === true;
const finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
const to = joinPath(target, finalName);
try {
await fs.copy(src, to);
taken.add(caseInsensitive ? finalName.toLowerCase() : finalName);
first ??= to;
} catch (e) {
errors.push(`${name}: ${errorMessage(e)}`);
const upload = source === "local" && isRemoteWindow() ? beginLocalImport() : undefined;
try {
for (const src of paths) {
if (upload?.cancelled) break;
const name = nameOf(src);
if (
!(source === "local" && isRemoteWindow()) &&
isSameOrInside(target, src) &&
target !== parentOf(src) &&
src !== target
) {
errors.push(`${name}: cannot copy a folder into itself`);
continue;
}
const srcIsDir =
get().listings.has(src) || currentModel().byKey.get(currentModel().keyOfPath.get(src) ?? src)?.dir === true;
const finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
const to = joinPath(target, finalName);
try {
if (source === "local") {
const skipped = await fs.importLocal(src, to, upload);
errors.push(...skipped);
} else await fs.copy(src, to);
taken.add(caseInsensitive ? finalName.toLowerCase() : finalName);
first ??= to;
} catch (e) {
if (isCancelled(e)) break;
errors.push(`${name}: ${errorMessage(e)}`);
}
}
} finally {
upload?.finish();
}
if (errors.length)
notifications().notify({ level: "error", title: "Some items could not be copied", body: errors.join("\n") });
@@ -650,10 +679,11 @@ export async function dropPaths(paths: string[], target: string, copy: boolean)
export async function importExternal(paths: string[], target: string) {
const { root } = get();
if (!root || !paths.length || isReadOnlyPath(target)) return;
if (isRemoteWindow()) return void (await transfer(paths, target, "copy", undefined, "local"));
const inside = paths.filter((p) => isSameOrInside(p, root));
const outside = paths.filter((p) => !isSameOrInside(p, root));
if (inside.length) await dropPaths(inside, target, false);
if (outside.length) await transfer(outside, target, "copy");
if (outside.length) await transfer(outside, target, "copy", undefined, "local");
}
// ---------------------------------------------------------------------------
+51 -4
Переглянути файл
@@ -1,9 +1,10 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { findJavaModule } from "@/platform/javaLaunch";
import { IpcError, type RunConfig } from "@/platform/ipc";
import { findJavaModule, prepareJavaLaunch } from "@/platform/javaLaunch";
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
import { provideNotificationService } from "@/workbench/contributions";
import { applicationConfig } from "./application";
import { resetRuns, saveUserConfigs, startRun } from "./store";
import { resetRuns, runtime, saveUserConfigs, startRun } from "./store";
import { applicationType } from "./jvmTypes";
import { withParams } from "./types";
@@ -63,7 +64,10 @@ beforeEach(() => {
vi.clearAllMocks();
provideNotificationService({ notify: vi.fn() });
});
afterEach(() => resetRuns());
afterEach(() => {
resetRuns();
_resetI18nForTests();
});
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
const session = await startRun({ ...config, module: "app", cwd });
@@ -112,3 +116,46 @@ it("does not substitute the working directory when sources are missing or ambigu
});
expect(await findJavaModule(config)).toBeNull();
});
it.each([
"jdtls: Given URI does not belong to any Java project.",
"jdtls: Launch configuration 1793460461218 references non-existing project parent.",
])("explains how to import a module when Run fails with %s", async (message) => {
ipc.javaResolveLaunch.mockResolvedValueOnce({ status: "error", error: { kind: "protocol", message } } as never);
const session = await startRun({ ...config, module: "web" });
expect(session?.status).toBe("failed");
const output = runtime(session!.id)!
.console.lines.map((line) => line.text)
.join("\n");
expect(output).toContain("Java module 'web' is not imported.");
expect(output).toContain("parent Maven or Gradle build");
expect(output).toContain("open its folder as a project");
expect(ipc.runStart).not.toHaveBeenCalled();
});
it.each([
["unavailable", "jdtls is not installed (Settings › Languages & Frameworks › Language Servers)"],
["unavailable", "jdtls exited with code 1: wrong Java version"],
["protocol", "jdtls: workspace/executeCommand timed out after 90 s"],
["internal", "Build failed"],
["cancelled", "jdtls: Given URI does not belong to any Java project."],
] as const)("preserves other launch errors (%s: %s)", async (kind, message) => {
const error = new IpcError({ kind, message });
ipc.javaResolveLaunch.mockRejectedValueOnce(error);
await expect(
prepareJavaLaunch({ ...config, module: "web" }, { request: 1, signal: new AbortController().signal }),
).rejects.toBe(error);
});
it("translates import recovery guidance for a root Spring Boot configuration", async () => {
await setLocale("zh");
ipc.javaResolveLaunch.mockRejectedValueOnce(
new IpcError({ kind: "protocol", message: "jdtls: Given URI does not belong to any Java project." }),
);
await expect(
prepareJavaLaunch(
{ ...config, kind: "spring-boot", module: "" },
{ request: 1, signal: new AbortController().signal },
),
).rejects.toThrow("Java 模块 '.' 尚未导入");
});
+2 -6
Переглянути файл
@@ -31,6 +31,7 @@ import {
type PaneLayout,
type TerminalTab,
} from "./store";
import { pasteTerminalClipboard } from "./paste";
import { TerminalFindBar } from "./FindBar";
import styles from "./Terminal.module.css";
@@ -102,12 +103,7 @@ function paneMenu(e: MouseEvent, key: string) {
{
label: "Paste",
shortcut: mac ? "⌘V" : "Ctrl+Shift+V",
run: () => {
void navigator.clipboard
?.readText()
.then((t) => t && session.paste(t))
.catch(() => undefined);
},
run: () => void pasteTerminalClipboard((text) => session.paste(text)),
},
{ label: "Select All", run: () => session.term.selectAll() },
{ kind: "separator" },
+3
Переглянути файл
@@ -4,6 +4,7 @@
* and size go to the owner instead of a terminal PTY (a Run console emulating
* a terminal feeds its process).
*/
import { installTerminalPaste } from "./paste";
import { Terminal, type IDisposable } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
@@ -83,6 +84,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal
},
}),
];
const removePaste = installTerminalPaste(host, (text) => term.paste(text));
term.open(host);
if (opts["aria-label"]) term.textarea?.setAttribute("aria-label", opts["aria-label"]);
@@ -109,6 +111,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal
fitter.cancel();
processResize.cancel();
observer.disconnect();
removePaste();
for (const d of disposables) d.dispose();
live.delete(term);
term.dispose();
+80
Переглянути файл
@@ -0,0 +1,80 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Terminal } from "@xterm/xterm";
import { commands } from "@/platform/ipc";
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
for (const route of ["event", "menu"]) {
it.each([
{ name: "text present", text: "plain", paths: ["/stale"], expected: "plain", calls: 0 },
{ name: "files plus list", text: "", paths: ["/a b", "/中文"], expected: "/a b\n/中文", calls: 1 },
{ name: "files without list", text: "", paths: [], expected: "", calls: 1 },
{ name: "backend error", text: "", paths: null, expected: "", calls: 1 },
])(`${route}: $name`, async ({ text, paths, expected, calls }) => {
const list = vi.spyOn(commands, "clipboardFileList");
if (paths) list.mockResolvedValue({ status: "ok", data: paths });
else list.mockRejectedValue(new Error("busy"));
const host = document.createElement("div");
const textarea = document.createElement("textarea");
host.append(textarea);
const paste = vi.fn();
const remove = installTerminalPaste(host, paste);
// Model xterm's bubble listener: file recovery must preempt its empty paste.
textarea.addEventListener("paste", (event) =>
paste((event as ClipboardEvent).clipboardData!.getData("text/plain")),
);
if (route === "event") {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", { value: { getData: () => text, files: [], types: ["Files"] } });
textarea.dispatchEvent(event);
expect(event.defaultPrevented).toBe(!text);
} else {
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => text } });
await pasteTerminalClipboard(paste);
}
await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(calls));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(paste.mock.calls).toEqual(expected ? [[expected]] : []);
remove();
});
}
it("ignores clipboard resolution after the terminal is disposed", async () => {
let finish!: (value: { status: "ok"; data: string[] }) => void;
vi.spyOn(commands, "clipboardFileList").mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const host = document.createElement("div");
const paste = vi.fn();
const remove = installTerminalPaste(host, paste);
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", { value: { getData: () => "", files: [], types: ["Files"] } });
host.dispatchEvent(event);
remove();
finish({ status: "ok", data: ["/late"] });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(paste).not.toHaveBeenCalled();
});
it("passes recovered multiline paths through xterm bracketed paste", async () => {
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/a b", "/中文"] });
const term = new Terminal({ allowProposedApi: true });
const data: string[] = [];
term.onData((text) => data.push(text));
try {
await new Promise<void>((resolve) => term.write("\x1b[?2004h", resolve));
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
await pasteTerminalClipboard((text) => term.paste(text));
expect(data).toEqual(["\x1b[200~/a b\r/中文\x1b[201~"]);
} finally {
term.dispose();
}
});
+24
Переглянути файл
@@ -0,0 +1,24 @@
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
export function installTerminalPaste(host: HTMLElement, paste: (text: string) => void): () => void {
let alive = true;
const onPaste = (event: ClipboardEvent) => {
pasteClipboardFiles(event, (text) => {
if (alive) paste(text);
});
};
host.addEventListener("paste", onPaste, true);
return () => {
alive = false;
host.removeEventListener("paste", onPaste, true);
};
}
export async function pasteTerminalClipboard(paste: (text: string) => void) {
try {
const text = await readClipboardText();
if (text) paste(text);
} catch {
/* Clipboard access may be denied. */
}
}
+4 -4
Переглянути файл
@@ -11,6 +11,7 @@ import { Channel } from "@tauri-apps/api/core";
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
import { editorService, notifications } from "@/workbench/contributions";
import { fitScheduler, settledResize } from "./fit";
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
import { ImeCommitGate } from "./imeCommit";
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
import { splitCommandLine } from "@/platform/commandLine";
@@ -275,16 +276,14 @@ export class TerminalSession {
if (atBottom !== this.snapshot.follow) this.update({ follow: atBottom });
}),
);
this.disposables.push({ dispose: installTerminalPaste(this.host, (text) => this.paste(text)) });
this.host.addEventListener("mousedown", this.onMiddleClick);
}
private onMiddleClick = (e: MouseEvent) => {
if (e.button !== 1 || !workflowSettings().terminal.pasteOnMiddleClick) return;
e.preventDefault();
void navigator.clipboard
?.readText()
.then((t) => t && this.paste(t))
.catch(() => undefined);
void pasteTerminalClipboard((text) => this.paste(text));
};
/** Applies Settings › Tools › Terminal changes to a live session. */
@@ -552,6 +551,7 @@ export class TerminalSession {
}
paste(text: string) {
if (this.disposed) return;
this.term.paste(text);
}
+117 -44
Переглянути файл
@@ -1,26 +1,100 @@
/** Chooser for "Compare with Branch or Revision…". */
/** Chooser for revision actions, including a selection spanning multiple repositories. */
import { useEffect, useMemo, useState, type KeyboardEvent } from "react";
import { Dialog, HighlightedText, Icon, List, SearchField, fuzzyMatch, listNavigate } from "@/ui";
import { sortLocal, sortRemote } from "./branches";
import { openDialog } from "./dialogs";
import { call, commands } from "@/platform/ipc";
import type { Branch } from "@/bindings";
import { currentRepo } from "./store";
import { currentRepo, repoName } from "./store";
import { tx } from "@/platform/i18n";
import styles from "./common.module.css";
interface Item {
export interface RevisionChoice {
rev: string;
/** null applies an entered revision to every repository in the selection. */
repositories: string[] | null;
}
interface Item extends RevisionChoice {
detail: string;
matches: number[] | null;
section?: boolean;
}
export interface RepositoryRevisions {
root: string | null;
branches: Branch[];
tags: string[];
}
export interface ChooseRevisionOptions {
/** Offer the repository's tags too. */
tags?: boolean;
placeholder?: string;
repositories?: string[];
}
export function chooseRevision(title: string, options: ChooseRevisionOptions = {}): Promise<string | null> {
/** Shared branches first, followed by each repository's revisions. */
export function revisionItems(repos: RepositoryRevisions[], query: string): Item[] {
const all: Item[] = [{ rev: "HEAD", detail: tx("Last commit"), repositories: null, matches: null }];
const multi = repos.length > 1;
if (multi) {
const shared = new Map<string, string[]>();
for (const repo of repos) {
for (const name of new Set(repo.branches.map((b) => b.name))) {
const roots = shared.get(name) ?? [];
if (repo.root) roots.push(repo.root);
shared.set(name, roots);
}
}
for (const [rev, repositories] of shared) {
if (repositories.length > 1)
all.push({ rev, detail: tx`in ${repositories.length} repositories`, repositories, matches: null });
}
}
for (const repo of repos) {
if (multi)
all.push({
rev: repoName(repo.root ?? ""),
detail: repo.root ?? "",
repositories: [],
matches: null,
section: true,
});
const repositories = repo.root ? [repo.root] : null;
all.push(
...sortLocal(repo.branches).map((b) => ({
rev: b.name,
detail: tx(b.current ? "current branch" : "local"),
repositories,
matches: null,
})),
...sortRemote(repo.branches).map((b) => ({ rev: b.name, detail: tx("remote"), repositories, matches: null })),
...repo.tags.map((rev) => ({ rev, detail: tx("tag"), repositories, matches: null })),
);
}
const q = query.trim();
if (!q) return all;
const filtered = all
.flatMap((i) => {
if (i.section) return [i];
const matches = fuzzyMatch(i.rev, q);
return matches ? [{ ...i, matches }] : [];
})
.filter((i, idx, list) => !i.section || (!!list[idx + 1] && !list[idx + 1]!.section));
// Always allow applying a typed revision across the full selection, even when one repo offers it.
if (!filtered.some((i) => !i.section && i.rev === q && i.repositories === null))
filtered.push({ rev: q, detail: tx("revision"), repositories: null, matches: null });
return filtered;
}
export async function chooseRevision(title: string, options: ChooseRevisionOptions = {}): Promise<string | null> {
return (await chooseRepositoryRevision(title, options))?.rev ?? null;
}
export function chooseRepositoryRevision(
title: string,
options: ChooseRevisionOptions,
): Promise<RevisionChoice | null> {
return new Promise((resolve) => {
const close = openDialog(() => (
<Chooser
@@ -42,57 +116,46 @@ function Chooser({
}: {
title: string;
options: ChooseRevisionOptions;
onDone: (rev: string | null) => void;
onDone: (rev: RevisionChoice | null) => void;
}) {
const [repo] = useState(currentRepo);
const [branches, setBranches] = useState<Branch[]>([]);
const [tags, setTags] = useState<string[]>([]);
const [roots] = useState(() => options.repositories ?? [currentRepo()]);
const [repos, setRepos] = useState<RepositoryRevisions[]>([]);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
useEffect(() => {
let alive = true;
void call(commands.vcsBranches(repo))
.then((b) => alive && setBranches(b))
.catch(() => undefined);
if (options.tags) {
void call(commands.vcsTags(repo))
.then((t) => alive && setTags(t))
.catch(() => undefined);
}
void Promise.all(
roots.map(async (root) => {
const [branches, tags] = await Promise.allSettled([
call(commands.vcsBranches(root)),
options.tags ? call(commands.vcsTags(root)) : Promise.resolve<string[]>([]),
]);
for (const outcome of [branches, tags])
if (outcome.status === "rejected" && alive) setError(`${root ?? ""}: ${String(outcome.reason)}`);
return {
root,
branches: branches.status === "fulfilled" ? branches.value : [],
tags: tags.status === "fulfilled" ? tags.value : [],
};
}),
)
.then((r) => alive && setRepos(r))
.catch((e) => alive && setError(String(e)));
return () => {
alive = false;
};
}, [options.tags]);
const items = useMemo(() => {
const all: Item[] = [
{ rev: "HEAD", detail: "Last commit", matches: null },
...sortLocal(branches).map((b) => ({
rev: b.name,
detail: b.current ? "current branch" : "local",
matches: null,
})),
...sortRemote(branches).map((b) => ({ rev: b.name, detail: "remote", matches: null })),
...tags.map((t) => ({ rev: t, detail: "tag", matches: null })),
];
const q = query.trim();
const filtered = q
? all.flatMap((i) => {
const m = fuzzyMatch(i.rev, q);
return m ? [{ ...i, matches: m }] : [];
})
: all;
if (q && !filtered.some((i) => i.rev === q)) filtered.push({ rev: q, detail: "revision", matches: null });
return filtered;
}, [branches, tags, query]);
}, [options.tags, roots]);
const items = useMemo(() => revisionItems(repos, query), [repos, query]);
const idx = Math.min(active, items.length - 1);
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
const it = items[idx];
if (it) onDone(it.rev);
if (it && !it.section) onDone(it);
return;
}
const n = listNavigate(e.key, { items, active: idx, wrap: true });
const n = listNavigate(e.key, { items, active: idx, isSection: (i) => !!i.section, wrap: true });
if (n !== null) {
e.preventDefault();
setActive(n);
@@ -114,13 +177,20 @@ function Chooser({
variant="bare"
/>
</div>
{error && (
<div className={styles.error} role="alert">
{error}
</div>
)}
<div style={{ height: 280, display: "flex", flexDirection: "column", padding: "4px 0" }}>
<List
items={items}
getKey={(i) => `${i.detail}:${i.rev}`}
getKey={(i) => `${i.repositories?.join(":")}:${i.detail}:${i.rev}`}
activeIndex={idx}
onActiveChange={setActive}
onActivate={(i) => onDone(i.rev)}
onActivate={(i) => onDone(i)}
isSection={(i) => !!i.section}
renderSection={(i) => <span title={i.detail}>{i.rev}</span>}
focusable={false}
hoverSelects
rowHeight={24}
@@ -128,7 +198,10 @@ function Chooser({
className={styles.grow}
renderItem={(i) => (
<span className={styles.fileRow} style={{ flex: 1, padding: 0 }}>
<Icon name={i.detail === "revision" ? "commit" : i.detail === "tag" ? "tag" : "branch"} size={14} />
<Icon
name={i.detail === tx("revision") ? "commit" : i.detail === tx("tag") ? "tag" : "branch"}
size={14}
/>
<HighlightedText
className={`${styles.fileName} ${styles.mono}`}
text={i.rev}
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { getAction, isActionEnabled } from "@/platform/actions";
import { provideProjectViewSelection } from "@/workbench/contributions";
import { registerVcsActions } from "../actions";
const mocks = vi.hoisted(() => ({ compare: vi.fn() }));
vi.mock("../comparePaths", () => ({ comparePathsWithRevision: mocks.compare, showDirectoryWorkingDiff: vi.fn() }));
afterEach(() => vi.clearAllMocks());
describe("compare action context", () => {
it("is enabled for Git folder selections and uses project selection in menu/Search Everywhere", async () => {
const unregister = registerVcsActions();
const dispose = provideProjectViewSelection(() => ["/workspace/client", "/workspace/server"]);
try {
const action = getAction("vcs.compareWithBranch")!;
expect(isActionEnabled(action, { vcsAvailable: true, projectViewFocus: true })).toBe(true);
await action.run({ arg: undefined, ctx: { vcsAvailable: true } });
expect(mocks.compare).toHaveBeenCalledWith(["/workspace/client", "/workspace/server"]);
await action.run({ arg: { path: "/workspace/client/a.ts" }, ctx: { vcsAvailable: true } });
expect(mocks.compare).toHaveBeenLastCalledWith(["/workspace/client/a.ts"]);
} finally {
dispose();
unregister();
}
});
});
+74
Переглянути файл
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ scope: vi.fn(), choose: vi.fn(), open: vi.fn(), show: vi.fn(), notify: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, vcsCompareScope: mocks.scope } };
});
vi.mock("../RevisionChooser", () => ({ chooseRepositoryRevision: mocks.choose }));
vi.mock("../diffInput", () => ({ openDiff: mocks.open }));
vi.mock("../operations", () => ({ showPathComparison: mocks.show }));
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify }) }));
import { useProject } from "@/platform/project";
import { comparePathsWithRevision, showDirectoryWorkingDiff } from "../comparePaths";
afterEach(() => {
vi.clearAllMocks();
useProject.setState({ project: null });
});
describe("comparison flow", () => {
it("keeps a single file's direct revision → worktree diff and uses its own repository's picker", async () => {
mocks.scope.mockResolvedValue({
status: "ok",
data: { repositories: ["/server"], singleFile: true, skippedPaths: [] },
});
mocks.choose.mockResolvedValue({ rev: "main", repositories: ["/server"] });
await comparePathsWithRevision(["/server/a.ts"]);
expect(mocks.choose).toHaveBeenCalledWith("Compare with Branch or Revision", {
repositories: ["/server"],
tags: true,
});
expect(mocks.open).toHaveBeenCalledWith({
path: "/server/a.ts",
left: { type: "rev", rev: "main", label: "main" },
right: { type: "worktree" },
});
expect(mocks.show).not.toHaveBeenCalled();
});
it("applies shared revisions across the selection so missing revisions are reported, and preserves repo-specific choices", async () => {
mocks.scope.mockResolvedValue({
status: "ok",
data: { repositories: ["/client", "/server", "/admin"], singleFile: false, skippedPaths: [] },
});
mocks.choose.mockResolvedValue({ rev: "main", repositories: ["/client", "/server"] });
await comparePathsWithRevision(["/workspace"]);
expect(mocks.show).toHaveBeenLastCalledWith(["/workspace"], "main", null);
mocks.choose.mockResolvedValue({ rev: "feature", repositories: ["/server"] });
await comparePathsWithRevision(["/workspace"]);
expect(mocks.show).toHaveBeenLastCalledWith(["/workspace"], "feature", ["/server"]);
});
it("reports non-repository selections before opening a picker", async () => {
mocks.scope.mockResolvedValue({
status: "ok",
data: { repositories: [], singleFile: false, skippedPaths: ["/workspace/loose/"] },
});
useProject.setState({ project: { root: "/workspace", name: "workspace" } as never });
await comparePathsWithRevision(["/workspace/loose"]);
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Selection is outside Git repositories", body: "loose/" }),
);
expect(mocks.choose).not.toHaveBeenCalled();
});
it("reuses the tree against HEAD for Show Diff on folders", async () => {
mocks.scope.mockResolvedValue({
status: "ok",
data: { repositories: ["/server"], singleFile: false, skippedPaths: [] },
});
expect(await showDirectoryWorkingDiff(["/server/src"])).toBe(true);
expect(mocks.show).toHaveBeenCalledWith(["/server/src"], "HEAD", null);
});
});
+164
Переглянути файл
@@ -0,0 +1,164 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { Branch, CompareResult } from "@/bindings";
const mocks = vi.hoisted(() => ({
compare: vi.fn(),
cancel: vi.fn(),
scope: vi.fn(),
choose: vi.fn(),
open: vi.fn(),
show: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
vcsComparePaths: mocks.compare,
cancelRequest: mocks.cancel,
vcsCompareScope: mocks.scope,
},
};
});
vi.mock("../DiffEditor", () => ({
DiffEditor: ({ input }: { input: unknown }) => <div data-testid="diff">{JSON.stringify(input)}</div>,
}));
import { useProject } from "@/platform/project";
import { ChangesBetweenDialog, comparisonEmpty } from "../operations";
import { revisionItems } from "../RevisionChooser";
const branch = (name: string, remote = false) => ({ name, remote, current: false, lastCommitMs: 0 }) as Branch;
const scope = { paths: ["/workspace"], repositories: null };
const result: CompareResult = {
skippedPaths: ["/workspace/loose/"],
repositories: [
{
root: "/workspace/client",
revision: "aaa",
error: null,
missingRevision: false,
files: [{ path: "src/app.ts", kind: "modified", oldPath: null, added: 3, removed: 1 }],
},
{ root: "/workspace/server", revision: null, error: null, missingRevision: true, files: [] },
],
};
beforeEach(() => {
vi.clearAllMocks();
useProject.setState({ project: { root: "/workspace", name: "workspace" } as never });
mocks.cancel.mockResolvedValue(undefined);
});
afterEach(() => {
cleanup();
useProject.setState({ project: null });
});
describe("directory comparison", () => {
it("offers shared branches plus each repository's local, remote and tag revisions", () => {
const repos = [
{
root: "/workspace/client",
branches: [branch("main"), branch("client-only"), branch("origin/main", true)],
tags: ["v1"],
},
{ root: "/workspace/server", branches: [branch("main"), branch("server-only")], tags: [] },
{ root: "/workspace/admin", branches: [branch("main")], tags: [] },
];
const items = revisionItems(repos, "");
expect(items.find((i) => i.rev === "main" && i.repositories?.length === 3)?.detail).toBe("in 3 repositories");
expect(items.filter((i) => i.section).map((i) => i.rev)).toEqual(["client", "server", "admin"]);
expect(items.find((i) => i.rev === "origin/main")?.repositories).toEqual(["/workspace/client"]);
expect(items.find((i) => i.rev === "v1")?.repositories).toEqual(["/workspace/client"]);
expect(revisionItems(repos, "client-only").some((i) => i.rev === "client-only" && i.repositories === null)).toBe(
true,
);
});
it("shows explicit empty results, skipped paths and repository-specific errors", async () => {
mocks.compare.mockResolvedValue({
status: "ok",
data: { ...result, repositories: result.repositories.map((r) => ({ ...r, files: [] })) },
});
render(<ChangesBetweenDialog from={{ rev: "main", label: "main" }} to={null} scope={scope} onClose={() => {}} />);
expect(await screen.findByText("No changes against main in 1 repository")).toBeInTheDocument();
expect(screen.getByText("server has no revision main")).toBeInTheDocument();
expect(screen.getByText(/Skipped content/)).toHaveTextContent("Skipped content outside Git repositories: loose/");
expect(comparisonEmpty("main", 2)).toBe("No changes against main in 2 repositories");
});
it("shows one calm state when every selected repository lacks the revision", async () => {
mocks.compare.mockResolvedValue({
status: "ok",
data: {
...result,
repositories: result.repositories.map((r) => ({ ...r, files: [], revision: null, missingRevision: true })),
},
});
render(
<ChangesBetweenDialog
from={{ rev: "missing-revision", label: "missing-revision" }}
to={null}
scope={scope}
onClose={() => {}}
/>,
);
expect(await screen.findByText("No repository in the selection has revision missing-revision")).toBeInTheDocument();
expect(screen.queryByText(/has no revision/)).toBeNull();
expect(screen.queryByText(/No changes against/)).toBeNull();
expect(screen.queryByRole("alert")).toBeNull();
});
it("keeps other repository errors visible", async () => {
mocks.compare.mockResolvedValue({
status: "ok",
data: {
...result,
repositories: [{ ...result.repositories[1], missingRevision: false, error: "fatal: bad config" }],
},
});
render(<ChangesBetweenDialog from={{ rev: "main", label: "main" }} to={null} scope={scope} onClose={() => {}} />);
expect(await screen.findByRole("alert")).toHaveTextContent("Cannot compare server against main: fatal: bad config");
expect(screen.queryByText(/No changes against/)).toBeNull();
});
it("caps the list of skipped project-relative children", async () => {
mocks.compare.mockResolvedValue({
status: "ok",
data: {
...result,
skippedPaths: Array.from({ length: 7 }, (_, i) => `/workspace/loose${i}/`),
},
});
render(<ChangesBetweenDialog from={{ rev: "main", label: "main" }} to={null} scope={scope} onClose={() => {}} />);
expect(await screen.findByText(/Skipped content/)).toHaveTextContent(
"Skipped content outside Git repositories: loose0/, loose1/, loose2/, loose3/, loose4/ and 2 more",
);
expect(screen.getByText(/Skipped content/)).not.toHaveTextContent("/workspace");
});
it("groups the existing changes tree by repo, includes counts and loads a diff only on click", async () => {
mocks.compare.mockResolvedValue({ status: "ok", data: result });
render(<ChangesBetweenDialog from={{ rev: "main", label: "main" }} to={null} scope={scope} onClose={() => {}} />);
expect(await screen.findByText("app.ts")).toBeInTheDocument();
expect(screen.getByText("client")).toBeInTheDocument();
expect(screen.getByText("+3")).toBeInTheDocument();
expect(screen.getByText("−1")).toBeInTheDocument();
expect(screen.queryByTestId("diff")).toBeNull();
fireEvent.mouseDown(screen.getByText("app.ts"), { button: 0 });
expect(screen.getByTestId("diff")).toHaveTextContent('"rev":"aaa"');
expect(screen.getByTestId("diff")).toHaveTextContent("/workspace/client/src/app.ts");
});
it("cancels the backend request when a running comparison is closed", async () => {
mocks.compare.mockReturnValue(new Promise(() => {}));
const view = render(
<ChangesBetweenDialog from={{ rev: "main", label: "main" }} to={null} scope={scope} onClose={() => {}} />,
);
await waitFor(() => expect(mocks.compare).toHaveBeenCalled());
const request = mocks.compare.mock.calls[0]![3];
view.unmount();
expect(mocks.cancel).toHaveBeenCalledWith(request);
});
});
+17 -9
Переглянути файл
@@ -5,7 +5,13 @@ import { registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { activeEditor, editorsFor } from "@/editor/api";
import { Menu, type MenuItem } from "@/ui";
import { editorService, maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
import {
editorService,
maybeEditorService,
notifications,
projectViewSelection,
toolWindowService,
} from "@/workbench/contributions";
import { annotationsShown, toggleAnnotations } from "./blame";
import { showBranchesPopup } from "./BranchWidget";
import { checkoutRevision, newBranch, newBranchInRepos } from "./branchOps";
@@ -29,7 +35,7 @@ import { openLogTab, revealCommit, selectGitTab, useGitLog } from "./logStore";
import { isModalCommit, openCommit, pushAfterCommit } from "./commitUi";
import { allRepos, runRemote } from "./ops";
import { showPushDialog, showUpdateDialog, type PushTarget } from "./remoteUi";
import { chooseRevision } from "./RevisionChooser";
import { comparePathsWithRevision, showDirectoryWorkingDiff } from "./comparePaths";
import { showCloneDialog } from "./clone";
import {
showManageRemotes,
@@ -103,6 +109,7 @@ const OPERATIONS: MenuItem[] = [
{ kind: "action", action: "vcs.showHistory" },
{ kind: "action", action: "vcs.annotate" },
{ kind: "action", action: "vcs.showDiff" },
{ kind: "action", action: "vcs.compareWithBranch" },
{ kind: "separator" },
{ kind: "action", action: "vcs.branches" },
{ kind: "action", action: "vcs.push" },
@@ -311,11 +318,13 @@ export function registerVcsActions(): () => void {
if (ctx.shelfFocus && arg === undefined) return showShelfDiff();
const line =
arg && typeof arg === "object" && "line" in arg ? Number((arg as { line: unknown }).line) : undefined;
const paths = contextPaths(arg).filter((p) => !p.endsWith("/"));
const selection = arg === undefined ? projectViewSelection() : [];
const paths = selection.length ? selection : contextPaths(arg);
if (!paths.length) {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
return;
}
if (await showDirectoryWorkingDiff(paths)) return;
for (const p of paths.slice(0, 5)) await openDiff(workingDiffData(p, line), { preview: paths.length === 1 });
},
},
@@ -326,14 +335,13 @@ export function registerVcsActions(): () => void {
icon: "diff",
when: VCS,
run: async ({ arg }) => {
const path = contextPaths(arg)[0];
if (!path) {
notifications().notify({ group: "vcs", level: "info", title: "Open or select a file to compare" });
const selection = arg === undefined ? projectViewSelection() : [];
const paths = selection.length ? selection : contextPaths(arg);
if (!paths.length) {
notifications().notify({ group: "vcs", level: "info", title: "Open or select a file or folder to compare" });
return;
}
const rev = await chooseRevision("Compare with Branch or Revision");
if (!rev) return;
await openDiff({ path, left: { type: "rev", rev, label: rev }, right: { type: "worktree" } });
await comparePathsWithRevision(paths);
},
},
{
+46
Переглянути файл
@@ -282,3 +282,49 @@
.manageRowSelected:hover {
background: var(--bg-list-selected);
}
.comparison {
display: flex;
height: min(520px, 65vh);
min-height: 180px;
padding: 0 12px 12px;
gap: 10px;
}
.comparisonTree {
flex: 1;
min-width: 0;
border: 1px solid var(--border);
}
.comparisonWithDiff .comparisonTree {
flex: 0 0 30%;
}
.comparisonDiff {
flex: 1;
min-width: 0;
min-height: 0;
overflow: hidden;
border: 1px solid var(--border);
}
.compareNotice {
padding: 6px 14px;
color: var(--fg-subtle);
overflow-wrap: anywhere;
}
.compareAdded {
color: var(--vcs-added);
font-variant-numeric: tabular-nums;
}
.compareRemoved {
color: var(--vcs-deleted);
font-variant-numeric: tabular-nums;
}
@media (max-width: 760px) {
.comparisonWithDiff {
flex-direction: column;
height: 65vh;
}
.comparisonWithDiff .comparisonTree {
flex: 0 0 30%;
min-height: 90px;
}
}
+53
Переглянути файл
@@ -0,0 +1,53 @@
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { chooseRepositoryRevision } from "./RevisionChooser";
import { openDiff } from "./diffInput";
import { showPathComparison } from "./operations";
import { displayPath } from "./compare";
export async function comparePathsWithRevision(paths: string[], revision?: string) {
const scope = await call(commands.vcsCompareScope(paths));
if (!scope.repositories.length) {
notifications().notify({
group: "vcs",
level: "info",
title: "Selection is outside Git repositories",
body: scope.skippedPaths.map((path) => displayPath(path)).join("\n"),
});
return;
}
const choice = revision
? { rev: revision, repositories: null }
: await chooseRepositoryRevision(tx("Compare with Branch or Revision"), {
repositories: scope.repositories,
tags: true,
});
if (!choice) return;
if (scope.singleFile && !revision) {
await openDiff({
path: paths[0]!,
left: { type: "rev", rev: choice.rev, label: choice.rev },
right: { type: "worktree" },
});
} else {
// A shared branch reviews the selection, including explicit errors for roots lacking it.
const repositories = choice.repositories && choice.repositories.length === 1 ? choice.repositories : null;
showPathComparison(paths, choice.rev, repositories);
}
}
/** Returns false for a single file, whose existing Show Diff behavior is retained. */
export async function showDirectoryWorkingDiff(paths: string[]): Promise<boolean> {
const scope = await call(commands.vcsCompareScope(paths));
if (scope.singleFile) return false;
if (!scope.repositories.length) {
notifications().notify({
group: "vcs",
level: "info",
title: "Selection is outside Git repositories",
body: scope.skippedPaths.map((path) => displayPath(path)).join("\n"),
});
} else showPathComparison(paths, "HEAD", null);
return true;
}
+203 -66
Переглянути файл
@@ -4,20 +4,23 @@ import { commitKey, commitRepo } from "./multiRoot";
* cherry-pick or revert, and the Git Log commit actions (Cherry-Pick, Revert
* Commit, Reset Current Branch to Here, New Tag, Compare with Local).
*/
import { useEffect, useState } from "react";
import type { ChangedFile, Commit, ResetMode } from "@/bindings";
import { useEffect, useMemo, useState } from "react";
import type { ChangedFile, Commit, CompareResult, ResetMode, WorkingTreeChange } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, Input, List, Spinner, fileIconName, T } from "@/ui";
import { call, commands, nextRequestId } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, Input, Tree, Spinner, fileIconName, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { openDiff, type DiffSide } from "./diffInput";
import { diffInput, openDiff, type DiffData, type DiffSide } from "./diffInput";
import { openDialog, promptText } from "./dialogs";
import { KIND_COLOR, baseName, dirName } from "./model";
import { KIND_COLOR, fileCount } from "./model";
import { runGitOperation, runOp } from "./ops";
import { reloadLog, useGitLog } from "./logStore";
import { conflictedFiles, currentRepo, currentRepoRoot, refreshNow, repoOf, useVcs } from "./store";
import { conflictedFiles, currentRepo, currentRepoRoot, refreshNow, repoName, repoOf, useVcs } from "./store";
import styles from "./common.module.css";
import { DiffEditor } from "./DiffEditor";
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
import { tx } from "@/platform/i18n";
import { displayPath } from "./compare";
// ---------------------------------------------------------------------------
// Operation in progress
@@ -479,102 +482,236 @@ export function showCompareRevisions(from: string, to: string, fromLabel = from,
));
}
export function showPathComparison(paths: string[], rev: string, repositories: string[] | null) {
openDialog((close) => (
<ChangesBetweenDialog from={{ rev, label: rev }} to={null} scope={{ paths, repositories }} onClose={close} />
));
}
interface Revision {
rev: string;
label: string;
}
/** Files that differ between `from` and `to` (`null`: the working tree). */
function ChangesBetweenDialog({ from, to, onClose }: { from: Revision; to: Revision | null; onClose: () => void }) {
interface ScopedComparison {
paths: string[];
repositories: string[] | null;
}
interface ComparisonFile extends ChangedFile {
root: string;
revision: string;
added?: number;
removed?: number;
}
export function comparisonEmpty(revision: string, repositories: number): string {
return repositories === 1
? tx`No changes against ${revision} in 1 repository`
: tx`No changes against ${revision} in ${repositories} repositories`;
}
/** Shared branch/commit comparison surface, also used for directory selections. */
export function ChangesBetweenDialog({
from,
to,
scope,
onClose,
}: {
from: Revision;
to: Revision | null;
scope?: ScopedComparison;
onClose: () => void;
}) {
const [root] = useState(currentRepoRoot);
const [repo] = useState(currentRepo);
const [files, setFiles] = useState<ChangedFile[] | null>(null);
const [files, setFiles] = useState<ComparisonFile[] | null>(null);
const [result, setResult] = useState<CompareResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [active, setActive] = useState(0);
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
const [current, setCurrent] = useState<ComparisonFile | null>(null);
const fromRev = from.rev;
const toRev = to?.rev ?? null;
useEffect(() => {
let alive = true;
call(toRev ? commands.vcsDiffRevisions(repo, fromRev, toRev) : commands.vcsDiffWithWorktree(repo, fromRev))
.then((f) => alive && setFiles(f))
.catch((e) => alive && setError(e instanceof Error ? e.message : String(e)));
let pending = true;
const request = nextRequestId();
const load = async () => {
if (scope) {
const r = await call(commands.vcsComparePaths(scope.paths, fromRev, scope.repositories, request));
if (!alive) return;
setResult(r);
setFiles(
r.repositories.flatMap((r) =>
r.files.map((f: WorkingTreeChange) => ({ ...f, root: r.root, revision: r.revision! })),
),
);
} else {
const f = await call(
toRev ? commands.vcsDiffRevisions(repo, fromRev, toRev) : commands.vcsDiffWithWorktree(repo, fromRev),
);
if (alive) setFiles(f.map((f) => ({ ...f, root: root ?? "", revision: fromRev })));
}
};
void load()
.catch((e) => alive && setError(e instanceof Error ? e.message : String(e)))
.finally(() => {
pending = false;
});
return () => {
alive = false;
if (scope && pending) void commands.cancelRequest(request);
};
}, [fromRev, toRev]);
const open = (f: ChangedFile) => {
const repoRoot = root;
}, [fromRev, toRev, repo, root, scope]);
const tree = useMemo(() => {
if (!scope) return buildFileTree(files ?? [], (f) => f.path);
return (result?.repositories ?? []).map((r): FileTreeNode<ComparisonFile> => {
const list = (files ?? []).filter((f) => f.root === r.root);
const prefix = (nodes: FileTreeNode<ComparisonFile>[]): FileTreeNode<ComparisonFile>[] =>
nodes.map((n) => ({ ...n, key: `${r.root}:${n.key}`, children: prefix(n.children) }));
return {
key: r.root,
name: repoName(r.root),
file: null,
count: list.length,
children: prefix(buildFileTree(list, (f) => f.path)),
};
});
}, [files, result, scope]);
const diffFor = (f: ComparisonFile): DiffData => {
const missing = (label: string): DiffSide => ({ type: "text", text: "", label });
void openDiff({
path: `${repoRoot}/${f.path}`,
return {
path: `${f.root}/${f.path}`,
left:
f.kind === "added" || f.kind === "untracked"
? missing("(does not exist)")
: { type: "rev", rev: from.rev, label: from.label, path: f.oldPath ? `${repoRoot}/${f.oldPath}` : undefined },
right: !to
? { type: "worktree" }
: f.kind === "deleted"
: {
type: "rev",
rev: f.revision,
label: from.label,
path: f.oldPath ? `${f.root}/${f.oldPath}` : undefined,
},
right:
f.kind === "deleted"
? missing("(deleted)")
: { type: "rev", rev: to.rev, label: to.label },
});
: !to
? { type: "worktree" }
: { type: "rev", rev: to.rev, label: to.label },
};
};
const current = files?.[active];
const input = current ? diffInput(diffFor(current)) : null;
const title = to
? tx`Changes between ${from.label} and ${to.label}`
: tx`Changes between ${from.label} and Local Working Tree`;
const count = files ? fileCount(files.length) : "";
const successful = result?.repositories.filter((r) => !r.error && !r.missingRevision).length ?? 1;
const allMissing = !!result?.repositories.length && result.repositories.every((r) => r.missingRevision);
const skipped = result?.skippedPaths.map((path) => displayPath(path)) ?? [];
const skippedNames = skipped.slice(0, 5).join(", ");
const skippedLabel = skipped.length > 5 ? tx`${skippedNames} and ${skipped.length - 5} more` : skippedNames;
return (
<Dialog
open
title={
to
? tx`Changes between ${from.label} and ${to.label}`
: tx`Changes between ${from.label} and Local Working Tree`
}
title={files ? `${title} — ${count}` : title}
onClose={onClose}
width={620}
width={input ? 1100 : 680}
buttons={[
{ label: "Show Diff", role: "default", disabled: !current, onClick: () => current && open(current) },
{
label: "Show Diff",
role: "default",
disabled: !current,
onClick: () => {
if (current) {
void openDiff(diffFor(current));
onClose();
}
},
},
{ label: "Close", role: "cancel" },
]}
>
<div className={styles.section}>{files ? `${files.length} file${files.length === 1 ? "" : "s"} differ` : ""}</div>
<div style={{ height: 300, display: "flex", flexDirection: "column", padding: "0 14px 14px" }}>
{error ? (
<div className={styles.error}>{error}</div>
) : !files ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<List
items={files}
getKey={(f) => f.path}
activeIndex={Math.min(active, Math.max(0, files.length - 1))}
onActiveChange={setActive}
rowHeight={22}
aria-label="Changed files"
className={styles.boxList}
empty={
<span>
<T>No differences</T>
</span>
}
onActivate={(f, _i, e) => {
if (e.type === "click" && (e as unknown as MouseEvent).detail < 2) return;
open(f);
{error && (
<div className={styles.error} role="alert">
{error}
</div>
)}
{result?.skippedPaths.length ? (
<div className={styles.compareNotice}>{tx`Skipped content outside Git repositories: ${skippedLabel}`}</div>
) : null}
{allMissing ? (
<div className={styles.empty} role="status">
{tx`No repository in the selection has revision ${from.label}`}
</div>
) : (
result?.repositories
.filter((r) => r.error || r.missingRevision)
.map((r) => (
<div key={r.root} className={styles.compareNotice} role={r.missingRevision ? "status" : "alert"}>
{r.missingRevision
? tx`${repoName(r.root)} has no revision ${from.label}`
: tx`Cannot compare ${repoName(r.root)} against ${from.label}: ${r.error}`}
</div>
))
)}
{!files && !error ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : null}
{files && !files.length && successful > 0 ? (
<div className={styles.empty} role="status">
{comparisonEmpty(from.label, successful)}
</div>
) : null}
{files && files.length > 0 ? (
<div className={`${styles.comparison} ${input ? styles.comparisonWithDiff : ""}`}>
<Tree<FileTreeNode<ComparisonFile>>
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => n.name}
getChildren={(n) => (n.file ? undefined : n.children)}
isExpandable={(n) => !n.file}
expanded={expanded ?? new Set(dirKeys(tree))}
onExpandedChange={setExpanded}
selected={selected}
onSelectionChange={(sel, lead) => {
setSelected(sel);
if (lead?.file) setCurrent(lead.file);
}}
renderItem={(f) => (
<span className={styles.fileRow} style={{ flex: 1, padding: 0 }}>
<Icon name={fileIconName(baseName(f.path))} size={14} />
onActivate={(n) => n.file && setCurrent(n.file)}
aria-label="Changed files"
className={styles.comparisonTree}
renderNode={(n) => (
<span className={styles.fileRow} style={{ flex: 1, padding: 0 }} title={n.file ? n.file.path : n.name}>
<Icon name={n.file ? fileIconName(n.name) : "folder"} size={14} />
<span
className={styles.fileName}
style={{ color: KIND_COLOR[f.kind === "untracked" ? "added" : f.kind] }}
style={
n.file ? { color: KIND_COLOR[n.file.kind === "untracked" ? "added" : n.file.kind] } : undefined
}
>
{baseName(f.path)}
{n.name}
</span>
<span className={styles.fileDir}>{dirName(f.path)}</span>
{n.file ? (
<>
<span className={styles.fileDir}>{tx(n.file.kind)}</span>
{n.file.added !== undefined && <span className={styles.compareAdded}>+{n.file.added}</span>}
{n.file.removed !== undefined && <span className={styles.compareRemoved}>−{n.file.removed}</span>}
</>
) : (
<span className={styles.fileDir}>{n.count}</span>
)}
</span>
)}
/>
)}
</div>
{input && (
<div className={styles.comparisonDiff}>
<DiffEditor key={input.key} input={input} />
</div>
)}
</div>
) : null}
</Dialog>
);
}
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { commands } from "./ipc";
import { pasteClipboardFiles, readClipboardText } from "./clipboard";
beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
function transfer(text: string, files = true): DataTransfer {
return { getData: () => text, files: [], types: files ? ["Files"] : ["text/plain"] } as unknown as DataTransfer;
}
const cases = [
{ name: "text present", text: "plain text", paths: ["/stale"], expected: "plain text", calls: 0 },
{
name: "files plus list",
text: "",
paths: ["/a b", "/中文", "C:\\folder"],
expected: "/a b\n/中文\nC:\\folder",
calls: 1,
},
{ name: "files without list", text: "", paths: [], expected: "", calls: 1 },
{ name: "backend error", text: "", paths: null, expected: "", calls: 1 },
];
describe("clipboard text", () => {
it.each(cases)("$name", async ({ text, paths, expected, calls }) => {
const list = vi.spyOn(commands, "clipboardFileList");
if (paths) list.mockResolvedValue({ status: "ok", data: paths });
else list.mockRejectedValue(new Error("busy"));
expect(await readClipboardText(transfer(text))).toBe(expected);
expect(list).toHaveBeenCalledTimes(calls);
list.mockClear();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => text } });
expect(await readClipboardText()).toBe(expected);
expect(list).toHaveBeenCalledTimes(calls);
});
it("does not consult files for an empty text-only event or a browser", async () => {
const list = vi.spyOn(commands, "clipboardFileList");
expect(await readClipboardText(transfer("", false))).toBe("");
vi.unstubAllGlobals();
expect(await readClipboardText(transfer(""))).toBe("");
expect(list).not.toHaveBeenCalled();
});
it("does not intercept text, already handled images, or an absent transfer", () => {
const paste = vi.fn();
for (const data of [transfer("text"), null]) {
const event = new Event("paste", { cancelable: true }) as ClipboardEvent;
Object.defineProperty(event, "clipboardData", { value: data });
expect(pasteClipboardFiles(event, paste)).toBe(false);
}
const event = new Event("paste", { cancelable: true }) as ClipboardEvent;
Object.defineProperty(event, "clipboardData", { value: transfer("") });
event.preventDefault();
expect(pasteClipboardFiles(event, paste)).toBe(false);
expect(paste).not.toHaveBeenCalled();
});
});
+48
Переглянути файл
@@ -0,0 +1,48 @@
import { call, commands, isTauri } from "./ipc";
import { ipcPath } from "./paths";
type FormatFiles = (paths: string[]) => string;
const rawPaths: FormatFiles = (paths) => paths.join("\n");
/** WebKit exposes native file URLs as Files, hiding the pasteboard's text flavor. */
export async function readClipboardText(
transfer?: DataTransfer | null,
formatFiles: FormatFiles = rawPaths,
): Promise<string> {
const text = transfer ? transfer.getData("text/plain") : ((await navigator.clipboard?.readText()) ?? "");
if ((text && formatFiles === rawPaths) || (transfer && !hasClipboardFiles(transfer)) || !isTauri()) return text;
try {
const paths = await call(commands.clipboardFileList());
// Windows also supplies the file list as text; unrelated text still wins.
if (text && text.replace(/\r\n/g, "\n").split("\n").map(ipcPath).join("\n") !== paths.join("\n")) return text;
return formatFiles(paths);
} catch {
return text;
}
}
function hasClipboardFiles(transfer: DataTransfer): boolean {
return !!transfer.files.length || Array.from(transfer.types).includes("Files");
}
/** Claim synchronously so the native handler cannot emit an empty paste while IPC runs. */
export function pasteClipboardFiles(
event: ClipboardEvent,
paste: (text: string) => void,
formatFiles: FormatFiles = rawPaths,
): boolean {
const transfer = event.clipboardData;
if (
event.defaultPrevented ||
!transfer ||
(transfer.getData("text/plain") && formatFiles === rawPaths) ||
!hasClipboardFiles(transfer)
)
return false;
event.preventDefault();
event.stopImmediatePropagation();
void readClipboardText(transfer, formatFiles).then((text) => {
if (text) paste(text);
});
return true;
}
+16 -2
Переглянути файл
@@ -4,7 +4,7 @@
* `${classpath}` (or `${testClasspath}`) and the `java` launcher are resolved
* through jdtls when the configuration starts.
*/
import { call, commands, type JavaLaunchInfo, type RunConfig, type RequestId } from "@/platform/ipc";
import { call, commands, IpcError, type JavaLaunchInfo, type RunConfig, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
export const CLASSPATH = "${classpath}";
@@ -167,7 +167,21 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep
const module = await resolveJavaModule(config);
signal.throwIfAborted();
const moduleMs = performance.now() - started;
const info = await call(commands.javaResolveLaunch(module, parsed.classpath === "test", true, preparation.request));
const info = await call(
commands.javaResolveLaunch(module, parsed.classpath === "test", true, preparation.request),
).catch((error: unknown) => {
if (
error instanceof IpcError &&
error.kind !== "cancelled" &&
/^jdtls:.*(?:does not belong to any java project|references non-existing project|not a java project)/i.test(
error.message,
)
)
throw new Error(
tx`Java module '${module || "."}' is not imported. Wait for Java project import to finish. If it still fails, check the run configuration's module and whether it is included in the parent Maven or Gradle build, or open its folder as a project.`,
);
throw error;
});
signal.throwIfAborted();
console.info("Java launch preparation", { module, moduleMs, resolveMs: performance.now() - started - moduleMs });
if (info.build === "withErrors")
+15 -1
Переглянути файл
@@ -1,4 +1,7 @@
{
"Uploading files": "正在上传文件",
"No files on the clipboard": "剪贴板中没有文件",
"File name is not valid UTF-8": "文件名不是有效的 UTF-8",
"Project opening cancelled": "已取消打开项目",
"Project is in Restricted Mode": "项目处于受限模式",
"Project is in Restricted Mode. Trust the project to enable execution.": "项目处于受限模式。信任项目后可启用执行功能。",
@@ -18,6 +21,7 @@
"Security": "安全",
"Remove Trusted Location": "移除受信任的位置",
"Cannot determine the module for main class '{value}'": "无法确定主类 '{value}' 所属的模块",
"Java module '{value}' is not imported. Wait for Java project import to finish. If it still fails, check the run configuration's module and whether it is included in the parent Maven or Gradle build, or open its folder as a project.": "Java 模块 '{value}' 尚未导入。请等待 Java 项目导入完成。如果仍然失败,请检查运行配置选择的模块,以及该模块是否已包含在父级 Maven 或 Gradle 构建中,或将其文件夹作为项目打开。",
"Attach": "附加",
"Remove from Workspace": "从工作区移除",
"Downloading Java {0} language server runtime": "正在下载 Java {0} 语言服务器运行时",
@@ -5344,5 +5348,15 @@
"No debug output available": "暂无可用的调试输出",
"The attached process may not provide standard output to the debugger.": "附加的进程可能不会向调试器提供标准输出。",
"Show in Debug Tool Window": "在调试工具窗口中显示",
"Suspended": "已暂停"
"Suspended": "已暂停",
"Cannot compare {root} against {label}: {error}": "无法将 {root} 与 {label} 比较:{error}",
"Compare with Branch or Revision": "与分支或修订比较",
"No changes against {revision} in 1 repository": "在 1 个仓库中与 {revision} 相比没有更改",
"No changes against {revision} in {repositories} repositories": "在 {repositories} 个仓库中与 {revision} 相比没有更改",
"Open or select a file or folder to compare": "打开或选择要比较的文件或文件夹",
"Selection is outside Git repositories": "所选内容不在 Git 仓库中",
"Skipped content outside Git repositories: {skippedLabel}": "已跳过 Git 仓库之外的内容:{skippedLabel}",
"in {length} repositories": "在 {length} 个仓库中",
"No repository in the selection has revision {label}": "所选内容中的仓库均无版本 {label}",
"{repoName} has no revision {label}": "{repoName} 没有版本 {label}"
}
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { nativeDropPoint } from "./nativeDrop";
describe("native drop coordinates", () => {
for (const os of ["macos", "linux", "windows"]) {
for (const scale of [1, 1.5, 2, 3]) {
for (const zoom of [0.5, 1, 1.25, 2, 3]) {
it(`${os}, display scale ${scale}, zoom ${zoom}`, () => {
// Native Cocoa/GTK locations are unzoomed logical points; Win32 is physical.
const unit = os === "windows" ? scale * zoom : zoom;
const dpr = os === "windows" ? scale * zoom : scale;
for (const point of [
{ x: 122, y: 116 },
{ x: 122, y: 236 },
{ x: 700, y: 800 },
]) {
const native = { x: point.x * unit, y: point.y * unit };
expect(nativeDropPoint(native, os, dpr, zoom)).toEqual(point);
}
});
}
}
}
it("matches measured Retina macOS positions at 100% and 125%", () => {
expect(nativeDropPoint({ x: 122, y: 236 }, "macos", 2, 1)).toEqual({ x: 122, y: 236 });
expect(nativeDropPoint({ x: 152, y: 295 }, "macos", 2, 1.25)).toEqual({ x: 121.6, y: 236 });
});
});
+21
Переглянути файл
@@ -0,0 +1,21 @@
import { usePlatform } from "./platformInfo";
import { useProject } from "./project";
import { clampZoom } from "./zoom";
interface Point {
x: number;
y: number;
}
/** Wry Cocoa/GTK supply logical points; Win32 supplies physical client pixels.
* WebView2's DPR includes zoom; WKWebView's does not. All consumers need CSS pixels.
*/
export function nativeDropPoint(
point: Point,
os = usePlatform.getState().os,
dpr = window.devicePixelRatio || 1,
zoom = clampZoom(useProject.getState().settings?.appearance?.zoom) / 100,
): Point {
const divisor = os === "windows" ? dpr : zoom;
return { x: point.x / divisor, y: point.y / divisor };
}
+36
Переглянути файл
@@ -71,6 +71,42 @@ describe("Tabs interactions", () => {
expect(onClose).toHaveBeenCalledWith("b");
});
it("Shift+left-click closes an editor tab without selecting it", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
render(<Tabs items={items} activeId="a" onSelect={onSelect} onClose={onClose} closeOnShiftClick />);
fireEvent.click(screen.getByRole("tab", { name: "B" }), { shiftKey: true, detail: 1 });
expect(onClose).toHaveBeenCalledWith("b");
expect(onSelect).not.toHaveBeenCalled();
});
it("Shift+click only closes closable tabs", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
render(<Tabs items={items} activeId="a" onSelect={onSelect} onClose={onClose} closeOnShiftClick />);
fireEvent.click(screen.getByRole("tab", { name: "C" }), { shiftKey: true, detail: 1 });
expect(onClose).not.toHaveBeenCalled();
expect(onSelect).toHaveBeenCalledWith("c");
});
it("keeps Shift+click selection where the strip does not opt in", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
render(<Tabs items={items} activeId="a" onSelect={onSelect} onClose={onClose} />);
fireEvent.click(screen.getByRole("tab", { name: "B" }), { shiftKey: true, detail: 1 });
expect(onClose).not.toHaveBeenCalled();
expect(onSelect).toHaveBeenCalledWith("b");
});
it("does not treat a keyboard click with Shift held as a close", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
render(<Tabs items={items} activeId="a" onSelect={onSelect} onClose={onClose} closeOnShiftClick />);
fireEvent.click(screen.getByRole("tab", { name: "B" }), { shiftKey: true });
expect(onClose).not.toHaveBeenCalled();
expect(onSelect).toHaveBeenCalledWith("b");
});
it("lets a container close the selected tab when it is closable", () => {
const handles: TabStripHandle[] = [];
const register = (h: TabStripHandle) => (handles.push(h), () => void handles.splice(handles.indexOf(h), 1));
+14 -2
Переглянути файл
@@ -88,6 +88,8 @@ export interface TabsProps {
onClose?: (id: string) => void;
/** Alt+click on a close button (IDEA: close all other tabs). */
onCloseOthers?: (id: string) => void;
/** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */
closeOnShiftClick?: boolean;
onDoubleClick?: (id: string) => void;
onContextMenu?: (id: string, e: MouseEvent) => void;
/** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */
@@ -114,6 +116,7 @@ export function Tabs({
onSelect,
onClose,
onCloseOthers,
closeOnShiftClick,
onDoubleClick,
onContextMenu,
variant = "editor",
@@ -287,7 +290,8 @@ export function Tabs({
onPointerDown={
dnd
? (e) => {
if ((e.target as Element).closest("[data-tab-close]")) return;
if ((closeOnShiftClick && e.shiftKey) || (e.target as Element).closest("[data-tab-close]"))
return;
startPointerDrag(
e,
e.currentTarget,
@@ -336,7 +340,15 @@ export function Tabs({
tabIndex={selected || (!activeId && index === 0) ? 0 : -1}
className={styles.tabButton}
style={item.color ? { color: item.color } : undefined}
onClick={() => onSelect(item.id)}
onClick={(e) => {
// Shift+click is mouse-only: a keyboard Enter with Shift held still selects.
if (closeOnShiftClick && e.shiftKey && e.detail > 0 && closable) {
e.preventDefault();
onClose!(item.id);
return;
}
onSelect(item.id);
}}
onDoubleClick={onDoubleClick ? () => onDoubleClick(item.id) : undefined}
onKeyDown={(e) => onKeyDown(e, index, item)}
{...tooltipAttrs(item.tooltip)}
+103 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
import { createRef } from "react";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { Tree, type TreeHandle } from "./Tree";
@@ -364,3 +364,105 @@ describe("Tree horizontal scrolling", () => {
}
});
});
describe("Tree scroll following", () => {
let scrollTo: ReturnType<typeof vi.fn>;
let original: PropertyDescriptor | undefined;
beforeAll(() => {
// jsdom has no Element.scrollTo; virtual-core calls it to write scrollTop.
scrollTo = vi.fn();
original = Object.getOwnPropertyDescriptor(Element.prototype, "scrollTo");
Object.defineProperty(Element.prototype, "scrollTo", { value: scrollTo, configurable: true, writable: true });
});
afterAll(() => {
if (original) Object.defineProperty(Element.prototype, "scrollTo", original);
else delete (Element.prototype as { scrollTo?: unknown }).scrollTo;
});
it("brings the keyboard lead into view", () => {
const { key } = setup();
scrollTo.mockClear();
key("End");
expect(scrollTo).toHaveBeenCalled();
});
it("keeps the viewport when expanding a folder above the selection", () => {
// The selected file stays selected while rows inserted above it shift its
// index; scrolling then would jump to the selection from the opened folder.
const { tree } = setup({ defaultSelected: ["README.md"] });
scrollTo.mockClear();
const chevron = tree.querySelector("[data-tree-toggle]");
expect(chevron).not.toBeNull();
fireEvent.mouseDown(chevron!, { button: 0 });
expect(scrollTo).not.toHaveBeenCalled();
// The folder did open, inserting rows above the selection.
expect(within(tree).queryAllByRole("treeitem").length).toBeGreaterThan(2);
});
it.each(["defaultSelected", "selected"] as const)("scrolls a late %s lead once when its row loads", (selection) => {
const view = (roots: N[]) => (
<Tree<N>
roots={roots}
getKey={(n) => n.id}
getLabel={(n) => n.id}
getChildren={(n) => n.children}
isExpandable={(n) => n.id === "src" || !!n.children}
defaultExpanded={["src"]}
{...{ [selection]: new Set(["late.ts"]) }}
/>
);
const { rerender } = render(view([{ id: "src" }]));
scrollTo.mockClear();
// An intermediate load still does not contain the selected row.
rerender(view([{ id: "src", children: [{ id: "main", children: [{ id: "App.tsx" }] }] }]));
expect(scrollTo).not.toHaveBeenCalled();
rerender(view([{ id: "src", children: [{ id: "main", children: [{ id: "App.tsx" }] }, { id: "late.ts" }] }]));
expect(scrollTo).toHaveBeenCalledTimes(1);
expect(screen.getByRole("treeitem", { name: "late.ts" })).toHaveAttribute("aria-selected", "true");
scrollTo.mockClear();
const folder = screen.getByRole("treeitem", { name: "main" });
fireEvent.mouseDown(folder.querySelector("[data-tree-toggle]")!, { button: 0 });
expect(screen.getByRole("treeitem", { name: "App.tsx" })).toBeInTheDocument();
expect(scrollTo).not.toHaveBeenCalled();
fireEvent.mouseDown(folder.querySelector("[data-tree-toggle]")!, { button: 0 });
expect(scrollTo).not.toHaveBeenCalled();
});
it("replaces a pending lead when the user selects another row", () => {
const view = (roots: N[]) => (
<Tree<N>
roots={roots}
getKey={(n) => n.id}
getLabel={(n) => n.id}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children}
defaultSelected={["late.ts"]}
/>
);
const { rerender } = render(view([{ id: "README.md" }]));
fireEvent.keyDown(screen.getByRole("tree"), { key: "End" });
scrollTo.mockClear();
rerender(view([{ id: "late.ts" }, { id: "README.md" }]));
expect(screen.getByRole("treeitem", { name: "README.md" })).toHaveAttribute("aria-selected", "true");
expect(scrollTo).not.toHaveBeenCalled();
});
it("explicitly reveals an unchanged lead", () => {
const handle = createRef<TreeHandle>();
setup({ handleRef: handle, defaultSelected: ["README.md"] });
scrollTo.mockClear();
act(() => handle.current!.reveal("README.md"));
expect(scrollTo).toHaveBeenCalledTimes(1);
});
it("brings speed search matches into view", () => {
const { key, lead } = setup({ defaultExpanded: ["src", "main"] });
key("Home");
scrollTo.mockClear();
key("u");
expect(lead()).toBe("util.ts");
expect(scrollTo).toHaveBeenCalledTimes(1);
});
});
+17 -2
Переглянути файл
@@ -307,9 +307,24 @@ export function Tree<T>(props: TreeProps<T>) {
getItemKey: (i) => rows[i]!.key,
});
// Keep the keyboard lead in view when the lead changes — not when its index
// shifts because expanding or collapsing elsewhere inserted rows above it:
// following the index would yank the viewport from the folder the user just
// opened back to the selection.
const pendingScrollToLead = useRef<string | null>(null);
useEffect(() => {
if (leadIndex >= 0) virtualizer.scrollToIndex(leadIndex, { align: "auto" });
}, [leadIndex, virtualizer]);
pendingScrollToLead.current = lead;
}, [lead]);
// A preselected lead may arrive before its row is loaded. Retry until it
// appears, then stop following index changes for that selection.
useEffect(() => {
const key = pendingScrollToLead.current;
if (key == null) return;
const i = indexOfKey.get(key);
if (i === undefined) return;
virtualizer.scrollToIndex(i, { align: "auto" });
pendingScrollToLead.current = null;
}, [lead, indexOfKey, virtualizer]);
// Speed search owns Escape while active.
useEffect(() => {
+3 -2
Переглянути файл
@@ -8,6 +8,7 @@ import { executeAction } from "@/platform/actions";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { nativeDropPoint } from "@/platform/nativeDrop";
import { editorService, OWNS_FILE_DROP } from "./contributions";
const OWNER_ATTR = Object.keys(OWNS_FILE_DROP)[0]!;
@@ -71,8 +72,8 @@ export function installFileDrop(): () => void {
.onDragDropEvent((event) => {
const p = event.payload;
if (p.type !== "drop") return;
const ratio = window.devicePixelRatio || 1;
void handleFileDrop(p.paths, p.position.x / ratio, p.position.y / ratio);
const { x, y } = nativeDropPoint(p.position);
void handleFileDrop(p.paths, x, y);
})
.then((u) => {
if (disposed) u();