From a31dec7a90fcdbcf93f0abaa0fb6927cbd870a15 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 13:00:42 +0800 Subject: [PATCH] =?UTF-8?q?refactor(platform):=20=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E8=A7=84=E5=88=99=E6=94=B9=E4=B8=BA=E6=95=B0=E6=8D=AE=EF=BC=8C?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E4=B8=93=E5=B1=9E=E6=B5=8B=E8=AF=95=E7=A7=BB?= =?UTF-8?q?=E5=88=B0=20lithe-platform-tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 lithe-platform crate:Platform { Unix, Windows } 与 Platform::HOST, 路径包含判断、斜杠路径、Windows 保留设备名、owner-only 权限、可执行位、 隐藏控制台窗口、batch 参数转义统一成按平台参数计算的函数 - LSP 进程在所有平台都放进 ProcessTree:macOS/Linux 终止或释放语言服务器时 一并结束它启动的子进程(旧代码下子进程会存活);Unix 语言服务器进入独立 进程组,终端 Ctrl-C 不再直接传给它 - Git 路径校验统一使用同一份保留名规则,新增拒绝 CONIN$/CONOUT$ - 补丁指纹无条件计入文件模式,Windows 打开远程 Unix 工作区时结果一致 - SSH Connection::close 调整关闭顺序,Unix 下不再固定等满 2 秒 - 新增 lithe-platform-tests 包:fixture 程序代替 shell 命令,迁入 git-host/tests/process.rs,并新增 LSP 进程树、Windows batch 参数、权限、 Git 可执行文件解析的真实系统测试 - 顺手修复 shared/plugins/sdk/e2e 中原有的 clippy needless-borrow 报错 --- rust/Cargo.lock | 21 + rust/crates/diagnostics/Cargo.toml | 1 + rust/crates/diagnostics/src/channel.rs | 7 +- rust/crates/git-host/Cargo.toml | 1 + rust/crates/git-host/src/configuration.rs | 88 ++-- rust/crates/git-host/src/lib.rs | 7 +- rust/crates/git-host/tests/process.rs | 203 -------- rust/crates/git/Cargo.toml | 1 + rust/crates/git/src/file_context.rs | 14 +- rust/crates/git/src/lib.rs | 2 - rust/crates/git/src/line_history.rs | 13 +- rust/crates/git/src/patch_exchange.rs | 9 +- rust/crates/git/src/process.rs | 32 +- rust/crates/git/src/rebase_session.rs | 7 +- rust/crates/git/src/repository.rs | 86 +++- rust/crates/git/src/rewrite.rs | 11 +- rust/crates/git/src/tests.rs | 6 - rust/crates/ide-host/Cargo.toml | 1 + rust/crates/ide-host/src/lib.rs | 14 +- rust/crates/lsp-transport/Cargo.toml | 5 +- rust/crates/lsp-transport/src/process.rs | 460 ++++++++---------- rust/crates/platform-tests/Cargo.toml | 12 + .../src/bin/lithe-platform-fixture.rs | 94 ++++ rust/crates/platform-tests/src/lib.rs | 117 +++++ .../tests/platform/git_executable.rs | 39 ++ .../tests/platform/lsp_process.rs | 174 +++++++ .../platform-tests/tests/platform/main.rs | 10 + .../tests/platform/permissions.rs | 89 ++++ .../tests/platform/process_tree.rs | 172 +++++++ .../platform-tests/tests/platform/support.rs | 120 +++++ rust/crates/platform/Cargo.toml | 8 + rust/crates/platform/src/fs.rs | 123 +++++ rust/crates/platform/src/lib.rs | 78 +++ rust/crates/platform/src/names.rs | 108 ++++ rust/crates/platform/src/paths.rs | 126 +++++ rust/crates/platform/src/process.rs | 68 +++ rust/crates/project-generators/Cargo.toml | 1 + rust/crates/project-generators/src/archive.rs | 66 +-- rust/crates/project-generators/src/plan.rs | 13 +- rust/crates/project/Cargo.toml | 1 + rust/crates/project/src/files/search.rs | 15 +- rust/crates/project/src/indexing.rs | 12 +- rust/crates/workspace/Cargo.toml | 1 + rust/crates/workspace/src/fs.rs | 13 +- rust/crates/workspace/src/sessions.rs | 15 +- shared/plugins/sdk/e2e/plugin_sdk/mod.rs | 4 +- 46 files changed, 1721 insertions(+), 747 deletions(-) delete mode 100644 rust/crates/git-host/tests/process.rs create mode 100644 rust/crates/platform-tests/Cargo.toml create mode 100644 rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs create mode 100644 rust/crates/platform-tests/src/lib.rs create mode 100644 rust/crates/platform-tests/tests/platform/git_executable.rs create mode 100644 rust/crates/platform-tests/tests/platform/lsp_process.rs create mode 100644 rust/crates/platform-tests/tests/platform/main.rs create mode 100644 rust/crates/platform-tests/tests/platform/permissions.rs create mode 100644 rust/crates/platform-tests/tests/platform/process_tree.rs create mode 100644 rust/crates/platform-tests/tests/platform/support.rs create mode 100644 rust/crates/platform/Cargo.toml create mode 100644 rust/crates/platform/src/fs.rs create mode 100644 rust/crates/platform/src/lib.rs create mode 100644 rust/crates/platform/src/names.rs create mode 100644 rust/crates/platform/src/paths.rs create mode 100644 rust/crates/platform/src/process.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 8d303a4a..38d43bf4 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -976,6 +976,7 @@ name = "lithe-diagnostics" version = "0.1.0" dependencies = [ "chrono", + "lithe-platform", "lithe-protocol", "regex", "serde", @@ -1053,6 +1054,7 @@ dependencies = [ "lithe-diff", "lithe-git-host", "lithe-github", + "lithe-platform", "lithe-protocol", "lithe-remote", "lithe-request-context", @@ -1069,6 +1071,7 @@ name = "lithe-git-host" version = "0.1.0" dependencies = [ "libc", + "lithe-platform", "rand", "serde", "serde_json", @@ -1090,6 +1093,7 @@ version = "0.1.0" dependencies = [ "axum", "fs2", + "lithe-platform", "reqwest", "rmcp", "serde", @@ -1159,6 +1163,7 @@ version = "0.1.0" dependencies = [ "lithe-diagnostics", "lithe-git-host", + "lithe-platform", "lithe-protocol", "lithe-remote", "lithe-workspace", @@ -1174,6 +1179,19 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lithe-platform" +version = "0.1.0" + +[[package]] +name = "lithe-platform-tests" +version = "0.1.0" +dependencies = [ + "lithe-git-host", + "lithe-lsp-transport", + "lithe-platform", +] + [[package]] name = "lithe-plugin-backend" version = "0.1.0" @@ -1383,6 +1401,7 @@ dependencies = [ "lithe-core-rules", "lithe-diagnostics", "lithe-git", + "lithe-platform", "lithe-protocol", "lithe-request-context", "lithe-text", @@ -1398,6 +1417,7 @@ dependencies = [ name = "lithe-project-generators" version = "0.1.0" dependencies = [ + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "rand", @@ -1503,6 +1523,7 @@ version = "0.1.0" dependencies = [ "lithe-diagnostics", "lithe-git-host", + "lithe-platform", "lithe-protocol", "lithe-remote", "lithe-request-context", diff --git a/rust/crates/diagnostics/Cargo.toml b/rust/crates/diagnostics/Cargo.toml index 65e24ef0..4fef138d 100644 --- a/rust/crates/diagnostics/Cargo.toml +++ b/rust/crates/diagnostics/Cargo.toml @@ -11,6 +11,7 @@ description = "Structured log catalog, channels, records, queries and the bounde test-support = [] [dependencies] +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } regex = "1.11" diff --git a/rust/crates/diagnostics/src/channel.rs b/rust/crates/diagnostics/src/channel.rs index 93632349..3c088535 100644 --- a/rust/crates/diagnostics/src/channel.rs +++ b/rust/crates/diagnostics/src/channel.rs @@ -131,12 +131,7 @@ pub fn validate_segment(value: &str) -> Result<(), LogError> { .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)); // Win32 strips trailing dots and reserves device basenames even with an extension. // Reject them on every host so the same identity always names the same file. - let basename = value.split('.').next().unwrap_or(""); - let device = matches!(basename, "con" | "prn" | "aux" | "nul") - || (basename.len() == 4 - && (basename.starts_with("com") || basename.starts_with("lpt")) - && matches!(basename.as_bytes()[3], b'1'..=b'9')); - if !valid || value.ends_with('.') || device { + if !valid || !lithe_platform::names::is_portable_windows_component(value) { return Err(LogError::new(-32033, "Invalid channel segment")); } Ok(()) diff --git a/rust/crates/git-host/Cargo.toml b/rust/crates/git-host/Cargo.toml index db4fed72..408a76d5 100644 --- a/rust/crates/git-host/Cargo.toml +++ b/rust/crates/git-host/Cargo.toml @@ -12,6 +12,7 @@ libc = "0.2" windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_System_JobObjects", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Threading", "Win32_Security"] } [dependencies] +lithe-platform = { path = "../platform" } rand = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rust/crates/git-host/src/configuration.rs b/rust/crates/git-host/src/configuration.rs index ca7b4f4f..13d9d12e 100644 --- a/rust/crates/git-host/src/configuration.rs +++ b/rust/crates/git-host/src/configuration.rs @@ -1,60 +1,42 @@ //! Native executable resolution and per-child Git environment configuration. +use lithe_platform::fs::is_launchable_file; +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; use std::path::PathBuf; use std::process::Command; /// Resolves a user-selected executable or the first runnable Git on PATH. pub fn executable(selected: Option<&str>) -> Option { + let platform = Platform::HOST; let candidates = match selected { Some(path) => vec![PathBuf::from(path)], - None => std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) - .flat_map(|directory| { - #[cfg(windows)] - let names = ["git.exe"]; - #[cfg(not(windows))] - let names = ["git"]; - names.map(|name| directory.join(name)) - }) - .collect(), + None => { + let name = platform.executable_name("git"); + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .map(|directory| directory.join(&name)) + .collect() + } }; candidates .into_iter() .find(|path| { - let Ok(metadata) = path.metadata() else { - return false; - }; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 - } - #[cfg(not(unix))] - { - metadata.is_file() - } + path.metadata() + .is_ok_and(|metadata| is_launchable_file(&metadata)) }) - .map(launch_path) + .map(|path| launch_path(path, platform)) } /// Some Windows hosts (disk-encryption or endpoint-security filters) make a Git started through a /// backslash path print nothing to a captured pipe, while the same executable started through a /// forward-slash path behaves normally. Windows accepts both separators, so launch with `/`. -fn launch_path(path: PathBuf) -> PathBuf { - #[cfg(windows)] - { - if let Some(text) = path.to_str() { - return PathBuf::from(forward_slash_path(text)); +/// Verbatim (`\\?\`) and UNC (`\\server`) paths keep their native form because `/` is not valid +/// there. +fn launch_path(path: PathBuf, platform: Platform) -> PathBuf { + match path.to_str() { + Some(text) if !text.starts_with(r"\\") => { + PathBuf::from(slash_separated(text, platform).into_owned()) } - } - path -} - -/// Verbatim (`\\?\`) and UNC (`\\server`) paths keep their native form because `/` is not valid there. -#[cfg(any(windows, test))] -fn forward_slash_path(path: &str) -> String { - if path.starts_with(r"\\") { - path.to_owned() - } else { - path.replace('\\', "/") + _ => path, } } @@ -158,34 +140,24 @@ mod tests { } #[test] - fn launch_paths_use_forward_slashes_except_unc_and_verbatim() { + fn windows_launch_paths_use_forward_slashes_except_unc_and_verbatim() { + let launch = |path: &str| launch_path(PathBuf::from(path), Platform::Windows); assert_eq!( - forward_slash_path(r"D:\Program Files\Git\cmd\git.exe"), - "D:/Program Files/Git/cmd/git.exe" + launch(r"D:\Program Files\Git\cmd\git.exe"), + PathBuf::from("D:/Program Files/Git/cmd/git.exe") ); assert_eq!( - forward_slash_path("D:/Git/cmd/git.exe"), - "D:/Git/cmd/git.exe" + launch("D:/Git/cmd/git.exe"), + PathBuf::from("D:/Git/cmd/git.exe") ); for native in [r"\\server\share\git.exe", r"\\?\D:\Git\cmd\git.exe"] { - assert_eq!(forward_slash_path(native), native); + assert_eq!(launch(native), PathBuf::from(native)); } } - // Regression: a backslash launch path makes some Windows hosts capture empty Git output, so the - // resolved executable must reach the process spawner with forward slashes. - #[cfg(windows)] #[test] - fn selected_executable_is_resolved_with_forward_slashes() { - let file = std::env::temp_dir().join(format!( - "lithe-git-host-launch-path-{}.exe", - std::process::id() - )); - std::fs::write(&file, b"").unwrap(); - let resolved = executable(file.to_str()); - std::fs::remove_file(&file).unwrap(); - let resolved = resolved.unwrap().to_string_lossy().into_owned(); - assert!(!resolved.contains('\\'), "{resolved}"); - assert!(resolved.ends_with(".exe"), "{resolved}"); + fn unix_launch_paths_keep_backslashes_as_name_characters() { + let path = PathBuf::from(r"/opt/odd\name/git"); + assert_eq!(launch_path(path.clone(), Platform::Unix), path); } } diff --git a/rust/crates/git-host/src/lib.rs b/rust/crates/git-host/src/lib.rs index 021d5baf..ddafdd18 100644 --- a/rust/crates/git-host/src/lib.rs +++ b/rust/crates/git-host/src/lib.rs @@ -355,12 +355,7 @@ impl InputFile { )); let mut options = OpenOptions::new(); options.read(true).write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - match options.open(&path) { + match lithe_platform::fs::owner_only_file(&mut options).open(&path) { Ok(file) => { let mut owned = Self { file, path }; owned.file.write_all(input)?; diff --git a/rust/crates/git-host/tests/process.rs b/rust/crates/git-host/tests/process.rs deleted file mode 100644 index c1b442e1..00000000 --- a/rust/crates/git-host/tests/process.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! Native integration fixtures execute only this test binary, never installed tools. -use lithe_git_host::{run, Failure, ProcessTree}; -use std::io::{BufRead, BufReader, Read, Write}; -use std::process::{Child, Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc; -use std::time::{Duration, Instant}; - -const TREE_DEADLINE: Duration = Duration::from_secs(5); - -#[test] -fn process_fixture() { - let Ok(mode) = std::env::var("LITHE_GIT_PROCESS_FIXTURE") else { - return; - }; - if mode == "failure" { - println!("fixture output"); - eprintln!("fixture error"); - std::process::exit(23); - } - if mode == "tree-parent" || mode == "tree-child" { - run_tree_fixture(&mode); - return; - } - // Output is the synchronization signal. The helper also has its own hard - // deadline, so a broken parent cancellation path cannot leave it running. - let deadline = Instant::now() + Duration::from_secs(3); - while Instant::now() < deadline { - if std::io::stdout().write_all(b"fixture-ready\n").is_err() { - break; - } - } -} - -#[test] -fn incremental_output_can_cancel_before_the_child_exits() { - let began = Instant::now(); - let started = AtomicBool::new(false); - let received = AtomicBool::new(false); - let mut command = Command::new(std::env::current_exe().expect("test executable")); - command - .args(["--exact", "process_fixture", "--nocapture"]) - .env("LITHE_GIT_PROCESS_FIXTURE", "cancel"); - let outcome = run( - &mut command, - None, - || received.load(Ordering::Relaxed) || began.elapsed() > Duration::from_secs(2), - || started.store(true, Ordering::Relaxed), - |_, bytes| { - assert!(started.load(Ordering::Relaxed)); - if bytes - .windows(b"fixture-ready".len()) - .any(|window| window == b"fixture-ready") - { - received.store(true, Ordering::Relaxed); - } - }, - ); - assert!( - received.load(Ordering::Relaxed), - "deadline elapsed before fixture output" - ); - assert!(matches!(outcome.failure, Some(Failure::Cancelled))); - assert!( - outcome.status.is_some(), - "owned child must be reaped before return" - ); -} - -#[test] -fn nonzero_exit_retains_both_streams() { - let deadline = Instant::now() + Duration::from_secs(2); - let mut command = Command::new(std::env::current_exe().expect("test executable")); - command - .args(["--exact", "process_fixture", "--nocapture"]) - .env("LITHE_GIT_PROCESS_FIXTURE", "failure"); - let outcome = run( - &mut command, - None, - || Instant::now() > deadline, - || {}, - |_, _| {}, - ); - assert!(outcome.failure.is_none()); - assert_eq!(outcome.status.and_then(|status| status.code()), Some(23)); - assert!(String::from_utf8_lossy(&outcome.stdout).contains("fixture output")); - assert!(String::from_utf8_lossy(&outcome.stderr).contains("fixture error")); -} - -/// A two-level tree like `cmd -> mvn -> java`. Both levels block on the -/// test's stdin pipe, so they also end on their own once the test drops it. -fn run_tree_fixture(mode: &str) { - let mut descendant = (mode == "tree-parent").then(|| { - let descendant = Command::new(std::env::current_exe().expect("test executable")) - .args(["--exact", "process_fixture", "--nocapture"]) - .env("LITHE_GIT_PROCESS_FIXTURE", "tree-child") - .stdin(Stdio::inherit()) - .stdout(Stdio::null()) - .spawn() - .expect("spawn descendant"); - println!("descendant-pid {}", descendant.id()); - std::io::stdout().flush().expect("announce descendant"); - descendant - }); - let _ = std::io::stdin().read_to_end(&mut Vec::new()); - if let Some(descendant) = descendant.as_mut() { - let _ = descendant.wait(); - } -} - -struct TreeFixture { - tree: ProcessTree, - descendant: u32, - root_exit: mpsc::Receiver<()>, - // Dropped last: closing it lets any survivor exit on its own. - _input: std::process::ChildStdin, -} - -fn spawn_tree_fixture() -> TreeFixture { - let mut command = Command::new(std::env::current_exe().expect("test executable")); - command - .args(["--exact", "process_fixture", "--nocapture"]) - .env("LITHE_GIT_PROCESS_FIXTURE", "tree-parent") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()); - ProcessTree::prepare(&mut command); - let mut root = command.spawn().expect("spawn tree root"); - let input = root.stdin.take().expect("root input"); - let output = root.stdout.take().expect("root output"); - let tree = ProcessTree::adopt(&mut root).expect("adopt tree"); - let descendant = read_descendant_pid(output); - TreeFixture { - tree, - descendant, - root_exit: reap_in_background(root), - _input: input, - } -} - -fn read_descendant_pid(output: std::process::ChildStdout) -> u32 { - let (sender, receiver) = mpsc::channel(); - std::thread::spawn(move || { - for line in BufReader::new(output).lines() { - let Ok(line) = line else { return }; - if let Some(pid) = line.strip_prefix("descendant-pid ") { - let _ = sender.send(pid.trim().parse::().expect("descendant pid")); - return; - } - } - }); - receiver - .recv_timeout(TREE_DEADLINE) - .expect("tree fixture did not start its descendant") -} - -/// A Unix group still counts an unreaped root, so the owner reaps it while -/// the tree is being ended, as the Run host's exit waiter does. -fn reap_in_background(mut root: Child) -> mpsc::Receiver<()> { - let (sender, receiver) = mpsc::channel(); - std::thread::spawn(move || { - let _ = root.wait(); - let _ = sender.send(()); - }); - receiver -} - -#[test] -fn process_tree_terminate_ends_the_root_and_its_descendants() { - let fixture = spawn_tree_fixture(); - assert_ne!(fixture.descendant, 0); - - fixture - .tree - .terminate(TREE_DEADLINE) - .expect("every process of the tree ends"); - fixture - .root_exit - .recv_timeout(TREE_DEADLINE) - .expect("root ended"); - // A second request after the tree is empty is harmless. - fixture - .tree - .terminate(TREE_DEADLINE) - .expect("an empty tree terminates"); -} - -#[cfg(windows)] -#[test] -fn dropping_a_process_tree_ends_it_like_a_crashed_host() { - // The kernel closes the job handle when the host dies; dropping the tree - // closes it the same way, without an explicit terminate. - let fixture = spawn_tree_fixture(); - let TreeFixture { - tree, - root_exit, - _input, - .. - } = fixture; - drop(tree); - root_exit - .recv_timeout(TREE_DEADLINE) - .expect("closing the job ends the root"); -} diff --git a/rust/crates/git/Cargo.toml b/rust/crates/git/Cargo.toml index 25dcf182..3e3214c7 100644 --- a/rust/crates/git/Cargo.toml +++ b/rust/crates/git/Cargo.toml @@ -17,6 +17,7 @@ lithe-diagnostics = { path = "../diagnostics" } lithe-diff = { path = "../diff" } lithe-git-host = { path = "../git-host" } lithe-github = { path = "../github" } +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } lithe-remote = { path = "../remote", default-features = false, features = ["client"] } lithe-request-context = { path = "../request-context" } diff --git a/rust/crates/git/src/file_context.rs b/rust/crates/git/src/file_context.rs index 11a38b3e..a229aeff 100644 --- a/rust/crates/git/src/file_context.rs +++ b/rust/crates/git/src/file_context.rs @@ -1,5 +1,7 @@ //! Resolve a file to its actual Git checkout, independently of UI selection. +use lithe_platform::paths::slash_separated; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use std::path::{Component, Path, PathBuf}; @@ -114,11 +116,7 @@ pub fn resolve(request: Request) -> Result, CoreError> { let relative = relative .to_str() .ok_or_else(|| CoreError::new(ErrorCode::InvalidRequest, "Git file path is not UTF-8"))?; - let relative = if cfg!(windows) { - relative.replace('\\', "/") - } else { - relative.to_owned() - }; + let relative = slash_separated(relative, Platform::HOST).into_owned(); if relative.is_empty() { return Err(CoreError::new( ErrorCode::InvalidRequest, @@ -131,11 +129,7 @@ pub fn resolve(request: Request) -> Result, CoreError> { "Git repository path is not UTF-8", ) })?; - let root = if cfg!(windows) { - root.replace('\\', "/") - } else { - root.to_owned() - }; + let root = slash_separated(root, Platform::HOST).into_owned(); Ok(Some(Context { root, path: relative, diff --git a/rust/crates/git/src/lib.rs b/rust/crates/git/src/lib.rs index d27aa254..fd9f3654 100644 --- a/rust/crates/git/src/lib.rs +++ b/rust/crates/git/src/lib.rs @@ -175,8 +175,6 @@ use serde::{Deserialize, Serialize}; use std::cell::RefCell; use std::collections::{HashSet, VecDeque}; use std::io::Read; -#[cfg(target_os = "windows")] -use std::os::windows::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/rust/crates/git/src/line_history.rs b/rust/crates/git/src/line_history.rs index cbbd371f..7c0589ef 100644 --- a/rust/crates/git/src/line_history.rs +++ b/rust/crates/git/src/line_history.rs @@ -109,14 +109,11 @@ fn create_line_history_scratch() -> Result return Ok(ScopedLineHistoryDirectory(candidate)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { diff --git a/rust/crates/git/src/patch_exchange.rs b/rust/crates/git/src/patch_exchange.rs index 720d8203..785d478a 100644 --- a/rust/crates/git/src/patch_exchange.rs +++ b/rust/crates/git/src/patch_exchange.rs @@ -5,6 +5,7 @@ use super::{ operation_state, repository_root, resolve_commit_revision, validate_root, CoreError, ErrorCode, GitCommandResponse, GitOperationStateRequest, TemporaryGitCommitContext, }; +use lithe_platform::Platform; use lithe_workspace::fs; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -243,7 +244,7 @@ fn parse_statistics(bytes: &[u8], allow_null_source: bool) -> Result Result<(), CoreError> { fn hash_working_file(hash: &mut Sha256, path: &Path) -> Result<(), CoreError> { use std::io::Read; let metadata = fs::symlink_metadata(path).map_err(patch_io_error)?; - #[cfg(unix)] - { - hash.update(metadata.mode().to_le_bytes()); - } + // Zero for a local Windows file, which stores no mode. + hash.update(metadata.mode().to_le_bytes()); hash.update([u8::from(metadata.file_type().is_symlink())]); if metadata.file_type().is_symlink() { let target = fs::read_link(path).map_err(patch_io_error)?; diff --git a/rust/crates/git/src/process.rs b/rust/crates/git/src/process.rs index aa28c42a..b7f5a2cb 100644 --- a/rust/crates/git/src/process.rs +++ b/rust/crates/git/src/process.rs @@ -466,25 +466,11 @@ pub(crate) fn git_process() -> Command { let options = execution_policy::current(); let executable = lithe_git_host::configuration::executable(options.executable.as_deref()) .unwrap_or_else(|| options.executable.unwrap_or_else(|| "git".into()).into()); - #[cfg(target_os = "windows")] - { - let mut process = Command::new(executable); - process.creation_flags(git_process_creation_flags()); - process - } - - #[cfg(not(target_os = "windows"))] - { - Command::new(executable) - } -} - -#[cfg(target_os = "windows")] -pub(crate) fn git_process_creation_flags() -> u32 { // Git runs as an IDE background task; attaching a console can briefly open // the user's default terminal whenever status or repository data refreshes. - const CREATE_NO_WINDOW: u32 = 0x08000000; - CREATE_NO_WINDOW + let mut process = Command::new(executable); + lithe_platform::process::hide_console_window(&mut process); + process } pub(crate) fn successful_git_result() -> GitCommandResponse { @@ -563,18 +549,8 @@ pub(crate) fn run_git( &[], false, )?; - #[cfg(unix)] - let status = { - use std::os::unix::process::ExitStatusExt; - std::process::ExitStatus::from_raw(output.exit_code << 8) - }; - #[cfg(windows)] - let status = { - use std::os::windows::process::ExitStatusExt; - std::process::ExitStatus::from_raw(output.exit_code as u32) - }; return Ok(std::process::Output { - status, + status: lithe_platform::process::exit_status_from_code(output.exit_code), stdout: output.stdout, stderr: output.stderr, }); diff --git a/rust/crates/git/src/rebase_session.rs b/rust/crates/git/src/rebase_session.rs index e90790e9..39b92db1 100644 --- a/rust/crates/git/src/rebase_session.rs +++ b/rust/crates/git/src/rebase_session.rs @@ -679,9 +679,10 @@ fn environment(root: &str, record: &SessionRecord) -> Result(path) + Ok::<_, CoreError>( + lithe_platform::paths::slash_separated(&path, lithe_platform::Platform::HOST) + .into_owned(), + ) }; Ok(vec![ ("GIT_SEQUENCE_EDITOR".into(), SEQUENCE_EDITOR.into()), diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index a0b05136..5abc4472 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -2,6 +2,8 @@ //! `.git` resolution, and the pathspec checks every command applies. use super::*; +use lithe_platform::names::is_reserved_device_name; +use lithe_platform::Platform; /// Discovers Git repositories for an opened workspace using shared traversal rules. pub fn workspace_repositories( @@ -110,8 +112,14 @@ fn repository_scan_directory_is_visible(name: &str) -> bool { /// Rejects Windows names that cannot round-trip through ordinary path identifiers. /// POSIX names keep their native meaning; Windows validates relative paths too. pub(crate) fn validate_windows_git_path(path: &Path) -> std::io::Result<()> { + validate_git_path_on(path, Platform::HOST) +} + +/// [`validate_windows_git_path`] for a repository that `platform` opens. A +/// drive or UNC path is checked on every platform. +fn validate_git_path_on(path: &Path, platform: Platform) -> std::io::Result<()> { let text = path.to_string_lossy().replace('\\', "/"); - let windows_path = cfg!(windows) + let windows_path = platform.is_windows() || text.starts_with("//") || (text.as_bytes().get(1) == Some(&b':') && text.as_bytes()[0].is_ascii_alphabetic()); if !windows_path { @@ -148,22 +156,7 @@ pub(crate) fn validate_windows_git_path(path: &Path) -> std::io::Result<()> { if matches!(*part, "." | "..") { return verbatim.is_some(); } - let basename = part - .split('.') - .next() - .unwrap_or_default() - .to_ascii_uppercase(); - let reserved = matches!(basename.as_str(), "CON" | "PRN" | "AUX" | "NUL") - || basename - .strip_prefix("COM") - .or_else(|| basename.strip_prefix("LPT")) - .is_some_and(|number| { - matches!( - number, - "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" - ) - }); - part.ends_with('.') || part.ends_with(' ') || reserved + part.ends_with('.') || part.ends_with(' ') || is_reserved_device_name(part) }); if text.starts_with("//./") || (verbatim.is_some() && !drive && !(network && components.len() >= 2)) @@ -409,14 +402,7 @@ pub(crate) fn is_safe_pathspec(path: &str) -> bool { } pub(crate) fn null_device() -> &'static str { - #[cfg(windows)] - { - "NUL" - } - #[cfg(not(windows))] - { - "/dev/null" - } + Platform::HOST.null_device() } pub(crate) fn relative_or_absolute(path: &Path, root: &Path) -> String { @@ -431,3 +417,53 @@ pub(crate) fn relative_or_absolute(path: &Path, root: &Path) -> String { }) .unwrap_or_else(|_| path.to_string_lossy().replace('\\', "/")) } + +#[cfg(test)] +mod tests { + use super::validate_git_path_on; + use lithe_platform::Platform; + use std::path::Path; + + #[test] + fn windows_rejects_relative_names_it_would_store_differently() { + for path in [ + "src/CON.txt", + "src/conin$", + "src/COM1", + "src/name.", + "src/name ", + "C:/repo/AUX", + ] { + assert!( + validate_git_path_on(Path::new(path), Platform::Windows).is_err(), + "{path}" + ); + } + for path in [ + "src/App.java", + "C:/repo/src/console.txt", + "//server/share/repo", + ] { + assert!( + validate_git_path_on(Path::new(path), Platform::Windows).is_ok(), + "{path}" + ); + } + } + + #[test] + fn unix_keeps_posix_names_but_still_checks_windows_paths() { + for path in ["src/CON.txt", "src/name.", "/repo/AUX"] { + assert!( + validate_git_path_on(Path::new(path), Platform::Unix).is_ok(), + "{path}" + ); + } + for path in ["C:/repo/AUX", "//./pipe/repo"] { + assert!( + validate_git_path_on(Path::new(path), Platform::Unix).is_err(), + "{path}" + ); + } + } +} diff --git a/rust/crates/git/src/rewrite.rs b/rust/crates/git/src/rewrite.rs index 75fdb2a8..6cd9f50d 100644 --- a/rust/crates/git/src/rewrite.rs +++ b/rust/crates/git/src/rewrite.rs @@ -624,15 +624,8 @@ fn workspace_snapshot(root: &str) -> Result { .filter(|path| !path.is_empty()) { lithe_protocol::cancellation::check()?; - #[cfg(unix)] - let relative = { - use std::os::unix::ffi::OsStrExt; - Path::new(std::ffi::OsStr::from_bytes(path)) - }; - #[cfg(not(unix))] - let relative = Path::new( - std::str::from_utf8(path).map_err(|_| invalid("Unsupported Git path encoding"))?, - ); + let relative = lithe_platform::paths::native_path_from_bytes(path) + .ok_or_else(|| invalid("Unsupported Git path encoding"))?; let file_path = Path::new(root).join(relative); let metadata = fs::symlink_metadata(&file_path).map_err(snapshot_io_error)?; if metadata.file_type().is_symlink() { diff --git a/rust/crates/git/src/tests.rs b/rust/crates/git/src/tests.rs index daf045a1..0127ca4a 100644 --- a/rust/crates/git/src/tests.rs +++ b/rust/crates/git/src/tests.rs @@ -416,12 +416,6 @@ fn create_tag_arguments_follow_the_lightweight_and_signature_matrix() { } } -#[cfg(target_os = "windows")] -#[test] -fn background_git_processes_do_not_create_windows_console() { - assert_eq!(super::git_process_creation_flags(), 0x08000000); -} - // A Latin-1 `é` (0xE9) decodes to U+FFFD; writing that patch back would // replace the original byte with EF BF BD, so the response must say so. #[test] diff --git a/rust/crates/ide-host/Cargo.toml b/rust/crates/ide-host/Cargo.toml index 423b5ddf..a9fc3540 100644 --- a/rust/crates/ide-host/Cargo.toml +++ b/rust/crates/ide-host/Cargo.toml @@ -12,6 +12,7 @@ mcp = ["dep:rmcp", "dep:reqwest"] [dependencies] axum = "0.8" fs2 = "0.4" +lithe-platform = { path = "../platform" } serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" diff --git a/rust/crates/ide-host/src/lib.rs b/rust/crates/ide-host/src/lib.rs index 2a8deeaf..a8a6a1a5 100644 --- a/rust/crates/ide-host/src/lib.rs +++ b/rust/crates/ide-host/src/lib.rs @@ -153,12 +153,7 @@ fn private_file(path: &std::path::Path, truncate: bool) -> std::io::Result .write(true) .read(true) .truncate(truncate); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - options.open(path) + lithe_platform::fs::owner_only_file(&mut options).open(path) } #[derive(Deserialize)] @@ -190,12 +185,7 @@ fn open(args: Value) -> Result { return Err("The packaged lithe-mcp helper is missing. Reinstall or rebuild Lithe.".into()); } std::fs::create_dir_all(&args.directory).map_err(|e| e.to_string())?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&args.directory, std::fs::Permissions::from_mode(0o700)) - .map_err(|e| e.to_string())?; - } + lithe_platform::fs::restrict_directory_to_owner(&args.directory).map_err(|e| e.to_string())?; let key = format!("{:x}", Sha256::digest(args.workspace_key.as_bytes())); let lock = private_file(&args.directory.join(format!("{key}.lock")), false) .map_err(|e| e.to_string())?; diff --git a/rust/crates/lsp-transport/Cargo.toml b/rust/crates/lsp-transport/Cargo.toml index e7533e61..89da1353 100644 --- a/rust/crates/lsp-transport/Cargo.toml +++ b/rust/crates/lsp-transport/Cargo.toml @@ -11,11 +11,10 @@ test-support = [] [dependencies] lithe-diagnostics = { path = "../diagnostics" } +lithe-git-host = { path = "../git-host" } +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } lithe-remote = { path = "../remote", default-features = false, features = ["client"] } lithe-workspace = { path = "../workspace" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } - -[target.'cfg(windows)'.dependencies] -lithe-git-host = { path = "../git-host" } diff --git a/rust/crates/lsp-transport/src/process.rs b/rust/crates/lsp-transport/src/process.rs index 05daa73a..4b4c584e 100644 --- a/rust/crates/lsp-transport/src/process.rs +++ b/rust/crates/lsp-transport/src/process.rs @@ -1,26 +1,24 @@ //! The language-server process boundary. //! //! The engine owns a language server's process and stdio, but it reaches them -//! only through these traits. That keeps the platform-specific spawn in one -//! place for the Windows client to substitute, and it lets the engine's -//! lifecycle rules -- deadlines, crash handling, restart isolation -- be tested -//! against a scripted server instead of a real one. +//! only through these traits. That lets the engine's lifecycle rules -- +//! deadlines, crash handling, restart isolation -- be tested against a +//! scripted server instead of a real one. //! -//! On Windows a server and everything it starts share one Job Object, so a -//! runtime a batch launcher starts ends with it and none outlives a crashed host. +//! A local server and everything it starts form one +//! [`lithe_git_host::ProcessTree`], so ending the server also ends a runtime +//! that its launcher script started. On Windows the tree is a Job Object, +//! which also ends it when the host crashes; on Unix it is a process group. +use lithe_git_host::ProcessTree; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use std::collections::BTreeMap; use std::io::{Read, Write}; -#[cfg(target_os = "windows")] -use std::path::Path; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::{Arc, Mutex}; -use std::time::Duration; - -#[cfg(target_os = "windows")] -use std::os::windows::process::CommandExt; +use std::time::{Duration, Instant}; /// Everything needed to start a language server, after provider adaptation has /// already rewritten the arguments. @@ -111,8 +109,7 @@ impl LspProcessLauncher for SystemProcessLauncher { .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); - #[cfg(target_os = "windows")] - lithe_git_host::ProcessTree::prepare(&mut command); + ProcessTree::prepare(&mut command); let mut child = command.spawn().map_err(|error| { CoreError::new( ErrorCode::ProcessStartFailed, @@ -120,8 +117,7 @@ impl LspProcessLauncher for SystemProcessLauncher { ) .with_details(error.to_string()) })?; - #[cfg(target_os = "windows")] - let tree = lithe_git_host::ProcessTree::adopt(&mut child).map_err(|error| { + let tree = ProcessTree::adopt(&mut child).map_err(|error| { CoreError::new( ErrorCode::ProcessStartFailed, "Could not take ownership of the language-server process tree.", @@ -142,7 +138,6 @@ impl LspProcessLauncher for SystemProcessLauncher { input: Mutex::new(Some(stdin)), child: Mutex::new(child), termination_failure: Mutex::new(None), - #[cfg(target_os = "windows")] tree, }), output: Box::new(stdout), @@ -152,62 +147,96 @@ impl LspProcessLauncher for SystemProcessLauncher { } fn language_server_command(spec: &LspProcessSpec) -> Command { - #[cfg(target_os = "windows")] - if is_windows_batch_script(&spec.executable) { - let mut command = Command::new("cmd.exe"); - command.envs(&spec.environment); - // Environment expansion is single-pass, so quoted values reach the batch - // file without cmd.exe interpreting path metacharacters or percent pairs. - command.env( - WINDOWS_BATCH_EXECUTABLE_ENV, - windows_batch_env_value(&spec.executable.to_string_lossy()), - ); - for (index, argument) in spec.arguments.iter().enumerate() { - command.env( - windows_batch_argument_env(index), - windows_batch_env_value(argument), - ); - } - command.raw_arg("/D"); - command.raw_arg("/S"); - command.raw_arg("/V:OFF"); - command.raw_arg("/C"); - command.raw_arg(windows_batch_command_line(spec.arguments.len())); - return command; + if let Some(batch) = BatchLaunch::new(spec, Platform::HOST) { + return batch.into_command(); } - let mut command = Command::new(&spec.executable); command.args(&spec.arguments).envs(&spec.environment); command } -#[cfg(target_os = "windows")] -fn is_windows_batch_script(executable: &Path) -> bool { +/// Program that runs a Windows batch script. +const BATCH_INTERPRETER: &str = "cmd.exe"; + +/// Variable that carries the script path to [`BATCH_INTERPRETER`]. +const BATCH_EXECUTABLE_ENV: &str = "LITHE_LSP_BATCH_EXECUTABLE"; + +/// How a Windows batch-script language server is started. +/// +/// `cmd.exe` parses its command line with its own rules, so the script path +/// and arguments travel in environment variables and the command line only +/// references them. Environment expansion is single-pass, so the values +/// reach the script without `cmd.exe` interpreting path metacharacters or +/// percent pairs. +#[derive(Debug, PartialEq, Eq)] +struct BatchLaunch { + /// Variables added to the inherited environment, in the order set. + environment: Vec<(String, String)>, + /// `cmd.exe` arguments, each passed exactly as written. + arguments: Vec, +} + +impl BatchLaunch { + /// The launch of `spec` when `platform` runs it as a batch script. + fn new(spec: &LspProcessSpec, platform: Platform) -> Option { + if !platform.is_windows() || !is_batch_script(&spec.executable) { + return None; + } + let mut environment: Vec<_> = spec + .environment + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect(); + environment.push(( + BATCH_EXECUTABLE_ENV.to_string(), + batch_env_value(&spec.executable.to_string_lossy()), + )); + for (index, argument) in spec.arguments.iter().enumerate() { + environment.push((batch_argument_env(index), batch_env_value(argument))); + } + let arguments = ["/D", "/S", "/V:OFF", "/C"] + .into_iter() + .map(str::to_string) + .chain([batch_command_line(spec.arguments.len())]) + .collect(); + Some(Self { + environment, + arguments, + }) + } + + fn into_command(self) -> Command { + let mut command = Command::new(BATCH_INTERPRETER); + command.envs(self.environment); + for argument in self.arguments { + lithe_platform::process::verbatim_argument(&mut command, argument); + } + command + } +} + +fn is_batch_script(executable: &Path) -> bool { matches!( executable.extension().and_then(|extension| extension.to_str()), Some(extension) if extension.eq_ignore_ascii_case("bat") || extension.eq_ignore_ascii_case("cmd") ) } -#[cfg(target_os = "windows")] -const WINDOWS_BATCH_EXECUTABLE_ENV: &str = "LITHE_LSP_BATCH_EXECUTABLE"; - -#[cfg(target_os = "windows")] -fn windows_batch_argument_env(index: usize) -> String { +fn batch_argument_env(index: usize) -> String { format!("LITHE_LSP_BATCH_ARGUMENT_{index}") } -#[cfg(target_os = "windows")] -fn windows_batch_command_line(argument_count: usize) -> String { - let mut command_line = format!("\"%{WINDOWS_BATCH_EXECUTABLE_ENV}%\""); +fn batch_command_line(argument_count: usize) -> String { + let mut command_line = format!("\"%{BATCH_EXECUTABLE_ENV}%\""); for index in 0..argument_count { - command_line.push_str(&format!(" \"%{}%\"", windows_batch_argument_env(index))); + command_line.push_str(&format!(" \"%{}%\"", batch_argument_env(index))); } format!("\"{command_line}\"") } -#[cfg(target_os = "windows")] -fn windows_batch_env_value(value: &str) -> String { +/// Escapes `value` so the Windows argument parser of the program the script +/// starts reads it back unchanged inside the quotes of [`batch_command_line`]. +fn batch_env_value(value: &str) -> String { let mut escaped = String::new(); let mut backslashes = 0; for character in value.chars() { @@ -230,17 +259,16 @@ fn windows_batch_env_value(value: &str) -> String { } /// Interval between exit checks while a native disposal waits for the root. -#[cfg(not(target_os = "windows"))] -const DISPOSAL_POLL_MS: u64 = 10; +const DISPOSAL_POLL: Duration = Duration::from_millis(10); struct SystemProcess { input: Mutex>, child: Mutex, /// At most one pending cleanup category, transferred to the owning engine. termination_failure: Mutex>, - /// The server and its descendants; dropping the handle ends all of them. - #[cfg(target_os = "windows")] - tree: lithe_git_host::ProcessTree, + /// The server and its descendants. On Windows dropping the handle also + /// ends all of them. + tree: ProcessTree, } impl LspProcessHandle for SystemProcess { @@ -307,32 +335,18 @@ impl LspProcessHandle for SystemProcess { } fn dispose(&self, timeout: Duration) -> Result<(), CoreError> { - #[cfg(target_os = "windows")] - self.tree.terminate(timeout).map_err(|error| { - CoreError::new( - ErrorCode::ProcessFailed, - "Language-server process tree did not exit.", - ) - .with_details(error.to_string()) - })?; // A signalled child is reaped asynchronously, so an immediate status // read after termination can still report it running. Repeat the // idempotent kill and poll until the bounded disposal deadline. The // last kill failure explains a root that outlives the deadline. - #[cfg(not(target_os = "windows"))] - let kill_failure = { - let mut last = None; - let deadline = std::time::Instant::now() + timeout; - while self.exit_status().is_none() && std::time::Instant::now() < deadline { - if let Err(error) = self.terminate_native() { - last = Some(error); - } - std::thread::sleep(Duration::from_millis(DISPOSAL_POLL_MS)); + let deadline = Instant::now() + timeout; + let mut kill_failure = None; + while self.exit_status().is_none() && Instant::now() < deadline { + if let Err(error) = self.terminate_native() { + kill_failure = Some(error); } - last - }; - #[cfg(target_os = "windows")] - let kill_failure: Option = None; + std::thread::sleep(DISPOSAL_POLL); + } if self.exit_status().is_none() { let error = CoreError::new( ErrorCode::ProcessFailed, @@ -343,13 +357,22 @@ impl LspProcessHandle for SystemProcess { None => error, }); } - Ok(()) + // The root is reaped now, so a Unix process group counts only the + // descendants that are still alive. + self.tree + .terminate(deadline.saturating_duration_since(Instant::now())) + .map_err(|error| { + CoreError::new( + ErrorCode::ProcessFailed, + "Language-server process tree did not exit.", + ) + .with_details(error.to_string()) + }) } } impl SystemProcess { fn terminate_native(&self) -> std::io::Result<()> { - #[cfg(target_os = "windows")] let tree_result = self.tree.kill(); let child_result = match self.child.lock() { Ok(mut child) => match child.kill() { @@ -360,7 +383,6 @@ impl SystemProcess { }, Err(_) => Err(std::io::Error::other("Process lock poisoned")), }; - #[cfg(target_os = "windows")] tree_result?; child_result } @@ -374,218 +396,122 @@ fn missing_stream(stream: &str) -> CoreError { .with_details(stream) } +// Starting real servers needs a host of each platform; those tests live in +// the lithe-platform-tests package. #[cfg(test)] -#[cfg(target_os = "windows")] mod tests { use super::{ - language_server_command, windows_batch_command_line, LspProcessLauncher, LspProcessSpec, - SystemProcessLauncher, WINDOWS_BATCH_EXECUTABLE_ENV, + batch_command_line, batch_env_value, language_server_command, BatchLaunch, LspProcessSpec, + BATCH_EXECUTABLE_ENV, }; + use lithe_platform::Platform; use std::collections::BTreeMap; use std::ffi::OsStr; - use std::fs; - use std::io::{Read, Write}; use std::path::PathBuf; - use std::sync::mpsc; - use std::thread; - use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + fn spec(executable: &str, arguments: &[&str]) -> LspProcessSpec { + LspProcessSpec { + executable: PathBuf::from(executable), + arguments: arguments + .iter() + .map(|argument| argument.to_string()) + .collect(), + working_directory: PathBuf::from("workspace"), + environment: BTreeMap::from([("JAVA_HOME".to_string(), "jdk".to_string())]), + } + } #[test] - fn batch_language_server_uses_cmd_exe() { - let spec = LspProcessSpec { - executable: PathBuf::from(r"C:\Program Files\Lithe\language-server.bat"), - arguments: vec!["-data".to_string(), r"C:\workspace data".to_string()], - working_directory: PathBuf::from(r"C:\workspace"), - environment: BTreeMap::new(), - }; + fn windows_starts_batch_scripts_through_cmd_exe() { + let spec = spec( + r"C:\Program Files\Lithe\language-server.bat", + &["-data", r"C:\workspace data"], + ); - let command = language_server_command(&spec); + let launch = BatchLaunch::new(&spec, Platform::Windows).expect("batch launch"); - assert_eq!(command.get_program(), OsStr::new("cmd.exe")); assert_eq!( - windows_batch_command_line(spec.arguments.len()), - r#"""%LITHE_LSP_BATCH_EXECUTABLE%" "%LITHE_LSP_BATCH_ARGUMENT_0%" "%LITHE_LSP_BATCH_ARGUMENT_1%"""# + launch.arguments, + [ + "/D", + "/S", + "/V:OFF", + "/C", + r#"""%LITHE_LSP_BATCH_EXECUTABLE%" "%LITHE_LSP_BATCH_ARGUMENT_0%" "%LITHE_LSP_BATCH_ARGUMENT_1%"""#, + ] + ); + assert_eq!( + launch.environment, + [ + ("JAVA_HOME".to_string(), "jdk".to_string()), + ( + BATCH_EXECUTABLE_ENV.to_string(), + r"C:\Program Files\Lithe\language-server.bat".to_string() + ), + ( + "LITHE_LSP_BATCH_ARGUMENT_0".to_string(), + "-data".to_string() + ), + ( + "LITHE_LSP_BATCH_ARGUMENT_1".to_string(), + r"C:\workspace data".to_string() + ), + ] ); - assert!(command.get_envs().any(|(name, value)| { - name == OsStr::new(WINDOWS_BATCH_EXECUTABLE_ENV) - && value == Some(spec.executable.as_os_str()) - })); } - /// Libtest name of [`argv_echo_helper`], which the batch test re-launches. - const ARGV_ECHO_TEST: &str = "process::tests::argv_echo_helper"; - /// Separates libtest's own arguments from the arguments under test. - const ARGV_ECHO_MARKER: &str = "lithe-argv-echo"; - const ARGV_ECHO_EXECUTABLE_ENV: &str = "LITHE_TEST_ARGV_ECHO_EXECUTABLE"; - const ARGV_ECHO_OUTPUT_ENV: &str = "LITHE_TEST_ARGV_ECHO_OUTPUT"; - - /// Not a scenario of its own: a no-op unless the batch test launches this - /// test binary with it. It then writes the arguments that follow the marker - /// exactly as this native Windows process parsed them. #[test] - fn argv_echo_helper() { - let Some(output) = std::env::var_os(ARGV_ECHO_OUTPUT_ENV) else { - return; - }; - let arguments = std::env::args() - .skip_while(|argument| argument != ARGV_ECHO_MARKER) - .skip(1) - .collect::>(); - fs::write(output, arguments.join("\r\n")).expect("argument echo output"); + fn batch_script_extensions_match_without_case() { + for executable in ["server.cmd", "server.CMD", "server.Bat"] { + assert!( + BatchLaunch::new(&spec(executable, &[]), Platform::Windows).is_some(), + "{executable}" + ); + } + for executable in ["server.exe", "server", "server.sh", "server.bat.txt"] { + assert!( + BatchLaunch::new(&spec(executable, &[]), Platform::Windows).is_none(), + "{executable}" + ); + } } - /// Libtest name of [`stdin_hold_helper`], which the termination test - /// re-launches from a batch script. - const STDIN_HOLD_TEST: &str = "process::tests::stdin_hold_helper"; - const STDIN_HOLD_ENV: &str = "LITHE_TEST_STDIN_HOLD"; - const STDIN_HOLD_READY: &str = "lithe-stdin-hold-ready"; - - /// Not a scenario of its own: a no-op unless the termination test launches - /// this test binary with it. It then stays alive until its inherited stdin - /// closes, like the runtime a batch language-server launcher starts. #[test] - fn stdin_hold_helper() { - if std::env::var_os(STDIN_HOLD_ENV).is_none() { - return; + fn unix_runs_scripts_named_like_batch_files_directly() { + let spec = spec("/opt/server/language-server.cmd", &["--stdio"]); + + assert_eq!(BatchLaunch::new(&spec, Platform::Unix), None); + if !Platform::HOST.is_windows() { + let command = language_server_command(&spec); + assert_eq!( + command.get_program(), + OsStr::new("/opt/server/language-server.cmd") + ); + assert_eq!(command.get_args().collect::>(), ["--stdio"]); } - // Written past libtest's output capture, so the parent sees it at once. - let mut stdout = std::io::stdout().lock(); - writeln!(stdout, "{STDIN_HOLD_READY}").expect("ready marker"); - stdout.flush().expect("ready marker"); - let _ = std::io::stdin().read_to_end(&mut Vec::new()); } #[test] - fn terminating_a_batch_language_server_ends_the_process_it_started() { - let stamp = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("clock") - .as_nanos(); - let root = std::env::temp_dir().join(format!("lithe lsp tree {stamp}")); - fs::create_dir_all(&root).expect("temp directory"); - let executable = root.join("holding server.cmd"); - fs::write( - &executable, - format!( - "@echo off\r\n\"%{ARGV_ECHO_EXECUTABLE_ENV}%\" --exact {STDIN_HOLD_TEST} --test-threads 1\r\n" - ), - ) - .expect("batch script"); - let spec = LspProcessSpec { - executable, - arguments: Vec::new(), - working_directory: root.clone(), - environment: BTreeMap::from([ - ( - ARGV_ECHO_EXECUTABLE_ENV.to_string(), - std::env::current_exe() - .expect("test executable") - .to_string_lossy() - .into_owned(), - ), - (STDIN_HOLD_ENV.to_string(), "1".to_string()), - ]), - }; - - let streams = SystemProcessLauncher - .launch(spec) - .expect("launch batch script"); - let mut output = streams.output; - let (events, received) = mpsc::channel(); - thread::spawn(move || { - let mut seen = String::new(); - let mut buffer = [0_u8; 1024]; - let mut ready = false; - while let Ok(count) = output.read(&mut buffer) { - if count == 0 { - break; - } - seen.push_str(&String::from_utf8_lossy(&buffer[..count])); - if !ready && seen.contains(STDIN_HOLD_READY) { - ready = true; - let _ = events.send("ready"); - } - } - let _ = events.send("closed"); - }); - assert_eq!( - received.recv_timeout(Duration::from_secs(10)), - Ok("ready"), - "the batch script should start its native child" - ); - - streams.handle.terminate(); - - // The child holds the stdout pipe; it closes only once the child is - // gone too, not just the cmd.exe that started it. + fn the_command_line_only_references_environment_variables() { + assert_eq!(batch_command_line(0), r#"""%LITHE_LSP_BATCH_EXECUTABLE%"""#); assert_eq!( - received.recv_timeout(Duration::from_secs(10)), - Ok("closed"), - "terminating the server should end the process its script started" + batch_command_line(1), + r#"""%LITHE_LSP_BATCH_EXECUTABLE%" "%LITHE_LSP_BATCH_ARGUMENT_0%"""# ); - fs::remove_dir_all(root).ok(); } #[test] - fn batch_language_server_preserves_spaced_paths_and_shell_metacharacters() { - let stamp = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("clock") - .as_nanos(); - let root = std::env::temp_dir().join(format!("lithe lsp batch {stamp}")); - fs::create_dir_all(&root).expect("temp directory"); - let executable = root.join("scripted server.cmd"); - let echo_output = root.join("arguments.txt"); - // The script forwards `%*` to a native Windows program, which parses the - // command line the way a real native language server does. - // This test binary plays that program: starting PowerShell here instead - // took from 0.2 s to the whole per-test budget on CI runners. - fs::write( - &executable, - format!( - "@echo off\r\n\"%{ARGV_ECHO_EXECUTABLE_ENV}%\" --exact {ARGV_ECHO_TEST} --test-threads 1 {ARGV_ECHO_MARKER} %*\r\n" - ), - ) - .expect("batch script"); - let arguments = vec![ - "workspace&echo_injected".to_string(), - "percent%PATH%value".to_string(), - "bang!value".to_string(), - "caret^value".to_string(), - "paren(value)".to_string(), - "quoted\"value".to_string(), - r"C:\workspace data\".to_string(), + fn batch_values_escape_quotes_and_the_backslashes_before_them() { + let cases = [ + ("plain", "plain"), + ("percent%PATH%value", "percent%PATH%value"), + ("quoted\"value", r#"quoted\"value"#), + (r#"slash\"quote"#, r#"slash\\\"quote"#), + (r"C:\workspace data\", r"C:\workspace data\\"), + (r"inner\path", r"inner\path"), ]; - let spec = LspProcessSpec { - executable, - arguments: arguments.clone(), - working_directory: root.clone(), - environment: BTreeMap::from([ - ( - ARGV_ECHO_EXECUTABLE_ENV.to_string(), - std::env::current_exe() - .expect("test executable") - .to_string_lossy() - .into_owned(), - ), - ( - ARGV_ECHO_OUTPUT_ENV.to_string(), - echo_output.to_string_lossy().into_owned(), - ), - ]), - }; - - let mut streams = SystemProcessLauncher - .launch(spec) - .expect("launch batch script"); - streams.handle.close_input(); - // Reading to the end waits for the script and the echo process to exit. - let mut output = String::new(); - streams.output.read_to_string(&mut output).expect("stdout"); - - let echoed = fs::read_to_string(&echo_output) - .unwrap_or_else(|error| panic!("echo output missing ({error}); stdout: {output}")); - assert_eq!(echoed, arguments.join("\r\n")); - fs::remove_dir_all(root).ok(); + for (value, escaped) in cases { + assert_eq!(batch_env_value(value), escaped, "{value}"); + } } } diff --git a/rust/crates/platform-tests/Cargo.toml b/rust/crates/platform-tests/Cargo.toml new file mode 100644 index 00000000..3b444b2b --- /dev/null +++ b/rust/crates/platform-tests/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "lithe-platform-tests" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +publish = false +description = "Tests that need a real Windows or Unix host, and the fixture program they start" + +[dev-dependencies] +lithe-git-host = { path = "../git-host" } +lithe-lsp-transport = { path = "../lsp-transport" } +lithe-platform = { path = "../platform" } diff --git a/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs b/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs new file mode 100644 index 00000000..c52d1485 --- /dev/null +++ b/rust/crates/platform-tests/src/bin/lithe-platform-fixture.rs @@ -0,0 +1,94 @@ +//! The program that `lithe-platform-tests` starts in place of a real tool. +//! +//! The first argument selects a [`Mode`]; that type describes each one. Every +//! mode exits after [`LIFETIME_LIMIT`] at the latest, so a test that fails to +//! end a fixture does not leave it running. + +use lithe_platform_tests::{ + Mode, ECHO_FILE_ENV, FAILURE_ERROR, FAILURE_EXIT_CODE, FAILURE_OUTPUT, LIFETIME_EXIT_CODE, + LIFETIME_LIMIT, READY_PREFIX, STREAM_DURATION, STREAM_LINE, +}; +use std::ffi::OsString; +use std::io::{self, Write}; +use std::process::{Command, ExitCode}; +use std::time::Instant; + +fn main() -> ExitCode { + std::thread::spawn(|| { + std::thread::sleep(LIFETIME_LIMIT); + std::process::exit(LIFETIME_EXIT_CODE); + }); + let mut arguments = std::env::args_os().skip(1); + let mode = arguments + .next() + .and_then(|name| name.into_string().ok()) + .and_then(|name| Mode::from_name(&name)); + let Some(mode) = mode else { + eprintln!("usage: lithe-platform-fixture [argument...]"); + return ExitCode::from(2); + }; + let result = match mode { + Mode::Hold => hold(), + Mode::Parent => parent(), + Mode::Failure => fail(), + Mode::Stream => { + stream(); + Ok(()) + } + Mode::EchoArguments => echo(arguments), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("lithe-platform-fixture {}: {error}", mode.name()); + ExitCode::FAILURE + } + } +} + +fn hold() -> io::Result<()> { + let mut output = io::stdout().lock(); + writeln!(output, "{READY_PREFIX}{}", std::process::id())?; + output.flush()?; + drop(output); + io::copy(&mut io::stdin().lock(), &mut io::sink())?; + Ok(()) +} + +fn parent() -> io::Result<()> { + // The child inherits every standard stream, as a runtime started by a + // launcher script does. + let status = Command::new(std::env::current_exe()?) + .arg(Mode::Hold.name()) + .status()?; + if status.success() { + Ok(()) + } else { + Err(io::Error::other(format!("the child ended with {status}"))) + } +} + +fn fail() -> ! { + println!("{FAILURE_OUTPUT}"); + eprintln!("{FAILURE_ERROR}"); + std::process::exit(FAILURE_EXIT_CODE); +} + +fn stream() { + let deadline = Instant::now() + STREAM_DURATION; + let mut output = io::stdout().lock(); + while Instant::now() < deadline { + if writeln!(output, "{STREAM_LINE}").is_err() { + return; + } + } +} + +fn echo(arguments: impl Iterator) -> io::Result<()> { + let file = std::env::var_os(ECHO_FILE_ENV) + .ok_or_else(|| io::Error::other(format!("{ECHO_FILE_ENV} is not set")))?; + let lines: Vec<_> = arguments + .map(|argument| argument.to_string_lossy().into_owned()) + .collect(); + std::fs::write(file, lines.join("\n")) +} diff --git a/rust/crates/platform-tests/src/lib.rs b/rust/crates/platform-tests/src/lib.rs new file mode 100644 index 00000000..e91ad613 --- /dev/null +++ b/rust/crates/platform-tests/src/lib.rs @@ -0,0 +1,117 @@ +//! Tests that need a real Windows or Unix host. +//! +//! Platform rules that can be written as data live in `lithe-platform` and +//! are unit-tested on every build machine. What only a real operating system +//! can show, such as process trees, `cmd.exe` argument parsing and permission +//! bits, is tested in this package. A build machine for one platform can run +//! `cargo test -p lithe-platform -p lithe-platform-tests` instead of the whole +//! workspace. +//! +//! The tests start only the `lithe-platform-fixture` program that this +//! package builds, never an installed tool. This library holds the protocol +//! the fixture and the tests share. + +use std::time::Duration; + +/// What the fixture program does, selected by its first argument. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Writes [`READY_PREFIX`] and its process ID as one line, then runs + /// until its standard input closes, like a language server. + Hold, + /// Starts a [`Mode::Hold`] child that shares its standard streams, then + /// waits for it: a two-level tree like `cmd.exe` starting `java`. The + /// ready line therefore comes from the child, and the output stream + /// closes only once both processes have exited. + Parent, + /// Writes [`FAILURE_OUTPUT`] and [`FAILURE_ERROR`] to its standard + /// streams and exits with [`FAILURE_EXIT_CODE`]. + Failure, + /// Writes [`STREAM_LINE`] lines until writing fails or + /// [`STREAM_DURATION`] passes. + Stream, + /// Writes its remaining arguments, one per line, to the file named by + /// [`ECHO_FILE_ENV`], exactly as the platform passed them. + EchoArguments, +} + +impl Mode { + /// Every mode, in declaration order. + pub const ALL: [Self; 5] = [ + Self::Hold, + Self::Parent, + Self::Failure, + Self::Stream, + Self::EchoArguments, + ]; + + /// The argument that selects this mode. + pub const fn name(self) -> &'static str { + match self { + Self::Hold => "hold", + Self::Parent => "parent", + Self::Failure => "failure", + Self::Stream => "stream", + Self::EchoArguments => "echo-arguments", + } + } + + /// The mode that `name` selects. + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|mode| mode.name() == name) + } +} + +/// Starts the line a [`Mode::Hold`] fixture writes once it runs. +pub const READY_PREFIX: &str = "ready "; + +/// Standard output of a [`Mode::Failure`] fixture. +pub const FAILURE_OUTPUT: &str = "fixture output"; + +/// Standard error of a [`Mode::Failure`] fixture. +pub const FAILURE_ERROR: &str = "fixture error"; + +/// Exit code of a [`Mode::Failure`] fixture. +pub const FAILURE_EXIT_CODE: i32 = 23; + +/// The line a [`Mode::Stream`] fixture repeats. +pub const STREAM_LINE: &str = "fixture-ready"; + +/// How long a [`Mode::Stream`] fixture writes when nobody stops it. +pub const STREAM_DURATION: Duration = Duration::from_secs(3); + +/// Environment variable that names the file a [`Mode::EchoArguments`] +/// fixture writes. +pub const ECHO_FILE_ENV: &str = "LITHE_PLATFORM_FIXTURE_ECHO_FILE"; + +/// Longest time any fixture runs. A test that fails to end its fixture +/// therefore leaves no process behind for longer than this. +pub const LIFETIME_LIMIT: Duration = Duration::from_secs(30); + +/// Exit code of a fixture that reached [`LIFETIME_LIMIT`]. +pub const LIFETIME_EXIT_CODE: i32 = 124; + +/// Parses the process ID from a line that a [`Mode::Hold`] fixture wrote. +pub fn ready_process_id(line: &str) -> Option { + line.trim_end().strip_prefix(READY_PREFIX)?.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::{ready_process_id, Mode, READY_PREFIX}; + + #[test] + fn every_mode_is_selected_by_its_own_name() { + for mode in Mode::ALL { + assert_eq!(Mode::from_name(mode.name()), Some(mode)); + } + assert_eq!(Mode::from_name("unknown"), None); + } + + #[test] + fn ready_lines_carry_the_process_id() { + assert_eq!(ready_process_id(&format!("{READY_PREFIX}42\r\n")), Some(42)); + assert_eq!(ready_process_id("ready"), None); + assert_eq!(ready_process_id("other 42"), None); + } +} diff --git a/rust/crates/platform-tests/tests/platform/git_executable.rs b/rust/crates/platform-tests/tests/platform/git_executable.rs new file mode 100644 index 00000000..ab5173a2 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/git_executable.rs @@ -0,0 +1,39 @@ +//! Git executable resolution on the host's file system. + +use crate::support::TempDir; +use lithe_git_host::configuration::executable; + +// Regression: a backslash launch path makes some Windows hosts capture empty +// Git output, so the resolved executable must reach the process spawner with +// forward slashes. +#[cfg(windows)] +#[test] +fn selected_executable_is_resolved_with_forward_slashes() { + let directory = TempDir::new("lithe git launch path"); + let file = directory.path().join("git.exe"); + std::fs::write(&file, b"").expect("placeholder executable"); + + let resolved = executable(file.to_str()) + .expect("a selected existing file is used") + .to_string_lossy() + .into_owned(); + + assert!(!resolved.contains('\\'), "{resolved}"); + assert!(resolved.ends_with("/git.exe"), "{resolved}"); +} + +#[cfg(unix)] +#[test] +fn a_selected_file_is_used_once_it_has_an_execute_bit() { + use std::os::unix::fs::PermissionsExt; + + let directory = TempDir::new("lithe git launch path"); + let file = directory.path().join("git"); + std::fs::write(&file, b"#!/bin/sh\n").expect("placeholder executable"); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).expect("chmod"); + assert_eq!(executable(file.to_str()), None); + + lithe_platform::fs::add_execute_bits(&file).expect("add execute bits"); + + assert_eq!(executable(file.to_str()), Some(file)); +} diff --git a/rust/crates/platform-tests/tests/platform/lsp_process.rs b/rust/crates/platform-tests/tests/platform/lsp_process.rs new file mode 100644 index 00000000..7e51c4e9 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/lsp_process.rs @@ -0,0 +1,174 @@ +//! Local language servers that `SystemProcessLauncher` starts. + +use crate::support::{OutputWatch, TempDir, DEADLINE, FIXTURE}; +use lithe_lsp_transport::process::{ + LspProcessHandle, LspProcessLauncher, LspProcessSpec, SystemProcessLauncher, +}; +use lithe_platform_tests::Mode; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; + +/// A launched server that is disposed when the test ends, also when an +/// assertion fails first. +struct Server { + handle: Arc, + output: OutputWatch, +} + +impl Drop for Server { + fn drop(&mut self) { + self.handle.close_input(); + let _ = self.handle.dispose(DEADLINE); + } +} + +fn launch( + executable: PathBuf, + arguments: &[&str], + directory: &TempDir, + environment: BTreeMap, +) -> Server { + let streams = SystemProcessLauncher + .launch(LspProcessSpec { + executable, + arguments: arguments + .iter() + .map(|argument| argument.to_string()) + .collect(), + working_directory: directory.path().to_path_buf(), + environment, + }) + .expect("launch the language server"); + Server { + handle: streams.handle, + output: OutputWatch::new(streams.output), + } +} + +/// A server whose process starts the actual runtime, like a launcher script. +fn launch_parent(directory: &TempDir) -> Server { + let server = launch( + PathBuf::from(FIXTURE), + &[Mode::Parent.name()], + directory, + BTreeMap::new(), + ); + server.output.ready(); + server +} + +#[test] +fn terminating_a_language_server_ends_the_processes_it_started() { + let directory = TempDir::new("lithe lsp terminate"); + let server = launch_parent(&directory); + + server.handle.terminate(); + + // The runtime shares the output pipe, so the stream closes only once the + // runtime is gone too, not just the process that started it. + server + .output + .wait_closed("terminating the server should end the process it started"); + assert!(server.handle.take_termination_failure().is_none()); + server + .handle + .dispose(DEADLINE) + .expect("a terminated server is disposed"); +} + +#[test] +fn disposing_a_language_server_ends_the_processes_it_started() { + let directory = TempDir::new("lithe lsp dispose"); + let server = launch_parent(&directory); + + server + .handle + .dispose(DEADLINE) + .expect("every process of the server ends"); + + server + .output + .wait_closed("disposing the server should end the process it started"); + assert!(server.handle.exit_status().is_some()); +} + +#[cfg(windows)] +mod batch { + //! `cmd.exe` scripts that start the actual language server. + + use super::{launch, TempDir, FIXTURE}; + use lithe_platform_tests::{Mode, ECHO_FILE_ENV}; + use std::collections::BTreeMap; + + /// Variable through which a test script finds the fixture program. + const FIXTURE_ENV: &str = "LITHE_TEST_FIXTURE"; + + fn script(directory: &TempDir, name: &str, mode: Mode) -> std::path::PathBuf { + let path = directory.path().join(name); + std::fs::write( + &path, + format!("@echo off\r\n\"%{FIXTURE_ENV}%\" {} %*\r\n", mode.name()), + ) + .expect("batch script"); + path + } + + #[test] + fn batch_language_server_preserves_spaced_paths_and_shell_metacharacters() { + let directory = TempDir::new("lithe lsp batch"); + // The script forwards `%*` to a native Windows program, which parses + // the command line the way a real native language server does. + let executable = script(&directory, "scripted server.cmd", Mode::EchoArguments); + let echo_file = directory.path().join("arguments.txt"); + let arguments = [ + "workspace&echo_injected", + "percent%PATH%value", + "bang!value", + "caret^value", + "paren(value)", + "quoted\"value", + r"C:\workspace data\", + ]; + let server = launch( + executable, + &arguments, + &directory, + BTreeMap::from([ + (FIXTURE_ENV.to_string(), FIXTURE.to_string()), + ( + ECHO_FILE_ENV.to_string(), + echo_file.to_string_lossy().into_owned(), + ), + ]), + ); + server.handle.close_input(); + server + .output + .wait_closed("the script and the program it starts should exit"); + + let echoed = std::fs::read_to_string(&echo_file).expect("echoed arguments"); + assert_eq!(echoed, arguments.join("\n")); + } + + #[test] + fn terminating_a_batch_language_server_ends_the_process_it_started() { + let directory = TempDir::new("lithe lsp batch tree"); + let executable = script(&directory, "holding server.cmd", Mode::Hold); + let server = launch( + executable, + &[], + &directory, + BTreeMap::from([(FIXTURE_ENV.to_string(), FIXTURE.to_string())]), + ); + server.output.ready(); + + server.handle.terminate(); + + // The program holds the stdout pipe; it closes only once that program + // is gone too, not just the cmd.exe that started it. + server + .output + .wait_closed("terminating the server should end the process its script started"); + } +} diff --git a/rust/crates/platform-tests/tests/platform/main.rs b/rust/crates/platform-tests/tests/platform/main.rs new file mode 100644 index 00000000..ef052e22 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/main.rs @@ -0,0 +1,10 @@ +//! Tests that need a real Windows or Unix host. +//! +//! Every module shares one test binary, so the helpers in `support` and the +//! dependencies are built once. + +mod git_executable; +mod lsp_process; +mod permissions; +mod process_tree; +mod support; diff --git a/rust/crates/platform-tests/tests/platform/permissions.rs b/rust/crates/platform-tests/tests/platform/permissions.rs new file mode 100644 index 00000000..ab469eaa --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/permissions.rs @@ -0,0 +1,89 @@ +//! File permissions through `lithe_platform::fs` on the host's file system. + +#[cfg(unix)] +mod unix { + use crate::support::TempDir; + use lithe_platform::fs::{ + add_execute_bits, directory_mode, has_execute_bit, is_launchable_file, owner_only_file, + restrict_directory_to_owner, unix_mode, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE, + }; + use std::fs::{DirBuilder, OpenOptions, Permissions}; + use std::os::unix::fs::PermissionsExt; + use std::path::Path; + + fn permission_bits(path: &Path) -> u32 { + std::fs::metadata(path) + .expect("metadata") + .permissions() + .mode() + & 0o777 + } + + #[test] + fn private_files_and_directories_are_readable_by_their_owner_only() { + let directory = TempDir::new("lithe owner only"); + let file = directory.path().join("token"); + owner_only_file(OpenOptions::new().write(true).create_new(true)) + .open(&file) + .expect("private file"); + let created = directory.path().join("created"); + directory_mode(&mut DirBuilder::new(), OWNER_ONLY_DIRECTORY_MODE) + .create(&created) + .expect("private directory"); + let existing = directory.path().join("existing"); + std::fs::create_dir(&existing).expect("directory"); + std::fs::set_permissions(&existing, Permissions::from_mode(0o755)).expect("chmod"); + + restrict_directory_to_owner(&existing).expect("restrict"); + + assert_eq!(permission_bits(&file), OWNER_ONLY_FILE_MODE); + assert_eq!(permission_bits(&created), OWNER_ONLY_DIRECTORY_MODE); + assert_eq!(permission_bits(&existing), OWNER_ONLY_DIRECTORY_MODE); + } + + #[test] + fn execute_bits_make_a_regular_file_launchable() { + let directory = TempDir::new("lithe execute bits"); + let file = directory.path().join("mvnw"); + std::fs::write(&file, b"#!/bin/sh\n").expect("script"); + std::fs::set_permissions(&file, Permissions::from_mode(0o644)).expect("chmod"); + let before = std::fs::metadata(&file).expect("metadata"); + assert_eq!(unix_mode(&before).map(|mode| mode & 0o777), Some(0o644)); + assert!(!has_execute_bit(&before)); + assert!(!is_launchable_file(&before)); + + add_execute_bits(&file).expect("add execute bits"); + + let after = std::fs::metadata(&file).expect("metadata"); + assert_eq!(permission_bits(&file), 0o755); + assert!(has_execute_bit(&after)); + assert!(is_launchable_file(&after)); + let folder = std::fs::metadata(directory.path()).expect("metadata"); + assert!( + has_execute_bit(&folder) && !is_launchable_file(&folder), + "a searchable directory is not a program" + ); + } +} + +#[cfg(windows)] +mod windows { + use crate::support::TempDir; + use lithe_platform::fs::{add_execute_bits, has_execute_bit, is_launchable_file, unix_mode}; + + #[test] + fn windows_stores_no_mode_and_launches_any_regular_file() { + let directory = TempDir::new("lithe execute bits"); + let file = directory.path().join("tool.exe"); + std::fs::write(&file, b"").expect("placeholder executable"); + + add_execute_bits(&file).expect("adding execute bits does nothing"); + + let metadata = std::fs::metadata(&file).expect("metadata"); + assert_eq!(unix_mode(&metadata), None); + assert!(!has_execute_bit(&metadata)); + assert!(is_launchable_file(&metadata)); + let folder = std::fs::metadata(directory.path()).expect("metadata"); + assert!(!is_launchable_file(&folder)); + } +} diff --git a/rust/crates/platform-tests/tests/platform/process_tree.rs b/rust/crates/platform-tests/tests/platform/process_tree.rs new file mode 100644 index 00000000..06b29381 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/process_tree.rs @@ -0,0 +1,172 @@ +//! `lithe_git_host` runs and process trees on the real host. + +use crate::support::{fixture, OutputWatch, DEADLINE}; +use lithe_git_host::{run, Failure, ProcessTree}; +use lithe_platform_tests::{Mode, FAILURE_ERROR, FAILURE_EXIT_CODE, FAILURE_OUTPUT, STREAM_LINE}; +use std::process::{Child, ChildStdin, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::{Duration, Instant}; + +#[test] +fn incremental_output_can_cancel_before_the_child_exits() { + let began = Instant::now(); + let started = AtomicBool::new(false); + let received = AtomicBool::new(false); + let mut command = fixture(Mode::Stream); + let outcome = run( + &mut command, + None, + || received.load(Ordering::Relaxed) || began.elapsed() > Duration::from_secs(2), + || started.store(true, Ordering::Relaxed), + |_, bytes| { + assert!(started.load(Ordering::Relaxed)); + if bytes + .windows(STREAM_LINE.len()) + .any(|window| window == STREAM_LINE.as_bytes()) + { + received.store(true, Ordering::Relaxed); + } + }, + ); + assert!( + received.load(Ordering::Relaxed), + "deadline elapsed before fixture output" + ); + assert!(matches!(outcome.failure, Some(Failure::Cancelled))); + assert!( + outcome.status.is_some(), + "owned child must be reaped before return" + ); +} + +#[test] +fn nonzero_exit_retains_both_streams() { + let deadline = Instant::now() + Duration::from_secs(2); + let mut command = fixture(Mode::Failure); + let outcome = run( + &mut command, + None, + || Instant::now() > deadline, + || {}, + |_, _| {}, + ); + assert!(outcome.failure.is_none()); + assert_eq!( + outcome.status.and_then(|status| status.code()), + Some(FAILURE_EXIT_CODE) + ); + assert!(String::from_utf8_lossy(&outcome.stdout).contains(FAILURE_OUTPUT)); + assert!(String::from_utf8_lossy(&outcome.stderr).contains(FAILURE_ERROR)); +} + +/// A fixture of `mode` that leads its own [`ProcessTree`] and has reported +/// that it runs. +struct Tree { + tree: ProcessTree, + root: Child, + output: OutputWatch, + // Dropped last: closing it lets a surviving fixture exit on its own. + _input: ChildStdin, +} + +fn spawn_tree(mode: Mode) -> Tree { + let mut command = fixture(mode); + command.stdin(Stdio::piped()).stdout(Stdio::piped()); + ProcessTree::prepare(&mut command); + let mut root = command.spawn().expect("spawn tree root"); + let input = root.stdin.take().expect("root input"); + let output = OutputWatch::new(root.stdout.take().expect("root output")); + let tree = ProcessTree::adopt(&mut root).expect("adopt tree"); + let ready = output.ready(); + assert_eq!( + ready == root.id(), + mode == Mode::Hold, + "a parent fixture reports its child" + ); + Tree { + tree, + root, + output, + _input: input, + } +} + +/// Waits for `root` on another thread, as the owner of a real tree does +/// while it ends the tree. +fn reap_in_background(mut root: Child) -> Receiver { + let (sender, receiver) = mpsc::channel(); + std::thread::spawn(move || { + if let Ok(status) = root.wait() { + let _ = sender.send(status); + } + }); + receiver +} + +#[test] +fn terminate_ends_the_root_and_its_descendants() { + let Tree { + tree, + root, + output, + _input, + } = spawn_tree(Mode::Parent); + let root_exit = reap_in_background(root); + + tree.terminate(DEADLINE) + .expect("every process of the tree ends"); + // The descendant shares the output pipe, so the stream closes only once + // the descendant is gone too. + output.wait_closed("ending the tree should end the descendant"); + root_exit.recv_timeout(DEADLINE).expect("root ended"); + // A second request after the tree is empty is harmless. + tree.terminate(DEADLINE).expect("an empty tree terminates"); +} + +/// Why an owner reaps the root while it ends a tree: until then the root is a +/// zombie that still belongs to its Unix process group. +#[cfg(unix)] +#[test] +fn a_unix_tree_ends_only_once_its_root_is_reaped() { + let Tree { + tree, + root, + output, + _input, + } = spawn_tree(Mode::Hold); + + let unreaped = tree + .terminate(Duration::from_millis(200)) + .expect_err("an unreaped root keeps the group alive"); + assert_eq!(unreaped.kind(), std::io::ErrorKind::TimedOut); + // The root no longer runs: only its process-table entry is left. + output.wait_closed("the killed root should close its output"); + + let status = reap_in_background(root) + .recv_timeout(DEADLINE) + .expect("root reaped"); + assert!(!status.success()); + tree.terminate(DEADLINE) + .expect("a reaped root no longer counts"); +} + +#[cfg(windows)] +#[test] +fn dropping_a_process_tree_ends_it_like_a_crashed_host() { + // The kernel closes the job handle when the host dies; dropping the tree + // closes it the same way, without an explicit terminate. + let Tree { + tree, + root, + output, + _input, + } = spawn_tree(Mode::Parent); + let root_exit = reap_in_background(root); + + drop(tree); + root_exit + .recv_timeout(DEADLINE) + .expect("closing the job ends the root"); + output.wait_closed("closing the job ends the descendant"); +} diff --git a/rust/crates/platform-tests/tests/platform/support.rs b/rust/crates/platform-tests/tests/platform/support.rs new file mode 100644 index 00000000..31f12894 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/support.rs @@ -0,0 +1,120 @@ +//! Starting the fixture program and waiting on it with deadlines. + +use lithe_platform_tests::{ready_process_id, Mode}; +use std::io::{BufRead, BufReader, ErrorKind, Read}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::{Duration, Instant}; + +/// The fixture program this package builds. +pub const FIXTURE: &str = env!("CARGO_BIN_EXE_lithe-platform-fixture"); + +/// Longest wait for one fixture event: generous on a loaded build machine, +/// and well below the fixture's own lifetime limit. +pub const DEADLINE: Duration = Duration::from_secs(10); + +/// A command that starts the fixture in `mode`. +pub fn fixture(mode: Mode) -> Command { + let mut command = Command::new(FIXTURE); + command.arg(mode.name()); + command +} + +#[derive(Debug)] +enum OutputEvent { + Ready(u32), + Closed, + Failed(String), +} + +/// Reads a fixture's standard output on its own thread. +pub struct OutputWatch { + events: Receiver, +} + +impl OutputWatch { + /// Starts reading `output`. + pub fn new(output: impl Read + Send + 'static) -> Self { + let (sender, events) = mpsc::channel(); + std::thread::spawn(move || { + let mut reader = BufReader::new(output); + let mut line = Vec::new(); + let last = loop { + line.clear(); + match reader.read_until(b'\n', &mut line) { + Ok(0) => break OutputEvent::Closed, + Ok(_) => { + if let Some(process_id) = ready_process_id(&String::from_utf8_lossy(&line)) + { + let _ = sender.send(OutputEvent::Ready(process_id)); + } + } + Err(error) if error.kind() == ErrorKind::Interrupted => {} + Err(error) => break OutputEvent::Failed(error.to_string()), + } + }; + let _ = sender.send(last); + }); + Self { events } + } + + /// Waits until a [`Mode::Hold`] fixture reports that it runs, and returns + /// its process ID. + pub fn ready(&self) -> u32 { + match self.events.recv_timeout(DEADLINE) { + Ok(OutputEvent::Ready(process_id)) => process_id, + other => panic!("the fixture did not report that it runs: {other:?}"), + } + } + + /// Waits until the stream closes, which happens only once every process + /// that shares it has exited. Panics with `failure` otherwise. + pub fn wait_closed(&self, failure: &str) { + let deadline = Instant::now() + DEADLINE; + loop { + match self + .events + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + { + Ok(OutputEvent::Closed) => return, + Ok(OutputEvent::Ready(_)) => {} + Ok(OutputEvent::Failed(error)) => panic!("{failure}: reading failed: {error}"), + Err(error) => panic!("{failure}: {error}"), + } + } + } +} + +/// An empty directory under the system temporary directory, removed when +/// dropped. +pub struct TempDir(PathBuf); + +impl TempDir { + /// Creates a directory whose name starts with `prefix`, which may contain + /// spaces. + pub fn new(prefix: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "{prefix} {} {}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + // A crashed earlier run with the same process ID may have left it. + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temporary directory"); + Self(path) + } + + /// The directory. + pub fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/rust/crates/platform/Cargo.toml b/rust/crates/platform/Cargo.toml new file mode 100644 index 00000000..6e088df3 --- /dev/null +++ b/rust/crates/platform/Cargo.toml @@ -0,0 +1,8 @@ +[package] +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 and console-less processes" + +[dependencies] diff --git a/rust/crates/platform/src/fs.rs b/rust/crates/platform/src/fs.rs new file mode 100644 index 00000000..a265571e --- /dev/null +++ b/rust/crates/platform/src/fs.rs @@ -0,0 +1,123 @@ +//! File permissions that only Unix stores. +//! +//! Unix keeps owner, group and other permission bits on every file. Windows +//! uses access-control lists that a new file inherits from its directory, and +//! decides whether a file runs by its extension. These helpers apply or read +//! the Unix bits and do nothing on Windows, so callers state their intent once +//! instead of repeating a `cfg` branch. + +use std::fs::{DirBuilder, Metadata, OpenOptions}; +use std::io; +use std::path::Path; + +/// Owner read and write: the Unix mode of a private file. +pub const OWNER_ONLY_FILE_MODE: u32 = 0o600; + +/// Owner read, write and search: the Unix mode of a private directory. +pub const OWNER_ONLY_DIRECTORY_MODE: u32 = 0o700; + +/// Execute permission for owner, group and others. +pub const EXECUTE_BITS: u32 = 0o111; + +/// Makes a file that `options` creates readable and writable only by its +/// owner. An existing file keeps its permissions. +pub fn owner_only_file(options: &mut OpenOptions) -> &mut OpenOptions { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(OWNER_ONLY_FILE_MODE); + } + options +} + +/// Applies the Unix `mode` to each directory that `builder` creates. +pub fn directory_mode(builder: &mut DirBuilder, mode: u32) -> &mut DirBuilder { + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(mode); + } + #[cfg(not(unix))] + let _ = mode; + builder +} + +/// Restricts the existing directory at `path` to its owner. +pub fn restrict_directory_to_owner(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions( + path, + std::fs::Permissions::from_mode(OWNER_ONLY_DIRECTORY_MODE), + ) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// The Unix mode of `metadata`, including its file-type bits, or `None` on a +/// platform that stores no mode. +pub fn unix_mode(metadata: &Metadata) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + Some(metadata.permissions().mode()) + } + #[cfg(not(unix))] + { + let _ = metadata; + None + } +} + +/// Whether a Unix `mode` lets anyone execute the file. +pub const fn mode_is_executable(mode: u32) -> bool { + mode & EXECUTE_BITS != 0 +} + +/// Whether `metadata` carries a Unix execute bit. Always `false` where the +/// platform stores no mode. +pub fn has_execute_bit(metadata: &Metadata) -> bool { + unix_mode(metadata).is_some_and(mode_is_executable) +} + +/// Whether the host could start the file `metadata` describes as a program: +/// a regular file that, on Unix, also has an execute bit. +pub fn is_launchable_file(metadata: &Metadata) -> bool { + metadata.is_file() && unix_mode(metadata).is_none_or(mode_is_executable) +} + +/// Adds [`EXECUTE_BITS`] to the file at `path`. +pub fn add_execute_bits(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut permissions = std::fs::metadata(path)?.permissions(); + permissions.set_mode(permissions.mode() | EXECUTE_BITS); + std::fs::set_permissions(path, permissions) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::mode_is_executable; + + #[test] + fn any_execute_bit_makes_a_mode_executable() { + for mode in [0o100, 0o010, 0o001, 0o755, 0o100_755] { + assert!(mode_is_executable(mode), "{mode:o}"); + } + for mode in [0o644, 0o600, 0o100_644] { + assert!(!mode_is_executable(mode), "{mode:o}"); + } + } +} diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs new file mode 100644 index 00000000..63a925cc --- /dev/null +++ b/rust/crates/platform/src/lib.rs @@ -0,0 +1,78 @@ +//! Host platform rules expressed as data. +//! +//! Windows and Unix differ in file names, path comparison, permissions and in +//! how a background process starts. Code that depends on such a rule takes a +//! [`Platform`] value instead of compiling one branch per target, so every +//! rule is unit-tested on every build machine. Production code passes +//! [`Platform::HOST`]; tests pass the platform whose rule they check. +//! +//! The few calls that need an operating-system API, such as Unix permission +//! bits or Windows process creation flags, stay behind `cfg` inside this +//! crate. Tests that need a real Windows or Unix host to observe them live in +//! the `lithe-platform-tests` package. + +pub mod fs; +pub mod names; +pub mod paths; +pub mod process; + +/// A family of host operating systems that share the rules in this crate. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Platform { + /// Linux, macOS and every other target that is not Windows. + Unix, + /// Windows. + Windows, +} + +impl Platform { + /// The platform this binary was compiled for. + pub const HOST: Self = if cfg!(windows) { + Self::Windows + } else { + Self::Unix + }; + + /// Whether this is [`Platform::Windows`]. + pub const fn is_windows(self) -> bool { + matches!(self, Self::Windows) + } + + /// File name of the executable called `stem`, as a `PATH` search finds it. + pub fn executable_name(self, stem: &str) -> String { + match self { + Self::Windows => format!("{stem}.exe"), + Self::Unix => stem.to_owned(), + } + } + + /// The device that discards writes and reads as empty. + pub const fn null_device(self) -> &'static str { + match self { + Self::Windows => "NUL", + Self::Unix => "/dev/null", + } + } +} + +#[cfg(test)] +mod tests { + use super::Platform; + + #[test] + fn host_matches_the_compilation_target() { + assert_eq!(Platform::HOST.is_windows(), cfg!(windows)); + } + + #[test] + fn executable_names_follow_the_platform() { + assert_eq!(Platform::Windows.executable_name("git"), "git.exe"); + assert_eq!(Platform::Unix.executable_name("git"), "git"); + } + + #[test] + fn null_devices_follow_the_platform() { + assert_eq!(Platform::Windows.null_device(), "NUL"); + assert_eq!(Platform::Unix.null_device(), "/dev/null"); + } +} diff --git a/rust/crates/platform/src/names.rs b/rust/crates/platform/src/names.rs new file mode 100644 index 00000000..5834f00e --- /dev/null +++ b/rust/crates/platform/src/names.rs @@ -0,0 +1,108 @@ +//! Windows file-name rules, checkable on every host. +//! +//! Windows reserves device names in every directory and strips or rejects +//! some characters, so a name that is ordinary on Unix can address a device, +//! open an alternate data stream, or be stored under a different name there. + +/// Whether `component` names a Windows device such as `CON` or `COM1`. +/// +/// Windows ignores everything from the first `.` and compares without case, +/// so `con.txt` and `Lpt1.log` address devices too. Superscript digits count +/// because Windows treats `COM¹` to `COM³` and `LPT¹` to `LPT³` as devices. +pub fn is_reserved_device_name(component: &str) -> bool { + let base = component + .split('.') + .next() + .unwrap_or_default() + .to_ascii_uppercase(); + matches!( + base.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) || ["COM", "LPT"].iter().any(|prefix| { + base.strip_prefix(prefix).is_some_and(|number| { + matches!( + number, + "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" + ) + }) + }) +} + +/// Whether Windows stores a file called `component` under exactly that name. +/// +/// Rejects device names, a trailing `.` or space (Windows strips both), +/// control characters, and `< > : " | ? *`; a `:` would also open an +/// alternate data stream of another file. +pub fn is_portable_windows_component(component: &str) -> bool { + !component.ends_with(['.', ' ']) + && !component + .chars() + .any(|character| character.is_control() || "<>:\"|?*".contains(character)) + && !is_reserved_device_name(component) +} + +#[cfg(test)] +mod tests { + use super::{is_portable_windows_component, is_reserved_device_name}; + + #[test] + fn device_names_are_reserved_with_any_extension_and_case() { + for name in [ + "CON", + "con.txt", + "Prn", + "aux.log", + "NUL", + "CONIN$", + "conout$.x", + "COM1", + "lpt9.txt", + "COM¹", + "LPT³.log", + ] { + assert!(is_reserved_device_name(name), "{name}"); + } + } + + #[test] + fn names_that_only_resemble_devices_are_not_reserved() { + for name in [ + "CONSOLE", "COM0", "COM10", "LPT", "xCON", "nul_file", ".CON", + ] { + assert!(!is_reserved_device_name(name), "{name}"); + } + } + + #[test] + fn windows_rejects_names_it_would_store_differently() { + for name in [ + "file:stream", + "CON.txt", + "LPT1", + "trailing.", + "space ", + "ab", + "a\"b", + "a|b", + "a?b", + "a*b", + "tab\tname", + ] { + assert!(!is_portable_windows_component(name), "{name}"); + } + } + + #[test] + fn ordinary_names_are_portable() { + for name in [ + "App.java", + "mvnw", + ".gitignore", + "name with spaces.txt", + "äpfel", + ] { + assert!(is_portable_windows_component(name), "{name}"); + } + } +} diff --git a/rust/crates/platform/src/paths.rs b/rust/crates/platform/src/paths.rs new file mode 100644 index 00000000..d4e18c79 --- /dev/null +++ b/rust/crates/platform/src/paths.rs @@ -0,0 +1,126 @@ +//! Path text that follows platform rules. +//! +//! Core identifies workspace files by `/`-separated paths. These helpers +//! compare such paths and convert native path text the way the given +//! platform's file systems would. + +use crate::Platform; +use std::borrow::Cow; +use std::path::Path; + +/// Whether `path` is `ancestor` itself or lies below it. +/// +/// Both paths are `/`-separated and relative to the same root, and `.` names +/// the root. Windows compares them case-insensitively, as its file systems +/// do; Unix compares them exactly. +pub fn relative_path_contains(ancestor: &str, path: &str, platform: Platform) -> bool { + let folded; + let (ancestor, path) = if platform.is_windows() { + folded = (ancestor.to_lowercase(), path.to_lowercase()); + (folded.0.as_str(), folded.1.as_str()) + } else { + (ancestor, path) + }; + ancestor == "." + || path == ancestor + || path + .strip_prefix(ancestor) + .is_some_and(|suffix| suffix.starts_with('/')) +} + +/// Writes every Windows `\` separator as `/`. +/// +/// On Unix `\` is an ordinary file-name character, so the text is returned +/// unchanged. +pub fn slash_separated(path: &str, platform: Platform) -> Cow<'_, str> { + if platform.is_windows() && path.contains('\\') { + Cow::Owned(path.replace('\\', "/")) + } else { + Cow::Borrowed(path) + } +} + +/// Reads a path stored as bytes, such as a NUL-separated Git path list. +/// +/// Unix paths are arbitrary bytes. Other platforms accept only UTF-8 and +/// return `None` for anything else. +pub fn native_path_from_bytes(bytes: &[u8]) -> Option<&Path> { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + Some(Path::new(std::ffi::OsStr::from_bytes(bytes))) + } + #[cfg(not(unix))] + { + std::str::from_utf8(bytes).ok().map(Path::new) + } +} + +#[cfg(test)] +mod tests { + use super::{native_path_from_bytes, relative_path_contains, slash_separated}; + use crate::Platform; + + #[test] + fn the_root_contains_every_path() { + for platform in [Platform::Unix, Platform::Windows] { + assert!(relative_path_contains(".", "src/main.rs", platform)); + assert!(relative_path_contains(".", ".", platform)); + } + } + + #[test] + fn a_directory_contains_itself_and_its_descendants_only() { + for platform in [Platform::Unix, Platform::Windows] { + assert!(relative_path_contains("src", "src", platform)); + assert!(relative_path_contains("src", "src/main.rs", platform)); + assert!(relative_path_contains("src/app", "src/app/a.rs", platform)); + assert!(!relative_path_contains("src", "srcs/main.rs", platform)); + assert!(!relative_path_contains("src/main.rs", "src", platform)); + assert!(!relative_path_contains("", "src", platform)); + } + } + + #[test] + fn only_windows_ignores_case() { + assert!(relative_path_contains( + "Src", + "src/Main.rs", + Platform::Windows + )); + assert!(relative_path_contains( + "ÄPFEL", + "äpfel/a", + Platform::Windows + )); + assert!(!relative_path_contains( + "Src", + "src/Main.rs", + Platform::Unix + )); + } + + #[test] + fn only_windows_treats_backslash_as_a_separator() { + assert_eq!( + slash_separated(r"C:\work\repo", Platform::Windows), + "C:/work/repo" + ); + assert_eq!( + slash_separated(r"name\with\backslash", Platform::Unix), + r"name\with\backslash" + ); + assert_eq!(slash_separated("a/b", Platform::Windows), "a/b"); + } + + #[test] + fn utf8_path_bytes_read_on_every_platform() { + let path = native_path_from_bytes("src/äpfel.rs".as_bytes()).expect("UTF-8 path"); + assert_eq!(path.to_str(), Some("src/äpfel.rs")); + } + + #[test] + fn non_utf8_path_bytes_read_only_on_unix() { + assert_eq!(native_path_from_bytes(b"src/\xff.rs").is_some(), cfg!(unix)); + } +} diff --git a/rust/crates/platform/src/process.rs b/rust/crates/platform/src/process.rs new file mode 100644 index 00000000..d4f7c879 --- /dev/null +++ b/rust/crates/platform/src/process.rs @@ -0,0 +1,68 @@ +//! Process creation and exit status for background tools. + +use std::ffi::OsStr; +use std::process::{Command, ExitStatus}; + +/// The Windows `CREATE_NO_WINDOW` process creation flag. +pub const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +/// Starts a console program without a console window. +/// +/// Core runs tools such as Git as background tasks; on Windows each one would +/// otherwise attach a console and can briefly open the user's terminal. +/// Replaces creation flags set on `command` before. Unix children have no +/// window, so nothing changes there. +pub fn hide_console_window(command: &mut Command) -> &mut Command { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(CREATE_NO_WINDOW); + } + command +} + +/// Appends `argument` to the child's command line exactly as written. +/// +/// A Windows program receives one command-line string and parses it itself, +/// so a program with its own rules, such as `cmd.exe`, needs text that the +/// standard library has not quoted. A Unix program receives an argument +/// array, where every argument is already passed as written. +pub fn verbatim_argument(command: &mut Command, argument: impl AsRef) -> &mut Command { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.raw_arg(argument) + } + #[cfg(not(windows))] + { + command.arg(argument) + } +} + +/// The status of a process that exited normally with `code`. +pub fn exit_status_from_code(code: i32) -> ExitStatus { + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + ExitStatus::from_raw(code << 8) + } + #[cfg(windows)] + { + use std::os::windows::process::ExitStatusExt; + ExitStatus::from_raw(code as u32) + } +} + +#[cfg(test)] +mod tests { + use super::exit_status_from_code; + + #[test] + fn exit_codes_round_trip_through_a_status() { + for code in [0, 1, 23, 128] { + let status = exit_status_from_code(code); + assert_eq!(status.code(), Some(code)); + assert_eq!(status.success(), code == 0); + } + } +} diff --git a/rust/crates/project-generators/Cargo.toml b/rust/crates/project-generators/Cargo.toml index 9947599f..a8369cb8 100644 --- a/rust/crates/project-generators/Cargo.toml +++ b/rust/crates/project-generators/Cargo.toml @@ -6,6 +6,7 @@ license = "Apache-2.0" description = "Project generators declared by Lithe plugins: declarations, the New Project form, generation plans and archive extraction" [dependencies] +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } regex = "1.11" diff --git a/rust/crates/project-generators/src/archive.rs b/rust/crates/project-generators/src/archive.rs index 371c0441..4134e4b1 100644 --- a/rust/crates/project-generators/src/archive.rs +++ b/rust/crates/project-generators/src/archive.rs @@ -5,6 +5,9 @@ //! existing files are never replaced, and the bytes actually written are //! bounded regardless of what the headers claim. +use lithe_platform::fs::{add_execute_bits, mode_is_executable}; +use lithe_platform::names::is_portable_windows_component; +use lithe_platform::Platform; use lithe_plugin_model::{PluginRejection, Validation}; use lithe_protocol::CoreError; use std::collections::HashSet; @@ -150,7 +153,7 @@ fn relative_entry(entry: &zip::read::ZipFile<'_>) -> Validation { } entry .enclosed_name() - .filter(|path| is_plain_relative(path)) + .filter(|path| is_plain_relative(path, Platform::HOST)) .ok_or_else(|| { PluginRejection::at( ARCHIVE_INVALID, @@ -213,12 +216,14 @@ fn validate_entries( Ok(()) } -fn is_plain_relative(path: &Path) -> bool { +/// Whether `path` is a relative path of ordinary names that `platform` +/// stores exactly as written. +fn is_plain_relative(path: &Path, platform: Platform) -> bool { let components: Vec<_> = path.components().collect(); !components.is_empty() && components.len() <= MAX_DEPTH && components.iter().all(|component| match component { - Component::Normal(value) => safe_component(value), + Component::Normal(value) => safe_component(value, platform), _ => false, }) } @@ -237,33 +242,10 @@ fn real_directory(metadata: &fs::Metadata) -> bool { true } -#[cfg(windows)] -fn safe_component(value: &std::ffi::OsStr) -> bool { - let Some(value) = value.to_str() else { - return false; - }; - let base = value.split('.').next().unwrap_or("").to_ascii_uppercase(); - !value.ends_with(['.', ' ']) - && !value - .chars() - .any(|ch| ch.is_control() || "<>:\"|?*".contains(ch)) - && !matches!( - base.as_str(), - "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" - ) - && !["COM", "LPT"].iter().any(|prefix| { - base.strip_prefix(prefix).is_some_and(|n| { - matches!( - n, - "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" - ) - }) - }) -} - -#[cfg(not(windows))] -fn safe_component(_: &std::ffi::OsStr) -> bool { - true +/// Unix stores any name the earlier checks let through. Windows needs valid +/// Unicode and rejects names it would store differently or open as a device. +fn safe_component(value: &std::ffi::OsStr, platform: Platform) -> bool { + !platform.is_windows() || value.to_str().is_some_and(is_portable_windows_component) } /// Creates each directory below `root` along `relative`, refusing to walk @@ -287,22 +269,13 @@ fn ensure_directories(root: &Path, relative: &Path) -> io::Result<()> { Ok(()) } -#[cfg(unix)] fn set_executable(path: &Path, mode: Option) -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - if mode.is_some_and(|mode| mode & 0o111 != 0) { - let mut permissions = fs::metadata(path)?.permissions(); - permissions.set_mode(permissions.mode() | 0o111); - fs::set_permissions(path, permissions)?; + if mode.is_some_and(mode_is_executable) { + add_execute_bits(path)?; } Ok(()) } -#[cfg(not(unix))] -fn set_executable(_: &Path, _: Option) -> io::Result<()> { - Ok(()) -} - #[cfg(test)] mod tests { use super::*; @@ -570,7 +543,6 @@ mod tests { ); } - #[cfg(windows)] #[test] fn windows_archive_paths_reject_ads_device_names_and_verbatim_normalization() { for name in [ @@ -580,11 +552,11 @@ mod tests { "trailing.", "space ", ] { - let (directory, path) = archive(&[(name, b"no", None)]); - let destination = directory.path().join("project"); - fs::create_dir(&destination).unwrap(); - assert!(extract(&path, &destination).is_err(), "{name}"); - assert_eq!(fs::read_dir(destination).unwrap().count(), 0); + assert!( + !is_plain_relative(Path::new(name), Platform::Windows), + "{name}" + ); + assert!(is_plain_relative(Path::new(name), Platform::Unix), "{name}"); } } diff --git a/rust/crates/project-generators/src/plan.rs b/rust/crates/project-generators/src/plan.rs index d6c4df0c..666a72fa 100644 --- a/rust/crates/project-generators/src/plan.rs +++ b/rust/crates/project-generators/src/plan.rs @@ -336,7 +336,7 @@ fn template_files( files.push(json!({ "path": path, "contents": contents, - "executable": is_executable(&metadata), + "executable": lithe_platform::fs::has_execute_bit(&metadata), })); } Ok(files) @@ -378,14 +378,3 @@ fn collect_files( } Ok(()) } - -#[cfg(unix)] -fn is_executable(metadata: &fs::Metadata) -> bool { - use std::os::unix::fs::PermissionsExt; - metadata.permissions().mode() & 0o111 != 0 -} - -#[cfg(not(unix))] -fn is_executable(_: &fs::Metadata) -> bool { - false -} diff --git a/rust/crates/project/Cargo.toml b/rust/crates/project/Cargo.toml index 15f55d4e..870ce107 100644 --- a/rust/crates/project/Cargo.toml +++ b/rust/crates/project/Cargo.toml @@ -17,6 +17,7 @@ encoding_rs = "0.8" lithe-core-rules = { path = "../core-rules" } lithe-diagnostics = { path = "../diagnostics" } lithe-git = { path = "../git" } +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } lithe-request-context = { path = "../request-context" } lithe-text = { path = "../text" } diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index 6b52bb4f..556ecb22 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -1,6 +1,8 @@ //! Text search, with and without the search index. use super::*; +use lithe_platform::paths::relative_path_contains; +use lithe_platform::Platform; /// Applies workspace matching to provider snapshots in one bounded request. pub fn search_text_batch(request: SearchTextBatchRequest) -> Result { @@ -87,16 +89,9 @@ pub fn search(request: SearchRequest) -> Result { pub(crate) fn scope_allows(scopes: &[String], path: &str) -> bool { scopes.is_empty() - || scopes.iter().any(|scope| { - #[cfg(windows)] - let (scope, path) = (scope.to_lowercase(), path.to_lowercase()); - scope.is_empty() - || scope == "." - || path == scope.as_str() - || path - .strip_prefix(scope.as_str()) - .is_some_and(|suffix| suffix.starts_with('/')) - }) + || scopes + .iter() + .any(|scope| scope.is_empty() || relative_path_contains(scope, path, Platform::HOST)) } pub(crate) fn search_with_index( diff --git a/rust/crates/project/src/indexing.rs b/rust/crates/project/src/indexing.rs index 3f36a456..72241142 100644 --- a/rust/crates/project/src/indexing.rs +++ b/rust/crates/project/src/indexing.rs @@ -1,6 +1,8 @@ //! Workspace-owned indexing exclusions, independent of tree visibility and Git writes. use super::files::{existing_root, relative_path}; +use lithe_platform::paths::relative_path_contains; +use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; @@ -593,15 +595,7 @@ pub fn prepare_provider_exclusions(root: &Path) -> Result bool { - #[cfg(windows)] - let (directory, path) = (directory.to_lowercase(), path.to_lowercase()); - #[cfg(windows)] - let (directory, path) = (directory.as_str(), path.as_str()); - directory == "." - || path == directory - || path - .strip_prefix(directory) - .is_some_and(|suffix| suffix.starts_with('/')) + relative_path_contains(directory, path, Platform::HOST) } impl IndexingContext { diff --git a/rust/crates/workspace/Cargo.toml b/rust/crates/workspace/Cargo.toml index 8cf36724..d152c8ee 100644 --- a/rust/crates/workspace/Cargo.toml +++ b/rust/crates/workspace/Cargo.toml @@ -12,6 +12,7 @@ test-support = [] [dependencies] lithe-diagnostics = { path = "../diagnostics" } lithe-git-host = { path = "../git-host" } +lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } lithe-remote = { path = "../remote", default-features = false, features = ["client"] } lithe-request-context = { path = "../request-context" } diff --git a/rust/crates/workspace/src/fs.rs b/rust/crates/workspace/src/fs.rs index f9c22864..a8a0e2df 100644 --- a/rust/crates/workspace/src/fs.rs +++ b/rust/crates/workspace/src/fs.rs @@ -142,13 +142,8 @@ fn native_metadata(metadata: std::fs::Metadata) -> Metadata { } else { methods::FileKind::Other }; - #[cfg(unix)] - let mode = { - use std::os::unix::fs::PermissionsExt; - metadata.permissions().mode() - }; - #[cfg(not(unix))] - let mode = 0; + // A Windows file stores no mode; Git snapshots then compare zero. + let mode = lithe_platform::fs::unix_mode(&metadata).unwrap_or(0); Metadata { kind, size: metadata.len(), @@ -469,10 +464,8 @@ pub fn create_dir_mode(path_value: &Path, recursive: bool, mode: Option) -> None => { let mut builder = std::fs::DirBuilder::new(); builder.recursive(recursive); - #[cfg(unix)] if let Some(mode) = mode { - use std::os::unix::fs::DirBuilderExt; - builder.mode(mode); + lithe_platform::fs::directory_mode(&mut builder, mode); } builder.create(path_value) } diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 2f94424c..493a6751 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -129,15 +129,12 @@ impl Connection { } match &self.transport { ConnectionTransport::Ssh { child, tree } => { - // Grace expiry is advisory: the checked kill and wait below own the result. - if let Err(error) = tree.terminate(EXIT_GRACE) { - if error.kind() != std::io::ErrorKind::TimedOut { - record_cleanup_io("tree-terminate", &error); - } - } let mut child = child .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Err(error) = tree.kill() { + record_cleanup_io("tree-kill", &error); + } if let Err(error) = child.kill() { // Killing an already exited child is an expected missing process. if !matches!(child.try_wait(), Ok(Some(_))) { @@ -147,6 +144,12 @@ impl Connection { if let Err(error) = child.wait() { record_cleanup_io("wait", &error); } + // A Unix process group counts an unreaped root as alive, so the + // tree is awaited only after the wait above; what remains are + // descendants that may outlive the session. + if let Err(error) = tree.terminate(EXIT_GRACE) { + record_cleanup_io("tree-terminate", &error); + } } #[cfg(any(test, feature = "test-support"))] ConnectionTransport::InProcess => {} diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index 5585f9d3..b32e15b8 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -392,7 +392,7 @@ pub fn run_sample_scenario(sample: &Sample) { serde_json::from_slice(&fs::read(package.join("plugin.json")).expect("sample manifest")) .expect("sample manifest JSON"); let plugin_id = manifest["id"].as_str().expect("plugin ID").to_string(); - let package_before = listing(&package); + let package_before = listing(package); // The manifest passes the same validation as an installed plugin. let validated = core( @@ -620,7 +620,7 @@ pub fn run_sample_scenario(sample: &Sample) { // The backend wrote only to the host's state directory, never the package. assert!( - listing(&package) == package_before, + listing(package) == package_before, "the plugin package changed at runtime" ); let state: Vec<_> = fs::read_dir(fixture.root.join("workspace-state"))