|
| 1 | +import json |
| 2 | + |
| 3 | +from tabulate import tabulate |
| 4 | + |
| 5 | +# This file is for defining macros for mkdocs-macros plugin |
| 6 | +# Check https://mkdocs-macros-plugin.readthedocs.io/en/latest/macros/ for the details |
| 7 | + |
| 8 | + |
| 9 | +def format_param_type(param_type): |
| 10 | + if param_type == "number": |
| 11 | + return "float" |
| 12 | + else: |
| 13 | + return param_type |
| 14 | + |
| 15 | + |
| 16 | +def format_param_range(param): |
| 17 | + list_of_range = [] |
| 18 | + if "enum" in param.keys(): |
| 19 | + list_of_range.append(param["enum"]) |
| 20 | + if "minimum" in param.keys(): |
| 21 | + list_of_range.append("≥" + str(param["minimum"])) |
| 22 | + if "exclusiveMinimum" in param.keys(): |
| 23 | + list_of_range.append(">" + str(param["exclusiveMinimum"])) |
| 24 | + if "maximum" in param.keys(): |
| 25 | + list_of_range.append("≤" + str(param["maximum"])) |
| 26 | + if "exclusiveMaximum" in param.keys(): |
| 27 | + list_of_range.append("<" + str(param["exclusiveMaximum"])) |
| 28 | + if "exclusive" in param.keys(): |
| 29 | + list_of_range.append("≠" + str(param["exclusive"])) |
| 30 | + |
| 31 | + if len(list_of_range) == 0: |
| 32 | + return "N/A" |
| 33 | + else: |
| 34 | + range_in_text = "" |
| 35 | + for item in list_of_range: |
| 36 | + if range_in_text != "": |
| 37 | + range_in_text += "<br/>" |
| 38 | + range_in_text += str(item) |
| 39 | + return range_in_text |
| 40 | + |
| 41 | + |
| 42 | +def extract_parameter_info(parameters, namespace=""): |
| 43 | + params = [] |
| 44 | + for k, v in parameters.items(): |
| 45 | + if v["type"] != "object": |
| 46 | + param = {} |
| 47 | + param["Name"] = namespace + k |
| 48 | + param["Type"] = format_param_type(v["type"]) |
| 49 | + param["Description"] = v["description"] |
| 50 | + param["Default"] = v["default"] |
| 51 | + param["Range"] = format_param_range(v) |
| 52 | + params.append(param) |
| 53 | + else: # if the object is namespace, then dive deeper in to json value |
| 54 | + params.extend(extract_parameter_info(v["properties"], k + ".")) |
| 55 | + return params |
| 56 | + |
| 57 | + |
| 58 | +def format_json(json_data): |
| 59 | + parameters = list(json_data["definitions"].values())[0]["properties"] |
| 60 | + # cspell: ignore tablefmt |
| 61 | + markdown_table = tabulate(extract_parameter_info(parameters), headers="keys", tablefmt="github") |
| 62 | + return markdown_table |
| 63 | + |
| 64 | + |
| 65 | +def define_env(env): |
| 66 | + @env.macro |
| 67 | + def json_to_markdown(json_schema_file_path): |
| 68 | + with open(json_schema_file_path) as f: |
| 69 | + data = json.load(f) |
| 70 | + return format_json(data) |
0 commit comments