use anyhow::{Context, Result, ensure};
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct FormatOptions {
pub line_width: usize,
pub indent_width: usize,
pub quote_style: QuoteStyle,
pub header_order: HeaderOrder,
pub import_order: ImportOrder,
pub empty_block_layout: EmptyBlockLayout,
pub empty_rpc_body: EmptyRpcBody,
pub empty_statements: EmptyStatements,
pub declaration_spacing: DeclarationSpacing,
pub comment_spacing: CommentSpacing,
pub rpc_signature_layout: RpcSignatureLayout,
pub field_options_layout: FieldOptionsLayout,
pub option_value_layout: OptionValueLayout,
pub blank_line_limit: usize,
pub ignore_directives: Vec<String>,
}
impl Default for FormatOptions {
fn default() -> Self {
Self {
line_width: 80,
indent_width: 2,
quote_style: QuoteStyle::Preserve,
header_order: HeaderOrder::Preserve,
import_order: ImportOrder::Preserve,
empty_block_layout: EmptyBlockLayout::Compact,
empty_rpc_body: EmptyRpcBody::Preserve,
empty_statements: EmptyStatements::Remove,
declaration_spacing: DeclarationSpacing::Preserve,
comment_spacing: CommentSpacing::Preserve,
rpc_signature_layout: RpcSignatureLayout::SingleLine,
field_options_layout: FieldOptionsLayout::SingleLine,
option_value_layout: OptionValueLayout::SingleLine,
blank_line_limit: 1,
ignore_directives: vec!["profmt-ignore".to_owned()],
}
}
}
impl FormatOptions {
pub fn from_toml(source: &str) -> Result<Self> {
let options: Self = toml::from_str(source).context("parse formatter configuration")?;
options.validate()?;
Ok(options)
}
pub fn validate(&self) -> Result<()> {
ensure!(self.line_width > 0, "line width must be greater than zero");
ensure!(self.indent_width > 0, "indent width must be greater than zero");
for directive in &self.ignore_directives {
ensure!(!directive.is_empty(), "ignore directives cannot be empty");
ensure!(
!directive.bytes().any(|byte| byte == b'\n' || byte == b'\r'),
"ignore directives cannot contain line breaks"
);
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum QuoteStyle {
Single,
Double,
#[default]
Preserve,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HeaderOrder {
#[default]
Preserve,
PackageFirst,
ImportsFirst,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ImportOrder {
#[default]
Preserve,
Sorted,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyBlockLayout {
#[default]
Compact,
Expanded,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyRpcBody {
#[default]
Preserve,
Semicolon,
Braces,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyStatements {
#[default]
Remove,
Preserve,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DeclarationSpacing {
#[default]
Preserve,
Separated,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommentSpacing {
#[default]
Preserve,
Normalized,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RpcSignatureLayout {
#[default]
SingleLine,
BreakBeforeReturns,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FieldOptionsLayout {
#[default]
SingleLine,
OnePerLine,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OptionValueLayout {
#[default]
SingleLine,
NewLine,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_follow_the_source_where_projects_differ() {
let options = FormatOptions::default();
assert_eq!(options.quote_style, QuoteStyle::Preserve);
assert_eq!(options.header_order, HeaderOrder::Preserve);
assert_eq!(options.import_order, ImportOrder::Preserve);
assert_eq!(options.empty_rpc_body, EmptyRpcBody::Preserve);
assert_eq!(options.declaration_spacing, DeclarationSpacing::Preserve);
assert_eq!(options.comment_spacing, CommentSpacing::Preserve);
assert_eq!(options.rpc_signature_layout, RpcSignatureLayout::SingleLine);
assert_eq!(options.field_options_layout, FieldOptionsLayout::SingleLine);
assert_eq!(options.option_value_layout, OptionValueLayout::SingleLine);
assert_eq!(options.ignore_directives, ["profmt-ignore"]);
}
#[test]
fn rejects_zero_widths() {
let options = FormatOptions {
line_width: 0,
..FormatOptions::default()
};
assert_eq!(
options.validate().expect_err("zero width should fail").to_string(),
"line width must be greater than zero"
);
}
#[test]
fn rejects_multiline_ignore_directives() {
let options = FormatOptions {
ignore_directives: vec!["profmt-ignore\nnext".to_owned()],
..FormatOptions::default()
};
assert_eq!(
options
.validate()
.expect_err("multiline directive should fail")
.to_string(),
"ignore directives cannot contain line breaks"
);
}
#[test]
fn parses_partial_configuration_over_defaults() {
let options = FormatOptions::from_toml(
r#"
line_width = 100
quote_style = "double"
header_order = "imports_first"
empty_rpc_body = "semicolon"
"#,
)
.expect("valid configuration");
assert_eq!(options.line_width, 100);
assert_eq!(options.indent_width, 2);
assert_eq!(options.quote_style, QuoteStyle::Double);
assert_eq!(options.header_order, HeaderOrder::ImportsFirst);
assert_eq!(options.empty_rpc_body, EmptyRpcBody::Semicolon);
}
#[test]
fn rejects_unknown_configuration_fields() {
let error = FormatOptions::from_toml("line_wdith = 100").expect_err("misspelled field should fail");
assert!(error.to_string().contains("parse formatter configuration"));
assert!(format!("{error:#}").contains("unknown field `line_wdith`"));
}
#[test]
fn rejects_unknown_enum_variants() {
let error =
FormatOptions::from_toml("empty_block_layout = \"tight\"").expect_err("unknown variant should fail");
assert!(format!("{error:#}").contains("unknown variant `tight`"));
}
}