Extract Zig support into an extension (#9893)

This PR extracts Zig support into an extension and removes the built-in
Zig support from Zed.

There's a small workaround necessary in order for us to set the file
permissions on the `zls` binary so that it can be run. Eventually we'll
want to build this into the extension API, but for now we're just
hard-coding it on the host side.

Release Notes:

- Removed built-in support for Zig, in favor of making it available as
an extension. The Zig extension will be suggested for download when you
open a `.zig` file.
This commit is contained in:
Marshall Bowers 2024-03-27 20:56:30 -04:00 committed by GitHub
parent 9bce5e8b82
commit ff685b299d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 170 additions and 158 deletions

17
Cargo.lock generated
View File

@ -5330,7 +5330,6 @@ dependencies = [
"tree-sitter-typescript",
"tree-sitter-vue",
"tree-sitter-yaml",
"tree-sitter-zig",
"unindent",
"util",
"workspace",
@ -10508,15 +10507,6 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "tree-sitter-zig"
version = "0.0.1"
source = "git+https://github.com/maxxnino/tree-sitter-zig?rev=0d08703e4c3f426ec61695d7617415fff97029bd#0d08703e4c3f426ec61695d7617415fff97029bd"
dependencies = [
"cc",
"tree-sitter",
]
[[package]]
name = "try-lock"
version = "0.2.4"
@ -12635,6 +12625,13 @@ dependencies = [
"zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "zed_zig"
version = "0.0.1"
dependencies = [
"zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "zeno"
version = "0.2.3"

View File

@ -103,6 +103,7 @@ members = [
"extensions/purescript",
"extensions/svelte",
"extensions/uiua",
"extensions/zig",
"tooling/xtask",
]
@ -325,7 +326,6 @@ tree-sitter-toml = { git = "https://github.com/tree-sitter/tree-sitter-toml", re
tree-sitter-typescript = { git = "https://github.com/tree-sitter/tree-sitter-typescript", rev = "5d20856f34315b068c41edaee2ac8a100081d259" }
tree-sitter-vue = { git = "https://github.com/zed-industries/tree-sitter-vue", rev = "6608d9d60c386f19d80af7d8132322fa11199c42" }
tree-sitter-yaml = { git = "https://github.com/zed-industries/tree-sitter-yaml", rev = "f545a41f57502e1b5ddf2a6668896c1b0620f930" }
tree-sitter-zig = { git = "https://github.com/maxxnino/tree-sitter-zig", rev = "0d08703e4c3f426ec61695d7617415fff97029bd" }
unindent = "0.1.7"
unicase = "2.6"
url = "2.2"

View File

@ -56,6 +56,19 @@ impl LspAdapter for ExtensionLspAdapter {
.host
.path_from_extension(&self.extension.manifest.id, command.command.as_ref());
// TODO: Eventually we'll want to expose an extension API for doing this, but for
// now we just manually set the file permissions for extensions that we know need it.
if self.extension.manifest.id.as_ref() == "zig" {
#[cfg(not(windows))]
{
use std::fs::{self, Permissions};
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, Permissions::from_mode(0o755))
.context("failed to set file permissions")?;
}
}
Ok(LanguageServerBinary {
path,
arguments: command.args.into_iter().map(|arg| arg.into()).collect(),

View File

@ -48,6 +48,7 @@ pub fn suggested_extension(file_extension_or_name: &str) -> Option<Arc<str>> {
("swift", "swift"),
("templ", "templ"),
("wgsl", "wgsl"),
("zig", "zig"),
]
.into_iter()
.map(|(name, file)| (file, name.into()))

View File

@ -73,7 +73,6 @@ tree-sitter-toml.workspace = true
tree-sitter-typescript.workspace = true
tree-sitter-vue.workspace = true
tree-sitter-yaml.workspace = true
tree-sitter-zig.workspace = true
tree-sitter.workspace = true
util.workspace = true

View File

@ -36,7 +36,6 @@ mod toml;
mod typescript;
mod vue;
mod yaml;
mod zig;
// 1. Add tree-sitter-{language} parser to zed crate
// 2. Create a language directory in zed/crates/zed/src/languages and add the language to init function below
@ -105,7 +104,6 @@ pub fn init(
("typescript", tree_sitter_typescript::language_typescript()),
("vue", tree_sitter_vue::language()),
("yaml", tree_sitter_yaml::language()),
("zig", tree_sitter_zig::language()),
("dart", tree_sitter_dart::language()),
]);
@ -212,7 +210,6 @@ pub fn init(
language!("go", vec![Arc::new(go::GoLspAdapter)]);
language!("gomod");
language!("gowork");
language!("zig", vec![Arc::new(zig::ZlsAdapter)]);
language!(
"heex",
vec![

View File

@ -1,143 +0,0 @@
use anyhow::{anyhow, Context, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use async_trait::async_trait;
use futures::{io::BufReader, StreamExt};
use gpui::AsyncAppContext;
use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
use lsp::LanguageServerBinary;
use smol::fs;
use std::env::consts::{ARCH, OS};
use std::{any::Any, path::PathBuf};
use util::github::latest_github_release;
use util::maybe;
use util::{github::GitHubLspBinaryVersion, ResultExt};
pub struct ZlsAdapter;
#[async_trait(?Send)]
impl LspAdapter for ZlsAdapter {
fn name(&self) -> LanguageServerName {
LanguageServerName("zls".into())
}
async fn fetch_latest_server_version(
&self,
delegate: &dyn LspAdapterDelegate,
) -> Result<Box<dyn 'static + Send + Any>> {
let release =
latest_github_release("zigtools/zls", true, false, delegate.http_client()).await?;
let asset_name = format!("zls-{ARCH}-{OS}.tar.gz");
let asset = release
.assets
.iter()
.find(|asset| asset.name == asset_name)
.ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
let version = GitHubLspBinaryVersion {
name: release.tag_name,
url: asset.browser_download_url.clone(),
};
Ok(Box::new(version) as Box<_>)
}
async fn check_if_user_installed(
&self,
delegate: &dyn LspAdapterDelegate,
_cx: &AsyncAppContext,
) -> Option<LanguageServerBinary> {
let env = delegate.shell_env().await;
let path = delegate.which("zls".as_ref()).await?;
Some(LanguageServerBinary {
path,
arguments: vec![],
env: Some(env),
})
}
async fn fetch_server_binary(
&self,
version: Box<dyn 'static + Send + Any>,
container_dir: PathBuf,
delegate: &dyn LspAdapterDelegate,
) -> Result<LanguageServerBinary> {
let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
let binary_path = container_dir.join("bin/zls");
if fs::metadata(&binary_path).await.is_err() {
let mut response = delegate
.http_client()
.get(&version.url, Default::default(), true)
.await
.context("error downloading release")?;
let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
let archive = Archive::new(decompressed_bytes);
archive.unpack(container_dir).await?;
}
// todo("windows")
#[cfg(not(windows))]
{
fs::set_permissions(
&binary_path,
<fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
)
.await?;
}
Ok(LanguageServerBinary {
path: binary_path,
env: None,
arguments: vec![],
})
}
async fn cached_server_binary(
&self,
container_dir: PathBuf,
_: &dyn LspAdapterDelegate,
) -> Option<LanguageServerBinary> {
get_cached_server_binary(container_dir).await
}
async fn installation_test_binary(
&self,
container_dir: PathBuf,
) -> Option<LanguageServerBinary> {
get_cached_server_binary(container_dir)
.await
.map(|mut binary| {
binary.arguments = vec!["--help".into()];
binary
})
}
}
async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
maybe!(async {
let mut last_binary_path = None;
let mut entries = fs::read_dir(&container_dir).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
if entry.file_type().await?.is_file()
&& entry
.file_name()
.to_str()
.map_or(false, |name| name == "zls")
{
last_binary_path = Some(entry.path());
}
}
if let Some(path) = last_binary_path {
Ok(LanguageServerBinary {
path,
env: None,
arguments: Vec::new(),
})
} else {
Err(anyhow!("no cached binary"))
}
})
.await
.log_err()
}

16
extensions/zig/Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[package]
name = "zed_zig"
version = "0.0.1"
edition = "2021"
publish = false
license = "Apache-2.0"
[lints]
workspace = true
[lib]
path = "src/zig.rs"
crate-type = ["cdylib"]
[dependencies]
zed_extension_api = "0.0.4"

View File

@ -0,0 +1 @@
../../LICENSE-APACHE

View File

@ -0,0 +1,15 @@
id = "zig"
name = "Zig"
description = "Zig support."
version = "0.0.1"
schema_version = 1
authors = ["Allan Calix <contact@acx.dev>"]
repository = "https://github.com/zed-industries/zed"
[language_servers.zls]
name = "zls"
language = "Zig"
[grammars.zig]
repository = "https://github.com/maxxnino/tree-sitter-zig"
commit = "0d08703e4c3f426ec61695d7617415fff97029bd"

116
extensions/zig/src/zig.rs Normal file
View File

@ -0,0 +1,116 @@
use std::fs;
use zed_extension_api::{self as zed, Result};
struct ZigExtension {
cached_binary_path: Option<String>,
}
impl ZigExtension {
fn language_server_binary_path(
&mut self,
config: zed::LanguageServerConfig,
worktree: &zed::Worktree,
) -> Result<String> {
if let Some(path) = &self.cached_binary_path {
if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
return Ok(path.clone());
}
}
if let Some(path) = worktree.which("zls") {
self.cached_binary_path = Some(path.clone());
return Ok(path);
}
zed::set_language_server_installation_status(
&config.name,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
"zigtools/zls",
zed::GithubReleaseOptions {
require_assets: true,
pre_release: false,
},
)?;
let (platform, arch) = zed::current_platform();
let asset_name = format!(
"zls-{arch}-{os}.{extension}",
arch = match arch {
zed::Architecture::Aarch64 => "aarch64",
zed::Architecture::X86 => "x86",
zed::Architecture::X8664 => "x86_64",
},
os = match platform {
zed::Os::Mac => "macos",
zed::Os::Linux => "linux",
zed::Os::Windows => "windows",
},
extension = match platform {
zed::Os::Mac | zed::Os::Linux => "tar.gz",
zed::Os::Windows => "zip",
}
);
let asset = release
.assets
.iter()
.find(|asset| asset.name == asset_name)
.ok_or_else(|| format!("no asset found matching {:?}", asset_name))?;
let version_dir = format!("zls-{}", release.version);
let binary_path = format!("{version_dir}/bin/zls");
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
&config.name,
&zed::LanguageServerInstallationStatus::Downloading,
);
zed::download_file(
&asset.download_url,
&version_dir,
match platform {
zed::Os::Mac | zed::Os::Linux => zed::DownloadedFileType::GzipTar,
zed::Os::Windows => zed::DownloadedFileType::Zip,
},
)
.map_err(|e| format!("failed to download file: {e}"))?;
let entries =
fs::read_dir(".").map_err(|e| format!("failed to list working directory {e}"))?;
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
fs::remove_dir_all(&entry.path()).ok();
}
}
}
self.cached_binary_path = Some(binary_path.clone());
Ok(binary_path)
}
}
impl zed::Extension for ZigExtension {
fn new() -> Self {
Self {
cached_binary_path: None,
}
}
fn language_server_command(
&mut self,
config: zed::LanguageServerConfig,
worktree: &zed::Worktree,
) -> Result<zed::Command> {
Ok(zed::Command {
command: self.language_server_binary_path(config, worktree)?,
args: vec![],
env: Default::default(),
})
}
}
zed::register_extension!(ZigExtension);