// SPDX-License-Identifier: MIT // Copyright (c) 2026 caomengxuan666 export module core:dispatcher; import std; import :cmd_meta; import :command_context; import :opt; import utils; import version; export template using CommandFunc = int (*)(CommandContext &) noexcept; export using CommandInvoker = int (*)(std::span) noexcept; export template struct CommandEntry { cmd::meta::CommandMetaHandle meta; CommandFunc handler; std::string_view brief_desc; CommandEntry() = default; CommandEntry(cmd::meta::CommandMetaHandle m, CommandFunc h) : meta(std::move(m)), handler(h), brief_desc(meta.brief_desc()) {} }; // Per-option information returned for completion export struct OptionInfo { std::string short_name; std::string long_name; std::string description; }; struct CommandEntryErased { std::span options; CommandInvoker handler = nullptr; std::string_view brief_desc; CommandEntryErased() = default; CommandEntryErased(std::span opts, CommandInvoker h, std::string_view brief) : options(opts), handler(h), brief_desc(brief) {} }; using ArgsRewriteHook = std::optional> (*)(std::span); using ArgsValidationHook = std::optional (*)(std::span); using SpecialDispatchHook = std::optional (*)(const CommandEntryErased &, std::span); using StandardInterceptionHook = bool (*)(std::span); constexpr size_t kMaxRewriteHooks = 5; struct CommandBehavior { int parse_error_exit_code = 1; ArgsValidationHook validate_args = nullptr; std::string_view validation_prefix; // Per-command shape of the obsolete-count context diagnostic: // tail says "option used in invalid context", head says "invalid // trailing option" and adds the Try-help line (head.c:1066-1069). bool validation_uses_trailing_option_wording = false; std::array rewrite_hooks{}; size_t rewrite_hook_count = 0; SpecialDispatchHook special_dispatch = nullptr; StandardInterceptionHook standard_interception_enabled = nullptr; // [GNU] printf, test and [ never call getopt: they recognize --help and // --version only as the sole command-line argument (printf.c/test.c use // `argc == 2`); anywhere else the token is an operand or format string. bool help_version_only_when_sole_argument = false; }; auto is_posixly_correct() -> bool { const char *value = std::getenv("POSIXLY_CORRECT"); return value != nullptr && value[0] != '\0'; } auto legacy_count_value(std::string_view arg) -> std::string { if (arg.empty()) return {}; if ((arg[0] == '-' || arg[0] == '+') && arg.size() > 1) { return std::string(arg.substr(1)); } return std::string(arg); } auto append_remaining_args(std::vector &out, std::span args, size_t start) -> void { for (size_t i = start; i < args.size(); ++i) { out.emplace_back(args[i]); } } auto parse_decimal_prefix(std::string_view arg, size_t start) -> size_t { size_t pos = start; while (pos < arg.size() && std::isdigit(static_cast(arg[pos])) != 0) { ++pos; } return pos; } auto rewrite_head_obsolete_args(std::span args) -> std::optional> { if (args.empty()) return std::nullopt; std::string_view first = args[0]; if (first.size() < 2 || first[0] != '-' || first[1] == '-') return std::nullopt; size_t suffix_pos = parse_decimal_prefix(first, 1); if (suffix_pos == 1) return std::nullopt; std::string count(first.substr(1, suffix_pos - 1)); std::string mode = "-n"; std::string value = count; std::vector flags; for (size_t i = suffix_pos; i < first.size(); ++i) { switch (first[i]) { case 'l': mode = "-n"; value = count; break; case 'c': mode = "-c"; value = count; break; case 'b': mode = "-c"; value = count + "b"; break; case 'k': mode = "-c"; value = count + "K"; break; case 'm': mode = "-c"; value = count + "M"; break; case 'q': flags.emplace_back("-q"); break; case 'v': flags.emplace_back("-v"); break; case 'z': // [GNU] '-2z' is the obsolete spelling of '-n 2 -z' // (head.c parse_obsolete_option accepts z; #1462). flags.emplace_back("-z"); break; default: return std::nullopt; } } std::vector rewritten; rewritten.reserve(args.size() + flags.size() + 1); rewritten.emplace_back(mode); rewritten.emplace_back(value); for (const auto &flag : flags) rewritten.emplace_back(flag); append_remaining_args(rewritten, args, 1); return rewritten; } struct TailObsoleteSuffix { char unit = 0; bool follow = false; }; // [GNU] tail.c parse_obsolete_option's suffix grammar, shared by // both signs: after the digits, at most ONE unit letter (b/c/l), // then at most one 'f', then the end of the string. A free-form // letter scan over-accepts shapes GNU rejects (-5lc, -5fb). auto parse_tail_obsolete_suffix(std::string_view arg, size_t suffix_pos) -> std::optional { TailObsoleteSuffix out; size_t i = suffix_pos; if (i < arg.size() && (arg[i] == 'b' || arg[i] == 'c' || arg[i] == 'l')) { out.unit = arg[i]; ++i; } if (i < arg.size() && arg[i] == 'f') { out.follow = true; ++i; } if (i != arg.size()) return std::nullopt; return out; } auto rewrite_tail_obsolete_args(std::span args) -> std::optional> { if (args.empty()) return std::nullopt; std::string_view first = args[0]; if (first.size() >= 2 && first[0] == '+' && first[1] != '+') { size_t suffix_pos = parse_decimal_prefix(first, 1); if (suffix_pos == 1) return std::nullopt; // [GNU] the obsolete form exists only inside parse_obsolete_ // option's argc gate (tail.c:2062-2067): the option string // plus at most one file operand, or a "--" in argv[2]. Outside // the gate a leading '+' argument is a file name, not an // option (audit #1462). if (!(args.size() == 1 || (args.size() == 2 && !(args[1].size() > 1 && args[1][0] == '-')) || (args.size() <= 3 && args[1] == "--"))) return std::nullopt; std::string count(first.substr(1, suffix_pos - 1)); std::string mode = "-n"; std::string value = "+" + count; auto suffix = parse_tail_obsolete_suffix(first, suffix_pos); if (!suffix) return std::nullopt; if (suffix->unit == 'c') { mode = "-c"; } else if (suffix->unit == 'b') { mode = "-c"; value = "+" + count + "b"; } std::vector rewritten; rewritten.reserve(args.size() + 2); rewritten.emplace_back(mode); rewritten.emplace_back(value); // [GNU] the '+' form accepts the trailing 'f' too // (parse_obsolete_option's grammar is shared by both signs); // dropping it treated "+5f" as a file name. if (suffix->follow) rewritten.emplace_back("-f"); append_remaining_args(rewritten, args, 1); return rewritten; } if (first.size() < 2 || first[0] != '-' || first[1] == '-') return std::nullopt; // [GNU] digit-less obsolete forms (tail.c parse_obsolete_option): // with no digits the count defaults to 10 (x512 for 'b'), one // unit letter, optional trailing 'f'. In the modern POSIX mode // a bare '-c' is NOT obsolete (it is the live option missing its // argument), so the accepted set is exactly -l, -b, -lf, -bf, // -cf -- and only in the restricted context, like the compact // forms below (audit #1462). if (first == "-l" || first == "-b" || first == "-lf" || first == "-bf" || first == "-cf") { if (args.size() > 2) return std::nullopt; std::vector rewritten; if (first[1] == 'l') { rewritten.emplace_back("-n"); rewritten.emplace_back("10"); } else if (first[1] == 'c') { rewritten.emplace_back("-c"); rewritten.emplace_back("10"); } else { rewritten.emplace_back("-c"); rewritten.emplace_back("10b"); } if (first.size() == 3) rewritten.emplace_back("-f"); append_remaining_args(rewritten, args, 1); return rewritten; } size_t suffix_pos = parse_decimal_prefix(first, 1); if (suffix_pos == 1) return std::nullopt; bool has_compact_suffix = suffix_pos < first.size(); if (has_compact_suffix && args.size() > 2) return std::nullopt; std::string count(first.substr(1, suffix_pos - 1)); std::string mode = "-n"; std::string value = count; auto suffix = parse_tail_obsolete_suffix(first, suffix_pos); if (!suffix) return std::nullopt; if (suffix->unit == 'c') { mode = "-c"; } else if (suffix->unit == 'b') { mode = "-c"; value = count + "b"; } std::vector rewritten; rewritten.reserve(args.size() + 2); rewritten.emplace_back(mode); rewritten.emplace_back(value); if (suffix->follow) rewritten.emplace_back("-f"); append_remaining_args(rewritten, args, 1); return rewritten; } auto is_head_obsolete_count_arg(std::string_view arg) -> bool { if (arg.size() < 2 || arg[0] != '-' || arg[1] == '-') return false; size_t suffix_pos = parse_decimal_prefix(arg, 1); if (suffix_pos == 1) return false; for (size_t i = suffix_pos; i < arg.size(); ++i) { switch (arg[i]) { case 'l': case 'c': case 'b': case 'k': case 'm': case 'q': case 'v': case 'z': break; default: return false; } } return true; } auto is_tail_obsolete_count_arg(std::string_view arg) -> bool { if (arg.size() < 2) return false; if (arg[0] == '+') { if (arg[1] == '+') return false; size_t suffix_pos = parse_decimal_prefix(arg, 1); if (suffix_pos == 1) return false; return parse_tail_obsolete_suffix(arg, suffix_pos).has_value(); } if (arg[0] != '-' || arg[1] == '-') return false; size_t suffix_pos = parse_decimal_prefix(arg, 1); if (suffix_pos == 1) return false; return parse_tail_obsolete_suffix(arg, suffix_pos).has_value(); } auto tail_invalid_obsolete_count_context(std::span args) -> std::optional { if (args.size() < 2) return std::nullopt; // [GNU] an obsolete '-' count in FIRST position is valid only // with at most one file operand (tail.c parse_obsolete_option's // argc gate): 'tail -5 f1 f2' dies 'option used in invalid // context -- 5'. The '+' forms are NOT errors outside the gate: // a leading '+' is a file name in the standard form (tail.c:2080), // so 'tail +2l f1 f2' opens '+2l' as an operand instead. Count // the file operands after it with the same scan discipline as // the loop below (audit #1462). if (args[0][0] == '-' && is_tail_obsolete_count_arg(args[0])) { size_t file_operands = 0; bool stop = false; bool skip_next = false; for (size_t i = 1; i < args.size(); ++i) { std::string_view arg = args[i]; if (skip_next) { skip_next = false; continue; } if (!stop && arg == "--") { stop = true; continue; } if (!stop && arg.size() > 1 && arg[0] == '-') { if (arg == "-c" || arg == "--bytes" || arg == "-n" || arg == "--lines" || arg == "-s" || arg == "--sleep-interval" || arg == "--max-unchanged-stats" || arg == "--pid") { skip_next = true; } continue; } ++file_operands; } if (file_operands > 1) { return legacy_count_value(args[0]); } } bool stop_option_parsing = false; bool expect_value = false; for (size_t i = 0; i < args.size(); ++i) { std::string_view arg = args[i]; if (stop_option_parsing) continue; if (arg == "--") { stop_option_parsing = true; continue; } if (expect_value) { expect_value = false; continue; } if (i > 0 && is_tail_obsolete_count_arg(arg)) { return legacy_count_value(arg); } if (arg == "-c" || arg == "--bytes" || arg == "-n" || arg == "--lines" || arg == "-s" || arg == "--sleep-interval" || arg == "--max-unchanged-stats" || arg == "--pid") { expect_value = true; continue; } if (arg == "--follow" && i + 1 < args.size() && args[i + 1] != "--" && !args[i + 1].empty() && args[i + 1][0] != '-') { expect_value = true; } } return std::nullopt; } auto head_invalid_obsolete_count_context(std::span args) -> std::optional { if (args.size() < 2) return std::nullopt; bool stop_option_parsing = false; bool expect_value = false; for (size_t i = 0; i < args.size(); ++i) { std::string_view arg = args[i]; if (stop_option_parsing) continue; if (arg == "--") { stop_option_parsing = true; continue; } if (expect_value) { expect_value = false; continue; } if (i > 0 && is_head_obsolete_count_arg(arg)) { return legacy_count_value(arg); } if (arg == "-c" || arg == "--bytes" || arg == "-n" || arg == "--lines") { expect_value = true; } } return std::nullopt; } auto is_chmod_negative_symbolic_mode_arg(std::string_view arg) -> bool { if (arg.size() < 2 || arg[0] != '-' || arg[1] == '-') { return false; } return std::ranges::all_of(arg.substr(1), [](unsigned char ch) { return ch == 'r' || ch == 'w' || ch == 'x'; }); } auto rewrite_chmod_gnu_negative_mode_args(std::string_view cmdName, std::span args) -> std::optional> { if (cmdName != "chmod" || args.empty()) { return std::nullopt; } std::vector negative_modes; std::vector pre_double_hyphen_args; std::vector post_double_hyphen_args; bool seen_double_hyphen = false; for (auto arg : args) { if (!seen_double_hyphen && arg == "--") { seen_double_hyphen = true; continue; } if (!seen_double_hyphen && is_chmod_negative_symbolic_mode_arg(arg)) { negative_modes.push_back("a" + std::string(arg)); continue; } if (seen_double_hyphen) { post_double_hyphen_args.emplace_back(arg); } else { pre_double_hyphen_args.emplace_back(arg); } } if (negative_modes.empty()) { return std::nullopt; } std::vector rewritten; rewritten.reserve(args.size() + 1); std::string merged_mode; for (size_t i = 0; i < negative_modes.size(); ++i) { if (i != 0) { merged_mode.push_back(','); } merged_mode += negative_modes[i]; } rewritten.push_back(std::move(merged_mode)); for (const auto &arg : pre_double_hyphen_args) { rewritten.push_back(arg); } if (seen_double_hyphen) { rewritten.push_back("--"); for (const auto &arg : post_double_hyphen_args) { rewritten.push_back(arg); } } return rewritten; } auto rewrite_chmod_args(std::span args) -> std::optional> { return rewrite_chmod_gnu_negative_mode_args("chmod", args); } auto is_chattr_mode_arg(std::string_view arg) -> bool { if (arg.size() < 2) return false; if (arg[0] != '+' && arg[0] != '-' && arg[0] != '=') return false; if (arg == "-R" || arg == "-V") return false; if (arg.starts_with("--")) return false; return std::ranges::all_of(arg.substr(1), [](unsigned char ch) { switch (ch) { case 'R': case 'r': case 'H': case 'h': case 'S': case 's': case 'A': case 'a': case 'I': case 'i': case 'T': case 't': case 'O': case 'o': return true; default: return false; } }); } auto rewrite_chattr_mode_args(std::span args) -> std::optional> { bool seen_double_hyphen = false; for (size_t i = 0; i < args.size(); ++i) { auto arg = args[i]; if (arg == "--") { seen_double_hyphen = true; continue; } if (seen_double_hyphen || !is_chattr_mode_arg(arg)) continue; std::vector rewritten; rewritten.reserve(args.size() + 1); for (size_t j = 0; j < i; ++j) rewritten.emplace_back(args[j]); rewritten.emplace_back("--"); append_remaining_args(rewritten, args, i); return rewritten; } return std::nullopt; } auto rewrite_chattr_args(std::span args) -> std::optional> { return rewrite_chattr_mode_args(args); } auto parse_legacy_nice_adjustment(std::string_view arg) -> std::optional { if (arg.size() < 2 || arg[0] != '-') { return std::nullopt; } if (arg == "-n" || arg == "--adjustment") { return std::nullopt; } std::string_view numeric = arg.substr(1); if (numeric.empty() || numeric == "-" || numeric == "+") { return std::nullopt; } if (numeric[0] == '+') { numeric.remove_prefix(1); if (numeric.empty()) { return std::nullopt; } } int value = 0; auto [ptr, ec] = std::from_chars(numeric.data(), numeric.data() + numeric.size(), value); if (ec != std::errc() || ptr != numeric.data() + numeric.size()) { return std::nullopt; } return value; } auto rewrite_nice_legacy_args(std::string_view cmdName, std::span args) -> std::optional> { if (cmdName != "nice" || args.empty()) { return std::nullopt; } std::vector rewritten; rewritten.reserve(args.size()); bool changed = false; bool seen_command = false; bool expecting_adjustment_value = false; for (auto arg : args) { if (seen_command) { rewritten.emplace_back(arg); continue; } if (arg == "--") { rewritten.emplace_back(arg); seen_command = true; expecting_adjustment_value = false; continue; } if (expecting_adjustment_value) { rewritten.emplace_back(arg); expecting_adjustment_value = false; continue; } if (arg == "-n" || arg == "--adjustment") { rewritten.emplace_back(arg); expecting_adjustment_value = true; continue; } if (arg.starts_with("-n") || arg.starts_with("--adjustment=")) { rewritten.emplace_back(arg); continue; } if (auto legacy_value = parse_legacy_nice_adjustment(arg)) { rewritten.emplace_back("-n" + std::to_string(*legacy_value)); changed = true; continue; } if (!arg.empty() && arg[0] != '-') { rewritten.emplace_back("--"); rewritten.emplace_back(arg); seen_command = true; changed = true; continue; } rewritten.emplace_back(arg); } if (!changed) { return std::nullopt; } return rewritten; } auto rewrite_nice_args(std::span args) -> std::optional> { return rewrite_nice_legacy_args("nice", args); } auto rewrite_pr_legacy_column_args(std::string_view cmdName, std::span args) -> std::optional> { if (cmdName != "pr" || args.empty()) { return std::nullopt; } std::vector rewritten; rewritten.reserve(args.size() + 2); bool changed = false; bool stop_option_parsing = false; for (auto arg : args) { if (!stop_option_parsing && arg == "--") { stop_option_parsing = true; rewritten.emplace_back(arg); continue; } if (!stop_option_parsing && arg.size() >= 2 && arg[0] == '-' && arg[1] != '-') { size_t suffix_pos = parse_decimal_prefix(arg, 1); if (suffix_pos == arg.size() && suffix_pos > 1) { rewritten.emplace_back("-COLUMN"); rewritten.emplace_back(std::string(arg.substr(1))); changed = true; continue; } } rewritten.emplace_back(arg); } if (!changed) { return std::nullopt; } return rewritten; } auto rewrite_pr_args(std::span args) -> std::optional> { return rewrite_pr_legacy_column_args("pr", args); } // GNU fold accepts the obsolete "-WIDTH" form (e.g. "fold -5"). The rewrite // happens in place so a later "-WIDTH" overrides an earlier "-w WIDTH", the // same last-one-wins rule GNU gets from processing options in sequence. // An argument is only eligible when it is not the value of a preceding // "-w"/"--width" and does not appear after a "--" terminator. auto rewrite_fold_obsolete_args(std::span args) -> std::optional> { if (args.empty()) { return std::nullopt; } std::vector rewritten; rewritten.reserve(args.size()); bool changed = false; bool stop_option_parsing = false; bool expect_width_value = false; for (auto arg : args) { if (!stop_option_parsing && arg == "--") { stop_option_parsing = true; rewritten.emplace_back(arg); expect_width_value = false; continue; } if (!stop_option_parsing && expect_width_value) { // This token is the value of -w/--width; leave it alone. rewritten.emplace_back(arg); expect_width_value = false; continue; } if (!stop_option_parsing && arg.size() >= 2 && arg[0] == '-' && arg[1] != '-') { size_t suffix_pos = parse_decimal_prefix(arg, 1); if (suffix_pos == arg.size()) { rewritten.emplace_back("--width=" + std::string(arg.substr(1))); changed = true; continue; } } if (!stop_option_parsing && (arg == "-w" || arg == "--width")) { expect_width_value = true; } rewritten.emplace_back(arg); } if (!changed) { return std::nullopt; } return rewritten; } // GNU fmt accepts the obsolete "-WIDTH" form (e.g. "fmt -60"), but only when // it is the very first argument; a digit option in any other position is a // getopt error in fmt.c. The whole rest of the argument must be digits — // "fmt -60s" fails with "invalid width: '60s'" — so the token is rewritten // to "-w " and fmt's own validation reports the same diagnostic. auto rewrite_fmt_obsolete_args(std::span args) -> std::optional> { if (args.empty()) { return std::nullopt; } std::string_view first = args[0]; if (first.size() < 2 || first[0] != '-' || first[1] == '-' || !std::isdigit(static_cast(first[1]))) { return std::nullopt; } std::vector rewritten; rewritten.reserve(args.size() + 1); rewritten.emplace_back("-w"); rewritten.emplace_back(first.substr(1)); append_remaining_args(rewritten, args, 1); return rewritten; } auto echo_posixly_correct_literal_mode(std::string_view cmdName, std::span args) -> bool { if (cmdName != "echo") { return false; } // [GNU] echo.c:115-118: presence of POSIXLY_CORRECT is what counts; // a present-but-empty value still selects the POSIX behavior. const char *value = std::getenv("POSIXLY_CORRECT"); if (value == nullptr) { return false; } return args.empty() || args[0] != "-n"; } auto command_declares_version_short( std::span options, std::string_view name) -> bool { return std::ranges::any_of(options, [name](const auto &option) { return option.short_name == name && option.long_name == "--version"; }); } // [GNU] echo.c never uses getopt: --help/--version are honored only as the // sole argument, and the POSIX literal mode never recognizes them at all. // The leading-[-neE] flag scan itself lives in the wired rust2 body // (echo.rs, #1488); the rewrite hook that once guarded data-looking tokens // behind a "--" for the generic parser retired with the 1.x echo body. auto echo_standard_interception_enabled(std::span args) -> bool { return !echo_posixly_correct_literal_mode("echo", args); } auto default_standard_interception_enabled(std::span) -> bool { return true; } // [GNU] nohup owns only the options before the wrapped command: coreutils // nohup.c parses with a leading-'+' getopt, so option processing ends at // the first non-option argument. --help/--version appearing after the // command name belong to the child (`nohup echo --help` must run // `echo --help`, not print nohup's help), so interception is enabled only // when one of them sits in nohup's own option prefix. auto nohup_standard_interception_enabled(std::span args) -> bool { for (const auto &arg : args) { if (arg == "--") { // "--" ends nohup's own option run; the rest belongs to the child. return false; } if (arg.size() < 2 || arg[0] != '-') { // First non-option token: the wrapped command's name. return false; } if (arg == "--help" || arg == "--version") { return true; } } return false; } auto command_owned_help_interception_disabled(std::span) -> bool { return false; } auto dispatch_wpm_help_version(const CommandEntryErased &entry, std::span args) -> std::optional { for (const auto &arg : args) { if (arg == "--help") { return entry.handler(std::span{}); } if (arg == "--version" || arg == "-V") { std::array version_args{"version"}; return entry.handler(version_args); } } return std::nullopt; } auto append_rewrite_hook(CommandBehavior &behavior, ArgsRewriteHook hook) -> void { if (behavior.rewrite_hook_count < behavior.rewrite_hooks.size()) { behavior.rewrite_hooks[behavior.rewrite_hook_count++] = hook; } } auto behavior_for(std::string_view name) -> CommandBehavior { CommandBehavior behavior; behavior.standard_interception_enabled = default_standard_interception_enabled; if (name == "env" || name == "nice" || name == "stdbuf" || name == "timeout" || name == "chroot" || name == "runcon") { // [GNU] chroot/runcon usage (option) errors also exit 125 // (EXIT_USAGE in the coreutils wrapper family, #1375); their // missing-operand paths already returned 125/1 inconsistently — // chroot's handler returns 125, runcon's stays 1 per its pinned // repo tests. behavior.parse_error_exit_code = 125; } else if (name == "nohup") { behavior.parse_error_exit_code = is_posixly_correct() ? 127 : 125; behavior.standard_interception_enabled = nohup_standard_interception_enabled; } else if (name == "printenv" || name == "tty" || name == "sort" || name == "ls" || name == "dir" || name == "vdir" || name == "getopt" || name == "expr" || name == "test" || name == "[" || name == "grep" || name == "diff" || name == "diff3" || name == "sdiff" || name == "cmp" || name == "patch") { // [GNU] these commands exit 2 on option/usage errors. GNU grep/diff/ // diff3/sdiff/cmp document 2 as "trouble" for any usage or option error // (and diff/cmp also use 1 for "inputs differ"), so a rejected option // must not be reported as an ordinary failure (WinuxCmd #1213). GNU // patch likewise exits 2 on usage errors (WinuxCmd #1345). behavior.parse_error_exit_code = 2; } if (name == "head") { behavior.validate_args = head_invalid_obsolete_count_context; behavior.validation_prefix = "head"; behavior.validation_uses_trailing_option_wording = true; append_rewrite_hook(behavior, rewrite_head_obsolete_args); } else if (name == "tail") { behavior.validate_args = tail_invalid_obsolete_count_context; behavior.validation_prefix = "tail"; append_rewrite_hook(behavior, rewrite_tail_obsolete_args); } else if (name == "chmod") { append_rewrite_hook(behavior, rewrite_chmod_args); } else if (name == "chattr") { append_rewrite_hook(behavior, rewrite_chattr_args); } else if (name == "nice") { append_rewrite_hook(behavior, rewrite_nice_args); } else if (name == "pr") { append_rewrite_hook(behavior, rewrite_pr_args); } else if (name == "fold") { append_rewrite_hook(behavior, rewrite_fold_obsolete_args); } else if (name == "fmt") { append_rewrite_hook(behavior, rewrite_fmt_obsolete_args); } else if (name == "echo") { // #1488 rust2 wiring: echo.c never calls getopt, so there is no rewrite // hook any more — the wired Rust body (echo.rs) scans the leading // [-neE]-only flags itself and receives ctx.raw_args verbatim. The // help/version interception stays C++ (WinuxCmd-branded metadata) but // narrows to the same sole-argument rule the library implements // (echo.c honors them only when they are the only argument: // `echo -n --version` prints "--version", `echo --help x` prints // "--help x" as data), gated by the POSIX literal-mode check // (POSIXLY_CORRECT=1 echo --help prints "--help"). behavior.help_version_only_when_sole_argument = true; behavior.standard_interception_enabled = echo_standard_interception_enabled; } else if (name == "wpm") { behavior.special_dispatch = dispatch_wpm_help_version; } // [GNU] printf/test/[ recognize --help/--version only when one of them // is the sole argument; in any other position the token is data. // true/false follow coreutils truefalse.c the same way: no getopt is run // at all, so `true -x --help` exits 0 with no output (#1196). // expr follows expr.c: `expr 1 --help` is a syntax error, not help. if (name == "printf" || name == "test" || name == "[" || name == "true" || name == "false" || name == "expr") { behavior.help_version_only_when_sole_argument = true; } // These commands own structured help output and translate it themselves. // Let their handlers receive --help instead of the generic metadata path. // find joins them in the #1488 wiring: GNU findutils owns --help, // --version and the single-dash -help/-version predicates, and the rust2 // body prints the probed 4.9 blocks byte-for-byte (gate rows fd001-fd005 // are strict against the GNU oracle). if (name == "top" || name == "mpicalc" || name == "tzset" || name == "find") { behavior.standard_interception_enabled = command_owned_help_interception_disabled; } return behavior; } auto replace_effective_args(std::vector rewritten, std::vector &storage, std::vector &views) -> std::span { storage = std::move(rewritten); views.clear(); views.reserve(storage.size()); for (const auto &arg : storage) { views.emplace_back(arg); } return std::span(views); } // #1303: classify each argv token the way the parser will see it, so // the dispatcher pre-passes (abbreviation expansion, --help/--version // interception) only act on real option tokens. Without this, a value // that looks like an option (grep --label --help, cp --suffix --ver) // or an operand of a wrapped command (xargs echo --help, timeout 5 // echo --help, find -exec echo --help \;) is wrongly expanded or // intercepted. The walk mirrors parse_command_runtime: "--" ends // options, value options swallow their value (attached or next argv), // TerminatedString swallows through ";" / "+", clusters keep walking, // and the first positional ends scanning once the command's stop (or // POSIXLY_CORRECT) is reached. enum class ArgRole { Option, Value, Data, Terminator }; auto classify_args_for_dispatch( std::string_view cmd_name, std::span args, std::span options) -> std::vector { const auto policy = option_policy_for_command(cmd_name); std::vector roles(args.size(), ArgRole::Data); // A command that parses its own argv (sed) has no option token the // pre-passes may act on: no abbreviation expansion, no --help/--version // interception -- the handler owns them. if (policy.all_args_are_positionals) return roles; bool end_of_options = false; size_t positionals = 0; const size_t stop_after = policy.posixly_correct ? (policy.stop_options_after_positionals == 0 ? 1 : std::min(policy.stop_options_after_positionals, size_t{1})) : policy.stop_options_after_positionals; auto note_positional = [&]() { ++positionals; if (stop_after != 0 && positionals >= stop_after) { end_of_options = true; } }; auto find_long = [&](std::string_view name) { const cmd::meta::OptionMeta* meta = nullptr; for (const auto& m : options) { if (m.long_name == name) { meta = &m; break; } } return meta; }; auto find_short = [&](char ch) { const cmd::meta::OptionMeta* meta = nullptr; for (const auto& m : options) { if (m.short_name.size() == 2 && m.short_name[0] == '-' && m.short_name[1] == ch) { meta = &m; break; } } return meta; }; auto has_numeric_meta = [&]() { for (const auto& m : options) { if (m.short_name == "-NUM") return true; } return false; }; auto is_digits = [](std::string_view value) { return !value.empty() && std::ranges::all_of(value, [](char c) { return std::isdigit(static_cast(c)) != 0; }); }; // Value handling shared by the long and single-dash-long forms: a // value taken from following argv entries is marked Value (and the // index advances past it, so the outer loop resumes after the value). auto swallow_long_value = [&](size_t& i, const cmd::meta::OptionMeta* meta, bool has_inline_value) { switch (meta->type) { case cmd::meta::OptionType::Int: case cmd::meta::OptionType::UInt: case cmd::meta::OptionType::UIntClamp: case cmd::meta::OptionType::String: if (!has_inline_value && i + 1 < args.size()) { roles[++i] = ArgRole::Value; } break; case cmd::meta::OptionType::TerminatedString: if (!has_inline_value) { while (++i < args.size()) { roles[i] = ArgRole::Value; if (args[i] == ";" || args[i] == "+") break; } } break; default: break; } }; for (size_t i = 0; i < args.size(); ++i) { std::string_view arg = args[i]; if (end_of_options) { roles[i] = ArgRole::Data; continue; } if (policy.recognize_double_dash && arg == "--") { roles[i] = ArgRole::Terminator; end_of_options = true; continue; } // ---------- long option ---------- if (policy.allow_long_options && arg.starts_with("--") && arg.size() > 2) { std::string_view name = arg; bool has_inline_value = false; if (policy.allow_long_equals) { if (auto eq = arg.find('='); eq != std::string_view::npos) { name = arg.substr(0, eq); has_inline_value = true; } } roles[i] = ArgRole::Option; const cmd::meta::OptionMeta* meta = find_long(name); if (meta == nullptr) { // Unabbreviated or unknown long: the abbreviation pass may // still expand a unique prefix, but it takes no value. std::vector matches; for (const auto& m : options) { if (m.long_name.size() > name.size() && m.long_name.starts_with(name)) { matches.push_back(m.long_name); } } if (matches.size() == 1) meta = find_long(matches[0]); } if (meta != nullptr) swallow_long_value(i, meta, has_inline_value); continue; } // ---------- single-dash long option (find -name, ...) ---------- if (policy.allow_single_dash_long_options && arg.size() > 2 && arg[0] == '-' && arg[1] != '-') { std::string_view exact_name = arg; bool exact_has_inline_value = false; if (policy.allow_long_equals) { if (auto eq = arg.find('='); eq != std::string_view::npos) { exact_name = arg.substr(0, eq); exact_has_inline_value = true; } } const cmd::meta::OptionMeta* exact_meta = nullptr; for (const auto& m : options) { if (!m.short_name.empty() && m.short_name == exact_name && m.short_name.size() > 2) { exact_meta = &m; break; } } if (exact_meta != nullptr) { roles[i] = ArgRole::Option; swallow_long_value(i, exact_meta, exact_has_inline_value); continue; } // Otherwise fall through to the short-cluster walk below. } // ---------- short option(s) ---------- if (arg.size() >= 2 && arg[0] == '-' && arg[1] != '-') { if (policy.allow_unknown_short_options_as_positionals) { bool has_registered_short_name = false; for (const auto& m : options) { if (m.short_name == arg) { has_registered_short_name = true; break; } } if (!has_registered_short_name) { bool glued_to_value_option = false; if (arg.size() > 2) { for (const auto& m : options) { if (m.short_name.size() == 2 && arg.starts_with(m.short_name)) { if ((m.type == cmd::meta::OptionType::String && policy.allow_short_attached_values) || (m.type == cmd::meta::OptionType::OptionalString && policy.allow_optional_short_attached_values) || (m.type == cmd::meta::OptionType::Int && policy.allow_short_attached_values) || (m.type == cmd::meta::OptionType::UInt && policy.allow_short_attached_values) || (m.type == cmd::meta::OptionType::UIntClamp && policy.allow_short_attached_values) || (m.type == cmd::meta::OptionType::OptionalInt && policy.allow_optional_short_attached_values) || (m.type == cmd::meta::OptionType::OptionalUInt && policy.allow_optional_short_attached_values) || (m.type == cmd::meta::OptionType::OptionalUIntClamp && policy.allow_optional_short_attached_values)) { glued_to_value_option = true; break; } } } } if (!glued_to_value_option) { roles[i] = ArgRole::Data; note_positional(); continue; } } } if (policy.allow_numeric_short_options && arg.size() > 1 && is_digits(arg.substr(1)) && has_numeric_meta()) { roles[i] = ArgRole::Option; continue; } if (!policy.allow_short_option_clusters && arg.size() > 2) { // The parser diagnoses this; the pre-passes leave it alone. roles[i] = ArgRole::Option; continue; } roles[i] = ArgRole::Option; for (size_t pos = 1; pos < arg.size(); ++pos) { char ch = arg[pos]; if (policy.allow_numeric_short_options && std::isdigit(static_cast(ch)) != 0 && has_numeric_meta()) { while (pos < arg.size() && std::isdigit(static_cast(arg[pos])) != 0) { ++pos; } --pos; continue; } const cmd::meta::OptionMeta* meta = find_short(ch); if (meta == nullptr) break; // unknown short; rest is opaque switch (meta->type) { case cmd::meta::OptionType::Bool: break; case cmd::meta::OptionType::Int: case cmd::meta::OptionType::UInt: case cmd::meta::OptionType::UIntClamp: case cmd::meta::OptionType::String: if (policy.allow_short_attached_values && pos + 1 < arg.size()) { pos = arg.size(); } else { if (i + 1 < args.size()) roles[++i] = ArgRole::Value; pos = arg.size(); } break; case cmd::meta::OptionType::OptionalInt: case cmd::meta::OptionType::OptionalUInt: case cmd::meta::OptionType::OptionalUIntClamp: case cmd::meta::OptionType::OptionalString: // With attached values the rest of the cluster is the // value; without them the cluster keeps walking (#1306). if (policy.allow_optional_short_attached_values && pos + 1 < arg.size()) { pos = arg.size(); } break; case cmd::meta::OptionType::TerminatedString: if (pos + 1 < arg.size()) { pos = arg.size(); } else { while (++i < args.size()) { roles[i] = ArgRole::Value; if (args[i] == ";" || args[i] == "+") break; } pos = arg.size(); } break; } } continue; } // ---------- positional ---------- roles[i] = ArgRole::Data; note_positional(); } return roles; } // #1581: GNU getopt_long is streaming: the first terminating event in // argv order (an option error, or --help/--version) decides the outcome, // so a --help/--version token only intercepts when every option token // before it parses clean. Run the argv prefix before the token through // the real parser -- the same parse_command_runtime make_context uses, // with the command's own policy -- instead of re-implementing option // validity in the dispatcher: an unknown long/short option, a flag // carrying "=value", or a missing value in the prefix all make it fail, // and the handler's own parse then reports the first error in order. // Value swallowing is already settled by classify_args_for_dispatch, so // a prefix judged at a help/version token never ends mid-value: an // option that takes a value has swallowed the help/version token itself // (mkdir --mode --help stays rc 1 missing operand, and grep --label // --help still searches). auto argv_prefix_has_parse_error( std::string_view cmd_name, std::span prefix, std::span options) -> bool { if (prefix.empty()) return false; const auto parsed = parse_command_runtime( prefix, options, option_policy_for_command(cmd_name)); return !parsed.ok; } // #1581: abbreviation candidates for a "--" token, over the same set the // abbreviation pass in run() uses: the command's declared long options // plus the implicit --help/--version. Only proper prefixes count; an // exact name is not an abbreviation of itself. auto abbreviation_matches( std::string_view name, std::span options) -> std::vector { std::vector matches; if (!name.starts_with("--") || name.size() <= 2) return matches; auto consider = [&matches](std::string_view candidate, std::string_view prefix) { if (candidate.size() > prefix.size() && candidate.starts_with(prefix) && std::ranges::find(matches, candidate) == matches.end()) { matches.push_back(candidate); } }; for (const auto &m : options) consider(m.long_name, name); consider(std::string_view("--help"), name); consider(std::string_view("--version"), name); return matches; } // #1581: true when `name` is the unique abbreviation of `target` among // the abbreviation candidates above. auto is_unambiguous_abbreviation( std::string_view name, std::string_view target, std::span options) -> bool { const auto matches = abbreviation_matches(name, options); return matches.size() == 1 && matches[0] == target; } // #1581: true when `name` abbreviates more than one candidate, so GNU // reports it ambiguous before any later token is reached. auto is_ambiguous_abbreviation( std::string_view name, std::span options) -> bool { return abbreviation_matches(name, options).size() > 1; } // #1305: GNU prints a usage tail after an option error for some // commands: grep gets its one-line Usage before the Try line, sed // gets its full help instead of the Try line. Returns false when the // tail replaces the Try line. auto print_parse_error_tail(std::string_view name) -> bool { if (name == "grep") { safeErrorPrintLn("Usage: grep [OPTION]... PATTERNS [FILE]..."); return true; } if (name == "sed") { std::string help = cmd::meta::Registry::get_help(name); if (!help.empty()) { safeErrorPrintLn(help); } return false; } return true; } // [GNU] Commands whose arguments are data strings rather than options: // long-option abbreviations are never expanded for them (`echo --hel` // prints "--hel"), and "--version" in an operand position is data, not a // flag. printf belongs here because printf.c parses options directly // rather than via getopt_long, precisely so that abbreviations such as // "--hel" are treated as the format string, not as --help; expr.c likewise // never abbreviates (`expr --hel` is an operand). // // This is the single source of truth for the set. The dispatcher's // abbreviation expansion and main.cpp's top-level --version pre-scan both // consult it through this function: #1215 was the two hand-copied tables // drifting apart (main's copy missed "expr", so `winuxcmd expr 1 // --version` printed the top-level version and exited 0 while GNU and the // expr shim reject the operand with exit 2). export bool is_literal_arg_command(std::string_view cmd_name) noexcept { static constexpr std::string_view kLiteralArgCommands[] = { "echo", "yes", "test", "[", "true", "false", "printf", "expr"}; return std::ranges::any_of( kLiteralArgCommands, [cmd_name](std::string_view name) { return name == cmd_name; }); } // Edition split of the entry-link surface (#1438, ruling of 2026-10-30). // // Every name here keeps its full implementation in both editions - the // multicall dispatcher still accepts `winuxcmd kill ...` - but the DEFAULT // edition does not materialize a per-name entry link next to winuxcmd.exe: // the user-facing semantics of these commands are defined by the host // shell's builtins, so an on-PATH exe entry advertises a dispatch the // builtin actually owns, and the exe form cannot be reconciled with the // builtin mechanism. `echo`, `printf` and `pwd` deliberately stay in the // default edition: they have real file-form work under rubash#2147's // literal-file gate. "env" is deliberately NOT in this list (#1622): env // is not a bash builtin (no $BUILTIN env in bash's builtins/*.def), so the // default edition ships env.exe like any other command. The FULL edition // materializes every registered entry. // // Build wiring: the CMake option WINUXCMD_PACKAGE_EDITION (`default` or // `full`) defines WINUXCMD_PACKAGE_EDITION_FULL for the winuxcmd-commands // target when it is `full`. Every consumer - wpm links rebuild/remove/ // verify, any packaging-side census, index generation - must read the names // through this one declaration; re-declaring the list anywhere else (a // second exclusion list in a packaging script, a hand-edited index files // array) is the defect class #1438 rules out. export namespace winux_edition { inline constexpr std::string_view kFullOnlyCommandNames[] = { "[", "false", "kill", "test", "time", "true"}; // True when this build ships the full entry set. consteval bool ships_full_entries() noexcept { #ifdef WINUXCMD_PACKAGE_EDITION_FULL return true; #else return false; #endif } inline constexpr bool is_full_only_command(std::string_view name) noexcept { return std::ranges::find(kFullOnlyCommandNames, name) != std::ranges::end(kFullOnlyCommandNames); } } // namespace winux_edition // Internal registry implementation class class RegistryImpl { std::unordered_map registry_; public: static auto parse_error_exit_code(std::string_view name) -> int { return behavior_for(name).parse_error_exit_code; } // Register a command with compile-time metadata template void add(std::string_view name, const cmd::meta::CommandMeta &meta, CommandInvoker handler) { // compile-time meta registry cmd::meta::Registry::register_command(name, meta); registry_.emplace( name, CommandEntryErased{meta.options(), handler, meta.brief_desc()}); } // Dispatch command execution int run(std::string_view cmdName, std::span args) { auto it = registry_.find(cmdName); if (it == registry_.end()) { safeErrorPrintLn(winux::i18n::format("core.error.command_not_found", "winuxcmd: command not found: {}", cmdName)); return 127; } const CommandBehavior behavior = behavior_for(cmdName); if (behavior.validate_args != nullptr) { if (auto invalid_arg = behavior.validate_args(args)) { if (behavior.validation_uses_trailing_option_wording) { safeErrorPrintLn(winux::i18n::format( "core.error.invalid_trailing_option", "{}: invalid trailing option -- {}", behavior.validation_prefix, *invalid_arg)); safeErrorPrintLn(winux::i18n::format( "common.try_help", "Try '{} --help' for more information.", behavior.validation_prefix)); } else { safeErrorPrintLn( winux::i18n::format("core.error.invalid_option_context", "{}: option used in invalid context -- {}", behavior.validation_prefix, *invalid_arg)); } return behavior.parse_error_exit_code; } } std::vector rewritten_storage; std::vector rewritten_views; std::span effective_args = args; for (size_t i = 0; i < behavior.rewrite_hook_count; ++i) { if (auto hook = behavior.rewrite_hooks[i]) { if (auto rewritten = hook(effective_args)) { effective_args = replace_effective_args( std::move(*rewritten), rewritten_storage, rewritten_views); } } } // Get meta data from the command auto options = it->second.options; // std::span // GNU getopt_long accepts any unambiguous abbreviation of a long option. // Normalise abbreviations against the command's declared long options plus // the implicit --help/--version, so hand-rolled option parsers get the // same behaviour. Commands whose leading arguments are data strings are // excluded (e.g. `echo --hel` must print "--hel", not help). { const bool literal_args = is_literal_arg_command(cmdName); if (!literal_args) { std::vector abbrev_storage; std::optional ambiguous; // #1303: only real option tokens are expanded; values and // wrapped-command operands keep their spelling (cp --suffix // --ver, grep --label --help). const std::vector roles = classify_args_for_dispatch(cmdName, effective_args, options); for (size_t ai = 0; ai < effective_args.size(); ++ai) { std::string_view arg = effective_args[ai]; if (roles[ai] != ArgRole::Option || !arg.starts_with("--")) { abbrev_storage.emplace_back(arg); continue; } std::string_view name = arg; std::string_view suffix; if (auto eq = arg.find('='); eq != std::string_view::npos) { name = arg.substr(0, eq); suffix = arg.substr(eq); } if (name.size() <= 2) { abbrev_storage.emplace_back(arg); continue; } bool exact = (name == "--help" || name == "--version"); for (const auto &m : options) { exact = exact || m.long_name == name; } if (exact) { abbrev_storage.emplace_back(arg); continue; } std::vector matches; auto consider = [&matches](std::string_view candidate, std::string_view prefix) { if (candidate.size() > prefix.size() && candidate.starts_with(prefix) && std::ranges::find(matches, candidate) == matches.end()) { matches.push_back(candidate); } }; for (const auto &m : options) consider(m.long_name, name); consider(std::string_view("--help"), name); consider(std::string_view("--version"), name); if (matches.empty()) { abbrev_storage.emplace_back(arg); continue; } if (matches.size() > 1) { std::string msg = "option '" + std::string(name) + "' is ambiguous; possibilities:"; for (std::string_view p : matches) { msg += " '"; msg += p; msg += "'"; } ambiguous = std::move(msg); break; } abbrev_storage.push_back(std::string(matches[0]) + std::string(suffix)); } if (ambiguous) { safeErrorPrintLn(std::string(cmdName) + ": " + *ambiguous); safeErrorPrintLn(winux::i18n::format( "common.try_help", "Try '{} --help' for more information.", cmdName)); return behavior.parse_error_exit_code; } effective_args = replace_effective_args( std::move(abbrev_storage), rewritten_storage, rewritten_views); } } if (behavior.special_dispatch != nullptr) { if (auto status = behavior.special_dispatch(it->second, effective_args)) { return *status; } } // Single argv-order scan for --help/--version (#1301/#1303): only // real option tokens count, so a value (grep --label --help) or a // wrapped command's operand (xargs echo --help, timeout 5 echo // --help, env echo --version) is never intercepted, and "--" still // ends scanning (echo -- --help prints "--help"). The first match // wins, so `cmd --version --help` prints the version, as GNU // does; `--help=x` / `--version=x` report "doesn't allow an // argument" instead of being intercepted. printf/test/[ narrow it // further: their --help/--version are honored only as the sole // argument, so `printf '%s\n' --help` prints "--help" and // `test --help x` is an expression error, not help. Commands that // opt out of standard interception (e.g. nohup, whose options end // at the wrapped command) skip the scan entirely. // #1581: the first terminating event in argv order wins -- an // option error before the help/version token suppresses the // interception entirely (mkdir --bogus --help is rc 1, not usage // on stdout; mkdir -q --help is rc 1, not usage). The prefix // before the event token is judged with // argv_prefix_has_parse_error, and only at an event token: judging // it at an ordinary option would misread a value that is simply // the next token (mkdir --mode -p --help must still print help). bool wants_help = false; bool wants_version = false; std::string_view no_argument_option; if (behavior.standard_interception_enabled(args)) { if (behavior.help_version_only_when_sole_argument) { wants_help = effective_args.size() == 1 && effective_args[0] == "--help"; wants_version = effective_args.size() == 1 && effective_args[0] == "--version"; } else { const std::vector roles = classify_args_for_dispatch(cmdName, effective_args, options); for (size_t i = 0; i < effective_args.size(); ++i) { if (roles[i] != ArgRole::Option) continue; const std::string_view arg = effective_args[i]; enum class Event { None, Help, Version, NoArgHelp, NoArgVersion }; Event event = Event::None; if (arg == "--help") { event = Event::Help; } else if (arg.starts_with("--help=")) { event = Event::NoArgHelp; } else if (arg == "--version") { event = Event::Version; } else if (arg.starts_with("--version=")) { event = Event::NoArgVersion; } else if (arg == "-v" && command_declares_version_short(options, "-v")) { event = Event::Version; } else if (arg == "-V" && command_declares_version_short(options, "-V")) { // [GNU] #1714: there is no global "-V means --version" rule. // GNU coreutils registers only the long --version spelling, so // `cksum -V` is "invalid option -- 'V'" with rc 1 while // procps/util-linux/ncurses tools that do document -V (free, // w, ps, col, clear, ...) print their version block. Only a // command whose own option table pairs -V with --version gets // the interception; every other applet judges -V itself (and // rejects it unless its table declares a different meaning, // e.g. `sort -V` = --version-sort, `chattr -V` = verbose). event = Event::Version; } if (event == Event::None) continue; if (argv_prefix_has_parse_error(cmdName, effective_args.first(i), options)) { // An earlier option already terminates the parse with an // error: no interception, the handler reports it. break; } switch (event) { case Event::Help: wants_help = true; break; case Event::Version: wants_version = true; break; case Event::NoArgHelp: no_argument_option = "--help"; break; case Event::NoArgVersion: no_argument_option = "--version"; break; case Event::None: break; } break; } } } if (wants_help) { cmd::meta::Registry::print_help(cmdName); // [GNU] true.c with false.c's EXIT_STATUS: 'false --help' // prints the help but exits with EXIT_FAILURE (1). return cmdName == "false" ? 1 : 0; } if (!no_argument_option.empty()) { safeErrorPrintLn( std::string(cmdName) + ": " + winux::i18n::format("common.error.option_no_argument", "option '{}' doesn't allow an argument", no_argument_option)); if (print_parse_error_tail(cmdName)) { safeErrorPrintLn(winux::i18n::format( "common.try_help", "Try '{} --help' for more information.", cmdName)); } return behavior.parse_error_exit_code; } if (wants_version) { // [GNU] --version prints a multi-line block in the shape of // "cmd (suite) version" + copyright/license/warranty/author (#1044). safePrintLn(std::string(cmdName) + " (WinuxCmd) " + std::string(WinuxCmd::VERSION_STRING)); safePrintLn("Copyright (C) 2026 WinuxCmd"); safePrintLn("License MIT ."); safePrintLn( "This is free software: you are free to change and " "redistribute it."); safePrintLn("There is NO WARRANTY, to the extent permitted by law."); safePrintLn(""); safePrintLn("Written by WinuxCmd contributors."); // [GNU] true.c:75-79 with false.c's EXIT_STATUS: the version // text is printed, then control returns EXIT_FAILURE (1). return cmdName == "false" ? 1 : 0; } return it->second.handler(effective_args); } // Print command help void help(std::string_view cmdName) { cmd::meta::Registry::print_help(cmdName); } // Get man page for a command std::string man(std::string_view cmdName) { return cmd::meta::Registry::get_man(cmdName); } // Get all registered command names std::vector> list() { std::vector> commands; commands.reserve(registry_.size()); for (const auto &[name, entry] : registry_) { commands.emplace_back(name, entry.brief_desc); } return commands; } // Get options for a specific command (for completion) std::vector command_options(std::string_view cmdName) { auto it = registry_.find(cmdName); if (it == registry_.end()) return {}; auto opts = it->second.options; std::vector result; result.reserve(opts.size()); for (const auto &opt : opts) { result.push_back({std::string(opt.short_name), std::string(opt.long_name), std::string(opt.description)}); } return result; } // [verb form] `winuxcmd ... --version` prints the top-level banner // only when "--version" is one of 's own option tokens under the // rule run() applies: the per-command interception policy (nohup stops // at the wrapped command, printf/test/[ honour it only as the sole // argument) and the #1303 role classification (wrapper operands, value // options and "--" are not options). Without this, `winuxcmd env echo // --version` stole the child's --version -- which #1438 turns into a // product-path defect, since the default edition reaches env/kill/... // only through the verb form. One source of truth with run(), so // main.cpp keeps no hand-copied table (WinuxCmd #1215). // #1581: and only when it is the first terminating event in argv // order: a --help before it means the command's help wins // (mkdir --help --version), and an option error before it means the // handler's diagnostic wins (mkdir --bogus --version). bool verb_form_wants_version(std::string_view cmdName, std::span args) { if (is_literal_arg_command(cmdName)) return false; auto it = registry_.find(cmdName); if (it == registry_.end()) return false; const CommandBehavior behavior = behavior_for(cmdName); if (!behavior.standard_interception_enabled(args)) return false; if (behavior.help_version_only_when_sole_argument) { return args.size() == 1 && args[0] == "--version"; } // #1581: the verb-form --version pre-scan obeys the same argv-order // termination contract as run(): the first terminating event wins. // A --help token (exact, or an unambiguous abbreviation of it) // before --version means the command's help wins, not the top-level // banner (mkdir --help --version); an ambiguous abbreviation // (mkdir --v --version) or an option error before --version // (mkdir --bogus --version) means the handler's diagnostic wins. // The args here are raw -- run() has not expanded abbreviations // yet -- so help/version abbreviations are recognised here, and // the prefix before a --version token is judged with the real // parser, exactly as run() judges it. const std::vector roles = classify_args_for_dispatch(cmdName, args, it->second.options); for (size_t i = 0; i < args.size(); ++i) { if (roles[i] != ArgRole::Option) continue; const std::string_view arg = args[i]; std::string_view name = arg; bool has_inline_value = false; if (auto eq = arg.find('='); eq != std::string_view::npos) { name = arg.substr(0, eq); has_inline_value = true; } // "--help=x" / "--version=x" is itself the first terminating // event: the no-argument error, not the banner. if (has_inline_value && (name == "--help" || name == "--version")) { return false; } if (name == "--help" || is_unambiguous_abbreviation(name, "--help", it->second.options)) { return false; } if (name == "--version" || is_unambiguous_abbreviation(name, "--version", it->second.options)) { return !argv_prefix_has_parse_error(cmdName, args.first(i), it->second.options); } if (is_ambiguous_abbreviation(name, it->second.options)) { return false; } } return false; } }; // Get singleton instance inline RegistryImpl &getImpl() { static RegistryImpl instance; return instance; } // Static interface class export class CommandRegistry { public: // Template method for registering commands with compile-time metadata template static void registerCommand(std::string_view name, const cmd::meta::CommandMeta &meta, CommandInvoker handler) { getImpl().add(name, meta, handler); } static int parseErrorExitCode(std::string_view name) noexcept { return RegistryImpl::parse_error_exit_code(name); } // #1305: print the command's option-error usage tail (grep's // one-line Usage, sed's full help). Returns false when the tail // replaces the Try line (sed). static bool printParseErrorTail(std::string_view name) { return print_parse_error_tail(name); } // Dispatch command execution (public interface) static int dispatch(std::string_view cmdName, std::span args) noexcept { return getImpl().run(cmdName, args); } // Print command help (public interface) static void printHelp(std::string_view cmdName) noexcept { getImpl().help(cmdName); } // Get all registered command names (public interface) static std::vector> getAllCommands() noexcept { return getImpl().list(); } // Get options for a command (for completion) static std::vector getCommandOptions( std::string_view cmdName) noexcept { return getImpl().command_options(cmdName); } // Check whether a command is registered. static bool hasCommand(std::string_view cmdName) noexcept { auto all = getImpl().list(); return std::ranges::any_of( all, [cmdName](const auto &item) { return item.first == cmdName; }); } // Verb-form `--version` scan (main.cpp): true only when --version is the // command's own option token under the dispatcher's interception rule. static bool verbFormWantsVersion(std::string_view cmdName, std::span args) noexcept { return getImpl().verb_form_wants_version(cmdName, args); } // Print man page for a command static std::string getManPage(std::string_view cmdName) noexcept { return getImpl().man(cmdName); } };