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