prettier_store.rs

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