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