|
| 1 | +"""Answers the device's GitHub requests (raw files and tree listings) from |
| 2 | +local checkouts instead, so the Apps page shows unpushed changes exactly as |
| 3 | +it would after a push. Everything else goes out to the real network. |
| 4 | +""" |
| 5 | + |
| 6 | +import errno |
| 7 | +import io |
| 8 | +import json |
| 9 | +import os |
| 10 | +import stat |
| 11 | +import subprocess |
| 12 | +from collections.abc import Callable |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | +from urllib.parse import urlsplit |
| 16 | + |
| 17 | +RAW_HOST = "raw.githubusercontent.com" |
| 18 | +API_HOST = "api.github.com" |
| 19 | + |
| 20 | +# Matches the device's own default when settings.txt has no repository_url. |
| 21 | +DEFAULT_REPOSITORY_URL = ( |
| 22 | + "https://raw.githubusercontent.com/MatrixBOX-dev/matrixbox/refs/heads/main/" |
| 23 | +) |
| 24 | + |
| 25 | +# Captured before the path sandbox replaces them, which would otherwise |
| 26 | +# redirect reads of the real checkout into the staged copy. |
| 27 | +_REAL_OPEN = io.open |
| 28 | +_REAL_STAT = os.stat |
| 29 | + |
| 30 | +_SKIPPED_DIRECTORY_NAMES = {"__pycache__"} |
| 31 | + |
| 32 | + |
| 33 | +def repository_identity(repository_url: str) -> tuple[str, str] | None: |
| 34 | + """The (owner, repo) in a raw.githubusercontent.com URL, taken the same |
| 35 | + way the device does: its 2nd and 3rd path segments.""" |
| 36 | + parts = repository_url.replace("https://", "").split("/") |
| 37 | + if len(parts) < 3 or not parts[1] or not parts[2]: |
| 38 | + return None |
| 39 | + |
| 40 | + return parts[1], parts[2] |
| 41 | + |
| 42 | + |
| 43 | +def repository_key(owner: str, repo: str) -> str: |
| 44 | + # GitHub is case-insensitive here, and the device rewrites the owner's |
| 45 | + # case on load, so all comparisons go through this. |
| 46 | + return f"{owner}/{repo}".lower() |
| 47 | + |
| 48 | + |
| 49 | +class LocalResponse: |
| 50 | + """The subset of an `adafruit_requests.Response` the device uses.""" |
| 51 | + |
| 52 | + def __init__(self, status_code: int, content: bytes) -> None: |
| 53 | + self.status_code = status_code |
| 54 | + self.content = content |
| 55 | + |
| 56 | + @property |
| 57 | + def text(self) -> str: |
| 58 | + return self.content.decode("utf-8", errors="replace") |
| 59 | + |
| 60 | + def json(self) -> Any: |
| 61 | + return json.loads(self.content) |
| 62 | + |
| 63 | + def close(self) -> None: |
| 64 | + pass |
| 65 | + |
| 66 | + |
| 67 | +class LocalRepository: |
| 68 | + """One local directory, served the way GitHub would serve it if the |
| 69 | + working tree were committed and pushed.""" |
| 70 | + |
| 71 | + def __init__(self, root: Path) -> None: |
| 72 | + self.root = root.resolve() |
| 73 | + |
| 74 | + def file_paths(self) -> list[str]: |
| 75 | + paths = self._git_file_paths() |
| 76 | + if paths is None: |
| 77 | + paths = self._walked_file_paths() |
| 78 | + |
| 79 | + # Deleted but not yet committed files still show up in git's index. |
| 80 | + return sorted(path for path in set(paths) if self._is_file(path)) |
| 81 | + |
| 82 | + def read(self, path: str) -> bytes | None: |
| 83 | + # Only what a push would publish: no ignored or stray files. |
| 84 | + if path not in self.file_paths(): |
| 85 | + return None |
| 86 | + |
| 87 | + with _REAL_OPEN(self.root / path, "rb") as file: |
| 88 | + return file.read() |
| 89 | + |
| 90 | + def tree(self) -> dict[str, Any]: |
| 91 | + blobs = self.file_paths() |
| 92 | + directories = { |
| 93 | + "/".join(path.split("/")[:depth]) |
| 94 | + for path in blobs |
| 95 | + for depth in range(1, path.count("/") + 1) |
| 96 | + } |
| 97 | + entries = [ |
| 98 | + { |
| 99 | + "path": path, |
| 100 | + "type": "blob", |
| 101 | + "mode": "100644", |
| 102 | + } |
| 103 | + for path in blobs |
| 104 | + ] |
| 105 | + entries += [ |
| 106 | + { |
| 107 | + "path": path, |
| 108 | + "type": "tree", |
| 109 | + "mode": "040000", |
| 110 | + } |
| 111 | + for path in directories |
| 112 | + ] |
| 113 | + entries.sort(key=lambda entry: entry["path"]) |
| 114 | + |
| 115 | + return { |
| 116 | + "sha": "local", |
| 117 | + "truncated": False, |
| 118 | + "tree": entries, |
| 119 | + } |
| 120 | + |
| 121 | + def _git_file_paths(self) -> list[str] | None: |
| 122 | + try: |
| 123 | + result = subprocess.run( |
| 124 | + ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], |
| 125 | + cwd=self.root, |
| 126 | + capture_output=True, |
| 127 | + check=True, |
| 128 | + ) |
| 129 | + except (OSError, subprocess.CalledProcessError): |
| 130 | + return None |
| 131 | + |
| 132 | + return [path for path in result.stdout.decode("utf-8").split("\0") if path] |
| 133 | + |
| 134 | + def _walked_file_paths(self) -> list[str]: |
| 135 | + paths = [] |
| 136 | + for directory, directory_names, file_names in os.walk(self.root): |
| 137 | + directory_names[:] = [ |
| 138 | + name |
| 139 | + for name in directory_names |
| 140 | + if not name.startswith(".") and name not in _SKIPPED_DIRECTORY_NAMES |
| 141 | + ] |
| 142 | + relative_directory = Path(directory).relative_to(self.root) |
| 143 | + for name in file_names: |
| 144 | + if not name.startswith("."): |
| 145 | + paths.append((relative_directory / name).as_posix()) |
| 146 | + |
| 147 | + return paths |
| 148 | + |
| 149 | + def _is_file(self, path: str) -> bool: |
| 150 | + try: |
| 151 | + return stat.S_ISREG(_REAL_STAT(str(self.root / path)).st_mode) |
| 152 | + except OSError: |
| 153 | + return False |
| 154 | + |
| 155 | + |
| 156 | +class GitHubInterceptor: |
| 157 | + """Routes GitHub raw and tree requests to local repositories. |
| 158 | +
|
| 159 | + The main repo is whatever the staged settings.txt's `repository_url` |
| 160 | + names, re-read on every request since the web UI can change it.""" |
| 161 | + |
| 162 | + def __init__( |
| 163 | + self, |
| 164 | + settings_path: Path, |
| 165 | + main_repository: LocalRepository | None, |
| 166 | + mapped_repositories: dict[str, LocalRepository], |
| 167 | + is_online: Callable[[], bool], |
| 168 | + ) -> None: |
| 169 | + self.settings_path = settings_path |
| 170 | + self.main_repository = main_repository |
| 171 | + self.mapped_repositories = mapped_repositories |
| 172 | + self.is_online = is_online |
| 173 | + |
| 174 | + def repository_url(self) -> str: |
| 175 | + try: |
| 176 | + with _REAL_OPEN(self.settings_path) as file: |
| 177 | + url = json.loads(file.read()).get("repository_url") |
| 178 | + except (OSError, ValueError, AttributeError): |
| 179 | + url = None |
| 180 | + |
| 181 | + return url if isinstance(url, str) and url else DEFAULT_REPOSITORY_URL |
| 182 | + |
| 183 | + def respond(self, method: str, url: str) -> LocalResponse | None: |
| 184 | + """A local answer for this request, or None to let it go out to the |
| 185 | + real network.""" |
| 186 | + if method.upper() != "GET": |
| 187 | + return None |
| 188 | + |
| 189 | + parts = urlsplit(url) |
| 190 | + segments = parts.path.lstrip("/").split("/") |
| 191 | + if parts.hostname == RAW_HOST and len(segments) >= 3: |
| 192 | + return self._respond_raw(url, segments) |
| 193 | + |
| 194 | + if ( |
| 195 | + parts.hostname == API_HOST |
| 196 | + and len(segments) >= 6 |
| 197 | + and segments[0] == "repos" |
| 198 | + and segments[3:5] == ["git", "trees"] |
| 199 | + ): |
| 200 | + return self._respond_tree(segments[1], segments[2]) |
| 201 | + |
| 202 | + return None |
| 203 | + |
| 204 | + def _repository_for(self, owner: str, repo: str) -> LocalRepository | None: |
| 205 | + key = repository_key(owner, repo) |
| 206 | + if key in self.mapped_repositories: |
| 207 | + return self.mapped_repositories[key] |
| 208 | + |
| 209 | + main_identity = repository_identity(self.repository_url()) |
| 210 | + if main_identity is not None and key == repository_key(*main_identity): |
| 211 | + return self.main_repository |
| 212 | + |
| 213 | + return None |
| 214 | + |
| 215 | + def _respond_raw(self, url: str, segments: list[str]) -> LocalResponse | None: |
| 216 | + repository = self._repository_for(segments[0], segments[1]) |
| 217 | + if repository is None: |
| 218 | + return None |
| 219 | + |
| 220 | + self._require_online() |
| 221 | + path = self._strip_main_prefix(url) or _strip_ref(segments[2:]) |
| 222 | + content = repository.read(path) if path else None |
| 223 | + if content is None: |
| 224 | + # GitHub's raw host answers a missing file with exactly this body. |
| 225 | + return LocalResponse(404, b"404: Not Found") |
| 226 | + |
| 227 | + return LocalResponse(200, content) |
| 228 | + |
| 229 | + def _respond_tree(self, owner: str, repo: str) -> LocalResponse | None: |
| 230 | + repository = self._repository_for(owner, repo) |
| 231 | + if repository is None: |
| 232 | + return None |
| 233 | + |
| 234 | + self._require_online() |
| 235 | + |
| 236 | + return LocalResponse(200, json.dumps(repository.tree()).encode("utf-8")) |
| 237 | + |
| 238 | + def _strip_main_prefix(self, url: str) -> str | None: |
| 239 | + # Matching repository_url literally is the only way to know where a |
| 240 | + # branch name containing "/" ends. |
| 241 | + prefix = self.repository_url().rstrip("/") + "/" |
| 242 | + |
| 243 | + request_path = url.split("?")[0] |
| 244 | + if request_path.lower().startswith(prefix.lower()): |
| 245 | + return request_path[len(prefix) :] |
| 246 | + |
| 247 | + return None |
| 248 | + |
| 249 | + def _require_online(self) -> None: |
| 250 | + # Same error the socket stub raises, so offline handling is identical. |
| 251 | + if not self.is_online(): |
| 252 | + raise OSError(errno.ENETUNREACH, "Network is unreachable") |
| 253 | + |
| 254 | + def install(self, session_class: type) -> None: |
| 255 | + """Patches `request`, which every get/post/... goes through.""" |
| 256 | + real_request = getattr(session_class, "request") |
| 257 | + |
| 258 | + def request( |
| 259 | + session: object, |
| 260 | + method: str, |
| 261 | + url: str, |
| 262 | + *args: Any, |
| 263 | + **kwargs: Any, |
| 264 | + ) -> object: |
| 265 | + response = self.respond(method, url) |
| 266 | + if response is None: |
| 267 | + return real_request(session, method, url, *args, **kwargs) |
| 268 | + |
| 269 | + return response |
| 270 | + |
| 271 | + setattr(session_class, "request", request) |
| 272 | + |
| 273 | + |
| 274 | +def _strip_ref(segments: list[str]) -> str: |
| 275 | + # refs/heads/<branch>/..., <branch>/... or HEAD/... ; a branch with "/" |
| 276 | + # in it can't be told apart from a directory here. |
| 277 | + if segments[:2] == ["refs", "heads"]: |
| 278 | + segments = segments[2:] |
| 279 | + |
| 280 | + return "/".join(segments[1:]) |
0 commit comments