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