File indexing completed on 2024-05-12 04:02:13

0001 #!/usr/bin/env python3
0002 # -*- coding: utf-8 -*-
0003 #
0004 # Generate SPDX-Comments syntax file
0005 #
0006 # SPDX-FileCopyrightText: 2020 Alex Turbov <i.zaufi@gmail.com>
0007 # SPDX-License-Identifier: MIT
0008 #
0009 # To install prerequisites:
0010 #
0011 #   $ pip install --user click jinja2
0012 #
0013 # To use:
0014 #
0015 #   $ ./generate-spdx-syntax.py > ../syntax/spdx-comments.xml
0016 #
0017 
0018 import json
0019 import pathlib
0020 import urllib.request
0021 
0022 import click
0023 import jinja2
0024 
0025 
0026 def get_json(url):
0027     with urllib.request.urlopen(url=url) as body:
0028         return json.load(body)
0029 
0030 
0031 @click.command()
0032 @click.argument('template', type=click.File('r'), default='./spdx-comments.xml.tpl')
0033 def cli(template):
0034 
0035     data = {
0036         'licenses': [
0037             *filter(
0038                 lambda l: not l['licenseId'].endswith('+')
0039               , get_json(url='https://spdx.org/licenses/licenses.json')['licenses']
0040               )
0041           ]
0042       , 'exceptions': [
0043             *filter(
0044                 lambda l: not l['licenseExceptionId'].endswith('+')
0045               , get_json(url='https://spdx.org/licenses/exceptions.json')['exceptions']
0046               )
0047           ]
0048       }
0049 
0050     env = jinja2.Environment(
0051         keep_trailing_newline=True
0052       )
0053     env.block_start_string = '<!--['
0054     env.block_end_string = ']-->'
0055     env.variable_start_string = '<!--{'
0056     env.variable_end_string = '}-->'
0057     env.comment_start_string = '<!--#'
0058     env.comment_end_string = '#-->'
0059 
0060     tpl = env.from_string(template.read())
0061     result = tpl.render(data)
0062     print(result.strip(), end=None)
0063 
0064 
0065 if __name__ == '__main__':
0066     cli()
0067     # TODO Handle execptions and show errors