use std::{collections::BTreeMap, fmt::Display};
use rumdl_lib::{
config::{Config, RuleConfig},
document_run::DocumentRun,
rule::Rule,
rules::{all_rules, filter_rules},
};
const MAX_FORMAT_PASSES: usize = 100;
pub(crate) struct Formatter {
config: Config,
rules: Vec<Box<dyn Rule>>,
}
impl Formatter {
#[must_use]
pub(crate) fn new() -> Self {
let mut config = Config::default();
config.global.extend_enable.push("MD060".to_owned());
config.rules.insert(
"MD060".to_owned(),
RuleConfig {
values: BTreeMap::from([(
"style".to_owned(),
toml::Value::String("aligned".to_owned()),
)]),
..RuleConfig::default()
},
);
let rules = filter_rules(&all_rules(&config), &config.global);
Self { config, rules }
}
pub(crate) fn format(&self, source: &str) -> Result<String, FormatError> {
let (formatted, result) = DocumentRun::new(source, &self.rules, &self.config)
.fix(MAX_FORMAT_PASSES)
.map_err(|message| FormatError::Failed(message.into_boxed_str()))?;
if !result.converged {
return Err(FormatError::DidNotConverge);
}
Ok(formatted)
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum FormatError {
#[error("rumdl failed to format Markdown: {0}")]
Failed(Box<str>),
#[error("rumdl did not converge after {MAX_FORMAT_PASSES} passes")]
DidNotConverge,
}
#[must_use]
pub(crate) fn code(text: impl Display) -> String {
format!("`{text}`")
}
#[must_use]
pub(crate) fn code_block(language: &str, content: impl Display) -> String {
format!("```{language}\n{content}\n```")
}
#[must_use]
pub(crate) fn link(text: impl Display, url: impl Display) -> String {
format!("[{text}]({url})")
}
#[must_use]
pub(crate) fn anchor_link(text: impl Display, anchor: impl Display) -> String {
format!("[{text}](#{anchor})")
}
#[derive(Debug, Default)]
pub(crate) struct List {
items: Vec<String>,
}
impl List {
#[must_use]
pub(crate) const fn new() -> Self {
Self { items: Vec::new() }
}
#[must_use]
pub(crate) fn items<I, T>(mut self, items: I) -> Self
where
I: IntoIterator<Item = T>,
T: Display,
{
self.items
.extend(items.into_iter().map(|item| item.to_string()));
self
}
#[must_use]
pub(crate) fn build(self) -> String {
self.items
.into_iter()
.map(|item| format!("- {item}"))
.collect::<Vec<_>>()
.join("\n")
}
}
#[derive(Debug, Default)]
pub(crate) struct Table {
headers: Vec<String>,
rows: Vec<Vec<String>>,
}
impl Table {
#[must_use]
pub(crate) const fn new() -> Self {
Self {
headers: Vec::new(),
rows: Vec::new(),
}
}
#[must_use]
pub(crate) fn headers<I, T>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = T>,
T: Display,
{
self.headers = headers.into_iter().map(|value| value.to_string()).collect();
self
}
#[must_use]
pub(crate) fn rows<I, R, T>(mut self, rows: I) -> Self
where
I: IntoIterator<Item = R>,
R: IntoIterator<Item = T>,
T: Display,
{
self.rows.extend(
rows.into_iter()
.map(|row| row.into_iter().map(|value| value.to_string()).collect()),
);
self
}
#[must_use]
pub(crate) fn build_markdown(self) -> String {
let mut lines = vec![render_table_row(&self.headers)];
lines.push(render_table_row(
&self.headers.iter().map(|_| "---").collect::<Vec<_>>(),
));
lines.extend(self.rows.iter().map(|row| render_table_row(row)));
lines.join("\n")
}
}
#[must_use]
pub(crate) fn render_table_row(cells: &[impl AsRef<str>]) -> String {
let cells = cells
.iter()
.map(|cell| cell.as_ref().replace('|', r"\|"))
.collect::<Vec<_>>();
format!("| {} |", cells.join(" | "))
}
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
#[gtest]
fn formats_blocks_and_collapses_excess_blank_lines() -> Result<()> {
let source = "intro\n## Heading\ntext\n\n\n```rust\nfn main() {}\n```\nafter";
let formatter = Formatter::new();
verify_eq!(
formatter.format(source).or_fail()?,
"intro\n\n## Heading\n\ntext\n\n```rust\nfn main() {}\n```\n\nafter\n"
)
}
#[gtest]
fn aligns_markdown_tables() -> Result<()> {
let source = "| Name | Description |\n| --- | --- |\n| a | Long value |\n";
let formatter = Formatter::new();
verify_eq!(
formatter.format(source).or_fail()?,
"| Name | Description |\n| ---- | ----------- |\n| a | Long value |\n"
)
}
}