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
 132/// Parses a path containing a position (e.g. `path:line:column`)
 133/// and returns its canonicalized string representation.
 134///
 135/// If a part of path doesn't exist, it will canonicalize the
 136/// existing part and append the non-existing part.
 137///
 138/// This method must return an absolute path, as many zed
 139/// crates assume absolute paths.
 140fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {
 141    match Path::new(argument_str).canonicalize() {
 142        Ok(existing_path) => Ok(PathWithPosition::from_path(existing_path)),
 143        Err(_) => PathWithPosition::parse_str(argument_str).map_path(|mut path| {
 144            let curdir = env::current_dir().context("retrieving current directory")?;
 145            let mut children = Vec::new();
 146            let root;
 147            loop {
 148                // canonicalize handles './', and '/'.
 149                if let Ok(canonicalized) = fs::canonicalize(&path) {
 150                    root = canonicalized;
 151                    break;
 152                }
 153                // The comparison to `curdir` is just a shortcut
 154                // since we know it is canonical. The other one
 155                // is if `argument_str` is a string that starts
 156                // with a name (e.g. "foo/bar").
 157                if path == curdir || path == Path::new("") {
 158                    root = curdir;
 159                    break;
 160                }
 161                children.push(
 162                    path.file_name()
 163                        .with_context(|| format!("parsing as path with position {argument_str}"))?
 164                        .to_owned(),
 165                );
 166                if !path.pop() {
 167                    unreachable!("parsing as path with position {argument_str}");
 168                }
 169            }
 170            Ok(children.iter().rev().fold(root, |mut path, child| {
 171                path.push(child);
 172                path
 173            }))
 174        }),
 175    }
 176    .map(|path_with_pos| path_with_pos.to_string(|path| path.to_string_lossy().into_owned()))
 177}
 178
 179#[cfg(test)]
 180mod tests {
 181    use super::*;
 182    use serde_json::json;
 183    use util::path;
 184    use util::paths::SanitizedPath;
 185    use util::test::TempTree;
 186
 187    macro_rules! assert_path_eq {
 188        ($left:expr, $right:expr) => {
 189            assert_eq!(
 190                SanitizedPath::new(Path::new(&$left)),
 191                SanitizedPath::new(Path::new(&$right))
 192            )
 193        };
 194    }
 195
 196    fn cwd() -> PathBuf {
 197        env::current_dir().unwrap()
 198    }
 199
 200    static CWD_LOCK: Mutex<()> = Mutex::new(());
 201
 202    fn with_cwd<T>(path: &Path, f: impl FnOnce() -> anyhow::Result<T>) -> anyhow::Result<T> {
 203        let _lock = CWD_LOCK.lock();
 204        let old_cwd = cwd();
 205        env::set_current_dir(path)?;
 206        let result = f();
 207        env::set_current_dir(old_cwd)?;
 208        result
 209    }
 210
 211    #[test]
 212    fn test_parse_non_existing_path() {
 213        // Absolute path
 214        let result = parse_path_with_position(path!("/non/existing/path.txt")).unwrap();
 215        assert_path_eq!(result, path!("/non/existing/path.txt"));
 216
 217        // Absolute path in cwd
 218        let path = cwd().join(path!("non/existing/path.txt"));
 219        let expected = path.to_string_lossy().to_string();
 220        let result = parse_path_with_position(&expected).unwrap();
 221        assert_path_eq!(result, expected);
 222
 223        // Relative path
 224        let result = parse_path_with_position(path!("non/existing/path.txt")).unwrap();
 225        assert_path_eq!(result, expected)
 226    }
 227
 228    #[test]
 229    fn test_parse_existing_path() {
 230        let temp_tree = TempTree::new(json!({
 231            "file.txt": "",
 232        }));
 233        let file_path = temp_tree.path().join("file.txt");
 234        let expected = file_path.to_string_lossy().to_string();
 235
 236        // Absolute path
 237        let result = parse_path_with_position(file_path.to_str().unwrap()).unwrap();
 238        assert_path_eq!(result, expected);
 239
 240        // Relative path
 241        let result = with_cwd(temp_tree.path(), || parse_path_with_position("file.txt")).unwrap();
 242        assert_path_eq!(result, expected);
 243    }
 244
 245    // NOTE:
 246    // While POSIX symbolic links are somewhat supported on Windows, they are an opt in by the user, and thus
 247    // we assume that they are not supported out of the box.
 248    #[cfg(not(windows))]
 249    #[test]
 250    fn test_parse_symlink_file() {
 251        let temp_tree = TempTree::new(json!({
 252            "target.txt": "",
 253        }));
 254        let target_path = temp_tree.path().join("target.txt");
 255        let symlink_path = temp_tree.path().join("symlink.txt");
 256        std::os::unix::fs::symlink(&target_path, &symlink_path).unwrap();
 257
 258        // Absolute path
 259        let result = parse_path_with_position(symlink_path.to_str().unwrap()).unwrap();
 260        assert_eq!(result, target_path.to_string_lossy());
 261
 262        // Relative path
 263        let result =
 264            with_cwd(temp_tree.path(), || parse_path_with_position("symlink.txt")).unwrap();
 265        assert_eq!(result, target_path.to_string_lossy());
 266    }
 267
 268    #[cfg(not(windows))]
 269    #[test]
 270    fn test_parse_symlink_dir() {
 271        let temp_tree = TempTree::new(json!({
 272            "some": {
 273                "dir": { // symlink target
 274                    "ec": {
 275                        "tory": {
 276                            "file.txt": "",
 277        }}}}}));
 278
 279        let target_file_path = temp_tree.path().join("some/dir/ec/tory/file.txt");
 280        let expected = target_file_path.to_string_lossy();
 281
 282        let dir_path = temp_tree.path().join("some/dir");
 283        let symlink_path = temp_tree.path().join("symlink");
 284        std::os::unix::fs::symlink(&dir_path, &symlink_path).unwrap();
 285
 286        // Absolute path
 287        let result =
 288            parse_path_with_position(symlink_path.join("ec/tory/file.txt").to_str().unwrap())
 289                .unwrap();
 290        assert_eq!(result, expected);
 291
 292        // Relative path
 293        let result = with_cwd(temp_tree.path(), || {
 294            parse_path_with_position("symlink/ec/tory/file.txt")
 295        })
 296        .unwrap();
 297        assert_eq!(result, expected);
 298    }
 299}
 300
 301fn parse_path_in_wsl(source: &str, wsl: &str) -> Result<String> {
 302    let mut source = PathWithPosition::parse_str(source);
 303    let mut command = util::command::new_std_command("wsl.exe");
 304
 305    let (user, distro_name) = if let Some((user, distro)) = wsl.split_once('@') {
 306        if user.is_empty() {
 307            anyhow::bail!("user is empty in wsl argument");
 308        }
 309        (Some(user), distro)
 310    } else {
 311        (None, wsl)
 312    };
 313
 314    if let Some(user) = user {
 315        command.arg("--user").arg(user);
 316    }
 317
 318    let output = command
 319        .arg("--distribution")
 320        .arg(distro_name)
 321        .arg("--exec")
 322        .arg("realpath")
 323        .arg("-s")
 324        .arg(&source.path)
 325        .output()?;
 326
 327    let result = String::from_utf8_lossy(&output.stdout);
 328    source.path = Path::new(result.trim()).to_owned();
 329
 330    Ok(source.to_string(|path| path.to_string_lossy().into_owned()))
 331}
 332
 333fn main() -> Result<()> {
 334    #[cfg(unix)]
 335    util::prevent_root_execution();
 336
 337    // Exit flatpak sandbox if needed
 338    #[cfg(target_os = "linux")]
 339    {
 340        flatpak::try_restart_to_host();
 341        flatpak::ld_extra_libs();
 342    }
 343
 344    // Intercept version designators
 345    #[cfg(target_os = "macos")]
 346    if let Some(channel) = std::env::args().nth(1).filter(|arg| arg.starts_with("--")) {
 347        // 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.
 348        use std::str::FromStr as _;
 349
 350        if let Ok(channel) = release_channel::ReleaseChannel::from_str(&channel[2..]) {
 351            return mac_os::spawn_channel_cli(channel, std::env::args().skip(2).collect());
 352        }
 353    }
 354    let args = Args::parse();
 355
 356    // `zed --askpass` Makes zed operate in nc/netcat mode for use with askpass
 357    if let Some(socket) = &args.askpass {
 358        askpass::main(socket);
 359        return Ok(());
 360    }
 361
 362    // Set custom data directory before any path operations
 363    let user_data_dir = args.user_data_dir.clone();
 364    if let Some(dir) = &user_data_dir {
 365        paths::set_custom_data_dir(dir);
 366    }
 367
 368    #[cfg(target_os = "linux")]
 369    let args = flatpak::set_bin_if_no_escape(args);
 370
 371    let app = Detect::detect(args.zed.as_deref()).context("Bundle detection")?;
 372
 373    if args.version {
 374        println!("{}", app.zed_version_string());
 375        return Ok(());
 376    }
 377
 378    if args.system_specs {
 379        let path = app.path();
 380        let msg = [
 381            "The `--system-specs` argument is not supported in the Zed CLI, only on Zed binary.",
 382            "To retrieve the system specs on the command line, run the following command:",
 383            &format!("{} --system-specs", path.display()),
 384        ];
 385        anyhow::bail!(msg.join("\n"));
 386    }
 387
 388    #[cfg(all(
 389        any(target_os = "linux", target_os = "macos"),
 390        not(feature = "no-bundled-uninstall")
 391    ))]
 392    if args.uninstall {
 393        static UNINSTALL_SCRIPT: &[u8] = include_bytes!("../../../script/uninstall.sh");
 394
 395        let tmp_dir = tempfile::tempdir()?;
 396        let script_path = tmp_dir.path().join("uninstall.sh");
 397        fs::write(&script_path, UNINSTALL_SCRIPT)?;
 398
 399        use std::os::unix::fs::PermissionsExt as _;
 400        fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755))?;
 401
 402        let status = std::process::Command::new("sh")
 403            .arg(&script_path)
 404            .env("ZED_CHANNEL", &*release_channel::RELEASE_CHANNEL_NAME)
 405            .status()
 406            .context("Failed to execute uninstall script")?;
 407
 408        std::process::exit(status.code().unwrap_or(1));
 409    }
 410
 411    let (server, server_name) =
 412        IpcOneShotServer::<IpcHandshake>::new().context("Handshake before Zed spawn")?;
 413    let url = format!("zed-cli://{server_name}");
 414
 415    let open_new_workspace = if args.new {
 416        Some(true)
 417    } else if args.add {
 418        Some(false)
 419    } else {
 420        None
 421    };
 422
 423    let env = {
 424        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 425        {
 426            use collections::HashMap;
 427
 428            // On Linux, the desktop entry uses `cli` to spawn `zed`.
 429            // We need to handle env vars correctly since std::env::vars() may not contain
 430            // project-specific vars (e.g. those set by direnv).
 431            // By setting env to None here, the LSP will use worktree env vars instead,
 432            // which is what we want.
 433            if !std::io::stdout().is_terminal() {
 434                None
 435            } else {
 436                Some(std::env::vars().collect::<HashMap<_, _>>())
 437            }
 438        }
 439
 440        #[cfg(target_os = "windows")]
 441        {
 442            // On Windows, by default, a child process inherits a copy of the environment block of the parent process.
 443            // So we don't need to pass env vars explicitly.
 444            None
 445        }
 446
 447        #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
 448        {
 449            use collections::HashMap;
 450
 451            Some(std::env::vars().collect::<HashMap<_, _>>())
 452        }
 453    };
 454
 455    let exit_status = Arc::new(Mutex::new(None));
 456    let mut paths = vec![];
 457    let mut urls = vec![];
 458    let mut diff_paths = vec![];
 459    let mut stdin_tmp_file: Option<fs::File> = None;
 460    let mut anonymous_fd_tmp_files = vec![];
 461
 462    for path in args.diff.chunks(2) {
 463        diff_paths.push([
 464            parse_path_with_position(&path[0])?,
 465            parse_path_with_position(&path[1])?,
 466        ]);
 467    }
 468
 469    #[cfg(target_os = "windows")]
 470    let wsl = args.wsl.as_ref();
 471    #[cfg(not(target_os = "windows"))]
 472    let wsl = None;
 473
 474    for path in args.paths_with_position.iter() {
 475        if URL_PREFIX.iter().any(|&prefix| path.starts_with(prefix)) {
 476            urls.push(path.to_string());
 477        } else if path == "-" && args.paths_with_position.len() == 1 {
 478            let file = NamedTempFile::new()?;
 479            paths.push(file.path().to_string_lossy().into_owned());
 480            let (file, _) = file.keep()?;
 481            stdin_tmp_file = Some(file);
 482        } else if let Some(file) = anonymous_fd(path) {
 483            let tmp_file = NamedTempFile::new()?;
 484            paths.push(tmp_file.path().to_string_lossy().into_owned());
 485            let (tmp_file, _) = tmp_file.keep()?;
 486            anonymous_fd_tmp_files.push((file, tmp_file));
 487        } else if let Some(wsl) = wsl {
 488            urls.push(format!("file://{}", parse_path_in_wsl(path, wsl)?));
 489        } else {
 490            paths.push(parse_path_with_position(path)?);
 491        }
 492    }
 493
 494    anyhow::ensure!(
 495        args.dev_server_token.is_none(),
 496        "Dev servers were removed in v0.157.x please upgrade to SSH remoting: https://zed.dev/docs/remote-development"
 497    );
 498
 499    rayon::ThreadPoolBuilder::new()
 500        .num_threads(4)
 501        .stack_size(10 * 1024 * 1024)
 502        .thread_name(|ix| format!("RayonWorker{}", ix))
 503        .build_global()
 504        .unwrap();
 505
 506    let sender: JoinHandle<anyhow::Result<()>> = thread::Builder::new()
 507        .name("CliReceiver".to_string())
 508        .spawn({
 509            let exit_status = exit_status.clone();
 510            let user_data_dir_for_thread = user_data_dir.clone();
 511            move || {
 512                let (_, handshake) = server.accept().context("Handshake after Zed spawn")?;
 513                let (tx, rx) = (handshake.requests, handshake.responses);
 514
 515                #[cfg(target_os = "windows")]
 516                let wsl = args.wsl;
 517                #[cfg(not(target_os = "windows"))]
 518                let wsl = None;
 519
 520                tx.send(CliRequest::Open {
 521                    paths,
 522                    urls,
 523                    diff_paths,
 524                    wsl,
 525                    wait: args.wait,
 526                    open_new_workspace,
 527                    reuse: args.reuse,
 528                    env,
 529                    user_data_dir: user_data_dir_for_thread,
 530                })?;
 531
 532                while let Ok(response) = rx.recv() {
 533                    match response {
 534                        CliResponse::Ping => {}
 535                        CliResponse::Stdout { message } => println!("{message}"),
 536                        CliResponse::Stderr { message } => eprintln!("{message}"),
 537                        CliResponse::Exit { status } => {
 538                            exit_status.lock().replace(status);
 539                            return Ok(());
 540                        }
 541                    }
 542                }
 543
 544                Ok(())
 545            }
 546        })
 547        .unwrap();
 548
 549    let stdin_pipe_handle: Option<JoinHandle<anyhow::Result<()>>> =
 550        stdin_tmp_file.map(|mut tmp_file| {
 551            thread::Builder::new()
 552                .name("CliStdin".to_string())
 553                .spawn(move || {
 554                    let mut stdin = std::io::stdin().lock();
 555                    if !io::IsTerminal::is_terminal(&stdin) {
 556                        io::copy(&mut stdin, &mut tmp_file)?;
 557                    }
 558                    Ok(())
 559                })
 560                .unwrap()
 561        });
 562
 563    let anonymous_fd_pipe_handles: Vec<_> = anonymous_fd_tmp_files
 564        .into_iter()
 565        .map(|(mut file, mut tmp_file)| {
 566            thread::Builder::new()
 567                .name("CliAnonymousFd".to_string())
 568                .spawn(move || io::copy(&mut file, &mut tmp_file))
 569                .unwrap()
 570        })
 571        .collect();
 572
 573    if args.foreground {
 574        app.run_foreground(url, user_data_dir.as_deref())?;
 575    } else {
 576        app.launch(url)?;
 577        sender.join().unwrap()?;
 578        if let Some(handle) = stdin_pipe_handle {
 579            handle.join().unwrap()?;
 580        }
 581        for handle in anonymous_fd_pipe_handles {
 582            handle.join().unwrap()?;
 583        }
 584    }
 585
 586    if let Some(exit_status) = exit_status.lock().take() {
 587        std::process::exit(exit_status);
 588    }
 589    Ok(())
 590}
 591
 592fn anonymous_fd(path: &str) -> Option<fs::File> {
 593    #[cfg(target_os = "linux")]
 594    {
 595        use std::os::fd::{self, FromRawFd};
 596
 597        let fd_str = path.strip_prefix("/proc/self/fd/")?;
 598
 599        let link = fs::read_link(path).ok()?;
 600        if !link.starts_with("memfd:") {
 601            return None;
 602        }
 603
 604        let fd: fd::RawFd = fd_str.parse().ok()?;
 605        let file = unsafe { fs::File::from_raw_fd(fd) };
 606        Some(file)
 607    }
 608    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
 609    {
 610        use std::os::{
 611            fd::{self, FromRawFd},
 612            unix::fs::FileTypeExt,
 613        };
 614
 615        let fd_str = path.strip_prefix("/dev/fd/")?;
 616
 617        let metadata = fs::metadata(path).ok()?;
 618        let file_type = metadata.file_type();
 619        if !file_type.is_fifo() && !file_type.is_socket() {
 620            return None;
 621        }
 622        let fd: fd::RawFd = fd_str.parse().ok()?;
 623        let file = unsafe { fs::File::from_raw_fd(fd) };
 624        Some(file)
 625    }
 626    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
 627    {
 628        _ = path;
 629        // not implemented for bsd, windows. Could be, but isn't yet
 630        None
 631    }
 632}
 633
 634#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 635mod linux {
 636    use std::{
 637        env,
 638        ffi::OsString,
 639        io,
 640        os::unix::net::{SocketAddr, UnixDatagram},
 641        path::{Path, PathBuf},
 642        process::{self, ExitStatus},
 643        thread,
 644        time::Duration,
 645    };
 646
 647    use anyhow::{Context as _, anyhow};
 648    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
 649    use fork::Fork;
 650
 651    use crate::{Detect, InstalledApp};
 652
 653    struct App(PathBuf);
 654
 655    impl Detect {
 656        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
 657            let path = if let Some(path) = path {
 658                path.to_path_buf().canonicalize()?
 659            } else {
 660                let cli = env::current_exe()?;
 661                let dir = cli.parent().context("no parent path for cli")?;
 662
 663                // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
 664                // ./zed is for the target directory in development builds.
 665                let possible_locations =
 666                    ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
 667                possible_locations
 668                    .iter()
 669                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
 670                    .with_context(|| {
 671                        format!("could not find any of: {}", possible_locations.join(", "))
 672                    })?
 673            };
 674
 675            Ok(App(path))
 676        }
 677    }
 678
 679    impl InstalledApp for App {
 680        fn zed_version_string(&self) -> String {
 681            format!(
 682                "Zed {}{}{}{}",
 683                if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
 684                    "".to_string()
 685                } else {
 686                    format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
 687                },
 688                option_env!("RELEASE_VERSION").unwrap_or_default(),
 689                match option_env!("ZED_COMMIT_SHA") {
 690                    Some(commit_sha) => format!(" {commit_sha} "),
 691                    None => "".to_string(),
 692                },
 693                self.0.display(),
 694            )
 695        }
 696
 697        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
 698            let sock_path = paths::data_dir().join(format!(
 699                "zed-{}.sock",
 700                *release_channel::RELEASE_CHANNEL_NAME
 701            ));
 702            let sock = UnixDatagram::unbound()?;
 703            if sock.connect(&sock_path).is_err() {
 704                self.boot_background(ipc_url)?;
 705            } else {
 706                sock.send(ipc_url.as_bytes())?;
 707            }
 708            Ok(())
 709        }
 710
 711        fn run_foreground(
 712            &self,
 713            ipc_url: String,
 714            user_data_dir: Option<&str>,
 715        ) -> io::Result<ExitStatus> {
 716            let mut cmd = std::process::Command::new(self.0.clone());
 717            cmd.arg(ipc_url);
 718            if let Some(dir) = user_data_dir {
 719                cmd.arg("--user-data-dir").arg(dir);
 720            }
 721            cmd.status()
 722        }
 723
 724        fn path(&self) -> PathBuf {
 725            self.0.clone()
 726        }
 727    }
 728
 729    impl App {
 730        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
 731            let path = &self.0;
 732
 733            match fork::fork() {
 734                Ok(Fork::Parent(_)) => Ok(()),
 735                Ok(Fork::Child) => {
 736                    unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
 737                    if fork::setsid().is_err() {
 738                        eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
 739                        process::exit(1);
 740                    }
 741                    if fork::close_fd().is_err() {
 742                        eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
 743                    }
 744                    let error =
 745                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
 746                    // if exec succeeded, we never get here.
 747                    eprintln!("failed to exec {:?}: {}", path, error);
 748                    process::exit(1)
 749                }
 750                Err(_) => Err(anyhow!(io::Error::last_os_error())),
 751            }
 752        }
 753
 754        fn wait_for_socket(
 755            &self,
 756            sock_addr: &SocketAddr,
 757            sock: &mut UnixDatagram,
 758        ) -> Result<(), std::io::Error> {
 759            for _ in 0..100 {
 760                thread::sleep(Duration::from_millis(10));
 761                if sock.connect_addr(sock_addr).is_ok() {
 762                    return Ok(());
 763                }
 764            }
 765            sock.connect_addr(sock_addr)
 766        }
 767    }
 768}
 769
 770#[cfg(target_os = "linux")]
 771mod flatpak {
 772    use std::ffi::OsString;
 773    use std::path::PathBuf;
 774    use std::process::Command;
 775    use std::{env, process};
 776
 777    const EXTRA_LIB_ENV_NAME: &str = "ZED_FLATPAK_LIB_PATH";
 778    const NO_ESCAPE_ENV_NAME: &str = "ZED_FLATPAK_NO_ESCAPE";
 779
 780    /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
 781    pub fn ld_extra_libs() {
 782        let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
 783            env::split_paths(&paths).collect()
 784        } else {
 785            Vec::new()
 786        };
 787
 788        if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
 789            paths.push(extra_path.into());
 790        }
 791
 792        unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
 793    }
 794
 795    /// Restarts outside of the sandbox if currently running within it
 796    pub fn try_restart_to_host() {
 797        if let Some(flatpak_dir) = get_flatpak_dir() {
 798            let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
 799            args.append(&mut get_xdg_env_args());
 800            args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
 801            args.push(
 802                format!(
 803                    "--env={EXTRA_LIB_ENV_NAME}={}",
 804                    flatpak_dir.join("lib").to_str().unwrap()
 805                )
 806                .into(),
 807            );
 808            args.push(flatpak_dir.join("bin").join("zed").into());
 809
 810            let mut is_app_location_set = false;
 811            for arg in &env::args_os().collect::<Vec<_>>()[1..] {
 812                args.push(arg.clone());
 813                is_app_location_set |= arg == "--zed";
 814            }
 815
 816            if !is_app_location_set {
 817                args.push("--zed".into());
 818                args.push(flatpak_dir.join("libexec").join("zed-editor").into());
 819            }
 820
 821            let error = exec::execvp("/usr/bin/flatpak-spawn", args);
 822            eprintln!("failed restart cli on host: {:?}", error);
 823            process::exit(1);
 824        }
 825    }
 826
 827    pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
 828        if env::var(NO_ESCAPE_ENV_NAME).is_ok()
 829            && env::var("FLATPAK_ID").is_ok_and(|id| id.starts_with("dev.zed.Zed"))
 830            && args.zed.is_none()
 831        {
 832            args.zed = Some("/app/libexec/zed-editor".into());
 833            unsafe { env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed") };
 834        }
 835        args
 836    }
 837
 838    fn get_flatpak_dir() -> Option<PathBuf> {
 839        if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
 840            return None;
 841        }
 842
 843        if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
 844            if !flatpak_id.starts_with("dev.zed.Zed") {
 845                return None;
 846            }
 847
 848            let install_dir = Command::new("/usr/bin/flatpak-spawn")
 849                .arg("--host")
 850                .arg("flatpak")
 851                .arg("info")
 852                .arg("--show-location")
 853                .arg(flatpak_id)
 854                .output()
 855                .unwrap();
 856            let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
 857            Some(install_dir.join("files"))
 858        } else {
 859            None
 860        }
 861    }
 862
 863    fn get_xdg_env_args() -> Vec<OsString> {
 864        let xdg_keys = [
 865            "XDG_DATA_HOME",
 866            "XDG_CONFIG_HOME",
 867            "XDG_CACHE_HOME",
 868            "XDG_STATE_HOME",
 869        ];
 870        env::vars()
 871            .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
 872            .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
 873            .collect()
 874    }
 875}
 876
 877#[cfg(target_os = "windows")]
 878mod windows {
 879    use anyhow::Context;
 880    use release_channel::app_identifier;
 881    use windows::{
 882        Win32::{
 883            Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
 884            Storage::FileSystem::{
 885                CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
 886            },
 887            System::Threading::CreateMutexW,
 888        },
 889        core::HSTRING,
 890    };
 891
 892    use crate::{Detect, InstalledApp};
 893    use std::io;
 894    use std::path::{Path, PathBuf};
 895    use std::process::ExitStatus;
 896
 897    fn check_single_instance() -> bool {
 898        let mutex = unsafe {
 899            CreateMutexW(
 900                None,
 901                false,
 902                &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
 903            )
 904            .expect("Unable to create instance sync event")
 905        };
 906        let last_err = unsafe { GetLastError() };
 907        let _ = unsafe { CloseHandle(mutex) };
 908        last_err != ERROR_ALREADY_EXISTS
 909    }
 910
 911    struct App(PathBuf);
 912
 913    impl InstalledApp for App {
 914        fn zed_version_string(&self) -> String {
 915            format!(
 916                "Zed {}{}{}{}",
 917                if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
 918                    "".to_string()
 919                } else {
 920                    format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
 921                },
 922                option_env!("RELEASE_VERSION").unwrap_or_default(),
 923                match option_env!("ZED_COMMIT_SHA") {
 924                    Some(commit_sha) => format!(" {commit_sha} "),
 925                    None => "".to_string(),
 926                },
 927                self.0.display(),
 928            )
 929        }
 930
 931        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
 932            if check_single_instance() {
 933                std::process::Command::new(self.0.clone())
 934                    .arg(ipc_url)
 935                    .spawn()?;
 936            } else {
 937                unsafe {
 938                    let pipe = CreateFileW(
 939                        &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
 940                        GENERIC_WRITE.0,
 941                        FILE_SHARE_MODE::default(),
 942                        None,
 943                        OPEN_EXISTING,
 944                        FILE_FLAGS_AND_ATTRIBUTES::default(),
 945                        None,
 946                    )?;
 947                    let message = ipc_url.as_bytes();
 948                    let mut bytes_written = 0;
 949                    WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
 950                    CloseHandle(pipe)?;
 951                }
 952            }
 953            Ok(())
 954        }
 955
 956        fn run_foreground(
 957            &self,
 958            ipc_url: String,
 959            user_data_dir: Option<&str>,
 960        ) -> io::Result<ExitStatus> {
 961            let mut cmd = std::process::Command::new(self.0.clone());
 962            cmd.arg(ipc_url).arg("--foreground");
 963            if let Some(dir) = user_data_dir {
 964                cmd.arg("--user-data-dir").arg(dir);
 965            }
 966            cmd.spawn()?.wait()
 967        }
 968
 969        fn path(&self) -> PathBuf {
 970            self.0.clone()
 971        }
 972    }
 973
 974    impl Detect {
 975        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
 976            let path = if let Some(path) = path {
 977                path.to_path_buf().canonicalize()?
 978            } else {
 979                let cli = std::env::current_exe()?;
 980                let dir = cli.parent().context("no parent path for cli")?;
 981
 982                // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
 983                // directory in development builds.
 984                let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
 985                possible_locations
 986                    .iter()
 987                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
 988                    .context(format!(
 989                        "could not find any of: {}",
 990                        possible_locations.join(", ")
 991                    ))?
 992            };
 993
 994            Ok(App(path))
 995        }
 996    }
 997}
 998
 999#[cfg(target_os = "macos")]
