main.rs

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