diff options
author | Qyriad <qyriad@qyriad.me> | 2024-04-08 21:43:38 -0600 |
---|---|---|
committer | eldritch horrors <pennae@lix.systems> | 2024-04-10 15:04:34 +0200 |
commit | 723ddadf92d0e8d54197424e1a0cb839e9d3d6b6 (patch) | |
tree | 9ce86d7f6b0f1debe9cb5755ef2b4896b8fa66dc /doc/manual/json-to-tree.py | |
parent | 7e139c52dd901c0feccf6a4f2cbc56673d5e0259 (diff) |
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
Diffstat (limited to 'doc/manual/json-to-tree.py')
-rwxr-xr-x | doc/manual/json-to-tree.py | 61 |
1 files changed, 61 insertions, 0 deletions
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()) |