|
| 1 | +import json |
| 2 | +import pathlib |
| 3 | + |
| 4 | + |
| 5 | +def prepend_pointer(pointer, key): |
| 6 | + if key == "/": |
| 7 | + return pointer |
| 8 | + elif pointer == "/": |
| 9 | + return key |
| 10 | + else: |
| 11 | + return key + pointer |
| 12 | + |
| 13 | + |
| 14 | +def inject_include(rules: dict, dirs=None): |
| 15 | + if dirs is None: |
| 16 | + dirs = [] |
| 17 | + dirs.append("") # adding default path |
| 18 | + dirs = [pathlib.Path(d) for d in dirs] |
| 19 | + |
| 20 | + # max 10 levels of nesting to avoid infinite loops |
| 21 | + current = rules |
| 22 | + |
| 23 | + for _ in range(10): |
| 24 | + # check if the rules have any include |
| 25 | + include_present = any(rule["type"] == "include" for rule in current) |
| 26 | + |
| 27 | + # if there are no includes, return the current ones |
| 28 | + if not include_present: |
| 29 | + return current |
| 30 | + |
| 31 | + enriched = [] |
| 32 | + # otherwise, do a round of replacement |
| 33 | + for rule in current: |
| 34 | + # copy all rules that are not include |
| 35 | + if rule["type"] != "include": |
| 36 | + enriched.append(rule) |
| 37 | + continue |
| 38 | + |
| 39 | + # if the rule is an include, expand the node with a copy of the included file |
| 40 | + replaced = False |
| 41 | + # the include file could be in any of the include directories |
| 42 | + for dir in dirs: |
| 43 | + spec_file = rule["spec_file"] |
| 44 | + f = dir / spec_file |
| 45 | + # check if the file exists |
| 46 | + if f.is_file(): |
| 47 | + with open(f, 'r') as ifs: |
| 48 | + include_rules = json.load(ifs) |
| 49 | + |
| 50 | + # loop over all rules to add the prefix |
| 51 | + for i_rule in include_rules: |
| 52 | + prefix = rule["pointer"] |
| 53 | + pointer = i_rule["pointer"] |
| 54 | + new_pointer = prepend_pointer(pointer, prefix) |
| 55 | + i_rule["pointer"] = new_pointer |
| 56 | + |
| 57 | + # save modified rules |
| 58 | + for i_rule in include_rules: |
| 59 | + enriched.append(i_rule) |
| 60 | + |
| 61 | + # one substitution is enough, give up the search over include dirs |
| 62 | + replaced = True |
| 63 | + break |
| 64 | + |
| 65 | + if not replaced: |
| 66 | + pointer = rule["pointer"] |
| 67 | + raise RuntimeError( |
| 68 | + f"Failed to replace the include rule: {pointer}") |
| 69 | + |
| 70 | + # now that we replaced the include, copy it back to current |
| 71 | + current = enriched |
| 72 | + |
| 73 | + raise RuntimeError("Reached maximal 10 levels of include recursion.") |
0 commit comments