1000mod mac_os {
1001    use anyhow::{Context as _, Result};
1002    use core_foundation::{
1003        array::{CFArray, CFIndex},
1004        base::TCFType as _,
1005        string::kCFStringEncodingUTF8,
1006        url::{CFURL, CFURLCreateWithBytes},
1007    };
1008    use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
1009    use serde::Deserialize;
1010    use std::{
1011        ffi::OsStr,
1012        fs, io,
1013        path::{Path, PathBuf},
1014        process::{Command, ExitStatus},
1015        ptr,
1016    };
1017
1018    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
1019
1020    use crate::{Detect, InstalledApp};
1021
1022    #[derive(Debug, Deserialize)]
1023    struct InfoPlist {
1024        #[serde(rename = "CFBundleShortVersionString")]
1025        bundle_short_version_string: String,
1026    }
1027
1028    enum Bundle {
1029        App {
1030            app_bundle: PathBuf,
1031            plist: InfoPlist,
1032        },
1033        LocalPath {
1034            executable: PathBuf,
1035        },
1036    }
1037
1038    fn locate_bundle() -> Result<PathBuf> {
1039        let cli_path = std::env::current_exe()?.canonicalize()?;
1040        let mut app_path = cli_path.clone();
1041        while app_path.extension() != Some(OsStr::new("app")) {
1042            anyhow::ensure!(
1043                app_path.pop(),
1044                "cannot find app bundle containing {cli_path:?}"
1045            );
1046        }
1047        Ok(app_path)
1048    }
1049
1050    impl Detect {
1051        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
1052            let bundle_path = if let Some(bundle_path) = path {
1053                bundle_path
1054                    .canonicalize()
1055                    .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
1056            } else {
1057                locate_bundle().context("bundle autodiscovery")?
1058            };
1059
1060            match bundle_path.extension().and_then(|ext| ext.to_str()) {
1061                Some("app") => {
1062                    let plist_path = bundle_path.join("Contents/Info.plist");
1063                    let plist =
1064                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
1065                            format!("Reading *.app bundle plist file at {plist_path:?}")
1066                        })?;
1067                    Ok(Bundle::App {
1068                        app_bundle: bundle_path,
1069                        plist,
1070                    })
1071                }
1072                _ => Ok(Bundle::LocalPath {
1073                    executable: bundle_path,
1074                }),
1075            }
1076        }
1077    }
1078
1079    impl InstalledApp for Bundle {
1080        fn zed_version_string(&self) -> String {
1081            format!("Zed {}{}", self.version(), self.path().display(),)
1082        }
1083
1084        fn launch(&self, url: String) -> anyhow::Result<()> {
1085            match self {
1086                Self::App { app_bundle, .. } => {
1087                    let app_path = app_bundle;
1088
1089                    let status = unsafe {
1090                        let app_url = CFURL::from_path(app_path, true)
1091                            .with_context(|| format!("invalid app path {app_path:?}"))?;
1092                        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
1093                            ptr::null(),
1094                            url.as_ptr(),
1095                            url.len() as CFIndex,
1096                            kCFStringEncodingUTF8,
1097                            ptr::null(),
1098                        ));
1099                        // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
1100                        let urls_to_open =
1101                            CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
1102                        LSOpenFromURLSpec(
1103                            &LSLaunchURLSpec {
1104                                appURL: app_url.as_concrete_TypeRef(),
1105                                itemURLs: urls_to_open.as_concrete_TypeRef(),
1106                                passThruParams: ptr::null(),
1107                                launchFlags: kLSLaunchDefaults,
1108                                asyncRefCon: ptr::null_mut(),
1109                            },
1110                            ptr::null_mut(),
1111                        )
1112                    };
1113
1114                    anyhow::ensure!(
1115                        status == 0,
1116                        "cannot start app bundle {}",
1117                        self.zed_version_string()
1118                    );
1119                }
1120
1121                Self::LocalPath { executable, .. } => {
1122                    let executable_parent = executable
1123                        .parent()
1124                        .with_context(|| format!("Executable {executable:?} path has no parent"))?;
1125                    let subprocess_stdout_file = fs::File::create(
1126                        executable_parent.join("zed_dev.log"),
1127                    )
1128                    .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
1129                    let subprocess_stdin_file =
1130                        subprocess_stdout_file.try_clone().with_context(|| {
1131                            format!("Cloning descriptor for file {subprocess_stdout_file:?}")
1132                        })?;
1133                    let mut command = std::process::Command::new(executable);
1134                    let command = command
1135                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
1136                        .stderr(subprocess_stdout_file)
1137                        .stdout(subprocess_stdin_file)
1138                        .arg(url);
1139
1140                    command
1141                        .spawn()
1142                        .with_context(|| format!("Spawning {command:?}"))?;
1143                }
1144            }
1145
1146            Ok(())
1147        }
1148
1149        fn run_foreground(
1150            &self,
1151            ipc_url: String,
1152            user_data_dir: Option<&str>,
1153        ) -> io::Result<ExitStatus> {
1154            let path = match self {
1155                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
1156                Bundle::LocalPath { executable, .. } => executable.clone(),
1157            };
1158
1159            let mut cmd = std::process::Command::new(path);
1160            cmd.arg(ipc_url);
1161            if let Some(dir) = user_data_dir {
1162                cmd.arg("--user-data-dir").arg(dir);
1163            }
1164            cmd.status()
1165        }
1166
1167        fn path(&self) -> PathBuf {
1168            match self {
1169                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
1170                Bundle::LocalPath { executable, .. } => executable.clone(),
1171            }
1172        }
1173    }
1174
1175    impl Bundle {
1176        fn version(&self) -> String {
1177            match self {
1178                Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
1179                Self::LocalPath { .. } => "<development>".to_string(),
1180            }
1181        }
1182
1183        fn path(&self) -> &Path {
1184            match self {
1185                Self::App { app_bundle, .. } => app_bundle,
1186                Self::LocalPath { executable, .. } => executable,
1187            }
1188        }
1189    }
1190
1191    pub(super) fn spawn_channel_cli(
1192        channel: release_channel::ReleaseChannel,
1193        leftover_args: Vec<String>,
1194    ) -> Result<()> {
1195        use anyhow::bail;
1196
1197        let app_path_prompt = format!(
1198            "POSIX path of (path to application \"{}\")",
1199            channel.display_name()
1200        );
1201        let app_path_output = Command::new("osascript")
1202            .arg("-e")
1203            .arg(&app_path_prompt)
1204            .output()?;
1205        if !app_path_output.status.success() {
1206            bail!(
1207                "Could not determine app path for {}",
1208                channel.display_name()
1209            );
1210        }
1211        let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
1212        let cli_path = format!("{app_path}/Contents/MacOS/cli");
1213        Command::new(cli_path).args(leftover_args).spawn()?;
1214        Ok(())
1215    }
1216}