Skip to main content

reddb_server/cli/
commands.rs

1/// RedDB command definitions.
2///
3/// Defines the command tree, Flag and Route types used by help and completion
4/// generators, and the schema for each built-in command.
5use super::types::FlagSchema;
6
7// ============================================================================
8// Help-layer types (used by help.rs and complete.rs)
9// ============================================================================
10
11/// Lightweight flag descriptor used by the help generator.
12#[derive(Debug, Clone)]
13pub struct Flag {
14    pub short: Option<char>,
15    pub long: String,
16    pub description: String,
17    pub default: Option<String>,
18    pub arg: Option<String>,
19}
20
21impl Flag {
22    pub fn new(long: &str, desc: &str) -> Self {
23        Self {
24            short: None,
25            long: long.to_string(),
26            description: desc.to_string(),
27            default: None,
28            arg: None,
29        }
30    }
31
32    pub fn with_short(mut self, short: char) -> Self {
33        self.short = Some(short);
34        self
35    }
36
37    pub fn with_default(mut self, default: &str) -> Self {
38        self.default = Some(default.to_string());
39        self
40    }
41
42    pub fn with_arg(mut self, arg: &str) -> Self {
43        self.arg = Some(arg.to_string());
44        self
45    }
46}
47
48/// A single routable verb within a resource.
49#[derive(Debug, Clone)]
50pub struct Route {
51    pub verb: &'static str,
52    pub summary: &'static str,
53    pub usage: &'static str,
54}
55
56// ============================================================================
57// RedDB command definitions
58// ============================================================================
59
60/// Command descriptor for a top-level RedDB command.
61pub struct CommandDef {
62    pub name: &'static str,
63    pub summary: &'static str,
64    pub usage: &'static str,
65    pub flags: Vec<FlagSchema>,
66}
67
68/// Return all RedDB commands.
69pub fn all_commands() -> Vec<CommandDef> {
70    vec![
71    CommandDef {
72      name: "server",
73      summary: "Start the database server (router/HTTP/gRPC/wire)",
74      usage: "red server [--grpc] [--http] [--grpc-bind 127.0.0.1:5555] [--http-bind 127.0.0.1:5055] [--wire-bind 127.0.0.1:5050] [--path ./data/reddb.rdb]",
75      flags: server_flags(),
76    },
77    CommandDef {
78      name: "service",
79      summary: "Install or inspect a systemd service",
80      usage: "red service <install|print-unit> [--binary /usr/local/bin/red] [--grpc-bind 0.0.0.0:5555] [--http-bind 0.0.0.0:5055] [--path /var/lib/reddb/data.rdb]",
81      flags: service_flags(),
82    },
83    CommandDef {
84      name: "query",
85      summary: "Execute a query against the database",
86      usage: "red query \"SELECT * FROM users WHERE age > 21\"",
87      flags: query_flags(),
88    },
89    CommandDef {
90      name: "insert",
91      summary: "Insert an entity into a collection",
92      usage: "red insert users '{\"name\": \"Alice\", \"age\": 30}'",
93      flags: insert_flags(),
94    },
95    CommandDef {
96      name: "get",
97      summary: "Get an entity by ID from a collection",
98      usage: "red get users abc123",
99      flags: get_flags(),
100    },
101    CommandDef {
102      name: "delete",
103      summary: "Delete an entity by ID from a collection",
104      usage: "red delete users abc123",
105      flags: delete_flags(),
106    },
107    CommandDef {
108      name: "health",
109      summary: "Run a health check against the server",
110      usage: "red health [--bind 127.0.0.1:5050] [--grpc|--http]",
111      flags: health_flags(),
112    },
113    CommandDef {
114      name: "tick",
115      summary: "Run maintenance/reclaim tick operations",
116      usage: "red tick [--bind 127.0.0.1:5055] [--operations maintenance,retention,checkpoint] [--dry-run]",
117      flags: tick_flags(),
118    },
119    CommandDef {
120      name: "migrate-from-redis",
121      summary: "Validate Redis to Blob Cache migration readiness; dual-write uses the documented application-owned helper pattern",
122      usage: "red migrate-from-redis --dry-run --redis-url redis://127.0.0.1:6379/0 [--path ./data/reddb.rdb]",
123      flags: migrate_from_redis_flags(),
124    },
125    CommandDef {
126      name: "replica",
127      summary: "Start as a read replica connected to a primary",
128      usage: "red replica --primary-addr http://primary:5555 [--grpc] [--http] [--grpc-bind 127.0.0.1:5555] [--http-bind 127.0.0.1:5055] [--path ./data/reddb.rdb]",
129      flags: replica_flags(),
130    },
131    CommandDef {
132      name: "status",
133      summary: "Show replication status",
134      usage: "red status [--bind 0.0.0.0:6380]",
135      flags: status_flags(),
136    },
137    CommandDef {
138      name: "mcp",
139      summary: "Start MCP server for AI agent integration",
140      usage: "red mcp [--path /data]",
141      flags: mcp_flags(),
142    },
143    CommandDef {
144      name: "auth",
145      summary: "Manage authentication (users, tokens, roles)",
146      usage: "red auth <subcommand>",
147      flags: auth_flags(),
148    },
149    CommandDef {
150      name: "connect",
151      summary: "Connect to a remote RedDB server (interactive REPL)",
152      usage: "red connect [--token <token>] [--query <sql>] <addr>",
153      flags: connect_flags(),
154    },
155    CommandDef {
156      name: "dump",
157      summary: "Export one or all collections as JSONL for backup/migration",
158      usage: "red dump [--path file] [--collection NAME] [-o FILE]",
159      flags: dump_flags(),
160    },
161    CommandDef {
162      name: "restore",
163      summary: "Import a previously dumped JSONL file into the database",
164      usage: "red restore [--path file] -i FILE [--collection NAME]",
165      flags: restore_flags(),
166    },
167    CommandDef {
168      name: "pitr-list",
169      summary: "List available point-in-time restore points from a snapshot archive",
170      usage: "red pitr-list --snapshot-prefix DIR --wal-prefix DIR",
171      flags: pitr_list_flags(),
172    },
173    CommandDef {
174      name: "pitr-restore",
175      summary: "Restore a database to a specific point in time from snapshots + WAL archive",
176      usage: "red pitr-restore --target-time UNIX_MS --dest PATH --snapshot-prefix DIR --wal-prefix DIR",
177      flags: pitr_restore_flags(),
178    },
179    CommandDef {
180      name: "doctor",
181      summary: "Health-check a running server against operator thresholds (PLAN.md Phase 5.5)",
182      usage: "red doctor [--bind 127.0.0.1:5055] [--token <admin>] [--json] [--backup-age-warn-secs 600] [--backup-age-crit-secs 3600] [--wal-lag-warn 1000] [--wal-lag-crit 10000]",
183      flags: doctor_flags(),
184    },
185    CommandDef {
186      name: "bootstrap",
187      summary: "One-shot first-admin bootstrap for headless containers / K8s Jobs",
188      usage: "red bootstrap --path PATH --vault [--username USER] [--password-stdin] [--print-certificate] [--json]",
189      flags: bootstrap_flags(),
190    },
191    CommandDef {
192      name: "version",
193      summary: "Show RedDB version information",
194      usage: "red version",
195      flags: vec![],
196    },
197    CommandDef {
198      name: "vcs",
199      summary: "Version-control operations (Git for Data)",
200      usage: "red vcs <commit|branch|branches|tag|tags|checkout|merge|log|status|lca|resolve> [args] [flags]",
201      flags: vcs_flags(),
202    },
203  ]
204}
205
206/// Return the help text for the main `red` command.
207pub fn main_help_text() -> String {
208    let mut out = String::with_capacity(1024);
209
210    out.push_str("reddb -- unified multi-model database engine\n");
211    out.push('\n');
212    out.push_str("Usage: red <command> [args] [flags]\n");
213    out.push('\n');
214
215    out.push_str("Commands:\n");
216    for cmd in all_commands() {
217        out.push_str(&format!("  {:<14} {}\n", cmd.name, cmd.summary));
218    }
219    out.push_str(&format!("  {:<14} {}\n", "help", "Show help for a command"));
220    out.push('\n');
221
222    out.push_str("Global flags:\n");
223    out.push_str(&format!("  {:<24} {}\n", "-h, --help", "Show help"));
224    out.push_str(&format!("  {:<24} {}\n", "-j, --json", "Force JSON output"));
225    out.push_str(&format!(
226        "  {:<24} {}\n",
227        "-o, --output FORMAT", "Output format [text|json|yaml]"
228    ));
229    out.push_str(&format!("  {:<24} {}\n", "-v, --verbose", "Verbose output"));
230    out.push_str(&format!(
231        "  {:<24} {}\n",
232        "    --no-color", "Disable colors"
233    ));
234    out.push_str(&format!("  {:<24} {}\n", "    --version", "Show version"));
235    out.push('\n');
236
237    out.push_str("Examples:\n");
238    out.push_str("  red server --path ./data/reddb.rdb\n");
239    out.push_str("  red server --grpc-bind 127.0.0.1:5555 --http-bind 127.0.0.1:5055 --path ./data/reddb.rdb\n");
240    out.push_str("  red server --wire-bind 127.0.0.1:5050 --path ./data/reddb.rdb\n");
241    out.push_str("  sudo red service install --binary /usr/local/bin/red --grpc-bind 0.0.0.0:5555 --http-bind 0.0.0.0:5055 --path /var/lib/reddb/data.rdb\n");
242    out.push_str("  red replica --primary-addr http://primary:5555 --path ./data/replica.rdb\n");
243    out.push_str("  red query \"SELECT * FROM users\"\n");
244    out.push_str("  red insert users '{\"name\": \"Alice\"}'\n");
245    out.push_str("  red get users abc123\n");
246    out.push_str("  red health\n");
247    out.push_str(
248        "  red tick --bind 127.0.0.1:5055 --operations maintenance,retention,checkpoint\n",
249    );
250    out.push_str("  red auth create-user alice --password secret --role admin\n");
251    out.push_str("  red auth create-api-key alice --name \"ci-token\" --role write\n");
252    out.push_str("  red auth list-users\n");
253    out.push_str("  red auth login alice --password secret\n");
254    out.push_str("  red connect 127.0.0.1:5050\n");
255    out.push_str("  red connect --query \"SELECT * FROM users\" 127.0.0.1:5050\n");
256    out.push('\n');
257
258    out.push_str("Run 'red <command> --help' for more information on a command.\n");
259    out
260}
261
262/// Return help text for a specific command.
263pub fn command_help_text(name: &str) -> Option<String> {
264    let cmds = all_commands();
265    let cmd = cmds.iter().find(|c| c.name == name)?;
266
267    let mut out = String::with_capacity(512);
268
269    out.push_str(&format!("red {} -- {}\n", cmd.name, cmd.summary));
270    out.push('\n');
271    out.push_str(&format!("Usage: {}\n", cmd.usage));
272    out.push('\n');
273
274    if !cmd.flags.is_empty() {
275        out.push_str("Flags:\n");
276        for flag in &cmd.flags {
277            let short_part = match flag.short {
278                Some(ch) => format!("-{}, ", ch),
279                None => "    ".to_string(),
280            };
281            let value_part = if flag.expects_value {
282                format!(" <{}>", flag.long.to_uppercase())
283            } else {
284                String::new()
285            };
286            let label = format!("{}--{}{}", short_part, flag.long, value_part);
287            let padding = if label.len() < 24 {
288                24 - label.len()
289            } else {
290                2
291            };
292            let default_text = match &flag.default {
293                Some(d) => format!(" (default: {})", d),
294                None => String::new(),
295            };
296            out.push_str(&format!(
297                "  {}{}{}{}\n",
298                label,
299                " ".repeat(padding),
300                flag.description,
301                default_text,
302            ));
303        }
304        out.push('\n');
305    }
306
307    Some(out)
308}
309
310// ============================================================================
311// Per-command flag schemas
312// ============================================================================
313
314fn server_flags() -> Vec<FlagSchema> {
315    vec![
316        FlagSchema::new("path")
317            .with_short('d')
318            .with_description("Persistent database file path (omit for in-memory)")
319            .with_default("./data/reddb.rdb"),
320        FlagSchema::new("bind").with_short('b').with_description(
321            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
322        ),
323        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
324        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
325        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
326        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
327        FlagSchema::new("wire-bind")
328            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
329        FlagSchema::new("wire-tls-bind")
330            .with_description("Explicit wire TLS bind address (host:port)"),
331        FlagSchema::new("wire-tls-cert")
332            .with_description("Path to TLS certificate PEM for wire TLS"),
333        FlagSchema::new("wire-tls-key")
334            .with_description("Path to TLS private key PEM for wire TLS"),
335        FlagSchema::new("pg-bind").with_description(
336            "PostgreSQL wire protocol bind address (enables psql / JDBC / DBeaver clients)",
337        ),
338        FlagSchema::new("role")
339            .with_short('r')
340            .with_description("Replication role")
341            .with_choices(&["standalone", "primary", "replica"])
342            .with_default("standalone"),
343        FlagSchema::new("primary-addr").with_description("Primary gRPC address for replica mode"),
344        FlagSchema::boolean("read-only").with_description("Open the database in read-only mode"),
345        FlagSchema::boolean("no-create-if-missing")
346            .with_description("Fail instead of creating the database file"),
347        FlagSchema::new("vault")
348            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
349            .with_default("false"),
350        FlagSchema::new("log-dir").with_description(
351            "Directory for rotating log files (defaults to the parent of --path / ./logs)",
352        ),
353        FlagSchema::new("log-level")
354            .with_description(
355                "Log level filter — trace / debug / info / warn / error, or a RUST_LOG expression",
356            )
357            .with_default("info"),
358        FlagSchema::new("log-format")
359            .with_description("Log output format")
360            .with_choices(&["pretty", "json"])
361            .with_default("pretty"),
362        FlagSchema::new("log-keep-days")
363            .with_description("Number of rotated log files to keep")
364            .with_default("14"),
365        FlagSchema::boolean("no-log-file")
366            .with_description("Disable rotating file logs (stderr only)"),
367    ]
368}
369
370fn replica_flags() -> Vec<FlagSchema> {
371    vec![
372        FlagSchema::new("primary-addr")
373            .with_short('p')
374            .with_description("Primary gRPC address (e.g. http://primary:50051)"),
375        FlagSchema::new("path")
376            .with_short('d')
377            .with_description("Local replica database file path")
378            .with_default("./data/reddb.rdb"),
379        FlagSchema::new("bind").with_short('b').with_description(
380            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
381        ),
382        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
383        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
384        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
385        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
386        FlagSchema::new("wire-bind")
387            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
388        FlagSchema::new("vault")
389            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
390            .with_default("false"),
391    ]
392}
393
394fn vcs_flags() -> Vec<FlagSchema> {
395    vec![
396        FlagSchema::new("path")
397            .with_short('d')
398            .with_description("Persistent database file path (omit for in-memory)"),
399        FlagSchema::new("connection")
400            .with_short('c')
401            .with_description("Connection id for workset scoping")
402            .with_default("1"),
403        FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
404        FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
405        FlagSchema::new("to").with_description("Upper bound for log range"),
406        FlagSchema::new("author")
407            .with_description("Commit author name")
408            .with_default("reddb"),
409        FlagSchema::new("email")
410            .with_description("Commit author email")
411            .with_default("reddb@localhost"),
412        FlagSchema::new("message")
413            .with_short('m')
414            .with_description("Commit message"),
415        FlagSchema::new("limit")
416            .with_description("Max log entries")
417            .with_default("20"),
418        FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
419        FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
420    ]
421}
422
423fn service_flags() -> Vec<FlagSchema> {
424    vec![
425        FlagSchema::new("binary")
426            .with_description("Path to the red binary")
427            .with_default("/usr/local/bin/red"),
428        FlagSchema::new("service-name")
429            .with_description("systemd unit name")
430            .with_default("reddb"),
431        FlagSchema::new("user")
432            .with_description("Service user")
433            .with_default("reddb"),
434        FlagSchema::new("group")
435            .with_description("Service group")
436            .with_default("reddb"),
437        FlagSchema::new("path")
438            .with_short('d')
439            .with_description("Persistent database file path")
440            .with_default("/var/lib/reddb/data.rdb"),
441        FlagSchema::new("bind").with_short('b').with_description(
442            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
443        ),
444        FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
445        FlagSchema::boolean("http").with_description("Install an HTTP service"),
446        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
447        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
448    ]
449}
450
451fn query_flags() -> Vec<FlagSchema> {
452    vec![FlagSchema::new("bind")
453        .with_short('b')
454        .with_description("Server address")
455        .with_default("0.0.0.0:6380")]
456}
457
458fn insert_flags() -> Vec<FlagSchema> {
459    vec![FlagSchema::new("bind")
460        .with_short('b')
461        .with_description("Server address")
462        .with_default("0.0.0.0:6380")]
463}
464
465fn get_flags() -> Vec<FlagSchema> {
466    vec![FlagSchema::new("bind")
467        .with_short('b')
468        .with_description("Server address")
469        .with_default("0.0.0.0:6380")]
470}
471
472fn delete_flags() -> Vec<FlagSchema> {
473    vec![FlagSchema::new("bind")
474        .with_short('b')
475        .with_description("Server address")
476        .with_default("0.0.0.0:6380")]
477}
478
479fn health_flags() -> Vec<FlagSchema> {
480    vec![
481        FlagSchema::new("bind")
482            .with_short('b')
483            .with_description("Server address; defaults by transport"),
484        FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
485        FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
486    ]
487}
488
489fn bootstrap_flags() -> Vec<FlagSchema> {
490    vec![
491        FlagSchema::new("path")
492            .with_short('d')
493            .with_description("Persistent database file path"),
494        FlagSchema::boolean("vault")
495            .with_description("Required: seal credentials in the encrypted vault"),
496        FlagSchema::new("username")
497            .with_short('u')
498            .with_description("Admin username (defaults to REDDB_USERNAME)"),
499        FlagSchema::new("password")
500            .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
501        FlagSchema::boolean("password-stdin")
502            .with_description("Read the admin password from stdin (one line)"),
503        FlagSchema::boolean("print-certificate")
504            .with_description("Print only the certificate to stdout"),
505    ]
506}
507
508fn doctor_flags() -> Vec<FlagSchema> {
509    vec![
510        FlagSchema::new("bind")
511            .with_description("HTTP address of the server to probe")
512            .with_default("127.0.0.1:5055"),
513        FlagSchema::new("token")
514            .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
515        FlagSchema::boolean("json")
516            .with_description("Emit a single JSON object instead of human text"),
517        FlagSchema::new("backup-age-warn-secs")
518            .with_description("Warn when last successful backup is older than N seconds")
519            .with_default("600"),
520        FlagSchema::new("backup-age-crit-secs")
521            .with_description("Critical when last successful backup is older than N seconds")
522            .with_default("3600"),
523        FlagSchema::new("wal-lag-warn")
524            .with_description("Warn when WAL archive lag exceeds N records")
525            .with_default("1000"),
526        FlagSchema::new("wal-lag-crit")
527            .with_description("Critical when WAL archive lag exceeds N records")
528            .with_default("10000"),
529    ]
530}
531
532fn dump_flags() -> Vec<FlagSchema> {
533    vec![
534        FlagSchema::new("path")
535            .with_description("Local database file to dump from")
536            .with_default("./data/reddb.rdb"),
537        FlagSchema::new("collection")
538            .with_short('c')
539            .with_description("Single collection to dump (omit for all)"),
540        FlagSchema::new("output")
541            .with_short('o')
542            .with_description("Destination file (defaults to stdout)"),
543    ]
544}
545
546fn restore_flags() -> Vec<FlagSchema> {
547    vec![
548        FlagSchema::new("path")
549            .with_description("Local database file to restore into")
550            .with_default("./data/reddb.rdb"),
551        FlagSchema::new("input")
552            .with_short('i')
553            .with_description("Dump file to read (required)"),
554        FlagSchema::new("collection")
555            .with_short('c')
556            .with_description("Override target collection name"),
557    ]
558}
559
560fn pitr_list_flags() -> Vec<FlagSchema> {
561    vec![
562        FlagSchema::new("snapshot-prefix")
563            .with_description("Directory (or remote prefix) holding .snapshot files"),
564        FlagSchema::new("wal-prefix")
565            .with_description("Directory (or remote prefix) holding archived WAL segments"),
566    ]
567}
568
569fn pitr_restore_flags() -> Vec<FlagSchema> {
570    vec![
571        FlagSchema::new("target-time")
572            .with_description("Recovery target — UNIX ms (0 = latest available)"),
573        FlagSchema::new("dest")
574            .with_description("Destination database file path for the restored DB"),
575        FlagSchema::new("snapshot-prefix")
576            .with_description("Directory (or remote prefix) holding .snapshot files"),
577        FlagSchema::new("wal-prefix")
578            .with_description("Directory (or remote prefix) holding archived WAL segments"),
579    ]
580}
581
582fn tick_flags() -> Vec<FlagSchema> {
583    vec![
584        FlagSchema::new("bind")
585            .with_short('b')
586            .with_description("Server HTTP bind address")
587            .with_default("127.0.0.1:5055"),
588        FlagSchema::new("operations")
589            .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
590        FlagSchema::boolean("dry-run")
591            .with_description("Validate operations without applying changes"),
592    ]
593}
594
595fn migrate_from_redis_flags() -> Vec<FlagSchema> {
596    vec![
597        FlagSchema::boolean("dry-run")
598            .with_description("Validate Redis and RedDB connectivity without cache writes"),
599        FlagSchema::new("redis-url")
600            .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
601        FlagSchema::new("path")
602            .with_short('d')
603            .with_description("Local RedDB .rdb file to open for connectivity validation"),
604        FlagSchema::new("phase")
605            .with_description("Migration phase: dry-run | dual-write")
606            .with_default("dry-run"),
607        FlagSchema::new("namespace")
608            .with_description("Blob Cache namespace recorded in dry-run output")
609            .with_default("redis-migration"),
610    ]
611}
612
613fn status_flags() -> Vec<FlagSchema> {
614    vec![FlagSchema::new("bind")
615        .with_short('b')
616        .with_description("Server address")
617        .with_default("0.0.0.0:6380")]
618}
619
620fn mcp_flags() -> Vec<FlagSchema> {
621    vec![FlagSchema::new("path")
622        .with_short('d')
623        .with_description("Data directory path (omit for in-memory)")
624        .with_default("")]
625}
626
627fn connect_flags() -> Vec<FlagSchema> {
628    vec![
629        FlagSchema::new("token")
630            .with_short('t')
631            .with_description("Auth token (session or API key)"),
632        FlagSchema::new("query")
633            .with_short('q')
634            .with_description("Execute a single query and exit"),
635        FlagSchema::new("user")
636            .with_short('u')
637            .with_description("Username for login"),
638        FlagSchema::new("password")
639            .with_short('p')
640            .with_description("Password for login"),
641    ]
642}
643
644fn auth_flags() -> Vec<FlagSchema> {
645    vec![
646        FlagSchema::new("bind")
647            .with_short('b')
648            .with_description("Server address")
649            .with_default("0.0.0.0:6380"),
650        FlagSchema::new("password")
651            .with_short('p')
652            .with_description("User password"),
653        FlagSchema::new("role")
654            .with_short('r')
655            .with_description("User role")
656            .with_choices(&["read", "write", "admin"]),
657        FlagSchema::new("name")
658            .with_short('n')
659            .with_description("API key name"),
660        FlagSchema::new("user")
661            .with_short('u')
662            .with_description("Target username"),
663    ]
664}
665
666// ============================================================================
667// Completion data helpers
668// ============================================================================
669
670/// Return domain data for completion scripts.
671pub fn completion_domains() -> Vec<(String, Vec<String>)> {
672    vec![
673        ("server".to_string(), vec![]),
674        ("service".to_string(), vec![]),
675        ("replica".to_string(), vec![]),
676        ("tick".to_string(), vec![]),
677        ("query".to_string(), vec!["q".to_string()]),
678        ("insert".to_string(), vec!["i".to_string()]),
679        ("get".to_string(), vec![]),
680        ("delete".to_string(), vec!["del".to_string()]),
681        ("health".to_string(), vec![]),
682        ("status".to_string(), vec![]),
683        ("migrate-from-redis".to_string(), vec![]),
684        ("mcp".to_string(), vec![]),
685        ("auth".to_string(), vec![]),
686        ("connect".to_string(), vec![]),
687        ("version".to_string(), vec![]),
688    ]
689}
690
691/// Return global flag data for completion scripts.
692pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
693    vec![
694        ("help", Some('h')),
695        ("json", Some('j')),
696        ("output", Some('o')),
697        ("verbose", Some('v')),
698        ("no-color", None),
699        ("version", None),
700    ]
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    #[test]
708    fn test_all_commands_defined() {
709        let cmds = all_commands();
710        let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
711        assert!(names.contains(&"server"));
712        assert!(names.contains(&"query"));
713        assert!(names.contains(&"insert"));
714        assert!(names.contains(&"get"));
715        assert!(names.contains(&"delete"));
716        assert!(names.contains(&"health"));
717        assert!(names.contains(&"tick"));
718        assert!(names.contains(&"migrate-from-redis"));
719        assert!(names.contains(&"status"));
720        assert!(names.contains(&"connect"));
721        assert!(names.contains(&"version"));
722    }
723
724    #[test]
725    fn test_server_has_flags() {
726        let cmds = all_commands();
727        let server = cmds.iter().find(|c| c.name == "server").unwrap();
728        let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
729        assert!(flag_names.contains(&"path"));
730        assert!(flag_names.contains(&"bind"));
731    }
732
733    #[test]
734    fn test_replica_has_flags() {
735        let cmds = all_commands();
736        let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
737        let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
738        assert!(flag_names.contains(&"primary-addr"));
739        assert!(flag_names.contains(&"path"));
740        assert!(flag_names.contains(&"bind"));
741    }
742
743    #[test]
744    fn test_main_help_text() {
745        let help = main_help_text();
746        assert!(help.contains("reddb"));
747        assert!(help.contains("Usage: red"));
748        assert!(help.contains("Commands:"));
749        assert!(help.contains("server"));
750        assert!(help.contains("query"));
751        assert!(help.contains("Global flags:"));
752        assert!(help.contains("--help"));
753        assert!(help.contains("Examples:"));
754    }
755
756    #[test]
757    fn test_command_help_text() {
758        let help = command_help_text("server").unwrap();
759        assert!(help.contains("red server"));
760        assert!(help.contains("--path"));
761        assert!(help.contains("--bind"));
762    }
763
764    #[test]
765    fn test_replica_command_help() {
766        let help = command_help_text("replica").unwrap();
767        assert!(help.contains("red replica"));
768        assert!(help.contains("--primary-addr"));
769    }
770
771    #[test]
772    fn test_migrate_from_redis_command_help() {
773        let help = command_help_text("migrate-from-redis").unwrap();
774        assert!(help.contains("red migrate-from-redis"));
775        assert!(help.contains("--dry-run"));
776        assert!(help.contains("--redis-url"));
777        assert!(help.contains("application-owned helper"));
778    }
779
780    #[test]
781    fn test_command_help_text_unknown() {
782        assert!(command_help_text("nonexistent").is_none());
783    }
784
785    #[test]
786    fn test_flag_builder() {
787        let flag = Flag::new("output", "Output format")
788            .with_short('o')
789            .with_default("text")
790            .with_arg("FORMAT");
791
792        assert_eq!(flag.long, "output");
793        assert_eq!(flag.short, Some('o'));
794        assert_eq!(flag.description, "Output format");
795        assert_eq!(flag.default, Some("text".to_string()));
796        assert_eq!(flag.arg, Some("FORMAT".to_string()));
797    }
798
799    #[test]
800    fn test_completion_domains() {
801        let domains = completion_domains();
802        let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
803        assert!(names.contains(&"server"));
804        assert!(names.contains(&"query"));
805        assert!(names.contains(&"health"));
806    }
807
808    #[test]
809    fn test_completion_global_flags() {
810        let flags = completion_global_flags();
811        assert!(flags.contains(&("help", Some('h'))));
812        assert!(flags.contains(&("json", Some('j'))));
813        assert!(flags.contains(&("verbose", Some('v'))));
814        assert!(flags.contains(&("no-color", None)));
815    }
816}