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