"""Select local checks from imports, matching test names and literal paths.""" import argparse, ast, re, subprocess, sys, time from pathlib import Path if __package__: from .reachability import Repository, tests_for else: from reachability import Repository, tests_for class Changes(Repository): def git(self, *args): return super().git(*args[:-1], self.only) if args[0] == 'diff' else super().git(*args) def select(root, base): git = lambda *args: subprocess.check_output(['git', '-C', str(root), *args], text=True).strip() changed = git('diff', '--name-only', f'{base}...HEAD').splitlines() if all(Path(f).suffix == '.md' for f in changed): return [] if any(Path(f).suffix != '.py' for f in changed): raise ValueError('非 Python 改动,运行全量检查') base = git('merge-base', base, 'HEAD') start = time.monotonic(); repo = Changes(root) print(f'建图:{time.monotonic() - start:.3f} s', flush=True) literals = {f: [n.value for n in ast.walk(tree) if isinstance(n, ast.Constant) and isinstance(n.value, str)] for f, tree in repo.trees.items() if Path(f).name.startswith('test_')} selected = set() for f in changed: repo.only = f tests = set(tests_for(repo, base)[0]['tests']) tests.update(t for t, strings in literals.items() if t == f or Path(t).name == f'test_{Path(f).stem}.py' or any(f in s or Path(f).name in s for s in strings)) if not tests: raise ValueError(f'未找到测试:{f}') selected.update(tests) print(f'快检:{len(selected)} 个测试文件,挑自 {len(changed)} 个改动文件', flush=True) return sorted(selected) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('--base', required=True) root = Path(__file__).resolve().parents[2] try: tests = select(root, parser.parse_args(argv).base) except (ValueError, OSError, SyntaxError, subprocess.CalledProcessError) as error: print(f'快检退回全量:{error}', flush=True); return 3 results = [] for f in tests: runner = ['-m', 'unittest', 'discover', '-s', str(Path(f).parent), '-p', Path(f).name, '-v'] if re.search(r'^(import unittest([\s,]|$)|from unittest import)', (root / f).read_text(), re.M) else ['-m', 'pytest', '-q', '-p', 'no:cacheprovider', f] print(f'快检测试:{f}', flush=True) results.append(subprocess.run([sys.executable, '-B', *runner], cwd=root).returncode) return int(any(results)) if __name__ == '__main__': sys.exit(main())