Make --json option global

This commit is contained in:
Andrey Golovizin 2021-06-29 23:15:02 +02:00
parent 1a2a96911e
commit 4abc08a34b

View file

@ -11,14 +11,11 @@ const BASE_URL: &str = "https://api.azirevpn.com/v1";
#[derive(Clap, Debug)]
struct Opts {
#[clap(subcommand)]
command: Command,
}
#[derive(Clap, Debug)]
struct EndpointsOpts {
#[clap(short, long)]
json: bool,
#[clap(subcommand)]
command: Command,
}
#[derive(Clap, Debug)]
@ -30,7 +27,7 @@ struct ConfigOpts {
#[derive(Clap, Debug)]
enum Command {
Endpoints(EndpointsOpts),
Endpoints,
Config(ConfigOpts),
Check,
}
@ -57,7 +54,7 @@ struct Locations {
#[derive(Serialize, Deserialize, Debug)]
struct CheckResult {
connected: bool,
ip: String, // XXX
ip: String, // XXX
location: String,
}
@ -85,14 +82,14 @@ fn main() -> Result<(), anyhow::Error> {
env_logger::init();
let opts = Opts::parse();
match &opts.command {
Command::Endpoints(list_opts) => list(&list_opts)?,
Command::Config(get_config_opts) => get_config(&get_config_opts)?,
Command::Check => check()?,
Command::Endpoints => list(&opts)?,
Command::Config(get_config_opts) => get_config(&opts, &get_config_opts)?,
Command::Check => check(&opts)?,
}
Ok(())
}
fn list(opts: &EndpointsOpts) -> Result<(), anyhow::Error> {
fn list(opts: &Opts) -> Result<(), anyhow::Error> {
let locations: Locations = get_locations()?;
if opts.json {
println!("{}", serde_json::to_string(&locations)?);
@ -117,20 +114,20 @@ fn get_locations() -> Result<Locations, anyhow::Error> {
Ok(locations)
}
fn get_config(opts: &ConfigOpts) -> Result<(), anyhow::Error> {
fn get_config(_opts: &Opts, config_opts: &ConfigOpts) -> Result<(), anyhow::Error> {
let locations = get_locations()?;
let location = locations
.locations
.iter()
.find(|location| location.name == opts.location)
.ok_or_else(|| anyhow::anyhow!("no such location: {}", opts.location))?;
.find(|location| location.name == config_opts.location)
.ok_or_else(|| anyhow::anyhow!("no such location: {}", config_opts.location))?;
debug!("location = {:?}", &location);
let keys = generage_keys()?;
debug!("keys = {:?}", &keys);
let config: WireguardConfig = ureq::post(&location.endpoints.wireguard)
.send_form(&[
("username", &opts.username),
("token", &opts.token),
("username", &config_opts.username),
("token", &config_opts.token),
("pubkey", &keys.public_key),
])?
.into_json()?;
@ -154,12 +151,16 @@ AllowedIPs = 0.0.0.0/0 #, ::/0",
Ok(())
}
fn check() -> Result<(), anyhow::Error> {
fn check(opts: &Opts) -> Result<(), anyhow::Error> {
let url = format!("{}/check", BASE_URL);
let result: CheckResult = ureq::get(&url).call()?.into_json()?;
println!("Connected: {:?}", result.connected);
println!("IP: {}", result.ip);
println!("Location: {}", result.location);
if opts.json {
println!("{}", serde_json::to_string(&result)?);
} else {
println!("Connected: {:?}", result.connected);
println!("IP: {}", result.ip);
println!("Location: {}", result.location);
}
Ok(())
}