Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Extract Astro support into an extension (#9835)
Marshall Bowers3676ca879bf3
diff --git a/Cargo.lock b/Cargo.lockindex 48048597893..5a15c420df5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5293,7 +5293,6 @@ dependencies = ["theme","toml 0.8.10","tree-sitter",- "tree-sitter-astro","tree-sitter-bash","tree-sitter-c","tree-sitter-c-sharp",@@ -10133,15 +10132,6 @@ dependencies = ["wasmtime-c-api-impl",]-[[package]]-name = "tree-sitter-astro"-version = "0.0.1"-source = "git+https://github.com/virchau13/tree-sitter-astro.git?rev=e924787e12e8a03194f36a113290ac11d6dc10f3#e924787e12e8a03194f36a113290ac11d6dc10f3"-dependencies = [- "cc",- "tree-sitter",-]-[[package]]name = "tree-sitter-bash"version = "0.20.4"@@ -12556,6 +12546,13 @@ dependencies = ["serde",]+[[package]]+name = "zed_astro"+version = "0.0.1"+dependencies = [+ "zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",+]+[[package]]name = "zed_extension_api"version = "0.0.4"diff --git a/Cargo.toml b/Cargo.tomlindex f74cd3d5b5e..ac35201bd78 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -95,6 +95,7 @@ members = ["crates/zed","crates/zed_actions",+ "extensions/astro","extensions/gleam","extensions/haskell","extensions/prisma",@@ -284,7 +285,6 @@ toml = "0.8"tokio = { version = "1", features = ["full"] }tower-http = "0.4.4"tree-sitter = { version = "0.20", features = ["wasm"] }-tree-sitter-astro = { git = "https://github.com/virchau13/tree-sitter-astro.git", rev = "e924787e12e8a03194f36a113290ac11d6dc10f3" }tree-sitter-bash = { git = "https://github.com/tree-sitter/tree-sitter-bash", rev = "7331995b19b8f8aba2d5e26deb51d2195c18bc94" }tree-sitter-c = "0.20.1"tree-sitter-clojure = { git = "https://github.com/prcastro/tree-sitter-clojure", branch = "update-ts" }diff --git a/crates/extensions_ui/src/extension_suggest.rs b/crates/extensions_ui/src/extension_suggest.rsindex 785407ae8cb..0283b621eff 100644--- a/crates/extensions_ui/src/extension_suggest.rs+++ b/crates/extensions_ui/src/extension_suggest.rs@@ -17,6 +17,7 @@ pub fn suggested_extension(file_extension_or_name: &str) -> Option<Arc<str>> {SUGGESTED.get_or_init(|| {[+ ("astro", "astro"),("beancount", "beancount"),("dockerfile", "Dockerfile"),("elisp", "el"),diff --git a/crates/languages/Cargo.toml b/crates/languages/Cargo.tomlindex fa4b888a615..ad23c912ec4 100644--- a/crates/languages/Cargo.toml+++ b/crates/languages/Cargo.toml@@ -36,7 +36,6 @@ shellexpand.workspace = truesmol.workspace = truetask.workspace = truetoml.workspace = true-tree-sitter-astro.workspace = truetree-sitter-bash.workspace = truetree-sitter-c-sharp.workspace = truetree-sitter-c.workspace = truediff --git a/crates/languages/src/astro.rs b/crates/languages/src/astro.rsdeleted file mode 100644index 5706f387394..00000000000--- a/crates/languages/src/astro.rs+++ /dev/null@@ -1,136 +0,0 @@-use anyhow::{anyhow, Result};-use async_trait::async_trait;-use futures::StreamExt;-use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};-use lsp::LanguageServerBinary;-use node_runtime::NodeRuntime;-use serde_json::json;-use smol::fs;-use std::{- any::Any,- ffi::OsString,- path::{Path, PathBuf},- sync::Arc,-};-use util::{maybe, ResultExt};--const SERVER_PATH: &str = "node_modules/@astrojs/language-server/bin/nodeServer.js";--fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {- vec![server_path.into(), "--stdio".into()]-}--pub struct AstroLspAdapter {- node: Arc<dyn NodeRuntime>,-}--impl AstroLspAdapter {- pub fn new(node: Arc<dyn NodeRuntime>) -> Self {- AstroLspAdapter { node }- }-}--#[async_trait(?Send)]-impl LspAdapter for AstroLspAdapter {- fn name(&self) -> LanguageServerName {- LanguageServerName("astro-language-server".into())- }-- async fn fetch_latest_server_version(- &self,- _: &dyn LspAdapterDelegate,- ) -> Result<Box<dyn 'static + Any + Send>> {- Ok(Box::new(- self.node- .npm_package_latest_version("@astrojs/language-server")- .await?,- ) as Box<_>)- }-- async fn fetch_server_binary(- &self,- latest_version: Box<dyn 'static + Send + Any>,- container_dir: PathBuf,- _: &dyn LspAdapterDelegate,- ) -> Result<LanguageServerBinary> {- let latest_version = latest_version.downcast::<String>().unwrap();- let server_path = container_dir.join(SERVER_PATH);- let package_name = "@astrojs/language-server";-- let should_install_npm_package = self- .node- .should_install_npm_package(package_name, &server_path, &container_dir, &latest_version)- .await;-- if should_install_npm_package {- self.node- .npm_install_packages(&container_dir, &[(package_name, latest_version.as_str())])- .await?;- }-- Ok(LanguageServerBinary {- path: self.node.binary_path().await?,- env: None,- arguments: server_binary_arguments(&server_path),- })- }-- async fn cached_server_binary(- &self,- container_dir: PathBuf,- _: &dyn LspAdapterDelegate,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir, &*self.node).await- }-- async fn installation_test_binary(- &self,- container_dir: PathBuf,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir, &*self.node).await- }-- async fn initialization_options(- self: Arc<Self>,- _: &Arc<dyn LspAdapterDelegate>,- ) -> Result<Option<serde_json::Value>> {- Ok(Some(json!({- "provideFormatter": true,- "typescript": {- "tsdk": "node_modules/typescript/lib",- }- })))- }-}--async fn get_cached_server_binary(- container_dir: PathBuf,- node: &dyn NodeRuntime,-) -> Option<LanguageServerBinary> {- maybe!(async {- let mut last_version_dir = 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_dir() {- last_version_dir = Some(entry.path());- }- }- let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;- let server_path = last_version_dir.join(SERVER_PATH);- if server_path.exists() {- Ok(LanguageServerBinary {- path: node.binary_path().await?,- env: None,- arguments: server_binary_arguments(&server_path),- })- } else {- Err(anyhow!(- "missing executable in directory {:?}",- last_version_dir- ))- }- })- .await- .log_err()-}diff --git a/crates/languages/src/lib.rs b/crates/languages/src/lib.rsindex 80401256df4..b8192e76f3f 100644--- a/crates/languages/src/lib.rs+++ b/crates/languages/src/lib.rs@@ -11,7 +11,6 @@ use crate::{elixir::elixir_task_context, rust::RustContextProvider};use self::{deno::DenoSettings, elixir::ElixirSettings};-mod astro;mod c;mod clojure;mod csharp;@@ -62,7 +61,6 @@ pub fn init(DenoSettings::register(cx);languages.register_native_grammars([- ("astro", tree_sitter_astro::language()),("bash", tree_sitter_bash::language()),("c", tree_sitter_c::language()),("c_sharp", tree_sitter_c_sharp::language()),@@ -168,13 +166,6 @@ pub fn init();};}- language!(- "astro",- vec![- Arc::new(astro::AstroLspAdapter::new(node_runtime.clone())),- Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),- ]- );language!("bash");language!("c", vec![Arc::new(c::CLspAdapter) as Arc<dyn LspAdapter>]);language!("clojure", vec![Arc::new(clojure::ClojureLspAdapter)]);@@ -353,6 +344,10 @@ pub fn init(language!("hcl", vec![]);language!("dart", vec![Arc::new(dart::DartLanguageServer {})]);+ languages.register_secondary_lsp_adapter(+ "Astro".into(),+ Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),+ );languages.register_secondary_lsp_adapter("Svelte".into(),Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),diff --git a/extensions/astro/Cargo.toml b/extensions/astro/Cargo.tomlnew file mode 100644index 00000000000..f2d1d3cb35a--- /dev/null+++ b/extensions/astro/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "zed_astro"+version = "0.0.1"+edition = "2021"+publish = false+license = "Apache-2.0"++[lints]+workspace = true++[lib]+path = "src/astro.rs"+crate-type = ["cdylib"]++[dependencies]+zed_extension_api = "0.0.4"diff --git a/extensions/astro/LICENSE-APACHE b/extensions/astro/LICENSE-APACHEnew file mode 120000index 00000000000..1cd601d0a3a--- /dev/null+++ b/extensions/astro/LICENSE-APACHE@@ -0,0 +1 @@+../../LICENSE-APACHE\ No newline at end of filediff --git a/extensions/astro/extension.toml b/extensions/astro/extension.tomlnew file mode 100644index 00000000000..461f52e8014--- /dev/null+++ b/extensions/astro/extension.toml@@ -0,0 +1,15 @@+id = "astro"+name = "Astro"+description = "Astro support."+version = "0.0.1"+schema_version = 1+authors = ["Alvaro Gaona <[email protected]>"]+repository = "https://github.com/zed-industries/zed"++[language_servers.astro-language-server]+name = "Astro Language Server"+language = "Astro"++[grammars.astro]+repository = "https://github.com/virchau13/tree-sitter-astro"+commit = "dfa0893bdc4bdfada102043404758c66e3580568"diff --git a/crates/languages/src/astro/brackets.scm b/extensions/astro/languages/astro/brackets.scmsimilarity index 100%rename from crates/languages/src/astro/brackets.scmrename to extensions/astro/languages/astro/brackets.scmdiff --git a/crates/languages/src/astro/config.toml b/extensions/astro/languages/astro/config.tomlsimilarity index 100%rename from crates/languages/src/astro/config.tomlrename to extensions/astro/languages/astro/config.tomldiff --git a/crates/languages/src/astro/highlights.scm b/extensions/astro/languages/astro/highlights.scmsimilarity index 100%rename from crates/languages/src/astro/highlights.scmrename to extensions/astro/languages/astro/highlights.scmdiff --git a/crates/languages/src/astro/injections.scm b/extensions/astro/languages/astro/injections.scmsimilarity index 100%rename from crates/languages/src/astro/injections.scmrename to extensions/astro/languages/astro/injections.scmdiff --git a/extensions/astro/src/astro.rs b/extensions/astro/src/astro.rsnew file mode 100644index 00000000000..cabe89adeaa--- /dev/null+++ b/extensions/astro/src/astro.rs@@ -0,0 +1,100 @@+use std::{env, fs};+use zed_extension_api::{self as zed, Result};++const SERVER_PATH: &str = "node_modules/@astrojs/language-server/bin/nodeServer.js";+const PACKAGE_NAME: &str = "@astrojs/language-server";++struct AstroExtension {+ did_find_server: bool,+}++impl AstroExtension {+ fn server_exists(&self) -> bool {+ fs::metadata(SERVER_PATH).map_or(false, |stat| stat.is_file())+ }++ fn server_script_path(&mut self, config: zed::LanguageServerConfig) -> Result<String> {+ let server_exists = self.server_exists();+ if self.did_find_server && server_exists {+ return Ok(SERVER_PATH.to_string());+ }++ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::CheckingForUpdate,+ );+ let version = zed::npm_package_latest_version(PACKAGE_NAME)?;++ if !server_exists+ || zed::npm_package_installed_version(PACKAGE_NAME)?.as_ref() != Some(&version)+ {+ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::Downloading,+ );+ let result = zed::npm_install_package(PACKAGE_NAME, &version);+ match result {+ Ok(()) => {+ if !self.server_exists() {+ Err(format!(+ "installed package '{PACKAGE_NAME}' did not contain expected path '{SERVER_PATH}'",+ ))?;+ }+ }+ Err(error) => {+ if !self.server_exists() {+ Err(error)?;+ }+ }+ }+ }++ self.did_find_server = true;+ Ok(SERVER_PATH.to_string())+ }+}++impl zed::Extension for AstroExtension {+ fn new() -> Self {+ Self {+ did_find_server: false,+ }+ }++ fn language_server_command(+ &mut self,+ config: zed::LanguageServerConfig,+ _worktree: &zed::Worktree,+ ) -> Result<zed::Command> {+ let server_path = self.server_script_path(config)?;+ Ok(zed::Command {+ command: zed::node_binary_path()?,+ args: vec![+ env::current_dir()+ .unwrap()+ .join(&server_path)+ .to_string_lossy()+ .to_string(),+ "--stdio".to_string(),+ ],+ env: Default::default(),+ })+ }++ fn language_server_initialization_options(+ &mut self,+ _config: zed::LanguageServerConfig,+ _worktree: &zed::Worktree,+ ) -> Result<Option<String>> {+ let initialization_options = r#"{+ "provideFormatter": true,+ "typescript": {+ "tsdk": "node_modules/typescript/lib"+ }+ }"#;++ Ok(Some(initialization_options.to_string()))+ }+}++zed::register_extension!(AstroExtension);