Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit ef21df73e807181ef3cfeaa6f83ca50fa10e6e2e
parent 634b60d251288d81e772b5c21326d60d76bf8056
Author: sentomk <mk20040924@outlook.com>
Date:   Sat, 21 Nov 2026 01:30:17 +0800

feat: fetch Git dependencies during builds

Diffstat:
Mkumo.toml | 10++++++++++
Mkumo_builder.cpp | 275++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
2 files changed, 275 insertions(+), 10 deletions(-)

diff --git a/kumo.toml b/kumo.toml @@ -47,3 +47,13 @@ flags = ["-O2", "-DNDEBUG"] [asan] flags = ["-g", "-O1", "-fsanitize=address,undefined", "-fno-omit-frame-pointer"] link = ["-fsanitize=address,undefined"] + +# Header-only Git dependencies are fetched on the first build that needs them. +# Cached tags stay at the commit they first resolved to. Use a full commit ID +# for reproducible checkouts if an upstream tag might move. +# Include paths are relative to the dependency checkout. +# +# [deps.patternia] +# git = "https://github.com/SentoMK/patternia.git" +# rev = "v0.9.6" +# include = ["include"] diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -66,6 +66,7 @@ #include <map> #include <sstream> #include <string> +#include <string_view> #include <system_error> #include <thread> #include <vector> @@ -308,7 +309,7 @@ static void print_command(const Cmd& cmd) { /// multi-line strings) is a syntax error. So is a key the builder does not /// know, so that a typo is never silently ignored. /// -/// All keys are optional: +/// All top-level keys are optional: /// - `name`: name of the executable, without the `.exe` that Windows adds /// (default: the name of the project directory); /// - `compiler`: the C++ compiler (default: `clang++`); @@ -325,8 +326,18 @@ static void print_command(const Cmd& cmd) { /// A platform or profile table may hold `compiler`, `flags` and `link`. On that /// platform or profile `compiler` overrides the top-level setting, and /// `flags`/`link` are appended. +/// A `[deps.name]` table declares a Git URL, a tag or full commit ID, and +/// header directories relative to the dependency's checkout. /// @{ +/// @brief The source, revision and header directories of a Git dependency. +struct Dependency { + std::string name; + std::string git; + std::string rev; + Cmd include_dirs; +}; + /// @brief The settings of the project, as read from #CONFIG_FILE. /// /// Output layout, for `src = "src"`, `out = "build"`, `name = "kumo"` and the @@ -349,6 +360,7 @@ struct Config { Cmd flags; ///< Compile flags, with platform and profile added. Cmd objcxx_flags; ///< Extra compile flags for `.mm` files. Cmd link_flags; ///< Link flags, with platform and profile added. + std::vector<Dependency> dependencies; }; /// @brief Reports a problem with #CONFIG_FILE and exits. @@ -366,6 +378,8 @@ struct Config { static constexpr const char* PLATFORM_TABLES[] = {"mac", "linux", "windows"}; /// @brief The profile tables supported in `kumo.toml`. static constexpr const char* PROFILE_TABLES[] = {"debug", "release", "asan"}; +static constexpr std::string_view DEPENDENCY_PREFIX = "deps."; +static const fs::path DEPENDENCY_CACHE = ".cache/kumoko/deps"; /// @brief One `key = value` pair of the file. struct Entry { @@ -390,12 +404,13 @@ class ConfigParser { } /// @brief Parses the whole text. - Table parse() { + Table parse(std::map<std::string, int>& dependency_tables) { Table table; std::string section; // the table being filled; empty at the top level std::vector<std::string> tables_seen; for (skip_blank(true); pos_ < text_.size(); skip_blank(true)) { if (text_[pos_] == '[') { + const int line = line_here(); section = parse_header(); // A table may be opened only once, as in TOML, so that its keys are // never split over two places. @@ -404,6 +419,9 @@ class ConfigParser { config_error(line_here(), "duplicate table '[" + section + "]'"); } tables_seen.push_back(section); + if (section.starts_with(DEPENDENCY_PREFIX)) { + dependency_tables.emplace(section, line); + } } else { parse_pair(section, table); } @@ -469,12 +487,23 @@ class ConfigParser { return text_.substr(start, pos_ - start); } - /// @brief Reads a `[name]` line and returns the name. + /// @brief Reads a `[name]` or `[deps.name]` table header. std::string parse_header() { ++pos_; // '[' skip_blank(false); std::string name = parse_name("a table name"); skip_blank(false); + if (name == "deps" && peek() == '.') { + ++pos_; + skip_blank(false); + const std::string dependency = parse_name("a dependency name"); + if (dependency.find_first_not_of("abcdefghijklmnopqrstuvwxyz" + "0123456789_-") != std::string::npos) { + fail("dependency names use lowercase ASCII letters, digits, '_' and '-'"); + } + name += "." + dependency; + skip_blank(false); + } if (peek() != ']') fail("expected ']'"); ++pos_; end_line(); @@ -486,7 +515,8 @@ class ConfigParser { const bool known_profile = std::find(std::begin(PROFILE_TABLES), std::end(PROFILE_TABLES), name) != std::end(PROFILE_TABLES); - if (!known_platform && !known_profile) { + if (!known_platform && !known_profile && + !name.starts_with(DEPENDENCY_PREFIX)) { config_error(line_here(), "unknown table '[" + name + "]'"); } return name; @@ -605,7 +635,8 @@ static Config load_config(const std::string& profile) { } std::stringstream buffer; buffer << file.rdbuf(); - Table table = ConfigParser(buffer.str()).parse(); + std::map<std::string, int> dependency_tables; + Table table = ConfigParser(buffer.str()).parse(dependency_tables); // Each take_*() removes the key from the table, so that what is left at the // end is exactly the unknown keys. @@ -671,6 +702,31 @@ static Config load_config(const std::string& profile) { } } + for (const auto& [section, line] : dependency_tables) { + Dependency dep{ + section.substr(DEPENDENCY_PREFIX.size()), + take_string(section + ".git", ""), + take_string(section + ".rev", ""), + take_list(section + ".include"), + }; + if (dep.git.empty() || dep.rev.empty() || dep.include_dirs.empty()) { + config_error(line, "'[" + section + "]' needs git, rev, and include"); + } + if (dep.git.find_first_of("\r\n\0", 0, 3) != std::string::npos || + dep.rev.find_first_of("\r\n\0", 0, 3) != std::string::npos) { + config_error(line, "dependency git and rev cannot contain line breaks or NUL"); + } + for (const std::string& dir : dep.include_dirs) { + const fs::path path(dir); + if (dir.find('\0') != std::string::npos || path.has_root_path() || + (path != "." && !is_inside_project(path))) { + config_error(line, "'" + section + + ".include' paths must stay inside the dependency"); + } + } + cfg.dependencies.push_back(std::move(dep)); + } + // Report the unknown key that was written first. const Entry* first = nullptr; std::string first_key; @@ -1228,7 +1284,8 @@ static void append_list(std::ostringstream& ss, const char* key, } /// @brief Computes a fingerprint of the active compiler and build flags. -static std::string toolchain_fingerprint(const Config& cfg) { +static std::string toolchain_fingerprint(const Config& cfg, + const Cmd& dependency_commits) { const std::string version = capture({cfg.compiler, "--version"}); if (version.empty()) { print_error("cannot run compiler '" + cfg.compiler + "'"); @@ -1241,19 +1298,24 @@ static std::string toolchain_fingerprint(const Config& cfg) { append_list(ss, "flags", cfg.flags); append_list(ss, "objcxx_flags", cfg.objcxx_flags); append_list(ss, "link", cfg.link_flags); + if (!dependency_commits.empty()) { + append_list(ss, "dependencies", dependency_commits); + } return ss.str(); } /// @brief Clears stale build outputs if the compiler or flags changed. -static void check_toolchain_cache(const Config& cfg) { +static void check_toolchain_cache(const Config& cfg, + const Cmd& dependency_commits) { const fs::path stamp = cfg.out_dir / ".toolchain"; - const std::string current = toolchain_fingerprint(cfg); + const std::string current = toolchain_fingerprint(cfg, dependency_commits); if (fs::exists(stamp)) { std::ifstream in(stamp, std::ios::binary); std::ostringstream old; old << in.rdbuf(); if (old.str() == current) return; + in.close(); // Windows cannot remove the stamp while this stream is open. log_step(Style::Cyan, "rebuild", "toolchain or flags changed, clearing " + cfg.out_dir.generic_string() + "/"); @@ -1274,6 +1336,196 @@ static void check_toolchain_cache(const Config& cfg) { /// @} +/// @name Header-only dependencies +/// @{ + +static bool dependency_error(const Dependency& dep, const std::string& message) { + print_error("dependency '" + dep.name + "' (" + dep.rev + "): " + message); + return false; +} + +static bool is_commit_id(std::string_view rev) { + return (rev.size() == 40 || rev.size() == 64) && + rev.find_first_not_of("0123456789abcdefABCDEF") == std::string_view::npos; +} + +/// @brief A portable cache name derived from a dependency's URL and revision. +/// +/// The receipt also records the original values to detect a hash collision. +static std::string dependency_cache_key(const Dependency& dep) { + std::uint64_t hash = 14695981039346656037ull; + for (unsigned char byte : dep.git + "\n" + dep.rev) { + hash ^= byte; + hash *= 1099511628211ull; + } + return std::to_string(hash); +} + +static bool dependency_path_within(const fs::path& inner, const fs::path& outer) { + auto component = inner.begin(); + for (const fs::path& part : outer) { + if (component == inner.end()) return false; +#if defined(_WIN32) + if (CompareStringOrdinal(component->c_str(), -1, part.c_str(), -1, TRUE) != + CSTR_EQUAL) { + return false; + } +#else + if (*component != part) return false; +#endif + ++component; + } + return true; +} + +static bool valid_dependency_cache(const Config& cfg) { + const fs::path project = fs::canonical(fs::current_path()); + const fs::path cache = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE)); + if (!dependency_path_within(cache, project) || + dependency_path_within(project, cache)) { + print_error("dependency cache must be inside the project"); + return false; + } + for (const fs::path* dir : {&cfg.src_dir, &cfg.tests_dir, &cfg.clean_dir}) { + const fs::path resolved = fs::weakly_canonical(fs::absolute(*dir)); + if (dependency_path_within(cache, resolved) || + dependency_path_within(resolved, cache)) { + print_error("dependency cache overlaps " + dir->generic_string()); + return false; + } + } + return true; +} + +static bool dependency_include_flags(const Dependency& dep, + const fs::path& entry, Cmd& flags) { + const fs::path source = entry / "source"; + if (!fs::is_directory(source)) { + return dependency_error(dep, "missing dependency checkout"); + } + const fs::path root = fs::canonical(source); + if (!dependency_path_within(root, fs::canonical(entry))) { + return dependency_error(dep, "checkout points outside its cache entry"); + } + for (const std::string& dir : dep.include_dirs) { + const fs::path path = (source / dir).lexically_normal(); + if (!fs::is_directory(path) || + !dependency_path_within(fs::canonical(path), root)) { + return dependency_error(dep, "missing or invalid include directory '" + dir + + "'"); + } + flags.push_back("-I" + path.generic_string()); + } + return true; +} + +/// @brief Fetches and validates a dependency before it enters the build cache. +static bool populate_dependency(const Dependency& dep, const fs::path& staging) { + std::string ref = dep.rev; + const bool is_tag = !is_commit_id(ref); + if (is_tag) { + if (!ref.starts_with("refs/tags/")) ref = "refs/tags/" + ref; + if (!run({"git", "check-ref-format", ref})) { + return dependency_error(dep, "invalid Git tag"); + } + } + + log_step(Style::Cyan, "fetch", dep.name + " " + dep.rev); + const std::string source = (staging / "source").generic_string(); + if (!run({"git", "clone", "--no-checkout", "--no-hardlinks", + "--no-recurse-submodules", "--", dep.git, source})) { + return dependency_error(dep, "git clone failed"); + } + std::string commit = capture({"git", "-C", source, "rev-parse", "--verify", + "--end-of-options", ref + "^{commit}"}); + while (!commit.empty() && (commit.back() == '\n' || commit.back() == '\r')) { + commit.pop_back(); + } + const bool matches_commit = + is_tag || (commit.size() == ref.size() && + std::equal(commit.begin(), commit.end(), ref.begin(), + [](unsigned char a, unsigned char b) { + return std::tolower(a) == std::tolower(b); + })); + if (!is_commit_id(commit) || !matches_commit) { + return dependency_error(dep, is_tag ? "Git tag not found" + : "Git commit not found"); + } + if (!run({"git", "-C", source, "checkout", "--quiet", "--detach", + "--no-recurse-submodules", commit})) { + return dependency_error(dep, "git checkout failed"); + } + + Cmd flags; + if (!dependency_include_flags(dep, staging, flags)) return false; + std::ofstream receipt(staging / "revision", std::ios::binary); + receipt << dep.git << '\n' << dep.rev << '\n' << commit << '\n'; + receipt.close(); + if (!receipt) return dependency_error(dep, "cannot write cache receipt"); + return true; +} + +static bool prepare_dependency(const Dependency& dep, Cmd& flags, Cmd& commits) { + const fs::path parent = DEPENDENCY_CACHE / ("dep-" + dep.name); + const fs::path root = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE)); + const std::string key = dependency_cache_key(dep); + const fs::path entry = parent / key; + if (!dependency_path_within(fs::weakly_canonical(fs::absolute(entry)), root)) { + return dependency_error(dep, "cache entry points outside the dependency cache"); + } + + if (!fs::exists(entry)) { + fs::create_directories(parent); + std::error_code error; + auto nonce = std::chrono::steady_clock::now().time_since_epoch().count(); + fs::path staging; + do { + staging = parent / (".tmp-" + key + "-" + std::to_string(nonce++)); + error.clear(); + } while (!fs::create_directory(staging, error) && !error); + if (error) return dependency_error(dep, error.message()); + + const bool ready = populate_dependency(dep, staging); + if (ready) fs::rename(staging, entry, error); + if (!ready || error) { + std::error_code ignored; + const fs::path resolved = fs::canonical(staging, ignored); + if (!ignored && !dependency_path_within(root, resolved) && + dependency_path_within(resolved, root)) { + fs::remove_all(fs::absolute(staging), ignored); + } + } + if (!ready) return false; + // Another invocation may have published the same dependency first. + if (error && !fs::exists(entry)) return dependency_error(dep, error.message()); + } + + std::ifstream receipt(entry / "revision", std::ios::binary); + std::string git, rev, commit; + if (!std::getline(receipt, git) || !std::getline(receipt, rev) || + !std::getline(receipt, commit) || git != dep.git || rev != dep.rev || + !is_commit_id(commit)) { + return dependency_error(dep, "invalid cache receipt in " + + entry.generic_string()); + } + if (!dependency_include_flags(dep, entry, flags)) return false; + commits.push_back(commit); + return true; +} + +static bool prepare_dependencies(Config& cfg, Cmd& commits) { + for (const Dependency& dep : cfg.dependencies) { + try { + if (!prepare_dependency(dep, cfg.flags, commits)) return false; + } catch (const fs::filesystem_error& error) { + return dependency_error(dep, error.what()); + } + } + return true; +} + +/// @} + /// @name compile_commands.json /// Tells clangd how each file is compiled. /// @{ @@ -1644,9 +1896,10 @@ int main(int argc, char** argv) { init_terminal(); rebuild_self(argc, argv); const Args args = parse_args(argc, argv); - const Config cfg = load_config(args.profile); + Config cfg = load_config(args.profile); const Clock::time_point began = Clock::now(); + if (!cfg.dependencies.empty() && !valid_dependency_cache(cfg)) return 1; if (args.command == "clean") { const std::uintmax_t removed = fs::remove_all(cfg.clean_dir); if (removed > 0) { @@ -1672,7 +1925,9 @@ int main(int argc, char** argv) { "' (key 'tests') does not exist"); } - check_toolchain_cache(cfg); + Cmd dependency_commits; + if (!prepare_dependencies(cfg, dependency_commits)) return 1; + check_toolchain_cache(cfg, dependency_commits); // The compile flags come from the builder and from kumo.toml, so an object // file older than either is stale.