forked from m5stack/M5Tab5-UserDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_legacy_i2c.py
More file actions
290 lines (233 loc) · 8.11 KB
/
check_legacy_i2c.py
File metadata and controls
290 lines (233 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
"""Detect legacy ESP-IDF I2C driver usage in the source tree.
This script scans the repository for includes of ``driver/i2c.h`` and for calls
to helpers that belong to the deprecated "legacy" I2C driver. Mixing those
helpers with the NG driver will trigger runtime conflicts on firmware boot, so
CI blocks them from landing in ``main``.
Run the script from the repository root::
python3 scripts/check_legacy_i2c.py
The exit status is non-zero when a forbidden pattern is found, making it easy
to wire the script into pre-commit hooks or CI jobs.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Iterator, Sequence
REPO_ROOT = Path(__file__).resolve().parents[1]
@dataclass(frozen=True)
class LegacyPattern:
"""Representation of a legacy usage that should be flagged."""
regex: re.Pattern[str]
description: str
@dataclass(frozen=True)
class Finding:
"""A single match of a legacy API usage."""
path: Path
line_no: int
reason: str
line: str
@dataclass(frozen=True)
class ScanResult:
"""Aggregated result of scanning one or more paths."""
files_scanned: int
findings: list[Finding]
SOURCE_SUFFIXES: frozenset[str] = frozenset(
{
".c",
".cc",
".cpp",
".cxx",
".h",
".hh",
".hpp",
".hxx",
".ipp",
}
)
EXCLUDED_DIRS: frozenset[str] = frozenset(
{
".git",
"build",
"cmake-build-debug",
"cmake-build-release",
"managed_components",
"__pycache__",
".venv",
}
)
KCONFIG_PREFIX: str = "sdkconfig"
LEGACY_PATTERNS: tuple[LegacyPattern, ...] = (
LegacyPattern(
re.compile(r"#\s*include\s*[\"<]driver/i2c\.h[\">]"),
"legacy driver include",
),
LegacyPattern(
re.compile(r"\bi2c_param_config\b"),
"legacy i2c_param_config helper",
),
LegacyPattern(
re.compile(r"\bi2c_driver_install\b"),
"legacy i2c_driver_install helper",
),
LegacyPattern(
re.compile(r"\bi2c_driver_delete\b"),
"legacy i2c_driver_delete helper",
),
LegacyPattern(
re.compile(r"\bi2c_cmd_link_create(?:_static)?\b"),
"legacy I2C command link creation",
),
LegacyPattern(
re.compile(r"\bi2c_cmd_link_delete(?:_static)?\b"),
"legacy I2C command link deletion",
),
LegacyPattern(
re.compile(r"\bi2c_master_cmd_begin\b"),
"legacy i2c_master_cmd_begin helper",
),
LegacyPattern(
re.compile(r"\bi2c_master_(?:start|stop|write_byte|write|read_byte|read)\b"),
"legacy low-level I2C master helper",
),
)
CONFIG_GUARDS: tuple[LegacyPattern, ...] = (
LegacyPattern(
re.compile(r"^CONFIG_I2C_ENABLE_LEGACY_DRIVERS=([yY])\b"),
"legacy I2C driver enabled in configuration",
),
LegacyPattern(
re.compile(r"^CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK=([nN])\b"),
"legacy driver conflict check still enabled in configuration",
),
LegacyPattern(
re.compile(r"^#\s*CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK\s+is not set"),
"legacy driver conflict check still enabled in configuration",
),
)
def iter_source_files(
paths: Sequence[Path],
*,
include_suffixes: Iterable[str] = SOURCE_SUFFIXES,
excluded_dirs: Iterable[str] = EXCLUDED_DIRS,
) -> Iterator[Path]:
"""Yield source files below *paths* that match the allowed suffixes."""
suffixes = {suffix.lower() for suffix in include_suffixes}
exclude = set(excluded_dirs)
for base in paths:
if base.is_file():
if base.suffix.lower() in suffixes:
yield base
continue
for dirpath, dirnames, filenames in os.walk(base, followlinks=False):
dirnames[:] = [d for d in dirnames if d not in exclude]
for filename in filenames:
path = Path(dirpath, filename)
if path.suffix.lower() in suffixes:
yield path
def iter_config_files(
paths: Sequence[Path],
*,
excluded_dirs: Iterable[str] = EXCLUDED_DIRS,
) -> Iterator[Path]:
"""Yield Kconfig-style files (``sdkconfig*``) below *paths*."""
exclude = set(excluded_dirs)
for base in paths:
if base.is_file():
if base.name.startswith(KCONFIG_PREFIX):
yield base
continue
for dirpath, dirnames, filenames in os.walk(base, followlinks=False):
dirnames[:] = [d for d in dirnames if d not in exclude]
for filename in filenames:
if filename.startswith(KCONFIG_PREFIX):
yield Path(dirpath, filename)
def scan_file(path: Path, patterns: Sequence[LegacyPattern] = LEGACY_PATTERNS) -> list[Finding]:
"""Return a list of legacy usage matches for *path*."""
matches: list[Finding] = []
with path.open("r", encoding="utf-8", errors="ignore") as handle:
for line_no, line in enumerate(handle, start=1):
for pattern in patterns:
if pattern.regex.search(line):
matches.append(
Finding(
path=path,
line_no=line_no,
reason=pattern.description,
line=line.rstrip(),
)
)
return matches
def scan_config_file(
path: Path,
patterns: Sequence[LegacyPattern] = CONFIG_GUARDS,
) -> list[Finding]:
"""Return a list of configuration violations for *path*."""
matches: list[Finding] = []
with path.open("r", encoding="utf-8", errors="ignore") as handle:
for line_no, line in enumerate(handle, start=1):
stripped = line.strip()
for pattern in patterns:
if pattern.regex.search(stripped):
matches.append(
Finding(
path=path,
line_no=line_no,
reason=pattern.description,
line=line.rstrip(),
)
)
return matches
def scan_paths(paths: Sequence[Path]) -> ScanResult:
"""Scan the provided *paths* for legacy I2C usage."""
findings: list[Finding] = []
files_scanned = 0
for file_path in iter_source_files(paths):
files_scanned += 1
findings.extend(scan_file(file_path))
for config_path in iter_config_files(paths):
files_scanned += 1
findings.extend(scan_config_file(config_path))
return ScanResult(files_scanned=files_scanned, findings=findings)
def _format_finding(finding: Finding, root: Path) -> str:
resolved_path = finding.path.resolve()
try:
relative_path = resolved_path.relative_to(root)
except ValueError:
relative_path = resolved_path
return (
f"{relative_path}:{finding.line_no}: {finding.reason}\n"
f" {finding.line}"
)
def run(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"paths",
nargs="*",
type=Path,
default=[REPO_ROOT],
help="Paths to scan (defaults to the repository root).",
)
parser.add_argument(
"--root",
type=Path,
default=REPO_ROOT,
help="Root used when reporting relative file paths.",
)
args = parser.parse_args(argv)
target_paths = [path if path.is_absolute() else args.root / path for path in args.paths]
result = scan_paths(target_paths)
if result.findings:
print(f"Found {len(result.findings)} legacy I2C usage(s) across {result.files_scanned} file(s):")
for finding in result.findings:
print(_format_finding(finding, args.root.resolve()))
return 1
print(f"No legacy I2C usage found in {result.files_scanned} file(s).")
return 0
def main() -> None: # pragma: no cover - thin CLI wrapper
sys.exit(run())
if __name__ == "__main__": # pragma: no cover - CLI entry point
main()