Option C Tools
Loading...
Searching...
No Matches
terminal.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# oct/core/terminal.py
4
5"""
6Purpose
7-------
8Provide shared terminal color support for OCT CLI output.
9
10Responsibilities
11----------------
12- Detect ANSI escape code support (including Windows VT mode).
13- Export color constants used by linter, health, and formatter modules.
14
15Diagnostics
16-----------
17Domain: OCT-CORE
18Levels:
19 L2 — terminal capability detection
20 L3 — color constant resolution
21 L4 — Windows VT mode probing
22
23Contracts
24---------
25- Color constants are empty strings when ANSI is not supported.
26- Safe to import at module level; no side effects beyond detection.
27"""
28
29import os
30import sys
31
32
33def supports_ansi() -> bool:
34 """Return True if the terminal supports ANSI escape codes."""
35 return supports_ansi_on(sys.stdout)
36
37
38def supports_ansi_on(stream) -> bool:
39 """Return True if *stream* supports ANSI escape codes."""
40 if not hasattr(stream, "isatty") or not stream.isatty():
41 return False
42 if os.name != "nt":
43 return True
44 # Windows 10 1511+ supports ANSI if VT mode is enabled
45 try:
46 import ctypes
47 kernel32 = ctypes.windll.kernel32
48 # Map stream to the correct console handle
49 if stream is sys.stderr:
50 handle = kernel32.GetStdHandle(-12) # STD_ERROR_HANDLE
51 else:
52 handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
53 mode = ctypes.c_ulong()
54 kernel32.GetConsoleMode(handle, ctypes.byref(mode))
55 # ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
56 return bool(mode.value & 0x0004)
57 except Exception:
58 return False
59
60
61if supports_ansi():
62 CYAN = "\033[96m"
63 GREEN = "\033[92m"
64 RED = "\033[91m"
65 YELLOW = "\033[93m"
66 RESET = "\033[0m"
67else:
68 CYAN = GREEN = RED = YELLOW = RESET = ""
bool supports_ansi()
Definition terminal.py:33
bool supports_ansi_on(stream)
Definition terminal.py:38