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