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