#include #include #include #include #include #include #include namespace Void::Build::Cli { namespace { Void::Result::Error make_error(std::string message) { return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, std::move(message)); } std::string trim(std::string_view text) { const auto first = text.find_first_not_of(" \t\r"); if (first == std::string_view::npos) { return {}; } const auto last = text.find_last_not_of(" \t\r"); return std::string{text.substr(first, last - first + 1)}; } std::vector split_lines(std::string_view text) { std::vector lines; std::size_t pos = 0; while (pos <= text.size()) { const auto eol = text.find('\n', pos); if (eol == std::string_view::npos) { lines.emplace_back(text.substr(pos)); break; } lines.emplace_back(text.substr(pos, eol - pos)); pos = eol + 1; } return lines; } // Splits " --project, -C Project directory" into its name and description parts. std::pair split_entry(std::string_view line) { const std::string content = trim(line); for (std::size_t i = 0; i + 1 < content.size(); ++i) { if (content[i] == ' ' && content[i + 1] == ' ') { return {trim(std::string_view{content}.substr(0, i)), trim(std::string_view{content}.substr(i))}; } } return {content, {}}; } OptionSpec parse_option_entry(std::string_view name_part, std::string description) { OptionSpec spec; spec.description = std::move(description); const std::string text{name_part}; std::size_t pos = 0; while (pos < text.size()) { const auto comma = text.find(", ", pos); const std::string token = trim(std::string_view{text}.substr( pos, comma == std::string::npos ? std::string::npos : comma - pos)); pos = comma == std::string::npos ? text.size() : comma + 2; std::string name = token; if (const auto value = name.find(" "); value != std::string::npos) { spec.takes_value = true; name = name.substr(0, value); } if (name.starts_with("--")) { if (spec.long_name.empty()) { spec.long_name = name; } } else if (name.starts_with("-") && spec.short_name.empty()) { spec.short_name = name; } } return spec; } struct ParsedHelp { std::string usage; std::string description; std::vector flags; std::vector options; std::vector> commands; }; ParsedHelp parse_help(std::string_view text) { ParsedHelp out; enum class Section { None, Commands, Arguments, Flags, Options }; enum class Last { None, Command, Flag, Option }; Section section = Section::None; Last last = Last::None; std::size_t last_index = 0; bool saw_usage = false; std::string description; const auto append = [](std::string &target, const std::string &text) { if (!target.empty()) { target += ' '; } target += text; }; for (const auto &line : split_lines(text)) { const std::string trimmed = trim(line); if (trimmed.starts_with("Usage:")) { out.usage = trim(std::string_view{trimmed}.substr(6)); saw_usage = true; continue; } if (trimmed == "Commands:") { section = Section::Commands; last = Last::None; continue; } if (trimmed == "Arguments:") { section = Section::Arguments; last = Last::None; continue; } if (trimmed == "Flags:") { section = Section::Flags; last = Last::None; continue; } if (trimmed == "Options:") { section = Section::Options; last = Last::None; continue; } if (trimmed.empty()) { continue; } const bool entry_line = line.starts_with(" ") && !line.starts_with(" "); if (!entry_line) { if (section == Section::None) { if (saw_usage) { append(description, trimmed); } continue; } switch (last) { case Last::Command: append(out.commands[last_index].second, trimmed); break; case Last::Flag: append(out.flags[last_index].description, trimmed); break; case Last::Option: append(out.options[last_index].description, trimmed); break; case Last::None: break; } continue; } const auto [name_part, entry_description] = split_entry(line); switch (section) { case Section::Commands: out.commands.emplace_back(name_part, entry_description); last = Last::Command; last_index = out.commands.size() - 1; break; case Section::Flags: out.flags.push_back(parse_option_entry(name_part, entry_description)); last = Last::Flag; last_index = out.flags.size() - 1; break; case Section::Options: out.options.push_back(parse_option_entry(name_part, entry_description)); last = Last::Option; last_index = out.options.size() - 1; break; case Section::Arguments: case Section::None: break; } } out.description = trim(description); return out; } std::string join_words(const std::vector &words) { std::string out; for (const auto &word : words) { if (!out.empty()) { out += ' '; } out += word; } return out; } Void::Result::Result run_help(const std::filesystem::path &vbs_executable, const std::vector &argv) { Platform::ProcessRequest req; req.executable = vbs_executable; req.arguments = argv; req.arguments.emplace_back("--help"); req.environment.set_vars["NO_COLOR"] = "1"; req.timeout = std::chrono::seconds{30}; auto res = Platform::run_supervised(req); if (!res) { return std::unexpected{res.error()}; } if (!res->succeeded()) { return std::unexpected{make_error(std::format("'vbs {} --help' failed (exit {})", join_words(argv), res->exit_code))}; } return res->stdout_data; } Void::Result::Result populate(const std::filesystem::path &vbs_executable, CommandSpec &command, int depth) { auto help = run_help(vbs_executable, command.argv); if (!help) { return std::unexpected{help.error()}; } const auto parsed = parse_help(*help); command.usage = parsed.usage; command.description = parsed.description; command.flags = parsed.flags; command.options = parsed.options; if (depth >= 4) { return {}; } for (const auto &[name, description] : parsed.commands) { CommandSpec child; child.name = name; child.argv = command.argv; child.argv.push_back(name); child.path = command.path + " " + name; child.description = description; auto populated = populate(vbs_executable, child, depth + 1); if (!populated) { return populated; } command.subcommands.push_back(std::move(child)); } return {}; } std::vector child_names(const CommandSpec &command) { std::vector names; names.reserve(command.subcommands.size()); for (const auto &child : command.subcommands) { names.push_back(child.name); } return names; } std::string case_pattern(const std::vector &names) { std::string pattern; for (const auto &name : names) { if (!pattern.empty()) { pattern += '|'; } pattern += name; } return pattern; } // Subcommand names plus every long and short option spelling, sorted and deduplicated. std::vector completion_words(const CommandSpec &command) { std::vector words = child_names(command); for (const auto &spec : command.flags) { if (!spec.long_name.empty()) { words.push_back(spec.long_name); } if (!spec.short_name.empty()) { words.push_back(spec.short_name); } } for (const auto &spec : command.options) { if (!spec.long_name.empty()) { words.push_back(spec.long_name); } if (!spec.short_name.empty()) { words.push_back(spec.short_name); } } std::sort(words.begin(), words.end()); words.erase(std::unique(words.begin(), words.end()), words.end()); return words; } std::string command_key(const CommandSpec &command) { return join_words(command.argv); } // Emits the path-walking preamble shared by the bash and zsh scripts. std::string render_path_walk(const std::vector &commands, std::string_view word_var) { std::string out; const std::string root_pattern = case_pattern(child_names(*commands.front())); out += " if [[ -z \"$path\" ]]; then\n"; out += std::format(" case \"${}\" in\n", word_var); out += std::format(" {}) path=\"${}\" ;;\n", root_pattern, word_var); out += " esac\n"; out += " else\n"; out += " case \"$path\" in\n"; for (const auto *command : commands) { if (command->subcommands.empty() || command->argv.empty()) { continue; } out += std::format(" \"{}\") case \"${}\" in {}) path=\"$path {}\" ;; esac ;;\n", command_key(*command), word_var, case_pattern(child_names(*command)), word_var); } out += " esac\n"; out += " fi\n"; return out; } std::string roff_escape(std::string_view text) { std::string out; for (const char c : text) { if (c == '\\') { out += "\\\\"; } else if (c == '-') { out += "\\-"; } else { out.push_back(c); } } return out; } std::string roff_text(std::string_view text) { std::string escaped = roff_escape(text); if (!escaped.empty() && (escaped.front() == '.' || escaped.front() == '\'')) { escaped.insert(escaped.begin(), '&'); } return escaped; } void append_option_section(std::string &out, std::string_view title, const std::vector &specs) { if (specs.empty()) { return; } out += std::format(".SH {}\n", title); for (const auto &spec : specs) { std::string names; if (!spec.long_name.empty()) { names += std::format("\\fB{}\\fR", roff_escape(spec.long_name)); } if (!spec.short_name.empty()) { if (!names.empty()) { names += ", "; } names += std::format("\\fB{}\\fR", roff_escape(spec.short_name)); } if (spec.takes_value) { names += " \\fI\\fR"; } out += ".TP\n" + names + "\n" + roff_text(spec.description) + "\n"; } } } // namespace std::vector CommandSpec::words() const { return completion_words(*this); } Void::Result::Result build_command_model(const std::filesystem::path &vbs_executable) { CommandSpec root; root.path = "vbs"; auto populated = populate(vbs_executable, root, 0); if (!populated) { return std::unexpected{populated.error()}; } return root; } std::vector flatten_commands(const CommandSpec &root) { std::vector out; out.push_back(&root); for (const auto &child : root.subcommands) { const auto nested = flatten_commands(child); out.insert(out.end(), nested.begin(), nested.end()); } return out; } std::string render_bash_completion(const CommandSpec &root) { const auto commands = flatten_commands(root); std::string out = "# bash completion for vbs (generated by `vbs completions --shell bash`)\n"; out += "_vbs_complete() {\n"; out += " local cur path word i opts\n"; out += " COMPREPLY=()\n"; out += " cur=\"${COMP_WORDS[COMP_CWORD]}\"\n"; out += " path=\"\"\n"; out += " for ((i = 1; i < COMP_CWORD; i++)); do\n"; out += " word=\"${COMP_WORDS[i]}\"\n"; out += " [[ \"$word\" == -* ]] && continue\n"; out += render_path_walk(commands, "word"); out += " done\n"; out += " opts=\"\"\n"; out += " case \"$path\" in\n"; for (const auto *command : commands) { out += std::format(" \"{}\") opts=\"{}\" ;;\n", command_key(*command), join_words(completion_words(*command))); } out += " *) opts=\"\" ;;\n"; out += " esac\n"; out += " COMPREPLY=( $(compgen -W \"$opts\" -- \"$cur\") )\n"; out += " return 0\n"; out += "}\n"; out += "complete -F _vbs_complete vbs\n"; return out; } std::string render_zsh_completion(const CommandSpec &root) { const auto commands = flatten_commands(root); std::string out = "#compdef vbs\n"; out += "# zsh completion for vbs (generated by `vbs completions --shell zsh`)\n"; out += "_vbs_complete() {\n"; out += " local cur path word i\n"; out += " local -a opts\n"; out += " cur=\"${words[CURRENT]}\"\n"; out += " path=\"\"\n"; out += " for ((i = 2; i < CURRENT; i++)); do\n"; out += " word=\"${words[i]}\"\n"; out += " [[ \"$word\" == -* ]] && continue\n"; out += render_path_walk(commands, "word"); out += " done\n"; out += " case \"$path\" in\n"; for (const auto *command : commands) { out += std::format(" \"{}\") opts=({}) ;;\n", command_key(*command), join_words(completion_words(*command))); } out += " *) opts=() ;;\n"; out += " esac\n"; out += " compadd -- $opts\n"; out += "}\n"; out += "if [ \"$funcstack[1]\" = \"_vbs_complete\" ]; then\n"; out += " _vbs_complete \"$@\"\n"; out += "else\n"; out += " compdef _vbs_complete vbs\n"; out += "fi\n"; return out; } std::string render_fish_completion(const CommandSpec &root) { const auto commands = flatten_commands(root); std::string out = "# fish completion for vbs (generated by `vbs completions --shell fish`)\n"; out += "function __vbs_path\n"; out += " set -l tokens (commandline -opc)\n"; out += " set -l path \"\"\n"; out += " for word in $tokens[2..-1]\n"; out += " if string match -q -- '-*' $word\n"; out += " continue\n"; out += " end\n"; out += " if test -z \"$path\"\n"; out += " switch $word\n"; out += std::format(" case {}\n", case_pattern(child_names(root))); out += " set path $word\n"; out += " end\n"; out += " else\n"; out += " switch $path\n"; for (const auto *command : commands) { if (command->subcommands.empty()) { continue; } out += std::format(" case '{}'\n", command_key(*command)); out += " switch $word\n"; out += std::format(" case {}\n", case_pattern(child_names(*command))); out += " set path \"$path $word\"\n"; out += " end\n"; } out += " end\n"; out += " end\n"; out += " end\n"; out += " echo $path\n"; out += "end\n"; out += "complete -c vbs -f\n"; for (const auto *command : commands) { out += std::format("complete -c vbs -n '__vbs_path = \"{}\"' -a '{}'\n", command_key(*command), join_words(completion_words(*command))); } return out; } std::string man_page_name(const CommandSpec &command) { std::string name = "vbs"; for (const auto &arg : command.argv) { name += "-" + arg; } return name; } std::string render_man_page(const CommandSpec &command, std::string_view version) { const std::string name = man_page_name(command); const std::string summary = command.description.empty() ? std::string{"VoidBuildSystem"} : command.description; std::string out; out += std::format(".TH {} 1 \"\" \"vbs {}\" \"VoidBuildSystem\"\n", roff_escape(name), roff_escape(version)); out += ".SH NAME\n"; out += std::format("{} \\- {}\n", roff_escape(name), roff_text(summary)); out += ".SH SYNOPSIS\n"; out += std::format(".B {}\n{}\n", roff_escape(name), roff_text(command.usage)); if (!command.subcommands.empty()) { out += ".SH COMMANDS\n"; for (const auto &child : command.subcommands) { out += std::format(".TP\n\\fB{}\\fR\n{}\n", roff_escape(child.name), roff_text(child.description)); } } append_option_section(out, "FLAGS", command.flags); append_option_section(out, "OPTIONS", command.options); out += ".SH SEE ALSO\n"; out += ".BR vbs (1)\n"; return out; } } // namespace Void::Build::Cli