1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use radicle::node;
use radicle::prelude::{NodeId, RepoId};

use crate::terminal as term;
use crate::terminal::Element;

pub fn run<S: node::routing::Store>(
    routing: &S,
    rid: Option<RepoId>,
    nid: Option<NodeId>,
    json: bool,
) -> anyhow::Result<()> {
    // Filters entries by RID or NID exclusively, or show all of them if none given.
    let entries = routing.entries()?.filter(|(rid_, nid_)| {
        (nid.is_none() || Some(nid_) == nid.as_ref())
            && (rid.is_none() || Some(rid_) == rid.as_ref())
    });

    if json {
        print_json(entries);
    } else {
        print_table(entries);
    }

    Ok(())
}

fn print_table(entries: impl IntoIterator<Item = (RepoId, NodeId)>) {
    let mut t = term::Table::new(term::table::TableOptions::bordered());
    t.header([
        term::format::default(String::from("RID")),
        term::format::default(String::from("NID")),
    ]);
    t.divider();

    for (rid, nid) in entries {
        t.push([
            term::format::highlight(rid.to_string()),
            term::format::node(&nid),
        ]);
    }
    t.print();
}

fn print_json(entries: impl IntoIterator<Item = (RepoId, NodeId)>) {
    for (rid, nid) in entries {
        println!("{}", serde_json::json!({ "rid": rid, "nid": nid }));
    }
}