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.
Files changed (56) hide show
  1. patchloop/__init__.py +23 -0
  2. patchloop/api.py +110 -0
  3. patchloop/build.py +118 -0
  4. patchloop/classify.py +137 -0
  5. patchloop/cli.py +370 -0
  6. patchloop/config.py +148 -0
  7. patchloop/detect.py +133 -0
  8. patchloop/doctor.py +207 -0
  9. patchloop/enrich/__init__.py +66 -0
  10. patchloop/enrich/epss.py +65 -0
  11. patchloop/enrich/kev.py +39 -0
  12. patchloop/fixers/__init__.py +1 -0
  13. patchloop/fixers/base.py +20 -0
  14. patchloop/fixers/js_fix.py +288 -0
  15. patchloop/fixers/poetry_fix.py +144 -0
  16. patchloop/fixers/uv_fix.py +118 -0
  17. patchloop/git_ops.py +171 -0
  18. patchloop/github.py +161 -0
  19. patchloop/hints.py +180 -0
  20. patchloop/images.py +208 -0
  21. patchloop/isolate.py +57 -0
  22. patchloop/js/__init__.py +1 -0
  23. patchloop/js/lockfiles.py +237 -0
  24. patchloop/js/manifest.py +121 -0
  25. patchloop/js/ranges.py +130 -0
  26. patchloop/js/registry.py +67 -0
  27. patchloop/js/yarn.py +189 -0
  28. patchloop/lockgraph.py +181 -0
  29. patchloop/models.py +248 -0
  30. patchloop/plan.py +194 -0
  31. patchloop/pr_body.py +253 -0
  32. patchloop/prioritize.py +38 -0
  33. patchloop/proc.py +71 -0
  34. patchloop/py.typed +0 -0
  35. patchloop/pypi.py +60 -0
  36. patchloop/report/__init__.py +1 -0
  37. patchloop/report/console.py +243 -0
  38. patchloop/report/json_out.py +26 -0
  39. patchloop/report/sarif.py +143 -0
  40. patchloop/runner.py +494 -0
  41. patchloop/scanner.py +214 -0
  42. patchloop/sources/__init__.py +1 -0
  43. patchloop/sources/base.py +5 -0
  44. patchloop/sources/imports.py +292 -0
  45. patchloop/sources/merge.py +113 -0
  46. patchloop/sources/osv.py +255 -0
  47. patchloop/specifiers.py +259 -0
  48. patchloop/validate.py +198 -0
  49. patchloop/versions.py +81 -0
  50. patchloop/workspaces.py +142 -0
  51. patchloop/worktree.py +153 -0
  52. patchloop-0.2.0.dist-info/METADATA +388 -0
  53. patchloop-0.2.0.dist-info/RECORD +56 -0
  54. patchloop-0.2.0.dist-info/WHEEL +4 -0
  55. patchloop-0.2.0.dist-info/entry_points.txt +3 -0
  56. patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,121 @@
