From 6ba662eceddd44b3958007810770577e5e6793c3 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 23 Nov 2026 17:46:12 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(api-11):=20=E6=96=87=E4=BB=B6=E5=8F=98?= =?UTF-8?q?=E6=9B=B4=E7=94=B1=20Core=20=E5=AE=8C=E6=88=90=EF=BC=8C?= =?UTF-8?q?=E6=96=B0=E5=BB=BA=E6=94=AF=E6=8C=81=E7=AC=A6=E5=8F=B7=E9=93=BE?= =?UTF-8?q?=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - plugin-rpc 严格检查 API-11 七个方法的参数:路径只有一种写法(无空、`.`、`..` 段, Windows 不能保存的名字也拒绝),移动不出根目录也不进自身,create 的字段必须与 kind 一致 - 新增内核命令 workspace.createEntry、renameEntry、copyEntry、resolveEntry 和错误码 entry_not_found、entry_exists;路径检查、不覆盖的重命名、只改大小写的重命名、 复制时链接保持为链接、失败回滚都在 lithe-project 里完成 - lithe-platform 新增 entries 模块(rename_no_replace、create_symlink), remote 服务端改用这份实现,不再各自保留一份 - workspace/create 支持 kind:"symlink" + linkTarget,原样保存目标,不放宽读取检查 - 契约 README、Core API 文档、API 总表、指南、更新记录和四个 SDK 同步更新, fixture 新增符号链接和路径写法用例 --- rust/Cargo.lock | 3 + rust/contracts/application-boundary.md | 3 + rust/contracts/rust-core-api.md | 36 ++ rust/crates/core/Cargo.toml | 2 + rust/crates/core/src/protocol/command.rs | 13 + .../core/src/runtime/dispatcher/workspace.rs | 20 + rust/crates/core/src/tests/file_changes.rs | 366 ++++++++++++++ rust/crates/core/src/tests/mod.rs | 1 + .../platform-tests/tests/platform/entries.rs | 97 ++++ .../platform-tests/tests/platform/main.rs | 1 + rust/crates/platform/Cargo.toml | 9 +- rust/crates/platform/src/entries.rs | 156 ++++++ rust/crates/platform/src/lib.rs | 1 + rust/crates/platform/src/paths.rs | 49 +- rust/crates/plugin-rpc/Cargo.toml | 2 + rust/crates/plugin-rpc/src/host_params.rs | 145 ++++++ rust/crates/plugin-rpc/src/host_requests.rs | 29 +- rust/crates/plugin-rpc/src/lib.rs | 216 ++++++++- rust/crates/project/src/file_changes.rs | 449 ++++++++++++++++++ rust/crates/project/src/lib.rs | 1 + rust/crates/protocol/src/error.rs | 7 + .../remote/src/server/platform/linux.rs | 28 -- .../remote/src/server/platform/macos.rs | 17 - rust/crates/remote/src/server/platform/mod.rs | 5 +- .../crates/remote/src/server/platform/unix.rs | 13 +- shared/plugins/contract/v1/README.md | 25 +- .../fixtures/backend/function-protocol.json | 3 + .../guides/plugin-backend-workspace.md | 4 +- shared/plugins/reference/api-catalog.md | 4 +- shared/plugins/reference/domains/backend.md | 4 +- .../plugins/reference/protocol-changelog.md | 16 +- shared/plugins/sdk/go/lithe/host.go | 8 +- .../io/github/litheidea/plugin/sdk/Host.java | 6 +- shared/plugins/sdk/node/src/index.d.ts | 6 +- shared/plugins/sdk/node/test/types/host.mts | 9 +- .../plugins/sdk/rust/plugin-sdk/src/host.rs | 9 +- 36 files changed, 1662 insertions(+), 101 deletions(-) create mode 100644 rust/crates/core/src/tests/file_changes.rs create mode 100644 rust/crates/platform-tests/tests/platform/entries.rs create mode 100644 rust/crates/platform/src/entries.rs create mode 100644 rust/crates/project/src/file_changes.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 3e143337..e0516d03 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -971,6 +971,7 @@ dependencies = [ "lithe-lsp-policy", "lithe-lsp-transport", "lithe-network", + "lithe-platform", "lithe-plugin-content-providers", "lithe-plugin-editor", "lithe-plugin-function-relay", @@ -1248,6 +1249,7 @@ name = "lithe-platform" version = "0.1.0" dependencies = [ "libc", + "windows-sys", ] [[package]] @@ -1415,6 +1417,7 @@ dependencies = [ name = "lithe-plugin-rpc" version = "0.1.0" dependencies = [ + "lithe-platform", "lithe-plugin-keymap-import", "lithe-plugin-language-servers", "lithe-plugin-model", diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index c64cba64..799c4511 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -405,6 +405,9 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported: - `git_untrusted_workspace`: the workspace is not trusted, so Git did not start - `parse_failed` - `encoding_unmappable` +- `entry_not_found`: a file change names a path, or a target's parent + directory, that does not exist below its root; nothing changed +- `entry_exists`: a file change's target already exists; nothing was replaced - `cancelled` - `timed_out` - `connection_closed`: the remote connection the request names closed or was lost diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1ea4ef58..023e028a 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -612,6 +612,10 @@ or removing a command fails until the table changes in the same commit. | `workspace.rankNames` | Pure ranking of candidate names that the platform enumerates itself (`{ query, candidates: [{ name, path? }], context: { openPaths, recentPaths }, limitPerTier? }`). Use it only for lists Core cannot index: Windows remote/WSL roots, symbol lists, navigator lists. Roots Core indexes go through `workspace.searchEverywhere`, so an inventory is never sent back to Core. Returns `matches: [{ index, degree, tier, nameMatchRanges }]` ordered by degree, open/recent tier, recency, then file-name order (fixture `rust/fixtures/search/rank-names-v1.json`) | | `workspace.planDuplicate` | Name the copy of one project item next to its source (`foo.txt` → `foo copy.txt`, then `foo copy 2.txt`) from the sibling names the host has seen to exist | | `workspace.planPaste` | Name pasted project items in one destination directory: a free name is kept, a taken one gets the copy suffix, and earlier items of the same paste count as taken | +| `workspace.createEntry` | Create one file, directory or symbolic link below a workspace root without replacing anything | +| `workspace.renameEntry` | Rename one entry to a new path of the same root without replacing anything; a link is renamed as a link | +| `workspace.copyEntry` | Copy one entry, a directory with everything in it, to a new path of the same root without replacing anything; links stay links | +| `workspace.resolveEntry` | Name one existing entry below a workspace root without following it | | `workspace.reduceDirectoryAction` | Apply "set role", "exclude" or "cancel exclusion" to a root's persisted directory rules and return the complete state to persist | | `workspace.relocateDirectoryRules` | Move (or drop, after a delete) the directory rule keys of a renamed, moved or deleted subtree, optionally into another workspace root's rules | | `workspace.repositories` | Discover deterministic Git repository roots for an opened workspace | @@ -7439,6 +7443,38 @@ to exist, creates the copy without replacing anything (`FileManager.copyItem`, w appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`. +`workspace.createEntry`, `workspace.renameEntry`, `workspace.copyEntry` and `workspace.resolveEntry` +change and name entries below a local workspace root on a plugin's behalf (plan API-11). Each takes +`root`, the absolute path of the root as the host spells it, and `path`, the entry below it. +`createEntry` takes `{ root, path, kind, text?, linkTarget? }`: `kind` is `file`, `directory` or +`symlink`; a file takes optional UTF-8 `text`, and a link takes the `linkTarget` it stores verbatim, +absolute or relative to the link's directory, which may leave the root or name nothing. On Windows each +`/` of `linkTarget` is stored as `\`, and the link is a directory link when the target is an existing +directory at creation, otherwise a file link. `renameEntry` and `copyEntry` take +`{ root, path, target }`, `target` being the full new path in the same root; `resolveEntry` takes +`{ root, path }`. Every command returns `{ path, fullPath, kind }`: `fullPath` is spelled from the +`root` the host sent, as its open documents name the entry, and `kind` is `file`, `directory`, +`symlink` or `other`. + +A path is `/`-separated with no empty, `.` or `..` component, and on Windows every component must be +one Windows stores as written (no reserved name such as `CON`, no trailing dot or space, none of +`\ : * ? " < > |`); the root itself is not an entry. The directory holding the entry must exist and +resolve inside the root, so no entry is created or moved through a link that leaves it; the last +component is never followed, so a link is renamed, copied or resolved as a link, and a copied +directory keeps its links as links. Nothing is replaced: macOS and Linux rename with one exclusive +system call (`renamex_np` with `RENAME_EXCL`, `renameat2` with `RENAME_NOREPLACE`) and fall back to a +check before the rename on volumes that refuse it; Windows renames with `MoveFileExW` without +`MOVEFILE_REPLACE_EXISTING`. A rename that only changes the case of a name on a file system that +ignores case is not a collision, and a target naming the source itself is. A directory is never moved +or copied into itself. A copy that fails part way removes what it created. + +Errors are `invalid_request` (a malformed path or root, fields that do not match the `kind`, a +directory moved into itself), `permission_denied` (a parent that resolves outside the root), +`workspace_not_found` (no root), `entry_not_found` (no entry, or no parent directory), `entry_exists` +(the target exists), and `unknown` with the system's message in `details` for anything else, such as +Windows refusing to create a link without Developer Mode or elevation. Saving and moving the open +documents under an entry, the system trash and refreshing the project tree stay with the host. + `history.planEvent` takes `{ event }` and returns `{ snapshots: [{ source, reason }] }`. `source` says whose text the host records: `beforeChange` (the text an event replaces), `afterChange` (the text it produced) or `editorBuffer` (unsaved editor text that is discarded). A save or auto-save records diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml index 01072a7e..09754c43 100644 --- a/rust/crates/core/Cargo.toml +++ b/rust/crates/core/Cargo.toml @@ -67,6 +67,8 @@ lithe-diagnostics = { path = "../diagnostics", features = ["test-support"] } lithe-execution = { path = "../execution", features = ["test-support"] } lithe-git = { path = "../git", features = ["test-support"] } lithe-lsp-transport = { path = "../lsp-transport", features = ["test-support"] } +# The file-change tests create symbolic links the way the kernel does. +lithe-platform = { path = "../platform" } lithe-project = { path = "../project", features = ["test-support"] } lithe-workspace = { path = "../workspace", features = ["test-support"] } serde_yaml_ng = "=0.10.0" diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 34a8611e..2db9f170 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -548,6 +548,15 @@ pub enum WorkspaceCommand { RankNames, /// Plans the name of a duplicated project item (`workspace.planDuplicate`). PlanDuplicate, + /// Creates a file, directory or symbolic link below a root + /// (`workspace.createEntry`). + CreateEntry, + /// Renames an entry without replacing one (`workspace.renameEntry`). + RenameEntry, + /// Copies an entry without replacing one (`workspace.copyEntry`). + CopyEntry, + /// Names an existing entry below a root (`workspace.resolveEntry`). + ResolveEntry, /// Plans the destination names of pasted project items (`workspace.planPaste`). PlanPaste, /// Applies a directory role, exclusion or cancel action (`workspace.reduceDirectoryAction`). @@ -1364,6 +1373,10 @@ impl CoreCommand { "workspace.orderEntries" => Some(Self::Workspace(WorkspaceCommand::OrderEntries)), "workspace.rankNames" => Some(Self::Workspace(WorkspaceCommand::RankNames)), "workspace.planDuplicate" => Some(Self::Workspace(WorkspaceCommand::PlanDuplicate)), + "workspace.createEntry" => Some(Self::Workspace(WorkspaceCommand::CreateEntry)), + "workspace.renameEntry" => Some(Self::Workspace(WorkspaceCommand::RenameEntry)), + "workspace.copyEntry" => Some(Self::Workspace(WorkspaceCommand::CopyEntry)), + "workspace.resolveEntry" => Some(Self::Workspace(WorkspaceCommand::ResolveEntry)), "workspace.planPaste" => Some(Self::Workspace(WorkspaceCommand::PlanPaste)), "workspace.reduceDirectoryAction" => { Some(Self::Workspace(WorkspaceCommand::ReduceDirectoryAction)) diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 535d4445..7904985a 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -165,6 +165,26 @@ pub(super) fn dispatch( payload, crate::project::file_operations::plan_paste_command, ), + WorkspaceCommand::CreateEntry => plugin_response( + id, + payload, + crate::project::file_changes::create_entry_command, + ), + WorkspaceCommand::RenameEntry => plugin_response( + id, + payload, + crate::project::file_changes::rename_entry_command, + ), + WorkspaceCommand::CopyEntry => plugin_response( + id, + payload, + crate::project::file_changes::copy_entry_command, + ), + WorkspaceCommand::ResolveEntry => plugin_response( + id, + payload, + crate::project::file_changes::resolve_entry_command, + ), WorkspaceCommand::ReduceDirectoryAction => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/file_changes.rs b/rust/crates/core/src/tests/file_changes.rs new file mode 100644 index 00000000..0ebf363f --- /dev/null +++ b/rust/crates/core/src/tests/file_changes.rs @@ -0,0 +1,366 @@ +//! `workspace.createEntry`, `renameEntry`, `copyEntry` and `resolveEntry` +//! on the host's file system. + +use super::support::{temporary_root, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; + +fn execute(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({"id": "file-changes", "command": command, "payload": payload}).to_string(), + )) + .expect("core response should be JSON") +} + +/// A new workspace root, removed when the returned guard drops. +fn workspace(label: &str) -> (PathBuf, Cleanup) { + let root = temporary_root(label); + fs::create_dir_all(&root).expect("workspace root"); + (root.clone(), Cleanup(root)) +} + +fn root_text(root: &Path) -> String { + root.to_string_lossy().into_owned() +} + +fn error_code(response: &Value) -> &str { + assert_eq!(response["ok"], false, "{response}"); + response["error"]["code"].as_str().expect("error code") +} + +/// Whether this host lets the test create symbolic links: Windows needs +/// Developer Mode or elevation. +fn links_allowed(root: &Path) -> bool { + let probe = root.join("link-probe"); + let allowed = lithe_platform::entries::create_symlink(Path::new("missing"), &probe).is_ok(); + let _ = fs::remove_file(&probe); + allowed +} + +#[test] +fn a_file_is_created_with_its_text_and_never_replaced() { + let (root, _cleanup) = workspace("create-file"); + fs::create_dir(root.join("src")).expect("src"); + let response = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "src/main.rs", "kind": "file", "text": "fn main() {}\n"}), + ); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["path"], "src/main.rs"); + assert_eq!(response["data"]["kind"], "file"); + assert_eq!( + Path::new(response["data"]["fullPath"].as_str().unwrap()), + root.join("src").join("main.rs") + ); + assert_eq!( + fs::read_to_string(root.join("src/main.rs")).unwrap(), + "fn main() {}\n" + ); + + let again = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "src/main.rs", "kind": "file", "text": "replaced"}), + ); + assert_eq!(error_code(&again), "entry_exists"); + assert_eq!( + fs::read_to_string(root.join("src/main.rs")).unwrap(), + "fn main() {}\n" + ); + + let empty = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "empty.txt", "kind": "file"}), + ); + assert_eq!(empty["ok"], true, "{empty}"); + assert_eq!(fs::read(root.join("empty.txt")).unwrap(), b""); +} + +#[test] +fn a_directory_needs_its_parent_and_takes_no_text() { + let (root, _cleanup) = workspace("create-directory"); + let created = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "docs", "kind": "directory"}), + ); + assert_eq!(created["data"]["kind"], "directory", "{created}"); + assert!(root.join("docs").is_dir()); + + let orphan = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "missing/inner", "kind": "directory"}), + ); + assert_eq!(error_code(&orphan), "entry_not_found"); + assert!(!root.join("missing").exists()); + + fs::write(root.join("plain.txt"), "").unwrap(); + let under_file = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "plain.txt/inner", "kind": "directory"}), + ); + assert_eq!(error_code(&under_file), "entry_not_found"); + + for fields in [ + json!({"kind": "directory", "text": ""}), + json!({"kind": "file", "linkTarget": "x"}), + json!({"kind": "symlink"}), + json!({"kind": "symlink", "linkTarget": ""}), + json!({"kind": "symlink", "linkTarget": "x", "text": ""}), + json!({"kind": "socket"}), + json!({"kind": "file", "mode": 420}), + ] { + let mut payload = json!({"root": root_text(&root), "path": "bad"}); + for (key, value) in fields.as_object().unwrap() { + payload[key] = value.clone(); + } + let response = execute("workspace.createEntry", payload); + assert_eq!(error_code(&response), "invalid_request", "{fields}"); + } + assert!(!root.join("bad").exists()); +} + +#[test] +fn paths_name_one_entry_below_the_root() { + let (root, _cleanup) = workspace("entry-paths"); + for path in ["", "/abs", "a//b", "./a", "a/", "../outside", "a/../b"] { + let response = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": path, "kind": "directory"}), + ); + assert_eq!(error_code(&response), "invalid_request", "{path:?}"); + } + let relative_root = execute( + "workspace.createEntry", + json!({"root": "relative/root", "path": "a", "kind": "directory"}), + ); + assert_eq!(error_code(&relative_root), "invalid_request"); + let missing_root = execute( + "workspace.createEntry", + json!({"root": root_text(&root.join("missing")), "path": "a", "kind": "directory"}), + ); + assert_eq!(error_code(&missing_root), "workspace_not_found"); +} + +#[test] +fn a_directory_link_that_leaves_the_root_cannot_hold_new_entries() { + let (root, _cleanup) = workspace("escape-parent"); + let (outside, _outside_cleanup) = workspace("escape-outside"); + if !links_allowed(&root) { + return; + } + lithe_platform::entries::create_symlink(&outside, &root.join("out")).unwrap(); + let response = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "out/planted.txt", "kind": "file", "text": "x"}), + ); + assert_eq!(error_code(&response), "permission_denied"); + assert!(!outside.join("planted.txt").exists()); +} + +#[test] +fn a_symlink_stores_its_target_verbatim() { + let (root, _cleanup) = workspace("create-symlink"); + if !links_allowed(&root) { + return; + } + fs::create_dir(root.join("shared")).unwrap(); + fs::write(root.join("shared/notes.md"), "notes").unwrap(); + let response = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "notes", "kind": "symlink", "linkTarget": "shared"}), + ); + assert_eq!(response["data"]["kind"], "symlink", "{response}"); + assert_eq!( + fs::read_to_string(root.join("notes/notes.md")).unwrap(), + "notes" + ); + + // A link may point outside the root or at nothing. + let dangling = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "dangling", "kind": "symlink", "linkTarget": "../nowhere/at/all"}), + ); + assert_eq!(dangling["ok"], true, "{dangling}"); + let stored = fs::read_link(root.join("dangling")).unwrap(); + assert_eq!( + stored.to_string_lossy().replace('\\', "/"), + "../nowhere/at/all" + ); + + let taken = execute( + "workspace.createEntry", + json!({"root": root_text(&root), "path": "dangling", "kind": "symlink", "linkTarget": "shared"}), + ); + assert_eq!(error_code(&taken), "entry_exists"); +} + +#[test] +fn a_rename_never_replaces_and_reports_the_target() { + let (root, _cleanup) = workspace("rename"); + fs::write(root.join("a.txt"), "a").unwrap(); + fs::write(root.join("b.txt"), "b").unwrap(); + let blocked = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "a.txt", "target": "b.txt"}), + ); + assert_eq!(error_code(&blocked), "entry_exists"); + assert_eq!(fs::read_to_string(root.join("b.txt")).unwrap(), "b"); + + fs::create_dir(root.join("dir")).unwrap(); + let moved = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "a.txt", "target": "dir/c.txt"}), + ); + assert_eq!(moved["data"]["path"], "dir/c.txt", "{moved}"); + assert_eq!(moved["data"]["kind"], "file"); + assert_eq!( + Path::new(moved["data"]["fullPath"].as_str().unwrap()), + root.join("dir").join("c.txt") + ); + assert!(!root.join("a.txt").exists()); + + let missing = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "a.txt", "target": "d.txt"}), + ); + assert_eq!(error_code(&missing), "entry_not_found"); + + let into_itself = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "dir", "target": "dir/inner"}), + ); + assert_eq!(error_code(&into_itself), "invalid_request"); + + let same = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "b.txt", "target": "b.txt"}), + ); + assert_eq!(error_code(&same), "entry_exists"); +} + +#[test] +fn a_rename_that_only_changes_case_is_not_a_collision() { + let (root, _cleanup) = workspace("rename-case"); + fs::write(root.join("readme.md"), "text").unwrap(); + let response = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "readme.md", "target": "README.md"}), + ); + assert_eq!(response["ok"], true, "{response}"); + let names: Vec<_> = fs::read_dir(&root) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + assert_eq!(names, ["README.md"]); +} + +#[test] +fn a_link_is_renamed_and_copied_as_a_link() { + let (root, _cleanup) = workspace("move-link"); + if !links_allowed(&root) { + return; + } + fs::create_dir(root.join("real")).unwrap(); + fs::write(root.join("real/file.txt"), "real").unwrap(); + lithe_platform::entries::create_symlink(Path::new("real"), &root.join("link")).unwrap(); + + let copied = execute( + "workspace.copyEntry", + json!({"root": root_text(&root), "path": "link", "target": "link copy"}), + ); + assert_eq!(copied["data"]["kind"], "symlink", "{copied}"); + assert!(fs::symlink_metadata(root.join("link copy")) + .unwrap() + .file_type() + .is_symlink()); + + // `link/x` is not inside `link`: the link is moved, not what it names. + let renamed = execute( + "workspace.renameEntry", + json!({"root": root_text(&root), "path": "link", "target": "real/link"}), + ); + assert_eq!(renamed["data"]["kind"], "symlink", "{renamed}"); + assert!(fs::symlink_metadata(root.join("real/link")) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!( + fs::read_to_string(root.join("real/file.txt")).unwrap(), + "real" + ); +} + +#[test] +fn a_copy_keeps_the_tree_and_never_replaces() { + let (root, _cleanup) = workspace("copy"); + fs::create_dir_all(root.join("src/nested")).unwrap(); + fs::write(root.join("src/a.txt"), "a").unwrap(); + fs::write(root.join("src/nested/b.txt"), "b").unwrap(); + let links = links_allowed(&root); + if links { + lithe_platform::entries::create_symlink(Path::new("a.txt"), &root.join("src/alias")) + .unwrap(); + } + + let copied = execute( + "workspace.copyEntry", + json!({"root": root_text(&root), "path": "src", "target": "src copy"}), + ); + assert_eq!(copied["data"]["kind"], "directory", "{copied}"); + assert_eq!( + fs::read_to_string(root.join("src copy/nested/b.txt")).unwrap(), + "b" + ); + assert_eq!( + fs::read_to_string(root.join("src copy/a.txt")).unwrap(), + "a" + ); + if links { + assert_eq!( + fs::read_link(root.join("src copy/alias")).unwrap(), + Path::new("a.txt") + ); + } + + let again = execute( + "workspace.copyEntry", + json!({"root": root_text(&root), "path": "src/a.txt", "target": "src copy/a.txt"}), + ); + assert_eq!(error_code(&again), "entry_exists"); + + let into_itself = execute( + "workspace.copyEntry", + json!({"root": root_text(&root), "path": "src", "target": "src/nested/src"}), + ); + assert_eq!(error_code(&into_itself), "invalid_request"); + assert!(!root.join("src/nested/src").exists()); +} + +#[test] +fn an_entry_resolves_without_following_it() { + let (root, _cleanup) = workspace("resolve"); + fs::create_dir(root.join("dir")).unwrap(); + let resolved = execute( + "workspace.resolveEntry", + json!({"root": root_text(&root), "path": "dir"}), + ); + assert_eq!(resolved["data"]["kind"], "directory", "{resolved}"); + assert_eq!( + Path::new(resolved["data"]["fullPath"].as_str().unwrap()), + root.join("dir") + ); + let missing = execute( + "workspace.resolveEntry", + json!({"root": root_text(&root), "path": "nothing"}), + ); + assert_eq!(error_code(&missing), "entry_not_found"); + if links_allowed(&root) { + lithe_platform::entries::create_symlink(Path::new("dir"), &root.join("link")).unwrap(); + let link = execute( + "workspace.resolveEntry", + json!({"root": root_text(&root), "path": "link"}), + ); + assert_eq!(link["data"]["kind"], "symlink", "{link}"); + } +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index bfabf10b..2bc0e169 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -12,6 +12,7 @@ mod directory_actions; mod document_uri; mod editor_dispatch; mod execution_commands; +mod file_changes; mod file_name_order; mod file_operations; mod git; diff --git a/rust/crates/platform-tests/tests/platform/entries.rs b/rust/crates/platform-tests/tests/platform/entries.rs new file mode 100644 index 00000000..8679df94 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/entries.rs @@ -0,0 +1,97 @@ +//! No-replace renames and symbolic links through `lithe_platform::entries` +//! on the host's file system. + +use crate::support::TempDir; +use lithe_platform::entries::{create_symlink, rename_no_replace}; +use std::fs; +use std::io::ErrorKind; +use std::path::Path; + +#[test] +fn a_rename_never_replaces_an_existing_entry() { + let directory = TempDir::new("lithe rename"); + let from = directory.path().join("from.txt"); + let to = directory.path().join("to.txt"); + fs::write(&from, "from").expect("from"); + fs::write(&to, "to").expect("to"); + + let error = rename_no_replace(&from, &to).expect_err("target exists"); + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + assert_eq!(fs::read_to_string(&to).expect("to"), "to"); + + fs::remove_file(&to).expect("remove target"); + rename_no_replace(&from, &to).expect("rename"); + assert_eq!(fs::read_to_string(&to).expect("to"), "from"); + assert!(!from.exists()); +} + +#[test] +fn a_directory_renames_without_replacing_one() { + let directory = TempDir::new("lithe rename directory"); + let from = directory.path().join("from"); + let to = directory.path().join("to"); + fs::create_dir(&from).expect("from"); + fs::write(from.join("inner.txt"), "inner").expect("inner"); + fs::create_dir(&to).expect("to"); + + let error = rename_no_replace(&from, &to).expect_err("target exists"); + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + + fs::remove_dir(&to).expect("remove target"); + rename_no_replace(&from, &to).expect("rename"); + assert_eq!( + fs::read_to_string(to.join("inner.txt")).expect("inner"), + "inner" + ); +} + +/// Windows creates links only with Developer Mode or elevation; build +/// machines run elevated, but a developer's shell may not. +fn links_refused(error: &std::io::Error) -> bool { + cfg!(windows) && error.raw_os_error() == Some(1314) +} + +#[test] +fn a_symlink_stores_its_target_and_never_replaces_an_entry() { + let directory = TempDir::new("lithe symlink"); + let link = directory.path().join("link"); + match create_symlink(Path::new("missing/target"), &link) { + Ok(()) => {} + Err(error) if links_refused(&error) => return, + Err(error) => panic!("link: {error}"), + } + let stored = fs::read_link(&link).expect("read link"); + let expected = if cfg!(windows) { + Path::new("missing\\target") + } else { + Path::new("missing/target") + }; + assert_eq!(stored, expected); + assert!(fs::symlink_metadata(&link) + .expect("link metadata") + .file_type() + .is_symlink()); + + let error = create_symlink(Path::new("other"), &link).expect_err("link exists"); + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + assert_eq!(fs::read_link(&link).expect("read link"), expected); +} + +#[test] +fn a_symlink_to_a_directory_lists_the_directory() { + let directory = TempDir::new("lithe symlink directory"); + let target = directory.path().join("shared"); + fs::create_dir(&target).expect("target"); + fs::write(target.join("inner.txt"), "inner").expect("inner"); + let link = directory.path().join("link"); + match create_symlink(Path::new("shared"), &link) { + Ok(()) => {} + Err(error) if links_refused(&error) => return, + Err(error) => panic!("link: {error}"), + } + assert!(fs::metadata(&link).expect("followed").is_dir()); + assert_eq!( + fs::read_to_string(link.join("inner.txt")).expect("through link"), + "inner" + ); +} diff --git a/rust/crates/platform-tests/tests/platform/main.rs b/rust/crates/platform-tests/tests/platform/main.rs index 8de6c9a5..9463ff27 100644 --- a/rust/crates/platform-tests/tests/platform/main.rs +++ b/rust/crates/platform-tests/tests/platform/main.rs @@ -4,6 +4,7 @@ //! dependencies are built once. mod askpass; +mod entries; mod git_executable; mod lsp_process; mod permissions; diff --git a/rust/crates/platform/Cargo.toml b/rust/crates/platform/Cargo.toml index 4cc86e5e..8b039632 100644 --- a/rust/crates/platform/Cargo.toml +++ b/rust/crates/platform/Cargo.toml @@ -3,14 +3,19 @@ name = "lithe-platform" version = "0.1.0" edition = "2021" license = "Apache-2.0" -description = "Host platform rules as data: path comparison, Windows file names, Unix permissions, Unix socket peers and console-less processes" +description = "Host platform rules as data: path comparison, Windows file names, Unix permissions, no-replace renames, symbolic links, Unix socket peers and console-less processes" [dependencies] -# Only the Unix socket peer checks need a system call that std does not wrap. +# The Unix socket peer checks and the no-replace rename need system calls +# that std does not wrap. [target.'cfg(unix)'.dependencies] libc = "0.2" +# The no-replace rename calls MoveFileExW, which std does not wrap. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + # Its tests check `Platform::HOST` against the host they run on, so CI also # runs them on macOS and Windows (scripts/rust-core/affected-crates.mjs). [package.metadata.lithe-ci] diff --git a/rust/crates/platform/src/entries.rs b/rust/crates/platform/src/entries.rs new file mode 100644 index 00000000..8a4f9906 --- /dev/null +++ b/rust/crates/platform/src/entries.rs @@ -0,0 +1,156 @@ +//! File-system changes whose system calls differ between hosts. +//! +//! `std::fs::rename` replaces an existing target on every host, and std +//! creates a symbolic link through a different function on Unix and Windows. +//! Callers that must never overwrite a file, or that create a link a user +//! asked for, call these instead of repeating a `cfg` branch. + +use std::io; +use std::path::Path; +#[cfg(windows)] +use std::path::PathBuf; + +/// Renames `from` to `to`, failing with [`io::ErrorKind::AlreadyExists`] +/// instead of replacing an entry already at `to`. +/// +/// macOS and Linux make the check and the rename one system call. On volumes +/// that refuse that call, such as SMB or FAT mounts and Linux kernels before +/// 3.15, the check and the rename are separate calls, so an entry created at +/// `to` between them can still be replaced. Windows never replaces without a +/// flag asking for it. +pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { + host_rename_no_replace(from, to) +} + +#[cfg(target_os = "macos")] +fn host_rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { + let from_c = c_path(from)?; + let to_c = c_path(to)?; + // SAFETY: both pointers reference NUL-terminated strings that outlive the + // call. + let status = unsafe { libc::renamex_np(from_c.as_ptr(), to_c.as_ptr(), libc::RENAME_EXCL) }; + if status == 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + match error.raw_os_error() { + // Volumes such as SMB or FAT mounts may not support RENAME_EXCL. + Some(libc::ENOTSUP) | Some(libc::EINVAL) => rename_if_absent(from, to), + _ => Err(error), + } +} + +/// `renameat2` is called through `syscall` because musl and older glibc +/// builds may lack the wrapper. +#[cfg(target_os = "linux")] +fn host_rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { + let from_c = c_path(from)?; + let to_c = c_path(to)?; + // SAFETY: both pointers reference NUL-terminated strings that outlive the + // call; the remaining arguments are plain integers. + let status = unsafe { + libc::syscall( + libc::SYS_renameat2, + libc::AT_FDCWD, + from_c.as_ptr(), + libc::AT_FDCWD, + to_c.as_ptr(), + libc::RENAME_NOREPLACE, + ) + }; + if status == 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + match error.raw_os_error() { + // Kernels before 3.15 lack the call; some filesystems reject the flag. + Some(libc::ENOSYS) | Some(libc::EINVAL) => rename_if_absent(from, to), + _ => Err(error), + } +} + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))] +fn host_rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { + rename_if_absent(from, to) +} + +/// `MoveFileExW` without `MOVEFILE_REPLACE_EXISTING` fails when `to` +/// exists, and without `MOVEFILE_COPY_ALLOWED` never copies across volumes. +#[cfg(windows)] +fn host_rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { + use windows_sys::Win32::Storage::FileSystem::MoveFileExW; + let from_w = wide_path(from); + let to_w = wide_path(to); + // SAFETY: both pointers reference NUL-terminated UTF-16 strings that + // outlive the call. + if unsafe { MoveFileExW(from_w.as_ptr(), to_w.as_ptr(), 0) } != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +/// The check and the rename are separate calls, so an entry created at `to` +/// between them can still be replaced. +#[cfg(unix)] +fn rename_if_absent(from: &Path, to: &Path) -> io::Result<()> { + match std::fs::symlink_metadata(to) { + Ok(_) => Err(io::Error::from(io::ErrorKind::AlreadyExists)), + Err(error) if error.kind() == io::ErrorKind::NotFound => std::fs::rename(from, to), + Err(error) => Err(error), + } +} + +#[cfg(any(target_os = "macos", target_os = "linux"))] +fn c_path(path: &Path) -> io::Result { + use std::os::unix::ffi::OsStrExt; + std::ffi::CString::new(path.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL")) +} + +#[cfg(windows)] +fn wide_path(path: &Path) -> Vec { + use std::os::windows::ffi::OsStrExt; + path.as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect() +} + +/// Creates a symbolic link at `link` that stores `target` as given: absolute, +/// or relative to the directory that holds `link`. The target need not exist. +/// An entry already at `link` fails with [`io::ErrorKind::AlreadyExists`]. +/// +/// Windows stores a file link and a directory link differently and follows +/// a relative target only through `\`. There the link is a directory link +/// when `target` names an existing directory at creation, otherwise a file +/// link, and each `/` in `target` is stored as `\`. Windows refuses to create +/// a link unless Developer Mode is on or the process runs elevated; that +/// refusal is returned as the system reports it. +pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> { + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link) + } + #[cfg(windows)] + { + let target = windows_link_target(target); + let resolved = match link.parent() { + Some(parent) if target.is_relative() => parent.join(&target), + _ => target.clone(), + }; + if std::fs::metadata(resolved).is_ok_and(|metadata| metadata.is_dir()) { + std::os::windows::fs::symlink_dir(&target, link) + } else { + std::os::windows::fs::symlink_file(&target, link) + } + } +} + +#[cfg(windows)] +fn windows_link_target(target: &Path) -> PathBuf { + match target.to_str() { + Some(text) => PathBuf::from(text.replace('/', "\\")), + None => target.to_path_buf(), + } +} diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs index 17b82dea..26f0b256 100644 --- a/rust/crates/platform/src/lib.rs +++ b/rust/crates/platform/src/lib.rs @@ -12,6 +12,7 @@ //! host to observe them live in the `lithe-platform-tests` package. pub mod cli; +pub mod entries; pub mod fs; pub mod names; pub mod paths; diff --git a/rust/crates/platform/src/paths.rs b/rust/crates/platform/src/paths.rs index 18628e67..98f440b5 100644 --- a/rust/crates/platform/src/paths.rs +++ b/rust/crates/platform/src/paths.rs @@ -82,6 +82,24 @@ pub fn invalid_relative_path(value: &str, platform: Platform) -> bool { }) } +/// Whether `/`-separated `value` fails to name one entry below a root on +/// `platform` in exactly one spelling. +/// +/// It fails [`invalid_relative_path`], or a component is empty or `.`, so +/// `a//b`, `./a` and `a/` are refused instead of read as `a/b` and `a`. On +/// Windows each component must also be a name Windows stores as written +/// ([`crate::names::is_portable_windows_component`]): a device name or a +/// trailing `.` or space would name another file than the one asked for. +pub fn invalid_entry_path(value: &str, platform: Platform) -> bool { + invalid_relative_path(value, platform) + || value.split('/').any(|component| { + component.is_empty() + || component == "." + || (platform.is_windows() + && !crate::names::is_portable_windows_component(component)) + }) +} + /// [`invalid_relative_path`] for native text, such as a path a user typed, /// that may spell `platform`'s own separators. pub fn invalid_native_relative_path(value: &str, platform: Platform) -> bool { @@ -160,13 +178,38 @@ pub fn native_path_from_bytes(bytes: &[u8]) -> Option<&Path> { #[cfg(test)] mod tests { use super::{ - invalid_native_relative_path, invalid_portable_relative_path, invalid_relative_path, - is_absolute_path, is_separator, join_native, native_path_from_bytes, path_list_separator, - relative_path_contains, slash_separated, slash_separated_path, + invalid_entry_path, invalid_native_relative_path, invalid_portable_relative_path, + invalid_relative_path, is_absolute_path, is_separator, join_native, native_path_from_bytes, + path_list_separator, relative_path_contains, slash_separated, slash_separated_path, }; use crate::Platform; use std::path::Path; + #[test] + fn an_entry_path_has_one_spelling() { + for platform in Platform::ALL { + for valid in ["a", "a/b.txt", ".gitignore", "a/..b", "a b/c"] { + assert!(!invalid_entry_path(valid, platform), "{valid} {platform:?}"); + } + for invalid in ["", "/a", "a//b", "./a", "a/.", "a/", "a/../b", "..", "a\0b"] { + assert!( + invalid_entry_path(invalid, platform), + "{invalid} {platform:?}" + ); + } + } + for windows_only in [r"a\b", "c:x", "CON", "nul.txt", "a/b.", "a /b", "a|b"] { + assert!( + invalid_entry_path(windows_only, Platform::Windows), + "{windows_only}" + ); + assert!( + !invalid_entry_path(windows_only, Platform::Unix), + "{windows_only}" + ); + } + } + #[test] fn the_root_contains_every_path() { for platform in [Platform::Unix, Platform::Windows] { diff --git a/rust/crates/plugin-rpc/Cargo.toml b/rust/crates/plugin-rpc/Cargo.toml index 0fc8714a..762475c4 100644 --- a/rust/crates/plugin-rpc/Cargo.toml +++ b/rust/crates/plugin-rpc/Cargo.toml @@ -6,6 +6,8 @@ license = "Apache-2.0" description = "Plugin backend JSON-RPC: litheFunctions negotiation, function calls, the host-method and host-notification catalog and its grants" [dependencies] +# Resource paths of file changes are checked with the host's file-name rules. +lithe-platform = { path = "../platform" } lithe-plugin-keymap-import = { path = "../plugin-keymap-import" } lithe-plugin-language-servers = { path = "../plugin-language-servers" } lithe-plugin-model = { path = "../plugin-model" } diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 488d8b57..680cfd34 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -67,6 +67,12 @@ pub(crate) fn check_host_params( &["context", "serverID", "state", "message", "percentage"] } HostParams::ContentProvider => &["context", "scheme", "function"], + HostParams::DocumentSave => &["context", "documentID", "expectedVersion"], + HostParams::DocumentSaveAs => &["context", "documentID", "target"], + HostParams::DocumentClose => &["context", "documentID"], + HostParams::WorkspaceCreate => &["context", "resource", "kind", "text", "linkTarget"], + HostParams::WorkspaceMove => &["context", "resource", "target"], + HostParams::WorkspaceTrash => &["context", "resource"], HostParams::Object => { return match params.get("context") { Some(context) if !is_context_reference(context) => { @@ -249,11 +255,150 @@ pub(crate) fn check_host_params( )); } } + HostParams::DocumentSave + | HostParams::DocumentSaveAs + | HostParams::DocumentClose + | HostParams::WorkspaceCreate + | HostParams::WorkspaceMove + | HostParams::WorkspaceTrash => check_file_change_params(rule, params, &invalid)?, HostParams::Empty | HostParams::Object => {} } Ok(()) } +/// Most UTF-8 bytes of `text` that `workspace/create` writes, the same +/// bound as a document snapshot, so the request stays well under the 1 MiB +/// limit after JSON escaping. +pub const MAX_CREATED_FILE_TEXT_BYTES: usize = 128 * 1024; + +/// Most bytes of a resource path or a symbolic link's target. +pub const MAX_FILE_CHANGE_PATH_BYTES: usize = 4096; + +const RESOURCE_MESSAGE: &str = "A resource is exactly {rootID, path}: a root ID of 1-128 ASCII letters, digits, '.', '_', ':' or '-', and a '/'-separated path of up to 4096 bytes below the root with no empty, '.' or '..' component."; + +/// The `{rootID, path}` at `key`, or `None` when it is malformed. The root +/// itself (`path: ""`) is malformed: no file change creates, moves or +/// trashes a root. +fn entry_resource<'a>( + params: &'a serde_json::Map, + key: &str, +) -> Option<(&'a str, &'a str)> { + let resource = params.get(key)?.as_object()?; + if resource.len() != 2 { + return None; + } + let root_id = resource.get("rootID")?.as_str()?; + let path = resource.get("path")?.as_str()?; + (is_credential_key(root_id) + && path.len() <= MAX_FILE_CHANGE_PATH_BYTES + && !lithe_platform::paths::invalid_entry_path(path, lithe_platform::Platform::HOST)) + .then_some((root_id, path)) +} + +/// Checks the params of the API-11 saves and file changes, so a host acts +/// only on a document ID, one root's paths it can name in one spelling, and +/// a `kind` with the fields that kind takes. Whether the document, root and +/// paths exist is the host's answer. +fn check_file_change_params( + rule: HostParams, + params: &serde_json::Map, + invalid: &dyn Fn(&'static str) -> HostRequestRefusal, +) -> Result<(), HostRequestRefusal> { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + if matches!( + rule, + HostParams::DocumentSave | HostParams::DocumentSaveAs | HostParams::DocumentClose + ) { + if !params + .get("documentID") + .and_then(Value::as_str) + .is_some_and(|id| !id.is_empty()) + { + return Err(invalid("documentID must name an open document.")); + } + if params + .get("expectedVersion") + .is_some_and(|version| version.as_u64().is_none()) + { + return Err(invalid("expectedVersion is a whole number.")); + } + if rule == HostParams::DocumentSaveAs && entry_resource(params, "target").is_none() { + return Err(invalid(RESOURCE_MESSAGE)); + } + return Ok(()); + } + let Some((root_id, path)) = entry_resource(params, "resource") else { + return Err(invalid(RESOURCE_MESSAGE)); + }; + match rule { + HostParams::WorkspaceMove => { + let Some((target_root_id, target)) = entry_resource(params, "target") else { + return Err(invalid(RESOURCE_MESSAGE)); + }; + if target_root_id != root_id { + return Err(invalid("The target must be in the resource's root.")); + } + if target + .strip_prefix(path) + .is_some_and(|rest| rest.starts_with('/')) + { + return Err(invalid("The target cannot be inside the resource.")); + } + } + HostParams::WorkspaceCreate => { + let kind = params.get("kind").and_then(Value::as_str); + let text = params.get("text"); + let link_target = params.get("linkTarget"); + match kind { + Some("file") => { + if link_target.is_some() { + return Err(invalid("Only a symlink takes linkTarget.")); + } + match text { + None => {} + Some(Value::String(text)) if text.len() <= MAX_CREATED_FILE_TEXT_BYTES => {} + Some(Value::String(_)) => { + return Err(HostRequestRefusal { + rpc_code: host_rpc_code(codes::HOST_LIMIT_EXCEEDED), + code: codes::HOST_LIMIT_EXCEEDED, + message: "text is over 128 KiB of UTF-8.", + details: Some( + json!({ "maximumBytes": MAX_CREATED_FILE_TEXT_BYTES }), + ), + }); + } + Some(_) => return Err(invalid("text must be a string.")), + } + } + Some("directory") => { + if text.is_some() || link_target.is_some() { + return Err(invalid("A directory takes neither text nor linkTarget.")); + } + } + Some("symlink") => { + if text.is_some() { + return Err(invalid("Only a file takes text.")); + } + if !link_target.and_then(Value::as_str).is_some_and(|target| { + !target.is_empty() + && target.len() <= MAX_FILE_CHANGE_PATH_BYTES + && !target.contains('\0') + }) { + return Err(invalid( + "A symlink takes linkTarget: 1-4096 bytes without NUL.", + )); + } + } + _ => return Err(invalid("kind is file, directory or symlink.")), + } + } + _ => {} + } + Ok(()) +} + /// Checks the params the `languageServer` host methods share: the context, /// the server, the method, and each method's own fields. Whether the server /// belongs to the plugin and the method is declared is the engine's answer, diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index 6914ea5b..bc35c34a 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -62,6 +62,21 @@ pub(crate) enum HostParams { FunctionProviders, /// `{ pluginID, functionID, context, params?, timeoutMilliseconds? }`. FunctionInvoke, + /// `{ context, documentID, expectedVersion? }` (plan API-11). + DocumentSave, + /// `{ context, documentID, target }`: a save to a new file of the same + /// root's files (plan API-11). + DocumentSaveAs, + /// `{ context, documentID }` (plan API-11). + DocumentClose, + /// `{ context, resource, kind, text?, linkTarget? }`: a new file, + /// directory or symbolic link below a root (plan API-11). + WorkspaceCreate, + /// `{ context, resource, target }`: a rename or copy within one root + /// (plan API-11). + WorkspaceMove, + /// `{ context, resource }`: a move to the system trash (plan API-11). + WorkspaceTrash, /// Any object whose `context`, when present, is a well-formed /// reference. The service checks the rest and answers /// `plugin.host.invalidParams` or, for a field it does not know, @@ -272,25 +287,25 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ method: "lithe/host/workspace/create", service: "workspace", permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), - params: HostParams::Object, + params: HostParams::WorkspaceCreate, }, HostMethod { method: "lithe/host/workspace/rename", service: "workspace", permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), - params: HostParams::Object, + params: HostParams::WorkspaceMove, }, HostMethod { method: "lithe/host/workspace/copy", service: "workspace", permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), - params: HostParams::Object, + params: HostParams::WorkspaceMove, }, HostMethod { method: "lithe/host/workspace/trash", service: "workspace", permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), - params: HostParams::Object, + params: HostParams::WorkspaceTrash, }, HostMethod { method: "lithe/host/documents/list", @@ -310,19 +325,19 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ method: "lithe/host/documents/save", service: "documents", permission: Some(PERMISSION_DOCUMENTS_SAVE), - params: HostParams::Object, + params: HostParams::DocumentSave, }, HostMethod { method: "lithe/host/documents/saveAs", service: "documents", permission: Some(PERMISSION_DOCUMENTS_SAVE), - params: HostParams::Object, + params: HostParams::DocumentSaveAs, }, HostMethod { method: "lithe/host/documents/close", service: "documents", permission: Some(PERMISSION_DOCUMENTS_SAVE), - params: HostParams::Object, + params: HostParams::DocumentClose, }, HostMethod { method: "lithe/host/editor/registerActions", diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 395e1c61..9b41d1cd 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -890,6 +890,212 @@ mod tests { /// Saving and file changes are method grants of their own (plan /// API-11): a session granted the `workspace` service, or only reading, /// never writes, and each new failure code has a number of its own. + fn file_change_refusal(method: &str, params: Value) -> Option<&'static str> { + let granted = BTreeSet::from([method.to_string()]); + host_request(method, Some(¶ms), Some(0), &granted) + .err() + .map(|refusal| refusal.code) + } + + #[test] + fn file_changes_name_one_spelling_of_one_root() { + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let create = "lithe/host/workspace/create"; + let with_path = |path: &str| json!({ "context": context, "resource": { "rootID": "r0", "path": path }, "kind": "directory" }); + for path in ["src", "src/main.rs", ".config/a b"] { + assert_eq!(file_change_refusal(create, with_path(path)), None, "{path}"); + } + let too_long = "a/".repeat(2048) + "b"; + for path in [ + "", + "/a", + "a//b", + "./a", + "a/", + "a/../b", + "..", + too_long.as_str(), + ] { + assert_eq!( + file_change_refusal(create, with_path(path)), + Some(codes::HOST_INVALID_PARAMS), + "{path}" + ); + } + for resource in [ + json!({ "rootID": "r0" }), + json!({ "rootID": "", "path": "a" }), + json!({ "rootID": "r0", "path": "a", "extra": true }), + json!("r0/a"), + ] { + assert_eq!( + file_change_refusal( + create, + json!({ "context": context, "resource": resource, "kind": "directory" }) + ), + Some(codes::HOST_INVALID_PARAMS), + "{resource}" + ); + } + assert_eq!( + file_change_refusal( + "lithe/host/workspace/trash", + json!({ "resource": { "rootID": "r0", "path": "a" } }) + ), + Some(codes::HOST_INVALID_PARAMS) + ); + assert_eq!( + file_change_refusal( + "lithe/host/workspace/trash", + json!({ "context": context, "resource": { "rootID": "r0", "path": "a" }, "permanent": true }) + ), + Some(codes::HOST_UNSUPPORTED_OPTION) + ); + } + + #[test] + fn a_move_stays_in_its_root_and_outside_its_source() { + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let resource = json!({ "rootID": "r0", "path": "src" }); + for method in ["lithe/host/workspace/rename", "lithe/host/workspace/copy"] { + let moving = |target: Value| json!({ "context": context, "resource": resource, "target": target }); + for path in ["lib", "src2", "source/src", "SRC"] { + assert_eq!( + file_change_refusal(method, moving(json!({ "rootID": "r0", "path": path }))), + None, + "{method} {path}" + ); + } + // The same path is the disk's `alreadyExists`, not malformed. + assert_eq!( + file_change_refusal(method, moving(json!({ "rootID": "r0", "path": "src" }))), + None + ); + for target in [ + json!({ "rootID": "r0", "path": "src/inner" }), + json!({ "rootID": "r1", "path": "lib" }), + json!({ "rootID": "r0", "path": "" }), + ] { + assert_eq!( + file_change_refusal(method, moving(target.clone())), + Some(codes::HOST_INVALID_PARAMS), + "{method} {target}" + ); + } + assert_eq!( + file_change_refusal(method, json!({ "context": context, "resource": resource })), + Some(codes::HOST_INVALID_PARAMS) + ); + } + } + + #[test] + fn a_created_entry_takes_the_fields_of_its_kind() { + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let create = |fields: Value| { + let mut params = + json!({ "context": context, "resource": { "rootID": "r0", "path": "a" } }); + for (key, value) in fields.as_object().expect("fields") { + params[key] = value.clone(); + } + file_change_refusal("lithe/host/workspace/create", params) + }; + for fields in [ + json!({ "kind": "file" }), + json!({ "kind": "file", "text": "" }), + json!({ "kind": "file", "text": "x".repeat(MAX_CREATED_FILE_TEXT_BYTES) }), + json!({ "kind": "directory" }), + json!({ "kind": "symlink", "linkTarget": "../outside/file.txt" }), + json!({ "kind": "symlink", "linkTarget": "/absolute/path" }), + ] { + assert_eq!(create(fields.clone()), None, "{fields}"); + } + for fields in [ + json!({}), + json!({ "kind": "hardlink" }), + json!({ "kind": "file", "text": 1 }), + json!({ "kind": "file", "linkTarget": "x" }), + json!({ "kind": "directory", "text": "" }), + json!({ "kind": "directory", "linkTarget": "x" }), + json!({ "kind": "symlink" }), + json!({ "kind": "symlink", "linkTarget": "" }), + json!({ "kind": "symlink", "linkTarget": "a\u{0}b" }), + json!({ "kind": "symlink", "linkTarget": "x".repeat(MAX_FILE_CHANGE_PATH_BYTES + 1) }), + json!({ "kind": "symlink", "linkTarget": "x", "text": "" }), + ] { + assert_eq!( + create(fields.clone()), + Some(codes::HOST_INVALID_PARAMS), + "{fields}" + ); + } + let oversized = "x".repeat(MAX_CREATED_FILE_TEXT_BYTES + 1); + let granted = BTreeSet::from(["lithe/host/workspace/create".to_string()]); + let refusal = host_request( + "lithe/host/workspace/create", + Some(&json!({ "context": context, "resource": { "rootID": "r0", "path": "a" }, "kind": "file", "text": oversized })), + Some(0), + &granted, + ) + .unwrap_err(); + assert_eq!(refusal.code, codes::HOST_LIMIT_EXCEEDED); + assert_eq!(refusal.rpc_code, host_rpc_code(codes::HOST_LIMIT_EXCEEDED)); + } + + #[test] + fn a_save_names_a_document_and_save_as_a_new_path() { + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let save = "lithe/host/documents/save"; + let save_as = "lithe/host/documents/saveAs"; + let close = "lithe/host/documents/close"; + let target = json!({ "rootID": "r0", "path": "copy.txt" }); + for (method, params) in [ + (save, json!({ "context": context, "documentID": "d1" })), + ( + save, + json!({ "context": context, "documentID": "d1", "expectedVersion": 4 }), + ), + ( + save_as, + json!({ "context": context, "documentID": "d1", "target": target }), + ), + (close, json!({ "context": context, "documentID": "d1" })), + ] { + assert_eq!( + file_change_refusal(method, params.clone()), + None, + "{method} {params}" + ); + } + for (method, params) in [ + (save, json!({ "context": context })), + (save, json!({ "context": context, "documentID": "" })), + ( + save, + json!({ "context": context, "documentID": "d1", "expectedVersion": -1 }), + ), + (save_as, json!({ "context": context, "documentID": "d1" })), + ( + save_as, + json!({ "context": context, "documentID": "d1", "target": { "rootID": "r0", "path": "../x" } }), + ), + (close, json!({ "documentID": "d1" })), + ] { + assert_eq!( + file_change_refusal(method, params.clone()), + Some(codes::HOST_INVALID_PARAMS), + "{method} {params}" + ); + } + assert_eq!( + file_change_refusal( + close, + json!({ "context": context, "documentID": "d1", "force": true }) + ), + Some(codes::HOST_UNSUPPORTED_OPTION) + ); + } + #[test] fn saves_and_file_changes_are_method_grants_of_their_own() { assert_eq!( @@ -911,13 +1117,21 @@ mod tests { ] ); let context = json!({ "contextID": "w-3f2a", "generation": 2 }); - let params = json!({ "context": context, "resource": { "rootID": "r0", "path": "a.txt" } }); + let resource = json!({ "rootID": "r0", "path": "a.txt" }); + let target = json!({ "rootID": "r0", "path": "b.txt" }); let reading = BTreeSet::from([ HOST_SERVICE_WORKSPACE.to_string(), "lithe/host/workspace/readFile".to_string(), ]); for method in &writes { assert!(is_host_grant(method), "{method}"); + let params = match *method { + "lithe/host/workspace/create" => { + json!({ "context": context, "resource": resource, "kind": "file" }) + } + "lithe/host/workspace/trash" => json!({ "context": context, "resource": resource }), + _ => json!({ "context": context, "resource": resource, "target": target }), + }; assert_eq!( host_request(method, Some(¶ms), Some(0), &reading) .unwrap_err() diff --git a/rust/crates/project/src/file_changes.rs b/rust/crates/project/src/file_changes.rs new file mode 100644 index 00000000..7da1804b --- /dev/null +++ b/rust/crates/project/src/file_changes.rs @@ -0,0 +1,449 @@ +//! Creating, renaming and copying entries below a workspace root. +//! +//! A host asks for these changes on a plugin's behalf (plan API-11), so +//! every one is bounded the same way on every host: +//! +//! - **One spelling of one root.** A path is `/`-separated and names an entry +//! below the root without empty, `.` or `..` components +//! ([`invalid_entry_path`]). The directory that holds the entry must exist +//! and resolve inside the root; an entry is never created through a link +//! that leaves it. +//! - **The last component is not followed.** A symbolic link is renamed or +//! copied as a link, never as the entry it points to, and a copied +//! directory keeps the links inside it as links. +//! - **Nothing is replaced.** A target that exists fails with +//! [`ErrorCode::EntryExists`]. A rename that changes only the case of a name +//! on a file system that ignores case is not a collision. +//! +//! The host keeps what only it owns: resolving a plugin's context to a root, +//! saving and moving the open documents under an entry, refreshing its views, +//! and moving entries to the system trash. Each command answers with the +//! entry's path below the root, its `fullPath` spelled from the root the host +//! sent, which is how the host's open documents name it, and its kind. +//! +//! Only local file systems are served; hosts refuse remote contexts before +//! asking. + +use lithe_platform::entries::{create_symlink, rename_no_replace}; +use lithe_platform::paths::invalid_entry_path; +use lithe_platform::Platform; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::fs::{self, Metadata, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +const COPY_FAILED: &str = "Could not copy the entry"; + +#[derive(Clone, Copy, Deserialize)] +#[serde(rename_all = "camelCase")] +enum EntryKind { + File, + Directory, + Symlink, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Create one file, directory or symbolic link (`workspace.createEntry`). +struct CreateEntryRequest { + root: String, + path: String, + kind: EntryKind, + /// The new file's UTF-8 text; files only, empty when absent. + #[serde(default)] + text: Option, + /// What the new link stores; symbolic links only. + #[serde(default)] + link_target: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Rename or copy one entry to a new path of the same root. +struct MoveEntryRequest { + root: String, + path: String, + target: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Name one existing entry (`workspace.resolveEntry`). +struct ResolveEntryRequest { + root: String, + path: String, +} + +/// The root the host sent and the directory it resolves to. +struct Root { + given: PathBuf, + canonical: PathBuf, +} + +/// An entry below a root whose parent directory exists inside the root. +struct Entry { + /// The request's `/`-separated path below the root. + relative: String, + /// The path spelled from the root the host sent. + full: PathBuf, + /// The entry in its resolved parent; the last component is not followed. + resolved: PathBuf, + /// The parent directory, resolved. + parent: PathBuf, +} + +impl Entry { + fn result(&self, kind: &str) -> Value { + json!({ + "path": self.relative, + "fullPath": self.full.to_string_lossy(), + "kind": kind, + }) + } + + fn name(&self) -> &std::ffi::OsStr { + self.resolved + .file_name() + .expect("an entry path has a last component") + } +} + +fn decode Deserialize<'de>>(payload: Value) -> Result { + serde_json::from_value(payload).map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid file change request") + .with_details(error.to_string()) + }) +} + +fn root(value: &str) -> Result { + let given = PathBuf::from(value); + if !given.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Workspace root must be an absolute path", + )); + } + let canonical = fs::canonicalize(&given).map_err(|error| match error.kind() { + io::ErrorKind::NotFound => { + CoreError::new(ErrorCode::WorkspaceNotFound, "Workspace does not exist") + } + _ => CoreError::new(ErrorCode::Unknown, "Could not open the workspace") + .with_details(error.to_string()), + })?; + if !canonical.is_dir() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Workspace root must be a directory", + )); + } + Ok(Root { given, canonical }) +} + +fn entry(root: &Root, path: &str) -> Result { + if invalid_entry_path(path, Platform::HOST) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Path must name an entry below the workspace root", + )); + } + let components: Vec<&str> = path.split('/').collect(); + let (name, parents) = components + .split_last() + .expect("a valid entry path has a component"); + let unresolved = parents + .iter() + .fold(root.canonical.clone(), |path, part| path.join(part)); + let parent = fs::canonicalize(&unresolved).map_err(|error| match error.kind() { + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => missing_parent(), + _ => failure("Could not open the entry's directory", &error), + })?; + if !parent.starts_with(&root.canonical) { + return Err(CoreError::new( + ErrorCode::PermissionDenied, + "Path is outside the workspace", + )); + } + if !parent.is_dir() { + return Err(missing_parent()); + } + Ok(Entry { + relative: path.to_string(), + full: components + .iter() + .fold(root.given.clone(), |path, part| path.join(part)), + resolved: parent.join(name), + parent, + }) +} + +fn missing_parent() -> CoreError { + CoreError::new( + ErrorCode::EntryNotFound, + "The directory that would hold the entry does not exist", + ) +} + +fn failure(message: &str, error: &io::Error) -> CoreError { + CoreError::new(ErrorCode::Unknown, message).with_details(error.to_string()) +} + +/// Maps a failure of the call that acts on the entry itself: an existing +/// target and a missing entry have codes of their own. A refusal by the +/// operating system is a failure, not [`ErrorCode::PermissionDenied`], +/// which says the path left the workspace. +fn entry_failure(message: &'static str) -> impl Fn(io::Error) -> CoreError { + move |error| match error.kind() { + io::ErrorKind::AlreadyExists => CoreError::new( + ErrorCode::EntryExists, + "An entry already exists at the target", + ), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => { + CoreError::new(ErrorCode::EntryNotFound, "The entry does not exist") + } + _ => failure(message, &error), + } +} + +/// `file`, `directory`, `symlink`, or `other` for a socket, pipe or device. +fn kind_name(metadata: &Metadata) -> &'static str { + let file_type = metadata.file_type(); + if file_type.is_symlink() { + "symlink" + } else if file_type.is_dir() { + "directory" + } else if file_type.is_file() { + "file" + } else { + "other" + } +} + +/// The entry at `entry` without following it. +fn existing(entry: &Entry) -> Result { + fs::symlink_metadata(&entry.resolved).map_err(entry_failure("Could not read the entry")) +} + +/// Creates one file, directory or symbolic link (`workspace.createEntry`). +/// +/// `{ root, path, kind, text?, linkTarget? }`: a file takes optional UTF-8 +/// `text`; a symbolic link takes the `linkTarget` it stores verbatim, which +/// may be absolute, relative to the link's directory, outside the root, or +/// missing (see [`create_symlink`] for Windows). Returns +/// `{ path, fullPath, kind }`. +pub fn create_entry_command(payload: Value) -> Result { + let request: CreateEntryRequest = decode(payload)?; + let fields_match = match request.kind { + EntryKind::File => request.link_target.is_none(), + EntryKind::Directory => request.text.is_none() && request.link_target.is_none(), + EntryKind::Symlink => { + request.text.is_none() + && request + .link_target + .as_deref() + .is_some_and(|target| !target.is_empty() && !target.contains('\0')) + } + }; + if !fields_match { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Only a file takes text, and only a symbolic link takes a non-empty linkTarget", + )); + } + let root = root(&request.root)?; + let entry = entry(&root, &request.path)?; + let created = match request.kind { + EntryKind::File => create_file( + &entry.resolved, + request.text.as_deref().unwrap_or_default().as_bytes(), + ), + EntryKind::Directory => fs::create_dir(&entry.resolved), + EntryKind::Symlink => create_symlink( + Path::new(request.link_target.as_deref().unwrap_or_default()), + &entry.resolved, + ), + }; + created.map_err(entry_failure("Could not create the entry"))?; + Ok(entry.result(match request.kind { + EntryKind::File => "file", + EntryKind::Directory => "directory", + EntryKind::Symlink => "symlink", + })) +} + +/// Writes a new file, removing it again when the write fails, so a failed +/// create leaves nothing behind. +fn create_file(path: &Path, bytes: &[u8]) -> io::Result<()> { + let mut file = OpenOptions::new().write(true).create_new(true).open(path)?; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + if written.is_err() { + drop(file); + let _ = fs::remove_file(path); + } + written +} + +/// The source and target of a rename or copy, after the checks both share. +fn move_entries(payload: Value) -> Result<(Entry, Entry, Metadata), CoreError> { + let request: MoveEntryRequest = decode(payload)?; + let root = root(&request.root)?; + let source = entry(&root, &request.path)?; + let target = entry(&root, &request.target)?; + let metadata = existing(&source)?; + // A link is moved as a link, so only a real directory can contain the + // target; its resolved path is then its canonical path. + if metadata.is_dir() && target.parent.starts_with(&source.resolved) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The target cannot be inside the entry", + )); + } + Ok((source, target, metadata)) +} + +/// Renames one entry to a new path of the same root +/// (`workspace.renameEntry`). +/// +/// `{ root, path, target }`. Fails with [`ErrorCode::EntryExists`] instead +/// of replacing an entry at `target`, except when `target` differs from +/// `path` only in case and the file system ignores case. Returns +/// `{ path, fullPath, kind }` of the target. A target that names the source +/// itself is an existing entry: macOS reports success for that rename and +/// Linux refuses it, so the kernel refuses it before asking either. +pub fn rename_entry_command(payload: Value) -> Result { + let (source, target, metadata) = move_entries(payload)?; + if source.resolved == target.resolved { + return Err(CoreError::new( + ErrorCode::EntryExists, + "An entry already exists at the target", + )); + } + let renamed = if changes_only_case(&source, &target) { + fs::rename(&source.resolved, &target.resolved) + } else { + rename_no_replace(&source.resolved, &target.resolved) + }; + renamed.map_err(entry_failure("Could not rename the entry"))?; + Ok(target.result(kind_name(&metadata))) +} + +/// Whether the rename only changes the case of the name on a file system +/// that ignores case: the target is found, yet no entry of the directory has +/// its exact name, so the name found is the source's own. Two names that +/// differ only in case cannot both exist there. +fn changes_only_case(source: &Entry, target: &Entry) -> bool { + if source.parent != target.parent || source.name() == target.name() { + return false; + } + let (Some(source_name), Some(target_name)) = (source.name().to_str(), target.name().to_str()) + else { + return false; + }; + if source_name.to_lowercase() != target_name.to_lowercase() + || fs::symlink_metadata(&target.resolved).is_err() + { + return false; + } + fs::read_dir(&target.parent).is_ok_and(|entries| { + !entries + .filter_map(Result::ok) + .any(|entry| entry.file_name() == target.name()) + }) +} + +/// Copies one entry to a new path of the same root (`workspace.copyEntry`). +/// +/// `{ root, path, target }`. A directory is copied with everything in it; +/// symbolic links stay links, and sockets, pipes and devices fail the copy. +/// Nothing at `target` is replaced, and a copy that fails part way removes +/// what it created. Returns `{ path, fullPath, kind }` of the copy. +pub fn copy_entry_command(payload: Value) -> Result { + let (source, target, metadata) = move_entries(payload)?; + copy_entry( + &source.resolved, + &target.resolved, + &metadata, + &entry_failure(COPY_FAILED), + )?; + Ok(target.result(kind_name(&metadata))) +} + +fn copy_failure(error: io::Error) -> CoreError { + failure(COPY_FAILED, &error) +} + +/// Creates `to` as a copy of `from`, which `metadata` describes without +/// following it. `create_failure` maps a failure to create `to` itself; +/// every later failure removes what this call created. +fn copy_entry( + from: &Path, + to: &Path, + metadata: &Metadata, + create_failure: &dyn Fn(io::Error) -> CoreError, +) -> Result<(), CoreError> { + lithe_protocol::cancellation::check()?; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + let link_target = fs::read_link(from).map_err(copy_failure)?; + return create_symlink(&link_target, to).map_err(create_failure); + } + if file_type.is_dir() { + fs::create_dir(to).map_err(create_failure)?; + let filled = copy_children(from, to) + .and_then(|()| fs::set_permissions(to, metadata.permissions()).map_err(copy_failure)); + if filled.is_err() { + let _ = fs::remove_dir_all(to); + } + return filled; + } + if file_type.is_file() { + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .open(to) + .map_err(create_failure)?; + let filled = fs::File::open(from) + .and_then(|mut input| io::copy(&mut input, &mut output)) + .and_then(|_| output.set_permissions(metadata.permissions())) + .map_err(copy_failure); + if filled.is_err() { + drop(output); + let _ = fs::remove_file(to); + } + return filled; + } + Err(CoreError::new( + ErrorCode::Unknown, + "Only files, directories and symbolic links can be copied", + ) + .with_details(from.display().to_string())) +} + +fn copy_children(from: &Path, to: &Path) -> Result<(), CoreError> { + for child in fs::read_dir(from).map_err(copy_failure)? { + let child = child.map_err(copy_failure)?; + // `DirEntry::metadata` does not follow a link on any host. + let metadata = child.metadata().map_err(copy_failure)?; + copy_entry( + &child.path(), + &to.join(child.file_name()), + &metadata, + ©_failure, + )?; + } + Ok(()) +} + +/// Names one existing entry without following it (`workspace.resolveEntry`). +/// +/// `{ root, path }`. Returns `{ path, fullPath, kind }`, so a host can save +/// the open documents under an entry or move it to the system trash by the +/// path the checks above admit. +pub fn resolve_entry_command(payload: Value) -> Result { + let request: ResolveEntryRequest = decode(payload)?; + let root = root(&request.root)?; + let entry = entry(&root, &request.path)?; + let metadata = existing(&entry)?; + Ok(entry.result(kind_name(&metadata))) +} diff --git a/rust/crates/project/src/lib.rs b/rust/crates/project/src/lib.rs index eaeb4817..256fad0f 100644 --- a/rust/crates/project/src/lib.rs +++ b/rust/crates/project/src/lib.rs @@ -11,6 +11,7 @@ pub mod directory_actions; mod document_lifecycle; pub mod document_save_batch; mod encoding; +pub mod file_changes; pub mod file_name_order; pub mod file_operations; pub mod files; diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 4f8c0e0b..5eafcf1e 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -65,6 +65,13 @@ pub enum ErrorCode { /// `file.write` text contains characters the requested encoding cannot /// represent; nothing is written and no character is substituted. EncodingUnmappable, + /// A `workspace.createEntry`, `renameEntry`, `copyEntry` or + /// `resolveEntry` path does not exist below its root, or the directory + /// that would hold its target does not. Nothing changed. + EntryNotFound, + /// A `workspace.createEntry`, `renameEntry` or `copyEntry` target already + /// exists. Nothing was replaced. + EntryExists, /// The caller cooperatively cancelled the operation. Cancelled, /// The operation exceeded its declared deadline. diff --git a/rust/crates/remote/src/server/platform/linux.rs b/rust/crates/remote/src/server/platform/linux.rs index 8077c238..669cd00d 100644 --- a/rust/crates/remote/src/server/platform/linux.rs +++ b/rust/crates/remote/src/server/platform/linux.rs @@ -44,34 +44,6 @@ pub(crate) fn prepare_child(command: &mut Command, kind: ChildKind) { } } -/// Atomic rename that fails when `to` exists. `renameat2` is called through -/// `syscall` because musl and older glibc builds may lack the wrapper. -pub(crate) fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { - let from_c = unix::c_path(from)?; - let to_c = unix::c_path(to)?; - // SAFETY: both pointers reference NUL-terminated strings that outlive the - // call; the remaining arguments are plain integers. - let status = unsafe { - libc::syscall( - libc::SYS_renameat2, - libc::AT_FDCWD, - from_c.as_ptr(), - libc::AT_FDCWD, - to_c.as_ptr(), - libc::RENAME_NOREPLACE, - ) - }; - if status == 0 { - return Ok(()); - } - let error = io::Error::last_os_error(); - match error.raw_os_error() { - // Kernels before 3.15 lack the call; some filesystems reject the flag. - Some(libc::ENOSYS) | Some(libc::EINVAL) => unix::rename_if_absent(from, to), - _ => Err(error), - } -} - pub(crate) fn case_sensitive(path: &Path) -> Option { unix::probe_case_sensitivity(path) } diff --git a/rust/crates/remote/src/server/platform/macos.rs b/rust/crates/remote/src/server/platform/macos.rs index 5c4411e8..138f45d7 100644 --- a/rust/crates/remote/src/server/platform/macos.rs +++ b/rust/crates/remote/src/server/platform/macos.rs @@ -33,23 +33,6 @@ pub(crate) fn prepare_child(command: &mut Command, kind: ChildKind) { } } -pub(crate) fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> { - let from_c = unix::c_path(from)?; - let to_c = unix::c_path(to)?; - // SAFETY: both pointers reference NUL-terminated strings that outlive the - // call. - let status = unsafe { libc::renamex_np(from_c.as_ptr(), to_c.as_ptr(), libc::RENAME_EXCL) }; - if status == 0 { - return Ok(()); - } - let error = io::Error::last_os_error(); - match error.raw_os_error() { - // Volumes such as SMB or FAT mounts may not support RENAME_EXCL. - Some(libc::ENOTSUP) | Some(libc::EINVAL) => unix::rename_if_absent(from, to), - _ => Err(error), - } -} - /// macOS hosts have no WSL, so no Windows interoperability. pub(crate) fn windows_interop() -> Option { None diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index 7cf3ad88..0ecf1c32 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -25,7 +25,10 @@ use macos as host; #[cfg(target_os = "macos")] pub(crate) use macos_watch as watcher; -pub(crate) use host::{case_sensitive, listening_ports, prepare_child, rename_no_replace}; +pub(crate) use host::{case_sensitive, listening_ports, prepare_child}; +// Every Lithe process that must not overwrite a file renames through the same +// no-replace call. +pub(crate) use lithe_platform::entries::rename_no_replace; // Linux and macOS read a socket peer through different calls; lithe-platform // keeps both for every Lithe process that checks who is on a Unix socket. pub(crate) use lithe_platform::socket::peer_uid; diff --git a/rust/crates/remote/src/server/platform/unix.rs b/rust/crates/remote/src/server/platform/unix.rs index 5139b4dc..42113fd3 100644 --- a/rust/crates/remote/src/server/platform/unix.rs +++ b/rust/crates/remote/src/server/platform/unix.rs @@ -175,17 +175,8 @@ fn swap_ascii_case(name: &OsStr) -> Vec { .collect() } -/// Fallback for hosts or filesystems without an atomic no-replace rename. -/// The check and the rename are separate calls, so a concurrent creation of -/// `to` can still be overwritten. -pub(crate) fn rename_if_absent(from: &Path, to: &Path) -> io::Result<()> { - match fs::symlink_metadata(to) { - Ok(_) => Err(io::Error::from(io::ErrorKind::AlreadyExists)), - Err(error) if error.kind() == io::ErrorKind::NotFound => fs::rename(from, to), - Err(error) => Err(error), - } -} - +/// Only macOS asks a volume about case through a path-taking system call. +#[cfg(target_os = "macos")] pub(crate) fn c_path(path: &Path) -> io::Result { std::ffi::CString::new(path.as_os_str().as_bytes()) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL")) diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 7dc93905..7073cda9 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4280,7 +4280,7 @@ methods. Unknown options fail before side effects with `unsupportedOption`. | `workspace/readFile` | `workspace.files.read` | `resource,maximumBytes?` | `{resource,source:"disk",byteCount,isTruncated,identity,text?,encoding?,base64?}` | | `workspace/watch` | `workspace.files.watch` | `resource,recursive?` (default false) | `{subscriptionID}`; events contain `{rootID,changedPaths,requiresRescan}` | | `workspace/findFiles` | `workspace.search` | `resource` naming the root (`path:""`), `query,fileMask?,cursor?,limit?` | `{matches:[],nextCursor,isTruncated,source:"disk"}` | -| `workspace/create` | `workspace.files.write` | `resource,kind` (`file` or `directory`), `text?` (files only) | `{resource,kind}`; never overwrites | +| `workspace/create` | `workspace.files.write` | `resource,kind` (`file`, `directory` or `symlink`), `text?` (files only), `linkTarget` (symlinks only) | `{resource,kind}`; never overwrites | | `workspace/rename` | `workspace.files.write` | `resource,target` | `{resource}` of the target; open documents follow | | `workspace/copy` | `workspace.files.write` | `resource,target` | `{resource}` of the copy; never overwrites | | `workspace/trash` | `workspace.files.write` | `resource` | `null` after moving it to the system trash | @@ -4365,22 +4365,35 @@ deadline, and a change that would need the user's choice is refused instead: | `documents/save` | `notFound` (no such document); `versionConflict` with `details.currentVersion` when `expectedVersion` is given and differs; `busy` (IME composition); `preconditionFailed` (an untitled document, which needs `saveAs`; a document with no file, such as a virtual one; a hard-linked file, whose save the user must choose); `diskChanged`; `failed` (the write failed; the user also sees the host's save-failed notice) | | `documents/saveAs` | `notFound` (no such document, or the target's parent directory does not exist); `alreadyExists`; `busy` (IME composition, or a save of the document is running); `failed` | | `documents/close` | the errors of `save`; `preconditionFailed` is not among them, since an untitled or virtual document closes without a write (an untitled document keeps its draft) | -| `workspace/create` | `notFound` (the parent directory does not exist); `alreadyExists`; `limitExceeded` (`text` is over 128 KiB of UTF-8); `failed` | +| `workspace/create` | `notFound` (the parent directory does not exist); `alreadyExists`; `limitExceeded` (`text` is over 128 KiB of UTF-8); `failed` (including a system that refuses to create a link, such as Windows without Developer Mode or administrator rights) | | `workspace/rename` | `notFound` (the resource or the target's parent); `alreadyExists`; `diskChanged`, `busy` or `failed` from saving an open document; `failed` | | `workspace/copy` | `notFound` (the resource or the target's parent); `alreadyExists`; `failed` | | `workspace/trash` | `notFound`; `diskChanged`, `busy` or `failed` from saving an open document; `failed` (the system trash refused the item) | Paths: `resource` and `target` are `{rootID,path}` resources of one root, and -`target` is the full new path, not a directory to move into. The root itself -(`path:""`) cannot be created, renamed, copied or trashed, and a target inside -its own source is refused; both are `invalidParams`. The target's parent must +`target` is the full new path, not a directory to move into. A path has one +spelling: `/`-separated components, none empty, `.` or `..`, at most 4,096 +bytes, and on Windows none that Windows cannot store as written (a reserved +name such as `CON`, a trailing dot or space, or one of `\ : * ? " < > |`). +The root itself (`path:""`) cannot be created, renamed, copied or trashed, and +a target inside its own source is refused; these are `invalidParams`. The target's parent must exist; nothing creates missing directories. The host checks that the parent of each path resolves inside the root, and acts on the last component itself: a symbolic link is renamed, copied or trashed as a link, never as the file it points to. A copy keeps symbolic links inside a copied directory as links. `create` writes `text` as UTF-8, or makes an empty file; a directory takes no -`text`. It does not open the file; call `editor/open` for that. `saveAs` writes +`text`. It does not open the file; call `editor/open` for that. A symbolic link +takes `linkTarget`, 1 to 4,096 bytes without NUL, and no `text`; `linkTarget` on +a file or directory is `invalidParams`. The link stores `linkTarget` verbatim: +an absolute path, or one relative to the directory that holds the link, which +may lead outside the root or to nothing. Creating a link grants nothing: +`workspace/readFile`, listings and `editor/open` keep their own containment +checks, so a link to a file outside the root does not make that file readable, +and no file is ever created through a parent directory that leaves the root. +On Windows each `/` in `linkTarget` is stored as `\`, and the link is a +directory link when `linkTarget` names an existing directory at creation, +otherwise a file link. `saveAs` writes the document's current text as UTF-8 with its line endings, then opens the new file and selects it; the original document stays open and unchanged, except that an untitled document whose text did not change during the write closes, diff --git a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json index 47deab18..c34ed926 100644 --- a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json +++ b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json @@ -527,6 +527,9 @@ {"name": "a document read grant never authorizes a save", "version": 0, "hostServices": ["lithe/host/documents/getSnapshot"], "method": "lithe/host/documents/save", "params": {"context": {"contextID": "w1", "generation": 1}, "documentID": "d1"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, {"name": "the aggregate workspace grant never authorizes a file change", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/create", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "notes/a.md"}, "kind": "file"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, {"name": "a file change is forwarded with its own grant", "version": 0, "hostServices": ["lithe/host/workspace/rename"], "method": "lithe/host/workspace/rename", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "a.md"}, "target": {"rootID": "r0", "path": "b.md"}}, "expected": {"forward": "workspace"}}, + {"name": "a symbolic link is created with its target", "version": 0, "hostServices": ["lithe/host/workspace/create"], "method": "lithe/host/workspace/create", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "shared"}, "kind": "symlink", "linkTarget": "../shared"}, "expected": {"forward": "workspace"}}, + {"name": "a symbolic link without a target is invalid", "version": 0, "hostServices": ["lithe/host/workspace/create"], "method": "lithe/host/workspace/create", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "shared"}, "kind": "symlink"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a file change path has one spelling", "version": 0, "hostServices": ["lithe/host/workspace/create"], "method": "lithe/host/workspace/create", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "notes/./a.md"}, "kind": "file"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a declared caller lists the providers of a function", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/providers", "params": {"functionID": "languageImport.settings"}, "expected": {"relay": true}}, {"name": "a declared caller invokes another plugin's function through the relay", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000}, "expected": {"relay": true}}, {"name": "a nested invocation names the relayed call it belongs to", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000, "parentOperationID": "17"}, "expected": {"relay": true}}, diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index 4cf2b6fa..ec7fa860 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -196,7 +196,7 @@ | `documents/save`、`documents/saveAs`、`documents/close` | `documents.save` | 保存、另存为、关闭打开的文档;关闭前先保存,从不丢弃用户的修改 | | `workspace/readDirectory`、`workspace/stat`、`workspace/readFile` | `workspace.files.read` | 读磁盘上的目录和文件 | | `workspace/watch` | `workspace.files.watch` | 订阅文件变化,事件经 `subscriptions/notify` 送达 | -| `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash` | `workspace.files.write` | 新建文件或目录、重命名、复制、移到系统废纸篓;从不覆盖已有文件,也不永久删除 | +| `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash` | `workspace.files.write` | 新建文件、目录或符号链接,重命名、复制、移到系统废纸篓;从不覆盖已有文件,也不永久删除。符号链接原样保存目标路径,不会让根目录外的文件变得可读 | | `workspace/findFiles`、`workspace/findText` | `workspace.search` | 按文件名或内容搜索,分页返回 | | `editor/open`、`editor/reveal` | `editor.open` | 打开文件并定位到某处 | | `preview/openHTML` | `preview.open` | 用内置预览打开 HTML 文件 | @@ -526,7 +526,7 @@ The host opens a set of public methods, each group behind a permission. `getCapa | `documents/save`, `documents/saveAs`, `documents/close` | `documents.save` | Save, save as, and close an open document; a close saves first and never discards the user's edits | | `workspace/readDirectory`, `workspace/stat`, `workspace/readFile` | `workspace.files.read` | Read directories and files on disk | | `workspace/watch` | `workspace.files.watch` | Subscribe to file changes; events arrive through `subscriptions/notify` | -| `workspace/create`, `workspace/rename`, `workspace/copy`, `workspace/trash` | `workspace.files.write` | Create a file or directory, rename, copy, or move to the system trash; never overwrites a file or deletes permanently | +| `workspace/create`, `workspace/rename`, `workspace/copy`, `workspace/trash` | `workspace.files.write` | Create a file, directory or symbolic link, rename, copy, or move to the system trash; never overwrites a file or deletes permanently. A link stores its target as given and makes no file outside the root readable | | `workspace/findFiles`, `workspace/findText` | `workspace.search` | Search by file name or content, paged | | `editor/open`, `editor/reveal` | `editor.open` | Open a file and go to a location | | `preview/openHTML` | `preview.open` | Open an HTML file in the built-in preview | diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 741b5f16..8cf00e14 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -109,7 +109,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-11 | `documents/save` | 保存打开的文档,写入当前全部内容;可带 `expectedVersion`;文件在磁盘上变了时返回 `plugin.host.diskChanged`,不写入 | `documents.save` | 0 | | API-11 | `documents/saveAs` | 把文档当前内容写到一个不存在的新文件并打开它;目标已存在时返回 `plugin.host.alreadyExists` | `documents.save` | 0 | | API-11 | `documents/close` | 先保存再关闭文档的标签,从不丢弃修改 | `documents.save` | 0 | -| API-11 | `workspace/create` | 新建文件(可带不超过 128 KiB 的文本)或目录,不覆盖已有项 | `workspace.files.write` | 0 | +| API-11 | `workspace/create` | 新建文件(可带不超过 128 KiB 的文本)、目录或符号链接,不覆盖已有项 | `workspace.files.write` | 0 | | API-11 | `workspace/rename` | 重命名或移动文件、目录;先保存其下打开的文档,文档跟着文件走 | `workspace.files.write` | 0 | | API-11 | `workspace/copy` | 复制文件或目录到一个不存在的目标,符号链接保持为链接 | `workspace.files.write` | 0 | | API-11 | `workspace/trash` | 先保存并关闭其下打开的文档,再把文件或目录移到系统废纸篓;不永久删除 | `workspace.files.write` | 0 | @@ -292,7 +292,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-11 | `documents/save` | Saves an open document, writing all of its current text; takes an optional `expectedVersion`; when the file changed on disk it returns `plugin.host.diskChanged` and writes nothing | `documents.save` | 0 | | API-11 | `documents/saveAs` | Writes the document's current text to a new file that does not exist and opens it; an existing target returns `plugin.host.alreadyExists` | `documents.save` | 0 | | API-11 | `documents/close` | Saves the document, then closes its tab; never discards edits | `documents.save` | 0 | -| API-11 | `workspace/create` | Creates a file (optionally with at most 128 KiB of text) or a directory, never over an existing item | `workspace.files.write` | 0 | +| API-11 | `workspace/create` | Creates a file (optionally with at most 128 KiB of text), a directory or a symbolic link, never over an existing item | `workspace.files.write` | 0 | | API-11 | `workspace/rename` | Renames or moves a file or directory; saves the open documents under it first, and they follow the file | `workspace.files.write` | 0 | | API-11 | `workspace/copy` | Copies a file or directory to a target that does not exist, keeping symbolic links as links | `workspace.files.write` | 0 | | API-11 | `workspace/trash` | Saves and closes the open documents under the resource, then moves it to the system trash; never deletes permanently | `workspace.files.write` | 0 | diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index b45f37da..6099f64b 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -55,7 +55,7 @@ | 凭据 | `credentials/get`、`set`、`delete` | `credentials.store` | | 工作区上下文 | `workspace/listContexts`、`getContext`、`getFolders` | `workspace.metadata` | | 文件与搜索 | `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText` | `workspace.files.read`、`workspace.files.watch`、`workspace.search` | -| 文件变更 | `workspace/create`、`rename`、`copy`、`trash`:不覆盖已有项,删除只移到系统废纸篓,见[契约](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | +| 文件变更 | `workspace/create`(文件、目录或符号链接)、`rename`、`copy`、`trash`:不覆盖已有项,删除只移到系统废纸篓,见[契约](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | | 文档与编辑器 | `documents/*`、`editor/*`,见[编辑器](editor.md) | `documents.read`、`documents.save`、`editor.edit`、`editor.open`、`editor.actions`、`editor.providers` | | 预览、浏览器、窗口消息 | `preview/openHTML`、`browser/openExternal`、`window/*` | `preview.open`、`browser.open`、`window.messages` | | 原生终端 | `terminal/*` | `terminal.create` | @@ -277,7 +277,7 @@ A backend sends requests to the host with the prefix `lithe/host/`. Each service | Credentials | `credentials/get`, `set`, `delete` | `credentials.store` | | Workspace contexts | `workspace/listContexts`, `getContext`, `getFolders` | `workspace.metadata` | | Files and search | `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText` | `workspace.files.read`, `workspace.files.watch`, `workspace.search` | -| File changes | `workspace/create`, `rename`, `copy`, `trash`: never over an existing item, and a delete only moves to the system trash; see the [contract](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | +| File changes | `workspace/create` (a file, directory or symbolic link), `rename`, `copy`, `trash`: never over an existing item, and a delete only moves to the system trash; see the [contract](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | | Documents and editors | `documents/*`, `editor/*`; see [Editor](editor.md) | `documents.read`, `documents.save`, `editor.edit`, `editor.open`, `editor.actions`, `editor.providers` | | Preview, browser, window messages | `preview/openHTML`, `browser/openExternal`, `window/*` | `preview.open`, `browser.open`, `window.messages` | | Native terminals | `terminal/*` | `terminal.create` | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index ef5511eb..4a37b446 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 +- [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`create` 可以新建文件、目录或符号链接,链接原样保存 `linkTarget`,不放宽读取和打开的根目录检查;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径检查、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 - [#176](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/176),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`languageServers` 0 内的说明补充(—):写明后端决定启动方式的语言服务器在 `immediate` 设置变化时的行为。启动应答自带 `workspaceConfiguration` 时,宿主用这次启动的四个目录、工作区 `context` 和新的 `settings` 再调用一次启动函数,同样交给 `plugins.languageServers.decodeLaunch` 解码,只把计划里的 `workspaceConfiguration` 通过 `lsp.updateWorkspaceConfiguration` 发出(整体替换原配置),应答的其余部分等下次启动;应答不带时发送声明的展开,不再调用函数。所以这类启动函数每次启动可能被调用多次,安装或下载只应在缺少时进行。契约 README 的 Workspace configuration 和 Backend-resolved launch 两节、`reference/domains/languages.md` 与 `settings.md` 的中英文随之补充。桌面端实现见 1lck/Lithe-IDEA#2319。Core 代码、能力版本、宿主方法、通知和协议字段都不变。 - [#175](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/175),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`ui` 0 内的补充(API-13、API-23):撤回 #174 新增的 `ui` 1,设置区域 `tool` 行的可选布尔字段 `choose` 改为 `ui` 0 内的补充,清单写 `requires.ui: 0` 即可使用。`capabilities.rs` 和清单 schema 的 `requires.ui` 回到只有 0,能力对照表删去 `ui` 1 一行。`choose` 不是布尔值时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`;旧宿主的 Core 不认识这个字段,同样会拒绝带它的视图,所以插件要等包含本改动的桌面端发布后再写。fixture `ui/view-results.json` 改为两个用例(接受选择器、`choose` 不是布尔值时拒绝),替换原来“`requires.ui` 为 0 时拒绝”的用例。`ui` 1 没有随任何宿主发布过。没有新增能力版本、宿主方法、通知或进程协议字段。 - [#174](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/174),[@xiaoyumuxi](https://github.com/xiaoyumuxi),**`ui` 1**(API-13、API-23):设置区域视图的 `tool` 行新增可选的布尔字段 `choose`,带上后这一行同时是该工具的选择器,像解释器下拉框一样列出自动选择、已发现和已添加的安装(带版本和来源)、添加目录和打开工具链页的入口;选择只改设置窗口的草稿,“应用”提交、“取消”丢弃,行上显示待提交的选择,应用后启动和运行拿到选中的安装。清单 `requires.ui` 为 0 时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`。契约 README 的插件视图一节补充:为某个工作区显示的视图(项目窗口里的工具窗口,或从项目窗口打开的设置页)调用时,带上该窗口的工作区上下文作为 invoke 的 `params.context`,后端可以在 `click` 里用它调用 `run/start` 等需要上下文的宿主方法;没有工作区时不带。fixture `ui/view-results.json` 新增一个用例,Node SDK 的视图节点类型加上 `choose`,Rust 和 Go SDK 的工作区上下文说明随之修正。没有新增宿主方法、通知或进程协议字段。(`ui` 1 已由 #175 撤回,`choose` 改为 `ui` 0 内的补充。) @@ -123,13 +123,13 @@ | API-10 | `editor/applyEdits` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-10 | `editor/replaceSelections` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-10 | `editor/insertText` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| API-11 | `documents/save` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `documents/saveAs` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `documents/close` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `workspace/create` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `workspace/rename` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `workspace/copy` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | -| API-11 | `workspace/trash` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `documents/save` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `documents/saveAs` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `documents/close` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `workspace/create` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `workspace/rename` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `workspace/copy` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | +| API-11 | `workspace/trash` | 0 | 待合入 | [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183) | | API-12 | `documents/registerContentProvider` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-15 | `editor/open` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-15 | `editor/reveal` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index d1934e21..89fe63a6 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -1052,9 +1052,11 @@ func (w *Workspace) FindText(context WorkspaceContext, params any) (json.RawMess return w.host.scoped(methodFindText, context, params) } -// Create takes resource, kind ("file" or "directory") and text? for a file, -// and answers { resource, kind }. It never overwrites: an existing resource is -// plugin.host.alreadyExists. +// Create takes resource, kind ("file", "directory" or "symlink"), text? for a +// file and linkTarget for a symlink, and answers { resource, kind }. A link +// stores linkTarget verbatim, absolute or relative to the link's directory, +// and makes nothing outside the root readable. It never overwrites: an +// existing resource is plugin.host.alreadyExists. func (w *Workspace) Create(context WorkspaceContext, params any) (json.RawMessage, error) { return w.host.scoped(methodCreate, context, params) } diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index 49e40387..516b3c54 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -534,8 +534,10 @@ public CompletableFuture> findText(Map context, M } /** - * Permission {@code workspace.files.write}. {@code params}: {@code resource, kind} ({@code "file"} or - * {@code "directory"}) and {@code text?} for a file; answers {@code { resource, kind }}. An existing + * Permission {@code workspace.files.write}. {@code params}: {@code resource, kind} ({@code "file"}, + * {@code "directory"} or {@code "symlink"}), {@code text?} for a file and {@code linkTarget} for a + * symlink; answers {@code { resource, kind }}. A link stores {@code linkTarget} verbatim, absolute or + * relative to the link's directory, and makes nothing outside the root readable. An existing * {@code resource} fails with {@code plugin.host.alreadyExists}; nothing is overwritten. */ public CompletableFuture> create(Map context, Map params) { diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 4ca8937f..5310d02e 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -334,7 +334,11 @@ export interface Host { * Permission `workspace.files.write`. Never overwrites: an existing * `resource` is `plugin.host.alreadyExists`. `text` is for a file only. */ - create: Scoped<{ resource: WorkspaceResource; kind: 'file' | 'directory'; text?: string }, { resource: WorkspaceResource; kind: 'file' | 'directory' }>; + create: Scoped< + | { resource: WorkspaceResource; kind: 'file'; text?: string } + | { resource: WorkspaceResource; kind: 'directory' } + | { resource: WorkspaceResource; kind: 'symlink'; linkTarget: string }, + { resource: WorkspaceResource; kind: 'file' | 'directory' | 'symlink' }>; /** * Permission `workspace.files.write`. `target` is the full new path. The * host saves the open documents under `resource` first; they follow the file. diff --git a/shared/plugins/sdk/node/test/types/host.mts b/shared/plugins/sdk/node/test/types/host.mts index 426887ea..41f12394 100644 --- a/shared/plugins/sdk/node/test/types/host.mts +++ b/shared/plugins/sdk/node/test/types/host.mts @@ -174,10 +174,15 @@ async function remoteRoots(context: WorkspaceContext) { async function fileChanges(context: WorkspaceContext) { const resource = { rootID: context.folders[0]!.rootID, path: 'notes/today.md' }; const created = await backend.host.workspace.create(context, { resource, kind: 'file', text: '# Today' }); - const kind: 'file' | 'directory' = created.kind; + const kind: 'file' | 'directory' | 'symlink' = created.kind; void kind; - // @ts-expect-error A created item is a file or a directory. + await backend.host.workspace.create(context, { resource, kind: 'symlink', linkTarget: '../shared/today.md' }); + // @ts-expect-error A created item is a file, a directory or a symbolic link. await backend.host.workspace.create(context, { resource, kind: 'link' }); + // @ts-expect-error A symbolic link names its target. + await backend.host.workspace.create(context, { resource, kind: 'symlink' }); + // @ts-expect-error Only a file takes text. + await backend.host.workspace.create(context, { resource, kind: 'directory', text: 'x' }); await backend.host.workspace.rename(context, { resource, target: { ...resource, path: 'notes/done.md' } }); await backend.host.workspace.copy(context, { resource, target: { ...resource, path: 'notes/copy.md' } }); const trashed: null = await backend.host.workspace.trash(context, { resource }); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 0651a7af..8b891ef3 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -917,9 +917,12 @@ impl Workspace { .scoped(methods::WORKSPACE_FIND_TEXT, context, params) } - /// `params`: `resource, kind` (`"file"` or `"directory"`), `text?` for a - /// file; answers `{ resource, kind }`. Never overwrites: an existing - /// resource is `plugin.host.alreadyExists`. + /// `params`: `resource, kind` (`"file"`, `"directory"` or `"symlink"`), + /// `text?` for a file, `linkTarget` for a symlink; answers + /// `{ resource, kind }`. A link stores `linkTarget` verbatim, absolute or + /// relative to the link's directory, and makes nothing outside the root + /// readable. Never overwrites: an existing resource is + /// `plugin.host.alreadyExists`. pub fn create(&self, context: &WorkspaceContext, params: Value) -> Result { self.host.scoped(methods::WORKSPACE_CREATE, context, params) } From 6a384c0fe46524309d125e0fd975e1ab1f19351a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 23 Nov 2026 17:59:29 +0800 Subject: [PATCH 2/3] =?UTF-8?q?docs(changelog):=20=E7=AC=A6=E5=8F=B7?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=E4=B8=8E=20Core=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E5=8D=95=E7=8B=AC=E8=AE=B0=E4=B8=80=E6=9D=A1?= =?UTF-8?q?=EF=BC=8C#183=20=E6=9D=A1=E7=9B=AE=E6=81=A2=E5=A4=8D=E5=8E=9F?= =?UTF-8?q?=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 4a37b446..439f6772 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,8 @@ ## 待合入 -- [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`create` 可以新建文件、目录或符号链接,链接原样保存 `linkTarget`,不放宽读取和打开的根目录检查;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径检查、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 +- [#PRNUM](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/PRNUM),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、宿主方法、通知或 SDK 版本。 +- [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 - [#176](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/176),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`languageServers` 0 内的说明补充(—):写明后端决定启动方式的语言服务器在 `immediate` 设置变化时的行为。启动应答自带 `workspaceConfiguration` 时,宿主用这次启动的四个目录、工作区 `context` 和新的 `settings` 再调用一次启动函数,同样交给 `plugins.languageServers.decodeLaunch` 解码,只把计划里的 `workspaceConfiguration` 通过 `lsp.updateWorkspaceConfiguration` 发出(整体替换原配置),应答的其余部分等下次启动;应答不带时发送声明的展开,不再调用函数。所以这类启动函数每次启动可能被调用多次,安装或下载只应在缺少时进行。契约 README 的 Workspace configuration 和 Backend-resolved launch 两节、`reference/domains/languages.md` 与 `settings.md` 的中英文随之补充。桌面端实现见 1lck/Lithe-IDEA#2319。Core 代码、能力版本、宿主方法、通知和协议字段都不变。 - [#175](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/175),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`ui` 0 内的补充(API-13、API-23):撤回 #174 新增的 `ui` 1,设置区域 `tool` 行的可选布尔字段 `choose` 改为 `ui` 0 内的补充,清单写 `requires.ui: 0` 即可使用。`capabilities.rs` 和清单 schema 的 `requires.ui` 回到只有 0,能力对照表删去 `ui` 1 一行。`choose` 不是布尔值时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`;旧宿主的 Core 不认识这个字段,同样会拒绝带它的视图,所以插件要等包含本改动的桌面端发布后再写。fixture `ui/view-results.json` 改为两个用例(接受选择器、`choose` 不是布尔值时拒绝),替换原来“`requires.ui` 为 0 时拒绝”的用例。`ui` 1 没有随任何宿主发布过。没有新增能力版本、宿主方法、通知或进程协议字段。 - [#174](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/174),[@xiaoyumuxi](https://github.com/xiaoyumuxi),**`ui` 1**(API-13、API-23):设置区域视图的 `tool` 行新增可选的布尔字段 `choose`,带上后这一行同时是该工具的选择器,像解释器下拉框一样列出自动选择、已发现和已添加的安装(带版本和来源)、添加目录和打开工具链页的入口;选择只改设置窗口的草稿,“应用”提交、“取消”丢弃,行上显示待提交的选择,应用后启动和运行拿到选中的安装。清单 `requires.ui` 为 0 时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`。契约 README 的插件视图一节补充:为某个工作区显示的视图(项目窗口里的工具窗口,或从项目窗口打开的设置页)调用时,带上该窗口的工作区上下文作为 invoke 的 `params.context`,后端可以在 `click` 里用它调用 `run/start` 等需要上下文的宿主方法;没有工作区时不带。fixture `ui/view-results.json` 新增一个用例,Node SDK 的视图节点类型加上 `choose`,Rust 和 Go SDK 的工作区上下文说明随之修正。没有新增宿主方法、通知或进程协议字段。(`ui` 1 已由 #175 撤回,`choose` 改为 `ui` 0 内的补充。) From ddbc9988edd213e522ea46dcdfdb5dd20ab2f190 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 23 Nov 2026 18:00:15 +0800 Subject: [PATCH 3/3] =?UTF-8?q?docs(changelog):=20=E8=A1=A5=E4=B8=8A=20PR?= =?UTF-8?q?=20=E7=BC=96=E5=8F=B7=20#184?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 439f6772..3a7776bc 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#PRNUM](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/PRNUM),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、宿主方法、通知或 SDK 版本。 +- [#184](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/184),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、宿主方法、通知或 SDK 版本。 - [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 - [#176](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/176),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`languageServers` 0 内的说明补充(—):写明后端决定启动方式的语言服务器在 `immediate` 设置变化时的行为。启动应答自带 `workspaceConfiguration` 时,宿主用这次启动的四个目录、工作区 `context` 和新的 `settings` 再调用一次启动函数,同样交给 `plugins.languageServers.decodeLaunch` 解码,只把计划里的 `workspaceConfiguration` 通过 `lsp.updateWorkspaceConfiguration` 发出(整体替换原配置),应答的其余部分等下次启动;应答不带时发送声明的展开,不再调用函数。所以这类启动函数每次启动可能被调用多次,安装或下载只应在缺少时进行。契约 README 的 Workspace configuration 和 Backend-resolved launch 两节、`reference/domains/languages.md` 与 `settings.md` 的中英文随之补充。桌面端实现见 1lck/Lithe-IDEA#2319。Core 代码、能力版本、宿主方法、通知和协议字段都不变。 - [#175](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/175),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`ui` 0 内的补充(API-13、API-23):撤回 #174 新增的 `ui` 1,设置区域 `tool` 行的可选布尔字段 `choose` 改为 `ui` 0 内的补充,清单写 `requires.ui: 0` 即可使用。`capabilities.rs` 和清单 schema 的 `requires.ui` 回到只有 0,能力对照表删去 `ui` 1 一行。`choose` 不是布尔值时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`;旧宿主的 Core 不认识这个字段,同样会拒绝带它的视图,所以插件要等包含本改动的桌面端发布后再写。fixture `ui/view-results.json` 改为两个用例(接受选择器、`choose` 不是布尔值时拒绝),替换原来“`requires.ui` 为 0 时拒绝”的用例。`ui` 1 没有随任何宿主发布过。没有新增能力版本、宿主方法、通知或进程协议字段。