Skip to main content

kc/
output.rs

1//! Rendering for the `kc` binary: the two shapes its output takes.
2
3use serde_json::Value;
4
5/// A JSON envelope, indented, so it reads in a terminal and pipes into `jq`.
6pub fn pretty(value: &Value) -> String {
7    serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
8}
9
10/// Two-column `key  value` block, with the keys padded to a common width.
11pub fn field_list(fields: &[(&str, String)]) -> String {
12    let width = fields
13        .iter()
14        .map(|(label, _)| label.len())
15        .max()
16        .unwrap_or(0);
17    fields
18        .iter()
19        .map(|(label, value)| format!("{label:<width$}  {value}", width = width + 1))
20        .collect::<Vec<_>>()
21        .join("\n")
22}
23
24#[cfg(test)]
25mod tests {
26    use super::*;
27
28    #[test]
29    fn a_field_list_pads_to_the_widest_key() {
30        let rendered = field_list(&[("keychain", "demo".to_string()), ("iv", "0011".to_string())]);
31        assert_eq!(rendered, "keychain   demo\niv         0011");
32    }
33
34    #[test]
35    fn json_is_pretty_printed() {
36        let rendered = pretty(&serde_json::json!({ "ok": true }));
37        assert_eq!(rendered, "{\n  \"ok\": true\n}");
38    }
39}