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