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