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