1use std::collections::VecDeque;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4
5use anyhow::Context;
6use collections::HashMap;
7use fs::Fs;
8use gpui::{AsyncAppContext, ModelHandle};
9use language::language_settings::language_settings;
10use language::{Buffer, Diff};
11use lsp::{LanguageServer, LanguageServerId};
12use node_runtime::NodeRuntime;
13use serde::{Deserialize, Serialize};
14use util::paths::DEFAULT_PRETTIER_DIR;
15
16pub enum Prettier {
17 Real(RealPrettier),
18 #[cfg(any(test, feature = "test-support"))]
19 Test(TestPrettier),
20}
21
22pub struct RealPrettier {
23 worktree_id: Option<usize>,
24 default: bool,
25 prettier_dir: PathBuf,
26 server: Arc<LanguageServer>,
27}
28
29#[cfg(any(test, feature = "test-support"))]
30pub struct TestPrettier {
31 worktree_id: Option<usize>,
32 prettier_dir: PathBuf,
33 default: bool,
34}
35
36#[derive(Debug)]
37pub struct LocateStart {
38 pub worktree_root_path: Arc<Path>,
39 pub starting_path: Arc<Path>,
40}
41
42pub const PRETTIER_SERVER_FILE: &str = "prettier_server.js";
43pub const PRETTIER_SERVER_JS: &str = include_str!("./prettier_server.js");
44const PRETTIER_PACKAGE_NAME: &str = "prettier";
45const TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME: &str = "prettier-plugin-tailwindcss";
46
47#[cfg(any(test, feature = "test-support"))]
48pub const FORMAT_SUFFIX: &str = "\nformatted by test prettier";
49
50impl Prettier {
51 pub const CONFIG_FILE_NAMES: &'static [&'static str] = &[
52 ".prettierrc",
53 ".prettierrc.json",
54 ".prettierrc.json5",
55 ".prettierrc.yaml",
56 ".prettierrc.yml",
57 ".prettierrc.toml",
58 ".prettierrc.js",
59 ".prettierrc.cjs",
60 "package.json",
61 "prettier.config.js",
62 "prettier.config.cjs",
63 ".editorconfig",
64 ];
65
66 pub async fn locate(
67 starting_path: Option<LocateStart>,
68 fs: Arc<dyn Fs>,
69 ) -> anyhow::Result<PathBuf> {
70 fn is_node_modules(path_component: &std::path::Component<'_>) -> bool {
71 path_component.as_os_str().to_string_lossy() == "node_modules"
72 }
73
74 let paths_to_check = match starting_path.as_ref() {
75 Some(starting_path) => {
76 let worktree_root = starting_path
77 .worktree_root_path
78 .components()
79 .into_iter()
80 .take_while(|path_component| !is_node_modules(path_component))
81 .collect::<PathBuf>();
82 if worktree_root != starting_path.worktree_root_path.as_ref() {
83 vec![worktree_root]
84 } else {
85 if starting_path.starting_path.as_ref() == Path::new("") {
86 worktree_root
87 .parent()
88 .map(|path| vec![path.to_path_buf()])
89 .unwrap_or_default()
90 } else {
91 let file_to_format = starting_path.starting_path.as_ref();
92 let mut paths_to_check = VecDeque::new();
93 let mut current_path = worktree_root;
94 for path_component in file_to_format.components().into_iter() {
95 let new_path = current_path.join(path_component);
96 let old_path = std::mem::replace(&mut current_path, new_path);
97 paths_to_check.push_front(old_path);
98 if is_node_modules(&path_component) {
99 break;
100 }
101 }
102 Vec::from(paths_to_check)
103 }
104 }
105 }
106 None => Vec::new(),
107 };
108
109 match find_closest_prettier_dir(paths_to_check, fs.as_ref())
110 .await
111 .with_context(|| format!("finding prettier starting with {starting_path:?}"))?
112 {
113 Some(prettier_dir) => Ok(prettier_dir),
114 None => Ok(DEFAULT_PRETTIER_DIR.to_path_buf()),
115 }
116 }
117
118 #[cfg(any(test, feature = "test-support"))]
119 pub async fn start(
120 worktree_id: Option<usize>,
121 _: LanguageServerId,
122 prettier_dir: PathBuf,
123 _: Arc<dyn NodeRuntime>,
124 _: AsyncAppContext,
125 ) -> anyhow::Result<Self> {
126 Ok(
127 #[cfg(any(test, feature = "test-support"))]
128 Self::Test(TestPrettier {
129 worktree_id,
130 default: prettier_dir == DEFAULT_PRETTIER_DIR.as_path(),
131 prettier_dir,
132 }),
133 )
134 }
135
136 #[cfg(not(any(test, feature = "test-support")))]
137 pub async fn start(
138 worktree_id: Option<usize>,
139 server_id: LanguageServerId,
140 prettier_dir: PathBuf,
141 node: Arc<dyn NodeRuntime>,
142 cx: AsyncAppContext,
143 ) -> anyhow::Result<Self> {
144 use lsp::LanguageServerBinary;
145
146 let backgroud = cx.background();
147 anyhow::ensure!(
148 prettier_dir.is_dir(),
149 "Prettier dir {prettier_dir:?} is not a directory"
150 );
151 let prettier_server = DEFAULT_PRETTIER_DIR.join(PRETTIER_SERVER_FILE);
152 anyhow::ensure!(
153 prettier_server.is_file(),
154 "no prettier server package found at {prettier_server:?}"
155 );
156
157 let node_path = backgroud
158 .spawn(async move { node.binary_path().await })
159 .await?;
160 let server = LanguageServer::new(
161 Arc::new(parking_lot::Mutex::new(None)),
162 server_id,
163 LanguageServerBinary {
164 path: node_path,
165 arguments: vec![prettier_server.into(), prettier_dir.as_path().into()],
166 },
167 Path::new("/"),
168 None,
169 cx,
170 )
171 .context("prettier server creation")?;
172 let server = backgroud
173 .spawn(server.initialize(None))
174 .await
175 .context("prettier server initialization")?;
176 Ok(Self::Real(RealPrettier {
177 worktree_id,
178 server,
179 default: prettier_dir == DEFAULT_PRETTIER_DIR.as_path(),
180 prettier_dir,
181 }))
182 }
183
184 pub async fn format(
185 &self,
186 buffer: &ModelHandle<Buffer>,
187 buffer_path: Option<PathBuf>,
188 cx: &AsyncAppContext,
189 ) -> anyhow::Result<Diff> {
190 match self {
191 Self::Real(local) => {
192 let params = buffer.read_with(cx, |buffer, cx| {
193 let buffer_language = buffer.language();
194 let parser_with_plugins = buffer_language.and_then(|l| {
195 let prettier_parser = l.prettier_parser_name()?;
196 let mut prettier_plugins = l
197 .lsp_adapters()
198 .iter()
199 .flat_map(|adapter| adapter.prettier_plugins())
200 .collect::<Vec<_>>();
201 prettier_plugins.dedup();
202 Some((prettier_parser, prettier_plugins))
203 });
204
205 let prettier_node_modules = self.prettier_dir().join("node_modules");
206 anyhow::ensure!(prettier_node_modules.is_dir(), "Prettier node_modules dir does not exist: {prettier_node_modules:?}");
207 let plugin_name_into_path = |plugin_name: &str| {
208 let prettier_plugin_dir = prettier_node_modules.join(plugin_name);
209 for possible_plugin_path in [
210 prettier_plugin_dir.join("dist").join("index.mjs"),
211 prettier_plugin_dir.join("dist").join("index.js"),
212 prettier_plugin_dir.join("dist").join("plugin.js"),
213 prettier_plugin_dir.join("index.mjs"),
214 prettier_plugin_dir.join("index.js"),
215 prettier_plugin_dir.join("plugin.js"),
216 prettier_plugin_dir,
217 ] {
218 if possible_plugin_path.is_file() {
219 return Some(possible_plugin_path);
220 }
221 }
222 None
223 };
224 let (parser, located_plugins) = match parser_with_plugins {
225 Some((parser, plugins)) => {
226 // Tailwind plugin requires being added last
227 // https://github.com/tailwindlabs/prettier-plugin-tailwindcss#compatibility-with-other-prettier-plugins
228 let mut add_tailwind_back = false;
229
230 let mut plugins = plugins.into_iter().filter(|&&plugin_name| {
231 if plugin_name == TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME {
232 add_tailwind_back = true;
233 false
234 } else {
235 true
236 }
237 }).map(|plugin_name| (plugin_name, plugin_name_into_path(plugin_name))).collect::<Vec<_>>();
238 if add_tailwind_back {
239 plugins.push((&TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME, plugin_name_into_path(TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME)));
240 }
241 (Some(parser.to_string()), plugins)
242 },
243 None => (None, Vec::new()),
244 };
245
246 let prettier_options = if self.is_default() {
247 let language_settings = language_settings(buffer_language, buffer.file(), cx);
248 let mut options = language_settings.prettier.clone();
249 if !options.contains_key("tabWidth") {
250 options.insert(
251 "tabWidth".to_string(),
252 serde_json::Value::Number(serde_json::Number::from(
253 language_settings.tab_size.get(),
254 )),
255 );
256 }
257 if !options.contains_key("printWidth") {
258 options.insert(
259 "printWidth".to_string(),
260 serde_json::Value::Number(serde_json::Number::from(
261 language_settings.preferred_line_length,
262 )),
263 );
264 }
265 Some(options)
266 } else {
267 None
268 };
269
270 let plugins = located_plugins.into_iter().filter_map(|(plugin_name, located_plugin_path)| {
271 match located_plugin_path {
272 Some(path) => Some(path),
273 None => {
274 log::error!("Have not found plugin path for {plugin_name:?} inside {prettier_node_modules:?}");
275 None},
276 }
277 }).collect();
278 log::debug!("Formatting file {:?} with prettier, plugins :{plugins:?}, options: {prettier_options:?}", buffer.file().map(|f| f.full_path(cx)));
279
280 anyhow::Ok(FormatParams {
281 text: buffer.text(),
282 options: FormatOptions {
283 parser,
284 plugins,
285 path: buffer_path,
286 prettier_options,
287 },
288 })
289 }).context("prettier params calculation")?;
290 let response = local
291 .server
292 .request::<Format>(params)
293 .await
294 .context("prettier format request")?;
295 let diff_task = buffer.read_with(cx, |buffer, cx| buffer.diff(response.text, cx));
296 Ok(diff_task.await)
297 }
298 #[cfg(any(test, feature = "test-support"))]
299 Self::Test(_) => Ok(buffer
300 .read_with(cx, |buffer, cx| {
301 let formatted_text = buffer.text() + FORMAT_SUFFIX;
302 buffer.diff(formatted_text, cx)
303 })
304 .await),
305 }
306 }
307
308 pub async fn clear_cache(&self) -> anyhow::Result<()> {
309 match self {
310 Self::Real(local) => local
311 .server
312 .request::<ClearCache>(())
313 .await
314 .context("prettier clear cache"),
315 #[cfg(any(test, feature = "test-support"))]
316 Self::Test(_) => Ok(()),
317 }
318 }
319
320 pub fn server(&self) -> Option<&Arc<LanguageServer>> {
321 match self {
322 Self::Real(local) => Some(&local.server),
323 #[cfg(any(test, feature = "test-support"))]
324 Self::Test(_) => None,
325 }
326 }
327
328 pub fn is_default(&self) -> bool {
329 match self {
330 Self::Real(local) => local.default,
331 #[cfg(any(test, feature = "test-support"))]
332 Self::Test(test_prettier) => test_prettier.default,
333 }
334 }
335
336 pub fn prettier_dir(&self) -> &Path {
337 match self {
338 Self::Real(local) => &local.prettier_dir,
339 #[cfg(any(test, feature = "test-support"))]
340 Self::Test(test_prettier) => &test_prettier.prettier_dir,
341 }
342 }
343
344 pub fn worktree_id(&self) -> Option<usize> {
345 match self {
346 Self::Real(local) => local.worktree_id,
347 #[cfg(any(test, feature = "test-support"))]
348 Self::Test(test_prettier) => test_prettier.worktree_id,
349 }
350 }
351}
352
353async fn find_closest_prettier_dir(
354 paths_to_check: Vec<PathBuf>,
355 fs: &dyn Fs,
356) -> anyhow::Result<Option<PathBuf>> {
357 for path in paths_to_check {
358 let possible_package_json = path.join("package.json");
359 if let Some(package_json_metadata) = fs
360 .metadata(&possible_package_json)
361 .await
362 .with_context(|| format!("Fetching metadata for {possible_package_json:?}"))?
363 {
364 if !package_json_metadata.is_dir && !package_json_metadata.is_symlink {
365 let package_json_contents = fs
366 .load(&possible_package_json)
367 .await
368 .with_context(|| format!("reading {possible_package_json:?} file contents"))?;
369 if let Ok(json_contents) = serde_json::from_str::<HashMap<String, serde_json::Value>>(
370 &package_json_contents,
371 ) {
372 if let Some(serde_json::Value::Object(o)) = json_contents.get("dependencies") {
373 if o.contains_key(PRETTIER_PACKAGE_NAME) {
374 return Ok(Some(path));
375 }
376 }
377 if let Some(serde_json::Value::Object(o)) = json_contents.get("devDependencies")
378 {
379 if o.contains_key(PRETTIER_PACKAGE_NAME) {
380 return Ok(Some(path));
381 }
382 }
383 }
384 }
385 }
386
387 let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
388 if let Some(node_modules_location_metadata) = fs
389 .metadata(&possible_node_modules_location)
390 .await
391 .with_context(|| format!("fetching metadata for {possible_node_modules_location:?}"))?
392 {
393 if node_modules_location_metadata.is_dir {
394 return Ok(Some(path));
395 }
396 }
397 }
398 Ok(None)
399}
400
401enum Format {}
402
403#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
404#[serde(rename_all = "camelCase")]
405struct FormatParams {
406 text: String,
407 options: FormatOptions,
408}
409
410#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
411#[serde(rename_all = "camelCase")]
412struct FormatOptions {
413 plugins: Vec<PathBuf>,
414 parser: Option<String>,
415 #[serde(rename = "filepath")]
416 path: Option<PathBuf>,
417 prettier_options: Option<HashMap<String, serde_json::Value>>,
418}
419
420#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
421#[serde(rename_all = "camelCase")]
422struct FormatResult {
423 text: String,
424}
425
426impl lsp::request::Request for Format {
427 type Params = FormatParams;
428 type Result = FormatResult;
429 const METHOD: &'static str = "prettier/format";
430}
431
432enum ClearCache {}
433
434impl lsp::request::Request for ClearCache {
435 type Params = ();
436 type Result = ();
437 const METHOD: &'static str = "prettier/clear_cache";
438}