1use std::{
2 ops::ControlFlow,
3 path::{Path, PathBuf},
4 sync::Arc,
5};
6
7use anyhow::{anyhow, Context, Result};
8use collections::HashSet;
9use fs::Fs;
10use futures::{
11 future::{self, Shared},
12 FutureExt,
13};
14use gpui::{AsyncAppContext, Model, ModelContext, Task, WeakModel};
15use language::{
16 language_settings::{Formatter, LanguageSettings},
17 Buffer, LanguageServerName, LocalFile,
18};
19use lsp::{LanguageServer, LanguageServerId};
20use node_runtime::NodeRuntime;
21use paths::default_prettier_dir;
22use prettier::Prettier;
23use util::{ResultExt, TryFutureExt};
24
25use crate::{
26 Event, File, FormatOperation, PathChange, Project, ProjectEntryId, Worktree, WorktreeId,
27};
28
29pub fn prettier_plugins_for_language(
30 language_settings: &LanguageSettings,
31) -> Option<&HashSet<String>> {
32 match &language_settings.formatter {
33 Formatter::Prettier { .. } | Formatter::Auto => Some(&language_settings.prettier.plugins),
34 Formatter::LanguageServer | Formatter::External { .. } | Formatter::CodeActions(_) => None,
35 }
36}
37
38pub(super) async fn format_with_prettier(
39 project: &WeakModel<Project>,
40 buffer: &Model<Buffer>,
41 cx: &mut AsyncAppContext,
42) -> Option<Result<FormatOperation>> {
43 let prettier_instance = project
44 .update(cx, |project, cx| {
45 project.prettier_instance_for_buffer(buffer, cx)
46 })
47 .ok()?
48 .await;
49
50 let Some((prettier_path, prettier_task)) = prettier_instance else {
51 return None;
52 };
53
54 let prettier_description = match prettier_path.as_ref() {
55 Some(path) => format!("prettier at {path:?}"),
56 None => "default prettier instance".to_string(),
57 };
58
59 match prettier_task.await {
60 Ok(prettier) => {
61 let buffer_path = buffer
62 .update(cx, |buffer, cx| {
63 File::from_dyn(buffer.file()).map(|file| file.abs_path(cx))
64 })
65 .ok()
66 .flatten();
67
68 let format_result = prettier
69 .format(buffer, buffer_path, cx)
70 .await
71 .map(FormatOperation::Prettier)
72 .with_context(|| format!("{} failed to format buffer", prettier_description));
73
74 Some(format_result)
75 }
76 Err(error) => {
77 project
78 .update(cx, |project, _| {
79 let instance_to_update = match prettier_path {
80 Some(prettier_path) => project.prettier_instances.get_mut(&prettier_path),
81 None => match &mut project.default_prettier.prettier {
82 PrettierInstallation::NotInstalled { .. } => None,
83 PrettierInstallation::Installed(instance) => Some(instance),
84 },
85 };
86
87 if let Some(instance) = instance_to_update {
88 instance.attempt += 1;
89 instance.prettier = None;
90 }
91 })
92 .log_err();
93
94 Some(Err(anyhow!(
95 "{} failed to spawn: {error:#}",
96 prettier_description
97 )))
98 }
99 }
100}
101
102pub struct DefaultPrettier {
103 prettier: PrettierInstallation,
104 installed_plugins: HashSet<Arc<str>>,
105}
106
107#[derive(Debug)]
108pub enum PrettierInstallation {
109 NotInstalled {
110 attempts: usize,
111 installation_task: Option<Shared<Task<Result<(), Arc<anyhow::Error>>>>>,
112 not_installed_plugins: HashSet<Arc<str>>,
113 },
114 Installed(PrettierInstance),
115}
116
117pub type PrettierTask = Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>;
118
119#[derive(Debug, Clone)]
120pub struct PrettierInstance {
121 attempt: usize,
122 prettier: Option<PrettierTask>,
123}
124
125impl Default for DefaultPrettier {
126 fn default() -> Self {
127 Self {
128 prettier: PrettierInstallation::NotInstalled {
129 attempts: 0,
130 installation_task: None,
131 not_installed_plugins: HashSet::default(),
132 },
133 installed_plugins: HashSet::default(),
134 }
135 }
136}
137
138impl DefaultPrettier {
139 pub fn instance(&self) -> Option<&PrettierInstance> {
140 if let PrettierInstallation::Installed(instance) = &self.prettier {
141 Some(instance)
142 } else {
143 None
144 }
145 }
146
147 pub fn prettier_task(
148 &mut self,
149 node: &Arc<dyn NodeRuntime>,
150 worktree_id: Option<WorktreeId>,
151 cx: &mut ModelContext<'_, Project>,
152 ) -> Option<Task<anyhow::Result<PrettierTask>>> {
153 match &mut self.prettier {
154 PrettierInstallation::NotInstalled { .. } => {
155 Some(start_default_prettier(Arc::clone(node), worktree_id, cx))
156 }
157 PrettierInstallation::Installed(existing_instance) => {
158 existing_instance.prettier_task(node, None, worktree_id, cx)
159 }
160 }
161 }
162}
163
164impl PrettierInstance {
165 pub fn prettier_task(
166 &mut self,
167 node: &Arc<dyn NodeRuntime>,
168 prettier_dir: Option<&Path>,
169 worktree_id: Option<WorktreeId>,
170 cx: &mut ModelContext<'_, Project>,
171 ) -> Option<Task<anyhow::Result<PrettierTask>>> {
172 if self.attempt > prettier::FAIL_THRESHOLD {
173 match prettier_dir {
174 Some(prettier_dir) => log::warn!(
175 "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting"
176 ),
177 None => log::warn!("Default prettier exceeded launch threshold, not starting"),
178 }
179 return None;
180 }
181 Some(match &self.prettier {
182 Some(prettier_task) => Task::ready(Ok(prettier_task.clone())),
183 None => match prettier_dir {
184 Some(prettier_dir) => {
185 let new_task = start_prettier(
186 Arc::clone(node),
187 prettier_dir.to_path_buf(),
188 worktree_id,
189 cx,
190 );
191 self.attempt += 1;
192 self.prettier = Some(new_task.clone());
193 Task::ready(Ok(new_task))
194 }
195 None => {
196 self.attempt += 1;
197 let node = Arc::clone(node);
198 cx.spawn(|project, mut cx| async move {
199 project
200 .update(&mut cx, |_, cx| {
201 start_default_prettier(node, worktree_id, cx)
202 })?
203 .await
204 })
205 }
206 },
207 })
208 }
209
210 pub async fn server(&self) -> Option<Arc<LanguageServer>> {
211 self.prettier.clone()?.await.ok()?.server().cloned()
212 }
213}
214
215fn start_default_prettier(
216 node: Arc<dyn NodeRuntime>,
217 worktree_id: Option<WorktreeId>,
218 cx: &mut ModelContext<'_, Project>,
219) -> Task<anyhow::Result<PrettierTask>> {
220 cx.spawn(|project, mut cx| async move {
221 let installation_task = project.update(&mut cx, |project, _| {
222 match &project.default_prettier.prettier {
223 PrettierInstallation::NotInstalled {
224 installation_task, ..
225 } => ControlFlow::Continue(installation_task.clone()),
226 PrettierInstallation::Installed(default_prettier) => {
227 ControlFlow::Break(default_prettier.clone())
228 }
229 }
230 })?;
231 match installation_task {
232 ControlFlow::Continue(None) => {
233 anyhow::bail!("Default prettier is not installed and cannot be started")
234 }
235 ControlFlow::Continue(Some(installation_task)) => {
236 log::info!("Waiting for default prettier to install");
237 if let Err(e) = installation_task.await {
238 project.update(&mut cx, |project, _| {
239 if let PrettierInstallation::NotInstalled {
240 installation_task,
241 attempts,
242 ..
243 } = &mut project.default_prettier.prettier
244 {
245 *installation_task = None;
246 *attempts += 1;
247 }
248 })?;
249 anyhow::bail!(
250 "Cannot start default prettier due to its installation failure: {e:#}"
251 );
252 }
253 let new_default_prettier = project.update(&mut cx, |project, cx| {
254 let new_default_prettier =
255 start_prettier(node, default_prettier_dir().clone(), worktree_id, cx);
256 project.default_prettier.prettier =
257 PrettierInstallation::Installed(PrettierInstance {
258 attempt: 0,
259 prettier: Some(new_default_prettier.clone()),
260 });
261 new_default_prettier
262 })?;
263 return Ok(new_default_prettier);
264 }
265 ControlFlow::Break(instance) => match instance.prettier {
266 Some(instance) => return Ok(instance),
267 None => {
268 let new_default_prettier = project.update(&mut cx, |project, cx| {
269 let new_default_prettier =
270 start_prettier(node, default_prettier_dir().clone(), worktree_id, cx);
271 project.default_prettier.prettier =
272 PrettierInstallation::Installed(PrettierInstance {
273 attempt: instance.attempt + 1,
274 prettier: Some(new_default_prettier.clone()),
275 });
276 new_default_prettier
277 })?;
278 return Ok(new_default_prettier);
279 }
280 },
281 }
282 })
283}
284
285fn start_prettier(
286 node: Arc<dyn NodeRuntime>,
287 prettier_dir: PathBuf,
288 worktree_id: Option<WorktreeId>,
289 cx: &mut ModelContext<'_, Project>,
290) -> PrettierTask {
291 cx.spawn(|project, mut cx| async move {
292 log::info!("Starting prettier at path {prettier_dir:?}");
293 let new_server_id = project.update(&mut cx, |project, _| {
294 project.languages.next_language_server_id()
295 })?;
296
297 let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone())
298 .await
299 .context("default prettier spawn")
300 .map(Arc::new)
301 .map_err(Arc::new)?;
302 register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx);
303 Ok(new_prettier)
304 })
305 .shared()
306}
307
308fn register_new_prettier(
309 project: &WeakModel<Project>,
310 prettier: &Prettier,
311 worktree_id: Option<WorktreeId>,
312 new_server_id: LanguageServerId,
313 cx: &mut AsyncAppContext,
314) {
315 let prettier_dir = prettier.prettier_dir();
316 let is_default = prettier.is_default();
317 if is_default {
318 log::info!("Started default prettier in {prettier_dir:?}");
319 } else {
320 log::info!("Started prettier in {prettier_dir:?}");
321 }
322 if let Some(prettier_server) = prettier.server() {
323 project
324 .update(cx, |project, cx| {
325 let name = if is_default {
326 LanguageServerName(Arc::from("prettier (default)"))
327 } else {
328 let worktree_path = worktree_id
329 .and_then(|id| project.worktree_for_id(id, cx))
330 .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path()));
331 let name = match worktree_path {
332 Some(worktree_path) => {
333 if prettier_dir == worktree_path.as_ref() {
334 let name = prettier_dir
335 .file_name()
336 .and_then(|name| name.to_str())
337 .unwrap_or_default();
338 format!("prettier ({name})")
339 } else {
340 let dir_to_display = prettier_dir
341 .strip_prefix(worktree_path.as_ref())
342 .ok()
343 .unwrap_or(prettier_dir);
344 format!("prettier ({})", dir_to_display.display())
345 }
346 }
347 None => format!("prettier ({})", prettier_dir.display()),
348 };
349 LanguageServerName(Arc::from(name))
350 };
351 project
352 .supplementary_language_servers
353 .insert(new_server_id, (name, Arc::clone(prettier_server)));
354 cx.emit(Event::LanguageServerAdded(new_server_id));
355 })
356 .ok();
357 }
358}
359
360async fn install_prettier_packages(
361 fs: &dyn Fs,
362 plugins_to_install: HashSet<Arc<str>>,
363 node: Arc<dyn NodeRuntime>,
364) -> anyhow::Result<()> {
365 let packages_to_versions = future::try_join_all(
366 plugins_to_install
367 .iter()
368 .chain(Some(&"prettier".into()))
369 .map(|package_name| async {
370 let returned_package_name = package_name.to_string();
371 let latest_version = node
372 .npm_package_latest_version(package_name)
373 .await
374 .with_context(|| {
375 format!("fetching latest npm version for package {returned_package_name}")
376 })?;
377 anyhow::Ok((returned_package_name, latest_version))
378 }),
379 )
380 .await
381 .context("fetching latest npm versions")?;
382
383 let default_prettier_dir = default_prettier_dir().as_path();
384 match fs.metadata(default_prettier_dir).await.with_context(|| {
385 format!("fetching FS metadata for default prettier dir {default_prettier_dir:?}")
386 })? {
387 Some(prettier_dir_metadata) => anyhow::ensure!(
388 prettier_dir_metadata.is_dir,
389 "default prettier dir {default_prettier_dir:?} is not a directory"
390 ),
391 None => fs
392 .create_dir(default_prettier_dir)
393 .await
394 .with_context(|| format!("creating default prettier dir {default_prettier_dir:?}"))?,
395 }
396
397 log::info!("Installing default prettier and plugins: {packages_to_versions:?}");
398 let borrowed_packages = packages_to_versions
399 .iter()
400 .map(|(package, version)| (package.as_str(), version.as_str()))
401 .collect::<Vec<_>>();
402 node.npm_install_packages(default_prettier_dir, &borrowed_packages)
403 .await
404 .context("fetching formatter packages")?;
405 anyhow::Ok(())
406}
407
408async fn save_prettier_server_file(fs: &dyn Fs) -> anyhow::Result<()> {
409 let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
410 fs.save(
411 &prettier_wrapper_path,
412 &text::Rope::from(prettier::PRETTIER_SERVER_JS),
413 text::LineEnding::Unix,
414 )
415 .await
416 .with_context(|| {
417 format!(
418 "writing {} file at {prettier_wrapper_path:?}",
419 prettier::PRETTIER_SERVER_FILE
420 )
421 })?;
422 Ok(())
423}
424
425async fn should_write_prettier_server_file(fs: &dyn Fs) -> bool {
426 let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
427 if !fs.is_file(&prettier_wrapper_path).await {
428 return true;
429 }
430 let Ok(prettier_server_file_contents) = fs.load(&prettier_wrapper_path).await else {
431 return true;
432 };
433 prettier_server_file_contents != prettier::PRETTIER_SERVER_JS
434}
435
436impl Project {
437 pub fn update_prettier_settings(
438 &self,
439 worktree: &Model<Worktree>,
440 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
441 cx: &mut ModelContext<'_, Project>,
442 ) {
443 let prettier_config_files = Prettier::CONFIG_FILE_NAMES
444 .iter()
445 .map(Path::new)
446 .collect::<HashSet<_>>();
447
448 let prettier_config_file_changed = changes
449 .iter()
450 .filter(|(_, _, change)| !matches!(change, PathChange::Loaded))
451 .filter(|(path, _, _)| {
452 !path
453 .components()
454 .any(|component| component.as_os_str().to_string_lossy() == "node_modules")
455 })
456 .find(|(path, _, _)| prettier_config_files.contains(path.as_ref()));
457 let current_worktree_id = worktree.read(cx).id();
458 if let Some((config_path, _, _)) = prettier_config_file_changed {
459 log::info!(
460 "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}"
461 );
462 let prettiers_to_reload =
463 self.prettiers_per_worktree
464 .get(¤t_worktree_id)
465 .iter()
466 .flat_map(|prettier_paths| prettier_paths.iter())
467 .flatten()
468 .filter_map(|prettier_path| {
469 Some((
470 current_worktree_id,
471 Some(prettier_path.clone()),
472 self.prettier_instances.get(prettier_path)?.clone(),
473 ))
474 })
475 .chain(self.default_prettier.instance().map(|default_prettier| {
476 (current_worktree_id, None, default_prettier.clone())
477 }))
478 .collect::<Vec<_>>();
479
480 cx.background_executor()
481 .spawn(async move {
482 let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_instance)| {
483 async move {
484 if let Some(instance) = prettier_instance.prettier {
485 match instance.await {
486 Ok(prettier) => {
487 prettier.clear_cache().log_err().await;
488 },
489 Err(e) => {
490 match prettier_path {
491 Some(prettier_path) => log::error!(
492 "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}"
493 ),
494 None => log::error!(
495 "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}"
496 ),
497 }
498 },
499 }
500 }
501 }
502 }))
503 .await;
504 })
505 .detach();
506 }
507 }
508
509 fn prettier_instance_for_buffer(
510 &mut self,
511 buffer: &Model<Buffer>,
512 cx: &mut ModelContext<Self>,
513 ) -> Task<Option<(Option<PathBuf>, PrettierTask)>> {
514 if !self.is_local() {
515 return Task::ready(None);
516 }
517 let buffer = buffer.read(cx);
518 let buffer_file = buffer.file();
519 if buffer.language().is_none() {
520 return Task::ready(None);
521 }
522 let Some(node) = self.node.clone() else {
523 return Task::ready(None);
524 };
525 match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx))) {
526 Some((worktree_id, buffer_path)) => {
527 let fs = Arc::clone(&self.fs);
528 let installed_prettiers = self.prettier_instances.keys().cloned().collect();
529 cx.spawn(|project, mut cx| async move {
530 match cx
531 .background_executor()
532 .spawn(async move {
533 Prettier::locate_prettier_installation(
534 fs.as_ref(),
535 &installed_prettiers,
536 &buffer_path,
537 )
538 .await
539 })
540 .await
541 {
542 Ok(ControlFlow::Break(())) => None,
543 Ok(ControlFlow::Continue(None)) => {
544 let default_instance = project
545 .update(&mut cx, |project, cx| {
546 project
547 .prettiers_per_worktree
548 .entry(worktree_id)
549 .or_default()
550 .insert(None);
551 project.default_prettier.prettier_task(
552 &node,
553 Some(worktree_id),
554 cx,
555 )
556 })
557 .ok()?;
558 Some((None, default_instance?.log_err().await?))
559 }
560 Ok(ControlFlow::Continue(Some(prettier_dir))) => {
561 project
562 .update(&mut cx, |project, _| {
563 project
564 .prettiers_per_worktree
565 .entry(worktree_id)
566 .or_default()
567 .insert(Some(prettier_dir.clone()))
568 })
569 .ok()?;
570 if let Some(prettier_task) = project
571 .update(&mut cx, |project, cx| {
572 project.prettier_instances.get_mut(&prettier_dir).map(
573 |existing_instance| {
574 existing_instance.prettier_task(
575 &node,
576 Some(&prettier_dir),
577 Some(worktree_id),
578 cx,
579 )
580 },
581 )
582 })
583 .ok()?
584 {
585 log::debug!("Found already started prettier in {prettier_dir:?}");
586 return Some((Some(prettier_dir), prettier_task?.await.log_err()?));
587 }
588
589 log::info!("Found prettier in {prettier_dir:?}, starting.");
590 let new_prettier_task = project
591 .update(&mut cx, |project, cx| {
592 let new_prettier_task = start_prettier(
593 node,
594 prettier_dir.clone(),
595 Some(worktree_id),
596 cx,
597 );
598 project.prettier_instances.insert(
599 prettier_dir.clone(),
600 PrettierInstance {
601 attempt: 0,
602 prettier: Some(new_prettier_task.clone()),
603 },
604 );
605 new_prettier_task
606 })
607 .ok()?;
608 Some((Some(prettier_dir), new_prettier_task))
609 }
610 Err(e) => {
611 log::error!("Failed to determine prettier path for buffer: {e:#}");
612 None
613 }
614 }
615 })
616 }
617 None => {
618 let new_task = self.default_prettier.prettier_task(&node, None, cx);
619 cx.spawn(|_, _| async move { Some((None, new_task?.log_err().await?)) })
620 }
621 }
622 }
623
624 pub fn install_default_prettier(
625 &mut self,
626 worktree: Option<WorktreeId>,
627 plugins: impl Iterator<Item = Arc<str>>,
628 cx: &mut ModelContext<Self>,
629 ) {
630 if cfg!(any(test, feature = "test-support")) {
631 self.default_prettier.installed_plugins.extend(plugins);
632 self.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance {
633 attempt: 0,
634 prettier: None,
635 });
636 return;
637 }
638
639 let mut new_plugins = plugins.collect::<HashSet<_>>();
640 let Some(node) = self.node.as_ref().cloned() else {
641 return;
642 };
643 let fs = Arc::clone(&self.fs);
644 let locate_prettier_installation = match worktree.and_then(|worktree_id| {
645 self.worktree_for_id(worktree_id, cx)
646 .map(|worktree| worktree.read(cx).abs_path())
647 }) {
648 Some(locate_from) => {
649 let installed_prettiers = self.prettier_instances.keys().cloned().collect();
650 cx.background_executor().spawn(async move {
651 Prettier::locate_prettier_installation(
652 fs.as_ref(),
653 &installed_prettiers,
654 locate_from.as_ref(),
655 )
656 .await
657 })
658 }
659 None => Task::ready(Ok(ControlFlow::Continue(None))),
660 };
661 new_plugins.retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin));
662 let mut installation_attempt = 0;
663 let previous_installation_task = match &mut self.default_prettier.prettier {
664 PrettierInstallation::NotInstalled {
665 installation_task,
666 attempts,
667 not_installed_plugins,
668 } => {
669 installation_attempt = *attempts;
670 if installation_attempt > prettier::FAIL_THRESHOLD {
671 *installation_task = None;
672 log::warn!(
673 "Default prettier installation had failed {installation_attempt} times, not attempting again",
674 );
675 return;
676 }
677 new_plugins.extend(not_installed_plugins.iter().cloned());
678 installation_task.clone()
679 }
680 PrettierInstallation::Installed { .. } => {
681 if new_plugins.is_empty() {
682 return;
683 }
684 None
685 }
686 };
687
688 log::info!("Initializing default prettier with plugins {new_plugins:?}");
689 let plugins_to_install = new_plugins.clone();
690 let fs = Arc::clone(&self.fs);
691 let new_installation_task = cx
692 .spawn(|project, mut cx| async move {
693 match locate_prettier_installation
694 .await
695 .context("locate prettier installation")
696 .map_err(Arc::new)?
697 {
698 ControlFlow::Break(()) => return Ok(()),
699 ControlFlow::Continue(prettier_path) => {
700 if prettier_path.is_some() {
701 new_plugins.clear();
702 }
703 let mut needs_install = should_write_prettier_server_file(fs.as_ref()).await;
704 if let Some(previous_installation_task) = previous_installation_task {
705 if let Err(e) = previous_installation_task.await {
706 log::error!("Failed to install default prettier: {e:#}");
707 project.update(&mut cx, |project, _| {
708 if let PrettierInstallation::NotInstalled { attempts, not_installed_plugins, .. } = &mut project.default_prettier.prettier {
709 *attempts += 1;
710 new_plugins.extend(not_installed_plugins.iter().cloned());
711 installation_attempt = *attempts;
712 needs_install = true;
713 };
714 })?;
715 }
716 };
717 if installation_attempt > prettier::FAIL_THRESHOLD {
718 project.update(&mut cx, |project, _| {
719 if let PrettierInstallation::NotInstalled { installation_task, .. } = &mut project.default_prettier.prettier {
720 *installation_task = None;
721 };
722 })?;
723 log::warn!(
724 "Default prettier installation had failed {installation_attempt} times, not attempting again",
725 );
726 return Ok(());
727 }
728 project.update(&mut cx, |project, _| {
729 new_plugins.retain(|plugin| {
730 !project.default_prettier.installed_plugins.contains(plugin)
731 });
732 if let PrettierInstallation::NotInstalled { not_installed_plugins, .. } = &mut project.default_prettier.prettier {
733 not_installed_plugins.retain(|plugin| {
734 !project.default_prettier.installed_plugins.contains(plugin)
735 });
736 not_installed_plugins.extend(new_plugins.iter().cloned());
737 }
738 needs_install |= !new_plugins.is_empty();
739 })?;
740 if needs_install {
741 let installed_plugins = new_plugins.clone();
742 cx.background_executor()
743 .spawn(async move {
744 install_prettier_packages(fs.as_ref(), new_plugins, node).await?;
745 // Save the server file last, so the reinstall need could be determined by the absence of the file.
746 save_prettier_server_file(fs.as_ref()).await?;
747 anyhow::Ok(())
748 })
749 .await
750 .context("prettier & plugins install")
751 .map_err(Arc::new)?;
752 log::info!("Initialized prettier with plugins: {installed_plugins:?}");
753 project.update(&mut cx, |project, _| {
754 project.default_prettier.prettier =
755 PrettierInstallation::Installed(PrettierInstance {
756 attempt: 0,
757 prettier: None,
758 });
759 project.default_prettier
760 .installed_plugins
761 .extend(installed_plugins);
762 })?;
763 }
764 }
765 }
766 Ok(())
767 })
768 .shared();
769 self.default_prettier.prettier = PrettierInstallation::NotInstalled {
770 attempts: installation_attempt,
771 installation_task: Some(new_installation_task),
772 not_installed_plugins: plugins_to_install,
773 };
774 }
775}