| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import os |
| 8 |
import re |
| 9 |
import shutil |
| 10 |
import subprocess |
| 11 |
import unicodedata |
| 12 |
from contextlib import contextmanager |
| 13 |
from dataclasses import dataclass |
| 14 |
from pathlib import Path |
| 15 |
from tempfile import TemporaryDirectory |
| 16 |
from typing import TYPE_CHECKING, Literal |
| 17 |
from urllib.parse import urlsplit, urlunsplit |
| 18 |
|
| 19 |
from griffe._internal.exceptions import BuiltinModuleError, GitError |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from collections.abc import Iterator |
| 23 |
|
| 24 |
from griffe._internal.models import Module |
| 25 |
|
| 26 |
|
| 27 |
_WORKTREE_PREFIX = "griffe-worktree-" |
| 28 |
|
| 29 |
|
| 30 |
def _normalize(value: str) -> str: |
| 31 |
value = unicodedata.normalize("NFKC", value) |
| 32 |
value = re.sub(r"[^\w]+", "-", value) |
| 33 |
return re.sub(r"[-\s]+", "-", value).strip("-") |
| 34 |
|
| 35 |
|
| 36 |
def _git(*args: str, check: bool = True) -> str: |
| 37 |
process = subprocess.run( |
| 38 |
["git", *args], |
| 39 |
check=False, |
| 40 |
text=True, |
| 41 |
stdout=subprocess.PIPE, |
| 42 |
stderr=subprocess.STDOUT, |
| 43 |
encoding="utf8", |
| 44 |
) |
| 45 |
if check and process.returncode != 0: |
| 46 |
raise GitError(process.stdout.strip()) |
| 47 |
return process.stdout.strip() |
| 48 |
|
| 49 |
|
| 50 |
def _assert_git_repo(path: str | Path) -> None: |
| 51 |
"""Deprecated. Assert that a directory is a Git repository. |
| 52 |
|
| 53 |
Parameters: |
| 54 |
path: Path to a directory. |
| 55 |
|
| 56 |
Raises: |
| 57 |
OSError: When the directory is not a Git repository. |
| 58 |
""" |
| 59 |
if not shutil.which("git"): |
| 60 |
raise RuntimeError("Could not find git executable. Please install git.") |
| 61 |
try: |
| 62 |
_git("-C", str(path), "rev-parse", "--is-inside-work-tree") |
| 63 |
except GitError as error: |
| 64 |
raise OSError(f"Not a git repository: {path}") from error |
| 65 |
|
| 66 |
|
| 67 |
def _get_latest_tag(repo: str | Path) -> str: |
| 68 |
"""Deprecated. Get latest tag of a Git repository. |
| 69 |
|
| 70 |
Parameters: |
| 71 |
repo: The path to Git repository. |
| 72 |
|
| 73 |
Returns: |
| 74 |
The latest tag. |
| 75 |
""" |
| 76 |
if isinstance(repo, str): |
| 77 |
repo = Path(repo) |
| 78 |
if not repo.is_dir(): |
| 79 |
repo = repo.parent |
| 80 |
try: |
| 81 |
output = _git("tag", "-l", "--sort=-creatordate") |
| 82 |
except GitError as error: |
| 83 |
raise GitError(f"Cannot list Git tags in {repo}: {error or 'no tags'}") from error |
| 84 |
return output.split("\n", 1)[0] |
| 85 |
|
| 86 |
|
| 87 |
def _get_repo_root(repo: str | Path) -> Path: |
| 88 |
"""Deprecated. Get the root of a Git repository. |
| 89 |
|
| 90 |
Parameters: |
| 91 |
repo: The path to a Git repository. |
| 92 |
|
| 93 |
Returns: |
| 94 |
The root of the repository. |
| 95 |
""" |
| 96 |
if isinstance(repo, str): |
| 97 |
repo = Path(repo) |
| 98 |
if not repo.is_dir(): |
| 99 |
repo = repo.parent |
| 100 |
return Path(_git("-C", str(repo), "rev-parse", "--show-toplevel")) |
| 101 |
|
| 102 |
|
| 103 |
@contextmanager |
| 104 |
def _tmp_worktree(repo: str | Path = ".", ref: str = "HEAD") -> Iterator[Path]: |
| 105 |
"""Deprecated. Context manager that checks out the given reference in the given repository to a temporary worktree. |
| 106 |
|
| 107 |
Parameters: |
| 108 |
repo: Path to the repository (i.e. the directory *containing* the `.git` directory) |
| 109 |
ref: A Git reference such as a commit, tag or branch. |
| 110 |
|
| 111 |
Yields: |
| 112 |
The path to the temporary worktree. |
| 113 |
|
| 114 |
Raises: |
| 115 |
OSError: If `repo` is not a valid `.git` repository |
| 116 |
RuntimeError: If the `git` executable is unavailable, or if it cannot create a worktree |
| 117 |
""" |
| 118 |
_assert_git_repo(repo) |
| 119 |
repo_name = Path(repo).resolve().name |
| 120 |
normref = _normalize(ref) |
| 121 |
with TemporaryDirectory(prefix=f"{_WORKTREE_PREFIX}{repo_name}-{normref}-") as tmp_dir: |
| 122 |
location = os.path.join(tmp_dir, normref) |
| 123 |
tmp_branch = f"griffe-{normref}" |
| 124 |
try: |
| 125 |
_git("-C", str(repo), "worktree", "add", "-b", tmp_branch, location, ref) |
| 126 |
except GitError as error: |
| 127 |
raise RuntimeError(f"Could not create git worktree: {error}") from error |
| 128 |
|
| 129 |
try: |
| 130 |
yield Path(location) |
| 131 |
finally: |
| 132 |
_git("-C", str(repo), "worktree", "remove", location, check=False) |
| 133 |
_git("-C", str(repo), "worktree", "prune", check=False) |
| 134 |
_git("-C", str(repo), "branch", "-D", tmp_branch, check=False) |
| 135 |
|
| 136 |
|
| 137 |
def _get_git_remote_url(repo: str | Path = ".") -> str: |
| 138 |
if git_url := os.getenv("GRIFFE_GIT_REMOTE_URL"): |
| 139 |
return git_url |
| 140 |
|
| 141 |
remote = "remote." + os.getenv("GRIFFE_GIT_REMOTE", "origin") + ".url" |
| 142 |
git_url = _git("-C", str(repo), "config", "--default", "", "--get", remote) |
| 143 |
if git_url.startswith("git@"): |
| 144 |
git_url = git_url.replace(":", "/", 1).replace("git@", "https://", 1) |
| 145 |
git_url = git_url.removesuffix(".git") |
| 146 |
|
| 147 |
|
| 148 |
if git_url.startswith(("http://", "https://")): |
| 149 |
|
| 150 |
urlparts = list(urlsplit(git_url)) |
| 151 |
urlparts[1] = urlparts[1].split("@", 1)[-1] |
| 152 |
git_url = urlunsplit(urlparts) |
| 153 |
|
| 154 |
return git_url |
| 155 |
|
| 156 |
|
| 157 |
KnownGitService = Literal["github", "gitlab", "sourcehut", "gitea", "gogs", "forgejo", "codeberg", "radicle"] |
| 158 |
"""Known Git hosting services.""" |
| 159 |
|
| 160 |
_service_re = re.compile(rf"({'|'.join(KnownGitService.__args__)})") |
| 161 |
|
| 162 |
|
| 163 |
def _get_git_known_service(git_remote_url: str) -> KnownGitService | None: |
| 164 |
if service := os.getenv("GRIFFE_GIT_SERVICE"): |
| 165 |
if service not in KnownGitService.__args__: |
| 166 |
return None |
| 167 |
return service |
| 168 |
if match := _service_re.search(urlsplit(git_remote_url).netloc): |
| 169 |
return match.group(1) |
| 170 |
return None |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
_RADICLE_URL = "https://app.radicle.at/nodes/seed.radicle.at" |
| 182 |
|
| 183 |
|
| 184 |
def _get_radicle_url(url_or_rid: str, commit_hash: str, filepath: str, lineno: int, endlineno: int) -> str: |
| 185 |
|
| 186 |
url = f"{_RADICLE_URL}/{url_or_rid.replace('//', '')}" if url_or_rid.startswith("rad://") else url_or_rid |
| 187 |
return f"{url}/tree/{commit_hash}/{filepath}#L{lineno}" |
| 188 |
|
| 189 |
|
| 190 |
_service_to_url = { |
| 191 |
"github": lambda url, ch, fp, ln, eln: f"{url}/blob/{ch}/{fp}#L{ln}-L{eln}", |
| 192 |
"gitlab": lambda url, ch, fp, ln, eln: f"{url}/-/blob/{ch}/{fp}#L{ln}-L{eln}", |
| 193 |
|
| 194 |
"sourcehut": lambda url, ch, fp, ln, eln: f"{url}/tree/{ch}/{fp}#L{ln}", |
| 195 |
|
| 196 |
"gogs": lambda url, ch, fp, ln, eln: f"{url}/blob/{ch}/{fp}#L{ln}-L{eln}", |
| 197 |
"gitea": lambda url, ch, fp, ln, eln: f"{url}/src/commit/{ch}/{fp}#L{ln}-L{eln}", |
| 198 |
"codeberg": lambda url, ch, fp, ln, eln: f"{url}/src/commit/{ch}/{fp}#L{ln}-L{eln}", |
| 199 |
"forgejo": lambda url, ch, fp, ln, eln: f"{url}/src/commit/{ch}/{fp}#L{ln}-L{eln}", |
| 200 |
"radicle": _get_radicle_url, |
| 201 |
} |
| 202 |
|
| 203 |
|
| 204 |
def _get_source_link( |
| 205 |
service: KnownGitService, |
| 206 |
remote_url: str, |
| 207 |
commit_hash: str, |
| 208 |
filepath: str | Path, |
| 209 |
lineno: int, |
| 210 |
endlineno: int, |
| 211 |
) -> str | None: |
| 212 |
if isinstance(filepath, Path): |
| 213 |
filepath = filepath.as_posix() |
| 214 |
return _service_to_url[service](remote_url, commit_hash, filepath, lineno, endlineno) |
| 215 |
|
| 216 |
|
| 217 |
def _get_git_commit_hash(repo: str | Path = ".") -> str: |
| 218 |
if commit_hash := os.getenv("GRIFFE_GIT_COMMIT_HASH"): |
| 219 |
return commit_hash |
| 220 |
return _git("-C", str(repo), "rev-parse", "HEAD") |
| 221 |
|
| 222 |
|
| 223 |
def _is_tracked(filepath: str | Path, repo: str | Path = ".") -> bool: |
| 224 |
return not _git("-C", str(repo), "check-ignore", str(filepath), check=False) |
| 225 |
|
| 226 |
|
| 227 |
@dataclass |
| 228 |
class GitInfo: |
| 229 |
"""Information about a Git repository.""" |
| 230 |
|
| 231 |
repository: Path |
| 232 |
"""The path to the Git repository.""" |
| 233 |
service: KnownGitService |
| 234 |
"""The Git hosting service (used to build the right URLs).""" |
| 235 |
remote_url: str |
| 236 |
"""The remote URL of the Git repository.""" |
| 237 |
commit_hash: str |
| 238 |
"""A commit hash (usually the current checked-out one).""" |
| 239 |
|
| 240 |
@classmethod |
| 241 |
def from_package(cls, package: Module) -> GitInfo | None: |
| 242 |
"""Create a GitInfo instance from a Griffe package. |
| 243 |
|
| 244 |
Returns: |
| 245 |
The GitInfo instance, or None if unknown. |
| 246 |
""" |
| 247 |
try: |
| 248 |
path = package.filepath[0] if isinstance(package.filepath, list) else package.filepath |
| 249 |
except BuiltinModuleError: |
| 250 |
return None |
| 251 |
try: |
| 252 |
repo = _get_repo_root(path) |
| 253 |
if not _is_tracked(path.relative_to(repo), repo): |
| 254 |
return None |
| 255 |
remote_url = _get_git_remote_url(repo) |
| 256 |
if not (service := _get_git_known_service(remote_url)): |
| 257 |
return None |
| 258 |
commit_hash = _get_git_commit_hash(repo) |
| 259 |
except (GitError, ValueError, OSError): |
| 260 |
|
| 261 |
|
| 262 |
return None |
| 263 |
return cls(repository=repo, service=service, remote_url=remote_url, commit_hash=commit_hash) |
| 264 |
|
| 265 |
def get_source_link(self, filepath: str | Path, lineno: int, endlineno: int) -> str | None: |
| 266 |
"""Get the source link for the file at the given line numbers. |
| 267 |
|
| 268 |
Returns: |
| 269 |
The source link, or None if unknown. |
| 270 |
""" |
| 271 |
return _get_source_link(self.service, self.remote_url, self.commit_hash, filepath, lineno, endlineno) |