json.rs

  1use super::installation::{latest_github_release, GitHubLspBinaryVersion};
  2use anyhow::{anyhow, Result};
  3use async_compression::futures::bufread::GzipDecoder;
  4use async_trait::async_trait;
  5use client::http::HttpClient;
  6use collections::HashMap;
  7use futures::{future::BoxFuture, io::BufReader, FutureExt, StreamExt};
  8use gpui::MutableAppContext;
  9use language::{LanguageRegistry, LanguageServerName, LspAdapter};
 10use serde_json::json;
 11use settings::{keymap_file_json_schema, settings_file_json_schema};
 12use smol::fs::{self, File};
 13use std::{
 14    any::Any,
 15    env::consts,
 16    future,
 17    path::{Path, PathBuf},
 18    sync::Arc,
 19};
 20use theme::ThemeRegistry;
 21use util::{paths, ResultExt, StaffMode};
 22
 23pub struct JsonLspAdapter {
 24    languages: Arc<LanguageRegistry>,
 25    themes: Arc<ThemeRegistry>,
 26}
 27
 28impl JsonLspAdapter {
 29    pub fn new(languages: Arc<LanguageRegistry>, themes: Arc<ThemeRegistry>) -> Self {
 30        Self { languages, themes }
 31    }
 32}
 33
 34#[async_trait]
 35impl LspAdapter for JsonLspAdapter {
 36    async fn name(&self) -> LanguageServerName {
 37        LanguageServerName("json-language-server".into())
 38    }
 39
 40    async fn server_args(&self) -> Vec<String> {
 41        vec!["--stdio".into()]
 42    }
 43
 44    async fn fetch_latest_server_version(
 45        &self,
 46        http: Arc<dyn HttpClient>,
 47    ) -> Result<Box<dyn 'static + Send + Any>> {
 48        let release = latest_github_release("zed-industries/json-language-server", http).await?;
 49        let asset_name = format!("json-language-server-darwin-{}.gz", consts::ARCH);
 50        let asset = release
 51            .assets
 52            .iter()
 53            .find(|asset| asset.name == asset_name)
 54            .ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
 55        let version = GitHubLspBinaryVersion {
 56            name: release.name,
 57            url: asset.browser_download_url.clone(),
 58        };
 59        Ok(Box::new(version) as Box<_>)
 60    }
 61
 62    async fn fetch_server_binary(
 63        &self,
 64        version: Box<dyn 'static + Send + Any>,
 65        http: Arc<dyn HttpClient>,
 66        container_dir: PathBuf,
 67    ) -> Result<PathBuf> {
 68        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
 69        let destination_path = container_dir.join(format!(
 70            "json-language-server-{}-{}",
 71            version.name,
 72            consts::ARCH
 73        ));
 74
 75        if fs::metadata(&destination_path).await.is_err() {
 76            let mut response = http
 77                .get(&version.url, Default::default(), true)
 78                .await
 79                .map_err(|err| anyhow!("error downloading release: {}", err))?;
 80            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
 81            let mut file = File::create(&destination_path).await?;
 82            futures::io::copy(decompressed_bytes, &mut file).await?;
 83            fs::set_permissions(
 84                &destination_path,
 85                <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
 86            )
 87            .await?;
 88
 89            if let Some(mut entries) = fs::read_dir(&container_dir).await.log_err() {
 90                while let Some(entry) = entries.next().await {
 91                    if let Some(entry) = entry.log_err() {
 92                        let entry_path = entry.path();
 93                        if entry_path.as_path() != destination_path {
 94                            fs::remove_file(&entry_path).await.log_err();
 95                        }
 96                    }
 97                }
 98            }
 99        }
100
101        Ok(destination_path)
102    }
103
104    async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf> {
105        (|| async move {
106            let mut last = None;
107            let mut entries = fs::read_dir(&container_dir).await?;
108            while let Some(entry) = entries.next().await {
109                last = Some(entry?.path());
110            }
111            last.ok_or_else(|| anyhow!("no cached binary"))
112        })()
113        .await
114        .log_err()
115    }
116
117    async fn initialization_options(&self) -> Option<serde_json::Value> {
118        Some(json!({
119            "provideFormatter": true
120        }))
121    }
122
123    fn workspace_configuration(
124        &self,
125        cx: &mut MutableAppContext,
126    ) -> Option<BoxFuture<'static, serde_json::Value>> {
127        let action_names = cx.all_action_names().collect::<Vec<_>>();
128        let theme_names = self
129            .themes
130            .list(**cx.default_global::<StaffMode>())
131            .map(|meta| meta.name)
132            .collect();
133        let language_names = self.languages.language_names();
134        Some(
135            future::ready(serde_json::json!({
136                "json": {
137                    "format": {
138                        "enable": true,
139                    },
140                    "schemas": [
141                        {
142                            "fileMatch": [schema_file_match(&paths::SETTINGS)],
143                            "schema": settings_file_json_schema(theme_names, &language_names),
144                        },
145                        {
146                            "fileMatch": [schema_file_match(&paths::KEYMAP)],
147                            "schema": keymap_file_json_schema(&action_names),
148                        }
149                    ]
150                }
151            }))
152            .boxed(),
153        )
154    }
155
156    async fn language_ids(&self) -> HashMap<String, String> {
157        [("JSON".into(), "jsonc".into())].into_iter().collect()
158    }
159}
160
161fn schema_file_match(path: &Path) -> &Path {
162    path.strip_prefix(path.parent().unwrap().parent().unwrap())
163        .unwrap()
164}