Skip to content

Instantly share code, notes, and snippets.

@nathants
Last active Jun 20, 2022
Embed
What would you like to do?
#!/usr/bin/env python3
# flake8: noqa
# type: ignore
"""
convert json/yaml to colorized yaml for easy reading
"""
import os
import re
import yaml
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).splitlines()
for line in lines:
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)
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