[Backport release-10.x] refactor(console): attach console early (#4998)

refactor(console): attach console early

also use RAII guard to free it instead of tracking it with a member variable


(cherry picked from commit ffd50e318a)

Signed-off-by: Rachel Powers <508861+Ryex@users.noreply.github.com>
This commit is contained in:
Rachel Powers 2026-02-10 20:15:05 -07:00 committed by GitHub
parent 8d8220283b
commit b178c1e84d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 79 additions and 84 deletions

View file

@ -24,12 +24,16 @@
#endif
#include <windows.h>
#include <consoleapi.h>
#include <fcntl.h>
#include <fileapi.h>
#include <io.h>
#include <stdio.h>
#include <cstddef>
#include <iostream>
namespace console {
void RedirectHandle(DWORD handle, FILE* stream, const char* mode)
{
HANDLE stdHandle = GetStdHandle(handle);
@ -157,3 +161,31 @@ std::error_code EnableAnsiSupport()
return {};
}
void FreeWindowsConsole()
{
fclose(stdout);
fclose(stdin);
fclose(stderr);
FreeConsole();
}
WindowsConsoleGuard::WindowsConsoleGuard() : m_consoleAttached(false)
{
if (console::AttachWindowsConsole()) {
m_consoleAttached = true;
if (auto err = console::EnableAnsiSupport(); err) {
std::cout << "Error setting up ansi console" << err.message() << std::endl;
}
}
}
WindowsConsoleGuard::~WindowsConsoleGuard()
{
// Detach from Windows console
if (m_consoleAttached) {
console::FreeWindowsConsole();
}
}
} // namespace console