Printing peers list in JSON using --json

This commit is contained in:
Maxime Van Hees committed 2024-06-05 08:20:31 +02:00
1 parent 9fc44174c9
commit 9841e1ef75
3 files changed
+37 -23

No files matched your search

+2 -2
View File
@@ -2528,9 +2528,9 @@ dependencies = [
[[package]]
name = "unicode-width"
version = "0.1.12"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6"
checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d"
[[package]]
name = "universal-hash"
+28 -18
View File
@@ -5,7 +5,10 @@ use std::net::SocketAddr;
use tracing::{debug, error};
/// List the peers the current node is connected to
pub async fn list_peers(server_addr: SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
pub async fn list_peers(
server_addr: SocketAddr,
json_print: bool,
) -> Result<(), Box<dyn std::error::Error>> {
// Make API call
let request_url = format!("http://{server_addr}/api/v1/admin/peers");
match reqwest::get(&request_url).await {
@@ -21,26 +24,33 @@ pub async fn list_peers(server_addr: SocketAddr) -> Result<(), Box<dyn std::erro
return Err(e.into());
}
Ok(peers) => {
let mut table = Table::new();
table.add_row(row![
"Protocol",
"Socket",
"Type",
"Connection",
"Rx total",
"Tx total"
]);
for peer in peers.iter() {
if json_print {
// Print peers in JSON format
let json_output = serde_json::to_string_pretty(&peers)?;
println!("{json_output}");
} else {
// Print peers in table format
let mut table = Table::new();
table.add_row(row![
peer.endpoint.proto(),
peer.endpoint.address(),
peer.pt,
peer.connection_state,
format_bytes(peer.rx_bytes),
format_bytes(peer.tx_bytes),
"Protocol",
"Socket",
"Type",
"Connection",
"Rx total",
"Tx total"
]);
for peer in peers.iter() {
table.add_row(row![
peer.endpoint.proto(),
peer.endpoint.address(),
peer.pt,
peer.connection_state,
format_bytes(peer.rx_bytes),
format_bytes(peer.tx_bytes),
]);
}
table.printstd();
}
table.printstd();
}
}
}
+7 -3
View File
@@ -137,7 +137,11 @@ pub enum MessageCommand {
#[derive(Debug, Subcommand)]
pub enum PeersCommand {
/// List the connected peers
List,
List {
/// Print the peers list in JSON format
#[arg(long = "json", default_value_t = false)]
json: bool,
},
/// Add peer(s)
Add { peers: Vec<String> },
/// Remove peer(s)
@@ -298,8 +302,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
},
Command::Peers { command } => match command {
PeersCommand::List {} => {
return cli::list_peers(cli.node_args.api_addr).await;
PeersCommand::List { json } => {
return cli::list_peers(cli.node_args.api_addr, json).await;
}
PeersCommand::Add { peers } => {
return cli::add_peers(cli.node_args.api_addr, peers).await;