prettier.rs

  1use 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                            Some(options)
296                        } else {
297                            None
298                        };
299
300                        let plugins = located_plugins
301                            .into_iter()
302                            .filter_map(|(plugin_name, located_plugin_path)| {
303                                match located_plugin_path {
304                                    Some(path) => Some(path),
305                                    None => {
306                                        log::error!("Have not found plugin path for {plugin_name:?} inside {prettier_node_modules:?}");
307                                        None
308                                    }
309                                }
310                            })
311                            .collect();
312                        log::debug!(
313                            "Formatting file {:?} with prettier, plugins :{:?}, options: {:?}",
314                            buffer.file().map(|f| f.full_path(cx)),
315                            plugins,
316                            prettier_options,
317                        );
318
319                        anyhow::Ok(FormatParams {
320                            text: buffer.text(),
321                            options: FormatOptions {
322                                parser: prettier_settings.parser.clone(),
323                                plugins,
324                                path: buffer_path,
325                                prettier_options,
326                            },
327                        })
328                    })?
329                    .context("prettier params calculation")?;
330                let response = local
331                    .server
332                    .request::<Format>(params)
333                    .await
334                    .context("prettier format request")?;
335                let diff_task = buffer.update(cx, |buffer, cx| buffer.diff(response.text, cx))?;
336                Ok(diff_task.await)
337            }
338            #[cfg(any(test, feature = "test-support"))]
339            Self::Test(_) => Ok(buffer
340                .update(cx, |buffer, cx| {
341                    match buffer
342                        .language()
343                        .map(|language| language.lsp_id())
344                        .as_deref()
345                    {
346                        Some("rust") => anyhow::bail!("prettier does not support Rust"),
347                        Some(_other) => {
348                            let formatted_text = buffer.text() + FORMAT_SUFFIX;
349                            Ok(buffer.diff(formatted_text, cx))
350                        }
351                        None => panic!("Should not format buffer without a language with prettier"),
352                    }
353                })??
354                .await),
355        }
356    }
357
358    pub async fn clear_cache(&self) -> anyhow::Result<()> {
359        match self {
360            Self::Real(local) => local
361                .server
362                .request::<ClearCache>(())
363                .await
364                .context("prettier clear cache"),
365            #[cfg(any(test, feature = "test-support"))]
366            Self::Test(_) => Ok(()),
367        }
368    }
369
370    pub fn server(&self) -> Option<&Arc<LanguageServer>> {
371        match self {
372            Self::Real(local) => Some(&local.server),
373            #[cfg(any(test, feature = "test-support"))]
374            Self::Test(_) => None,
375        }
376    }
377
378    pub fn is_default(&self) -> bool {
379        match self {
380            Self::Real(local) => local.default,
381            #[cfg(any(test, feature = "test-support"))]
382            Self::Test(test_prettier) => test_prettier.default,
383        }
384    }
385
386    pub fn prettier_dir(&self) -> &Path {
387        match self {
388            Self::Real(local) => &local.prettier_dir,
389            #[cfg(any(test, feature = "test-support"))]
390            Self::Test(test_prettier) => &test_prettier.prettier_dir,
391        }
392    }
393}
394
395async fn has_prettier_in_node_modules(fs: &dyn Fs, path: &Path) -> anyhow::Result<bool> {
396    let possible_node_modules_location = path.join("node_modules").join(PRETTIER_PACKAGE_NAME);
397    if let Some(node_modules_location_metadata) = fs
398        .metadata(&possible_node_modules_location)
399        .await
400        .with_context(|| format!("fetching metadata for {possible_node_modules_location:?}"))?
401    {
402        return Ok(node_modules_location_metadata.is_dir);
403    }
404    Ok(false)
405}
406
407async fn read_package_json(
408    fs: &dyn Fs,
409    path: &Path,
410) -> anyhow::Result<Option<HashMap<String, serde_json::Value>>> {
411    let possible_package_json = path.join("package.json");
412    if let Some(package_json_metadata) = fs
413        .metadata(&possible_package_json)
414        .await
415        .with_context(|| format!("fetching metadata for package json {possible_package_json:?}"))?
416    {
417        if !package_json_metadata.is_dir && !package_json_metadata.is_symlink {
418            let package_json_contents = fs
419                .load(&possible_package_json)
420                .await
421                .with_context(|| format!("reading {possible_package_json:?} file contents"))?;
422            return serde_json::from_str::<HashMap<String, serde_json::Value>>(
423                &package_json_contents,
424            )
425            .map(Some)
426            .with_context(|| format!("parsing {possible_package_json:?} file contents"));
427        }
428    }
429    Ok(None)
430}
431
432fn has_prettier_in_package_json(
433    package_json_contents: &HashMap<String, serde_json::Value>,
434) -> bool {
435    if let Some(serde_json::Value::Object(o)) = package_json_contents.get("dependencies") {
436        if o.contains_key(PRETTIER_PACKAGE_NAME) {
437            return true;
438        }
439    }
440    if let Some(serde_json::Value::Object(o)) = package_json_contents.get("devDependencies") {
441        if o.contains_key(PRETTIER_PACKAGE_NAME) {
442            return true;
443        }
444    }
445    false
446}
447
448enum Format {}
449
450#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
451#[serde(rename_all = "camelCase")]
452struct FormatParams {
453    text: String,
454    options: FormatOptions,
455}
456
457#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
458#[serde(rename_all = "camelCase")]
459struct FormatOptions {
460    plugins: Vec<PathBuf>,
461    parser: Option<String>,
462    #[serde(rename = "filepath")]
463    path: Option<PathBuf>,
464    prettier_options: Option<HashMap<String, serde_json::Value>>,
465}
466
467#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
468#[serde(rename_all = "camelCase")]
469struct FormatResult {
470    text: String,
471}
472
473impl lsp::request::Request for Format {
474    type Params = FormatParams;
475    type Result = FormatResult;
476    const METHOD: &'static str = "prettier/format";
477}
478
479enum ClearCache {}
480
481impl lsp::request::Request for ClearCache {
482    type Params = ();
483    type Result = ();
484    const METHOD: &'static str = "prettier/clear_cache";
485}
486
487#[cfg(test)]
488mod tests {
489    use fs::FakeFs;
490    use serde_json::json;
491
492    use super::*;
493
494    #[gpui::test]
495    async fn test_prettier_lookup_finds_nothing(cx: &mut gpui::TestAppContext) {
496        let fs = FakeFs::new(cx.executor());
497        fs.insert_tree(
498            "/root",
499            json!({
500                ".config": {
501                    "zed": {
502                        "settings.json": r#"{ "formatter": "auto" }"#,
503                    },
504                },
505                "work": {
506                    "project": {
507                        "src": {
508                            "index.js": "// index.js file contents",
509                        },
510                        "node_modules": {
511                            "expect": {
512                                "build": {
513                                    "print.js": "// print.js file contents",
514                                },
515                                "package.json": r#"{
516                                    "devDependencies": {
517                                        "prettier": "2.5.1"
518                                    }
519                                }"#,
520                            },
521                            "prettier": {
522                                "index.js": "// Dummy prettier package file",
523                            },
524                        },
525                        "package.json": r#"{}"#
526                    },
527                }
528            }),
529        )
530        .await;
531
532        assert!(
533            matches!(
534                Prettier::locate_prettier_installation(
535                    fs.as_ref(),
536                    &HashSet::default(),
537                    Path::new("/root/.config/zed/settings.json"),
538                )
539                .await,
540                Ok(ControlFlow::Continue(None))
541            ),
542            "Should successfully find no prettier for path hierarchy without it"
543        );
544        assert!(
545            matches!(
546                Prettier::locate_prettier_installation(
547                    fs.as_ref(),
548                    &HashSet::default(),
549                    Path::new("/root/work/project/src/index.js")
550                )
551                .await,
552                Ok(ControlFlow::Continue(None))
553            ),
554            "Should successfully find no prettier for path hierarchy that has node_modules with prettier, but no package.json mentions of it"
555        );
556        assert!(
557            matches!(
558                Prettier::locate_prettier_installation(
559                    fs.as_ref(),
560                    &HashSet::default(),
561                    Path::new("/root/work/project/node_modules/expect/build/print.js")
562                )
563                .await,
564                Ok(ControlFlow::Break(()))
565            ),
566            "Should not format files inside node_modules/"
567        );
568    }
569
570    #[gpui::test]
571    async fn test_prettier_lookup_in_simple_npm_projects(cx: &mut gpui::TestAppContext) {
572        let fs = FakeFs::new(cx.executor());
573        fs.insert_tree(
574            "/root",
575            json!({
576                "web_blog": {
577                    "node_modules": {
578                        "prettier": {
579                            "index.js": "// Dummy prettier package file",
580                        },
581                        "expect": {
582                            "build": {
583                                "print.js": "// print.js file contents",
584                            },
585                            "package.json": r#"{
586                                "devDependencies": {
587                                    "prettier": "2.5.1"
588                                }
589                            }"#,
590                        },
591                    },
592                    "pages": {
593                        "[slug].tsx": "// [slug].tsx file contents",
594                    },
595                    "package.json": r#"{
596                        "devDependencies": {
597                            "prettier": "2.3.0"
598                        },
599                        "prettier": {
600                            "semi": false,
601                            "printWidth": 80,
602                            "htmlWhitespaceSensitivity": "strict",
603                            "tabWidth": 4
604                        }
605                    }"#
606                }
607            }),
608        )
609        .await;
610
611        assert_eq!(
612            Prettier::locate_prettier_installation(
613                fs.as_ref(),
614                &HashSet::default(),
615                Path::new("/root/web_blog/pages/[slug].tsx")
616            )
617            .await
618            .unwrap(),
619            ControlFlow::Continue(Some(PathBuf::from("/root/web_blog"))),
620            "Should find a preinstalled prettier in the project root"
621        );
622        assert_eq!(
623            Prettier::locate_prettier_installation(
624                fs.as_ref(),
625                &HashSet::default(),
626                Path::new("/root/web_blog/node_modules/expect/build/print.js")
627            )
628            .await
629            .unwrap(),
630            ControlFlow::Break(()),
631            "Should not allow formatting node_modules/ contents"
632        );
633    }
634
635    #[gpui::test]
636    async fn test_prettier_lookup_for_not_installed(cx: &mut gpui::TestAppContext) {
637        let fs = FakeFs::new(cx.executor());
638        fs.insert_tree(
639            "/root",
640            json!({
641                "work": {
642                    "web_blog": {
643                        "node_modules": {
644                            "expect": {
645                                "build": {
646                                    "print.js": "// print.js file contents",
647                                },
648                                "package.json": r#"{
649                                    "devDependencies": {
650                                        "prettier": "2.5.1"
651                                    }
652                                }"#,
653                            },
654                        },
655                        "pages": {
656                            "[slug].tsx": "// [slug].tsx file contents",
657                        },
658                        "package.json": r#"{
659                            "devDependencies": {
660                                "prettier": "2.3.0"
661                            },
662                            "prettier": {
663                                "semi": false,
664                                "printWidth": 80,
665                                "htmlWhitespaceSensitivity": "strict",
666                                "tabWidth": 4
667                            }
668                        }"#
669                    }
670                }
671            }),
672        )
673        .await;
674
675        match Prettier::locate_prettier_installation(
676            fs.as_ref(),
677            &HashSet::default(),
678            Path::new("/root/work/web_blog/pages/[slug].tsx")
679        )
680        .await {
681            Ok(path) => panic!("Expected to fail for prettier in package.json but not in node_modules found, but got path {path:?}"),
682            Err(e) => {
683                let message = e.to_string();
684                assert!(message.contains("/root/work/web_blog"), "Error message should mention which project had prettier defined");
685            },
686        };
687
688        assert_eq!(
689            Prettier::locate_prettier_installation(
690                fs.as_ref(),
691                &HashSet::from_iter(
692                    [PathBuf::from("/root"), PathBuf::from("/root/work")].into_iter()
693                ),
694                Path::new("/root/work/web_blog/pages/[slug].tsx")
695            )
696            .await
697            .unwrap(),
698            ControlFlow::Continue(Some(PathBuf::from("/root/work"))),
699            "Should return closest cached value found without path checks"
700        );
701
702        assert_eq!(
703            Prettier::locate_prettier_installation(
704                fs.as_ref(),
705                &HashSet::default(),
706                Path::new("/root/work/web_blog/node_modules/expect/build/print.js")
707            )
708            .await
709            .unwrap(),
710            ControlFlow::Break(()),
711            "Should not allow formatting files inside node_modules/"
712        );
713        assert_eq!(
714            Prettier::locate_prettier_installation(
715                fs.as_ref(),
716                &HashSet::from_iter(
717                    [PathBuf::from("/root"), PathBuf::from("/root/work")].into_iter()
718                ),
719                Path::new("/root/work/web_blog/node_modules/expect/build/print.js")
720            )
721            .await
722            .unwrap(),
723            ControlFlow::Break(()),
724            "Should ignore cache lookup for files inside node_modules/"
725        );
726    }
727
728    #[gpui::test]
729    async fn test_prettier_lookup_in_npm_workspaces(cx: &mut gpui::TestAppContext) {
730        let fs = FakeFs::new(cx.executor());
731        fs.insert_tree(
732            "/root",
733            json!({
734                "work": {
735                    "full-stack-foundations": {
736                        "exercises": {
737                            "03.loading": {
738                                "01.problem.loader": {
739                                    "app": {
740                                        "routes": {
741                                            "users+": {
742                                                "$username_+": {
743                                                    "notes.tsx": "// notes.tsx file contents",
744                                                },
745                                            },
746                                        },
747                                    },
748                                    "node_modules": {
749                                        "test.js": "// test.js contents",
750                                    },
751                                    "package.json": r#"{
752                                        "devDependencies": {
753                                            "prettier": "^3.0.3"
754                                        }
755                                    }"#
756                                },
757                            },
758                        },
759                        "package.json": r#"{
760                            "workspaces": ["exercises/*/*", "examples/*"]
761                        }"#,
762                        "node_modules": {
763                            "prettier": {
764                                "index.js": "// Dummy prettier package file",
765                            },
766                        },
767                    },
768                }
769            }),
770        )
771        .await;
772
773        assert_eq!(
774            Prettier::locate_prettier_installation(
775                fs.as_ref(),
776                &HashSet::default(),
777                Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/app/routes/users+/$username_+/notes.tsx"),
778            ).await.unwrap(),
779            ControlFlow::Continue(Some(PathBuf::from("/root/work/full-stack-foundations"))),
780            "Should ascend to the multi-workspace root and find the prettier there",
781        );
782
783        assert_eq!(
784            Prettier::locate_prettier_installation(
785                fs.as_ref(),
786                &HashSet::default(),
787                Path::new("/root/work/full-stack-foundations/node_modules/prettier/index.js")
788            )
789            .await
790            .unwrap(),
791            ControlFlow::Break(()),
792            "Should not allow formatting files inside root node_modules/"
793        );
794        assert_eq!(
795            Prettier::locate_prettier_installation(
796                fs.as_ref(),
797                &HashSet::default(),
798                Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/node_modules/test.js")
799            )
800            .await
801            .unwrap(),
802            ControlFlow::Break(()),
803            "Should not allow formatting files inside submodule's node_modules/"
804        );
805    }
806
807    #[gpui::test]
808    async fn test_prettier_lookup_in_npm_workspaces_for_not_installed(
809        cx: &mut gpui::TestAppContext,
810    ) {
811        let fs = FakeFs::new(cx.executor());
812        fs.insert_tree(
813            "/root",
814            json!({
815                "work": {
816                    "full-stack-foundations": {
817                        "exercises": {
818                            "03.loading": {
819                                "01.problem.loader": {
820                                    "app": {
821                                        "routes": {
822                                            "users+": {
823                                                "$username_+": {
824                                                    "notes.tsx": "// notes.tsx file contents",
825                                                },
826                                            },
827                                        },
828                                    },
829                                    "node_modules": {},
830                                    "package.json": r#"{
831                                        "devDependencies": {
832                                            "prettier": "^3.0.3"
833                                        }
834                                    }"#
835                                },
836                            },
837                        },
838                        "package.json": r#"{
839                            "workspaces": ["exercises/*/*", "examples/*"]
840                        }"#,
841                    },
842                }
843            }),
844        )
845        .await;
846
847        match Prettier::locate_prettier_installation(
848            fs.as_ref(),
849            &HashSet::default(),
850            Path::new("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader/app/routes/users+/$username_+/notes.tsx")
851        )
852        .await {
853            Ok(path) => panic!("Expected to fail for prettier in package.json but not in node_modules found, but got path {path:?}"),
854            Err(e) => {
855                let message = e.to_string();
856                assert!(message.contains("/root/work/full-stack-foundations/exercises/03.loading/01.problem.loader"), "Error message should mention which project had prettier defined");
857                assert!(message.contains("/root/work/full-stack-foundations"), "Error message should mention potential candidates without prettier node_modules contents");
858            },
859        };
860    }
861}