install_cli.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use client::ZED_URL_SCHEME;
  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!(cli, [Install, RegisterZedScheme]);
 12
 13async fn install_script(cx: &AsyncApp) -> Result<PathBuf> {
 14    let cli_path = cx.update(|cx| cx.path_for_auxiliary_executable("cli"))??;
 15    let link_path = Path::new("/usr/local/bin/zed");
 16    let bin_dir_path = link_path.parent().unwrap();
 17
 18    // Don't re-create symlink if it points to the same CLI binary.
 19    if smol::fs::read_link(link_path).await.ok().as_ref() == Some(&cli_path) {
 20        return Ok(link_path.into());
 21    }
 22
 23    // If the symlink is not there or is outdated, first try replacing it
 24    // without escalating.
 25    smol::fs::remove_file(link_path).await.log_err();
 26    // todo("windows")
 27    #[cfg(not(windows))]
 28    {
 29        if smol::fs::unix::symlink(&cli_path, link_path)
 30            .await
 31            .log_err()
 32            .is_some()
 33        {
 34            return Ok(link_path.into());
 35        }
 36    }
 37
 38    // The symlink could not be created, so use osascript with admin privileges
 39    // to create it.
 40    let status = smol::process::Command::new("/usr/bin/osascript")
 41        .args([
 42            "-e",
 43            &format!(
 44                "do shell script \" \
 45                    mkdir -p \'{}\' && \
 46                    ln -sf \'{}\' \'{}\' \
 47                \" with administrator privileges",
 48                bin_dir_path.to_string_lossy(),
 49                cli_path.to_string_lossy(),
 50                link_path.to_string_lossy(),
 51            ),
 52        ])
 53        .stdout(smol::process::Stdio::inherit())
 54        .stderr(smol::process::Stdio::inherit())
 55        .output()
 56        .await?
 57        .status;
 58    if status.success() {
 59        Ok(link_path.into())
 60    } else {
 61        Err(anyhow!("error running osascript"))
 62    }
 63}
 64
 65pub async fn register_zed_scheme(cx: &AsyncApp) -> anyhow::Result<()> {
 66    cx.update(|cx| cx.register_url_scheme(ZED_URL_SCHEME))?
 67        .await
 68}
 69
 70pub fn install_cli(window: &mut Window, cx: &mut Context<Workspace>) {
 71    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.";
 72
 73    cx.spawn_in(window, async move |workspace, cx| {
 74        if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 75            let prompt = cx.prompt(
 76                PromptLevel::Warning,
 77                "CLI should already be installed",
 78                Some(LINUX_PROMPT_DETAIL),
 79                &["Ok"],
 80            );
 81            cx.background_spawn(prompt).detach();
 82            return Ok(());
 83        }
 84        let path = install_script(cx.deref())
 85            .await
 86            .context("error creating CLI symlink")?;
 87
 88        workspace.update_in(cx, |workspace, _, cx| {
 89            struct InstalledZedCli;
 90
 91            workspace.show_toast(
 92                Toast::new(
 93                    NotificationId::unique::<InstalledZedCli>(),
 94                    format!(
 95                        "Installed `zed` to {}. You can launch {} from your terminal.",
 96                        path.to_string_lossy(),
 97                        ReleaseChannel::global(cx).display_name()
 98                    ),
 99                ),
100                cx,
101            )
102        })?;
103        register_zed_scheme(&cx).await.log_err();
104        Ok(())
105    })
106    .detach_and_prompt_err("Error installing zed cli", window, cx, |_, _, _| None);
107}