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