gh-133346: Make theming support in _colorize extensible (GH-133347)

Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
This commit is contained in:
Łukasz Langa 2025-05-05 23:45:25 +02:00 committed by GitHub
parent 9cc77aaf9d
commit f610bbdf74
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 585 additions and 371 deletions

View file

@ -7,7 +7,7 @@ import argparse
import json
import re
import sys
from _colorize import ANSIColors, can_colorize
from _colorize import get_theme, can_colorize
# The string we are colorizing is valid JSON,
@ -17,27 +17,27 @@ from _colorize import ANSIColors, can_colorize
_color_pattern = re.compile(r'''
(?P<key>"(\\.|[^"\\])*")(?=:) |
(?P<string>"(\\.|[^"\\])*") |
(?P<number>NaN|-?Infinity|[0-9\-+.Ee]+) |
(?P<boolean>true|false) |
(?P<null>null)
''', re.VERBOSE)
_colors = {
'key': ANSIColors.INTENSE_BLUE,
'string': ANSIColors.BOLD_GREEN,
'boolean': ANSIColors.BOLD_CYAN,
'null': ANSIColors.BOLD_CYAN,
_group_to_theme_color = {
"key": "definition",
"string": "string",
"number": "number",
"boolean": "keyword",
"null": "keyword",
}
def _replace_match_callback(match):
for key, color in _colors.items():
if m := match.group(key):
return f"{color}{m}{ANSIColors.RESET}"
return match.group()
def _colorize_json(json_str, theme):
def _replace_match_callback(match):
for group, color in _group_to_theme_color.items():
if m := match.group(group):
return f"{theme[color]}{m}{theme.reset}"
return match.group()
def _colorize_json(json_str):
return re.sub(_color_pattern, _replace_match_callback, json_str)
@ -100,13 +100,16 @@ def main():
else:
outfile = open(options.outfile, 'w', encoding='utf-8')
with outfile:
for obj in objs:
if can_colorize(file=outfile):
if can_colorize(file=outfile):
t = get_theme(tty_file=outfile).syntax
for obj in objs:
json_str = json.dumps(obj, **dump_args)
outfile.write(_colorize_json(json_str))
else:
outfile.write(_colorize_json(json_str, t))
outfile.write('\n')
else:
for obj in objs:
json.dump(obj, outfile, **dump_args)
outfile.write('\n')
outfile.write('\n')
except ValueError as e:
raise SystemExit(e)