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
23 changes: 15 additions & 8 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 @@ -29,13 +29,13 @@ path = "tests/spec_test.rs"
harness = false

[dependencies]
anyhow = "1.0.64"
dprint-core = { version = "0.67.4", features = ["formatting"] }
dprint-core = { version = "0.68.2", features = ["formatting"] }
dprint-core-macros = "0.1.0"
pulldown-cmark = { version = "0.11.2", default-features = false }
regex = "1"
serde = { version = "1.0.144", features = ["derive"] }
serde_json = { version = "1.0", optional = true }
thiserror = "2.0"
unicode-width = "0.1.10"

[dev-dependencies]
Expand Down
40 changes: 27 additions & 13 deletions src/format_text.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use anyhow::bail;
use anyhow::Result;
use dprint_core::configuration::resolve_new_line_kind;
use dprint_core::formatting::*;

Expand All @@ -10,14 +8,31 @@ use super::generation::parse_cmark_ast;
use super::generation::strip_metadata_header;
use super::generation::Context;

/// Error that can occur while formatting markdown text.
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
/// The text could not be parsed as markdown.
#[error("{0}")]
Parse(String),
/// An error occurred while formatting the text of a code block.
#[error("{0}")]
CodeBlock(Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl From<std::string::FromUtf8Error> for FormatError {
fn from(err: std::string::FromUtf8Error) -> Self {
FormatError::CodeBlock(err.into())
}
}

/// Formats a file.
///
/// Returns the file text or an error when it failed to parse.
pub fn format_text(
file_text: &str,
config: &Configuration,
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>>,
) -> Result<Option<String>> {
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>, FormatError>,
) -> Result<Option<String>, FormatError> {
let result = format_text_inner(file_text, config, format_code_block_text)?;

match result {
Expand All @@ -30,8 +45,8 @@ pub fn format_text(
fn format_text_inner(
file_text: &str,
config: &Configuration,
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>>,
) -> Result<Option<String>> {
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>, FormatError>,
) -> Result<Option<String>, FormatError> {
let file_text = strip_bom(file_text);
let (source_file, markdown_text) = match parse_source_file(file_text, config)? {
ParseFileResult::IgnoreFile => return Ok(None),
Expand All @@ -54,7 +69,7 @@ fn format_text_inner(
pub fn trace_file(
file_text: &str,
config: &Configuration,
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>>,
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>, FormatError>,
) -> dprint_core::formatting::TracingResult {
let (source_file, markdown_text) = match parse_source_file(file_text, config).unwrap() {
ParseFileResult::IgnoreFile => panic!("Cannot trace file because it has an ignore file comment."),
Expand All @@ -80,22 +95,21 @@ enum ParseFileResult<'a> {
SourceFile((crate::generation::common::SourceFile, &'a str)),
}

fn parse_source_file<'a>(file_text: &'a str, config: &Configuration) -> Result<ParseFileResult<'a>> {
fn parse_source_file<'a>(file_text: &'a str, config: &Configuration) -> Result<ParseFileResult<'a>, FormatError> {
// check for the presence of a dprint-ignore-file comment before parsing
if file_has_ignore_file_directive(strip_metadata_header(file_text), &config.ignore_file_directive) {
return Ok(ParseFileResult::IgnoreFile);
}

match parse_cmark_ast(file_text) {
Ok(source_file) => Ok(ParseFileResult::SourceFile((source_file, file_text))),
Err(error) => bail!(
"{}",
Err(error) => Err(FormatError::Parse(
dprint_core::formatting::utils::string_utils::format_diagnostic(
Some((error.range.start, error.range.end)),
&error.message,
file_text
)
),
file_text,
),
)),
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/generation/gen_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use regex::Regex;
use super::utils::*;
use crate::configuration::Configuration;
use crate::format_text;
use anyhow::Result;
use crate::format_text::FormatError;

type FormatResult = Result<Option<String>>;
type FormatResult = Result<Option<String>, FormatError>;

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod format_text;
mod generation;

pub use format_text::format_text;
pub use format_text::FormatError;

#[cfg(feature = "tracing")]
pub use format_text::trace_file;
Expand Down
8 changes: 5 additions & 3 deletions src/wasm_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,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 as CoreFormatError;
use dprint_core::plugins::FormatRange;
use dprint_core::plugins::FormatResult;
use dprint_core::plugins::PluginInfo;
Expand Down Expand Up @@ -46,7 +47,7 @@ impl SyncPluginHandler<Configuration> for MarkdownPluginHandler {
}
}

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

Expand Down Expand Up @@ -91,13 +92,14 @@ impl SyncPluginHandler<Configuration> for MarkdownPluginHandler {
match result {
Ok(Some(bytes)) => Ok(Some(String::from_utf8(bytes)?)),
Ok(None) => Ok(None),
Err(err) => Err(err),
Err(err) => Err(super::FormatError::CodeBlock(err.into())),
}
} else {
Ok(None)
}
})
.map(|maybe_text| maybe_text.map(|t| t.into_bytes()));
.map(|maybe_text| maybe_text.map(|t| t.into_bytes()))
.map_err(CoreFormatError::new);

fn tag_to_extension<'a>(tag: &str, config: &'a Configuration) -> Option<&'a str> {
let tag_lower = tag.trim().to_lowercase();
Expand Down
1 change: 1 addition & 0 deletions tests/spec_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ fn main() {
Ok(None)
}
})
.map_err(Into::into)
})
},
Arc::new(move |_, _file_text, _spec_config| {
Expand Down