diff --git a/CMakeLists.txt b/CMakeLists.txt index 2d4330a..5a3f273 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,7 @@ add_library(VoidBuild_Core STATIC src/Config/CmakeImport.cpp src/Config/Presets.cpp src/Config/Scaffold.cpp + src/Cli/CommandModel.cpp src/Daemon/Daemon.cpp src/Report/Cdash.cpp src/Report/Coverage.cpp diff --git a/include/Void/Build/Cli/CommandModel.hpp b/include/Void/Build/Cli/CommandModel.hpp new file mode 100644 index 0000000..7be4361 --- /dev/null +++ b/include/Void/Build/Cli/CommandModel.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Cli { + +struct OptionSpec { + std::string long_name; // "--project" (empty for a positional-only entry) + std::string short_name; // "-C" or empty + bool takes_value{false}; + std::string description; +}; + +struct CommandSpec { + std::string name; // "build", "use"; empty for the root command + std::string path; // "vbs", "vbs build", "vbs compdb use" + std::vector argv; // {"compdb", "use"} + std::string usage; + std::string description; + std::vector flags; + std::vector options; + std::vector subcommands; + + [[nodiscard]] std::vector words() const; +}; + +// Collects the whole command model by running ` --help` for the root command and +// every subcommand, so completions and man pages can never drift from the parser. +[[nodiscard]] Void::Result::Result +build_command_model(const std::filesystem::path &vbs_executable); + +// Flattens the tree into every command (root first, then depth-first). +[[nodiscard]] std::vector flatten_commands(const CommandSpec &root); + +[[nodiscard]] std::string render_bash_completion(const CommandSpec &root); +[[nodiscard]] std::string render_zsh_completion(const CommandSpec &root); +[[nodiscard]] std::string render_fish_completion(const CommandSpec &root); + +// roff man page for one command; `man_page_name` is its file stem ("vbs", "vbs-compdb-use"). +[[nodiscard]] std::string man_page_name(const CommandSpec &command); +[[nodiscard]] std::string render_man_page(const CommandSpec &command, std::string_view version); + +} // namespace Void::Build::Cli diff --git a/include/Void/Build/Util/UserCache.hpp b/include/Void/Build/Util/UserCache.hpp new file mode 100644 index 0000000..9b2c762 --- /dev/null +++ b/include/Void/Build/Util/UserCache.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Util { + +// Shared per-user cache root: $XDG_CACHE_HOME/vbs/, or ~/.cache/vbs/. +// +// These caches only ever hold content-addressed artifacts (toolchain probe results, compiled +// build descriptors) whose keys include the compiler identity and every input hash, so sharing +// them across build directories and projects cannot change a build's result. Set +// VBS_SHARED_CACHE=0 to keep every build directory self-contained (CI isolation). +[[nodiscard]] inline std::optional +user_cache_dir(std::string_view subdirectory) { + const std::string enabled = Void::Configuration::get_env_or("VBS_SHARED_CACHE", "1"); + if (enabled == "0" || enabled == "false" || enabled == "off") { + return std::nullopt; + } + std::filesystem::path base; + const std::string xdg = Void::Configuration::get_env_or("XDG_CACHE_HOME", ""); + if (!xdg.empty()) { + base = xdg; + } else { + const std::string home = Void::Configuration::get_env_or("HOME", ""); + if (home.empty()) { + return std::nullopt; + } + base = std::filesystem::path{home} / ".cache"; + } + std::error_code ec; + const auto dir = base / "vbs" / subdirectory; + std::filesystem::create_directories(dir, ec); + if (ec) { + return std::nullopt; + } + return dir; +} + +} // namespace Void::Build::Util diff --git a/src/Cli/CommandModel.cpp b/src/Cli/CommandModel.cpp new file mode 100644 index 0000000..5e0576c --- /dev/null +++ b/src/Cli/CommandModel.cpp @@ -0,0 +1,521 @@ +#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 diff --git a/src/Config/Frontend.cpp b/src/Config/Frontend.cpp index cffa66d..b34de97 100644 --- a/src/Config/Frontend.cpp +++ b/src/Config/Frontend.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include #include @@ -561,6 +563,30 @@ compile_descriptor(const FrontendOptions &options) { const auto exe_path = config_dir / ("descriptor_" + seed_id.substr(0, 16)); const auto meta_path = config_dir / ("descriptor_" + seed_id.substr(0, 16) + ".headers.json"); + // A fresh build directory can reuse a descriptor compiled for the same seed identity from + // the shared per-user cache: the identity covers the host compiler, the SDK, the generated + // driver source and every configuration source (path + content), and the discovered headers + // are re-verified below either way. + if (const auto shared_dir = Util::user_cache_dir("descriptors")) { + std::error_code shared_ec; + const bool local_missing = !std::filesystem::is_regular_file(exe_path, shared_ec) || + !std::filesystem::is_regular_file(meta_path, shared_ec); + const auto shared_exe = *shared_dir / exe_path.filename(); + const auto shared_meta = *shared_dir / meta_path.filename(); + if (local_missing && std::filesystem::is_regular_file(shared_exe, shared_ec) && + std::filesystem::is_regular_file(shared_meta, shared_ec)) { + std::filesystem::copy_file(shared_exe, exe_path, + std::filesystem::copy_options::overwrite_existing, + shared_ec); + std::filesystem::copy_file(shared_meta, meta_path, + std::filesystem::copy_options::overwrite_existing, + shared_ec); + if (!shared_ec) { + Void::Log::debug("Config", "descriptor artifact reused from the shared cache"); + } + } + } + // Check if cached descriptor executable exists AND all previously discovered headers match! // Header entries carry a stat fingerprint (size + mtime) beside the SHA-256: when the // fingerprint is unchanged the content hash is trusted and no file is read. Legacy entries @@ -772,6 +798,15 @@ compile_descriptor(const FrontendOptions &options) { } write_meta(persisted_headers); + // Publish the freshly compiled descriptor to the shared per-user cache (best effort). + if (const auto shared_dir = Util::user_cache_dir("descriptors")) { + std::error_code shared_ec; + std::filesystem::copy_file(exe_path, *shared_dir / exe_path.filename(), + std::filesystem::copy_options::overwrite_existing, shared_ec); + std::filesystem::copy_file(meta_path, *shared_dir / meta_path.filename(), + std::filesystem::copy_options::overwrite_existing, shared_ec); + } + CompiledDescriptor desc; desc.executable_path = exe_path; desc.seed_identity_hash = seed_id; diff --git a/src/Main.cpp b/src/Main.cpp index de70f3b..02e17bf 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -3742,6 +3743,92 @@ struct GraphCmdOptions { std::string format{"dot"}; }; +struct CompletionsCmdOptions { + std::string shell_arg; + std::optional output_arg; +}; + +struct ManCmdOptions { + std::optional output_arg; +}; + +int execute_completions_command(const CompletionsCmdOptions &opts) { + if (opts.shell_arg != "bash" && opts.shell_arg != "zsh" && opts.shell_arg != "fish") { + std::cerr << "vbs completions: unsupported --shell '" << opts.shell_arg + << "' (expected bash, zsh or fish)\n"; + return 2; + } + auto exe = Platform::current_executable_path(); + if (!exe) { + std::cerr << "vbs completions: " << exe.error().message() << '\n'; + return 1; + } + auto model = Cli::build_command_model(*exe); + if (!model) { + std::cerr << "vbs completions: " << model.error().message() << '\n'; + return 1; + } + std::string script; + if (opts.shell_arg == "bash") { + script = Cli::render_bash_completion(*model); + } else if (opts.shell_arg == "zsh") { + script = Cli::render_zsh_completion(*model); + } else { + script = Cli::render_fish_completion(*model); + } + if (opts.output_arg) { + if (auto written = Platform::atomic_write_file(*opts.output_arg, script, false); !written) { + std::cerr << "vbs completions: cannot write '" << *opts.output_arg + << "': " << written.error().message() << '\n'; + return 1; + } + std::cout << "wrote " << *opts.output_arg << '\n'; + return 0; + } + std::cout << script; + return 0; +} + +int execute_man_command(const ManCmdOptions &opts) { + auto exe = Platform::current_executable_path(); + if (!exe) { + std::cerr << "vbs man: " << exe.error().message() << '\n'; + return 1; + } + auto model = Cli::build_command_model(*exe); + if (!model) { + std::cerr << "vbs man: " << model.error().message() << '\n'; + return 1; + } + const std::string version{Bootstrap::version}; + if (!opts.output_arg) { + std::cout << Cli::render_man_page(*model, version); + return 0; + } + std::error_code ec; + const std::filesystem::path out_dir{*opts.output_arg}; + std::filesystem::create_directories(out_dir, ec); + if (ec) { + std::cerr << "vbs man: cannot create '" << out_dir.string() << "': " << ec.message() + << '\n'; + return 1; + } + std::size_t written_pages = 0; + for (const auto *command : Cli::flatten_commands(*model)) { + const auto page = out_dir / (Cli::man_page_name(*command) + ".1"); + if (auto wrote = Platform::atomic_write_file(page, Cli::render_man_page(*command, version), + false); + !wrote) { + std::cerr << "vbs man: cannot write '" << page.string() + << "': " << wrote.error().message() << '\n'; + return 1; + } + ++written_pages; + } + std::cout << "wrote " << written_pages << " man page(s) to " << out_dir.string() << '\n'; + return 0; +} + int execute_graph_command(const GraphCmdOptions &opts) { if (opts.format != "dot" && opts.format != "json") { std::cerr << "vbs graph: unsupported --format '" << opts.format @@ -4132,6 +4219,8 @@ int main(int argc, char **argv) { const std::string clean_default_build = clean_opts.build_arg; GraphCmdOptions graph_opts; graph_opts.project_arg = cwd; + CompletionsCmdOptions completions_opts; + ManCmdOptions man_opts; IdeCmdOptions ide_opts; ide_opts.project_arg = cwd; DaemonCmdOptions daemon_opts; @@ -4556,6 +4645,21 @@ int main(int argc, char **argv) { root.subcommand("doctor", "Check host compilers, tools, and VBS runtime capabilities"); add_log_flags(doctor_cmd); + auto &completions_cmd = root.subcommand( + "completions", "Print a shell completion script generated from the CLI itself"); + completions_cmd + .option_default("--shell", "-s", "Shell: bash, zsh or fish", completions_opts.shell_arg, + "bash") + .option("--output", "-o", "Write the script to this file instead of stdout", + completions_opts.output_arg); + add_log_flags(completions_cmd); + + auto &man_cmd = + root.subcommand("man", "Render man pages for vbs and every subcommand"); + man_cmd.option("--output", "-o", "Directory to write vbs.1 and vbs-.1 pages into", + man_opts.output_arg); + add_log_flags(man_cmd); + auto &graph_cmd = root.subcommand("graph", "Export target dependency graph in Graphviz DOT or JSON format"); graph_cmd.option_default("--project", "-C", "Project directory", graph_opts.project_arg, cwd) @@ -4924,6 +5028,12 @@ int main(int argc, char **argv) { if (cmd == "doctor") { return execute_doctor_command(); } + if (cmd == "completions") { + return execute_completions_command(completions_opts); + } + if (cmd == "man") { + return execute_man_command(man_opts); + } if (cmd == "graph") { return execute_graph_command(graph_opts); } diff --git a/src/Toolchain/Driver.cpp b/src/Toolchain/Driver.cpp index 555e714..e7cb7d7 100644 --- a/src/Toolchain/Driver.cpp +++ b/src/Toolchain/Driver.cpp @@ -4,8 +4,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -410,14 +412,38 @@ discover_and_probe(const ProfileContext &context, } const std::string probe_cache_key = key_hasher.finalize_hex(); + // Probe results are content-addressed by compiler identity, sysroot, target and the relevant + // environment, so a shared per-user cache can serve fresh build directories (CI jobs, new + // clones) without re-running ~20 compiler probes. + const auto shared_probe_dir = Util::user_cache_dir("probes"); + const auto load_cached = [&](const std::filesystem::path &file) + -> std::optional { + auto cached_text = Void::FileSystem::read_file(file); + if (!cached_text) { + return std::nullopt; + } + auto cached = deserialize_capabilities(*cached_text); + if (!cached) { + return std::nullopt; + } + cached->relevant_env = relevant_env; + attach_shader_tools(*cached); + return *cached; + }; if (cache_dir) { - const auto cache_file = *cache_dir / (probe_cache_key + ".json"); - if (auto cached_text = Void::FileSystem::read_file(cache_file); cached_text) { - if (auto cached = deserialize_capabilities(*cached_text); cached) { - cached->relevant_env = relevant_env; - attach_shader_tools(*cached); - return *cached; + if (auto cached = load_cached(*cache_dir / (probe_cache_key + ".json"))) { + return *cached; + } + } + if (shared_probe_dir) { + if (auto cached = load_cached(*shared_probe_dir / (probe_cache_key + ".json"))) { + if (cache_dir) { + // Seed the build-local cache so later runs never touch the shared one. + (void)Platform::atomic_write_file(*cache_dir / (probe_cache_key + ".json"), + serialize_capabilities(*cached), false); } + Void::Log::debug("Toolchain", "probe capabilities reused from the shared cache"); + return *cached; } } @@ -566,6 +592,10 @@ discover_and_probe(const ProfileContext &context, const auto cache_file = *cache_dir / (probe_cache_key + ".json"); (void)Platform::atomic_write_file(cache_file, serialize_capabilities(cap), false); } + if (shared_probe_dir) { + (void)Platform::atomic_write_file(*shared_probe_dir / (probe_cache_key + ".json"), + serialize_capabilities(cap), false); + } attach_shader_tools(cap); return cap; diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 7e76144..568e72e 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -35,6 +35,9 @@ check_process(0 "Usage: vbs explain " "" explain --help) check_process(0 "--format" "" explain --help) check_process(2 "" "unsupported --format" explain --format xml) check_process(0 "--trace" "" build --help) +check_process(0 "Usage: vbs completions " "" completions --help) +check_process(2 "" "unsupported --shell" completions --shell tcsh) +check_process(0 "Usage: vbs man " "" man --help) check_process(2 "" "invalid --repeat mode" test --repeat bogus) check_process(2 "" "invalid --repeat count" test --repeat until-pass:0) check_process(2 "" "invalid --retry value" test --retry 99) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index e349006..c2c2d94 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -4069,3 +4069,148 @@ void build(Void::Build::Project &p) { Void::Testing::expect(saw_phase); Void::Testing::expect(saw_action); } + +// === Cold-start performance: shared per-user descriptor and probe caches === +VOID_TEST(FullV1Tests, shared_user_cache_reuses_descriptor_and_probes_across_build_dirs) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_shared_cache_"}; + const auto proj = tmp / "proj"; + const auto cache = tmp / "cache"; + + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("demo").sources({"src/a.cpp"}); + p.executable("app").sources({"src/main.cpp"}).link(lib); +} +)cpp"); + write_file(proj / "src" / "a.cpp", "int a() { return 1; }\n"); + write_file(proj / "src" / "main.cpp", "int a();\nint main() { return a() == 1 ? 0 : 1; }\n"); + + auto run_vbs = [&](const std::filesystem::path &build_dir, bool shared) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = {"build", "--project", proj.string(), "--build-dir", build_dir.string(), + "--jobs", "2"}; + req.environment.set_vars["XDG_CACHE_HOME"] = cache.string(); + if (!shared) { + req.environment.set_vars["VBS_SHARED_CACHE"] = "0"; + } + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + + // First build in a fresh build directory compiles the descriptor and probes the toolchain. + auto first = run_vbs(tmp / "build-a", true); + Void::Testing::expect(first.has_value() && first->succeeded()); + if (first) { + Void::Testing::expect((first->stdout_data + first->stderr_data).find("compiled") != + std::string::npos); + } + Void::Testing::expect(std::filesystem::exists(cache / "vbs" / "descriptors")); + Void::Testing::expect(std::filesystem::exists(cache / "vbs" / "probes")); + + // A second, independent build directory reuses both artifacts instead of recompiling. + auto second = run_vbs(tmp / "build-b", true); + Void::Testing::expect(second.has_value() && second->succeeded()); + if (second) { + Void::Testing::expect((second->stdout_data + second->stderr_data) + .find("up to date (cached)") != std::string::npos); + } + + // Opting out keeps a build directory self-contained. + auto isolated = run_vbs(tmp / "build-c", false); + Void::Testing::expect(isolated.has_value() && isolated->succeeded()); + if (isolated) { + Void::Testing::expect((isolated->stdout_data + isolated->stderr_data).find("compiled") != + std::string::npos); + } +} + +// === CLI surface: generated shell completions and man pages === +VOID_TEST(FullV1Tests, completions_and_man_pages_are_generated_from_the_cli) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_completions_"}; + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{120}; + return Platform::run_supervised(req); + }; + + auto bash_script = run_vbs({"completions", "--shell", "bash"}); + Void::Testing::expect(bash_script.has_value() && bash_script->succeeded()); + if (bash_script) { + Void::Testing::expect(bash_script->stdout_data.find("_vbs_complete") != std::string::npos); + Void::Testing::expect(bash_script->stdout_data.find("complete -F _vbs_complete vbs") != + std::string::npos); + Void::Testing::expect(bash_script->stdout_data.find("--project") != std::string::npos); + Void::Testing::expect(bash_script->stdout_data.find("\"compdb use\")") != + std::string::npos); + // The generated script must be valid bash. + if (const auto bash = Platform::resolve_executable("bash"); bash) { + const auto script_path = tmp / "vbs.bash"; + write_file(script_path, bash_script->stdout_data); + Platform::ProcessRequest check; + check.executable = *bash; + check.arguments = {"-n", script_path.string()}; + check.timeout = std::chrono::seconds{30}; + auto checked = Platform::run_supervised(check); + Void::Testing::expect(checked.has_value() && checked->succeeded()); + } + } + + auto zsh_script = run_vbs({"completions", "--shell", "zsh"}); + Void::Testing::expect(zsh_script.has_value() && zsh_script->succeeded()); + if (zsh_script) { + Void::Testing::expect(zsh_script->stdout_data.find("#compdef vbs") != std::string::npos); + Void::Testing::expect(zsh_script->stdout_data.find("compadd") != std::string::npos); + } + + auto fish_script = run_vbs({"completions", "--shell", "fish"}); + Void::Testing::expect(fish_script.has_value() && fish_script->succeeded()); + if (fish_script) { + Void::Testing::expect(fish_script->stdout_data.find("complete -c vbs") != std::string::npos); + Void::Testing::expect(fish_script->stdout_data.find("__vbs_path") != std::string::npos); + } + + auto bad_shell = run_vbs({"completions", "--shell", "tcsh"}); + Void::Testing::expect(bad_shell.has_value() && bad_shell->exit_code == 2); + + // Root man page on stdout. + auto man_root = run_vbs({"man"}); + Void::Testing::expect(man_root.has_value() && man_root->succeeded()); + if (man_root) { + Void::Testing::expect(man_root->stdout_data.find(".TH vbs 1") != std::string::npos); + Void::Testing::expect(man_root->stdout_data.find(".SH COMMANDS") != std::string::npos); + Void::Testing::expect(man_root->stdout_data.find(".SH OPTIONS") != std::string::npos); + } + + // A full page set on disk, including nested commands. + const auto man_dir = tmp / "man"; + auto man_pages = run_vbs({"man", "--output", man_dir.string()}); + Void::Testing::expect(man_pages.has_value() && man_pages->succeeded()); + Void::Testing::expect(std::filesystem::exists(man_dir / "vbs.1")); + Void::Testing::expect(std::filesystem::exists(man_dir / "vbs-build.1")); + Void::Testing::expect(std::filesystem::exists(man_dir / "vbs-compdb-use.1")); + std::size_t page_count = 0; + std::error_code ec; + for (const auto &entry : std::filesystem::directory_iterator(man_dir, ec)) { + if (entry.path().extension() == ".1") { + ++page_count; + } + } + Void::Testing::expect(page_count >= 20); + auto nested = Void::FileSystem::read_file(man_dir / "vbs-compdb-use.1"); + Void::Testing::require(nested.has_value()); + Void::Testing::expect(nested->find(".TH vbs\\-compdb\\-use 1") != std::string::npos); +}