1
+ """Read and minimally edit package.json: version ranges, temporary pins, and overrides.
2
+
3
+ The file is rewritten with its own indentation and key order, so a diff shows only the
4
+ values that changed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from typing import Any
12
+
13
+ from patchloop.js.ranges import allows, raise_range
14
+ from patchloop.specifiers import SpecifierEditError
15
+
16
+ SECTIONS = ("dependencies", "optionalDependencies", "devDependencies")
17
+
18
+
19
+ def _indent(text: str) -> int | str:
20
+ m = re.search(r"^([ \t]+)\S", text, re.MULTILINE)
21
+ if not m:
22
+ return 2
23
+ ws = m.group(1)
24
+ return "\t" if ws.startswith("\t") else len(ws)
25
+
26
+
27
+ def load(text: str) -> dict[str, Any]:
28
+ data: dict[str, Any] = json.loads(text)
29
+ return data
30
+
31
+
32
+ def dump(data: dict[str, Any], like: str) -> str:
33
+ out = json.dumps(data, indent=_indent(like), ensure_ascii=False)
34
+ out += "\n" if like.endswith("\n") else ""
35
+ return out.replace("\n", "\r\n") if "\r\n" in like else out
36
+
37
+
38
+ def _replace_values(text: str, edits: list[tuple[str, str, str]]) -> str | None:
39
+ """Swap each ``"key": "old"`` for ``"key": "new"`` in place, keeping the file's own
40
+ formatting; None when a pair is not found exactly once."""
41
+ for key, old, new in edits:
42
+ pattern = re.compile(rf'("{re.escape(key)}"\s*:\s*)"{re.escape(old)}"')
43
+ if len(pattern.findall(text)) != 1:
44
+ return None
45
+ text = pattern.sub(lambda m: f'{m.group(1)}"{new}"', text) # noqa: B023
46
+ return text
47
+
48
+
49
+ def _entries(data: dict[str, Any], package: str) -> list[tuple[str, str]]:
50
+ name = package.lower()
51
+ return [
52
+ (section, key)
53
+ for section in SECTIONS
54
+ for key in (data.get(section) or {})
55
+ if key.lower() == name
56
+ ]
57
+
58
+
59
+ def manifest_allows(text: str, package: str, version: str) -> bool:
60
+ data = load(text)
61
+ return all(allows(str(data[s][k]), version) for s, k in _entries(data, package))
62
+
63
+
64
+ def raise_in_manifest(text: str, package: str, target: str) -> tuple[str, list[tuple[str, str]]]:
65
+ """Rewrite every range on ``package`` that excludes ``target``; return (text, changes)."""
66
+ data = load(text)
67
+ changes, edits = [], []
68
+ for section, key in _entries(data, package):
69
+ spec = str(data[section][key])
70
+ if allows(spec, target):
71
+ continue
72
+ new = raise_range(spec, target)
73
+ data[section][key] = new
74
+ edits.append((key, spec, new))
75
+ changes.append((f'"{key}": "{spec}"', f'"{key}": "{new}"'))
76
+ if not changes:
77
+ return text, changes
78
+ in_place = _replace_values(text, edits)
79
+ return (in_place if in_place is not None else dump(data, text)), changes
80
+
81
+
82
+ def with_pins(
83
+ text: str,
84
+ manager: str,
85
+ direct: dict[str, str],
86
+ overrides: list[tuple[str, str, str]],
87
+ yarn_berry: bool = False,
88
+ ) -> str:
89
+ """Pin ``direct`` packages to exact versions in their own entries, and transitive ones
90
+ through the manager's override mechanism. ``overrides``: (name, from, to); npm and
91
+ pnpm key each by the version it replaces, so other copies of the package are kept."""
92
+ data = load(text)
93
+ for package, version in direct.items():
94
+ for section, key in _entries(data, package):
95
+ data[section][key] = version
96
+ if overrides:
97
+ if manager == "npm":
98
+ table = data.setdefault("overrides", {})
99
+ for name, old, new in overrides:
100
+ table[f"{name}@{old}"] = new
101
+ elif manager == "pnpm":
102
+ table = data.setdefault("pnpm", {}).setdefault("overrides", {})
103
+ for name, old, new in overrides:
104
+ table[f"{name}@{old}"] = new
105
+ elif manager == "yarn":
106
+ table = data.setdefault("resolutions", {})
107
+ for name, _, new in overrides:
108
+ table[name if yarn_berry else f"**/{name}"] = new
109
+ else: # pragma: no cover - only JS managers reach here
110
+ raise SpecifierEditError(f"no override mechanism for {manager}")
111
+ return text if data == load(text) else dump(data, text) # untouched files keep their bytes
112
+
113
+
114
+ def with_root_deps(text: str, pins: dict[str, str]) -> str:
115
+ """Add exact ``dependencies`` entries, so the root resolves each package to that version
116
+ (npm workspaces: overrides are not applied to an existing lockfile)."""
117
+ data = load(text)
118
+ deps = data.setdefault("dependencies", {})
119
+ for name, version in pins.items():
120
+ deps[name] = version
121
+ return dump(data, text)
patchloop/js/ranges.py ADDED
@@ -0,0 +1,130 @@
1
+ """npm semver ranges in package.json: does a range allow a version, and the smallest edit
2
+ that makes it allow a fixed one, kept in the range's own style.
3
+
4
+ Covers ``^`` ``~`` exact, comparators (``>=1.2 <2``), x-ranges (``1.x``, ``1.2``, ``*``),
5
+ hyphen ranges (``1.2 - 2.3``) and ``||``. A spec that is not a range (a git URL, a path,
6
+ ``workspace:``, ``npm:`` aliases, ``patch:``, pnpm ``catalog:``, a dist-tag such as
7
+ ``latest``) is not from the registry by version: :func:`is_range` says so and PatchLoop
8
+ leaves it alone.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+
15
+ from packaging.specifiers import InvalidSpecifier, SpecifierSet
16
+ from packaging.version import InvalidVersion, Version
17
+
18
+ from patchloop.specifiers import SpecifierEditError, adjust_specifier, poetry_specifier
19
+
20
+ _NOT_A_RANGE = re.compile(
21
+ r"^(git|git\+|https?:|file:|link:|workspace:|npm:|github:|patch:|portal:|exec:|catalog:"
22
+ r"|[\w.-]+/[\w.-]+$)"
23
+ )
24
+ _OP_GAP = re.compile(r"(<=|>=|<|>|=|\^|~)\s*v?")
25
+ _PARTIAL = re.compile(r"^[vV]?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?$")
26
+ _HYPHEN = re.compile(r"^\s*(\S+)\s+-\s+(\S+)\s*$")
27
+
28
+
29
+ def is_range(spec: str) -> bool:
30
+ s = spec.strip()
31
+ if _NOT_A_RANGE.match(s):
32
+ return False
33
+ return s in ("", "*", "x", "X") or bool(re.search(r"\d", s))
34
+
35
+
36
+ def _partial_bounds(text: str) -> tuple[str, str | None] | None:
37
+ """'1' -> ('1', '2'), '1.2' / '1.2.x' -> ('1.2', '1.3'), '1.2.3' -> None (exact)."""
38
+ m = _PARTIAL.match(text)
39
+ if not m:
40
+ return None
41
+ parts = [p for p in m.groups() if p is not None and p not in ("x", "X", "*")]
42
+ if len(parts) == 3:
43
+ return None
44
+ if not parts:
45
+ return "0", None
46
+ major = int(parts[0])
47
+ if len(parts) == 1:
48
+ return f"{major}", f"{major + 1}"
49
+ minor = int(parts[1])
50
+ return f"{major}.{minor}", f"{major}.{minor + 1}"
51
+
52
+
53
+ def _tidy(alt: str) -> str:
54
+ """'>= 1.2.3' / '^v1.2' -> '>=1.2.3' / '^1.2': npm allows a space or a 'v' after an
55
+ operator."""
56
+ return _OP_GAP.sub(r"\1", alt.strip())
57
+
58
+
59
+ def _comparator(token: str) -> str | None:
60
+ """A comparator on a partial version, the way npm reads it ('<=1.2' is '<1.3')."""
61
+ m = re.fullmatch(r"(<=|>=|<|>)(\d+(?:\.\d+)?)", token)
62
+ if not m:
63
+ return None
64
+ op, ver = m.groups()
65
+ bounds = _partial_bounds(ver)
66
+ if bounds is None or bounds[1] is None:
67
+ return None
68
+ low, high = bounds
69
+ return {"<=": f"<{high}", ">": f">={high}", "<": f"<{low}", ">=": f">={low}"}[op]
70
+
71
+
72
+ def _alternative(alt: str) -> SpecifierSet:
73
+ alt = _tidy(alt)
74
+ if alt in ("", "*", "x", "X", "latest"):
75
+ return SpecifierSet()
76
+ hyphen = _HYPHEN.match(alt)
77
+ if hyphen:
78
+ low, high = hyphen.groups()
79
+ upper = _partial_bounds(high)
80
+ high_spec = f"<{upper[1]}" if upper and upper[1] else f"<={high}"
81
+ return SpecifierSet(f">={low.rstrip('.xX*')},{high_spec}")
82
+ specs: list[str] = []
83
+ for token in alt.split():
84
+ if (partial := _comparator(token)) is not None:
85
+ specs.append(partial)
86
+ continue
87
+ bare = token.lstrip("=v")
88
+ bounds = _partial_bounds(bare) if token[:1].isdigit() or token[:1] in "vVxX*=" else None
89
+ if bounds is not None:
90
+ low, high = bounds
91
+ specs.append(f">={low}")
92
+ if high:
93
+ specs.append(f"<{high}")
94
+ else:
95
+ specs.append(str(poetry_specifier(token.replace("=v", "=").lstrip("v"))))
96
+ return SpecifierSet(",".join(s for s in specs if s))
97
+
98
+
99
+ def allows(spec: str, version: str) -> bool:
100
+ if not is_range(spec):
101
+ return True # not a version range; PatchLoop does not plan around it
102
+ try:
103
+ v = Version(version)
104
+ except InvalidVersion:
105
+ return False
106
+ try:
107
+ return any(_alternative(a).contains(v, prereleases=True) for a in spec.split("||"))
108
+ except (InvalidSpecifier, InvalidVersion, ValueError):
109
+ return True # a range PatchLoop can't read (e.g. '^1.2.3-next.0'): leave it to npm
110
+
111
+
112
+ def raise_range(spec: str, target: str) -> str:
113
+ """Smallest rewrite of ``spec`` that allows ``target``, in the same style."""
114
+ s = _tidy(spec)
115
+ if "||" in s:
116
+ raise SpecifierEditError(f"cannot safely rewrite the range '{s}'")
117
+ if re.fullmatch(r"\^\s*v?\d+(\.\d+){0,2}", s):
118
+ return f"^{target}"
119
+ if re.fullmatch(r"~\s*v?\d+(\.\d+){0,2}", s):
120
+ return f"~{target}"
121
+ if re.fullmatch(r"=?v?\d+\.\d+\.\d+", s):
122
+ return target # exact pin stays exact
123
+ if _PARTIAL.match(s.lstrip("=v")):
124
+ return f"~{target}" # '1.2.x' that excludes the target -> the target's patch line
125
+ try:
126
+ new = adjust_specifier(_alternative(s), target)
127
+ except (InvalidSpecifier, InvalidVersion, ValueError) as exc:
128
+ raise SpecifierEditError(f"cannot read the range '{s}'") from exc
129
+ parts = sorted((str(x) for x in new), key=lambda x: (not x.startswith(">"), x))
130
+ return " ".join(p.replace("==", "") if p.startswith("==") else p for p in parts)
@@ -0,0 +1,67 @@
1
+ """Released versions of an npm package, from the public npm registry.
2
+
3
+ Pre-releases are skipped, and so are deprecated versions (the npm counterpart of PyPI's
4
+ yanked) unless a whole major line is deprecated: npm still installs those, and the fix may
5
+ only exist there.
6
+
7
+ A package the registry does not know (e.g. on a private registry) returns None, and the
8
+ planner falls back to the advisories' fixed versions.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+ from urllib.parse import quote
15
+
16
+ import httpx
17
+ from packaging.version import InvalidVersion, Version
18
+
19
+ from patchloop import __version__
20
+
21
+ REGISTRY = "https://registry.npmjs.org"
22
+ TIMEOUT_S = 20.0
23
+ # The abbreviated document lists versions and deprecation without READMEs.
24
+ _ACCEPT = "application/vnd.npm.install-v1+json"
25
+
26
+
27
+ def usable_versions(doc: dict[str, Any]) -> list[str]:
28
+ releases: list[tuple[Version, str, bool]] = []
29
+ for version, meta in (doc.get("versions") or {}).items():
30
+ try:
31
+ v = Version(version)
32
+ except InvalidVersion:
33
+ continue
34
+ if not v.is_prerelease:
35
+ releases.append((v, version, bool((meta or {}).get("deprecated"))))
36
+ live_majors = {v.major for v, _, deprecated in releases if not deprecated}
37
+ return [
38
+ text for v, text, deprecated in releases if not deprecated or v.major not in live_majors
39
+ ]
40
+
41
+
42
+ class NpmIndex:
43
+ def __init__(
44
+ self, client: httpx.Client | None = None, names: dict[str, str] | None = None
45
+ ) -> None:
46
+ self._names = names or {}
47
+ """lower-cased name -> name as written, from the lockfile."""
48
+ self._client = client or httpx.Client(
49
+ timeout=TIMEOUT_S,
50
+ headers={"User-Agent": f"patchloop/{__version__}", "Accept": _ACCEPT},
51
+ follow_redirects=True,
52
+ )
53
+ self._cache: dict[str, list[str] | None] = {}
54
+
55
+ def releases(self, package: str) -> list[str] | None:
56
+ if package not in self._cache:
57
+ try:
58
+ name = self._names.get(package, package)
59
+ response = self._client.get(f"{REGISTRY}/{quote(name, safe='@')}")
60
+ if response.status_code == 404:
61
+ self._cache[package] = None
62
+ else:
63
+ response.raise_for_status()
64
+ self._cache[package] = usable_versions(response.json())
65
+ except (httpx.HTTPError, ValueError):
66
+ self._cache[package] = None
67
+ return self._cache[package]
patchloop/js/yarn.py ADDED
@@ -0,0 +1,189 @@
1
+ """Pin a package to an exact version in yarn.lock without touching package.json.
2
+
3
+ yarn keys its lockfile by range (``lodash@^4.17.0``), so the pin-and-unpin trick used for
4
+ npm and pnpm does not work: dropping the pin makes yarn resolve the range afresh. Instead:
5
+
6
+ - Berry: ``yarn set resolution <descriptor> npm:<version>``, yarn's own command for this.
7
+ - Classic (v1), which has no such command: the entry for each matching range is rewritten
8
+ with the target's version, tarball URL, integrity and dependencies from the npm registry;
9
+ the next ``yarn install`` then adds the new version's own dependencies and checks it.
10
+
11
+ Only ranges that allow the target are pinned; a range that excludes it is a cap, handled
12
+ by the caller with ``resolutions``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from collections.abc import Callable
19
+ from pathlib import Path
20
+ from typing import Any
21
+ from urllib.parse import quote
22
+
23
+ import httpx
24
+ import yaml
25
+ from packaging.version import InvalidVersion, Version
26
+
27
+ from patchloop import __version__, proc
28
+ from patchloop.js.ranges import allows
29
+ from patchloop.js.registry import REGISTRY
30
+ from patchloop.proc import ToolNotFoundError, ToolTimeoutError
31
+
32
+
33
+ class YarnPinError(Exception):
34
+ """yarn.lock could not be pinned."""
35
+
36
+
37
+ def version_doc(package: str, version: str) -> dict[str, Any]:
38
+ url = f"{REGISTRY}/{quote(package, safe='@')}/{version}"
39
+ try:
40
+ response = httpx.get(url, timeout=20, headers={"User-Agent": f"patchloop/{__version__}"})
41
+ response.raise_for_status()
42
+ data: dict[str, Any] = response.json()
43
+ return data
44
+ except (httpx.HTTPError, ValueError) as exc:
45
+ raise YarnPinError(f"could not read {package}@{version} from the npm registry") from exc
46
+
47
+
48
+ def _range_of(descriptor: str) -> str:
49
+ descriptor = descriptor.strip().strip('"')
50
+ at = descriptor.find("@", 1)
51
+ spec = descriptor[at + 1 :] if at > 0 else ""
52
+ return spec.removeprefix("npm:")
53
+
54
+
55
+ def _name_of(descriptor: str) -> str:
56
+ descriptor = descriptor.strip().strip('"')
57
+ at = descriptor.find("@", 1)
58
+ return descriptor[:at] if at > 0 else descriptor
59
+
60
+
61
+ def _below(current: str | None, target: str) -> bool:
62
+ """``current`` is older than ``target`` (unknown versions count as older)."""
63
+ try:
64
+ return current is None or Version(current) < Version(target)
65
+ except InvalidVersion:
66
+ return True
67
+
68
+
69
+ # --- Berry -----------------------------------------------------------------------------
70
+
71
+
72
+ def berry_descriptors(
73
+ lockfile: Path, package: str, only_from: str | None, skip_version: str | None = None
74
+ ) -> list[str]:
75
+ """Descriptors of ``package`` (optionally only those locked at ``only_from``, and never
76
+ those already locked at ``skip_version``)."""
77
+ data = yaml.safe_load(lockfile.read_text("utf-8")) or {}
78
+ out = []
79
+ for key, entry in data.items():
80
+ if key == "__metadata" or not isinstance(entry, dict):
81
+ continue
82
+ if only_from is not None and str(entry.get("version")) != only_from:
83
+ continue
84
+ if skip_version is not None and not _below(str(entry.get("version")), skip_version):
85
+ continue # already there (yarn fails on that) or newer: never pin it down
86
+ for descriptor in str(key).split(","):
87
+ descriptor = descriptor.strip()
88
+ if _name_of(descriptor).lower() == package.lower() and "@npm:" in descriptor:
89
+ out.append(descriptor)
90
+ return out
91
+
92
+
93
+ def berry_pin(
94
+ run: Callable[[list[str]], None],
95
+ yarn: list[str],
96
+ lockfile: Path,
97
+ package: str,
98
+ version: str,
99
+ only_from: str | None = None,
100
+ ) -> int:
101
+ """Pin every matching range of ``package`` to ``version``; return how many are at it.
102
+
103
+ Ranges already locked at ``version`` count as pinned without a yarn call."""
104
+ already = len(berry_descriptors(lockfile, package, version))
105
+ pinned = 0
106
+ for descriptor in berry_descriptors(lockfile, package, only_from, skip_version=version):
107
+ if allows(_range_of(descriptor), version):
108
+ run([*yarn, "set", "resolution", descriptor, f"npm:{version}"])
109
+ pinned += 1
110
+ return pinned + already
111
+
112
+
113
+ # --- Classic ---------------------------------------------------------------------------
114
+
115
+ _BLOCK_HEAD = re.compile(r"^(\S.*):\s*$")
116
+
117
+
118
+ def _quote(name: str) -> str:
119
+ return f'"{name}"' if re.search(r"[@/:]", name) else name
120
+
121
+
122
+ def classic_pin(lockfile: Path, package: str, version: str, only_from: str | None = None) -> int:
123
+ """Rewrite the yarn.lock entries of ``package`` whose ranges allow ``version``."""
124
+ lines = lockfile.read_text("utf-8").splitlines()
125
+ doc: dict[str, Any] | None = None
126
+ out: list[str] = []
127
+ pinned = 0
128
+ i = 0
129
+ while i < len(lines):
130
+ line = lines[i]
131
+ head = _BLOCK_HEAD.match(line)
132
+ if not head:
133
+ out.append(line)
134
+ i += 1
135
+ continue
136
+ descriptors = [d.strip() for d in head.group(1).split(",")]
137
+ j = i + 1
138
+ while j < len(lines) and (lines[j].startswith(" ") or not lines[j].strip()):
139
+ j += 1
140
+ block = lines[i:j]
141
+ current = next((b.split('"')[1] for b in block if b.strip().startswith("version ")), None)
142
+ matches = [d for d in descriptors if _name_of(d).lower() == package.lower()]
143
+ if matches and current == version:
144
+ pinned += 1 # already at the target: nothing to rewrite
145
+ out.extend(block)
146
+ i = j
147
+ continue
148
+ wanted = (
149
+ matches
150
+ and (only_from is None or current == only_from)
151
+ and _below(current, version) # never pin a newer copy down
152
+ and all(allows(_range_of(d), version) for d in matches)
153
+ )
154
+ if not wanted:
155
+ out.extend(block)
156
+ i = j
157
+ continue
158
+ if doc is None:
159
+ doc = version_doc(_name_of(matches[0]), version) # the registry is case-sensitive
160
+ dist = doc.get("dist") or {}
161
+ out.append(line)
162
+ out.append(f' version "{version}"')
163
+ out.append(f' resolved "{dist.get("tarball")}#{dist.get("shasum")}"')
164
+ if dist.get("integrity"):
165
+ out.append(f" integrity {dist['integrity']}")
166
+ for section in ("dependencies", "optionalDependencies"):
167
+ deps = doc.get(section) or {}
168
+ if deps:
169
+ out.append(f" {section}:")
170
+ out.extend(f' {_quote(n)} "{r}"' for n, r in sorted(deps.items()))
171
+ trailing = [b for b in block[1:] if not b.strip()]
172
+ out.extend(trailing or [""])
173
+ pinned += 1
174
+ i = j
175
+ lockfile.write_text("\n".join(out).rstrip("\n") + "\n", "utf-8")
176
+ return pinned
177
+
178
+
179
+ def run_in(project_dir: Path, env: dict[str, str]) -> Callable[[list[str]], None]:
180
+ def run(cmd: list[str]) -> None:
181
+ try:
182
+ result = proc.run(cmd, cwd=project_dir, timeout=600, env=env)
183
+ except (ToolNotFoundError, ToolTimeoutError) as exc:
184
+ raise YarnPinError(f"{' '.join(cmd[:4])} failed: {exc}") from exc
185
+ if not result.ok:
186
+ detail = (result.stderr or result.stdout).strip().splitlines()[-1:] or ["no output"]
187
+ raise YarnPinError(f"{' '.join(cmd[:4])} failed: {detail[0]}")
188
+
189
+ return run
patchloop/lockgraph.py ADDED
@@ -0,0 +1,181 @@
1
+ """Dependency graph of a project: which packages are direct, and how others are pulled in."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from collections import deque
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from packaging.requirements import InvalidRequirement, Requirement
12
+
13
+ from patchloop.detect import project_name
14
+ from patchloop.models import JS_MANAGERS, Project, normalize_package
15
+
16
+ MAX_PATHS = 5
17
+
18
+
19
+ @dataclass
20
+ class LockGraph:
21
+ root: str
22
+ edges: dict[str, set[str]] = field(default_factory=dict)
23
+ """package -> packages it depends on (normalized names)."""
24
+ direct: set[str] = field(default_factory=set)
25
+ """Runtime direct dependencies of the project (incl. optional extras)."""
26
+ direct_dev: set[str] = field(default_factory=set)
27
+ """Direct dependencies that come only from dependency groups (dev)."""
28
+ ecosystem: str = "PyPI"
29
+
30
+ def is_direct(self, package: str) -> bool:
31
+ name = normalize_package(package, self.ecosystem)
32
+ return name in self.direct or name in self.direct_dev
33
+
34
+ def _reachable(self, starts: set[str]) -> set[str]:
35
+ seen: set[str] = set()
36
+ queue = deque(starts)
37
+ while queue:
38
+ node = queue.popleft()
39
+ if node in seen:
40
+ continue
41
+ seen.add(node)
42
+ queue.extend(self.edges.get(node, ()))
43
+ return seen
44
+
45
+ def is_dev_only(self, package: str) -> bool:
46
+ name = normalize_package(package, self.ecosystem)
47
+ return name not in self._reachable(self.direct) and name in self._reachable(self.direct_dev)
48
+
49
+ def paths_to(self, package: str) -> list[list[str]]:
50
+ """Shortest path from the project to ``package`` through each direct dependency."""
51
+ target = normalize_package(package, self.ecosystem)
52
+ paths: list[list[str]] = []
53
+ for first in sorted(self.direct | self.direct_dev):
54
+ path = self._shortest(first, target)
55
+ if path is not None:
56
+ paths.append([self.root, *path])
57
+ paths.sort(key=len)
58
+ return paths[:MAX_PATHS]
59
+
60
+ def _shortest(self, start: str, target: str) -> list[str] | None:
61
+ queue: deque[list[str]] = deque([[start]])
62
+ seen = {start}
63
+ while queue:
64
+ path = queue.popleft()
65
+ node = path[-1]
66
+ if node == target:
67
+ return path
68
+ for nxt in sorted(self.edges.get(node, ())):
69
+ if nxt not in seen:
70
+ seen.add(nxt)
71
+ queue.append([*path, nxt])
72
+ return None
73
+
74
+
75
+ def _names(entries: list[dict[str, Any]]) -> set[str]:
76
+ return {normalize_package(e["name"]) for e in entries}
77
+
78
+
79
+ def load_uv_graph(lockfile: Path, root_name: str) -> LockGraph:
80
+ """In a workspace, every member's dependencies are direct (uv.lock lists the members)."""
81
+ data = tomllib.loads(lockfile.read_text(encoding="utf-8"))
82
+ root = normalize_package(root_name)
83
+ graph = LockGraph(root=root)
84
+ manifest = data.get("manifest", {})
85
+ own = {root} | {normalize_package(m) for m in manifest.get("members", [])}
86
+ for group in (manifest.get("dependency-groups") or {}).values(): # a virtual root's groups
87
+ graph.direct_dev |= _names(group)
88
+ for pkg in data.get("package", []):
89
+ name = normalize_package(pkg["name"])
90
+ deps = _names(pkg.get("dependencies", []))
91
+ for extra in pkg.get("optional-dependencies", {}).values():
92
+ deps |= _names(extra)
93
+ if name in own:
94
+ graph.direct |= deps
95
+ for group in pkg.get("dev-dependencies", {}).values():
96
+ graph.direct_dev |= _names(group)
97
+ graph.edges.setdefault(name, set()).update(deps)
98
+ graph.direct -= own
99
+ graph.direct_dev -= graph.direct | own
100
+ graph.edges[root] = graph.direct | graph.direct_dev
101
+ return graph
102
+
103
+
104
+ def _requirement_names(specs: list[str]) -> set[str]:
105
+ names: set[str] = set()
106
+ for spec in specs:
107
+ try:
108
+ names.add(normalize_package(Requirement(spec).name))
109
+ except InvalidRequirement:
110
+ continue
111
+ return names
112
+
113
+
114
+ def load_poetry_graph(
115
+ pyproject: dict[str, Any], root_name: str, lockfile: Path | None = None
116
+ ) -> LockGraph:
117
+ """Direct packages from pyproject.toml; edges from poetry.lock's per-package dependencies."""
118
+ graph = LockGraph(root=normalize_package(root_name))
119
+ if lockfile is not None and lockfile.is_file():
120
+ data = tomllib.loads(lockfile.read_text(encoding="utf-8"))
121
+ for pkg in data.get("package", []):
122
+ deps = {normalize_package(n) for n in (pkg.get("dependencies") or {})}
123
+ graph.edges.setdefault(normalize_package(pkg["name"]), set()).update(deps)
124
+ project = pyproject.get("project", {})
125
+ graph.direct |= _requirement_names(project.get("dependencies", []))
126
+ for extra in (project.get("optional-dependencies") or {}).values():
127
+ graph.direct |= _requirement_names(extra)
128
+ poetry = pyproject.get("tool", {}).get("poetry", {})
129
+ graph.direct |= {normalize_package(n) for n in poetry.get("dependencies", {}) if n != "python"}
130
+ graph.direct_dev |= {normalize_package(n) for n in poetry.get("dev-dependencies", {})}
131
+ for group in poetry.get("group", {}).values():
132
+ graph.direct_dev |= {normalize_package(n) for n in group.get("dependencies", {})}
133
+ groups = (pyproject.get("dependency-groups") or {}).values()
134
+ graph.direct_dev |= {
135
+ n for g in groups for n in _requirement_names([s for s in g if isinstance(s, str)])
136
+ }
137
+ graph.direct_dev -= graph.direct
138
+ graph.edges[graph.root] = graph.direct | graph.direct_dev
139
+ return graph
140
+
141
+
142
+ def load_graph(project: Project) -> LockGraph:
143
+ if project.manager in JS_MANAGERS:
144
+ from patchloop.js.lockfiles import load_js_graph
145
+
146
+ return load_js_graph(project.root, project.manager, project.lockfile, project.members)
147
+ pyproject = tomllib.loads((project.root / "pyproject.toml").read_text(encoding="utf-8"))
148
+ name = project_name(pyproject) or project.root.name
149
+ if project.manager == "uv":
150
+ return load_uv_graph(project.lockfile, name)
151
+ return load_poetry_graph(pyproject, name, project.lockfile)
152
+
153
+
154
+ def project_lock_versions(project: Project) -> dict[str, str]:
155
+ """name -> locked version, for mapping image findings onto the lockfile."""
156
+ if project.manager in JS_MANAGERS:
157
+ from patchloop.js.lockfiles import lock_versions_js
158
+
159
+ return lock_versions_js(project.manager, project.lockfile)
160
+ return lock_versions(project.lockfile)
161
+
162
+
163
+ def lock_version_sets(lockfile: Path) -> dict[str, set[str]]:
164
+ """Normalized name -> every locked version (a package can be locked once per Python
165
+ version range: uv and Poetry "forks")."""
166
+ data = tomllib.loads(lockfile.read_text(encoding="utf-8"))
167
+ out: dict[str, set[str]] = {}
168
+ for p in data.get("package", []):
169
+ if "name" in p and "version" in p:
170
+ out.setdefault(normalize_package(p["name"]), set()).add(str(p["version"]))
171
+ return out
172
+
173
+
174
+ def lock_versions(lockfile: Path) -> dict[str, str]:
175
+ """Normalized package name -> locked version (uv.lock and poetry.lock share the shape)."""
176
+ data = tomllib.loads(lockfile.read_text(encoding="utf-8"))
177
+ return {
178
+ normalize_package(p["name"]): str(p["version"])
179
+ for p in data.get("package", [])
180
+ if "name" in p and "version" in p
181
+ }