@gnost-cli/darwin-arm64 0.5.3 → 0.6.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/_internal/base_library.zip +0 -0
- package/bundle/_internal/certifi/cacert.pem +3885 -0
- package/bundle/_internal/gnost/__init__.py +1 -1
- package/bundle/_internal/gnost/analysis/analyzers/readability_analyzer.py +4 -1
- package/bundle/_internal/gnost/analysis/utils/tool_command.py +8 -0
- package/bundle/_internal/gnost/changes/__init__.py +1 -0
- package/bundle/_internal/gnost/changes/analyzer.py +215 -0
- package/bundle/_internal/gnost/changes/findings.py +55 -0
- package/bundle/_internal/gnost/changes/impact.py +59 -0
- package/bundle/_internal/gnost/changes/refs.py +105 -0
- package/bundle/_internal/gnost/changes/render.py +172 -0
- package/bundle/_internal/gnost/changes/report.py +124 -0
- package/bundle/_internal/gnost/changes/snapshot.py +109 -0
- package/bundle/_internal/gnost/ci/__init__.py +1 -0
- package/bundle/_internal/gnost/ci/baseline.py +88 -0
- package/bundle/_internal/gnost/ci/exit_codes.py +19 -0
- package/bundle/_internal/gnost/ci/fingerprint.py +44 -0
- package/bundle/_internal/gnost/ci/gate.py +42 -0
- package/bundle/_internal/gnost/ci/paths.py +57 -0
- package/bundle/_internal/gnost/ci/run.py +135 -0
- package/bundle/_internal/gnost/ci/sarif.py +149 -0
- package/bundle/_internal/gnost/ci/scorecard.py +95 -0
- package/bundle/_internal/gnost/cli/app.py +406 -155
- package/bundle/_internal/gnost/cli/commands/changes.py +144 -0
- package/bundle/_internal/gnost/cli/commands/init.py +192 -0
- package/bundle/_internal/gnost/cli/commands/onboard.py +83 -27
- package/bundle/_internal/gnost/cli/commands/remote.py +53 -0
- package/bundle/_internal/gnost/cli/commands/show.py +15 -14
- package/bundle/_internal/gnost/config/languages.py +19 -4
- package/bundle/_internal/gnost/config/settings.py +127 -2
- package/bundle/_internal/gnost/core/flow.py +27 -0
- package/bundle/_internal/gnost/core/insight_builder.py +3 -1
- package/bundle/_internal/gnost/core/risk.py +115 -0
- package/bundle/_internal/gnost/reporters/insights_json.py +65 -1
- package/bundle/_internal/gnost/reporters/loc_summary.py +3 -3
- package/bundle/_internal/gnost/reporters/markdown.py +89 -10
- package/bundle/_internal/gnost/reporters/mermaid.py +7 -0
- package/bundle/_internal/gnost/reporters/readme.py +11 -6
- package/bundle/_internal/gnost/reporters/stats.py +3 -3
- package/bundle/_internal/gnost/reporters/summary.py +48 -1
- package/bundle/_internal/gnost/scanner/filters.py +45 -12
- package/bundle/_internal/gnost/scanner/loc.py +5 -0
- package/bundle/_internal/gnost/schemas/insights.schema.json +153 -0
- package/bundle/_internal/gnost/utils/footer.py +36 -0
- package/bundle/_internal/gnost/utils/integrations.py +346 -0
- package/bundle/_internal/gnost/utils/layout.py +111 -0
- package/bundle/_internal/gnost/utils/progress.py +6 -3
- package/bundle/_internal/gnost/utils/update_check.py +253 -0
- package/bundle/_internal/gnost/vcs/__init__.py +1 -0
- package/bundle/_internal/gnost/vcs/git.py +181 -0
- package/bundle/_internal/gnost/vcs/history.py +404 -0
- package/bundle/_internal/gnost/vcs/remote.py +204 -0
- package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/METADATA +7 -4
- package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/RECORD +88 -30
- package/bundle/_internal/gnost-0.6.0rc1.dist-info/REQUESTED +0 -0
- package/bundle/_internal/yaml/_yaml.cpython-312-darwin.so +0 -0
- package/bundle/gnost +0 -0
- package/package.json +1 -1
- /package/bundle/_internal/{gnost-0.5.3.dist-info/REQUESTED → certifi/py.typed} +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/INSTALLER +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/WHEEL +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/direct_url.json +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/entry_points.txt +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/licenses/LICENSE +0 -0
- /package/bundle/_internal/{gnost-0.5.3.dist-info → gnost-0.6.0rc1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Tells people on a terminal when a newer GNOST release exists (`gnost --version`).
|
|
2
|
+
|
|
3
|
+
`UpdateNotifier` composes a `Version` comparison, an on-disk `UpdateCache`, a `PyPIFeed` and an
|
|
4
|
+
`UpdatePolicy`. Everything is silent on failure and off in CI, scripts and when switched off.
|
|
5
|
+
Its only request goes to pypi.org (never a GNOST server), at most once a day.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
import urllib.request
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, Callable, Dict, Mapping, Optional, TextIO, Tuple
|
|
18
|
+
|
|
19
|
+
PYPI_URL = "https://pypi.org/pypi/gnost/json"
|
|
20
|
+
URL_ENV = "GNOST_UPDATE_CHECK_URL" # tests point this at a local server
|
|
21
|
+
SWITCH_OFF_ENV = "GNOST_NO_UPDATE_CHECK"
|
|
22
|
+
INSTALL_DOCS = "https://gnost.readthedocs.io/en/stable/install.html"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, order=True)
|
|
26
|
+
class Version:
|
|
27
|
+
"""A release number that sorts correctly: 0.10.0 > 0.9.0 and 0.6.0 > 0.6.0rc2 > 0.6.0rc1."""
|
|
28
|
+
|
|
29
|
+
release: Tuple[int, ...]
|
|
30
|
+
stage: int # a < b < rc < final
|
|
31
|
+
number: int
|
|
32
|
+
|
|
33
|
+
_PATTERN = re.compile(r"^(\d+(?:\.\d+)*)(?:(a|b|rc)(\d+))?$")
|
|
34
|
+
_STAGES = {"a": 1, "b": 2, "rc": 3}
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def parse(cls, text: str) -> Optional["Version"]:
|
|
38
|
+
"""The version for text such as 0.6.0 or 0.6.0rc1, or None for any other form."""
|
|
39
|
+
match = cls._PATTERN.match(text.strip())
|
|
40
|
+
if not match:
|
|
41
|
+
return None
|
|
42
|
+
numbers = [int(n) for n in match.group(1).split(".")]
|
|
43
|
+
while len(numbers) > 1 and numbers[-1] == 0:
|
|
44
|
+
numbers.pop()
|
|
45
|
+
return cls(
|
|
46
|
+
tuple(numbers),
|
|
47
|
+
cls._STAGES.get(match.group(2) or "", 4),
|
|
48
|
+
int(match.group(3) or 0),
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def is_newer_than(self, other: "Version") -> bool:
|
|
52
|
+
"""Whether this release comes after other."""
|
|
53
|
+
return self > other
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class UpdateCache:
|
|
57
|
+
"""Remembers the last answer (a day) and the last failure (six hours) in a small JSON file."""
|
|
58
|
+
|
|
59
|
+
FRESH_FOR = 24 * 3600
|
|
60
|
+
RETRY_AFTER_FAILURE = 6 * 3600
|
|
61
|
+
|
|
62
|
+
def __init__(self, path: str) -> None:
|
|
63
|
+
self.path = path
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def in_home(cls, home: Optional[str] = None) -> "UpdateCache":
|
|
67
|
+
"""The cache in ~/.gnost (or in `home`)."""
|
|
68
|
+
base = home or os.path.join(os.path.expanduser("~"), ".gnost")
|
|
69
|
+
return cls(os.path.join(base, "update-check.json"))
|
|
70
|
+
|
|
71
|
+
def fresh_latest(self, now: float) -> Optional[str]:
|
|
72
|
+
"""The stored latest version if it was learned less than a day ago."""
|
|
73
|
+
data = self._read()
|
|
74
|
+
latest, when = data.get("latest"), data.get("checked_at")
|
|
75
|
+
if (
|
|
76
|
+
isinstance(latest, str)
|
|
77
|
+
and isinstance(when, (int, float))
|
|
78
|
+
and now - when < self.FRESH_FOR
|
|
79
|
+
):
|
|
80
|
+
return latest
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
def stored_latest(self) -> Optional[str]:
|
|
84
|
+
"""The stored latest version, however old."""
|
|
85
|
+
latest = self._read().get("latest")
|
|
86
|
+
return latest if isinstance(latest, str) else None
|
|
87
|
+
|
|
88
|
+
def recently_failed(self, now: float) -> bool:
|
|
89
|
+
"""True if the last attempt failed less than six hours ago."""
|
|
90
|
+
failed = self._read().get("failed_at")
|
|
91
|
+
return (
|
|
92
|
+
isinstance(failed, (int, float)) and now - failed < self.RETRY_AFTER_FAILURE
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def record_success(self, latest: str, now: float) -> None:
|
|
96
|
+
"""Store a freshly learned latest version."""
|
|
97
|
+
self._write({"latest": latest, "checked_at": now})
|
|
98
|
+
|
|
99
|
+
def record_failure(self, now: float) -> None:
|
|
100
|
+
"""Remember a failed attempt, keeping any older answer."""
|
|
101
|
+
self._write({**self._read(), "failed_at": now})
|
|
102
|
+
|
|
103
|
+
def _read(self) -> Dict[str, Any]:
|
|
104
|
+
"""The stored data, or {} if the file is missing or unreadable."""
|
|
105
|
+
try:
|
|
106
|
+
with open(self.path, encoding="utf-8") as f:
|
|
107
|
+
data = json.load(f)
|
|
108
|
+
return data if isinstance(data, dict) else {}
|
|
109
|
+
except (OSError, ValueError):
|
|
110
|
+
return {}
|
|
111
|
+
|
|
112
|
+
def _write(self, data: Dict[str, Any]) -> None:
|
|
113
|
+
"""Save data; an unwritable cache is not a problem."""
|
|
114
|
+
try:
|
|
115
|
+
os.makedirs(os.path.dirname(self.path), exist_ok=True)
|
|
116
|
+
with open(self.path, "w", encoding="utf-8") as f:
|
|
117
|
+
json.dump(data, f)
|
|
118
|
+
except OSError:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class PyPIFeed:
|
|
123
|
+
"""Asks the package index for the latest non-pre-release version of gnost."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, url: Optional[str] = None, timeout: float = 1.5) -> None:
|
|
126
|
+
self.url = url or os.environ.get(URL_ENV) or PYPI_URL
|
|
127
|
+
self.timeout = timeout
|
|
128
|
+
|
|
129
|
+
def latest(self) -> Optional[str]:
|
|
130
|
+
"""The latest version string; raises on any network or format problem."""
|
|
131
|
+
request = urllib.request.Request(
|
|
132
|
+
self.url, headers={"User-Agent": "gnost-update-check"}
|
|
133
|
+
)
|
|
134
|
+
with urllib.request.urlopen(
|
|
135
|
+
request, timeout=self.timeout, context=self._tls()
|
|
136
|
+
) as response:
|
|
137
|
+
if response.status != 200:
|
|
138
|
+
return None
|
|
139
|
+
version = json.load(response).get("info", {}).get("version")
|
|
140
|
+
return version if isinstance(version, str) else None
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _tls() -> Any:
|
|
144
|
+
"""A TLS context with certifi's certificates when available (frozen builds need them)."""
|
|
145
|
+
try:
|
|
146
|
+
import ssl
|
|
147
|
+
|
|
148
|
+
import certifi
|
|
149
|
+
|
|
150
|
+
return ssl.create_default_context(cafile=certifi.where())
|
|
151
|
+
except Exception:
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class UpdatePolicy:
|
|
156
|
+
"""Decides whether the check may run: terminal only, never in CI, and not switched off."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, env: Mapping[str, str], config_allows: bool = True) -> None:
|
|
159
|
+
self.env = env
|
|
160
|
+
self.config_allows = config_allows
|
|
161
|
+
|
|
162
|
+
def allows(self, stream: TextIO) -> bool:
|
|
163
|
+
"""True if a notice may be shown on this stream."""
|
|
164
|
+
if not self.config_allows or self.env.get(SWITCH_OFF_ENV, "").strip() not in (
|
|
165
|
+
"",
|
|
166
|
+
"0",
|
|
167
|
+
):
|
|
168
|
+
return False
|
|
169
|
+
if self.env.get("CI", "").strip() not in ("", "0", "false", "False"):
|
|
170
|
+
return False
|
|
171
|
+
try:
|
|
172
|
+
return bool(stream.isatty())
|
|
173
|
+
except Exception:
|
|
174
|
+
return False
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class UpdateNotifier:
|
|
178
|
+
"""Prints one line on a terminal when a newer release exists; silent on any failure."""
|
|
179
|
+
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
current: str,
|
|
183
|
+
cache: UpdateCache,
|
|
184
|
+
feed: PyPIFeed,
|
|
185
|
+
policy: UpdatePolicy,
|
|
186
|
+
clock: Callable[[], float] = time.time,
|
|
187
|
+
) -> None:
|
|
188
|
+
self.current = current
|
|
189
|
+
self.cache = cache
|
|
190
|
+
self.feed = feed
|
|
191
|
+
self.policy = policy
|
|
192
|
+
self.clock = clock
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def standard(cls, current: str, config_allows: bool = True) -> "UpdateNotifier":
|
|
196
|
+
"""The notifier used by the command line: real cache, PyPI and environment."""
|
|
197
|
+
return cls(
|
|
198
|
+
current,
|
|
199
|
+
UpdateCache.in_home(),
|
|
200
|
+
PyPIFeed(),
|
|
201
|
+
UpdatePolicy(dict(os.environ), config_allows),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def notify(self, stream: Optional[TextIO] = None) -> bool:
|
|
205
|
+
"""Print the update line to stderr if one is due; returns whether it did."""
|
|
206
|
+
try:
|
|
207
|
+
out = stream if stream is not None else sys.stderr
|
|
208
|
+
if not self.policy.allows(out):
|
|
209
|
+
return False
|
|
210
|
+
latest = self.latest_version()
|
|
211
|
+
if latest and self._is_newer(latest):
|
|
212
|
+
print(self.message(latest), file=out)
|
|
213
|
+
return True
|
|
214
|
+
except Exception:
|
|
215
|
+
pass
|
|
216
|
+
return False
|
|
217
|
+
|
|
218
|
+
def latest_version(self) -> Optional[str]:
|
|
219
|
+
"""The latest release, from the cache when fresh, else from the network."""
|
|
220
|
+
now = self.clock()
|
|
221
|
+
fresh = self.cache.fresh_latest(now)
|
|
222
|
+
if fresh or self.cache.recently_failed(now):
|
|
223
|
+
return fresh or self.cache.stored_latest()
|
|
224
|
+
try:
|
|
225
|
+
found = self.feed.latest()
|
|
226
|
+
except Exception:
|
|
227
|
+
found = None
|
|
228
|
+
if found:
|
|
229
|
+
self.cache.record_success(found, now)
|
|
230
|
+
return found
|
|
231
|
+
self.cache.record_failure(now)
|
|
232
|
+
return self.cache.stored_latest()
|
|
233
|
+
|
|
234
|
+
def message(self, latest: str) -> str:
|
|
235
|
+
"""The two-line notice: what is available and how to upgrade."""
|
|
236
|
+
return (
|
|
237
|
+
f"A new version of gnost is available: {latest} (you have {self.current}).\n"
|
|
238
|
+
f"Upgrade: {self.upgrade_command()} ({INSTALL_DOCS})"
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def upgrade_command() -> str:
|
|
243
|
+
"""The upgrade command that matches how this copy of gnost was installed."""
|
|
244
|
+
if getattr(sys, "frozen", False):
|
|
245
|
+
return "npm install --global gnost-cli@latest (or pull the newest Docker image)"
|
|
246
|
+
if "pipx" in sys.prefix.replace("\\", "/").lower():
|
|
247
|
+
return "pipx upgrade gnost"
|
|
248
|
+
return "pip install -U gnost"
|
|
249
|
+
|
|
250
|
+
def _is_newer(self, latest: str) -> bool:
|
|
251
|
+
"""True when latest is a valid release after the current one."""
|
|
252
|
+
new, old = Version.parse(latest), Version.parse(self.current)
|
|
253
|
+
return new is not None and old is not None and new.is_newer_than(old)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Version-control helpers (git)."""
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Running git safely and asking questions about a repository.
|
|
2
|
+
|
|
3
|
+
`GitRunner` is the one place that starts the git process (list arguments, no prompts,
|
|
4
|
+
fixed locale, a time limit). `GitRepository` wraps one repository on top of it.
|
|
5
|
+
Problems raise `GitError` with a message the user can act on.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import io
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import tarfile
|
|
15
|
+
from typing import Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
DEFAULT_TIMEOUT = 120
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GitError(Exception):
|
|
21
|
+
"""A git command failed; the message is meant for the user."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class GitUnavailable(GitError):
|
|
25
|
+
"""git is not installed (or not on PATH)."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class GitRunner:
|
|
29
|
+
"""Starts git commands with safe defaults; swap it out in tests."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, timeout: int = DEFAULT_TIMEOUT) -> None:
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
|
|
34
|
+
def available(self) -> bool:
|
|
35
|
+
"""Whether a git executable is on PATH."""
|
|
36
|
+
return shutil.which("git") is not None
|
|
37
|
+
|
|
38
|
+
def run(
|
|
39
|
+
self,
|
|
40
|
+
args: List[str],
|
|
41
|
+
cwd: str,
|
|
42
|
+
timeout: Optional[int] = None,
|
|
43
|
+
env: Optional[Dict[str, str]] = None,
|
|
44
|
+
) -> str:
|
|
45
|
+
"""Run `git <args>` in cwd and return stdout as text; raise GitError on failure."""
|
|
46
|
+
return self.run_bytes(args, cwd, timeout, env).decode("utf-8", "replace")
|
|
47
|
+
|
|
48
|
+
def run_bytes(
|
|
49
|
+
self,
|
|
50
|
+
args: List[str],
|
|
51
|
+
cwd: str,
|
|
52
|
+
timeout: Optional[int] = None,
|
|
53
|
+
env: Optional[Dict[str, str]] = None,
|
|
54
|
+
) -> bytes:
|
|
55
|
+
"""Run `git <args>` in cwd and return raw stdout; raise GitError on any failure."""
|
|
56
|
+
if not self.available():
|
|
57
|
+
raise GitUnavailable(
|
|
58
|
+
"git is not installed or not on PATH, so history is not available. "
|
|
59
|
+
"Install git (https://git-scm.com) and run the command again."
|
|
60
|
+
)
|
|
61
|
+
limit = timeout or self.timeout
|
|
62
|
+
try:
|
|
63
|
+
done = subprocess.run(
|
|
64
|
+
["git", "-c", "core.quotepath=off", *args],
|
|
65
|
+
cwd=cwd,
|
|
66
|
+
capture_output=True,
|
|
67
|
+
timeout=limit,
|
|
68
|
+
env=self._environment(env),
|
|
69
|
+
)
|
|
70
|
+
except subprocess.TimeoutExpired as exc:
|
|
71
|
+
raise GitError(f"git {args[0]} took longer than {limit} seconds") from exc
|
|
72
|
+
except OSError as exc:
|
|
73
|
+
raise GitError(f"could not run git: {exc}") from exc
|
|
74
|
+
if done.returncode != 0:
|
|
75
|
+
detail = done.stderr.decode("utf-8", "replace").strip().splitlines()
|
|
76
|
+
raise GitError(
|
|
77
|
+
f"git {args[0]} failed: {detail[-1] if detail else 'no details'}"
|
|
78
|
+
)
|
|
79
|
+
return done.stdout
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def _environment(extra: Optional[Dict[str, str]]) -> Dict[str, str]:
|
|
83
|
+
"""The process environment with prompts off and a stable locale."""
|
|
84
|
+
env = dict(os.environ)
|
|
85
|
+
env.update(
|
|
86
|
+
{"GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", "GIT_OPTIONAL_LOCKS": "0"}
|
|
87
|
+
)
|
|
88
|
+
env.update(extra or {})
|
|
89
|
+
return env
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class GitRepository:
|
|
93
|
+
"""One git repository (its top folder) and what can be asked of it."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, root: str, runner: Optional[GitRunner] = None) -> None:
|
|
96
|
+
self.root = root
|
|
97
|
+
self.runner = runner or GitRunner()
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def containing(
|
|
101
|
+
cls, path: str, runner: Optional[GitRunner] = None
|
|
102
|
+
) -> Optional["GitRepository"]:
|
|
103
|
+
"""The repository that contains path, or None. Raises GitUnavailable without git."""
|
|
104
|
+
runner = runner or GitRunner()
|
|
105
|
+
folder = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path))
|
|
106
|
+
try:
|
|
107
|
+
top = runner.run(
|
|
108
|
+
["rev-parse", "--show-toplevel"], folder, timeout=20
|
|
109
|
+
).strip()
|
|
110
|
+
except GitUnavailable:
|
|
111
|
+
raise
|
|
112
|
+
except GitError:
|
|
113
|
+
return None
|
|
114
|
+
return cls(os.path.realpath(top), runner) if top else None
|
|
115
|
+
|
|
116
|
+
def run(
|
|
117
|
+
self, args: List[str], cwd: Optional[str] = None, timeout: Optional[int] = None
|
|
118
|
+
) -> str:
|
|
119
|
+
"""Run a git command here (or in cwd, a folder inside the repository)."""
|
|
120
|
+
return self.runner.run(args, cwd or self.root, timeout)
|
|
121
|
+
|
|
122
|
+
def is_shallow(self) -> bool:
|
|
123
|
+
"""True for a shallow clone (a CI checkout with fetch-depth 1), whose history is cut."""
|
|
124
|
+
try:
|
|
125
|
+
return (
|
|
126
|
+
self.run(["rev-parse", "--is-shallow-repository"], timeout=20).strip()
|
|
127
|
+
== "true"
|
|
128
|
+
)
|
|
129
|
+
except GitError:
|
|
130
|
+
return False
|
|
131
|
+
|
|
132
|
+
def commit_count(self) -> int:
|
|
133
|
+
"""Commits reachable from HEAD; 0 for an empty repository."""
|
|
134
|
+
try:
|
|
135
|
+
return int(self.run(["rev-list", "--count", "HEAD"], timeout=60).strip())
|
|
136
|
+
except (GitError, ValueError):
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
def history_problem(self, allow_shallow: bool = False) -> Optional[str]:
|
|
140
|
+
"""Why history cannot be used here, as one sentence, or None if it can.
|
|
141
|
+
|
|
142
|
+
`allow_shallow` accepts a cut-short history (a remote clone that had to be shallow).
|
|
143
|
+
"""
|
|
144
|
+
if self.commit_count() == 0:
|
|
145
|
+
return "the repository has no commits yet"
|
|
146
|
+
if not allow_shallow and self.is_shallow():
|
|
147
|
+
return (
|
|
148
|
+
"this is a shallow clone, so the history is cut short; "
|
|
149
|
+
"fetch it fully (in GitHub Actions: `fetch-depth: 0`)"
|
|
150
|
+
)
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
def resolve(self, ref: str) -> str:
|
|
154
|
+
"""The commit id a ref (branch, tag, `HEAD~3`, sha) points to; GitError if unknown."""
|
|
155
|
+
if ref.startswith("-"):
|
|
156
|
+
raise GitError(f"not a valid ref: {ref}")
|
|
157
|
+
return self.run(
|
|
158
|
+
["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"]
|
|
159
|
+
).strip()
|
|
160
|
+
|
|
161
|
+
def merge_base(self, first: str, second: str) -> str:
|
|
162
|
+
"""The commit where two refs split (what a pull request is compared against)."""
|
|
163
|
+
return self.run(["merge-base", first, second]).strip()
|
|
164
|
+
|
|
165
|
+
def checkout_to(self, ref: str, dest: str, subpath: str = ".") -> None:
|
|
166
|
+
"""Export the files of `ref` (under subpath) into dest without touching the work tree."""
|
|
167
|
+
args = ["archive", "--format=tar", ref]
|
|
168
|
+
if subpath not in ("", "."):
|
|
169
|
+
args += ["--", subpath]
|
|
170
|
+
dest = os.path.realpath(dest)
|
|
171
|
+
data = self.runner.run_bytes(args, self.root, timeout=600)
|
|
172
|
+
with tarfile.open(fileobj=io.BytesIO(data)) as tar:
|
|
173
|
+
for member in tar.getmembers():
|
|
174
|
+
target = os.path.realpath(os.path.join(dest, member.name))
|
|
175
|
+
inside = target == dest or target.startswith(dest + os.sep)
|
|
176
|
+
if not inside or not (member.isfile() or member.isdir()):
|
|
177
|
+
continue # skips links and anything that would leave dest
|
|
178
|
+
if hasattr(tarfile, "data_filter"):
|
|
179
|
+
tar.extract(member, dest, filter="data")
|
|
180
|
+
else:
|
|
181
|
+
tar.extract(member, dest)
|