From 723ddadf92d0e8d54197424e1a0cb839e9d3d6b6 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Mon, 8 Apr 2024 21:43:38 -0600 Subject: docs: generalize manpage generation script as json-to-tree.py This should be capable of replacing every invocation of nix eval --write-to. Change-Id: I60387bc9b0fc54a91244eddb639beaa64d705878 --- doc/manual/json-to-tree.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100755 doc/manual/json-to-tree.py (limited to 'doc/manual/json-to-tree.py') diff --git a/doc/manual/json-to-tree.py b/doc/manual/json-to-tree.py new file mode 100755 index 000000000..27c8e417c --- /dev/null +++ b/doc/manual/json-to-tree.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +""" +This script is a helper for this project's Meson buildsystem, to replace its +usage of `nix eval --write-to`. Writing a JSON object as a nested directory +tree is more generic, easier to maintain, and far, far less cursed. Nix +has 'good' support for JSON output. Let's just use it. +""" + +import argparse +from pathlib import Path +import json +import sys + +name = 'json-to-tree.py' + +def log(*args, **kwargs): + kwargs['file'] = sys.stderr + return print(f'{name}:', *args, **kwargs) + +def write_dict_to_directory(current_directory: Path, data: dict, files_written=0): + current_directory.mkdir(parents=True, exist_ok=True) + for key, value in data.items(): + nested_path = current_directory / key + match value: + case dict(nested_data): + files_written += write_dict_to_directory(nested_path, nested_data) + + case str(content): + nested_path.write_text(content) + files_written += 1 + + case rest: + assert False, \ + f'should have been called on a dict or string, not {type(rest)=}\n\t{rest=}' + + return files_written + +def main(): + parser = argparse.ArgumentParser(name) + parser.add_argument('-i', '--input', type=argparse.FileType('r'), default='-', + help='The JSON input to operate on and output as a directory tree', + ) + parser.add_argument('-o', '--output', type=Path, required=True, + help='The place to put the directory tree', + ) + args = parser.parse_args() + + json_string = args.input.read() + + try: + data = json.loads(json_string) + except json.JSONDecodeError: + log(f'could not decode JSON from input: {json_string}') + raise + + + files_written = write_dict_to_directory(args.output, data) + log(f'wrote {files_written} files') + +sys.exit(main()) -- cgit v1.2.3