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