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