profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
Documentation
use anyhow::{Context, Result, ensure};
use serde::Deserialize;

/// Formatting policy used by [`crate::format_with_options`].
///
/// Defaults are project-neutral: layouts that a project could reasonably
/// choose either way default to following the source (`preserve`).
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct FormatOptions {
    /// Maximum width used when deciding whether a document group fits. Only
    /// layouts that opt into wrapping consult it.
    pub line_width: usize,
    /// Spaces emitted for one indentation level.
    pub indent_width: usize,
    /// Preferred delimiter for string literals.
    pub quote_style: QuoteStyle,
    /// Order of the `syntax`, `package`, `import` and `option` statements
    /// that open a file.
    pub header_order: HeaderOrder,
    /// Order of the `import` statements within the file header.
    pub import_order: ImportOrder,
    /// Layout of a `message`, `enum`, `service`, `oneof`, `extend` or group
    /// body with no statements.
    pub empty_block_layout: EmptyBlockLayout,
    /// How an `rpc` with no options is terminated.
    pub empty_rpc_body: EmptyRpcBody,
    /// What happens to a `;` that terminates nothing.
    pub empty_statements: EmptyStatements,
    /// Whether block-bodied declarations are always set apart by blank lines.
    pub declaration_spacing: DeclarationSpacing,
    /// Spacing between `//` and the text of a line comment.
    pub comment_spacing: CommentSpacing,
    /// Whether an `rpc` signature may break when it does not fit.
    pub rpc_signature_layout: RpcSignatureLayout,
    /// Whether a field or enum value option list may break when it does not
    /// fit.
    pub field_options_layout: FieldOptionsLayout,
    /// Whether an `option` value may leave its statement's line when the
    /// statement does not fit.
    pub option_value_layout: OptionValueLayout,
    /// Maximum number of consecutive blank lines kept between statements.
    pub blank_line_limit: usize,
    /// Comment bodies that make the following statement print verbatim.
    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 {
    /// Parse a strict TOML configuration, filling omitted fields from the
    /// project-neutral defaults.
    pub fn from_toml(source: &str) -> Result<Self> {
        let options: Self = toml::from_str(source).context("parse formatter configuration")?;
        options.validate()?;
        Ok(options)
    }

    /// Validate options assembled programmatically.
    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(())
    }
}

/// Preferred delimiter for string literals.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum QuoteStyle {
    /// Prefer single quotes where changing delimiters is semantics-preserving.
    Single,
    /// Prefer double quotes where changing delimiters is semantics-preserving.
    Double,
    /// Keep the source delimiter.
    #[default]
    Preserve,
}

/// Order of the statements that open a file, up to the first `message`,
/// `enum`, `service` or `extend`. `syntax` always comes first and file
/// `option`s always come last; the variants choose what sits between.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HeaderOrder {
    /// Keep the source order.
    #[default]
    Preserve,
    /// `syntax`, `package`, imports, options: the Google style guide order.
    PackageFirst,
    /// `syntax`, imports, `package`, options.
    ImportsFirst,
}

/// Order of the `import` statements within the file header.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ImportOrder {
    /// Keep the source order.
    #[default]
    Preserve,
    /// One contiguous block sorted by path; each import keeps its comments.
    Sorted,
}

/// Layout of a block with no statements.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyBlockLayout {
    /// `message Empty {}`
    #[default]
    Compact,
    /// The closing brace on its own line.
    Expanded,
}

/// How an `rpc` with no options is terminated.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyRpcBody {
    /// Keep `;` or `{}` as written.
    #[default]
    Preserve,
    /// `rpc Get(GetRequest) returns (GetResponse);`
    Semicolon,
    /// `rpc Get(GetRequest) returns (GetResponse) {}`
    Braces,
}

/// What happens to a `;` that terminates nothing.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EmptyStatements {
    /// Drop it.
    #[default]
    Remove,
    /// Keep it directly after the statement it follows.
    Preserve,
}

/// Whether block-bodied declarations are always set apart by blank lines.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DeclarationSpacing {
    /// Keep the blank lines of the source, up to the configured limit.
    #[default]
    Preserve,
    /// A `message`, `enum`, `service`, `oneof`, `extend`, group or `rpc` with
    /// a body is preceded and followed by a blank line, except at the start
    /// or end of the block that contains it.
    Separated,
}

/// Spacing between `//` and the text of a line comment.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommentSpacing {
    /// Keep the comment as written.
    #[default]
    Preserve,
    /// `//text` becomes `// text`. Comments opening with a further `/` or
    /// `!`, and block comments, are kept as written.
    Normalized,
}

/// Whether an `rpc` signature may break when it does not fit.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RpcSignatureLayout {
    /// `rpc Name(Request) returns (Response)` stays on one line whatever
    /// its width.
    #[default]
    SingleLine,
    /// `returns (Response)` moves to an indented line when the signature
    /// does not fit.
    BreakBeforeReturns,
}

/// Whether a field or enum value option list may break when it does not fit.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FieldOptionsLayout {
    /// `[a = 1, b = 2]` stays on the field's line whatever its width.
    #[default]
    SingleLine,
    /// Each option moves to its own indented line, with the closing bracket
    /// back at the field's indentation, when the field does not fit.
    OnePerLine,
}

/// Whether an `option` value may leave its statement's line when the
/// statement does not fit.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OptionValueLayout {
    /// `option name = value;` stays on one line whatever its width.
    #[default]
    SingleLine,
    /// The value moves to an indented line when the statement does not fit.
    /// A text-format message literal never moves; it breaks in place.
    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`"));
    }
}