Skip to content

Commit 4a876cf

Browse files
authored
fix(BREAKING): drop anyhow (#804)
1 parent 16c86f0 commit 4a876cf

10 files changed

Lines changed: 74 additions & 39 deletions

File tree

Cargo.lock

Lines changed: 11 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ path = "tests/spec_test.rs"
3030
harness = false
3131

3232
[dependencies]
33-
anyhow = "1.0.64"
3433
capacity_builder = "0.5.0"
3534
deno_ast = { version = "0.53.0", features = ["view"] }
36-
dprint-core = { version = "0.67.4", features = ["formatting"] }
35+
dprint-core = { version = "0.68.2", features = ["formatting"] }
3736
dprint-core-macros = "0.1.0"
3837
percent-encoding = "2.3.1"
3938
rustc-hash = "2.1.1"
4039
serde = { version = "1.0.144", features = ["derive"] }
4140
serde_json = { version = "1.0", optional = true }
41+
thiserror = "2.0.18"
4242

4343
[dev-dependencies]
4444
dprint-development = "0.10.1"

src/error.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use deno_ast::ParseDiagnostic;
2+
use deno_ast::ParseDiagnosticsError;
3+
4+
/// An error that occurred while formatting a file.
5+
#[derive(Debug, thiserror::Error)]
6+
pub enum FormatError {
7+
/// The source text could not be parsed due to a fatal syntax error.
8+
#[error(transparent)]
9+
Parse(#[from] ParseDiagnostic),
10+
/// The source text had one or more syntax errors that prevent formatting.
11+
#[error(transparent)]
12+
SyntaxErrors(#[from] ParseDiagnosticsError),
13+
/// Any other error that occurred while formatting (ex. a generation diagnostic).
14+
#[error("{0}")]
15+
Other(String),
16+
}
17+
18+
impl From<String> for FormatError {
19+
fn from(message: String) -> Self {
20+
FormatError::Other(message)
21+
}
22+
}
23+
24+
impl From<&str> for FormatError {
25+
fn from(message: &str) -> Self {
26+
FormatError::Other(message.to_string())
27+
}
28+
}

src/format_text.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use std::path::Path;
22
use std::sync::Arc;
33

4-
use anyhow::Result;
54
use deno_ast::ParsedSource;
65
use dprint_core::configuration::resolve_new_line_kind;
76
use dprint_core::formatting::*;
87

98
use crate::swc::ensure_no_specific_syntax_errors;
9+
use crate::FormatError;
10+
use crate::Result;
1011

1112
use super::configuration::Configuration;
1213
use super::generation::generate;
@@ -93,7 +94,7 @@ pub fn format_parsed_source(source: &ParsedSource, config: &Configuration, exter
9394
}
9495

9596
fn inner_format(parsed_source: &ParsedSource, config: &Configuration, external_formatter: Option<&ExternalFormatter>) -> Result<Option<String>> {
96-
let mut maybe_err: Box<Option<anyhow::Error>> = Box::new(None);
97+
let mut maybe_err: Box<Option<FormatError>> = Box::new(None);
9798
let result = dprint_core::formatting::format(
9899
|| match generate(parsed_source, config, external_formatter) {
99100
Ok(print_items) => print_items,
@@ -161,7 +162,7 @@ mod test {
161162
config: &config,
162163
external_formatter: Some(&|lang, _text, _config| {
163164
assert!(matches!(lang, "html"));
164-
Err(anyhow::anyhow!("Syntax error from external formatter"))
165+
Err("Syntax error from external formatter".into())
165166
}),
166167
});
167168
assert!(result.is_err());

src/generation/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use crate::utils::Stack;
4646
/// cases the templates will be left as they are.
4747
///
4848
/// Only templates with no interpolation are supported.
49-
pub type ExternalFormatter = dyn Fn(&str, String, &Configuration) -> anyhow::Result<Option<String>>;
49+
pub type ExternalFormatter = dyn Fn(&str, String, &Configuration) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync + 'static>>;
5050

5151
pub(crate) struct GenerateDiagnostic {
5252
pub message: String,

src/generation/generate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use super::*;
2525
use crate::configuration::*;
2626
use crate::utils;
2727

28-
pub fn generate(parsed_source: &ParsedSource, config: &Configuration, external_formatter: Option<&ExternalFormatter>) -> anyhow::Result<PrintItems> {
28+
pub fn generate(parsed_source: &ParsedSource, config: &Configuration, external_formatter: Option<&ExternalFormatter>) -> crate::Result<PrintItems> {
2929
// eprintln!("Leading: {:?}", parsed_source.comments().leading_map());
3030
// eprintln!("Trailing: {:?}", parsed_source.comments().trailing_map());
3131

@@ -50,7 +50,7 @@ pub fn generate(parsed_source: &ParsedSource, config: &Configuration, external_f
5050
context.assert_end_of_file_state();
5151

5252
if let Some(diagnostic) = context.diagnostics.pop() {
53-
return Err(anyhow::anyhow!(diagnostic.message));
53+
return Err(diagnostic.message.into());
5454
}
5555

5656
if config.file_indent_level > 0 {

src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,17 @@
1111
#![deny(clippy::print_stdout)]
1212

1313
pub mod configuration;
14+
mod error;
1415
mod format_text;
1516
mod generation;
1617
mod swc;
1718
mod utils;
1819

20+
pub use error::FormatError;
21+
22+
/// Result type used throughout the crate.
23+
pub(crate) type Result<T> = std::result::Result<T, FormatError>;
24+
1925
pub use format_text::format_parsed_source;
2026
pub use format_text::format_text;
2127
pub use format_text::ExternalFormatter;

src/swc.rs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
use anyhow::anyhow;
2-
use anyhow::bail;
3-
use anyhow::Result;
41
use deno_ast::swc::parser::error::SyntaxError;
52
use deno_ast::swc::parser::Syntax;
63
use deno_ast::ModuleSpecifier;
74
use deno_ast::ParsedSource;
85
use std::path::Path;
96
use std::sync::Arc;
107

8+
use crate::Result;
9+
1110
pub fn parse_swc_ast(file_path: &Path, file_extension: Option<&str>, file_text: Arc<str>) -> Result<ParsedSource> {
1211
match parse_inner(file_path, file_extension, file_text.clone()) {
1312
Ok(result) => Ok(result),
@@ -53,7 +52,7 @@ fn parse_inner_no_diagnostic_check(file_path: &Path, file_extension: Option<&str
5352
scope_analysis: false,
5453
text,
5554
})
56-
.map_err(|diagnostic| anyhow!("{:#}", &diagnostic))
55+
.map_err(Into::into)
5756
}
5857

5958
fn path_to_specifier(path: &Path) -> Result<ModuleSpecifier> {
@@ -62,10 +61,10 @@ fn path_to_specifier(path: &Path) -> Result<ModuleSpecifier> {
6261
} else if let Some(file_name) = path.file_name() {
6362
match ModuleSpecifier::parse(&format!("file:///{}", file_name.to_string_lossy())) {
6463
Ok(specifier) => Ok(specifier),
65-
Err(err) => bail!("could not convert path to specifier: '{}', error: {:#}", path.display(), err),
64+
Err(err) => Err(format!("could not convert path to specifier: '{}', error: {:#}", path.display(), err).into()),
6665
}
6766
} else {
68-
bail!("could not convert path to specifier: '{}'", path.display())
67+
Err(format!("could not convert path to specifier: '{}'", path.display()).into())
6968
}
7069
}
7170

@@ -140,19 +139,13 @@ pub fn ensure_no_specific_syntax_errors(parsed_source: &ParsedSource) -> Result<
140139
SyntaxError::TS1185
141140
)
142141
})
142+
.cloned()
143143
.collect::<Vec<_>>();
144144

145145
if diagnostics.is_empty() {
146146
Ok(())
147147
} else {
148-
let mut final_message = String::new();
149-
for diagnostic in diagnostics {
150-
if !final_message.is_empty() {
151-
final_message.push_str("\n\n");
152-
}
153-
final_message.push_str(&format!("{diagnostic}"));
154-
}
155-
bail!("{}", final_message)
148+
Err(deno_ast::ParseDiagnosticsError(diagnostics).into())
156149
}
157150
}
158151

src/wasm_plugin.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use dprint_core::generate_plugin_code;
44
use dprint_core::plugins::CheckConfigUpdatesMessage;
55
use dprint_core::plugins::ConfigChange;
66
use dprint_core::plugins::FileMatchingInfo;
7+
use dprint_core::plugins::FormatError;
78
use dprint_core::plugins::FormatResult;
89
use dprint_core::plugins::PluginInfo;
910
use dprint_core::plugins::PluginResolveConfigurationResult;
@@ -38,7 +39,7 @@ impl SyncPluginHandler<Configuration> for TypeScriptPluginHandler {
3839
}
3940
}
4041

41-
fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, anyhow::Error> {
42+
fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError> {
4243
Ok(Vec::new())
4344
}
4445

@@ -60,15 +61,16 @@ impl SyncPluginHandler<Configuration> for TypeScriptPluginHandler {
6061

6162
fn format(&mut self, request: SyncFormatRequest<Configuration>, _format_with_host: impl FnMut(SyncHostFormatRequest) -> FormatResult) -> FormatResult {
6263
let file_text = String::from_utf8(request.file_bytes)?;
63-
super::format_text(super::FormatTextOptions {
64+
let maybe_text = super::format_text(super::FormatTextOptions {
6465
path: request.file_path,
6566
extension: None,
6667
text: file_text,
6768
config: request.config,
6869
// todo: support this in Wasm
6970
external_formatter: None,
7071
})
71-
.map(|maybe_text| maybe_text.map(|t| t.into_bytes()))
72+
.map_err(FormatError::new)?;
73+
Ok(maybe_text.map(|t| t.into_bytes()))
7274
}
7375
}
7476

tests/spec_test.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use std::path::{Path, PathBuf};
22
use std::sync::Arc;
33

4-
use anyhow::Result;
54
use dprint_core::configuration::*;
65
use dprint_development::*;
76
use dprint_plugin_typescript::configuration::*;
87
use dprint_plugin_typescript::*;
98

9+
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;
10+
1011
fn external_formatter(lang: &str, text: String, config: &Configuration) -> Result<Option<String>> {
1112
match lang {
1213
"css" => format_embedded_css(&text, config),
@@ -69,7 +70,7 @@ fn format_sql(text: &str, config: &Configuration) -> Result<Option<String>> {
6970
let options = dprint_plugin_sql::configuration::ConfigurationBuilder::new()
7071
.indent_width(config.indent_width)
7172
.build();
72-
dprint_plugin_sql::format_text(Path::new("_path.sql"), text, &options)
73+
dprint_plugin_sql::format_text(Path::new("_path.sql"), text, &options).map_err(Into::into)
7374
}
7475

7576
fn main() {
@@ -94,13 +95,17 @@ fn main() {
9495
let config_result = resolve_config(spec_config, &global_config);
9596
ensure_no_diagnostics(&config_result.diagnostics);
9697

97-
format_text(FormatTextOptions {
98+
// dprint-development's callback wants an `anyhow::Result`, so bridge the
99+
// crate's boxed error through `std::io::Error` to avoid depending on anyhow
100+
let result = format_text(FormatTextOptions {
98101
path: file_name,
99102
extension: None,
100103
text: file_text.into(),
101104
config: &config_result.config,
102105
external_formatter: Some(&external_formatter),
103106
})
107+
.map_err(std::io::Error::other)?;
108+
Ok(result)
104109
})
105110
},
106111
Arc::new(move |_file_name, _file_text, _spec_config| {

0 commit comments

Comments
 (0)