|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Copyright (c) 2025 James Roy <rruuaanng@outlook.com> |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | + |
| 6 | +# This script is used to replace the properties containing |
| 7 | +# underscores in the binding. |
| 8 | + |
| 9 | + |
| 10 | +import argparse |
| 11 | +import os |
| 12 | +import sys |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +import yaml |
| 16 | + |
| 17 | +# bindings base |
| 18 | +BINDINGS_PATH = [Path("dts/bindings/")] |
| 19 | +BINDINGS_PROPERTIES_AL = None |
| 20 | +with open(Path(__file__).parent / 'bindings_properties_allowlist.yaml') as f: |
| 21 | + allowlist = yaml.safe_load(f.read()) |
| 22 | + if allowlist is not None: |
| 23 | + BINDINGS_PROPERTIES_AL = set(allowlist) |
| 24 | + else: |
| 25 | + BINDINGS_PROPERTIES_AL = set() |
| 26 | + |
| 27 | + |
| 28 | +def parse_cmd_args(): |
| 29 | + parse = argparse.ArgumentParser(allow_abbrev=False) |
| 30 | + parse.add_argument("--path", nargs="+", help="User binding path directory", type=Path) |
| 31 | + return parse.parse_args() |
| 32 | + |
| 33 | + |
| 34 | +def get_yaml_binding_paths() -> list: |
| 35 | + """Returns a list of 'dts/bindings/**/*.yaml'""" |
| 36 | + from glob import glob |
| 37 | + |
| 38 | + bindings = [] |
| 39 | + for path in BINDINGS_PATH: |
| 40 | + yamls = glob(f"{os.fspath(path)}/**/*.yaml", recursive=True) |
| 41 | + bindings.extend(yamls) |
| 42 | + return bindings |
| 43 | + |
| 44 | + |
| 45 | +def replace_bindings_underscores(binding_paths): |
| 46 | + """ |
| 47 | + Replace all property names containing underscores in the bindings. |
| 48 | + """ |
| 49 | + for binding_path in binding_paths: |
| 50 | + with open(binding_path, encoding="utf-8") as f: |
| 51 | + yaml_binding = yaml.safe_load(f) |
| 52 | + properties = yaml_binding.get("properties", {}) |
| 53 | + for prop_name in properties: |
| 54 | + if '_' in prop_name and prop_name not in BINDINGS_PROPERTIES_AL: |
| 55 | + _replace_underscores(binding_path, prop_name) |
| 56 | + |
| 57 | + |
| 58 | +def _replace_underscores(binding_path, prop_name): |
| 59 | + """Replace implementation""" |
| 60 | + with open(binding_path, "r+", encoding="utf-8") as f: |
| 61 | + lines = f.readlines() |
| 62 | + for i, rowline in enumerate(lines): |
| 63 | + line = rowline.split(":")[0].strip() |
| 64 | + if prop_name == line and "#" not in rowline: |
| 65 | + new_key = prop_name.replace("_", "-") |
| 66 | + if new_key != line: |
| 67 | + lines[i] = rowline.replace(line, new_key) |
| 68 | + f.seek(0) |
| 69 | + f.writelines(lines) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + args = parse_cmd_args() |
| 74 | + |
| 75 | + if args.path is not None: |
| 76 | + BINDINGS_PATH.extend(args.path) |
| 77 | + |
| 78 | + bindings = get_yaml_binding_paths() |
| 79 | + replace_bindings_underscores(bindings) |
| 80 | + |
| 81 | + sys.exit(0) |
0 commit comments