Skip to main content

kevy_cli/
lib.rs

1//! CLI-shaped Reply formatter for the kevy-cli REPL.
2//!
3//! Only `format_reply` lives here — the protocol pieces (TCP connect, request
4//! loop) live in the [`kevy-resp-client`](https://crates.io/crates/kevy-resp-client)
5//! crate so they're reusable by integration tests / scripts / other tools.
6//! This file is the CLI-specific bit (how a redis-cli user expects bulk
7//! strings quoted, arrays numbered, nil shown as `(nil)`).
8
9#![forbid(unsafe_code)]
10#![warn(missing_docs)]
11
12pub use kevy_resp::Reply;
13
14/// Backup / restore container support. See
15/// [`backup::pack`] and [`backup::unpack`].
16pub mod backup;
17
18/// Migration toolchain (`export` / `import`). See
19/// [`migrate::run_export`] and [`migrate::run_import`].
20pub mod migrate;
21
22/// Where a subcommand connects when the caller says nothing. Shared
23/// rather than repeated: two copies of a default is a drift waiting to
24/// be reported as a bug.
25pub const DEFAULT_HOST: &str = "127.0.0.1";
26/// The port half of the same default.
27pub const DEFAULT_PORT: u16 = 6379;
28
29/// Prefix bulk ops + diagnostics (`copy-prefix` /
30/// `delete-prefix` / `digest` / `diff` / `inspect`).
31pub mod bulk;
32
33/// `shadow` — run the old query and the new one side by side and
34/// report where they disagree, in membership AND in order.
35pub mod shadow;
36
37/// `doctor` — every table's VERIFY counters, turned into an exit code
38/// a cron can act on.
39pub mod backfill_keys;
40pub(crate) mod collections;
41pub mod doctor;
42pub mod lint;
43
44/// Route the migration-playbook tools, which share a shape: they read
45/// and report, none of them moves data, and each exits with its own
46/// verdict. `None` when `args` names something else.
47pub fn route_tool(args: &[String]) -> Option<std::process::ExitCode> {
48    let rest = args.get(1..).unwrap_or(&[]);
49    match args.first().map(String::as_str)? {
50        "doctor" => Some(doctor::run_doctor_cli(rest)),
51        "shadow" => Some(shadow::run_shadow_cli(rest)),
52        "lint" => Some(lint::run_lint_cli(rest)),
53        "backfill-keys" => Some(backfill_keys::run_backfill_keys_cli(rest)),
54        _ => None,
55    }
56}
57
58/// Pretty-print a reply roughly the way `redis-cli` does. Arrays are
59/// numbered + indented; bulk strings are quoted; nil shows as `(nil)`.
60pub fn format_reply(reply: &Reply, indent: usize) -> String {
61    match reply {
62        Reply::Simple(s) => String::from_utf8_lossy(s).into_owned(),
63        Reply::Error(s) | Reply::BlobError(s) => {
64            format!("(error) {}", String::from_utf8_lossy(s))
65        }
66        Reply::Int(n) => format!("(integer) {n}"),
67        Reply::Bulk(b) => format!("\"{}\"", String::from_utf8_lossy(b)),
68        Reply::Nil | Reply::Null => "(nil)".to_string(),
69        Reply::Array(items) if items.is_empty() => "(empty array)".to_string(),
70        Reply::Array(items) | Reply::Set(items) | Reply::Push(items) => {
71            let pad = "   ".repeat(indent);
72            items
73                .iter()
74                .enumerate()
75                .map(|(i, it)| format!("{pad}{}) {}", i + 1, format_reply(it, indent + 1)))
76                .collect::<Vec<_>>()
77                .join("\n")
78        }
79        // RESP3 additions: format the same way redis-cli does today.
80        Reply::Map(pairs) if pairs.is_empty() => "(empty map)".to_string(),
81        Reply::Map(pairs) => {
82            let pad = "   ".repeat(indent);
83            pairs
84                .iter()
85                .enumerate()
86                .map(|(i, (k, v))| {
87                    format!(
88                        "{pad}{}) {} => {}",
89                        i + 1,
90                        format_reply(k, indent + 1),
91                        format_reply(v, indent + 1)
92                    )
93                })
94                .collect::<Vec<_>>()
95                .join("\n")
96        }
97        Reply::Double(v) => format!("(double) {v}"),
98        Reply::Boolean(b) => format!("(boolean) {}", if *b { "t" } else { "f" }),
99        Reply::Verbatim { fmt, data } => format!(
100            "(verbatim/{}) \"{}\"",
101            String::from_utf8_lossy(fmt),
102            String::from_utf8_lossy(data)
103        ),
104        Reply::BigNumber(s) => format!("(bignum) {}", String::from_utf8_lossy(s)),
105    }
106}