lockly 0.1.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.
lockly/git.py ADDED
@@ -0,0 +1,96 @@
1
+ """Read lockfiles from git: which changed since a base, and their contents on
2
+ each side. Compares against the merge base, as a pull request's diff does,
3
+ so changes that landed on the base branch afterwards don't show up."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import posixpath
8
+ import subprocess
9
+ from pathlib import Path
10
+
11
+ from . import parsers
12
+ from .model import Lockfile, LockfileError
13
+
14
+
15
+ def _git(*args: str, cwd: str = ".") -> str:
16
+ try:
17
+ out = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, timeout=60)
18
+ except FileNotFoundError:
19
+ raise LockfileError("git isn't installed") from None
20
+ if out.returncode != 0:
21
+ raise LockfileError(f"git {' '.join(args[:2])} failed: {out.stderr.strip().splitlines()[-1] if out.stderr.strip() else 'unknown error'}")
22
+ return out.stdout
23
+
24
+
25
+ def root(cwd: str = ".") -> str:
26
+ return _git("rev-parse", "--show-toplevel", cwd=cwd).strip()
27
+
28
+
29
+ def merge_base(base: str, head: str | None, cwd: str) -> str:
30
+ try:
31
+ return _git("merge-base", base, head or "HEAD", cwd=cwd).strip()
32
+ except LockfileError:
33
+ pass
34
+ # Shallow CI checkouts may lack the history; the base itself will do.
35
+ try:
36
+ return _git("rev-parse", "--verify", "--quiet", base + "^{commit}", cwd=cwd).strip()
37
+ except LockfileError:
38
+ raise LockfileError(f"can't find '{base}' in this repository (in CI, fetch it first: "
39
+ f"git fetch origin {base})") from None
40
+
41
+
42
+ def _read(ref: str | None, path: str, repo: str) -> str | None:
43
+ """A file's contents at a ref, or in the working tree when ref is None.
44
+ None when it doesn't exist there."""
45
+ if ref is None:
46
+ p = Path(repo) / path
47
+ return p.read_text("utf-8") if p.is_file() else None
48
+ out = subprocess.run(["git", "show", f"{ref}:{path}"], cwd=repo, capture_output=True, text=True, timeout=60)
49
+ return out.stdout if out.returncode == 0 else None
50
+
51
+
52
+ def changed_lockfiles(base: str, head: str | None, paths: list[str], repo: str) -> list[str]:
53
+ args = ["diff", "--name-only", base] + ([head] if head else [])
54
+ names = _git(*args, "--", *paths, cwd=repo).splitlines()
55
+ if head is None:
56
+ names += _git("ls-files", "--others", "--exclude-standard", "--", *paths, cwd=repo).splitlines()
57
+ found = []
58
+ for name in sorted(set(names)):
59
+ if not parsers.is_lockfile(name):
60
+ continue
61
+ # go.mod is the lockfile in effect; a go.sum change is read through it.
62
+ if posixpath.basename(name) == "go.sum":
63
+ go_mod = posixpath.join(posixpath.dirname(name), "go.mod")
64
+ if _read(head, go_mod, repo) is not None or _read(base, go_mod, repo) is not None:
65
+ name = go_mod
66
+ if name not in found:
67
+ found.append(name)
68
+ return found
69
+
70
+
71
+ def load_pair(path: str, base: str, head: str | None, repo: str, kind: str = "") -> tuple[Lockfile, Lockfile]:
72
+ fmt = parsers.format_for(path, kind)
73
+ manifest = parsers.manifest_path(path, fmt)
74
+ sides = []
75
+ for ref in (base, head):
76
+ text = _read(ref, path, repo) or ""
77
+ man = _read(ref, manifest, repo) if manifest else None
78
+ sides.append(parsers.parse(path, text, man, kind))
79
+ return sides[0], sides[1]
80
+
81
+
82
+ def load_file(path: str, kind: str = "") -> Lockfile:
83
+ """A lockfile from disk, with its manifest from the same directory."""
84
+ p = Path(path)
85
+ try:
86
+ text = p.read_text("utf-8")
87
+ except FileNotFoundError:
88
+ raise LockfileError(f"{path}: no such file") from None
89
+ except OSError as exc:
90
+ raise LockfileError(f"{path}: can't read ({exc.strerror})") from None
91
+ fmt = parsers.format_for(path, kind)
92
+ manifest = None
93
+ if fmt.manifest:
94
+ m = p.with_name(fmt.manifest)
95
+ manifest = m.read_text("utf-8") if m.is_file() else None
96
+ return parsers.parse(path, text, manifest, kind)
lockly/html.py ADDED
@@ -0,0 +1,178 @@
1
+ """Self-contained, offline HTML report for a Diff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import datetime
7
+ import re
8
+ from html import escape
9
+ from importlib import resources
10
+
11
+ from . import __version__
12
+ from .diff import CHANGE_KINDS, Diff
13
+ from .render import CHANGE_TITLES, FINDING_TITLES, fixed_total, gating, plural, summary
14
+
15
+ # docs/brand/lockly-icon.svg, inlined so the report stays self-contained.
16
+ # Keep the two in sync.
17
+ _FAVICON_SVG = (
18
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'
19
+ '<rect width="64" height="64" rx="14" fill="#0a0d12"/>'
20
+ '<rect x="25" y="11" width="28" height="28" rx="6" fill="#0a0d12" stroke="#4f8cff" stroke-width="3.5"/>'
21
+ '<rect x="18" y="18" width="28" height="28" rx="6" fill="#0a0d12" stroke="#f5c84c" stroke-width="3.5"/>'
22
+ '<rect x="11" y="25" width="28" height="28" rx="6" fill="#0a0d12" stroke="#eef1f6" stroke-width="3.5"/>'
23
+ '<path d="M21.5 38.5v-3a3.5 3.5 0 0 1 7 0v3M19.5 38.5h11v8h-11z" fill="none" stroke="#ff4d5e" '
24
+ 'stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>'
25
+ '</svg>'
26
+ )
27
+
28
+ _STAT_SUBS = {
29
+ "added": "New in the lockfile",
30
+ "removed": "No longer installed",
31
+ "upgraded": "Moved to a newer version",
32
+ "downgraded": "Moved to an older version",
33
+ "changed": "Same version, new contents or source",
34
+ }
35
+
36
+
37
+ def _asset(name: str) -> bytes:
38
+ return resources.files("lockly").joinpath("assets", name).read_bytes()
39
+
40
+
41
+ def _b64(data: bytes) -> str:
42
+ return base64.b64encode(data).decode("ascii")
43
+
44
+
45
+ def _fill(template: str, values: dict[str, str]) -> str:
46
+ # One pass, so a placeholder-shaped string inside a package name can
47
+ # never be expanded by a later replacement.
48
+ return re.sub(r"\{\{([A-Z0-9_]+)\}\}", lambda m: values.get(m.group(1), m.group(0)), template)
49
+
50
+
51
+ def _stat(kind: str, label: str, number: int, sub: str) -> str:
52
+ zero = " zero" if number == 0 else ""
53
+ return (f'<div class="stat-card k-{kind}{zero}"><div class="stat-label">{escape(label)}</div>'
54
+ f'<div class="stat-number">{number}</div><div class="stat-sub">{escape(sub)}</div></div>')
55
+
56
+
57
+ def _lockfile_card(fd) -> str:
58
+ counts = ", ".join(f"{fd.count(k)} {k}" for k in CHANGE_KINDS if fd.count(k)) or "no changes"
59
+ rows = [("ecosystem", fd.ecosystem), ("format", fd.kind), ("changes", counts),
60
+ ("unchanged", str(fd.unchanged)), ("findings", str(sum(1 for f in fd.findings if f.gating)))]
61
+ items = "".join(f"<dt>{escape(k)}</dt><dd>{escape(v)}</dd>" for k, v in rows)
62
+ return f'<div class="sbom-card"><h2>{escape(fd.path)}</h2><dl>{items}</dl></div>'
63
+
64
+
65
+ def _findings(d: Diff) -> str:
66
+ if not d.findings:
67
+ return '<div class="empty">Nothing to review: no new install scripts, publishers, sources or vulnerabilities.</div>'
68
+ multi = len(d.files) > 1
69
+ cards = []
70
+ for f in d.findings:
71
+ kind = f.kind if f.gating else "info"
72
+ label = FINDING_TITLES[f.kind] + ("" if f.gating else " · info")
73
+ where = f'<span class="where">{escape(f.lockfile)}</span>' if multi else ""
74
+ cards.append(
75
+ f'<div class="finding k-{kind}"><span class="badge">{escape(label)}</span>'
76
+ f'<div class="finding-title">{escape(f.name)}<code>{escape(f.version)}</code>{where}</div>'
77
+ f'<div class="finding-msg">{escape(f.message)}</div></div>'
78
+ )
79
+ return f'<div class="findings">{"".join(cards)}</div>'
80
+
81
+
82
+ def _fixed(d: Diff) -> str:
83
+ n = fixed_total(d)
84
+ if not n:
85
+ return ""
86
+ names = sorted({k for f in d.files for k in f.fixed})
87
+ shown = ", ".join(names[:8]) + (" …" if len(names) > 8 else "")
88
+ return (f'<p class="fixed-note"><strong>{escape(plural(n, "known vulnerability", "known vulnerabilities"))} '
89
+ f"fixed</strong> by these changes: {escape(shown)}.</p>")
90
+
91
+
92
+ def _notes(d: Diff) -> str:
93
+ fixed = _fixed(d)
94
+ notes = "".join(f"<p>{escape(n)}</p>" for n in d.notes)
95
+ return fixed + (f'<div class="notes">{notes}</div>' if notes else "")
96
+
97
+
98
+ def _version_cell(kind: str, old: str, new: str) -> str:
99
+ if kind == "added":
100
+ return escape(new)
101
+ if kind == "removed":
102
+ return f'<span class="old">{escape(old)}</span>'
103
+ if old == new:
104
+ return escape(new)
105
+ return f'<span class="old">{escape(old)}</span><span class="sep">→</span>{escape(new)}'
106
+
107
+
108
+ def _changes(d: Diff) -> str:
109
+ changes = d.changes
110
+ if not changes:
111
+ return '<div class="empty">No dependencies were added, removed or changed version.</div>'
112
+ buttons = ['<button class="filter-btn" type="button" data-kind-filter="" aria-pressed="true">All</button>']
113
+ for kind in CHANGE_KINDS:
114
+ n = d.count(kind)
115
+ if n:
116
+ buttons.append(f'<button class="filter-btn k-{kind}" type="button" data-kind-filter="{kind}" '
117
+ f'aria-pressed="false">{escape(CHANGE_TITLES[kind])} {n}</button>')
118
+ multi = len(d.files) > 1
119
+ rows = []
120
+ for c in sorted(changes, key=lambda c: (not c.direct, CHANGE_KINDS.index(c.kind), c.name.lower())):
121
+ where = ("direct" if c.direct else "") + (" · dev" if c.dev else "")
122
+ where = where.strip(" ·")
123
+ search = " ".join((c.name, c.ecosystem, c.old_version, c.new_version, c.lockfile)).lower()
124
+ rows.append(
125
+ f'<tr data-kind="{c.kind}" data-search="{escape(search)}">'
126
+ f'<td><span class="badge k-{c.kind}">{escape(c.kind)}</span></td>'
127
+ f'<td class="pkg">{escape(c.name)}<small>{escape(c.ecosystem)}'
128
+ f'{" · " + escape(c.lockfile) if multi else ""}</small></td>'
129
+ f'<td class="ver">{_version_cell(c.kind, c.old_version, c.new_version)}</td>'
130
+ f'<td class="where">{escape(where) or "—"}</td></tr>'
131
+ )
132
+ return (
133
+ '<div class="controls">'
134
+ '<input class="search-input" id="changeSearch" type="search" '
135
+ 'placeholder="search package or version…" aria-label="Search changes" />'
136
+ f'{"".join(buttons)}<span class="result-count" id="resultCount"></span></div>'
137
+ '<div class="table-wrap"><table id="changesTable"><thead><tr>'
138
+ '<th>Change</th><th>Package</th><th>Version</th><th>Dependency</th>'
139
+ f'</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
140
+ )
141
+
142
+
143
+ def to_html(d: Diff, theme: str = "dark", title: str = "") -> str:
144
+ template = _asset("report.html").decode("utf-8")
145
+ flagged = len(gating(d))
146
+ if flagged:
147
+ badge_class, badge_text = "k-findings", f"{flagged} to review"
148
+ elif d.changes:
149
+ badge_class, badge_text = "k-upgraded", plural(len(d.changes), "change")
150
+ else:
151
+ badge_class, badge_text = "k-added", "no changes"
152
+
153
+ paths = [f.path for f in d.files]
154
+ hero = escape(title) if title else (escape(paths[0]) if len(paths) == 1 else escape(plural(len(paths), "lockfile")))
155
+ headline = summary(d) + (f" {plural(flagged, 'finding')} to review." if flagged else "")
156
+
157
+ stats = [_stat(k, CHANGE_TITLES[k], d.count(k), _STAT_SUBS[k]) for k in CHANGE_KINDS]
158
+ stats.append(_stat("findings", "Findings", flagged, "Worth a reviewer's look"))
159
+ stats.append(_stat("fixed", "Fixed", fixed_total(d), "Known vulnerabilities fixed"))
160
+
161
+ return _fill(template, {
162
+ "THEME_ATTR": ' data-theme="light"' if theme == "light" else "",
163
+ "FAVICON_B64": _b64(_FAVICON_SVG.encode()),
164
+ "FONT_DISPLAY_B64": _b64(_asset("space-grotesk-var.woff2")),
165
+ "FONT_MONO_B64": _b64(_asset("jetbrains-mono-var.woff2")),
166
+ "TITLE": escape(title or ", ".join(paths) or "lockfiles"),
167
+ "BADGE_CLASS": badge_class,
168
+ "BADGE_TEXT": escape(badge_text),
169
+ "HERO_TITLE": hero,
170
+ "HEADLINE": escape(headline),
171
+ "LOCKFILES": "".join(_lockfile_card(f) for f in d.files),
172
+ "STAT_CARDS": "".join(stats),
173
+ "FINDINGS": _findings(d),
174
+ "NOTES": _notes(d),
175
+ "CHANGES": _changes(d),
176
+ "VERSION": escape(__version__),
177
+ "REPORT_DATE": datetime.date.today().strftime("%d %b %Y"),
178
+ })
lockly/licenses.py ADDED
@@ -0,0 +1,150 @@
1
+ """Rough copyleft classification of licence expressions.
2
+
3
+ This is a triage signal for a reviewer, not legal advice: it decides which
4
+ licence changes deserve a second look.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ NONE, WEAK, STRONG, NETWORK = 0, 1, 2, 3
12
+
13
+ LABELS = {
14
+ NONE: "permissive or unknown",
15
+ WEAK: "weak copyleft",
16
+ STRONG: "strong copyleft",
17
+ NETWORK: "network copyleft",
18
+ }
19
+
20
+ # Checked in order; the first match wins, so the narrower names come first
21
+ # (LGPL before GPL, AGPL before GPL).
22
+ _ID_RULES: list[tuple[re.Pattern[str], int]] = [
23
+ (re.compile(r"^(AGPL|SSPL)", re.I), NETWORK),
24
+ (re.compile(r"^(LGPL|MPL|EPL|CDDL|CPL|MS-RL|EUPL)", re.I), WEAK),
25
+ (re.compile(r"^(GPL|OSL|RPL|Sleepycat|CC-BY-SA|CC-BY-NC-SA)", re.I), STRONG),
26
+ ]
27
+
28
+ # Free-text names, for metadata that carries "GNU General Public License v3"
29
+ # instead of an SPDX id.
30
+ _NAME_RULES: list[tuple[re.Pattern[str], int]] = [
31
+ (re.compile(r"affero|server side public", re.I), NETWORK),
32
+ (re.compile(r"(lesser|library) general public|mozilla public|eclipse public|common development and distribution", re.I), WEAK),
33
+ (re.compile(r"general public licen[cs]e|\bgnu gpl\b", re.I), STRONG),
34
+ ]
35
+
36
+ # Exceptions that let you link without the copyleft reaching your code.
37
+ _LINKING_EXCEPTION = re.compile(r"classpath|linking|gcc-exception|llvm-exception|autoconf", re.I)
38
+
39
+
40
+ def _classify_term(term: str) -> int:
41
+ term = term.strip()
42
+ if not term:
43
+ return NONE
44
+ parts = re.split(r"\s+WITH\s+", term, maxsplit=1, flags=re.I)
45
+ base = parts[0]
46
+ exception = parts[1] if len(parts) > 1 else ""
47
+ level = NONE
48
+ for pattern, rule_level in _ID_RULES:
49
+ if pattern.match(base):
50
+ level = rule_level
51
+ break
52
+ else:
53
+ for pattern, rule_level in _NAME_RULES:
54
+ if pattern.search(base):
55
+ level = rule_level
56
+ break
57
+ if level == STRONG and _LINKING_EXCEPTION.search(exception):
58
+ return WEAK
59
+ return level
60
+
61
+
62
+ # Trove classifier names and common spellings, for registries (PyPI) that
63
+ # give those instead of SPDX ids.
64
+ _ALIASES = {
65
+ "mit license": "MIT", "the mit license": "MIT", "mit/x11": "MIT",
66
+ "apache software license": "Apache-2.0", "apache 2.0": "Apache-2.0", "apache license 2.0": "Apache-2.0",
67
+ "apache license, version 2.0": "Apache-2.0", "apache-2": "Apache-2.0", "apache 2": "Apache-2.0",
68
+ "bsd license": "BSD", "isc license (iscl)": "ISC", "isc license": "ISC",
69
+ "mozilla public license 2.0 (mpl 2.0)": "MPL-2.0", "python software foundation license": "PSF-2.0",
70
+ "the unlicense (unlicense)": "Unlicense",
71
+ }
72
+
73
+
74
+ def _canonical(expression: str) -> str:
75
+ text = expression.strip()
76
+ if text.lower() in _ALIASES:
77
+ return _ALIASES[text.lower()]
78
+ # 'Apache-2.0 license', 'MIT License': the id with a word on the end.
79
+ if text.lower().endswith(" license") and " " not in text[:-8].strip():
80
+ text = text[:-8].strip()
81
+ # Cargo's old 'MIT/Apache-2.0' is 'MIT OR Apache-2.0'.
82
+ if "/" in text and " " not in text:
83
+ text = " OR ".join(p.strip() for p in text.split("/"))
84
+ return text
85
+
86
+
87
+ def normalise(expression: str) -> str:
88
+ """A comparison key: 'MPL-2.0 AND MIT' and 'mit and mpl-2.0' are the same licence.
89
+
90
+ Only flat expressions (one operator, no brackets) are reordered; anything
91
+ more involved is compared as written, give or take case and spacing.
92
+ """
93
+ text = " ".join(_canonical(expression).split()).casefold()
94
+ if "(" in text or ")" in text:
95
+ return text
96
+ for op in (" and ", " or "):
97
+ terms = text.split(op)
98
+ if len(terms) > 1 and not any((" and " if op == " or " else " or ") in t for t in terms):
99
+ return op.join(sorted(terms))
100
+ return text
101
+
102
+
103
+ def copyleft_level(expression: str) -> int:
104
+ """The least restrictive option the expression allows.
105
+
106
+ 'MIT OR GPL-3.0' lets you pick MIT, so it scores as permissive.
107
+ 'MIT AND GPL-3.0' binds you to both, so it scores as strong copyleft.
108
+ AND binds tighter than OR, as in the SPDX spec.
109
+ """
110
+ tokens = re.findall(r"\(|\)|[^\s()]+", expression)
111
+ pos = 0
112
+
113
+ def peek() -> str:
114
+ return tokens[pos].upper() if pos < len(tokens) else ""
115
+
116
+ def atom() -> int:
117
+ nonlocal pos
118
+ if peek() == "(":
119
+ pos += 1
120
+ level = either()
121
+ if peek() == ")":
122
+ pos += 1
123
+ return level
124
+ # A licence term runs until an operator or bracket, so free-text
125
+ # names with spaces and "X WITH exception" stay in one piece.
126
+ words = []
127
+ while pos < len(tokens) and peek() not in ("AND", "OR", "(", ")"):
128
+ words.append(tokens[pos])
129
+ pos += 1
130
+ if not words and pos < len(tokens) and peek() != ")":
131
+ pos += 1 # A stray operator; skip it rather than loop.
132
+ return _classify_term(" ".join(words))
133
+
134
+ def both() -> int:
135
+ nonlocal pos
136
+ level = atom()
137
+ while peek() == "AND":
138
+ pos += 1
139
+ level = max(level, atom())
140
+ return level
141
+
142
+ def either() -> int:
143
+ nonlocal pos
144
+ level = both()
145
+ while peek() == "OR":
146
+ pos += 1
147
+ level = min(level, both())
148
+ return level
149
+
150
+ return either() if tokens else NONE
lockly/miniyaml.py ADDED
@@ -0,0 +1,184 @@
1
+ """Just enough YAML to read pnpm-lock.yaml and Yarn Berry's yarn.lock.
2
+
3
+ Both are machine-written with a narrow, consistent style: block mappings
4
+ indented by two spaces, block sequences of scalars, flow mappings and
5
+ sequences one level deep ({integrity: sha512-...}, [x64]), and single- or
6
+ double-quoted scalars. This reads that and nothing more: no anchors, tags,
7
+ multi-line strings or documents. Anything else raises ValueError, so a
8
+ change in either tool's output fails loudly rather than misreading.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+
15
+ _COMMENT = re.compile(r"(^|\s)#.*$")
16
+
17
+
18
+ def _scalar(text: str):
19
+ text = text.strip()
20
+ if not text:
21
+ return None
22
+ if text[0] in "'\"":
23
+ return _quoted(text)
24
+ if text.startswith("{"):
25
+ return _flow_map(text)
26
+ if text.startswith("["):
27
+ return _flow_seq(text)
28
+ if text in ("null", "~"):
29
+ return None
30
+ if text == "true":
31
+ return True
32
+ if text == "false":
33
+ return False
34
+ return text # numbers stay strings: versions like 1.10 must not become floats
35
+
36
+
37
+ def _quoted(text: str) -> str:
38
+ quote = text[0]
39
+ if not text.endswith(quote) or len(text) < 2:
40
+ raise ValueError(f"unterminated string: {text[:40]}")
41
+ body = text[1:-1]
42
+ if quote == "'":
43
+ return body.replace("''", "'")
44
+ return body.encode("utf-8").decode("unicode_escape") if "\\" in body else body
45
+
46
+
47
+ def _split_flow(body: str) -> list[str]:
48
+ """Split a flow collection's body on top-level commas."""
49
+ parts, depth, current, quote = [], 0, [], ""
50
+ for ch in body:
51
+ if quote:
52
+ current.append(ch)
53
+ if ch == quote:
54
+ quote = ""
55
+ continue
56
+ if ch in "'\"":
57
+ quote = ch
58
+ elif ch in "{[":
59
+ depth += 1
60
+ elif ch in "}]":
61
+ depth -= 1
62
+ elif ch == "," and depth == 0:
63
+ parts.append("".join(current))
64
+ current = []
65
+ continue
66
+ current.append(ch)
67
+ if "".join(current).strip():
68
+ parts.append("".join(current))
69
+ return parts
70
+
71
+
72
+ def _flow_map(text: str) -> dict:
73
+ if not text.endswith("}"):
74
+ raise ValueError(f"unterminated flow mapping: {text[:40]}")
75
+ out = {}
76
+ for part in _split_flow(text[1:-1]):
77
+ key, value = _split_key(part.strip())
78
+ out[key] = _scalar(value)
79
+ return out
80
+
81
+
82
+ def _flow_seq(text: str) -> list:
83
+ if not text.endswith("]"):
84
+ raise ValueError(f"unterminated flow sequence: {text[:40]}")
85
+ return [_scalar(p) for p in _split_flow(text[1:-1])]
86
+
87
+
88
+ def _split_key(line: str) -> tuple[str, str]:
89
+ """'key: value' → (key, value), honouring quoted keys with colons in them."""
90
+ if line[:1] in "'\"":
91
+ quote = line[0]
92
+ end = 1
93
+ while True:
94
+ end = line.index(quote, end)
95
+ if quote == "'" and line[end + 1:end + 2] == "'":
96
+ end += 2
97
+ continue
98
+ break
99
+ key = _quoted(line[:end + 1])
100
+ rest = line[end + 1:]
101
+ if not rest.startswith(":"):
102
+ raise ValueError(f"expected ':' after key: {line[:60]}")
103
+ return key, rest[1:]
104
+ # A plain key ends at the first ': ' or a trailing ':', so keys like
105
+ # pnpm 5's file:playground/x: keep their inner colons.
106
+ m = re.match(r"^(.*?):(\s|$)(.*)$", line)
107
+ if not m:
108
+ raise ValueError(f"not a key: {line[:60]}")
109
+ return m.group(1).strip(), m.group(3)
110
+
111
+
112
+ def loads_all(text: str) -> list:
113
+ """Every document in the stream. pnpm 10 writes two: its own install
114
+ first, then the project's lockfile."""
115
+ docs, current = [], []
116
+ for raw in text.splitlines():
117
+ if raw.rstrip() == "---":
118
+ docs.append(current)
119
+ current = []
120
+ continue
121
+ current.append(raw)
122
+ docs.append(current)
123
+ return [_load_lines(d) for d in docs if any(line.strip() and not line.lstrip().startswith("#") for line in d)]
124
+
125
+
126
+ def loads(text: str):
127
+ docs = loads_all(text)
128
+ return docs[-1] if docs else None
129
+
130
+
131
+ def _load_lines(raw_lines: list[str]):
132
+ lines = []
133
+ for raw in raw_lines:
134
+ if not raw.strip() or raw.lstrip().startswith("#"):
135
+ continue
136
+ stripped = raw.rstrip()
137
+ indent = len(stripped) - len(stripped.lstrip(" "))
138
+ lines.append((indent, stripped.lstrip(" ")))
139
+ value, pos = _block(lines, 0, 0)
140
+ if pos != len(lines):
141
+ raise ValueError(f"unexpected indentation near: {lines[pos][1][:60]}")
142
+ return value
143
+
144
+
145
+ def _block(lines, pos, indent):
146
+ if pos >= len(lines):
147
+ return None, pos
148
+ if lines[pos][1].startswith("- ") or lines[pos][1] == "-":
149
+ return _sequence(lines, pos, lines[pos][0])
150
+ return _mapping(lines, pos, lines[pos][0])
151
+
152
+
153
+ def _sequence(lines, pos, indent):
154
+ out = []
155
+ while pos < len(lines) and lines[pos][0] == indent and (lines[pos][1].startswith("- ") or lines[pos][1] == "-"):
156
+ item = lines[pos][1][2:]
157
+ pos += 1
158
+ if item.strip():
159
+ out.append(_scalar(item))
160
+ else:
161
+ value, pos = _block(lines, pos, indent + 1)
162
+ out.append(value)
163
+ return out, pos
164
+
165
+
166
+ def _mapping(lines, pos, indent):
167
+ out: dict = {}
168
+ while pos < len(lines) and lines[pos][0] == indent:
169
+ text = lines[pos][1]
170
+ if text.startswith("- "):
171
+ break
172
+ key, rest = _split_key(text)
173
+ pos += 1
174
+ rest = _COMMENT.sub("", rest) if "#" in rest and rest.strip()[:1] not in "'\"" else rest
175
+ if rest.strip():
176
+ out[key] = _scalar(rest)
177
+ elif pos < len(lines) and lines[pos][0] > indent:
178
+ out[key], pos = _block(lines, pos, lines[pos][0])
179
+ elif pos < len(lines) and lines[pos][0] == indent and lines[pos][1].startswith("- "):
180
+ # A sequence written at the same indent as its key (allowed in YAML).
181
+ out[key], pos = _sequence(lines, pos, indent)
182
+ else:
183
+ out[key] = None
184
+ return out, pos
lockly/model.py ADDED
@@ -0,0 +1,58 @@
1
+ """Packages read from a lockfile, the same shape whatever the format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+
8
+ # OSV's names for the ecosystems, used everywhere so lookups need no mapping.
9
+ NPM, PYPI, GO, CARGO = "npm", "PyPI", "Go", "crates.io"
10
+
11
+
12
+ class LockfileError(Exception):
13
+ pass
14
+
15
+
16
+ @dataclass
17
+ class Package:
18
+ ecosystem: str
19
+ name: str
20
+ version: str
21
+ # True: the project depends on it directly. False: only through another
22
+ # package. None: the lockfile doesn't say and no manifest was found.
23
+ direct: bool | None = None
24
+ dev: bool = False
25
+ # Where it comes from: a registry host, "git", "path" or a URL. Empty
26
+ # means the ecosystem's default registry.
27
+ source: str = ""
28
+ integrity: str = ""
29
+ license: str = ""
30
+ # True only when the lockfile records it (npm's hasInstallScript,
31
+ # pnpm's requiresBuild); None when the format can't tell.
32
+ install_script: bool | None = None
33
+ # When this version was published, if the lockfile records it (uv does).
34
+ published: str = ""
35
+
36
+ @property
37
+ def key(self) -> tuple[str, str]:
38
+ return self.ecosystem, normalise_name(self.ecosystem, self.name)
39
+
40
+
41
+ def normalise_name(ecosystem: str, name: str) -> str:
42
+ if ecosystem == PYPI:
43
+ return re.sub(r"[-_.]+", "-", name).lower() # PEP 503
44
+ if ecosystem == CARGO:
45
+ return name.replace("_", "-").lower()
46
+ return name
47
+
48
+
49
+ @dataclass
50
+ class Lockfile:
51
+ path: str
52
+ kind: str # package-lock, yarn, pnpm, uv, poetry, pipfile, go, cargo
53
+ ecosystem: str
54
+ packages: list[Package] = field(default_factory=list)
55
+
56
+ @property
57
+ def label(self) -> str:
58
+ return self.path