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}
107
108#[cfg(test)]
109mod format_reply_tests {
110    use super::format_reply;
111    use kevy_resp::Reply;
112
113    fn f(r: &Reply) -> String {
114        format_reply(r, 0)
115    }
116
117    /// One case per `Reply` variant. `format_reply` carried 79 never-executed
118    /// regions — the largest single symbol in this crate — while being a pure
119    /// function from a reply to a string, which is as cheap to test as code
120    /// gets. The expectations are redis-cli's rendering, which is what the
121    /// function's own comment says it follows.
122    #[test]
123    fn every_reply_variant_renders() {
124        assert_eq!(f(&Reply::Simple(b"OK".to_vec())), "OK");
125        assert_eq!(f(&Reply::Error(b"ERR nope".to_vec())), "(error) ERR nope");
126        assert_eq!(f(&Reply::Int(-7)), "(integer) -7");
127        assert_eq!(f(&Reply::Bulk(b"hi".to_vec())), "\"hi\"");
128        assert_eq!(f(&Reply::Nil), "(nil)");
129        assert_eq!(f(&Reply::Array(vec![])), "(empty array)");
130        assert_eq!(f(&Reply::Double(1.5)), "(double) 1.5");
131        assert_eq!(f(&Reply::Boolean(true)), "(boolean) t");
132        assert_eq!(f(&Reply::Boolean(false)), "(boolean) f");
133        assert_eq!(f(&Reply::BigNumber(b"123456789012345678901".to_vec())),
134                   "(bignum) 123456789012345678901");
135
136        // RESP3's second null and second error spelling render as their
137        // RESP2 counterparts — a client must not be able to tell which
138        // wire form it got from the printed line.
139        assert_eq!(f(&Reply::Null), "(nil)");
140        assert_eq!(f(&Reply::BlobError(b"ERR nope".to_vec())), "(error) ERR nope");
141
142        assert_eq!(
143            f(&Reply::Verbatim { fmt: *b"txt", data: b"hello".to_vec() }),
144            "(verbatim/txt) \"hello\""
145        );
146
147        // Set and Push share the array arm; a set of one is still numbered.
148        assert_eq!(f(&Reply::Set(vec![Reply::Int(4)])), "1) (integer) 4");
149        assert_eq!(
150            f(&Reply::Push(vec![Reply::Bulk(b"message".to_vec())])),
151            "1) \"message\""
152        );
153    }
154
155    /// Arrays number from one and nest by indent — the recursive arm, which
156    /// a single flat array would leave unexercised.
157    #[test]
158    fn arrays_number_from_one_and_nest() {
159        let flat = Reply::Array(vec![Reply::Int(1), Reply::Bulk(b"x".to_vec())]);
160        assert_eq!(f(&flat), "1) (integer) 1\n2) \"x\"");
161
162        let nested = Reply::Array(vec![Reply::Array(vec![Reply::Int(9)])]);
163        // The inner element is padded by one level; the outer is not.
164        assert_eq!(f(&nested), "1)    1) (integer) 9");
165    }
166
167    /// An empty map is not an empty array, and a populated one renders
168    /// `key => value` rather than as two flat elements.
169    #[test]
170    fn maps_render_as_pairs() {
171        assert_eq!(f(&Reply::Map(vec![])), "(empty map)");
172        let m = Reply::Map(vec![(Reply::Bulk(b"k".to_vec()), Reply::Int(1))]);
173        assert_eq!(f(&m), "1) \"k\" => (integer) 1");
174    }
175}