ctb_cli/
routing.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//! Subcommand definitions and argument routing for the CLI.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29// Any nontrivial logic should go in the associated crate, rather than this file and crate.
30// 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.
31
32use anyhow::{Result, anyhow};
33use clap::Subcommand;
34use ctb_formats_stagel::convert::run_stagel_bootstrap_convert;
35use ctb_utilities::json::maybe_value::MaybeOption;
36use std::path::PathBuf;
37
38use crate::utilities::{
39    get_this_executable, spawn_detached, upgrade_in_place,
40    wait_for_ctoolbox_exit_and_clean_up,
41};
42use crate::{StringInput, generate_help_bytes};
43pub use ctb_formats_internetarchive::cli::IACommand;
44use ctb_formats_math::cli::{BaseArgs, run_base_convert, run_base2base};
45
46/// Return true if this is a command that can be run without booting.
47pub fn is_lightweight_command(command: &str) -> bool {
48    matches!(
49        command,
50        "adduser"
51            | "validate-docker-image"
52            | "csc"
53            | "archive"
54            | "csc-archive"
55            | "csc-verify"
56            | "cscv"
57            | "csc-diff"
58            | "fsindex"
59            | "fsearch"
60            | "csum"
61            | "compress"
62            | "decompress"
63            | "file"
64            | "detect"
65            | "file-detect"
66            | "base2base"
67            | "hex2dec"
68            | "dec2hex"
69            | "hexfmt"
70            | "hex2bin"
71            | "bin2hex"
72            | "ctb-asset-bundle-extract"
73            | "js-lint"
74            | "js-test"
75            | "gdb_instructions_generate"
76            | "ia"
77            | "pan2csv"
78            | "pan2macro"
79            | "pan2procedures"
80            | "panmacro2ast"
81            | "stagel-bootstrap-parse"
82            | "stagel-bootstrap-convert"
83            | "pan2parsejson"
84            | "file2metadatajson"
85            | "metadatajson2file"
86            | "pdf2txt"
87            | "pdf2json"
88            | "pdf2md"
89            | "warcat"
90            | "help"
91            | "ctb-dev-sign"
92            | "ctb-dev-gz-sha256"
93            | "ctb-dev-key-create"
94            | "ctb-dev-release-check"
95            | "ctb-dev-release-expire"
96            | "install"
97            | "make-offline-installer"
98            | "ts-check"
99            | "update"
100            | "uninstall"
101            | "ctb-upgrade-canary"
102            | "jq"
103            | "json-escape"
104            | "dceutils_php_to_csv"
105            | "x86-instruction-sets"
106            | "range_gen"
107            | "range-gen"
108            | "hexdump"
109            | "hd"
110            | "xxd"
111            | "short-dc"
112            | "short_dc"
113            | "shortdc"
114            | "gid"
115            | "graph-id"
116            | "graph_id"
117            | "explain-ctbnodes"
118            | "character_description"
119            | "character-description"
120            | "chardesc"
121            | "convert"
122            | "run"
123    )
124}
125
126macro_rules! note_continuous_hex {
127    () => {
128        "Continuous Hex vs. Byte Streams:\n  Continuous hex strings (e.g. \"deadbeef\") are parsed as a single large scalar\n  integer (3735928559). Pass `--bytes` to chunk them into individual byte values (0..=255)."
129    };
130}
131
132macro_rules! note_stdin {
133    () => {
134        "Note on Stdin:\n  This command expects arguments and does not read standard input (stdin)."
135    };
136}
137
138#[derive(Subcommand, Debug)]
139pub enum Command {
140    /// Register a new non-administrator local user
141    #[command(name = "adduser")]
142    AddUser {
143        /// Username for the new non-administrator account
144        username: String,
145        /// Read password from stdin even if running interactively
146        #[arg(long = "password-stdin")]
147        password_stdin: bool,
148    },
149    /// Wait for the provided PID to shutdown, then clean up
150    #[command(name = "waitshutdown")]
151    WaitShutdown {
152        /// Process ID to wait for
153        #[arg(long)]
154        pid: u32,
155    },
156    /// Wait for the provided PID to shutdown, then start ctoolbox with the
157    /// given port
158    #[command(name = "waitrestart")]
159    WaitRestart {
160        /// Process ID to wait for
161        #[arg(long)]
162        pid: u32,
163        /// Port to pass to the new ctoolbox instance
164        #[arg(long)]
165        port: u16,
166    },
167    /// Wait for the provided PID to shutdown, then upgrade the ctoolbox
168    /// instance in place, then restart it. (Will need to copy the executable
169    /// before upgrading it probably because Windows locks running executables.)
170    #[command(name = "waitupgrade")]
171    WaitUpgrade {
172        /// Process ID to wait for
173        #[arg(long)]
174        pid: u32,
175        /// Path to the temporary file holding the new ctoolbox executable
176        #[arg(long)]
177        temp_path: PathBuf,
178        /// Path to the installed ctoolbox executable
179        #[arg(long)]
180        target_path: PathBuf,
181        /// Port to pass to the new ctoolbox instance
182        #[arg(long)]
183        port: u16,
184    },
185    /// Convert delimited numbers between positional radix numeral systems
186    /// (bases 1..=36, or up to 64 with `--output-alphabet base64_standard`).
187    ///
188    /// NOTE: This performs mathematical place-value conversion on numbers,
189    /// not raw binary data armoring. For file or byte stream encoding, see
190    /// `bin2hex` and `hex2bin`. See also `hexdump`.
191    ///
192    /// NOTE: This command expects arguments and does not read standard input.
193    #[command(
194        name = "base2base",
195        after_help = concat!(
196            "Examples:\n  $ ctoolbox base2base 10 16 \"255 16 10\"\n  ff 10 a\n\n  $ ctoolbox base2base 10 16 255 16 10\n  ff 10 a\n\n  $ ctoolbox base2base 2 10 \"1101 1010\"\n  13 10\n\n  $ ctoolbox base2base 16 2 --prefix \"0b\" 1f 2a\n  0b11111 0b101010\n\n  $ ctoolbox base2base 10 16 --bytes 255 128\n  ff 80\n\n  $ ctoolbox base2base 10 64 \"0 1 63 64 255\" --output-alphabet base64_standard\n  A B / BA D/\n\nNote on Base 64 vs. Data Armor:\n  This command converts numbers in a mathematical base-64 radix (e.g. 255 -> D/).\n  To encode raw binary files or octet streams using RFC 4648 Base64 (where 0xFF -> /w==),\n  use a data armoring tool.\n\n",
197            note_continuous_hex!(),
198            "\n\n",
199            note_stdin!()
200        )
201    )]
202    Base2Base {
203        /// All positional arguments for custom parsing
204        #[arg(required = true)]
205        args: Vec<String>,
206        #[command(flatten)]
207        base_args: BaseArgs,
208    },
209    /// Convert from hexadecimal to decimal.
210    ///
211    /// NOTE: Continuous hex strings (e.g. "deadbeef") are parsed as a single
212    /// large scalar integer (3735928559). Pass `--bytes` to chunk into byte
213    /// values (222 173 190 239).
214    ///
215    /// NOTE: This command expects arguments and does not read standard input.
216    #[command(
217        name = "hex2dec",
218        after_help = concat!(
219            "Examples:\n  $ ctoolbox hex2dec 1A 2B 3C\n  26 43 60\n\n  $ ctoolbox hex2dec \"0x1A 0x2B\"\n  26 43\n\n  $ ctoolbox hex2dec -s \", \" FF 80 00\n  255, 128, 0\n\n  $ ctoolbox hex2dec deadbeef\n  3735928559\n\n  $ ctoolbox hex2dec --bytes deadbeef\n  222 173 190 239\n\n",
220            note_continuous_hex!(),
221            "\n\n",
222            note_stdin!()
223        )
224    )]
225    Hex2Dec {
226        #[command(flatten)]
227        string_input: StringInput,
228        #[command(flatten)]
229        base_args: BaseArgs,
230    },
231    /// Convert from decimal to hexadecimal.
232    ///
233    /// NOTE: This command expects arguments and does not read standard input.
234    #[command(
235        name = "dec2hex",
236        after_help = concat!(
237            "Examples:\n  $ ctoolbox dec2hex 255 128 64\n  ff 80 40\n\n  $ ctoolbox dec2hex --prefix \"0x\" 10 20 30\n  0xa 0x14 0x1e\n\n  $ ctoolbox dec2hex --bytes 255 16\n  ff 10\n\n",
238            note_continuous_hex!(),
239            "\n\n",
240            note_stdin!()
241        )
242    )]
243    Dec2Hex {
244        #[command(flatten)]
245        string_input: StringInput,
246        #[command(flatten)]
247        base_args: BaseArgs,
248    },
249    /// Reformat hexadecimal number strings (delimiters, prefixes, case, padding).
250    ///
251    /// NOTE: This formats lists of hexadecimal numbers (not hexdump outputs with
252    /// line offsets or ASCII sidebars). For generating or formatting actual
253    /// hexdumps, see `hexdump` (or `hd` / `xxd`).
254    ///
255    /// NOTE: Continuous hex strings (e.g. "1a2b3c4d") are treated as a single
256    /// number unless `--bytes` or `--limit` is passed.
257    ///
258    /// NOTE: This command expects arguments and does not read standard input.
259    #[command(
260        name = "hexfmt",
261        after_help = concat!(
262            "Examples:\n  $ ctoolbox hexfmt 1a 2b 3c 4d\n  1a 2b 3c 4d\n\n  $ ctoolbox hexfmt -s \", \" 1a 2b 3c 4d\n  1a, 2b, 3c, 4d\n\n  $ ctoolbox hexfmt --prefix \"0x\" 1a 2b\n  0x1a 0x2b\n\n  $ ctoolbox hexfmt --bytes \"deadbeef\"\n  de ad be ef\n\nNote on Hexdumps vs. Number Formatting:\n  This tool reformats hexadecimal numbers. To inspect or format raw binary\n  data or files as hexdumps, use `ctoolbox hexdump` (or `xxd`).\n\n",
263            note_stdin!()
264        )
265    )]
266    Hexfmt {
267        #[command(flatten)]
268        string_input: StringInput,
269        #[command(flatten)]
270        base_args: BaseArgs,
271    },
272    /// Convert a hexadecimal string to binary data
273    #[command(
274        name = "hex2bin",
275        after_help = "Examples:\n  $ ctoolbox hex2bin \"48656c6c6f\"\n  Hello\n\n  $ echo \"48 65 6c 6c 6f\" | ctoolbox hex2bin\n  Hello\n\n  $ ctoolbox hex2bin -f file.hex -o file.bin\n  $ ctoolbox hex2bin \"48656c6c6f\" > output.bin"
276    )]
277    Hex2Bin(ctb_formats_hexdump::cli::Hex2BinArgs),
278    /// Convert binary data to a hexadecimal string or hex dump
279    #[command(
280        name = "bin2hex",
281        after_help = "Examples:\n  $ ctoolbox bin2hex \"Hello\"\n  48656c6c6f\n\n  $ echo -n \"Hello\" | ctoolbox bin2hex\n  48656c6c6f\n\n  $ cat file.exe | ctoolbox bin2hex\n  4d5a...\n\n  $ ctoolbox bin2hex -f file.bin -o file.hex\n  $ ctoolbox bin2hex --hd -f file.bin\n  $ ctoolbox bin2hex --hf \"Hello\"\n  $ ctoolbox bin2hex --xxd \"Hello\""
282    )]
283    Bin2Hex(ctb_formats_hexdump::cli::Bin2HexArgs),
284    /// Format binary data as a hex dump (fancy by default, or --plain / --xxd)
285    #[command(
286        name = "hexdump",
287        alias = "hd",
288        after_help = "Examples:\n  $ ctoolbox hexdump \"Hello\"\n  $ ctoolbox hd -f file.bin\n  $ ctoolbox hexdump --plain \"Hello\"\n  $ ctoolbox hexdump --xxd \"Hello\""
289    )]
290    Hexdump(ctb_formats_hexdump::cli::HexDumpArgs),
291    /// Format binary data as an xxd hex dump
292    #[command(
293        name = "xxd",
294        after_help = "Examples:\n  $ ctoolbox xxd \"Hello\"\n  $ echo -n \"Hello\" | ctoolbox xxd\n  $ ctoolbox xxd -f file.bin -o file.hex\n  $ ctoolbox xxd --plain \"Hello\"\n  $ ctoolbox xxd --fancy \"Hello\""
295    )]
296    Xxd(ctb_formats_hexdump::cli::XxdArgs),
297    /// Convert Document Character (Dc) shorthand to Global Graph ID or show metadata
298    #[command(
299        name = "short-dc",
300        alias = "short_dc",
301        alias = "shortdc",
302        after_help = "Examples:\n  $ ctoolbox short-dc 296\n  1114408\n\n  $ ctoolbox short-dc f80\n  2228304\n\n  $ ctoolbox short-dc -i 296"
303    )]
304    ShortDc(ctb_formats_dcstring::cli_identifiers::ShortDcArgs),
305    /// Convert Global Graph ID to short representation or show full metadata
306    #[command(
307        name = "gid",
308        alias = "graph-id",
309        alias = "graph_id",
310        after_help = "Examples:\n  $ ctoolbox gid --s 1114408\n  dc:296\n\n  $ ctoolbox gid -i 1114408"
311    )]
312    Gid(ctb_formats_dcstring::cli_identifiers::GidArgs),
313    /// Render a .ctbnodes ledger file with synthesized human-readable explanation comments
314    #[command(name = "explain-ctbnodes")]
315    ExplainCtbnodes(ctb_formats_dcstring::cli_identifiers::ExplainCtbnodesArgs),
316    /// Generate a range of numbers in various bases
317    #[command(
318        name = "range_gen",
319        alias = "range-gen",
320        after_help = "Examples:\n  $ ctoolbox range_gen 1 10\n  1\n  2\n  3\n  4\n  5\n  6\n  7\n  8\n  9\n  10\n\n  $ ctoolbox range_gen -s 2 1 10\n  1\n  3\n  5\n  7\n  9\n\n  $ ctoolbox range_gen -b 16 -t -S, 18D0C 18D12\n  18D0C,18D0D,18D0E,18D0F,18D10,18D11,18D12,\n\n  $ ctoolbox range_gen -b hex 0x00 0x10\n  00\n  01\n  02\n  03\n  04\n  05\n  06\n  07\n  08\n  09\n  0A\n  0B\n  0C\n  0D\n  0E\n  0F\n  10"
321    )]
322    RangeGen(ctb_formats_math::range_generator::RangeGenArgs),
323    /// Describe Unicode characters, Dcs, and Graph IDs with annotations, aliases, and meanings. This feature may be changed or simplified in future.
324    #[command(
325        name = "character_description",
326        alias = "character-description",
327        alias = "chardesc"
328    )]
329    CharacterDescription(ctb_formats_conversion::cli::CharacterDescriptionArgs),
330    /// Convert documents or text between supported formats
331    #[command(name = "convert")]
332    Convert(ctb_formats_conversion::cli::ConvertArgs),
333    /// Generate GDB instructions from symbols
334    #[command(name = "gdb_instructions_generate")]
335    GdbInstructionsGenerate {},
336    /// Analyze an x86/x64 object or archive file and list CPU instruction set features
337    #[command(name = "x86-instruction-sets")]
338    X86InstructionSets {
339        /// Path to the object or archive file
340        path: PathBuf,
341    },
342    /// Internet Archive utilities.
343    #[command(name = "ia")]
344    IA {
345        #[command(subcommand)]
346        command: IACommand,
347    },
348    /// Convert a .pan file to CSV format (writes to stdout)
349    #[command(name = "pan2csv")]
350    Pan2Csv {
351        /// Format data using Panorama output patterns (also strips subsequent lines of text fields by default)
352        #[arg(long, short = 'p')]
353        patterns: bool,
354        /// When formatting with patterns, keep full multiline text strings instead of truncating at first newline
355        #[arg(long = "keep-multiline")]
356        keep_multiline: bool,
357        /// Include CSV header row with field names (default: true)
358        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
359        header: bool,
360        /// Do not include CSV header row (alias for --header=false)
361        #[arg(long = "no-header")]
362        no_header: bool,
363        /// Export delimiter / format: commas (default), tabs, tabs-no-quotes, wordperfect
364        #[arg(long, short = 'd', default_value = "commas")]
365        delimiter: String,
366        /// Output character encoding (utf8, mac, windows)
367        #[arg(long, default_value = "utf8")]
368        encoding: String,
369        /// Line terminator: crlf (\r\n) or lf (\n)
370        #[arg(long)]
371        crlf: bool,
372        /// Replicate export inconsistencies and legacy double-encoding behavior
373        #[arg(long = "replicate-double-encoding")]
374        replicate_double_encoding: bool,
375        /// Run the startup procedure (.Initialize) before exporting CSV
376        #[arg(long = "run-startup-procedure")]
377        run_startup_procedure: bool,
378        /// Input PAN file path
379        pan_file: PathBuf,
380    },
381    /// Parse a StageL file to token output
382    #[command(name = "stagel-bootstrap-parse")]
383    StagelBootstrapParse {
384        /// Input StageL file path
385        input_file: PathBuf,
386    },
387    /// Translate a StageL file using the bootstrap compiler
388    #[command(name = "stagel-bootstrap-convert")]
389    StagelBootstrapConvert {
390        /// Optional cache directory (if specified, enables caching)
391        #[arg(long)]
392        cache_dir: Option<PathBuf>,
393        /// Disable debug build
394        #[arg(long)]
395        no_debug: bool,
396        /// Disable runtime type checks
397        #[arg(long)]
398        no_runtime_type_checks: bool,
399        /// Input StageL file path
400        input_file: PathBuf,
401        /// Target language (js or bash)
402        target_lang: String,
403    },
404    /// Convert a .pan file to JSON of parse (writes to stdout)
405    #[command(name = "pan2parsejson")]
406    Pan2ParseJson {
407        /// Input PAN file path
408        pan_file: PathBuf,
409    },
410    /// Extract a macro/procedure from a .pan file (writes to stdout)
411    #[command(name = "pan2macro")]
412    Pan2Macro {
413        /// Output character encoding (mac, windows, utf8)
414        #[arg(long, default_value = "windows")]
415        encoding: String,
416        /// Input PAN file path
417        pan_file: PathBuf,
418        /// Name of the macro/procedure to extract
419        macro_name: String,
420    },
421    /// Export procedures from a .pan file into a directory of individual procedure files
422    #[command(name = "pan2procedures")]
423    Pan2Procedures {
424        /// Optional output directory (defaults to <`pan_stem`>_procedures)
425        #[arg(long, short = 'o')]
426        output_dir: Option<PathBuf>,
427        /// Optional procedure file extension (e.g. "estes", defaults to no extension)
428        #[arg(long, short = 'e')]
429        extension: Option<String>,
430        /// Output character encoding (utf8, mac, windows)
431        #[arg(long, default_value = "utf8")]
432        encoding: String,
433        /// Input PAN file path
434        pan_file: PathBuf,
435    },
436    /// Parse a macro/procedure into AST JSON from a macro code file (or whole .pan database if `macro_name` is provided) and write to stdout
437    #[command(name = "panmacro2ast")]
438    PanMacro2Ast {
439        /// Input character encoding (utf-8, macroman, win-1252 / windows)
440        #[arg(
441            long = "input-encoding",
442            short = 'i',
443            default_value = "macroman"
444        )]
445        input_encoding: String,
446        /// Output character encoding (utf-8, macroman, win-1252 / windows)
447        #[arg(long = "output-encoding", short = 'o', default_value = "utf-8")]
448        output_encoding: String,
449        /// Input file path (macro code file, or PAN database file if `macro_name` is given, or - for stdin)
450        input_file: PathBuf,
451        /// Optional name of the macro/procedure (if provided, `input_file` is parsed as a whole .pan database)
452        macro_name: Option<String>,
453    },
454    /// Convert a PDF file to text output. Not yet implemented.
455    #[command(name = "pdf2txt")]
456    Pdf2Txt {
457        /// Input PDF file path (or - for stdin)
458        pdf_file: PathBuf,
459    },
460    /// Convert a PDF file to JSON output. Not yet implemented.
461    #[command(name = "pdf2json")]
462    Pdf2Json {
463        /// Input PDF file path (or - for stdin)
464        pdf_file: PathBuf,
465    },
466    /// Convert a PDF file to Markdown output. Not yet implemented.
467    #[command(name = "pdf2md")]
468    Pdf2Md {
469        /// Input PDF file path (or - for stdin)
470        pdf_file: PathBuf,
471    },
472    /// Read a file and export comprehensive metadata from io/file to JSON
473    #[command(name = "file2metadatajson")]
474    File2MetadataJson {
475        /// Include file body content (base64-encoded) in JSON
476        #[arg(long)]
477        body: bool,
478
479        /// Omit extended attributes, resource forks, and alternate streams
480        #[arg(long)]
481        no_streams: bool,
482
483        /// Input file path to inspect
484        file: PathBuf,
485    },
486    /// Read file metadata JSON and rematerialize the file to the given path
487    #[command(name = "metadatajson2file")]
488    MetadataJson2File {
489        /// Overwrite existing destination file or directory metadata
490        #[arg(long)]
491        overwrite: bool,
492
493        /// Permit creating special files (FIFOs, character/block devices)
494        #[arg(long = "copy-specials-as-specials")]
495        copy_specials_as_specials: bool,
496
497        /// Proceed best-effort if destination filesystem cannot reproduce all metadata
498        #[arg(long = "best-effort-metadata")]
499        best_effort_metadata: bool,
500
501        /// Path to metadata JSON file (or - for stdin)
502        metadata_file: PathBuf,
503
504        /// Destination path to rematerialize the file to
505        path: PathBuf,
506    },
507    /// WARC archiving tool
508    #[command(
509        name = "warcat",
510        trailing_var_arg = true,
511        allow_hyphen_values = true,
512        disable_help_flag = true
513    )]
514    Warcat {
515        /// Arguments passed to warcat
516        args: Vec<String>,
517    },
518    /// Extract a ctoolbox asset bundle to a directory tree.
519    #[command(name = "ctb-asset-bundle-extract")]
520    CtbAssetBundleExtract {
521        /// Path to the `.rsrc` asset bundle.
522        bundle_path: PathBuf,
523        /// Output directory for the extracted assets. Defaults to the current directory. The bundle name will be appended as a subdirectory, such as extracting to a folder `test` will place the extracted files within `test/bundle_v3-extracted/`.
524        output_dir: Option<PathBuf>,
525    },
526    /// Lint JavaScript and TypeScript sources.
527    #[command(name = "js-lint")]
528    JsLint {
529        #[command(flatten)]
530        cli: ctb_formats_javascript::js_lint::JsLintCli,
531    },
532    /// Type-check TypeScript code.
533    #[command(name = "ts-check")]
534    TsCheck {
535        #[command(flatten)]
536        args: ctb_formats_javascript::ts_check::TsCheckArgs,
537    },
538    /// Run JavaScript tests.
539    #[command(name = "js-test")]
540    JsTest {
541        #[command(flatten)]
542        args: ctb_formats_javascript::js_test::JsTestArgs,
543    },
544    /// Run the embedded Python interpreter or execute Python scripts.
545    #[command(
546        name = "python",
547        trailing_var_arg = true,
548        allow_hyphen_values = true
549    )]
550    Python(ctb_formats_python::cli::PythonArgs),
551    /// Validate a docker save image tarball
552    #[command(name = "validate-docker-image")]
553    ValidateDockerImage {
554        /// Tarball file path (or - for stdin)
555        #[arg(value_name = "FILE")]
556        file: Option<PathBuf>,
557        /// Fail if any unreferenced blobs are present in blobs/
558        #[arg(long)]
559        strict: bool,
560    },
561    /// Checksummed copy with rsync-compatible path resolution and an extra verification step
562    #[command(name = "csc")]
563    Csc(ctb_io_csc::args::CscArgs),
564    /// Create, list, verify, or extract a self-contained CSC archive.
565    #[command(name = "archive", alias = "csc-archive")]
566    Archive(ctb_io_csc::archive::cli::ArchiveArgs),
567    /// Copy files or directories with an extra verification step (alias for `csc --delete-manifest-after`)
568    #[command(name = "cp")]
569    Cp(ctb_io_csc::args::CscArgs),
570    /// Move files or directories without copying when possible, or run verified cross-device copy
571    #[command(name = "mv")]
572    Mv(ctb_io_csc::args::MvArgs),
573    /// Verify a directory against a manifest recorded by csc
574    #[command(name = "csc-verify", alias = "cscv")]
575    CscVerify(ctb_io_csc::args::CscVerifyArgs),
576    /// Compare two filesystem paths with the same verification strictness and logic as csc
577    #[command(name = "csc-diff")]
578    CscDiff(ctb_io_csc::args::CscDiffArgs),
579    /// Index a directory or csc manifest for quick searching
580    #[command(name = "fsindex")]
581    Fsindex(ctb_io_csc::args::FsindexArgs),
582    /// Fast indexed search against a .cscindex.sqlite database
583    #[command(name = "fsearch")]
584    Fsearch(ctb_io_csc::args::FsearchArgs),
585    /// Calculate checksum for a file or stdin
586    #[command(name = "csum")]
587    Csum {
588        /// Hash algorithm type (`sha256`, `xxh32`, `xxh64`, `xxh3`, `xxh128`)
589        algo: ctb_formats_checksum::HashAlgorithm,
590        /// Input file path (or - for stdin)
591        #[arg(default_value = "-")]
592        file: PathBuf,
593        /// Prefix the output hex string with 0x
594        #[arg(long = "prefix-0x")]
595        prefix_0x: bool,
596    },
597    /// Compress a file or stdin using single-stream compression format
598    #[command(name = "compress")]
599    Compress(ctb_formats_compression_cli::CliCompressArgs),
600    /// Decompress a compressed file or stdin
601    #[command(name = "decompress")]
602    Decompress {
603        /// Optional compression format (e.g. `br`, `gz`, `deflate`, `zlib`). If omitted, detected from file extension or magic bytes.
604        format: Option<String>,
605        /// Input file path (or - for stdin)
606        #[arg(default_value = "-")]
607        file: PathBuf,
608        /// Output file path or - for stdout. Defaults to stdout when input is stdin, or strips the compression extension (or appends `.decompressed` if none recognized) when decompressing a file.
609        #[arg(
610            short = 'o',
611            long = "output",
612            alias = "file",
613            value_name = "OUTPUT"
614        )]
615        output: Option<PathBuf>,
616        /// Force overwrite of existing destination file without confirmation
617        #[arg(long = "force")]
618        force: bool,
619    },
620    /// Detect format, MIME type, and characteristics of files (like `file`)
621    #[command(name = "file", alias = "detect", alias = "file-detect")]
622    File(ctb_formats_detection::cli::FileDetectionArgs),
623    /// Process a file using wfparser logic
624    #[command(name = "wfparser")]
625    Wfparser {
626        /// Input file path (or - for stdin)
627        #[arg(default_value = "-")]
628        file: PathBuf,
629    },
630    /// Process a file using wfscan logic
631    #[command(name = "wfscan")]
632    Wfscan {
633        /// Input file path (or - for stdin)
634        #[arg(default_value = "-")]
635        file: PathBuf,
636    },
637    /// Convert PHP data file arrays to CSV files
638    #[command(name = "dceutils_php_to_csv")]
639    DceutilsPhpToCsv {
640        /// Path to the PHP data file
641        php_file: PathBuf,
642    },
643    /// Show help
644    Help,
645    /// Unimplemented, just an example
646    ShowNode {
647        /// Example parameter
648        #[arg(short, long)]
649        id: i128,
650    },
651    /// Sign release artifacts for distribution (developer command)
652    #[command(name = "ctb-dev-sign")]
653    DevSign {
654        /// Directory containing release artifacts to sign.
655        /// Defaults to ~/ctb_release/input if not specified.
656        #[expect(
657            clippy::doc_markdown,
658            reason = "doc comment references local path conventions"
659        )]
660        #[arg(long)]
661        input_dir: Option<PathBuf>,
662        /// Directory to write signed chunks and manifest.
663        /// Defaults to ~/ctb_release/releases if not specified.
664        #[expect(
665            clippy::doc_markdown,
666            reason = "doc comment references local path conventions"
667        )]
668        #[arg(long)]
669        output_dir: Option<PathBuf>,
670        /// Target for this release (e.g. linux-x64, linux-x86, windows-x64,
671        /// mac-x64, mac-arm64).
672        /// Defaults to current platform if not specified.
673        #[arg(long)]
674        platform: Option<String>,
675    },
676    /// Compress a tar file with the server's gzip settings and print its SHA256 hex (developer command)
677    #[command(name = "ctb-dev-gz-sha256")]
678    DevGzSha256 {
679        /// Path to the tar file
680        path: PathBuf,
681    },
682
683    /// Generate a signing keypair for `ctb-dev-sign`.
684    ///
685    /// If `--write` is provided, writes the generated keys into local
686    /// `pc_settings.json` as `dev_signing_private_key` and
687    /// `dev_signing_public_key`.
688    #[command(name = "ctb-dev-key-create")]
689    DevKeyCreate {
690        /// Write keys into local `pc_settings.json`.
691        #[arg(long)]
692        write: bool,
693    },
694    /// Verify an uploaded release: check signature and chunk hashes
695    #[command(name = "ctb-dev-release-check")]
696    DevReleaseCheck {
697        /// Path to the manifest file to verify.
698        /// Defaults to `{storage_dir}/releases/ctb-{platform}-latest.json` if
699        /// not specified.
700        #[arg(long)]
701        manifest: Option<PathBuf>,
702        /// Path to the chunks directory.
703        /// Defaults to `{storage_dir}/releases/bh/` if not specified.
704        #[arg(long)]
705        chunks_dir: Option<PathBuf>,
706
707        /// Target(s) to verify (e.g. `linux-x64,linux-x86,windows-x64,freebsd-x64`).
708        /// May be specified multiple times or comma-separated; defaults to the
709        /// current platform.
710        #[arg(long, value_delimiter = ',')]
711        platform: Vec<String>,
712    },
713    /// Delete old release chunks and manifests to reclaim disk space.
714    ///
715    /// Scans the releases directory for manifest files, builds a set of all
716    /// chunk hashes referenced by manifests newer than the threshold, then
717    /// deletes any chunks not in the keep set along with old manifest files.
718    #[command(name = "ctb-dev-release-expire")]
719    DevReleaseExpire {
720        /// Only expire chunks from releases older than this many days.
721        /// Defaults to 30 days if not specified.
722        #[arg(long, default_value = "30")]
723        older_than: u32,
724        /// Path to the releases directory.
725        /// Defaults to `{storage_dir}/releases/` if not specified.
726        #[arg(long)]
727        releases_dir: Option<PathBuf>,
728    },
729    /// Launch the installer GUI (or TUI if --no-gui).
730    ///
731    /// Installs from files in the current directory if present, otherwise
732    /// downloads from the update server.
733    Install {
734        /// Use text-mode installer instead of GUI.
735        #[arg(long)]
736        no_gui: bool,
737        /// Run in unattended mode with default options (implies --no-gui).
738        #[arg(long)]
739        unattended: bool,
740    },
741    /// Download and package the latest offline installer bundle.
742    #[command(name = "make-offline-installer")]
743    MakeOfflineInstaller {
744        /// Output path for the generated bundle.
745        output: PathBuf,
746        /// Target platform to fetch. Defaults to the current platform.
747        #[arg(long)]
748        platform: Option<String>,
749        /// Release version to fetch. Defaults to latest.
750        #[arg(long)]
751        version: Option<String>,
752        /// URL of the update server.
753        /// Defaults to the configured server URL.
754        #[arg(long)]
755        server_url: Option<String>,
756    },
757    /// Check for updates and optionally apply them.
758    ///
759    /// By default, prompts the user if an update is available. Use
760    /// --unattended to automatically apply updates without prompting.
761    Update {
762        /// Automatically apply updates without prompting.
763        #[arg(long)]
764        unattended: bool,
765        /// URL of the update server.
766        /// Defaults to the configured server URL.
767        #[arg(long)]
768        server_url: Option<String>,
769    },
770    /// Uninstall ctoolbox from this system.
771    ///
772    /// Reads installation.json to determine installed files, removes them,
773    /// removes the desktop entry, and removes PATH modifications.
774    Uninstall {
775        /// Use text-mode uninstaller instead of GUI.
776        #[arg(long)]
777        no_gui: bool,
778        /// Run without prompting for confirmation.
779        #[arg(long)]
780        unattended: bool,
781    },
782    /// Internal: Post-upgrade canary validation.
783    ///
784    /// This command is run by the new binary after an upgrade. If the process
785    /// survives 30 seconds, the backup is deleted and the process exits. If
786    /// it crashes, the caller's watchdog logic restores the backup.
787    #[command(name = "ctb-upgrade-canary")]
788    UpgradeCanary {
789        /// Path to the backup copy of the previous binary.
790        #[arg(long)]
791        backup_path: PathBuf,
792        /// Path to the installed binary location.
793        #[arg(long)]
794        target_path: PathBuf,
795        /// Optional port to restart ctoolbox with after successful validation.
796        #[arg(long)]
797        port: Option<u16>,
798    },
799    /// Lightweight JQ implementation
800    #[command(name = "jq")]
801    Jq {
802        /// Use raw output (no quotes around strings)
803        #[arg(short = 'r', long = "raw-output")]
804        raw_output: bool,
805        /// The JQ query string
806        query: String,
807        /// Optional path to the JSON file, or - for stdin
808        file: Option<PathBuf>,
809    },
810    /// Escape a string to be a valid JSON string value (enclosed in double
811    /// quotes).
812    #[command(name = "json-escape")]
813    JsonEscape {
814        /// The string to escape. If not provided, reads from stdin.
815        value: Option<String>,
816    },
817    /// Compile, execute, and render a Document Character (Dc) document or StageL 3 / StageR 3 program.
818    #[command(name = "run")]
819    Run(ctb_runtime::cli::RunArgs),
820}
821
822/// Attaches dynamically generated format-table `after_help` strings on demand
823/// when rendering `--help` output or CLI documentation.
824#[must_use]
825pub fn attach_dynamic_after_help(cmd: clap::Command) -> clap::Command {
826    cmd.mut_subcommand("character_description", |sub| {
827        sub.after_help(
828            ctb_formats_conversion::cli::CHARACTER_DESCRIPTION_AFTER_HELP
829                .as_str(),
830        )
831    })
832    .mut_subcommand("convert", |sub| {
833        sub.after_help(ctb_formats_conversion::cli::CONVERT_AFTER_HELP.as_str())
834    })
835    .mut_subcommand("csum", |sub| {
836        sub.after_help(ctb_formats_checksum::CSUM_AFTER_HELP.as_str())
837    })
838    .mut_subcommand("compress", |sub| {
839        sub.after_help(ctb_formats_compression::COMPRESSION_AFTER_HELP.as_str())
840    })
841    .mut_subcommand("decompress", |sub| {
842        sub.after_help(ctb_formats_compression::COMPRESSION_AFTER_HELP.as_str())
843    })
844    .mut_subcommand("run", |sub| {
845        sub.after_help(ctb_runtime::cli::RUN_AFTER_HELP.as_str())
846    })
847}
848
849fn read_file_or_stdin(path: &std::path::Path) -> Result<Vec<u8>> {
850    use std::io::Read;
851    if path.to_str() == Some("-") {
852        let mut buf = Vec::new();
853        std::io::stdin()
854            .lock()
855            .read_to_end(&mut buf)
856            .context("Failed to read from stdin")?;
857        Ok(buf)
858    } else {
859        std::fs::read(path).with_context(|| {
860            format!(
861                "Could not read file: {path_display}",
862                path_display = path.display()
863            )
864        })
865    }
866}
867
868fn check_overwrite_prompt(path: &std::path::Path, force: bool) -> Result<bool> {
869    use std::io::IsTerminal;
870    if force || path == std::path::Path::new("-") || !path.exists() {
871        return Ok(true);
872    }
873    if std::io::stdin().is_terminal() {
874        eprint!(
875            "Output file '{path_display}' already exists. Overwrite? [y/N] ",
876            path_display = path.display()
877        );
878        let mut response = String::new();
879        std::io::stdin().read_line(&mut response)?;
880        let trimmed = response.trim().to_ascii_lowercase();
881        if trimmed != "y" && trimmed != "yes" {
882            return Ok(false);
883        }
884    }
885    Ok(true)
886}
887
888// ---------------------------
889// Command Execution
890// ---------------------------
891
892#[expect(
893    clippy::too_many_lines,
894    reason = "uniform tool command router is naturally long"
895)]
896pub async fn run_lightweight_command(cmd: &Command) -> Result<ToolResult> {
897    match cmd {
898        Command::AddUser {
899            username,
900            password_stdin,
901        } => ctb_storage::cli::adduser(username, *password_stdin),
902        Command::WaitShutdown { pid } => {
903            wait_for_ctoolbox_exit_and_clean_up(*pid);
904            Ok(ToolResult::immediate_ok(Vec::new()))
905        }
906        Command::WaitRestart { pid, port } => {
907            wait_for_ctoolbox_exit_and_clean_up(*pid);
908            spawn_detached(
909                &get_this_executable()?,
910                ["--ctoolbox-ipc-port", port.to_string().as_str()],
911            )?;
912            Ok(ToolResult::immediate_ok(Vec::new()))
913        }
914        Command::WaitUpgrade {
915            pid,
916            temp_path,
917            target_path,
918            port,
919        } => {
920            wait_for_ctoolbox_exit_and_clean_up(*pid);
921            upgrade_in_place(temp_path, target_path)?;
922            spawn_detached(
923                target_path,
924                ["--ctoolbox-ipc-port", port.to_string().as_str()],
925            )?;
926            Ok(ToolResult::immediate_ok(Vec::new()))
927        }
928        Command::Base2Base { args, base_args } => {
929            run_base2base(args, base_args)
930        }
931        Command::Hex2Dec {
932            string_input,
933            base_args,
934        } => run_base_convert(
935            &Some(16),
936            &Some(10),
937            &string_input.joined(),
938            base_args,
939        ),
940        Command::Dec2Hex {
941            string_input,
942            base_args,
943        } => run_base_convert(
944            &Some(10),
945            &Some(16),
946            &string_input.joined(),
947            base_args,
948        ),
949        Command::Hexfmt {
950            string_input,
951            base_args,
952        } => run_base_convert(
953            &Some(16),
954            &Some(16),
955            &string_input.joined(),
956            base_args,
957        ),
958        Command::Hex2Bin(args) => {
959            let out = ctb_formats_hexdump::cli::execute_cli_hex2bin(
960                args.clone(),
961                read_file_or_stdin,
962            )?;
963            let bytes = match out {
964                Some(b) => b,
965                None => Vec::new(),
966            };
967            Ok(ToolResult::immediate_ok(bytes))
968        }
969        Command::Bin2Hex(args) => {
970            let out = ctb_formats_hexdump::cli::execute_cli_bin2hex(
971                args.clone(),
972                read_file_or_stdin,
973            )?;
974            let bytes = match out {
975                Some(b) => b,
976                None => Vec::new(),
977            };
978            Ok(ToolResult::immediate_ok(bytes))
979        }
980        Command::Hexdump(args) => {
981            let out = ctb_formats_hexdump::cli::execute_cli_hexdump(
982                args.clone(),
983                read_file_or_stdin,
984            )?;
985            let bytes = match out {
986                Some(b) => b,
987                None => Vec::new(),
988            };
989            Ok(ToolResult::immediate_ok(bytes))
990        }
991        Command::Xxd(args) => {
992            let out = ctb_formats_hexdump::cli::execute_cli_xxd(
993                args.clone(),
994                read_file_or_stdin,
995            )?;
996            let bytes = match out {
997                Some(b) => b,
998                None => Vec::new(),
999            };
1000            Ok(ToolResult::immediate_ok(bytes))
1001        }
1002        Command::ShortDc(args) => {
1003            let output =
1004                ctb_formats_dcstring::cli_identifiers::execute_cli_short_dc(
1005                    args,
1006                )?;
1007            Ok(ToolResult::immediate_ok(output.into_bytes()))
1008        }
1009        Command::Gid(args) => {
1010            let output =
1011                ctb_formats_dcstring::cli_identifiers::execute_cli_gid(args)?;
1012            Ok(ToolResult::immediate_ok(output.into_bytes()))
1013        }
1014        Command::ExplainCtbnodes(args) => {
1015            let out =
1016                ctb_formats_dcstring::cli_identifiers::execute_cli_explain_ctbnodes(
1017                    args,
1018                    read_file_or_stdin,
1019                )?;
1020            let bytes = match out {
1021                Some(b) => b,
1022                None => Vec::new(),
1023            };
1024            Ok(ToolResult::immediate_ok(bytes))
1025        }
1026        Command::RangeGen(args) => {
1027            let output =
1028                ctb_formats_math::range_generator::range_cli_handler(args)?;
1029            Ok(ToolResult::immediate_ok(output.into_bytes()))
1030        }
1031        Command::CharacterDescription(args) => {
1032            let out =
1033                ctb_formats_conversion::cli::execute_cli_character_description(
1034                    args.clone(),
1035                    read_file_or_stdin,
1036                )?;
1037            let bytes = match out {
1038                Some(b) => b,
1039                None => Vec::new(),
1040            };
1041            Ok(ToolResult::immediate_ok(bytes))
1042        }
1043        Command::Convert(args) => {
1044            let out = ctb_formats_conversion::cli::execute_cli_convert(
1045                args.clone(),
1046                read_file_or_stdin,
1047            )?;
1048            let bytes = match out {
1049                Some(b) => b,
1050                None => Vec::new(),
1051            };
1052            Ok(ToolResult::immediate_ok(bytes))
1053        }
1054        Command::Run(args) => {
1055            let out = ctb_runtime::cli::execute_cli_run(
1056                args.clone(),
1057                read_file_or_stdin,
1058            )?;
1059            let bytes = match out {
1060                Some(b) => b,
1061                None => Vec::new(),
1062            };
1063            Ok(ToolResult::immediate_ok(bytes))
1064        }
1065        Command::GdbInstructionsGenerate {} => {
1066            // FIXME: Use a streaming ToolResult here
1067            crate::utilities::debug_tools::generate_gdb_instructions_streaming(
1068            )?;
1069            Ok(ToolResult::immediate_ok(Vec::new()))
1070        }
1071        Command::IA { command } => {
1072            ctb_formats_internetarchive::cli::run_internetarchive(command)
1073        }
1074        Command::Pan2Csv {
1075            patterns,
1076            keep_multiline,
1077            header,
1078            no_header,
1079            delimiter,
1080            encoding,
1081            crlf,
1082            replicate_double_encoding,
1083            run_startup_procedure,
1084            pan_file,
1085        } => ctb_formats_pan::cli::pan2csv(
1086            pan_file,
1087            header,
1088            no_header,
1089            encoding,
1090            delimiter,
1091            patterns,
1092            keep_multiline,
1093            crlf,
1094            replicate_double_encoding,
1095            run_startup_procedure,
1096            read_file_or_stdin,
1097        ),
1098        Command::StagelBootstrapParse { input_file } => {
1099            let data = std::fs::read(input_file).with_context(|| {
1100                format!("Failed to read input file: {input_file:?}")
1101            })?;
1102            let filename = input_file
1103                .file_stem()
1104                .ok_or_else(|| {
1105                    anyhow::anyhow!(
1106                        "Input file path {input_file:?} has no valid file stem"
1107                    )
1108                })?
1109                .to_string_lossy();
1110            let output = ctb_formats_stagel::parse::parse(&data, &filename)?;
1111            Ok(ToolResult::immediate_ok(output))
1112        }
1113        Command::StagelBootstrapConvert {
1114            cache_dir,
1115            no_debug,
1116            no_runtime_type_checks,
1117            input_file,
1118            target_lang,
1119        } => {
1120            let output = run_stagel_bootstrap_convert(
1121                !no_debug,
1122                !no_runtime_type_checks,
1123                cache_dir.as_deref(),
1124                input_file,
1125                target_lang,
1126            )?;
1127            Ok(ToolResult::immediate_ok(output))
1128        }
1129        Command::Pan2ParseJson { pan_file } => {
1130            let data = read_file_or_stdin(pan_file.as_path())?;
1131            let output =
1132                ctb_formats_pan::output::pan_to_parse_json(&data)?.into_bytes();
1133            Ok(ToolResult::immediate_ok(output))
1134        }
1135        Command::Pan2Macro {
1136            encoding,
1137            pan_file,
1138            macro_name,
1139        } => {
1140            let data = read_file_or_stdin(pan_file.as_path())?;
1141            let enc = match encoding.to_ascii_lowercase().as_str() {
1142                "mac" | "macroman" | "mac-roman" | "macintosh" => {
1143                    ctb_formats_pan::output::PanCsvEncoding::MacRoman
1144                }
1145                "win" | "windows" | "win1252" | "windows-1252"
1146                | "panwindows" => {
1147                    ctb_formats_pan::output::PanCsvEncoding::Windows
1148                }
1149                "utf8-windows" | "windows-utf8" | "utf8-win" | "win-utf8" => {
1150                    ctb_formats_pan::output::PanCsvEncoding::Utf8Windows
1151                }
1152                _ => ctb_formats_pan::output::PanCsvEncoding::Windows,
1153            };
1154            let output = ctb_formats_pan::output::pan_to_macro_with_encoding(
1155                &data, macro_name, enc,
1156            )?
1157            .into_bytes();
1158            Ok(ToolResult::immediate_ok(output))
1159        }
1160        Command::Pan2Procedures {
1161            output_dir,
1162            extension,
1163            encoding,
1164            pan_file,
1165        } => ctb_formats_pan::cli::pan2procedures(
1166            pan_file.as_path(),
1167            output_dir.as_deref(),
1168            extension.as_deref(),
1169            encoding,
1170            read_file_or_stdin,
1171        ),
1172        Command::PanMacro2Ast {
1173            input_encoding,
1174            output_encoding,
1175            input_file,
1176            macro_name,
1177        } => {
1178            let data = read_file_or_stdin(input_file.as_path())?;
1179            let in_enc = match input_encoding.to_ascii_lowercase().as_str() {
1180                "utf-8" | "utf8" => {
1181                    ctb_formats_pan::output::PanCsvEncoding::Utf8
1182                }
1183                "win" | "windows" | "win1252" | "win-1252" | "windows-1252" => {
1184                    ctb_formats_pan::output::PanCsvEncoding::Windows
1185                }
1186                _ => ctb_formats_pan::output::PanCsvEncoding::MacRoman,
1187            };
1188            let out_enc = match output_encoding.to_ascii_lowercase().as_str() {
1189                // FIXME: use short names from formats data library instead of this
1190                "mac" | "macroman" | "mac-roman" | "macintosh" => {
1191                    ctb_formats_pan::output::PanCsvEncoding::MacRoman
1192                }
1193                "win" | "windows" | "win1252" | "win-1252" | "windows-1252" => {
1194                    ctb_formats_pan::output::PanCsvEncoding::Windows
1195                }
1196                _ => ctb_formats_pan::output::PanCsvEncoding::Utf8,
1197            };
1198
1199            let ast_json = ctb_formats_pan::output::panmacro_to_ast_json(
1200                &data,
1201                macro_name.as_deref(),
1202                in_enc,
1203            )?;
1204            let output = ctb_formats_pan::output::encode_ast_json_output(
1205                &ast_json, out_enc,
1206            )?;
1207            Ok(ToolResult::immediate_ok(output))
1208        }
1209        Command::Pdf2Txt { pdf_file } => {
1210            let data = read_file_or_stdin(pdf_file.as_path())?;
1211            let output = ctb_formats_pdf::pdf2txt(&data)?;
1212            Ok(ToolResult::immediate_ok(output.into_bytes()))
1213        }
1214        Command::Pdf2Json { pdf_file } => {
1215            let data = read_file_or_stdin(pdf_file.as_path())?;
1216            let output = ctb_formats_pdf::pdf2json(&data)?;
1217            Ok(ToolResult::immediate_ok(output.into_bytes()))
1218        }
1219        Command::Pdf2Md { pdf_file } => {
1220            let data = read_file_or_stdin(pdf_file.as_path())?;
1221            let output = ctb_formats_pdf::pdf2md(&data)?;
1222            Ok(ToolResult::immediate_ok(output.into_bytes()))
1223        }
1224        Command::File2MetadataJson {
1225            body,
1226            no_streams,
1227            file,
1228        } => {
1229            let json = ctb_io_file::export_file_metadata_json(
1230                file.as_path(),
1231                *body,
1232                !*no_streams,
1233            )?;
1234            Ok(ToolResult::immediate_ok(json.into_bytes()))
1235        }
1236        Command::MetadataJson2File {
1237            overwrite,
1238            copy_specials_as_specials,
1239            best_effort_metadata,
1240            metadata_file,
1241            path,
1242        } => {
1243            let data = read_file_or_stdin(metadata_file.as_path())?;
1244            let json_str = std::str::from_utf8(&data)
1245                .context("Metadata JSON input is not valid UTF-8")?;
1246            let options = ctb_io_file::MaterializeOptions {
1247                strict_lossless: !*best_effort_metadata,
1248                copy_specials: *copy_specials_as_specials,
1249                force_overwrite: *overwrite,
1250                existing_entry_policy: if *overwrite {
1251                    ctb_io_file::ExistingEntryPolicy::Replace
1252                } else {
1253                    ctb_io_file::ExistingEntryPolicy::Refuse
1254                },
1255                ..ctb_io_file::MaterializeOptions::default()
1256            };
1257            ctb_io_file::rematerialize_from_metadata_json(
1258                json_str,
1259                path.as_path(),
1260                &options,
1261            )?;
1262            Ok(ToolResult::immediate_ok(Vec::new()))
1263        }
1264        Command::Warcat { args } => {
1265            let mut warcat_args = vec!["warcat".to_string()];
1266            warcat_args.extend(args.clone());
1267            let exit_code = ctb_formats_warc::run_warcat(warcat_args);
1268            Ok(ToolResult::Immediate {
1269                stdout: Vec::new(),
1270                stderr: Vec::new(),
1271                exit_code,
1272            })
1273        }
1274        Command::CtbAssetBundleExtract {
1275            bundle_path,
1276            output_dir,
1277        } => {
1278            let cwd = std::env::current_dir()
1279                .context("Failed to get current directory")?;
1280            let cwd = cwd.as_path();
1281            // Reason for fallback: when optional output_dir CLI parameter is omitted, extraction defaults to current working directory (cwd).
1282            let output_dir =
1283                ctb_formats_ctb_asset_bundle::extract_asset_bundle(
1284                    bundle_path.as_path(),
1285                    output_dir.as_deref().unwrap_or(cwd),
1286                )?;
1287            Ok(ToolResult::immediate_ok(
1288                format!("Extracted asset bundle to {}\n", output_dir.display())
1289                    .into_bytes(),
1290            ))
1291        }
1292        Command::JsLint { cli } => Ok(ToolResult::Immediate {
1293            stdout: Vec::new(),
1294            stderr: Vec::new(),
1295            exit_code: ctb_formats_javascript::js_lint::run_cli(cli)?,
1296        }),
1297        Command::TsCheck { args } => Ok(ToolResult::Immediate {
1298            stdout: Vec::new(),
1299            stderr: Vec::new(),
1300            exit_code: ctb_formats_javascript::ts_check::run_typecheck_args(
1301                args,
1302            )?,
1303        }),
1304        Command::JsTest { args } => Ok(ToolResult::Immediate {
1305            stdout: Vec::new(),
1306            stderr: Vec::new(),
1307            exit_code: ctb_formats_javascript::js_test::run_test_args(args)?,
1308        }),
1309        Command::Python(args) => ctb_formats_python::cli::run_python_cli(args),
1310        Command::ValidateDockerImage { file, strict } => {
1311            ctb_formats_docker::cli::run_validate_docker_image(
1312                file.as_deref(),
1313                *strict,
1314            )
1315        }
1316        Command::Csc(args) => ctb_io_csc::cli::run_csc(args.clone()),
1317        Command::Archive(args) => ctb_io_csc::archive::cli::run_archive(args),
1318        Command::Cp(args) => {
1319            let mut cp_args = args.clone();
1320            cp_args.delete_manifest_after = true;
1321            ctb_io_csc::cli::run_csc(cp_args)
1322        }
1323        Command::Mv(args) => ctb_io_csc::move_engine::run_mv(args.clone()),
1324        Command::CscVerify(args) => ctb_io_csc::verifier::run_csc_verify(args),
1325        Command::CscDiff(args) => ctb_io_csc::diff_engine::run_csc_diff(args),
1326        Command::Fsindex(args) => {
1327            ctb_io_csc::index_engine::run_fsindex(args.clone()).await
1328        }
1329        Command::Fsearch(args) => {
1330            ctb_io_csc::search_engine::run_fsearch(args.clone()).await
1331        }
1332        Command::Csum {
1333            algo,
1334            file,
1335            prefix_0x,
1336        } => ctb_formats_checksum::cli::csum(
1337            *algo,
1338            file.as_path(),
1339            *prefix_0x,
1340            read_file_or_stdin,
1341        ),
1342        Command::Compress(args) => ctb_formats_compression_cli::run_compress(
1343            args.clone(),
1344            read_file_or_stdin,
1345            check_overwrite_prompt,
1346        ),
1347        Command::Decompress {
1348            format,
1349            file,
1350            output,
1351            force,
1352        } => ctb_formats_compression_cli::run_decompress(
1353            format.clone(),
1354            file.clone(),
1355            output.clone(),
1356            *force,
1357            read_file_or_stdin,
1358            check_overwrite_prompt,
1359        ),
1360        Command::File(args) => {
1361            ctb_formats_detection::cli::run_file_detection(args)
1362        }
1363        Command::Wfparser { file } => ctb_formats_wfscan::cli::wfparser(
1364            file.as_path(),
1365            read_file_or_stdin,
1366        ),
1367        Command::Wfscan { file } => {
1368            ctb_formats_wfscan::cli::wfscan(file.as_path(), read_file_or_stdin)
1369        }
1370        Command::DceutilsPhpToCsv { php_file } => {
1371            ctb_formats_dceutils::cli::php_to_csv(php_file)
1372        }
1373        Command::Help => Ok(ToolResult::immediate_ok(generate_help_bytes())),
1374        Command::ShowNode { .. } => Err(anyhow!(
1375            "ShowNode should not be run as lightweight command; it needs the full environment"
1376        )),
1377        Command::DevSign {
1378            input_dir,
1379            output_dir,
1380            platform,
1381        } => {
1382            let summary = ctb_installer::dev_sign::run_dev_sign(
1383                input_dir.as_deref(),
1384                output_dir.as_deref(),
1385                platform.as_deref(),
1386            )?;
1387            println!("{summary}");
1388            Ok(ToolResult::immediate_ok(Vec::new()))
1389        }
1390        Command::DevGzSha256 { path } => {
1391            let sha = ctb_installer::dev_sign::compress_gz_sha256(path)?;
1392            println!("{sha}");
1393            Ok(ToolResult::immediate_ok(Vec::new()))
1394        }
1395        Command::DevKeyCreate { write } => {
1396            use crate::utilities::pc_settings::PcSettings;
1397            use ctb_installer::signing::{
1398                KeyId, generate_keypair, private_key_to_base64,
1399                public_key_to_base64,
1400            };
1401
1402            let (private_key, public_key) = generate_keypair();
1403            let private_b64 = private_key_to_base64(&private_key);
1404            let public_b64 = public_key_to_base64(&public_key);
1405            let key_id = KeyId::from_public_key(&public_key);
1406
1407            if *write {
1408                PcSettings::apply_patch(PcSettings {
1409                    dev_signing_private_key: MaybeOption::Value(
1410                        private_b64.clone(),
1411                    ),
1412                    dev_signing_public_key: MaybeOption::Value(
1413                        public_b64.clone(),
1414                    ),
1415                    ..Default::default()
1416                })?;
1417            }
1418
1419            println!("Signing keypair generated");
1420            println!("Key ID: {key_id}");
1421            println!();
1422            println!("dev_signing_private_key (base64): {private_b64}");
1423            println!("dev_signing_public_key (base64):  {public_b64}");
1424            println!();
1425            println!(
1426                "Server `release_public_key` should be set to the public key above."
1427            );
1428
1429            Ok(ToolResult::immediate_ok(Vec::new()))
1430        }
1431        Command::DevReleaseCheck {
1432            manifest,
1433            chunks_dir,
1434            platform,
1435        } => {
1436            let summary = ctb_installer::release_check::run_dev_release_check(
1437                manifest.as_deref(),
1438                chunks_dir.as_deref(),
1439                platform,
1440            )?;
1441            println!("{summary}");
1442            Ok(ToolResult::immediate_ok(Vec::new()))
1443        }
1444        Command::DevReleaseExpire {
1445            older_than,
1446            releases_dir,
1447        } => {
1448            let summary = ctb_installer::release_expire::run_release_expire(
1449                *older_than,
1450                releases_dir.as_deref(),
1451            )?;
1452            println!("{summary}");
1453            Ok(ToolResult::immediate_ok(Vec::new()))
1454        }
1455        Command::Install { no_gui, unattended } => {
1456            // Unattended implies no_gui
1457            let use_tui = *no_gui || *unattended;
1458
1459            if use_tui {
1460                ctb_installer::tui::run_installer(*unattended)?;
1461            } else {
1462                ctb_installer::gui::run_installer()?;
1463            }
1464            Ok(ToolResult::immediate_ok(Vec::new()))
1465        }
1466        Command::MakeOfflineInstaller {
1467            output,
1468            platform,
1469            version,
1470            server_url,
1471        } => {
1472            ctb_installer::tarball::download_offline_bundle_to_path(
1473                output,
1474                server_url.as_deref(),
1475                platform.as_deref(),
1476                version.as_deref(),
1477            )?;
1478            println!(
1479                "Offline installer bundle written to {}",
1480                output.display()
1481            );
1482            Ok(ToolResult::immediate_ok(Vec::new()))
1483        }
1484        Command::Update {
1485            unattended,
1486            server_url,
1487        } => {
1488            ctb_installer::install::run_update_check(
1489                server_url.as_deref(),
1490                *unattended,
1491            )?;
1492            Ok(ToolResult::immediate_ok(Vec::new()))
1493        }
1494        Command::Uninstall { no_gui, unattended } => {
1495            let use_tui = *no_gui || *unattended;
1496
1497            if *unattended {
1498                // Run unattended uninstall (no prompts)
1499                ctb_installer::install::run_uninstall_unattended()?;
1500            } else if use_tui {
1501                ctb_installer::tui::run_uninstall()?;
1502            } else {
1503                ctb_installer::gui::run_uninstall()?;
1504            }
1505            Ok(ToolResult::immediate_ok(Vec::new()))
1506        }
1507        Command::UpgradeCanary {
1508            backup_path,
1509            target_path,
1510            port,
1511        } => {
1512            ctb_installer::upgrade::run_canary_validation(
1513                backup_path,
1514                target_path,
1515                *port,
1516            )?;
1517            Ok(ToolResult::immediate_ok(Vec::new()))
1518        }
1519        Command::Jq {
1520            raw_output,
1521            query,
1522            file,
1523        } => {
1524            use std::io::Read;
1525
1526            let input_bytes = if let Some(path) = file {
1527                read_file_or_stdin(path)?
1528            } else {
1529                let mut buf = Vec::new();
1530                std::io::stdin().read_to_end(&mut buf)?;
1531                buf
1532            };
1533            let input_str = String::from_utf8(input_bytes)
1534                .context("Input is not valid UTF-8")?;
1535
1536            let cli = ctb_utilities::json::Cli {
1537                raw_output: *raw_output,
1538                compact_output: true,
1539                ..Default::default()
1540            };
1541            let output =
1542                ctb_utilities::json::jq_implementation(query, &input_str, cli)?;
1543            Ok(ToolResult::immediate_ok(output.into_bytes()))
1544        }
1545        Command::JsonEscape { value } => {
1546            let input_str = if let Some(val) = value {
1547                val.clone()
1548            } else {
1549                use std::io::Read;
1550                let mut buf = Vec::new();
1551                std::io::stdin().read_to_end(&mut buf)?;
1552                String::from_utf8(buf).context("Input is not valid UTF-8")?
1553            };
1554            let escaped = ctb_utilities::json::json_escape(&input_str)?;
1555            Ok(ToolResult::immediate_ok(escaped.into_bytes()))
1556        }
1557        Command::X86InstructionSets { path } => {
1558            ctb_formats_x86::cli::instruction_sets(path)
1559        }
1560    }
1561}
1562
1563#[cfg(test)]
1564#[allow(
1565    clippy::panic,
1566    clippy::expect_used,
1567    clippy::unwrap_used,
1568    clippy::unwrap_in_result,
1569    clippy::panic_in_result_fn,
1570    clippy::indexing_slicing,
1571    clippy::arithmetic_side_effects,
1572    reason = "Standard repository test boilerplate"
1573)]
1574mod tests {
1575    use super::*;
1576
1577    #[crate::ctb_test]
1578    fn test_is_lightweight_command_general() {
1579        let lightweight_commands = [
1580            "adduser",
1581            "validate-docker-image",
1582            "compress",
1583            "decompress",
1584            "file",
1585            "detect",
1586            "base2base",
1587            "hex2dec",
1588            "dec2hex",
1589            "hexfmt",
1590            "pan2procedures",
1591            "x86-instruction-sets",
1592            "json-escape",
1593            "jq",
1594            "file2metadatajson",
1595            "metadatajson2file",
1596            "run",
1597        ];
1598        for cmd_name in lightweight_commands {
1599            assert!(
1600                is_lightweight_command(cmd_name),
1601                "Expected '{cmd_name}' to be recognized as a lightweight command"
1602            );
1603        }
1604
1605        let non_lightweight_commands =
1606            ["nonexistent-subcommand-12345", "server", "start", ""];
1607        for cmd_name in non_lightweight_commands {
1608            assert!(
1609                !is_lightweight_command(cmd_name),
1610                "Expected '{cmd_name}' NOT to be recognized as a lightweight command"
1611            );
1612        }
1613    }
1614
1615    #[crate::ctb_test("tokio")]
1616    async fn test_run_lightweight_command_dispatch() -> Result<()> {
1617        let cmd = Command::JsonEscape {
1618            value: Some("hello \"world\"".to_string()),
1619        };
1620        let res = run_lightweight_command(&cmd).await?;
1621        match res {
1622            ToolResult::Immediate {
1623                stdout, exit_code, ..
1624            } => {
1625                assert_eq!(exit_code, 0);
1626                assert_eq!(
1627                    String::from_utf8(stdout)?,
1628                    "\"hello \\\"world\\\"\""
1629                );
1630            }
1631            _ => panic!("Expected Immediate ToolResult"),
1632        }
1633        Ok(())
1634    }
1635
1636    // Don't add command-specific tests here! Any nontrivial logic should go in the associated crate, rather than this file and crate.
1637    // 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.
1638}