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        return 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        return 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        return 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        sync::LazyLock,
404        thread,
405        time::Duration,
406    };
407
408    use anyhow::{Context as _, anyhow};
409    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
410    use fork::Fork;
411
412    use crate::{Detect, InstalledApp};
413
414    static RELEASE_CHANNEL: LazyLock<String> =
415        LazyLock::new(|| include_str!("../../zed/RELEASE_CHANNEL").trim().to_string());
416
417    struct App(PathBuf);
418
419    impl Detect {
420        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
421            let path = if let Some(path) = path {
422                path.to_path_buf().canonicalize()?
423            } else {
424                let cli = env::current_exe()?;
425                let dir = cli.parent().context("no parent path for cli")?;
426
427                // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
428                // ./zed is for the target directory in development builds.
429                let possible_locations =
430                    ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
431                possible_locations
432                    .iter()
433                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
434                    .with_context(|| {
435                        format!("could not find any of: {}", possible_locations.join(", "))
436                    })?
437            };
438
439            Ok(App(path))
440        }
441    }
442
443    impl InstalledApp for App {
444        fn zed_version_string(&self) -> String {
445            format!(
446                "Zed {}{}{}{}",
447                if *RELEASE_CHANNEL == "stable" {
448                    "".to_string()
449                } else {
450                    format!("{} ", *RELEASE_CHANNEL)
451                },
452                option_env!("RELEASE_VERSION").unwrap_or_default(),
453                match option_env!("ZED_COMMIT_SHA") {
454                    Some(commit_sha) => format!(" {commit_sha} "),
455                    None => "".to_string(),
456                },
457                self.0.display(),
458            )
459        }
460
461        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
462            let sock_path = paths::data_dir().join(format!("zed-{}.sock", *RELEASE_CHANNEL));
463            let sock = UnixDatagram::unbound()?;
464            if sock.connect(&sock_path).is_err() {
465                self.boot_background(ipc_url)?;
466            } else {
467                sock.send(ipc_url.as_bytes())?;
468            }
469            Ok(())
470        }
471
472        fn run_foreground(
473            &self,
474            ipc_url: String,
475            user_data_dir: Option<&str>,
476        ) -> io::Result<ExitStatus> {
477            let mut cmd = std::process::Command::new(self.0.clone());
478            cmd.arg(ipc_url);
479            if let Some(dir) = user_data_dir {
480                cmd.arg("--user-data-dir").arg(dir);
481            }
482            cmd.status()
483        }
484
485        fn path(&self) -> PathBuf {
486            self.0.clone()
487        }
488    }
489
490    impl App {
491        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
492            let path = &self.0;
493
494            match fork::fork() {
495                Ok(Fork::Parent(_)) => Ok(()),
496                Ok(Fork::Child) => {
497                    unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
498                    if let Err(_) = fork::setsid() {
499                        eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
500                        process::exit(1);
501                    }
502                    if let Err(_) = fork::close_fd() {
503                        eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
504                    }
505                    let error =
506                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
507                    // if exec succeeded, we never get here.
508                    eprintln!("failed to exec {:?}: {}", path, error);
509                    process::exit(1)
510                }
511                Err(_) => Err(anyhow!(io::Error::last_os_error())),
512            }
513        }
514
515        fn wait_for_socket(
516            &self,
517            sock_addr: &SocketAddr,
518            sock: &mut UnixDatagram,
519        ) -> Result<(), std::io::Error> {
520            for _ in 0..100 {
521                thread::sleep(Duration::from_millis(10));
522                if sock.connect_addr(&sock_addr).is_ok() {
523                    return Ok(());
524                }
525            }
526            sock.connect_addr(&sock_addr)
527        }
528    }
529}
530
531#[cfg(target_os = "linux")]
532mod flatpak {
533    use std::ffi::OsString;
534    use std::path::PathBuf;
535    use std::process::Command;
536    use std::{env, process};
537
538    const EXTRA_LIB_ENV_NAME: &'static str = "ZED_FLATPAK_LIB_PATH";
539    const NO_ESCAPE_ENV_NAME: &'static str = "ZED_FLATPAK_NO_ESCAPE";
540
541    /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
542    pub fn ld_extra_libs() {
543        let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
544            env::split_paths(&paths).collect()
545        } else {
546            Vec::new()
547        };
548
549        if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
550            paths.push(extra_path.into());
551        }
552
553        unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
554    }
555
556    /// Restarts outside of the sandbox if currently running within it
557    pub fn try_restart_to_host() {
558        if let Some(flatpak_dir) = get_flatpak_dir() {
559            let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
560            args.append(&mut get_xdg_env_args());
561            args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
562            args.push(
563                format!(
564                    "--env={EXTRA_LIB_ENV_NAME}={}",
565                    flatpak_dir.join("lib").to_str().unwrap()
566                )
567                .into(),
568            );
569            args.push(flatpak_dir.join("bin").join("zed").into());
570
571            let mut is_app_location_set = false;
572            for arg in &env::args_os().collect::<Vec<_>>()[1..] {
573                args.push(arg.clone());
574                is_app_location_set |= arg == "--zed";
575            }
576
577            if !is_app_location_set {
578                args.push("--zed".into());
579                args.push(flatpak_dir.join("libexec").join("zed-editor").into());
580            }
581
582            let error = exec::execvp("/usr/bin/flatpak-spawn", args);
583            eprintln!("failed restart cli on host: {:?}", error);
584            process::exit(1);
585        }
586    }
587
588    pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
589        if env::var(NO_ESCAPE_ENV_NAME).is_ok()
590            && env::var("FLATPAK_ID").map_or(false, |id| id.starts_with("dev.zed.Zed"))
591        {
592            if args.zed.is_none() {
593                args.zed = Some("/app/libexec/zed-editor".into());
594                unsafe {
595                    env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed")
596                };
597            }
598        }
599        args
600    }
601
602    fn get_flatpak_dir() -> Option<PathBuf> {
603        if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
604            return None;
605        }
606
607        if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
608            if !flatpak_id.starts_with("dev.zed.Zed") {
609                return None;
610            }
611
612            let install_dir = Command::new("/usr/bin/flatpak-spawn")
613                .arg("--host")
614                .arg("flatpak")
615                .arg("info")
616                .arg("--show-location")
617                .arg(flatpak_id)
618                .output()
619                .unwrap();
620            let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
621            Some(install_dir.join("files"))
622        } else {
623            None
624        }
625    }
626
627    fn get_xdg_env_args() -> Vec<OsString> {
628        let xdg_keys = [
629            "XDG_DATA_HOME",
630            "XDG_CONFIG_HOME",
631            "XDG_CACHE_HOME",
632            "XDG_STATE_HOME",
633        ];
634        env::vars()
635            .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
636            .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
637            .collect()
638    }
639}
640
641#[cfg(target_os = "windows")]
642mod windows {
643    use anyhow::Context;
644    use release_channel::app_identifier;
645    use windows::{
646        Win32::{
647            Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
648            Storage::FileSystem::{
649                CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
650            },
651            System::Threading::CreateMutexW,
652        },
653        core::HSTRING,
654    };
655
656    use crate::{Detect, InstalledApp};
657    use std::io;
658    use std::path::{Path, PathBuf};
659    use std::process::ExitStatus;
660
661    fn check_single_instance() -> bool {
662        let mutex = unsafe {
663            CreateMutexW(
664                None,
665                false,
666                &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
667            )
668            .expect("Unable to create instance sync event")
669        };
670        let last_err = unsafe { GetLastError() };
671        let _ = unsafe { CloseHandle(mutex) };
672        last_err != ERROR_ALREADY_EXISTS
673    }
674
675    struct App(PathBuf);
676
677    impl InstalledApp for App {
678        fn zed_version_string(&self) -> String {
679            format!(
680                "Zed {}{}{}{}",
681                if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
682                    "".to_string()
683                } else {
684                    format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
685                },
686                option_env!("RELEASE_VERSION").unwrap_or_default(),
687                match option_env!("ZED_COMMIT_SHA") {
688                    Some(commit_sha) => format!(" {commit_sha} "),
689                    None => "".to_string(),
690                },
691                self.0.display(),
692            )
693        }
694
695        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
696            if check_single_instance() {
697                std::process::Command::new(self.0.clone())
698                    .arg(ipc_url)
699                    .spawn()?;
700            } else {
701                unsafe {
702                    let pipe = CreateFileW(
703                        &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
704                        GENERIC_WRITE.0,
705                        FILE_SHARE_MODE::default(),
706                        None,
707                        OPEN_EXISTING,
708                        FILE_FLAGS_AND_ATTRIBUTES::default(),
709                        None,
710                    )?;
711                    let message = ipc_url.as_bytes();
712                    let mut bytes_written = 0;
713                    WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
714                    CloseHandle(pipe)?;
715                }
716            }
717            Ok(())
718        }
719
720        fn run_foreground(
721            &self,
722            ipc_url: String,
723            user_data_dir: Option<&str>,
724        ) -> io::Result<ExitStatus> {
725            let mut cmd = std::process::Command::new(self.0.clone());
726            cmd.arg(ipc_url).arg("--foreground");
727            if let Some(dir) = user_data_dir {
728                cmd.arg("--user-data-dir").arg(dir);
729            }
730            cmd.spawn()?.wait()
731        }
732
733        fn path(&self) -> PathBuf {
734            self.0.clone()
735        }
736    }
737
738    impl Detect {
739        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
740            let path = if let Some(path) = path {
741                path.to_path_buf().canonicalize()?
742            } else {
743                let cli = std::env::current_exe()?;
744                let dir = cli.parent().context("no parent path for cli")?;
745
746                // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
747                // directory in development builds.
748                let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
749                possible_locations
750                    .iter()
751                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
752                    .context(format!(
753                        "could not find any of: {}",
754                        possible_locations.join(", ")
755                    ))?
756            };
757
758            Ok(App(path))
759        }
760    }
761}
762
763#[cfg(target_os = "macos")]
764mod mac_os {
765    use anyhow::{Context as _, Result};
766    use core_foundation::{
767        array::{CFArray, CFIndex},
768        base::TCFType as _,
769        string::kCFStringEncodingUTF8,
770        url::{CFURL, CFURLCreateWithBytes},
771    };
772    use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
773    use serde::Deserialize;
774    use std::{
775        ffi::OsStr,
776        fs, io,
777        path::{Path, PathBuf},
778        process::{Command, ExitStatus},
779        ptr,
780    };
781
782    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
783
784    use crate::{Detect, InstalledApp};
785
786    #[derive(Debug, Deserialize)]
787    struct InfoPlist {
788        #[serde(rename = "CFBundleShortVersionString")]
789        bundle_short_version_string: String,
790    }
791
792    enum Bundle {
793        App {
794            app_bundle: PathBuf,
795            plist: InfoPlist,
796        },
797        LocalPath {
798            executable: PathBuf,
799        },
800    }
801
802    fn locate_bundle() -> Result<PathBuf> {
803        let cli_path = std::env::current_exe()?.canonicalize()?;
804        let mut app_path = cli_path.clone();
805        while app_path.extension() != Some(OsStr::new("app")) {
806            anyhow::ensure!(
807                app_path.pop(),
808                "cannot find app bundle containing {cli_path:?}"
809            );
810        }
811        Ok(app_path)
812    }
813
814    impl Detect {
815        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
816            let bundle_path = if let Some(bundle_path) = path {
817                bundle_path
818                    .canonicalize()
819                    .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
820            } else {
821                locate_bundle().context("bundle autodiscovery")?
822            };
823
824            match bundle_path.extension().and_then(|ext| ext.to_str()) {
825                Some("app") => {
826                    let plist_path = bundle_path.join("Contents/Info.plist");
827                    let plist =
828                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
829                            format!("Reading *.app bundle plist file at {plist_path:?}")
830                        })?;
831                    Ok(Bundle::App {
832                        app_bundle: bundle_path,
833                        plist,
834                    })
835                }
836                _ => Ok(Bundle::LocalPath {
837                    executable: bundle_path,
838                }),
839            }
840        }
841    }
842
843    impl InstalledApp for Bundle {
844        fn zed_version_string(&self) -> String {
845            format!("Zed {}{}", self.version(), self.path().display(),)
846        }
847
848        fn launch(&self, url: String) -> anyhow::Result<()> {
849            match self {
850                Self::App { app_bundle, .. } => {
851                    let app_path = app_bundle;
852
853                    let status = unsafe {
854                        let app_url = CFURL::from_path(app_path, true)
855                            .with_context(|| format!("invalid app path {app_path:?}"))?;
856                        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
857                            ptr::null(),
858                            url.as_ptr(),
859                            url.len() as CFIndex,
860                            kCFStringEncodingUTF8,
861                            ptr::null(),
862                        ));
863                        // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
864                        let urls_to_open =
865                            CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
866                        LSOpenFromURLSpec(
867                            &LSLaunchURLSpec {
868                                appURL: app_url.as_concrete_TypeRef(),
869                                itemURLs: urls_to_open.as_concrete_TypeRef(),
870                                passThruParams: ptr::null(),
871                                launchFlags: kLSLaunchDefaults,
872                                asyncRefCon: ptr::null_mut(),
873                            },
874                            ptr::null_mut(),
875                        )
876                    };
877
878                    anyhow::ensure!(
879                        status == 0,
880                        "cannot start app bundle {}",
881                        self.zed_version_string()
882                    );
883                }
884
885                Self::LocalPath { executable, .. } => {
886                    let executable_parent = executable
887                        .parent()
888                        .with_context(|| format!("Executable {executable:?} path has no parent"))?;
889                    let subprocess_stdout_file = fs::File::create(
890                        executable_parent.join("zed_dev.log"),
891                    )
892                    .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
893                    let subprocess_stdin_file =
894                        subprocess_stdout_file.try_clone().with_context(|| {
895                            format!("Cloning descriptor for file {subprocess_stdout_file:?}")
896                        })?;
897                    let mut command = std::process::Command::new(executable);
898                    let command = command
899                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
900                        .stderr(subprocess_stdout_file)
901                        .stdout(subprocess_stdin_file)
902                        .arg(url);
903
904                    command
905                        .spawn()
906                        .with_context(|| format!("Spawning {command:?}"))?;
907                }
908            }
909
910            Ok(())
911        }
912
913        fn run_foreground(
914            &self,
915            ipc_url: String,
916            user_data_dir: Option<&str>,
917        ) -> io::Result<ExitStatus> {
918            let path = match self {
919                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
920                Bundle::LocalPath { executable, .. } => executable.clone(),
921            };
922
923            let mut cmd = std::process::Command::new(path);
924            cmd.arg(ipc_url);
925            if let Some(dir) = user_data_dir {
926                cmd.arg("--user-data-dir").arg(dir);
927            }
928            cmd.status()
929        }
930
931        fn path(&self) -> PathBuf {
932            match self {
933                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed").clone(),
934                Bundle::LocalPath { executable, .. } => executable.clone(),
935            }
936        }
937    }
938
939    impl Bundle {
940        fn version(&self) -> String {
941            match self {
942                Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
943                Self::LocalPath { .. } => "<development>".to_string(),
944            }
945        }
946
947        fn path(&self) -> &Path {
948            match self {
949                Self::App { app_bundle, .. } => app_bundle,
950                Self::LocalPath { executable, .. } => executable,
951            }
952        }
953    }
954
955    pub(super) fn spawn_channel_cli(
956        channel: release_channel::ReleaseChannel,
957        leftover_args: Vec<String>,
958    ) -> Result<()> {
959        use anyhow::bail;
960
961        let app_id_prompt = format!("id of app \"{}\"", channel.display_name());
962        let app_id_output = Command::new("osascript")
963            .arg("-e")
964            .arg(&app_id_prompt)
965            .output()?;
966        if !app_id_output.status.success() {
967            bail!("Could not determine app id for {}", channel.display_name());
968        }
969        let app_name = String::from_utf8(app_id_output.stdout)?.trim().to_owned();
970        let app_path_prompt = format!("kMDItemCFBundleIdentifier == '{app_name}'");
971        let app_path_output = Command::new("mdfind").arg(app_path_prompt).output()?;
972        if !app_path_output.status.success() {
973            bail!(
974                "Could not determine app path for {}",
975                channel.display_name()
976            );
977        }
978        let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
979        let cli_path = format!("{app_path}/Contents/MacOS/cli");
980        Command::new(cli_path).args(leftover_args).spawn()?;
981        Ok(())
982    }
983}