Skip to main content

context7_cli/
platform.rs

1//! Platform-specific initialization for console encoding and ANSI support.
2//!
3//! On Windows, configures UTF-8 code page (65001) and enables
4//! virtual terminal processing for ANSI escape sequences.
5//! On other platforms, this is a no-op.
6
7/// Initialises platform-specific console settings.
8///
9/// Must be called as the FIRST action in `main()`, before any I/O.
10pub fn inicializar_plataforma() {
11    #[cfg(windows)]
12    configurar_console_utf8();
13
14    #[cfg(windows)]
15    habilitar_ansi_windows();
16}
17
18#[cfg(windows)]
19fn configurar_console_utf8() {
20    use windows_sys::Win32::System::Console::{SetConsoleCP, SetConsoleOutputCP};
21    // SAFETY: funções Windows API idempotentes que apenas definem codepage do console.
22    // Sem concorrência neste ponto — chamadas únicas no início de main() antes de qualquer thread.
23    unsafe {
24        SetConsoleOutputCP(65001); // CP_UTF8
25        SetConsoleCP(65001);
26    }
27}
28
29#[cfg(windows)]
30fn habilitar_ansi_windows() {
31    use colored::control;
32    // colored v2 em Windows Terminal/PowerShell 7+ detecta ANSI automaticamente.
33    // Para cmd.exe legado sem VirtualTerminalProcessing: forçar via set_virtual_terminal.
34    // Se falhar (cmd.exe muito antigo), desabilitar cores para evitar escape sequences brutas.
35    if control::set_virtual_terminal(true).is_err() {
36        control::set_override(false);
37    }
38}