context7_cli/platform.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Platform-specific initialisation (Windows UTF-8 + ANSI).
3//! Platform-specific initialization for console encoding and ANSI support.
4//!
5//! On Windows, configures UTF-8 code page (65001) and enables
6//! virtual terminal processing for ANSI escape sequences.
7//! On other platforms, this is a no-op.
8
9/// Initialises platform-specific console settings.
10///
11/// Must be called as the FIRST action in `main()`, before any I/O.
12pub fn init_platform() {
13 #[cfg(windows)]
14 configure_console_utf8();
15
16 #[cfg(windows)]
17 enable_ansi_windows();
18}
19
20#[cfg(windows)]
21fn configure_console_utf8() {
22 use windows_sys::Win32::System::Console::{SetConsoleCP, SetConsoleOutputCP};
23 // SAFETY: Windows API functions are idempotent and only set the console codepage.
24 // No concurrency at this point — single calls at the start of main() before any thread.
25 unsafe {
26 SetConsoleOutputCP(65001); // CP_UTF8
27 SetConsoleCP(65001);
28 }
29}
30
31#[cfg(windows)]
32fn enable_ansi_windows() {
33 use colored::control;
34 // colored v2 on Windows Terminal / PowerShell 7+ auto-detects ANSI.
35 // For legacy cmd.exe without VirtualTerminalProcessing: force via set_virtual_terminal.
36 // If it fails (very old cmd.exe), disable colours to avoid raw escape sequences.
37 if control::set_virtual_terminal(true).is_err() {
38 control::set_override(false);
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 /// Verifies that `init_platform` does not panic on any platform.
47 ///
48 /// On Linux and macOS the function is no-op; on Windows it configures UTF-8 and ANSI.
49 /// The test ensures the call is safe regardless of the operating system.
50 #[test]
51 fn test_init_platform_does_not_panic() {
52 // Must complete without panic on Linux, macOS, and Windows.
53 init_platform();
54 }
55
56 /// Verifies that `init_platform` is a safe no-op on non-Windows platforms.
57 ///
58 /// On Linux and macOS the function does not execute any instructions — it just returns.
59 /// The test confirms that multiple consecutive calls are safe (idempotent).
60 #[cfg(not(windows))]
61 #[test]
62 fn test_init_platform_is_noop_on_non_windows() {
63 // Multiple calls must be idempotent and not cause side effects.
64 init_platform();
65 init_platform();
66 init_platform();
67 }
68}