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},
 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, rel_path::RelPath};
 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<RelPath>, ProjectEntryId, PathChange)],
446        cx: &mut Context<Self>,
447    ) {
448        let prettier_config_files = Prettier::CONFIG_FILE_NAMES
449            .iter()
450            .map(|name| RelPath::unix(name).unwrap())
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 == "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    let formatters = language_settings.formatter.as_ref();
704    if formatters.contains(&Formatter::Prettier) || formatters.contains(&Formatter::Auto) {
705        return Some(&language_settings.prettier.plugins);
706    }
707    None
708}
709
710pub(super) async fn format_with_prettier(
711    prettier_store: &WeakEntity<PrettierStore>,
712    buffer: &Entity<Buffer>,
713    cx: &mut AsyncApp,
714) -> Option<Result<language::Diff>> {
715    let prettier_instance = prettier_store
716        .update(cx, |prettier_store, cx| {
717            prettier_store.prettier_instance_for_buffer(buffer, cx)
718        })
719        .ok()?
720        .await;
721
722    let ignore_dir = prettier_store
723        .update(cx, |prettier_store, cx| {
724            prettier_store.prettier_ignore_for_buffer(buffer, cx)
725        })
726        .ok()?
727        .await;
728
729    let (prettier_path, prettier_task) = prettier_instance?;
730
731    let prettier_description = match prettier_path.as_ref() {
732        Some(path) => format!("prettier at {path:?}"),
733        None => "default prettier instance".to_string(),
734    };
735
736    match prettier_task.await {
737        Ok(prettier) => {
738            let buffer_path = buffer
739                .update(cx, |buffer, cx| {
740                    File::from_dyn(buffer.file()).map(|file| file.abs_path(cx))
741                })
742                .ok()
743                .flatten();
744
745            let format_result = prettier
746                .format(buffer, buffer_path, ignore_dir, cx)
747                .await
748                .with_context(|| format!("{} failed to format buffer", prettier_description));
749
750            Some(format_result)
751        }
752        Err(error) => {
753            prettier_store
754                .update(cx, |project, _| {
755                    let instance_to_update = match prettier_path {
756                        Some(prettier_path) => project.prettier_instances.get_mut(&prettier_path),
757                        None => match &mut project.default_prettier.prettier {
758                            PrettierInstallation::NotInstalled { .. } => None,
759                            PrettierInstallation::Installed(instance) => Some(instance),
760                        },
761                    };
762
763                    if let Some(instance) = instance_to_update {
764                        instance.attempt += 1;
765                        instance.prettier = None;
766                    }
767                })
768                .log_err();
769
770            Some(Err(anyhow!(
771                "{prettier_description} failed to spawn: {error:#}"
772            )))
773        }
774    }
775}
776
777#[derive(Debug)]
778pub struct DefaultPrettier {
779    prettier: PrettierInstallation,
780    installed_plugins: HashSet<Arc<str>>,
781}
782
783#[derive(Debug)]
784pub enum PrettierInstallation {
785    NotInstalled {
786        attempts: usize,
787        installation_task: Option<Shared<Task<Result<(), Arc<anyhow::Error>>>>>,
788        not_installed_plugins: HashSet<Arc<str>>,
789    },
790    Installed(PrettierInstance),
791}
792
793pub type PrettierTask = Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>;
794
795#[derive(Debug, Clone)]
796pub struct PrettierInstance {
797    attempt: usize,
798    prettier: Option<PrettierTask>,
799}
800
801impl Default for DefaultPrettier {
802    fn default() -> Self {
803        Self {
804            prettier: PrettierInstallation::NotInstalled {
805                attempts: 0,
806                installation_task: None,
807                not_installed_plugins: HashSet::default(),
808            },
809            installed_plugins: HashSet::default(),
810        }
811    }
812}
813
814impl DefaultPrettier {
815    pub const fn instance(&self) -> Option<&PrettierInstance> {
816        if let PrettierInstallation::Installed(instance) = &self.prettier {
817            Some(instance)
818        } else {
819            None
820        }
821    }
822
823    pub fn prettier_task(
824        &mut self,
825        node: &NodeRuntime,
826        worktree_id: Option<WorktreeId>,
827        cx: &mut Context<PrettierStore>,
828    ) -> Option<Task<anyhow::Result<PrettierTask>>> {
829        match &mut self.prettier {
830            PrettierInstallation::NotInstalled { .. } => Some(
831                PrettierStore::start_default_prettier(node.clone(), worktree_id, cx),
832            ),
833            PrettierInstallation::Installed(existing_instance) => {
834                existing_instance.prettier_task(node, None, worktree_id, cx)
835            }
836        }
837    }
838}
839
840impl PrettierInstance {
841    pub fn prettier_task(
842        &mut self,
843        node: &NodeRuntime,
844        prettier_dir: Option<&Path>,
845        worktree_id: Option<WorktreeId>,
846        cx: &mut Context<PrettierStore>,
847    ) -> Option<Task<anyhow::Result<PrettierTask>>> {
848        if self.attempt > prettier::FAIL_THRESHOLD {
849            match prettier_dir {
850                Some(prettier_dir) => log::warn!(
851                    "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting"
852                ),
853                None => log::warn!("Default prettier exceeded launch threshold, not starting"),
854            }
855            return None;
856        }
857        Some(match &self.prettier {
858            Some(prettier_task) => Task::ready(Ok(prettier_task.clone())),
859            None => match prettier_dir {
860                Some(prettier_dir) => {
861                    let new_task = PrettierStore::start_prettier(
862                        node.clone(),
863                        prettier_dir.to_path_buf(),
864                        worktree_id,
865                        cx,
866                    );
867                    self.attempt += 1;
868                    self.prettier = Some(new_task.clone());
869                    Task::ready(Ok(new_task))
870                }
871                None => {
872                    self.attempt += 1;
873                    let node = node.clone();
874                    cx.spawn(async move |prettier_store, cx| {
875                        prettier_store
876                            .update(cx, |_, cx| {
877                                PrettierStore::start_default_prettier(node, worktree_id, cx)
878                            })?
879                            .await
880                    })
881                }
882            },
883        })
884    }
885
886    pub async fn server(&self) -> Option<Arc<LanguageServer>> {
887        self.prettier.clone()?.await.ok()?.server().cloned()
888    }
889}
890
891async fn install_prettier_packages(
892    fs: &dyn Fs,
893    plugins_to_install: HashSet<Arc<str>>,
894    node: NodeRuntime,
895) -> anyhow::Result<()> {
896    let packages_to_versions = future::try_join_all(
897        plugins_to_install
898            .iter()
899            .chain(Some(&"prettier".into()))
900            .map(|package_name| async {
901                let returned_package_name = package_name.to_string();
902                let latest_version = node
903                    .npm_package_latest_version(package_name)
904                    .await
905                    .with_context(|| {
906                        format!("fetching latest npm version for package {returned_package_name}")
907                    })?;
908                anyhow::Ok((returned_package_name, latest_version))
909            }),
910    )
911    .await
912    .context("fetching latest npm versions")?;
913
914    let default_prettier_dir = default_prettier_dir().as_path();
915    match fs.metadata(default_prettier_dir).await.with_context(|| {
916        format!("fetching FS metadata for default prettier dir {default_prettier_dir:?}")
917    })? {
918        Some(prettier_dir_metadata) => anyhow::ensure!(
919            prettier_dir_metadata.is_dir,
920            "default prettier dir {default_prettier_dir:?} is not a directory"
921        ),
922        None => fs
923            .create_dir(default_prettier_dir)
924            .await
925            .with_context(|| format!("creating default prettier dir {default_prettier_dir:?}"))?,
926    }
927
928    log::info!("Installing default prettier and plugins: {packages_to_versions:?}");
929    let borrowed_packages = packages_to_versions
930        .iter()
931        .map(|(package, version)| (package.as_str(), version.as_str()))
932        .collect::<Vec<_>>();
933    node.npm_install_packages(default_prettier_dir, &borrowed_packages)
934        .await
935        .context("fetching formatter packages")?;
936    anyhow::Ok(())
937}
938
939async fn save_prettier_server_file(fs: &dyn Fs) -> anyhow::Result<()> {
940    let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
941    fs.save(
942        &prettier_wrapper_path,
943        &text::Rope::from(prettier::PRETTIER_SERVER_JS),
944        text::LineEnding::Unix,
945    )
946    .await
947    .with_context(|| {
948        format!(
949            "writing {} file at {prettier_wrapper_path:?}",
950            prettier::PRETTIER_SERVER_FILE
951        )
952    })?;
953    Ok(())
954}
955
956async fn should_write_prettier_server_file(fs: &dyn Fs) -> bool {
957    let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
958    if !fs.is_file(&prettier_wrapper_path).await {
959        return true;
960    }
961    let Ok(prettier_server_file_contents) = fs.load(&prettier_wrapper_path).await else {
962        return true;
963    };
964    prettier_server_file_contents != prettier::PRETTIER_SERVER_JS
965}