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(&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 unsafe { 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 unsafe { 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 unsafe {
566 env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed")
567 };
568 }
569 }
570 args
571 }
572
573 fn get_flatpak_dir() -> Option<PathBuf> {
574 if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
575 return None;
576 }
577
578 if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
579 if !flatpak_id.starts_with("dev.zed.Zed") {
580 return None;
581 }
582
583 let install_dir = Command::new("/usr/bin/flatpak-spawn")
584 .arg("--host")
585 .arg("flatpak")
586 .arg("info")
587 .arg("--show-location")
588 .arg(flatpak_id)
589 .output()
590 .unwrap();
591 let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
592 Some(install_dir.join("files"))
593 } else {
594 None
595 }
596 }
597
598 fn get_xdg_env_args() -> Vec<OsString> {
599 let xdg_keys = [
600 "XDG_DATA_HOME",
601 "XDG_CONFIG_HOME",
602 "XDG_CACHE_HOME",
603 "XDG_STATE_HOME",
604 ];
605 env::vars()
606 .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
607 .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
608 .collect()
609 }
610}
611
612#[cfg(target_os = "windows")]
613mod windows {
614 use anyhow::Context;
615 use release_channel::app_identifier;
616 use windows::{
617 Win32::{
618 Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
619 Storage::FileSystem::{
620 CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
621 },
622 System::Threading::CreateMutexW,
623 },
624 core::HSTRING,
625 };
626
627 use crate::{Detect, InstalledApp};
628 use std::io;
629 use std::path::{Path, PathBuf};
630 use std::process::ExitStatus;
631
632 fn check_single_instance() -> bool {
633 let mutex = unsafe {
634 CreateMutexW(
635 None,
636 false,
637 &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
638 )
639 .expect("Unable to create instance sync event")
640 };
641 let last_err = unsafe { GetLastError() };
642 let _ = unsafe { CloseHandle(mutex) };
643 last_err != ERROR_ALREADY_EXISTS
644 }
645
646 struct App(PathBuf);
647
648 impl InstalledApp for App {
649 fn zed_version_string(&self) -> String {
650 format!(
651 "Zed {}{}{} – {}",
652 if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
653 "".to_string()
654 } else {
655 format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
656 },
657 option_env!("RELEASE_VERSION").unwrap_or_default(),
658 match option_env!("ZED_COMMIT_SHA") {
659 Some(commit_sha) => format!(" {commit_sha} "),
660 None => "".to_string(),
661 },
662 self.0.display(),
663 )
664 }
665
666 fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
667 if check_single_instance() {
668 std::process::Command::new(self.0.clone())
669 .arg(ipc_url)
670 .spawn()?;
671 } else {
672 unsafe {
673 let pipe = CreateFileW(
674 &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
675 GENERIC_WRITE.0,
676 FILE_SHARE_MODE::default(),
677 None,
678 OPEN_EXISTING,
679 FILE_FLAGS_AND_ATTRIBUTES::default(),
680 None,
681 )?;
682 let message = ipc_url.as_bytes();
683 let mut bytes_written = 0;
684 WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
685 CloseHandle(pipe)?;
686 }
687 }
688 Ok(())
689 }
690
691 fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
692 std::process::Command::new(self.0.clone())
693 .arg(ipc_url)
694 .arg("--foreground")
695 .spawn()?
696 .wait()
697 }
698
699 fn path(&self) -> PathBuf {
700 self.0.clone()
701 }
702 }
703
704 impl Detect {
705 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
706 let path = if let Some(path) = path {
707 path.to_path_buf().canonicalize()?
708 } else {
709 let cli = std::env::current_exe()?;
710 let dir = cli.parent().context("no parent path for cli")?;
711
712 // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
713 // directory in development builds.
714 let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
715 possible_locations
716 .iter()
717 .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
718 .context(format!(
719 "could not find any of: {}",
720 possible_locations.join(", ")
721 ))?
722 };
723
724 Ok(App(path))
725 }
726 }
727}
728
729#[cfg(target_os = "macos")]
730mod mac_os {
731 use anyhow::{Context as _, Result, anyhow};
732 use core_foundation::{
733 array::{CFArray, CFIndex},
734 base::TCFType as _,
735 string::kCFStringEncodingUTF8,
736 url::{CFURL, CFURLCreateWithBytes},
737 };
738 use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
739 use serde::Deserialize;
740 use std::{
741 ffi::OsStr,
742 fs, io,
743 path::{Path, PathBuf},
744 process::{Command, ExitStatus},
745 ptr,
746 };
747
748 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
749
750 use crate::{Detect, InstalledApp};
751
752 #[derive(Debug, Deserialize)]
753 struct InfoPlist {
754 #[serde(rename = "CFBundleShortVersionString")]
755 bundle_short_version_string: String,
756 }
757
758 enum Bundle {
759 App {
760 app_bundle: PathBuf,
761 plist: InfoPlist,
762 },
763 LocalPath {
764 executable: PathBuf,
765 },
766 }
767
768 fn locate_bundle() -> Result<PathBuf> {
769 let cli_path = std::env::current_exe()?.canonicalize()?;
770 let mut app_path = cli_path.clone();
771 while app_path.extension() != Some(OsStr::new("app")) {
772 if !app_path.pop() {
773 return Err(anyhow!("cannot find app bundle containing {:?}", cli_path));
774 }
775 }
776 Ok(app_path)
777 }
778
779 impl Detect {
780 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
781 let bundle_path = if let Some(bundle_path) = path {
782 bundle_path
783 .canonicalize()
784 .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
785 } else {
786 locate_bundle().context("bundle autodiscovery")?
787 };
788
789 match bundle_path.extension().and_then(|ext| ext.to_str()) {
790 Some("app") => {
791 let plist_path = bundle_path.join("Contents/Info.plist");
792 let plist =
793 plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
794 format!("Reading *.app bundle plist file at {plist_path:?}")
795 })?;
796 Ok(Bundle::App {
797 app_bundle: bundle_path,
798 plist,
799 })
800 }
801 _ => Ok(Bundle::LocalPath {
802 executable: bundle_path,
803 }),
804 }
805 }
806 }
807
808 impl InstalledApp for Bundle {
809 fn zed_version_string(&self) -> String {
810 format!("Zed {} – {}", self.version(), self.path().display(),)
811 }
812
813 fn launch(&self, url: String) -> anyhow::Result<()> {
814 match self {
815 Self::App { app_bundle, .. } => {
816 let app_path = app_bundle;
817
818 let status = unsafe {
819 let app_url = CFURL::from_path(app_path, true)
820 .with_context(|| format!("invalid app path {app_path:?}"))?;
821 let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
822 ptr::null(),
823 url.as_ptr(),
824 url.len() as CFIndex,
825 kCFStringEncodingUTF8,
826 ptr::null(),
827 ));
828 // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
829 let urls_to_open =
830 CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
831 LSOpenFromURLSpec(
832 &LSLaunchURLSpec {
833 appURL: app_url.as_concrete_TypeRef(),
834 itemURLs: urls_to_open.as_concrete_TypeRef(),
835 passThruParams: ptr::null(),
836 launchFlags: kLSLaunchDefaults,
837 asyncRefCon: ptr::null_mut(),
838 },
839 ptr::null_mut(),
840 )
841 };
842
843 anyhow::ensure!(
844 status == 0,
845 "cannot start app bundle {}",
846 self.zed_version_string()
847 );
848 }
849
850 Self::LocalPath { executable, .. } => {
851 let executable_parent = executable
852 .parent()
853 .with_context(|| format!("Executable {executable:?} path has no parent"))?;
854 let subprocess_stdout_file = fs::File::create(
855 executable_parent.join("zed_dev.log"),
856 )
857 .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
858 let subprocess_stdin_file =
859 subprocess_stdout_file.try_clone().with_context(|| {
860 format!("Cloning descriptor for file {subprocess_stdout_file:?}")
861 })?;
862 let mut command = std::process::Command::new(executable);
863 let command = command
864 .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
865 .stderr(subprocess_stdout_file)
866 .stdout(subprocess_stdin_file)
867 .arg(url);
868
869 command
870 .spawn()
871 .with_context(|| format!("Spawning {command:?}"))?;
872 }
873 }
874
875 Ok(())
876 }
877
878 fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
879 let path = match self {
880 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
881 Bundle::LocalPath { executable, .. } => executable.clone(),
882 };
883
884 std::process::Command::new(path).arg(ipc_url).status()
885 }
886
887 fn path(&self) -> PathBuf {
888 match self {
889 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed").clone(),
890 Bundle::LocalPath { executable, .. } => executable.clone(),
891 }
892 }
893 }
894
895 impl Bundle {
896 fn version(&self) -> String {
897 match self {
898 Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
899 Self::LocalPath { .. } => "<development>".to_string(),
900 }
901 }
902
903 fn path(&self) -> &Path {
904 match self {
905 Self::App { app_bundle, .. } => app_bundle,
906 Self::LocalPath { executable, .. } => executable,
907 }
908 }
909 }
910
911 pub(super) fn spawn_channel_cli(
912 channel: release_channel::ReleaseChannel,
913 leftover_args: Vec<String>,
914 ) -> Result<()> {
915 use anyhow::bail;
916
917 let app_id_prompt = format!("id of app \"{}\"", channel.display_name());
918 let app_id_output = Command::new("osascript")
919 .arg("-e")
920 .arg(&app_id_prompt)
921 .output()?;
922 if !app_id_output.status.success() {
923 bail!("Could not determine app id for {}", channel.display_name());
924 }
925 let app_name = String::from_utf8(app_id_output.stdout)?.trim().to_owned();
926 let app_path_prompt = format!("kMDItemCFBundleIdentifier == '{app_name}'");
927 let app_path_output = Command::new("mdfind").arg(app_path_prompt).output()?;
928 if !app_path_output.status.success() {
929 bail!(
930 "Could not determine app path for {}",
931 channel.display_name()
932 );
933 }
934 let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
935 let cli_path = format!("{app_path}/Contents/MacOS/cli");
936 Command::new(cli_path).args(leftover_args).spawn()?;
937 Ok(())
938 }
939}