1use anyhow::{anyhow, Result};
2use async_trait::async_trait;
3use futures::StreamExt;
4use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
5use lsp::LanguageServerBinary;
6use node_runtime::NodeRuntime;
7use serde_json::json;
8use smol::fs;
9use std::{
10 any::Any,
11 ffi::OsString,
12 path::{Path, PathBuf},
13 sync::Arc,
14};
15use util::{maybe, ResultExt};
16
17const SERVER_PATH: &str =
18 "node_modules/vscode-langservers-extracted/bin/vscode-css-language-server";
19
20fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
21 vec![server_path.into(), "--stdio".into()]
22}
23
24pub struct CssLspAdapter {
25 node: NodeRuntime,
26}
27
28impl CssLspAdapter {
29 pub fn new(node: NodeRuntime) -> Self {
30 CssLspAdapter { node }
31 }
32}
33
34#[async_trait(?Send)]
35impl LspAdapter for CssLspAdapter {
36 fn name(&self) -> LanguageServerName {
37 LanguageServerName("vscode-css-language-server".into())
38 }
39
40 async fn fetch_latest_server_version(
41 &self,
42 _: &dyn LspAdapterDelegate,
43 ) -> Result<Box<dyn 'static + Any + Send>> {
44 Ok(Box::new(
45 self.node
46 .npm_package_latest_version("vscode-langservers-extracted")
47 .await?,
48 ) as Box<_>)
49 }
50
51 async fn fetch_server_binary(
52 &self,
53 latest_version: Box<dyn 'static + Send + Any>,
54 container_dir: PathBuf,
55 _: &dyn LspAdapterDelegate,
56 ) -> Result<LanguageServerBinary> {
57 let latest_version = latest_version.downcast::<String>().unwrap();
58 let server_path = container_dir.join(SERVER_PATH);
59 let package_name = "vscode-langservers-extracted";
60
61 let should_install_language_server = self
62 .node
63 .should_install_npm_package(package_name, &server_path, &container_dir, &latest_version)
64 .await;
65
66 if should_install_language_server {
67 self.node
68 .npm_install_packages(&container_dir, &[(package_name, latest_version.as_str())])
69 .await?;
70 }
71
72 Ok(LanguageServerBinary {
73 path: self.node.binary_path().await?,
74 env: None,
75 arguments: server_binary_arguments(&server_path),
76 })
77 }
78
79 async fn cached_server_binary(
80 &self,
81 container_dir: PathBuf,
82 _: &dyn LspAdapterDelegate,
83 ) -> Option<LanguageServerBinary> {
84 get_cached_server_binary(container_dir, &self.node).await
85 }
86
87 async fn initialization_options(
88 self: Arc<Self>,
89 _: &Arc<dyn LspAdapterDelegate>,
90 ) -> Result<Option<serde_json::Value>> {
91 Ok(Some(json!({
92 "provideFormatter": true
93 })))
94 }
95}
96
97async fn get_cached_server_binary(
98 container_dir: PathBuf,
99 node: &NodeRuntime,
100) -> Option<LanguageServerBinary> {
101 maybe!(async {
102 let mut last_version_dir = None;
103 let mut entries = fs::read_dir(&container_dir).await?;
104 while let Some(entry) = entries.next().await {
105 let entry = entry?;
106 if entry.file_type().await?.is_dir() {
107 last_version_dir = Some(entry.path());
108 }
109 }
110 let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
111 let server_path = last_version_dir.join(SERVER_PATH);
112 if server_path.exists() {
113 Ok(LanguageServerBinary {
114 path: node.binary_path().await?,
115 env: None,
116 arguments: server_binary_arguments(&server_path),
117 })
118 } else {
119 Err(anyhow!(
120 "missing executable in directory {:?}",
121 last_version_dir
122 ))
123 }
124 })
125 .await
126 .log_err()
127}
128
129#[cfg(test)]
130mod tests {
131 use gpui::{Context, TestAppContext};
132 use unindent::Unindent;
133
134 #[gpui::test]
135 async fn test_outline(cx: &mut TestAppContext) {
136 let language = crate::language("css", tree_sitter_css::LANGUAGE.into());
137
138 let text = r#"
139 /* Import statement */
140 @import './fonts.css';
141
142 /* multiline list of selectors with nesting */
143 .test-class,
144 div {
145 .nested-class {
146 color: red;
147 }
148 }
149
150 /* descendant selectors */
151 .test .descendant {}
152
153 /* pseudo */
154 .test:not(:hover) {}
155
156 /* media queries */
157 @media screen and (min-width: 3000px) {
158 .desktop-class {}
159 }
160 "#
161 .unindent();
162
163 let buffer =
164 cx.new_model(|cx| language::Buffer::local(text, cx).with_language(language, cx));
165 let outline = buffer.update(cx, |buffer, _| buffer.snapshot().outline(None).unwrap());
166 assert_eq!(
167 outline
168 .items
169 .iter()
170 .map(|item| (item.text.as_str(), item.depth))
171 .collect::<Vec<_>>(),
172 &[
173 ("@import './fonts.css'", 0),
174 (".test-class, div", 0),
175 (".nested-class", 1),
176 (".test .descendant", 0),
177 (".test:not(:hover)", 0),
178 ("@media screen and (min-width: 3000px)", 0),
179 (".desktop-class", 1),
180 ]
181 );
182 }
183}