Skip to content

fix: encapsulate terminal color output and add cross-platform color detection - #16672

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
Ricardo-shuo-liu:fix-color
Jul 7, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
Ricardo-shuo-liu:fix-color

Conversation

@Ricardo-shuo-liu

Copy link
Copy Markdown
Contributor

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_color function 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.

…e-flight color support detection to avoid unwanted garbled escape characters.
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 390bd5ba-f681-4d99-abcc-dcdba06cba5f

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7c9f5 and 0f21cb7.

📒 Files selected for processing (1)
  • run_tests.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • run_tests.py

📝 Walkthrough

Walkthrough

This change adds ANSI terminal color support to run_tests.py, converting Colors into an Enum, detecting terminal color capability, adding set_color, and applying colorized labels and status messages throughout the test runner.

Changes

Terminal Color Support

Layer / File(s) Summary
Color infrastructure: Colors enum, detection, and helper
run_tests.py
Introduces Colors as an Enum, adds _is_color_supported() for OS/terminal detection, defines COLOR_SUPPORT, and adds set_color() to conditionally wrap text in ANSI codes.
Apply coloring to runner messages
run_tests.py
Updates [INFO]/[ERROR] labels, execution header, success/coverage messages, and [FAILURE]/[INTERRUPTED] reporting to use set_color.

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)
Loading

Poem

A rabbit hops through terminal light,
Painting [INFO] green and [ERROR] bright,
Colors dance where text once was plain,
Even KeyboardInterrupt gets a stain—
Of red for failure, calm for success,
This bunny's code is now dressed to impress! 🐇🎨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: unified terminal color handling with cross-platform detection.
Description check ✅ Passed The description includes the required Summary section and gives clear context plus the key implementation points.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
run_tests.py (3)

66-69: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Simplify the exception handling.

except BaseException as e: if isinstance(e, (SystemExit, KeyboardInterrupt)): raise e; return False is equivalent to just except Exception: — SystemExit/KeyboardInterrupt derive from BaseException, not Exception, so catching Exception already 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 win

No logging in the new color-detection flow.

_is_color_supported() silently swallows all exceptions (Windows-version parsing failures, ctypes access errors, tput failures) and returns False with no diagnostic trail, making it hard to debug why colors unexpectedly stay disabled in a given environment. As per coding guidelines, **/*.py changes 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 value

Repeated 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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1659d963-51ab-44c0-89d0-811b2f71f5df

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and 0f7c9f5.

📒 Files selected for processing (1)
  • run_tests.py

Comment thread run_tests.py Resolved
Comment thread run_tests.py
Comment on lines +87 to +107
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3a247db) to head (e576bb9).
⚠️ Report is 6 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit ab5958f into infiniflow:main Jul 7, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants