prettier.rs

  1use anyhow::{anyhow, Context};
  2use collections::{HashMap, HashSet};
  3use fs::Fs;
  4use gpui::{AsyncAppContext, Model};
  5use language::{language_settings::language_settings, Buffer, Diff};
  6use lsp::{LanguageServer, LanguageServerId};
  7use node_runtime::NodeRuntime;
  8use paths::default_prettier_dir;
  9use serde::{Deserialize, Serialize};
 10use std::{
 11    ops::ControlFlow,
 12    path::{Path, PathBuf},
 13    sync::Arc,
 14};
 15use util::paths::PathMatcher;
 16
 17#[derive(Clone)]
 18pub enum Prettier {
 19    Real(RealPrettier),
 20    #[cfg(any(test, feature = "test-support"))]
 21    Test(TestPrettier),
 22}
 23
 24#[derive(Clone)]
 25pub struct RealPrettier {
 26    default: bool,
 27    prettier_dir: PathBuf,
 28    server: Arc<LanguageServer>,
 29}
 30
 31#[cfg(any(test, feature = "test-support"))]
 32#[derive(Clone)]
 33pub struct TestPrettier {
 34    prettier_dir: PathBuf,
 35    default: bool,
 36}
 37
 38pub const FAIL_THRESHOLD: usize = 4;
 39pub const PRETTIER_SERVER_FILE: &str = "prettier_server.js";
 40pub const PRETTIER_SERVER_JS: &str = include_str!("./prettier_server.js");
 41const PRETTIER_PACKAGE_NAME: &str = "prettier";
 42const TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME: &str = "prettier-plugin-tailwindcss";
 43
 44#[cfg(any(test, feature = "test-support"))]
 45pub const FORMAT_SUFFIX: &str = "\nformatted by test prettier";
 46
 47impl Prettier {
 48    pub const CONFIG_FILE_NAMES: &'static [&'static str] = &[
 49        ".prettierrc",
 50        ".prettierrc.json",
 51        ".prettierrc.json5",
 52        ".prettierrc.yaml",
 53        ".prettierrc.yml",
 54        ".prettierrc.toml",
 55        ".prettierrc.js",
 56        ".prettierrc.cjs",
 57        "package.json",
 58        "prettier.config.js",
 59        "prettier.config.cjs",
 60        ".editorconfig",
 61    ];
 62
 63    pub async fn locate_prettier_installation(
 64        fs: &dyn Fs,
 65        installed_prettiers: &HashSet<PathBuf>,
 66        locate_from: &Path,
 67    ) -> anyhow::Result<ControlFlow<(), Option<PathBuf>>> {
 68        let mut path_to_check = locate_from
 69            .components()
 70            .take_while(|component| component.as_os_str().to_string_lossy() != "node_modules")
 71            .collect::<PathBuf>();
 72        if path_to_check != locate_from {
 73            log::debug!(
 74                "Skipping prettier location for path {path_to_check:?} that is inside node_modules"
 75            );
 76            return Ok(ControlFlow::Break(()));
 77        }
 78        let path_to_check_metadata = fs
 79            .metadata(&path_to_check)
 80            .await
 81            .with_context(|| format!("failed to get metadata for initial path {path_to_check:?}"))?
 82            .with_context(|| format!("empty metadata for initial path {path_to_check:?}"))?;
 83        if !path_to_check_metadata.is_dir {
 84            path_to_check.pop();
 85        }
 86
 87        let mut project_path_with_prettier_dependency = None;
 88        loop {
 89            if installed_prettiers.contains(&path_to_check) {
 90                log::debug!("Found prettier path {path_to_check:?} in installed prettiers");
 91                return Ok(ControlFlow::Continue(Some(path_to_check)));
 92            } else if let Some(package_json_contents) =
 93                read_package_json(fs, &path_to_check).await?
 94            {
 95                if has_prettier_in_package_json(&package_json_contents) {
 96                    if has_prettier_in_node_modules(fs, &path_to_check).await? {
 97                        log::debug!("Found prettier path {path_to_check:?} in both package.json and node_modules");
 98                        return Ok(ControlFlow::Continue(Some(path_to_check)));
 99                    } else if project_path_with_prettier_dependency.is_none() {
100                        project_path_with_prettier_dependency = Some(path_to_check.clone());
101                    }
102                } else {
103                    match package_json_contents.get("workspaces") {
104                            Some(serde_json::Value::Array(workspaces)) => {
105                                match &project_path_with_prettier_dependency {
106                                    Some(project_path_with_prettier_dependency) => {
107                                        let subproject_path = project_path_with_prettier_dependency.strip_prefix(&path_to_check).expect("traversing path parents, should be able to strip prefix");
108                                        if workspaces.iter().filter_map(|value| {
109                                            if let serde_json::Value::String(s) = value {
110                                                Some(s.clone())
111                                            } else {
112                                                log::warn!("Skipping non-string 'workspaces' value: {value:?}");
113                                                None
114                                            }
115                                        }).any(|workspace_definition| {
116                                            if let Some(path_matcher) = PathMatcher::new(&[workspace_definition.clone()]).ok() {
117                                                path_matcher.is_match(subproject_path)
118                                            } else {
119                                                workspace_definition == subproject_path.to_string_lossy()
120                                            }
121                                        }) {
122                                            anyhow::ensure!(has_prettier_in_node_modules(fs, &path_to_check).await?, "Found prettier path {path_to_check:?} in the workspace root for project in {project_path_with_prettier_dependency:?}, but it's not installed into workspace root's node_modules");
123                                            log::info!("Found prettier path {path_to_check:?} in the workspace root for project in {project_path_with_prettier_dependency:?}");
124                                            return Ok(ControlFlow::Continue(Some(path_to_check)));
125                                        } else {
126                                            log::warn!("Skipping path {path_to_check:?} that has prettier in its 'node_modules' subdirectory, but is not included in its package.json workspaces {workspaces:?}");
127                                        }
128                                    }
129                                    None => {
130                                        log::warn!("Skipping path {path_to_check:?} that has prettier in its 'node_modules' subdirectory, but has no prettier in its package.json");
131                                    }
132                                }
133                            },
134                            Some(unknown) => log::error!("Failed to parse workspaces for {path_to_check:?} from package.json, got {unknown:?}. Skipping."),
135                            None => log::warn!("Skipping path {path_to_check:?} that has no prettier dependency and no workspaces section in its package.json"),
136                        }
137                }
138            }
139
140            if !path_to_check.pop() {
141                match project_path_with_prettier_dependency {
142                    Some(closest_prettier_discovered) => {
143                        anyhow::bail!("No prettier found in node_modules for ancestors of {locate_from:?}, but discovered prettier package.json dependency in {closest_prettier_discovered:?}")
144                    }
145                    None => {
146                        log::debug!("Found no prettier in ancestors of {locate_from:?}");
147                        return Ok(ControlFlow::Continue(None));
148                    }
149                }
150            }
151        }
152    }
153
154    #[cfg(any(test, feature = "test-support"))]
155    pub async fn start(
156        _: LanguageServerId,
157        prettier_dir: PathBuf,
158        _: Arc<dyn NodeRuntime>,
159        _: AsyncAppContext,
160    ) -> anyhow::Result<Self> {
161        Ok(Self::Test(TestPrettier {
162            default: prettier_dir == default_prettier_dir().as_path(),
163            prettier_dir,
164        }))
165    }
166
167    #[cfg(not(any(test, feature = "test-support")))]
168    pub async fn start(
169        server_id: LanguageServerId,
170        prettier_dir: PathBuf,
171        node: Arc<dyn NodeRuntime>,
172        cx: AsyncAppContext,
173    ) -> anyhow::Result<Self> {
174        use lsp::LanguageServerBinary;
175
176        let executor = cx.background_executor().clone();
177        anyhow::ensure!(
178            prettier_dir.is_dir(),
179            "Prettier dir {prettier_dir:?} is not a directory"
180        );
181        let prettier_server = default_prettier_dir().join(PRETTIER_SERVER_FILE);
182        anyhow::ensure!(
183            prettier_server.is_file(),
184            "no prettier server package found at {prettier_server:?}"
185        );
186
187        let node_path = executor
188            .spawn(async move { node.binary_path().await })
189            .await?;
190        let server = LanguageServer::new(
191            Arc::new(parking_lot::Mutex::new(None)),
192            server_id,
193            LanguageServerBinary {
194                path: node_path,
195                arguments: vec![prettier_server.into(), prettier_dir.as_path().into()],
196                env: None,
197            },
198            &prettier_dir,
199            None,
200            cx.clone(),
201        )
202        .context("prettier server creation")?;
203        let server = cx
204            .update(|cx| executor.spawn(server.initialize(None, cx)))?
205            .await
206            .context("prettier server initialization")?;
207        Ok(Self::Real(RealPrettier {
208            server,
209            default: prettier_dir == default_prettier_dir().as_path(),
210            prettier_dir,
211        }))
212    }
213
214    pub async fn format(
215        &self,
216        buffer: &Model<Buffer>,
217        buffer_path: Option<PathBuf>,
218        cx: &mut AsyncAppContext,
219    ) -> anyhow::Result<Diff> {
220        match self {
221            Self::Real(local) => {
222                let params = buffer
223                    .update(cx, |buffer, cx| {
224                        let buffer_language = buffer.language();
225                        let language_settings = language_settings(buffer_language, buffer.file(), cx);
226                        let prettier_settings = &language_settings.prettier;
227                        anyhow::ensure!(
228                            prettier_settings.allowed,
229                            "Cannot format: prettier is not allowed for language {buffer_language:?}"
230                        );
231                        let prettier_node_modules = self.prettier_dir().join("node_modules");
232                        anyhow::ensure!(
233                            prettier_node_modules.is_dir(),
234                            "Prettier node_modules dir does not exist: {prettier_node_modules:?}"
235                        );
236                        let plugin_name_into_path = |plugin_name: &str| {
237                            let prettier_plugin_dir = prettier_node_modules.join(plugin_name);
238                            [
239                                prettier_plugin_dir.join("dist").join("index.mjs"),
240                                prettier_plugin_dir.join("dist").join("index.js"),
241                                prettier_plugin_dir.join("dist").join("plugin.js"),
242                                prettier_plugin_dir.join("index.mjs"),
243                                prettier_plugin_dir.join("index.js"),
244                                prettier_plugin_dir.join("plugin.js"),
245                                // this one is for @prettier/plugin-php
246                                prettier_plugin_dir.join("standalone.js"),
247                                prettier_plugin_dir,
248                            ]
249                            .into_iter()
250                            .find(|possible_plugin_path| possible_plugin_path.is_file())
251                        };
252
253                        // Tailwind plugin requires being added last
254                        // https://github.com/tailwindlabs/prettier-plugin-tailwindcss#compatibility-with-other-prettier-plugins
255                        let mut add_tailwind_back = false;
256
257                        let mut located_plugins = prettier_settings.plugins.iter()
258                            .filter(|plugin_name| {
259                                if plugin_name.as_str() == TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME {
260                                    add_tailwind_back = true;
261                                    false
262                                } else {
263                                    true
264                                }
265                            })
266                            .map(|plugin_name| {
267                                let plugin_path = plugin_name_into_path(plugin_name);
268                                (plugin_name.clone(), plugin_path)
269                            })
270                            .collect::<Vec<_>>();
271                        if add_tailwind_back {
272                            located_plugins.push((
273                                TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME.to_owned(),
274                                plugin_name_into_path(TAILWIND_PRETTIER_PLUGIN_PACKAGE_NAME),
275                            ));
276                        }
277
278                        let prettier_options = if self.is_default() {
279                            let mut options = prettier_settings.options.clone();
280                            if !options.contains_key("tabWidth") {
281                                options.insert(
282                                    "tabWidth".to_string(),
283                                    serde_json::Value::Number(serde_json::Number::from(
284                                        language_settings.tab_size.get(),
285                                    )),
286                                );
287                            }
288                            if !options.contains_key("printWidth") {
289                                options.insert(
290                                    "printWidth".to_string(),
291                                    serde_json::Value::Number(serde_json::Number::from(
292                                        language_settings.preferred_line_length,
293                                    )),
294                                );
295                            }
296                            if !options.contains_key("useTabs") {
297                                options.insert(
298                                    "useTabs".to_string(),
299                                    serde_json::Value::Bool(language_settings.hard_tabs),
300                                );
301                            }
302                            Some(options)
303                        } else {
304                            None
305                        };
306
307                        let plugins = located_plugins
308                            .into_iter()
309                            .filter_map(|(plugin_name, located_plugin_path)| {
310                                match located_plugin_path {
311                                    Some(path) => Some(path),
312                                    None => {
313                                        log::error!("Have not found plugin path for {plugin_name:?} inside {prettier_node_modules:?}");
314                                        None
315                                    }
316                                }
317                            })
318                            .collect();
319
320                        let prettier_parser = prettier_settings.parser.as_deref().or_else(|| buffer_language.and_then(|language| language.prettier_parser_name()));
321
322                        if prettier_parser.is_none() && buffer_path.is_none() {
323                            log::error!("Formatting unsaved file with prettier failed. No prettier parser configured for language {buffer_language:?}");
324                            return Err(anyhow!("Cannot determine prettier parser for unsaved file"));
325                        }
326
327                        log::debug!(
328                            "Formatting file {:?} with prettier, plugins :{:?}, options: {:?}",
329                            buffer.file().map(|f| f.full_path(cx)),
330                            plugins,
331                            prettier_options,
332                        );
333
334                        anyhow::Ok(FormatParams {
335                            text: buffer.text(),
336                            options: FormatOptions {
337                                parser: prettier_parser.map(ToOwned::to_owned),
338                                plugins,
339                                path: buffer_path,
340                                prettier_options,
341                            },
342                        })
343                    })?
344                    .context("prettier params calculation")?;
345
346                let response = local
347                    .server
348                    .request::<Format>(params)
349                    .await
350                    .context("prettier format request")?;
351                let diff_task = buffer.update(cx, |buffer, cx| buffer.diff(response.text, cx))?;
352                Ok(diff_task.await)
353            }
354            #[cfg(any(test, feature = "test-support"))]
355            Self::Test(_) => Ok(buffer
356                .update(cx, |buffer, cx| {
357                    match buffer
358                        .language()
359                        .map(|language| language.lsp_id())
360                        .as_deref()
361                    {
362                        Some("rust") => anyhow::bail!("prettier does not support Rust"),
363                        Some(_other) => {
364                            let formatted_text = buffer.text() + FORMAT_SUFFIX;
365                            Ok(buffer.diff(formatted_text, cx))
366                        }
367                        None => panic!("Should not format buffer without a language with prettier"),
368                    }
369                })??
370                .await),
371        }
372    }
373
374    pub async fn clear_cache(&self) -> anyhow::Result<()> {
375        match self {
376            Self::Real(local) => local
377                .server
378                .request::<ClearCache>(())
379                .await
380                .context("prettier clear cache"),
381            #[cfg(any(test, feature = "test-support"))]
382            Self::Test(_) => Ok(()),
383        }
384    }
385
386    pub fn server(&self) -> Option<&Arc<LanguageServer>> {
387        match self {
388            Self::Real(local) => Some(&local.server),
389            #[cfg(any(test, feature = "test-support"))]
390            Self::Test(_) => None,
391        }
392    }
393
394    pub fn is_default(&self) -> bool {
395        match self {
396            Self::Real(local) => local.default,
397            #[cfg(any(test, feature = "test-support"))]
398            Self::Test(test_prettier) => test_prettier.default,
399        }
400    }
401
402    pub fn prettier_dir(&self) -> &Path {
403        match self {
404            Self::Real(local) => &local.prettier_dir,
405            #[cfg(any(test, feature = "test-support"))]
406            Self::Test(test_prettier) => &test_prettier.prettier_dir,
407        }
408    }
409}
410
411async fn has_prettier_in_node_modules(fs: &dyn Fs, path: &Path) -> anyhow::Result<bool> {
412    let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
413    if let Some(node_modules_location_metadata) = fs
414        .metadata(&possible_node_modules_location)
415        .await
416        .with_context(|| format!("fetching metadata for {possible_node_modules_location:?}"))?
417    {
418        return Ok(node_modules_location_metadata.is_dir);
419    }
420    Ok(false)
421}
422
423async fn read_package_json(
424    fs: &dyn Fs,
425    path: &Path,
426) -> anyhow::Result<Option<HashMap<String, serde_json::Value>>> {
427    let possible_package_json = path.join("package.json");
428    if let Some(package_json_metadata) = fs
429        .metadata(&possible_package_json)
430        .await
431        .with_context(|| format!("fetching metadata for package json {possible_package_json:?}"))?
432    {
433        if !package_json_metadata.is_dir && !package_json_metadata.is_symlink {
434            let package_json_contents = fs
435                .load(&possible_package_json)
436                .await
437                .with_context(|| format!("reading {possible_package_json:?} file contents"))?;
438            return serde_json::from_str::<HashMap<String, serde_json::Value>>(
439                &package_json_contents,
440            )
441            .map(Some)
442            .with_context(|| format!("parsing {possible_package_json:?} file contents"));
443        }
444    }
445    Ok(None)
446}
447
448fn has_prettier_in_package_json(
449    package_json_contents: &HashMap<String, serde_json::Value>,
450) -> bool {
451    if let Some(serde_json::Value::Object(o)) = package_json_contents.get("dependencies") {
452        if o.contains_key(PRETTIER_PACKAGE_NAME) {
453            return true;
454        }
455    }
456    if let Some(serde_json::Value::Object(o)) = package_json_contents.get("devDependencies") {
457        if o.contains_key(PRETTIER_PACKAGE_NAME) {
458            return true;
459        }
460    }
461    false
462}
463
464enum Format {}
465
466#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
467#[serde(rename_all = "camelCase")]
468struct FormatParams {
469    text: String,
470    options: FormatOptions,
471}
472
473#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
474#[serde(rename_all = "camelCase")]
475struct FormatOptions {
476    plugins: Vec<PathBuf>,
477    parser: Option<String>,
478    #[serde(rename = "filepath")]
479    path: Option<PathBuf>,
480    prettier_options: Option<HashMap<String, serde_json::Value>>,
481}
482
483#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
484#[serde(rename_all = "camelCase")]
485struct FormatResult {
486    text: String,
487}
488
489impl lsp::request::Request for Format {
490    type Params = FormatParams;
491    type Result = FormatResult;
492    const METHOD: &'static str = "prettier/format";
493}
494
495enum ClearCache {}
496
497impl lsp::request::Request for ClearCache {
498    type Params = ();
499    type Result = ();
500    const METHOD: &'static str = "prettier/clear_cache";
501}
502
503#[cfg(test)]
504mod tests {
505    use fs::FakeFs;
506    use serde_json::json;
507
508    use super::*;
509
510    #[gpui::test]
511    async fn test_prettier_lookup_finds_nothing(cx: &mut gpui::TestAppContext) {
512        let fs = FakeFs::new(cx.executor());
513        fs.insert_tree(
514            "/root",
515            json!({
516                ".config": {
517                    "zed": {
518                        "settings.json": r#"{ "formatter": "auto" }"#,
519                    },
520                },
521                "work": {
522                    "project": {
523                        "src": {
524                            "index.js": "// index.js file contents",
525                        },
526                        "node_modules": {
527                            "expect": {
528                                "build": {
529                                    "print.js": "// print.js file contents",
530                                },
531                                "package.json": r#"{
532                                    "devDependencies": {
533                                        "prettier": "2.5.1"
534                                    }
535                                }"#,
536                            },
537                            "prettier": {
538                                "index.js": "// Dummy prettier package file",
539                            },
540                        },
541                        "package.json": r#"{}"#
542                    },
543                }
544            }),
545        )
546        .await;
547
548        assert!(
549            matches!(
550                Prettier::locate_prettier_installation(
551                    fs.as_ref(),
552                    &HashSet::default(),
553                    Path::new("/root/.config/zed/settings.json"),
554                )
555                .await,
556                Ok(ControlFlow::Continue(None))
557            ),
558            "Should successfully find no prettier for path hierarchy without it"
559        );
560        assert!(
561            matches!(
562                Prettier::locate_prettier_installation(
563                    fs.as_ref(),
564                    &HashSet::default(),
565                    Path::new("/root/work/project/src/index.js")
566                )
567                .await,
568                Ok(ControlFlow::Continue(None))
569            ),
570            "Should successfully find no prettier for path hierarchy that has node_modules with prettier, but no package.json mentions of it"
571        );
572        assert!(
573            matches!(
574                Prettier::locate_prettier_installation(
575                    fs.as_ref(),
576                    &HashSet::default(),
577                    Path::new("/root/work/project/node_modules/expect/build/print.js")
578                )
579                .await,
580                Ok(ControlFlow::Break(()))
581            ),
582            "Should not format files inside node_modules/"
583        );
584    }
585
586    #[gpui::test]
587    async fn test_prettier_lookup_in_simple_npm_projects(cx: &mut gpui::TestAppContext) {
588        let fs = FakeFs::new(cx.executor());
589        fs.insert_tree(
590            "/root",
591            json!({
592                "web_blog": {
593                    "node_modules": {
594                        "prettier": {
595                            "index.js": "// Dummy prettier package file",
596                        },
597                        "expect": {
598                            "build": {
599                                "print.js": "// print.js file contents",
600                            },
601                            "package.json": r#"{
602                                "devDependencies": {
603                                    "prettier": "2.5.1"
604                                }
605                            }"#,
606                        },
607                    },
608                    "pages": {
609                        "[slug].tsx": "// [slug].tsx file contents",
610                    },
611                    "package.json": r#"{
612                        "devDependencies": {
613                            "prettier": "2.3.0"
614                        },
615                        "prettier": {
616                            "semi": false,
617                            "printWidth": 80,
618                            "htmlWhitespaceSensitivity": "strict",
619                            "tabWidth": 4
620                        }
621                    }"#
622                }
623            }),
624        )
625        .await;
626
627        assert_eq!(
628            Prettier::locate_prettier_installation(
629                fs.as_ref(),
630                &HashSet::default(),
631                Path::new("/root/web_blog/pages/[slug].tsx")
632            )
633            .await
634            .unwrap(),
635            ControlFlow::Continue(Some(PathBuf::from("/root/web_blog"))),
636            "Should find a preinstalled prettier in the project root"
637        );
638        assert_eq!(
639            Prettier::locate_prettier_installation(
640                fs.as_ref(),
641                &HashSet::default(),
642                Path::new("/root/web_blog/node_modules/expect/build/print.js")
643            )
644            .await
645            .unwrap(),
646            ControlFlow::Break(()),
647            "Should not allow formatting node_modules/ contents"
648        );
649    }
650
651    #[gpui::test]
652    async fn test_prettier_lookup_for_not_installed(cx: &mut gpui::TestAppContext) {
653        let fs = FakeFs::new(cx.executor());
654        fs.insert_tree(
655            "/root",
656            json!({
657                "work": {
658                    "web_blog": {
659                        "node_modules": {
660                            "expect": {
661                                "build": {
662                                    "print.js": "// print.js file contents",
663                                },
664                                "package.json": r#"{
665                                    "devDependencies": {
666                                        "prettier": "2.5.1"
667                                    }
668                                }"#,
669                            },
670                        },
671                        "pages": {
672                            "[slug].tsx": "// [slug].tsx file contents",
673                        },
674                        "package.json": r#"{
675                            "devDependencies": {
676                                "prettier": "2.3.0"
677                            },
678                            "prettier": {
679                                "semi": false,
680                                "printWidth": 80,
681                                "htmlWhitespaceSensitivity": "strict",
682                                "tabWidth": 4
683                            }
684                        }"#
685                    }
686                }
687            }),
688        )
689        .await;
690
691        match Prettier::locate_prettier_installation(
692            fs.as_ref(),
693            &HashSet::default(),
694            Path::new("/root/work/web_blog/pages/[slug].tsx")
695        )
696        .await {
697            Ok(path) => panic!("Expected to fail for prettier in package.json but not in node_modules found, but got path {path:?}"),
698            Err(e) => {
699                let message = e.to_string();
700                assert!(message.contains("/root/work/web_blog"), "Error message should mention which project had prettier defined");
701            },
702        };
703
704        assert_eq!(
705            Prettier::locate_prettier_installation(
706                fs.as_ref(),
707                &HashSet::from_iter(
708                    [PathBuf::from("/root"), PathBuf::from("/root/work")].into_iter()
709                ),
710                Path::new("/root/work/web_blog/pages/[slug].tsx")
711            )
712            .await
713            .unwrap(),
714            ControlFlow::Continue(Some(PathBuf::from("/root/work"))),
715            "Should return closest cached value found without path checks"
716        );
717
718        assert_eq!(
719            Prettier::locate_prettier_installation(
720                fs.as_ref(),
721                &HashSet::default(),
722                Path::new("/root/work/web_blog/node_modules/expect/build/print.js")
723            )
724            .await
725            .unwrap(),
726            ControlFlow::Break(()),
727            "Should not allow formatting files inside node_modules/"
728        );
729        assert_eq!(
730            Prettier::locate_prettier_installation(
731                fs.as_ref(),
732                &HashSet::from_iter(
733                    [PathBuf::from("/root"), PathBuf::from("/root/work")].into_iter()
734                ),
735                Path::new("/root/work/web_blog/node_modules/expect/build/print.js")
736            )
737            .await
738            .unwrap(),
739            ControlFlow::Break(()),
740            "Should ignore cache lookup for files inside node_modules/"
741        );
742    }
743
744    #[gpui::test]
745    async fn test_prettier_lookup_in_npm_workspaces(cx: &mut gpui::TestAppContext) {
746        let fs = FakeFs::new(cx.executor());
747        fs.insert_tree(
748            "/root",
749            json!({
750                "work": {
751                    "full-stack-foundations": {
752                        "exercises": {
753                            "03.loading": {
754                                "01.problem.loader": {
755                                    "app": {
756                                        "routes": {
757                                            "users+": {
758                                                "$username_+": {
759                                                    "notes.tsx": "// notes.tsx file contents",
760                                                },
761                                            },
762                                        },
763                                    },
764                                    "node_modules": {
765                                        "test.js": "// test.js contents",
766                                    },
767                                    "package.json": r#"{
768                                        "devDependencies": {
769                                            "prettier": "^3.0.3"
770                                        }
771                                    }"#
772                                },
773                            },
774                        },
775                        "package.json": r#"{
776                            "workspaces": ["exercises/*/*", "examples/*"]
777                        }"#,
778                        "node_modules": {
779                            "prettier": {
780                                "index.js": "// Dummy prettier package file",
781                            },
782                        },
783                    },
784                }
785            }),
786        )
787        .await;
788
789        assert_eq!(
790            Prettier::locate_prettier_installation(
791                fs.as_ref(),
792                &HashSet::default(),
793                Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/app/routes/users+/$username_+/notes.tsx"),
794            ).await.unwrap(),
795            ControlFlow::Continue(Some(PathBuf::from("/root/work/full-stack-foundations"))),
796            "Should ascend to the multi-workspace root and find the prettier there",
797        );
798
799        assert_eq!(
800            Prettier::locate_prettier_installation(
801                fs.as_ref(),
802                &HashSet::default(),
803                Path::new("/root/work/full-stack-foundations/node_modules/prettier/index.js")
804            )
805            .await
806            .unwrap(),
807            ControlFlow::Break(()),
808            "Should not allow formatting files inside root node_modules/"
809        );
810        assert_eq!(
811            Prettier::locate_prettier_installation(
812                fs.as_ref(),
813                &HashSet::default(),
814                Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/node_modules/test.js")
815            )
816            .await
817            .unwrap(),
818            ControlFlow::Break(()),
819            "Should not allow formatting files inside submodule's node_modules/"
820        );
821    }
822
823    #[gpui::test]
824    async fn test_prettier_lookup_in_npm_workspaces_for_not_installed(
825        cx: &mut gpui::TestAppContext,
826    ) {
827        let fs = FakeFs::new(cx.executor());
828        fs.insert_tree(
829            "/root",
830            json!({
831                "work": {
832                    "full-stack-foundations": {
833                        "exercises": {
834                            "03.loading": {
835                                "01.problem.loader": {
836                                    "app": {
837                                        "routes": {
838                                            "users+": {
839                                                "$username_+": {
840                                                    "notes.tsx": "// notes.tsx file contents",
841                                                },
842                                            },
843                                        },
844                                    },
845                                    "node_modules": {},
846                                    "package.json": r#"{
847                                        "devDependencies": {
848                                            "prettier": "^3.0.3"
849                                        }
850                                    }"#
851                                },
852                            },
853                        },
854                        "package.json": r#"{
855                            "workspaces": ["exercises/*/*", "examples/*"]
856                        }"#,
857                    },
858                }
859            }),
860        )
861        .await;
862
863        match Prettier::locate_prettier_installation(
864            fs.as_ref(),
865            &HashSet::default(),
866            Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/app/routes/users+/$username_+/notes.tsx")
867        )
868        .await {
869            Ok(path) => panic!("Expected to fail for prettier in package.json but not in node_modules found, but got path {path:?}"),
870            Err(e) => {
871                let message = e.to_string();
872                assert!(message.contains("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader"), "Error message should mention which project had prettier defined");
873                assert!(message.contains("/root/work/full-stack-foundations"), "Error message should mention potential candidates without prettier node_modules contents");
874            },
875        };
876    }
877}