prettier_store.rs

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