Skip to content

Commit 0d18e91

Browse files
gmarullcarlescufi
authored andcommitted
scripts: utils: add include migration script
All includes are now prefixed with <zephyr/...>, even though the old include paths can still be used when CONFIG_LEGACY_INCLUDE_PATH=y, an option still enabled by default. Migrating large projects can be tedious and time consuming. This patch provides a script that can be used to migrate any Zephyr-based project to the new include path. It is used like this: python $ZEPHYR_BASE/scripts/utils/migrate_includes.py \ -p path/to/zephyr-based-project Signed-off-by: Gerard Marull-Paretas <[email protected]>
1 parent b11fcc8 commit 0d18e91

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

scripts/utils/migrate_includes.py

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

0 commit comments

Comments
 (0)