"""Use Git's own ignore implementation, including nested rules and negation.""" import os from pathlib import Path import subprocess EXCLUDE = {'.git', '.gradle', '.idea', '.remotecompile', '.kotlin', 'build', 'node_modules', '.cxx', '.externalnativebuild', '__pycache__'} def reserved(name): parts = name.lower().split('/') leaf = parts[-1] return any(p in EXCLUDE for p in parts) or leaf == 'local.properties' or leaf.startswith('.env') or leaf.endswith(('.jks', '.keystore')) or leaf in ('key.properties', 'keystore.properties') def git(root, *args, data=None): return subprocess.run(['git', '-C', str(root), *args], input=data, capture_output=True, timeout=60) def git_snapshot(root): try: repo = git(root, 'rev-parse', '--is-inside-work-tree') except FileNotFoundError: return None if repo.returncode or repo.stdout.strip() != b'true': return None def read(*args): result = git(root, *args) return result.stdout.decode('utf-8').strip() if result.returncode == 0 else '' status = git(root, 'status', '--porcelain', '--untracked-files=normal') if status.returncode: raise RuntimeError('Cannot read local Git status') return dict(head=read('rev-parse', '--verify', 'HEAD'), branch=read('symbolic-ref', '--short', '-q', 'HEAD'), dirty=bool(status.stdout), upstream=read('rev-parse', '--abbrev-ref', '@{upstream}'), aheadBehind=read('rev-list', '--left-right', '--count', 'HEAD...@{upstream}')) def collect(root: Path, snapshot): if snapshot is not None: listing = git(root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard') if listing.returncode: raise RuntimeError('Cannot list Git source files') names = [p for p in dict.fromkeys(listing.stdout.decode('utf-8').split('\0')) if p and not reserved(p)] ignored = git(root, 'check-ignore', '--no-index', '-z', '--stdin', data=('\0'.join(names)+'\0').encode('utf-8')) if names else None if ignored is not None and ignored.returncode not in (0, 1): raise RuntimeError('Git ignore check failed; sync stopped') skipped = set(ignored.stdout.decode('utf-8').split('\0')) if ignored else set() paths = [root / p for p in names if p not in skipped and os.path.lexists(root / p)] else: paths = [] for directory, dirs, names in os.walk(root, followlinks=False): dirs[:] = [d for d in dirs if not reserved((Path(directory)/d).relative_to(root).as_posix())] for d in dirs: if (Path(directory)/d).is_symlink(): raise RuntimeError('Directory symlinks unsupported') paths.extend(Path(directory)/n for n in names if not reserved((Path(directory)/n).relative_to(root).as_posix())) if any(p.name == '.gitignore' for p in paths): raise RuntimeError('.gitignore found without a readable Git working tree; sync stopped') for path in paths: if path.is_symlink() or not path.is_file(): raise RuntimeError(f'Symlinks, submodules and nested repositories unsupported: {path}') return paths def text_hash(name, content): import hashlib leaf = Path(name).name.lower() extensions = {'.kt', '.kts', '.java', '.xml', '.gradle', '.properties', '.json', '.toml', '.yaml', '.yml', '.txt', '.md', '.proto', '.c', '.cc', '.cpp', '.h', '.hpp', '.cmake', '.aidl', '.pro', '.cfg', '.ini', '.csv', '.html', '.css', '.js', '.ts', '.svg'} if Path(leaf).suffix not in extensions and leaf not in {'.gitignore', '.gitattributes', '.editorconfig', 'cmakelists.txt'}: return None if b'\0' in content: return None try: content.decode('utf-8') except UnicodeDecodeError: return None return hashlib.sha256(content.replace(b'\r\n', b'\n')).hexdigest()