|
| 1 | +import shlex |
| 2 | +import subprocess |
| 3 | +import json |
| 4 | +from json import JSONDecodeError |
| 5 | + |
| 6 | + |
| 7 | +def resources_dict_from_api_resources(): |
| 8 | + """ |
| 9 | + Build dict with resources and matched values. |
| 10 | +
|
| 11 | + Output example for resource: |
| 12 | + { |
| 13 | + 'api_version': 'networking.k8s.io/v1', |
| 14 | + 'api_group': {'config.openshift.io': 'false', 'networking.k8s.io': 'true'} |
| 15 | + } |
| 16 | + """ |
| 17 | + resources_dict = {} |
| 18 | + api_resources = subprocess.check_output(shlex.split("oc api-resources --no-headers")) |
| 19 | + api_resources = api_resources.decode("utf-8") |
| 20 | + for line in api_resources.splitlines(): |
| 21 | + line_list = line.split() |
| 22 | + try: |
| 23 | + _, _, api_version, namespaced, kind = line_list |
| 24 | + except ValueError: |
| 25 | + _, api_version, namespaced, kind = line_list |
| 26 | + |
| 27 | + split_api_version = api_version.split("/") |
| 28 | + api_group = split_api_version[0] if len(split_api_version) > 1 else None |
| 29 | + resources_dict.setdefault(kind, {}).setdefault("api_group", {}) |
| 30 | + resources_dict[kind]["api_group"].update({api_group: {}}) |
| 31 | + resources_dict[kind]["api_group"][api_group]["namespaced"] = namespaced |
| 32 | + resources_dict[kind]["api_group"][api_group]["api_version"] = split_api_version[-1] |
| 33 | + |
| 34 | + return resources_dict |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + data_file = "tests/scripts/resources_definitions.json" |
| 39 | + with open(data_file, "r") as fd_read: |
| 40 | + try: |
| 41 | + data = json.loads(fd_read.read()) |
| 42 | + except JSONDecodeError: |
| 43 | + data = {} |
| 44 | + |
| 45 | + new_data = resources_dict_from_api_resources() |
| 46 | + if new_data: |
| 47 | + for key in new_data: |
| 48 | + data[key] = new_data[key] |
| 49 | + |
| 50 | + with open(data_file, "w") as fd_write: |
| 51 | + fd_write.write(json.dumps(data)) |
0 commit comments