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_data:?}")
 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_data:?}")
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            server_id,
214            LanguageServerBinary {
215                path: node_path,
216                arguments: vec![prettier_server.into(), prettier_dir.as_path().into()],
217            },
218            Path::new("/"),
219            None,
220            cx,
221        )
222        .context("prettier server creation")?;
223        let server = backgroud
224            .spawn(server.initialize(None))
225            .await
226            .context("prettier server initialization")?;
227        Ok(Self::Real(RealPrettier {
228            worktree_id,
229            server,
230            default: prettier_dir == DEFAULT_PRETTIER_DIR.as_path(),
231            prettier_dir,
232        }))
233    }
234
235    pub async fn format(
236        &self,
237        buffer: &ModelHandle<Buffer>,
238        buffer_path: Option<PathBuf>,
239        cx: &AsyncAppContext,
240    ) -> anyhow::Result<Diff> {
241        match self {
242            Self::Real(local) => {
243                let params = buffer.read_with(cx, |buffer, cx| {
244                    let buffer_language = buffer.language();
245                    let parser_with_plugins = buffer_language.and_then(|l| {
246                        let prettier_parser = l.prettier_parser_name()?;
247                        let mut prettier_plugins = l
248                            .lsp_adapters()
249                            .iter()
250                            .flat_map(|adapter| adapter.prettier_plugins())
251                            .collect::<Vec<_>>();
252                        prettier_plugins.dedup();
253                        Some((prettier_parser, prettier_plugins))
254                    });
255
256                    let prettier_node_modules = self.prettier_dir().join("node_modules");
257                    anyhow::ensure!(prettier_node_modules.is_dir(), "Prettier node_modules dir does not exist: {prettier_node_modules:?}");
258                    let plugin_name_into_path = |plugin_name: &str| {
259                        let prettier_plugin_dir = prettier_node_modules.join(plugin_name);
260                        for possible_plugin_path in [
261                            prettier_plugin_dir.join("dist").join("index.mjs"),
262                            prettier_plugin_dir.join("dist").join("index.js"),
263                            prettier_plugin_dir.join("dist").join("plugin.js"),
264                            prettier_plugin_dir.join("index.mjs"),
265                            prettier_plugin_dir.join("index.js"),
266                            prettier_plugin_dir.join("plugin.js"),
267                            prettier_plugin_dir,
268                        ] {
269                            if possible_plugin_path.is_file() {
270                                return Some(possible_plugin_path);
271                            }
272                        }
273                        None
274                    };
275                    let (parser, located_plugins) = match parser_with_plugins {
276                        Some((parser, plugins)) => {
277                            // Tailwind plugin requires being added last
278                            // https://github.com/tailwindlabs/prettier-plugin-tailwindcss#compatibility-with-other-prettier-plugins
279                            let mut add_tailwind_back = false;
280
281                            let mut plugins = plugins.into_iter().filter(|&&plugin_name| {
282                                if plugin_name == TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME {
283                                    add_tailwind_back = true;
284                                    false
285                                } else {
286                                    true
287                                }
288                            }).map(|plugin_name| (plugin_name, plugin_name_into_path(plugin_name))).collect::<Vec<_>>();
289                            if add_tailwind_back {
290                                plugins.push((&TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME, plugin_name_into_path(TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME)));
291                            }
292                            (Some(parser.to_string()), plugins)
293                        },
294                        None => (None, Vec::new()),
295                    };
296
297                    let prettier_options = if self.is_default() {
298                        let language_settings = language_settings(buffer_language, buffer.file(), cx);
299                        let mut options = language_settings.prettier.clone();
300                        if !options.contains_key("tabWidth") {
301                            options.insert(
302                                "tabWidth".to_string(),
303                                serde_json::Value::Number(serde_json::Number::from(
304                                    language_settings.tab_size.get(),
305                                )),
306                            );
307                        }
308                        if !options.contains_key("printWidth") {
309                            options.insert(
310                                "printWidth".to_string(),
311                                serde_json::Value::Number(serde_json::Number::from(
312                                    language_settings.preferred_line_length,
313                                )),
314                            );
315                        }
316                        Some(options)
317                    } else {
318                        None
319                    };
320
321                    let plugins = located_plugins.into_iter().filter_map(|(plugin_name, located_plugin_path)| {
322                        match located_plugin_path {
323                            Some(path) => Some(path),
324                            None => {
325                                log::error!("Have not found plugin path for {plugin_name:?} inside {prettier_node_modules:?}");
326                                None},
327                        }
328                    }).collect();
329                    log::debug!("Formatting file {:?} with prettier, plugins :{plugins:?}, options: {prettier_options:?}", buffer.file().map(|f| f.full_path(cx)));
330
331                    anyhow::Ok(FormatParams {
332                        text: buffer.text(),
333                        options: FormatOptions {
334                            parser,
335                            plugins,
336                            path: buffer_path,
337                            prettier_options,
338                        },
339                    })
340                }).context("prettier params calculation")?;
341                let response = local
342                    .server
343                    .request::<Format>(params)
344                    .await
345                    .context("prettier format request")?;
346                let diff_task = buffer.read_with(cx, |buffer, cx| buffer.diff(response.text, cx));
347                Ok(diff_task.await)
348            }
349            #[cfg(any(test, feature = "test-support"))]
350            Self::Test(_) => Ok(buffer
351                .read_with(cx, |buffer, cx| {
352                    let formatted_text = buffer.text() + FORMAT_SUFFIX;
353                    buffer.diff(formatted_text, cx)
354                })
355                .await),
356        }
357    }
358
359    pub async fn clear_cache(&self) -> anyhow::Result<()> {
360        match self {
361            Self::Real(local) => local
362                .server
363                .request::<ClearCache>(())
364                .await
365                .context("prettier clear cache"),
366            #[cfg(any(test, feature = "test-support"))]
367            Self::Test(_) => Ok(()),
368        }
369    }
370
371    pub fn server(&self) -> Option<&Arc<LanguageServer>> {
372        match self {
373            Self::Real(local) => Some(&local.server),
374            #[cfg(any(test, feature = "test-support"))]
375            Self::Test(_) => None,
376        }
377    }
378
379    pub fn is_default(&self) -> bool {
380        match self {
381            Self::Real(local) => local.default,
382            #[cfg(any(test, feature = "test-support"))]
383            Self::Test(test_prettier) => test_prettier.default,
384        }
385    }
386
387    pub fn prettier_dir(&self) -> &Path {
388        match self {
389            Self::Real(local) => &local.prettier_dir,
390            #[cfg(any(test, feature = "test-support"))]
391            Self::Test(test_prettier) => &test_prettier.prettier_dir,
392        }
393    }
394
395    pub fn worktree_id(&self) -> Option<usize> {
396        match self {
397            Self::Real(local) => local.worktree_id,
398            #[cfg(any(test, feature = "test-support"))]
399            Self::Test(test_prettier) => test_prettier.worktree_id,
400        }
401    }
402}
403
404async fn find_closest_prettier_dir(
405    paths_to_check: Vec<PathBuf>,
406    fs: &dyn Fs,
407) -> anyhow::Result<Option<PathBuf>> {
408    for path in paths_to_check {
409        let possible_package_json = path.join("package.json");
410        if let Some(package_json_metadata) = fs
411            .metadata(&possible_package_json)
412            .await
413            .with_context(|| format!("Fetching metadata for {possible_package_json:?}"))?
414        {
415            if !package_json_metadata.is_dir && !package_json_metadata.is_symlink {
416                let package_json_contents = fs
417                    .load(&possible_package_json)
418                    .await
419                    .with_context(|| format!("reading {possible_package_json:?} file contents"))?;
420                if let Ok(json_contents) = serde_json::from_str::<HashMap<String, serde_json::Value>>(
421                    &package_json_contents,
422                ) {
423                    if let Some(serde_json::Value::Object(o)) = json_contents.get("dependencies") {
424                        if o.contains_key(PRETTIER_PACKAGE_NAME) {
425                            return Ok(Some(path));
426                        }
427                    }
428                    if let Some(serde_json::Value::Object(o)) = json_contents.get("devDependencies")
429                    {
430                        if o.contains_key(PRETTIER_PACKAGE_NAME) {
431                            return Ok(Some(path));
432                        }
433                    }
434                }
435            }
436        }
437
438        let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
439        if let Some(node_modules_location_metadata) = fs
440            .metadata(&possible_node_modules_location)
441            .await
442            .with_context(|| format!("fetching metadata for {possible_node_modules_location:?}"))?
443        {
444            if node_modules_location_metadata.is_dir {
445                return Ok(Some(path));
446            }
447        }
448    }
449    Ok(None)
450}
451
452enum Format {}
453
454#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
455#[serde(rename_all = "camelCase")]
456struct FormatParams {
457    text: String,
458    options: FormatOptions,
459}
460
461#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
462#[serde(rename_all = "camelCase")]
463struct FormatOptions {
464    plugins: Vec<PathBuf>,
465    parser: Option<String>,
466    #[serde(rename = "filepath")]
467    path: Option<PathBuf>,
468    prettier_options: Option<HashMap<String, serde_json::Value>>,
469}
470
471#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
472#[serde(rename_all = "camelCase")]
473struct FormatResult {
474    text: String,
475}
476
477impl lsp::request::Request for Format {
478    type Params = FormatParams;
479    type Result = FormatResult;
480    const METHOD: &'static str = "prettier/format";
481}
482
483enum ClearCache {}
484
485impl lsp::request::Request for ClearCache {
486    type Params = ();
487    type Result = ();
488    const METHOD: &'static str = "prettier/clear_cache";
489}