Last active
January 29, 2024 03:56
-
-
Save nathants/1955b2c3130b7d1a00c8420ad6231639 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# flake8: noqa | |
# type: ignore | |
# The MIT License (MIT) | |
# Copyright (c) 2022-present Nathan Todd-Stone | |
# https://en.wikipedia.org/wiki/MIT_License#License_terms | |
""" | |
convert json/yaml to colorized yaml for easy reading | |
""" | |
import os | |
import re | |
import sys | |
import json | |
import yaml # pip install pyyaml | |
force = 'COLORS' in os.environ | |
def _make_color(code, text): | |
if force or sys.stdout.isatty(): | |
return "\033[{}m{}\033[0m".format(code, text) | |
else: | |
return text | |
clear = lambda text: _make_color(38, text) | |
red = lambda text: _make_color(31, text) | |
green = lambda text: _make_color(32, text) | |
yellow = lambda text: _make_color(33, text) | |
blue = lambda text: _make_color(34, text) | |
magenta = lambda text: _make_color(35, text) | |
cyan = lambda text: _make_color(36, text) | |
white = lambda text: _make_color(37, text) | |
_rm_color = re.compile(r'\x1b[^m]*m') | |
def rm_color(text): | |
return _rm_color.sub('', text) | |
data = sys.stdin.read() | |
try: | |
datas = [json.loads(data)] | |
except: | |
try: | |
datas = [json.loads(x) for x in data.splitlines()] | |
except: | |
try: | |
datas = [yaml.safe_load(data)] | |
except: | |
datas = [yaml.safe_load(x) for x in data.split('\n---\n')] | |
for i, data in enumerate(datas): | |
if i > 0 : | |
print('---') | |
lines = yaml.dump(data, width=10000).splitlines() | |
for line in lines: | |
if not line.strip(): | |
continue | |
try: | |
if line.strip()[0] != '-' or ': ' in line or line.endswith(':'): | |
size = len(line) - len(line.replace('- ', '').lstrip()) | |
line = { | |
0: blue, | |
2: green, | |
4: yellow, | |
6: red, | |
8: magenta, | |
10: cyan, | |
}.get(size, white)(line) | |
except: | |
print("failed to parse:", [line]) | |
raise | |
else: | |
try: | |
a, b = line.split(': ', 1) | |
except ValueError: | |
pass | |
else: | |
line = a + ': ' + clear(b) | |
print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment