profmt 0.1.0

A fast, deterministic, configurable Protocol Buffers formatter built on tree-sitter
Documentation
//! Each option variant the compatibility profile does not select, checked
//! against a small input.

use profmt::{
    CommentSpacing, DeclarationSpacing, EmptyBlockLayout, EmptyRpcBody, EmptyStatements, FieldOptionsLayout,
    FormatOptions, HeaderOrder, ImportOrder, OptionValueLayout, QuoteStyle, RpcSignatureLayout,
};

fn format(source: &str, options: FormatOptions) -> String {
    profmt::format_with_options(source.as_bytes(), &options).expect("format")
}

fn with(source: &str, adjust: impl FnOnce(&mut FormatOptions)) -> String {
    let mut options = FormatOptions::default();
    adjust(&mut options);
    format(source, options)
}

#[test]
fn defaults_follow_the_source() {
    let source = "syntax = \"proto2\";\nimport 'b.proto';\nimport 'a.proto';\npackage p;\nmessage A {\n\n\n  optional int32 a = 1;\n  message B {}\n};\nservice S {\n  rpc F(A) returns (B) {}\n  rpc G(A) returns (B);\n}\n";
    assert_eq!(
        format(source, FormatOptions::default()),
        "syntax = \"proto2\";\nimport 'b.proto';\nimport 'a.proto';\npackage p;\nmessage A {\n  optional int32 a = 1;\n  message B {}\n}\nservice S {\n  rpc F(A) returns (B) {}\n  rpc G(A) returns (B);\n}\n"
    );
}

#[test]
fn quote_style_switches_delimiters_only_when_lossless() {
    let source = "import 'a.proto';\nimport \"it's\";\nmessage A {\n  optional string s = 1 [default = 'x\\'y'];\n  reserved 'r';\n}\n";
    assert_eq!(
        with(source, |o| o.quote_style = QuoteStyle::Double),
        "import \"a.proto\";\nimport \"it's\";\nmessage A {\n  optional string s = 1 [default = 'x\\'y'];\n  reserved \"r\";\n}\n"
    );
    assert_eq!(
        with("import \"a.proto\";\n", |o| o.quote_style = QuoteStyle::Single),
        "import 'a.proto';\n"
    );
}

#[test]
fn header_order_package_first_follows_the_google_style_guide() {
    let source =
        "// file\nsyntax = \"proto3\";\noption a = 1;\nimport \"x.proto\";\n// pkg\npackage p;\nmessage A {}\n";
    assert_eq!(
        with(source, |o| o.header_order = HeaderOrder::PackageFirst),
        "// file\nsyntax = \"proto3\";\n\n// pkg\npackage p;\n\nimport \"x.proto\";\n\noption a = 1;\n\nmessage A {}\n"
    );
}

#[test]
fn header_order_leaves_statements_after_the_first_definition_alone() {
    let source = "package p;\nmessage A {}\nimport \"late.proto\";\noption a = 1;\n";
    assert_eq!(
        with(source, |o| o.header_order = HeaderOrder::ImportsFirst),
        "package p;\n\nmessage A {}\nimport \"late.proto\";\noption a = 1;\n"
    );
}

#[test]
fn sorted_imports_keep_their_comments_and_drop_gaps() {
    let source = "import \"b.proto\";\n\n// why a\nimport \"a.proto\"; // trailing\nimport public \"c.proto\";\n";
    assert_eq!(
        with(source, |o| o.import_order = ImportOrder::Sorted),
        "// why a\nimport \"a.proto\"; // trailing\nimport \"b.proto\";\nimport public \"c.proto\";\n"
    );
}

#[test]
fn preserved_header_order_still_sorts_imports_in_place() {
    let source = "import \"b.proto\";\nimport \"a.proto\";\npackage p;\n";
    assert_eq!(
        with(source, |o| o.import_order = ImportOrder::Sorted),
        "import \"a.proto\";\nimport \"b.proto\";\n\npackage p;\n"
    );
}

#[test]
fn expanded_empty_blocks_put_the_closing_brace_on_its_own_line() {
    let source = "message A {}\nenum E {}\nservice S {\n  rpc F(A) returns (A) {}\n}\n";
    assert_eq!(
        with(source, |o| o.empty_block_layout = EmptyBlockLayout::Expanded),
        "message A {\n}\nenum E {\n}\nservice S {\n  rpc F(A) returns (A) {\n  }\n}\n"
    );
}

#[test]
fn empty_rpc_body_rewrites_both_directions() {
    let source = "service S {\n  rpc F(A) returns (A) {}\n  rpc G(A) returns (A);\n}\n";
    assert_eq!(
        with(source, |o| o.empty_rpc_body = EmptyRpcBody::Semicolon),
        "service S {\n  rpc F(A) returns (A);\n  rpc G(A) returns (A);\n}\n"
    );
    assert_eq!(
        with(source, |o| o.empty_rpc_body = EmptyRpcBody::Braces),
        "service S {\n  rpc F(A) returns (A) {}\n  rpc G(A) returns (A) {}\n}\n"
    );
}

#[test]
fn preserved_empty_statements_stay_with_the_statement_before_them() {
    let source = "message A {\n  optional int32 a = 1;;\n  oneof o {\n    int32 b = 2;\n  };\n};\n";
    assert_eq!(
        with(source, |o| o.empty_statements = EmptyStatements::Preserve),
        "message A {\n  optional int32 a = 1;;\n  oneof o {\n    int32 b = 2;\n  };\n};\n"
    );
    assert_eq!(
        format(source, FormatOptions::default()),
        "message A {\n  optional int32 a = 1;\n  oneof o {\n    int32 b = 2;\n  }\n}\n"
    );
}

