prettier.rs

  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        let paths_to_check = match starting_path.as_ref() {
 71            Some(starting_path) => {
 72                let worktree_root = starting_path
 73                    .worktree_root_path
 74                    .components()
 75                    .into_iter()
 76                    .take_while(|path_component| {
 77                        path_component.as_os_str().to_string_lossy() != "node_modules"
 78                    })
 79                    .collect::<PathBuf>();
 80
 81                if worktree_root != starting_path.worktree_root_path.as_ref() {
 82                    vec![worktree_root]
 83                } else {
 84                    let (worktree_root_metadata, start_path_metadata) = if starting_path
 85                        .starting_path
 86                        .as_ref()
 87                        == Path::new("")
 88                    {
 89                        let worktree_root_data =
 90                            fs.metadata(&worktree_root).await.with_context(|| {
 91                                format!(
 92                                    "FS metadata fetch for worktree root path {worktree_root:?}",
 93                                )
 94                            })?;
 95                        (worktree_root_data.unwrap_or_else(|| {
 96                            panic!("cannot query prettier for non existing worktree root at {worktree_root:?}")
 97                        }), None)
 98                    } else {
 99                        let full_starting_path = worktree_root.join(&starting_path.starting_path);
100                        let (worktree_root_data, start_path_data) = futures::try_join!(
101                            fs.metadata(&worktree_root),
102                            fs.metadata(&full_starting_path),
103                        )
104                        .with_context(|| {
105                            format!("FS metadata fetch for starting path {full_starting_path:?}",)
106                        })?;
107                        (
108                            worktree_root_data.unwrap_or_else(|| {
109                                panic!("cannot query prettier for non existing worktree root at {worktree_root:?}")
110                            }),
111                            start_path_data,
112                        )
113                    };
114
115                    match start_path_metadata {
116                        Some(start_path_metadata) => {
117                            anyhow::ensure!(worktree_root_metadata.is_dir,
118                                "For non-empty start path, worktree root {starting_path:?} should be a directory");
119                            anyhow::ensure!(
120                                !start_path_metadata.is_dir,
121                                "For non-empty start path, it should not be a directory {starting_path:?}"
122                            );
123                            anyhow::ensure!(
124                                !start_path_metadata.is_symlink,
125                                "For non-empty start path, it should not be a symlink {starting_path:?}"
126                            );
127
128                            let file_to_format = starting_path.starting_path.as_ref();
129                            let mut paths_to_check = VecDeque::from(vec![worktree_root.clone()]);
130                            let mut current_path = worktree_root;
131                            for path_component in file_to_format.components().into_iter() {
132                                current_path = current_path.join(path_component);
133                                paths_to_check.push_front(current_path.clone());
134                                if path_component.as_os_str().to_string_lossy() == "node_modules" {
135                                    break;
136                                }
137                            }
138                            paths_to_check.pop_front(); // last one is the file itself or node_modules, skip it
139                            Vec::from(paths_to_check)
140                        }
141                        None => {
142                            anyhow::ensure!(
143                                !worktree_root_metadata.is_dir,
144                                "For empty start path, worktree root should not be a directory {starting_path:?}"
145                            );
146                            anyhow::ensure!(
147                                !worktree_root_metadata.is_symlink,
148                                "For empty start path, worktree root should not be a symlink {starting_path:?}"
149                            );
150                            worktree_root
151                                .parent()
152                                .map(|path| vec![path.to_path_buf()])
153                                .unwrap_or_default()
154                        }
155                    }
156                }
157            }
158            None => Vec::new(),
159        };
160
161        match find_closest_prettier_dir(paths_to_check, fs.as_ref())
162            .await
163            .with_context(|| format!("finding prettier starting with {starting_path:?}"))?
164        {
165            Some(prettier_dir) => Ok(prettier_dir),
166            None => Ok(DEFAULT_PRETTIER_DIR.to_path_buf()),
167        }
168    }
169
170    #[cfg(any(test, feature = "test-support"))]
171    pub async fn start(
172        worktree_id: Option<usize>,
173        _: LanguageServerId,
174        prettier_dir: PathBuf,
175        _: Arc<dyn NodeRuntime>,
176        _: AsyncAppContext,
177    ) -> anyhow::Result<Self> {
178        Ok(
179            #[cfg(any(test, feature = "test-support"))]
180            Self::Test(TestPrettier {
181                worktree_id,
182                default: prettier_dir == DEFAULT_PRETTIER_DIR.as_path(),
183                prettier_dir,
184            }),
185        )
186    }
187
188    #[cfg(not(any(test, feature = "test-support")))]
189    pub async fn start(
190        worktree_id: Option<usize>,
191        server_id: LanguageServerId,
192        prettier_dir: PathBuf,
193        node: Arc<dyn NodeRuntime>,
194        cx: AsyncAppContext,
195    ) -> anyhow::Result<Self> {
196        use lsp::LanguageServerBinary;
197
198        let backgroud = cx.background();
199        anyhow::ensure!(
200            prettier_dir.is_dir(),
201            "Prettier dir {prettier_dir:?} is not a directory"
202        );
203        let prettier_server = DEFAULT_PRETTIER_DIR.join(PRETTIER_SERVER_FILE);
204        anyhow::ensure!(
205            prettier_server.is_file(),
206            "no prettier server package found at {prettier_server:?}"
207        );
208
209        let node_path = backgroud
210            .spawn(async move { node.binary_path().await })
211            .await?;
212        let server = LanguageServer::new(
213            Arc::new(parking_lot::Mutex::new(None)),
214            server_id,
215            LanguageServerBinary {
216                path: node_path,
217                arguments: vec![prettier_server.into(), prettier_dir.as_path().into()],
218            },
219            Path::new("/"),
220            None,
221            cx,
222        )
223        .context("prettier server creation")?;
224        let server = backgroud
225            .spawn(server.initialize(None))
226            .await
227            .context("prettier server initialization")?;
228        Ok(Self::Real(RealPrettier {
229            worktree_id,
230            server,
231            default: prettier_dir == DEFAULT_PRETTIER_DIR.as_path(),
232            prettier_dir,
233        }))
234    }
235
236    pub async fn format(
237        &self,
238        buffer: &ModelHandle<Buffer>,
239        buffer_path: Option<PathBuf>,
240        cx: &AsyncAppContext,
241    ) -> anyhow::Result<Diff> {
242        match self {
243            Self::Real(local) => {
244                let params = buffer.read_with(cx, |buffer, cx| {
245                    let buffer_language = buffer.language();
246                    let parser_with_plugins = buffer_language.and_then(|l| {
247                        let prettier_parser = l.prettier_parser_name()?;
248                        let mut prettier_plugins = l
249                            .lsp_adapters()
250                            .iter()
251                            .flat_map(|adapter| adapter.prettier_plugins())
252                            .collect::<Vec<_>>();
253                        prettier_plugins.dedup();
254                        Some((prettier_parser, prettier_plugins))
255                    });
256
257                    let prettier_node_modules = self.prettier_dir().join("node_modules");
258                    anyhow::ensure!(prettier_node_modules.is_dir(), "Prettier node_modules dir does not exist: {prettier_node_modules:?}");
259                    let plugin_name_into_path = |plugin_name: &str| {
260                        let prettier_plugin_dir = prettier_node_modules.join(plugin_name);
261                        for possible_plugin_path in [
262                            prettier_plugin_dir.join("dist").join("index.mjs"),
263                            prettier_plugin_dir.join("dist").join("index.js"),
264                            prettier_plugin_dir.join("dist").join("plugin.js"),
265                            prettier_plugin_dir.join("index.mjs"),
266                            prettier_plugin_dir.join("index.js"),
267                            prettier_plugin_dir.join("plugin.js"),
268                            prettier_plugin_dir,
269                        ] {
270                            if possible_plugin_path.is_file() {
271                                return Some(possible_plugin_path);
272                            }
273                        }
274                        None
275                    };
276                    let (parser, located_plugins) = match parser_with_plugins {
277                        Some((parser, plugins)) => {
278                            // Tailwind plugin requires being added last
279                            // https://github.com/tailwindlabs/prettier-plugin-tailwindcss#compatibility-with-other-prettier-plugins
280                            let mut add_tailwind_back = false;
281
282                            let mut plugins = plugins.into_iter().filter(|&&plugin_name| {
283                                if plugin_name == TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME {
284                                    add_tailwind_back = true;
285                                    false
286                                } else {
287                                    true
288                                }
289                            }).map(|plugin_name| (plugin_name, plugin_name_into_path(plugin_name))).collect::<Vec<_>>();
290                            if add_tailwind_back {
291                                plugins.push((&TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME, plugin_name_into_path(TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME)));
292                            }
293                            (Some(parser.to_string()), plugins)
294                        },
295                        None => (None, Vec::new()),
296                    };
297
298                    let prettier_options = if self.is_default() {
299                        let language_settings = language_settings(buffer_language, buffer.file(), cx);
300                        let mut options = language_settings.prettier.clone();
301                        if !options.contains_key("tabWidth") {
302                            options.insert(
303                                "tabWidth".to_string(),
304                                serde_json::Value::Number(serde_json::Number::from(
305                                    language_settings.tab_size.get(),
306                                )),
307                            );
308                        }
309                        if !options.contains_key("printWidth") {
310                            options.insert(
311                                "printWidth".to_string(),
312                                serde_json::Value::Number(serde_json::Number::from(
313                                    language_settings.preferred_line_length,
314                                )),
315                            );
316                        }
317                        Some(options)
318                    } else {
319                        None
320                    };
321
322                    let plugins = located_plugins.into_iter().filter_map(|(plugin_name, located_plugin_path)| {
323                        match located_plugin_path {
324                            Some(path) => Some(path),
325                            None => {
326                                log::error!("Have not found plugin path for {plugin_name:?} inside {prettier_node_modules:?}");
327                                None},
328                        }
329                    }).collect();
330                    log::debug!("Formatting file {:?} with prettier, plugins :{plugins:?}, options: {prettier_options:?}", buffer.file().map(|f| f.full_path(cx)));
331
332                    anyhow::Ok(FormatParams {
333                        text: buffer.text(),
334                        options: FormatOptions {
335                            parser,
336                            plugins,
337                            path: buffer_path,
338                            prettier_options,
339                        },
340                    })
341                }).context("prettier params calculation")?;
342                let response = local
343                    .server
344                    .request::<Format>(params)
345                    .await
346                    .context("prettier format request")?;
347                let diff_task = buffer.read_with(cx, |buffer, cx| buffer.diff(response.text, cx));
348                Ok(diff_task.await)
349            }
350            #[cfg(any(test, feature = "test-support"))]
351            Self::Test(_) => Ok(buffer
352                .read_with(cx, |buffer, cx| {
353                    let formatted_text = buffer.text() + FORMAT_SUFFIX;
354                    buffer.diff(formatted_text, cx)
355                })
356                .await),
357        }
358    }
359
360    pub async fn clear_cache(&self) -> anyhow::Result<()> {
361        match self {
362            Self::Real(local) => local
363                .server
364                .request::<ClearCache>(())
365                .await
366                .context("prettier clear cache"),
367            #[cfg(any(test, feature = "test-support"))]
368            Self::Test(_) => Ok(()),
369        }
370    }
371
372    pub fn server(&self) -> Option<&Arc<LanguageServer>> {
373        match self {
374            Self::Real(local) => Some(&local.server),
375            #[cfg(any(test, feature = "test-support"))]
376            Self::Test(_) => None,
377        }
378    }
379
380    pub fn is_default(&self) -> bool {
381        match self {
382            Self::Real(local) => local.default,
383            #[cfg(any(test, feature = "test-support"))]
384            Self::Test(test_prettier) => test_prettier.default,
385        }
386    }
387
388    pub fn prettier_dir(&self) -> &Path {
389        match self {
390            Self::Real(local) => &local.prettier_dir,
391            #[cfg(any(test, feature = "test-support"))]
392            Self::Test(test_prettier) => &test_prettier.prettier_dir,
393        }
394    }
395
396    pub fn worktree_id(&self) -> Option<usize> {
397        match self {
398            Self::Real(local) => local.worktree_id,
399            #[cfg(any(test, feature = "test-support"))]
400            Self::Test(test_prettier) => test_prettier.worktree_id,
401        }
402    }
403}
404
405async fn find_closest_prettier_dir(
406    paths_to_check: Vec<PathBuf>,
407    fs: &dyn Fs,
408) -> anyhow::Result<Option<PathBuf>> {
409    for path in paths_to_check {
410        let possible_package_json = path.join("package.json");
411        if let Some(package_json_metadata) = fs
412            .metadata(&possible_package_json)
413            .await
414            .with_context(|| format!("Fetching metadata for {possible_package_json:?}"))?
415        {
416            if !package_json_metadata.is_dir && !package_json_metadata.is_symlink {
417                let package_json_contents = fs
418                    .load(&possible_package_json)
419                    .await
420                    .with_context(|| format!("reading {possible_package_json:?} file contents"))?;
421                if let Ok(json_contents) = serde_json::from_str::<HashMap<String, serde_json::Value>>(
422                    &package_json_contents,
423                ) {
424                    if let Some(serde_json::Value::Object(o)) = json_contents.get("dependencies") {
425                        if o.contains_key(PRETTIER_PACKAGE_NAME) {
426                            return Ok(Some(path));
427                        }
428                    }
429                    if let Some(serde_json::Value::Object(o)) = json_contents.get("devDependencies")
430                    {
431                        if o.contains_key(PRETTIER_PACKAGE_NAME) {
432                            return Ok(Some(path));
433                        }
434                    }
435                }
436            }
437        }
438
439        let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
440        if let Some(node_modules_location_metadata) = fs
441            .metadata(&possible_node_modules_location)
442            .await
443            .with_context(|| format!("fetching metadata for {possible_node_modules_location:?}"))?
444        {
445            if node_modules_location_metadata.is_dir {
446                return Ok(Some(path));
447            }
448        }
449    }
450    Ok(None)
451}
452
453enum Format {}
454
455#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase")]
457struct FormatParams {
458    text: String,
459    options: FormatOptions,
460}
461
462#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
463#[serde(rename_all = "camelCase")]
464struct FormatOptions {
465    plugins: Vec<PathBuf>,
466    parser: Option<String>,
467    #[serde(rename = "filepath")]
468    path: Option<PathBuf>,
469    prettier_options: Option<HashMap<String, serde_json::Value>>,
470}
471
472#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
473#[serde(rename_all = "camelCase")]
474struct FormatResult {
475    text: String,
476}
477
478impl lsp::request::Request for Format {
479    type Params = FormatParams;
480    type Result = FormatResult;
481    const METHOD: &'static str = "prettier/format";
482}
483
484enum ClearCache {}
485
486impl lsp::request::Request for ClearCache {
487    type Params = ();
488    type Result = ();
489    const METHOD: &'static str = "prettier/clear_cache";
490}