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