|
| 1 | +# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: The Coding Guidelines Subcommittee Contributors |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import hashlib |
| 7 | +import os |
| 8 | +import platform |
| 9 | +import shutil |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +import tarfile |
| 13 | +import tempfile |
| 14 | +import zipfile |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +import requests |
| 18 | + |
| 19 | +DELTA_VERSION = "0.18.2" |
| 20 | +DELTA_RELEASE_BASE = ( |
| 21 | + f"https://github.com/dandavison/delta/releases/download/{DELTA_VERSION}" |
| 22 | +) |
| 23 | + |
| 24 | +DELTA_ASSETS: dict[str, dict[str, str]] = { |
| 25 | + "x86_64-unknown-linux-gnu": { |
| 26 | + "filename": f"delta-{DELTA_VERSION}-x86_64-unknown-linux-gnu.tar.gz", |
| 27 | + "sha256": "99607c43238e11a77fe90a914d8c2d64961aff84b60b8186c1b5691b39955b0f", |
| 28 | + "binary": "delta", |
| 29 | + }, |
| 30 | + "aarch64-unknown-linux-gnu": { |
| 31 | + "filename": f"delta-{DELTA_VERSION}-aarch64-unknown-linux-gnu.tar.gz", |
| 32 | + "sha256": "adf7674086daa4582f598f74ce9caa6b70c1ba8f4a57d2911499b37826b014f9", |
| 33 | + "binary": "delta", |
| 34 | + }, |
| 35 | + "aarch64-apple-darwin": { |
| 36 | + "filename": f"delta-{DELTA_VERSION}-aarch64-apple-darwin.tar.gz", |
| 37 | + "sha256": "6ba38dce9f91ee1b9a24aa4aede1db7195258fe176c3f8276ae2d4457d8170a0", |
| 38 | + "binary": "delta", |
| 39 | + }, |
| 40 | + "x86_64-pc-windows-msvc": { |
| 41 | + "filename": f"delta-{DELTA_VERSION}-x86_64-pc-windows-msvc.zip", |
| 42 | + "sha256": "6ea59864091b4cfca89d9ee38388ff1a3ccdc8244b6e1cdd5201259de89b0b06", |
| 43 | + "binary": "delta.exe", |
| 44 | + }, |
| 45 | +} |
| 46 | + |
| 47 | +DELTA_ARGS = [ |
| 48 | + "--color-only", |
| 49 | + "--paging=never", |
| 50 | + "--side-by-side", |
| 51 | + "--line-numbers", |
| 52 | + "--file-style", |
| 53 | + "bold yellow ul", |
| 54 | + "--file-decoration-style", |
| 55 | + "none", |
| 56 | + "--hunk-header-decoration-style", |
| 57 | + "none", |
| 58 | + "--max-line-length", |
| 59 | + "0", |
| 60 | + "--wrap-max-lines", |
| 61 | + "0", |
| 62 | + "--whitespace-error-style", |
| 63 | + "red reverse", |
| 64 | +] |
| 65 | + |
| 66 | + |
| 67 | +def detect_target() -> str | None: |
| 68 | + system = sys.platform |
| 69 | + machine = platform.machine().lower() |
| 70 | + if system.startswith("linux"): |
| 71 | + if machine in ("x86_64", "amd64"): |
| 72 | + return "x86_64-unknown-linux-gnu" |
| 73 | + if machine in ("aarch64", "arm64"): |
| 74 | + return "aarch64-unknown-linux-gnu" |
| 75 | + if system == "darwin": |
| 76 | + if machine in ("aarch64", "arm64"): |
| 77 | + return "aarch64-apple-darwin" |
| 78 | + if system == "win32": |
| 79 | + if machine in ("x86_64", "amd64"): |
| 80 | + return "x86_64-pc-windows-msvc" |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +def resolve_delta_binary( |
| 85 | + cache_dir: Path, |
| 86 | + session: requests.Session, |
| 87 | + delta_path: Path | None, |
| 88 | + disable_delta: bool, |
| 89 | +) -> tuple[Path | None, str | None]: |
| 90 | + if disable_delta: |
| 91 | + return None, None |
| 92 | + |
| 93 | + if delta_path: |
| 94 | + resolved = delta_path |
| 95 | + if not resolved.is_absolute(): |
| 96 | + resolved = Path.cwd() / resolved |
| 97 | + if not resolved.exists(): |
| 98 | + raise RuntimeError(f"delta binary not found at {resolved}") |
| 99 | + if not resolved.is_file(): |
| 100 | + raise RuntimeError(f"delta path is not a file: {resolved}") |
| 101 | + return resolved, None |
| 102 | + |
| 103 | + warning = None |
| 104 | + target = detect_target() |
| 105 | + if target: |
| 106 | + try: |
| 107 | + return install_delta(cache_dir, session, target), None |
| 108 | + except RuntimeError as exc: |
| 109 | + warning = str(exc) |
| 110 | + else: |
| 111 | + warning = f"delta not available for platform {sys.platform} {platform.machine()}" |
| 112 | + |
| 113 | + system_delta = shutil.which("delta") |
| 114 | + if system_delta: |
| 115 | + return Path(system_delta), warning |
| 116 | + |
| 117 | + return None, warning |
| 118 | + |
| 119 | + |
| 120 | +def install_delta(cache_dir: Path, session: requests.Session, target: str) -> Path: |
| 121 | + info = DELTA_ASSETS.get(target) |
| 122 | + if not info: |
| 123 | + raise RuntimeError(f"delta target {target} is not supported") |
| 124 | + |
| 125 | + install_dir = cache_dir / "tools" / "delta" / DELTA_VERSION / target |
| 126 | + binary_path = install_dir / info["binary"] |
| 127 | + if binary_path.exists(): |
| 128 | + return binary_path |
| 129 | + |
| 130 | + install_dir.mkdir(parents=True, exist_ok=True) |
| 131 | + archive_path = install_dir / info["filename"] |
| 132 | + if archive_path.exists() and not verify_sha256(archive_path, info["sha256"]): |
| 133 | + archive_path.unlink() |
| 134 | + |
| 135 | + if not archive_path.exists(): |
| 136 | + url = f"{DELTA_RELEASE_BASE}/{info['filename']}" |
| 137 | + download_asset(session, url, archive_path) |
| 138 | + |
| 139 | + if not verify_sha256(archive_path, info["sha256"]): |
| 140 | + raise RuntimeError(f"delta checksum mismatch for {archive_path.name}") |
| 141 | + |
| 142 | + with tempfile.TemporaryDirectory(dir=install_dir) as temp_dir: |
| 143 | + temp_path = Path(temp_dir) |
| 144 | + extract_archive(archive_path, temp_path) |
| 145 | + extracted = find_binary(temp_path, info["binary"]) |
| 146 | + shutil.copy2(extracted, binary_path) |
| 147 | + |
| 148 | + if os.name != "nt": |
| 149 | + binary_path.chmod(binary_path.stat().st_mode | 0o111) |
| 150 | + |
| 151 | + return binary_path |
| 152 | + |
| 153 | + |
| 154 | +def download_asset(session: requests.Session, url: str, dest: Path) -> None: |
| 155 | + dest.parent.mkdir(parents=True, exist_ok=True) |
| 156 | + with session.get(url, stream=True, timeout=60) as response: |
| 157 | + response.raise_for_status() |
| 158 | + with tempfile.NamedTemporaryFile(dir=dest.parent, delete=False) as temp_file: |
| 159 | + for chunk in response.iter_content(chunk_size=1024 * 1024): |
| 160 | + if chunk: |
| 161 | + temp_file.write(chunk) |
| 162 | + temp_path = Path(temp_file.name) |
| 163 | + temp_path.replace(dest) |
| 164 | + |
| 165 | + |
| 166 | +def verify_sha256(path: Path, expected: str) -> bool: |
| 167 | + digest = hashlib.sha256() |
| 168 | + with path.open("rb") as handle: |
| 169 | + for chunk in iter(lambda: handle.read(1024 * 1024), b""): |
| 170 | + digest.update(chunk) |
| 171 | + return digest.hexdigest() == expected |
| 172 | + |
| 173 | + |
| 174 | +def extract_archive(archive_path: Path, dest_dir: Path) -> None: |
| 175 | + if archive_path.name.endswith(".tar.gz"): |
| 176 | + with tarfile.open(archive_path, "r:gz") as archive: |
| 177 | + safe_extract_tar(archive, dest_dir) |
| 178 | + return |
| 179 | + if archive_path.suffix == ".zip": |
| 180 | + with zipfile.ZipFile(archive_path, "r") as archive: |
| 181 | + safe_extract_zip(archive, dest_dir) |
| 182 | + return |
| 183 | + raise RuntimeError(f"Unsupported delta archive {archive_path.name}") |
| 184 | + |
| 185 | + |
| 186 | +def safe_extract_tar(archive: tarfile.TarFile, dest_dir: Path) -> None: |
| 187 | + for member in archive.getmembers(): |
| 188 | + member_path = dest_dir / member.name |
| 189 | + if not is_within_directory(dest_dir, member_path): |
| 190 | + raise RuntimeError("Blocked tar extraction outside destination") |
| 191 | + archive.extractall(dest_dir) |
| 192 | + |
| 193 | + |
| 194 | +def safe_extract_zip(archive: zipfile.ZipFile, dest_dir: Path) -> None: |
| 195 | + for member in archive.infolist(): |
| 196 | + member_path = dest_dir / member.filename |
| 197 | + if not is_within_directory(dest_dir, member_path): |
| 198 | + raise RuntimeError("Blocked zip extraction outside destination") |
| 199 | + archive.extractall(dest_dir) |
| 200 | + |
| 201 | + |
| 202 | +def is_within_directory(directory: Path, target: Path) -> bool: |
| 203 | + directory_resolved = directory.resolve() |
| 204 | + target_resolved = target.resolve(strict=False) |
| 205 | + if target_resolved == directory_resolved: |
| 206 | + return True |
| 207 | + return str(target_resolved).startswith(str(directory_resolved) + os.sep) |
| 208 | + |
| 209 | + |
| 210 | +def find_binary(root: Path, binary_name: str) -> Path: |
| 211 | + matches = list(root.rglob(binary_name)) |
| 212 | + if not matches: |
| 213 | + raise RuntimeError(f"delta binary {binary_name} not found in archive") |
| 214 | + matches.sort() |
| 215 | + return matches[0] |
| 216 | + |
| 217 | + |
| 218 | +def render_delta_diff(delta_path: Path, diff_lines: list[str]) -> tuple[str | None, str | None]: |
| 219 | + if not diff_lines: |
| 220 | + return None, None |
| 221 | + diff_text = "\n".join(diff_lines) |
| 222 | + if not diff_text.endswith("\n"): |
| 223 | + diff_text += "\n" |
| 224 | + result = subprocess.run( |
| 225 | + [str(delta_path), *DELTA_ARGS], |
| 226 | + input=diff_text, |
| 227 | + text=True, |
| 228 | + capture_output=True, |
| 229 | + check=False, |
| 230 | + ) |
| 231 | + if result.returncode != 0: |
| 232 | + error = result.stderr.strip() or f"delta exited with status {result.returncode}" |
| 233 | + return None, error |
| 234 | + return result.stdout, None |
0 commit comments