Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix opening `path:line` in a running Zed on Windows (#66501)
Ivan K.e21ff1b368b0
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 0f4d6746371..a14495666dd 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -26,7 +26,7 @@ use std::{thread::{self, JoinHandle},};use tempfile::{NamedTempFile, TempDir};-use util::paths::PathWithPosition;+use util::paths::{PathWithPosition, parse_path_with_position};use walkdir::WalkDir;use std::io::IsTerminal;@@ -155,53 +155,6 @@ struct Args {askpass: Option<String>,}-/// Parses a path containing a position (e.g. `path:line:column`)-/// and returns its canonicalized string representation.-///-/// If a part of path doesn't exist, it will canonicalize the-/// existing part and append the non-existing part.-///-/// This method must return an absolute path, as many zed-/// crates assume absolute paths.-fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {- match Path::new(argument_str).canonicalize() {- Ok(existing_path) => Ok(PathWithPosition::from_path(existing_path)),- Err(_) => PathWithPosition::parse_str(argument_str).map_path(|mut path| {- let curdir = env::current_dir().context("retrieving current directory")?;- let mut children = Vec::new();- let root;- loop {- // canonicalize handles './', and '/'.- if let Ok(canonicalized) = fs::canonicalize(&path) {- root = canonicalized;- break;- }- // The comparison to `curdir` is just a shortcut- // since we know it is canonical. The other one- // is if `argument_str` is a string that starts- // with a name (e.g. "foo/bar").- if path == curdir || path == Path::new("") {- root = curdir;- break;- }- children.push(- path.file_name()- .with_context(|| format!("parsing as path with position {argument_str}"))?- .to_owned(),- );- if !path.pop() {- unreachable!("parsing as path with position {argument_str}");- }- }- Ok(children.iter().rev().fold(root, |mut path, child| {- path.push(child);- path- }))- }),- }- .map(|path_with_pos| path_with_pos.to_string(&|path| path.to_string_lossy().into_owned()))-}-/// Returns whether a `--diff` argument refers to an existing path, allowing a/// trailing `:line:column` suffix (parsed later by the Zed side, matching how/// regular `zed path:line:column` arguments are handled).diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rsindex 510294da6f6..8029d34cae4 100644--- a/crates/util/src/paths.rs+++ b/crates/util/src/paths.rs@@ -751,6 +751,55 @@ impl PathWithPosition {}}+/// Parses a path containing a position (e.g. `path:line:column`)+/// and returns its canonicalized string representation.+///+/// If a part of path doesn't exist, it will canonicalize the+/// existing part and append the non-existing part.+///+/// This method must return an absolute path, as many zed+/// crates assume absolute paths.+pub fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {+ use anyhow::Context as _;++ match Path::new(argument_str).canonicalize() {+ Ok(existing_path) => Ok(PathWithPosition::from_path(existing_path)),+ Err(_) => PathWithPosition::parse_str(argument_str).map_path(|mut path| {+ let curdir = std::env::current_dir().context("retrieving current directory")?;+ let mut children = Vec::new();+ let root;+ loop {+ // canonicalize handles './', and '/'.+ if let Ok(canonicalized) = std::fs::canonicalize(&path) {+ root = canonicalized;+ break;+ }+ // The comparison to `curdir` is just a shortcut+ // since we know it is canonical. The other one+ // is if `argument_str` is a string that starts+ // with a name (e.g. "foo/bar").+ if path == curdir || path == Path::new("") {+ root = curdir;+ break;+ }+ children.push(+ path.file_name()+ .with_context(|| format!("parsing as path with position {argument_str}"))?+ .to_owned(),+ );+ if !path.pop() {+ unreachable!("parsing as path with position {argument_str}");+ }+ }+ Ok(children.iter().rev().fold(root, |mut path, child| {+ path.push(child);+ path+ }))+ }),+ }+ .map(|path_with_pos| path_with_pos.to_string(&|path| path.to_string_lossy().into_owned()))+}+#[derive(Clone)]pub struct PathMatcher {sources: Vec<(String, RelPathBuf, /*trailing separator*/ bool)>,diff --git a/crates/zed/src/zed/windows_only_instance.rs b/crates/zed/src/zed/windows_only_instance.rsindex c43e4f9e198..a86f8a83c39 100644--- a/crates/zed/src/zed/windows_only_instance.rs+++ b/crates/zed/src/zed/windows_only_instance.rs@@ -4,7 +4,7 @@ use anyhow::Context;use cli::{CliRequest, CliResponse, IpcHandshake, ipc::IpcOneShotServer};use parking_lot::Mutex;use release_channel::app_identifier;-use util::ResultExt;+use util::{ResultExt, paths::parse_path_with_position};use windows::{Win32::{Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError, HANDLE},@@ -107,6 +107,27 @@ fn retrieve_message_from_pipe_inner(pipe: HANDLE) -> anyhow::Result<String> {Ok(message.to_string_lossy().into_owned())}+fn split_paths_and_urls(paths_or_urls: &[String]) -> (Vec<String>, Vec<String>) {+ let mut paths = vec![];+ let mut urls = vec![];+ for path in paths_or_urls {+ if path.starts_with("zed://")+ || path.starts_with("http://")+ || path.starts_with("https://")+ || path.starts_with("file://")+ || path.starts_with("ssh://")+ {+ urls.push(path.clone());+ } else {+ match parse_path_with_position(path) {+ Ok(path) => paths.push(path),+ Err(error) => log::error!("error parsing path argument: {}", error),+ }+ }+ }+ (paths, urls)+}+// This part of code is mostly from crates/cli/src/main.rsfn send_args_to_instance(args: &Args) -> anyhow::Result<()> {if let Some(dock_menu_action_idx) = args.dock_action {@@ -119,27 +140,8 @@ fn send_args_to_instance(args: &Args) -> anyhow::Result<()> {let url = format!("zed-cli://{server_name}");let request = {- let mut paths = vec![];- let mut urls = vec![];+ let (paths, urls) = split_paths_and_urls(&args.paths_or_urls);let mut diff_paths = vec![];- for path in args.paths_or_urls.iter() {- match std::fs::canonicalize(&path) {- Ok(path) => paths.push(path.to_string_lossy().into_owned()),- Err(error) => {- if path.starts_with("zed://")- || path.starts_with("http://")- || path.starts_with("https://")- || path.starts_with("file://")- || path.starts_with("ssh://")- {- urls.push(path.clone());- } else {- log::error!("error parsing path argument: {}", error);- }- }- }- }-for path in args.diff.chunks(2) {let old = std::fs::canonicalize(&path[0]).log_err();let new = std::fs::canonicalize(&path[1]).log_err();@@ -222,3 +224,20 @@ fn write_message_to_instance_pipe(message: &[u8]) -> anyhow::Result<()> {}Ok(())}++#[cfg(test)]+mod tests {+ use super::split_paths_and_urls;++ #[test]+ fn test_split_paths_and_urls() {+ let file = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");+ let canonical = std::fs::canonicalize(file).unwrap();+ let url = "zed://file/C:/project/main.rs:3";++ let (paths, urls) = split_paths_and_urls(&[format!("{file}:2:5"), url.to_string()]);++ assert_eq!(paths, [format!("{}:2:5", canonical.display())]);+ assert_eq!(urls, [url]);+ }+}