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