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