1use super::register_zed_scheme;
  2use anyhow::{Context as _, Result};
  3use gpui::{AppContext as _, AsyncApp, Context, PromptLevel, Window, actions};
  4use release_channel::ReleaseChannel;
  5use std::ops::Deref;
  6use std::path::{Path, PathBuf};
  7use util::ResultExt;
  8use workspace::notifications::{DetachAndPromptErr, NotificationId};
  9use workspace::{Toast, Workspace};
 10
 11actions!(
 12    cli,
 13    [
 14        /// Installs the Zed CLI tool to the system PATH.
 15        InstallCliBinary,
 16    ]
 17);
 18
 19async fn install_script(cx: &AsyncApp) -> Result<PathBuf> {
 20    let cli_path = cx.update(|cx| cx.path_for_auxiliary_executable("cli"))??;
 21    let link_path = Path::new("/usr/local/bin/zed");
 22    let bin_dir_path = link_path.parent().unwrap();
 23
 24    // Don't re-create symlink if it points to the same CLI binary.
 25    if smol::fs::read_link(link_path).await.ok().as_ref() == Some(&cli_path) {
 26        return Ok(link_path.into());
 27    }
 28
 29    // If the symlink is not there or is outdated, first try replacing it
 30    // without escalating.
 31    smol::fs::remove_file(link_path).await.log_err();
 32    if smol::fs::unix::symlink(&cli_path, link_path)
 33        .await
 34        .log_err()
 35        .is_some()
 36    {
 37        return Ok(link_path.into());
 38    }
 39
 40    // The symlink could not be created, so use osascript with admin privileges
 41    // to create it.
 42    let status = smol::process::Command::new("/usr/bin/osascript")
 43        .args([
 44            "-e",
 45            &format!(
 46                "do shell script \" \
 47                    mkdir -p \'{}\' && \
 48                    ln -sf \'{}\' \'{}\' \
 49                \" with administrator privileges",
 50                bin_dir_path.to_string_lossy(),
 51                cli_path.to_string_lossy(),
 52                link_path.to_string_lossy(),
 53            ),
 54        ])
 55        .stdout(smol::process::Stdio::inherit())
 56        .stderr(smol::process::Stdio::inherit())
 57        .output()
 58        .await?
 59        .status;
 60    anyhow::ensure!(status.success(), "error running osascript");
 61    Ok(link_path.into())
 62}
 63
 64pub fn install_cli_binary(window: &mut Window, cx: &mut Context<Workspace>) {
 65    const LINUX_PROMPT_DETAIL: &str = "If you installed Zed from our official release add ~/.local/bin to your PATH.\n\nIf you installed Zed from a different source like your package manager, then you may need to create an alias/symlink manually.\n\nDepending on your package manager, the CLI might be named zeditor, zedit, zed-editor or something else.";
 66
 67    cx.spawn_in(window, async move |workspace, cx| {
 68        if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 69            let prompt = cx.prompt(
 70                PromptLevel::Warning,
 71                "CLI should already be installed",
 72                Some(LINUX_PROMPT_DETAIL),
 73                &["Ok"],
 74            );
 75            cx.background_spawn(prompt).detach();
 76            return Ok(());
 77        }
 78        let path = install_script(cx.deref())
 79            .await
 80            .context("error creating CLI symlink")?;
 81
 82        workspace.update_in(cx, |workspace, _, cx| {
 83            struct InstalledZedCli;
 84
 85            workspace.show_toast(
 86                Toast::new(
 87                    NotificationId::unique::<InstalledZedCli>(),
 88                    format!(
 89                        "Installed `zed` to {}. You can launch {} from your terminal.",
 90                        path.to_string_lossy(),
 91                        ReleaseChannel::global(cx).display_name()
 92                    ),
 93                ),
 94                cx,
 95            )
 96        })?;
 97        register_zed_scheme(cx).await.log_err();
 98        Ok(())
 99    })
100    .detach_and_prompt_err("Error installing zed cli", window, cx, |_, _, _| None);
101}