universal_dependencies / tools /03_generate_README.py
iiegn's picture
Refactor: Rename and simplify README generation script
8dd6802 verified
#!/usr/bin/env -S uv run --script
#
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "Jinja2",
# "load-dotenv",
# ]
# ///
"""
Generate README-{UD_VER} from templates/README.tmpl using metadata-{UD_VER}.json.
"""
import json
import argparse
import logging
from os import getenv
from pathlib import Path, PurePath
import jinja2
from dotenv import load_dotenv
load_dotenv()
UD_VER = getenv('UD_VER', "2.15")
# Parse command line arguments
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-o', '--override', action='store_true',
help='override output file if it already exists')
parser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity level')
args = parser.parse_args()
# Set up logging
logging.basicConfig(
level = max(logging.DEBUG, logging.INFO - args.verbose * 10),
format='%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
if __name__ == '__main__':
basepath = Path(__file__).parent.relative_to(Path.cwd())
# Read the metadata from json
with Path(basepath, f"metadata-{UD_VER}.json").open(mode='r') as fh:
metadata = json.load(fh)
with Path(basepath, "etc", f"description-{UD_VER}").open(mode='r') as fh:
description = (fh.read()).strip()
with Path(basepath, "etc", f"citation-{UD_VER}").open(mode='r') as fh:
citation = (fh.read()).strip()
# Generate README from template
template_fn = Path(basepath, "templates", "README.tmpl")
output_fn = Path(basepath, f"README-{UD_VER}")
if args.override or not output_fn.exists():
with template_fn.open(mode='r') as fh:
template = jinja2.Template(fh.read())
with output_fn.open(mode='w') as fh:
output = template.render(citation=citation,
description=description,
data=metadata, ud_ver=UD_VER,)
fh.write(output)
print(f"{output_fn} written")
else:
logging.info(f"Output {output_fn} already exists: Not overriding.")