|
| 1 | +import json |
| 2 | +import os |
| 3 | +import re |
| 4 | +import jsonschema |
| 5 | + |
| 6 | +path_to_json_files = os.path.realpath(os.path.dirname(__file__)) |
| 7 | +json_file_names = sorted([filename for filename in os.listdir(path_to_json_files) |
| 8 | + if filename.endswith('.json') and filename.startswith('os')]) |
| 9 | +json_schema = { |
| 10 | + "$schema": "os_support_schema", |
| 11 | + "type": "object", |
| 12 | + "properties": { |
| 13 | + "versions": { |
| 14 | + "type": "array", |
| 15 | + "items": { |
| 16 | + "type": "object", |
| 17 | + "properties": { |
| 18 | + "version": { |
| 19 | + "type": "string" |
| 20 | + }, |
| 21 | + "os": { |
| 22 | + "type": "array", |
| 23 | + "items": { |
| 24 | + "type": "object", |
| 25 | + "properties": { |
| 26 | + "name": { |
| 27 | + "type": "string" |
| 28 | + }, |
| 29 | + "description": { |
| 30 | + "type": "string" |
| 31 | + } |
| 32 | + }, |
| 33 | + "required": [ |
| 34 | + "name", |
| 35 | + "description" |
| 36 | + ] |
| 37 | + } |
| 38 | + } |
| 39 | + }, |
| 40 | + "required": [ |
| 41 | + "version", |
| 42 | + "os" |
| 43 | + ] |
| 44 | + } |
| 45 | + } |
| 46 | + }, |
| 47 | + "required": [ |
| 48 | + "versions" |
| 49 | + ] |
| 50 | +} |
| 51 | + |
| 52 | + |
| 53 | +def create_merged_dict(files): |
| 54 | + prev_dir = os.getcwd() |
| 55 | + os.chdir(path_to_json_files) |
| 56 | + versions = list() |
| 57 | + for file in files: |
| 58 | + with open(file, 'r') as infile: |
| 59 | + try: |
| 60 | + version_dict = dict( |
| 61 | + { |
| 62 | + 'version': re.match("os_(.*).json", file).groups()[0], |
| 63 | + 'os': json.load(infile)['os'] |
| 64 | + } |
| 65 | + ) |
| 66 | + versions.append(version_dict) |
| 67 | + except AttributeError: |
| 68 | + raise Exception("All files should respect the 'os_(.*).json' regex") |
| 69 | + |
| 70 | + merged_dict = dict({'versions': versions}) |
| 71 | + os.chdir(prev_dir) |
| 72 | + return merged_dict |
| 73 | + |
| 74 | + |
| 75 | +def write_merged_json(merged_dict): |
| 76 | + with open(f"{path_to_json_files}/merged_os_support.json", 'w') as output_file: |
| 77 | + json.dump(merged_dict, output_file, indent=4) |
| 78 | + print(f"Written merged json in {path_to_json_files}/merged_os_support.json") |
| 79 | + |
| 80 | + |
| 81 | +def validate_json(json_data): |
| 82 | + try: |
| 83 | + jsonschema.validate(instance=json_data, schema=json_schema) |
| 84 | + except jsonschema.exceptions.ValidationError as err: |
| 85 | + return False |
| 86 | + return True |
| 87 | + |
| 88 | + |
| 89 | +if __name__ == "__main__": |
| 90 | + merged_dictionary = create_merged_dict(json_file_names) |
| 91 | + print("Merged JSON data respects the schema" if validate_json(merged_dictionary) |
| 92 | + else "Merged JSON data does not respect the schema") |
| 93 | + write_merged_json(merged_dictionary) |
0 commit comments