|
| 1 | +""" |
| 2 | +Utility to convert examples from one format to another. |
| 3 | +
|
| 4 | +Example: |
| 5 | +python convert.py to-yaml ../docs/timeline/timeline-1.json ../docs/timeline/timeline-1.yaml |
| 6 | +""" |
| 7 | +import json |
| 8 | +import re |
| 9 | +import sys |
| 10 | +from typing import Optional |
| 11 | + |
| 12 | +import click |
| 13 | +import yaml |
| 14 | +from essentials.json import dumps as friendly_json_dumps |
| 15 | + |
| 16 | +_YAML_EXT = re.compile(r"\.ya?ml$", re.IGNORECASE) |
| 17 | +_JSON_EXT = re.compile(r"\.json$", re.IGNORECASE) |
| 18 | + |
| 19 | + |
| 20 | +def read_text_file(file_path: str) -> str: |
| 21 | + with open(file_path, "rt", encoding="utf8") as source_file: |
| 22 | + return source_file.read() |
| 23 | + |
| 24 | + |
| 25 | +def write_text_file(file_path: str, contents: str): |
| 26 | + with open(file_path, "wt", encoding="utf8") as dest_file: |
| 27 | + dest_file.write(contents) |
| 28 | + |
| 29 | + |
| 30 | +@click.group() |
| 31 | +def convert(): |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +@click.command("to-json") |
| 36 | +@click.argument("source") |
| 37 | +@click.argument("destination", required=False) |
| 38 | +def yaml_to_json(source: str, destination: Optional[str]): |
| 39 | + if _YAML_EXT.search(source): |
| 40 | + contents = read_text_file(source) |
| 41 | + data = yaml.safe_load(contents) |
| 42 | + output = friendly_json_dumps(data, indent=4, ensure_ascii=False) |
| 43 | + if destination: |
| 44 | + write_text_file(destination, output) |
| 45 | + else: |
| 46 | + print(output) |
| 47 | + else: |
| 48 | + click.echo(f'Unsupported source: "{source}"') |
| 49 | + sys.exit(1) |
| 50 | + |
| 51 | + |
| 52 | +@click.command("to-yaml") |
| 53 | +@click.argument("source") |
| 54 | +@click.argument("destination", required=False) |
| 55 | +def json_to_yaml(source: str, destination: Optional[str]): |
| 56 | + if _JSON_EXT.search(source): |
| 57 | + contents = read_text_file(source) |
| 58 | + data = json.loads(contents) |
| 59 | + if destination: |
| 60 | + write_text_file(destination, yaml.dump(data)) |
| 61 | + else: |
| 62 | + print(yaml.dump(data)) |
| 63 | + else: |
| 64 | + click.echo(f'Unsupported source: "{source}"') |
| 65 | + sys.exit(1) |
| 66 | + |
| 67 | + |
| 68 | +convert.add_command(yaml_to_json) |
| 69 | +convert.add_command(json_to_yaml) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + convert() |
0 commit comments