Skip to main content

dprint_core/plugins/
plugin_handler.rs

1use serde::Deserialize;
2use serde::Serialize;
3
4#[cfg(feature = "async_runtime")]
5use crate::async_runtime::FutureExt;
6#[cfg(feature = "async_runtime")]
7use crate::async_runtime::LocalBoxFuture;
8
9use crate::configuration::ConfigKeyMap;
10use crate::configuration::ConfigKeyValue;
11use crate::configuration::ConfigurationDiagnostic;
12use crate::configuration::GlobalConfiguration;
13#[cfg(feature = "wasm")]
14use crate::plugins::PluginInfo;
15#[cfg(feature = "process")]
16use crate::plugins::ProcessPluginInfo;
17
18use super::FileMatchingInfo;
19
20pub trait CancellationToken: Send + Sync + std::fmt::Debug {
21  fn is_cancelled(&self) -> bool;
22  #[cfg(feature = "async_runtime")]
23  fn wait_cancellation(&self) -> LocalBoxFuture<'static, ()>;
24}
25
26#[cfg(feature = "async_runtime")]
27impl CancellationToken for tokio_util::sync::CancellationToken {
28  fn is_cancelled(&self) -> bool {
29    self.is_cancelled()
30  }
31
32  fn wait_cancellation(&self) -> LocalBoxFuture<'static, ()> {
33    let token = self.clone();
34    async move { token.cancelled().await }.boxed_local()
35  }
36}
37
38/// A cancellation token that always says it's not cancelled.
39#[derive(Debug)]
40pub struct NullCancellationToken;
41
42impl CancellationToken for NullCancellationToken {
43  fn is_cancelled(&self) -> bool {
44    false
45  }
46
47  #[cfg(feature = "async_runtime")]
48  fn wait_cancellation(&self) -> LocalBoxFuture<'static, ()> {
49    // never resolves
50    Box::pin(std::future::pending())
51  }
52}
53
54pub type FormatRange = Option<std::ops::Range<usize>>;
55
56/// An error returned by formatting operations.
57///
58/// This can hold any error, allowing plugins to return their own error types,
59/// while still implementing [`std::error::Error`] so that consumers can convert
60/// it into their own error type.
61#[derive(Debug, thiserror::Error)]
62#[error(transparent)]
63pub struct FormatError(Box<dyn std::error::Error + Send + Sync + 'static>);
64
65impl FormatError {
66  /// Creates a new error from anything that can be turned into a boxed error
67  /// (for example a `String`, `&str`, or any [`std::error::Error`]).
68  pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
69    FormatError(error.into())
70  }
71
72  /// Attempts to downcast the underlying error to a concrete type
73  /// (ex. to check for a [`CriticalFormatError`]).
74  pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
75    self.0.downcast_ref::<E>()
76  }
77}
78
79/// Formats an error and its source chain into a single string,
80/// joining each level with `: ` (equivalent to formatting an
81/// `anyhow` error with the alternate `{:#}` specifier).
82pub fn error_to_string(err: &(dyn std::error::Error + 'static)) -> String {
83  // cap the depth so a pathological error with a cyclic `source()` chain
84  // can't make this loop forever
85  const MAX_DEPTH: usize = 100;
86  let mut result = err.to_string();
87  let mut source = err.source();
88  for _ in 0..MAX_DEPTH {
89    let Some(err) = source else { break };
90    result.push_str(": ");
91    result.push_str(&err.to_string());
92    source = err.source();
93  }
94  result
95}
96
97macro_rules! impl_format_error_from {
98  ($($t:ty),* $(,)?) => {
99    $(
100      impl From<$t> for FormatError {
101        fn from(error: $t) -> Self {
102          FormatError(error.into())
103        }
104      }
105    )*
106  };
107}
108
109impl_format_error_from!(
110  String,
111  &str,
112  Box<dyn std::error::Error + Send + Sync + 'static>,
113  std::io::Error,
114  std::str::Utf8Error,
115  std::string::FromUtf8Error,
116  CriticalFormatError,
117);
118
119#[cfg(test)]
120mod tests {
121  use super::FormatError;
122
123  #[test]
124  fn should_convert_utf8_error_to_format_error() {
125    let bytes = [u8::MAX];
126    let utf8_error = std::str::from_utf8(&bytes).unwrap_err();
127    let format_error: FormatError = utf8_error.into();
128
129    assert!(format_error.downcast_ref::<std::str::Utf8Error>().is_some());
130  }
131}
132
133#[cfg(feature = "serde_json")]
134impl_format_error_from!(serde_json::Error);
135
136#[cfg(feature = "async_runtime")]
137impl_format_error_from!(tokio::task::JoinError, tokio::sync::oneshot::error::RecvError);
138
139/// A formatting error where the plugin cannot recover.
140///
141/// Return one of these to signal to the dprint CLI that
142/// it should recreate the plugin.
143#[derive(Debug, thiserror::Error)]
144#[error(transparent)]
145pub struct CriticalFormatError(pub FormatError);
146
147#[derive(Debug, Serialize, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub struct CheckConfigUpdatesMessage {
150  /// dprint versions < 0.47 won't have this set
151  #[serde(default)]
152  pub old_version: Option<String>,
153  pub config: ConfigKeyMap,
154}
155
156#[cfg(feature = "process")]
157#[derive(Debug)]
158pub struct HostFormatRequest {
159  pub file_path: std::path::PathBuf,
160  pub file_bytes: Vec<u8>,
161  /// Range to format.
162  pub range: FormatRange,
163  pub override_config: ConfigKeyMap,
164  pub token: std::sync::Arc<dyn CancellationToken>,
165}
166
167#[cfg(feature = "wasm")]
168#[derive(Debug)]
169pub struct SyncHostFormatRequest<'a> {
170  pub file_path: &'a std::path::Path,
171  pub file_bytes: &'a [u8],
172  /// Range to format.
173  pub range: FormatRange,
174  pub override_config: &'a ConfigKeyMap,
175}
176
177/// `Ok(Some(text))` - Changes due to the format.
178/// `Ok(None)` - No changes.
179/// `Err(err)` - Error formatting. Use a `CriticalError` to signal that the plugin can't recover.
180pub type FormatResult = Result<Option<Vec<u8>>, FormatError>;
181
182#[derive(Debug, Clone, Serialize, Deserialize)]
183pub struct RawFormatConfig {
184  pub plugin: ConfigKeyMap,
185  pub global: GlobalConfiguration,
186}
187
188/// A unique configuration id used for formatting.
189#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
190pub struct FormatConfigId(u32);
191
192impl std::fmt::Display for FormatConfigId {
193  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194    write!(f, "${}", self.0)
195  }
196}
197
198impl FormatConfigId {
199  pub fn from_raw(raw: u32) -> FormatConfigId {
200    FormatConfigId(raw)
201  }
202
203  pub fn uninitialized() -> FormatConfigId {
204    FormatConfigId(0)
205  }
206
207  pub fn as_raw(&self) -> u32 {
208    self.0
209  }
210}
211
212#[cfg(feature = "process")]
213pub struct FormatRequest<TConfiguration> {
214  pub file_path: std::path::PathBuf,
215  pub file_bytes: Vec<u8>,
216  pub config_id: FormatConfigId,
217  pub config: std::sync::Arc<TConfiguration>,
218  /// Range to format.
219  pub range: FormatRange,
220  pub token: std::sync::Arc<dyn CancellationToken>,
221}
222
223#[cfg(feature = "wasm")]
224pub struct SyncFormatRequest<'a, TConfiguration> {
225  pub file_path: &'a std::path::Path,
226  pub file_bytes: Vec<u8>,
227  pub config_id: FormatConfigId,
228  pub config: &'a TConfiguration,
229  /// Range to format.
230  pub range: FormatRange,
231  pub token: &'a dyn CancellationToken,
232  /// The pool to create the arenas for formatting the file from (ex. `request.arena_pool.create_arena()`),
233  /// which reuses their memory between formats.
234  ///
235  /// The memory is kept for as long as the plugin is loaded, which costs little since
236  /// the memory of a Wasm plugin doesn't shrink when it's freed.
237  #[cfg(feature = "formatting")]
238  pub arena_pool: &'a crate::formatting::ArenaPool,
239}
240
241#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
242#[serde(untagged)]
243pub enum ConfigChangePathItem {
244  /// String property name.
245  String(String),
246  /// Number if an index in an array.
247  Number(usize),
248}
249
250impl From<String> for ConfigChangePathItem {
251  fn from(value: String) -> Self {
252    Self::String(value)
253  }
254}
255
256impl From<usize> for ConfigChangePathItem {
257  fn from(value: usize) -> Self {
258    Self::Number(value)
259  }
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264pub struct ConfigChange {
265  /// The path to make modifications at.
266  pub path: Vec<ConfigChangePathItem>,
267  #[serde(flatten)]
268  pub kind: ConfigChangeKind,
269}
270
271#[derive(Debug, Clone, Serialize, Deserialize)]
272#[serde(tag = "kind", content = "value")]
273pub enum ConfigChangeKind {
274  /// Adds an object property or array element.
275  Add(ConfigKeyValue),
276  /// Overwrites an existing value at the provided path.
277  Set(ConfigKeyValue),
278  /// Removes the value at the path.
279  Remove,
280}
281
282#[derive(Clone, Serialize)]
283#[serde(rename_all = "camelCase")]
284pub struct PluginResolveConfigurationResult<T>
285where
286  T: Clone + Serialize,
287{
288  /// Information about what files are matched for the provided configuration.
289  pub file_matching: FileMatchingInfo,
290
291  /// The configuration diagnostics.
292  pub diagnostics: Vec<ConfigurationDiagnostic>,
293
294  /// The configuration derived from the unresolved configuration
295  /// that can be used to format a file.
296  pub config: T,
297}
298
299/// Trait for implementing a process plugin.
300#[cfg(feature = "process")]
301#[crate::async_runtime::async_trait(?Send)]
302pub trait AsyncPluginHandler: 'static {
303  type Configuration: Serialize + Clone + Send + Sync;
304
305  /// Gets the plugin's plugin info.
306  fn plugin_info(&self) -> ProcessPluginInfo;
307  /// Gets the plugin's license text.
308  fn license_text(&self) -> String;
309  /// Resolves configuration based on the provided config map and global configuration.
310  async fn resolve_config(&self, config: ConfigKeyMap, global_config: GlobalConfiguration) -> PluginResolveConfigurationResult<Self::Configuration>;
311  /// Updates the config key map. This will be called after the CLI has upgraded the
312  /// plugin in `dprint config update`.
313  async fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError> {
314    Ok(Vec::new())
315  }
316  /// Formats the provided file text based on the provided file path and configuration.
317  async fn format(
318    &self,
319    request: FormatRequest<Self::Configuration>,
320    format_with_host: impl FnMut(HostFormatRequest) -> LocalBoxFuture<'static, FormatResult> + 'static,
321  ) -> FormatResult;
322}
323
324/// Trait for implementing a Wasm plugin.
325#[cfg(feature = "wasm")]
326pub trait SyncPluginHandler<TConfiguration: Clone + serde::Serialize> {
327  /// Resolves configuration based on the provided config map and global configuration.
328  fn resolve_config(&mut self, config: ConfigKeyMap, global_config: &GlobalConfiguration) -> PluginResolveConfigurationResult<TConfiguration>;
329  /// Gets the plugin's plugin info.
330  fn plugin_info(&mut self) -> PluginInfo;
331  /// Gets the plugin's license text.
332  fn license_text(&mut self) -> String;
333  /// Updates the config key map. This will be called after the CLI has upgraded the
334  /// plugin in `dprint config update`.
335  fn check_config_updates(&self, message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError>;
336  /// Formats the provided file text based on the provided file path and configuration.
337  fn format(&mut self, request: SyncFormatRequest<TConfiguration>, format_with_host: impl FnMut(SyncHostFormatRequest) -> FormatResult) -> FormatResult;
338}