Visual Studio Code, rebuilt in Rust
Rust
fix(windows): resolve drive-letter paths and file urls as upstream does
rokartur365f7a51fba8
diff --git a/native/crates/app/build.rs b/native/crates/app/build.rsindex 48b28d46657..13a2778f095 100644--- a/native/crates/app/build.rs+++ b/native/crates/app/build.rs@@ -15,7 +15,7 @@ fn main() {collect_ts(&src.join("vs"), &mut files);files.sort();for file in files {- let module = file.strip_prefix(&src).unwrap().with_extension("").to_string_lossy().into_owned();+ let module = file.strip_prefix(&src).unwrap().with_extension("").to_string_lossy().replace('\\', "/");let Ok(text) = std::fs::read_to_string(&file) else { continue };for captures in call.captures_iter(&text) {let key = captures.get(1).or(captures.get(2)).or(captures.get(3)).unwrap().as_str();diff --git a/native/crates/app/src/editor.rs b/native/crates/app/src/editor.rsindex df2afe8cadc..6c0f80de1d7 100644--- a/native/crates/app/src/editor.rs+++ b/native/crates/app/src/editor.rs@@ -1976,7 +1976,11 @@ mod tests {};assert_eq!(uri("foo", "//testing/virtual.js"), (serde_json::json!("testing"), serde_json::json!("/virtual.js"), "foo://testing/virtual.js".to_string()));assert_eq!(uri("sc", "//auth"), (serde_json::json!("auth"), serde_json::json!(""), "sc://auth".to_string()));- assert_eq!(uri("file", "//w/a.ts"), (serde_json::json!(""), serde_json::json!("//w/a.ts"), "file:////w/a.ts".to_string()));+ if cfg!(windows) {+ assert_eq!(uri("file", "//w/a.ts"), (serde_json::json!("w"), serde_json::json!("/a.ts"), "file://w/a.ts".to_string()));+ } else {+ assert_eq!(uri("file", "//w/a.ts"), (serde_json::json!(""), serde_json::json!("//w/a.ts"), "file:////w/a.ts".to_string()));+ }}#[test]diff --git a/native/crates/app/src/explorer.rs b/native/crates/app/src/explorer.rsindex 18617401145..ed0f24621af 100644--- a/native/crates/app/src/explorer.rs+++ b/native/crates/app/src/explorer.rs@@ -848,19 +848,27 @@ mod tests {tree.rows().into_iter().map(|row| (row.name, row.depth)).collect()}+ /// Windows opens a folder handle only with FILE_FLAG_BACKUP_SEMANTICS, and sets its time only with write access.+ fn open_folder(folder: &Path) -> std::fs::File {+ #[cfg(windows)]+ return std::os::windows::fs::OpenOptionsExt::custom_flags(std::fs::OpenOptions::new().write(true), windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS).open(folder).unwrap();+ #[cfg(not(windows))]+ std::fs::File::open(folder).unwrap()+ }+/// A folder unchanged for 2 s is read from disk once while its mtime stays; a change to its mtime reads it again.#[test]fn reads_a_folder_again_when_its_mtime_changes() {let root = std::env::temp_dir().join(format!("explorer-cache-test-{}", std::process::id()));std::fs::create_dir_all(&root).unwrap();std::fs::write(root.join("a.txt"), "").unwrap();- let set_mtime = |seconds_ago| std::fs::File::open(&root).unwrap().set_modified(SystemTime::now() - std::time::Duration::from_secs(seconds_ago)).unwrap();+ let set_mtime = |seconds_ago| open_folder(&root).set_modified(SystemTime::now() - std::time::Duration::from_secs(seconds_ago)).unwrap();set_mtime(10);let mtime = std::fs::metadata(&root).unwrap().modified().unwrap();let tree = FileTree::new(Workspace::folder(root.clone()), crate::default_settings());assert_eq!(names(&tree), [("a.txt".to_string(), 1)]);std::fs::write(root.join("b.txt"), "").unwrap();- std::fs::File::open(&root).unwrap().set_modified(mtime).unwrap();+ open_folder(&root).set_modified(mtime).unwrap();assert_eq!(names(&tree), [("a.txt".to_string(), 1)], "the mtime did not change, so the folder was not read");set_mtime(5);assert_eq!(names(&tree), [("a.txt".to_string(), 1), ("b.txt".to_string(), 1)]);@@ -877,7 +885,7 @@ mod tests {let second = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - 1;let fine = UNIX_EPOCH + Duration::new(second, 500_000_000);let whole = UNIX_EPOCH + Duration::from_secs(second + 1);- let set_mtime = |mtime| std::fs::File::open(&root).unwrap().set_modified(mtime).unwrap();+ let set_mtime = |mtime| open_folder(&root).set_modified(mtime).unwrap();set_mtime(fine);let tree = FileTree::new(Workspace::folder(root.clone()), crate::default_settings());assert_eq!(names(&tree), [("a.txt".to_string(), 1)]);@@ -1209,7 +1217,7 @@ mod tests {std::fs::create_dir_all(&root).unwrap();for (age, file) in [(3, "a.ts"), (1, "a.js"), (2, "c.md"), (4, "z.css"), (5, "0.md"), (0, "b/"), (5, "x/")] {let file = match file.strip_suffix('/') {- Some(folder) => std::fs::create_dir_all(root.join(folder)).and_then(|_| std::fs::File::open(root.join(folder))),+ Some(folder) => std::fs::create_dir_all(root.join(folder)).map(|_| open_folder(&root.join(folder))),None => std::fs::File::create(root.join(file)),};file.unwrap().set_modified(now - std::time::Duration::from_secs(age * 60)).unwrap();diff --git a/native/crates/app/src/extension_point_messages.rs b/native/crates/app/src/extension_point_messages.rsindex 4305992116d..f03d65ed911 100644--- a/native/crates/app/src/extension_point_messages.rs+++ b/native/crates/app/src/extension_point_messages.rs@@ -194,7 +194,7 @@ fn icons(extensions: &[ScannedExtension]) {let location = join_path(&extension.location, font_path);if !location.starts_with(&extension.location) {// Upstream's message uses `{0}` twice, so the font path stands in for the extension's folder.- return report(Severity::Warning, format!("Expected `contributes.icons.default.fontPath` ({0}) to be included inside extension's folder ({0}).", location.display()));+ return report(Severity::Warning, format!("Expected `contributes.icons.default.fontPath` ({0}) to be included inside extension's folder ({0}).", uri_path(&location)));}}}@@ -259,7 +259,12 @@ fn json_validation_registry(extensions: &[ScannedExtension]) {fn outside_message(point: &str, location: &Path, extension_location: &Path) -> String {let location = crate::editor_history::file_uri_string(location);- format!("Expected `contributes.{point}.url` ({location}) to be included inside extension's folder ({}). This might make the extension non-portable.", extension_location.display())+ format!("Expected `contributes.{point}.url` ({location}) to be included inside extension's folder ({}). This might make the extension non-portable.", uri_path(extension_location))+}++/// A location as upstream's messages show `uri.path`: `/`-separated on Windows too.+pub fn uri_path(location: &Path) -> String {+ crate::uri::Uri::file(&location.to_string_lossy()).path}/// `resources.joinPath`: the relative path's `.` and `..` segments resolved against the root.diff --git a/native/crates/app/src/language_features.rs b/native/crates/app/src/language_features.rsindex f517077c654..03cd714240c 100644--- a/native/crates/app/src/language_features.rs+++ b/native/crates/app/src/language_features.rs@@ -154,8 +154,8 @@ fn matches_pattern(pattern: &Value, path: &str) -> bool {return pattern == path || files::glob::match_pattern(pattern, path, options);}let base = pattern["baseUri"].as_object().map(|_| fs_path(&pattern["baseUri"])).or_else(|| pattern["base"].as_str().map(String::from)).unwrap_or_default();- let base = base.trim_end_matches('/');- let Some(relative) = path.strip_prefix(base).and_then(|rest| rest.strip_prefix('/')) else { return false };+ let base = base.trim_end_matches(std::path::is_separator);+ let Some(relative) = path.strip_prefix(base).and_then(|rest| rest.strip_prefix(std::path::is_separator)) else { return false };files::glob::match_pattern(pattern["pattern"].as_str().unwrap_or_default(), relative, options)}diff --git a/native/crates/app/src/languages.rs b/native/crates/app/src/languages.rsindex 3c7d729c40b..edf1d8772a7 100644--- a/native/crates/app/src/languages.rs+++ b/native/crates/app/src/languages.rs@@ -123,7 +123,7 @@ impl Languages {}let location = crate::extension_point_messages::join_path(extension_location, path);Ok((!location.starts_with(extension_location)).then(|| {- format!("Expected `contributes.grammars.path` ({}) to be included inside extension's folder ({}). This might make the extension non-portable.", location.display(), extension_location.display())+ format!("Expected `contributes.grammars.path` ({}) to be included inside extension's folder ({}). This might make the extension non-portable.", crate::extension_point_messages::uri_path(&location), crate::extension_point_messages::uri_path(extension_location))}))}diff --git a/native/crates/app/src/local_history.rs b/native/crates/app/src/local_history.rsindex eb23b974923..e40d8a8562d 100644--- a/native/crates/app/src/local_history.rs+++ b/native/crates/app/src/local_history.rs@@ -70,7 +70,7 @@ pub fn tracked(settings: &Settings, file: &Path, size: u64) -> Option<Limits> {if relative.as_ref().is_some_and(|relative| expression.matches(relative, None, None).is_some()) {return None;}- let has_absolute_path = exclude.keys().any(|key| key.starts_with('/'));+ let has_absolute_path = exclude.keys().any(|key| key.starts_with('/') || Path::new(key).is_absolute());if has_absolute_path && relative.as_deref() != Some(&*absolute) && expression.matches(&absolute, None, None).is_some() {return None;}diff --git a/native/crates/app/src/quick_input.rs b/native/crates/app/src/quick_input.rsindex f53e98115df..5d7c89351eb 100644--- a/native/crates/app/src/quick_input.rs+++ b/native/crates/app/src/quick_input.rs@@ -918,6 +918,9 @@ pub fn path_label(path: &Path, workspace: Option<&Workspace>) -> String {(true, false) => format!("{} \u{2022} {relative}", folder.name),};}+ if cfg!(windows) {+ return normalize_drive_letter(&path.to_string_lossy());+ }if let Some(home) = std::env::var_os("HOME") {if let Ok(relative) = path.strip_prefix(&home) {return format!("~/{}", relative.to_string_lossy());@@ -926,14 +929,23 @@ pub fn path_label(path: &Path, workspace: Option<&Workspace>) -> String {path.to_string_lossy().into_owned()}+/// labels.ts `normalizeDriveLetter`, which labelService.ts applies on Windows in place of `tildify`: `c:\a` is `C:\a`.+fn normalize_drive_letter(path: &str) -> String {+ let mut chars = path.chars();+ match (chars.next(), chars.next()) {+ (Some(letter), Some(':')) if letter.is_ascii_alphabetic() => format!("{}{}", letter.to_ascii_uppercase(), &path[1..]),+ _ => path.to_owned(),+ }+}+/// `labelService.getUriLabel(uri, { relative, noPrefix: true, separator })` for a file: like `path_label` but-/// without the folder name and the `~`, each `/` written as `separator`.+/// without the folder name and the `~`, each `/` (and `\` on Windows) written as `separator`.pub fn path_label_without_prefix(path: &Path, workspace: Option<&Workspace>, relative: bool, separator: &str) -> String {let label = match workspace.filter(|_| relative).and_then(|workspace| workspace.folder_of(path)) {Some(folder) => path.iter().skip(folder.path.iter().count()).collect::<PathBuf>().to_string_lossy().into_owned(),None => path.to_string_lossy().into_owned(),};- label.replace('/', separator)+ label.replace(['/', std::path::MAIN_SEPARATOR], separator)}/// labels.ts `shorten` with the posix separator: each path cut to the first shortest run of its segments that nodiff --git a/native/crates/app/src/quick_input/tests.rs b/native/crates/app/src/quick_input/tests.rsindex 67226086ae9..5cd352ac048 100644--- a/native/crates/app/src/quick_input/tests.rs+++ b/native/crates/app/src/quick_input/tests.rs@@ -374,7 +374,7 @@ fn path_labels_in_a_multi_root_workspace_start_with_the_folder_name() {let workspace = Workspace { file: Some(PathBuf::from("/test.code-workspace")), folders, transient: false };let label = |path: &str| path_label(Path::new(path), Some(&workspace));assert_eq!(label("/folder1/src/file"), "Sources \u{2022} file");- assert_eq!(label("/folder1/src/folder/file"), "Sources \u{2022} folder/file");+ assert_eq!(label("/folder1/src/folder/file"), format!("Sources \u{2022} folder{}file", std::path::MAIN_SEPARATOR));assert_eq!(label("/folder1/src"), "Sources");assert_eq!(label("/folder1/other"), "/folder1/other");assert_eq!(label("/folder2/other"), "folder2 \u{2022} other");diff --git a/native/crates/app/src/settings_import.rs b/native/crates/app/src/settings_import.rsindex 3bfeb36e852..7ba5aa07d32 100644--- a/native/crates/app/src/settings_import.rs+++ b/native/crates/app/src/settings_import.rs@@ -30,6 +30,11 @@ pub fn sources(home: &Path) -> Vec<Source> {// shortcut: the default %APPDATA%, not FOLDERID_RoamingAppData; read it when a user moves AppData.#[cfg(target_os = "windows")]let support = home.join("AppData").join("Roaming");+ sources_in(home, &support)+}++/// `sources` with the user data folders under `support`.+fn sources_in(home: &Path, support: &Path) -> Vec<Source> {let source = |name, folder: &str, extensions: &str| Source { name, user_dir: support.join(folder).join("User"), extensions_dir: home.join(extensions).join("extensions") };let all = [source("VS Code", "Code", ".vscode"), source("Cursor", "Cursor", ".cursor"), source("VSCodium", "VSCodium", ".vscode-oss")];all.into_iter().filter(|source| source.user_dir.is_dir() || source.extensions_dir.is_dir()).collect()diff --git a/native/crates/app/src/settings_import/tests.rs b/native/crates/app/src/settings_import/tests.rsindex 69895c3c891..dba6f67835a 100644--- a/native/crates/app/src/settings_import/tests.rs+++ b/native/crates/app/src/settings_import/tests.rs@@ -2,18 +2,22 @@ use serde_json::json;use super::*;-/// port/fixtures/settings-import: a home folder with VS Code, Cursor and VSCodium user data.+/// port/fixtures/settings-import: a macOS home folder with VS Code, Cursor and VSCodium user data.fn fixture_home() -> PathBuf {PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/settings-import")}+fn fixture_sources() -> Vec<Source> {+ sources_in(&fixture_home(), &fixture_home().join("Library/Application Support"))+}+fn source(name: &str) -> Source {- sources(&fixture_home()).into_iter().find(|source| source.name == name).unwrap()+ fixture_sources().into_iter().find(|source| source.name == name).unwrap()}#[test]fn finds_the_three_editors() {- let names: Vec<&str> = sources(&fixture_home()).iter().map(|source| source.name).collect();+ let names: Vec<&str> = fixture_sources().iter().map(|source| source.name).collect();assert_eq!(names, ["VS Code", "Cursor", "VSCodium"]);assert!(sources(Path::new("/nonexistent")).is_empty());}diff --git a/native/crates/app/src/snippets.rs b/native/crates/app/src/snippets.rsindex 44c4d085c05..7400932608e 100644--- a/native/crates/app/src/snippets.rs+++ b/native/crates/app/src/snippets.rs@@ -302,8 +302,8 @@ fn to_valid_snippet(extension_name: &str, extension_root: &Path, snippet: &Valueif !location.starts_with(extension_root) {return Err(format!("Expected `contributes.{extension_name}.path` ({}) to be included inside extension's folder ({}). This might make the extension non-portable.",- location.display(),- extension_root.display()+ crate::extension_point_messages::uri_path(&location),+ crate::extension_point_messages::uri_path(extension_root)));}let language = snippet.get("language").and_then(Value::as_str).filter(|language| !language.is_empty()).map(String::from);diff --git a/native/crates/app/src/tasks/problem_collector.rs b/native/crates/app/src/tasks/problem_collector.rsindex b9bfc8f9db2..25a6a924a0b 100644--- a/native/crates/app/src/tasks/problem_collector.rs+++ b/native/crates/app/src/tasks/problem_collector.rs@@ -415,7 +415,7 @@ mod tests {assert!(changes.is_empty(), "the file is delivered once another file starts, and the last line has no break yet");collector.done(&service, &mut changes);let MarkerChange::Set { resource, markers, .. } = &changes[0] else { panic!() };- assert_eq!((resource.to_str().unwrap(), markers.len()), ("/a.go", 2));+ assert_eq!((resource.as_path(), markers.len()), (std::path::Path::new("/a.go"), 2));assert_eq!(changes[1], MarkerChange::Set { owner: "go".into(), resource: "/b.go".into(), markers: vec![json!({ "severity": 8, "startLineNumber": 3, "startColumn": 1, "endLineNumber": 3, "endColumn": (1u64 << 31) - 1, "message": "z" })] });assert_eq!(changes[2], MarkerChange::Remove { owner: "go".into(), resources: vec!["/old.go".into()] });assert_eq!(collector.number_of_matches, 3);@@ -429,7 +429,7 @@ mod tests {let mut changes = Vec::new();let events = collector.process_output("start\n/a.go:1: x\nend\n", &service, &mut changes);assert_eq!(events, [CollectorEvent::BackgroundProcessingBegins, CollectorEvent::BackgroundProcessingEnds]);- assert!(matches!(&changes[0], MarkerChange::Set { resource, .. } if resource.to_str() == Some("/a.go")));+ assert!(matches!(&changes[0], MarkerChange::Set { resource, .. } if resource == std::path::Path::new("/a.go")));assert_eq!(changes[1], MarkerChange::Remove { owner: "go".into(), resources: vec!["/old.go".into()] });}}diff --git a/native/crates/app/src/terminal/completion_service.rs b/native/crates/app/src/terminal/completion_service.rsindex 0af580fe329..1bbf4161a4f 100644--- a/native/crates/app/src/terminal/completion_service.rs+++ b/native/crates/app/src/terminal/completion_service.rs@@ -7,7 +7,9 @@ use serde_json::Value;use super::completion_item::{TerminalCompletion, TerminalCompletionItemKind};-#[cfg(test)]+// The resolver reads POSIX paths only and `from_dto` turns a `\` separator away: port/ledger.md M24 row+// app/src/terminal/completion_service.rs:104.+#[cfg(all(test, not(windows)))]mod tests;/// `ITerminalCompletionProvider` as registered; the caller asks the extension host for its completions.diff --git a/native/crates/app/src/walkthroughs.rs b/native/crates/app/src/walkthroughs.rsindex ccda5b9f35a..a4f54094927 100644--- a/native/crates/app/src/walkthroughs.rs+++ b/native/crates/app/src/walkthroughs.rs@@ -34,10 +34,11 @@ pub struct StartEntry {}/// `startEntries`, in order (`rankElement` is `-order`).-pub const START_ENTRIES: [StartEntry; 5] = [+pub const START_ENTRIES: [StartEntry; 6] = [StartEntry { id: "welcome.showNewFileEntries", title: "New File...", description: "Open a new untitled text file, notebook, or custom editor.", icon: "new-file", when: None, command: "command:welcome.showNewFileEntries" },StartEntry { id: "topLevelOpenMac", title: "Open...", description: "Open a file or folder to start working", icon: "folder-opened", when: Some("!isWeb && isMac"), command: "command:workbench.action.files.openFileFolder" },StartEntry { id: "topLevelOpenFile", title: "Open File...", description: "Open a file to start working", icon: "go-to-file", when: Some("isWeb || !isMac"), command: "command:workbench.action.files.openFile" },+ StartEntry { id: "topLevelOpenFolder", title: "Open Folder...", description: "Open a folder to start working", icon: "folder-opened", when: Some("!isWeb && !isMac"), command: "command:workbench.action.files.openFolder" },StartEntry { id: "topLevelOpenFolderWeb", title: "Open Folder...", description: "Open a folder to start working", icon: "folder-opened", when: Some("!openFolderWorkspaceSupport && workbenchState == 'workspace'"), command: "command:workbench.action.files.openFolderViaWorkspace" },StartEntry { id: "topLevelGitClone", title: "Clone Git Repository...", description: "Clone a remote repository to a local folder", icon: "source-control", when: Some("config.git.enabled && !git.missing"), command: "command:git.clone" },];@@ -827,8 +828,9 @@ mod tests {#[test]fn filters_start_entries_and_steps_by_when() {let shown = |context: &HashMap<String, Value>| START_ENTRIES.iter().filter(|entry| when_holds(entry.when, context)).map(|entry| entry.id).collect::<Vec<_>>();- assert_eq!(shown(&context(&[("config.git.enabled", json!(true))])), ["welcome.showNewFileEntries", "topLevelOpenMac", "topLevelGitClone"]);- assert_eq!(shown(&context(&[("config.git.enabled", json!(true)), ("git.missing", json!(true)), ("workbenchState", json!("workspace"))])), ["welcome.showNewFileEntries", "topLevelOpenMac"]);+ let open: &[&str] = if cfg!(windows) { &["topLevelOpenFile", "topLevelOpenFolder"] } else { &["topLevelOpenMac"] };+ assert_eq!(shown(&context(&[("config.git.enabled", json!(true))])), [&["welcome.showNewFileEntries"], open, &["topLevelGitClone"]].concat());+ assert_eq!(shown(&context(&[("config.git.enabled", json!(true)), ("git.missing", json!(true)), ("workbenchState", json!("workspace"))])), [&["welcome.showNewFileEntries"], open].concat());let beginner = &built_in(Path::new("/app"))[2];let steps = |context: &HashMap<String, Value>| beginner.steps.iter().filter(|step| when_holds(step.when.as_deref(), context)).map(|step| step.id.as_str()).collect::<Vec<_>>();let empty_window = context(&[("config.git.enabled", json!(true)), ("workspaceFolderCount", json!(0)), ("isWorkspaceTrusted", json!(false))]);@@ -860,7 +862,8 @@ mod tests {assert_eq!(walkthroughs[0].source, "Ext");let ids: Vec<&str> = walkthroughs[0].steps.iter().map(|step| step.id.as_str()).collect();assert_eq!(ids, ["pub.ext#tour#one", "pub.ext#tour#two"]);- assert_eq!(walkthroughs[0].steps[0].media, Media::Image { paths: ThemePaths { dark: "/ext/d.png".into(), light: "/ext/l.png".into(), hc_dark: "/ext/h.png".into(), hc_light: "/ext/l.png".into() }, alt_text: "A".into() });+ let media = |name: &str| Path::new("/ext").join(name).to_string_lossy().into_owned();+ assert_eq!(walkthroughs[0].steps[0].media, Media::Image { paths: ThemePaths { dark: media("d.png"), light: media("l.png"), hc_dark: media("h.png"), hc_light: media("l.png") }, alt_text: "A".into() });assert_eq!(walkthroughs[0].steps[1].media, Media::Markdown { path: "/ext/docs/two.md".into(), module: None, base: "/ext/docs".into(), root: "/ext".into() });}}diff --git a/native/crates/app/src/workbench/explorer_actions.rs b/native/crates/app/src/workbench/explorer_actions.rsindex edcd2792312..b7e1fef97d9 100644--- a/native/crates/app/src/workbench/explorer_actions.rs+++ b/native/crates/app/src/workbench/explorer_actions.rs@@ -268,11 +268,11 @@ impl Workbench {let key = if relative { "explorer.copyRelativePathSeparator" } else { "explorer.copyPathSeparator" };let separator = match self.setting(key).as_str() {Some(separator @ ("/" | "\\")) => separator.to_string(),- _ => "/".to_string(),+ _ => std::path::MAIN_SEPARATOR_STR.to_string(),};let workspace = self.workspace();let labels: Vec<String> = resources.iter().map(|path| crate::quick_input::path_label_without_prefix(path, workspace, relative, &separator)).collect();- cx.write_to_clipboard(gpui::ClipboardItem::new_string(labels.join("\n")));+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(labels.join(if cfg!(windows) { "\r\n" } else { "\n" })));Outcome::done()}diff --git a/native/crates/app/src/workbench/url_handler.rs b/native/crates/app/src/workbench/url_handler.rsindex 09ff8664574..f3b9ad5e5aa 100644--- a/native/crates/app/src/workbench/url_handler.rs+++ b/native/crates/app/src/workbench/url_handler.rs@@ -88,8 +88,8 @@ pub(crate) fn open_system_urls(urls: Vec<String>, cx: &mut gpui::App) {let mut args = vec![String::new()];for url in urls {match Uri::parse(&url) {- // `Uri::new` makes a file path absolute: it starts with `/`, so it never reads as a flag.- Ok(uri) if uri.scheme == "file" => args.push(uri.path),+ // An absolute `fsPath` starts with `/` or a drive letter, so it never reads as a flag.+ Ok(uri) if uri.scheme == "file" => args.push(uri.fs_path()),_ => open_system_url(url, cx),}}@@ -139,7 +139,8 @@ pub(super) async fn handle_url(workbench: &WeakEntity<Workbench>, uri: Uri, trus/// `getWindowOpenableFromProtocolUrl` and `shouldBlockOpenable` for a `file` url, opened in `gotoLineMode`.async fn open_file_url(workbench: &WeakEntity<Workbench>, raw_path: &str, new_window: bool, cx: &mut AsyncWindowContext) -> bool {let (path, line) = parse_line_and_column(raw_path);- let path = PathBuf::from(path);+ // `URI.file(uri.fsPath)`: `/C:/a` is `c:\a` on Windows.+ let path = PathBuf::from(Uri::file(&path).fs_path());let openable = Openable::of(path.clone());// A protocol url opens a workspace file, or a file or folder (`fileUri`).let what = match path.extension().is_some_and(|extension| extension == "code-workspace") {@@ -282,6 +283,15 @@ impl Workbench {mod tests {use super::*;+ fn url_path(path: &std::path::Path) -> String {+ Uri::file(&path.to_string_lossy()).path+ }++ /// The path a file url opens: `fsPath` lowercases a Windows drive letter.+ fn fs_path_of(path: &std::path::Path) -> PathBuf {+ PathBuf::from(Uri::file(&path.to_string_lossy()).fs_path())+ }+#[test]fn parse_line_and_column_matches_extpath() {assert_eq!(parse_line_and_column("/a/b.ts:10:5"), ("/a/b.ts".into(), Some((10., 5.))));@@ -302,10 +312,10 @@ mod tests {let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));workbench.update(cx, |workbench, _| workbench.update_setting("security.promptForLocalFileProtocolHandling", json!(false)));- cx.cx.update(|cx| open_system_url(format!("{URL_PROTOCOL}://file{}:2:1", file.display()), cx));+ cx.cx.update(|cx| open_system_url(format!("{URL_PROTOCOL}://file{}:2:1", url_path(&file)), cx));cx.run_until_parked();let opened = workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| (editor.document().path.clone(), editor.selections[0].start().line)));- assert_eq!(opened, Some((file, 1)));+ assert_eq!(opened, Some((fs_path_of(&file), 1)));std::fs::remove_dir_all(dir).unwrap();}@@ -324,12 +334,12 @@ mod tests {let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));// NSURL `absoluteString`, as gpui hands it over.- let url = format!("file://{}", workspace_file.display()).replace(' ', "%20");+ let url = Uri::file(&workspace_file.to_string_lossy()).to_string(false);cx.cx.update(|cx| open_system_urls(vec![url], cx));cx.run_until_parked();let windows: Vec<gpui::Entity<Workbench>> = cx.cx.update(|cx| cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.entity(cx).ok()).collect());let opened: Vec<Vec<PathBuf>> = windows.iter().filter(|other| **other != workbench).filter_map(|other| other.read_with(cx, |other, _| other.workspace().map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone()).collect()))).collect();- assert_eq!(opened, [["one", "two", "three"].map(|folder| dir.join(folder)).to_vec()]);+ assert_eq!(opened, [["one", "two", "three"].map(|folder| fs_path_of(&dir.join(folder))).to_vec()]);std::fs::remove_dir_all(dir).unwrap();}@@ -347,7 +357,7 @@ mod tests {let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));let open_from_finder = |cx: &mut gpui::VisualTestContext| {- cx.cx.update(|cx| open_system_urls(vec![format!("file://{}", file.display())], cx));+ cx.cx.update(|cx| open_system_urls(vec![Uri::file(&file.to_string_lossy()).to_string(false)], cx));cx.run_until_parked();};workbench.update(cx, |workbench, _| workbench.update_setting("window.openFilesInNewWindow", json!("default")));@@ -358,7 +368,7 @@ mod tests {cx.cx.update(|cx| cx.windows().into_iter().find(|handle| handle.downcast::<Workbench>().is_some_and(|handle| handle.entity(cx).is_ok_and(|other| other != workbench))).unwrap().update(cx, |_, window, _| window.remove_window()).unwrap());open_from_finder(cx);assert_eq!(cx.cx.update(|cx| cx.windows().len()), 1);- assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().path.clone())), Some(file));+ assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().path.clone())), Some(fs_path_of(&file)));std::fs::remove_dir_all(dir).unwrap();}@@ -397,13 +407,13 @@ mod tests {let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));workbench.update(cx, |workbench, _| workbench.update_setting("security.promptForLocalFileProtocolHandling", json!(false)));- let url = format!("{URL_PROTOCOL}://file{}:2:1?windowId=_blank", file.display());+ let url = format!("{URL_PROTOCOL}://file{}:2:1?windowId=_blank", url_path(&file));workbench.update_in(cx, |workbench, window, cx| workbench.open_protocol_url(&url, window, cx));cx.run_until_parked();assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().is_none()), "this window opens nothing");let others: Vec<gpui::Entity<Workbench>> = cx.cx.update(|cx| cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.entity(cx).ok()).collect());let opened: Vec<_> = others.iter().filter(|other| **other != workbench).map(|other| other.read_with(cx, |other, _| other.editors.active().map(|editor| (editor.document().path.clone(), editor.selections[0].start().line)))).collect();- assert_eq!(opened, [Some((file, 1))]);+ assert_eq!(opened, [Some((fs_path_of(&file), 1))]);std::fs::remove_dir_all(dir).unwrap();}@@ -420,11 +430,11 @@ mod tests {let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));workbench.update(cx, |workbench, _| workbench.update_setting("security.promptForLocalFileProtocolHandling", json!(false)));- let link = format!("{URL_PROTOCOL}://file{}:2:1", file.display());+ let link = format!("{URL_PROTOCOL}://file{}:2:1", url_path(&file));workbench.update_in(cx, |workbench, window, cx| workbench.open_webview_link(&link, &json!(false), window, cx));cx.run_until_parked();let opened = workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().path.clone()));- assert_eq!(opened, Some(file));+ assert_eq!(opened, Some(fs_path_of(&file)));std::fs::remove_dir_all(dir).unwrap();}diff --git a/native/crates/config/src/workspace.rs b/native/crates/config/src/workspace.rsindex 10e8371ace0..40717d390d4 100644--- a/native/crates/config/src/workspace.rs+++ b/native/crates/config/src/workspace.rs@@ -201,6 +201,9 @@ fn resolve(base: &Path, path: &str) -> PathBuf {/// `starts_with` checks whole segments.fn comparison_key(path: &Path) -> String {let mut key = path.to_string_lossy().to_lowercase();+ if cfg!(windows) {+ key = key.replace('\\', "/");+ }if !key.ends_with('/') {key.push('/');}diff --git a/native/crates/files/src/lib.rs b/native/crates/files/src/lib.rsindex 77663202acd..fc7bdbd7af7 100644--- a/native/crates/files/src/lib.rs+++ b/native/crates/files/src/lib.rs@@ -212,7 +212,9 @@ pub trait FileSystem {/// `FileService.withProvider`: the provider's capabilities.fn with_provider(fs: &mut impl FileSystem, resource: &Resource) -> Result<u32> {- if resource.scheme == "file" && !resource.path.starts_with('/') {+ // A `file` resource holds the fs path, which on Windows starts with a drive or `\\`.+ let absolute = resource.path.starts_with('/') || cfg!(windows) && std::path::Path::new(&resource.path).is_absolute();+ if resource.scheme == "file" && !absolute {return Err(operation_error(Operation::InvalidPath, format!("Unable to resolve filesystem provider with relative file path '{}'", resource.for_error())));}fs.capabilities(&resource.scheme).ok_or_else(|| FileError {