#[test]
fn separated_declarations_gain_blank_lines_but_not_at_block_edges() {
    let source = "message A {\n  message B {\n    optional int32 a = 1;\n  }\n  optional int32 b = 2;\n  // note\n  enum E {\n    X = 0;\n  }\n}\nmessage C {}\n";
    assert_eq!(
        with(source, |o| o.declaration_spacing = DeclarationSpacing::Separated),
        "message A {\n  message B {\n    optional int32 a = 1;\n  }\n\n  optional int32 b = 2;\n\n  // note\n  enum E {\n    X = 0;\n  }\n}\n\nmessage C {}\n"
    );
}

#[test]
fn normalized_comment_spacing_touches_only_bare_line_comments() {
    let source = "//a\n///b\n//!c\n// d\n/*e*/\nmessage A {} //f\n";
    assert_eq!(
        with(source, |o| o.comment_spacing = CommentSpacing::Normalized),
        "// a\n///b\n//!c\n// d\n/*e*/\nmessage A {} // f\n"
    );
}

#[test]
fn blank_line_limit_caps_runs_of_blank_lines() {
    let source = "message A {}\n\n\n\n\nmessage B {}\n";
    assert_eq!(
        with(source, |o| o.blank_line_limit = 2),
        "message A {}\n\n\nmessage B {}\n"
    );
    assert_eq!(with(source, |o| o.blank_line_limit = 0), "message A {}\nmessage B {}\n");
}

#[test]
fn ignore_directives_are_configurable() {
    let source = "// keep\nmessage   A   {}\n// profmt-ignore\nmessage   B   {}\n";
    assert_eq!(
        with(source, |o| o.ignore_directives = vec!["keep".to_owned()]),
        "// keep\nmessage   A   {}\n// profmt-ignore\nmessage B {}\n"
    );
    assert_eq!(
        with(source, |o| o.ignore_directives.clear()),
        "// keep\nmessage A {}\n// profmt-ignore\nmessage B {}\n"
    );
}

#[test]
fn ignored_oneof_members_keep_their_semicolon() {
    let source = "message A {\n  oneof o {\n    // profmt-ignore\n    int32   a=1;\n    int32   b=2;\n  }\n}\n";
    assert_eq!(
        format(source, FormatOptions::default()),
        "message A {\n  oneof o {\n    // profmt-ignore\n    int32   a=1;\n    int32 b = 2;\n  }\n}\n"
    );
}

#[test]
fn declarations_never_break_by_default() {
    let source = "option (a).b = \"a value long enough to overflow a narrow line\";\nservice S {\n  rpc LongName(LongRequest) returns (LongResponse) {\n    option (x) = 1;\n  }\n}\nmessage A {\n  optional int32 a = 1 [default = 1, (x).y = \"long enough to overflow\"];\n  reserved 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n}\n";
    assert_eq!(with(source, |o| o.line_width = 20), source);
}

#[test]
fn rpc_signatures_can_break_before_returns() {
    let source = "service S {\n  rpc LongName(LongRequest) returns (LongResponse) {\n    option (x) = 1;\n  }\n  rpc Short(A) returns (B);\n}\n";
    assert_eq!(
        with(source, |o| {
            o.line_width = 40;
            o.indent_width = 4;
            o.rpc_signature_layout = RpcSignatureLayout::BreakBeforeReturns;
        }),
        "service S {\n    rpc LongName(LongRequest)\n        returns (LongResponse) {\n        option (x) = 1;\n    }\n    rpc Short(A) returns (B);\n}\n"
    );
}

#[test]
fn field_options_can_break_one_per_line() {
    let source = "message A {\n  optional int32 a = 1 [default = 1, (x).y = \"long\"];\n  optional int32 b = 2 [default = 1];\n}\nenum E {\n  V = 1 [deprecated = true, (x).y = \"long\"];\n}\n";
    assert_eq!(
        with(source, |o| {
            o.line_width = 40;
            o.field_options_layout = FieldOptionsLayout::OnePerLine;
        }),
        "message A {\n  optional int32 a = 1 [\n    default = 1,\n    (x).y = \"long\"\n  ];\n  optional int32 b = 2 [default = 1];\n}\nenum E {\n  V = 1 [\n    deprecated = true,\n    (x).y = \"long\"\n  ];\n}\n"
    );
}

#[test]
fn option_values_can_move_to_a_new_line() {
    let source = "option (a).b = \"a value long enough to overflow\";\noption (a).c = { key: \"a value long enough to overflow\" };\noption d = 1;\n";
    assert_eq!(
        with(source, |o| {
            o.line_width = 40;
            o.option_value_layout = OptionValueLayout::NewLine;
        }),
        "option (a).b =\n  \"a value long enough to overflow\";\noption (a).c = {\n  key: \"a value long enough to overflow\"\n};\noption d = 1;\n"
    );
}

#[test]
fn byte_order_mark_and_empty_input_survive() {
    assert_eq!(format("", FormatOptions::default()), "");
    assert_eq!(
        format("\u{feff}message A{}", FormatOptions::default()),
        "\u{feff}message A {}\n"
    );
}

#[test]
fn invalid_input_is_an_error() {
    let error = profmt::format(b"message {").expect_err("parse error");
    assert!(error.to_string().contains("parse error at line 1"), "{error:#}");
    let error = profmt::format(b"\xff").expect_err("invalid UTF-8");
    assert!(error.to_string().contains("not valid UTF-8"), "{error:#}");
}