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