Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git
commit 32f2b0cde0b748c9802ee6e236993be2f19146f5
parent 12f45926209df5fe25a2c5a52956173745973ebc
Author: sentomk <sentomk@proton.me>
Date:   Tue, 13 Oct 2026 20:25:27 +0800

feat: add help, report command line mistakes and clearer output

`kumoko help`, -h and --help print the usage. A command or an option that
is not known is now an error with status 2; before, `kumoko help` and any
other word were taken for `build` and finished without a word.

Messages get labels in a fixed column and, on a terminal, colors (NO_COLOR
turns them off). Compiling shows a counter, a build ends with how many files
were compiled and how long it took or says that it is up to date, and a
failure names the files that did not compile or the executable that did not
link. -v prints the full commands.

Tests print one line each, PASS, FAIL or CRASH with the time; a crash says
which signal killed the program. `run` says how the program ended and passes
its exit status on. `clean` says what it removed.

To report these, the processes group now keeps the exit status of every child
(its code, or the signal that killed it) and which command it belonged to.

Diffstat:
Mkumo_builder.cpp | 558++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
1 file changed, 482 insertions(+), 76 deletions(-)

diff --git a/kumo_builder.cpp b/kumo_builder.cpp @@ -18,13 +18,20 @@ /// Usage (always from the project root; on Windows type `kumoko` without the /// leading `./`): /// @code -/// ./kumoko # incremental build -/// ./kumoko run # incremental build, then run the executable -/// ./kumoko clean # delete all build output -/// ./kumoko test [name] # build and run the tests, only those whose name -/// # contains `name` if one is given +/// ./kumoko # incremental build +/// ./kumoko run # incremental build, then run the executable +/// ./kumoko test [name] # build and run the tests, only those whose name +/// # contains `name` if one is given +/// ./kumoko clean # delete all build output +/// ./kumoko help # show the usage; also -h and --help +/// ./kumoko -v ... # print full commands, list every test case /// @endcode /// +/// Output is colored when it goes to a terminal; set `NO_COLOR` to turn that +/// off. The exit status is 0 on success, 1 if building or a test failed (or the +/// status of the program that `run` ran), and 2 for a mistake on the command +/// line. +/// /// Platform-specific source files are marked by their name, see /// is_built_here(). /// @@ -36,6 +43,7 @@ #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX +#include <io.h> #include <windows.h> #else #include <spawn.h> @@ -46,9 +54,12 @@ #include <algorithm> #include <cctype> #include <cerrno> +#include <chrono> #include <cstddef> +#include <cstdint> #include <cstdio> #include <cstdlib> +#include <cstring> #include <filesystem> #include <fstream> #include <map> @@ -124,6 +135,133 @@ static const fs::path CONFIG_FILE = "kumo.toml"; /// @} +/// @name Terminal output +/// How the builder talks to the person at the terminal: colors, labels in a +/// fixed column, durations, and errors. +/// @{ + +/// @brief Whether messages are colored. Set once by init_terminal(). +static bool color_enabled = false; + +/// @brief Whether commands are printed in full and every test case is listed. +/// Set by `-v` or `--verbose`. +static bool verbose = false; + +/// @brief The colors a message can have. +enum class Style { Plain, Dim, Red, Green, Cyan }; + +/// @brief Decides whether to use colors. +/// +/// Only when standard output is a terminal, and `NO_COLOR` is not set (see +/// https://no-color.org). On Windows the terminal must also accept escape +/// codes, which this turns on. +static void init_terminal() { + const char* no_color = std::getenv("NO_COLOR"); + if (no_color != nullptr && no_color[0] != '\0') return; +#if defined(_WIN32) + if (!_isatty(_fileno(stdout))) return; + HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD mode = 0; + if (out == INVALID_HANDLE_VALUE || !GetConsoleMode(out, &mode)) return; + if (!SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return; + color_enabled = true; +#else + color_enabled = isatty(STDOUT_FILENO) != 0; +#endif +} + +/// @brief Wraps @p text in the escape codes of @p style, if colors are on. +static std::string paint(Style style, const std::string& text) { + if (!color_enabled || style == Style::Plain) return text; + const char* code = "0"; + switch (style) { + case Style::Dim: + code = "2"; + break; + case Style::Red: + code = "31"; + break; + case Style::Green: + code = "32"; + break; + case Style::Cyan: + code = "36"; + break; + case Style::Plain: + break; + } + return std::string("\033[") + code + "m" + text + "\033[0m"; +} + +/// @brief Pads @p text on the right with spaces up to @p width characters. +static std::string pad(const std::string& text, size_t width) { + return text.size() >= width ? text + : text + std::string(width - text.size(), ' '); +} + +/// @brief "1 test program" or "3 test programs". +static std::string plural(size_t count, const std::string& noun) { + return std::to_string(count) + " " + noun + (count == 1 ? "" : "s"); +} + +/// @brief Prints one line of progress: a label in a fixed column, then a text, +/// then an optional note in a dimmer color. +/// +/// @code +/// compile src/main.cpp [1/3] +/// link build/kumo +/// @endcode +static void log_step(Style style, const std::string& label, + const std::string& text, const std::string& note = "") { + std::string line = paint(style, pad(label, 8)) + " " + text; + if (!note.empty()) line += " " + paint(Style::Dim, note); + std::printf("%s\n", line.c_str()); +} + +/// @brief Prints an error message on standard error. +/// +/// Standard output is flushed first, so that the message does not overtake +/// lines printed before it when both go to the same place. +static void print_error(const std::string& message) { + std::fflush(stdout); + std::fprintf(stderr, "%s %s\n", paint(Style::Red, "error:").c_str(), + message.c_str()); +} + +/// @brief Formats a duration for people: `87 ms`, `1.24 s`, `2 min 3 s`. +static std::string format_duration(std::chrono::steady_clock::duration time) { + const auto ms = + std::chrono::duration_cast<std::chrono::milliseconds>(time).count(); + char buffer[48]; + if (ms < 1000) { + std::snprintf(buffer, sizeof(buffer), "%lld ms", + static_cast<long long>(ms)); + } else if (ms < 60000) { + std::snprintf(buffer, sizeof(buffer), "%.2f s", + static_cast<double>(ms) / 1000.0); + } else { + std::snprintf(buffer, sizeof(buffer), "%lld min %lld s", + static_cast<long long>(ms / 60000), + static_cast<long long>(ms % 60000 / 1000)); + } + return buffer; +} + +/// @brief Prints a command on one line, dimmed, as `-v` does. Arguments with +/// spaces or quotes are put in quotes, which is for reading only. +static void print_command(const Cmd& cmd) { + std::string line = "$"; + for (const std::string& arg : cmd) { + const bool plain = + !arg.empty() && arg.find_first_of(" \t\"'") == std::string::npos; + line += ' '; + line += plain ? arg : "\"" + arg + "\""; + } + std::printf(" %s\n", paint(Style::Dim, line).c_str()); +} + +/// @} + /// @name Project configuration /// Reading `kumo.toml`, which says how the project is organized and compiled. /// @@ -186,11 +324,8 @@ struct Config { /// @param msg What is wrong. [[noreturn]] static void config_error(int line, const std::string& msg) { const std::string file = CONFIG_FILE.string(); - if (line > 0) { - std::fprintf(stderr, "%s:%d: %s\n", file.c_str(), line, msg.c_str()); - } else { - std::fprintf(stderr, "%s: %s\n", file.c_str(), msg.c_str()); - } + print_error(line > 0 ? file + ":" + std::to_string(line) + ": " + msg + : file + ": " + msg); std::exit(EXIT_FAILURE); } @@ -658,8 +793,9 @@ static Process spawn(const Cmd& cmd) { PROCESS_INFORMATION info = {}; if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &info)) { - std::fprintf(stderr, "failed to spawn %s (error %lu)\n", cmd[0].c_str(), - static_cast<unsigned long>(GetLastError())); + print_error("cannot start " + cmd[0] + " (error " + + std::to_string(static_cast<unsigned long>(GetLastError())) + + ")"); std::exit(EXIT_FAILURE); } CloseHandle(info.hThread); // only the process handle is needed @@ -677,49 +813,88 @@ static Process spawn(const Cmd& cmd) { pid_t pid = 0; if (posix_spawnp(&pid, argv[0], nullptr, nullptr, argv.data(), environ) != 0) { - std::fprintf(stderr, "failed to spawn %s\n", argv[0]); + print_error(std::string("cannot start ") + argv[0]); std::exit(EXIT_FAILURE); } return pid; #endif } +/// @brief How a child process ended. +struct ExitStatus { + int code = 0; ///< Exit status; -1 if waiting for the child failed. + int signal = 0; ///< The signal that killed it (macOS, Linux), or 0. + + bool ok() const { return code == 0 && signal == 0; } +}; + +/// @brief A running child and the index of the command it was started for. +struct Child { + Process process; + size_t index; +}; + +/// @brief "No command": the index wait_any() reports when waiting itself +/// failed. +constexpr size_t kNoIndex = static_cast<size_t>(-1); + /// @brief Blocks until any one of the running children exits. /// /// The child that finished is removed from @p running. /// /// @param running Children that were started and not yet waited for. -/// @return `true` if that child exited normally with status 0. `false` if it -/// failed or waiting itself failed; in the latter case @p running is -/// emptied, since the remaining children can no longer be tracked. -static bool wait_any(std::vector<Process>& running) { +/// @param index Receives the index of the command of the child that finished, +/// or #kNoIndex if waiting itself failed; in that case @p +/// running is emptied, since the remaining children can no +/// longer be tracked. +/// @return How that child ended. +static ExitStatus wait_any(std::vector<Child>& running, size_t* index) { + ExitStatus status; + *index = kNoIndex; #if defined(_WIN32) - DWORD index = WaitForMultipleObjects(static_cast<DWORD>(running.size()), - running.data(), FALSE, INFINITE); + std::vector<HANDLE> handles; + for (const Child& child : running) handles.push_back(child.process); + DWORD which = WaitForMultipleObjects(static_cast<DWORD>(handles.size()), + handles.data(), FALSE, INFINITE); // On success the result is WAIT_OBJECT_0 (== 0) plus the index of the handle // that became signaled; anything else is an error. - if (index >= running.size()) { + if (which >= handles.size()) { running.clear(); - return false; + status.code = -1; + return status; } DWORD code = 1; - GetExitCodeProcess(running[index], &code); - CloseHandle(running[index]); - running.erase(running.begin() + index); - return code == 0; + GetExitCodeProcess(handles[which], &code); + CloseHandle(handles[which]); + *index = running[which].index; + running.erase(running.begin() + which); + status.code = static_cast<int>(code); + return status; #else - int status = 0; + int raw = 0; pid_t done; do { - done = waitpid(-1, &status, 0); // -1 means "any child" + done = waitpid(-1, &raw, 0); // -1 means "any child" } while (done < 0 && errno == EINTR); // retry if a signal interrupted us if (done < 0) { running.clear(); - return false; + status.code = -1; + return status; + } + auto it = std::find_if(running.begin(), running.end(), + [done](const Child& c) { return c.process == done; }); + if (it != running.end()) { + *index = it->index; + running.erase(it); + } + if (WIFSIGNALED(raw)) { + status.signal = WTERMSIG(raw); + } else if (WIFEXITED(raw)) { + status.code = WEXITSTATUS(raw); + } else { + status.code = -1; } - running.erase(std::remove(running.begin(), running.end(), done), - running.end()); - return WIFEXITED(status) && WEXITSTATUS(status) == 0; + return status; #endif } @@ -737,17 +912,25 @@ static bool wait_any(std::vector<Process>& running) { /// @param max_jobs Maximum number of commands running at the same time. /// Capped at 60, because Windows can wait on at most 64 /// handles at once. +/// @param failed If not null, receives the indices of the commands that +/// failed. /// @return `true` only if every command succeeded. -static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs) { +static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs, + std::vector<size_t>* failed = nullptr) { max_jobs = std::min(max_jobs, 60u); - size_t next = 0; // index of the next command to start - std::vector<Process> running; // children currently running + size_t next = 0; // index of the next command to start + std::vector<Child> running; // children currently running bool ok = true; while ((ok && next < cmds.size()) || !running.empty()) { if (ok && next < cmds.size() && running.size() < max_jobs) { - running.push_back(spawn(cmds[next++])); - } else if (!wait_any(running)) { - ok = false; + running.push_back({spawn(cmds[next]), next}); + ++next; + } else { + size_t index = kNoIndex; + if (!wait_any(running, &index).ok()) { + ok = false; + if (failed != nullptr && index != kNoIndex) failed->push_back(index); + } } } return ok; @@ -756,8 +939,53 @@ static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs) { /// @brief Runs a single command and waits for it. /// /// @param cmd Command to run. +/// @return How it ended. +static ExitStatus run_status(const Cmd& cmd) { + std::vector<Child> running = {{spawn(cmd), 0}}; + size_t ignored = kNoIndex; + return wait_any(running, &ignored); +} + +/// @brief Runs a single command and waits for it. +/// +/// @param cmd Command to run. /// @return `true` if the command succeeded. -static bool run(const Cmd& cmd) { return run_all({cmd}, 1); } +static bool run(const Cmd& cmd) { return run_status(cmd).ok(); } + +/// @brief Says in words how a child ended, to follow the name of the program: +/// `exited with status 3` or `was killed by signal 11 (Segmentation +/// fault)`. +static std::string describe(const ExitStatus& status) { + if (status.signal != 0) { +#if defined(_WIN32) + return "was stopped by signal " + std::to_string(status.signal); +#else + const char* name = strsignal(status.signal); + return "was killed by signal " + std::to_string(status.signal) + + (name != nullptr ? " (" + std::string(name) + ")" : ""); +#endif + } + if (status.code == -1) return "could not be waited for"; +#if defined(_WIN32) + // Windows reports a crash as an exit status such as 0xC0000005. + if (static_cast<unsigned>(status.code) >= 0xC0000000u) { + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "crashed with code 0x%08X", + static_cast<unsigned>(status.code)); + return buffer; + } +#endif + return "exited with status " + std::to_string(status.code); +} + +/// @brief The exit status the builder itself should end with when it passes on +/// the failure of a program it ran: its status, or 128 plus the signal, +/// and never 0 for a failure. +static int exit_code_of(const ExitStatus& status) { + if (status.signal != 0) return 128 + status.signal; + if (status.code <= 0 || status.code > 255) return status.ok() ? 0 : 1; + return status.code; +} /// @} @@ -951,18 +1179,40 @@ static std::vector<Unit> plan_units(const Config& cfg, const fs::path& dir, /// @brief Compiles those of the given units that are stale, in parallel. /// -/// @param units The units to consider; the up to date ones are skipped. +/// Each file is announced with a counter, and a failure ends with a line naming +/// the files that did not compile, after the diagnostics of the compiler. +/// +/// @param units The units to consider; the up to date ones are skipped. +/// @param compiled If not null, receives the number of files compiled. /// @return `true` if every compilation succeeded. -static bool compile_stale(const std::vector<const Unit*>& units) { - std::vector<Cmd> cmds; +static bool compile_stale(const std::vector<const Unit*>& units, + size_t* compiled = nullptr) { + std::vector<const Unit*> stale; for (const Unit* unit : units) { - if (!unit->stale) continue; - std::printf("[cc] %s\n", unit->src.generic_string().c_str()); - cmds.push_back(unit->cmd); + if (unit->stale) stale.push_back(unit); + } + if (compiled != nullptr) *compiled = stale.size(); + + std::vector<Cmd> cmds; + for (size_t i = 0; i < stale.size(); ++i) { + log_step( + Style::Cyan, "compile", stale[i]->src.generic_string(), + "[" + std::to_string(i + 1) + "/" + std::to_string(stale.size()) + "]"); + if (verbose) print_command(stale[i]->cmd); + cmds.push_back(stale[i]->cmd); } + // hardware_concurrency may return 0, meaning "unknown". unsigned jobs = std::thread::hardware_concurrency(); - return run_all(cmds, jobs ? jobs : 4); + std::vector<size_t> failed; + if (run_all(cmds, jobs ? jobs : 4, &failed)) return true; + + std::string names; + for (size_t index : failed) { + names += (names.empty() ? "" : ", ") + stale[index]->src.generic_string(); + } + print_error("failed to compile " + (names.empty() ? "the sources" : names)); + return false; } /// @brief Links object files into an executable, unless it is up to date. @@ -975,10 +1225,12 @@ static bool compile_stale(const std::vector<const Unit*>& units) { /// @param cfg Project settings. /// @param objects The objects to link. /// @param exe The executable to produce. +/// @param linked If not null, tells whether a link was done. /// @return `true` if the executable is up to date afterwards. static bool link_if_needed(const Config& cfg, const std::vector<fs::path>& objects, - const fs::path& exe) { + const fs::path& exe, bool* linked = nullptr) { + if (linked != nullptr) *linked = false; bool needed = !fs::exists(exe); for (const fs::path& obj : objects) { if (!needed && fs::last_write_time(obj) > fs::last_write_time(exe)) { @@ -987,13 +1239,17 @@ static bool link_if_needed(const Config& cfg, } if (!needed) return true; - std::printf("[link] %s\n", exe.generic_string().c_str()); + log_step(Style::Cyan, "link", exe.generic_string()); fs::create_directories(exe.parent_path()); Cmd link = {cfg.compiler}; for (const fs::path& obj : objects) link.push_back(obj.string()); link.insert(link.end(), cfg.link_flags.begin(), cfg.link_flags.end()); link.insert(link.end(), {"-o", exe.string()}); - return run(link); + if (verbose) print_command(link); + if (linked != nullptr) *linked = true; + if (run(link)) return true; + print_error("failed to link " + exe.generic_string()); + return false; } /// @} @@ -1019,6 +1275,86 @@ static fs::path test_exe(const Config& cfg, const fs::path& src) { /// @} +/// @name Command line +/// @{ + +/// @brief Prints the usage of the builder. +static void print_usage(std::FILE* out) { + std::fputs(R"usage(kumoko, the build tool of Kumo + +Usage: + kumoko [options] [command] [name] + +Commands: + build Compile and link the program (the default) + run Build, then run the program + test [name] Build and run the tests; with a name, only those whose path + contains it, e.g. `test raster` or `test e2e/` + clean Delete all build output + help Show this text + +Options: + -v, --verbose Print full commands, and list every test case + -h, --help Show this text + +Run it from the project root; its settings are in kumo.toml. Output is colored +on a terminal; set NO_COLOR to turn that off. +)usage", + out); +} + +/// @brief What the command line asks for. +struct Args { + std::string command = "build"; + std::string pattern; ///< For `test`: part of the name of the tests to run. +}; + +/// @brief Reads the command line. +/// +/// Prints the usage and exits for `help`, `-h` and `--help`; prints an error +/// and exits with status 2 for anything it does not understand, instead of +/// guessing what was meant. +static Args parse_args(int argc, char** argv) { + const auto mistake = [](const std::string& message) { + print_error(message); + std::fprintf(stderr, "Run `kumoko help` for the usage.\n"); + std::exit(2); + }; + + std::vector<std::string> words; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "-h" || arg == "--help") { + print_usage(stdout); + std::exit(0); + } else if (arg == "-v" || arg == "--verbose") { + verbose = true; + } else if (arg.size() > 1 && arg[0] == '-') { + mistake("unknown option '" + arg + "'"); + } else { + words.push_back(arg); + } + } + + Args args; + if (!words.empty()) args.command = words[0]; + if (args.command == "help") { + print_usage(stdout); + std::exit(0); + } + if (args.command != "build" && args.command != "run" && + args.command != "test" && args.command != "clean") { + mistake("unknown command '" + args.command + "'"); + } + if (words.size() > (args.command == "test" ? 2u : 1u)) { + mistake("too many arguments for '" + args.command + "'"); + } + if (words.size() == 2) args.pattern = words[1]; + return args; +} + +/// @} + /// @name Entry point /// @{ @@ -1045,8 +1381,8 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(SELF_EXE)) return; - std::printf("[self] %s changed, rebuilding\n", - SELF_SRC.generic_string().c_str()); + log_step(Style::Cyan, "self", + SELF_SRC.generic_string() + " changed, rebuilding the builder"); const Cmd compile = {SELF_CXX, "-std=c++20", SELF_SRC.string(), "-o", SELF_EXE.string()}; @@ -1054,24 +1390,28 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { std::error_code ec; fs::rename(SELF_EXE, SELF_OLD_EXE, ec); if (ec) { - std::fprintf(stderr, "cannot move %s aside: %s\n", - SELF_EXE.string().c_str(), ec.message().c_str()); + print_error("cannot move " + SELF_EXE.string() + " aside: " + ec.message()); std::exit(1); } if (!run(compile)) { // Put the old builder back so the next run can try again. fs::rename(SELF_OLD_EXE, SELF_EXE, ec); + print_error("failed to rebuild " + SELF_SRC.generic_string()); std::exit(1); } Cmd relaunch(argv, argv + argc); relaunch[0] = SELF_EXE.string(); std::exit(run(relaunch) ? 0 : 1); #else - if (!run(compile)) std::exit(1); + if (!run(compile)) { + print_error("failed to rebuild " + SELF_SRC.generic_string()); + std::exit(1); + } execv(SELF_EXE.c_str(), argv); // execv does not return on success; reaching this line means it failed. - std::perror("execv"); + print_error(std::string("cannot restart the builder: ") + + std::strerror(errno)); std::exit(1); #endif } @@ -1079,21 +1419,32 @@ static void rebuild_self([[maybe_unused]] int argc, char** argv) { /// @brief Builds the project, runs it, or builds and runs its tests. /// /// @param argc Argument count. -/// @param argv `argv[1]` selects the mode: `build` (default), `run`, `test` or -/// `clean`. In `test` mode `argv[2]` may select tests by name. -/// @return 0 on success, 1 if compiling, linking or running failed or a test -/// failed. +/// @param argv The command line, see print_usage(). +/// @return 0 on success, 1 if building failed or a test failed, 2 for a +/// mistake on the command line; for `run`, the status of the program if +/// it failed. int main(int argc, char** argv) { + using Clock = std::chrono::steady_clock; + init_terminal(); rebuild_self(argc, argv); + const Args args = parse_args(argc, argv); const Config cfg = load_config(); + const Clock::time_point began = Clock::now(); - std::string mode = argc > 1 ? argv[1] : "build"; - if (mode == "clean") { - fs::remove_all(cfg.out_dir); + if (args.command == "clean") { + const std::uintmax_t removed = fs::remove_all(cfg.out_dir); + if (removed > 0) { + log_step(Style::Cyan, "clean", + "removed " + cfg.out_dir.generic_string() + "/"); + } else { + log_step(Style::Cyan, "clean", + "nothing to remove, " + cfg.out_dir.generic_string() + + "/ does not exist"); + } return 0; } - const bool testing = mode == "test"; - const std::string filter = testing && argc > 2 ? argv[2] : ""; + const bool testing = args.command == "test"; + const std::string& filter = args.pattern; if (!fs::is_directory(cfg.src_dir)) { config_error(0, "the source directory '" + cfg.src_dir.string() + @@ -1155,27 +1506,47 @@ int main(int argc, char** argv) { to_compile.push_back(&test); } if (selected.empty()) { - std::printf("no tests found%s%s\n", filter.empty() ? "" : " matching ", - filter.c_str()); + print_error(filter.empty() ? "there are no tests in " + + cfg.tests_dir.generic_string() + "/" + : "no test matches '" + filter + "'"); return 1; } } // Step 3: compile whatever is stale, in parallel. - if (!compile_stale(to_compile)) return 1; + size_t compiled = 0; + if (!compile_stale(to_compile, &compiled)) return 1; - // Step 4: link and run. + // Step 4: link, and run or report. if (!testing) { - if (!link_if_needed(cfg, objects, cfg.exe)) return 1; - if (mode == "run") { + bool linked = false; + if (!link_if_needed(cfg, objects, cfg.exe, &linked)) return 1; + if (args.command == "run") { + log_step(Style::Cyan, "run", cfg.exe.generic_string()); // Windows wants backslashes in the path of a program to start. fs::path program = cfg.exe; program.make_preferred(); - return run({program.string()}) ? 0 : 1; + const ExitStatus status = run_status({program.string()}); + if (status.ok()) return 0; + print_error(cfg.exe.generic_string() + " " + describe(status)); + return exit_code_of(status); + } + const std::string took = format_duration(Clock::now() - began); + if (compiled == 0 && !linked) { + log_step(Style::Green, "built", + cfg.exe.generic_string() + " is up to date"); + } else { + log_step(Style::Green, "built", cfg.exe.generic_string(), + plural(compiled, "file") + " compiled in " + took); } return 0; } + size_t name_width = 0; + for (const Unit* test : selected) { + name_width = std::max(name_width, test_name(cfg, test->src).size()); + } + std::vector<std::string> failed; for (const Unit* test : selected) { std::vector<fs::path> test_objects = {test->obj}; @@ -1183,20 +1554,55 @@ int main(int argc, char** argv) { const fs::path exe = test_exe(cfg, test->src); if (!link_if_needed(cfg, test_objects, exe)) return 1; + // The test program is told whether to color and whether to list its cases. const std::string name = test_name(cfg, test->src); - std::printf("[test] %s\n", name.c_str()); fs::path program = exe; program.make_preferred(); - if (!run({program.string()})) failed.push_back(name); + Cmd command = {program.string()}; + if (color_enabled) command.push_back("--color"); + if (verbose) { + command.push_back("--verbose"); + std::printf("%s\n", paint(Style::Dim, "running " + name).c_str()); + } + + const Clock::time_point test_began = Clock::now(); + const ExitStatus status = run_status(command); + const std::string took = format_duration(Clock::now() - test_began); + + // A test program that fails its checks exits with status 1; anything else + // that is not success (a signal, another status) is a crash. + const bool crashed = + !status.ok() && !(status.signal == 0 && status.code == 1); + if (status.ok()) { + std::printf("%s %s %s\n", paint(Style::Green, "PASS ").c_str(), + pad(name, name_width).c_str(), + paint(Style::Dim, took).c_str()); + } else { + failed.push_back(name); + std::printf( + "%s %s %s%s\n", + paint(Style::Red, crashed ? "CRASH" : "FAIL ").c_str(), + pad(name, name_width).c_str(), paint(Style::Dim, took).c_str(), + crashed ? (" " + paint(Style::Red, describe(status))).c_str() : ""); + } } + const std::string total = " in " + format_duration(Clock::now() - began); + std::printf("\n"); if (failed.empty()) { - std::printf("all %zu test programs passed\n", selected.size()); + std::printf( + "%s%s\n", + paint(Style::Green, plural(selected.size(), "test program") + " passed") + .c_str(), + paint(Style::Dim, total).c_str()); return 0; } - std::printf("%zu of %zu test programs failed:\n", failed.size(), - selected.size()); - for (const std::string& name : failed) std::printf(" %s\n", name.c_str()); + std::printf( + "%s%s\n", + paint(Style::Red, std::to_string(failed.size()) + " of " + + plural(selected.size(), "test program") + " failed") + .c_str(), + paint(Style::Dim, total).c_str()); return 1; }