git @ Cat's Eye Technologies Chrysoberyl / master script / make-files-jsonp
master

Tree @master (Download .tar.gz)

make-files-jsonp @masterraw · history · blame

#!/usr/bin/env python3

# SPDX-FileCopyrightText: Chris Pressey, the original author of this work, has dedicated it to the public domain.
# For more information, please refer to <https://unlicense.org/>
# SPDX-License-Identifier: Unlicense

from argparse import ArgumentParser
import json
import sys

if __name__ == '__main__':
    argparser = ArgumentParser()
    argparser.add_argument('filenames', metavar='FILENAME', type=str, nargs='+',
                           help='The files to put in the JSON.  If a file is listed '
                                'more than once, it will only be included the first time.')
    argparser.add_argument('-v', '--varname', metavar='VARNAME', type=str, default='examplePrograms',
                           help='The Javascript variable to assign the JSON value to.')
    options = argparser.parse_args(sys.argv[1:])

    seen = set()
    data = []

    for filename in sorted(options.filenames):
        if filename in seen:
            continue
        seen.add(filename)
        with open(filename, 'r') as f:
            data.append({
                'filename': filename,
                'contents': f.read()
            })

    sys.stdout.write("""\
{} = {};
""".format(options.varname, json.dumps(data, indent=4, sort_keys=True)))