Skip to content

Instantly share code, notes, and snippets.

@QuiteClose
Last active June 18, 2024 00:06
Show Gist options
  • Save QuiteClose/c21e45e67677864715deb3a4d6e4cd0f to your computer and use it in GitHub Desktop.
Save QuiteClose/c21e45e67677864715deb3a4d6e4cd0f to your computer and use it in GitHub Desktop.
Generate a schema from a YAML file (or from stdin.)
#!/usr/bin/env python3
'''
schema.py - Generate a schema from a YAML file (or from stdin.)
Required:
pip install PyYAML
Usage:
python3 schema.py < PATH
python3 schema.py PATH [PATH ...]
'''
import sys
from yaml import load
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
###############################################################################
def schema_sorter(data):
def compare(key):
'''Simple types first, then dict types, then list types.'''
if isinstance(data[key], dict):
return 'zz_dict_'+key
if isinstance(data[key], list):
return 'zz_list_'+key
else:
return 'aa_'+key
return compare
def get_schema(data, indent=' ', prefix=''):
type_name = type(data).__name__
result = [f'<{type_name}>']
if isinstance(data, dict):
ordered_keys = sorted(data.keys(), key=schema_sorter(data))
for key in ordered_keys:
child_schema = get_schema(data[key], indent, prefix+indent)
result.append(f'{prefix}{key}: {child_schema}')
elif isinstance(data, list):
child_schema = get_schema(data[0], indent, prefix+indent)
result.append(f'{prefix}-{indent[1:]}{child_schema}')
return '\n'.join(result)
def load_schema(file, indent=' '):
data = load(file, Loader=Loader)
return get_schema(data, indent)
def main(args):
if not args:
print(load_schema(sys.stdin))
for path in args:
print(f'# {path}')
with open(path) as f:
print(load_schema(f))
return sys.exit(0)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment