#nested #format #block #print #code

codize

简单、语言无关的库,为您的代码生成工具格式化代码

8 个版本

0.3.3 2024年5月23日
0.3.2 2024年5月23日
0.2.0 2024年5月4日
0.1.2 2023年6月13日
0.1.0 2023年4月19日

73值格式化 中排名

Download history 6/week @ 2024-04-25 462/week @ 2024-05-02 27/week @ 2024-05-09 9/week @ 2024-05-16 273/week @ 2024-05-23 4/week @ 2024-05-30 5/week @ 2024-06-06 8/week @ 2024-06-13 2/week @ 2024-06-20 11/week @ 2024-07-18 47/week @ 2024-07-25

58 每月下载次数
用于 regen-lang

Unlicense

34KB
842

codize

Build Badge Version Badge License Badge Issue Badge

简单、语言无关的库,为您的代码生成工具格式化代码。

首先,使用以下方式之一创建一个具有代码结构的 Code 枚举。然后,可以使用 Format 结构来格式化输出。或者,您可以直接使用 to_string 以默认参数进行快速格式化

Code 示例

Code 枚举存储所有代码结构。您可以以下方式之一创建它

  • 使用 into()String&str 转换为单行
  • 使用具有缩进主体的代码块和 cblock!
  • 使用具有分隔符的代码段列表和 clist!
  • 使用多个代码段的连接,可以是迭代器转换的,也可以是使用允许混合不同类型代码段的 cconcat!

通常,宏将自动通过调用 Code::from 将输入转换为 Code

use codize::{cblock, clist, cconcat};

let code = cconcat![
    "",
    "/// This block is auto-generated",
    "",
    cblock!("fn main() {", [
        cblock!("println!(", [
            clist!("," => [r#""{}, {}!""#, r#""Hello""#, r#""world!""#])
        ], ");")
    ], "}"),
];

let expected = r#"
/// This block is auto-generated

fn main() {
    println!(
        "{}, {}!",
        "Hello",
        "world!",
    );
}"#;

assert_eq!(expected, code.to_string());

Format 示例

您可以使用 FormatCode 特性和 Format 结构体来更改全局格式化选项

use codize::{cblock, Format, FormatCode};
let code = cblock!("fn main() {", ["println!(\"Hello, world!\");"], "}");

let indent_2 = 
r#"fn main() {
  println!("Hello, world!");
}"#;
assert_eq!(indent_2, code.format_with(&Format::indent(2)));

let indent_tab =
"fn main() {
\tprintln!(\"Hello, world!\");
}";
assert_eq!(indent_tab, code.format_with(&Format::indent_tab()));

依赖项

~1.5MB
~36K SLoC