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