дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
9876a69e60 | ||
|
|
f48cd85d0b | ||
|
|
9e35cfc064 | ||
|
|
0a71f6be88 | ||
|
|
b3c3150489 | ||
|
|
1d937d52e5 | ||
|
|
5f57ce962e | ||
|
|
95b45c095d | ||
|
|
9dc736de09 | ||
|
|
369c63979d | ||
|
|
347e3525d2 | ||
|
|
5280c9e584 | ||
|
|
67cad01ba7 | ||
|
|
ad92b1577f | ||
|
|
06109aae95 | ||
|
|
b2d1188049 | ||
|
|
5329ddc469 | ||
|
|
2faa64fb68 | ||
|
|
d6f6525ca5 | ||
|
|
2c9a6470ff | ||
|
|
cf51b57924 | ||
|
|
e7740e4032 | ||
|
|
bdadecdf91 | ||
|
|
178fc9eaba | ||
|
|
17e3cd2b39 |
No files matched your search
@@ -70,6 +70,12 @@ jobs:
|
||||
- name: Linux x64
|
||||
os: ubuntu-22.04
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- name: Linux arm64
|
||||
os: ubuntu-22.04-arm
|
||||
target: aarch64-unknown-linux-gnu
|
||||
- name: Windows arm64
|
||||
os: windows-11-arm
|
||||
target: aarch64-pc-windows-msvc
|
||||
- name: Windows x64
|
||||
os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
@@ -196,11 +202,16 @@ jobs:
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
[/_arm64_en-US\.msi$/, ["windows-aarch64", "windows-aarch64-msi"]],
|
||||
[/_arm64-setup\.exe$/, ["windows-aarch64-nsis"]],
|
||||
[/_x64_en-US\.msi$/, ["windows-x86_64", "windows-x86_64-msi"]],
|
||||
[/_x64-setup\.exe$/, ["windows-x86_64-nsis"]],
|
||||
];
|
||||
|
||||
Створено
+39
-35
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4061,7 +4061,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4075,7 +4075,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4090,7 +4090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4115,7 +4115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4129,7 +4129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4147,7 +4147,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4208,7 +4208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4253,7 +4253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4271,7 +4271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4293,7 +4293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4309,7 +4309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4364,7 +4364,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4388,7 +4388,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4411,7 +4411,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4429,7 +4429,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4442,7 +4442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4459,7 +4459,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4482,7 +4482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4501,7 +4501,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4521,7 +4521,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4534,7 +4534,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4553,7 +4553,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4568,7 +4568,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4581,7 +4581,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4593,7 +4593,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4614,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4633,7 +4633,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4655,7 +4655,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4671,7 +4671,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6141,9 +6141,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"block2 0.6.2",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"ide-agent",
|
||||
@@ -6180,6 +6181,9 @@ dependencies = [
|
||||
"ide-vfs",
|
||||
"ide-web",
|
||||
"ide-workspace",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.29"
|
||||
version = "0.1.32"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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"]})));
|
||||
}
|
||||
|
||||
|
||||
@@ -222,6 +222,13 @@ fn choose<'a>(entry: &'a Entry, platform: Platform, on_path: &dyn Fn(&str) -> bo
|
||||
{
|
||||
return Some(Choice::Uvx(p));
|
||||
}
|
||||
// Last resort: npx and uvx run natively, this one under OS emulation.
|
||||
if platform.os == Os::Windows
|
||||
&& platform.arch == Arch::Arm64
|
||||
&& let Some(b) = d.binary.get("windows-x86_64")
|
||||
{
|
||||
return Some(Choice::Binary(b));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -689,6 +696,20 @@ mod tests {
|
||||
const LINUX: Platform = Platform { os: Os::Linux, arch: Arch::X64 };
|
||||
const WINDOWS: Platform = Platform { os: Os::Windows, arch: Arch::X64 };
|
||||
|
||||
#[test]
|
||||
fn windows_arm_binary_prefers_native_then_x64() {
|
||||
let mut entry = parse(INDEX).unwrap().remove(0);
|
||||
let arm = Platform { os: Os::Windows, arch: Arch::Arm64 };
|
||||
assert!(matches!(choose(&entry, arm, &|_| false), Some(Choice::Binary(_))));
|
||||
assert!(choose(&entry, Platform { os: Os::Linux, arch: Arch::Arm64 }, &|_| false).is_none());
|
||||
entry.distribution.npx = Some(serde_json::from_str(r#"{"package":"amp-acp"}"#).unwrap());
|
||||
assert!(matches!(choose(&entry, arm, &|_| true), Some(Choice::Npx(_))));
|
||||
let mut native = entry.distribution.binary["windows-x86_64"].clone();
|
||||
native.cmd = "native.exe".into();
|
||||
entry.distribution.binary.insert("windows-aarch64".into(), native);
|
||||
assert!(matches!(choose(&entry, arm, &|_| false), Some(Choice::Binary(b)) if b.cmd == "native.exe"));
|
||||
}
|
||||
|
||||
const INDEX: &str = r#"{"version":"1.0.0","agents":[
|
||||
{"id":"amp-acp","name":"Amp","version":"0.10.0","description":"Amp over ACP",
|
||||
"repository":"https://github.com/x/amp-acp","authors":["x"],"license":"Apache-2.0",
|
||||
|
||||
@@ -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 })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ use std::sync::Arc;
|
||||
pub enum IdeEvent {
|
||||
/// Project window membership or selection changed.
|
||||
WindowGroupsChanged,
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
trusted: bool,
|
||||
},
|
||||
/// Files or directories changed on disk (after debouncing, ignore rules applied).
|
||||
FsChanged {
|
||||
created: Vec<crate::IpcPath>,
|
||||
|
||||
@@ -285,6 +285,8 @@ pub struct AppearanceSettings {
|
||||
pub project_colors_in_toolbar: bool,
|
||||
pub dnd_with_alt_only: bool,
|
||||
pub menu_icons: bool,
|
||||
/// `hamburger` | `merged`: main menu presentation in the frameless title bar.
|
||||
pub main_menu_style: String,
|
||||
/// `subpixel` | `greyscale` | `none`
|
||||
pub ide_antialiasing: String,
|
||||
pub editor_antialiasing: String,
|
||||
@@ -331,6 +333,7 @@ impl Default for AppearanceSettings {
|
||||
project_colors_in_toolbar: true,
|
||||
dnd_with_alt_only: false,
|
||||
menu_icons: true,
|
||||
main_menu_style: "hamburger".into(),
|
||||
ide_antialiasing: "greyscale".into(),
|
||||
editor_antialiasing: "greyscale".into(),
|
||||
show_tool_window_bars: true,
|
||||
@@ -446,6 +449,8 @@ impl Default for EditorSettings {
|
||||
pub struct FileSettings {
|
||||
/// Save on focus loss / tab switch, like IDEA.
|
||||
pub auto_save: bool,
|
||||
/// Re-check open files against disk when the IDE window gains focus.
|
||||
pub sync_on_focus: bool,
|
||||
pub exclude: Vec<String>,
|
||||
/// Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`].
|
||||
pub ignored_names: Vec<String>,
|
||||
@@ -477,6 +482,7 @@ impl Default for FileSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_save: true,
|
||||
sync_on_focus: true,
|
||||
exclude: vec!["**/.git".into(), "**/node_modules".into(), "**/target".into()],
|
||||
ignored_names: crate::ignored::DEFAULT_IGNORED_NAMES.iter().map(|s| (*s).into()).collect(),
|
||||
trim_trailing_whitespace: true,
|
||||
@@ -713,6 +719,15 @@ impl Settings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn main_menu_style_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"compactMode":true}}"#).unwrap();
|
||||
assert_eq!(old.appearance.main_menu_style, "hamburger");
|
||||
let merged: Settings = serde_json::from_str(r#"{"appearance":{"mainMenuStyle":"merged"}}"#).unwrap();
|
||||
assert_eq!(merged.appearance.main_menu_style, "merged");
|
||||
assert_eq!(serde_json::to_value(merged).unwrap()["appearance"]["mainMenuStyle"], "merged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_font_weights_default_to_regular_and_bold() {
|
||||
let json = serde_json::to_value(Settings::default()).unwrap();
|
||||
|
||||
@@ -44,6 +44,7 @@ struct State {
|
||||
project: Changes,
|
||||
/// Project roots whose `postStartCommand` ran in this process.
|
||||
post_started: HashSet<PathBuf>,
|
||||
post_commands: std::collections::HashMap<PathBuf, CancellationToken>,
|
||||
}
|
||||
|
||||
pub struct Environment {
|
||||
@@ -78,7 +79,12 @@ impl Environment {
|
||||
|
||||
pub(crate) fn project_closed(&self) {
|
||||
if self.project_env {
|
||||
self.state.lock().project.clear();
|
||||
let mut state = self.state.lock();
|
||||
for (_, token) in state.post_commands.drain() {
|
||||
token.cancel();
|
||||
}
|
||||
state.project.clear();
|
||||
drop(state);
|
||||
self.publish();
|
||||
}
|
||||
}
|
||||
@@ -144,6 +150,7 @@ impl Environment {
|
||||
/// a failure is a notification.
|
||||
pub(crate) fn spawn_post_start(&self, cmd: LifecycleCommand, root: PathBuf, sink: SharedSink) {
|
||||
let cancel = self.cancel.child_token();
|
||||
self.state.lock().post_commands.insert(root.clone(), cancel.clone());
|
||||
let spawned = std::thread::Builder::new().name("openidea-post-start".into()).spawn(move || {
|
||||
run_post_start(&cmd, &root, &sink, &cancel);
|
||||
});
|
||||
@@ -263,6 +270,9 @@ fn run_post_start(cmd: &LifecycleCommand, root: &Path, sink: &SharedSink, cancel
|
||||
/// Runs `argv` in `root` with the children's environment, its stdout and stderr line by line
|
||||
/// to `on_line`; `Err` says how it failed.
|
||||
fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &dyn Fn(String)) -> Result<(), String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
let (program, args) = argv.split_first().ok_or("empty command")?;
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(program))
|
||||
.args(args)
|
||||
|
||||
@@ -12,6 +12,7 @@ mod proxy;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
|
||||
pub use project::{Project, apply_git_executable, apply_workspace_edit, history_retention};
|
||||
|
||||
@@ -44,6 +45,7 @@ pub struct HostConfig {
|
||||
}
|
||||
|
||||
pub struct Host {
|
||||
pub trust: trust::TrustStore,
|
||||
pub config_dir: PathBuf,
|
||||
pub data_dir: PathBuf,
|
||||
pub languages: Arc<LanguageRegistry>,
|
||||
@@ -67,6 +69,7 @@ pub struct Host {
|
||||
/// One project per window, keyed by window label.
|
||||
projects: RwLock<HashMap<String, Arc<Project>>>,
|
||||
requests: requests::Requests,
|
||||
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
@@ -77,6 +80,7 @@ impl Host {
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let host = Self {
|
||||
trust: trust::TrustStore::load(&config_dir, &data_dir),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
|
||||
ssh,
|
||||
@@ -95,6 +99,7 @@ impl Host {
|
||||
runtime,
|
||||
projects: RwLock::default(),
|
||||
requests: Default::default(),
|
||||
project_requests: RwLock::default(),
|
||||
};
|
||||
host.apply_proxy();
|
||||
host
|
||||
@@ -119,6 +124,10 @@ impl Host {
|
||||
.ok_or_else(|| IdeError::not_found("no project is open in this window"))
|
||||
}
|
||||
|
||||
pub fn require_trust(&self, window: &str) -> IdeResult<()> {
|
||||
self.project(window)?.require_trust()
|
||||
}
|
||||
|
||||
/// The window that owns what `window` starts.
|
||||
pub fn owner_window<'a>(&self, window: &'a str) -> &'a str {
|
||||
(self.owner)(window)
|
||||
@@ -212,7 +221,19 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_request(id);
|
||||
self.project_requests.write().entry(self.owner_window(window).to_owned()).or_default().push(id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
token.cancel();
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
pub fn end_request(&self, id: RequestId) {
|
||||
for ids in self.project_requests.write().values_mut() {
|
||||
ids.retain(|entry| *entry != id);
|
||||
}
|
||||
self.requests.end(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -407,6 +407,24 @@ impl NotebookService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn restrict(&self) {
|
||||
let documents: Vec<_> = self.registry.lock().documents.values().cloned().collect();
|
||||
for document in &documents {
|
||||
let mut state = document.state.lock();
|
||||
state.generation += 1;
|
||||
if let Some(batch) = &state.active {
|
||||
batch.cancel.cancel();
|
||||
}
|
||||
}
|
||||
for document in documents {
|
||||
let _ = self.kernels.shutdown_kernel(&document.path).await;
|
||||
let batch = document.state.lock().active.clone();
|
||||
if let Err(error) = self.drain(&document, batch).await {
|
||||
tracing::warn!("notebook restriction: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) {
|
||||
self.stop_admission();
|
||||
self.kernels.shutdown().await;
|
||||
|
||||
@@ -17,6 +17,7 @@ pub fn subscribe(host: &Host, window: &str, on_event: Emit<AgentEvent>) -> IdeRe
|
||||
}
|
||||
|
||||
pub fn providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
host.require_trust(window)?;
|
||||
let mut providers = host.project(window)?.agents.providers();
|
||||
ide_agent::registry::mark_updates(®istry_paths(host), &mut providers);
|
||||
Ok(providers)
|
||||
@@ -88,6 +89,7 @@ pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>
|
||||
}
|
||||
|
||||
pub async fn create(host: &Host, window: &str, mut request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let requested = request.project_root.take();
|
||||
@@ -99,6 +101,7 @@ pub async fn create(host: &Host, window: &str, mut request: NewAgentTask) -> Ide
|
||||
|
||||
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
|
||||
pub async fn prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.prompt(&task, prompt, now).await
|
||||
}
|
||||
|
||||
@@ -109,26 +112,31 @@ pub fn unqueue(host: &Host, window: &str, task: String, queued: String) -> IdeRe
|
||||
|
||||
/// Sends a queued message now, interrupting the current turn.
|
||||
pub fn send_queued_now(host: &Host, window: &str, task: String, queued: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.send_queued_now(&task, &queued)
|
||||
}
|
||||
|
||||
/// Changes a session setting (model, mode, thinking effort…).
|
||||
pub async fn set_config(host: &Host, window: &str, task: String, option: String, value: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.set_config(&task, &option, value).await
|
||||
}
|
||||
|
||||
/// Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`).
|
||||
pub async fn fork(host: &Host, window: &str, task: String, turns: Option<u32>) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.fork(&task, turns).await
|
||||
}
|
||||
|
||||
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
|
||||
pub async fn rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.rollback(&task, turns).await
|
||||
}
|
||||
|
||||
/// What the agent reports about itself when it starts, without opening a session.
|
||||
pub async fn probe(host: &Host, window: &str, provider: String, refresh: bool) -> IdeResult<AgentProbe> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.probe(&provider, refresh).await
|
||||
}
|
||||
|
||||
@@ -139,6 +147,7 @@ pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>)
|
||||
|
||||
/// Answers a permission request; `option: None` cancels it.
|
||||
pub fn respond(host: &Host, window: &str, task: String, permission: u32, option: Option<String>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.respond(&task, permission, option)
|
||||
}
|
||||
|
||||
@@ -151,15 +160,18 @@ pub fn unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
pub async fn delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
|
||||
pub async fn changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentChange>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.changes(&task).await
|
||||
}
|
||||
|
||||
/// Content of `path` when the task started (left side of its diff).
|
||||
pub async fn base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
|
||||
/// Maven and Gradle projects of the window's project, from the build files plus the last sync.
|
||||
pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
tokio::task::spawn_blocking(move || load(&root, &cache, &settings)).await.map_err(join_err)
|
||||
@@ -93,9 +94,10 @@ pub async fn build_sync(
|
||||
profiles: Vec<String>,
|
||||
on_progress: Channel<SyncProgress>,
|
||||
) -> IdeResult<BuildModel> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
let token = host.begin_request(request);
|
||||
let token = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let current = load(&root, &cache, &settings);
|
||||
let env = match tool {
|
||||
@@ -223,11 +225,12 @@ pub async fn build_run(
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let settings = project.settings.effective();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let token = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send
|
||||
/// How to run `config` with coverage: the command to launch and where its report will be,
|
||||
/// or which tool is missing.
|
||||
pub async fn coverage_prepare(host: &Host, window: &str, config: RunConfig) -> IdeResult<CoveragePrepared> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache) = (project.root.clone(), project.cache_dir.join("coverage"));
|
||||
blocking(move || {
|
||||
@@ -26,7 +27,8 @@ pub async fn coverage_prepare(host: &Host, window: &str, config: RunConfig) -> I
|
||||
}
|
||||
|
||||
/// Reads the report a coverage run left behind.
|
||||
pub async fn coverage_collect(_host: &Host, _window: &str, report: CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
host.require_trust(window)?;
|
||||
blocking(move || ide_coverage::collect(&report)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::path::PathBuf;
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
|
||||
host.require_trust(window)?;
|
||||
let mut config = match_java_debug_encoding(config, cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
&& config.request == "launch"
|
||||
@@ -76,6 +77,7 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
host.require_trust(window)?;
|
||||
let result = host.debugger.start_with(config, owner, custom).await;
|
||||
flush_output();
|
||||
result
|
||||
@@ -307,11 +309,12 @@ pub async fn debug_attachable_processes(_host: &Host, _window: &str) -> IdeResul
|
||||
/// JVM to connect to `host:port`; returns the loopback port java-debug attaches to.
|
||||
pub async fn debug_listen_for_jvm(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
jvm_host: String,
|
||||
port: u16,
|
||||
) -> IdeResult<u16> {
|
||||
host.require_trust(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let result = jdwp::listen_for_jvm(&jvm_host, port, token).await;
|
||||
host.end_request(request);
|
||||
|
||||
@@ -38,6 +38,18 @@ pub async fn save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
/// Recovers external changes missed by the project's file watchers.
|
||||
pub async fn sync_from_disk(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
if project.settings.effective().files.sync_on_focus {
|
||||
project.documents.sync_from_disk();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn snapshot(host: &Host, window: &str, doc: DocId) -> IdeResult<DocumentInfo> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.snapshot(doc)).await
|
||||
@@ -45,3 +57,6 @@ pub async fn snapshot(host: &Host, window: &str, doc: DocId) -> IdeResult<Docume
|
||||
|
||||
mod commands;
|
||||
pub use commands::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,200 @@
|
||||
use super::*;
|
||||
use crate::{HostConfig, Project};
|
||||
use ide_core::{IdeEvent, TextChange, event::NotifyLevel};
|
||||
use parking_lot::Mutex;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
struct Fixture {
|
||||
host: Host,
|
||||
project: Arc<Project>,
|
||||
events: Arc<Mutex<Vec<IdeEvent>>>,
|
||||
path: PathBuf,
|
||||
outside: PathBuf,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
// Keep watcher delivery out of these tests: the op must recover it itself.
|
||||
let excluded = root.join("node_modules");
|
||||
std::fs::create_dir_all(&excluded).unwrap();
|
||||
let path = excluded.join("file.txt");
|
||||
let outside = base.join("outside.txt");
|
||||
std::fs::write(&path, "original\n").unwrap();
|
||||
std::fs::write(&outside, "outside\n").unwrap();
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let captured = events.clone();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |_| {
|
||||
let events = captured.clone();
|
||||
Arc::new(move |event| events.lock().push(event))
|
||||
}),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
Self { _temp: temp, host, project, events, path, outside }
|
||||
}
|
||||
|
||||
async fn open(&self, path: &Path) -> DocumentInfo {
|
||||
open(&self.host, "main", path.to_path_buf()).await.unwrap()
|
||||
}
|
||||
|
||||
async fn sync(&self) {
|
||||
sync_from_disk(&self.host, "main").await.unwrap();
|
||||
}
|
||||
|
||||
fn document_events(&self) -> Vec<IdeEvent> {
|
||||
self.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::DocPatched { .. } | IdeEvent::DocDirty { .. } | IdeEvent::Notify { .. }))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn changed_clean_document_reloads_once() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
std::fs::write(&f.path, "externally changed\n").unwrap();
|
||||
f.sync().await;
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(loaded.text, "externally changed\n");
|
||||
assert!(!loaded.dirty);
|
||||
assert!(loaded.version > original.version);
|
||||
f.events.lock().clear();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().version, loaded.version);
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn unchanged_document_has_no_patch_or_event() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
f.events.lock().clear();
|
||||
f.sync().await;
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(loaded.text, original.text);
|
||||
assert_eq!(loaded.version, original.version);
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn dirty_document_keeps_edits_and_warns_once() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
edit(
|
||||
&f.host,
|
||||
"main",
|
||||
original.id,
|
||||
original.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
|
||||
)
|
||||
.unwrap();
|
||||
f.events.lock().clear();
|
||||
std::fs::write(&f.path, "external replacement\n").unwrap();
|
||||
f.sync().await;
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(loaded.text, "local original\n");
|
||||
assert!(loaded.dirty);
|
||||
assert!(matches!(f.document_events().as_slice(), [IdeEvent::Notify { level: NotifyLevel::Warning, .. }]));
|
||||
f.events.lock().clear();
|
||||
f.sync().await;
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn deleted_document_keeps_its_buffer_and_other_documents_still_reload() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.path).await;
|
||||
let outside = f.open(&f.outside).await;
|
||||
std::fs::remove_file(&f.path).unwrap();
|
||||
std::fs::write(&f.outside, "outside changed after deletion\n").unwrap();
|
||||
f.sync().await;
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
assert_eq!(loaded.text, original.text);
|
||||
assert_eq!(loaded.version, original.version);
|
||||
assert_eq!(f.project.documents.snapshot(outside.id).unwrap().text, "outside changed after deletion\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn outside_project_document_reloads() {
|
||||
let f = Fixture::new();
|
||||
assert!(!f.outside.starts_with(&f.project.root));
|
||||
let original = f.open(&f.outside).await;
|
||||
std::fs::write(&f.outside, "outside changed externally\n").unwrap();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "outside changed externally\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn setting_defaults_on_and_disabled_sync_keeps_buffer() {
|
||||
let f = Fixture::new();
|
||||
assert!(f.project.settings.effective().files.sync_on_focus);
|
||||
assert!(serde_json::from_value::<ide_core::settings::FileSettings>(serde_json::json!({})).unwrap().sync_on_focus);
|
||||
let original = f.open(&f.outside).await;
|
||||
f.project.settings.set(ide_workspace::settings::SettingsScope::Project, "files.syncOnFocus", false.into()).unwrap();
|
||||
std::fs::write(&f.outside, "external change while disabled\n").unwrap();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().version, original.version);
|
||||
f.project.settings.set(ide_workspace::settings::SettingsScope::Project, "files.syncOnFocus", true.into()).unwrap();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "external change while disabled\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn properties_reload_preserves_native_to_ascii_decoding() {
|
||||
let f = Fixture::new();
|
||||
let path = f.outside.with_extension("properties");
|
||||
std::fs::write(&path, "key=\\u4F60\n").unwrap();
|
||||
let mut defaults = f.project.documents.file_defaults();
|
||||
defaults.native_to_ascii = true;
|
||||
f.project.documents.set_file_defaults(defaults);
|
||||
let original = f.open(&path).await;
|
||||
assert_eq!(original.text, "key=你\n");
|
||||
std::fs::write(&path, "key=\\u4E16\\u754C\n").unwrap();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "key=世界\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn binary_and_virtual_documents_are_skipped() {
|
||||
let f = Fixture::new();
|
||||
let path = f.outside.with_extension("bin");
|
||||
std::fs::write(&path, b"\0\0binary payload").unwrap();
|
||||
let binary = f.open(&path).await;
|
||||
assert!(binary.read_only);
|
||||
let virtual_doc =
|
||||
f.project.documents.open_virtual("test://virtual", ide_core::LanguageId::plain_text(), "virtual").unwrap();
|
||||
std::fs::write(&path, "now ordinary text").unwrap();
|
||||
f.events.lock().clear();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(binary.id).unwrap().version, binary.version);
|
||||
assert_eq!(f.project.documents.snapshot(virtual_doc.id).unwrap().text, "virtual");
|
||||
assert!(f.document_events().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn synchronization_only_changes_the_calling_windows_documents() {
|
||||
let f = Fixture::new();
|
||||
let original = f.open(&f.outside).await;
|
||||
let other_root = f.outside.parent().unwrap().join("other-project");
|
||||
std::fs::create_dir(&other_root).unwrap();
|
||||
let other = f.host.open_project("other", &other_root).unwrap();
|
||||
let other_doc = open(&f.host, "other", f.outside.clone()).await.unwrap();
|
||||
std::fs::write(&f.outside, "external change in shared file\n").unwrap();
|
||||
f.sync().await;
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "external change in shared file\n");
|
||||
assert_eq!(other.documents.snapshot(other_doc.id).unwrap().text, other_doc.text);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use std::sync::Arc;
|
||||
/// Re-reads the login shell (and the window's project `remoteEnv` where it applies);
|
||||
/// running terminals and processes keep their environment.
|
||||
pub async fn reload(host: &Arc<Host>, window: &str) -> IdeResult<EnvReloaded> {
|
||||
let root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let root = host.project(window).ok().filter(|p| !p.light && p.is_trusted()).map(|p| p.root.clone());
|
||||
let sink = host.window_sink(window);
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.environment.reload(root.as_deref(), &sink)).await
|
||||
|
||||
@@ -20,7 +20,8 @@ pub async fn java_resolve_launch(
|
||||
build: bool,
|
||||
request: RequestId,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let cancel = host.begin_request(request);
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = resolve_launch(host, window, module, test, build, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
@@ -104,6 +105,7 @@ async fn resolve_launch(
|
||||
|
||||
/// Port of java-debug's DAP server inside the jdtls serving `module` (started on demand).
|
||||
pub async fn java_debug_server(host: &Host, window: &str, module: PathBuf) -> IdeResult<u16> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
project.lsp.java_debug_server(&module).await
|
||||
@@ -115,6 +117,7 @@ pub async fn java_build_workspace(
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
) -> IdeResult<ide_lsp::jdtls::JavaBuildStatus> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
project.lsp.java_build(&module, &CancellationToken::new()).await
|
||||
|
||||
@@ -54,6 +54,7 @@ pub async fn reload(host: &Host, window: &str, id: String) -> IdeResult<Notebook
|
||||
}
|
||||
|
||||
pub async fn restart(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot> {
|
||||
host.require_trust(window)?;
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.reload(&id, true).await })
|
||||
.await
|
||||
@@ -84,8 +85,9 @@ pub async fn execute(
|
||||
request: RequestId,
|
||||
on_output: Channel<NotebookOutputEvent>,
|
||||
) -> IdeResult<NotebookSnapshot> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let _request = RequestGuard { host, request, cancel: cancel.clone() };
|
||||
// Reserve the WHOLE batch and capture source before asynchronous discovery.
|
||||
let admission = project.notebooks.admit(&id, cells, cancel.clone())?;
|
||||
|
||||
@@ -10,6 +10,7 @@ use std::sync::Arc;
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProjectInfo {
|
||||
pub trusted: bool,
|
||||
pub root: ide_core::IpcPath,
|
||||
pub name: String,
|
||||
pub is_git: bool,
|
||||
@@ -22,6 +23,7 @@ pub fn info(project: &Project) -> ProjectInfo {
|
||||
let settings = project.settings.effective();
|
||||
let custom = settings.general.project_name.trim();
|
||||
ProjectInfo {
|
||||
trusted: project.is_trusted(),
|
||||
name: if custom.is_empty() {
|
||||
project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
|
||||
} else {
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::time::Duration;
|
||||
|
||||
/// Detected configs followed by user-defined ones (user ids win on conflict).
|
||||
pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let user = ide_run::load_user_configs(&root)?;
|
||||
@@ -70,6 +71,7 @@ pub fn save_configs(
|
||||
}
|
||||
|
||||
pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit<OutputChunk>) -> IdeResult<RunInfo> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
if config.command.is_empty() {
|
||||
return Err(IdeError::invalid("run configuration has no command"));
|
||||
@@ -135,6 +137,7 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: if member.is_some() { vec![root.clone()] } else { super::python::paths(&project) },
|
||||
};
|
||||
project.require_trust()?;
|
||||
let mut sink = project.sink.clone();
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
let previous = sink;
|
||||
|
||||
@@ -50,6 +50,7 @@ pub async fn run_test_reports(
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_home(host: &Host, window: &str, home: String) -> IdeResult<ide_run::tomcat::TomcatHome> {
|
||||
host.require_trust(window)?;
|
||||
let root = host.project(window)?.root.clone();
|
||||
tokio::task::spawn_blocking(move || ide_run::tomcat::validate_home(&root.join(home)))
|
||||
.await
|
||||
@@ -57,6 +58,7 @@ pub async fn run_tomcat_home(host: &Host, window: &str, home: String) -> IdeResu
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<ide_build::web::WebArtifact>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
@@ -67,6 +69,7 @@ pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult<Vec<id
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> IdeResult<Option<RunConfig>> {
|
||||
host.require_trust(window)?;
|
||||
if config.extras.params.get("deployment").is_some_and(|v| v != "artifact") {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -119,6 +122,7 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
}
|
||||
|
||||
pub async fn run_tomcat_update(host: &Host, window: &str, config: RunConfig, mode: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
if !host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
|
||||
return Err(IdeError::invalid("Start this Tomcat configuration before updating it"));
|
||||
|
||||
@@ -22,12 +22,14 @@ pub struct LocatedTools {
|
||||
|
||||
/// Installed interpreters / toolchains of `kind`; project-local ones first.
|
||||
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
|
||||
host.require_trust(window)?;
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
tokio::task::spawn_blocking(move || ide_sdk::detect(kind, root.as_deref())).await.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The interpreter the project uses: the configured one, else its virtualenv.
|
||||
pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
Ok(ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()).map(Into::into))
|
||||
}
|
||||
@@ -35,6 +37,7 @@ pub fn sdk_python_effective(host: &Host, window: &str) -> IdeResult<Option<ide_c
|
||||
/// SDK / library source folders shown under "External Libraries" in the Project view,
|
||||
/// with the Maven / Gradle dependency jars of the build model.
|
||||
pub async fn sdk_project_libraries(host: &Host, window: &str) -> IdeResult<Vec<ide_sdk::libraries::LibraryGroup>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -56,11 +59,12 @@ pub async fn sdk_project_libraries(host: &Host, window: &str) -> IdeResult<Vec<i
|
||||
|
||||
/// Looks up `names` (bare command names): `node_modules/.bin` above `near`, then the search path.
|
||||
pub async fn sdk_locate_tools(
|
||||
_host: &Host,
|
||||
_window: &str,
|
||||
host: &Host,
|
||||
window: &str,
|
||||
names: Vec<String>,
|
||||
near: Option<PathBuf>,
|
||||
) -> IdeResult<LocatedTools> {
|
||||
host.require_trust(window)?;
|
||||
tokio::task::spawn_blocking(move || LocatedTools {
|
||||
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
|
||||
compile_dir: ide_sdk::locate::compile_dir().into(),
|
||||
@@ -72,13 +76,14 @@ pub async fn sdk_locate_tools(
|
||||
/// `base -m venv location`; output lines stream through `on_output`.
|
||||
pub async fn sdk_python_create_venv(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
window: &str,
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<Sdk> {
|
||||
let cancel = host.begin_request(request);
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::python::create_venv(&base, &location, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
@@ -92,11 +97,12 @@ pub async fn sdk_python_create_venv(
|
||||
|
||||
pub async fn sdk_python_packages(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
window: &str,
|
||||
python: PathBuf,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PythonPackage>> {
|
||||
let cancel = host.begin_request(request);
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
|
||||
host.end_request(request);
|
||||
@@ -107,7 +113,7 @@ pub async fn sdk_python_packages(
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn sdk_python_pip(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
window: &str,
|
||||
python: PathBuf,
|
||||
requirement: String,
|
||||
uninstall: bool,
|
||||
@@ -115,7 +121,8 @@ pub async fn sdk_python_pip(
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let cancel = host.begin_request(request);
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let send = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
|
||||
@@ -3,12 +3,24 @@ use crate::Host;
|
||||
use ide_core::{IdeResult, TerminalId};
|
||||
use ide_terminal::{TerminalInfo, TerminalOptions};
|
||||
|
||||
pub fn spawn(host: &Host, window: &str, options: TerminalOptions, on_output: Emit<String>) -> IdeResult<TerminalInfo> {
|
||||
pub fn spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
mut options: TerminalOptions,
|
||||
on_output: Emit<String>,
|
||||
) -> IdeResult<TerminalInfo> {
|
||||
if !host.project(window).is_ok_and(|p| p.is_trusted()) {
|
||||
// Project terminal settings can otherwise start a command as soon as a tab restores.
|
||||
let global = host.global_settings.effective().terminal;
|
||||
options.shell = None;
|
||||
options.args.clear();
|
||||
options.env = global.env;
|
||||
}
|
||||
// Python › "Activate virtualenv": typed into the new shell, like PyCharm.
|
||||
let activation = host
|
||||
.project(window)
|
||||
.ok()
|
||||
.and_then(|p| ide_sdk::apply::terminal_activation(&p.root, &p.settings.effective(), options.shell.as_deref()));
|
||||
let activation =
|
||||
host.project(window).ok().filter(|p| p.is_trusted()).and_then(|p| {
|
||||
ide_sdk::apply::terminal_activation(&p.root, &p.settings.effective(), options.shell.as_deref())
|
||||
});
|
||||
let info = host.terminals.spawn(options, host.window_sink(window), Box::new(move |chunk| on_output(chunk)))?;
|
||||
if let Some(line) = activation {
|
||||
let _ = host.terminals.write(info.id, &format!(" {line}\r"));
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::path::PathBuf;
|
||||
|
||||
/// The installer, reporting the executables chosen in the window's settings.
|
||||
fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
host.require_trust(window)?;
|
||||
let data = host.data_dir.clone();
|
||||
let (settings, root) = match host.project(window) {
|
||||
Ok(project) => (project.settings.effective(), project.root.clone()),
|
||||
|
||||
@@ -7,7 +7,9 @@ pub async fn status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
apply_git_executable(&settings);
|
||||
if project.is_trusted() {
|
||||
apply_git_executable(&settings);
|
||||
}
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
|
||||
@@ -259,6 +259,7 @@ pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> Id
|
||||
}
|
||||
|
||||
pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
|
||||
}
|
||||
@@ -271,6 +272,7 @@ pub async fn vcs_add_to_ignore(
|
||||
paths: Vec<PathBuf>,
|
||||
destination: IgnoreDestination,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
for path in &paths {
|
||||
@@ -292,16 +294,19 @@ pub async fn vcs_add_to_ignore(
|
||||
}
|
||||
|
||||
pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_stage_patch(host: &Host, window: &str, patch: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.stage_patch(&patch, &|path| project.vcs_encoding(path, Some(":0"))))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_discard(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || per_repo(&project, &paths, Some("Rollback"), |r, paths| r.discard(paths))).await
|
||||
}
|
||||
@@ -313,6 +318,7 @@ pub async fn vcs_commit(
|
||||
message: String,
|
||||
options: CommitOptions,
|
||||
) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
// Commit hooks may run for a long time.
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
@@ -331,6 +337,7 @@ pub async fn vcs_checkout(
|
||||
create: bool,
|
||||
options: Option<ide_vcs::CheckoutOptions>,
|
||||
) -> IdeResult<ide_vcs::CheckoutOutcome> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let options = options.unwrap_or_default();
|
||||
blocking(move || {
|
||||
@@ -349,6 +356,7 @@ pub async fn vcs_create_branch(
|
||||
start: Option<String>,
|
||||
checkout: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let recorded = checkout.then_some("Git checkout");
|
||||
blocking(move || {
|
||||
@@ -360,6 +368,7 @@ pub async fn vcs_create_branch(
|
||||
/// Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged.
|
||||
/// Returns the undone commit's message.
|
||||
pub async fn vcs_undo_commit(host: &Host, window: &str, repo: Option<PathBuf>, commit: String) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.undo_commit(&commit))).await
|
||||
}
|
||||
@@ -370,6 +379,7 @@ pub async fn vcs_delete_branch(
|
||||
repo: Option<PathBuf>,
|
||||
branch: String,
|
||||
) -> IdeResult<ide_vcs::DeletedBranch> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch_restorable(&branch))).await
|
||||
}
|
||||
@@ -381,6 +391,7 @@ pub async fn vcs_restore_branch(
|
||||
repo: Option<PathBuf>,
|
||||
deleted: ide_vcs::DeletedBranch,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_branch(&deleted))).await
|
||||
}
|
||||
@@ -392,16 +403,19 @@ pub async fn vcs_rename_branch(
|
||||
from: String,
|
||||
to: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.rename_branch(&from, &to))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_merge(host: &Host, window: &str, repo: Option<PathBuf>, branch: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge(&branch))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_rebase(host: &Host, window: &str, repo: Option<PathBuf>, onto: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase(&onto))).await
|
||||
}
|
||||
@@ -414,6 +428,7 @@ pub async fn vcs_stash_push(
|
||||
include_untracked: bool,
|
||||
keep_index: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git stash"), |r| {
|
||||
@@ -432,6 +447,7 @@ pub async fn vcs_stash_apply(
|
||||
reinstate_index: bool,
|
||||
branch: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| match branch.as_deref() {
|
||||
@@ -443,6 +459,7 @@ pub async fn vcs_stash_apply(
|
||||
}
|
||||
|
||||
pub async fn vcs_stash_drop(host: &Host, window: &str, repo: Option<PathBuf>, index: u32) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stash_drop(index))).await
|
||||
}
|
||||
@@ -456,6 +473,7 @@ pub async fn vcs_remote(
|
||||
op: RemoteOp,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
@@ -514,6 +532,7 @@ pub fn vcs_diff_hunks(_host: &Host, _window: &str, old_text: String, new_text: S
|
||||
/// Stages only the selected hunks of a file's working-tree changes.
|
||||
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
|
||||
pub async fn vcs_stage_hunks(host: &Host, window: &str, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let encoding = project.vcs_encoding(&path, Some(":0"))?;
|
||||
@@ -556,7 +575,8 @@ pub async fn vcs_init(host: &Host, _window: &str, dir: PathBuf) -> IdeResult<()>
|
||||
|
||||
/// Settings › Git › Test: runs `git --version` on `path`, or on the auto-detected
|
||||
/// executable when `path` is empty.
|
||||
pub async fn vcs_git_version(_host: &Host, _window: &str, path: String) -> IdeResult<GitExecutableInfo> {
|
||||
pub async fn vcs_git_version(host: &Host, window: &str, path: String) -> IdeResult<GitExecutableInfo> {
|
||||
host.require_trust(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let explicit = path.trim();
|
||||
let exe = if explicit.is_empty() {
|
||||
@@ -598,6 +618,7 @@ pub async fn vcs_operation(
|
||||
op: GitOperation,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
@@ -638,6 +659,7 @@ pub async fn vcs_create_tag(
|
||||
message: Option<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.create_tag(&name, &commit, message.as_deref(), force)))
|
||||
.await
|
||||
@@ -656,6 +678,7 @@ pub async fn vcs_merge_with(
|
||||
branches: Vec<String>,
|
||||
options: MergeOptions,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge_with(&branches, &options))
|
||||
@@ -671,6 +694,7 @@ pub async fn vcs_rebase_with(
|
||||
upstream: String,
|
||||
options: RebaseOptions,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase_with(&upstream, &options))
|
||||
@@ -684,6 +708,7 @@ pub async fn vcs_remotes(host: &Host, window: &str, repo: Option<PathBuf>) -> Id
|
||||
}
|
||||
|
||||
pub async fn vcs_edit_remote(host: &Host, window: &str, repo: Option<PathBuf>, edit: RemoteEdit) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.edit_remote(&edit))).await
|
||||
}
|
||||
@@ -701,6 +726,7 @@ pub async fn vcs_add_worktree(
|
||||
commitish: String,
|
||||
new_branch: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_at(repo.as_deref(), |r| r.add_worktree(&path, &commitish, new_branch.as_deref()))
|
||||
@@ -715,10 +741,38 @@ pub async fn vcs_remove_worktree(
|
||||
path: PathBuf,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
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,
|
||||
@@ -790,12 +844,14 @@ pub async fn vcs_apply_patch(
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.apply_patch(&patch))).await
|
||||
}
|
||||
|
||||
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
|
||||
pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec<PathBuf>) -> IdeResult<ShelvedChangeList> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
in_primary_repo(&project, &paths)?;
|
||||
@@ -819,6 +875,7 @@ pub async fn vcs_unshelve(
|
||||
remove: bool,
|
||||
path: Option<String>,
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(None, Some("Unshelve"), |r| {
|
||||
@@ -1010,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
|
||||
});
|
||||
|
||||
@@ -15,9 +15,11 @@ use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoo
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// Everything bound to one open project folder.
|
||||
pub struct Project {
|
||||
pub(crate) trusted: Arc<AtomicBool>,
|
||||
pub root: PathBuf,
|
||||
/// Window-scoped event sink, for commands that emit project events.
|
||||
pub sink: SharedSink,
|
||||
@@ -80,7 +82,9 @@ impl Host {
|
||||
self.close_project(window);
|
||||
let sink: SharedSink = (self.sink_for)(window);
|
||||
// Before anything the project starts: its children get the project's environment.
|
||||
let post_start = self.environment.project_opened(&root, &sink);
|
||||
let trusted = Arc::new(AtomicBool::new(self.trust.trusted(&root)?));
|
||||
let post_start =
|
||||
trusted.load(Ordering::Acquire).then(|| self.environment.project_opened(&root, &sink)).flatten();
|
||||
let settings = SettingsStore::load(&self.config_dir, Some(&root));
|
||||
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
|
||||
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read());
|
||||
@@ -114,6 +118,7 @@ impl Host {
|
||||
)?;
|
||||
mark("index");
|
||||
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
|
||||
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
lsp.set_content_roots(extra_roots.clone());
|
||||
let settings = Arc::new(settings);
|
||||
{
|
||||
@@ -208,9 +213,13 @@ impl Host {
|
||||
root: root.clone(),
|
||||
sink: sink.clone(),
|
||||
runtime: self.runtime.clone(),
|
||||
trusted: trusted.clone(),
|
||||
}));
|
||||
|
||||
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
}
|
||||
let watcher = {
|
||||
let repos = repos.clone();
|
||||
let settings = settings.clone();
|
||||
@@ -224,6 +233,7 @@ impl Host {
|
||||
let remote = self.remote.clone();
|
||||
let runtime = self.runtime.clone();
|
||||
let lsp = lsp.clone();
|
||||
let trusted = trusted.clone();
|
||||
Watcher::start(
|
||||
&root.clone(),
|
||||
excludes.clone(),
|
||||
@@ -241,7 +251,7 @@ impl Host {
|
||||
documents.redetect_languages();
|
||||
}
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
if !batch.removed.is_empty() {
|
||||
if trusted.load(Ordering::Acquire) && !batch.removed.is_empty() {
|
||||
delete_deployed(
|
||||
&runtime,
|
||||
remote.clone(),
|
||||
@@ -331,6 +341,7 @@ impl Host {
|
||||
);
|
||||
ide_agent::registry::maintain(crate::ops::agent::registry_paths(self));
|
||||
let project = Arc::new(Project {
|
||||
trusted,
|
||||
root,
|
||||
sink,
|
||||
languages,
|
||||
@@ -446,6 +457,7 @@ impl Host {
|
||||
sink.clone(),
|
||||
);
|
||||
let project = Arc::new(Project {
|
||||
trusted: Arc::new(AtomicBool::new(true)),
|
||||
sink,
|
||||
languages,
|
||||
settings,
|
||||
@@ -476,6 +488,18 @@ impl Host {
|
||||
}
|
||||
|
||||
impl Project {
|
||||
pub fn is_trusted(&self) -> bool {
|
||||
self.trusted.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn require_trust(&self) -> IdeResult<()> {
|
||||
if self.is_trusted() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
|
||||
}
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
pub fn watch_light_dir(&self, dir: &Path) {
|
||||
if !self.light {
|
||||
@@ -550,7 +574,11 @@ impl Project {
|
||||
|
||||
/// The project's git repositories.
|
||||
pub fn repos(&self) -> Repos {
|
||||
self.repos.read().clone()
|
||||
let repos = self.repos.read().clone();
|
||||
for repo in repos.all() {
|
||||
repo.set_execution_allowed(self.is_trusted());
|
||||
}
|
||||
repos
|
||||
}
|
||||
|
||||
/// Runs `f` with the repository whose root is `at`, the project's primary repository
|
||||
@@ -582,7 +610,9 @@ impl Project {
|
||||
|
||||
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let settings = self.settings.effective();
|
||||
apply_git_executable(&settings);
|
||||
if self.is_trusted() {
|
||||
apply_git_executable(&settings);
|
||||
}
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
f(repo)
|
||||
}
|
||||
@@ -981,6 +1011,7 @@ impl DocumentObserver for HistoryObserver {
|
||||
|
||||
/// Uploads saved files: remote files' local copies, and automatic upload to the default server.
|
||||
struct DeployObserver {
|
||||
trusted: Arc<AtomicBool>,
|
||||
remote: Arc<ide_remote::RemoteService>,
|
||||
settings: Arc<SettingsStore>,
|
||||
root: PathBuf,
|
||||
@@ -990,6 +1021,9 @@ struct DeployObserver {
|
||||
|
||||
impl DocumentObserver for DeployObserver {
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) {
|
||||
if !self.trusted.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let (remote, settings, root, sink, path) =
|
||||
(self.remote.clone(), self.settings.clone(), self.root.clone(), self.sink.clone(), path.to_path_buf());
|
||||
self.runtime.spawn(async move {
|
||||
|
||||
@@ -24,7 +24,7 @@ use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -138,6 +138,15 @@ impl Dispatcher {
|
||||
/// terminals, runs and VCS status.
|
||||
pub fn standard() -> Self {
|
||||
let mut d = Self::default();
|
||||
d.add("project_trust_status", |c| async move { c.host.trust.status(&c.arg::<PathBuf>("path")?) })
|
||||
.add("project_trust_list", |c| async move { c.host.trust.decisions() })
|
||||
.add("project_trust_set", |c| async move {
|
||||
c.host.set_project_trust(&c.arg::<PathBuf>("path")?, c.arg("trusted")?, c.arg("folder")?).await
|
||||
})
|
||||
.add("project_trust_remove_location", |c| async move {
|
||||
c.host.trust.remove_location(&c.arg::<PathBuf>("path")?)?;
|
||||
c.host.refresh_project_trust().await
|
||||
});
|
||||
d.add("open_project", |c| async move {
|
||||
let path: PathBuf = c.arg("path")?;
|
||||
let project = ops::project::open(&c.host, &c.window, &path).await?;
|
||||
@@ -189,6 +198,7 @@ impl Dispatcher {
|
||||
})
|
||||
.add("doc_save", |c| async move { ops::doc::save(&c.host, &c.window, c.arg("doc")?).await })
|
||||
.add("doc_save_all", |c| async move { ops::doc::save_all(&c.host, &c.window).await })
|
||||
.add("doc_sync_from_disk", |c| async move { ops::doc::sync_from_disk(&c.host, &c.window).await })
|
||||
.add("doc_snapshot", |c| async move { ops::doc::snapshot(&c.host, &c.window, c.arg("doc")?).await })
|
||||
.add("search_start", |c| async move {
|
||||
let on_event = c.channel("onEvent")?;
|
||||
@@ -290,6 +300,7 @@ impl Handler for ServerHandler {
|
||||
let Some(handler) = self.dispatcher.handlers.get(call.cmd.as_str()).cloned() else {
|
||||
return Err((codes::METHOD_NOT_FOUND, format!("command {} is not available remotely", call.cmd)));
|
||||
};
|
||||
self.host.authorize_command(&call.window, &call.cmd).map_err(error_reply)?;
|
||||
let c = Call { host: self.host.clone(), window: call.window, args: call.args, peer: self.peer.clone() };
|
||||
// Requests run on blocking-capable threads: wait for the command here.
|
||||
self.host.runtime.block_on(handler(c)).map_err(error_reply)
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! User-owned project execution decisions. Project settings never grant trust.
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TrustDecisions {
|
||||
pub projects: Vec<PathBuf>,
|
||||
pub locations: Vec<PathBuf>,
|
||||
pub restricted: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
pub struct TrustStore {
|
||||
file: PathBuf,
|
||||
state: Mutex<IdeResult<TrustDecisions>>,
|
||||
}
|
||||
|
||||
impl TrustStore {
|
||||
pub fn load(config: &Path, data: &Path) -> Self {
|
||||
let file = data.join("project-trust.json");
|
||||
let state = match std::fs::read(&file) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| IdeError::invalid(e.to_string())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let projects = ide_workspace::RecentProjects::load(config)
|
||||
.paths()
|
||||
.into_iter()
|
||||
.filter_map(|p| dunce::canonicalize(p).ok())
|
||||
.collect();
|
||||
let migrated = TrustDecisions { projects, ..Default::default() };
|
||||
persist(&file, &migrated).map(|()| migrated)
|
||||
}
|
||||
Err(e) => Err(e.into()),
|
||||
};
|
||||
Self { file, state: Mutex::new(state) }
|
||||
}
|
||||
|
||||
pub fn decisions(&self) -> IdeResult<TrustDecisions> {
|
||||
self.state.lock().clone()
|
||||
}
|
||||
|
||||
pub fn trusted(&self, path: &Path) -> IdeResult<bool> {
|
||||
let root = dunce::canonicalize(path)?;
|
||||
let decisions = self.decisions()?;
|
||||
Ok(!decisions.restricted.contains(&root)
|
||||
&& (decisions.projects.contains(&root) || decisions.locations.iter().any(|p| root.starts_with(p))))
|
||||
}
|
||||
|
||||
pub fn decide(&self, path: &Path, trusted: bool, folder: bool) -> IdeResult<()> {
|
||||
let root = match dunce::canonicalize(path) {
|
||||
Ok(root) => root,
|
||||
Err(_) if !trusted && path.is_absolute() => path.to_path_buf(),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let mut state = self.state.lock();
|
||||
let mut next = state.clone()?;
|
||||
next.projects.retain(|p| p != &root);
|
||||
next.restricted.retain(|p| p != &root);
|
||||
if trusted {
|
||||
next.projects.push(root.clone());
|
||||
if folder && let Some(parent) = root.parent() {
|
||||
let parent = parent.to_path_buf();
|
||||
if !next.locations.contains(&parent) {
|
||||
next.locations.push(parent);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
next.restricted.push(root);
|
||||
}
|
||||
persist(&self.file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_location(&self, path: &Path) -> IdeResult<()> {
|
||||
let mut state = self.state.lock();
|
||||
let mut next = state.clone()?;
|
||||
next.locations.retain(|p| p != path);
|
||||
persist(&self.file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(file: &Path, state: &TrustDecisions) -> IdeResult<()> {
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let bytes = serde_json::to_vec_pretty(state).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
ide_vfs::write_atomic(file, &bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl crate::Host {
|
||||
pub async fn set_project_trust(&self, path: &Path, trusted: bool, folder: bool) -> IdeResult<()> {
|
||||
self.trust.decide(path, trusted, folder)?;
|
||||
self.refresh_project_trust().await
|
||||
}
|
||||
|
||||
pub async fn refresh_project_trust(&self) -> IdeResult<()> {
|
||||
for project in self.projects().into_iter().filter(|p| !p.light) {
|
||||
let trusted = self.trust.trusted(&project.root).unwrap_or(false);
|
||||
let previous = project.trusted.swap(trusted, std::sync::atomic::Ordering::AcqRel);
|
||||
if previous == trusted {
|
||||
continue;
|
||||
}
|
||||
if !trusted {
|
||||
project.lsp.set_execution_allowed(false);
|
||||
}
|
||||
project.repos();
|
||||
if trusted {
|
||||
if let Some(cmd) = self.environment.project_opened(&project.root, &project.sink) {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
project.agents.shutdown();
|
||||
self.processes.kill_project(&project.root);
|
||||
project.notebooks.restrict().await;
|
||||
let windows: Vec<_> = self
|
||||
.projects
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(_, current)| std::sync::Arc::ptr_eq(current, &project))
|
||||
.map(|(window, _)| window.clone())
|
||||
.collect();
|
||||
for window in windows {
|
||||
let requests = self.project_requests.write().remove(&window).unwrap_or_default();
|
||||
for request in requests {
|
||||
self.cancel_request(request);
|
||||
}
|
||||
for session in self.debugger.sessions(Some(&window)) {
|
||||
let _ = self.debugger.stop(session.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
project.lsp.reconfigure().await;
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectTrustChanged { root: project.root.clone().into(), trusted });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands which only inspect/edit source or operate user-owned application state.
|
||||
/// New execution commands are denied until deliberately classified here.
|
||||
pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
if [
|
||||
"fs_",
|
||||
"doc_",
|
||||
"syntax_",
|
||||
"search_",
|
||||
"nav_",
|
||||
"history_",
|
||||
"spell_",
|
||||
"analysis_",
|
||||
"structural_",
|
||||
"refactor_",
|
||||
"bytes_",
|
||||
"window_",
|
||||
"window_group_",
|
||||
"term_",
|
||||
"settings_",
|
||||
"project_trust_",
|
||||
"ssh_",
|
||||
"git_credential",
|
||||
]
|
||||
.iter()
|
||||
.any(|p| cmd.starts_with(p))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
cmd,
|
||||
"app_info"
|
||||
| "app_metrics"
|
||||
| "app_quit"
|
||||
| "app_cancel_quit"
|
||||
| "app_restart"
|
||||
| "languages"
|
||||
| "menu_refresh"
|
||||
| "menu_model"
|
||||
| "menu_configure"
|
||||
| "menu_set_disabled"
|
||||
| "lsp_servers"
|
||||
| "lsp_resend_diagnostics"
|
||||
| "recent_projects"
|
||||
| "remove_recent_project"
|
||||
| "open_project"
|
||||
| "close_project"
|
||||
| "project_current"
|
||||
| "project_roots"
|
||||
| "index_status"
|
||||
| "jvm_file_presentations"
|
||||
| "deploy_coverage"
|
||||
| "find_files"
|
||||
| "find_symbols"
|
||||
| "mark_recent"
|
||||
| "remove_recent"
|
||||
| "recent_files"
|
||||
| "web_goto"
|
||||
| "path_completions"
|
||||
| "web_unresolved_references"
|
||||
| "project_rename"
|
||||
| "light_edit_open"
|
||||
| "workspace_create"
|
||||
| "workspace_update"
|
||||
| "workspace_attach"
|
||||
| "cancel_request"
|
||||
| "cancel_task"
|
||||
| "log_frontend"
|
||||
| "env_reload"
|
||||
| "remote_invoke"
|
||||
| "remote_current"
|
||||
| "remote_disconnect"
|
||||
| "remote_connect"
|
||||
| "remote_list"
|
||||
| "remote_open"
|
||||
| "remote_of"
|
||||
| "web_browsers"
|
||||
| "web_url"
|
||||
| "web_open"
|
||||
| "debug_attachable_processes"
|
||||
| "agent_subscribe"
|
||||
| "agent_entries"
|
||||
| "agent_commands"
|
||||
| "agent_unqueue"
|
||||
| "agent_cancel"
|
||||
| "agent_archive"
|
||||
| "agent_unarchive"
|
||||
| "agent_registry_list"
|
||||
| "agent_registry_install"
|
||||
| "agent_registry_remove"
|
||||
| "coverage_import"
|
||||
| "system_font_families"
|
||||
| "plugin_subscribe"
|
||||
| "plugin_list"
|
||||
| "plugin_set_active_file"
|
||||
| "plugin_set_theme"
|
||||
| "plugin_set_theme_frame"
|
||||
| "plugin_catalog"
|
||||
| "notebook_open"
|
||||
| "notebook_get"
|
||||
| "notebook_edit"
|
||||
| "notebook_save"
|
||||
| "notebook_undo"
|
||||
| "notebook_redo"
|
||||
| "notebook_reload"
|
||||
| "notebook_close"
|
||||
| "notebook_interrupt"
|
||||
| "run_stop"
|
||||
| "run_list"
|
||||
| "debug_stop"
|
||||
| "debug_sessions"
|
||||
| "vcs_clone"
|
||||
| "vcs_init"
|
||||
| "vcs_status"
|
||||
| "vcs_roots"
|
||||
| "vcs_branch_info"
|
||||
| "vcs_line_hunks"
|
||||
| "vcs_file_at"
|
||||
| "vcs_blame"
|
||||
| "vcs_log"
|
||||
| "vcs_commit_files"
|
||||
| "vcs_commits_changes"
|
||||
| "vcs_branches"
|
||||
| "vcs_stashes"
|
||||
| "vcs_conflict_versions"
|
||||
| "vcs_diff_text"
|
||||
| "vcs_diff_hunks"
|
||||
| "vcs_detected_git"
|
||||
| "vcs_config_get"
|
||||
| "vcs_tags"
|
||||
| "vcs_remotes"
|
||||
| "vcs_worktrees"
|
||||
| "vcs_diff_with_worktree"
|
||||
| "vcs_compare_scope"
|
||||
| "vcs_compare_paths"
|
||||
| "vcs_diff_revisions"
|
||||
| "vcs_merge_base"
|
||||
| "vcs_shelves"
|
||||
| "vcs_shelf_patch"
|
||||
| "vcs_changelists_load"
|
||||
) || cmd.starts_with("plugin:")
|
||||
}
|
||||
|
||||
impl crate::Host {
|
||||
pub fn authorize_command(&self, window: &str, command: &str) -> IdeResult<()> {
|
||||
if restricted_command_allowed(command) {
|
||||
return Ok(());
|
||||
}
|
||||
self.project(window)?.require_trust()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TrustStatus {
|
||||
pub root: ide_core::IpcPath,
|
||||
pub trusted: bool,
|
||||
pub decided: bool,
|
||||
}
|
||||
impl TrustStore {
|
||||
pub fn status(&self, path: &Path) -> IdeResult<TrustStatus> {
|
||||
let root = dunce::canonicalize(path)?;
|
||||
let trusted = self.trusted(&root)?;
|
||||
let state = self.decisions()?;
|
||||
Ok(TrustStatus { decided: trusted || state.restricted.contains(&root), root: root.into(), trusted })
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
let original = "hello=\\u4f60\\u597d\\uD83D\\uDE00target\nsecond=unchanged\nescaped=line\\u000Alogical\n";
|
||||
std::fs::write(&path, original).unwrap();
|
||||
let host = host(&base);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if !project.repos().is_empty() {
|
||||
|
||||
@@ -100,6 +100,7 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
"postStartCommand": ["/bin/sh", "-c", "echo \"$FROM_PROJECT\" >> started.txt; echo post-start-output"],
|
||||
}"#,
|
||||
);
|
||||
host.trust.decide(&project, true, false).unwrap();
|
||||
runtime.block_on(ide_host::ops::project::open(&host, "main", &project)).unwrap();
|
||||
assert_eq!(child_var("FROM_PROJECT"), "two-demo");
|
||||
assert!(child_var("PATH").starts_with("/project/bin:"), "{}", child_var("PATH"));
|
||||
@@ -158,6 +159,7 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
// Reopening the project doesn't run postStartCommand again (once per server start).
|
||||
host.close_project("main");
|
||||
assert_eq!(child_var("FROM_PROJECT"), "", "remoteEnv leaves with the project");
|
||||
host.trust.decide(&project, true, false).unwrap();
|
||||
runtime.block_on(ide_host::ops::project::open(&host, "main", &project)).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
assert_eq!(std::fs::read_to_string(&started).unwrap(), "two-demo\n");
|
||||
@@ -165,6 +167,7 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
// A failing postStartCommand is a notification; the project opens regardless.
|
||||
let failing = tmp.join("failing");
|
||||
write(&failing.join(".devcontainer.json"), r#"{ "postStartCommand": "echo oops >&2; exit 7" }"#);
|
||||
host.trust.decide(&failing, true, false).unwrap();
|
||||
runtime.block_on(ide_host::ops::project::open(&host, "main", &failing)).unwrap();
|
||||
wait_for("the failure notification", || {
|
||||
events.0.lock().iter().any(|e| {
|
||||
@@ -176,6 +179,7 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
// A broken file is a warning, not an error.
|
||||
let broken = tmp.join("broken");
|
||||
write(&broken.join(".devcontainer.json"), "{ \"remoteEnv\": ");
|
||||
host.trust.decide(&broken, true, false).unwrap();
|
||||
runtime.block_on(ide_host::ops::project::open(&host, "main", &broken)).unwrap();
|
||||
assert!(events.0.lock().iter().any(|e| matches!(e,
|
||||
IdeEvent::Notify { level: NotifyLevel::Warning, title, .. } if title == "devcontainer.json was not applied")));
|
||||
|
||||
@@ -70,11 +70,24 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let client = Arc::new(Client::default());
|
||||
let peer = Peer::connect(cr, cw, client.clone());
|
||||
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": 1 }), None).await.unwrap();
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
|
||||
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
|
||||
|
||||
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
invoke(&peer, "index_status", json!({})).await.unwrap();
|
||||
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
|
||||
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
|
||||
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
|
||||
assert!(files.is_array());
|
||||
for command in ["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start"] {
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
assert!(peer.request::<_, Value>("invoke", call, None).await.is_err());
|
||||
invoke(&peer, "project_trust_set", json!({"path": project, "trusted": true, "folder": false})).await.unwrap();
|
||||
let current = invoke(&peer, "project_current", json!({})).await.unwrap();
|
||||
assert_eq!(current["name"], "demo");
|
||||
|
||||
@@ -112,6 +125,14 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
invoke(&peer, "doc_save", json!({ "doc": id })).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "print('needle')\nprint('more')\n");
|
||||
|
||||
let outside = tmp.path().join("outside.txt");
|
||||
std::fs::write(&outside, "original\n").unwrap();
|
||||
let external = invoke(&peer, "doc_open", json!({ "path": outside })).await.unwrap();
|
||||
std::fs::write(&outside, "external change\n").unwrap();
|
||||
invoke(&peer, "doc_sync_from_disk", json!({})).await.unwrap();
|
||||
let snapshot = invoke(&peer, "doc_snapshot", json!({ "doc": external["id"] })).await.unwrap();
|
||||
assert_eq!(snapshot["text"], "external change\n");
|
||||
|
||||
// Commands shared with the desktop shell (camelCase argument names, as Tauri takes them).
|
||||
invoke(&peer, "doc_set_line_ending", json!({ "doc": id, "lineEnding": "crLf" })).await.unwrap();
|
||||
invoke(&peer, "doc_save", json!({ "doc": id })).await.unwrap();
|
||||
@@ -239,6 +260,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
tokio::spawn(rpc::serve(host, dispatcher, slot, sr, sw));
|
||||
let (cr, cw) = tokio::io::split(client_io);
|
||||
let peer = Peer::connect(cr, cw, Arc::new(Client::default()));
|
||||
invoke(&peer, "project_trust_set", json!({"path": project, "trusted": true, "folder": false})).await.unwrap();
|
||||
invoke(&peer, "open_project", json!({"path": project})).await.unwrap();
|
||||
let deployment = json!({"servers": [{"id":"local", "kind":"local", "rootPath":target}], "defaultServer":"local"});
|
||||
invoke(&peer, "settings_set", json!({"scope":"project", "key":"deployment", "value":deployment.to_string()}))
|
||||
|
||||
@@ -21,6 +21,7 @@ async fn removed_detections_stay_removed_and_overrides_restore() {
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{"scripts":{"dev":"node app.js","test":"node test.js"}}"#).unwrap();
|
||||
let host = host(&root.join("app"));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let detected = ops::run::configs(&host, "main").unwrap();
|
||||
assert!(detected.len() >= 2);
|
||||
@@ -58,6 +59,7 @@ async fn gradle_defaults_are_not_saved_as_explicit_run_choices() {
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
let host = host(&root.join("app"));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
ops::project::set_settings(
|
||||
&host,
|
||||
@@ -88,6 +90,8 @@ async fn workspace_cmake_before_launch_tasks_resolve_in_the_member() {
|
||||
let workspace = root.join("workspace");
|
||||
ide_workspace::workspace::Workspace::save(&workspace, "Native", vec![member.clone()], true).unwrap();
|
||||
let host = host(&root.join("app"));
|
||||
host.trust.decide(&workspace, true, false).unwrap();
|
||||
host.trust.decide(&member, true, false).unwrap();
|
||||
host.open_project("main", &workspace).unwrap();
|
||||
let configs = ops::run::configs(&host, "main").unwrap();
|
||||
let build = configs.iter().find(|c| c.kind == "cmake" && c.args.first().is_some_and(|a| a == "--build")).unwrap();
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
use ide_core::NullSink;
|
||||
#[cfg(unix)]
|
||||
use ide_host::ops;
|
||||
use ide_host::{Host, HostConfig, trust::TrustStore};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
#[cfg(unix)]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn host(base: &Path, environment: bool) -> Arc<Host> {
|
||||
Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: environment,
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persists_user_decisions_locations_revocation_and_one_time_migration() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = tmp.path().join("config");
|
||||
let data = tmp.path().join("data");
|
||||
let a = tmp.path().join("projects/a");
|
||||
let b = tmp.path().join("projects/b");
|
||||
std::fs::create_dir_all(a.join(".openidea")).unwrap();
|
||||
std::fs::create_dir_all(b.join(".openidea")).unwrap();
|
||||
std::fs::write(a.join(".openidea/project-trust.json"), r#"{"trusted":true}"#).unwrap();
|
||||
std::fs::write(b.join(".openidea/project-trust.json"), r#"{"trusted":true}"#).unwrap();
|
||||
let recent = ide_workspace::RecentProjects::load(&config);
|
||||
recent.touch(&a, None).unwrap();
|
||||
let trust = TrustStore::load(&config, &data);
|
||||
assert!(trust.trusted(&a).unwrap());
|
||||
assert!(!trust.status(&b).unwrap().decided);
|
||||
recent.touch(&b, None).unwrap();
|
||||
let trust = TrustStore::load(&config, &data);
|
||||
assert!(!trust.trusted(&b).unwrap(), "migration is not repeated");
|
||||
trust.decide(&a, true, true).unwrap();
|
||||
assert!(trust.trusted(&b).unwrap());
|
||||
trust.decide(&b, false, false).unwrap();
|
||||
assert!(!trust.trusted(&b).unwrap(), "revocation overrides a trusted location");
|
||||
let trust = TrustStore::load(&config, &data);
|
||||
assert!(!trust.trusted(&b).unwrap());
|
||||
trust.remove_location(&dunce::canonicalize(a.parent().unwrap()).unwrap()).unwrap();
|
||||
assert!(trust.trusted(&a).unwrap());
|
||||
trust.decide(&a, false, false).unwrap();
|
||||
assert!(!TrustStore::load(&config, &data).trusted(&a).unwrap());
|
||||
std::fs::write(data.join("project-trust.json"), "broken").unwrap();
|
||||
assert!(TrustStore::load(&config, &data).trusted(&a).is_err(), "corruption fails closed");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn script(root: &Path, name: &str, marker: &str) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = root.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\nprintf executed > '{marker}'\n")).unwrap();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn malicious_project_stays_editable_then_starts_in_place_after_trust() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("malicious");
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
script(&root, "hook", "hook.marker");
|
||||
script(&root, "server", "lsp.marker");
|
||||
script(&root, "gradlew", "build.marker");
|
||||
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
std::fs::write(root.join("main.py"), "print('safe')\n").unwrap();
|
||||
std::fs::write(root.join(".devcontainer.json"), r#"{"postStartCommand":["./hook"]}"#).unwrap();
|
||||
std::fs::write(root.join(".openidea/settings.toml"), format!(
|
||||
"[languageServers.trust-witness]\nlanguages = ['python']\ncommand = {:?}\n[languageServers.pyright]\nenabled = false\n", root.join("server").to_str().unwrap()
|
||||
)).unwrap();
|
||||
let host = host(&tmp.path().join("app"), true);
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
assert!(!project.is_trusted());
|
||||
let doc = ops::doc::open(&host, "main", root.join("main.py")).await.unwrap();
|
||||
ops::doc::save(&host, "main", doc.id).await.unwrap();
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(project.index.status().files > 0);
|
||||
let sync = || {
|
||||
ops::build::build_sync(
|
||||
&host,
|
||||
"main",
|
||||
ide_build::BuildTool::Gradle,
|
||||
ide_core::RequestId(472),
|
||||
false,
|
||||
vec![],
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
};
|
||||
assert!(sync().await.is_err(), "restricted build marker: {}", root.join("build.marker").exists());
|
||||
assert!(
|
||||
ops::sdk::sdk_locate_tools(&host, "missing-window", vec!["server".into()], Some(root.clone())).await.is_err()
|
||||
);
|
||||
for command in [
|
||||
"run_start",
|
||||
"debug_start",
|
||||
"notebook_execute",
|
||||
"coverage_collect",
|
||||
"profiler_collect",
|
||||
"docker_compose_op",
|
||||
"agent_prompt",
|
||||
"sdk_detect",
|
||||
"build_sync",
|
||||
] {
|
||||
assert!(host.authorize_command("main", command).is_err(), "{command}");
|
||||
assert!(host.authorize_command("missing-window", command).is_err(), "{command}");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
for marker in ["hook.marker", "lsp.marker", "build.marker"] {
|
||||
assert!(!root.join(marker).exists(), "{marker}");
|
||||
}
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
assert!(Arc::ptr_eq(&project, &host.project("main").unwrap()));
|
||||
assert_eq!(project.documents.snapshot(doc.id).unwrap().text, doc.text);
|
||||
sync().await.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !root.join("hook.marker").exists() || !root.join("lsp.marker").exists() {
|
||||
assert!(Instant::now() < deadline, "trusted services must start");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(root.join("build.marker").exists());
|
||||
host.set_project_trust(&root, false, false).await.unwrap();
|
||||
assert!(!project.is_trusted());
|
||||
assert!(sync().await.is_err());
|
||||
ops::doc::save(&host, "main", doc.id).await.unwrap();
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn restricted_terminal_keeps_user_input_but_ignores_project_startup_commands() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let host = host(&tmp.path().join("app"), false);
|
||||
host.global_settings
|
||||
.set(
|
||||
ide_workspace::SettingsScope::Global,
|
||||
"terminal.env",
|
||||
serde_json::json!({"ZDOTDIR": root, "ENV": "/dev/null", "BASH_ENV": "/dev/null"}),
|
||||
)
|
||||
.unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let terminal = ops::term::spawn(
|
||||
&host,
|
||||
"main",
|
||||
ide_terminal::TerminalOptions {
|
||||
cwd: root.clone().into(),
|
||||
shell: Some("/bin/sh".into()),
|
||||
args: vec!["-c".into(), "touch automatic.marker".into()],
|
||||
env: Default::default(),
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
shell_integration: false,
|
||||
},
|
||||
Arc::new(|_| {}),
|
||||
)
|
||||
.unwrap();
|
||||
host.terminals.write(terminal.id, "printf user > terminal.marker; exit\n").unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !root.join("terminal.marker").exists() {
|
||||
assert!(Instant::now() < deadline, "user terminal input must run");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(!root.join("automatic.marker").exists());
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn trusted_locations_use_canonical_directory_boundaries() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("trusted/project");
|
||||
let other = tmp.path().join("trusted-other/project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::os::unix::fs::symlink(other.parent().unwrap(), root.parent().unwrap().join("escape")).unwrap();
|
||||
let trust = TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
|
||||
trust.decide(&root, true, true).unwrap();
|
||||
assert!(!trust.trusted(&other).unwrap());
|
||||
let alias = root.parent().unwrap().join("escape/project");
|
||||
assert!(!trust.trusted(&alias).unwrap());
|
||||
assert_eq!(trust.status(&alias).unwrap().root.as_ref(), dunce::canonicalize(&other).unwrap());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn restricted_git_views_ignore_project_executables_and_mutations_cannot_run_hooks() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
let git = |args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(&root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&["init", "-q"]);
|
||||
git(&["config", "user.name", "Test"]);
|
||||
git(&["config", "user.email", "[email protected]"]);
|
||||
git(&["config", "commit.gpgsign", "false"]);
|
||||
git(&["config", "core.hooksPath", ".git/hooks"]);
|
||||
let file = root.join("safe.txt");
|
||||
std::fs::write(&file, "safe\n").unwrap();
|
||||
script(&root, ".git/hooks/pre-commit", "git-hook.marker");
|
||||
let executable = root.join(".openidea/git-witness");
|
||||
std::fs::write(&executable, "#!/bin/sh\nprintf executed > git-executable.marker\nexec git \"$@\"\n").unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(
|
||||
root.join(".openidea/settings.toml"),
|
||||
format!("[vcs.git]\nexecutable = {:?}\n", executable.to_str().unwrap()),
|
||||
)
|
||||
.unwrap();
|
||||
let host = host(&tmp.path().join("app"), false);
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
assert!(!project.with_repo(|repo| repo.status()).unwrap().is_empty());
|
||||
assert!(ops::vcs::vcs_stage(&host, "main", vec![file.clone()]).await.is_err());
|
||||
assert!(!root.join("git-hook.marker").exists());
|
||||
assert!(!root.join("git-executable.marker").exists());
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
ops::vcs::vcs_stage(&host, "main", vec![file]).await.unwrap();
|
||||
project.with_repo(|repo| repo.commit("trusted", false, false)).unwrap();
|
||||
assert!(root.join("git-executable.marker").exists());
|
||||
assert!(root.join("git-hook.marker").exists());
|
||||
ide_vcs::set_git_executable(None);
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn revocation_still_applies_when_a_project_folder_was_removed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let host = host(&tmp.path().join("app"), false);
|
||||
host.trust.decide(&root, true, true).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
host.set_project_trust(&project.root, false, false).await.unwrap();
|
||||
assert!(!project.is_trusted());
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The configured Git binary is process-wide, so it has its own test binary.
|
||||
#![cfg(unix)]
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn restricted_status_does_not_select_the_project_git_for_other_windows() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
let root = base.join("malicious");
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
let marker = base.join("git.marker");
|
||||
let git = root.join("git");
|
||||
std::fs::write(&git, format!("#!/bin/sh\nprintf executed > '{}'\n", marker.display())).unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::write(root.join(".openidea/settings.toml"), format!("[vcs.git]\nexecutable = {:?}\n", git)).unwrap();
|
||||
ide_vcs::init(&root).unwrap();
|
||||
|
||||
host.open_project("main", &root).unwrap();
|
||||
ops::vcs::status(&host, "main").await.unwrap();
|
||||
|
||||
let _ = ide_vcs::git_version(None);
|
||||
assert!(!marker.exists(), "another window's next Git command would run the project's binary");
|
||||
}
|
||||
@@ -35,6 +35,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if !project.repos().is_empty() {
|
||||
|
||||
@@ -38,6 +38,7 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
|
||||
@@ -30,6 +30,7 @@ async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_di
|
||||
project_environment: false,
|
||||
});
|
||||
std::fs::write(root.join("internal-needle.txt"), "needle").unwrap();
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
assert_eq!(ops::project::info(&project).name, "Full stack");
|
||||
assert_eq!(ops::project::attach_workspace(&host, "main", &roots[1]).unwrap().as_ref(), root.as_path());
|
||||
|
||||
@@ -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)))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -174,6 +174,7 @@ pub struct LspManager {
|
||||
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
|
||||
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
shown_messages: Mutex<HashSet<(String, String)>>,
|
||||
/// Virtual (non-`file:`) URIs a server returned, by the server that owns them.
|
||||
@@ -305,6 +306,7 @@ impl LspManager {
|
||||
candidates_hook: RwLock::new(None),
|
||||
excludes_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
virtual_origins: Mutex::new(HashMap::new()),
|
||||
virtual_docs: Mutex::new(HashMap::new()),
|
||||
@@ -372,6 +374,9 @@ impl LspManager {
|
||||
|
||||
/// The definitions of the servers `language` uses.
|
||||
fn language_servers(&self, language: &LanguageId) -> Vec<LanguageServerConfig> {
|
||||
if !self.execution_allowed.load(Ordering::Acquire) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(cfg) = self.languages.get(language) else { return Vec::new() };
|
||||
match self.servers_hook.read().clone() {
|
||||
Some(hook) => hook(language, &cfg.language_servers),
|
||||
@@ -418,7 +423,7 @@ impl LspManager {
|
||||
}
|
||||
|
||||
fn ensure_started(&self, server: &Arc<Server>) {
|
||||
if self.shutting_down.load(Ordering::Acquire) {
|
||||
if self.shutting_down.load(Ordering::Acquire) || !self.execution_allowed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let Some(generation) = server.begin_start() else { return };
|
||||
@@ -436,7 +441,13 @@ impl LspManager {
|
||||
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
|
||||
// servers may take a while to start listening.
|
||||
let launched = tokio::task::spawn_blocking(move || {
|
||||
if !me.execution_allowed.load(Ordering::Acquire) {
|
||||
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
|
||||
}
|
||||
let mut cfg = me.configured(&tail);
|
||||
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
|
||||
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
|
||||
}
|
||||
tail.set_effective_config(cfg.clone());
|
||||
let prepare = me.prepare_hook.read().clone();
|
||||
if !cancel.is_cancelled()
|
||||
@@ -453,6 +464,9 @@ impl LspManager {
|
||||
let missing = !me.launcher.available(&cfg, &root);
|
||||
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
|
||||
}
|
||||
if !me.execution_allowed.load(Ordering::Acquire) || cancel.is_cancelled() {
|
||||
return Err(LaunchError::Config("Project is in Restricted Mode".into()));
|
||||
}
|
||||
me.launcher.launch_cancellable(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
|
||||
})
|
||||
.await
|
||||
@@ -2008,6 +2022,10 @@ impl LspManager {
|
||||
/// The server's base configuration with the settings hook applied.
|
||||
fn configured(&self, server: &Server) -> LanguageServerConfig {
|
||||
let mut cfg = server.config.clone();
|
||||
if !self.execution_allowed.load(Ordering::Acquire) {
|
||||
cfg.launch_error = Some("Project is in Restricted Mode".into());
|
||||
return cfg;
|
||||
}
|
||||
if let Some(hook) = self.config_hook.read().clone() {
|
||||
hook(&mut cfg, &server.root);
|
||||
}
|
||||
@@ -2018,7 +2036,27 @@ impl LspManager {
|
||||
/// (e.g. a new project interpreter); stopped ones pick it up on their next start.
|
||||
/// A change of `settings` alone reaches a running server without a restart.
|
||||
/// Servers no longer enabled stop; newly enabled ones attach to open documents.
|
||||
pub fn set_execution_allowed(&self, allowed: bool) {
|
||||
let previous = self.execution_allowed.swap(allowed, Ordering::AcqRel);
|
||||
if !allowed {
|
||||
for server in self.servers.lock().iter() {
|
||||
server.start_token().cancel();
|
||||
}
|
||||
}
|
||||
if allowed && !previous {
|
||||
for server in self.servers.lock().iter() {
|
||||
server.reset_for_restart();
|
||||
self.ensure_started(server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reconfigure(&self) {
|
||||
if !self.execution_allowed.load(Ordering::Acquire) {
|
||||
let servers = self.servers.lock().clone();
|
||||
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
|
||||
return;
|
||||
}
|
||||
self.stop_unlisted().await;
|
||||
let Some(me) = self.me.upgrade() else { return };
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
|
||||
@@ -92,7 +92,10 @@ impl LoadedPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
type ProjectPolicy = Arc<dyn Fn(&Path) -> bool + Send + Sync>;
|
||||
|
||||
pub struct PluginHost {
|
||||
project_policy: RwLock<ProjectPolicy>,
|
||||
engine: PluginEngine,
|
||||
plugins_dir: PathBuf,
|
||||
sink: Arc<dyn PluginEventSink>,
|
||||
@@ -116,6 +119,7 @@ impl PluginHost {
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
Ok(Self {
|
||||
project_policy: RwLock::new(Arc::new(|_| false)),
|
||||
engine: PluginEngine::new().map_err(IdeError::internal)?,
|
||||
plugins_dir,
|
||||
sink,
|
||||
@@ -159,7 +163,30 @@ impl PluginHost {
|
||||
}
|
||||
|
||||
/// Loads new dev plugins from `<root>/.openidea/plugins/` and unloads vanished ones.
|
||||
pub fn set_project_policy(&self, policy: ProjectPolicy) {
|
||||
*self.project_policy.write() = policy;
|
||||
}
|
||||
|
||||
pub fn restrict_project(&self, root: &Path) {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let ids: Vec<_> = self
|
||||
.plugins
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
for id in ids {
|
||||
self.unload(&id);
|
||||
}
|
||||
self.emit(None, PluginEvent::CommandsChanged);
|
||||
}
|
||||
|
||||
pub fn sync_project(&self, root: &Path) {
|
||||
if !(self.project_policy.read())(root) {
|
||||
self.restrict_project(root);
|
||||
return;
|
||||
}
|
||||
let _guard = self.lifecycle.lock();
|
||||
let dirs = package_dirs(&ide_core::project_dir::path(root, "plugins"));
|
||||
let stale: Vec<String> = self
|
||||
@@ -448,7 +475,12 @@ impl PluginHost {
|
||||
// ---- internals ----
|
||||
|
||||
fn get(&self, id: &str) -> IdeResult<Arc<LoadedPlugin>> {
|
||||
self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no plugin {id:?}")))
|
||||
let plugin =
|
||||
self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no plugin {id:?}")))?;
|
||||
if plugin.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root)) {
|
||||
return Err(IdeError::unavailable("Project is in Restricted Mode"));
|
||||
}
|
||||
Ok(plugin)
|
||||
}
|
||||
|
||||
fn is_loaded_from(&self, dir: &Path) -> bool {
|
||||
|
||||
@@ -380,6 +380,7 @@ fn state_persists_across_restarts() {
|
||||
#[test]
|
||||
fn dev_plugins_follow_the_project() {
|
||||
let f = fixture(Limits::default());
|
||||
f.host.set_project_policy(Arc::new(|_| true));
|
||||
let dev = f.project.join(DEV_PLUGINS_DIR).join("toy");
|
||||
copy_dir(&sample("language-toy"), &dev);
|
||||
f.host.sync_project(&f.project);
|
||||
@@ -474,3 +475,38 @@ fn catalog_lists_sample_packages() {
|
||||
let x = catalog.iter().find(|c| c.id == "x").unwrap();
|
||||
assert!(x.problem.as_deref().unwrap().contains("plugin.wasm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_dev_plugin_has_no_activation_registration() {
|
||||
let f = fixture(Limits::default());
|
||||
let dev = f.project.join(DEV_PLUGINS_DIR).join("hello");
|
||||
copy_dir(&sample("hello"), &dev);
|
||||
let manifest = dev.join("plugin.toml");
|
||||
let text = std::fs::read_to_string(&manifest).unwrap();
|
||||
std::fs::write(&manifest, text.split("[[contributes.commands]]").next().unwrap()).unwrap();
|
||||
assert!(PluginManifest::load(&dev).unwrap().contributes.commands.is_empty());
|
||||
let trusted = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let policy = trusted.clone();
|
||||
f.host.set_project_policy(Arc::new(move |_| policy.load(std::sync::atomic::Ordering::Acquire)));
|
||||
f.host.sync_project(&f.project);
|
||||
let untrusted = f.host.list(Some(&f.project));
|
||||
assert!(
|
||||
!untrusted.plugins.iter().flat_map(|plugin| &plugin.commands).any(|command| command.id == "word-count"),
|
||||
"untrusted development plugin registered its activation witness"
|
||||
);
|
||||
assert!(untrusted.plugins.is_empty());
|
||||
assert!(f.host.info_of("hello").is_err());
|
||||
|
||||
// Positive control: activation itself registers these commands, not the manifest.
|
||||
trusted.store(true, std::sync::atomic::Ordering::Release);
|
||||
f.host.sync_project(&f.project);
|
||||
let info = f.host.info_of("hello").unwrap();
|
||||
assert_eq!(info.status, PluginStatus::Active);
|
||||
assert!(info.commands.iter().any(|c| c.id == "word-count"));
|
||||
trusted.store(false, std::sync::atomic::Ordering::Release);
|
||||
assert!(f.host.reload("hello").is_err());
|
||||
assert!(f.host.set_enabled("hello", true).is_err());
|
||||
assert!(f.run("hello", "word-count", None).is_err());
|
||||
f.host.sync_project(&f.project);
|
||||
assert!(f.host.list(Some(&f.project)).plugins.is_empty());
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! configurations on run targets ([`target`]).
|
||||
|
||||
pub mod deploy;
|
||||
pub mod import;
|
||||
pub mod mapping;
|
||||
pub mod service;
|
||||
pub mod target;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -46,6 +46,7 @@ struct StopCommand {
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
project_root: PathBuf,
|
||||
id: RunId,
|
||||
config_id: String,
|
||||
name: String,
|
||||
@@ -337,7 +338,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("Go build and run requires the output console"));
|
||||
}
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
return self.start_pty(root, config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
}
|
||||
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
@@ -384,6 +385,7 @@ impl ProcessManager {
|
||||
_ => None,
|
||||
};
|
||||
let entry = Arc::new(Entry {
|
||||
project_root: root.to_path_buf(),
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
@@ -444,6 +446,7 @@ impl ProcessManager {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_pty(
|
||||
&self,
|
||||
root: &Path,
|
||||
config: &RunConfig,
|
||||
inv: &Invocation,
|
||||
cwd: &Path,
|
||||
@@ -493,6 +496,7 @@ impl ProcessManager {
|
||||
|
||||
let id = RunId::next();
|
||||
let entry = Arc::new(Entry {
|
||||
project_root: root.to_path_buf(),
|
||||
id,
|
||||
config_id: config.id.clone(),
|
||||
name: config.name.clone(),
|
||||
@@ -640,6 +644,16 @@ impl ProcessManager {
|
||||
}
|
||||
|
||||
/// Kills every running process tree at once (shutting down).
|
||||
pub fn kill_project(&self, root: &Path) {
|
||||
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
|
||||
if !entry.exited.load(Ordering::Acquire)
|
||||
&& let Some(pid) = *entry.pid.lock()
|
||||
{
|
||||
kill_tree(pid, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill_all(&self) {
|
||||
for entry in self.runs.lock().values() {
|
||||
entry.stopping.store(true, Ordering::Release);
|
||||
|
||||
@@ -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"\\?\"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -474,6 +474,26 @@ fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoking_one_project_stops_only_its_runs() {
|
||||
let h = harness();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
let (mine, _) = start(&h, &cfg("mine", "/bin/sh", &["-c", "sleep 30"]));
|
||||
let theirs =
|
||||
h.pm.start(
|
||||
other.path(),
|
||||
&cfg("theirs", "/bin/sh", &["-c", "sleep 30"]),
|
||||
&StartOptions::default(),
|
||||
h.sink.clone(),
|
||||
Box::new(|_| {}),
|
||||
)
|
||||
.unwrap();
|
||||
h.pm.kill_project(h.root.path());
|
||||
wait_exit(&h, mine, Duration::from_secs(5));
|
||||
assert!(h.pm.list().iter().any(|run| run.id == theirs.id && run.running));
|
||||
h.pm.stop(theirs.id).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires CMake, CTest and a C++ compiler"]
|
||||
fn cmake_configure_discovers_builds_and_runs_a_multifile_target() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -323,9 +323,9 @@ impl Tools {
|
||||
picked =
|
||||
adoptium_pick(&http.get_text(&adoptium_assets_url(feature, self.platform), cancel)?, self.platform)?;
|
||||
}
|
||||
if picked.is_none() && self.platform.os == Os::Mac && self.platform.arch == Arch::Arm64 {
|
||||
// Java 8 has no Apple Silicon build: the Intel one runs under Rosetta.
|
||||
let intel = Platform { os: Os::Mac, arch: Arch::X64 };
|
||||
if picked.is_none() && matches!(self.platform.os, Os::Mac | Os::Windows) && self.platform.arch == Arch::Arm64 {
|
||||
// Older JDKs may need the OS-provided x64 emulation.
|
||||
let intel = Platform { os: self.platform.os, arch: Arch::X64 };
|
||||
picked = adoptium_pick(&http.get_text(&adoptium_assets_url(feature, intel), cancel)?, intel)?;
|
||||
}
|
||||
let (dl, major) = picked.ok_or_else(|| {
|
||||
|
||||
@@ -61,8 +61,8 @@ pub const fn any_arch(os: Os, pattern: &'static str) -> AssetRule {
|
||||
}
|
||||
|
||||
/// Picks the asset for `platform`: rules are tried in order and the first
|
||||
/// rule matching any asset name wins. Apple Silicon falls back to x64 assets
|
||||
/// (Rosetta) when no native build exists.
|
||||
/// rule matching any asset name wins. ARM64 macOS and Windows fall back to x64 assets
|
||||
/// under OS emulation when no native build exists.
|
||||
pub fn select_asset<'a>(names: &[&'a str], rules: &[AssetRule], platform: Platform) -> Option<&'a str> {
|
||||
let pick = |arch: Arch| {
|
||||
rules
|
||||
@@ -70,8 +70,11 @@ pub fn select_asset<'a>(names: &[&'a str], rules: &[AssetRule], platform: Platfo
|
||||
.filter(|r| r.os == platform.os && r.arch.is_none_or(|a| a == arch))
|
||||
.find_map(|r| names.iter().copied().find(|n| glob_match(r.pattern, n)))
|
||||
};
|
||||
pick(platform.arch)
|
||||
.or_else(|| (platform.os == Os::Mac && platform.arch == Arch::Arm64).then(|| pick(Arch::X64)).flatten())
|
||||
pick(platform.arch).or_else(|| {
|
||||
(matches!(platform.os, Os::Mac | Os::Windows) && platform.arch == Arch::Arm64)
|
||||
.then(|| pick(Arch::X64))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Case-insensitive glob with `*` wildcards only.
|
||||
@@ -175,6 +178,36 @@ mod tests {
|
||||
assert_eq!(select_asset(&old, rules, LINUX_X64), Some("codelldb-x86_64-linux.vsix"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arm64_native_then_emulated_assets() {
|
||||
for os in [Os::Mac, Os::Windows, Os::Linux] {
|
||||
let rules = [rule(os, Arch::X64, "tool-x64"), rule(os, Arch::Arm64, "tool-arm64")];
|
||||
let platform = Platform { os, arch: Arch::Arm64 };
|
||||
assert_eq!(select_asset(&["tool-x64", "tool-arm64"], &rules, platform), Some("tool-arm64"));
|
||||
let fallback = if os == Os::Linux { None } else { Some("tool-x64") };
|
||||
assert_eq!(select_asset(&["tool-x64"], &rules, platform), fallback);
|
||||
assert_eq!(select_asset(&[], &rules, platform), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_windows_release_rules() {
|
||||
let platform = Platform { os: Os::Windows, arch: Arch::Arm64 };
|
||||
for (tool, asset) in [
|
||||
("zls", "zls-aarch64-windows.zip"),
|
||||
("terraform-ls", "terraform-ls_0.39.1_windows_arm64.zip"),
|
||||
("taplo", "taplo-windows-aarch64.zip"),
|
||||
("buf", "buf-Windows-arm64.zip"),
|
||||
("texlab", "texlab-aarch64-windows.zip"),
|
||||
("neocmakelsp", "neocmakelsp-aarch64-pc-windows-msvc.zip"),
|
||||
] {
|
||||
assert_eq!(
|
||||
select_asset(&[asset], crate::registry::find(tool).unwrap().asset_rules(), platform),
|
||||
Some(asset)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exe_suffix() {
|
||||
assert_eq!(WIN.exe("clangd"), "clangd.exe");
|
||||
|
||||
@@ -435,6 +435,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
rule(Linux, X64, "taplo-linux-x86_64.gz"),
|
||||
rule(Linux, Arm64, "taplo-linux-aarch64.gz"),
|
||||
rule(Windows, X64, "taplo-windows-x86_64.zip"),
|
||||
rule(Windows, Arm64, "taplo-windows-aarch64.zip"),
|
||||
],
|
||||
locate: &["taplo"],
|
||||
},
|
||||
@@ -456,6 +457,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
rule(Linux, X64, "zls-x86_64-linux.tar.xz"),
|
||||
rule(Linux, Arm64, "zls-aarch64-linux.tar.xz"),
|
||||
rule(Windows, X64, "zls-x86_64-windows.zip"),
|
||||
rule(Windows, Arm64, "zls-aarch64-windows.zip"),
|
||||
],
|
||||
locate: &["zls"],
|
||||
},
|
||||
@@ -477,6 +479,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
rule(Linux, X64, "terraform-ls_*_linux_amd64.zip"),
|
||||
rule(Linux, Arm64, "terraform-ls_*_linux_arm64.zip"),
|
||||
rule(Windows, X64, "terraform-ls_*_windows_amd64.zip"),
|
||||
rule(Windows, Arm64, "terraform-ls_*_windows_arm64.zip"),
|
||||
],
|
||||
locate: &["terraform-ls"],
|
||||
},
|
||||
|
||||
@@ -202,7 +202,25 @@ pub(crate) fn run_paths(root: &Path, args: &[&str], paths: &[String]) -> IdeResu
|
||||
|
||||
/// Builds a `git` command with the environment every invocation needs.
|
||||
pub(crate) fn command(root: &Path) -> IdeResult<Command> {
|
||||
let mut cmd = Command::new(git_binary()?);
|
||||
let restricted = !crate::execution_allowed();
|
||||
let binary = if restricted {
|
||||
detected_git().ok_or_else(|| IdeError::unavailable("git executable not found"))?.to_path_buf()
|
||||
} else {
|
||||
git_binary()?
|
||||
};
|
||||
let mut cmd = Command::new(binary);
|
||||
if restricted {
|
||||
for setting in [
|
||||
"core.fsmonitor=false",
|
||||
"core.hooksPath=",
|
||||
"diff.external=",
|
||||
"core.attributesFile=",
|
||||
"submodule.recurse=false",
|
||||
] {
|
||||
cmd.arg("-c").arg(setting);
|
||||
}
|
||||
cmd.env_remove("GIT_EXTERNAL_DIFF").env("GIT_NO_LAZY_FETCH", "1");
|
||||
}
|
||||
cmd.current_dir(root)
|
||||
.arg("-c")
|
||||
.arg("core.quotepath=off")
|
||||
@@ -330,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)?;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -484,8 +486,16 @@ pub use roots::Repos;
|
||||
pub fn clone(url: &str, dest: &Path, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let parent = dest.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let dest = if dest.is_absolute() { dest.to_path_buf() } else { std::env::current_dir()?.join(dest) };
|
||||
let dest = dest.to_string_lossy();
|
||||
cli::run_streaming(parent, &["clone", "--progress", "--", url, &dest], cancel, on_output)
|
||||
// Cloning must not inherit an enclosing project's executable Git settings.
|
||||
let cwd = tempfile::tempdir()?;
|
||||
cli::run_streaming(
|
||||
cwd.path(),
|
||||
&["-c", "core.hooksPath=", "clone", "--progress", "--", url, &dest],
|
||||
cancel,
|
||||
on_output,
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates an empty repository in `dir` (`git init`).
|
||||
@@ -502,6 +512,7 @@ pub fn diff_hunks(old_text: &str, new_text: &str) -> Vec<LineHunk> {
|
||||
/// An open git repository (worktree). Cheap to keep around; all reads re-check the
|
||||
/// on-disk state, so it never needs to be reopened after external changes.
|
||||
pub struct Repo {
|
||||
execution_allowed: std::sync::atomic::AtomicBool,
|
||||
root: PathBuf,
|
||||
git_dir: PathBuf,
|
||||
inner: std::sync::Mutex<repo::Cache>,
|
||||
@@ -515,27 +526,33 @@ impl Repo {
|
||||
}
|
||||
/// The worktree root.
|
||||
pub fn root(&self) -> &Path {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
&self.root
|
||||
}
|
||||
/// Untracked files with one of these names (or under such a folder) are not reported.
|
||||
pub fn set_ignored_names(&self, names: IgnoredNames) {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
*self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names;
|
||||
}
|
||||
/// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes,
|
||||
/// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind.
|
||||
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
status::status(self)
|
||||
}
|
||||
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
refs::branch_info(self)
|
||||
}
|
||||
/// Current branch (short name; `None` when detached) and HEAD commit, without
|
||||
/// upstream tracking (cheap enough to call for every repository on each refresh).
|
||||
pub fn head(&self) -> IdeResult<(Option<String>, Option<String>)> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
refs::head(&self.gix()?)
|
||||
}
|
||||
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
|
||||
pub fn operation(&self) -> IdeResult<Option<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
Ok(refs::operation(&self.gix()?))
|
||||
}
|
||||
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
|
||||
@@ -547,12 +564,14 @@ impl Repo {
|
||||
encoding: impl Into<TextEncoding>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let rel = self.rel_path(path)?;
|
||||
let repo = self.gix()?;
|
||||
Ok(repo::blob_at(&repo, &rel, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned()))
|
||||
}
|
||||
/// Raw revision bytes, for encoding detection when the working file is absent.
|
||||
pub fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
repo::blob_at(&self.gix()?, &self.rel_path(path)?, rev.unwrap_or("HEAD"))
|
||||
}
|
||||
/// Stage selected decoded hunks, retaining the index encoding, BOM and line endings.
|
||||
@@ -564,6 +583,7 @@ impl Repo {
|
||||
encoding: impl Into<TextEncoding>,
|
||||
) -> IdeResult<()> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stage_hunks(self, path, current, selected, encoding)
|
||||
}
|
||||
/// Hunks of `current_text` against HEAD (or the index when `against_index`).
|
||||
@@ -580,6 +600,7 @@ impl Repo {
|
||||
encoding: impl Into<TextEncoding>,
|
||||
) -> IdeResult<Vec<LineHunk>> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let Ok(rel) = self.rel_path(path) else { return Ok(Vec::new()) };
|
||||
if rel.is_empty() || rel == ".git" || rel.starts_with(".git/") {
|
||||
return Ok(Vec::new());
|
||||
@@ -609,6 +630,7 @@ impl Repo {
|
||||
encoding: impl Into<TextEncoding>,
|
||||
) -> IdeResult<Vec<BlameLine>> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::blame(self, path, current_text, revision, encoding)
|
||||
}
|
||||
/// Commits newest-first in topological order (children before parents).
|
||||
@@ -619,43 +641,52 @@ impl Repo {
|
||||
/// `skip`/`limit` paginate over the filtered result; `limit == 0` means no limit.
|
||||
/// `refs` decorations are `HEAD`, branch names (`main`, `origin/main`) and `tag: <name>`.
|
||||
pub fn log(&self, query: &LogQuery) -> IdeResult<Vec<Commit>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
history::log(self, query)
|
||||
}
|
||||
/// Files changed by `commit` relative to its first parent (renames detected).
|
||||
pub fn commit_files(&self, commit: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
history::commit_files(self, commit)
|
||||
}
|
||||
/// Combined changes of several commits (oldest first): per file, before the first commit
|
||||
/// that touched it ↔ after the last one (IDEA's multi-commit Git Log selection).
|
||||
pub fn commits_changes(&self, commits: &[String]) -> IdeResult<Vec<RevisionChange>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
history::commits_changes(self, commits)
|
||||
}
|
||||
/// Local and remote branches; the current branch first, then most recent first.
|
||||
pub fn branches(&self) -> IdeResult<Vec<Branch>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
refs::branches(self)
|
||||
}
|
||||
/// Stash entries, newest (`stash@{0}`) first.
|
||||
pub fn stashes(&self) -> IdeResult<Vec<Stash>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
refs::stashes(self)
|
||||
}
|
||||
/// Unified diff of a file: index↔worktree (`staged == false`, untracked files diff
|
||||
/// against /dev/null) or HEAD↔index (`staged == true`). Empty when unchanged.
|
||||
pub fn diff_text(&self, path: &Path, staged: bool, encoding: impl Into<TextEncoding>) -> IdeResult<String> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::diff_text(self, path, staged, encoding)
|
||||
}
|
||||
|
||||
/// `git config --get <key>` (all scopes); `None` when unset.
|
||||
pub fn config_get(&self, key: &str) -> IdeResult<Option<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let out = cli::run_raw(&self.root, &["config", "--get", key], None)?;
|
||||
Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string()))
|
||||
}
|
||||
|
||||
// ---- writes (git CLI) ----
|
||||
pub fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stage(self, paths)
|
||||
}
|
||||
pub fn unstage(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::unstage(self, paths)
|
||||
}
|
||||
/// Applies a unified-diff patch to the index (partial staging of hunks/lines).
|
||||
@@ -665,16 +696,19 @@ impl Repo {
|
||||
patch: &str,
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<E>,
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stage_patch(self, patch, &|path| encoding(path).map(Into::into))
|
||||
}
|
||||
/// Discards unstaged changes: tracked paths are restored from the index (staged
|
||||
/// changes are kept), untracked files and directories are deleted.
|
||||
pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::discard(self, paths)
|
||||
}
|
||||
/// Commits the index; returns the new HEAD commit id. An empty message with
|
||||
/// `amend` keeps the previous message.
|
||||
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
|
||||
write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8.into()))
|
||||
}
|
||||
@@ -685,12 +719,14 @@ impl Repo {
|
||||
options: &CommitOptions,
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<E>,
|
||||
) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::commit(self, message, options, &|path| encoding(path).map(Into::into))
|
||||
}
|
||||
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
|
||||
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
|
||||
/// detached.
|
||||
pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::checkout(self, branch, create)
|
||||
}
|
||||
/// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or
|
||||
@@ -698,62 +734,75 @@ impl Repo {
|
||||
/// is behind fast-forwards that branch, while one that is ahead is reported (or
|
||||
/// rebased / reset per `options.diverged`).
|
||||
pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult<CheckoutOutcome> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::checkout_with(self, branch, create, options)
|
||||
}
|
||||
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
|
||||
/// remote-tracking start point (`origin/x`) becomes the new branch's upstream.
|
||||
pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::create_branch(self, name, start, checkout)
|
||||
}
|
||||
/// Undo Commit: resets the current branch to the parent of `commit` (which must be
|
||||
/// HEAD and not a merge) keeping its changes staged; undoing the initial commit
|
||||
/// leaves an unborn branch. Returns the undone commit's message.
|
||||
pub fn undo_commit(&self, commit: &str) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::undo_commit(self, commit)
|
||||
}
|
||||
/// Deletes a local branch (`git branch -d`, `-D` when `force`).
|
||||
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::delete_branch(self, branch, force)
|
||||
}
|
||||
/// Deletes a local branch as IDEA does: without asking, force-deleting one that is not
|
||||
/// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`]
|
||||
/// needs to undo it.
|
||||
pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult<DeletedBranch> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::delete_branch_restorable(self, branch)
|
||||
}
|
||||
/// Recreates a deleted branch at its old tip, with its upstream.
|
||||
pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::restore_branch(self, deleted)
|
||||
}
|
||||
/// Renames a local branch (`git branch -m`); its upstream configuration moves with it.
|
||||
pub fn rename_branch(&self, from: &str, to: &str) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::rename_branch(self, from, to)
|
||||
}
|
||||
/// Merges `branch` into HEAD; local changes are stashed and restored around it. On
|
||||
/// conflicts an error is returned and the repository is left mid-merge
|
||||
/// (`branch_info().operation == Some("merge")`).
|
||||
pub fn merge(&self, branch: &str) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::merge(self, branch)
|
||||
}
|
||||
/// Rebases the current branch onto `onto`; local changes are stashed and restored.
|
||||
pub fn rebase(&self, onto: &str) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::rebase(self, onto)
|
||||
}
|
||||
/// `keep_index`: changes already staged stay in the index (and the working tree).
|
||||
pub fn stash_push(&self, message: Option<&str>, include_untracked: bool, keep_index: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stash_push(self, message, include_untracked, keep_index)
|
||||
}
|
||||
/// `reinstate_index`: also restore what was staged when the stash was made.
|
||||
pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stash_apply(self, index, pop, reinstate_index)
|
||||
}
|
||||
/// Creates and checks out `branch` at the commit the stash was made on, applies the
|
||||
/// stash there (index included) and drops it.
|
||||
pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stash_branch(self, index, branch)
|
||||
}
|
||||
/// Removes `stash@{index}` without applying it.
|
||||
pub fn stash_drop(&self, index: u32) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::stash_drop(self, index)
|
||||
}
|
||||
/// Deletes a branch on a remote (`git push <remote> --delete <branch>`); `branch` is the
|
||||
@@ -764,16 +813,19 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::delete_remote_branch(self, branch, cancel, on_output)
|
||||
}
|
||||
/// Network operations stream progress lines through `on_output`.
|
||||
/// Fetches all remotes (pruning deleted branches).
|
||||
pub fn fetch(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
cli::run_streaming(&self.root, &["fetch", "--progress", "--all", "--prune"], cancel, on_output)
|
||||
}
|
||||
/// Update Project: pulls the upstream by merge or rebase. Local changes are stashed
|
||||
/// and restored; the merge mode fast-forwards when possible whatever `pull.ff` says.
|
||||
pub fn pull(&self, rebase: bool, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let mode: &[&str] = if rebase { &["--rebase"] } else { &["--no-rebase", "--ff"] };
|
||||
let mut args = vec!["pull", "--progress", "--autostash"];
|
||||
args.extend_from_slice(mode);
|
||||
@@ -788,6 +840,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push(self, force_with_lease, set_upstream, None, cancel, on_output)
|
||||
}
|
||||
/// [`Repo::push`] that also pushes tags (Push dialog › Push tags).
|
||||
@@ -799,6 +852,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push(self, force_with_lease, set_upstream, tags, cancel, on_output)
|
||||
}
|
||||
/// Pushes a local branch, or its history up to `revision`, to its upstream (Git Log
|
||||
@@ -811,6 +865,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push_branch(
|
||||
self,
|
||||
branch,
|
||||
@@ -829,11 +884,13 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push_branch(self, branch, options, cancel, on_output)
|
||||
}
|
||||
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
|
||||
/// Update). Fails when the branch has diverged.
|
||||
pub fn update_branch(&self, branch: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::update_branch(self, branch, cancel, on_output)
|
||||
}
|
||||
// ---- in-progress operations, history rewriting, tags ----
|
||||
@@ -841,13 +898,16 @@ impl Repo {
|
||||
/// Continues the merge / rebase / cherry-pick / revert in progress; fails while
|
||||
/// conflicts are unresolved.
|
||||
pub fn continue_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::continue_op(self, cancel, on_output)
|
||||
}
|
||||
pub fn abort_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::abort_op(self, cancel, on_output)
|
||||
}
|
||||
/// Skips the current commit of a rebase / cherry-pick / revert.
|
||||
pub fn skip_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::skip_op(self, cancel, on_output)
|
||||
}
|
||||
/// Cherry-picks `commits` in order (oldest first). Stops mid-way on conflicts.
|
||||
@@ -857,10 +917,12 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::cherry_pick(self, commits, cancel, on_output)
|
||||
}
|
||||
/// Reverts `commits` in order (newest first) with git's default messages.
|
||||
pub fn revert(&self, commits: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::revert(self, commits, cancel, on_output)
|
||||
}
|
||||
/// Interactive rebase of `base..HEAD` (`None`: from the root) following `entries`,
|
||||
@@ -873,6 +935,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::interactive_rebase(self, base, entries, cancel, on_output)
|
||||
}
|
||||
/// Moves the current branch to `commit` (`git reset --<mode>`).
|
||||
@@ -883,26 +946,32 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::reset(self, commit, mode, cancel, on_output)
|
||||
}
|
||||
/// Creates tag `name` on `commit` (annotated when `message` is given).
|
||||
pub fn create_tag(&self, name: &str, commit: &str, message: Option<&str>, force: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::create_tag(self, name, commit, message, force)
|
||||
}
|
||||
pub fn tags(&self) -> IdeResult<Vec<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::tags(self)
|
||||
}
|
||||
/// Files that differ between revisions `from` and `to`.
|
||||
pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::diff_revisions(self, from, to)
|
||||
}
|
||||
/// Tracked files whose working-tree content differs from `rev`.
|
||||
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::diff_with_worktree(self, rev)
|
||||
}
|
||||
/// `(repo-relative path, added lines, deleted lines)` of the tracked files whose
|
||||
/// working-tree content differs from `rev`.
|
||||
pub fn numstat_with_worktree(&self, rev: &str) -> IdeResult<Vec<(String, u32, u32)>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::numstat_with_worktree(self, rev)
|
||||
}
|
||||
|
||||
@@ -910,37 +979,45 @@ impl Repo {
|
||||
|
||||
/// Patch of the local changes of `paths` against HEAD (untracked files included).
|
||||
pub fn create_patch(&self, paths: &[PathBuf], reverse: bool) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let rel = self.rel_paths(paths)?;
|
||||
Ok(patch::working_patch(self, &rel, reverse, true)?.0)
|
||||
}
|
||||
/// Patch of the changes made by `commits` (oldest first).
|
||||
pub fn create_commits_patch(&self, commits: &[String], reverse: bool) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
patch::commits_patch(self, commits, reverse)
|
||||
}
|
||||
pub fn patch_preview(&self, patch: &str) -> IdeResult<Vec<PatchFile>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
patch::preview(self, patch)
|
||||
}
|
||||
/// Applies a patch to the working tree, 3-way merging when it does not apply cleanly.
|
||||
pub fn apply_patch(&self, patch: &str) -> IdeResult<ApplyOutcome> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
patch::apply(self, patch)
|
||||
}
|
||||
/// Saves the changes of `paths` under `shelf_dir` and reverts them.
|
||||
pub fn shelve(&self, shelf_dir: &Path, name: &str, paths: &[PathBuf]) -> IdeResult<ShelvedChangeList> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let rel = self.rel_paths(paths)?;
|
||||
shelf::shelve(self, shelf_dir, name, &rel)
|
||||
}
|
||||
pub fn unshelve(&self, shelf_dir: &Path, id: &str, remove: bool) -> IdeResult<ApplyOutcome> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
shelf::unshelve(self, shelf_dir, id, remove)
|
||||
}
|
||||
|
||||
/// Who is on each side of the conflicts of the operation in progress.
|
||||
pub fn merge_sides(&self) -> IdeResult<MergeSides> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::merge_sides(self)
|
||||
}
|
||||
/// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
|
||||
/// dialog shows them (sides swapped during a rebase).
|
||||
pub fn merge_versions(&self, path: &Path, encoding: impl Into<TextEncoding>) -> IdeResult<MergeVersions> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let (base, ours, theirs) = self.conflict_versions(path, encoding)?;
|
||||
let sides = self.merge_sides()?;
|
||||
let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
|
||||
@@ -957,6 +1034,7 @@ impl Repo {
|
||||
encoding: impl Into<TextEncoding>,
|
||||
) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let rel = self.rel_path(path)?;
|
||||
let repo = self.gix()?;
|
||||
let stage = |n: u8| -> IdeResult<Option<String>> {
|
||||
@@ -965,3 +1043,25 @@ impl Repo {
|
||||
Ok((stage(1)?, stage(2)?, stage(3)?))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! { static EXECUTION_ALLOWED: std::cell::Cell<bool> = const { std::cell::Cell::new(true) }; }
|
||||
struct ExecutionScope(bool);
|
||||
impl ExecutionScope {
|
||||
fn enter(allowed: bool) -> Self {
|
||||
Self(EXECUTION_ALLOWED.with(|current| current.replace(current.get() && allowed)))
|
||||
}
|
||||
}
|
||||
impl Drop for ExecutionScope {
|
||||
fn drop(&mut self) {
|
||||
EXECUTION_ALLOWED.with(|current| current.set(self.0));
|
||||
}
|
||||
}
|
||||
pub(crate) fn execution_allowed() -> bool {
|
||||
EXECUTION_ALLOWED.with(|current| current.get())
|
||||
}
|
||||
impl Repo {
|
||||
pub fn set_execution_allowed(&self, allowed: bool) {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
self.execution_allowed.store(allowed, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
}
|
||||
@@ -210,6 +210,7 @@ pub(crate) fn parse_worktrees(text: &str) -> Vec<Worktree> {
|
||||
impl Repo {
|
||||
/// Merges `branches` into the current branch (Git › Merge…).
|
||||
pub fn merge_with(&self, branches: &[String], options: &MergeOptions) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = merge_args(branches, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
run(self.root(), &args, None).map(|_| ())
|
||||
@@ -217,6 +218,7 @@ impl Repo {
|
||||
|
||||
/// Rebases the current branch onto `upstream` (or `upstream..HEAD` onto `options.onto`).
|
||||
pub fn rebase_with(&self, upstream: &str, options: &RebaseOptions) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = rebase_args(upstream, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
run(self.root(), &args, None).map(|_| ())
|
||||
@@ -232,6 +234,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = pull_args(remote, branches, rebase, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
cli::run_streaming(self.root(), &args, cancel, on_output)
|
||||
@@ -239,6 +242,7 @@ impl Repo {
|
||||
|
||||
/// Manage Remotes: adds, removes or edits a remote.
|
||||
pub fn edit_remote(&self, edit: &RemoteEdit) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
match edit {
|
||||
RemoteEdit::Add { name, url } => {
|
||||
let (name, url) = (arg(name, "remote name")?, arg(url, "URL")?);
|
||||
@@ -262,6 +266,7 @@ impl Repo {
|
||||
|
||||
/// Working trees of the repository, the main one first.
|
||||
pub fn worktrees(&self) -> IdeResult<Vec<Worktree>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let out = run(self.root(), &["worktree", "list", "--porcelain"], None)?;
|
||||
Ok(parse_worktrees(&out.stdout_str()))
|
||||
}
|
||||
@@ -269,6 +274,7 @@ impl Repo {
|
||||
/// Git › New Worktree…: checks out `commitish` at `path`, on a new branch `new_branch`
|
||||
/// when given (otherwise `commitish` must be a branch not checked out elsewhere).
|
||||
pub fn add_worktree(&self, path: &Path, commitish: &str, new_branch: Option<&str>) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
let commitish = arg(commitish, "revision")?;
|
||||
let mut args: Vec<String> = vec!["worktree".into(), "add".into()];
|
||||
@@ -281,6 +287,7 @@ impl Repo {
|
||||
}
|
||||
|
||||
pub fn remove_worktree(&self, path: &Path, force: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
let mut args = vec!["worktree", "remove"];
|
||||
if force {
|
||||
|
||||
@@ -70,16 +70,9 @@ pub(crate) fn merge_sides(r: &Repo) -> IdeResult<MergeSides> {
|
||||
/// Three-way merge of file contents (`git merge-file --diff3`): changes that don't
|
||||
/// conflict are merged, each conflict is left as a diff3 block.
|
||||
pub(crate) fn merge_file(r: &Repo, ours: &str, base: &str, theirs: &str) -> IdeResult<String> {
|
||||
struct TempDir(std::path::PathBuf);
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
let dir = TempDir(r.git_dir.join(format!("openidea-merge-{}", std::process::id())));
|
||||
std::fs::create_dir_all(&dir.0)?;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let file = |name: &str, text: &str| -> IdeResult<String> {
|
||||
let path = dir.0.join(name);
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, text)?;
|
||||
Ok(path.to_string_lossy().into_owned())
|
||||
};
|
||||
@@ -345,6 +338,38 @@ pub(crate) fn tags(r: &Repo) -> IdeResult<Vec<String>> {
|
||||
/// Tracked files that differ between `rev` and the working tree (Compare with Local).
|
||||
pub(crate) fn diff_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
check_commits(&[rev.to_string()])?;
|
||||
if !crate::execution_allowed() {
|
||||
let out = run(
|
||||
r.root(),
|
||||
&["diff", "--cached", "--name-status", "-z", "--no-ext-diff", "--no-textconv", rev, "--"],
|
||||
None,
|
||||
)?;
|
||||
let mut paths: std::collections::BTreeSet<String> =
|
||||
parse_name_status(&out.stdout_str()).into_iter().map(|c| c.path).collect();
|
||||
paths.extend(r.status()?.into_iter().filter(|s| s.unstaged != Some(ChangeKind::Untracked)).map(|s| s.rel_path));
|
||||
let repo = r.gix()?;
|
||||
let mut changes = Vec::new();
|
||||
for path in paths {
|
||||
let old = crate::repo::blob_at(&repo, &path, rev)?;
|
||||
let new = match std::fs::read(r.abs_path(&path)) {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if old == new {
|
||||
continue;
|
||||
}
|
||||
let kind = if old.is_none() {
|
||||
ChangeKind::Added
|
||||
} else if new.is_none() {
|
||||
ChangeKind::Deleted
|
||||
} else {
|
||||
ChangeKind::Modified
|
||||
};
|
||||
changes.push(ChangedFile { path, kind, old_path: None });
|
||||
}
|
||||
return Ok(changes);
|
||||
}
|
||||
let out = run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", rev, "--"], None)?;
|
||||
Ok(parse_name_status(&out.stdout_str()))
|
||||
}
|
||||
@@ -372,7 +397,8 @@ pub(crate) fn parse_numstat(text: &str) -> Vec<(String, u32, u32)> {
|
||||
/// Files that differ between two revisions (Update Project's "N files updated").
|
||||
pub(crate) fn diff_revisions(r: &Repo, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
check_commits(&[from.to_string(), to.to_string()])?;
|
||||
let out = run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", from, to, "--"], None)?;
|
||||
let out =
|
||||
run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", "--no-textconv", from, to, "--"], None)?;
|
||||
Ok(parse_name_status(&out.stdout_str()))
|
||||
}
|
||||
|
||||
|
||||
@@ -40,12 +40,14 @@ pub(crate) fn parse_remotes(text: &str) -> Vec<Remote> {
|
||||
impl Repo {
|
||||
/// Configured remotes with their fetch URLs.
|
||||
pub fn remotes(&self) -> IdeResult<Vec<Remote>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let out = cli::run(self.root(), &["remote", "-v"], None)?;
|
||||
Ok(parse_remotes(&out.stdout_str()))
|
||||
}
|
||||
|
||||
/// Whether `rev` names a commit present in the object database.
|
||||
pub fn has_commit(&self, rev: &str) -> bool {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
check_rev(rev).is_ok()
|
||||
&& cli::run_raw(self.root(), &["cat-file", "-e", &format!("{rev}^{{commit}}")], None)
|
||||
.is_ok_and(|o| o.code == Some(0))
|
||||
@@ -60,6 +62,7 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
check_rev(remote)?;
|
||||
for r in refspecs {
|
||||
check_rev(r)?;
|
||||
@@ -71,6 +74,7 @@ impl Repo {
|
||||
|
||||
/// The best common ancestor of two revisions, if any.
|
||||
pub fn merge_base(&self, a: &str, b: &str) -> IdeResult<Option<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
check_rev(a)?;
|
||||
check_rev(b)?;
|
||||
let out = cli::run_raw(self.root(), &["merge-base", a, b], None)?;
|
||||
@@ -79,9 +83,14 @@ impl Repo {
|
||||
|
||||
/// Files changed between two revisions (renames detected).
|
||||
pub fn diff_files(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
check_rev(from)?;
|
||||
check_rev(to)?;
|
||||
let out = cli::run(self.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", from, to, "--"], None)?;
|
||||
let out = cli::run(
|
||||
self.root(),
|
||||
&["diff", "--name-status", "-z", "-M", "--no-ext-diff", "--no-textconv", from, to, "--"],
|
||||
None,
|
||||
)?;
|
||||
Ok(crate::ops::parse_name_status(&out.stdout_str()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,13 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
let common_dir = absolute(repo.common_dir())?;
|
||||
let files = config_files(&git_dir, &common_dir);
|
||||
let cache = Cache { config_stamp: stamp(&files), config_files: files, repo: ts };
|
||||
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
|
||||
Ok(Some(Repo {
|
||||
execution_allowed: std::sync::atomic::AtomicBool::new(true),
|
||||
root,
|
||||
git_dir,
|
||||
inner: std::sync::Mutex::new(cache),
|
||||
ignored: Default::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn absolute(p: &Path) -> IdeResult<PathBuf> {
|
||||
@@ -70,6 +76,11 @@ impl Repo {
|
||||
/// A thread-local gitoxide handle; reopened when the git configuration changed
|
||||
/// on disk (e.g. after `push --set-upstream` or `git config` in a terminal).
|
||||
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
|
||||
return gix::open_opts(&self.git_dir, gix::open::Options::default().filter_config_section(|_| false))
|
||||
.map_err(gx);
|
||||
}
|
||||
let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let now = stamp(&cache.config_files);
|
||||
if now != cache.config_stamp {
|
||||
@@ -89,6 +100,7 @@ impl Repo {
|
||||
/// Repository-relative path with `/` separators. Accepts absolute paths inside the
|
||||
/// worktree or paths already relative to it.
|
||||
pub(crate) fn rel_path(&self, path: &Path) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let rel = if path.is_absolute() {
|
||||
self.strip_root(path)
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?
|
||||
@@ -140,6 +152,7 @@ impl Repo {
|
||||
|
||||
/// Absolute path for a repository-relative path.
|
||||
pub(crate) fn abs_path(&self, rel: &str) -> PathBuf {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let mut p = self.root.clone();
|
||||
for part in rel.split('/').filter(|s| !s.is_empty()) {
|
||||
p.push(part);
|
||||
|
||||
@@ -16,6 +16,7 @@ const UNCOMMITTED_AUTHOR: &str = "Not Committed Yet";
|
||||
|
||||
impl Repo {
|
||||
pub(crate) fn rel_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -26,6 +27,7 @@ impl Repo {
|
||||
}
|
||||
|
||||
pub(crate) fn has_head(&self) -> IdeResult<bool> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let repo = self.gix()?;
|
||||
Ok(!repo.head().map_err(gx)?.is_unborn())
|
||||
}
|
||||
@@ -86,11 +88,17 @@ pub(crate) fn blame(
|
||||
if !tracked_in_head {
|
||||
return Ok(uncommitted_lines(line_count));
|
||||
}
|
||||
let out = run(
|
||||
r.root(),
|
||||
&["--literal-pathspecs", "blame", "--porcelain", "--contents", "-", revision, "--", &rel],
|
||||
Some(&contents),
|
||||
)?;
|
||||
// Restricted blame reads committed blobs only. Feeding working-tree bytes to
|
||||
// Git's --contents path would run configured clean filters.
|
||||
let out = if crate::execution_allowed() {
|
||||
run(
|
||||
r.root(),
|
||||
&["--literal-pathspecs", "blame", "--porcelain", "--contents", "-", revision, "--", &rel],
|
||||
Some(&contents),
|
||||
)?
|
||||
} else {
|
||||
run(r.root(), &["--literal-pathspecs", "blame", "--no-textconv", "--porcelain", revision, "--", &rel], None)?
|
||||
};
|
||||
let mut lines = crate::blame::parse_porcelain(&out.stdout_str());
|
||||
for line in &mut lines {
|
||||
if line.commit.bytes().all(|b| b == b'0') {
|
||||
@@ -98,6 +106,14 @@ pub(crate) fn blame(
|
||||
line.summary = String::new();
|
||||
}
|
||||
}
|
||||
if !crate::execution_allowed() {
|
||||
let base = r.file_at(path, Some(revision), encoding)?.unwrap_or_default();
|
||||
for hunk in crate::diff::line_hunks(&base, &text).into_iter().rev() {
|
||||
let start = (hunk.old_start as usize).min(lines.len());
|
||||
let end = (start + hunk.old_lines as usize).min(lines.len());
|
||||
lines.splice(start..end, uncommitted_lines(hunk.lines as usize));
|
||||
}
|
||||
}
|
||||
// Defensive: always exactly one entry per line.
|
||||
lines.truncate(line_count);
|
||||
while lines.len() < line_count {
|
||||
@@ -161,6 +177,16 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
|
||||
|
||||
pub(crate) fn diff_text(r: &Repo, path: &Path, staged: bool, encoding: TextEncoding) -> IdeResult<String> {
|
||||
let rel = r.rel_path(path)?;
|
||||
if !crate::execution_allowed() {
|
||||
let old = r.file_at(path, Some(if staged { "HEAD" } else { ":0" }), encoding)?.unwrap_or_default();
|
||||
let new = if staged {
|
||||
r.file_at(path, Some(":0"), encoding)?.unwrap_or_default()
|
||||
} else {
|
||||
std::fs::read(r.abs_path(&rel)).map(|b| decode(&b, encoding).into_owned()).unwrap_or_default()
|
||||
};
|
||||
let selected: Vec<_> = (0..crate::diff::line_hunks(&old, &new).len()).collect();
|
||||
return Ok(crate::diff::build_partial_patch(&rel, &old, &new, &selected));
|
||||
}
|
||||
let base =
|
||||
["-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.external=", "--literal-pathspecs"];
|
||||
let in_index = {
|
||||
@@ -221,7 +247,11 @@ pub(crate) fn stage_patch(r: &Repo, patch: &str, encoding: &dyn Fn(&Path) -> Ide
|
||||
|
||||
/// Paths with unresolved conflicts (index stages 1–3).
|
||||
pub(crate) fn unmerged_paths(r: &Repo) -> IdeResult<Vec<String>> {
|
||||
let out = run(r.root(), &["diff", "--name-only", "--diff-filter=U", "-z"], None)?;
|
||||
let out = run(
|
||||
r.root(),
|
||||
&["diff", "--cached", "--no-ext-diff", "--no-textconv", "--name-only", "--diff-filter=U", "-z"],
|
||||
None,
|
||||
)?;
|
||||
Ok(out.stdout_str().split('\0').filter(|s| !s.is_empty()).map(str::to_string).collect())
|
||||
}
|
||||
|
||||
|
||||
@@ -1534,3 +1534,62 @@ fn gbk_text_patch_keeps_utf8_paths_and_encoded_payload() {
|
||||
assert!(repo.stage_patch(&patch, &|_| Ok(encoding_rs::GBK)).is_err());
|
||||
assert_eq!(repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(), encoding_rs::GBK.encode(new).0.as_ref());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restricted_reads_ignore_executable_repository_configuration() {
|
||||
let f = Fixture::new();
|
||||
f.write("a.txt", "one\ntwo\n");
|
||||
f.commit_all("initial");
|
||||
f.write(".gitattributes", "*.txt filter=evil diff=evil\n");
|
||||
f.write("a.txt", "one\nchanged\n");
|
||||
for key in ["filter.evil.clean", "diff.evil.textconv", "diff.external", "core.fsmonitor"] {
|
||||
f.git(&["config", key, "touch execution.marker; cat"]);
|
||||
}
|
||||
let repo = f.repo();
|
||||
repo.set_execution_allowed(false);
|
||||
assert!(!repo.status().unwrap().is_empty());
|
||||
assert!(repo.diff_text(&f.path("a.txt"), false, encoding_rs::UTF_8).unwrap().contains("changed"));
|
||||
assert_eq!(repo.blame(&f.path("a.txt"), None, None, encoding_rs::UTF_8).unwrap().len(), 2);
|
||||
assert!(!repo.diff_with_worktree("HEAD").unwrap().is_empty());
|
||||
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());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restricted_conflict_preview_uses_host_owned_temporary_files() {
|
||||
let f = Fixture::new();
|
||||
f.write("a.txt", "base\n");
|
||||
f.commit_all("base");
|
||||
f.git(&["checkout", "-b", "other"]);
|
||||
f.write("a.txt", "other\n");
|
||||
f.commit_all("other");
|
||||
f.git(&["checkout", "main"]);
|
||||
f.write("a.txt", "mine\n");
|
||||
f.commit_all("mine");
|
||||
let output = Command::new("git").current_dir(&f.dir).args(["merge", "other"]).output().unwrap();
|
||||
assert!(!output.status.success());
|
||||
let trap = f.path(&format!(".git/openidea-merge-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&trap).unwrap();
|
||||
let marker = f._tmp.path().join("user-data");
|
||||
std::fs::write(&marker, "untouched").unwrap();
|
||||
std::os::unix::fs::symlink(&marker, trap.join("ours")).unwrap();
|
||||
let repo = f.repo();
|
||||
repo.set_execution_allowed(false);
|
||||
let versions = repo.merge_versions(&f.path("a.txt"), encoding_rs::UTF_8).unwrap();
|
||||
assert!(versions.merged.unwrap().contains("<<<<<<<"));
|
||||
assert_eq!(std::fs::read_to_string(marker).unwrap(), "untouched");
|
||||
}
|
||||
@@ -791,6 +791,21 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// Re-checks open file buffers, including files outside the watched roots.
|
||||
/// Call from a blocking worker; unchanged files only need their metadata.
|
||||
pub fn sync_from_disk(&self) {
|
||||
let slots: Vec<Slot> = self.registry.lock().docs.values().map(|e| e.slot.clone()).collect();
|
||||
let paths: Vec<PathBuf> = slots
|
||||
.iter()
|
||||
.filter_map(|slot| {
|
||||
let st = slot.lock();
|
||||
(!st.closed && st.uri.is_none() && !st.binary && !ide_vfs::is_archive_path(&st.path))
|
||||
.then(|| st.path.clone())
|
||||
})
|
||||
.collect();
|
||||
self.on_disk_changed(&paths);
|
||||
}
|
||||
|
||||
/// Re-reads from disk after an external change. Clean documents reload
|
||||
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
|
||||
/// Changes matching our own last save are ignored.
|
||||
@@ -798,6 +813,9 @@ impl Documents {
|
||||
for path in paths {
|
||||
let Some(id) = self.by_path(path) else { continue };
|
||||
let result = self.with_doc(id, |st| {
|
||||
if st.uri.is_some() || st.binary || ide_vfs::is_archive_path(&st.path) {
|
||||
return Ok(());
|
||||
}
|
||||
let Ok(meta) = std::fs::metadata(&st.path) else { return Ok(()) };
|
||||
let mtime = ide_vfs::mtime_ms(&meta);
|
||||
if mtime == st.disk_mtime && meta.len() == st.disk_len {
|
||||
|
||||
@@ -597,6 +597,10 @@ fn archive_entries_open_read_only_without_observers() {
|
||||
assert_eq!((info.text.as_str(), info.language.as_str(), info.read_only), ("fn main() {}\n", "rust", true));
|
||||
assert_eq!(*info.path, *path);
|
||||
assert!(f.rec.log.lock().is_empty(), "language servers / history never see archive entries");
|
||||
fs::remove_file(&jar).unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().version, info.version);
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().text, info.text);
|
||||
f.docs.close(info.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -295,7 +295,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
222 themeable tokens: 116 in the UI theme file, 106 in the editor colour scheme file.
|
||||
223 themeable tokens: 117 in the UI theme file, 106 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
@@ -304,6 +304,7 @@ a token.
|
||||
| `--bg-app` | `#191a1c` | `#ffffff` |
|
||||
| `--bg-elev` | `#212326` | `#f7f8f9` |
|
||||
| `--bg-popup` | `#26282c` | `#ffffff` |
|
||||
| `--bg-floating-toolbar` | `#33353b` | `#ffffff` |
|
||||
| `--bg-hover` | `#2e2f30` | `#ededed` |
|
||||
| `--bg-selected` | `#2a4371` | `#d0dffe` |
|
||||
| `--bg-selected-strong` | `#2e4d89` | `#bdd3ff` |
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.29",
|
||||
"version": "0.1.32",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -14,6 +14,7 @@ export const UI_KEYS: Record<string, string[]> = {
|
||||
"--bg-island": ["ToolWindow.background", "Panel.background"],
|
||||
"--bg-elev": ["ToolWindow.background", "SidePanel.background"],
|
||||
"--bg-popup": ["Popup.background", "PopupMenu.background"],
|
||||
"--bg-floating-toolbar": ["Toolbar.Floating.background"],
|
||||
"--bg-backdrop": ["Popup.background"],
|
||||
"--bg-hover": ["List.hoverBackground", "Tree.hoverBackground"],
|
||||
"--bg-selected": ["List.selectionBackground", "Tree.selectionBackground"],
|
||||
|
||||
@@ -69,3 +69,9 @@ ide-tools = { path = "../crates/ide-tools" }
|
||||
ide-plugin = { path = "../crates/ide-plugin" }
|
||||
ide-docker = { path = "../crates/ide-docker" }
|
||||
ide-github = { path = "../crates/ide-github" }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSButton", "NSResponder", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
@@ -266,3 +266,41 @@ pub fn log_frontend(level: LogLevel, message: String) {
|
||||
LogLevel::Error => tracing::error!(target: "frontend", "{message}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn project_trust_status(state: State<'_, AppState>, path: PathBuf) -> IdeResult<ide_host::trust::TrustStatus> {
|
||||
state.trust.status(&path)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn project_trust_list(state: State<'_, AppState>) -> IdeResult<ide_host::trust::TrustDecisions> {
|
||||
state.trust.decisions()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn project_trust_set(
|
||||
state: State<'_, AppState>,
|
||||
path: PathBuf,
|
||||
trusted: bool,
|
||||
folder: bool,
|
||||
) -> IdeResult<()> {
|
||||
state.host.set_project_trust(&path, trusted, folder).await?;
|
||||
if !trusted {
|
||||
state.plugins.restrict_project(&dunce::canonicalize(&path).unwrap_or(path));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn project_trust_remove_location(state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
|
||||
state.trust.remove_location(&path)?;
|
||||
state.host.refresh_project_trust().await?;
|
||||
for project in state.host.projects().into_iter().filter(|p| !p.is_trusted()) {
|
||||
state.plugins.restrict_project(&project.root);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -23,8 +23,12 @@ pub async fn coverage_prepare(
|
||||
/// Reads the report a coverage run left behind.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn coverage_collect(state: State<'_, AppState>, report: CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
ide_host::ops::coverage::coverage_collect(&state.host, "", report).await
|
||||
pub async fn coverage_collect(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
report: CoverageReportSpec,
|
||||
) -> IdeResult<CoverageSuite> {
|
||||
ide_host::ops::coverage::coverage_collect(&state.host, window.label(), report).await
|
||||
}
|
||||
|
||||
/// Reads a report collected elsewhere (CI): lcov, a Go cover profile or JaCoCo XML,
|
||||
|
||||
@@ -50,6 +50,12 @@ pub async fn doc_save_all(window: Window, state: State<'_, AppState>) -> IdeResu
|
||||
ide_host::ops::doc::save_all(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_sync_from_disk(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
|
||||
ide_host::ops::doc::sync_from_disk(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_snapshot(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<DocumentInfo> {
|
||||
|
||||
@@ -64,6 +64,10 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
app::recent_projects,
|
||||
app::remove_recent_project,
|
||||
app::open_project,
|
||||
app::project_trust_status,
|
||||
app::project_trust_list,
|
||||
app::project_trust_set,
|
||||
app::project_trust_remove_location,
|
||||
workspace::workspace_create,
|
||||
workspace::workspace_attach,
|
||||
workspace::workspace_update,
|
||||
@@ -143,6 +147,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
doc::doc_edit,
|
||||
doc::doc_save,
|
||||
doc::doc_save_all,
|
||||
doc::doc_sync_from_disk,
|
||||
doc::doc_snapshot,
|
||||
doc::doc_ui_mode,
|
||||
doc::doc_set_encoding,
|
||||
@@ -266,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,
|
||||
@@ -351,6 +358,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
window::window_open_settings,
|
||||
window::window_cycle,
|
||||
window::window_toggle_fullscreen,
|
||||
window::window_set_titlebar_height,
|
||||
window::window_take_launch,
|
||||
window::window_close_context,
|
||||
window::window_open_projects,
|
||||
@@ -471,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,
|
||||
|
||||
@@ -36,8 +36,16 @@ fn deliver(client: Option<&str>, event: PluginEvent) {
|
||||
}
|
||||
|
||||
/// Creates the host over `<app-data>/plugins` and loads installed plugins in the background.
|
||||
pub fn create_host(_app: &AppHandle, data_dir: &Path) -> IdeResult<Arc<PluginHost>> {
|
||||
pub fn create_host(
|
||||
_app: &AppHandle,
|
||||
data_dir: &Path,
|
||||
project_host: &Arc<ide_host::Host>,
|
||||
) -> IdeResult<Arc<PluginHost>> {
|
||||
let host = Arc::new(PluginHost::new(data_dir.join("plugins"), Arc::new(deliver), Limits::default())?);
|
||||
let weak = Arc::downgrade(project_host);
|
||||
host.set_project_policy(Arc::new(move |root| {
|
||||
weak.upgrade().is_some_and(|host| host.trust.trusted(root).unwrap_or(false))
|
||||
}));
|
||||
let loader = host.clone();
|
||||
std::thread::Builder::new().name("plugin-load".into()).spawn(move || loader.load_all())?;
|
||||
Ok(host)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -102,6 +102,20 @@ pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// Height of the web title bar in native logical pixels (CSS height × IDE zoom).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResult<()> {
|
||||
if !height.is_finite() || !(1.0..=1000.0).contains(&height) {
|
||||
return Err(IdeError::invalid("invalid title bar height"));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::titlebar::set_height(&window, height).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = window;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What this window was opened for (taken once).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
+101
-64
@@ -13,6 +13,8 @@ mod remote_dev;
|
||||
|
||||
mod state;
|
||||
mod theme_frame;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod titlebar;
|
||||
mod window_groups;
|
||||
mod windows;
|
||||
|
||||
@@ -84,76 +86,111 @@ pub fn run() {
|
||||
// Paths macOS asked to open (Finder's Open With, the Dock) before setup ran: the first window takes them.
|
||||
let early_opens: Arc<Mutex<Option<Vec<PathBuf>>>> = Arc::default();
|
||||
let setup_opens = early_opens.clone();
|
||||
app.invoke_handler(builder.invoke_handler())
|
||||
.setup(move |app| {
|
||||
builder.mount_events(app);
|
||||
let state = AppState::new(app.handle().clone())?;
|
||||
let windows = WindowsState::default();
|
||||
if let Ok(cwd) = std::env::current_dir()
|
||||
&& let Some(path) = windows::cli_path(&std::env::args().collect::<Vec<_>>(), &cwd)
|
||||
{
|
||||
windows.set_launch("main", windows::path_launch(path));
|
||||
let invoke = Arc::new(builder.invoke_handler());
|
||||
app.invoke_handler(move |request| {
|
||||
let webview = request.message.webview_ref();
|
||||
if let Some(state) = webview.try_state::<AppState>() {
|
||||
let label = AppState::owner_window(webview.label());
|
||||
if let Some(connection) = state.remote_dev.get(label) {
|
||||
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(()) => {
|
||||
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),
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
let menu_state = menu::MenuState::default();
|
||||
menu::install(app.handle(), &menu_state, &state.recent.list());
|
||||
app.manage(state);
|
||||
app.manage(windows);
|
||||
app.manage(menu_state);
|
||||
if let Some(paths) = setup_opens.lock().take() {
|
||||
windows::open_paths_at_launch(app.handle(), paths);
|
||||
if let Err(error) = state.host.authorize_command(webview.label(), request.message.command()) {
|
||||
request.resolver.reject(error);
|
||||
return true;
|
||||
}
|
||||
app.on_menu_event(on_menu_event);
|
||||
windows::create_main_window(app.handle())?;
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| match event {
|
||||
tauri::WindowEvent::Focused(true) => {
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
w.focused(window.label());
|
||||
}
|
||||
}
|
||||
invoke(request)
|
||||
})
|
||||
.setup(move |app| {
|
||||
builder.mount_events(app);
|
||||
let state = AppState::new(app.handle().clone())?;
|
||||
let windows = WindowsState::default();
|
||||
if let Ok(cwd) = std::env::current_dir()
|
||||
&& let Some(path) = windows::cli_path(&std::env::args().collect::<Vec<_>>(), &cwd)
|
||||
{
|
||||
windows.set_launch("main", windows::path_launch(path));
|
||||
}
|
||||
let menu_state = menu::MenuState::default();
|
||||
menu::install(app.handle(), &menu_state, &state.recent.list());
|
||||
app.manage(state);
|
||||
app.manage(windows);
|
||||
app.manage(menu_state);
|
||||
if let Some(paths) = setup_opens.lock().take() {
|
||||
windows::open_paths_at_launch(app.handle(), paths);
|
||||
}
|
||||
app.on_menu_event(on_menu_event);
|
||||
windows::create_main_window(app.handle())?;
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| match event {
|
||||
tauri::WindowEvent::Focused(true) => {
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
w.focused(window.label());
|
||||
}
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
window_groups::destroyed(window.app_handle(), window.label());
|
||||
if let Some(settings) = window.app_handle().get_webview_window(&windows::settings_label(window.label()))
|
||||
{
|
||||
let _ = settings.destroy();
|
||||
}
|
||||
if let Some(state) = window.try_state::<AppState>() {
|
||||
state.close_project(window.label());
|
||||
}
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
w.forget(window.label());
|
||||
}
|
||||
if !windows::is_settings_window(window.label()) {
|
||||
windows::continue_quit(window.app_handle(), Some(window.label()));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.build(context)
|
||||
.expect("error while running OpenIDEA")
|
||||
.run(move |app, event| {
|
||||
}
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Opened { urls } = &event {
|
||||
let paths = windows::opened_paths(urls);
|
||||
if app.try_state::<WindowsState>().is_some() {
|
||||
windows::open_paths(app, paths);
|
||||
} else {
|
||||
early_opens.lock().get_or_insert_default().extend(paths);
|
||||
}
|
||||
titlebar::forget(window);
|
||||
window_groups::destroyed(window.app_handle(), window.label());
|
||||
if let Some(settings) = window.app_handle().get_webview_window(&windows::settings_label(window.label())) {
|
||||
let _ = settings.destroy();
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = &early_opens;
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.host.shutdown_notebooks_on_exit();
|
||||
}
|
||||
// Cleanup must finish before update/restart replaces this process.
|
||||
if app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested()) {
|
||||
tauri::process::restart(&app.env());
|
||||
}
|
||||
if let Some(state) = window.try_state::<AppState>() {
|
||||
state.close_project(window.label());
|
||||
}
|
||||
});
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
w.forget(window.label());
|
||||
}
|
||||
if !windows::is_settings_window(window.label()) {
|
||||
windows::continue_quit(window.app_handle(), Some(window.label()));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.build(context)
|
||||
.expect("error while running OpenIDEA")
|
||||
.run(move |app, event| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Opened { urls } = &event {
|
||||
let paths = windows::opened_paths(urls);
|
||||
if app.try_state::<WindowsState>().is_some() {
|
||||
windows::open_paths(app, paths);
|
||||
} else {
|
||||
early_opens.lock().get_or_insert_default().extend(paths);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = &early_opens;
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
state.host.shutdown_notebooks_on_exit();
|
||||
}
|
||||
// Cleanup must finish before update/restart replaces this process.
|
||||
if app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested()) {
|
||||
tauri::process::restart(&app.env());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn window_state_flags() -> tauri_plugin_window_state::StateFlags {
|
||||
|
||||
@@ -53,6 +53,28 @@ type Channels = Arc<Mutex<HashMap<u64, (Channel<ChannelFrame>, u64)>>>;
|
||||
#[derive(Default)]
|
||||
pub struct Connections(Mutex<HashMap<String, Arc<Connection>>>);
|
||||
|
||||
impl Connection {
|
||||
pub async fn authorize_command(&self, window: &str, command: &str) -> IdeResult<()> {
|
||||
if ide_host::trust::restricted_command_allowed(command) {
|
||||
return Ok(());
|
||||
}
|
||||
let project: Option<ide_host::ops::project::ProjectInfo> = self
|
||||
.peer
|
||||
.request(
|
||||
"invoke",
|
||||
Invoke { window: window.to_owned(), cmd: "project_current".into(), args: serde_json::json!({}) },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(ide_host::rpc::error_from_reply)?;
|
||||
if project.is_some_and(|p| p.trusted) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable("Project is in Restricted Mode"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Connections {
|
||||
pub fn get(&self, window: &str) -> Option<Arc<Connection>> {
|
||||
self.0.lock().get(window).cloned()
|
||||
@@ -446,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::*;
|
||||
|
||||
@@ -92,7 +92,7 @@ impl AppState {
|
||||
recent: RecentProjects::load(&config_dir),
|
||||
askpass: start_askpass(&app),
|
||||
sink: global_sink,
|
||||
plugins: crate::commands::plugin::create_host(&app, &data_dir)?,
|
||||
plugins: crate::commands::plugin::create_host(&app, &data_dir, &host)?,
|
||||
web: ide_web::WebServer::new(),
|
||||
remote_dev: crate::remote_dev::Connections::default(),
|
||||
host,
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Keep the native window buttons aligned with the web toolbar, in AppKit points.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_app_kit::{NSWindow, NSWindowButton, NSWindowDidUpdateNotification, NSWindowStyleMask};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSPoint};
|
||||
|
||||
struct Titlebar {
|
||||
height: Rc<Cell<f64>>,
|
||||
observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
}
|
||||
|
||||
impl Drop for Titlebar {
|
||||
fn drop(&mut self) {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver((*self.observer).as_ref()) };
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static TITLEBARS: RefCell<HashMap<String, Titlebar>> = RefCell::default();
|
||||
}
|
||||
|
||||
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
|
||||
let label = window.label().to_owned();
|
||||
// with_webview runs on the AppKit thread; the observer is also delivered there.
|
||||
window.with_webview(move |webview| unsafe {
|
||||
let native = &*webview.ns_window().cast::<NSWindow>();
|
||||
TITLEBARS.with_borrow_mut(|bars| {
|
||||
let bar = bars.entry(label).or_insert_with(|| {
|
||||
let height = Rc::new(Cell::new(height));
|
||||
let current = height.clone();
|
||||
let pointer = native as *const NSWindow;
|
||||
let block = RcBlock::new(move |_| center_buttons(&*pointer, current.get()));
|
||||
let observer = NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
|
||||
Some(NSWindowDidUpdateNotification),
|
||||
Some(native),
|
||||
None,
|
||||
&block,
|
||||
);
|
||||
Titlebar { height, observer }
|
||||
});
|
||||
bar.height.set(height);
|
||||
center_buttons(native, height);
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
pub fn forget(window: &tauri::Window) {
|
||||
let label = window.label().to_owned();
|
||||
let _ = window.run_on_main_thread(move || {
|
||||
TITLEBARS.with_borrow_mut(|bars| bars.remove(&label));
|
||||
});
|
||||
}
|
||||
|
||||
unsafe fn center_buttons(window: &NSWindow, height: f64) {
|
||||
// Fullscreen uses AppKit's own revealable title bar.
|
||||
if window.styleMask().contains(NSWindowStyleMask::FullScreen) {
|
||||
return;
|
||||
}
|
||||
let Some(close) = window.standardWindowButton(NSWindowButton::CloseButton) else { return };
|
||||
let Some(minimize) = window.standardWindowButton(NSWindowButton::MiniaturizeButton) else { return };
|
||||
let spacing = minimize.frame().origin.x - close.frame().origin.x;
|
||||
let Some(container) = (unsafe { close.superview().and_then(|view| view.superview()) }) else { return };
|
||||
let Some(content) = window.contentView() else { return };
|
||||
let mut frame = container.frame();
|
||||
let top = frame.origin.y + frame.size.height;
|
||||
if (frame.size.height - height).abs() > 0.01 {
|
||||
frame.size.height = height;
|
||||
frame.origin.y = top - height;
|
||||
container.setFrame(frame);
|
||||
}
|
||||
let bounds = content.bounds();
|
||||
let y = bounds.origin.y + if content.isFlipped() { height / 2.0 } else { bounds.size.height - height / 2.0 };
|
||||
for (index, kind) in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let Some(button) = window.standardWindowButton(kind) else { continue };
|
||||
let Some(parent) = (unsafe { button.superview() }) else { continue };
|
||||
let center = parent.convertPoint_fromView(NSPoint::new(0.0, y), Some(&content));
|
||||
let frame = button.frame();
|
||||
let x = 14.0 + index as f64 * spacing;
|
||||
let target = center.y - frame.size.height / 2.0;
|
||||
if (frame.origin.x - x).abs() > 0.01 || (frame.origin.y - target).abs() > 0.01 {
|
||||
button.setFrameOrigin(NSPoint::new(x, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,6 +297,8 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
.and_then(|b| b.build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window);
|
||||
// "Sync with OS" needs the OS mode, known once the window exists.
|
||||
if let Some(a) = appearance.filter(|a| plugin_frame.is_none() && (a.sync_with_os || a.theme == "system"))
|
||||
&& window.theme().is_ok_and(|t| t == Theme::Dark)
|
||||
@@ -317,6 +319,20 @@ fn apply_zoom(app: &AppHandle, window: &WebviewWindow) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Aligns the native window buttons before the page reports its title bar height,
|
||||
/// so they don't visibly move once it loads.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn align_titlebar(app: &AppHandle, window: &WebviewWindow) {
|
||||
// `--h-titlebar` in tokens.css.
|
||||
const HEIGHT: f64 = 40.0;
|
||||
const COMPACT_HEIGHT: f64 = 32.0;
|
||||
let Some(a) = app.try_state::<AppState>().map(|s| s.global_settings.effective().appearance) else {
|
||||
return;
|
||||
};
|
||||
let height = if a.compact_mode { COMPACT_HEIGHT } else { HEIGHT };
|
||||
let _ = crate::titlebar::set_height(window, height * f64::from(a.zoom.clamp(50, 300)) / 100.0);
|
||||
}
|
||||
|
||||
/// The first window (`create: false` in tauri.conf.json so it can take the theme's colour).
|
||||
pub fn create_main_window(app: &AppHandle) -> IdeResult<WebviewWindow> {
|
||||
build_project_window(app, window_config(app)?)
|
||||
@@ -747,20 +763,16 @@ pub fn open_settings_window(
|
||||
.and_then(|b| b.build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create settings window: {e}")))?;
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window);
|
||||
// Restore runs during build; fit its size to the parent's current display before showing.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(e) = fit_settings_window(&window, &parent) {
|
||||
tracing::warn!("cannot fit settings window: {e}");
|
||||
}
|
||||
// Elsewhere the remembered size is kept and the position follows the parent.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if let (Ok(pos), Ok(size), Ok(own), Ok(scale)) =
|
||||
(parent.outer_position(), parent.outer_size(), window.outer_size(), parent.scale_factor())
|
||||
{
|
||||
let (pos, size, own) =
|
||||
(pos.to_logical::<f64>(scale), size.to_logical::<f64>(scale), own.to_logical::<f64>(scale));
|
||||
let at = centered(pos.x, pos.y, size.width, size.height, own.width, own.height);
|
||||
let _ = window.set_position(tauri::LogicalPosition::new(at.0, at.1));
|
||||
if let Err(e) = place_settings_window(&window, &parent) {
|
||||
tracing::warn!("cannot place settings window: {e}");
|
||||
}
|
||||
focus(&window);
|
||||
Ok(())
|
||||
@@ -805,7 +817,45 @@ fn fit_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri:
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
/// Centres the settings window over its owner, inside the owner's monitor work area. The window
|
||||
/// may still be on another display with a different scale, so its size is converted with its own
|
||||
/// scale and its position is given in physical pixels.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn place_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri::Result<()> {
|
||||
let Some(monitor) = parent.current_monitor()?.or(parent.primary_monitor()?) else {
|
||||
return Ok(());
|
||||
};
|
||||
let scale = monitor.scale_factor();
|
||||
let area = monitor.work_area();
|
||||
let origin = area.position.to_logical::<f64>(scale);
|
||||
let available = area.size.to_logical::<f64>(scale);
|
||||
let pos = parent.outer_position()?.to_logical::<f64>(scale);
|
||||
let size = parent.outer_size()?.to_logical::<f64>(scale);
|
||||
let own_scale = window.scale_factor()?;
|
||||
let own = window.outer_size()?.to_logical::<f64>(own_scale);
|
||||
let inner = window.inner_size()?.to_logical::<f64>(own_scale);
|
||||
let frame = (own.width - inner.width, own.height - inner.height);
|
||||
let bounds = fit_bounds(
|
||||
(pos.x, pos.y, size.width, size.height),
|
||||
(own.width, own.height),
|
||||
(origin.x, origin.y, available.width, available.height),
|
||||
);
|
||||
window.set_position(tauri::PhysicalPosition::new(
|
||||
(bounds.0 * scale).round() as i32,
|
||||
(bounds.1 * scale).round() as i32,
|
||||
))?;
|
||||
if (bounds.2, bounds.3) != (own.width, own.height) {
|
||||
// Sizes are set on the client area, and even an undecorated window has a resize frame.
|
||||
let (width, height) = ((bounds.2 - frame.0).max(1.0), (bounds.3 - frame.1).max(1.0));
|
||||
window.set_min_size(Some(tauri::LogicalSize::new(
|
||||
SETTINGS_MIN_SIZE.0.min(width),
|
||||
SETTINGS_MIN_SIZE.1.min(height),
|
||||
)))?;
|
||||
window.set_size(tauri::LogicalSize::new(width, height))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fit_bounds(parent: (f64, f64, f64, f64), size: (f64, f64), work: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
|
||||
let width = size.0.min(work.2);
|
||||
let height = size.1.min(work.3);
|
||||
@@ -1094,6 +1144,8 @@ mod tests {
|
||||
(0.0, 0.0, 1280.0, 1040.0 / 1.5),
|
||||
(150.0, 0.0, 980.0, 1040.0 / 1.5),
|
||||
),
|
||||
// 3840×2160 at 250% scaling: an owner taller than the work area must not push it off screen.
|
||||
((100.0, 60.0, 1440.0, 900.0), (980.0, 720.0), (0.0, 0.0, 1536.0, 816.0), (330.0, 96.0, 980.0, 720.0)),
|
||||
// Restored geometry from a larger display.
|
||||
((100.0, 50.0, 1440.0, 900.0), (2400.0, 1600.0), (0.0, 24.0, 1920.0, 1016.0), (0.0, 24.0, 1920.0, 1016.0)),
|
||||
// Secondary display with a negative origin and reserved top/left space.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.29",
|
||||
"version": "0.1.32",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
@@ -21,10 +21,6 @@
|
||||
"minHeight": 500,
|
||||
"titleBarStyle": "Overlay",
|
||||
"hiddenTitle": true,
|
||||
"trafficLightPosition": {
|
||||
"x": 14,
|
||||
"y": 22
|
||||
},
|
||||
"backgroundColor": "#E9EAEE",
|
||||
"dragDropEnabled": true
|
||||
}
|
||||
|
||||
+61
-1
@@ -11,6 +11,10 @@ export const commands = {
|
||||
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
|
||||
removeRecentProject: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remove_recent_project", { path })),
|
||||
openProject: (path: string) => typedError<ProjectInfo_Serialize, IdeError>(__TAURI_INVOKE("open_project", { path })),
|
||||
projectTrustStatus: (path: string) => typedError<TrustStatus, IdeError>(__TAURI_INVOKE("project_trust_status", { path })),
|
||||
projectTrustList: () => typedError<TrustDecisions, IdeError>(__TAURI_INVOKE("project_trust_list")),
|
||||
projectTrustSet: (path: string, trusted: boolean, folder: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_set", { path, trusted, folder })),
|
||||
projectTrustRemoveLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_remove_location", { path })),
|
||||
workspaceCreate: (path: string, name: string, projects: string[]) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_create", { path, name, projects })),
|
||||
workspaceAttach: (path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("workspace_attach", { path })),
|
||||
workspaceUpdate: (name: string, projects: string[]) => typedError<ProjectInfo_Serialize, IdeError>(__TAURI_INVOKE("workspace_update", { name, projects })),
|
||||
@@ -28,6 +32,7 @@ export const commands = {
|
||||
lightEditOpen: (path: string) => typedError<Settings_Serialize, IdeError>(__TAURI_INVOKE("light_edit_open", { path })),
|
||||
/** The project open in this window (a settings window: its parent's), if any. */
|
||||
projectCurrent: () => __TAURI_INVOKE<{
|
||||
trusted: boolean,
|
||||
root: IpcPath,
|
||||
name: string,
|
||||
isGit: boolean,
|
||||
@@ -199,6 +204,7 @@ export const commands = {
|
||||
docEdit: (doc: DocId, baseVersion: number, changes: ChangeSet) => typedError<number, IdeError>(__TAURI_INVOKE("doc_edit", { doc, baseVersion, changes })),
|
||||
docSave: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_save", { doc })),
|
||||
docSaveAll: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_save_all")),
|
||||
docSyncFromDisk: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_sync_from_disk")),
|
||||
docSnapshot: (doc: DocId) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_snapshot", { doc })),
|
||||
/**
|
||||
* The CodeMirror mode `path` gets when opened (`DocumentInfo::ui_mode`),
|
||||
@@ -503,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. */
|
||||
@@ -714,6 +722,8 @@ export const commands = {
|
||||
/** Focuses the next / previous window (⌘` / ⇧⌘`). */
|
||||
windowCycle: (forward: boolean) => __TAURI_INVOKE<void>("window_cycle", { forward }),
|
||||
windowToggleFullscreen: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_fullscreen")),
|
||||
/** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */
|
||||
windowSetTitlebarHeight: (height: number | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_set_titlebar_height", { height })),
|
||||
/** What this window was opened for (taken once). */
|
||||
windowTakeLaunch: () => __TAURI_INVOKE<{
|
||||
/** Project folder to open. */
|
||||
@@ -1008,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.
|
||||
@@ -1407,6 +1419,8 @@ export type AppearanceSettings = {
|
||||
projectColorsInToolbar?: boolean,
|
||||
dndWithAltOnly?: boolean,
|
||||
menuIcons?: boolean,
|
||||
/** `hamburger` | `merged`: main menu presentation in the frameless title bar. */
|
||||
mainMenuStyle?: string,
|
||||
/** `subpixel` | `greyscale` | `none` */
|
||||
ideAntialiasing?: string,
|
||||
editorAntialiasing?: string,
|
||||
@@ -1876,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. */
|
||||
@@ -3050,6 +3076,8 @@ export type FileRenameEdits = {
|
||||
export type FileSettings = {
|
||||
/** Save on focus loss / tab switch, like IDEA. */
|
||||
autoSave?: boolean,
|
||||
/** Re-check open files against disk when the IDE window gains focus. */
|
||||
syncOnFocus?: boolean,
|
||||
exclude?: string[],
|
||||
/** Ignored Files and Folders: name patterns hidden everywhere; see [`crate::ignored`]. */
|
||||
ignoredNames?: string[],
|
||||
@@ -3458,7 +3486,7 @@ export type IdeError = {
|
||||
|
||||
export type IdeEvent =
|
||||
/** Project window membership or selection changed. */
|
||||
{ type: "windowGroupsChanged" } |
|
||||
{ type: "windowGroupsChanged" } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
|
||||
/** Files or directories changed on disk (after debouncing, ignore rules applied). */
|
||||
{ type: "fsChanged"; created: IpcPath[]; modified: IpcPath[]; removed: IpcPath[] } |
|
||||
/** Excluded or ignored folders whose contents changed; they stay out of `FsChanged`. */
|
||||
@@ -4765,6 +4793,7 @@ export type ProjectFileSet =
|
||||
export type ProjectInfo = ProjectInfo_Serialize | ProjectInfo_Deserialize;
|
||||
|
||||
export type ProjectInfo_Deserialize = {
|
||||
trusted: boolean,
|
||||
root: IpcPath,
|
||||
name: string,
|
||||
isGit: boolean,
|
||||
@@ -4773,6 +4802,7 @@ export type ProjectInfo_Deserialize = {
|
||||
};
|
||||
|
||||
export type ProjectInfo_Serialize = {
|
||||
trusted: boolean,
|
||||
root: IpcPath,
|
||||
name: string,
|
||||
isGit: boolean,
|
||||
@@ -5109,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;
|
||||
|
||||
@@ -6106,6 +6146,18 @@ export type TransferReport = {
|
||||
errors: TransferError[],
|
||||
};
|
||||
|
||||
export type TrustDecisions = {
|
||||
projects: string[],
|
||||
locations: string[],
|
||||
restricted: string[],
|
||||
};
|
||||
|
||||
export type TrustStatus = {
|
||||
root: IpcPath,
|
||||
trusted: boolean,
|
||||
decided: boolean,
|
||||
};
|
||||
|
||||
export type TypeScriptSettings = {
|
||||
/**
|
||||
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
|
||||
@@ -6266,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. */
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 {
|
||||
@@ -38,6 +41,8 @@ export interface DocBackend {
|
||||
close(doc: DocId): Promise<void>;
|
||||
edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise<number>;
|
||||
save(doc: DocId): Promise<void>;
|
||||
/** Re-check every open file for external changes missed by file watchers. */
|
||||
syncFromDisk?(): Promise<void>;
|
||||
snapshot(doc: DocId): Promise<DocumentInfo>;
|
||||
setLineEnding(doc: DocId, lineEnding: LineEnding): Promise<void>;
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding. */
|
||||
@@ -67,6 +72,7 @@ export const ipcBackend: DocBackend = {
|
||||
close: async (doc) => void (await call(commands.docClose(doc))),
|
||||
edit: (doc, baseVersion, changes) => call(commands.docEdit(doc, baseVersion, { changes })),
|
||||
save: async (doc) => void (await call(commands.docSave(doc))),
|
||||
syncFromDisk: async () => void (await call(commands.docSyncFromDisk())),
|
||||
snapshot: (doc) => call(commands.docSnapshot(doc)),
|
||||
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
|
||||
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
|
||||
@@ -126,6 +132,8 @@ const EXT_LANG: Record<string, string> = {
|
||||
cmd: "bat",
|
||||
sql: "sql",
|
||||
xml: "xml",
|
||||
svg: "xml",
|
||||
vue: "vue",
|
||||
};
|
||||
|
||||
const MEM_LANGUAGES: LanguageInfo[] = [
|
||||
@@ -237,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",
|
||||
@@ -504,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) {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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));
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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" }]);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача