Repository navigation
fix: encapsulate terminal color output and add cross-platform color detection - #16672
Conversation
…e-flight color support detection to avoid unwanted garbled escape characters.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis change adds ANSI terminal color support to ChangesTerminal Color Support
Estimated code review effort: 2 (Simple) | ~10 minutes Sequence Diagram(s)sequenceDiagram
participant run_tests.py
participant stdout
participant tput
participant Windows console
run_tests.py->>stdout: check isatty()
run_tests.py->>Windows console: enable ANSI mode on Windows
run_tests.py->>tput: query colors on non-Windows
run_tests.py->>run_tests.py: set COLOR_SUPPORT
run_tests.py->>run_tests.py: set_color(text, color)
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
run_tests.py (3)
66-69: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSimplify the exception handling.
except BaseException as e: if isinstance(e, (SystemExit, KeyboardInterrupt)): raise e; return Falseis equivalent to justexcept Exception:—SystemExit/KeyboardInterruptderive fromBaseException, notException, so catchingExceptionalready lets them propagate.♻️ Proposed simplification
- except BaseException as e: - if isinstance(e, (SystemExit, KeyboardInterrupt)): - raise e - return False + except Exception: + return False🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@run_tests.py` around lines 66 - 69, Simplify the exception handling in the test runner’s wrapper by replacing the broad BaseException catch in the relevant function with a normal Exception catch, since SystemExit and KeyboardInterrupt will still propagate automatically; update the try/except block in the test-execution path so it just returns False on ordinary failures without the explicit isinstance check.
38-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo logging in the new color-detection flow.
_is_color_supported()silently swallows all exceptions (Windows-version parsing failures, ctypes access errors,tputfailures) and returnsFalsewith no diagnostic trail, making it hard to debug why colors unexpectedly stay disabled in a given environment. As per coding guidelines,**/*.pychanges should "Add logging for new flows."🪵 Example
+import logging +logger = logging.getLogger(__name__) ... - except BaseException as e: - if isinstance(e, (SystemExit, KeyboardInterrupt)): - raise e - return False + except Exception as e: + logger.debug("Color support detection failed: %s", e) + return False🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@run_tests.py` around lines 38 - 85, The new color-detection flow in _is_color_supported() suppresses all failures and only returns False, so add logging at the exception paths and key decision points to explain why color support was disabled. Update the Windows and Unix branches in _is_color_supported() to emit a diagnostic message when platform.version parsing, ctypes/windll access, or tput checks fail, and keep COLOR_SUPPORT initialized from the helper so the logging happens during startup.Source: Coding guidelines
253-266: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRepeated label/color/print pattern could be consolidated.
The
print(f"\n{set_color(s="[...]",color="...")} ...")pattern is repeated for EXECUTING/SUCCESS/coverage-INFO/FAILURE/INTERRUPTED. A small helper (e.g.print_status(label, color, message)) would reduce duplication and make future label/color changes a single-point edit.♻️ Example helper
+ `@staticmethod` + def print_status(label: str, color: str, message: str = "") -> None: + print(f"\n{set_color(s=f'[{label}]', color=color)} {message}".rstrip())Also applies to: 275-279
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@run_tests.py` around lines 253 - 266, The status print pattern in the test runner is duplicated across the EXECUTING, SUCCESS, INFO, FAILURE, and INTERRUPTED paths, so consolidate it into a small helper and use that helper everywhere the labeled colorized message is printed. Add a reusable function such as print_status and update the relevant logic in run_tests.py to call it instead of repeating set_color and print formatting, keeping the existing labels and messages unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@run_tests.py`:
- Around line 87-107: The set_color helper does not follow its documented
fallback when an invalid color name is passed. Update set_color to safely
resolve the Colors member in the color handling branch, and if the lookup fails,
return the original string s unchanged instead of raising. Keep the behavior
centered in set_color so current callers continue to work with valid color names
while the invalid-color contract is honored.
- Around line 51-69: The Windows ANSI enablement path in the helper that checks
`sys.platform.startswith("win")` should validate both the `GetStdHandle(-11)`
return value and the result of `kernel32.SetConsoleMode`; update the logic so it
only returns True when a valid handle is obtained and console mode is
successfully applied, otherwise fall back to False. Keep the fix localized to
the Windows branch in `run_tests.py` so unsupported terminals do not claim ANSI
support.
---
Nitpick comments:
In `@run_tests.py`:
- Around line 66-69: Simplify the exception handling in the test runner’s
wrapper by replacing the broad BaseException catch in the relevant function with
a normal Exception catch, since SystemExit and KeyboardInterrupt will still
propagate automatically; update the try/except block in the test-execution path
so it just returns False on ordinary failures without the explicit isinstance
check.
- Around line 38-85: The new color-detection flow in _is_color_supported()
suppresses all failures and only returns False, so add logging at the exception
paths and key decision points to explain why color support was disabled. Update
the Windows and Unix branches in _is_color_supported() to emit a diagnostic
message when platform.version parsing, ctypes/windll access, or tput checks
fail, and keep COLOR_SUPPORT initialized from the helper so the logging happens
during startup.
- Around line 253-266: The status print pattern in the test runner is duplicated
across the EXECUTING, SUCCESS, INFO, FAILURE, and INTERRUPTED paths, so
consolidate it into a small helper and use that helper everywhere the labeled
colorized message is printed. Add a reusable function such as print_status and
update the relevant logic in run_tests.py to call it instead of repeating
set_color and print formatting, keeping the existing labels and messages
unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
| def set_color(s: str, | ||
| color: str) -> str: | ||
| """ | ||
| Wrap input string with specified ANSI terminal color escape sequence. | ||
| Color name argument is case-insensitive. If color is unsupported or invalid, | ||
| returns original raw string without any escape codes. | ||
|
|
||
| Args: | ||
| s: Original text string to be colored | ||
| color: Color enum name, case-insensitive (e.g. "red", "GREEN", "Yellow") | ||
| Returns: | ||
| str: Text wrapped with ANSI color codes if color output is available, | ||
| otherwise the unmodified input string | ||
| Examples: | ||
| >>> set_color(s="hello world",color="red") | ||
|
|
||
| """ | ||
|
|
||
| if COLOR_SUPPORT: | ||
| return f"{getattr(Colors, color.strip().upper()).value}{s}{Colors.NC.value}" | ||
| return f"{s}" # pragma: no cover |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
set_color doesn't honor its own documented fallback for invalid colors.
The docstring states: "If color is unsupported or invalid, returns original raw string without any escape codes." — but getattr(Colors, color.strip().upper()) has no default, so an invalid/unsupported color name raises AttributeError instead of returning s unchanged. Current call sites all pass valid names so this doesn't trigger today, but the contract is broken for any future/typo'd usage.
🔧 Proposed fix
if COLOR_SUPPORT:
- return f"{getattr(Colors, color.strip().upper()).value}{s}{Colors.NC.value}"
+ try:
+ color_code = Colors[color.strip().upper()].value
+ except KeyError:
+ return s
+ return f"{color_code}{s}{Colors.NC.value}"
return f"{s}" # pragma: no cover📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def set_color(s: str, | |
| color: str) -> str: | |
| """ | |
| Wrap input string with specified ANSI terminal color escape sequence. | |
| Color name argument is case-insensitive. If color is unsupported or invalid, | |
| returns original raw string without any escape codes. | |
| Args: | |
| s: Original text string to be colored | |
| color: Color enum name, case-insensitive (e.g. "red", "GREEN", "Yellow") | |
| Returns: | |
| str: Text wrapped with ANSI color codes if color output is available, | |
| otherwise the unmodified input string | |
| Examples: | |
| >>> set_color(s="hello world",color="red") | |
| """ | |
| if COLOR_SUPPORT: | |
| return f"{getattr(Colors, color.strip().upper()).value}{s}{Colors.NC.value}" | |
| return f"{s}" # pragma: no cover | |
| def set_color(s: str, | |
| color: str) -> str: | |
| """ | |
| Wrap input string with specified ANSI terminal color escape sequence. | |
| Color name argument is case-insensitive. If color is unsupported or invalid, | |
| returns original raw string without any escape codes. | |
| Args: | |
| s: Original text string to be colored | |
| color: Color enum name, case-insensitive (e.g. "red", "GREEN", "Yellow") | |
| Returns: | |
| str: Text wrapped with ANSI color codes if color output is available, | |
| otherwise the unmodified input string | |
| Examples: | |
| >>> set_color(s="hello world",color="red") | |
| """ | |
| if COLOR_SUPPORT: | |
| try: | |
| color_code = Colors[color.strip().upper()].value | |
| except KeyError: | |
| return s | |
| return f"{color_code}{s}{Colors.NC.value}" | |
| return f"{s}" # pragma: no cover |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@run_tests.py` around lines 87 - 107, The set_color helper does not follow its
documented fallback when an invalid color name is passed. Update set_color to
safely resolve the Colors member in the color handling branch, and if the lookup
fails, return the original string s unchanged instead of raising. Keep the
behavior centered in set_color so current callers continue to work with valid
color names while the invalid-color contract is honored.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16672 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
The compatibility issue with colored terminal output I encountered was documented in issue #16628 . This PR resolves the problem and implements the following features:
1.Encapsulate terminal color rendering logic into a unified
set_colorfunction for better maintainability and extensibility.2.Add cross-platform color support pre-detection, automatically disable ANSI color escape codes in non-interactive terminals or unsupported environments.
3.Enable native Windows terminal ANSI color support to avoid garbled characters.
4.Optimize terminal color compatibility, clean up redundant hard-coded color strings.