5 个版本
0.1.4 | 2024年6月27日 |
---|---|
0.1.3 | 2024年3月15日 |
0.1.2 | 2024年2月26日 |
0.1.1 | 2024年2月16日 |
0.1.0 | 2024年2月13日 |
#865 在 命令行界面
每月 71 次下载
用于 openstack_cli
17KB
216 行
结构体表格 derive 宏
你很可能不想直接使用这个 crate。它是 OpenStack 的辅助工具。
此 crate 实现了 derive 宏,用于将结构体(或结构体向量)转换为表格(字符串的向量向量 - 作为行和列)。
根据 OutputConfig,可以构建包含所选字段的元组(标题,行)
use std::collections::BTreeSet;
use serde_json::Value;
use serde::Serialize;
use structable_derive::StructTable;
#[derive(Serialize, StructTable)]
struct User {
#[structable(title = "ID")]
id: u64,
first_name: &'static str,
last_name: &'static str,
#[structable(title = "Long(only in wide mode)", wide)]
extra: &'static str,
#[structable(optional, pretty)]
complex_data: Option<Value>
}
struct OutputConfig {
/// Limit fields (their titles) to be returned
fields: BTreeSet<String>,
/// Wide mode (additional fields requested)
wide: bool,
// Pretty-print
pretty: bool
}
trait StructTable {
fn build(&self, options: &OutputConfig) -> (Vec<String>, Vec<Vec<String>>);
}
示例
use std::collections::BTreeSet;
use serde_json::{json, Value};
use serde::Serialize;
use structable_derive::StructTable;
struct OutputConfig {
/// Limit fields (their titles) to be returned
fields: BTreeSet<String>,
/// Wide mode (additional fields requested)
wide: bool,
// Pretty-print
pretty: bool
}
trait StructTable {
fn build(&self, options: &OutputConfig) -> (Vec<String>, Vec<Vec<String>>);
}
#[derive(Serialize, StructTable)]
struct User {
#[structable(title = "ID")]
id: u64,
first_name: &'static str,
last_name: &'static str,
#[structable(title = "Long(only in wide mode)", wide)]
extra: &'static str,
#[structable(optional, pretty)]
complex_data: Option<Value>
}
let users = vec![
User {
id: 1,
first_name: "Scooby",
last_name: "Doo",
extra: "Foo",
complex_data: Some(json!({"a": "b", "c": "d"}))
},
User {
id: 2,
first_name: "John",
last_name: "Cena",
extra: "Bar",
complex_data: None
},
];
let user = User {
id: 1,
first_name: "Scooby",
last_name: "Doo",
extra: "XYZ",
complex_data: Some(json!({"a": "b", "c": "d"}))
};
let ln_fields: BTreeSet<String> = BTreeSet::from(["Last Name".to_string()]);
let config = OutputConfig {
fields: BTreeSet::new(), // ln_fields,
wide: false,
pretty: false
};
let data = user.build(&config);
println!("Single user {:?} => {:?}", data.0, data.1);
let data2 = users.build(&config);
println!("multiple users {:?} => {:?}", data2.0, data2.1);
Single user ["Attribute", "Value"] => [["id", "1"], ["first_name", "Scooby"], ["last_name", "Doo"], ["long_only", "XYZ"]]
multiple user ["id", "first_name", "last_name", "long_only"] => [["1", "Scooby", "Doo", "Foo"], ["2", "John", "Cena", "Bar"]]
依赖项
~0.6–1MB
~24K SLoC