Files
cutdex/tool/check_package_boundaries.py
T
lingjhf 0343e2f723 refactor(build): unify SDK configuration and release tooling
Pin Flutter with FVM and share local environment loading across IDE, Python, and Dart entrypoints. Keep CI on the verified preinstalled SDK and skip local overrides.

Extract common build presets, process execution, and file hashing. Propagate project roots through SDK selection and release commands, and migrate macOS release, signing, and DMG orchestration to Python.

Reuse local check suites in CI, support Android source overrides, and update documentation and regression tests.
2026-10-06 23:34:15 +08:00

127 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Check declared dependencies and public imports across workspace boundaries."""
from pathlib import Path
import posixpath
import re
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parent.parent
RUNTIME = {
'cutdex_native': {'flutter', 'path'},
'cutdex_ui': {'flutter', 'cutdex_native', 'freezed_annotation'},
}
DEVELOPMENT = {
'cutdex_native': {'flutter_test', 'flutter_lints'},
'cutdex_ui': {'flutter_test', 'flutter_lints', 'build_runner', 'freezed'},
}
TOKENS = re.compile(
r"//[^\n]*|/\*.*?\*/|"
r"(?P<string>r?(?:\"\"\".*?\"\"\"|'''.*?'''|"
r"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'))|"
r"(?P<word>\w+)|(?P<punct>[^\s])",
re.DOTALL,
)
def directives(source):
"""Read URI strings in each directive, including conditional alternatives."""
tokens = [token for token in TOKENS.finditer(source) if token.lastgroup]
index = 0
while index < len(tokens):
token = tokens[index]
kind = token.group()
index += 1
if token.lastgroup != 'word' or kind not in ('import', 'export', 'part'):
continue
if index >= len(tokens) or tokens[index].lastgroup != 'string':
continue
while index < len(tokens) and tokens[index].group() != ';':
token = tokens[index]
index += 1
if token.lastgroup == 'string':
value = token.group()
if value.startswith('r'):
value = value[1:]
quote = value[0] * (3 if value[:3] == value[0] * 3 else 1)
yield kind, value[len(quote):-len(quote)]
def package_uri(uri):
dependency, _, path = uri.removeprefix('package:').partition('/')
return dependency, posixpath.normpath(unquote(path))
def dependency_names(manifest, section):
"""Read the flat dependency keys used by our workspace manifests."""
match = re.search(rf'^{section}:\s*\n(.*?)(?=^\S|\Z)', manifest,
flags=re.MULTILINE | re.DOTALL)
if not match:
return set()
return set(re.findall(r'^ ([\w]+):', match.group(1), re.MULTILINE))
def check(root):
errors = []
def reject(source, message):
errors.append(f'{source.relative_to(root)}: {message}')
for package, allowed in RUNTIME.items():
directory = root / 'packages' / package
manifest_path = directory / 'pubspec.yaml'
manifest = manifest_path.read_text(encoding='utf-8')
dependencies = dependency_names(manifest, 'dependencies')
dev_dependencies = dependency_names(manifest, 'dev_dependencies')
for dependency in sorted(dependencies - allowed):
reject(manifest_path, f'forbidden dependency {dependency}')
for dependency in sorted(dev_dependencies - DEVELOPMENT[package]):
reject(manifest_path, f'forbidden dev_dependency {dependency}')
for key, value in [('name', package), ('resolution', 'workspace'), ('publish_to', 'none')]:
if not re.search(rf'^{key}:\s*{value}\s*$', manifest, re.MULTILINE):
reject(manifest_path, f'expected {key}: {value}')
for area in ['lib', 'test', 'tool']:
declared = dependencies | {package}
if area != 'lib':
declared |= dev_dependencies
for source in (directory / area).rglob('*.dart'):
for kind, uri in directives(source.read_text(encoding='utf-8')):
if uri.startswith('package:'):
dependency, path = package_uri(uri)
if dependency not in declared:
reject(source, f'undeclared {kind} {uri}')
if dependency != package and (path == 'src' or path.startswith('src/')):
reject(source, f'private {kind} {uri}')
elif not uri.startswith('dart:'):
target = (source.parent / uri).resolve()
boundary = directory / ('lib' if area == 'lib' else '')
if not target.is_relative_to(boundary.resolve()):
reject(source, f'escaping {kind} {uri}')
for area in ['lib', 'test', 'integration_test', 'test_driver', 'tool']:
for source in (root / area).rglob('*.dart'):
for kind, uri in directives(source.read_text(encoding='utf-8')):
if uri.startswith('package:'):
dependency, path = package_uri(uri)
if dependency != 'cutdex' and (path == 'src' or path.startswith('src/')):
reject(source, f'private {kind} {uri}')
elif not uri.startswith('dart:'):
target = (source.parent / uri).resolve()
boundary = root / ('lib' if area == 'lib' else '')
if not target.is_relative_to(boundary.resolve()):
reject(source, f'escaping {kind} {uri}')
if any(target.is_relative_to((root / 'packages' / package).resolve())
for package in RUNTIME):
reject(source, f'relative workspace {kind} {uri}')
return errors
def main():
errors = check(ROOT)
if errors:
raise SystemExit('\n'.join(errors))
print('Internal package boundaries: passed')
if __name__ == '__main__':
main()