spacetimedb_cli/subcommands/
energy.rs1use crate::common_args;
3use clap::ArgMatches;
4
5use crate::config::Config;
6use crate::util::{self, get_login_token_or_log_in, UNSTABLE_WARNING};
7
8pub fn cli() -> clap::Command {
9 clap::Command::new("energy")
10 .about(format!(
11 "Invokes commands related to database budgets. {}",
12 UNSTABLE_WARNING
13 ))
14 .args_conflicts_with_subcommands(true)
15 .subcommand_required(true)
16 .subcommands(get_energy_subcommands())
17}
18
19fn get_energy_subcommands() -> Vec<clap::Command> {
20 vec![clap::Command::new("balance")
21 .about("Show current energy balance for an identity")
22 .arg(
23 common_args::identity()
24 .help("The identity to check the balance for")
25 .long_help(
26 "The identity to check the balance for. If no identity is provided, the default one will be used.",
27 ),
28 )
29 .arg(
30 common_args::server()
31 .help("The nickname, host name or URL of the server from which to request balance information"),
32 )
33 .arg(common_args::yes())]
34}
35
36async fn exec_subcommand(config: Config, cmd: &str, args: &ArgMatches) -> Result<(), anyhow::Error> {
37 match cmd {
38 "balance" => exec_status(config, args).await,
39 unknown => Err(anyhow::anyhow!("Invalid subcommand: {}", unknown)),
40 }
41}
42
43pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
44 let (cmd, subcommand_args) = args.subcommand().expect("Subcommand required");
45 eprintln!("{}\n", UNSTABLE_WARNING);
46 exec_subcommand(config, cmd, subcommand_args).await
47}
48
49async fn exec_status(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
50 let identity = args.get_one::<String>("identity");
52 let server = args.get_one::<String>("server").map(|s| s.as_ref());
53 let force = args.get_flag("force");
54 let identity = if let Some(identity) = identity {
56 identity.clone()
57 } else {
58 let token = get_login_token_or_log_in(&mut config, server, !force).await?;
59 util::decode_identity(&token)?
60 };
61
62 let status = reqwest::Client::new()
63 .get(format!("{}/v1/energy/{}", config.get_host_url(server)?, identity))
64 .send()
65 .await?
66 .error_for_status()?
67 .text()
68 .await?;
69
70 println!("{}", status);
71
72 Ok(())
73}