#![allow(clippy::too_many_arguments)]
pub mod breaks;
pub mod columns;
pub mod config;
pub mod includes;
pub mod layout;
pub mod macros;
pub mod options;
pub mod output;
pub mod presets;
pub mod regions;
pub mod render;
pub mod roles;
pub mod rows;
pub mod space;
pub mod tokens;
pub mod trailing;
pub use config::{ConfigError, Style};
pub fn format(source: &str, style: &Style) -> String {
if regions::is_fully_disabled(style) {
return source.to_string();
}
finish(render::format(source, None, style), style)
}
fn finish(rendered: String, style: &Style) -> String {
let aligned_comments = trailing::align(&rendered, style);
macros::align_escaped_newlines(&aligned_comments, style)
}
pub fn format_file(path: &std::path::Path, source: &str, style: &Style) -> String {
if regions::is_fully_disabled(style) {
return source.to_string();
}
finish(
render::format(
source,
path.file_stem().and_then(|stem| stem.to_str()),
style,
),
style,
)
}
pub fn format_range(source: &str, style: &Style, first: usize, last: usize) -> String {
let formatted = format(source, style);
if formatted == source {
return formatted;
}
let original: Vec<&str> = source.split_inclusive('\n').collect();
let new: Vec<&str> = formatted.split_inclusive('\n').collect();
let mut out = String::with_capacity(source.len());
for (index, line) in original.iter().enumerate() {
if index >= first && index <= last {
out.push_str(new.get(index).copied().unwrap_or(line));
} else {
out.push_str(line);
}
}
out
}
pub fn format_with_config(source: &str, config: &str) -> Result<String, ConfigError> {
let style = config::parse(config, None)?;
Ok(format(source, &style))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_range_leaves_the_lines_outside_it_alone() {
let source = "int a = 1;\nint b = 2;\n";
let out = format_range(source, &Style::default_style(), 1, 1);
assert_eq!(
out.lines().next(),
Some("int a = 1;"),
"line 0 is not in the range"
);
assert_eq!(out.lines().nth(1), Some("int b = 2;"), "line 1 is");
}
#[test]
fn a_whole_file_range_is_the_whole_file() {
let source = "int a = 1;\n";
let whole = format(source, &Style::default_style());
assert_eq!(format_range(source, &Style::default_style(), 0, 1), whole);
}
}