ctb_cli/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Command-line interface definitions and top-level CLI runner.
21
22// Any nontrivial logic should go in the associated crate, rather than this file and crate.
23// This module and crate should be as small as possible, with any logic related to parsing and dispatching of commands implemented in the respective crates relevant to the functionality.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace crate prelude"
29)]
30pub(crate) use ctb_utilities::*;
31
32use anyhow::Result;
33use clap::{CommandFactory, Parser};
34use ctb_utilities::ipc::{ChildKind, format_child_kind};
35use futures::StreamExt;
36use std::env;
37
38use crate::routing::{Command, run_lightweight_command};
39use ctb_storage::get_help_for_tty;
40
41pub mod routing;
42pub mod subprocess;
43
44// -----------------------------------------------------------------------------
45// Invocation Enum – top-level discrimination between subprocess & user CLI
46// -----------------------------------------------------------------------------
47
48#[derive(Debug)]
49pub enum Invocation {
50    Subprocess(SubprocessArgs),
51    User(Cli),
52}
53
54impl Default for Invocation {
55    fn default() -> Self {
56        Invocation::User(Cli {
57            ctoolbox_ipc_port: None,
58            no_update: false,
59            use_bundled_tls_validator: false,
60            use_system_tls_validator: false,
61            insecure_skip_crlite_check: false,
62            retry_on_host_error:
63                invocation_settings::DEFAULT_RETRY_ON_HOST_ERROR,
64            recover_graph: false,
65            version_json: false,
66            command: None,
67        })
68    }
69}
70
71impl Invocation {
72    pub fn is_subprocess(&self) -> bool {
73        matches!(self, Invocation::Subprocess(_))
74    }
75
76    pub fn subprocess(&self) -> Option<&SubprocessArgs> {
77        if let Invocation::Subprocess(s) = self {
78            Some(s)
79        } else {
80            None
81        }
82    }
83
84    pub fn as_cli(&self) -> Option<&Cli> {
85        if let Invocation::User(cli) = self {
86            Some(cli)
87        } else {
88            None
89        }
90    }
91
92    pub fn expect_cli(&self) -> Result<&Cli> {
93        match self {
94            Invocation::User(cli) => Ok(cli),
95            Invocation::Subprocess(_) => {
96                anyhow::bail!("Called expect_cli() on a subprocess invocation")
97            }
98        }
99    }
100
101    pub fn get_service_name(&self) -> String {
102        if self.is_subprocess() {
103            // Reason for fallback: format_child_kind returns a String for subprocesses; if self.subprocess() is None (non-subprocess invocation state), defaulting to empty string indicates no subprocess service name.
104            self.subprocess()
105                .map(|s| format_child_kind(&s.kind).to_string())
106                .unwrap_or_default()
107        } else {
108            String::new()
109        }
110    }
111}
112
113// -----------------------------------------------------------------------------
114// Subprocess Argument Structures
115// -----------------------------------------------------------------------------
116
117#[derive(Debug, Clone)]
118pub struct SubprocessArgs {
119    pub kind: ChildKind,
120    pub args: Vec<String>,
121}
122
123fn normalize_fsearch_flags(args: Vec<String>) -> Vec<String> {
124    let mut normalized = Vec::with_capacity(args.len());
125    let mut in_fsearch = false;
126    for arg in args {
127        if arg == "fsearch" {
128            in_fsearch = true;
129            normalized.push(arg);
130            continue;
131        }
132        if in_fsearch {
133            match arg.as_str() {
134                "-rp" => normalized.push("--regex-path".to_string()),
135                "-rt" => normalized.push("--regex-text".to_string()),
136                "-rn" => normalized.push("--regex-name".to_string()),
137                "-gp" => normalized.push("--glob-path".to_string()),
138                "-gt" => normalized.push("--glob-text".to_string()),
139                "-gn" => normalized.push("--glob-name".to_string()),
140                "-kp" => normalized.push("--keyword-path".to_string()),
141                "-kt" => normalized.push("--keyword-text".to_string()),
142                "-kn" => normalized.push("--keyword-name".to_string()),
143                "-sp" => normalized.push("--substring-path".to_string()),
144                "-st" => normalized.push("--substring-text".to_string()),
145                "-sn" => normalized.push("--substring-name".to_string()),
146                _ => normalized.push(arg),
147            }
148        } else {
149            normalized.push(arg);
150        }
151    }
152    normalized
153}
154
155// Public parsing entry point used by lib::entry().
156pub fn parse_invocation(args: Option<Vec<String>>) -> Result<Invocation> {
157    // Reason for fallback: when caller passes None for explicit args (normal entrypoint), harvest process arguments directly from std::env::args().
158    let raw: Vec<String> = args.unwrap_or_else(|| env::args().collect());
159    let (kind, _remaining_args) =
160        subprocess::parse_subprocess_cli(raw.clone())?;
161    if let Some(kind) = kind {
162        environment::set_process_role(
163            environment::ProcessRole::ServiceSubprocess,
164        );
165        return Ok(Invocation::Subprocess(SubprocessArgs { kind, args: raw }));
166    }
167    let normalized = normalize_fsearch_flags(raw);
168    // Fallback: user CLI (fast path avoids evaluating dynamic format-table after_help LazyLocks)
169    let cli = match Cli::try_parse_from(&normalized) {
170        Ok(cli) => cli,
171        Err(_fast_err) => {
172            let mut full_cmd = Cli::command_with_help();
173            let matches = match full_cmd.try_get_matches_from_mut(normalized) {
174                Ok(m) => m,
175                Err(err) => err.exit(),
176            };
177            match <Cli as clap::FromArgMatches>::from_arg_matches(&matches) {
178                Ok(c) => c,
179                Err(err) => err.exit(),
180            }
181        }
182    };
183    if cli.command.is_some() {
184        environment::set_process_role(environment::ProcessRole::LightweightCli);
185    } else {
186        environment::set_process_role(environment::ProcessRole::WorkspaceMain);
187    }
188    Ok(Invocation::User(cli))
189}
190
191// -----------------------------------------------------------------------------
192// Regular (human CLI use or desktop app main process) CLI definition
193// -----------------------------------------------------------------------------
194
195#[derive(Parser, Debug)]
196#[command(
197    name = "ctoolbox",
198    version = ctb_build_info::ctb_version_display(),
199    about = "Collective Toolbox",
200    disable_help_subcommand = true
201)]
202pub struct Cli {
203    #[arg(long)]
204    pub ctoolbox_ipc_port: Option<u16>,
205
206    /// Skip automatic update checks on startup
207    #[arg(long)]
208    pub no_update: bool,
209
210    #[arg(
211        long,
212        conflicts_with = "use_system_tls_validator",
213        help = "Use bundled certificate roots for this run only"
214    )]
215    pub use_bundled_tls_validator: bool,
216
217    #[arg(
218        long,
219        conflicts_with = "use_bundled_tls_validator",
220        help = "Use the system certificate store for this run only"
221    )]
222    pub use_system_tls_validator: bool,
223
224    #[arg(long, help = "Skip CRLite revocation checking for this run only")]
225    pub insecure_skip_crlite_check: bool,
226
227    #[arg(
228        long,
229        default_value_t = invocation_settings::DEFAULT_RETRY_ON_HOST_ERROR,
230        help = "Number of retry attempts on DNS or host connection errors"
231    )]
232    pub retry_on_host_error: usize,
233
234    #[arg(
235        long,
236        global = true,
237        help = "Recover valid graph nodes and warn instead of failing on corrupted or inconsistent graph data"
238    )]
239    pub recover_graph: bool,
240
241    /// Print version information in JSON format and exit
242    #[arg(long, help = "Print version information in JSON format and exit")]
243    pub version_json: bool,
244
245    #[command(subcommand)]
246    pub command: Option<Command>,
247}
248
249impl Cli {
250    /// Builds the full [`clap::Command`] including dynamically generated format-table `after_help`.
251    #[must_use]
252    pub fn command_with_help() -> clap::Command {
253        routing::attach_dynamic_after_help(Self::command())
254    }
255}
256
257// ---------------------------
258// Lightweight Execution Gate
259// ---------------------------
260
261// Decides if we exit early.
262// Returns Ok(Some(exit_code)) if a lightweight command was executed.
263// Returns Ok(None) if we should proceed to heavy boot.
264// Errors bubble up as Err(...).
265pub async fn maybe_run_lightweight(cli: &Cli) -> Result<Option<i32>> {
266    if cli.version_json {
267        let info = ctb_build_info::build_info();
268        let formatted = serde_json::to_string_pretty(&info)?;
269        println!("{formatted}");
270        return Ok(Some(0));
271    }
272
273    let Some(cmd) = &cli.command else {
274        return Ok(None); // no command => proceed to full app
275    };
276
277    let result = run_lightweight_command(cmd).await?;
278    let exit_code = dispatch_tool_result(result).await?;
279    Ok(Some(exit_code))
280}
281
282// ---------------------------
283// Tool Result Abstractions
284// ---------------------------
285
286// Central dispatcher for writing a ToolResult to real stdio.
287async fn dispatch_tool_result(result: ToolResult) -> Result<i32> {
288    use std::io::{Write, stderr, stdout};
289
290    match result {
291        ToolResult::Immediate {
292            stdout: out,
293            stderr: err,
294            exit_code,
295        } => {
296            let mut so = stdout().lock();
297            let mut se = stderr().lock();
298            if !out.is_empty() {
299                so.write_all(&out)?;
300            }
301            if !err.is_empty() {
302                se.write_all(&err)?;
303            }
304            Ok(exit_code)
305        }
306        ToolResult::Streaming {
307            mut stream,
308            exit_code,
309        } => {
310            let mut so = stdout().lock();
311            let mut se = stderr().lock();
312            while let Some(chunk) = stream.next().await {
313                match chunk {
314                    OutputChunk::Stdout(d) => so.write_all(&d)?,
315                    OutputChunk::Stderr(d) => se.write_all(&d)?,
316                }
317            }
318            Ok(exit_code)
319        }
320    }
321}
322
323// ---------------------------
324// Shared Arg Structures
325// ---------------------------
326
327#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
328pub struct StringInput {
329    /// Input number(s) or string (supports quoted strings or multiple tokens).
330    #[arg(required = true, num_args = 1..)]
331    pub input: Vec<String>,
332}
333
334impl StringInput {
335    /// Joins input tokens into a single whitespace-delimited string.
336    #[must_use]
337    pub fn joined(&self) -> String {
338        self.input.join(" ")
339    }
340}
341
342// Utilities
343
344fn generate_help_bytes() -> Vec<u8> {
345    // Could introspect Clap auto-generated help if desired:
346    // let mut cmd = Cli::command();
347    // let mut buf = Vec::new();
348    // cmd.write_help(&mut buf).unwrap();
349    // buf
350    // Reason for fallback: when TTY help generation produces no output or fails, returning empty byte slice indicates no help text was rendered.
351    get_help_for_tty(get_width()).unwrap_or_default()
352}
353
354/// Return the width of the terminal
355pub fn get_width() -> u16 {
356    // Reason for fallback: when stdout is non-interactive (not a TTY) or terminal dimension query fails, 80 columns is standard default terminal width.
357    termsize::get().map_or(80, |s| s.cols)
358}
359
360/// Generate comprehensive markdown documentation for the ctoolbox CLI and all its subcommands.
361pub fn generate_cli_markdown_docs() -> String {
362    use std::fmt::Write as _;
363
364    let mut doc = String::new();
365    let _ = writeln!(doc, "# Collective Toolbox CLI Reference\n");
366    let _ = writeln!(
367        doc,
368        "This document is automatically generated from the `ctoolbox` CLI command definitions.\n"
369    );
370
371    let mut root_cmd = Cli::command_with_help();
372    root_cmd.build();
373
374    let mut root_help = Vec::new();
375    let _ = root_cmd.write_help(&mut root_help);
376    let root_help_str = String::from_utf8_lossy(&root_help);
377
378    let _ = writeln!(doc, "## Overview\n");
379    let _ = writeln!(doc, "```text\n{}\n```\n", root_help_str.trim());
380
381    let _ = writeln!(doc, "## Subcommands\n");
382
383    fn render_subcommands(
384        doc: &mut String,
385        cmd: &clap::Command,
386        parent_path: &str,
387    ) {
388        use std::fmt::Write as _;
389        let mut subcommands: Vec<_> = cmd.get_subcommands().collect();
390        subcommands.sort_by_key(|s| s.get_name());
391
392        for sub in subcommands {
393            let name = sub.get_name();
394            if name == "help" || sub.is_hide_set() {
395                continue;
396            }
397            let full_name = format!("{parent_path} {name}");
398            let _ = writeln!(doc, "### `{full_name}`\n");
399
400            if name == "warcat" {
401                let mut warcat_cmd = ctb_formats_warc::warcat_command();
402                warcat_cmd.build();
403                let mut warcat_help_buf = Vec::new();
404                let _ = warcat_cmd.write_help(&mut warcat_help_buf);
405                let warcat_help_str = String::from_utf8_lossy(&warcat_help_buf);
406
407                let _ =
408                    writeln!(doc, "```text\n{}\n```\n", warcat_help_str.trim());
409
410                render_subcommands(doc, &warcat_cmd, &full_name);
411            } else {
412                let mut sub_clone = sub.clone();
413                sub_clone.build();
414                let mut help_buf = Vec::new();
415                let _ = sub_clone.write_help(&mut help_buf);
416                let help_str = String::from_utf8_lossy(&help_buf);
417
418                let _ = writeln!(doc, "```text\n{}\n```\n", help_str.trim());
419
420                if sub.has_subcommands() {
421                    render_subcommands(doc, sub, &full_name);
422                }
423            }
424        }
425    }
426
427    render_subcommands(&mut doc, &root_cmd, "ctoolbox");
428    doc
429}
430
431#[cfg(test)]
432#[allow(
433    clippy::panic,
434    clippy::expect_used,
435    clippy::unwrap_used,
436    clippy::unwrap_in_result,
437    clippy::panic_in_result_fn,
438    clippy::indexing_slicing,
439    clippy::arithmetic_side_effects,
440    reason = "Standard repository test boilerplate"
441)]
442mod tests {
443    use super::*;
444
445    #[crate::ctb_test]
446    fn test_get_help_bytes() {
447        let help_bytes = generate_help_bytes();
448        assert!(String::from_utf8_lossy(&help_bytes).contains("## Synopsis"));
449    }
450
451    #[crate::ctb_test]
452    fn test_all_cli_commands_help_and_generate_docs() {
453        //bypass-tempdir-lint
454        // Assert that all clap options, subcommands, and flags are valid without panics
455        Cli::command_with_help().debug_assert();
456
457        let docs = generate_cli_markdown_docs();
458        assert!(docs.contains("ctoolbox adduser"));
459        assert!(docs.contains("ctoolbox base2base"));
460        assert!(docs.contains("ctoolbox range_gen"));
461        assert!(docs.contains("ctoolbox ia"));
462        assert!(docs.contains("ctoolbox warcat"));
463        assert!(docs.contains("ctoolbox warcat export"));
464        assert!(docs.contains("ctoolbox convert"));
465
466        // If running in repository workspace, ensure docs/cli/commands.generated.md is written / up to date
467        if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
468            let path = std::path::Path::new(&manifest_dir)
469                .join("../../docs/cli/commands.generated.md");
470            if let Some(parent) = path.parent() {
471                let _ = std::fs::create_dir_all(parent);
472            }
473            let _ = std::fs::write(&path, &docs);
474        }
475    }
476
477    #[crate::ctb_test("tokio")]
478    async fn test_convert_command_lightweight() {
479        let args = vec![
480            "ctoolbox".to_string(),
481            "convert".to_string(),
482            "--from".to_string(),
483            "dcal".to_string(),
484            "--to".to_string(),
485            "utf8".to_string(),
486            "72 101 108 108 111 ".to_string(),
487        ];
488        let invocation =
489            parse_invocation(Some(args)).expect("parse invocation");
490        let cli = invocation.expect_cli().expect("expect cli");
491        let exit_code = maybe_run_lightweight(cli)
492            .await
493            .expect("maybe_run_lightweight")
494            .expect("should return exit code for subcommand");
495        assert_eq!(exit_code, 0);
496    }
497
498    #[crate::ctb_test("tokio")]
499    async fn test_hex2bin_and_bin2hex_commands() {}
500
501    #[crate::ctb_test("tokio")]
502    async fn test_maybe_run_lightweight_with_options() {
503        let args = vec![
504            "ctoolbox".to_string(),
505            "--insecure-skip-crlite-check".to_string(),
506            "--recover-graph".to_string(),
507            "hex2dec".to_string(),
508            "1A 2B".to_string(),
509        ];
510        let invocation =
511            parse_invocation(Some(args)).expect("parse invocation");
512        let cli = invocation.expect_cli().expect("expect cli");
513        assert!(cli.insecure_skip_crlite_check);
514        assert!(cli.recover_graph);
515        assert!(cli.command.is_some());
516
517        let exit_code = maybe_run_lightweight(cli)
518            .await
519            .expect("maybe_run_lightweight")
520            .expect("should return exit code for subcommand");
521        assert_eq!(exit_code, 0);
522    }
523
524    #[crate::ctb_test("tokio")]
525    async fn test_version_json_flag() {
526        let args = vec!["ctoolbox".to_string(), "--version-json".to_string()];
527        let invocation =
528            parse_invocation(Some(args)).expect("parse invocation");
529        let cli = invocation.expect_cli().expect("expect cli");
530        assert!(cli.version_json);
531
532        let exit_code = maybe_run_lightweight(cli)
533            .await
534            .expect("maybe_run_lightweight")
535            .expect("should return exit code for --version-json");
536        assert_eq!(exit_code, 0);
537    }
538
539    // Don't add command-specific tests here! Any nontrivial logic should go in the associated crate, rather than this file and crate.
540    // This module and crate should be as small as possible, with any logic related to parsing and dispatching of commands implemented in the respective crates relevant to the functionality.
541}