Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ path = "tests/spec_test.rs"
harness = false

[dependencies]
anyhow = "1.0.64"
capacity_builder = "0.5.0"
deno_ast = { version = "0.53.0", features = ["view"] }
dprint-core = { version = "0.67.4", features = ["formatting"] }
dprint-core = { version = "0.68.2", features = ["formatting"] }
dprint-core-macros = "0.1.0"
percent-encoding = "2.3.1"
rustc-hash = "2.1.1"
serde = { version = "1.0.144", features = ["derive"] }
serde_json = { version = "1.0", optional = true }
thiserror = "2.0.18"

[dev-dependencies]
dprint-development = "0.10.1"
Expand Down
28 changes: 28 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use deno_ast::ParseDiagnostic;
use deno_ast::ParseDiagnosticsError;

/// An error that occurred while formatting a file.
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
/// The source text could not be parsed due to a fatal syntax error.
#[error(transparent)]
Parse(#[from] ParseDiagnostic),
/// The source text had one or more syntax errors that prevent formatting.
#[error(transparent)]
SyntaxErrors(#[from] ParseDiagnosticsError),
/// Any other error that occurred while formatting (ex. a generation diagnostic).
#[error("{0}")]
Other(String),
}

impl From<String> for FormatError {
fn from(message: String) -> Self {
FormatError::Other(message)
}
}

impl From<&str> for FormatError {
fn from(message: &str) -> Self {
FormatError::Other(message.to_string())
}
}
7 changes: 4 additions & 3 deletions src/format_text.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::path::Path;
use std::sync::Arc;

use anyhow::Result;
use deno_ast::ParsedSource;
use dprint_core::configuration::resolve_new_line_kind;
use dprint_core::formatting::*;

use crate::swc::ensure_no_specific_syntax_errors;
use crate::FormatError;
use crate::Result;

use super::configuration::Configuration;
use super::generation::generate;
Expand Down Expand Up @@ -93,7 +94,7 @@ pub fn format_parsed_source(source: &ParsedSource, config: &Configuration, exter
}

fn inner_format(parsed_source: &ParsedSource, config: &Configuration, external_formatter: Option<&ExternalFormatter>) -> Result<Option<String>> {
let mut maybe_err: Box<Option<anyhow::Error>> = Box::new(None);
let mut maybe_err: Box<Option<FormatError>> = Box::new(None);
let result = dprint_core::formatting::format(
|| match generate(parsed_source, config, external_formatter) {
Ok(print_items) => print_items,
Expand Down Expand Up @@ -161,7 +162,7 @@ mod test {
config: &config,
external_formatter: Some(&|lang, _text, _config| {
assert!(matches!(lang, "html"));
Err(anyhow::anyhow!("Syntax error from external formatter"))
Err("Syntax error from external formatter".into())
}),
});
assert!(result.is_err());
Expand Down
2 changes: 1 addition & 1 deletion src/generation/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use crate::utils::Stack;
/// cases the templates will be left as they are.
///
/// Only templates with no interpolation are supported.
pub type ExternalFormatter = dyn Fn(&str, String, &Configuration) -> anyhow::Result<Option<String>>;
pub type ExternalFormatter = dyn Fn(&str, String, &Configuration) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync + 'static>>;

pub(crate) struct GenerateDiagnostic {
pub message: String,
Expand Down
4 changes: 2 additions & 2 deletions src/generation/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use super::*;
use crate::configuration::*;
use crate::utils;

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

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

if let Some(diagnostic) = context.diagnostics.pop() {
return Err(anyhow::anyhow!(diagnostic.message));
return Err(diagnostic.message.into());
}

if config.file_indent_level > 0 {
Expand Down
6 changes: 6 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@
#![deny(clippy::print_stdout)]

pub mod configuration;
mod error;
mod format_text;
mod generation;
mod swc;
mod utils;

pub use error::FormatError;

/// Result type used throughout the crate.
pub(crate) type Result<T> = std::result::Result<T, FormatError>;

pub use format_text::format_parsed_source;
pub use format_text::format_text;
pub use format_text::ExternalFormatter;
Expand Down
21 changes: 7 additions & 14 deletions src/swc.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use anyhow::anyhow;
use anyhow::bail;
use anyhow::Result;
use deno_ast::swc::parser::error::SyntaxError;
use deno_ast::swc::parser::Syntax;
use deno_ast::ModuleSpecifier;
use deno_ast::ParsedSource;
use std::path::Path;
use std::sync::Arc;

use crate::Result;

pub fn parse_swc_ast(file_path: &Path, file_extension: Option<&str>, file_text: Arc<str>) -> Result<ParsedSource> {
match parse_inner(file_path, file_extension, file_text.clone()) {
Ok(result) => Ok(result),
Expand Down Expand Up @@ -53,7 +52,7 @@ fn parse_inner_no_diagnostic_check(file_path: &Path, file_extension: Option<&str
scope_analysis: false,
text,
})
.map_err(|diagnostic| anyhow!("{:#}", &diagnostic))
.map_err(Into::into)
}

fn path_to_specifier(path: &Path) -> Result<ModuleSpecifier> {
Expand All @@ -62,10 +61,10 @@ fn path_to_specifier(path: &Path) -> Result<ModuleSpecifier> {
} else if let Some(file_name) = path.file_name() {
match ModuleSpecifier::parse(&format!("file:///{}", file_name.to_string_lossy())) {
Ok(specifier) => Ok(specifier),
Err(err) => bail!("could not convert path to specifier: '{}', error: {:#}", path.display(), err),
Err(err) => Err(format!("could not convert path to specifier: '{}', error: {:#}", path.display(), err).into()),
}
} else {
bail!("could not convert path to specifier: '{}'", path.display())
Err(format!("could not convert path to specifier: '{}'", path.display()).into())
}
}

Expand Down Expand Up @@ -140,19 +139,13 @@ pub fn ensure_no_specific_syntax_errors(parsed_source: &ParsedSource) -> Result<
SyntaxError::TS1185
)
})
.cloned()
.collect::<Vec<_>>();

if diagnostics.is_empty() {
Ok(())
} else {
let mut final_message = String::new();
for diagnostic in diagnostics {
if !final_message.is_empty() {
final_message.push_str("\n\n");
}
final_message.push_str(&format!("{diagnostic}"));
}
bail!("{}", final_message)
Err(deno_ast::ParseDiagnosticsError(diagnostics).into())
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/wasm_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use dprint_core::generate_plugin_code;
use dprint_core::plugins::CheckConfigUpdatesMessage;
use dprint_core::plugins::ConfigChange;
use dprint_core::plugins::FileMatchingInfo;
use dprint_core::plugins::FormatError;
use dprint_core::plugins::FormatResult;
use dprint_core::plugins::PluginInfo;
use dprint_core::plugins::PluginResolveConfigurationResult;
Expand Down Expand Up @@ -38,7 +39,7 @@ impl SyncPluginHandler<Configuration> for TypeScriptPluginHandler {
}
}

fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, anyhow::Error> {
fn check_config_updates(&self, _message: CheckConfigUpdatesMessage) -> Result<Vec<ConfigChange>, FormatError> {
Ok(Vec::new())
}

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

fn format(&mut self, request: SyncFormatRequest<Configuration>, _format_with_host: impl FnMut(SyncHostFormatRequest) -> FormatResult) -> FormatResult {
let file_text = String::from_utf8(request.file_bytes)?;
super::format_text(super::FormatTextOptions {
let maybe_text = super::format_text(super::FormatTextOptions {
path: request.file_path,
extension: None,
text: file_text,
config: request.config,
// todo: support this in Wasm
external_formatter: None,
})
.map(|maybe_text| maybe_text.map(|t| t.into_bytes()))
.map_err(FormatError::new)?;
Ok(maybe_text.map(|t| t.into_bytes()))
}
}

Expand Down
11 changes: 8 additions & 3 deletions tests/spec_test.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::Result;
use dprint_core::configuration::*;
use dprint_development::*;
use dprint_plugin_typescript::configuration::*;
use dprint_plugin_typescript::*;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;

fn external_formatter(lang: &str, text: String, config: &Configuration) -> Result<Option<String>> {
match lang {
"css" => format_embedded_css(&text, config),
Expand Down Expand Up @@ -69,7 +70,7 @@ fn format_sql(text: &str, config: &Configuration) -> Result<Option<String>> {
let options = dprint_plugin_sql::configuration::ConfigurationBuilder::new()
.indent_width(config.indent_width)
.build();
dprint_plugin_sql::format_text(Path::new("_path.sql"), text, &options)
dprint_plugin_sql::format_text(Path::new("_path.sql"), text, &options).map_err(Into::into)
}

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

format_text(FormatTextOptions {
// dprint-development's callback wants an `anyhow::Result`, so bridge the
// crate's boxed error through `std::io::Error` to avoid depending on anyhow
let result = format_text(FormatTextOptions {
path: file_name,
extension: None,
text: file_text.into(),
config: &config_result.config,
external_formatter: Some(&external_formatter),
})
.map_err(std::io::Error::other)?;
Ok(result)
})
},
Arc::new(move |_file_name, _file_text, _spec_config| {
Expand Down