patchloop 0.2.0__py3-none-any.whl
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.
- patchloop/__init__.py +23 -0
- patchloop/api.py +110 -0
- patchloop/build.py +118 -0
- patchloop/classify.py +137 -0
- patchloop/cli.py +370 -0
- patchloop/config.py +148 -0
- patchloop/detect.py +133 -0
- patchloop/doctor.py +207 -0
- patchloop/enrich/__init__.py +66 -0
- patchloop/enrich/epss.py +65 -0
- patchloop/enrich/kev.py +39 -0
- patchloop/fixers/__init__.py +1 -0
- patchloop/fixers/base.py +20 -0
- patchloop/fixers/js_fix.py +288 -0
- patchloop/fixers/poetry_fix.py +144 -0
- patchloop/fixers/uv_fix.py +118 -0
- patchloop/git_ops.py +171 -0
- patchloop/github.py +161 -0
- patchloop/hints.py +180 -0
- patchloop/images.py +208 -0
- patchloop/isolate.py +57 -0
- patchloop/js/__init__.py +1 -0
- patchloop/js/lockfiles.py +237 -0
- patchloop/js/manifest.py +121 -0
- patchloop/js/ranges.py +130 -0
- patchloop/js/registry.py +67 -0
- patchloop/js/yarn.py +189 -0
- patchloop/lockgraph.py +181 -0
- patchloop/models.py +248 -0
- patchloop/plan.py +194 -0
- patchloop/pr_body.py +253 -0
- patchloop/prioritize.py +38 -0
- patchloop/proc.py +71 -0
- patchloop/py.typed +0 -0
- patchloop/pypi.py +60 -0
- patchloop/report/__init__.py +1 -0
- patchloop/report/console.py +243 -0
- patchloop/report/json_out.py +26 -0
- patchloop/report/sarif.py +143 -0
- patchloop/runner.py +494 -0
- patchloop/scanner.py +214 -0
- patchloop/sources/__init__.py +1 -0
- patchloop/sources/base.py +5 -0
- patchloop/sources/imports.py +292 -0
- patchloop/sources/merge.py +113 -0
- patchloop/sources/osv.py +255 -0
- patchloop/specifiers.py +259 -0
- patchloop/validate.py +198 -0
- patchloop/versions.py +81 -0
- patchloop/workspaces.py +142 -0
- patchloop/worktree.py +153 -0
- patchloop-0.2.0.dist-info/METADATA +388 -0
- patchloop-0.2.0.dist-info/RECORD +56 -0
- patchloop-0.2.0.dist-info/WHEEL +4 -0
- patchloop-0.2.0.dist-info/entry_points.txt +3 -0
- patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Apply upgrades to a Poetry project, to the exact target version.
|
|
2
|
+
|
|
3
|
+
Poetry has no ``uv lock --upgrade-package pkg==ver``, and ``poetry update pkg`` jumps to the
|
|
4
|
+
newest version the range allows. Instead, each target is pinned in a temporary dependency
|
|
5
|
+
group, the project is locked, the group is removed and the project is locked again.
|
|
6
|
+
``poetry lock`` keeps already-locked versions, so the pinned versions stay and
|
|
7
|
+
pyproject.toml ends up with only the bound edits a direct dependency needed. If a parent's
|
|
8
|
+
locked version blocks a pin, Poetry moves that parent forward itself; that is reported as a
|
|
9
|
+
parent upgrade.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import tomlkit
|
|
18
|
+
|
|
19
|
+
from patchloop import proc
|
|
20
|
+
from patchloop.fixers.base import LockError, direct_parents, last_lines
|
|
21
|
+
from patchloop.lockgraph import LockGraph, lock_version_sets
|
|
22
|
+
from patchloop.models import Upgrade, normalize_package
|
|
23
|
+
from patchloop.proc import ToolNotFoundError, ToolTimeoutError
|
|
24
|
+
from patchloop.specifiers import SpecifierEditError, raise_to
|
|
25
|
+
|
|
26
|
+
LOCK_TIMEOUT_S = 600
|
|
27
|
+
PIN_GROUP = "patchloop-pin"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def poetry_major(env: dict[str, str] | None = None) -> int:
|
|
31
|
+
"""Major version of the installed Poetry (2 when it cannot be told)."""
|
|
32
|
+
try:
|
|
33
|
+
result = proc.run(["poetry", "--version"], timeout=60, env=env)
|
|
34
|
+
except (ToolNotFoundError, ToolTimeoutError) as exc:
|
|
35
|
+
raise LockError("poetry is not installed; it is needed for Poetry projects") from exc
|
|
36
|
+
match = re.search(r"(\d+)\.\d+", result.stdout + result.stderr)
|
|
37
|
+
return int(match.group(1)) if match else 2
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def with_pins(pyproject_text: str, pins: dict[str, str]) -> str:
|
|
41
|
+
doc = tomlkit.parse(pyproject_text)
|
|
42
|
+
tool = doc.setdefault("tool", tomlkit.table(is_super_table=True))
|
|
43
|
+
poetry = tool.setdefault("poetry", tomlkit.table())
|
|
44
|
+
groups = poetry.setdefault("group", tomlkit.table(is_super_table=True))
|
|
45
|
+
deps = tomlkit.table()
|
|
46
|
+
for package, version in pins.items():
|
|
47
|
+
deps[package] = f"=={version}"
|
|
48
|
+
group = tomlkit.table()
|
|
49
|
+
group["dependencies"] = deps
|
|
50
|
+
groups[PIN_GROUP] = group
|
|
51
|
+
return tomlkit.dumps(doc)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PoetryFixer:
|
|
55
|
+
def __init__(self, project_dir: Path, graph: LockGraph, env: dict[str, str]) -> None:
|
|
56
|
+
self.project_dir = project_dir
|
|
57
|
+
self.pyproject = project_dir / "pyproject.toml"
|
|
58
|
+
self.lockfile = project_dir / "poetry.lock"
|
|
59
|
+
self.graph = graph
|
|
60
|
+
self.env = {**env, "POETRY_NO_INTERACTION": "1"}
|
|
61
|
+
self._orig_pyproject = self.pyproject.read_bytes()
|
|
62
|
+
self._orig_lock = self.lockfile.read_bytes()
|
|
63
|
+
self._orig_versions = lock_version_sets(self.lockfile)
|
|
64
|
+
# Poetry 1.x re-resolves everything on `poetry lock` unless told not to.
|
|
65
|
+
self._lock_cmd = ["poetry", "lock"]
|
|
66
|
+
if poetry_major(self.env) < 2:
|
|
67
|
+
self._lock_cmd.append("--no-update")
|
|
68
|
+
self.manifest_changes: dict[str, list[tuple[str, str, str]]] = {}
|
|
69
|
+
self.resolver_errors: dict[str, str] = {}
|
|
70
|
+
"""package -> Poetry's full message, written to the run log."""
|
|
71
|
+
|
|
72
|
+
def restore(self) -> None:
|
|
73
|
+
self.pyproject.write_bytes(self._orig_pyproject)
|
|
74
|
+
self.lockfile.write_bytes(self._orig_lock)
|
|
75
|
+
|
|
76
|
+
def _lock(self) -> None:
|
|
77
|
+
try:
|
|
78
|
+
result = proc.run(
|
|
79
|
+
self._lock_cmd, cwd=self.project_dir, timeout=LOCK_TIMEOUT_S, env=self.env
|
|
80
|
+
)
|
|
81
|
+
except ToolTimeoutError as exc:
|
|
82
|
+
raise LockError(f"poetry lock timed out after {LOCK_TIMEOUT_S}s") from exc
|
|
83
|
+
if not result.ok:
|
|
84
|
+
raise LockError(last_lines(result.stderr or result.stdout))
|
|
85
|
+
|
|
86
|
+
def apply(self, upgrades: list[Upgrade]) -> None:
|
|
87
|
+
self.restore()
|
|
88
|
+
if not upgrades:
|
|
89
|
+
return
|
|
90
|
+
text = self._orig_pyproject.decode("utf-8")
|
|
91
|
+
for u in upgrades:
|
|
92
|
+
if u.method == "raise-bound":
|
|
93
|
+
try:
|
|
94
|
+
text, changes = raise_to(text, u.package, u.to_version)
|
|
95
|
+
except SpecifierEditError as exc:
|
|
96
|
+
raise LockError(str(exc)) from exc
|
|
97
|
+
self.manifest_changes[u.package] = [("pyproject.toml", o, n) for o, n in changes]
|
|
98
|
+
try:
|
|
99
|
+
pins = {u.package: u.to_version for u in upgrades}
|
|
100
|
+
self.pyproject.write_text(with_pins(text, pins), encoding="utf-8")
|
|
101
|
+
self._lock()
|
|
102
|
+
self.pyproject.write_text(text, encoding="utf-8")
|
|
103
|
+
self._lock()
|
|
104
|
+
locked = lock_version_sets(self.lockfile)
|
|
105
|
+
for u in upgrades:
|
|
106
|
+
got = locked.get(normalize_package(u.package), set())
|
|
107
|
+
if u.to_version not in got or u.from_version in got:
|
|
108
|
+
found = ", ".join(sorted(got)) or "nothing"
|
|
109
|
+
raise LockError(f"{u.package} did not stay at {u.to_version} (got {found})")
|
|
110
|
+
except LockError:
|
|
111
|
+
self.restore()
|
|
112
|
+
raise
|
|
113
|
+
|
|
114
|
+
def _moved_parents(self, package: str) -> list[str]:
|
|
115
|
+
now = lock_version_sets(self.lockfile)
|
|
116
|
+
return [
|
|
117
|
+
p
|
|
118
|
+
for p in direct_parents(self.graph, package)
|
|
119
|
+
if now.get(p) != self._orig_versions.get(p)
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
def resolve_each(self, upgrades: list[Upgrade]) -> tuple[list[Upgrade], dict[str, str]]:
|
|
123
|
+
accepted: list[Upgrade] = []
|
|
124
|
+
blocked: dict[str, str] = {}
|
|
125
|
+
for u in upgrades:
|
|
126
|
+
try:
|
|
127
|
+
self.apply([*accepted, u])
|
|
128
|
+
except LockError as exc:
|
|
129
|
+
self.resolver_errors[u.package] = str(exc)
|
|
130
|
+
parents = direct_parents(self.graph, u.package)
|
|
131
|
+
if parents and not self.graph.is_direct(u.package):
|
|
132
|
+
blocked[u.package] = (
|
|
133
|
+
f"{', '.join(parents)} does not allow {u.package} {u.to_version}, "
|
|
134
|
+
"even at its newest version"
|
|
135
|
+
)
|
|
136
|
+
else:
|
|
137
|
+
blocked[u.package] = f"Poetry could not resolve {u.package} {u.to_version}"
|
|
138
|
+
continue
|
|
139
|
+
moved = [] if self.graph.is_direct(u.package) else self._moved_parents(u.package)
|
|
140
|
+
if moved:
|
|
141
|
+
u = u.model_copy(update={"method": "parent-upgrade", "parents": moved})
|
|
142
|
+
accepted.append(u)
|
|
143
|
+
self.restore()
|
|
144
|
+
return accepted, blocked
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Apply upgrades to a uv project: pyproject.toml specifier edits + `uv lock -P pkg==ver`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from patchloop import proc
|
|
9
|
+
from patchloop.fixers.base import LockError, direct_parents, last_lines
|
|
10
|
+
from patchloop.lockgraph import LockGraph
|
|
11
|
+
from patchloop.models import Upgrade
|
|
12
|
+
from patchloop.proc import ToolTimeoutError
|
|
13
|
+
from patchloop.specifiers import SpecifierEditError, raise_to
|
|
14
|
+
|
|
15
|
+
LOCK_TIMEOUT_S = 300
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class UvFixer:
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
project_dir: Path,
|
|
22
|
+
graph: LockGraph,
|
|
23
|
+
env: dict[str, str],
|
|
24
|
+
members: list[str] | None = None,
|
|
25
|
+
) -> None:
|
|
26
|
+
self.project_dir = project_dir
|
|
27
|
+
self.pyproject = project_dir / "pyproject.toml"
|
|
28
|
+
self.manifests = [
|
|
29
|
+
self.pyproject,
|
|
30
|
+
*(project_dir / m / "pyproject.toml" for m in members or []),
|
|
31
|
+
]
|
|
32
|
+
self.lockfile = project_dir / "uv.lock"
|
|
33
|
+
self.graph = graph
|
|
34
|
+
self.env = env
|
|
35
|
+
self._orig = {p: p.read_bytes() for p in self.manifests}
|
|
36
|
+
self._orig_lock = self.lockfile.read_bytes()
|
|
37
|
+
self.manifest_changes: dict[str, list[tuple[str, str, str]]] = {}
|
|
38
|
+
"""package -> (file, old, new) requirement edits."""
|
|
39
|
+
self.resolver_errors: dict[str, str] = {}
|
|
40
|
+
"""package -> uv's full message, written to the run log."""
|
|
41
|
+
|
|
42
|
+
def restore(self) -> None:
|
|
43
|
+
for path, data in self._orig.items():
|
|
44
|
+
path.write_bytes(data)
|
|
45
|
+
self.lockfile.write_bytes(self._orig_lock)
|
|
46
|
+
|
|
47
|
+
def _lock(self, upgrades: list[Upgrade]) -> None:
|
|
48
|
+
cmd = ["uv", "lock"]
|
|
49
|
+
counts = Counter(u.package for u in upgrades)
|
|
50
|
+
for u in upgrades:
|
|
51
|
+
# uv.lock can hold a package once per Python-version range ("forks"); `==` would
|
|
52
|
+
# force one version on every fork, so let uv pick the newest allowed for each.
|
|
53
|
+
pin = u.package if counts[u.package] > 1 else f"{u.package}=={u.to_version}"
|
|
54
|
+
cmd += ["--upgrade-package", pin]
|
|
55
|
+
for parent in u.parents:
|
|
56
|
+
cmd += ["--upgrade-package", parent]
|
|
57
|
+
try:
|
|
58
|
+
result = proc.run(cmd, cwd=self.project_dir, timeout=LOCK_TIMEOUT_S, env=self.env)
|
|
59
|
+
except ToolTimeoutError as exc:
|
|
60
|
+
raise LockError(f"uv lock timed out after {LOCK_TIMEOUT_S}s") from exc
|
|
61
|
+
if not result.ok:
|
|
62
|
+
raise LockError(last_lines(result.stderr or result.stdout))
|
|
63
|
+
|
|
64
|
+
def apply(self, upgrades: list[Upgrade]) -> None:
|
|
65
|
+
self.restore()
|
|
66
|
+
if not upgrades:
|
|
67
|
+
return
|
|
68
|
+
texts = {p: data.decode("utf-8") for p, data in self._orig.items()}
|
|
69
|
+
for u in upgrades:
|
|
70
|
+
if u.method != "raise-bound":
|
|
71
|
+
continue
|
|
72
|
+
edits: list[tuple[str, str, str]] = []
|
|
73
|
+
for path, text in texts.items():
|
|
74
|
+
try:
|
|
75
|
+
texts[path], changes = raise_to(text, u.package, u.to_version)
|
|
76
|
+
except SpecifierEditError as exc:
|
|
77
|
+
raise LockError(str(exc)) from exc
|
|
78
|
+
label = path.relative_to(self.project_dir).as_posix()
|
|
79
|
+
edits += [(label, old, new) for old, new in changes]
|
|
80
|
+
self.manifest_changes[u.package] = edits
|
|
81
|
+
for path, text in texts.items():
|
|
82
|
+
if text != self._orig[path].decode("utf-8"):
|
|
83
|
+
path.write_text(text, encoding="utf-8")
|
|
84
|
+
try:
|
|
85
|
+
self._lock(upgrades)
|
|
86
|
+
except LockError:
|
|
87
|
+
self.restore()
|
|
88
|
+
raise
|
|
89
|
+
|
|
90
|
+
def resolve_each(self, upgrades: list[Upgrade]) -> tuple[list[Upgrade], dict[str, str]]:
|
|
91
|
+
accepted: list[Upgrade] = []
|
|
92
|
+
blocked: dict[str, str] = {}
|
|
93
|
+
for u in upgrades:
|
|
94
|
+
try:
|
|
95
|
+
self.apply([*accepted, u])
|
|
96
|
+
accepted.append(u)
|
|
97
|
+
continue
|
|
98
|
+
except LockError as exc:
|
|
99
|
+
first_error = str(exc)
|
|
100
|
+
parents = direct_parents(self.graph, u.package)
|
|
101
|
+
if not self.graph.is_direct(u.package) and parents:
|
|
102
|
+
lifted = u.model_copy(update={"method": "parent-upgrade", "parents": parents})
|
|
103
|
+
try:
|
|
104
|
+
self.apply([*accepted, lifted])
|
|
105
|
+
accepted.append(lifted)
|
|
106
|
+
continue
|
|
107
|
+
except LockError:
|
|
108
|
+
pass
|
|
109
|
+
self.resolver_errors[u.package] = first_error
|
|
110
|
+
if parents:
|
|
111
|
+
blocked[u.package] = (
|
|
112
|
+
f"{', '.join(parents)} does not allow {u.package} {u.to_version}, "
|
|
113
|
+
"even at its newest version"
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
blocked[u.package] = f"uv could not resolve {u.package} {u.to_version}"
|
|
117
|
+
self.restore()
|
|
118
|
+
return accepted, blocked
|
patchloop/git_ops.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Commit, branch and push for the one PatchLoop PR.
|
|
2
|
+
|
|
3
|
+
The PR branch is rebuilt from the base commit on every run: one commit, holding only
|
|
4
|
+
pyproject.toml and the lockfile. Every PatchLoop commit carries a ``PatchLoop-Run:``
|
|
5
|
+
trailer; a branch holding any other non-merge commit belongs to a human, and PatchLoop
|
|
6
|
+
refuses to overwrite it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from patchloop import proc
|
|
17
|
+
from patchloop.proc import ProcResult, ToolNotFoundError, ToolTimeoutError
|
|
18
|
+
|
|
19
|
+
TRAILER = "PatchLoop-Run"
|
|
20
|
+
|
|
21
|
+
# git@host:owner/repo(.git) · ssh://git@host[:port]/owner/repo · https://host/owner/repo
|
|
22
|
+
_REMOTE_RE = re.compile(
|
|
23
|
+
r"^(?:(?:ssh|https?|git)://)?(?:[^@/\s]+@)?"
|
|
24
|
+
r"(?P<host>[\w.-]+)(?::\d+)?[:/](?P<owner>[\w.-]+)/(?P<repo>[\w.-]+?)(?:\.git)?/?$"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class GitError(Exception):
|
|
29
|
+
"""A git step failed; the message says which and why."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class BranchState:
|
|
34
|
+
"""Where the PR branch stands before this run changes anything."""
|
|
35
|
+
|
|
36
|
+
name: str
|
|
37
|
+
sha: str | None
|
|
38
|
+
"""Its current commit, or None if the branch does not exist."""
|
|
39
|
+
foreign: list[str]
|
|
40
|
+
"""Short SHAs of commits on it that PatchLoop did not make."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def git(args: list[str], cwd: Path, *, env: dict[str, str] | None = None) -> ProcResult:
|
|
44
|
+
full_env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", **(env or {})}
|
|
45
|
+
try:
|
|
46
|
+
return proc.run(["git", *args], cwd=cwd, timeout=300, env=full_env)
|
|
47
|
+
except ToolNotFoundError as exc:
|
|
48
|
+
raise GitError("git is not installed") from exc
|
|
49
|
+
except ToolTimeoutError as exc:
|
|
50
|
+
raise GitError(f"git {args[0]} timed out") from exc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _must(result: ProcResult, what: str) -> str:
|
|
54
|
+
if not result.ok:
|
|
55
|
+
lines = [ln for ln in result.stderr.strip().splitlines() if ln.strip()]
|
|
56
|
+
raise GitError(f"{what}: {lines[-1] if lines else f'exit code {result.returncode}'}")
|
|
57
|
+
return result.stdout.strip()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def repo_slug(repo: Path, remote: str = "origin") -> str:
|
|
61
|
+
"""``owner/name`` of the GitHub repo behind ``remote`` (SSH host aliases are fine)."""
|
|
62
|
+
url = _must(git(["remote", "get-url", remote], repo), f"no '{remote}' remote")
|
|
63
|
+
match = _REMOTE_RE.match(url.strip())
|
|
64
|
+
if not match:
|
|
65
|
+
raise GitError(f"cannot read a GitHub owner/repo from the '{remote}' remote URL")
|
|
66
|
+
return f"{match['owner']}/{match['repo']}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def has_remote(repo: Path, remote: str = "origin") -> bool:
|
|
70
|
+
return remote in _must(git(["remote"], repo), "git remote").split()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def remote_branch_sha(repo: Path, branch: str, env: dict[str, str] | None = None) -> str | None:
|
|
74
|
+
out = _must(
|
|
75
|
+
git(["ls-remote", "--heads", "origin", f"refs/heads/{branch}"], repo, env=env),
|
|
76
|
+
"could not read branches from origin",
|
|
77
|
+
)
|
|
78
|
+
return out.split()[0] if out else None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def local_branch_sha(repo: Path, branch: str) -> str | None:
|
|
82
|
+
result = git(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}^{{commit}}"], repo)
|
|
83
|
+
return result.stdout.strip() if result.ok else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def foreign_commits(repo: Path, base: str, tip: str) -> list[str]:
|
|
87
|
+
"""Non-merge commits in base..tip without the PatchLoop trailer.
|
|
88
|
+
|
|
89
|
+
Merge commits are allowed (GitHub's "Update branch" makes them); they only bring in
|
|
90
|
+
base commits, and the rebuild drops them anyway.
|
|
91
|
+
"""
|
|
92
|
+
out = _must(
|
|
93
|
+
git(
|
|
94
|
+
[
|
|
95
|
+
"log",
|
|
96
|
+
"--no-merges",
|
|
97
|
+
f"--format=%h %(trailers:key={TRAILER},valueonly,separator=%x2C)",
|
|
98
|
+
f"{base}..{tip}",
|
|
99
|
+
],
|
|
100
|
+
repo,
|
|
101
|
+
),
|
|
102
|
+
"could not read the PR branch history",
|
|
103
|
+
)
|
|
104
|
+
return [line.split()[0] for line in out.splitlines() if len(line.split()) < 2]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def branch_state(
|
|
108
|
+
repo: Path, branch: str, base_sha: str, *, remote: bool, env: dict[str, str] | None = None
|
|
109
|
+
) -> BranchState:
|
|
110
|
+
"""The PR branch on origin (``remote``) or in the local repo, and any foreign commits."""
|
|
111
|
+
if remote:
|
|
112
|
+
sha = remote_branch_sha(repo, branch, env)
|
|
113
|
+
if sha:
|
|
114
|
+
_must(
|
|
115
|
+
git(["fetch", "--quiet", "origin", f"refs/heads/{branch}"], repo, env=env),
|
|
116
|
+
f"could not fetch {branch}",
|
|
117
|
+
)
|
|
118
|
+
else:
|
|
119
|
+
sha = local_branch_sha(repo, branch)
|
|
120
|
+
foreign = foreign_commits(repo, base_sha, sha) if sha else []
|
|
121
|
+
return BranchState(branch, sha, foreign)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def foreign_error(state: BranchState, where: str) -> GitError:
|
|
125
|
+
shown = ", ".join(state.foreign[:5]) + (" …" if len(state.foreign) > 5 else "")
|
|
126
|
+
return GitError(
|
|
127
|
+
f"{where} branch '{state.name}' holds commits PatchLoop didn't make ({shown}); "
|
|
128
|
+
"nothing was pushed. Move that work to another branch, or delete the branch "
|
|
129
|
+
"to let PatchLoop rebuild it."
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def commit(worktree: Path, paths: list[str], message: str) -> str:
|
|
134
|
+
"""Commit exactly ``paths`` in the worktree (detached at the base commit); return the SHA."""
|
|
135
|
+
_must(git(["add", "--", *paths], worktree), "git add")
|
|
136
|
+
staged = _must(git(["diff", "--cached", "--name-only"], worktree), "git diff")
|
|
137
|
+
extra = set(staged.splitlines()) - set(paths)
|
|
138
|
+
if extra:
|
|
139
|
+
raise GitError(f"refusing to commit unexpected files: {sorted(extra)}")
|
|
140
|
+
result = git(["commit", "--quiet", "--no-verify", "-m", message], worktree)
|
|
141
|
+
if not result.ok and "tell me who you are" in result.stderr.lower():
|
|
142
|
+
raise GitError("git has no user.name / user.email set for this repo; set them first")
|
|
143
|
+
_must(result, "git commit")
|
|
144
|
+
return _must(git(["rev-parse", "HEAD"], worktree), "git rev-parse")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def same_change(repo: Path, a: str, b: str) -> bool:
|
|
148
|
+
"""Same parent and same tree: pushing ``b`` over ``a`` would change nothing."""
|
|
149
|
+
out = _must(
|
|
150
|
+
git(["rev-parse", f"{a}^{{tree}}", f"{b}^{{tree}}", f"{a}^", f"{b}^"], repo),
|
|
151
|
+
"git rev-parse",
|
|
152
|
+
).split()
|
|
153
|
+
return out[0] == out[1] and out[2] == out[3]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def push(repo: Path, sha: str, branch: str, expected: str | None, env: dict[str, str]) -> None:
|
|
157
|
+
"""Force-push ``sha`` to ``branch``, but only if origin still has ``expected`` there."""
|
|
158
|
+
lease = f"--force-with-lease=refs/heads/{branch}:{expected or ''}"
|
|
159
|
+
result = git(["push", "--quiet", lease, "origin", f"{sha}:refs/heads/{branch}"], repo, env=env)
|
|
160
|
+
if not result.ok and "stale info" in result.stderr:
|
|
161
|
+
raise GitError(f"'{branch}' changed on origin during the run; nothing was pushed. Re-run.")
|
|
162
|
+
_must(result, f"git push to {branch}")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def set_local_branch(repo: Path, branch: str, sha: str) -> None:
|
|
166
|
+
result = git(["branch", "--force", branch, sha], repo)
|
|
167
|
+
if not result.ok and "used by worktree" in result.stderr:
|
|
168
|
+
raise GitError(
|
|
169
|
+
f"'{branch}' is checked out; switch to another branch so PatchLoop can rebuild it"
|
|
170
|
+
)
|
|
171
|
+
_must(result, f"could not update local branch {branch}")
|
patchloop/github.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Open or update the one PatchLoop PR through the ``gh`` CLI.
|
|
2
|
+
|
|
3
|
+
With ``pr.gh_user`` set, gh and git push run with that account's token (``GH_TOKEN``) for
|
|
4
|
+
PatchLoop's own commands only; the account active in gh is never switched. The token is
|
|
5
|
+
kept in memory and passed only to gh and git, never logged or written anywhere.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Protocol
|
|
16
|
+
|
|
17
|
+
from patchloop import proc
|
|
18
|
+
from patchloop.proc import ProcResult, ToolNotFoundError, ToolTimeoutError
|
|
19
|
+
|
|
20
|
+
_PR_URL_RE = re.compile(r"https://\S+/pull/(\d+)")
|
|
21
|
+
_CAN_PUSH = {"ADMIN", "MAINTAIN", "WRITE"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class GitHubError(Exception):
|
|
25
|
+
"""A gh step failed; the message says which and why."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class PullRequest:
|
|
30
|
+
number: int
|
|
31
|
+
url: str
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PRHost(Protocol):
|
|
35
|
+
"""Where the PR lives. The real one is :class:`GhCli`; tests use a fake."""
|
|
36
|
+
|
|
37
|
+
def push_env(self) -> dict[str, str]:
|
|
38
|
+
"""Extra environment for ``git push`` (credentials for HTTPS remotes)."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def find_open(self, branch: str) -> PullRequest | None: ...
|
|
42
|
+
|
|
43
|
+
def create(self, base: str, branch: str, title: str, body_file: Path) -> PullRequest: ...
|
|
44
|
+
|
|
45
|
+
def update(self, pr: PullRequest, title: str, body_file: Path) -> None: ...
|
|
46
|
+
|
|
47
|
+
def decorate(self, pr: PullRequest, labels: list[str], reviewers: list[str]) -> list[str]:
|
|
48
|
+
"""Add labels and reviewers; return warnings for the ones that could not be added."""
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _last_line(result: ProcResult) -> str:
|
|
53
|
+
lines = [ln for ln in (result.stderr or result.stdout).strip().splitlines() if ln.strip()]
|
|
54
|
+
return lines[-1] if lines else f"exit code {result.returncode}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class GhCli:
|
|
58
|
+
def __init__(self, slug: str, user: str | None = None) -> None:
|
|
59
|
+
self.slug = slug
|
|
60
|
+
self.user = user
|
|
61
|
+
self._env = {**os.environ, "GH_PROMPT_DISABLED": "1", "GH_NO_UPDATE_NOTIFIER": "1"}
|
|
62
|
+
if user:
|
|
63
|
+
token = self._run(["auth", "token", "--user", user], f"gh has no login for {user}")
|
|
64
|
+
self._env["GH_TOKEN"] = token.strip()
|
|
65
|
+
|
|
66
|
+
def _run(self, args: list[str], what: str) -> str:
|
|
67
|
+
try:
|
|
68
|
+
result = proc.run(["gh", *args], timeout=120, env=self._env)
|
|
69
|
+
except ToolNotFoundError as exc:
|
|
70
|
+
raise GitHubError("gh is not installed") from exc
|
|
71
|
+
except ToolTimeoutError as exc:
|
|
72
|
+
raise GitHubError(f"gh {args[0]} timed out") from exc
|
|
73
|
+
if not result.ok:
|
|
74
|
+
hint = " (run: gh auth login)" if "auth" in args[:2] else ""
|
|
75
|
+
raise GitHubError(f"{what}: {_last_line(result)}{hint}")
|
|
76
|
+
return result.stdout
|
|
77
|
+
|
|
78
|
+
def check_access(self) -> None:
|
|
79
|
+
"""Fail early, before any slow work, if this account cannot push to the repo."""
|
|
80
|
+
out = self._run(
|
|
81
|
+
["repo", "view", self.slug, "--json", "viewerPermission"],
|
|
82
|
+
f"cannot open {self.slug} on GitHub",
|
|
83
|
+
)
|
|
84
|
+
permission = json.loads(out).get("viewerPermission", "")
|
|
85
|
+
if permission not in _CAN_PUSH:
|
|
86
|
+
who = self.user or "the active gh account"
|
|
87
|
+
raise GitHubError(
|
|
88
|
+
f"{who} cannot push to {self.slug} (permission: {permission or 'none'}); "
|
|
89
|
+
"set pr.gh_user in patchloop.yml to an account that can"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def push_env(self) -> dict[str, str]:
|
|
93
|
+
return {"GH_TOKEN": self._env["GH_TOKEN"]} if "GH_TOKEN" in self._env else {}
|
|
94
|
+
|
|
95
|
+
def find_open(self, branch: str) -> PullRequest | None:
|
|
96
|
+
out = self._run(
|
|
97
|
+
[
|
|
98
|
+
"pr", "list", "--repo", self.slug, "--head", branch, "--state", "open",
|
|
99
|
+
"--json", "number,url,isCrossRepository", "--limit", "20",
|
|
100
|
+
],
|
|
101
|
+
"could not list pull requests",
|
|
102
|
+
) # fmt: skip
|
|
103
|
+
mine = [p for p in json.loads(out) if not p.get("isCrossRepository")]
|
|
104
|
+
if not mine:
|
|
105
|
+
return None
|
|
106
|
+
newest = max(mine, key=lambda p: p["number"])
|
|
107
|
+
return PullRequest(int(newest["number"]), str(newest["url"]))
|
|
108
|
+
|
|
109
|
+
def create(self, base: str, branch: str, title: str, body_file: Path) -> PullRequest:
|
|
110
|
+
out = self._run(
|
|
111
|
+
[
|
|
112
|
+
"pr", "create", "--repo", self.slug, "--base", base, "--head", branch,
|
|
113
|
+
"--title", title, "--body-file", str(body_file),
|
|
114
|
+
],
|
|
115
|
+
"could not open the pull request",
|
|
116
|
+
) # fmt: skip
|
|
117
|
+
match = _PR_URL_RE.search(out)
|
|
118
|
+
if not match:
|
|
119
|
+
raise GitHubError("gh pr create did not return a PR URL")
|
|
120
|
+
return PullRequest(int(match.group(1)), match.group(0))
|
|
121
|
+
|
|
122
|
+
def update(self, pr: PullRequest, title: str, body_file: Path) -> None:
|
|
123
|
+
self._run(
|
|
124
|
+
[
|
|
125
|
+
"pr", "edit", str(pr.number), "--repo", self.slug,
|
|
126
|
+
"--title", title, "--body-file", str(body_file),
|
|
127
|
+
],
|
|
128
|
+
f"could not update PR #{pr.number}",
|
|
129
|
+
) # fmt: skip
|
|
130
|
+
|
|
131
|
+
def decorate(self, pr: PullRequest, labels: list[str], reviewers: list[str]) -> list[str]:
|
|
132
|
+
warnings: list[str] = []
|
|
133
|
+
if labels:
|
|
134
|
+
out = self._run(
|
|
135
|
+
["label", "list", "--repo", self.slug, "--json", "name", "--limit", "500"],
|
|
136
|
+
"could not list labels",
|
|
137
|
+
)
|
|
138
|
+
existing = {str(lbl["name"]).lower() for lbl in json.loads(out)}
|
|
139
|
+
usable = [lbl for lbl in labels if lbl.lower() in existing]
|
|
140
|
+
missing = [lbl for lbl in labels if lbl.lower() not in existing]
|
|
141
|
+
if missing:
|
|
142
|
+
warnings.append(f"labels not in the repo, not added: {', '.join(missing)}")
|
|
143
|
+
if usable:
|
|
144
|
+
try:
|
|
145
|
+
self._run(
|
|
146
|
+
["pr", "edit", str(pr.number), "--repo", self.slug,
|
|
147
|
+
"--add-label", ",".join(usable)],
|
|
148
|
+
"could not add labels",
|
|
149
|
+
) # fmt: skip
|
|
150
|
+
except GitHubError as exc:
|
|
151
|
+
warnings.append(str(exc))
|
|
152
|
+
if reviewers:
|
|
153
|
+
try:
|
|
154
|
+
self._run(
|
|
155
|
+
["pr", "edit", str(pr.number), "--repo", self.slug,
|
|
156
|
+
"--add-reviewer", ",".join(reviewers)],
|
|
157
|
+
"could not request reviewers",
|
|
158
|
+
) # fmt: skip
|
|
159
|
+
except GitHubError as exc:
|
|
160
|
+
warnings.append(str(exc))
|
|
161
|
+
return warnings
|