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