Crafter.Build/implementations/Crafter.Build-Progress.cpp
catbot 8e2d21a2bc fix: decide a build step by its exit code, not by whether it printed
RunCommand merged stderr into stdout, dropped pclose's status and returned
the text; every compile, link and archive site then read "printed something"
as "failed". A warning is printing something, so a translation unit that
warned failed the build — but only on the run that actually recompiled it,
since warnings aren't re-emitted for an object that's already up to date.
The same unchanged source therefore passed or failed depending on the state
of the build tree: flaky-looking tests locally, and a cold CI checkout
surfacing every latent warning in a project at once as unrelated failures.

RunCommand is gone, replaced by RunBuildCommand: it goes through
RunCommandChecked, returns "" when the command exited 0 (so every caller's
`if (!result.empty())` error path is unchanged) and hands any warnings to
the new Progress::Diagnostic instead of to the error path. That also closes
the quiet half of the bug — a compiler killed by the OOM killer prints
nothing, so it used to read as success and leave the build carrying on with
a missing object; it now reports the signal that killed it.

Warnings are now shown rather than swallowed, which they weren't in either
direction before: invisible on an incremental build, fatal on a cold one.
Failing on them stays a project's choice, via -Werror in compileFlags.
2026-08-26 00:51:15 +00:00

159 lines
5.1 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <io.h>
#include <windows.h>
#ifndef STDOUT_FILENO
#define STDOUT_FILENO _fileno(stdout)
#endif
#define CRAFTER_PROGRESS_ISATTY _isatty
#else
#include <unistd.h>
#include <sys/ioctl.h>
#define CRAFTER_PROGRESS_ISATTY isatty
#endif
export module Crafter.Build:Progress_impl;
import std;
import :Progress;
namespace {
std::mutex StateMutex;
std::atomic<std::int32_t> Total{0};
std::atomic<std::int32_t> Done{0};
Crafter::Progress::Verbosity ActiveVerbosity = Crafter::Progress::Verbosity::Default;
bool IsTty = false;
bool LineDirty = false; // status line has uncleared content
bool Finalized = false;
std::chrono::steady_clock::time_point StartTime = std::chrono::steady_clock::now();
std::int32_t TerminalWidth() {
#if defined(_WIN32)
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO info;
if (h != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(h, &info)) {
std::int32_t w = info.srWindow.Right - info.srWindow.Left + 1;
if (w > 0) return w;
}
#else
winsize ws{};
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) {
return ws.ws_col;
}
#endif
if (const char* col = std::getenv("COLUMNS")) {
try { std::int32_t c = std::stoi(col); if (c > 0) return c; } catch (...) {}
}
return 80;
}
// Caller holds StateMutex.
void RenderStatus(std::string_view label) {
if (ActiveVerbosity != Crafter::Progress::Verbosity::Default || !IsTty) return;
std::int32_t done = Done.load(std::memory_order_relaxed);
std::int32_t total = Total.load(std::memory_order_relaxed);
std::string prefix = std::format("[{}/{}] ", done, total);
std::int32_t width = TerminalWidth();
std::int32_t avail = width - static_cast<std::int32_t>(prefix.size()) - 1;
std::string trimmed{label};
if (avail > 0 && static_cast<std::int32_t>(trimmed.size()) > avail) {
trimmed.resize(static_cast<std::size_t>(avail));
}
// \r returns to col 0, \033[2K erases the whole line. No newline.
std::fputs("\r\033[2K", stdout);
std::fputs(prefix.c_str(), stdout);
std::fputs(trimmed.c_str(), stdout);
std::fflush(stdout);
LineDirty = true;
}
// Caller holds StateMutex.
void ClearLineLocked() {
if (LineDirty) {
std::fputs("\r\033[2K", stdout);
std::fflush(stdout);
LineDirty = false;
}
}
}
namespace Crafter::Progress {
void SetVerbosity(Verbosity v) {
std::lock_guard lock(StateMutex);
ActiveVerbosity = v;
IsTty = CRAFTER_PROGRESS_ISATTY(STDOUT_FILENO) != 0;
StartTime = std::chrono::steady_clock::now();
Total.store(0);
Done.store(0);
Finalized = false;
}
Verbosity GetVerbosity() {
std::lock_guard lock(StateMutex);
return ActiveVerbosity;
}
Task::Task(std::string label) : label_(std::move(label)) {
Total.fetch_add(1, std::memory_order_relaxed);
std::lock_guard lock(StateMutex);
if (ActiveVerbosity == Verbosity::Default && IsTty) {
RenderStatus(label_);
}
}
Task::~Task() {
std::int32_t done = Done.fetch_add(1, std::memory_order_relaxed) + 1;
std::lock_guard lock(StateMutex);
if (ActiveVerbosity == Verbosity::Default) {
if (IsTty) {
RenderStatus(label_);
} else {
// Non-TTY: one append-only line per completed task (ninja-style).
std::int32_t total = Total.load(std::memory_order_relaxed);
std::println("[{}/{}] {}", done, total, label_);
}
}
}
void EchoCommand(std::string_view command) {
std::lock_guard lock(StateMutex);
if (ActiveVerbosity == Verbosity::Verbose) {
std::println("$ {}", command);
}
}
void Diagnostic(std::string_view text) {
std::lock_guard lock(StateMutex);
if (ActiveVerbosity == Verbosity::Quiet) return;
ClearLineLocked();
// Written whole under StateMutex: parallel compiles hand us one warning
// block each, and interleaving them line-by-line would make every
// "note: ..." continuation follow the wrong diagnostic.
std::fwrite(text.data(), 1, text.size(), stderr);
if (!text.ends_with('\n')) std::fputc('\n', stderr);
std::fflush(stderr);
}
void Clear() {
std::lock_guard lock(StateMutex);
ClearLineLocked();
}
void Finalize() {
std::lock_guard lock(StateMutex);
if (Finalized) return;
Finalized = true;
ClearLineLocked();
if (ActiveVerbosity == Verbosity::Quiet) return;
std::int32_t done = Done.load();
if (done == 0) return; // Nothing happened (cached build); stay silent.
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - StartTime);
std::println("Built {} step{} in {}ms", done, done == 1 ? "" : "s", elapsed.count());
}
} // namespace Crafter::Progress