main.rs

  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        app.launch(url)?;
261        sender.join().unwrap()?;
262        pipe_handle.join().unwrap()?;
263    }
264
265    if let Some(exit_status) = exit_status.lock().take() {
266        std::process::exit(exit_status);
267    }
268    Ok(())
269}
270
271#[cfg(any(target_os = "linux", target_os = "freebsd"))]
272mod linux {
273    use std::{
274        env,
275        ffi::OsString,
276        io,
277        os::unix::net::{SocketAddr, UnixDatagram},
278        path::{Path, PathBuf},
279        process::{self, ExitStatus},
280        thread,
281        time::Duration,
282    };
283
284    use anyhow::anyhow;
285    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
286    use fork::Fork;
287    use once_cell::sync::Lazy;
288
289    use crate::{Detect, InstalledApp};
290
291    static RELEASE_CHANNEL: Lazy<String> =
292        Lazy::new(|| include_str!("../../zed/RELEASE_CHANNEL").trim().to_string());
293
294    struct App(PathBuf);
295
296    impl Detect {
297        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
298            let path = if let Some(path) = path {
299                path.to_path_buf().canonicalize()?
300            } else {
301                let cli = env::current_exe()?;
302                let dir = cli
303                    .parent()
304                    .ok_or_else(|| anyhow!("no parent path for cli"))?;
305
306                // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
307                // ./zed is for the target directory in development builds.
308                let possible_locations =
309                    ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
310                possible_locations
311                    .iter()
312                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
313                    .ok_or_else(|| {
314                        anyhow!("could not find any of: {}", possible_locations.join(", "))
315                    })?
316            };
317
318            Ok(App(path))
319        }
320    }
321
322    impl InstalledApp for App {
323        fn zed_version_string(&self) -> String {
324            format!(
325                "Zed {}{}{}",
326                if *RELEASE_CHANNEL == "stable" {
327                    "".to_string()
328                } else {
329                    format!(" {} ", *RELEASE_CHANNEL)
330                },
331                option_env!("RELEASE_VERSION").unwrap_or_default(),
332                self.0.display(),
333            )
334        }
335
336        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
337            let sock_path = paths::support_dir().join(format!("zed-{}.sock", *RELEASE_CHANNEL));
338            let sock = UnixDatagram::unbound()?;
339            if sock.connect(&sock_path).is_err() {
340                self.boot_background(ipc_url)?;
341            } else {
342                sock.send(ipc_url.as_bytes())?;
343            }
344            Ok(())
345        }
346
347        fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
348            std::process::Command::new(self.0.clone())
349                .arg(ipc_url)
350                .status()
351        }
352    }
353
354    impl App {
355        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
356            let path = &self.0;
357
358            match fork::fork() {
359                Ok(Fork::Parent(_)) => Ok(()),
360                Ok(Fork::Child) => {
361                    std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "");
362                    if let Err(_) = fork::setsid() {
363                        eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
364                        process::exit(1);
365                    }
366                    if let Err(_) = fork::close_fd() {
367                        eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
368                    }
369                    let error =
370                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
371                    // if exec succeeded, we never get here.
372                    eprintln!("failed to exec {:?}: {}", path, error);
373                    process::exit(1)
374                }
375                Err(_) => Err(anyhow!(io::Error::last_os_error())),
376            }
377        }
378
379        fn wait_for_socket(
380            &self,
381            sock_addr: &SocketAddr,
382            sock: &mut UnixDatagram,
383        ) -> Result<(), std::io::Error> {
384            for _ in 0..100 {
385                thread::sleep(Duration::from_millis(10));
386                if sock.connect_addr(&sock_addr).is_ok() {
387                    return Ok(());
388                }
389            }
390            sock.connect_addr(&sock_addr)
391        }
392    }
393}
394
395#[cfg(any(target_os = "linux", target_os = "freebsd"))]
396mod flatpak {
397    use std::ffi::OsString;
398    use std::path::PathBuf;
399    use std::process::Command;
400    use std::{env, process};
401
402    const EXTRA_LIB_ENV_NAME: &'static str = "ZED_FLATPAK_LIB_PATH";
403    const NO_ESCAPE_ENV_NAME: &'static str = "ZED_FLATPAK_NO_ESCAPE";
404
405    /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
406    pub fn ld_extra_libs() {
407        let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
408            env::split_paths(&paths).collect()
409        } else {
410            Vec::new()
411        };
412
413        if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
414            paths.push(extra_path.into());
415        }
416
417        env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap());
418    }
419
420    /// Restarts outside of the sandbox if currently running within it
421    pub fn try_restart_to_host() {
422        if let Some(flatpak_dir) = get_flatpak_dir() {
423            let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
424            args.append(&mut get_xdg_env_args());
425            args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
426            args.push(
427                format!(
428                    "--env={EXTRA_LIB_ENV_NAME}={}",
429                    flatpak_dir.join("lib").to_str().unwrap()
430                )
431                .into(),
432            );
433            args.push(flatpak_dir.join("bin").join("zed").into());
434
435            let mut is_app_location_set = false;
436            for arg in &env::args_os().collect::<Vec<_>>()[1..] {
437                args.push(arg.clone());
438                is_app_location_set |= arg == "--zed";
439            }
440
441            if !is_app_location_set {
442                args.push("--zed".into());
443                args.push(flatpak_dir.join("libexec").join("zed-editor").into());
444            }
445
446            let error = exec::execvp("/usr/bin/flatpak-spawn", args);
447            eprintln!("failed restart cli on host: {:?}", error);
448            process::exit(1);
449        }
450    }
451
452    pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
453        if env::var(NO_ESCAPE_ENV_NAME).is_ok()
454            && env::var("FLATPAK_ID").map_or(false, |id| id.starts_with("dev.zed.Zed"))
455        {
456            if args.zed.is_none() {
457                args.zed = Some("/app/libexec/zed-editor".into());
458                env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed");
459            }
460        }
461        args
462    }
463
464    fn get_flatpak_dir() -> Option<PathBuf> {
465        if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
466            return None;
467        }
468
469        if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
470            if !flatpak_id.starts_with("dev.zed.Zed") {
471                return None;
472            }
473
474            let install_dir = Command::new("/usr/bin/flatpak-spawn")
475                .arg("--host")
476                .arg("flatpak")
477                .arg("info")
478                .arg("--show-location")
479                .arg(flatpak_id)
480                .output()
481                .unwrap();
482            let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
483            Some(install_dir.join("files"))
484        } else {
485            None
486        }
487    }
488
489    fn get_xdg_env_args() -> Vec<OsString> {
490        let xdg_keys = [
491            "XDG_DATA_HOME",
492            "XDG_CONFIG_HOME",
493            "XDG_CACHE_HOME",
494            "XDG_STATE_HOME",
495        ];
496        env::vars()
497            .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
498            .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
499            .collect()
500    }
501}
502
503// todo("windows")
504#[cfg(target_os = "windows")]
505mod windows {
506    use crate::{Detect, InstalledApp};
507    use std::io;
508    use std::path::Path;
509    use std::process::ExitStatus;
510
511    struct App;
512    impl InstalledApp for App {
513        fn zed_version_string(&self) -> String {
514            unimplemented!()
515        }
516        fn launch(&self, _ipc_url: String) -> anyhow::Result<()> {
517            unimplemented!()
518        }
519        fn run_foreground(&self, _ipc_url: String) -> io::Result<ExitStatus> {
520            unimplemented!()
521        }
522    }
523
524    impl Detect {
525        pub fn detect(_path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
526            Ok(App)
527        }
528    }
529}
530
531#[cfg(target_os = "macos")]
532mod mac_os {
533    use anyhow::{anyhow, Context, Result};
534    use core_foundation::{
535        array::{CFArray, CFIndex},
536        string::kCFStringEncodingUTF8,
537        url::{CFURLCreateWithBytes, CFURL},
538    };
539    use core_services::{kLSLaunchDefaults, LSLaunchURLSpec, LSOpenFromURLSpec, TCFType};
540    use serde::Deserialize;
541    use std::{
542        ffi::OsStr,
543        fs, io,
544        path::{Path, PathBuf},
545        process::{Command, ExitStatus},
546        ptr,
547    };
548
549    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
550
551    use crate::{Detect, InstalledApp};
552
553    #[derive(Debug, Deserialize)]
554    struct InfoPlist {
555        #[serde(rename = "CFBundleShortVersionString")]
556        bundle_short_version_string: String,
557    }
558
559    enum Bundle {
560        App {
561            app_bundle: PathBuf,
562            plist: InfoPlist,
563        },
564        LocalPath {
565            executable: PathBuf,
566            plist: InfoPlist,
567        },
568    }
569
570    fn locate_bundle() -> Result<PathBuf> {
571        let cli_path = std::env::current_exe()?.canonicalize()?;
572        let mut app_path = cli_path.clone();
573        while app_path.extension() != Some(OsStr::new("app")) {
574            if !app_path.pop() {
575                return Err(anyhow!("cannot find app bundle containing {:?}", cli_path));
576            }
577        }
578        Ok(app_path)
579    }
580
581    impl Detect {
582        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
583            let bundle_path = if let Some(bundle_path) = path {
584                bundle_path
585                    .canonicalize()
586                    .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
587            } else {
588                locate_bundle().context("bundle autodiscovery")?
589            };
590
591            match bundle_path.extension().and_then(|ext| ext.to_str()) {
592                Some("app") => {
593                    let plist_path = bundle_path.join("Contents/Info.plist");
594                    let plist =
595                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
596                            format!("Reading *.app bundle plist file at {plist_path:?}")
597                        })?;
598                    Ok(Bundle::App {
599                        app_bundle: bundle_path,
600                        plist,
601                    })
602                }
603                _ => {
604                    println!("Bundle path {bundle_path:?} has no *.app extension, attempting to locate a dev build");
605                    let plist_path = bundle_path
606                        .parent()
607                        .with_context(|| format!("Bundle path {bundle_path:?} has no parent"))?
608                        .join("WebRTC.framework/Resources/Info.plist");
609                    let plist =
610                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
611                            format!("Reading dev bundle plist file at {plist_path:?}")
612                        })?;
613                    Ok(Bundle::LocalPath {
614                        executable: bundle_path,
615                        plist,
616                    })
617                }
618            }
619        }
620    }
621
622    impl InstalledApp for Bundle {
623        fn zed_version_string(&self) -> String {
624            let is_dev = matches!(self, Self::LocalPath { .. });
625            format!(
626                "Zed {}{}{}",
627                self.plist().bundle_short_version_string,
628                if is_dev { " (dev)" } else { "" },
629                self.path().display(),
630            )
631        }
632
633        fn launch(&self, url: String) -> anyhow::Result<()> {
634            match self {
635                Self::App { app_bundle, .. } => {
636                    let app_path = app_bundle;
637
638                    let status = unsafe {
639                        let app_url = CFURL::from_path(app_path, true)
640                            .with_context(|| format!("invalid app path {app_path:?}"))?;
641                        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
642                            ptr::null(),
643                            url.as_ptr(),
644                            url.len() as CFIndex,
645                            kCFStringEncodingUTF8,
646                            ptr::null(),
647                        ));
648                        // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
649                        let urls_to_open =
650                            CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
651                        LSOpenFromURLSpec(
652                            &LSLaunchURLSpec {
653                                appURL: app_url.as_concrete_TypeRef(),
654                                itemURLs: urls_to_open.as_concrete_TypeRef(),
655                                passThruParams: ptr::null(),
656                                launchFlags: kLSLaunchDefaults,
657                                asyncRefCon: ptr::null_mut(),
658                            },
659                            ptr::null_mut(),
660                        )
661                    };
662
663                    anyhow::ensure!(
664                        status == 0,
665                        "cannot start app bundle {}",
666                        self.zed_version_string()
667                    );
668                }
669
670                Self::LocalPath { executable, .. } => {
671                    let executable_parent = executable
672                        .parent()
673                        .with_context(|| format!("Executable {executable:?} path has no parent"))?;
674                    let subprocess_stdout_file = fs::File::create(
675                        executable_parent.join("zed_dev.log"),
676                    )
677                    .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
678                    let subprocess_stdin_file =
679                        subprocess_stdout_file.try_clone().with_context(|| {
680                            format!("Cloning descriptor for file {subprocess_stdout_file:?}")
681                        })?;
682                    let mut command = std::process::Command::new(executable);
683                    let command = command
684                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
685                        .stderr(subprocess_stdout_file)
686                        .stdout(subprocess_stdin_file)
687                        .arg(url);
688
689                    command
690                        .spawn()
691                        .with_context(|| format!("Spawning {command:?}"))?;
692                }
693            }
694
695            Ok(())
696        }
697
698        fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
699            let path = match self {
700                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
701                Bundle::LocalPath { executable, .. } => executable.clone(),
702            };
703
704            std::process::Command::new(path).arg(ipc_url).status()
705        }
706    }
707
708    impl Bundle {
709        fn plist(&self) -> &InfoPlist {
710            match self {
711                Self::App { plist, .. } => plist,
712                Self::LocalPath { plist, .. } => plist,
713            }
714        }
715
716        fn path(&self) -> &Path {
717            match self {
718                Self::App { app_bundle, .. } => app_bundle,
719                Self::LocalPath { executable, .. } => executable,
720            }
721        }
722    }
723
724    pub(super) fn spawn_channel_cli(
725        channel: release_channel::ReleaseChannel,
726        leftover_args: Vec<String>,
727    ) -> Result<()> {
728        use anyhow::bail;
729
730        let app_id_prompt = format!("id of app \"{}\"", channel.display_name());
731        let app_id_output = Command::new("osascript")
732            .arg("-e")
733            .arg(&app_id_prompt)
734            .output()?;
735        if !app_id_output.status.success() {
736            bail!("Could not determine app id for {}", channel.display_name());
737        }
738        let app_name = String::from_utf8(app_id_output.stdout)?.trim().to_owned();
739        let app_path_prompt = format!("kMDItemCFBundleIdentifier == '{app_name}'");
740        let app_path_output = Command::new("mdfind").arg(app_path_prompt).output()?;
741        if !app_path_output.status.success() {
742            bail!(
743                "Could not determine app path for {}",
744                channel.display_name()
745            );
746        }
747        let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
748        let cli_path = format!("{app_path}/Contents/MacOS/cli");
749        Command::new(cli_path).args(leftover_args).spawn()?;
750        Ok(())
751    }
752}