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                            if 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                        };
606                        if installation_attempt > prettier::FAIL_THRESHOLD {
607                            prettier_store.update(cx, |prettier_store, _| {
608                                if let PrettierInstallation::NotInstalled { installation_task, .. } = &mut prettier_store.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                        prettier_store.update(cx, |prettier_store, _| {
618                            new_plugins.retain(|plugin| {
619                                !prettier_store.default_prettier.installed_plugins.contains(plugin)
620                            });
621                            if let PrettierInstallation::NotInstalled { not_installed_plugins, .. } = &mut prettier_store.default_prettier.prettier {
622                                not_installed_plugins.retain(|plugin| {
623                                    !prettier_store.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                            log::info!("Initializing default prettier with plugins {new_plugins:?}");
631                            let installed_plugins = new_plugins.clone();
632                            cx.background_spawn(async move {
633                                install_prettier_packages(fs.as_ref(), new_plugins, node).await?;
634                                // Save the server file last, so the reinstall need could be determined by the absence of the file.
635                                save_prettier_server_file(fs.as_ref()).await?;
636                                anyhow::Ok(())
637                            })
638                                .await
639                                .context("prettier & plugins install")
640                                .map_err(Arc::new)?;
641                            log::info!("Initialized default prettier with plugins: {installed_plugins:?}");
642                            prettier_store.update(cx, |prettier_store, _| {
643                                prettier_store.default_prettier.prettier =
644                                    PrettierInstallation::Installed(PrettierInstance {
645                                        attempt: 0,
646                                        prettier: None,
647                                    });
648                                prettier_store.default_prettier
649                                    .installed_plugins
650                                    .extend(installed_plugins);
651                            })?;
652                        } else {
653                            prettier_store.update(cx, |prettier_store, _| {
654                                if let PrettierInstallation::NotInstalled { .. } = &mut prettier_store.default_prettier.prettier {
655                                    prettier_store.default_prettier.prettier =
656                                        PrettierInstallation::Installed(PrettierInstance {
657                                            attempt: 0,
658                                            prettier: None,
659                                        });
660                                }
661                            })?;
662                        }
663                    }
664                }
665                Ok(())
666            })
667            .shared();
668        self.default_prettier.prettier = PrettierInstallation::NotInstalled {
669            attempts: installation_attempt,
670            installation_task: Some(new_installation_task),
671            not_installed_plugins: plugins_to_install,
672        };
673    }
674
675    pub fn on_settings_changed(
676        &mut self,
677        language_formatters_to_check: Vec<(Option<WorktreeId>, LanguageSettings)>,
678        cx: &mut Context<Self>,
679    ) {
680        let mut prettier_plugins_by_worktree = HashMap::default();
681        for (worktree, language_settings) in language_formatters_to_check {
682            if language_settings.prettier.allowed {
683                if let Some(plugins) = prettier_plugins_for_language(&language_settings) {
684                    prettier_plugins_by_worktree
685                        .entry(worktree)
686                        .or_insert_with(HashSet::default)
687                        .extend(plugins.iter().cloned());
688                }
689            }
690        }
691        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
692            self.install_default_prettier(
693                worktree,
694                prettier_plugins.into_iter().map(Arc::from),
695                cx,
696            );
697        }
698    }
699}
700
701pub fn prettier_plugins_for_language(
702    language_settings: &LanguageSettings,
703) -> Option<&HashSet<String>> {
704    match &language_settings.formatter {
705        SelectedFormatter::Auto => Some(&language_settings.prettier.plugins),
706
707        SelectedFormatter::List(list) => list
708            .as_ref()
709            .contains(&Formatter::Prettier)
710            .then_some(&language_settings.prettier.plugins),
711    }
712}
713
714pub(super) async fn format_with_prettier(
715    prettier_store: &WeakEntity<PrettierStore>,
716    buffer: &Entity<Buffer>,
717    cx: &mut AsyncApp,
718) -> Option<Result<language::Diff>> {
719    let prettier_instance = prettier_store
720        .update(cx, |prettier_store, cx| {
721            prettier_store.prettier_instance_for_buffer(buffer, cx)
722        })
723        .ok()?
724        .await;
725
726    let ignore_dir = prettier_store
727        .update(cx, |prettier_store, cx| {
728            prettier_store.prettier_ignore_for_buffer(buffer, cx)
729        })
730        .ok()?
731        .await;
732
733    let (prettier_path, prettier_task) = prettier_instance?;
734
735    let prettier_description = match prettier_path.as_ref() {
736        Some(path) => format!("prettier at {path:?}"),
737        None => "default prettier instance".to_string(),
738    };
739
740    match prettier_task.await {
741        Ok(prettier) => {
742            let buffer_path = buffer
743                .update(cx, |buffer, cx| {
744                    File::from_dyn(buffer.file()).map(|file| file.abs_path(cx))
745                })
746                .ok()
747                .flatten();
748
749            let format_result = prettier
750                .format(buffer, buffer_path, ignore_dir, cx)
751                .await
752                .with_context(|| format!("{} failed to format buffer", prettier_description));
753
754            Some(format_result)
755        }
756        Err(error) => {
757            prettier_store
758                .update(cx, |project, _| {
759                    let instance_to_update = match prettier_path {
760                        Some(prettier_path) => project.prettier_instances.get_mut(&prettier_path),
761                        None => match &mut project.default_prettier.prettier {
762                            PrettierInstallation::NotInstalled { .. } => None,
763                            PrettierInstallation::Installed(instance) => Some(instance),
764                        },
765                    };
766
767                    if let Some(instance) = instance_to_update {
768                        instance.attempt += 1;
769                        instance.prettier = None;
770                    }
771                })
772                .log_err();
773
774            Some(Err(anyhow!(
775                "{prettier_description} failed to spawn: {error:#}"
776            )))
777        }
778    }
779}
780
781#[derive(Debug)]
782pub struct DefaultPrettier {
783    prettier: PrettierInstallation,
784    installed_plugins: HashSet<Arc<str>>,
785}
786
787#[derive(Debug)]
788pub enum PrettierInstallation {
789    NotInstalled {
790        attempts: usize,
791        installation_task: Option<Shared<Task<Result<(), Arc<anyhow::Error>>>>>,
792        not_installed_plugins: HashSet<Arc<str>>,
793    },
794    Installed(PrettierInstance),
795}
796
797pub type PrettierTask = Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>;
798
799#[derive(Debug, Clone)]
800pub struct PrettierInstance {
801    attempt: usize,
802    prettier: Option<PrettierTask>,
803}
804
805impl Default for DefaultPrettier {
806    fn default() -> Self {
807        Self {
808            prettier: PrettierInstallation::NotInstalled {
809                attempts: 0,
810                installation_task: None,
811                not_installed_plugins: HashSet::default(),
812            },
813            installed_plugins: HashSet::default(),
814        }
815    }
816}
817
818impl DefaultPrettier {
819    pub fn instance(&self) -> Option<&PrettierInstance> {
820        if let PrettierInstallation::Installed(instance) = &self.prettier {
821            Some(instance)
822        } else {
823            None
824        }
825    }
826
827    pub fn prettier_task(
828        &mut self,
829        node: &NodeRuntime,
830        worktree_id: Option<WorktreeId>,
831        cx: &mut Context<PrettierStore>,
832    ) -> Option<Task<anyhow::Result<PrettierTask>>> {
833        match &mut self.prettier {
834            PrettierInstallation::NotInstalled { .. } => Some(
835                PrettierStore::start_default_prettier(node.clone(), worktree_id, cx),
836            ),
837            PrettierInstallation::Installed(existing_instance) => {
838                existing_instance.prettier_task(node, None, worktree_id, cx)
839            }
840        }
841    }
842}
843
844impl PrettierInstance {
845    pub fn prettier_task(
846        &mut self,
847        node: &NodeRuntime,
848        prettier_dir: Option<&Path>,
849        worktree_id: Option<WorktreeId>,
850        cx: &mut Context<PrettierStore>,
851    ) -> Option<Task<anyhow::Result<PrettierTask>>> {
852        if self.attempt > prettier::FAIL_THRESHOLD {
853            match prettier_dir {
854                Some(prettier_dir) => log::warn!(
855                    "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting"
856                ),
857                None => log::warn!("Default prettier exceeded launch threshold, not starting"),
858            }
859            return None;
860        }
861        Some(match &self.prettier {
862            Some(prettier_task) => Task::ready(Ok(prettier_task.clone())),
863            None => match prettier_dir {
864                Some(prettier_dir) => {
865                    let new_task = PrettierStore::start_prettier(
866                        node.clone(),
867                        prettier_dir.to_path_buf(),
868                        worktree_id,
869                        cx,
870                    );
871                    self.attempt += 1;
872                    self.prettier = Some(new_task.clone());
873                    Task::ready(Ok(new_task))
874                }
875                None => {
876                    self.attempt += 1;
877                    let node = node.clone();
878                    cx.spawn(async move |prettier_store, cx| {
879                        prettier_store
880                            .update(cx, |_, cx| {
881                                PrettierStore::start_default_prettier(node, worktree_id, cx)
882                            })?
883                            .await
884                    })
885                }
886            },
887        })
888    }
889
890    pub async fn server(&self) -> Option<Arc<LanguageServer>> {
891        self.prettier.clone()?.await.ok()?.server().cloned()
892    }
893}
894
895async fn install_prettier_packages(
896    fs: &dyn Fs,
897    plugins_to_install: HashSet<Arc<str>>,
898    node: NodeRuntime,
899) -> anyhow::Result<()> {
900    let packages_to_versions = future::try_join_all(
901        plugins_to_install
902            .iter()
903            .chain(Some(&"prettier".into()))
904            .map(|package_name| async {
905                let returned_package_name = package_name.to_string();
906                let latest_version = node
907                    .npm_package_latest_version(package_name)
908                    .await
909                    .with_context(|| {
910                        format!("fetching latest npm version for package {returned_package_name}")
911                    })?;
912                anyhow::Ok((returned_package_name, latest_version))
913            }),
914    )
915    .await
916    .context("fetching latest npm versions")?;
917
918    let default_prettier_dir = default_prettier_dir().as_path();
919    match fs.metadata(default_prettier_dir).await.with_context(|| {
920        format!("fetching FS metadata for default prettier dir {default_prettier_dir:?}")
921    })? {
922        Some(prettier_dir_metadata) => anyhow::ensure!(
923            prettier_dir_metadata.is_dir,
924            "default prettier dir {default_prettier_dir:?} is not a directory"
925        ),
926        None => fs
927            .create_dir(default_prettier_dir)
928            .await
929            .with_context(|| format!("creating default prettier dir {default_prettier_dir:?}"))?,
930    }
931
932    log::info!("Installing default prettier and plugins: {packages_to_versions:?}");
933    let borrowed_packages = packages_to_versions
934        .iter()
935        .map(|(package, version)| (package.as_str(), version.as_str()))
936        .collect::<Vec<_>>();
937    node.npm_install_packages(default_prettier_dir, &borrowed_packages)
938        .await
939        .context("fetching formatter packages")?;
940    anyhow::Ok(())
941}
942
943async fn save_prettier_server_file(fs: &dyn Fs) -> anyhow::Result<()> {
944    let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
945    fs.save(
946        &prettier_wrapper_path,
947        &text::Rope::from(prettier::PRETTIER_SERVER_JS),
948        text::LineEnding::Unix,
949    )
950    .await
951    .with_context(|| {
952        format!(
953            "writing {} file at {prettier_wrapper_path:?}",
954            prettier::PRETTIER_SERVER_FILE
955        )
956    })?;
957    Ok(())
958}
959
960async fn should_write_prettier_server_file(fs: &dyn Fs) -> bool {
961    let prettier_wrapper_path = default_prettier_dir().join(prettier::PRETTIER_SERVER_FILE);
962    if !fs.is_file(&prettier_wrapper_path).await {
963        return true;
964    }
965    let Ok(prettier_server_file_contents) = fs.load(&prettier_wrapper_path).await else {
966        return true;
967    };
968    prettier_server_file_contents != prettier::PRETTIER_SERVER_JS
969}