css.rs

  1use anyhow::Result;
  2use async_trait::async_trait;
  3use gpui::AsyncApp;
  4use language::{LspAdapter, LspAdapterDelegate, LspInstaller, Toolchain};
  5use lsp::{LanguageServerBinary, LanguageServerName, Uri};
  6use node_runtime::{NodeRuntime, VersionStrategy};
  7use project::lsp_store::language_server_settings;
  8use serde_json::json;
  9use std::{
 10    ffi::OsString,
 11    path::{Path, PathBuf},
 12    sync::Arc,
 13};
 14use util::{ResultExt, maybe, merge_json_value_into};
 15
 16const SERVER_PATH: &str =
 17    "node_modules/vscode-langservers-extracted/bin/vscode-css-language-server";
 18
 19fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
 20    vec![server_path.into(), "--stdio".into()]
 21}
 22
 23pub struct CssLspAdapter {
 24    node: NodeRuntime,
 25}
 26
 27impl CssLspAdapter {
 28    const PACKAGE_NAME: &str = "vscode-langservers-extracted";
 29    pub fn new(node: NodeRuntime) -> Self {
 30        CssLspAdapter { node }
 31    }
 32}
 33
 34impl LspInstaller for CssLspAdapter {
 35    type BinaryVersion = String;
 36
 37    async fn fetch_latest_server_version(
 38        &self,
 39        _: &dyn LspAdapterDelegate,
 40        _: bool,
 41        _: &mut AsyncApp,
 42    ) -> Result<String> {
 43        self.node
 44            .npm_package_latest_version("vscode-langservers-extracted")
 45            .await
 46    }
 47
 48    async fn check_if_user_installed(
 49        &self,
 50        delegate: &dyn LspAdapterDelegate,
 51        _: Option<Toolchain>,
 52        _: &AsyncApp,
 53    ) -> Option<LanguageServerBinary> {
 54        let path = delegate
 55            .which("vscode-css-language-server".as_ref())
 56            .await?;
 57        let env = delegate.shell_env().await;
 58
 59        Some(LanguageServerBinary {
 60            path,
 61            env: Some(env),
 62            arguments: vec!["--stdio".into()],
 63        })
 64    }
 65
 66    async fn fetch_server_binary(
 67        &self,
 68        latest_version: String,
 69        container_dir: PathBuf,
 70        _: &dyn LspAdapterDelegate,
 71    ) -> Result<LanguageServerBinary> {
 72        let server_path = container_dir.join(SERVER_PATH);
 73
 74        self.node
 75            .npm_install_packages(
 76                &container_dir,
 77                &[(Self::PACKAGE_NAME, latest_version.as_str())],
 78            )
 79            .await?;
 80
 81        Ok(LanguageServerBinary {
 82            path: self.node.binary_path().await?,
 83            env: None,
 84            arguments: server_binary_arguments(&server_path),
 85        })
 86    }
 87
 88    async fn check_if_version_installed(
 89        &self,
 90        version: &String,
 91        container_dir: &PathBuf,
 92        _: &dyn LspAdapterDelegate,
 93    ) -> Option<LanguageServerBinary> {
 94        let server_path = container_dir.join(SERVER_PATH);
 95
 96        let should_install_language_server = self
 97            .node
 98            .should_install_npm_package(
 99                Self::PACKAGE_NAME,
100                &server_path,
101                container_dir,
102                VersionStrategy::Latest(version),
103            )
104            .await;
105
106        if should_install_language_server {
107            None
108        } else {
109            Some(LanguageServerBinary {
110                path: self.node.binary_path().await.ok()?,
111                env: None,
112                arguments: server_binary_arguments(&server_path),
113            })
114        }
115    }
116
117    async fn cached_server_binary(
118        &self,
119        container_dir: PathBuf,
120        _: &dyn LspAdapterDelegate,
121    ) -> Option<LanguageServerBinary> {
122        get_cached_server_binary(container_dir, &self.node).await
123    }
124}
125
126#[async_trait(?Send)]
127impl LspAdapter for CssLspAdapter {
128    fn name(&self) -> LanguageServerName {
129        LanguageServerName("vscode-css-language-server".into())
130    }
131
132    async fn initialization_options(
133        self: Arc<Self>,
134        _: &Arc<dyn LspAdapterDelegate>,
135    ) -> Result<Option<serde_json::Value>> {
136        Ok(Some(json!({
137            "provideFormatter": true
138        })))
139    }
140
141    async fn workspace_configuration(
142        self: Arc<Self>,
143        delegate: &Arc<dyn LspAdapterDelegate>,
144        _: Option<Toolchain>,
145        _: Option<Uri>,
146        cx: &mut AsyncApp,
147    ) -> Result<serde_json::Value> {
148        let mut default_config = json!({
149            "css": {
150                "lint": {}
151            },
152            "less": {
153                "lint": {}
154            },
155            "scss": {
156                "lint": {}
157            }
158        });
159
160        let project_options = cx.update(|cx| {
161            language_server_settings(delegate.as_ref(), &self.name(), cx)
162                .and_then(|s| s.settings.clone())
163        })?;
164
165        if let Some(override_options) = project_options {
166            merge_json_value_into(override_options, &mut default_config);
167        }
168
169        Ok(default_config)
170    }
171}
172
173async fn get_cached_server_binary(
174    container_dir: PathBuf,
175    node: &NodeRuntime,
176) -> Option<LanguageServerBinary> {
177    maybe!(async {
178        let server_path = container_dir.join(SERVER_PATH);
179        anyhow::ensure!(
180            server_path.exists(),
181            "missing executable in directory {server_path:?}"
182        );
183        Ok(LanguageServerBinary {
184            path: node.binary_path().await?,
185            env: None,
186            arguments: server_binary_arguments(&server_path),
187        })
188    })
189    .await
190    .log_err()
191}
192
193#[cfg(test)]
194mod tests {
195    use gpui::{AppContext as _, TestAppContext};
196    use unindent::Unindent;
197
198    #[gpui::test]
199    async fn test_outline(cx: &mut TestAppContext) {
200        let language = crate::language("css", tree_sitter_css::LANGUAGE.into());
201
202        let text = r#"
203            /* Import statement */
204            @import './fonts.css';
205
206            /* multiline list of selectors with nesting */
207            .test-class,
208            div {
209                .nested-class {
210                    color: red;
211                }
212            }
213
214            /* descendant selectors */
215            .test .descendant {}
216
217            /* pseudo */
218            .test:not(:hover) {}
219
220            /* media queries */
221            @media screen and (min-width: 3000px) {
222                .desktop-class {}
223            }
224        "#
225        .unindent();
226
227        let buffer =
228            cx.new(|cx| language::Buffer::local(text, cx).with_language_immediate(language, cx));
229        let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None));
230        assert_eq!(
231            outline
232                .items
233                .iter()
234                .map(|item| (item.text.as_str(), item.depth))
235                .collect::<Vec<_>>(),
236            &[
237                ("@import './fonts.css'", 0),
238                (".test-class, div", 0),
239                (".nested-class", 1),
240                (".test .descendant", 0),
241                (".test:not(:hover)", 0),
242                ("@media screen and (min-width: 3000px)", 0),
243                (".desktop-class", 1),
244            ]
245        );
246    }
247}