From d010f5f98db5f0c930d4441d058bcf017899fcbd Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Mon, 27 Nov 2023 12:54:35 +0200 Subject: [PATCH 01/16] Exctract the common code --- crates/project/src/project.rs | 168 ++++++++++++++-------------------- 1 file changed, 69 insertions(+), 99 deletions(-) diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index cf3fa547f69338a229d53734172c0e60f74e643c..d7b10cad7c93f0bcebbeed3ac54ef9db60b9c248 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -170,11 +170,13 @@ pub struct Project { node: Option>, default_prettier: Option, prettiers_per_worktree: HashMap>>, - prettier_instances: HashMap, Arc>>>>, + prettier_instances: HashMap, } +type PrettierInstance = Shared, Arc>>>; + struct DefaultPrettier { - instance: Option, Arc>>>>, + instance: Option, installation_process: Option>>>>, #[cfg(not(any(test, feature = "test-support")))] installed_plugins: HashSet<&'static str>, @@ -542,6 +544,14 @@ struct ProjectLspAdapterDelegate { http_client: Arc, } +// Currently, formatting operations are represented differently depending on +// whether they come from a language server or an external command. +enum FormatOperation { + Lsp(Vec<(Range, String)>), + External(Diff), + Prettier(Diff), +} + impl FormatTrigger { fn from_proto(value: i32) -> FormatTrigger { match value { @@ -4099,14 +4109,6 @@ impl Project { buffer.end_transaction(cx) }); - // Currently, formatting operations are represented differently depending on - // whether they come from a language server or an external command. - enum FormatOperation { - Lsp(Vec<(Range, String)>), - External(Diff), - Prettier(Diff), - } - // Apply language-specific formatting using either a language server // or external command. let mut format_operation = None; @@ -4155,46 +4157,10 @@ impl Project { } } (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => { - if let Some((prettier_path, prettier_task)) = project - .update(&mut cx, |project, cx| { - project.prettier_instance_for_buffer(buffer, cx) - }).await { - match prettier_task.await - { - Ok(prettier) => { - let buffer_path = buffer.update(&mut cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - }); - format_operation = Some(FormatOperation::Prettier( - prettier - .format(buffer, buffer_path, &cx) - .await - .context("formatting via prettier")?, - )); - } - Err(e) => { - project.update(&mut cx, |project, _| { - match &prettier_path { - Some(prettier_path) => { - project.prettier_instances.remove(prettier_path); - }, - None => { - if let Some(default_prettier) = project.default_prettier.as_mut() { - default_prettier.instance = None; - } - }, - } - }); - match &prettier_path { - Some(prettier_path) => { - log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}"); - }, - None => { - log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}"); - }, - } - } - } + if let Some(new_operation) = + format_with_prettier(&project, buffer, &mut cx).await + { + format_operation = Some(new_operation); } else if let Some((language_server, buffer_abs_path)) = language_server.as_ref().zip(buffer_abs_path.as_ref()) { @@ -4213,47 +4179,11 @@ impl Project { } } (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => { - if let Some((prettier_path, prettier_task)) = project - .update(&mut cx, |project, cx| { - project.prettier_instance_for_buffer(buffer, cx) - }).await { - match prettier_task.await - { - Ok(prettier) => { - let buffer_path = buffer.update(&mut cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - }); - format_operation = Some(FormatOperation::Prettier( - prettier - .format(buffer, buffer_path, &cx) - .await - .context("formatting via prettier")?, - )); - } - Err(e) => { - project.update(&mut cx, |project, _| { - match &prettier_path { - Some(prettier_path) => { - project.prettier_instances.remove(prettier_path); - }, - None => { - if let Some(default_prettier) = project.default_prettier.as_mut() { - default_prettier.instance = None; - } - }, - } - }); - match &prettier_path { - Some(prettier_path) => { - log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}"); - }, - None => { - log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}"); - }, - } - } - } - } + if let Some(new_operation) = + format_with_prettier(&project, buffer, &mut cx).await + { + format_operation = Some(new_operation); + } } }; @@ -8541,12 +8471,7 @@ impl Project { &mut self, buffer: &ModelHandle, cx: &mut ModelContext, - ) -> Task< - Option<( - Option, - Shared, Arc>>>, - )>, - > { + ) -> Task, PrettierInstance)>> { let buffer = buffer.read(cx); let buffer_file = buffer.file(); let Some(buffer_language) = buffer.language() else { @@ -8814,7 +8739,7 @@ fn start_default_prettier( node: Arc, worktree_id: Option, cx: &mut ModelContext<'_, Project>, -) -> Task, Arc>>>> { +) -> Task { cx.spawn(|project, mut cx| async move { loop { let default_prettier_installing = project.update(&mut cx, |project, _| { @@ -8864,7 +8789,7 @@ fn start_prettier( prettier_dir: PathBuf, worktree_id: Option, cx: &mut ModelContext<'_, Project>, -) -> Shared, Arc>>> { +) -> PrettierInstance { cx.spawn(|project, mut cx| async move { let new_server_id = project.update(&mut cx, |project, _| { project.languages.next_language_server_id() @@ -9281,3 +9206,48 @@ fn include_text(server: &lsp::LanguageServer) -> bool { }) .unwrap_or(false) } + +async fn format_with_prettier( + project: &ModelHandle, + buffer: &ModelHandle, + cx: &mut AsyncAppContext, +) -> Option { + if let Some((prettier_path, prettier_task)) = project + .update(cx, |project, cx| { + project.prettier_instance_for_buffer(buffer, cx) + }) + .await + { + match prettier_task.await { + Ok(prettier) => { + let buffer_path = buffer.update(cx, |buffer, cx| { + File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) + }); + match prettier.format(buffer, buffer_path, cx).await { + Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), + Err(e) => { + log::error!( + "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" + ); + } + } + } + Err(e) => { + project.update(cx, |project, _| match &prettier_path { + Some(prettier_path) => { + log::error!("Failed to create prettier instance from {prettier_path:?} for buffer: {e:#}"); + project.prettier_instances.remove(prettier_path); + } + None => { + log::error!("Failed to create default prettier instance from {prettier_path:?} for buffer: {e:#}"); + if let Some(default_prettier) = project.default_prettier.as_mut() { + default_prettier.instance = None; + } + } + }); + } + } + } + + None +} From c288c6eaf9e063fa50c38455eec79c9bab61a0f0 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Mon, 27 Nov 2023 15:13:10 +0200 Subject: [PATCH 02/16] Use enum variants for prettier installation and startup phases --- crates/prettier/src/prettier.rs | 4 + crates/project/src/project.rs | 442 ++++++++++++++++---------------- 2 files changed, 226 insertions(+), 220 deletions(-) diff --git a/crates/prettier/src/prettier.rs b/crates/prettier/src/prettier.rs index cb9d32d0b05115e1e9b3176c38ed6caf4b98ec49..61a6656ea4136c7f9345a32569fba3cdf6d193f5 100644 --- a/crates/prettier/src/prettier.rs +++ b/crates/prettier/src/prettier.rs @@ -13,12 +13,14 @@ use node_runtime::NodeRuntime; use serde::{Deserialize, Serialize}; use util::paths::{PathMatcher, DEFAULT_PRETTIER_DIR}; +#[derive(Clone)] pub enum Prettier { Real(RealPrettier), #[cfg(any(test, feature = "test-support"))] Test(TestPrettier), } +#[derive(Clone)] pub struct RealPrettier { default: bool, prettier_dir: PathBuf, @@ -26,11 +28,13 @@ pub struct RealPrettier { } #[cfg(any(test, feature = "test-support"))] +#[derive(Clone)] pub struct TestPrettier { prettier_dir: PathBuf, default: bool, } +pub const LAUNCH_THRESHOLD: usize = 5; pub const PRETTIER_SERVER_FILE: &str = "prettier_server.js"; pub const PRETTIER_SERVER_JS: &str = include_str!("./prettier_server.js"); const PRETTIER_PACKAGE_NAME: &str = "prettier"; diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index d7b10cad7c93f0bcebbeed3ac54ef9db60b9c248..52b011cb2a26ce052963d1a2b27269f6890bc842 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -168,20 +168,54 @@ pub struct Project { copilot_log_subscription: Option, current_lsp_settings: HashMap, LspSettings>, node: Option>, - default_prettier: Option, + default_prettier: DefaultPrettier, prettiers_per_worktree: HashMap>>, prettier_instances: HashMap, } -type PrettierInstance = Shared, Arc>>>; +type PrettierInstance = Shared>; + +#[derive(Clone)] +enum PrettierProcess { + Running(Arc), + Stopped { start_attempts: usize }, +} struct DefaultPrettier { - instance: Option, - installation_process: Option>>>>, - #[cfg(not(any(test, feature = "test-support")))] + prettier: PrettierInstallation, installed_plugins: HashSet<&'static str>, } +enum PrettierInstallation { + NotInstalled { + attempts: usize, + installation_process: Option>>>>, + }, + Installed(PrettierInstance), +} + +impl Default for DefaultPrettier { + fn default() -> Self { + Self { + prettier: PrettierInstallation::NotInstalled { + attempts: 0, + installation_process: None, + }, + installed_plugins: HashSet::default(), + } + } +} + +impl DefaultPrettier { + fn instance(&self) -> Option<&PrettierInstance> { + if let PrettierInstallation::Installed(instance) = &self.prettier { + Some(instance) + } else { + None + } + } +} + struct DelayedDebounced { task: Option>, cancel_channel: Option>, @@ -700,7 +734,7 @@ impl Project { copilot_log_subscription: None, current_lsp_settings: settings::get::(cx).lsp.clone(), node: Some(node), - default_prettier: None, + default_prettier: DefaultPrettier::default(), prettiers_per_worktree: HashMap::default(), prettier_instances: HashMap::default(), } @@ -801,7 +835,7 @@ impl Project { copilot_log_subscription: None, current_lsp_settings: settings::get::(cx).lsp.clone(), node: None, - default_prettier: None, + default_prettier: DefaultPrettier::default(), prettiers_per_worktree: HashMap::default(), prettier_instances: HashMap::default(), }; @@ -6521,55 +6555,45 @@ impl Project { log::info!( "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}" ); - let prettiers_to_reload = self - .prettiers_per_worktree - .get(¤t_worktree_id) - .iter() - .flat_map(|prettier_paths| prettier_paths.iter()) - .flatten() - .filter_map(|prettier_path| { - Some(( - current_worktree_id, - Some(prettier_path.clone()), - self.prettier_instances.get(prettier_path)?.clone(), - )) - }) - .chain(self.default_prettier.iter().filter_map(|default_prettier| { - Some(( - current_worktree_id, - None, - default_prettier.instance.clone()?, - )) - })) - .collect::>(); + let prettiers_to_reload = + self.prettiers_per_worktree + .get(¤t_worktree_id) + .iter() + .flat_map(|prettier_paths| prettier_paths.iter()) + .flatten() + .filter_map(|prettier_path| { + Some(( + current_worktree_id, + Some(prettier_path.clone()), + self.prettier_instances.get(prettier_path)?.clone(), + )) + }) + .chain(self.default_prettier.instance().map(|default_prettier| { + (current_worktree_id, None, default_prettier.clone()) + })) + .collect::>(); cx.background() .spawn(async move { - for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| { + let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| { async move { - prettier_task.await? - .clear_cache() - .await - .with_context(|| { - match prettier_path { - Some(prettier_path) => format!( - "clearing prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update" - ), - None => format!( - "clearing default prettier cache for worktree {worktree_id:?} on prettier settings update" - ), - } - - }) - .map_err(Arc::new) + if let PrettierProcess::Running(prettier) = prettier_task.await { + if let Err(e) = prettier + .clear_cache() + .await { + match prettier_path { + Some(prettier_path) => log::error!( + "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + None => log::error!( + "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + } + } + } } })) - .await - { - if let Err(e) = task_result { - log::error!("Failed to clear cache for prettier: {e:#}"); - } - } + .await; }) .detach(); } @@ -8514,19 +8538,23 @@ impl Project { .entry(worktree_id) .or_default() .insert(None); - project.default_prettier.as_ref().and_then( - |default_prettier| default_prettier.instance.clone(), - ) + project.default_prettier.instance().cloned() }); match started_default_prettier { - Some(old_task) => return Some((None, old_task)), + Some(old_task) => { + dbg!("Old prettier was found!"); + return Some((None, old_task)); + } None => { + dbg!("starting new default prettier"); let new_default_prettier = project .update(&mut cx, |_, cx| { start_default_prettier(node, Some(worktree_id), cx) }) + .log_err() .await; - return Some((None, new_default_prettier)); + dbg!("started a default prettier"); + return Some((None, new_default_prettier?)); } } } @@ -8565,52 +8593,37 @@ impl Project { Some((Some(prettier_dir), new_prettier_task)) } Err(e) => { - return Some(( - None, - Task::ready(Err(Arc::new( - e.context("determining prettier path"), - ))) - .shared(), - )); + log::error!("Failed to determine prettier path for buffer: {e:#}"); + return None; } } }); } - None => { - let started_default_prettier = self - .default_prettier - .as_ref() - .and_then(|default_prettier| default_prettier.instance.clone()); - match started_default_prettier { - Some(old_task) => return Task::ready(Some((None, old_task))), - None => { - let new_task = start_default_prettier(node, None, cx); - return cx.spawn(|_, _| async move { Some((None, new_task.await)) }); - } + None => match self.default_prettier.instance().cloned() { + Some(old_task) => return Task::ready(Some((None, old_task))), + None => { + let new_task = start_default_prettier(node, None, cx).log_err(); + return cx.spawn(|_, _| async move { Some((None, new_task.await?)) }); } - } + }, } - } else if self.remote_id().is_some() { - return Task::ready(None); } else { - Task::ready(Some(( - None, - Task::ready(Err(Arc::new(anyhow!("project does not have a remote id")))).shared(), - ))) + return Task::ready(None); } } - #[cfg(any(test, feature = "test-support"))] - fn install_default_formatters( - &mut self, - _worktree: Option, - _new_language: &Language, - _language_settings: &LanguageSettings, - _cx: &mut ModelContext, - ) { - } + // TODO kb uncomment + // #[cfg(any(test, feature = "test-support"))] + // fn install_default_formatters( + // &mut self, + // _worktree: Option, + // _new_language: &Language, + // _language_settings: &LanguageSettings, + // _cx: &mut ModelContext, + // ) { + // } - #[cfg(not(any(test, feature = "test-support")))] + // #[cfg(not(any(test, feature = "test-support")))] fn install_default_formatters( &mut self, worktree: Option, @@ -8660,78 +8673,86 @@ impl Project { None => Task::ready(Ok(ControlFlow::Break(()))), }; let mut plugins_to_install = prettier_plugins; - let previous_installation_process = - if let Some(default_prettier) = &mut self.default_prettier { - plugins_to_install - .retain(|plugin| !default_prettier.installed_plugins.contains(plugin)); + plugins_to_install + .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); + let mut installation_attempts = 0; + let previous_installation_process = match &self.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_process, + attempts, + } => { + installation_attempts = *attempts; + installation_process.clone() + } + PrettierInstallation::Installed { .. } => { if plugins_to_install.is_empty() { return; } - default_prettier.installation_process.clone() - } else { None - }; + } + }; + + if installation_attempts > prettier::LAUNCH_THRESHOLD { + log::warn!( + "Default prettier installation has failed {installation_attempts} times, not attempting again", + ); + return; + } + let fs = Arc::clone(&self.fs); - let default_prettier = self - .default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: None, - installed_plugins: HashSet::default(), - }); - default_prettier.installation_process = Some( - cx.spawn(|this, mut cx| async move { - match locate_prettier_installation - .await - .context("locate prettier installation") - .map_err(Arc::new)? - { - ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), - ControlFlow::Continue(None) => { - let mut needs_install = match previous_installation_process { - Some(previous_installation_process) => { - previous_installation_process.await.is_err() - } - None => true, - }; - this.update(&mut cx, |this, _| { - if let Some(default_prettier) = &mut this.default_prettier { + self.default_prettier.prettier = PrettierInstallation::NotInstalled { + attempts: installation_attempts + 1, + installation_process: Some( + cx.spawn(|this, mut cx| async move { + match locate_prettier_installation + .await + .context("locate prettier installation") + .map_err(Arc::new)? + { + ControlFlow::Break(()) => return Ok(()), + ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), + ControlFlow::Continue(None) => { + let mut needs_install = match previous_installation_process { + Some(previous_installation_process) => { + previous_installation_process.await.is_err() + } + None => true, + }; + this.update(&mut cx, |this, _| { plugins_to_install.retain(|plugin| { - !default_prettier.installed_plugins.contains(plugin) + !this.default_prettier.installed_plugins.contains(plugin) }); needs_install |= !plugins_to_install.is_empty(); - } - }); - if needs_install { - let installed_plugins = plugins_to_install.clone(); - cx.background() - .spawn(async move { - install_default_prettier(plugins_to_install, node, fs).await - }) - .await - .context("prettier & plugins install") - .map_err(Arc::new)?; - this.update(&mut cx, |this, _| { - let default_prettier = - this.default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: Some( - Task::ready(Ok(())).shared(), - ), - installed_plugins: HashSet::default(), - }); - default_prettier.instance = None; - default_prettier.installed_plugins.extend(installed_plugins); }); + if needs_install { + let installed_plugins = plugins_to_install.clone(); + cx.background() + .spawn(async move { + install_default_prettier(plugins_to_install, node, fs).await + }) + .await + .context("prettier & plugins install") + .map_err(Arc::new)?; + this.update(&mut cx, |this, cx| { + this.default_prettier.prettier = + PrettierInstallation::Installed( + cx.spawn(|_, _| async move { + PrettierProcess::Stopped { start_attempts: 0 } + }) + .shared(), + ); + this.default_prettier + .installed_plugins + .extend(installed_plugins); + }); + } } } - } - Ok(()) - }) - .shared(), - ); + Ok(()) + }) + .shared(), + ), + }; } } @@ -8739,48 +8760,40 @@ fn start_default_prettier( node: Arc, worktree_id: Option, cx: &mut ModelContext<'_, Project>, -) -> Task { +) -> Task> { cx.spawn(|project, mut cx| async move { loop { - let default_prettier_installing = project.update(&mut cx, |project, _| { - project - .default_prettier - .as_ref() - .and_then(|default_prettier| default_prettier.installation_process.clone()) - }); - match default_prettier_installing { - Some(installation_task) => { - if installation_task.await.is_ok() { - break; + let installation_process = project.update(&mut cx, |project, _| { + match &project.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_process, + .. + } => ControlFlow::Continue(installation_process.clone()), + PrettierInstallation::Installed(default_prettier) => { + ControlFlow::Break(default_prettier.clone()) } } - None => break, - } - } + }); - project.update(&mut cx, |project, cx| { - match project - .default_prettier - .as_mut() - .and_then(|default_prettier| default_prettier.instance.as_mut()) - { - Some(default_prettier) => default_prettier.clone(), - None => { - let new_default_prettier = - start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); - project - .default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: None, - #[cfg(not(any(test, feature = "test-support")))] - installed_plugins: HashSet::default(), - }) - .instance = Some(new_default_prettier.clone()); - new_default_prettier + match installation_process { + ControlFlow::Continue(installation_process) => { + if let Some(installation_process) = installation_process.clone() { + if let Err(e) = installation_process.await { + anyhow::bail!("Cannot start default prettier due to its installation failure: {e:#}"); + } + } + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(new_default_prettier.clone()); + new_default_prettier + }); + return Ok(new_default_prettier); } + ControlFlow::Break(prettier) => return Ok(prettier), } - }) + } }) } @@ -8794,13 +8807,18 @@ fn start_prettier( let new_server_id = project.update(&mut cx, |project, _| { project.languages.next_language_server_id() }); - let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) - .await - .context("default prettier spawn") - .map(Arc::new) - .map_err(Arc::new)?; - register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); - Ok(new_prettier) + + match Prettier::start(new_server_id, prettier_dir.clone(), node, cx.clone()).await { + Ok(new_prettier) => { + register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); + PrettierProcess::Running(Arc::new(new_prettier)) + } + Err(e) => { + log::error!("Failed to start prettier in dir {prettier_dir:?}: {e:#}"); + // TODO kb increment + PrettierProcess::Stopped { start_attempts: 1 } + } + } }) .shared() } @@ -8855,7 +8873,6 @@ fn register_new_prettier( } } -#[cfg(not(any(test, feature = "test-support")))] async fn install_default_prettier( plugins_to_install: HashSet<&'static str>, node: Arc, @@ -9218,34 +9235,19 @@ async fn format_with_prettier( }) .await { - match prettier_task.await { - Ok(prettier) => { - let buffer_path = buffer.update(cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - }); - match prettier.format(buffer, buffer_path, cx).await { - Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), - Err(e) => { - log::error!( - "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" - ); - } + // TODO kb re-insert incremented value here? + if let PrettierProcess::Running(prettier) = prettier_task.await { + let buffer_path = buffer.update(cx, |buffer, cx| { + File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) + }); + match prettier.format(buffer, buffer_path, cx).await { + Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), + Err(e) => { + log::error!( + "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" + ); } } - Err(e) => { - project.update(cx, |project, _| match &prettier_path { - Some(prettier_path) => { - log::error!("Failed to create prettier instance from {prettier_path:?} for buffer: {e:#}"); - project.prettier_instances.remove(prettier_path); - } - None => { - log::error!("Failed to create default prettier instance from {prettier_path:?} for buffer: {e:#}"); - if let Some(default_prettier) = project.default_prettier.as_mut() { - default_prettier.instance = None; - } - } - }); - } } } From e7e56757dc1e0e4356c170887758f58a92c75461 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 00:40:01 +0200 Subject: [PATCH 03/16] Limit prettier installation and start attempts --- crates/project/src/project.rs | 291 +++++++++++++++++++++++----------- 1 file changed, 198 insertions(+), 93 deletions(-) diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index 52b011cb2a26ce052963d1a2b27269f6890bc842..13cee48feda3f66fad1988e5bd0271c551cbc4a7 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -173,12 +173,59 @@ pub struct Project { prettier_instances: HashMap, } -type PrettierInstance = Shared>; +type PrettierTask = Shared, Arc>>>; #[derive(Clone)] -enum PrettierProcess { - Running(Arc), - Stopped { start_attempts: usize }, +struct PrettierInstance { + attempt: usize, + prettier: Option, +} + +impl PrettierInstance { + fn prettier_task( + &mut self, + node: &Arc, + prettier_dir: Option<&Path>, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + if self.attempt > prettier::LAUNCH_THRESHOLD { + match prettier_dir { + Some(prettier_dir) => log::warn!( + "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting" + ), + None => log::warn!("Default prettier exceeded launch threshold, not starting"), + } + return None; + } + Some(match &self.prettier { + Some(prettier_task) => Task::ready(Ok(prettier_task.clone())), + None => match prettier_dir { + Some(prettier_dir) => { + let new_task = start_prettier( + Arc::clone(node), + prettier_dir.to_path_buf(), + worktree_id, + cx, + ); + self.attempt += 1; + self.prettier = Some(new_task.clone()); + Task::ready(Ok(new_task)) + } + None => { + self.attempt += 1; + let node = Arc::clone(node); + cx.spawn(|project, mut cx| async move { + project + .update(&mut cx, |_, cx| { + start_default_prettier(node, worktree_id, cx) + }) + .await + }) + } + }, + }) + } } struct DefaultPrettier { @@ -214,6 +261,24 @@ impl DefaultPrettier { None } } + + fn prettier_task( + &mut self, + node: &Arc, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + match &mut self.prettier { + PrettierInstallation::NotInstalled { .. } => { + // `start_default_prettier` will start the installation process if it's not already running and wait for it to finish + let new_task = start_default_prettier(Arc::clone(node), worktree_id, cx); + Some(cx.spawn(|_, _| async move { new_task.await })) + } + PrettierInstallation::Installed(existing_instance) => { + existing_instance.prettier_task(node, None, worktree_id, cx) + } + } + } } struct DelayedDebounced { @@ -6575,20 +6640,23 @@ impl Project { cx.background() .spawn(async move { - let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| { + let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_instance)| { async move { - if let PrettierProcess::Running(prettier) = prettier_task.await { - if let Err(e) = prettier - .clear_cache() - .await { - match prettier_path { - Some(prettier_path) => log::error!( - "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" - ), - None => log::error!( - "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" - ), - } + if let Some(instance) = prettier_instance.prettier { + match instance.await { + Ok(prettier) => { + prettier.clear_cache().log_err().await; + }, + Err(e) => { + match prettier_path { + Some(prettier_path) => log::error!( + "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + None => log::error!( + "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + } + }, } } } @@ -8495,7 +8563,7 @@ impl Project { &mut self, buffer: &ModelHandle, cx: &mut ModelContext, - ) -> Task, PrettierInstance)>> { + ) -> Task, PrettierTask)>> { let buffer = buffer.read(cx); let buffer_file = buffer.file(); let Some(buffer_language) = buffer.language() else { @@ -8531,32 +8599,19 @@ impl Project { return None; } Ok(ControlFlow::Continue(None)) => { - let started_default_prettier = - project.update(&mut cx, |project, _| { - project - .prettiers_per_worktree - .entry(worktree_id) - .or_default() - .insert(None); - project.default_prettier.instance().cloned() - }); - match started_default_prettier { - Some(old_task) => { - dbg!("Old prettier was found!"); - return Some((None, old_task)); - } - None => { - dbg!("starting new default prettier"); - let new_default_prettier = project - .update(&mut cx, |_, cx| { - start_default_prettier(node, Some(worktree_id), cx) - }) - .log_err() - .await; - dbg!("started a default prettier"); - return Some((None, new_default_prettier?)); - } - } + let default_instance = project.update(&mut cx, |project, cx| { + project + .prettiers_per_worktree + .entry(worktree_id) + .or_default() + .insert(None); + project.default_prettier.prettier_task( + &node, + Some(worktree_id), + cx, + ) + }); + Some((None, default_instance?.log_err().await?)) } Ok(ControlFlow::Continue(Some(prettier_dir))) => { project.update(&mut cx, |project, _| { @@ -8566,15 +8621,27 @@ impl Project { .or_default() .insert(Some(prettier_dir.clone())) }); - if let Some(existing_prettier) = - project.update(&mut cx, |project, _| { - project.prettier_instances.get(&prettier_dir).cloned() + if let Some(prettier_task) = + project.update(&mut cx, |project, cx| { + project.prettier_instances.get_mut(&prettier_dir).map( + |existing_instance| { + existing_instance.prettier_task( + &node, + Some(&prettier_dir), + Some(worktree_id), + cx, + ) + }, + ) }) { log::debug!( "Found already started prettier in {prettier_dir:?}" ); - return Some((Some(prettier_dir), existing_prettier)); + return Some(( + Some(prettier_dir), + prettier_task?.await.log_err()?, + )); } log::info!("Found prettier in {prettier_dir:?}, starting."); @@ -8585,9 +8652,13 @@ impl Project { Some(worktree_id), cx, ); - project - .prettier_instances - .insert(prettier_dir.clone(), new_prettier_task.clone()); + project.prettier_instances.insert( + prettier_dir.clone(), + PrettierInstance { + attempt: 0, + prettier: Some(new_prettier_task.clone()), + }, + ); new_prettier_task }); Some((Some(prettier_dir), new_prettier_task)) @@ -8599,13 +8670,11 @@ impl Project { } }); } - None => match self.default_prettier.instance().cloned() { - Some(old_task) => return Task::ready(Some((None, old_task))), - None => { - let new_task = start_default_prettier(node, None, cx).log_err(); - return cx.spawn(|_, _| async move { Some((None, new_task.await?)) }); - } - }, + None => { + let new_task = self.default_prettier.prettier_task(&node, None, cx); + return cx + .spawn(|_, _| async move { Some((None, new_task?.log_err().await?)) }); + } } } else { return Task::ready(None); @@ -8727,20 +8796,19 @@ impl Project { if needs_install { let installed_plugins = plugins_to_install.clone(); cx.background() + // TODO kb instead of always installing, try to start the existing installation first? .spawn(async move { install_default_prettier(plugins_to_install, node, fs).await }) .await .context("prettier & plugins install") .map_err(Arc::new)?; - this.update(&mut cx, |this, cx| { + this.update(&mut cx, |this, _| { this.default_prettier.prettier = - PrettierInstallation::Installed( - cx.spawn(|_, _| async move { - PrettierProcess::Stopped { start_attempts: 0 } - }) - .shared(), - ); + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); this.default_prettier .installed_plugins .extend(installed_plugins); @@ -8760,20 +8828,24 @@ fn start_default_prettier( node: Arc, worktree_id: Option, cx: &mut ModelContext<'_, Project>, -) -> Task> { +) -> Task> { cx.spawn(|project, mut cx| async move { loop { + let mut install_attempt = 0; let installation_process = project.update(&mut cx, |project, _| { match &project.default_prettier.prettier { PrettierInstallation::NotInstalled { installation_process, - .. - } => ControlFlow::Continue(installation_process.clone()), + attempts + } => { + install_attempt = *attempts; + ControlFlow::Continue(installation_process.clone())}, PrettierInstallation::Installed(default_prettier) => { ControlFlow::Break(default_prettier.clone()) } } }); + install_attempt += 1; match installation_process { ControlFlow::Continue(installation_process) => { @@ -8786,12 +8858,26 @@ fn start_default_prettier( let new_default_prettier = start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); project.default_prettier.prettier = - PrettierInstallation::Installed(new_default_prettier.clone()); + PrettierInstallation::Installed(PrettierInstance { attempt: install_attempt, prettier: Some(new_default_prettier.clone()) }); new_default_prettier }); return Ok(new_default_prettier); } - ControlFlow::Break(prettier) => return Ok(prettier), + ControlFlow::Break(instance) => { + match instance.prettier { + Some(instance) => return Ok(instance), + None => { + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { attempt: instance.attempt + 1, prettier: Some(new_default_prettier.clone()) }); + new_default_prettier + }); + return Ok(new_default_prettier); + }, + } + }, } } }) @@ -8802,23 +8888,19 @@ fn start_prettier( prettier_dir: PathBuf, worktree_id: Option, cx: &mut ModelContext<'_, Project>, -) -> PrettierInstance { +) -> PrettierTask { cx.spawn(|project, mut cx| async move { let new_server_id = project.update(&mut cx, |project, _| { project.languages.next_language_server_id() }); - match Prettier::start(new_server_id, prettier_dir.clone(), node, cx.clone()).await { - Ok(new_prettier) => { - register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); - PrettierProcess::Running(Arc::new(new_prettier)) - } - Err(e) => { - log::error!("Failed to start prettier in dir {prettier_dir:?}: {e:#}"); - // TODO kb increment - PrettierProcess::Stopped { start_attempts: 1 } - } - } + let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) + .await + .context("default prettier spawn") + .map(Arc::new) + .map_err(Arc::new)?; + register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); + Ok(new_prettier) }) .shared() } @@ -9235,19 +9317,42 @@ async fn format_with_prettier( }) .await { - // TODO kb re-insert incremented value here? - if let PrettierProcess::Running(prettier) = prettier_task.await { - let buffer_path = buffer.update(cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - }); - match prettier.format(buffer, buffer_path, cx).await { - Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), - Err(e) => { - log::error!( - "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" - ); + match prettier_task.await { + Ok(prettier) => { + let buffer_path = buffer.update(cx, |buffer, cx| { + File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) + }); + match prettier.format(buffer, buffer_path, cx).await { + Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), + Err(e) => { + log::error!( + "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" + ); + } } } + Err(e) => project.update(cx, |project, _| { + let instance_to_update = match prettier_path { + Some(prettier_path) => { + log::error!( + "Prettier instance from path {prettier_path:?} failed to spawn: {e:#}" + ); + project.prettier_instances.get_mut(&prettier_path) + } + None => { + log::error!("Default prettier instance failed to spawn: {e:#}"); + match &mut project.default_prettier.prettier { + PrettierInstallation::NotInstalled { .. } => None, + PrettierInstallation::Installed(instance) => Some(instance), + } + } + }; + + if let Some(instance) = instance_to_update { + instance.attempt += 1; + instance.prettier = None; + } + }), } } From eab347630473257cb543f6373c75c6f025fe8fd2 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 12:09:55 +0200 Subject: [PATCH 04/16] Split prettier code off to a separate module --- crates/project/src/prettier_support.rs | 708 +++++++++++++++++++++++++ crates/project/src/project.rs | 703 +----------------------- 2 files changed, 721 insertions(+), 690 deletions(-) create mode 100644 crates/project/src/prettier_support.rs diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs new file mode 100644 index 0000000000000000000000000000000000000000..f59ff20a24c21952fcfd4c7e099643190f63049f --- /dev/null +++ b/crates/project/src/prettier_support.rs @@ -0,0 +1,708 @@ +use std::{ + ops::ControlFlow, + path::{Path, PathBuf}, + sync::Arc, +}; + +use anyhow::Context; +use collections::HashSet; +use fs::Fs; +use futures::{ + future::{self, Shared}, + FutureExt, +}; +use gpui::{AsyncAppContext, ModelContext, ModelHandle, Task}; +use language::{ + language_settings::{Formatter, LanguageSettings}, + Buffer, Language, LanguageServerName, LocalFile, +}; +use lsp::LanguageServerId; +use node_runtime::NodeRuntime; +use prettier::Prettier; +use util::{paths::DEFAULT_PRETTIER_DIR, ResultExt, TryFutureExt}; + +use crate::{ + Event, File, FormatOperation, PathChange, Project, ProjectEntryId, Worktree, WorktreeId, +}; + +pub(super) async fn format_with_prettier( + project: &ModelHandle, + buffer: &ModelHandle, + cx: &mut AsyncAppContext, +) -> Option { + if let Some((prettier_path, prettier_task)) = project + .update(cx, |project, cx| { + project.prettier_instance_for_buffer(buffer, cx) + }) + .await + { + match prettier_task.await { + Ok(prettier) => { + let buffer_path = buffer.update(cx, |buffer, cx| { + File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) + }); + match prettier.format(buffer, buffer_path, cx).await { + Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), + Err(e) => { + log::error!( + "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" + ); + } + } + } + Err(e) => project.update(cx, |project, _| { + let instance_to_update = match prettier_path { + Some(prettier_path) => { + log::error!( + "Prettier instance from path {prettier_path:?} failed to spawn: {e:#}" + ); + project.prettier_instances.get_mut(&prettier_path) + } + None => { + log::error!("Default prettier instance failed to spawn: {e:#}"); + match &mut project.default_prettier.prettier { + PrettierInstallation::NotInstalled { .. } => None, + PrettierInstallation::Installed(instance) => Some(instance), + } + } + }; + + if let Some(instance) = instance_to_update { + instance.attempt += 1; + instance.prettier = None; + } + }), + } + } + + None +} + +pub struct DefaultPrettier { + prettier: PrettierInstallation, + installed_plugins: HashSet<&'static str>, +} + +pub enum PrettierInstallation { + NotInstalled { + attempts: usize, + installation_process: Option>>>>, + }, + Installed(PrettierInstance), +} + +pub type PrettierTask = Shared, Arc>>>; + +#[derive(Clone)] +pub struct PrettierInstance { + attempt: usize, + prettier: Option, +} + +impl Default for DefaultPrettier { + fn default() -> Self { + Self { + prettier: PrettierInstallation::NotInstalled { + attempts: 0, + installation_process: None, + }, + installed_plugins: HashSet::default(), + } + } +} + +impl DefaultPrettier { + pub fn instance(&self) -> Option<&PrettierInstance> { + if let PrettierInstallation::Installed(instance) = &self.prettier { + Some(instance) + } else { + None + } + } + + pub fn prettier_task( + &mut self, + node: &Arc, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + match &mut self.prettier { + PrettierInstallation::NotInstalled { .. } => { + // `start_default_prettier` will start the installation process if it's not already running and wait for it to finish + let new_task = start_default_prettier(Arc::clone(node), worktree_id, cx); + Some(cx.spawn(|_, _| async move { new_task.await })) + } + PrettierInstallation::Installed(existing_instance) => { + existing_instance.prettier_task(node, None, worktree_id, cx) + } + } + } +} + +impl PrettierInstance { + pub fn prettier_task( + &mut self, + node: &Arc, + prettier_dir: Option<&Path>, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + if self.attempt > prettier::LAUNCH_THRESHOLD { + match prettier_dir { + Some(prettier_dir) => log::warn!( + "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting" + ), + None => log::warn!("Default prettier exceeded launch threshold, not starting"), + } + return None; + } + Some(match &self.prettier { + Some(prettier_task) => Task::ready(Ok(prettier_task.clone())), + None => match prettier_dir { + Some(prettier_dir) => { + let new_task = start_prettier( + Arc::clone(node), + prettier_dir.to_path_buf(), + worktree_id, + cx, + ); + self.attempt += 1; + self.prettier = Some(new_task.clone()); + Task::ready(Ok(new_task)) + } + None => { + self.attempt += 1; + let node = Arc::clone(node); + cx.spawn(|project, mut cx| async move { + project + .update(&mut cx, |_, cx| { + start_default_prettier(node, worktree_id, cx) + }) + .await + }) + } + }, + }) + } +} + +fn start_default_prettier( + node: Arc, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, +) -> Task> { + cx.spawn(|project, mut cx| async move { + loop { + let mut install_attempt = 0; + let installation_process = project.update(&mut cx, |project, _| { + match &project.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_process, + attempts + } => { + install_attempt = *attempts; + ControlFlow::Continue(installation_process.clone())}, + PrettierInstallation::Installed(default_prettier) => { + ControlFlow::Break(default_prettier.clone()) + } + } + }); + install_attempt += 1; + + match installation_process { + ControlFlow::Continue(installation_process) => { + if let Some(installation_process) = installation_process.clone() { + if let Err(e) = installation_process.await { + anyhow::bail!("Cannot start default prettier due to its installation failure: {e:#}"); + } + } + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { attempt: install_attempt, prettier: Some(new_default_prettier.clone()) }); + new_default_prettier + }); + return Ok(new_default_prettier); + } + ControlFlow::Break(instance) => { + match instance.prettier { + Some(instance) => return Ok(instance), + None => { + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { attempt: instance.attempt + 1, prettier: Some(new_default_prettier.clone()) }); + new_default_prettier + }); + return Ok(new_default_prettier); + }, + } + }, + } + } + }) +} + +fn start_prettier( + node: Arc, + prettier_dir: PathBuf, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, +) -> PrettierTask { + cx.spawn(|project, mut cx| async move { + let new_server_id = project.update(&mut cx, |project, _| { + project.languages.next_language_server_id() + }); + + let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) + .await + .context("default prettier spawn") + .map(Arc::new) + .map_err(Arc::new)?; + register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); + Ok(new_prettier) + }) + .shared() +} + +fn register_new_prettier( + project: &ModelHandle, + prettier: &Prettier, + worktree_id: Option, + new_server_id: LanguageServerId, + cx: &mut AsyncAppContext, +) { + let prettier_dir = prettier.prettier_dir(); + let is_default = prettier.is_default(); + if is_default { + log::info!("Started default prettier in {prettier_dir:?}"); + } else { + log::info!("Started prettier in {prettier_dir:?}"); + } + if let Some(prettier_server) = prettier.server() { + project.update(cx, |project, cx| { + let name = if is_default { + LanguageServerName(Arc::from("prettier (default)")) + } else { + let worktree_path = worktree_id + .and_then(|id| project.worktree_for_id(id, cx)) + .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path())); + let name = match worktree_path { + Some(worktree_path) => { + if prettier_dir == worktree_path.as_ref() { + let name = prettier_dir + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or_default(); + format!("prettier ({name})") + } else { + let dir_to_display = prettier_dir + .strip_prefix(worktree_path.as_ref()) + .ok() + .unwrap_or(prettier_dir); + format!("prettier ({})", dir_to_display.display()) + } + } + None => format!("prettier ({})", prettier_dir.display()), + }; + LanguageServerName(Arc::from(name)) + }; + project + .supplementary_language_servers + .insert(new_server_id, (name, Arc::clone(prettier_server))); + cx.emit(Event::LanguageServerAdded(new_server_id)); + }); + } +} + +async fn install_default_prettier( + plugins_to_install: HashSet<&'static str>, + node: Arc, + fs: Arc, +) -> anyhow::Result<()> { + let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); + // method creates parent directory if it doesn't exist + fs.save( + &prettier_wrapper_path, + &text::Rope::from(prettier::PRETTIER_SERVER_JS), + text::LineEnding::Unix, + ) + .await + .with_context(|| { + format!( + "writing {} file at {prettier_wrapper_path:?}", + prettier::PRETTIER_SERVER_FILE + ) + })?; + + let packages_to_versions = + future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( + |package_name| async { + let returned_package_name = package_name.to_string(); + let latest_version = node + .npm_package_latest_version(package_name) + .await + .with_context(|| { + format!("fetching latest npm version for package {returned_package_name}") + })?; + anyhow::Ok((returned_package_name, latest_version)) + }, + )) + .await + .context("fetching latest npm versions")?; + + log::info!("Fetching default prettier and plugins: {packages_to_versions:?}"); + let borrowed_packages = packages_to_versions + .iter() + .map(|(package, version)| (package.as_str(), version.as_str())) + .collect::>(); + node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages) + .await + .context("fetching formatter packages")?; + anyhow::Ok(()) +} + +impl Project { + pub fn update_prettier_settings( + &self, + worktree: &ModelHandle, + changes: &[(Arc, ProjectEntryId, PathChange)], + cx: &mut ModelContext<'_, Project>, + ) { + let prettier_config_files = Prettier::CONFIG_FILE_NAMES + .iter() + .map(Path::new) + .collect::>(); + + let prettier_config_file_changed = changes + .iter() + .filter(|(_, _, change)| !matches!(change, PathChange::Loaded)) + .filter(|(path, _, _)| { + !path + .components() + .any(|component| component.as_os_str().to_string_lossy() == "node_modules") + }) + .find(|(path, _, _)| prettier_config_files.contains(path.as_ref())); + let current_worktree_id = worktree.read(cx).id(); + if let Some((config_path, _, _)) = prettier_config_file_changed { + log::info!( + "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}" + ); + let prettiers_to_reload = + self.prettiers_per_worktree + .get(¤t_worktree_id) + .iter() + .flat_map(|prettier_paths| prettier_paths.iter()) + .flatten() + .filter_map(|prettier_path| { + Some(( + current_worktree_id, + Some(prettier_path.clone()), + self.prettier_instances.get(prettier_path)?.clone(), + )) + }) + .chain(self.default_prettier.instance().map(|default_prettier| { + (current_worktree_id, None, default_prettier.clone()) + })) + .collect::>(); + + cx.background() + .spawn(async move { + let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_instance)| { + async move { + if let Some(instance) = prettier_instance.prettier { + match instance.await { + Ok(prettier) => { + prettier.clear_cache().log_err().await; + }, + Err(e) => { + match prettier_path { + Some(prettier_path) => log::error!( + "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + None => log::error!( + "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + } + }, + } + } + } + })) + .await; + }) + .detach(); + } + } + + fn prettier_instance_for_buffer( + &mut self, + buffer: &ModelHandle, + cx: &mut ModelContext, + ) -> Task, PrettierTask)>> { + let buffer = buffer.read(cx); + let buffer_file = buffer.file(); + let Some(buffer_language) = buffer.language() else { + return Task::ready(None); + }; + if buffer_language.prettier_parser_name().is_none() { + return Task::ready(None); + } + + if self.is_local() { + let Some(node) = self.node.as_ref().map(Arc::clone) else { + return Task::ready(None); + }; + match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx))) + { + Some((worktree_id, buffer_path)) => { + let fs = Arc::clone(&self.fs); + let installed_prettiers = self.prettier_instances.keys().cloned().collect(); + return cx.spawn(|project, mut cx| async move { + match cx + .background() + .spawn(async move { + Prettier::locate_prettier_installation( + fs.as_ref(), + &installed_prettiers, + &buffer_path, + ) + .await + }) + .await + { + Ok(ControlFlow::Break(())) => { + return None; + } + Ok(ControlFlow::Continue(None)) => { + let default_instance = project.update(&mut cx, |project, cx| { + project + .prettiers_per_worktree + .entry(worktree_id) + .or_default() + .insert(None); + project.default_prettier.prettier_task( + &node, + Some(worktree_id), + cx, + ) + }); + Some((None, default_instance?.log_err().await?)) + } + Ok(ControlFlow::Continue(Some(prettier_dir))) => { + project.update(&mut cx, |project, _| { + project + .prettiers_per_worktree + .entry(worktree_id) + .or_default() + .insert(Some(prettier_dir.clone())) + }); + if let Some(prettier_task) = + project.update(&mut cx, |project, cx| { + project.prettier_instances.get_mut(&prettier_dir).map( + |existing_instance| { + existing_instance.prettier_task( + &node, + Some(&prettier_dir), + Some(worktree_id), + cx, + ) + }, + ) + }) + { + log::debug!( + "Found already started prettier in {prettier_dir:?}" + ); + return Some(( + Some(prettier_dir), + prettier_task?.await.log_err()?, + )); + } + + log::info!("Found prettier in {prettier_dir:?}, starting."); + let new_prettier_task = project.update(&mut cx, |project, cx| { + let new_prettier_task = start_prettier( + node, + prettier_dir.clone(), + Some(worktree_id), + cx, + ); + project.prettier_instances.insert( + prettier_dir.clone(), + PrettierInstance { + attempt: 0, + prettier: Some(new_prettier_task.clone()), + }, + ); + new_prettier_task + }); + Some((Some(prettier_dir), new_prettier_task)) + } + Err(e) => { + log::error!("Failed to determine prettier path for buffer: {e:#}"); + return None; + } + } + }); + } + None => { + let new_task = self.default_prettier.prettier_task(&node, None, cx); + return cx + .spawn(|_, _| async move { Some((None, new_task?.log_err().await?)) }); + } + } + } else { + return Task::ready(None); + } + } + + #[cfg(any(test, feature = "test-support"))] + pub fn install_default_prettier( + &mut self, + _worktree: Option, + _new_language: &Language, + language_settings: &LanguageSettings, + _cx: &mut ModelContext, + ) { + // suppress unused code warnings + match &language_settings.formatter { + Formatter::Prettier { .. } | Formatter::Auto => {} + Formatter::LanguageServer | Formatter::External { .. } => return, + }; + let _ = &self.default_prettier.installed_plugins; + } + + #[cfg(not(any(test, feature = "test-support")))] + pub fn install_default_prettier( + &mut self, + worktree: Option, + new_language: &Language, + language_settings: &LanguageSettings, + cx: &mut ModelContext, + ) { + match &language_settings.formatter { + Formatter::Prettier { .. } | Formatter::Auto => {} + Formatter::LanguageServer | Formatter::External { .. } => return, + }; + let Some(node) = self.node.as_ref().cloned() else { + return; + }; + + let mut prettier_plugins = None; + if new_language.prettier_parser_name().is_some() { + prettier_plugins + .get_or_insert_with(|| HashSet::<&'static str>::default()) + .extend( + new_language + .lsp_adapters() + .iter() + .flat_map(|adapter| adapter.prettier_plugins()), + ) + } + let Some(prettier_plugins) = prettier_plugins else { + return; + }; + + let fs = Arc::clone(&self.fs); + let locate_prettier_installation = match worktree.and_then(|worktree_id| { + self.worktree_for_id(worktree_id, cx) + .map(|worktree| worktree.read(cx).abs_path()) + }) { + Some(locate_from) => { + let installed_prettiers = self.prettier_instances.keys().cloned().collect(); + cx.background().spawn(async move { + Prettier::locate_prettier_installation( + fs.as_ref(), + &installed_prettiers, + locate_from.as_ref(), + ) + .await + }) + } + None => Task::ready(Ok(ControlFlow::Break(()))), + }; + let mut plugins_to_install = prettier_plugins; + plugins_to_install + .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); + let mut installation_attempts = 0; + let previous_installation_process = match &self.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_process, + attempts, + } => { + installation_attempts = *attempts; + installation_process.clone() + } + PrettierInstallation::Installed { .. } => { + if plugins_to_install.is_empty() { + return; + } + None + } + }; + + if installation_attempts > prettier::LAUNCH_THRESHOLD { + log::warn!( + "Default prettier installation has failed {installation_attempts} times, not attempting again", + ); + return; + } + + let fs = Arc::clone(&self.fs); + self.default_prettier.prettier = PrettierInstallation::NotInstalled { + attempts: installation_attempts + 1, + installation_process: Some( + cx.spawn(|this, mut cx| async move { + match locate_prettier_installation + .await + .context("locate prettier installation") + .map_err(Arc::new)? + { + ControlFlow::Break(()) => return Ok(()), + ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), + ControlFlow::Continue(None) => { + let mut needs_install = match previous_installation_process { + Some(previous_installation_process) => { + previous_installation_process.await.is_err() + } + None => true, + }; + this.update(&mut cx, |this, _| { + plugins_to_install.retain(|plugin| { + !this.default_prettier.installed_plugins.contains(plugin) + }); + needs_install |= !plugins_to_install.is_empty(); + }); + if needs_install { + let installed_plugins = plugins_to_install.clone(); + cx.background() + // TODO kb instead of always installing, try to start the existing installation first? + .spawn(async move { + install_default_prettier(plugins_to_install, node, fs).await + }) + .await + .context("prettier & plugins install") + .map_err(Arc::new)?; + this.update(&mut cx, |this, _| { + this.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); + this.default_prettier + .installed_plugins + .extend(installed_plugins); + }); + } + } + } + Ok(()) + }) + .shared(), + ), + }; + } +} diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index 13cee48feda3f66fad1988e5bd0271c551cbc4a7..ad2a13482b128d69d7aa41fad0b101ef52797f5d 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -1,5 +1,6 @@ mod ignore; mod lsp_command; +mod prettier_support; pub mod project_settings; pub mod search; pub mod terminals; @@ -20,7 +21,7 @@ use futures::{ mpsc::{self, UnboundedReceiver}, oneshot, }, - future::{self, try_join_all, Shared}, + future::{try_join_all, Shared}, stream::FuturesUnordered, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt, }; @@ -31,9 +32,7 @@ use gpui::{ }; use itertools::Itertools; use language::{ - language_settings::{ - language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings, - }, + language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind}, point_to_lsp, proto::{ deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version, @@ -54,7 +53,7 @@ use lsp_command::*; use node_runtime::NodeRuntime; use parking_lot::Mutex; use postage::watch; -use prettier::Prettier; +use prettier_support::{DefaultPrettier, PrettierInstance}; use project_settings::{LspSettings, ProjectSettings}; use rand::prelude::*; use search::SearchQuery; @@ -72,7 +71,7 @@ use std::{ hash::Hash, mem, num::NonZeroU32, - ops::{ControlFlow, Range}, + ops::Range, path::{self, Component, Path, PathBuf}, process::Stdio, str, @@ -85,11 +84,8 @@ use std::{ use terminals::Terminals; use text::Anchor; use util::{ - debug_panic, defer, - http::HttpClient, - merge_json_value_into, - paths::{DEFAULT_PRETTIER_DIR, LOCAL_SETTINGS_RELATIVE_PATH}, - post_inc, ResultExt, TryFutureExt as _, + debug_panic, defer, http::HttpClient, merge_json_value_into, + paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt, TryFutureExt as _, }; pub use fs::*; @@ -173,114 +169,6 @@ pub struct Project { prettier_instances: HashMap, } -type PrettierTask = Shared, Arc>>>; - -#[derive(Clone)] -struct PrettierInstance { - attempt: usize, - prettier: Option, -} - -impl PrettierInstance { - fn prettier_task( - &mut self, - node: &Arc, - prettier_dir: Option<&Path>, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, - ) -> Option>> { - if self.attempt > prettier::LAUNCH_THRESHOLD { - match prettier_dir { - Some(prettier_dir) => log::warn!( - "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting" - ), - None => log::warn!("Default prettier exceeded launch threshold, not starting"), - } - return None; - } - Some(match &self.prettier { - Some(prettier_task) => Task::ready(Ok(prettier_task.clone())), - None => match prettier_dir { - Some(prettier_dir) => { - let new_task = start_prettier( - Arc::clone(node), - prettier_dir.to_path_buf(), - worktree_id, - cx, - ); - self.attempt += 1; - self.prettier = Some(new_task.clone()); - Task::ready(Ok(new_task)) - } - None => { - self.attempt += 1; - let node = Arc::clone(node); - cx.spawn(|project, mut cx| async move { - project - .update(&mut cx, |_, cx| { - start_default_prettier(node, worktree_id, cx) - }) - .await - }) - } - }, - }) - } -} - -struct DefaultPrettier { - prettier: PrettierInstallation, - installed_plugins: HashSet<&'static str>, -} - -enum PrettierInstallation { - NotInstalled { - attempts: usize, - installation_process: Option>>>>, - }, - Installed(PrettierInstance), -} - -impl Default for DefaultPrettier { - fn default() -> Self { - Self { - prettier: PrettierInstallation::NotInstalled { - attempts: 0, - installation_process: None, - }, - installed_plugins: HashSet::default(), - } - } -} - -impl DefaultPrettier { - fn instance(&self) -> Option<&PrettierInstance> { - if let PrettierInstallation::Installed(instance) = &self.prettier { - Some(instance) - } else { - None - } - } - - fn prettier_task( - &mut self, - node: &Arc, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, - ) -> Option>> { - match &mut self.prettier { - PrettierInstallation::NotInstalled { .. } => { - // `start_default_prettier` will start the installation process if it's not already running and wait for it to finish - let new_task = start_default_prettier(Arc::clone(node), worktree_id, cx); - Some(cx.spawn(|_, _| async move { new_task.await })) - } - PrettierInstallation::Installed(existing_instance) => { - existing_instance.prettier_task(node, None, worktree_id, cx) - } - } - } -} - struct DelayedDebounced { task: Option>, cancel_channel: Option>, @@ -1038,7 +926,7 @@ impl Project { } for (worktree, language, settings) in language_formatters_to_check { - self.install_default_formatters(worktree, &language, &settings, cx); + self.install_default_prettier(worktree, &language, &settings, cx); } // Start all the newly-enabled language servers. @@ -2795,7 +2683,7 @@ impl Project { let buffer_file = File::from_dyn(buffer_file.as_ref()); let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx)); - self.install_default_formatters(worktree, &new_language, &settings, cx); + self.install_default_prettier(worktree, &new_language, &settings, cx); if let Some(file) = buffer_file { let worktree = file.worktree.clone(); if let Some(tree) = worktree.read(cx).as_local() { @@ -4257,7 +4145,8 @@ impl Project { } (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => { if let Some(new_operation) = - format_with_prettier(&project, buffer, &mut cx).await + prettier_support::format_with_prettier(&project, buffer, &mut cx) + .await { format_operation = Some(new_operation); } else if let Some((language_server, buffer_abs_path)) = @@ -4279,7 +4168,8 @@ impl Project { } (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => { if let Some(new_operation) = - format_with_prettier(&project, buffer, &mut cx).await + prettier_support::format_with_prettier(&project, buffer, &mut cx) + .await { format_operation = Some(new_operation); } @@ -6595,78 +6485,6 @@ impl Project { .detach(); } - fn update_prettier_settings( - &self, - worktree: &ModelHandle, - changes: &[(Arc, ProjectEntryId, PathChange)], - cx: &mut ModelContext<'_, Project>, - ) { - let prettier_config_files = Prettier::CONFIG_FILE_NAMES - .iter() - .map(Path::new) - .collect::>(); - - let prettier_config_file_changed = changes - .iter() - .filter(|(_, _, change)| !matches!(change, PathChange::Loaded)) - .filter(|(path, _, _)| { - !path - .components() - .any(|component| component.as_os_str().to_string_lossy() == "node_modules") - }) - .find(|(path, _, _)| prettier_config_files.contains(path.as_ref())); - let current_worktree_id = worktree.read(cx).id(); - if let Some((config_path, _, _)) = prettier_config_file_changed { - log::info!( - "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}" - ); - let prettiers_to_reload = - self.prettiers_per_worktree - .get(¤t_worktree_id) - .iter() - .flat_map(|prettier_paths| prettier_paths.iter()) - .flatten() - .filter_map(|prettier_path| { - Some(( - current_worktree_id, - Some(prettier_path.clone()), - self.prettier_instances.get(prettier_path)?.clone(), - )) - }) - .chain(self.default_prettier.instance().map(|default_prettier| { - (current_worktree_id, None, default_prettier.clone()) - })) - .collect::>(); - - cx.background() - .spawn(async move { - let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_instance)| { - async move { - if let Some(instance) = prettier_instance.prettier { - match instance.await { - Ok(prettier) => { - prettier.clear_cache().log_err().await; - }, - Err(e) => { - match prettier_path { - Some(prettier_path) => log::error!( - "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" - ), - None => log::error!( - "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" - ), - } - }, - } - } - } - })) - .await; - }) - .detach(); - } - } - pub fn set_active_path(&mut self, entry: Option, cx: &mut ModelContext) { let new_active_entry = entry.and_then(|project_path| { let worktree = self.worktree_for_id(project_path.worktree_id, cx)?; @@ -8558,448 +8376,6 @@ impl Project { Vec::new() } } - - fn prettier_instance_for_buffer( - &mut self, - buffer: &ModelHandle, - cx: &mut ModelContext, - ) -> Task, PrettierTask)>> { - let buffer = buffer.read(cx); - let buffer_file = buffer.file(); - let Some(buffer_language) = buffer.language() else { - return Task::ready(None); - }; - if buffer_language.prettier_parser_name().is_none() { - return Task::ready(None); - } - - if self.is_local() { - let Some(node) = self.node.as_ref().map(Arc::clone) else { - return Task::ready(None); - }; - match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx))) - { - Some((worktree_id, buffer_path)) => { - let fs = Arc::clone(&self.fs); - let installed_prettiers = self.prettier_instances.keys().cloned().collect(); - return cx.spawn(|project, mut cx| async move { - match cx - .background() - .spawn(async move { - Prettier::locate_prettier_installation( - fs.as_ref(), - &installed_prettiers, - &buffer_path, - ) - .await - }) - .await - { - Ok(ControlFlow::Break(())) => { - return None; - } - Ok(ControlFlow::Continue(None)) => { - let default_instance = project.update(&mut cx, |project, cx| { - project - .prettiers_per_worktree - .entry(worktree_id) - .or_default() - .insert(None); - project.default_prettier.prettier_task( - &node, - Some(worktree_id), - cx, - ) - }); - Some((None, default_instance?.log_err().await?)) - } - Ok(ControlFlow::Continue(Some(prettier_dir))) => { - project.update(&mut cx, |project, _| { - project - .prettiers_per_worktree - .entry(worktree_id) - .or_default() - .insert(Some(prettier_dir.clone())) - }); - if let Some(prettier_task) = - project.update(&mut cx, |project, cx| { - project.prettier_instances.get_mut(&prettier_dir).map( - |existing_instance| { - existing_instance.prettier_task( - &node, - Some(&prettier_dir), - Some(worktree_id), - cx, - ) - }, - ) - }) - { - log::debug!( - "Found already started prettier in {prettier_dir:?}" - ); - return Some(( - Some(prettier_dir), - prettier_task?.await.log_err()?, - )); - } - - log::info!("Found prettier in {prettier_dir:?}, starting."); - let new_prettier_task = project.update(&mut cx, |project, cx| { - let new_prettier_task = start_prettier( - node, - prettier_dir.clone(), - Some(worktree_id), - cx, - ); - project.prettier_instances.insert( - prettier_dir.clone(), - PrettierInstance { - attempt: 0, - prettier: Some(new_prettier_task.clone()), - }, - ); - new_prettier_task - }); - Some((Some(prettier_dir), new_prettier_task)) - } - Err(e) => { - log::error!("Failed to determine prettier path for buffer: {e:#}"); - return None; - } - } - }); - } - None => { - let new_task = self.default_prettier.prettier_task(&node, None, cx); - return cx - .spawn(|_, _| async move { Some((None, new_task?.log_err().await?)) }); - } - } - } else { - return Task::ready(None); - } - } - - // TODO kb uncomment - // #[cfg(any(test, feature = "test-support"))] - // fn install_default_formatters( - // &mut self, - // _worktree: Option, - // _new_language: &Language, - // _language_settings: &LanguageSettings, - // _cx: &mut ModelContext, - // ) { - // } - - // #[cfg(not(any(test, feature = "test-support")))] - fn install_default_formatters( - &mut self, - worktree: Option, - new_language: &Language, - language_settings: &LanguageSettings, - cx: &mut ModelContext, - ) { - match &language_settings.formatter { - Formatter::Prettier { .. } | Formatter::Auto => {} - Formatter::LanguageServer | Formatter::External { .. } => return, - }; - let Some(node) = self.node.as_ref().cloned() else { - return; - }; - - let mut prettier_plugins = None; - if new_language.prettier_parser_name().is_some() { - prettier_plugins - .get_or_insert_with(|| HashSet::<&'static str>::default()) - .extend( - new_language - .lsp_adapters() - .iter() - .flat_map(|adapter| adapter.prettier_plugins()), - ) - } - let Some(prettier_plugins) = prettier_plugins else { - return; - }; - - let fs = Arc::clone(&self.fs); - let locate_prettier_installation = match worktree.and_then(|worktree_id| { - self.worktree_for_id(worktree_id, cx) - .map(|worktree| worktree.read(cx).abs_path()) - }) { - Some(locate_from) => { - let installed_prettiers = self.prettier_instances.keys().cloned().collect(); - cx.background().spawn(async move { - Prettier::locate_prettier_installation( - fs.as_ref(), - &installed_prettiers, - locate_from.as_ref(), - ) - .await - }) - } - None => Task::ready(Ok(ControlFlow::Break(()))), - }; - let mut plugins_to_install = prettier_plugins; - plugins_to_install - .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); - let mut installation_attempts = 0; - let previous_installation_process = match &self.default_prettier.prettier { - PrettierInstallation::NotInstalled { - installation_process, - attempts, - } => { - installation_attempts = *attempts; - installation_process.clone() - } - PrettierInstallation::Installed { .. } => { - if plugins_to_install.is_empty() { - return; - } - None - } - }; - - if installation_attempts > prettier::LAUNCH_THRESHOLD { - log::warn!( - "Default prettier installation has failed {installation_attempts} times, not attempting again", - ); - return; - } - - let fs = Arc::clone(&self.fs); - self.default_prettier.prettier = PrettierInstallation::NotInstalled { - attempts: installation_attempts + 1, - installation_process: Some( - cx.spawn(|this, mut cx| async move { - match locate_prettier_installation - .await - .context("locate prettier installation") - .map_err(Arc::new)? - { - ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), - ControlFlow::Continue(None) => { - let mut needs_install = match previous_installation_process { - Some(previous_installation_process) => { - previous_installation_process.await.is_err() - } - None => true, - }; - this.update(&mut cx, |this, _| { - plugins_to_install.retain(|plugin| { - !this.default_prettier.installed_plugins.contains(plugin) - }); - needs_install |= !plugins_to_install.is_empty(); - }); - if needs_install { - let installed_plugins = plugins_to_install.clone(); - cx.background() - // TODO kb instead of always installing, try to start the existing installation first? - .spawn(async move { - install_default_prettier(plugins_to_install, node, fs).await - }) - .await - .context("prettier & plugins install") - .map_err(Arc::new)?; - this.update(&mut cx, |this, _| { - this.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { - attempt: 0, - prettier: None, - }); - this.default_prettier - .installed_plugins - .extend(installed_plugins); - }); - } - } - } - Ok(()) - }) - .shared(), - ), - }; - } -} - -fn start_default_prettier( - node: Arc, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, -) -> Task> { - cx.spawn(|project, mut cx| async move { - loop { - let mut install_attempt = 0; - let installation_process = project.update(&mut cx, |project, _| { - match &project.default_prettier.prettier { - PrettierInstallation::NotInstalled { - installation_process, - attempts - } => { - install_attempt = *attempts; - ControlFlow::Continue(installation_process.clone())}, - PrettierInstallation::Installed(default_prettier) => { - ControlFlow::Break(default_prettier.clone()) - } - } - }); - install_attempt += 1; - - match installation_process { - ControlFlow::Continue(installation_process) => { - if let Some(installation_process) = installation_process.clone() { - if let Err(e) = installation_process.await { - anyhow::bail!("Cannot start default prettier due to its installation failure: {e:#}"); - } - } - let new_default_prettier = project.update(&mut cx, |project, cx| { - let new_default_prettier = - start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); - project.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { attempt: install_attempt, prettier: Some(new_default_prettier.clone()) }); - new_default_prettier - }); - return Ok(new_default_prettier); - } - ControlFlow::Break(instance) => { - match instance.prettier { - Some(instance) => return Ok(instance), - None => { - let new_default_prettier = project.update(&mut cx, |project, cx| { - let new_default_prettier = - start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); - project.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { attempt: instance.attempt + 1, prettier: Some(new_default_prettier.clone()) }); - new_default_prettier - }); - return Ok(new_default_prettier); - }, - } - }, - } - } - }) -} - -fn start_prettier( - node: Arc, - prettier_dir: PathBuf, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, -) -> PrettierTask { - cx.spawn(|project, mut cx| async move { - let new_server_id = project.update(&mut cx, |project, _| { - project.languages.next_language_server_id() - }); - - let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) - .await - .context("default prettier spawn") - .map(Arc::new) - .map_err(Arc::new)?; - register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); - Ok(new_prettier) - }) - .shared() -} - -fn register_new_prettier( - project: &ModelHandle, - prettier: &Prettier, - worktree_id: Option, - new_server_id: LanguageServerId, - cx: &mut AsyncAppContext, -) { - let prettier_dir = prettier.prettier_dir(); - let is_default = prettier.is_default(); - if is_default { - log::info!("Started default prettier in {prettier_dir:?}"); - } else { - log::info!("Started prettier in {prettier_dir:?}"); - } - if let Some(prettier_server) = prettier.server() { - project.update(cx, |project, cx| { - let name = if is_default { - LanguageServerName(Arc::from("prettier (default)")) - } else { - let worktree_path = worktree_id - .and_then(|id| project.worktree_for_id(id, cx)) - .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path())); - let name = match worktree_path { - Some(worktree_path) => { - if prettier_dir == worktree_path.as_ref() { - let name = prettier_dir - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or_default(); - format!("prettier ({name})") - } else { - let dir_to_display = prettier_dir - .strip_prefix(worktree_path.as_ref()) - .ok() - .unwrap_or(prettier_dir); - format!("prettier ({})", dir_to_display.display()) - } - } - None => format!("prettier ({})", prettier_dir.display()), - }; - LanguageServerName(Arc::from(name)) - }; - project - .supplementary_language_servers - .insert(new_server_id, (name, Arc::clone(prettier_server))); - cx.emit(Event::LanguageServerAdded(new_server_id)); - }); - } -} - -async fn install_default_prettier( - plugins_to_install: HashSet<&'static str>, - node: Arc, - fs: Arc, -) -> anyhow::Result<()> { - let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); - // method creates parent directory if it doesn't exist - fs.save( - &prettier_wrapper_path, - &text::Rope::from(prettier::PRETTIER_SERVER_JS), - text::LineEnding::Unix, - ) - .await - .with_context(|| { - format!( - "writing {} file at {prettier_wrapper_path:?}", - prettier::PRETTIER_SERVER_FILE - ) - })?; - - let packages_to_versions = - future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( - |package_name| async { - let returned_package_name = package_name.to_string(); - let latest_version = node - .npm_package_latest_version(package_name) - .await - .with_context(|| { - format!("fetching latest npm version for package {returned_package_name}") - })?; - anyhow::Ok((returned_package_name, latest_version)) - }, - )) - .await - .context("fetching latest npm versions")?; - - log::info!("Fetching default prettier and plugins: {packages_to_versions:?}"); - let borrowed_packages = packages_to_versions - .iter() - .map(|(package, version)| (package.as_str(), version.as_str())) - .collect::>(); - node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages) - .await - .context("fetching formatter packages")?; - anyhow::Ok(()) } fn subscribe_for_copilot_events( @@ -9305,56 +8681,3 @@ fn include_text(server: &lsp::LanguageServer) -> bool { }) .unwrap_or(false) } - -async fn format_with_prettier( - project: &ModelHandle, - buffer: &ModelHandle, - cx: &mut AsyncAppContext, -) -> Option { - if let Some((prettier_path, prettier_task)) = project - .update(cx, |project, cx| { - project.prettier_instance_for_buffer(buffer, cx) - }) - .await - { - match prettier_task.await { - Ok(prettier) => { - let buffer_path = buffer.update(cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - }); - match prettier.format(buffer, buffer_path, cx).await { - Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), - Err(e) => { - log::error!( - "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" - ); - } - } - } - Err(e) => project.update(cx, |project, _| { - let instance_to_update = match prettier_path { - Some(prettier_path) => { - log::error!( - "Prettier instance from path {prettier_path:?} failed to spawn: {e:#}" - ); - project.prettier_instances.get_mut(&prettier_path) - } - None => { - log::error!("Default prettier instance failed to spawn: {e:#}"); - match &mut project.default_prettier.prettier { - PrettierInstallation::NotInstalled { .. } => None, - PrettierInstallation::Installed(instance) => Some(instance), - } - } - }; - - if let Some(instance) = instance_to_update { - instance.attempt += 1; - instance.prettier = None; - } - }), - } - } - - None -} From 938f2531c40a766d67d3f6a95fc95a99fce9b98c Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 16:31:24 +0200 Subject: [PATCH 05/16] Always write prettier server file --- crates/project/src/prettier_support.rs | 92 ++++++++++++++------------ 1 file changed, 50 insertions(+), 42 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index f59ff20a24c21952fcfd4c7e099643190f63049f..32f32cc0dc14a04c69b5708f1c282dd0026dbbd7 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -193,51 +193,53 @@ fn start_default_prettier( ) -> Task> { cx.spawn(|project, mut cx| async move { loop { - let mut install_attempt = 0; let installation_process = project.update(&mut cx, |project, _| { match &project.default_prettier.prettier { PrettierInstallation::NotInstalled { installation_process, - attempts - } => { - install_attempt = *attempts; - ControlFlow::Continue(installation_process.clone())}, + .. + } => ControlFlow::Continue(installation_process.clone()), PrettierInstallation::Installed(default_prettier) => { ControlFlow::Break(default_prettier.clone()) } } }); - install_attempt += 1; - match installation_process { - ControlFlow::Continue(installation_process) => { - if let Some(installation_process) = installation_process.clone() { - if let Err(e) = installation_process.await { - anyhow::bail!("Cannot start default prettier due to its installation failure: {e:#}"); - } + ControlFlow::Continue(None) => { + anyhow::bail!("Default prettier is not installed and cannot be started") + } + ControlFlow::Continue(Some(installation_process)) => { + if let Err(e) = installation_process.await { + anyhow::bail!( + "Cannot start default prettier due to its installation failure: {e:#}" + ); } let new_default_prettier = project.update(&mut cx, |project, cx| { let new_default_prettier = start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); project.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { attempt: install_attempt, prettier: Some(new_default_prettier.clone()) }); + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: Some(new_default_prettier.clone()), + }); new_default_prettier }); return Ok(new_default_prettier); } - ControlFlow::Break(instance) => { - match instance.prettier { - Some(instance) => return Ok(instance), - None => { - let new_default_prettier = project.update(&mut cx, |project, cx| { - let new_default_prettier = - start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); - project.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { attempt: instance.attempt + 1, prettier: Some(new_default_prettier.clone()) }); - new_default_prettier - }); - return Ok(new_default_prettier); - }, + ControlFlow::Break(instance) => match instance.prettier { + Some(instance) => return Ok(instance), + None => { + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: instance.attempt + 1, + prettier: Some(new_default_prettier.clone()), + }); + new_default_prettier + }); + return Ok(new_default_prettier); } }, } @@ -322,21 +324,6 @@ async fn install_default_prettier( node: Arc, fs: Arc, ) -> anyhow::Result<()> { - let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); - // method creates parent directory if it doesn't exist - fs.save( - &prettier_wrapper_path, - &text::Rope::from(prettier::PRETTIER_SERVER_JS), - text::LineEnding::Unix, - ) - .await - .with_context(|| { - format!( - "writing {} file at {prettier_wrapper_path:?}", - prettier::PRETTIER_SERVER_FILE - ) - })?; - let packages_to_versions = future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( |package_name| async { @@ -364,6 +351,23 @@ async fn install_default_prettier( anyhow::Ok(()) } +async fn save_prettier_server_file(fs: &dyn Fs) -> Result<(), anyhow::Error> { + let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); + fs.save( + &prettier_wrapper_path, + &text::Rope::from(prettier::PRETTIER_SERVER_JS), + text::LineEnding::Unix, + ) + .await + .with_context(|| { + format!( + "writing {} file at {prettier_wrapper_path:?}", + prettier::PRETTIER_SERVER_FILE + ) + })?; + Ok(()) +} + impl Project { pub fn update_prettier_settings( &self, @@ -662,7 +666,10 @@ impl Project { .map_err(Arc::new)? { ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), + ControlFlow::Continue(Some(_non_default_prettier)) => { + save_prettier_server_file(fs.as_ref()).await?; + return Ok(()); + } ControlFlow::Continue(None) => { let mut needs_install = match previous_installation_process { Some(previous_installation_process) => { @@ -681,6 +688,7 @@ impl Project { cx.background() // TODO kb instead of always installing, try to start the existing installation first? .spawn(async move { + save_prettier_server_file(fs.as_ref()).await?; install_default_prettier(plugins_to_install, node, fs).await }) .await From 46ac82f49862992074c9835e509e7f643edd3ace Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 18:45:12 +0200 Subject: [PATCH 06/16] Do not attempt to run default prettier if it's not installed yet --- crates/project/src/prettier_support.rs | 180 +++++++++++++------------ 1 file changed, 96 insertions(+), 84 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 32f32cc0dc14a04c69b5708f1c282dd0026dbbd7..04e56d2b8aec038990b50740b36c41127db9f9b5 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -86,7 +86,7 @@ pub struct DefaultPrettier { pub enum PrettierInstallation { NotInstalled { attempts: usize, - installation_process: Option>>>>, + installation_task: Option>>>>, }, Installed(PrettierInstance), } @@ -104,7 +104,7 @@ impl Default for DefaultPrettier { Self { prettier: PrettierInstallation::NotInstalled { attempts: 0, - installation_process: None, + installation_task: None, }, installed_plugins: HashSet::default(), } @@ -128,9 +128,7 @@ impl DefaultPrettier { ) -> Option>> { match &mut self.prettier { PrettierInstallation::NotInstalled { .. } => { - // `start_default_prettier` will start the installation process if it's not already running and wait for it to finish - let new_task = start_default_prettier(Arc::clone(node), worktree_id, cx); - Some(cx.spawn(|_, _| async move { new_task.await })) + Some(start_default_prettier(Arc::clone(node), worktree_id, cx)) } PrettierInstallation::Installed(existing_instance) => { existing_instance.prettier_task(node, None, worktree_id, cx) @@ -193,23 +191,31 @@ fn start_default_prettier( ) -> Task> { cx.spawn(|project, mut cx| async move { loop { - let installation_process = project.update(&mut cx, |project, _| { + let installation_task = project.update(&mut cx, |project, _| { match &project.default_prettier.prettier { PrettierInstallation::NotInstalled { - installation_process, - .. - } => ControlFlow::Continue(installation_process.clone()), + installation_task, .. + } => ControlFlow::Continue(installation_task.clone()), PrettierInstallation::Installed(default_prettier) => { ControlFlow::Break(default_prettier.clone()) } } }); - match installation_process { + match installation_task { ControlFlow::Continue(None) => { anyhow::bail!("Default prettier is not installed and cannot be started") } - ControlFlow::Continue(Some(installation_process)) => { - if let Err(e) = installation_process.await { + ControlFlow::Continue(Some(installation_task)) => { + log::info!("Waiting for default prettier to install"); + if let Err(e) = installation_task.await { + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { + installation_task, .. + } = &mut project.default_prettier.prettier + { + *installation_task = None; + } + }); anyhow::bail!( "Cannot start default prettier due to its installation failure: {e:#}" ); @@ -254,6 +260,7 @@ fn start_prettier( cx: &mut ModelContext<'_, Project>, ) -> PrettierTask { cx.spawn(|project, mut cx| async move { + log::info!("Starting prettier at path {prettier_dir:?}"); let new_server_id = project.update(&mut cx, |project, _| { project.languages.next_language_server_id() }); @@ -319,10 +326,9 @@ fn register_new_prettier( } } -async fn install_default_prettier( +async fn install_prettier_packages( plugins_to_install: HashSet<&'static str>, node: Arc, - fs: Arc, ) -> anyhow::Result<()> { let packages_to_versions = future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( @@ -563,23 +569,24 @@ impl Project { } } - #[cfg(any(test, feature = "test-support"))] - pub fn install_default_prettier( - &mut self, - _worktree: Option, - _new_language: &Language, - language_settings: &LanguageSettings, - _cx: &mut ModelContext, - ) { - // suppress unused code warnings - match &language_settings.formatter { - Formatter::Prettier { .. } | Formatter::Auto => {} - Formatter::LanguageServer | Formatter::External { .. } => return, - }; - let _ = &self.default_prettier.installed_plugins; - } - - #[cfg(not(any(test, feature = "test-support")))] + // TODO kb uncomment + // #[cfg(any(test, feature = "test-support"))] + // pub fn install_default_prettier( + // &mut self, + // _worktree: Option, + // _new_language: &Language, + // language_settings: &LanguageSettings, + // _cx: &mut ModelContext, + // ) { + // // suppress unused code warnings + // match &language_settings.formatter { + // Formatter::Prettier { .. } | Formatter::Auto => {} + // Formatter::LanguageServer | Formatter::External { .. } => return, + // }; + // let _ = &self.default_prettier.installed_plugins; + // } + + // #[cfg(not(any(test, feature = "test-support")))] pub fn install_default_prettier( &mut self, worktree: Option, @@ -632,13 +639,13 @@ impl Project { plugins_to_install .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); let mut installation_attempts = 0; - let previous_installation_process = match &self.default_prettier.prettier { + let previous_installation_task = match &self.default_prettier.prettier { PrettierInstallation::NotInstalled { - installation_process, + installation_task, attempts, } => { installation_attempts = *attempts; - installation_process.clone() + installation_task.clone() } PrettierInstallation::Installed { .. } => { if plugins_to_install.is_empty() { @@ -656,61 +663,66 @@ impl Project { } let fs = Arc::clone(&self.fs); - self.default_prettier.prettier = PrettierInstallation::NotInstalled { - attempts: installation_attempts + 1, - installation_process: Some( - cx.spawn(|this, mut cx| async move { - match locate_prettier_installation - .await - .context("locate prettier installation") - .map_err(Arc::new)? - { - ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => { - save_prettier_server_file(fs.as_ref()).await?; - return Ok(()); - } - ControlFlow::Continue(None) => { - let mut needs_install = match previous_installation_process { - Some(previous_installation_process) => { - previous_installation_process.await.is_err() + let new_installation_task = cx + .spawn(|this, mut cx| async move { + match locate_prettier_installation + .await + .context("locate prettier installation") + .map_err(Arc::new)? + { + ControlFlow::Break(()) => return Ok(()), + ControlFlow::Continue(Some(_non_default_prettier)) => { + save_prettier_server_file(fs.as_ref()).await?; + return Ok(()); + } + ControlFlow::Continue(None) => { + let mut needs_install = match previous_installation_task { + Some(previous_installation_task) => { + match previous_installation_task.await { + Ok(()) => false, + Err(e) => { + log::error!("Failed to install default prettier: {e:#}"); + true + } } - None => true, - }; + } + None => true, + }; + this.update(&mut cx, |this, _| { + plugins_to_install.retain(|plugin| { + !this.default_prettier.installed_plugins.contains(plugin) + }); + needs_install |= !plugins_to_install.is_empty(); + }); + if needs_install { + let installed_plugins = plugins_to_install.clone(); + cx.background() + .spawn(async move { + save_prettier_server_file(fs.as_ref()).await?; + install_prettier_packages(plugins_to_install, node).await + }) + .await + .context("prettier & plugins install") + .map_err(Arc::new)?; this.update(&mut cx, |this, _| { - plugins_to_install.retain(|plugin| { - !this.default_prettier.installed_plugins.contains(plugin) - }); - needs_install |= !plugins_to_install.is_empty(); + this.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); + this.default_prettier + .installed_plugins + .extend(installed_plugins); }); - if needs_install { - let installed_plugins = plugins_to_install.clone(); - cx.background() - // TODO kb instead of always installing, try to start the existing installation first? - .spawn(async move { - save_prettier_server_file(fs.as_ref()).await?; - install_default_prettier(plugins_to_install, node, fs).await - }) - .await - .context("prettier & plugins install") - .map_err(Arc::new)?; - this.update(&mut cx, |this, _| { - this.default_prettier.prettier = - PrettierInstallation::Installed(PrettierInstance { - attempt: 0, - prettier: None, - }); - this.default_prettier - .installed_plugins - .extend(installed_plugins); - }); - } } } - Ok(()) - }) - .shared(), - ), + } + Ok(()) + }) + .shared(); + self.default_prettier.prettier = PrettierInstallation::NotInstalled { + attempts: installation_attempts + 1, + installation_task: Some(new_installation_task), }; } } From 465e53ef41d636601fe8b5a292e3786e97caee53 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 18:48:46 +0200 Subject: [PATCH 07/16] Always install default prettier --- crates/project/src/prettier_support.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 04e56d2b8aec038990b50740b36c41127db9f9b5..de256192b411695d0bc3d6b9271f2d394c47fdaa 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -671,11 +671,7 @@ impl Project { .map_err(Arc::new)? { ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => { - save_prettier_server_file(fs.as_ref()).await?; - return Ok(()); - } - ControlFlow::Continue(None) => { + ControlFlow::Continue(_) => { let mut needs_install = match previous_installation_task { Some(previous_installation_task) => { match previous_installation_task.await { From 43d28cc0c1b22c4bef81532e0764c13a39568759 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 18:56:16 +0200 Subject: [PATCH 08/16] Ignore `initialized` LSP request in prettier wrapper --- crates/prettier/src/prettier_server.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/prettier/src/prettier_server.js b/crates/prettier/src/prettier_server.js index 191431da0b89aaf8c98ae01b004e4fd1af981d43..bf62e538ddee2d29a5e41872f49f2258674cd82e 100644 --- a/crates/prettier/src/prettier_server.js +++ b/crates/prettier/src/prettier_server.js @@ -153,7 +153,10 @@ async function handleMessage(message, prettier) { const { method, id, params } = message; if (method === undefined) { throw new Error(`Message method is undefined: ${JSON.stringify(message)}`); + } else if (method == "initialized") { + return; } + if (id === undefined) { throw new Error(`Message id is undefined: ${JSON.stringify(message)}`); } From 64259e4a0b106efc4dc50583fe71a34669ca5a08 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 21:18:35 +0200 Subject: [PATCH 09/16] Properly increment installation attempts --- crates/project/src/prettier_support.rs | 46 +++++++++++++++++--------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index de256192b411695d0bc3d6b9271f2d394c47fdaa..ab99eed346cb04e0d8a3ab5f2328b5d2e4f386fa 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -210,10 +210,12 @@ fn start_default_prettier( if let Err(e) = installation_task.await { project.update(&mut cx, |project, _| { if let PrettierInstallation::NotInstalled { - installation_task, .. + installation_task, + attempts, } = &mut project.default_prettier.prettier { *installation_task = None; + *attempts += 1; } }); anyhow::bail!( @@ -654,17 +656,9 @@ impl Project { None } }; - - if installation_attempts > prettier::LAUNCH_THRESHOLD { - log::warn!( - "Default prettier installation has failed {installation_attempts} times, not attempting again", - ); - return; - } - let fs = Arc::clone(&self.fs); let new_installation_task = cx - .spawn(|this, mut cx| async move { + .spawn(|project, mut cx| async move { match locate_prettier_installation .await .context("locate prettier installation") @@ -677,6 +671,18 @@ impl Project { match previous_installation_task.await { Ok(()) => false, Err(e) => { + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { + attempts, + .. + } = &mut project.default_prettier.prettier + { + *attempts += 1; + installation_attempts = *attempts; + } else { + installation_attempts += 1; + } + }); log::error!("Failed to install default prettier: {e:#}"); true } @@ -684,9 +690,17 @@ impl Project { } None => true, }; - this.update(&mut cx, |this, _| { + + if installation_attempts > prettier::LAUNCH_THRESHOLD { + log::warn!( + "Default prettier installation has failed {installation_attempts} times, not attempting again", + ); + return Ok(()); + } + + project.update(&mut cx, |project, _| { plugins_to_install.retain(|plugin| { - !this.default_prettier.installed_plugins.contains(plugin) + !project.default_prettier.installed_plugins.contains(plugin) }); needs_install |= !plugins_to_install.is_empty(); }); @@ -700,13 +714,13 @@ impl Project { .await .context("prettier & plugins install") .map_err(Arc::new)?; - this.update(&mut cx, |this, _| { - this.default_prettier.prettier = + project.update(&mut cx, |project, _| { + project.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance { attempt: 0, prettier: None, }); - this.default_prettier + project.default_prettier .installed_plugins .extend(installed_plugins); }); @@ -717,7 +731,7 @@ impl Project { }) .shared(); self.default_prettier.prettier = PrettierInstallation::NotInstalled { - attempts: installation_attempts + 1, + attempts: installation_attempts, installation_task: Some(new_installation_task), }; } From acd1aec86206ac8d977b88f63e82ca3ee0c46f27 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 22:16:16 +0200 Subject: [PATCH 10/16] Properly determine default prettier plugins to install --- crates/project/src/prettier_support.rs | 109 +++++++++++++------------ 1 file changed, 56 insertions(+), 53 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index ab99eed346cb04e0d8a3ab5f2328b5d2e4f386fa..35ba1d0f8b17a42310d6adb54b7f36ed6b9ca7c9 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -87,6 +87,7 @@ pub enum PrettierInstallation { NotInstalled { attempts: usize, installation_task: Option>>>>, + not_installed_plugins: HashSet<&'static str>, }, Installed(PrettierInstance), } @@ -105,6 +106,7 @@ impl Default for DefaultPrettier { prettier: PrettierInstallation::NotInstalled { attempts: 0, installation_task: None, + not_installed_plugins: HashSet::default(), }, installed_plugins: HashSet::default(), } @@ -212,6 +214,7 @@ fn start_default_prettier( if let PrettierInstallation::NotInstalled { installation_task, attempts, + .. } = &mut project.default_prettier.prettier { *installation_task = None; @@ -571,24 +574,23 @@ impl Project { } } - // TODO kb uncomment - // #[cfg(any(test, feature = "test-support"))] - // pub fn install_default_prettier( - // &mut self, - // _worktree: Option, - // _new_language: &Language, - // language_settings: &LanguageSettings, - // _cx: &mut ModelContext, - // ) { - // // suppress unused code warnings - // match &language_settings.formatter { - // Formatter::Prettier { .. } | Formatter::Auto => {} - // Formatter::LanguageServer | Formatter::External { .. } => return, - // }; - // let _ = &self.default_prettier.installed_plugins; - // } + #[cfg(any(test, feature = "test-support"))] + pub fn install_default_prettier( + &mut self, + _worktree: Option, + _new_language: &Language, + language_settings: &LanguageSettings, + _cx: &mut ModelContext, + ) { + // suppress unused code warnings + match &language_settings.formatter { + Formatter::Prettier { .. } | Formatter::Auto => {} + Formatter::LanguageServer | Formatter::External { .. } => return, + }; + let _ = &self.default_prettier.installed_plugins; + } - // #[cfg(not(any(test, feature = "test-support")))] + #[cfg(not(any(test, feature = "test-support")))] pub fn install_default_prettier( &mut self, worktree: Option, @@ -637,25 +639,28 @@ impl Project { } None => Task::ready(Ok(ControlFlow::Break(()))), }; - let mut plugins_to_install = prettier_plugins; - plugins_to_install + let mut new_plugins = prettier_plugins; + new_plugins .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); - let mut installation_attempts = 0; + let mut installation_attempt = 0; let previous_installation_task = match &self.default_prettier.prettier { PrettierInstallation::NotInstalled { installation_task, attempts, + not_installed_plugins } => { - installation_attempts = *attempts; + installation_attempt = *attempts; + new_plugins.extend(not_installed_plugins.iter()); installation_task.clone() } PrettierInstallation::Installed { .. } => { - if plugins_to_install.is_empty() { + if new_plugins.is_empty() { return; } None } }; + let plugins_to_install = new_plugins.clone(); let fs = Arc::clone(&self.fs); let new_installation_task = cx .spawn(|project, mut cx| async move { @@ -665,51 +670,48 @@ impl Project { .map_err(Arc::new)? { ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(_) => { - let mut needs_install = match previous_installation_task { - Some(previous_installation_task) => { - match previous_installation_task.await { - Ok(()) => false, - Err(e) => { - project.update(&mut cx, |project, _| { - if let PrettierInstallation::NotInstalled { - attempts, - .. - } = &mut project.default_prettier.prettier - { - *attempts += 1; - installation_attempts = *attempts; - } else { - installation_attempts += 1; - } - }); - log::error!("Failed to install default prettier: {e:#}"); - true + ControlFlow::Continue(prettier_path) => { + if prettier_path.is_some() { + new_plugins.clear(); + } + let mut needs_install = false; + if let Some(previous_installation_task) = previous_installation_task { + if let Err(e) = previous_installation_task.await { + log::error!("Failed to install default prettier (attempt {installation_attempt}): {e:#}"); + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { attempts, not_installed_plugins, .. } = &mut project.default_prettier.prettier { + *attempts += 1; + new_plugins.extend(not_installed_plugins.iter()); + installation_attempt = *attempts; + needs_install = true; } - } + }) } - None => true, }; - - if installation_attempts > prettier::LAUNCH_THRESHOLD { + if installation_attempt > prettier::LAUNCH_THRESHOLD { log::warn!( - "Default prettier installation has failed {installation_attempts} times, not attempting again", + "Default prettier installation has failed {installation_attempt} times, not attempting again", ); return Ok(()); } - project.update(&mut cx, |project, _| { - plugins_to_install.retain(|plugin| { + new_plugins.retain(|plugin| { !project.default_prettier.installed_plugins.contains(plugin) }); - needs_install |= !plugins_to_install.is_empty(); + if let PrettierInstallation::NotInstalled { not_installed_plugins, .. } = &mut project.default_prettier.prettier { + not_installed_plugins.retain(|plugin| { + !project.default_prettier.installed_plugins.contains(plugin) + }); + not_installed_plugins.extend(new_plugins.iter()); + } + needs_install |= !new_plugins.is_empty(); }); if needs_install { - let installed_plugins = plugins_to_install.clone(); + let installed_plugins = new_plugins.clone(); cx.background() .spawn(async move { save_prettier_server_file(fs.as_ref()).await?; - install_prettier_packages(plugins_to_install, node).await + install_prettier_packages(new_plugins, node).await }) .await .context("prettier & plugins install") @@ -731,8 +733,9 @@ impl Project { }) .shared(); self.default_prettier.prettier = PrettierInstallation::NotInstalled { - attempts: installation_attempts, + attempts: installation_attempt, installation_task: Some(new_installation_task), + not_installed_plugins: plugins_to_install, }; } } From 96f6b89508367d564e3a1ef3698e54fff1aae441 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 23:12:46 +0200 Subject: [PATCH 11/16] Clear failed installation task when error threshold gets exceeded --- crates/prettier/src/prettier.rs | 2 +- crates/project/src/prettier_support.rs | 27 +++++++++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/prettier/src/prettier.rs b/crates/prettier/src/prettier.rs index 61a6656ea4136c7f9345a32569fba3cdf6d193f5..0886d68747369e0c64e12d43d34ad787c31ddd61 100644 --- a/crates/prettier/src/prettier.rs +++ b/crates/prettier/src/prettier.rs @@ -34,7 +34,7 @@ pub struct TestPrettier { default: bool, } -pub const LAUNCH_THRESHOLD: usize = 5; +pub const FAIL_THRESHOLD: usize = 4; pub const PRETTIER_SERVER_FILE: &str = "prettier_server.js"; pub const PRETTIER_SERVER_JS: &str = include_str!("./prettier_server.js"); const PRETTIER_PACKAGE_NAME: &str = "prettier"; diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 35ba1d0f8b17a42310d6adb54b7f36ed6b9ca7c9..a61589b8b4caf890a19dc9ac993e3a2945577dd0 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -147,7 +147,7 @@ impl PrettierInstance { worktree_id: Option, cx: &mut ModelContext<'_, Project>, ) -> Option>> { - if self.attempt > prettier::LAUNCH_THRESHOLD { + if self.attempt > prettier::FAIL_THRESHOLD { match prettier_dir { Some(prettier_dir) => log::warn!( "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting" @@ -643,13 +643,20 @@ impl Project { new_plugins .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); let mut installation_attempt = 0; - let previous_installation_task = match &self.default_prettier.prettier { + let previous_installation_task = match &mut self.default_prettier.prettier { PrettierInstallation::NotInstalled { installation_task, attempts, not_installed_plugins } => { installation_attempt = *attempts; + if installation_attempt > prettier::FAIL_THRESHOLD { + *installation_task = None; + log::warn!( + "Default prettier installation had failed {installation_attempt} times, not attempting again", + ); + return; + } new_plugins.extend(not_installed_plugins.iter()); installation_task.clone() } @@ -660,6 +667,7 @@ impl Project { None } }; + let plugins_to_install = new_plugins.clone(); let fs = Arc::clone(&self.fs); let new_installation_task = cx @@ -677,20 +685,25 @@ impl Project { let mut needs_install = false; if let Some(previous_installation_task) = previous_installation_task { if let Err(e) = previous_installation_task.await { - log::error!("Failed to install default prettier (attempt {installation_attempt}): {e:#}"); + log::error!("Failed to install default prettier: {e:#}"); project.update(&mut cx, |project, _| { if let PrettierInstallation::NotInstalled { attempts, not_installed_plugins, .. } = &mut project.default_prettier.prettier { *attempts += 1; new_plugins.extend(not_installed_plugins.iter()); installation_attempt = *attempts; needs_install = true; - } - }) + }; + }); } }; - if installation_attempt > prettier::LAUNCH_THRESHOLD { + if installation_attempt > prettier::FAIL_THRESHOLD { + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { installation_task, .. } = &mut project.default_prettier.prettier { + *installation_task = None; + }; + }); log::warn!( - "Default prettier installation has failed {installation_attempt} times, not attempting again", + "Default prettier installation had failed {installation_attempt} times, not attempting again", ); return Ok(()); } From f1314afe357e1f3ed05cc6f37c34765c330048e6 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Tue, 28 Nov 2023 23:23:05 +0200 Subject: [PATCH 12/16] Simplify default prettier installation function --- crates/project/src/prettier_support.rs | 53 +++++++++++--------------- crates/project/src/project.rs | 13 +++++-- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index a61589b8b4caf890a19dc9ac993e3a2945577dd0..314c571fd8a200e80ced94c4fdecb8460a33d5ba 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -25,6 +25,26 @@ use crate::{ Event, File, FormatOperation, PathChange, Project, ProjectEntryId, Worktree, WorktreeId, }; +pub fn prettier_plugins_for_language(language: &Language, language_settings: &LanguageSettings) -> Option> { + match &language_settings.formatter { + Formatter::Prettier { .. } | Formatter::Auto => {} + Formatter::LanguageServer | Formatter::External { .. } => return None, + }; + let mut prettier_plugins = None; + if language.prettier_parser_name().is_some() { + prettier_plugins + .get_or_insert_with(|| HashSet::default()) + .extend( + language + .lsp_adapters() + .iter() + .flat_map(|adapter| adapter.prettier_plugins()), + ) + } + + prettier_plugins +} + pub(super) async fn format_with_prettier( project: &ModelHandle, buffer: &ModelHandle, @@ -578,15 +598,10 @@ impl Project { pub fn install_default_prettier( &mut self, _worktree: Option, - _new_language: &Language, - language_settings: &LanguageSettings, + _plugins: HashSet<&'static str>, _cx: &mut ModelContext, ) { // suppress unused code warnings - match &language_settings.formatter { - Formatter::Prettier { .. } | Formatter::Auto => {} - Formatter::LanguageServer | Formatter::External { .. } => return, - }; let _ = &self.default_prettier.installed_plugins; } @@ -594,33 +609,12 @@ impl Project { pub fn install_default_prettier( &mut self, worktree: Option, - new_language: &Language, - language_settings: &LanguageSettings, + mut new_plugins: HashSet<&'static str>, cx: &mut ModelContext, ) { - match &language_settings.formatter { - Formatter::Prettier { .. } | Formatter::Auto => {} - Formatter::LanguageServer | Formatter::External { .. } => return, - }; let Some(node) = self.node.as_ref().cloned() else { return; }; - - let mut prettier_plugins = None; - if new_language.prettier_parser_name().is_some() { - prettier_plugins - .get_or_insert_with(|| HashSet::<&'static str>::default()) - .extend( - new_language - .lsp_adapters() - .iter() - .flat_map(|adapter| adapter.prettier_plugins()), - ) - } - let Some(prettier_plugins) = prettier_plugins else { - return; - }; - let fs = Arc::clone(&self.fs); let locate_prettier_installation = match worktree.and_then(|worktree_id| { self.worktree_for_id(worktree_id, cx) @@ -637,9 +631,8 @@ impl Project { .await }) } - None => Task::ready(Ok(ControlFlow::Break(()))), + None => Task::ready(Ok(ControlFlow::Continue(None))), }; - let mut new_plugins = prettier_plugins; new_plugins .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); let mut installation_attempt = 0; diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index ad2a13482b128d69d7aa41fad0b101ef52797f5d..a4ee9fb55296671bb40129df0d9af25bb2180ec2 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -925,8 +925,14 @@ impl Project { .detach(); } + let mut prettier_plugins_by_worktree = HashMap::default(); for (worktree, language, settings) in language_formatters_to_check { - self.install_default_prettier(worktree, &language, &settings, cx); + if let Some(plugins) = prettier_support::prettier_plugins_for_language(&language, &settings) { + prettier_plugins_by_worktree.entry(worktree).or_insert_with(|| HashSet::default()).extend(plugins); + } + } + for (worktree, prettier_plugins) in prettier_plugins_by_worktree { + self.install_default_prettier(worktree, prettier_plugins, cx); } // Start all the newly-enabled language servers. @@ -2682,8 +2688,9 @@ impl Project { let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone(); let buffer_file = File::from_dyn(buffer_file.as_ref()); let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx)); - - self.install_default_prettier(worktree, &new_language, &settings, cx); + if let Some(prettier_plugins) = prettier_support::prettier_plugins_for_language(&new_language, &settings) { + self.install_default_prettier(worktree, prettier_plugins, cx); + }; if let Some(file) = buffer_file { let worktree = file.worktree.clone(); if let Some(tree) = worktree.read(cx).as_local() { From 6e44f53ea15cd770a814601cde23031e59ea167b Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Wed, 29 Nov 2023 11:33:29 +0200 Subject: [PATCH 13/16] Style fixes --- crates/project/src/prettier_support.rs | 12 ++++++++---- crates/project/src/project.rs | 19 ++++++++++++------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 314c571fd8a200e80ced94c4fdecb8460a33d5ba..063c4abcc44301c30f77825eeeaebb3c15699a18 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -25,7 +25,10 @@ use crate::{ Event, File, FormatOperation, PathChange, Project, ProjectEntryId, Worktree, WorktreeId, }; -pub fn prettier_plugins_for_language(language: &Language, language_settings: &LanguageSettings) -> Option> { +pub fn prettier_plugins_for_language( + language: &Language, + language_settings: &LanguageSettings, +) -> Option> { match &language_settings.formatter { Formatter::Prettier { .. } | Formatter::Auto => {} Formatter::LanguageServer | Formatter::External { .. } => return None, @@ -603,6 +606,8 @@ impl Project { ) { // suppress unused code warnings let _ = &self.default_prettier.installed_plugins; + let _ = install_prettier_packages; + let _ = save_prettier_server_file; } #[cfg(not(any(test, feature = "test-support")))] @@ -633,14 +638,13 @@ impl Project { } None => Task::ready(Ok(ControlFlow::Continue(None))), }; - new_plugins - .retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); + new_plugins.retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); let mut installation_attempt = 0; let previous_installation_task = match &mut self.default_prettier.prettier { PrettierInstallation::NotInstalled { installation_task, attempts, - not_installed_plugins + not_installed_plugins, } => { installation_attempt = *attempts; if installation_attempt > prettier::FAIL_THRESHOLD { diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index a4ee9fb55296671bb40129df0d9af25bb2180ec2..a2ad82585eadb9d4e010fe953ae17319ad23728f 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -927,8 +927,13 @@ impl Project { let mut prettier_plugins_by_worktree = HashMap::default(); for (worktree, language, settings) in language_formatters_to_check { - if let Some(plugins) = prettier_support::prettier_plugins_for_language(&language, &settings) { - prettier_plugins_by_worktree.entry(worktree).or_insert_with(|| HashSet::default()).extend(plugins); + if let Some(plugins) = + prettier_support::prettier_plugins_for_language(&language, &settings) + { + prettier_plugins_by_worktree + .entry(worktree) + .or_insert_with(|| HashSet::default()) + .extend(plugins); } } for (worktree, prettier_plugins) in prettier_plugins_by_worktree { @@ -2688,7 +2693,9 @@ impl Project { let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone(); let buffer_file = File::from_dyn(buffer_file.as_ref()); let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx)); - if let Some(prettier_plugins) = prettier_support::prettier_plugins_for_language(&new_language, &settings) { + if let Some(prettier_plugins) = + prettier_support::prettier_plugins_for_language(&new_language, &settings) + { self.install_default_prettier(worktree, prettier_plugins, cx); }; if let Some(file) = buffer_file { @@ -4077,8 +4084,6 @@ impl Project { let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save; let ensure_final_newline = settings.ensure_final_newline_on_save; - let format_on_save = settings.format_on_save.clone(); - let formatter = settings.formatter.clone(); let tab_size = settings.tab_size; // First, format buffer's whitespace according to the settings. @@ -4106,7 +4111,7 @@ impl Project { // Apply language-specific formatting using either a language server // or external command. let mut format_operation = None; - match (formatter, format_on_save) { + match (&settings.formatter, &settings.format_on_save) { (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {} (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off) @@ -4173,7 +4178,7 @@ impl Project { )); } } - (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => { + (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => { if let Some(new_operation) = prettier_support::format_with_prettier(&project, buffer, &mut cx) .await From 3796e7eecb4b922de599b815c87a2bd3808485c9 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Wed, 29 Nov 2023 11:48:10 +0200 Subject: [PATCH 14/16] Port to gpui2 --- crates/prettier2/src/prettier2.rs | 4 + crates/prettier2/src/prettier_server.js | 3 + crates/project2/src/prettier_support.rs | 765 ++++++++++++++++++++++++ crates/project2/src/project2.rs | 728 ++-------------------- 4 files changed, 823 insertions(+), 677 deletions(-) create mode 100644 crates/project2/src/prettier_support.rs diff --git a/crates/prettier2/src/prettier2.rs b/crates/prettier2/src/prettier2.rs index a01144ced330fa3bfcb75ac8330c6f526b25dfb1..61bcf9c9b3520993b09ed6110723fa5a7631b1ca 100644 --- a/crates/prettier2/src/prettier2.rs +++ b/crates/prettier2/src/prettier2.rs @@ -13,12 +13,14 @@ use std::{ }; use util::paths::{PathMatcher, DEFAULT_PRETTIER_DIR}; +#[derive(Clone)] pub enum Prettier { Real(RealPrettier), #[cfg(any(test, feature = "test-support"))] Test(TestPrettier), } +#[derive(Clone)] pub struct RealPrettier { default: bool, prettier_dir: PathBuf, @@ -26,11 +28,13 @@ pub struct RealPrettier { } #[cfg(any(test, feature = "test-support"))] +#[derive(Clone)] pub struct TestPrettier { prettier_dir: PathBuf, default: bool, } +pub const FAIL_THRESHOLD: usize = 4; pub const PRETTIER_SERVER_FILE: &str = "prettier_server.js"; pub const PRETTIER_SERVER_JS: &str = include_str!("./prettier_server.js"); const PRETTIER_PACKAGE_NAME: &str = "prettier"; diff --git a/crates/prettier2/src/prettier_server.js b/crates/prettier2/src/prettier_server.js index 191431da0b89aaf8c98ae01b004e4fd1af981d43..bf62e538ddee2d29a5e41872f49f2258674cd82e 100644 --- a/crates/prettier2/src/prettier_server.js +++ b/crates/prettier2/src/prettier_server.js @@ -153,7 +153,10 @@ async function handleMessage(message, prettier) { const { method, id, params } = message; if (method === undefined) { throw new Error(`Message method is undefined: ${JSON.stringify(message)}`); + } else if (method == "initialized") { + return; } + if (id === undefined) { throw new Error(`Message id is undefined: ${JSON.stringify(message)}`); } diff --git a/crates/project2/src/prettier_support.rs b/crates/project2/src/prettier_support.rs new file mode 100644 index 0000000000000000000000000000000000000000..15f3028d8504700ef9085575be09182ab5b1dc11 --- /dev/null +++ b/crates/project2/src/prettier_support.rs @@ -0,0 +1,765 @@ +use std::{ + ops::ControlFlow, + path::{Path, PathBuf}, + sync::Arc, +}; + +use anyhow::Context; +use collections::HashSet; +use fs::Fs; +use futures::{ + future::{self, Shared}, + FutureExt, +}; +use gpui::{AsyncAppContext, Model, ModelContext, Task, WeakModel}; +use language::{ + language_settings::{Formatter, LanguageSettings}, + Buffer, Language, LanguageServerName, LocalFile, +}; +use lsp::LanguageServerId; +use node_runtime::NodeRuntime; +use prettier::Prettier; +use util::{paths::DEFAULT_PRETTIER_DIR, ResultExt, TryFutureExt}; + +use crate::{ + Event, File, FormatOperation, PathChange, Project, ProjectEntryId, Worktree, WorktreeId, +}; + +pub fn prettier_plugins_for_language( + language: &Language, + language_settings: &LanguageSettings, +) -> Option> { + match &language_settings.formatter { + Formatter::Prettier { .. } | Formatter::Auto => {} + Formatter::LanguageServer | Formatter::External { .. } => return None, + }; + let mut prettier_plugins = None; + if language.prettier_parser_name().is_some() { + prettier_plugins + .get_or_insert_with(|| HashSet::default()) + .extend( + language + .lsp_adapters() + .iter() + .flat_map(|adapter| adapter.prettier_plugins()), + ) + } + + prettier_plugins +} + +pub(super) async fn format_with_prettier( + project: &WeakModel, + buffer: &Model, + cx: &mut AsyncAppContext, +) -> Option { + if let Some((prettier_path, prettier_task)) = project + .update(cx, |project, cx| { + project.prettier_instance_for_buffer(buffer, cx) + }) + .ok()? + .await + { + match prettier_task.await { + Ok(prettier) => { + let buffer_path = buffer + .update(cx, |buffer, cx| { + File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) + }) + .ok()?; + match prettier.format(buffer, buffer_path, cx).await { + Ok(new_diff) => return Some(FormatOperation::Prettier(new_diff)), + Err(e) => { + log::error!( + "Prettier instance from {prettier_path:?} failed to format a buffer: {e:#}" + ); + } + } + } + Err(e) => project + .update(cx, |project, _| { + let instance_to_update = match prettier_path { + Some(prettier_path) => { + log::error!( + "Prettier instance from path {prettier_path:?} failed to spawn: {e:#}" + ); + project.prettier_instances.get_mut(&prettier_path) + } + None => { + log::error!("Default prettier instance failed to spawn: {e:#}"); + match &mut project.default_prettier.prettier { + PrettierInstallation::NotInstalled { .. } => None, + PrettierInstallation::Installed(instance) => Some(instance), + } + } + }; + + if let Some(instance) = instance_to_update { + instance.attempt += 1; + instance.prettier = None; + } + }) + .ok()?, + } + } + + None +} + +pub struct DefaultPrettier { + prettier: PrettierInstallation, + installed_plugins: HashSet<&'static str>, +} + +pub enum PrettierInstallation { + NotInstalled { + attempts: usize, + installation_task: Option>>>>, + not_installed_plugins: HashSet<&'static str>, + }, + Installed(PrettierInstance), +} + +pub type PrettierTask = Shared, Arc>>>; + +#[derive(Clone)] +pub struct PrettierInstance { + attempt: usize, + prettier: Option, +} + +impl Default for DefaultPrettier { + fn default() -> Self { + Self { + prettier: PrettierInstallation::NotInstalled { + attempts: 0, + installation_task: None, + not_installed_plugins: HashSet::default(), + }, + installed_plugins: HashSet::default(), + } + } +} + +impl DefaultPrettier { + pub fn instance(&self) -> Option<&PrettierInstance> { + if let PrettierInstallation::Installed(instance) = &self.prettier { + Some(instance) + } else { + None + } + } + + pub fn prettier_task( + &mut self, + node: &Arc, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + match &mut self.prettier { + PrettierInstallation::NotInstalled { .. } => { + Some(start_default_prettier(Arc::clone(node), worktree_id, cx)) + } + PrettierInstallation::Installed(existing_instance) => { + existing_instance.prettier_task(node, None, worktree_id, cx) + } + } + } +} + +impl PrettierInstance { + pub fn prettier_task( + &mut self, + node: &Arc, + prettier_dir: Option<&Path>, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, + ) -> Option>> { + if self.attempt > prettier::FAIL_THRESHOLD { + match prettier_dir { + Some(prettier_dir) => log::warn!( + "Prettier from path {prettier_dir:?} exceeded launch threshold, not starting" + ), + None => log::warn!("Default prettier exceeded launch threshold, not starting"), + } + return None; + } + Some(match &self.prettier { + Some(prettier_task) => Task::ready(Ok(prettier_task.clone())), + None => match prettier_dir { + Some(prettier_dir) => { + let new_task = start_prettier( + Arc::clone(node), + prettier_dir.to_path_buf(), + worktree_id, + cx, + ); + self.attempt += 1; + self.prettier = Some(new_task.clone()); + Task::ready(Ok(new_task)) + } + None => { + self.attempt += 1; + let node = Arc::clone(node); + cx.spawn(|project, mut cx| async move { + project + .update(&mut cx, |_, cx| { + start_default_prettier(node, worktree_id, cx) + })? + .await + }) + } + }, + }) + } +} + +fn start_default_prettier( + node: Arc, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, +) -> Task> { + cx.spawn(|project, mut cx| async move { + loop { + let installation_task = project.update(&mut cx, |project, _| { + match &project.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_task, .. + } => ControlFlow::Continue(installation_task.clone()), + PrettierInstallation::Installed(default_prettier) => { + ControlFlow::Break(default_prettier.clone()) + } + } + })?; + match installation_task { + ControlFlow::Continue(None) => { + anyhow::bail!("Default prettier is not installed and cannot be started") + } + ControlFlow::Continue(Some(installation_task)) => { + log::info!("Waiting for default prettier to install"); + if let Err(e) = installation_task.await { + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { + installation_task, + attempts, + .. + } = &mut project.default_prettier.prettier + { + *installation_task = None; + *attempts += 1; + } + })?; + anyhow::bail!( + "Cannot start default prettier due to its installation failure: {e:#}" + ); + } + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: Some(new_default_prettier.clone()), + }); + new_default_prettier + })?; + return Ok(new_default_prettier); + } + ControlFlow::Break(instance) => match instance.prettier { + Some(instance) => return Ok(instance), + None => { + let new_default_prettier = project.update(&mut cx, |project, cx| { + let new_default_prettier = + start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: instance.attempt + 1, + prettier: Some(new_default_prettier.clone()), + }); + new_default_prettier + })?; + return Ok(new_default_prettier); + } + }, + } + } + }) +} + +fn start_prettier( + node: Arc, + prettier_dir: PathBuf, + worktree_id: Option, + cx: &mut ModelContext<'_, Project>, +) -> PrettierTask { + cx.spawn(|project, mut cx| async move { + log::info!("Starting prettier at path {prettier_dir:?}"); + let new_server_id = project.update(&mut cx, |project, _| { + project.languages.next_language_server_id() + })?; + + let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) + .await + .context("default prettier spawn") + .map(Arc::new) + .map_err(Arc::new)?; + register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); + Ok(new_prettier) + }) + .shared() +} + +fn register_new_prettier( + project: &WeakModel, + prettier: &Prettier, + worktree_id: Option, + new_server_id: LanguageServerId, + cx: &mut AsyncAppContext, +) { + let prettier_dir = prettier.prettier_dir(); + let is_default = prettier.is_default(); + if is_default { + log::info!("Started default prettier in {prettier_dir:?}"); + } else { + log::info!("Started prettier in {prettier_dir:?}"); + } + if let Some(prettier_server) = prettier.server() { + project + .update(cx, |project, cx| { + let name = if is_default { + LanguageServerName(Arc::from("prettier (default)")) + } else { + let worktree_path = worktree_id + .and_then(|id| project.worktree_for_id(id, cx)) + .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path())); + let name = match worktree_path { + Some(worktree_path) => { + if prettier_dir == worktree_path.as_ref() { + let name = prettier_dir + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or_default(); + format!("prettier ({name})") + } else { + let dir_to_display = prettier_dir + .strip_prefix(worktree_path.as_ref()) + .ok() + .unwrap_or(prettier_dir); + format!("prettier ({})", dir_to_display.display()) + } + } + None => format!("prettier ({})", prettier_dir.display()), + }; + LanguageServerName(Arc::from(name)) + }; + project + .supplementary_language_servers + .insert(new_server_id, (name, Arc::clone(prettier_server))); + cx.emit(Event::LanguageServerAdded(new_server_id)); + }) + .ok(); + } +} + +async fn install_prettier_packages( + plugins_to_install: HashSet<&'static str>, + node: Arc, +) -> anyhow::Result<()> { + let packages_to_versions = + future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( + |package_name| async { + let returned_package_name = package_name.to_string(); + let latest_version = node + .npm_package_latest_version(package_name) + .await + .with_context(|| { + format!("fetching latest npm version for package {returned_package_name}") + })?; + anyhow::Ok((returned_package_name, latest_version)) + }, + )) + .await + .context("fetching latest npm versions")?; + + log::info!("Fetching default prettier and plugins: {packages_to_versions:?}"); + let borrowed_packages = packages_to_versions + .iter() + .map(|(package, version)| (package.as_str(), version.as_str())) + .collect::>(); + node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages) + .await + .context("fetching formatter packages")?; + anyhow::Ok(()) +} + +async fn save_prettier_server_file(fs: &dyn Fs) -> Result<(), anyhow::Error> { + let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); + fs.save( + &prettier_wrapper_path, + &text::Rope::from(prettier::PRETTIER_SERVER_JS), + text::LineEnding::Unix, + ) + .await + .with_context(|| { + format!( + "writing {} file at {prettier_wrapper_path:?}", + prettier::PRETTIER_SERVER_FILE + ) + })?; + Ok(()) +} + +impl Project { + pub fn update_prettier_settings( + &self, + worktree: &Model, + changes: &[(Arc, ProjectEntryId, PathChange)], + cx: &mut ModelContext<'_, Project>, + ) { + let prettier_config_files = Prettier::CONFIG_FILE_NAMES + .iter() + .map(Path::new) + .collect::>(); + + let prettier_config_file_changed = changes + .iter() + .filter(|(_, _, change)| !matches!(change, PathChange::Loaded)) + .filter(|(path, _, _)| { + !path + .components() + .any(|component| component.as_os_str().to_string_lossy() == "node_modules") + }) + .find(|(path, _, _)| prettier_config_files.contains(path.as_ref())); + let current_worktree_id = worktree.read(cx).id(); + if let Some((config_path, _, _)) = prettier_config_file_changed { + log::info!( + "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}" + ); + let prettiers_to_reload = + self.prettiers_per_worktree + .get(¤t_worktree_id) + .iter() + .flat_map(|prettier_paths| prettier_paths.iter()) + .flatten() + .filter_map(|prettier_path| { + Some(( + current_worktree_id, + Some(prettier_path.clone()), + self.prettier_instances.get(prettier_path)?.clone(), + )) + }) + .chain(self.default_prettier.instance().map(|default_prettier| { + (current_worktree_id, None, default_prettier.clone()) + })) + .collect::>(); + + cx.background_executor() + .spawn(async move { + let _: Vec<()> = future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_instance)| { + async move { + if let Some(instance) = prettier_instance.prettier { + match instance.await { + Ok(prettier) => { + prettier.clear_cache().log_err().await; + }, + Err(e) => { + match prettier_path { + Some(prettier_path) => log::error!( + "Failed to clear prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + None => log::error!( + "Failed to clear default prettier cache for worktree {worktree_id:?} on prettier settings update: {e:#}" + ), + } + }, + } + } + } + })) + .await; + }) + .detach(); + } + } + + fn prettier_instance_for_buffer( + &mut self, + buffer: &Model, + cx: &mut ModelContext, + ) -> Task, PrettierTask)>> { + let buffer = buffer.read(cx); + let buffer_file = buffer.file(); + let Some(buffer_language) = buffer.language() else { + return Task::ready(None); + }; + if buffer_language.prettier_parser_name().is_none() { + return Task::ready(None); + } + + if self.is_local() { + let Some(node) = self.node.as_ref().map(Arc::clone) else { + return Task::ready(None); + }; + match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx))) + { + Some((worktree_id, buffer_path)) => { + let fs = Arc::clone(&self.fs); + let installed_prettiers = self.prettier_instances.keys().cloned().collect(); + return cx.spawn(|project, mut cx| async move { + match cx + .background_executor() + .spawn(async move { + Prettier::locate_prettier_installation( + fs.as_ref(), + &installed_prettiers, + &buffer_path, + ) + .await + }) + .await + { + Ok(ControlFlow::Break(())) => { + return None; + } + Ok(ControlFlow::Continue(None)) => { + let default_instance = project + .update(&mut cx, |project, cx| { + project + .prettiers_per_worktree + .entry(worktree_id) + .or_default() + .insert(None); + project.default_prettier.prettier_task( + &node, + Some(worktree_id), + cx, + ) + }) + .ok()?; + Some((None, default_instance?.log_err().await?)) + } + Ok(ControlFlow::Continue(Some(prettier_dir))) => { + project + .update(&mut cx, |project, _| { + project + .prettiers_per_worktree + .entry(worktree_id) + .or_default() + .insert(Some(prettier_dir.clone())) + }) + .ok()?; + if let Some(prettier_task) = project + .update(&mut cx, |project, cx| { + project.prettier_instances.get_mut(&prettier_dir).map( + |existing_instance| { + existing_instance.prettier_task( + &node, + Some(&prettier_dir), + Some(worktree_id), + cx, + ) + }, + ) + }) + .ok()? + { + log::debug!( + "Found already started prettier in {prettier_dir:?}" + ); + return Some(( + Some(prettier_dir), + prettier_task?.await.log_err()?, + )); + } + + log::info!("Found prettier in {prettier_dir:?}, starting."); + let new_prettier_task = project + .update(&mut cx, |project, cx| { + let new_prettier_task = start_prettier( + node, + prettier_dir.clone(), + Some(worktree_id), + cx, + ); + project.prettier_instances.insert( + prettier_dir.clone(), + PrettierInstance { + attempt: 0, + prettier: Some(new_prettier_task.clone()), + }, + ); + new_prettier_task + }) + .ok()?; + Some((Some(prettier_dir), new_prettier_task)) + } + Err(e) => { + log::error!("Failed to determine prettier path for buffer: {e:#}"); + return None; + } + } + }); + } + None => { + let new_task = self.default_prettier.prettier_task(&node, None, cx); + return cx + .spawn(|_, _| async move { Some((None, new_task?.log_err().await?)) }); + } + } + } else { + return Task::ready(None); + } + } + + #[cfg(any(test, feature = "test-support"))] + pub fn install_default_prettier( + &mut self, + _worktree: Option, + _plugins: HashSet<&'static str>, + _cx: &mut ModelContext, + ) { + // suppress unused code warnings + let _ = &self.default_prettier.installed_plugins; + let _ = install_prettier_packages; + let _ = save_prettier_server_file; + } + + #[cfg(not(any(test, feature = "test-support")))] + pub fn install_default_prettier( + &mut self, + worktree: Option, + mut new_plugins: HashSet<&'static str>, + cx: &mut ModelContext, + ) { + let Some(node) = self.node.as_ref().cloned() else { + return; + }; + let fs = Arc::clone(&self.fs); + let locate_prettier_installation = match worktree.and_then(|worktree_id| { + self.worktree_for_id(worktree_id, cx) + .map(|worktree| worktree.read(cx).abs_path()) + }) { + Some(locate_from) => { + let installed_prettiers = self.prettier_instances.keys().cloned().collect(); + cx.background_executor().spawn(async move { + Prettier::locate_prettier_installation( + fs.as_ref(), + &installed_prettiers, + locate_from.as_ref(), + ) + .await + }) + } + None => Task::ready(Ok(ControlFlow::Continue(None))), + }; + new_plugins.retain(|plugin| !self.default_prettier.installed_plugins.contains(plugin)); + let mut installation_attempt = 0; + let previous_installation_task = match &mut self.default_prettier.prettier { + PrettierInstallation::NotInstalled { + installation_task, + attempts, + not_installed_plugins, + } => { + installation_attempt = *attempts; + if installation_attempt > prettier::FAIL_THRESHOLD { + *installation_task = None; + log::warn!( + "Default prettier installation had failed {installation_attempt} times, not attempting again", + ); + return; + } + new_plugins.extend(not_installed_plugins.iter()); + installation_task.clone() + } + PrettierInstallation::Installed { .. } => { + if new_plugins.is_empty() { + return; + } + None + } + }; + + let plugins_to_install = new_plugins.clone(); + let fs = Arc::clone(&self.fs); + let new_installation_task = cx + .spawn(|project, mut cx| async move { + match locate_prettier_installation + .await + .context("locate prettier installation") + .map_err(Arc::new)? + { + ControlFlow::Break(()) => return Ok(()), + ControlFlow::Continue(prettier_path) => { + if prettier_path.is_some() { + new_plugins.clear(); + } + let mut needs_install = false; + if let Some(previous_installation_task) = previous_installation_task { + if let Err(e) = previous_installation_task.await { + log::error!("Failed to install default prettier: {e:#}"); + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { attempts, not_installed_plugins, .. } = &mut project.default_prettier.prettier { + *attempts += 1; + new_plugins.extend(not_installed_plugins.iter()); + installation_attempt = *attempts; + needs_install = true; + }; + })?; + } + }; + if installation_attempt > prettier::FAIL_THRESHOLD { + project.update(&mut cx, |project, _| { + if let PrettierInstallation::NotInstalled { installation_task, .. } = &mut project.default_prettier.prettier { + *installation_task = None; + }; + })?; + log::warn!( + "Default prettier installation had failed {installation_attempt} times, not attempting again", + ); + return Ok(()); + } + project.update(&mut cx, |project, _| { + new_plugins.retain(|plugin| { + !project.default_prettier.installed_plugins.contains(plugin) + }); + if let PrettierInstallation::NotInstalled { not_installed_plugins, .. } = &mut project.default_prettier.prettier { + not_installed_plugins.retain(|plugin| { + !project.default_prettier.installed_plugins.contains(plugin) + }); + not_installed_plugins.extend(new_plugins.iter()); + } + needs_install |= !new_plugins.is_empty(); + })?; + if needs_install { + let installed_plugins = new_plugins.clone(); + cx.background_executor() + .spawn(async move { + save_prettier_server_file(fs.as_ref()).await?; + install_prettier_packages(new_plugins, node).await + }) + .await + .context("prettier & plugins install") + .map_err(Arc::new)?; + project.update(&mut cx, |project, _| { + project.default_prettier.prettier = + PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); + project.default_prettier + .installed_plugins + .extend(installed_plugins); + })?; + } + } + } + Ok(()) + }) + .shared(); + self.default_prettier.prettier = PrettierInstallation::NotInstalled { + attempts: installation_attempt, + installation_task: Some(new_installation_task), + not_installed_plugins: plugins_to_install, + }; + } +} diff --git a/crates/project2/src/project2.rs b/crates/project2/src/project2.rs index 856c280ac02e8971ae54e7cbf583267f0e0ff1ee..d2cc4fe406a0eb67de102e624ab9025338ad8689 100644 --- a/crates/project2/src/project2.rs +++ b/crates/project2/src/project2.rs @@ -1,5 +1,6 @@ mod ignore; mod lsp_command; +mod prettier_support; pub mod project_settings; pub mod search; pub mod terminals; @@ -20,7 +21,7 @@ use futures::{ mpsc::{self, UnboundedReceiver}, oneshot, }, - future::{self, try_join_all, Shared}, + future::{try_join_all, Shared}, stream::FuturesUnordered, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt, }; @@ -31,9 +32,7 @@ use gpui::{ }; use itertools::Itertools; use language::{ - language_settings::{ - language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings, - }, + language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind}, point_to_lsp, proto::{ deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version, @@ -54,7 +53,7 @@ use lsp_command::*; use node_runtime::NodeRuntime; use parking_lot::Mutex; use postage::watch; -use prettier::Prettier; +use prettier_support::{DefaultPrettier, PrettierInstance}; use project_settings::{LspSettings, ProjectSettings}; use rand::prelude::*; use search::SearchQuery; @@ -70,7 +69,7 @@ use std::{ hash::Hash, mem, num::NonZeroU32, - ops::{ControlFlow, Range}, + ops::Range, path::{self, Component, Path, PathBuf}, process::Stdio, str, @@ -83,11 +82,8 @@ use std::{ use terminals::Terminals; use text::Anchor; use util::{ - debug_panic, defer, - http::HttpClient, - merge_json_value_into, - paths::{DEFAULT_PRETTIER_DIR, LOCAL_SETTINGS_RELATIVE_PATH}, - post_inc, ResultExt, TryFutureExt as _, + debug_panic, defer, http::HttpClient, merge_json_value_into, + paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt, TryFutureExt as _, }; pub use fs::*; @@ -166,16 +162,9 @@ pub struct Project { copilot_log_subscription: Option, current_lsp_settings: HashMap, LspSettings>, node: Option>, - default_prettier: Option, + default_prettier: DefaultPrettier, prettiers_per_worktree: HashMap>>, - prettier_instances: HashMap, Arc>>>>, -} - -struct DefaultPrettier { - instance: Option, Arc>>>>, - installation_process: Option>>>>, - #[cfg(not(any(test, feature = "test-support")))] - installed_plugins: HashSet<&'static str>, + prettier_instances: HashMap, } struct DelayedDebounced { @@ -540,6 +529,14 @@ struct ProjectLspAdapterDelegate { http_client: Arc, } +// Currently, formatting operations are represented differently depending on +// whether they come from a language server or an external command. +enum FormatOperation { + Lsp(Vec<(Range, String)>), + External(Diff), + Prettier(Diff), +} + impl FormatTrigger { fn from_proto(value: i32) -> FormatTrigger { match value { @@ -689,7 +686,7 @@ impl Project { copilot_log_subscription: None, current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(), node: Some(node), - default_prettier: None, + default_prettier: DefaultPrettier::default(), prettiers_per_worktree: HashMap::default(), prettier_instances: HashMap::default(), } @@ -792,7 +789,7 @@ impl Project { copilot_log_subscription: None, current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(), node: None, - default_prettier: None, + default_prettier: DefaultPrettier::default(), prettiers_per_worktree: HashMap::default(), prettier_instances: HashMap::default(), }; @@ -965,8 +962,19 @@ impl Project { .detach(); } + let mut prettier_plugins_by_worktree = HashMap::default(); for (worktree, language, settings) in language_formatters_to_check { - self.install_default_formatters(worktree, &language, &settings, cx); + if let Some(plugins) = + prettier_support::prettier_plugins_for_language(&language, &settings) + { + prettier_plugins_by_worktree + .entry(worktree) + .or_insert_with(|| HashSet::default()) + .extend(plugins); + } + } + for (worktree, prettier_plugins) in prettier_plugins_by_worktree { + self.install_default_prettier(worktree, prettier_plugins, cx); } // Start all the newly-enabled language servers. @@ -2722,8 +2730,11 @@ impl Project { let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone(); let buffer_file = File::from_dyn(buffer_file.as_ref()); let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx)); - - self.install_default_formatters(worktree, &new_language, &settings, cx); + if let Some(prettier_plugins) = + prettier_support::prettier_plugins_for_language(&new_language, &settings) + { + self.install_default_prettier(worktree, prettier_plugins, cx); + }; if let Some(file) = buffer_file { let worktree = file.worktree.clone(); if let Some(tree) = worktree.read(cx).as_local() { @@ -4126,7 +4137,8 @@ impl Project { this.buffers_being_formatted .remove(&buffer.read(cx).remote_id()); } - }).ok(); + }) + .ok(); } }); @@ -4138,8 +4150,6 @@ impl Project { let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save; let ensure_final_newline = settings.ensure_final_newline_on_save; - let format_on_save = settings.format_on_save.clone(); - let formatter = settings.formatter.clone(); let tab_size = settings.tab_size; // First, format buffer's whitespace according to the settings. @@ -4164,18 +4174,10 @@ impl Project { buffer.end_transaction(cx) })?; - // Currently, formatting operations are represented differently depending on - // whether they come from a language server or an external command. - enum FormatOperation { - Lsp(Vec<(Range, String)>), - External(Diff), - Prettier(Diff), - } - // Apply language-specific formatting using either a language server // or external command. let mut format_operation = None; - match (formatter, format_on_save) { + match (&settings.formatter, &settings.format_on_save) { (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {} (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off) @@ -4220,46 +4222,11 @@ impl Project { } } (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => { - if let Some((prettier_path, prettier_task)) = project - .update(&mut cx, |project, cx| { - project.prettier_instance_for_buffer(buffer, cx) - })?.await { - match prettier_task.await - { - Ok(prettier) => { - let buffer_path = buffer.update(&mut cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - })?; - format_operation = Some(FormatOperation::Prettier( - prettier - .format(buffer, buffer_path, &mut cx) - .await - .context("formatting via prettier")?, - )); - } - Err(e) => { - project.update(&mut cx, |project, _| { - match &prettier_path { - Some(prettier_path) => { - project.prettier_instances.remove(prettier_path); - }, - None => { - if let Some(default_prettier) = project.default_prettier.as_mut() { - default_prettier.instance = None; - } - }, - } - })?; - match &prettier_path { - Some(prettier_path) => { - log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}"); - }, - None => { - log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}"); - }, - } - } - } + if let Some(new_operation) = + prettier_support::format_with_prettier(&project, buffer, &mut cx) + .await + { + format_operation = Some(new_operation); } else if let Some((language_server, buffer_abs_path)) = language_server.as_ref().zip(buffer_abs_path.as_ref()) { @@ -4277,48 +4244,13 @@ impl Project { )); } } - (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => { - if let Some((prettier_path, prettier_task)) = project - .update(&mut cx, |project, cx| { - project.prettier_instance_for_buffer(buffer, cx) - })?.await { - match prettier_task.await - { - Ok(prettier) => { - let buffer_path = buffer.update(&mut cx, |buffer, cx| { - File::from_dyn(buffer.file()).map(|file| file.abs_path(cx)) - })?; - format_operation = Some(FormatOperation::Prettier( - prettier - .format(buffer, buffer_path, &mut cx) - .await - .context("formatting via prettier")?, - )); - } - Err(e) => { - project.update(&mut cx, |project, _| { - match &prettier_path { - Some(prettier_path) => { - project.prettier_instances.remove(prettier_path); - }, - None => { - if let Some(default_prettier) = project.default_prettier.as_mut() { - default_prettier.instance = None; - } - }, - } - })?; - match &prettier_path { - Some(prettier_path) => { - log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}"); - }, - None => { - log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}"); - }, - } - } - } - } + (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => { + if let Some(new_operation) = + prettier_support::format_with_prettier(&project, buffer, &mut cx) + .await + { + format_operation = Some(new_operation); + } } }; @@ -6638,84 +6570,6 @@ impl Project { .detach(); } - fn update_prettier_settings( - &self, - worktree: &Model, - changes: &[(Arc, ProjectEntryId, PathChange)], - cx: &mut ModelContext<'_, Project>, - ) { - let prettier_config_files = Prettier::CONFIG_FILE_NAMES - .iter() - .map(Path::new) - .collect::>(); - - let prettier_config_file_changed = changes - .iter() - .filter(|(_, _, change)| !matches!(change, PathChange::Loaded)) - .filter(|(path, _, _)| { - !path - .components() - .any(|component| component.as_os_str().to_string_lossy() == "node_modules") - }) - .find(|(path, _, _)| prettier_config_files.contains(path.as_ref())); - let current_worktree_id = worktree.read(cx).id(); - if let Some((config_path, _, _)) = prettier_config_file_changed { - log::info!( - "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}" - ); - let prettiers_to_reload = self - .prettiers_per_worktree - .get(¤t_worktree_id) - .iter() - .flat_map(|prettier_paths| prettier_paths.iter()) - .flatten() - .filter_map(|prettier_path| { - Some(( - current_worktree_id, - Some(prettier_path.clone()), - self.prettier_instances.get(prettier_path)?.clone(), - )) - }) - .chain(self.default_prettier.iter().filter_map(|default_prettier| { - Some(( - current_worktree_id, - None, - default_prettier.instance.clone()?, - )) - })) - .collect::>(); - - cx.background_executor() - .spawn(async move { - for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| { - async move { - prettier_task.await? - .clear_cache() - .await - .with_context(|| { - match prettier_path { - Some(prettier_path) => format!( - "clearing prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update" - ), - None => format!( - "clearing default prettier cache for worktree {worktree_id:?} on prettier settings update" - ), - } - }) - .map_err(Arc::new) - } - })) - .await - { - if let Err(e) = task_result { - log::error!("Failed to clear cache for prettier: {e:#}"); - } - } - }) - .detach(); - } - } - pub fn set_active_path(&mut self, entry: Option, cx: &mut ModelContext) { let new_active_entry = entry.and_then(|project_path| { let worktree = self.worktree_for_id(project_path.worktree_id, cx)?; @@ -8579,486 +8433,6 @@ impl Project { Vec::new() } } - - fn prettier_instance_for_buffer( - &mut self, - buffer: &Model, - cx: &mut ModelContext, - ) -> Task< - Option<( - Option, - Shared, Arc>>>, - )>, - > { - let buffer = buffer.read(cx); - let buffer_file = buffer.file(); - let Some(buffer_language) = buffer.language() else { - return Task::ready(None); - }; - if buffer_language.prettier_parser_name().is_none() { - return Task::ready(None); - } - - if self.is_local() { - let Some(node) = self.node.as_ref().map(Arc::clone) else { - return Task::ready(None); - }; - match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx))) - { - Some((worktree_id, buffer_path)) => { - let fs = Arc::clone(&self.fs); - let installed_prettiers = self.prettier_instances.keys().cloned().collect(); - return cx.spawn(|project, mut cx| async move { - match cx - .background_executor() - .spawn(async move { - Prettier::locate_prettier_installation( - fs.as_ref(), - &installed_prettiers, - &buffer_path, - ) - .await - }) - .await - { - Ok(ControlFlow::Break(())) => { - return None; - } - Ok(ControlFlow::Continue(None)) => { - match project.update(&mut cx, |project, _| { - project - .prettiers_per_worktree - .entry(worktree_id) - .or_default() - .insert(None); - project.default_prettier.as_ref().and_then( - |default_prettier| default_prettier.instance.clone(), - ) - }) { - Ok(Some(old_task)) => Some((None, old_task)), - Ok(None) => { - match project.update(&mut cx, |_, cx| { - start_default_prettier(node, Some(worktree_id), cx) - }) { - Ok(new_default_prettier) => { - return Some((None, new_default_prettier.await)) - } - Err(e) => { - Some(( - None, - Task::ready(Err(Arc::new(e.context("project is gone during default prettier startup")))) - .shared(), - )) - } - } - } - Err(e) => Some((None, Task::ready(Err(Arc::new(e.context("project is gone during default prettier checks")))) - .shared())), - } - } - Ok(ControlFlow::Continue(Some(prettier_dir))) => { - match project.update(&mut cx, |project, _| { - project - .prettiers_per_worktree - .entry(worktree_id) - .or_default() - .insert(Some(prettier_dir.clone())); - project.prettier_instances.get(&prettier_dir).cloned() - }) { - Ok(Some(existing_prettier)) => { - log::debug!( - "Found already started prettier in {prettier_dir:?}" - ); - return Some((Some(prettier_dir), existing_prettier)); - } - Err(e) => { - return Some(( - Some(prettier_dir), - Task::ready(Err(Arc::new(e.context("project is gone during custom prettier checks")))) - .shared(), - )) - } - _ => {}, - } - - log::info!("Found prettier in {prettier_dir:?}, starting."); - let new_prettier_task = - match project.update(&mut cx, |project, cx| { - let new_prettier_task = start_prettier( - node, - prettier_dir.clone(), - Some(worktree_id), - cx, - ); - project.prettier_instances.insert( - prettier_dir.clone(), - new_prettier_task.clone(), - ); - new_prettier_task - }) { - Ok(task) => task, - Err(e) => return Some(( - Some(prettier_dir), - Task::ready(Err(Arc::new(e.context("project is gone during custom prettier startup")))) - .shared() - )), - }; - Some((Some(prettier_dir), new_prettier_task)) - } - Err(e) => { - return Some(( - None, - Task::ready(Err(Arc::new( - e.context("determining prettier path"), - ))) - .shared(), - )); - } - } - }); - } - None => { - let started_default_prettier = self - .default_prettier - .as_ref() - .and_then(|default_prettier| default_prettier.instance.clone()); - match started_default_prettier { - Some(old_task) => return Task::ready(Some((None, old_task))), - None => { - let new_task = start_default_prettier(node, None, cx); - return cx.spawn(|_, _| async move { Some((None, new_task.await)) }); - } - } - } - } - } else if self.remote_id().is_some() { - return Task::ready(None); - } else { - Task::ready(Some(( - None, - Task::ready(Err(Arc::new(anyhow!("project does not have a remote id")))).shared(), - ))) - } - } - - #[cfg(any(test, feature = "test-support"))] - fn install_default_formatters( - &mut self, - _: Option, - _: &Language, - _: &LanguageSettings, - _: &mut ModelContext, - ) { - } - - #[cfg(not(any(test, feature = "test-support")))] - fn install_default_formatters( - &mut self, - worktree: Option, - new_language: &Language, - language_settings: &LanguageSettings, - cx: &mut ModelContext, - ) { - match &language_settings.formatter { - Formatter::Prettier { .. } | Formatter::Auto => {} - Formatter::LanguageServer | Formatter::External { .. } => return, - }; - let Some(node) = self.node.as_ref().cloned() else { - return; - }; - - let mut prettier_plugins = None; - if new_language.prettier_parser_name().is_some() { - prettier_plugins - .get_or_insert_with(|| HashSet::<&'static str>::default()) - .extend( - new_language - .lsp_adapters() - .iter() - .flat_map(|adapter| adapter.prettier_plugins()), - ) - } - let Some(prettier_plugins) = prettier_plugins else { - return; - }; - - let fs = Arc::clone(&self.fs); - let locate_prettier_installation = match worktree.and_then(|worktree_id| { - self.worktree_for_id(worktree_id, cx) - .map(|worktree| worktree.read(cx).abs_path()) - }) { - Some(locate_from) => { - let installed_prettiers = self.prettier_instances.keys().cloned().collect(); - cx.background_executor().spawn(async move { - Prettier::locate_prettier_installation( - fs.as_ref(), - &installed_prettiers, - locate_from.as_ref(), - ) - .await - }) - } - None => Task::ready(Ok(ControlFlow::Break(()))), - }; - let mut plugins_to_install = prettier_plugins; - let previous_installation_process = - if let Some(default_prettier) = &mut self.default_prettier { - plugins_to_install - .retain(|plugin| !default_prettier.installed_plugins.contains(plugin)); - if plugins_to_install.is_empty() { - return; - } - default_prettier.installation_process.clone() - } else { - None - }; - - let fs = Arc::clone(&self.fs); - let default_prettier = self - .default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: None, - installed_plugins: HashSet::default(), - }); - default_prettier.installation_process = Some( - cx.spawn(|this, mut cx| async move { - match locate_prettier_installation - .await - .context("locate prettier installation") - .map_err(Arc::new)? - { - ControlFlow::Break(()) => return Ok(()), - ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()), - ControlFlow::Continue(None) => { - let mut needs_install = match previous_installation_process { - Some(previous_installation_process) => { - previous_installation_process.await.is_err() - } - None => true, - }; - this.update(&mut cx, |this, _| { - if let Some(default_prettier) = &mut this.default_prettier { - plugins_to_install.retain(|plugin| { - !default_prettier.installed_plugins.contains(plugin) - }); - needs_install |= !plugins_to_install.is_empty(); - } - })?; - if needs_install { - let installed_plugins = plugins_to_install.clone(); - cx.background_executor() - .spawn(async move { - install_default_prettier(plugins_to_install, node, fs).await - }) - .await - .context("prettier & plugins install") - .map_err(Arc::new)?; - this.update(&mut cx, |this, _| { - let default_prettier = - this.default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: Some( - Task::ready(Ok(())).shared(), - ), - installed_plugins: HashSet::default(), - }); - default_prettier.instance = None; - default_prettier.installed_plugins.extend(installed_plugins); - })?; - } - } - } - Ok(()) - }) - .shared(), - ); - } -} - -fn start_default_prettier( - node: Arc, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, -) -> Task, Arc>>>> { - cx.spawn(|project, mut cx| async move { - loop { - let default_prettier_installing = match project.update(&mut cx, |project, _| { - project - .default_prettier - .as_ref() - .and_then(|default_prettier| default_prettier.installation_process.clone()) - }) { - Ok(installation) => installation, - Err(e) => { - return Task::ready(Err(Arc::new( - e.context("project is gone during default prettier installation"), - ))) - .shared() - } - }; - match default_prettier_installing { - Some(installation_task) => { - if installation_task.await.is_ok() { - break; - } - } - None => break, - } - } - - match project.update(&mut cx, |project, cx| { - match project - .default_prettier - .as_mut() - .and_then(|default_prettier| default_prettier.instance.as_mut()) - { - Some(default_prettier) => default_prettier.clone(), - None => { - let new_default_prettier = - start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx); - project - .default_prettier - .get_or_insert_with(|| DefaultPrettier { - instance: None, - installation_process: None, - #[cfg(not(any(test, feature = "test-support")))] - installed_plugins: HashSet::default(), - }) - .instance = Some(new_default_prettier.clone()); - new_default_prettier - } - } - }) { - Ok(task) => task, - Err(e) => Task::ready(Err(Arc::new( - e.context("project is gone during default prettier startup"), - ))) - .shared(), - } - }) -} - -fn start_prettier( - node: Arc, - prettier_dir: PathBuf, - worktree_id: Option, - cx: &mut ModelContext<'_, Project>, -) -> Shared, Arc>>> { - cx.spawn(|project, mut cx| async move { - let new_server_id = project.update(&mut cx, |project, _| { - project.languages.next_language_server_id() - })?; - let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone()) - .await - .context("default prettier spawn") - .map(Arc::new) - .map_err(Arc::new)?; - register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx); - Ok(new_prettier) - }) - .shared() -} - -fn register_new_prettier( - project: &WeakModel, - prettier: &Prettier, - worktree_id: Option, - new_server_id: LanguageServerId, - cx: &mut AsyncAppContext, -) { - let prettier_dir = prettier.prettier_dir(); - let is_default = prettier.is_default(); - if is_default { - log::info!("Started default prettier in {prettier_dir:?}"); - } else { - log::info!("Started prettier in {prettier_dir:?}"); - } - if let Some(prettier_server) = prettier.server() { - project - .update(cx, |project, cx| { - let name = if is_default { - LanguageServerName(Arc::from("prettier (default)")) - } else { - let worktree_path = worktree_id - .and_then(|id| project.worktree_for_id(id, cx)) - .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path())); - let name = match worktree_path { - Some(worktree_path) => { - if prettier_dir == worktree_path.as_ref() { - let name = prettier_dir - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or_default(); - format!("prettier ({name})") - } else { - let dir_to_display = prettier_dir - .strip_prefix(worktree_path.as_ref()) - .ok() - .unwrap_or(prettier_dir); - format!("prettier ({})", dir_to_display.display()) - } - } - None => format!("prettier ({})", prettier_dir.display()), - }; - LanguageServerName(Arc::from(name)) - }; - project - .supplementary_language_servers - .insert(new_server_id, (name, Arc::clone(prettier_server))); - cx.emit(Event::LanguageServerAdded(new_server_id)); - }) - .ok(); - } -} - -#[cfg(not(any(test, feature = "test-support")))] -async fn install_default_prettier( - plugins_to_install: HashSet<&'static str>, - node: Arc, - fs: Arc, -) -> anyhow::Result<()> { - let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE); - // method creates parent directory if it doesn't exist - fs.save( - &prettier_wrapper_path, - &text::Rope::from(prettier::PRETTIER_SERVER_JS), - text::LineEnding::Unix, - ) - .await - .with_context(|| { - format!( - "writing {} file at {prettier_wrapper_path:?}", - prettier::PRETTIER_SERVER_FILE - ) - })?; - - let packages_to_versions = - future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map( - |package_name| async { - let returned_package_name = package_name.to_string(); - let latest_version = node - .npm_package_latest_version(package_name) - .await - .with_context(|| { - format!("fetching latest npm version for package {returned_package_name}") - })?; - anyhow::Ok((returned_package_name, latest_version)) - }, - )) - .await - .context("fetching latest npm versions")?; - - log::info!("Fetching default prettier and plugins: {packages_to_versions:?}"); - let borrowed_packages = packages_to_versions - .iter() - .map(|(package, version)| (package.as_str(), version.as_str())) - .collect::>(); - node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages) - .await - .context("fetching formatter packages")?; - anyhow::Ok(()) } fn subscribe_for_copilot_events( From 3e3b64bb1cf4a642d85618f8e058c8255f26ee90 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Wed, 29 Nov 2023 12:10:41 +0200 Subject: [PATCH 15/16] Fix the tests --- crates/project/src/prettier_support.rs | 9 +++++++-- crates/project2/src/prettier_support.rs | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 063c4abcc44301c30f77825eeeaebb3c15699a18..1b0faff3e96fe8d84bb7f906403aa28614ebcc08 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -601,13 +601,18 @@ impl Project { pub fn install_default_prettier( &mut self, _worktree: Option, - _plugins: HashSet<&'static str>, + plugins: HashSet<&'static str>, _cx: &mut ModelContext, ) { // suppress unused code warnings - let _ = &self.default_prettier.installed_plugins; let _ = install_prettier_packages; let _ = save_prettier_server_file; + + self.default_prettier.installed_plugins.extend(plugins); + self.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); } #[cfg(not(any(test, feature = "test-support")))] diff --git a/crates/project2/src/prettier_support.rs b/crates/project2/src/prettier_support.rs index 15f3028d8504700ef9085575be09182ab5b1dc11..e9ce8d9a064887a7ecf84addcaeed19b054d6244 100644 --- a/crates/project2/src/prettier_support.rs +++ b/crates/project2/src/prettier_support.rs @@ -615,13 +615,18 @@ impl Project { pub fn install_default_prettier( &mut self, _worktree: Option, - _plugins: HashSet<&'static str>, + plugins: HashSet<&'static str>, _cx: &mut ModelContext, ) { // suppress unused code warnings - let _ = &self.default_prettier.installed_plugins; let _ = install_prettier_packages; let _ = save_prettier_server_file; + + self.default_prettier.installed_plugins.extend(plugins); + self.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance { + attempt: 0, + prettier: None, + }); } #[cfg(not(any(test, feature = "test-support")))] From d92153218cee5c1869437863a29c55513ce72d49 Mon Sep 17 00:00:00 2001 From: Kirill Bulatov Date: Wed, 29 Nov 2023 13:44:19 +0200 Subject: [PATCH 16/16] Log prettier installation start & success --- crates/project/src/prettier_support.rs | 2 ++ crates/project2/src/prettier_support.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/project/src/prettier_support.rs b/crates/project/src/prettier_support.rs index 1b0faff3e96fe8d84bb7f906403aa28614ebcc08..c438f294b689de194583a409d712f48569e0adaa 100644 --- a/crates/project/src/prettier_support.rs +++ b/crates/project/src/prettier_support.rs @@ -625,6 +625,7 @@ impl Project { let Some(node) = self.node.as_ref().cloned() else { return; }; + log::info!("Initializing default prettier with plugins {new_plugins:?}"); let fs = Arc::clone(&self.fs); let locate_prettier_installation = match worktree.and_then(|worktree_id| { self.worktree_for_id(worktree_id, cx) @@ -731,6 +732,7 @@ impl Project { .await .context("prettier & plugins install") .map_err(Arc::new)?; + log::info!("Initialized prettier with plugins: {installed_plugins:?}"); project.update(&mut cx, |project, _| { project.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance { diff --git a/crates/project2/src/prettier_support.rs b/crates/project2/src/prettier_support.rs index e9ce8d9a064887a7ecf84addcaeed19b054d6244..c176c79a91f2e76ae84c6fcb25d95fd9b8568106 100644 --- a/crates/project2/src/prettier_support.rs +++ b/crates/project2/src/prettier_support.rs @@ -639,6 +639,7 @@ impl Project { let Some(node) = self.node.as_ref().cloned() else { return; }; + log::info!("Initializing default prettier with plugins {new_plugins:?}"); let fs = Arc::clone(&self.fs); let locate_prettier_installation = match worktree.and_then(|worktree_id| { self.worktree_for_id(worktree_id, cx) @@ -745,6 +746,7 @@ impl Project { .await .context("prettier & plugins install") .map_err(Arc::new)?; + log::info!("Initialized prettier with plugins: {installed_plugins:?}"); project.update(&mut cx, |project, _| { project.default_prettier.prettier = PrettierInstallation::Installed(PrettierInstance {