aboutsummaryrefslogtreecommitdiffstats
path: root/adenosine-cli/src/main.rs
blob: 0246fd648d12a5625846ebf1d96a5ac350c9d132 (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use adenosine_cli::*;
use anyhow::anyhow;
use serde_json::Value;
use std::collections::HashMap;

use colored_json::to_colored_json_auto;
use log::{self, debug, info};
use std::io::Write;
use std::path::PathBuf;
use structopt::StructOpt;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case", about = "CLI interface for AT Protocol")]
struct Opt {
    #[structopt(
        global = true,
        long = "--host",
        env = "ATP_HOST",
        default_value = "https://localhost:8080"
    )]
    atp_host: String,

    // API auth tokens can be generated from the account page in the fatcat.wiki web interface
    #[structopt(
        global = true,
        long = "--auth-token",
        env = "ATP_AUTH_TOKEN",
        hide_env_values = true
    )]
    auth_token: Option<String>,

    /// Log more messages. Pass multiple times for ever more verbosity
    ///
    /// By default, it'll only report errors. Passing `-v` one time also prints
    /// warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace.
    #[structopt(global = true, long, short = "v", parse(from_occurrences))]
    verbose: i8,

    #[structopt(long = "--shell-completions", hidden = true)]
    shell_completions: Option<structopt::clap::Shell>,

    #[structopt(subcommand)]
    cmd: Command,
}

#[derive(StructOpt)]
enum AccountCommand {
    /// Register a new account
    Register {
        #[structopt(long, short)]
        email: String,

        #[structopt(long, short)]
        username: String,

        #[structopt(long, short)]
        password: String,
    },
    Delete,
    Login,
    Logout,
    Info,
    CreateRevocationKey,
}

#[derive(StructOpt)]
enum Command {
    Get {
        uri: String,
    },

    Xrpc {
        method: XrpcMethod,
        nsid: String,
        params: Option<String>,
    },

    /// Sub-commands for managing account
    Account {
        #[structopt(subcommand)]
        cmd: AccountCommand,
    },

    /// Summarize connection and authentication with API
    Status,
}

fn main() -> Result<()> {
    let opt = Opt::from_args();

    let log_level = match opt.verbose {
        std::i8::MIN..=-1 => "none",
        0 => "error",
        1 => "warn",
        2 => "info",
        3 => "debug",
        4..=std::i8::MAX => "trace",
    };
    // hyper logging is very verbose, so crank that down even if everything else is more verbose
    let log_filter = format!("{},hyper=error", log_level);
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(log_filter))
        .format_timestamp(None)
        .init();

    debug!("Args parsed, starting up");

    #[cfg(windows)]
    colored_json::enable_ansi_support();

    if let Some(shell) = opt.shell_completions {
        Opt::clap().gen_completions_to("adenosine", shell, &mut std::io::stdout());
        std::process::exit(0);
    }

    if let Err(err) = run(opt) {
        // Be graceful about some errors
        if let Some(io_err) = err.root_cause().downcast_ref::<std::io::Error>() {
            if let std::io::ErrorKind::BrokenPipe = io_err.kind() {
                // presumably due to something like writing to stdout and piped to `head -n10` and
                // stdout was closed
                debug!("got BrokenPipe error, assuming stdout closed as expected and exiting with success");
                std::process::exit(0);
            }
        }
        let mut color_stderr = StandardStream::stderr(if atty::is(atty::Stream::Stderr) {
            ColorChoice::Auto
        } else {
            ColorChoice::Never
        });
        color_stderr.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true))?;
        eprintln!("Error: {:?}", err);
        color_stderr.set_color(&ColorSpec::new())?;
        std::process::exit(1);
    }
    Ok(())
}

fn run(opt: Opt) -> Result<()> {
    let xrpc_client = XrpcClient::new(opt.atp_host, opt.auth_token)?;

    match opt.cmd {
        Command::Xrpc {
            method,
            nsid,
            params,
        } => {
            let body: Value = ().into();
            let res = match method {
                // XXX: parse params
                XrpcMethod::Get => xrpc_client.get(nsid, None)?,
                XrpcMethod::Post => xrpc_client.post(nsid, None, body)?,
            };
            if let Some(val) = res {
                writeln!(&mut std::io::stdout(), "{}", to_colored_json_auto(&val)?)?
            };
        }
        Command::Get { uri } => {
            println!("GET: {}", uri);
            /*
            let result = specifier.get_from_api(&mut api_client, expand, hide)?;
            if toml {
                writeln!(&mut std::io::stdout(), "{}", result.to_toml_string()?)?
            } else {
                // "if json"
                writeln!(
                    &mut std::io::stdout(),
                    "{}",
                    to_colored_json_auto(&result.to_json_value()?)?
                )?
            }
            */
        }
        Command::Account {
            cmd:
                AccountCommand::Register {
                    email,
                    username,
                    password,
                },
        } => {
            println!(
                "REGISTER: email={} username={} password={}",
                email, username, password
            );
        }
        _ => {
            unimplemented!("some command");
        }
    }
    Ok(())
}