Martí Bolívar | 3f8d33e | 2023-08-09 16:59:20 -0700 | [diff] [blame] | 1 | """ |
| 2 | Utility script to migrate Zephyr-based projects to the new <zephyr/...> include |
| 3 | prefix. |
| 4 | |
| 5 | .. note:: |
| 6 | The script will also migrate <zephyr.h> or <zephyr/zephyr.h> to |
| 7 | <zephyr/kernel.h>. |
| 8 | |
| 9 | Usage:: |
| 10 | |
| 11 | python $ZEPHYR_BASE/scripts/utils/migrate_includes.py \ |
| 12 | -p path/to/zephyr-based-project |
| 13 | |
| 14 | Copyright (c) 2022 Nordic Semiconductor ASA |
| 15 | SPDX-License-Identifier: Apache-2.0 |
| 16 | """ |
| 17 | |
| 18 | import argparse |
| 19 | from pathlib import Path |
| 20 | import re |
| 21 | import sys |
| 22 | |
| 23 | |
| 24 | ZEPHYR_BASE = Path(__file__).parents[2] |
| 25 | |
| 26 | EXTENSIONS = ("c", "cpp", "h", "hpp", "dts", "dtsi", "rst", "S", "overlay", "ld") |
| 27 | |
| 28 | |
| 29 | def update_includes(project, dry_run): |
| 30 | for p in project.glob("**/*"): |
| 31 | if not p.is_file() or not p.suffix or p.suffix[1:] not in EXTENSIONS: |
| 32 | continue |
| 33 | |
| 34 | try: |
| 35 | with open(p) as f: |
| 36 | lines = f.readlines() |
| 37 | except UnicodeDecodeError: |
| 38 | print(f"File with invalid encoding: {p}, skipping", file=sys.stderr) |
| 39 | continue |
| 40 | |
| 41 | content = "" |
| 42 | migrate = False |
| 43 | for line in lines: |
| 44 | m = re.match(r"^(.*)#include <(.*\.h)>(.*)$", line) |
| 45 | if m and m.group(2) in ("zephyr.h", "zephyr/zephyr.h"): |
| 46 | content += ( |
| 47 | m.group(1) |
| 48 | + "#include <zephyr/kernel.h>" |
| 49 | + m.group(3) |
| 50 | + "\n" |
| 51 | ) |
| 52 | migrate = True |
| 53 | elif ( |
| 54 | m |
| 55 | and not m.group(2).startswith("zephyr/") |
| 56 | and (ZEPHYR_BASE / "include" / "zephyr" / m.group(2)).exists() |
| 57 | ): |
| 58 | content += ( |
| 59 | m.group(1) |
| 60 | + "#include <zephyr/" |
| 61 | + m.group(2) |
| 62 | + ">" |
| 63 | + m.group(3) |
| 64 | + "\n" |
| 65 | ) |
| 66 | migrate = True |
| 67 | else: |
| 68 | content += line |
| 69 | |
| 70 | if migrate: |
| 71 | print(f"Updating {p}{' (dry run)' if dry_run else ''}") |
| 72 | if not dry_run: |
| 73 | with open(p, "w") as f: |
| 74 | f.write(content) |
| 75 | |
| 76 | |
| 77 | if __name__ == "__main__": |
| 78 | parser = argparse.ArgumentParser(allow_abbrev=False) |
| 79 | parser.add_argument( |
| 80 | "-p", "--project", type=Path, required=True, help="Zephyr-based project path" |
| 81 | ) |
| 82 | parser.add_argument("--dry-run", action="store_true", help="Dry run") |
| 83 | args = parser.parse_args() |
| 84 | |
| 85 | update_includes(args.project, args.dry_run) |