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