Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5478,9 +5478,11 @@ by `rust/fixtures/workspace/directory-rules-v1.json`.

`workspace.planDuplicate` takes `{ name, isDirectory, existing?, caseInsensitive? }` and returns
`{ name }`; `workspace.planPaste` takes `{ items: [{ name, isDirectory }], existing?, caseInsensitive? }`
and returns `{ names }`. A file name is split at its last dot, a directory name and a leading-dot name
are not. Core never touches the file system: the host passes the names it has seen to exist, creates the
copy without replacing anything (`FileManager.copyItem`, which refuses an existing destination, on macOS;
and returns `{ names }`. Every name must be one file name on the host: an empty name, `.`, `..` and a
name containing `/` are rejected everywhere, and on Windows a name containing `\` or `:` is too, while
on Unix those are ordinary characters. A file name is split at its last dot, a directory name and a
leading-dot name are not. Core never touches the file system: the host passes the names it has seen
to exist, creates the copy without replacing anything (`FileManager.copyItem`, which refuses an existing destination, on macOS;
`create_new` and `MoveFileEx` without replacement on Windows) and, when that fails because the name
appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports
the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`.
Expand Down
43 changes: 43 additions & 0 deletions rust/crates/core/src/tests/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,49 @@ fn git_write_appends_shared_and_local_ignore_patterns_without_duplicates() {
fs::remove_dir_all(root).expect("temporary workspace should be removable");
}

/// A Unix file name may hold a backslash. The pattern must ignore that one file
/// rather than read the backslash as a separator or let Git read it as an escape.
#[cfg(unix)]
#[test]
fn git_write_ignores_a_unix_file_whose_name_holds_a_backslash() {
let root = temporary_root("git-write-ignore-backslash");
fs::create_dir_all(root.join("logs")).expect("temporary repository should be creatable");
let run = |arguments: &[&str]| {
Command::new("git")
.args(arguments)
.current_dir(&root)
.output()
.expect("git should be available")
};
assert!(run(&["init", "-q"]).status.success());
fs::write(root.join("logs\\app.log"), "ignored\n").expect("log file should be writable");
fs::write(root.join("logs/app.log"), "kept\n").expect("nested file should be writable");

let response: Value = serde_json::from_str(&execute_json(
&serde_json::to_string(&serde_json::json!({
"id": "ignore",
"command": "git.write",
"payload": {"root": root, "operation": "ignore", "paths": ["logs\\app.log"]}
}))
.expect("ignore request should encode"),
))
.expect("ignore response should be JSON");
assert_eq!(response["ok"], true, "{response:?}");

assert_eq!(
fs::read_to_string(root.join(".gitignore")).expect("gitignore should be readable"),
"/logs\\\\app.log\n"
);
assert!(run(&["check-ignore", "-q", "logs\\app.log"])
.status
.success());
assert!(!run(&["check-ignore", "-q", "logs/app.log"])
.status
.success());

fs::remove_dir_all(root).expect("temporary workspace should be removable");
}

#[test]
fn git_write_edits_a_local_commit_message_and_rebuilds_descendants() {
let root = history_rewrite_repository("git-edit-commit-message");
Expand Down
22 changes: 20 additions & 2 deletions rust/crates/core/src/tests/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1763,6 +1763,9 @@ fn file_commands_round_trip_and_reject_traversal() {
assert_eq!(traversal_response["ok"], false);
assert_eq!(traversal_response["error"]["code"], "invalid_request");

// Windows reads these as leaving the root and rejects them. On Unix each is
// one file name inside the root, and none of them exists. Neither reads
// outside the workspace.
for path in [
"..\\outside.txt",
"nested\\..\\outside.txt",
Expand All @@ -1777,12 +1780,27 @@ fn file_commands_round_trip_and_reject_traversal() {
&serde_json::to_string(&request).expect("Windows path request should encode"),
))
.expect("Windows path response should be JSON");
assert_eq!(response["ok"], false, "path {path} should be rejected");
assert_eq!(response["error"]["code"], "invalid_request");
assert_eq!(response["ok"], false, "path {path} should not be read");
}

#[cfg(unix)]
{
fs::write(root.join("..\\outside.txt"), "inside")
.expect("a Unix name with a backslash should be writable");
let named = serde_json::json!({
"id": "backslash-name",
"command": "file.read",
"payload": {"root": root, "path": "..\\outside.txt"}
});
let named_response: Value = serde_json::from_str(&execute_json(
&serde_json::to_string(&named).expect("backslash name request should encode"),
))
.expect("backslash name response should be JSON");
assert_eq!(
named_response["data"]["text"], "inside",
"{named_response:?}"
);

std::os::unix::fs::symlink(&outside, root.join("link"))
.expect("test symlink should be creatable");
let symlink_write = serde_json::json!({
Expand Down
50 changes: 48 additions & 2 deletions rust/crates/core/src/tests/project_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

use serde_json::{json, Value};

fn run(request: &Value) -> Value {
fn execute(command: &str, payload: Value) -> Value {
serde_json::from_str(&crate::execute_json(
&json!({"command": "workspace.projectTree.rows", "payload": request}).to_string(),
&json!({"command": command, "payload": payload}).to_string(),
))
.unwrap()
}

fn run(request: &Value) -> Value {
execute("workspace.projectTree.rows", request.clone())
}

#[test]
fn shared_project_tree_rows_fixture_runs_every_case() {
let fixture: Value = serde_json::from_str(include_str!(concat!(
Expand All @@ -31,3 +35,45 @@ fn shared_project_tree_rows_fixture_runs_every_case() {
);
}
}

/// Issue 2009: Spring Boot on macOS writes a Windows-style `logging.file.path`
/// such as `D:\logs` as one folder name. On Unix `\` and `:` are ordinary
/// file-name characters, so the listing keeps each entry one level below its
/// folder and the project tree accepts the rows built from it.
#[cfg(unix)]
#[test]
fn names_with_backslashes_stay_one_level_below_their_folder_on_unix() {
let root = super::support::temporary_root("backslash-file-names");
std::fs::create_dir_all(root.join(r"D:\logs")).unwrap();
std::fs::write(root.join(r"D:\logs").join("spring.log"), "").unwrap();
std::fs::write(root.join(r"D:\logs\app.log"), "").unwrap();

let listing = execute(
"workspace.listDirectories",
json!({"root": root, "paths": ["", r"D:\logs"]}),
);
let removed = std::fs::remove_dir_all(&root);
assert_eq!(listing["ok"], true, "{listing}");
removed.expect("temporary fixture should be removable");

let children = |index: usize| {
listing["data"]["directories"][index]["children"]
.as_array()
.unwrap()
.iter()
.map(|child| child["path"].as_str().unwrap().to_string())
.collect::<Vec<_>>()
};
assert_eq!(children(0), [r"D:\logs", r"D:\logs\app.log"]);
assert_eq!(listing["data"]["directories"][1]["path"], r"D:\logs");
assert_eq!(children(1), [r"D:\logs/spring.log"]);

let rows = run(&json!({"nodes": [
{"path": "", "depth": 0, "open": true},
{"path": r"D:\logs", "depth": 1, "open": true},
{"path": r"D:\logs/spring.log", "depth": 2},
{"path": r"D:\logs\app.log", "depth": 1},
]}));
assert_eq!(rows["ok"], true, "{rows}");
assert_eq!(rows["data"]["rows"], json!([0, 1, 2, 3]));
}
1 change: 1 addition & 0 deletions rust/crates/debug/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ description = "Debug Adapter Protocol sessions for Lithe: adapter declarations,
[dependencies]
base64 = "0.22"
lithe-diagnostics = { path = "../diagnostics" }
lithe-platform = { path = "../platform" }
lithe-plugin-model = { path = "../plugin-model" }
lithe-protocol = { path = "../protocol" }
serde = { version = "1.0", features = ["derive"] }
Expand Down
13 changes: 7 additions & 6 deletions rust/crates/debug/src/projection_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//! Version 1 stays authoritative until every consumer migrates. The engine emits v2
//! beside it, built here from the raw adapter body so no v1 narrowing leaks into v2.

use lithe_platform::paths::slash_separated;
use lithe_platform::Platform;
#[cfg(test)]
use lithe_protocol::{CoreError, ErrorCode};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -456,13 +458,12 @@ fn finish(projection: SessionProjection) -> Option<SessionProjection> {
fn workspace_relative(path: &str, root: &str) -> Option<String> {
let is_windows =
root.as_bytes().get(1) == Some(&b':') && root.as_bytes()[0].is_ascii_alphabetic();
let normalize = |text: &str| {
if is_windows {
text.replace('\\', "/")
} else {
text.to_string()
}
let platform = if is_windows {
Platform::Windows
} else {
Platform::Unix
};
let normalize = |text: &str| slash_separated(text, platform).into_owned();
let (path, root) = (normalize(path), normalize(root));
let root = root.trim_end_matches('/');
let rest = if is_windows && path.len() >= root.len() && path.is_char_boundary(root.len()) {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/document-uri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ license = "Apache-2.0"
description = "Lexical conversions between native filesystem paths and LSP document URIs that both platform hosts share"

[dependencies]
lithe-platform = { path = "../platform" }
lithe-protocol = { path = "../protocol" }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["preserve_order"] }
Expand Down
6 changes: 4 additions & 2 deletions rust/crates/document-uri/src/encode.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Platform-neutral conversion of absolute filesystem paths to LSP file URIs.

use lithe_platform::paths::slash_separated;
use lithe_platform::Platform;
use lithe_protocol::{CoreError, ErrorCode};
use serde::Deserialize;
use serde_json::{json, Value};
Expand Down Expand Up @@ -77,13 +79,13 @@ fn document_uri(path: &str, platform: DocumentPathPlatform) -> Result<String, Co
path.to_owned()
}
DocumentPathPlatform::Windows => {
let path = path.replace('\\', "/");
let path = slash_separated(path, Platform::Windows);
if let Some(rest) = path.strip_prefix("//?/UNC/") {
format!("//{rest}")
} else if let Some(rest) = path.strip_prefix("//?/") {
rest.to_owned()
} else {
path
path.into_owned()
}
}
DocumentPathPlatform::Auto => unreachable!("auto platform is resolved above"),
Expand Down
1 change: 1 addition & 0 deletions rust/crates/execution/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ test-support = []
[dependencies]
ignore = "=0.4.33"
lithe-diagnostics = { path = "../diagnostics" }
lithe-platform = { path = "../platform" }
lithe-plugin-model = { path = "../plugin-model" }
lithe-protocol = { path = "../protocol" }
lithe-toolchain = { path = "../toolchain" }
Expand Down
6 changes: 5 additions & 1 deletion rust/crates/execution/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ pub use project_toolchain::{project_toolchain, ProjectToolchainRequest};

use super::generated_layer::{self, GeneratedLayer};
use super::types::{Confidence, Execution, RunCategory};
use lithe_protocol::{invalid_relative_path, CoreError, ErrorCode};
use lithe_platform::paths::{
invalid_native_relative_path, invalid_portable_relative_path, slash_separated_path,
};
use lithe_platform::Platform;
use lithe_protocol::{CoreError, ErrorCode};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
Expand Down
5 changes: 1 addition & 4 deletions rust/crates/execution/src/configuration/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ impl BuildProviderRunReference {
.user_arguments
.iter()
.any(|arg| arg.len() > 4096 || arg.contains('\0'))
|| invalid_relative_path(&self.root)
|| self.root.is_empty()
|| self.root.contains('\\')
|| self.root.contains('\0')
|| invalid_portable_relative_path(&self.root)
{
return Err(CoreError::new(
ErrorCode::InvalidRequest,
Expand Down
9 changes: 4 additions & 5 deletions rust/crates/execution/src/configuration/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,10 @@ pub(crate) fn project_inputs(root: &Path) -> Result<ProjectInputs, CoreError> {
if !fingerprint_input(&path) {
continue;
}
let relative = path
.strip_prefix(root)
.expect("scan stays within root")
.to_string_lossy()
.replace('\\', "/");
let relative = slash_separated_path(
path.strip_prefix(root).expect("scan stays within root"),
Platform::HOST,
);
lithe_protocol::cancellation::check()?;
// The scan lists files through the workspace adapter, so content reads
// must use the same adapter or remote projects look permanently unreadable.
Expand Down
4 changes: 1 addition & 3 deletions rust/crates/execution/src/configuration/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use super::*;
/// Extracts existing Run document values; framework goals and runtime semantics stay in providers.
pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result<Value, CoreError> {
let root = existing_root(&request.root)?;
if invalid_relative_path(&request.provider_root)
|| !project_directory_exists(&root, &request.provider_root)
{
if !project_directory_exists(&root, &request.provider_root) {
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"The provider instance leaves the workspace.",
Expand Down
6 changes: 3 additions & 3 deletions rust/crates/execution/src/configuration/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub(crate) fn normalize_working_directory(root: &Path, value: &str) -> Result<St

pub(crate) fn normalize_project_directory(root: &Path, value: &str) -> Result<String, CoreError> {
let candidate = Path::new(value);
if (!candidate.is_absolute() && invalid_relative_path(value))
if (!candidate.is_absolute() && invalid_native_relative_path(value, Platform::HOST))
|| candidate
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
Expand Down Expand Up @@ -86,12 +86,12 @@ pub(crate) fn normalize_project_directory(root: &Path, value: &str) -> Result<St
if relative.as_os_str().is_empty() {
Ok(".".to_string())
} else {
Ok(relative.to_string_lossy().replace('\\', "/"))
Ok(slash_separated_path(relative, Platform::HOST))
}
}

pub(crate) fn project_directory_exists(root: &Path, value: &str) -> bool {
if invalid_relative_path(value) {
if invalid_native_relative_path(value, Platform::HOST) {
return false;
}
let Ok(canonical_root) = fs::canonicalize(root) else {
Expand Down
Loading
Loading