|
| 1 | +"""GitHub source parsing and git-based ralph fetching. |
| 2 | +
|
| 3 | +Parses ``owner/repo``, ``owner/repo/ralph-name``, and full GitHub URLs |
| 4 | +into a normalised form, then clones the repo (shallow) and extracts the |
| 5 | +requested ralph directory. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import re |
| 11 | +import shutil |
| 12 | +import subprocess |
| 13 | +import tempfile |
| 14 | +from dataclasses import dataclass |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +from ralphify._frontmatter import RALPH_MARKER |
| 18 | + |
| 19 | + |
| 20 | +@dataclass(frozen=True) |
| 21 | +class ParsedSource: |
| 22 | + """Normalised representation of a GitHub ralph source.""" |
| 23 | + |
| 24 | + repo_url: str |
| 25 | + """Clone URL, e.g. ``https://github.com/owner/repo.git``.""" |
| 26 | + |
| 27 | + subpath: str | None |
| 28 | + """Path segment(s) after ``owner/repo``, or *None* for repo-root.""" |
| 29 | + |
| 30 | + handle: str |
| 31 | + """Canonical short-form, e.g. ``owner/repo/ralph-name``.""" |
| 32 | + |
| 33 | + name: str |
| 34 | + """Derived ralph name (leaf directory or repo name).""" |
| 35 | + |
| 36 | + |
| 37 | +# --------------------------------------------------------------------------- |
| 38 | +# GitHub URL helpers |
| 39 | +# --------------------------------------------------------------------------- |
| 40 | + |
| 41 | +_GITHUB_URL_RE = re.compile( |
| 42 | + r"^https?://github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+?)(?:\.git)?(?:/tree/[^/]+(?:/(?P<path>.+))?)?/?$" |
| 43 | +) |
| 44 | + |
| 45 | +_SHORTHAND_RE = re.compile(r"^(?P<owner>[^/]+)/(?P<repo>[^/]+)(?:/(?P<rest>.+))?$") |
| 46 | + |
| 47 | + |
| 48 | +def parse_github_source(source: str) -> ParsedSource: |
| 49 | + """Parse a GitHub source string into a :class:`ParsedSource`. |
| 50 | +
|
| 51 | + Accepted formats:: |
| 52 | +
|
| 53 | + owner/repo |
| 54 | + owner/repo/ralph-name |
| 55 | + owner/repo/some/path/to/ralph |
| 56 | + https://github.com/owner/repo |
| 57 | + https://github.com/owner/repo/tree/main/path |
| 58 | +
|
| 59 | + Raises ``ValueError`` for unrecognised formats. |
| 60 | + """ |
| 61 | + owner: str | None = None |
| 62 | + repo: str | None = None |
| 63 | + rest: str | None = None |
| 64 | + |
| 65 | + # Try full URL first. |
| 66 | + m = _GITHUB_URL_RE.match(source) |
| 67 | + if m: |
| 68 | + owner, repo, rest = m.group("owner"), m.group("repo"), m.group("path") |
| 69 | + else: |
| 70 | + m = _SHORTHAND_RE.match(source) |
| 71 | + if m: |
| 72 | + owner, repo, rest = m.group("owner"), m.group("repo"), m.group("rest") |
| 73 | + |
| 74 | + if not owner or not repo: |
| 75 | + raise ValueError( |
| 76 | + f"Cannot parse source '{source}'. " |
| 77 | + "Expected owner/repo, owner/repo/ralph-name, or a GitHub URL." |
| 78 | + ) |
| 79 | + |
| 80 | + repo_url = f"https://github.com/{owner}/{repo}.git" |
| 81 | + subpath = rest.strip("/") if rest else None |
| 82 | + name = subpath.rstrip("/").rsplit("/", 1)[-1] if subpath else repo |
| 83 | + handle = f"{owner}/{repo}/{subpath}" if subpath else f"{owner}/{repo}" |
| 84 | + |
| 85 | + return ParsedSource(repo_url=repo_url, subpath=subpath, handle=handle, name=name) |
| 86 | + |
| 87 | + |
| 88 | +# --------------------------------------------------------------------------- |
| 89 | +# Git clone + ralph extraction |
| 90 | +# --------------------------------------------------------------------------- |
| 91 | + |
| 92 | + |
| 93 | +def _find_ralphs_in(root: Path) -> list[Path]: |
| 94 | + """Return all directories under *root* that contain a RALPH.md.""" |
| 95 | + return sorted( |
| 96 | + p.parent for p in root.rglob(RALPH_MARKER) if p.is_file() |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +def _shallow_clone(repo_url: str, dest: Path) -> None: |
| 101 | + """Run ``git clone --depth 1`` into *dest*. |
| 102 | +
|
| 103 | + Raises ``RuntimeError`` on failure. |
| 104 | + """ |
| 105 | + try: |
| 106 | + subprocess.run( |
| 107 | + ["git", "clone", "--depth", "1", repo_url, str(dest)], |
| 108 | + capture_output=True, |
| 109 | + text=True, |
| 110 | + check=True, |
| 111 | + ) |
| 112 | + except FileNotFoundError: |
| 113 | + raise RuntimeError( |
| 114 | + "git is required for 'ralph add'. Install it from https://git-scm.com/" |
| 115 | + ) from None |
| 116 | + except subprocess.CalledProcessError as exc: |
| 117 | + stderr = exc.stderr.strip() if exc.stderr else "unknown error" |
| 118 | + raise RuntimeError(f"git clone failed: {stderr}") from None |
| 119 | + |
| 120 | + |
| 121 | +@dataclass(frozen=True) |
| 122 | +class FetchResult: |
| 123 | + """Result of fetching ralph(s) from a source.""" |
| 124 | + |
| 125 | + installed: list[tuple[str, Path]] |
| 126 | + """List of ``(name, dest_path)`` for each installed ralph.""" |
| 127 | + |
| 128 | + |
| 129 | +def fetch_ralphs(parsed: ParsedSource, ralphs_dir: Path) -> FetchResult: |
| 130 | + """Clone the repo and extract ralph(s) to *ralphs_dir*. |
| 131 | +
|
| 132 | + *ralphs_dir* is the ``.ralphify/ralphs/`` directory. Each ralph is |
| 133 | + placed in ``ralphs_dir/<name>/``. |
| 134 | +
|
| 135 | + Returns a :class:`FetchResult` describing what was installed. |
| 136 | + Raises ``RuntimeError`` on any failure. |
| 137 | + """ |
| 138 | + with tempfile.TemporaryDirectory() as tmp: |
| 139 | + clone_dir = Path(tmp) / "repo" |
| 140 | + _shallow_clone(parsed.repo_url, clone_dir) |
| 141 | + |
| 142 | + if parsed.subpath is None: |
| 143 | + # owner/repo — check if root is a ralph, else install all. |
| 144 | + return _fetch_repo_ralphs(clone_dir, parsed, ralphs_dir) |
| 145 | + else: |
| 146 | + # owner/repo/ralph-name — search for the ralph. |
| 147 | + return _fetch_named_ralph(clone_dir, parsed, ralphs_dir) |
| 148 | + |
| 149 | + |
| 150 | +def _fetch_repo_ralphs( |
| 151 | + clone_dir: Path, parsed: ParsedSource, ralphs_dir: Path, |
| 152 | +) -> FetchResult: |
| 153 | + """Handle ``owner/repo`` — repo root is a ralph, or install all.""" |
| 154 | + root_ralph = clone_dir / RALPH_MARKER |
| 155 | + if root_ralph.is_file(): |
| 156 | + dest = ralphs_dir / parsed.name |
| 157 | + _copy_ralph(clone_dir, dest) |
| 158 | + return FetchResult(installed=[(parsed.name, dest)]) |
| 159 | + |
| 160 | + # Scan for all ralphs in the repo. |
| 161 | + ralph_dirs = _find_ralphs_in(clone_dir) |
| 162 | + if not ralph_dirs: |
| 163 | + raise RuntimeError( |
| 164 | + f"No {RALPH_MARKER} found in {parsed.handle}." |
| 165 | + ) |
| 166 | + |
| 167 | + installed: list[tuple[str, Path]] = [] |
| 168 | + for rd in ralph_dirs: |
| 169 | + name = rd.name |
| 170 | + dest = ralphs_dir / name |
| 171 | + _copy_ralph(rd, dest) |
| 172 | + installed.append((name, dest)) |
| 173 | + return FetchResult(installed=installed) |
| 174 | + |
| 175 | + |
| 176 | +def _fetch_named_ralph( |
| 177 | + clone_dir: Path, parsed: ParsedSource, ralphs_dir: Path, |
| 178 | +) -> FetchResult: |
| 179 | + """Handle ``owner/repo/ralph-name`` — search or exact subpath.""" |
| 180 | + assert parsed.subpath is not None |
| 181 | + |
| 182 | + # First try exact subpath. |
| 183 | + exact = clone_dir / parsed.subpath |
| 184 | + if exact.is_dir() and (exact / RALPH_MARKER).is_file(): |
| 185 | + dest = ralphs_dir / parsed.name |
| 186 | + _copy_ralph(exact, dest) |
| 187 | + return FetchResult(installed=[(parsed.name, dest)]) |
| 188 | + |
| 189 | + # Search by name (leaf segment). |
| 190 | + ralph_name = parsed.name |
| 191 | + all_ralphs = _find_ralphs_in(clone_dir) |
| 192 | + matches = [rd for rd in all_ralphs if rd.name == ralph_name] |
| 193 | + |
| 194 | + if len(matches) == 1: |
| 195 | + dest = ralphs_dir / ralph_name |
| 196 | + _copy_ralph(matches[0], dest) |
| 197 | + return FetchResult(installed=[(ralph_name, dest)]) |
| 198 | + |
| 199 | + if len(matches) > 1: |
| 200 | + paths = "\n".join( |
| 201 | + f" - {m.relative_to(clone_dir)}/{RALPH_MARKER}" for m in matches |
| 202 | + ) |
| 203 | + owner_repo = "/".join(parsed.handle.split("/")[:2]) |
| 204 | + raise RuntimeError( |
| 205 | + f"Found multiple ralphs named '{ralph_name}' in {owner_repo}:\n" |
| 206 | + f"{paths}\n\n" |
| 207 | + f"Use the full path to disambiguate, e.g.:\n" |
| 208 | + f" ralph add {owner_repo}/{matches[0].relative_to(clone_dir)}" |
| 209 | + ) |
| 210 | + |
| 211 | + raise RuntimeError( |
| 212 | + f"No ralph named '{ralph_name}' found in {parsed.handle}." |
| 213 | + ) |
| 214 | + |
| 215 | + |
| 216 | +def _copy_ralph(src: Path, dest: Path) -> None: |
| 217 | + """Copy a ralph directory to *dest*, overwriting if it exists.""" |
| 218 | + if dest.exists(): |
| 219 | + shutil.rmtree(dest) |
| 220 | + shutil.copytree(src, dest, ignore=shutil.ignore_patterns(".git")) |
0 commit comments