Skip to main content

kevy_cli/rcli/
entry.rs

1//! Startup: defaults, options, environment, then the first enabled mode.
2
3use super::opts_parse::{Parsed, parse};
4use super::session::{Connect, Session};
5use std::io::IsTerminal;
6
7/// Run redis-cli with `args` (without the program name); the exit code.
8///
9/// Output goes to the process's stdout and stderr, as redis-cli's does.
10///
11/// # Examples
12///
13/// ```
14/// // `--version` answers without a server and exits 0.
15/// assert_eq!(kevy_cli::rcli::run(&[b"--version".to_vec()]), 0);
16/// ```
17pub fn run(args: &[Vec<u8>]) -> u8 {
18    let stdout_tty = std::io::stdout().is_terminal() || std::env::var_os("FAKETTY").is_some();
19    let (mut opts, first) = match parse(args, stdout_tty) {
20        Parsed::Exit(code) => return code,
21        Parsed::Run(opts, first) => (*opts, first),
22    };
23    if opts.auth.is_none() {
24        opts.auth = auth_from_env();
25    }
26    if opts.askpass {
27        opts.auth = ask_password();
28    }
29    let command = &args[first..];
30    let mut session = Session::new(opts);
31    if let Some((flag, tool)) = command.split_first()
32        && flag == b"--kevy"
33    {
34        if super::modes::dispatch::any(&session.opts) {
35            super::session::eprint_bytes(&[
36                b"kevy-cli: --kevy runs one tool; it cannot be combined with a special mode (--scan, --stat, --cluster, --eval, ...)\n",
37            ]);
38            return 1;
39        }
40        return super::rds::route::run_kevy(&mut session, tool);
41    }
42    if let Some(input) = session.opts.modes.test_hint.clone() {
43        return super::hint_modes::print_hint(&mut session, &input);
44    }
45    if let Some(path) = session.opts.modes.test_hint_file.clone() {
46        return super::hint_modes::check_hints(&mut session, &path);
47    }
48    if let Some(code) = super::modes::dispatch::run(&mut session) {
49        return code;
50    }
51    if let Some(file) = session.opts.modes.eval.clone() {
52        return super::modes::eval::run(&mut session, &file, command);
53    }
54    if command.is_empty() {
55        session.connect(Connect::Report);
56        return super::repl::run(&mut session);
57    }
58    session.connect(Connect::Quiet);
59    super::oneshot::run(&mut session, command)
60}
61
62/// `parseEnv`: the password from the environment, kevy's name first.
63fn auth_from_env() -> Option<Vec<u8>> {
64    use std::os::unix::ffi::OsStringExt;
65    ["KEVYCLI_AUTH", "VALKEYCLI_AUTH", "REDISCLI_AUTH"]
66        .iter()
67        .find_map(std::env::var_os)
68        .map(OsStringExt::into_vec)
69}
70
71/// `--askpass`: the password typed at a masked prompt, or a line of piped
72/// input without one.
73fn ask_password() -> Option<Vec<u8>> {
74    super::input::Input::read_secret(b"Please input password: ")
75}