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(|tmp_file| {
319 thread::spawn(move || {
320 let stdin = std::io::stdin().lock();
321 if io::IsTerminal::is_terminal(&stdin) {
322 return Ok(());
323 }
324 return pipe_to_tmp(stdin, tmp_file);
325 })
326 });
327
328 let anonymous_fd_pipe_handles: Vec<JoinHandle<anyhow::Result<()>>> = anonymous_fd_tmp_files
329 .into_iter()
330 .map(|(file, tmp_file)| thread::spawn(move || pipe_to_tmp(file, 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 pipe_to_tmp(mut src: impl io::Read, mut dest: fs::File) -> Result<()> {
353 let mut buffer = [0; 8 * 1024];
354 loop {
355 let bytes_read = match src.read(&mut buffer) {
356 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
357 res => res?,
358 };
359 if bytes_read == 0 {
360 break;
361 }
362 io::Write::write_all(&mut dest, &buffer[..bytes_read])?;
363 }
364 io::Write::flush(&mut dest)?;
365 Ok(())
366}
367
368fn anonymous_fd(path: &str) -> Option<fs::File> {
369 #[cfg(target_os = "linux")]
370 {
371 use std::os::fd::{self, FromRawFd};
372
373 let fd_str = path.strip_prefix("/proc/self/fd/")?;
374
375 let link = fs::read_link(path).ok()?;
376 if !link.starts_with("memfd:") {
377 return None;
378 }
379
380 let fd: fd::RawFd = fd_str.parse().ok()?;
381 let file = unsafe { fs::File::from_raw_fd(fd) };
382 return Some(file);
383 }
384 #[cfg(any(target_os = "macos", target_os = "freebsd"))]
385 {
386 use std::os::{
387 fd::{self, FromRawFd},
388 unix::fs::FileTypeExt,
389 };
390
391 let fd_str = path.strip_prefix("/dev/fd/")?;
392
393 let metadata = fs::metadata(path).ok()?;
394 let file_type = metadata.file_type();
395 if !file_type.is_fifo() && !file_type.is_socket() {
396 return None;
397 }
398 let fd: fd::RawFd = fd_str.parse().ok()?;
399 let file = unsafe { fs::File::from_raw_fd(fd) };
400 return Some(file);
401 }
402 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
403 {
404 _ = path;
405 // not implemented for bsd, windows. Could be, but isn't yet
406 return None;
407 }
408}
409
410#[cfg(any(target_os = "linux", target_os = "freebsd"))]
411mod linux {
412 use std::{
413 env,
414 ffi::OsString,
415 io,
416 os::unix::net::{SocketAddr, UnixDatagram},
417 path::{Path, PathBuf},
418 process::{self, ExitStatus},
419 sync::LazyLock,
420 thread,
421 time::Duration,
422 };
423
424 use anyhow::{Context as _, anyhow};
425 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
426 use fork::Fork;
427
428 use crate::{Detect, InstalledApp};
429
430 static RELEASE_CHANNEL: LazyLock<String> =
431 LazyLock::new(|| include_str!("../../zed/RELEASE_CHANNEL").trim().to_string());
432
433 struct App(PathBuf);
434
435 impl Detect {
436 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
437 let path = if let Some(path) = path {
438 path.to_path_buf().canonicalize()?
439 } else {
440 let cli = env::current_exe()?;
441 let dir = cli.parent().context("no parent path for cli")?;
442
443 // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
444 // ./zed is for the target directory in development builds.
445 let possible_locations =
446 ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
447 possible_locations
448 .iter()
449 .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
450 .with_context(|| {
451 format!("could not find any of: {}", possible_locations.join(", "))
452 })?
453 };
454
455 Ok(App(path))
456 }
457 }
458
459 impl InstalledApp for App {
460 fn zed_version_string(&self) -> String {
461 format!(
462 "Zed {}{}{} – {}",
463 if *RELEASE_CHANNEL == "stable" {
464 "".to_string()
465 } else {
466 format!("{} ", *RELEASE_CHANNEL)
467 },
468 option_env!("RELEASE_VERSION").unwrap_or_default(),
469 match option_env!("ZED_COMMIT_SHA") {
470 Some(commit_sha) => format!(" {commit_sha} "),
471 None => "".to_string(),
472 },
473 self.0.display(),
474 )
475 }
476
477 fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
478 let sock_path = paths::data_dir().join(format!("zed-{}.sock", *RELEASE_CHANNEL));
479 let sock = UnixDatagram::unbound()?;
480 if sock.connect(&sock_path).is_err() {
481 self.boot_background(ipc_url)?;
482 } else {
483 sock.send(ipc_url.as_bytes())?;
484 }
485 Ok(())
486 }
487
488 fn run_foreground(
489 &self,
490 ipc_url: String,
491 user_data_dir: Option<&str>,
492 ) -> io::Result<ExitStatus> {
493 let mut cmd = std::process::Command::new(self.0.clone());
494 cmd.arg(ipc_url);
495 if let Some(dir) = user_data_dir {
496 cmd.arg("--user-data-dir").arg(dir);
497 }
498 cmd.status()
499 }
500
501 fn path(&self) -> PathBuf {
502 self.0.clone()
503 }
504 }
505
506 impl App {
507 fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
508 let path = &self.0;
509
510 match fork::fork() {
511 Ok(Fork::Parent(_)) => Ok(()),
512 Ok(Fork::Child) => {
513 unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
514 if let Err(_) = fork::setsid() {
515 eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
516 process::exit(1);
517 }
518 if let Err(_) = fork::close_fd() {
519 eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
520 }
521 let error =
522 exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
523 // if exec succeeded, we never get here.
524 eprintln!("failed to exec {:?}: {}", path, error);
525 process::exit(1)
526 }
527 Err(_) => Err(anyhow!(io::Error::last_os_error())),
528 }
529 }
530
531 fn wait_for_socket(
532 &self,
533 sock_addr: &SocketAddr,
534 sock: &mut UnixDatagram,
535 ) -> Result<(), std::io::Error> {
536 for _ in 0..100 {
537 thread::sleep(Duration::from_millis(10));
538 if sock.connect_addr(&sock_addr).is_ok() {
539 return Ok(());
540 }
541 }
542 sock.connect_addr(&sock_addr)
543 }
544 }
545}
546
547#[cfg(target_os = "linux")]
548mod flatpak {
549 use std::ffi::OsString;
550 use std::path::PathBuf;
551 use std::process::Command;
552 use std::{env, process};
553
554 const EXTRA_LIB_ENV_NAME: &'static str = "ZED_FLATPAK_LIB_PATH";
555 const NO_ESCAPE_ENV_NAME: &'static str = "ZED_FLATPAK_NO_ESCAPE";
556
557 /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
558 pub fn ld_extra_libs() {
559 let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
560 env::split_paths(&paths).collect()
561 } else {
562 Vec::new()
563 };
564
565 if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
566 paths.push(extra_path.into());
567 }
568
569 unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
570 }
571
572 /// Restarts outside of the sandbox if currently running within it
573 pub fn try_restart_to_host() {
574 if let Some(flatpak_dir) = get_flatpak_dir() {
575 let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
576 args.append(&mut get_xdg_env_args());
577 args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
578 args.push(
579 format!(
580 "--env={EXTRA_LIB_ENV_NAME}={}",
581 flatpak_dir.join("lib").to_str().unwrap()
582 )
583 .into(),
584 );
585 args.push(flatpak_dir.join("bin").join("zed").into());
586
587 let mut is_app_location_set = false;
588 for arg in &env::args_os().collect::<Vec<_>>()[1..] {
589 args.push(arg.clone());
590 is_app_location_set |= arg == "--zed";
591 }
592
593 if !is_app_location_set {
594 args.push("--zed".into());
595 args.push(flatpak_dir.join("libexec").join("zed-editor").into());
596 }
597
598 let error = exec::execvp("/usr/bin/flatpak-spawn", args);
599 eprintln!("failed restart cli on host: {:?}", error);
600 process::exit(1);
601 }
602 }
603
604 pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
605 if env::var(NO_ESCAPE_ENV_NAME).is_ok()
606 && env::var("FLATPAK_ID").map_or(false, |id| id.starts_with("dev.zed.Zed"))
607 {
608 if args.zed.is_none() {
609 args.zed = Some("/app/libexec/zed-editor".into());
610 unsafe {
611 env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed")
612 };
613 }
614 }
615 args
616 }
617
618 fn get_flatpak_dir() -> Option<PathBuf> {
619 if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
620 return None;
621 }
622
623 if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
624 if !flatpak_id.starts_with("dev.zed.Zed") {
625 return None;
626 }
627
628 let install_dir = Command::new("/usr/bin/flatpak-spawn")
629 .arg("--host")
630 .arg("flatpak")
631 .arg("info")
632 .arg("--show-location")
633 .arg(flatpak_id)
634 .output()
635 .unwrap();
636 let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
637 Some(install_dir.join("files"))
638 } else {
639 None
640 }
641 }
642
643 fn get_xdg_env_args() -> Vec<OsString> {
644 let xdg_keys = [
645 "XDG_DATA_HOME",
646 "XDG_CONFIG_HOME",
647 "XDG_CACHE_HOME",
648 "XDG_STATE_HOME",
649 ];
650 env::vars()
651 .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
652 .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
653 .collect()
654 }
655}
656
657#[cfg(target_os = "windows")]
658mod windows {
659 use anyhow::Context;
660 use release_channel::app_identifier;
661 use windows::{
662 Win32::{
663 Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
664 Storage::FileSystem::{
665 CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
666 },
667 System::Threading::CreateMutexW,
668 },
669 core::HSTRING,
670 };
671
672 use crate::{Detect, InstalledApp};
673 use std::io;
674 use std::path::{Path, PathBuf};
675 use std::process::ExitStatus;
676
677 fn check_single_instance() -> bool {
678 let mutex = unsafe {
679 CreateMutexW(
680 None,
681 false,
682 &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
683 )
684 .expect("Unable to create instance sync event")
685 };
686 let last_err = unsafe { GetLastError() };
687 let _ = unsafe { CloseHandle(mutex) };
688 last_err != ERROR_ALREADY_EXISTS
689 }
690
691 struct App(PathBuf);
692
693 impl InstalledApp for App {
694 fn zed_version_string(&self) -> String {
695 format!(
696 "Zed {}{}{} – {}",
697 if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
698 "".to_string()
699 } else {
700 format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
701 },
702 option_env!("RELEASE_VERSION").unwrap_or_default(),
703 match option_env!("ZED_COMMIT_SHA") {
704 Some(commit_sha) => format!(" {commit_sha} "),
705 None => "".to_string(),
706 },
707 self.0.display(),
708 )
709 }
710
711 fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
712 if check_single_instance() {
713 std::process::Command::new(self.0.clone())
714 .arg(ipc_url)
715 .spawn()?;
716 } else {
717 unsafe {
718 let pipe = CreateFileW(
719 &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
720 GENERIC_WRITE.0,
721 FILE_SHARE_MODE::default(),
722 None,
723 OPEN_EXISTING,
724 FILE_FLAGS_AND_ATTRIBUTES::default(),
725 None,
726 )?;
727 let message = ipc_url.as_bytes();
728 let mut bytes_written = 0;
729 WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
730 CloseHandle(pipe)?;
731 }
732 }
733 Ok(())
734 }
735
736 fn run_foreground(
737 &self,
738 ipc_url: String,
739 user_data_dir: Option<&str>,
740 ) -> io::Result<ExitStatus> {
741 let mut cmd = std::process::Command::new(self.0.clone());
742 cmd.arg(ipc_url).arg("--foreground");
743 if let Some(dir) = user_data_dir {
744 cmd.arg("--user-data-dir").arg(dir);
745 }
746 cmd.spawn()?.wait()
747 }
748
749 fn path(&self) -> PathBuf {
750 self.0.clone()
751 }
752 }
753
754 impl Detect {
755 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
756 let path = if let Some(path) = path {
757 path.to_path_buf().canonicalize()?
758 } else {
759 let cli = std::env::current_exe()?;
760 let dir = cli.parent().context("no parent path for cli")?;
761
762 // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
763 // directory in development builds.
764 let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
765 possible_locations
766 .iter()
767 .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
768 .context(format!(
769 "could not find any of: {}",
770 possible_locations.join(", ")
771 ))?
772 };
773
774 Ok(App(path))
775 }
776 }
777}
778
779#[cfg(target_os = "macos")]
780mod mac_os {
781 use anyhow::{Context as _, Result};
782 use core_foundation::{
783 array::{CFArray, CFIndex},
784 base::TCFType as _,
785 string::kCFStringEncodingUTF8,
786 url::{CFURL, CFURLCreateWithBytes},
787 };
788 use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
789 use serde::Deserialize;
790 use std::{
791 ffi::OsStr,
792 fs, io,
793 path::{Path, PathBuf},
794 process::{Command, ExitStatus},
795 ptr,
796 };
797
798 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
799
800 use crate::{Detect, InstalledApp};
801
802 #[derive(Debug, Deserialize)]
803 struct InfoPlist {
804 #[serde(rename = "CFBundleShortVersionString")]
805 bundle_short_version_string: String,
806 }
807
808 enum Bundle {
809 App {
810 app_bundle: PathBuf,
811 plist: InfoPlist,
812 },
813 LocalPath {
814 executable: PathBuf,
815 },
816 }
817
818 fn locate_bundle() -> Result<PathBuf> {
819 let cli_path = std::env::current_exe()?.canonicalize()?;
820 let mut app_path = cli_path.clone();
821 while app_path.extension() != Some(OsStr::new("app")) {
822 anyhow::ensure!(
823 app_path.pop(),
824 "cannot find app bundle containing {cli_path:?}"
825 );
826 }
827 Ok(app_path)
828 }
829
830 impl Detect {
831 pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
832 let bundle_path = if let Some(bundle_path) = path {
833 bundle_path
834 .canonicalize()
835 .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
836 } else {
837 locate_bundle().context("bundle autodiscovery")?
838 };
839
840 match bundle_path.extension().and_then(|ext| ext.to_str()) {
841 Some("app") => {
842 let plist_path = bundle_path.join("Contents/Info.plist");
843 let plist =
844 plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
845 format!("Reading *.app bundle plist file at {plist_path:?}")
846 })?;
847 Ok(Bundle::App {
848 app_bundle: bundle_path,
849 plist,
850 })
851 }
852 _ => Ok(Bundle::LocalPath {
853 executable: bundle_path,
854 }),
855 }
856 }
857 }
858
859 impl InstalledApp for Bundle {
860 fn zed_version_string(&self) -> String {
861 format!("Zed {} – {}", self.version(), self.path().display(),)
862 }
863
864 fn launch(&self, url: String) -> anyhow::Result<()> {
865 match self {
866 Self::App { app_bundle, .. } => {
867 let app_path = app_bundle;
868
869 let status = unsafe {
870 let app_url = CFURL::from_path(app_path, true)
871 .with_context(|| format!("invalid app path {app_path:?}"))?;
872 let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
873 ptr::null(),
874 url.as_ptr(),
875 url.len() as CFIndex,
876 kCFStringEncodingUTF8,
877 ptr::null(),
878 ));
879 // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
880 let urls_to_open =
881 CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
882 LSOpenFromURLSpec(
883 &LSLaunchURLSpec {
884 appURL: app_url.as_concrete_TypeRef(),
885 itemURLs: urls_to_open.as_concrete_TypeRef(),
886 passThruParams: ptr::null(),
887 launchFlags: kLSLaunchDefaults,
888 asyncRefCon: ptr::null_mut(),
889 },
890 ptr::null_mut(),
891 )
892 };
893
894 anyhow::ensure!(
895 status == 0,
896 "cannot start app bundle {}",
897 self.zed_version_string()
898 );
899 }
900
901 Self::LocalPath { executable, .. } => {
902 let executable_parent = executable
903 .parent()
904 .with_context(|| format!("Executable {executable:?} path has no parent"))?;
905 let subprocess_stdout_file = fs::File::create(
906 executable_parent.join("zed_dev.log"),
907 )
908 .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
909 let subprocess_stdin_file =
910 subprocess_stdout_file.try_clone().with_context(|| {
911 format!("Cloning descriptor for file {subprocess_stdout_file:?}")
912 })?;
913 let mut command = std::process::Command::new(executable);
914 let command = command
915 .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
916 .stderr(subprocess_stdout_file)
917 .stdout(subprocess_stdin_file)
918 .arg(url);
919
920 command
921 .spawn()
922 .with_context(|| format!("Spawning {command:?}"))?;
923 }
924 }
925
926 Ok(())
927 }
928
929 fn run_foreground(
930 &self,
931 ipc_url: String,
932 user_data_dir: Option<&str>,
933 ) -> io::Result<ExitStatus> {
934 let path = match self {
935 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
936 Bundle::LocalPath { executable, .. } => executable.clone(),
937 };
938
939 let mut cmd = std::process::Command::new(path);
940 cmd.arg(ipc_url);
941 if let Some(dir) = user_data_dir {
942 cmd.arg("--user-data-dir").arg(dir);
943 }
944 cmd.status()
945 }
946
947 fn path(&self) -> PathBuf {
948 match self {
949 Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed").clone(),
950 Bundle::LocalPath { executable, .. } => executable.clone(),
951 }
952 }
953 }
954
955 impl Bundle {
956 fn version(&self) -> String {
957 match self {
958 Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
959 Self::LocalPath { .. } => "<development>".to_string(),
960 }
961 }
962
963 fn path(&self) -> &Path {
964 match self {
965 Self::App { app_bundle, .. } => app_bundle,
966 Self::LocalPath { executable, .. } => executable,
967 }
968 }
969 }
970
971 pub(super) fn spawn_channel_cli(
972 channel: release_channel::ReleaseChannel,
973 leftover_args: Vec<String>,
974 ) -> Result<()> {
975 use anyhow::bail;
976
977 let app_id_prompt = format!("id of app \"{}\"", channel.display_name());
978 let app_id_output = Command::new("osascript")
979 .arg("-e")
980 .arg(&app_id_prompt)
981 .output()?;
982 if !app_id_output.status.success() {
983 bail!("Could not determine app id for {}", channel.display_name());
984 }
985 let app_name = String::from_utf8(app_id_output.stdout)?.trim().to_owned();
986 let app_path_prompt = format!("kMDItemCFBundleIdentifier == '{app_name}'");
987 let app_path_output = Command::new("mdfind").arg(app_path_prompt).output()?;
988 if !app_path_output.status.success() {
989 bail!(
990 "Could not determine app path for {}",
991 channel.display_name()
992 );
993 }
994 let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
995 let cli_path = format!("{app_path}/Contents/MacOS/cli");
996 Command::new(cli_path).args(leftover_args).spawn()?;
997 Ok(())
998 }
999}