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#[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 Box::pin(std::future::pending())
51 }
52}
53
54pub type FormatRange = Option<std::ops::Range<usize>>;
55
56#[derive(Debug, thiserror::Error)]
62#[error(transparent)]
63pub struct FormatError(Box<dyn std::error::Error + Send + Sync + 'static>);
64
65impl FormatError {
66 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
69 FormatError(error.into())
70 }
71
72 pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
75 self.0.downcast_ref::<E>()
76 }
77}
78
79pub fn error_to_string(err: &(dyn std::error::Error + 'static)) -> String {
83 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#[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 #[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 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 pub range: FormatRange,
174 pub override_config: &'a ConfigKeyMap,
175}
176
177pub 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#[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 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 pub range: FormatRange,
231 pub token: &'a dyn CancellationToken,
232 #[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(String),
246 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 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 Add(ConfigKeyValue),
276 Set(ConfigKeyValue),
278 Remove,
280}
281
282#[derive(Clone, Serialize)]
283#[serde(rename_all = "camelCase")]
284pub struct PluginResolveConfigurationResult<T>
285where
286 T: Clone + Serialize,
287{
288 pub file_matching: FileMatchingInfo,
290
291 pub diagnostics: Vec<ConfigurationDiagnostic>,
293
294 pub config: T,
297}
298
299#[cfg(feature = "process")]
301#[crate::async_runtime::async_trait(?Send)]
302pub trait AsyncPluginHandler: 'static {
303 type Configuration: Serialize + Clone + Send + Sync;
304
305 fn plugin_info(&self) -> ProcessPluginInfo;
307 fn license_text(&self) -> String;
309 async fn resolve_config(&self, config: ConfigKeyMap, global_config: GlobalConfiguration) -> PluginResolveConfigurationResult<Self::Configuration>;
311 async fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError> {
314 Ok(Vec::new())
315 }
316 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#[cfg(feature = "wasm")]
326pub trait SyncPluginHandler<TConfiguration: Clone + serde::Serialize> {
327 fn resolve_config(&mut self, config: ConfigKeyMap, global_config: &GlobalConfiguration) -> PluginResolveConfigurationResult<TConfiguration>;
329 fn plugin_info(&mut self) -> PluginInfo;
331 fn license_text(&mut self) -> String;
333 fn check_config_updates(&self, message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError>;
336 fn format(&mut self, request: SyncFormatRequest<TConfiguration>, format_with_host: impl FnMut(SyncHostFormatRequest) -> FormatResult) -> FormatResult;
338}