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