1#![cfg_attr(
2 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3 allow(dead_code)
4)]
5
6use anyhow::{Context as _, Result};
7use clap::Parser;
8use cli::{CliRequest, CliResponse, IpcHandshake, ipc::IpcOneShotServer};
9use parking_lot::Mutex;
10use std::{
11 env, fs, io,
12 path::{Path, PathBuf},
13 process::ExitStatus,
14 sync::Arc,
15 thread::{self, JoinHandle},
16};
17use tempfile::NamedTempFile;
18use util::paths::PathWithPosition;
19
20#[cfg(any(target_os = "linux", target_os = "freebsd"))]
21use std::io::IsTerminal;
22
23struct Detect;
24
25trait InstalledApp {
26 fn zed_version_string(&self) -> String;
27 fn launch(&self, ipc_url: String) -> anyhow::Result<()>;
28 fn run_foreground(
29 &self,
30 ipc_url: String,
31 user_data_dir: Option<&str>,
32 ) -> io::Result<ExitStatus>;
33 fn path(&self) -> PathBuf;
34}
35
36#[derive(Parser, Debug)]
37#[command(
38 name = "zed",
39 disable_version_flag = true,
40 before_help = "The Zed CLI binary.
41This CLI is a separate binary that invokes Zed.
42
43Examples:
44 `zed`
45 Simply opens Zed
46 `zed --foreground`
47 Runs in foreground (shows all logs)
48 `zed path-to-your-project`
49 Open your project in Zed
50 `zed -n path-to-file `
51 Open file/folder in a new window",
52 after_help = "To read from stdin, append '-', e.g. 'ps axf | zed -'"
53)]
54struct Args {
55 /// Wait for all of the given paths to be opened/closed before exiting.
56 #[arg(short, long)]
57 wait: bool,
58 /// Add files to the currently open workspace
59 #[arg(short, long, overrides_with = "new")]
60 add: bool,
61 /// Create a new workspace
62 #[arg(short, long, overrides_with = "add")]
63 new: bool,
64 /// Sets a custom directory for all user data (e.g., database, extensions, logs).
65 /// This overrides the default platform-specific data directory location.
66 /// On macOS, the default is `~/Library/Application Support/Zed`.
67 /// On Linux/FreeBSD, the default is `$XDG_DATA_HOME/zed`.
68 /// On Windows, the default is `%LOCALAPPDATA%\Zed`.
69 #[arg(long, value_name = "DIR")]
70 user_data_dir: Option<String>,
71 /// The paths to open in Zed (space-separated).
72 ///
73 /// Use `path:line:column` syntax to open a file at the given line and column.
74 paths_with_position: Vec<String>,
75 /// Print Zed's version and the app path.
76 #[arg(short, long)]
77 version: bool,
78 /// Run zed in the foreground (useful for debugging)
79 #[arg(long)]
80 foreground: bool,
81 /// Custom path to Zed.app or the zed binary
82 #[arg(long)]
83 zed: Option<PathBuf>,
84 /// Run zed in dev-server mode
85 #[arg(long)]
86 dev_server_token: Option<String>,
87 /// The username and WSL distribution to use when opening paths. If not specified,
88 /// Zed will attempt to open the paths directly.
89 ///
90 /// The username is optional, and if not specified, the default user for the distribution
91 /// will be used.
92 ///
93 /// Example: `me@Ubuntu` or `Ubuntu`.
94 ///
95 /// WARN: You should not fill in this field by hand.
96 #[cfg(target_os = "windows")]
97 #[arg(long, value_name = "USER@DISTRO")]
98 wsl: Option<String>,
99 /// Not supported in Zed CLI, only supported on Zed binary
100 /// Will attempt to give the correct command to run
101 #[arg(long)]
102 system_specs: bool,
103 /// Pairs of file paths to diff. Can be specified multiple times.
104 #[arg(long, action = clap::ArgAction::Append, num_args = 2, value_names = ["OLD_PATH", "NEW_PATH"])]
105 diff: Vec<String>,
106 /// Uninstall Zed from user system
107 #[cfg(all(
108 any(target_os = "linux", target_os = "macos"),
109 not(feature = "no-bundled-uninstall")
110 ))]
111 #[arg(long)]
112 uninstall: bool,
113}
114
115fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {
116 let canonicalized = match Path::new(argument_str).canonicalize() {
117 Ok(existing_path) => PathWithPosition::from_path(existing_path),
118 Err(_) => {
119 let path = PathWithPosition::parse_str(argument_str);
120 let curdir = env::current_dir().context("retrieving current directory")?;
121 path.map_path(|path| match fs::canonicalize(&path) {
122 Ok(path) => Ok(path),
123 Err(e) => {
124 if let Some(mut parent) = path.parent() {
125 if parent == Path::new("") {
126 parent = &curdir
127 }
128 match fs::canonicalize(parent) {
129 Ok(parent) => Ok(parent.join(path.file_name().unwrap())),
130 Err(_) => Err(e),
131 }
132 } else {
133 Err(e)
134 }
135 }
136 })
137 }
138 .with_context(|| format!("parsing as path with position {argument_str}"))?,
139 };
140 Ok(canonicalized.to_string(|path| path.to_string_lossy().to_string()))
141}
142
143fn parse_path_in_wsl(source: &str, wsl: &str) -> Result<String> {
144 let mut command = util::command::new_std_command("wsl.exe");
145
146 let (user, distro_name) = if let Some((user, distro)) = wsl.split_once('@') {
147 if user.is_empty() {
148 anyhow::bail!("user is empty in wsl argument");
149 }
150 (Some(user), distro)
151 } else {
152 (None, wsl)
153 };
154
155 if let Some(user) = user {
156 command.arg("--user").arg(user);
157 }
158
159 let output = command
160 .arg("--distribution")
161 .arg(distro_name)
162 .arg("wslpath")
163 .arg("-m")
164 .arg(source)
165 .output()?;
166
167 let result = String::from_utf8_lossy(&output.stdout);
168 let prefix = format!("//wsl.localhost/{}", distro_name);
169
170 Ok(result
171 .trim()
172 .strip_prefix(&prefix)
173 .unwrap_or(&result)
174 .to_string())
175}
176
177fn main() -> Result<()> {
178 #[cfg(unix)]
179 util::prevent_root_execution();
180
181 // Exit flatpak sandbox if needed
182 #[cfg(target_os = "linux")]
183 {
184 flatpak::try_restart_to_host();
185 flatpak::ld_extra_libs();
186 }
187
188 // Intercept version designators
189 #[cfg(target_os = "macos")]
190 if let Some(channel) = std::env::args().nth(1).filter(|arg| arg.starts_with("--")) {
191 // When the first argument is a name of a release channel, we're going to spawn off the CLI of that version, with trailing args passed along.
192 use std::str::FromStr as _;
193
194 if let Ok(channel) = release_channel::ReleaseChannel::from_str(&channel[2..]) {
195 return mac_os::spawn_channel_cli(channel, std::env::args().skip(2).collect());
196 }
197 }
198 let args = Args::parse();
199
200 // Set custom data directory before any path operations
201 let user_data_dir = args.user_data_dir.clone();
202 if let Some(dir) = &user_data_dir {
203 paths::set_custom_data_dir(dir);
204 }
205
206 #[cfg(target_os = "linux")]
207 let args = flatpak::set_bin_if_no_escape(args);
208
209 let app = Detect::detect(args.zed.as_deref()).context("Bundle detection")?;
210
211 if args.version {
212 println!("{}", app.zed_version_string());
213 return Ok(());
214 }
215
216 if args.system_specs {
217 let path = app.path();
218 let msg = [
219 "The `--system-specs` argument is not supported in the Zed CLI, only on Zed binary.",
220 "To retrieve the system specs on the command line, run the following command:",
221 &format!("{} --system-specs", path.display()),
222 ];
223 anyhow::bail!(msg.join("\n"));
224 }
225
226 #[cfg(all(
227 any(target_os = "linux", target_os = "macos"),
228 not(feature = "no-bundled-uninstall")
229 ))]
230 if args.uninstall {
231 static UNINSTALL_SCRIPT: &[u8] = include_bytes!("../../../script/uninstall.sh");
232
233 let tmp_dir = tempfile::tempdir()?;
234 let script_path = tmp_dir.path().join("uninstall.sh");
235 fs::write(&script_path, UNINSTALL_SCRIPT)?;
236
237 use std::os::unix::fs::PermissionsExt as _;
238 fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755))?;
239
240 let status = std::process::Command::new("sh")
241 .arg(&script_path)
242 .env("ZED_CHANNEL", &*release_channel::RELEASE_CHANNEL_NAME)
243 .status()
244 .context("Failed to execute uninstall script")?;
245
246 std::process::exit(status.code().unwrap_or(1));
247 }
248
249 let (server, server_name) =
250 IpcOneShotServer::<IpcHandshake>::new().context("Handshake before Zed spawn")?;
251 let url = format!("zed-cli://{server_name}");
252
253 let open_new_workspace = if args.new {
254 Some(true)
255 } else if args.add {
256 Some(false)
257 } else {
258 None
259 };
260
261 let env = {
262 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
263 {
264 use collections::HashMap;
265
266 // On Linux, the desktop entry uses `cli` to spawn `zed`.
267 // We need to handle env vars correctly since std::env::vars() may not contain
268 // project-specific vars (e.g. those set by direnv).
269 // By setting env to None here, the LSP will use worktree env vars instead,
270 // which is what we want.
271 if !std::io::stdout().is_terminal() {
272 None
273 } else {
274 Some(std::env::vars().collect::<HashMap<_, _>>())
275 }
276 }
277
278 #[cfg(target_os = "windows")]
279 {
280 // On Windows, by default, a child process inherits a copy of the environment block of the parent process.
281 // So we don't need to pass env vars explicitly.
282 None
283 }
284
285 #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
286 {
287 use collections::HashMap;
288
289 Some(std::env::vars().collect::<HashMap<_, _>>())
290 }
291 };
292
293 let exit_status = Arc::new(Mutex::new(None));
294 let mut paths = vec![];
295 let mut urls = vec![];
296 let mut diff_paths = vec![];
297 let mut stdin_tmp_file: Option<fs::File> = None;
298 let mut anonymous_fd_tmp_files = vec![];
299
300 for path in args.diff.chunks(2) {
301 diff_paths.push([
302 parse_path_with_position(&path[0])?,
303 parse_path_with_position(&path[1])?,
304 ]);
305 }
306
307 #[cfg(target_os = "windows")]
308 let wsl = args.wsl.as_ref();
309 #[cfg(not(target_os = "windows"))]
310 let wsl = None;
311
312 for path in args.paths_with_position.iter() {
313 if path.starts_with("zed://")
314 || path.starts_with("http://")
315 || path.starts_with("https://")
316 || path.starts_with("file://")
317 || path.starts_with("ssh://")
318 {
319 urls.push(path.to_string());
320 } else if path == "-" && args.paths_with_position.len() == 1 {
321 let file = NamedTempFile::new()?;
322 paths.push(file.path().to_string_lossy().to_string());
323 let (file, _) = file.keep()?;
324 stdin_tmp_file = Some(file);
325 } else if let Some(file) = anonymous_fd(path) {
326 let tmp_file = NamedTempFile::new()?;
327 paths.push(tmp_file.path().to_string_lossy().to_string());
328 let (tmp_file, _) = tmp_file.keep()?;
329 anonymous_fd_tmp_files.push((file, tmp_file));
330 } else if let Some(wsl) = wsl {
331 urls.push(format!("file://{}", parse_path_in_wsl(path, wsl)?));
332 } else {
333 paths.push(parse_path_with_position(path)?);
334 }
335 }
336
337 anyhow::ensure!(
338 args.dev_server_token.is_none(),
339 "Dev servers were removed in v0.157.x please upgrade to SSH remoting: https://zed.dev/docs/remote-development"
340 );
341
342 let sender: JoinHandle<anyhow::Result<()>> = thread::Builder::new()
343 .name("CliReceiver".to_string())
344 .spawn({
345 let exit_status = exit_status.clone();
346 let user_data_dir_for_thread = user_data_dir.clone();
347 move || {
348 let (_, handshake) = server.accept().context("Handshake after Zed spawn")?;
349 let (tx, rx) = (handshake.requests, handshake.responses);
350
351 #[cfg(target_os = "windows")]
352 let wsl = args.wsl;
353 #[cfg(not(target_os = "windows"))]
354 let wsl = None;
355
356 tx.send(CliRequest::Open {
357 paths,
358 urls,
359 diff_paths,
360 wsl,
361 wait: args.wait,
362 open_new_workspace,
363 env,
364 user_data_dir: user_data_dir_for_thread,
365 })?;
366
367 while let Ok(response) = rx.recv() {
368 match response {
369 CliResponse::Ping => {}
370 CliResponse::Stdout { message } => println!("{message}"),
371 CliResponse::Stderr { message } => eprintln!("{message}"),
372 CliResponse::Exit { status } => {
373 exit_status.lock().replace(status);
374 return Ok(());
375 }
376 }
377 }
378
379 Ok(())
380 }
381 })
382 .unwrap();
383
384 let stdin_pipe_handle: Option<JoinHandle<anyhow::Result<()>>> =
385 stdin_tmp_file.map(|mut tmp_file| {
386 thread::Builder::new()
387 .name("CliStdin".to_string())
388 .spawn(move || {
389 let mut stdin = std::io::stdin().lock();
390 if !io::IsTerminal::is_terminal(&stdin) {
391 io::copy(&mut stdin, &mut tmp_file)?;
392 }
393 Ok(())
394 })
395 .unwrap()
396 });
397
398 let anonymous_fd_pipe_handles: Vec<_> = anonymous_fd_tmp_files
399 .into_iter()
400 .map(|(mut file, mut tmp_file)| {
401 thread::Builder::new()
402 .name("CliAnonymousFd".to_string())
403 .spawn(move || io::copy(&mut file, &mut tmp_file))
404 .unwrap()
405 })
406 .collect();
407
408 if args.foreground {
409 app.run_foreground(url, user_data_dir.as_deref())?;
410 } else {
411 app.launch(url)?;
412 sender.join().unwrap()?;
413 if let Some(handle) = stdin_pipe_handle {
414 handle.join().unwrap()?;
415 }
416 for handle in anonymous_fd_pipe_handles {
417 handle.join().unwrap()?;
418 }
419 }
420
421 if let Some(exit_status) = exit_status.lock().take() {
422 std::process::exit(exit_status);
423 }
424 Ok(())
425}
426
427fn anonymous_fd(path: &str) -> Option<fs::File> {
428 #[cfg(target_os = "linux")]
429 {
430 use std::os::fd::{self, FromRawFd};
431
432 let fd_str = path.strip_prefix("/proc/self/fd/")?;
433
434 let link = fs::read_link(path).ok()?;
435 if !link.starts_with("memfd:") {
436 return None;
437 }
438
439 let fd: fd::RawFd = fd_str.parse().ok()?;
440 let file = unsafe { fs::File::from_raw_fd(fd) };
441 Some(file)
442 }
443 #[cfg(any(target_os = "macos", target_os = "freebsd"))]
444 {
445 use std::os::{
446 fd::{self, FromRawFd},
447 unix::fs::FileTypeExt,
448 };
449
450 let fd_str = path.strip_prefix("/dev/fd/")?;
451
452 let metadata = fs::metadata(path).ok()?;
453 let file_type = metadata.file_type();
454 if !file_type.is_fifo() && !file_type.is_socket() {
455 return None;
456 }
457 let fd: fd::RawFd = fd_str.parse().ok()?;
458 let file = unsafe { fs::File::from_raw_fd(fd) };
459 Some(file)
460 }
461 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
462 {
463 _ = path;
464 // not implemented for bsd, windows. Could be, but isn't yet
465 None
466 }
467}
468
469#[cfg(any(target_os = "linux", target_os = "freebsd"))]
470mod linux {
471 use std::{
472 env,
473 ffi::OsString,
474 io,
475 os::unix::net::{SocketAddr, UnixDatagram},
476 path::{Path, PathBuf},
477 process::{self, ExitStatus},
478 thread,
479 time::Duration,
480 };
481
482 use anyhow::{Context as _, anyhow};
483 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
484 use fork::Fork;
485
486 use crate::{Detect, InstalledApp};
487
488 struct App(PathBuf);
489
490 impl Detect {
491 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
492 let path = if let Some(path) = path {
493 path.to_path_buf().canonicalize()?
494 } else {
495 let cli = env::current_exe()?;
496 let dir = cli.parent().context("no parent path for cli")?;
497
498 // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
499 // ./zed is for the target directory in development builds.
500 let possible_locations =
501 ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
502 possible_locations
503 .iter()
504 .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
505 .with_context(|| {
506 format!("could not find any of: {}", possible_locations.join(", "))
507 })?
508 };
509
510 Ok(App(path))
511 }
512 }
513
514 impl InstalledApp for App {
515 fn zed_version_string(&self) -> String {
516 format!(
517 "Zed {}{}{} – {}",
518 if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
519 "".to_string()
520 } else {
521 format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
522 },
523 option_env!("RELEASE_VERSION").unwrap_or_default(),
524 match option_env!("ZED_COMMIT_SHA") {
525 Some(commit_sha) => format!(" {commit_sha} "),
526 None => "".to_string(),
527 },
528 self.0.display(),
529 )
530 }
531
532 fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
533 let sock_path = paths::data_dir().join(format!(
534 "zed-{}.sock",
535 *release_channel::RELEASE_CHANNEL_NAME
536 ));
537 let sock = UnixDatagram::unbound()?;
538 if sock.connect(&sock_path).is_err() {
539 self.boot_background(ipc_url)?;
540 } else {
541 sock.send(ipc_url.as_bytes())?;
542 }
543 Ok(())
544 }
545
546 fn run_foreground(
547 &self,
548 ipc_url: String,
549 user_data_dir: Option<&str>,
550 ) -> io::Result<ExitStatus> {
551 let mut cmd = std::process::Command::new(self.0.clone());
552 cmd.arg(ipc_url);
553 if let Some(dir) = user_data_dir {
554 cmd.arg("--user-data-dir").arg(dir);
555 }
556 cmd.status()
557 }
558
559 fn path(&self) -> PathBuf {
560 self.0.clone()
561 }
562 }
563
564 impl App {
565 fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
566 let path = &self.0;
567
568 match fork::fork() {
569 Ok(Fork::Parent(_)) => Ok(()),
570 Ok(Fork::Child) => {
571 unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
572 if fork::setsid().is_err() {
573 eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
574 process::exit(1);
575 }
576 if fork::close_fd().is_err() {
577 eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
578 }
579 let error =
580 exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
581 // if exec succeeded, we never get here.
582 eprintln!("failed to exec {:?}: {}", path, error);
583 process::exit(1)
584 }
585 Err(_) => Err(anyhow!(io::Error::last_os_error())),
586 }
587 }
588
589 fn wait_for_socket(
590 &self,
591 sock_addr: &SocketAddr,
592 sock: &mut UnixDatagram,
593 ) -> Result<(), std::io::Error> {
594 for _ in 0..100 {
595 thread::sleep(Duration::from_millis(10));
596 if sock.connect_addr(sock_addr).is_ok() {
597 return Ok(());
598 }
599 }
600 sock.connect_addr(sock_addr)
601 }
602 }
603}
604
605#[cfg(target_os = "linux")]
606mod flatpak {
607 use std::ffi::OsString;
608 use std::path::PathBuf;
609 use std::process::Command;
610 use std::{env, process};
611
612 const EXTRA_LIB_ENV_NAME: &str = "ZED_FLATPAK_LIB_PATH";
613 const NO_ESCAPE_ENV_NAME: &str = "ZED_FLATPAK_NO_ESCAPE";
614
615 /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
616 pub fn ld_extra_libs() {
617 let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
618 env::split_paths(&paths).collect()
619 } else {
620 Vec::new()
621 };
622
623 if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
624 paths.push(extra_path.into());
625 }
626
627 unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
628 }
629
630 /// Restarts outside of the sandbox if currently running within it
631 pub fn try_restart_to_host() {
632 if let Some(flatpak_dir) = get_flatpak_dir() {
633 let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
634 args.append(&mut get_xdg_env_args());
635 args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
636 args.push(
637 format!(
638 "--env={EXTRA_LIB_ENV_NAME}={}",
639 flatpak_dir.join("lib").to_str().unwrap()
640 )
641 .into(),
642 );
643 args.push(flatpak_dir.join("bin").join("zed").into());
644
645 let mut is_app_location_set = false;
646 for arg in &env::args_os().collect::<Vec<_>>()[1..] {
647 args.push(arg.clone());
648 is_app_location_set |= arg == "--zed";
649 }
650
651 if !is_app_location_set {
652 args.push("--zed".into());
653 args.push(flatpak_dir.join("libexec").join("zed-editor").into());
654 }
655
656 let error = exec::execvp("/usr/bin/flatpak-spawn", args);
657 eprintln!("failed restart cli on host: {:?}", error);
658 process::exit(1);
659 }
660 }
661
662 pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
663 if env::var(NO_ESCAPE_ENV_NAME).is_ok()
664 && env::var("FLATPAK_ID").is_ok_and(|id| id.starts_with("dev.zed.Zed"))
665 && args.zed.is_none()
666 {
667 args.zed = Some("/app/libexec/zed-editor".into());
668 unsafe { env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed") };
669 }
670 args
671 }
672
673 fn get_flatpak_dir() -> Option<PathBuf> {
674 if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
675 return None;
676 }
677
678 if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
679 if !flatpak_id.starts_with("dev.zed.Zed") {
680 return None;
681 }
682
683 let install_dir = Command::new("/usr/bin/flatpak-spawn")
684 .arg("--host")
685 .arg("flatpak")
686 .arg("info")
687 .arg("--show-location")
688 .arg(flatpak_id)
689 .output()
690 .unwrap();
691 let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
692 Some(install_dir.join("files"))
693 } else {
694 None
695 }
696 }
697
698 fn get_xdg_env_args() -> Vec<OsString> {
699 let xdg_keys = [
700 "XDG_DATA_HOME",
701 "XDG_CONFIG_HOME",
702 "XDG_CACHE_HOME",
703 "XDG_STATE_HOME",
704 ];
705 env::vars()
706 .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
707 .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
708 .collect()
709 }
710}
711
712#[cfg(target_os = "windows")]
713mod windows {
714 use anyhow::Context;
715 use release_channel::app_identifier;
716 use windows::{
717 Win32::{
718 Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
719 Storage::FileSystem::{
720 CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
721 },
722 System::Threading::{CREATE_NEW_PROCESS_GROUP, CreateMutexW},
723 },
724 core::HSTRING,
725 };
726
727 use crate::{Detect, InstalledApp};
728 use std::path::{Path, PathBuf};
729 use std::process::ExitStatus;
730 use std::{io, os::windows::process::CommandExt};
731
732 fn check_single_instance() -> bool {
733 let mutex = unsafe {
734 CreateMutexW(
735 None,
736 false,
737 &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
738 )
739 .expect("Unable to create instance sync event")
740 };
741 let last_err = unsafe { GetLastError() };
742 let _ = unsafe { CloseHandle(mutex) };
743 last_err != ERROR_ALREADY_EXISTS
744 }
745
746 struct App(PathBuf);
747
748 impl InstalledApp for App {
749 fn zed_version_string(&self) -> String {
750 format!(
751 "Zed {}{}{} – {}",
752 if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
753 "".to_string()
754 } else {
755 format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
756 },
757 option_env!("RELEASE_VERSION").unwrap_or_default(),
758 match option_env!("ZED_COMMIT_SHA") {
759 Some(commit_sha) => format!(" {commit_sha} "),
760 None => "".to_string(),
761 },
762 self.0.display(),
763 )
764 }
765
766 fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
767 if check_single_instance() {
768 std::process::Command::new(self.0.clone())
769 .creation_flags(CREATE_NEW_PROCESS_GROUP.0)
770 .arg(ipc_url)
771 .spawn()?;
772 } else {
773 unsafe {
774 let pipe = CreateFileW(
775 &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
776 GENERIC_WRITE.0,
777 FILE_SHARE_MODE::default(),
778 None,
779 OPEN_EXISTING,
780 FILE_FLAGS_AND_ATTRIBUTES::default(),
781 None,
782 )?;
783 let message = ipc_url.as_bytes();
784 let mut bytes_written = 0;
785 WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
786 CloseHandle(pipe)?;
787 }
788 }
789 Ok(())
790 }
791
792 fn run_foreground(
793 &self,
794 ipc_url: String,
795 user_data_dir: Option<&str>,
796 ) -> io::Result<ExitStatus> {
797 let mut cmd = std::process::Command::new(self.0.clone());
798 cmd.arg(ipc_url).arg("--foreground");
799 if let Some(dir) = user_data_dir {
800 cmd.arg("--user-data-dir").arg(dir);
801 }
802 cmd.spawn()?.wait()
803 }
804
805 fn path(&self) -> PathBuf {
806 self.0.clone()
807 }
808 }
809
810 impl Detect {
811 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
812 let path = if let Some(path) = path {
813 path.to_path_buf().canonicalize()?
814 } else {
815 let cli = std::env::current_exe()?;
816 let dir = cli.parent().context("no parent path for cli")?;
817
818 // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
819 // directory in development builds.
820 let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
821 possible_locations
822 .iter()
823 .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
824 .context(format!(
825 "could not find any of: {}",
826 possible_locations.join(", ")
827 ))?
828 };
829
830 Ok(App(path))
831 }
832 }
833}
834
835#[cfg(target_os = "macos")]
836mod mac_os {
837 use anyhow::{Context as _, Result};
838 use core_foundation::{
839 array::{CFArray, CFIndex},
840 base::TCFType as _,
841 string::kCFStringEncodingUTF8,
842 url::{CFURL, CFURLCreateWithBytes},
843 };
844 use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
845 use serde::Deserialize;
846 use std::{
847 ffi::OsStr,
848 fs, io,
849 path::{Path, PathBuf},
850 process::{Command, ExitStatus},
851 ptr,
852 };
853
854 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
855
856 use crate::{Detect, InstalledApp};
857
858 #[derive(Debug, Deserialize)]
859 struct InfoPlist {
860 #[serde(rename = "CFBundleShortVersionString")]
861 bundle_short_version_string: String,
862 }
863
864 enum Bundle {
865 App {
866 app_bundle: PathBuf,
867 plist: InfoPlist,
868 },
869 LocalPath {
870 executable: PathBuf,
871 },
872 }
873
874 fn locate_bundle() -> Result<PathBuf> {
875 let cli_path = std::env::current_exe()?.canonicalize()?;
876 let mut app_path = cli_path.clone();
877 while app_path.extension() != Some(OsStr::new("app")) {
878 anyhow::ensure!(
879 app_path.pop(),
880 "cannot find app bundle containing {cli_path:?}"
881 );
882 }
883 Ok(app_path)
884 }
885
886 impl Detect {
887 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
888 let bundle_path = if let Some(bundle_path) = path {
889 bundle_path
890 .canonicalize()
891 .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
892 } else {
893 locate_bundle().context("bundle autodiscovery")?
894 };
895
896 match bundle_path.extension().and_then(|ext| ext.to_str()) {
897 Some("app") => {
898 let plist_path = bundle_path.join("Contents/Info.plist");
899 let plist =
900 plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
901 format!("Reading *.app bundle plist file at {plist_path:?}")
902 })?;
903 Ok(Bundle::App {
904 app_bundle: bundle_path,
905 plist,
906 })
907 }
908 _ => Ok(Bundle::LocalPath {
909 executable: bundle_path,
910 }),
911 }
912 }
913 }
914
915 impl InstalledApp for Bundle {
916 fn zed_version_string(&self) -> String {
917 format!("Zed {} – {}", self.version(), self.path().display(),)
918 }
919
920 fn launch(&self, url: String) -> anyhow::Result<()> {
921 match self {
922 Self::App { app_bundle, .. } => {
923 let app_path = app_bundle;
924
925 let status = unsafe {
926 let app_url = CFURL::from_path(app_path, true)
927 .with_context(|| format!("invalid app path {app_path:?}"))?;
928 let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
929 ptr::null(),
930 url.as_ptr(),
931 url.len() as CFIndex,
932 kCFStringEncodingUTF8,
933 ptr::null(),
934 ));
935 // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
936 let urls_to_open =
937 CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
938 LSOpenFromURLSpec(
939 &LSLaunchURLSpec {
940 appURL: app_url.as_concrete_TypeRef(),
941 itemURLs: urls_to_open.as_concrete_TypeRef(),
942 passThruParams: ptr::null(),
943 launchFlags: kLSLaunchDefaults,
944 asyncRefCon: ptr::null_mut(),
945 },
946 ptr::null_mut(),
947 )
948 };
949
950 anyhow::ensure!(
951 status == 0,
952 "cannot start app bundle {}",
953 self.zed_version_string()
954 );
955 }
956
957 Self::LocalPath { executable, .. } => {
958 let executable_parent = executable
959 .parent()
960 .with_context(|| format!("Executable {executable:?} path has no parent"))?;
961 let subprocess_stdout_file = fs::File::create(
962 executable_parent.join("zed_dev.log"),
963 )
964 .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
965 let subprocess_stdin_file =
966 subprocess_stdout_file.try_clone().with_context(|| {
967 format!("Cloning descriptor for file {subprocess_stdout_file:?}")
968 })?;
969 let mut command = std::process::Command::new(executable);
970 let command = command
971 .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
972 .stderr(subprocess_stdout_file)
973 .stdout(subprocess_stdin_file)
974 .arg(url);
975
976 command
977 .spawn()
978 .with_context(|| format!("Spawning {command:?}"))?;
979 }
980 }
981
982 Ok(())
983 }
984
985 fn run_foreground(
986 &self,
987 ipc_url: String,
988 user_data_dir: Option<&str>,
989 ) -> io::Result<ExitStatus> {
990 let path = match self {
991 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
992 Bundle::LocalPath { executable, .. } => executable.clone(),
993 };
994
995 let mut cmd = std::process::Command::new(path);
996 cmd.arg(ipc_url);
997 if let Some(dir) = user_data_dir {
998 cmd.arg("--user-data-dir").arg(dir);
999 }
1000 cmd.status()
1001 }
1002
1003 fn path(&self) -> PathBuf {
1004 match self {
1005 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
1006 Bundle::LocalPath { executable, .. } => executable.clone(),
1007 }
1008 }
1009 }
1010
1011 impl Bundle {
1012 fn version(&self) -> String {
1013 match self {
1014 Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
1015 Self::LocalPath { .. } => "<development>".to_string(),
1016 }
1017 }
1018
1019 fn path(&self) -> &Path {
1020 match self {
1021 Self::App { app_bundle, .. } => app_bundle,
1022 Self::LocalPath { executable, .. } => executable,
1023 }
1024 }
1025 }
1026
1027 pub(super) fn spawn_channel_cli(
1028 channel: release_channel::ReleaseChannel,
1029 leftover_args: Vec<String>,
1030 ) -> Result<()> {
1031 use anyhow::bail;
1032
1033 let app_path_prompt = format!(
1034 "POSIX path of (path to application \"{}\")",
1035 channel.display_name()
1036 );
1037 let app_path_output = Command::new("osascript")
1038 .arg("-e")
1039 .arg(&app_path_prompt)
1040 .output()?;
1041 if !app_path_output.status.success() {
1042 bail!(
1043 "Could not determine app path for {}",
1044 channel.display_name()
1045 );
1046 }
1047 let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
1048 let cli_path = format!("{app_path}/Contents/MacOS/cli");
1049 Command::new(cli_path).args(leftover_args).spawn()?;
1050 Ok(())
1051 }
1052}