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