lean-pkg 0.25.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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/__init__.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# lean-pkg search adapters -- one module per public source
|
|
2
|
+
"""Network adapters for `lean-pkg search`, one module each: loogle, leansearch,
|
|
3
|
+
reservoir, palomar, github. Each exposes `NAME`, `search(term, timeout=10) -> dict`
|
|
4
|
+
and `revision() -> str | None`.
|
|
5
|
+
|
|
6
|
+
A result is {"state": "ok" | "skipped", "reason": str | None, "revision": str | None,
|
|
7
|
+
"hits": [{"name", "summary", "url", "extra"}]}. An unreachable source is `skipped`
|
|
8
|
+
with a reason, never zero hits. With state `ok`, `reason` may carry a note.
|
|
9
|
+
|
|
10
|
+
All I/O goes through `http_get` and `run_cmd` below, which call the module
|
|
11
|
+
attributes `urlopen` and `subprocess_run`; the test suite replaces both so no test
|
|
12
|
+
can reach the network or run `gh`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import pathlib
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import urllib.error
|
|
23
|
+
import urllib.parse
|
|
24
|
+
import urllib.request
|
|
25
|
+
|
|
26
|
+
USER_AGENT = "lean-pkg"
|
|
27
|
+
urlopen = urllib.request.urlopen
|
|
28
|
+
subprocess_run = subprocess.run
|
|
29
|
+
_WORD = re.compile(r"[\W_]+", re.UNICODE)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fold(text) -> str:
|
|
33
|
+
"""NFKD, strip combining marks, casefold: Itô -> ito, Black–Scholes keeps its words. The one folding
|
|
34
|
+
used by every search source (lean_pkg.search imports it), applied to the term and the text alike."""
|
|
35
|
+
import unicodedata
|
|
36
|
+
s = unicodedata.normalize("NFKD", str(text or ""))
|
|
37
|
+
return "".join(ch for ch in s if not unicodedata.combining(ch)).casefold()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def http_get(url: str, body: bytes | None = None, timeout: float = 10) -> tuple[int, bytes] | None:
|
|
41
|
+
"""(status, body bytes); an HTTP error gives (status, b""); None when unreachable.
|
|
42
|
+
With `body`, the request is a POST of JSON."""
|
|
43
|
+
headers = {"User-Agent": USER_AGENT}
|
|
44
|
+
if body is not None:
|
|
45
|
+
headers["Content-Type"] = "application/json"
|
|
46
|
+
req = urllib.request.Request(url, data=body, headers=headers)
|
|
47
|
+
try:
|
|
48
|
+
with urlopen(req, timeout=timeout) as r:
|
|
49
|
+
return int(r.status), r.read()
|
|
50
|
+
except urllib.error.HTTPError as e:
|
|
51
|
+
return int(e.code), b""
|
|
52
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError):
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def run_cmd(argv: list[str], timeout: float = 120) -> tuple[int, bytes, str] | None:
|
|
57
|
+
"""(returncode, stdout bytes, stderr text); None when the program is not installed."""
|
|
58
|
+
if shutil.which(argv[0]) is None:
|
|
59
|
+
return None
|
|
60
|
+
try:
|
|
61
|
+
p = subprocess_run(argv, capture_output=True, timeout=timeout, check=False)
|
|
62
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
63
|
+
return 1, b"", type(e).__name__
|
|
64
|
+
return p.returncode, p.stdout, p.stderr.decode("utf-8", errors="replace")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ok(revision: str | None, hits: list[dict], reason: str | None = None,
|
|
68
|
+
partial: list[str] | None = None, capped: list[str] | None = None,
|
|
69
|
+
cap_limit: int | None = None, total: int | None = None) -> dict:
|
|
70
|
+
"""`partial` names the parts of the source that failed (GitHub's `code` search): the source answered,
|
|
71
|
+
but a zero from it is not a negative result. `capped` names the parts that returned exactly their
|
|
72
|
+
result limit `cap_limit`: more matches may exist beyond the ones listed. `total` is how many matches the
|
|
73
|
+
source found when it lists fewer: more than len(hits) marks the `results` part capped at len(hits)."""
|
|
74
|
+
r = {"state": "ok", "reason": reason, "revision": revision, "hits": hits}
|
|
75
|
+
if partial:
|
|
76
|
+
r["partial"] = list(partial)
|
|
77
|
+
capped = list(capped or [])
|
|
78
|
+
if isinstance(total, int) and total > len(hits):
|
|
79
|
+
capped.append("results")
|
|
80
|
+
cap_limit = cap_limit or len(hits)
|
|
81
|
+
r["total"] = total
|
|
82
|
+
if capped:
|
|
83
|
+
r["capped"], r["cap_limit"] = capped, cap_limit
|
|
84
|
+
return r
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def skipped(reason: str, revision: str | None = None) -> dict:
|
|
88
|
+
return {"state": "skipped", "reason": reason, "revision": revision, "hits": []}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def one_line(s, limit: int = 200) -> str:
|
|
92
|
+
s = " ".join(str(s or "").split())
|
|
93
|
+
return s if len(s) <= limit else s[:limit - 3] + "..."
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def hit(name, summary, url, **extra) -> dict:
|
|
97
|
+
return {"name": str(name), "summary": one_line(summary), "url": url, "extra": extra}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def words(text) -> list[str]:
|
|
101
|
+
return [w for w in _WORD.split(fold(text)) if w]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def matches(term: str, *texts) -> bool:
|
|
105
|
+
"""Every word of the term occurs in the texts (substring, case- and accent-insensitive: both sides
|
|
106
|
+
folded), like a `grep -i` per word over descriptions: 'Fisher-Tippett' matches 'Fisher-Tippett-Gnedenko',
|
|
107
|
+
'Godel' matches 'Gödel'."""
|
|
108
|
+
hay = fold(" ".join(str(t or "") for t in texts))
|
|
109
|
+
ws = words(term)
|
|
110
|
+
return bool(ws) and all(w in hay for w in ws)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# `search --cache-dir DIR` sets CACHE_ROOT for one run; otherwise $XDG_CACHE_HOME/lean-pkg, else ~/.cache/lean-pkg.
|
|
114
|
+
CACHE_ROOT: pathlib.Path | None = None
|
|
115
|
+
# What the adapters wrote under the cache root during the current source (paths relative to it): a search
|
|
116
|
+
# without --record still refreshes Palomar's snapshot and Reservoir's index, and says so (field report).
|
|
117
|
+
CACHE_WRITES: list[str] = []
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cache_root() -> pathlib.Path:
|
|
121
|
+
"""The lean-pkg cache directory: CACHE_ROOT (`--cache-dir`), else $XDG_CACHE_HOME/lean-pkg, else
|
|
122
|
+
~/.cache/lean-pkg."""
|
|
123
|
+
if CACHE_ROOT is not None:
|
|
124
|
+
return pathlib.Path(CACHE_ROOT).expanduser()
|
|
125
|
+
base = os.environ.get("XDG_CACHE_HOME", "").strip() or str(pathlib.Path.home() / ".cache")
|
|
126
|
+
return pathlib.Path(base).expanduser() / "lean-pkg"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def cache_root_source() -> str:
|
|
130
|
+
"""Where the cache root came from: `--cache-dir`, `XDG_CACHE_HOME` or `default` (~/.cache/lean-pkg)."""
|
|
131
|
+
if CACHE_ROOT is not None:
|
|
132
|
+
return "--cache-dir"
|
|
133
|
+
return "XDG_CACHE_HOME" if os.environ.get("XDG_CACHE_HOME", "").strip() else "default"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cache_dir(*parts: str) -> pathlib.Path:
|
|
137
|
+
"""<cache root>/<parts>: see cache_root()."""
|
|
138
|
+
return cache_root().joinpath(*parts)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def note_cache_write(*parts: str) -> None:
|
|
142
|
+
"""Record that an adapter wrote <cache root>/<parts> (relative, so no host path reaches the output)."""
|
|
143
|
+
CACHE_WRITES.append("/".join(parts))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def docs_url(decl: str) -> str:
|
|
147
|
+
return "https://leanprover-community.github.io/mathlib4_docs/find/?pattern=" + \
|
|
148
|
+
urllib.parse.quote(decl, safe="") + "#doc"
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""GitHub long tail through `gh search repos` and `gh search code` (Lean only).
|
|
2
|
+
|
|
3
|
+
The term always follows `--`, so a term that starts with a dash is never read
|
|
4
|
+
as a flag. Unlicensed hits can be cited, not copied.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from . import hit, ok, run_cmd, skipped
|
|
12
|
+
|
|
13
|
+
NAME = "github"
|
|
14
|
+
LIMIT = "30"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def runner(argv: list[str], timeout: float = 60):
|
|
18
|
+
return run_cmd(argv, timeout)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def revision() -> str:
|
|
22
|
+
return "live"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _json(r):
|
|
26
|
+
if r is None or r[0] != 0:
|
|
27
|
+
return None, (r[2].strip().splitlines()[0][:120] if r and r[2].strip() else "failed")
|
|
28
|
+
try:
|
|
29
|
+
data = json.loads(r[1])
|
|
30
|
+
except ValueError:
|
|
31
|
+
return None, "answer is not JSON"
|
|
32
|
+
return (data, None) if isinstance(data, list) else (None, "unexpected answer")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def search(term: str, timeout: float = 30) -> dict:
|
|
36
|
+
repos_r = runner(["gh", "search", "repos", "--language", "Lean", "--limit", LIMIT, "--json",
|
|
37
|
+
"fullName,description,stargazersCount,license,updatedAt", "--", term], timeout)
|
|
38
|
+
if repos_r is None:
|
|
39
|
+
return skipped("gh not installed")
|
|
40
|
+
code_r = runner(["gh", "search", "code", "--language", "Lean", "--limit", LIMIT, "--json",
|
|
41
|
+
"repository,path,url", "--", term], timeout)
|
|
42
|
+
repos, repos_err = _json(repos_r)
|
|
43
|
+
code, code_err = _json(code_r)
|
|
44
|
+
if repos is None and code is None:
|
|
45
|
+
return skipped(f"gh search failed: {repos_err}")
|
|
46
|
+
hits = []
|
|
47
|
+
for r in repos or []:
|
|
48
|
+
if isinstance(r, dict) and r.get("fullName"):
|
|
49
|
+
lic = r.get("license") if isinstance(r.get("license"), dict) else {}
|
|
50
|
+
hits.append(hit(r["fullName"], r.get("description"), f"https://github.com/{r['fullName']}",
|
|
51
|
+
kind="repo", stars=r.get("stargazersCount"), license=lic.get("key")))
|
|
52
|
+
for c in code or []:
|
|
53
|
+
repo = (c.get("repository") or {}).get("nameWithOwner") if isinstance(c, dict) else None
|
|
54
|
+
if repo and c.get("path"):
|
|
55
|
+
hits.append(hit(f"{repo}:{c['path']}", "", c.get("url") or f"https://github.com/{repo}",
|
|
56
|
+
kind="code"))
|
|
57
|
+
note, partial = None, []
|
|
58
|
+
if repos is None:
|
|
59
|
+
note, partial = f"repository search failed: {repos_err}", ["repository"]
|
|
60
|
+
elif code is None:
|
|
61
|
+
note, partial = f"code search failed: {code_err}", ["code"]
|
|
62
|
+
# A sub-search that returned exactly LIMIT results hit its cap: more may exist (field report).
|
|
63
|
+
capped = [part for part, rows in (("repository", repos), ("code", code))
|
|
64
|
+
if rows is not None and len(rows) >= int(LIMIT)]
|
|
65
|
+
return ok(revision(), hits, note, partial, capped, int(LIMIT))
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""LeanSearch (https://leansearch.net): natural-language search over Mathlib.
|
|
2
|
+
|
|
3
|
+
Checked 2026-10-06: `POST https://leansearch.net/search` with
|
|
4
|
+
{"query": [term], "num_results": N} answers a list (one per query) of
|
|
5
|
+
{"result": {...}, "distance": x}; `GET /api/search` answers 404. A 404 or any
|
|
6
|
+
other non-200 answer is `skipped`, so a moved API never reads as zero hits. The
|
|
7
|
+
reason says what to do: a 5xx is the service failing (2026-10-14: every query
|
|
8
|
+
answered 500 while the site's own page sent this exact request), a 404 means the
|
|
9
|
+
endpoint moved and this adapter needs updating.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
|
|
16
|
+
from . import docs_url, hit, http_get, ok, skipped
|
|
17
|
+
|
|
18
|
+
NAME = "leansearch"
|
|
19
|
+
URL = "https://leansearch.net/search"
|
|
20
|
+
LIMIT = 10
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def fetch(url: str, body: bytes, timeout: float = 10):
|
|
24
|
+
return http_get(url, body=body, timeout=timeout)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def revision() -> str:
|
|
28
|
+
return "live"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def status_reason(status: int) -> str:
|
|
32
|
+
"""The skip reason for a non-200 answer, keeping `HTTP <status>` first for anything matching on it."""
|
|
33
|
+
if 500 <= status <= 599:
|
|
34
|
+
return f"HTTP {status}: service error at leansearch.net; retry later"
|
|
35
|
+
if status == 404:
|
|
36
|
+
return f"HTTP {status}: API moved ({URL} not found); the leansearch adapter needs updating"
|
|
37
|
+
return f"HTTP {status}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _name(v) -> str:
|
|
41
|
+
return ".".join(str(x) for x in v) if isinstance(v, list) else str(v or "")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def search(term: str, timeout: float = 10) -> dict:
|
|
45
|
+
body = json.dumps({"query": [term], "num_results": LIMIT}).encode("utf-8")
|
|
46
|
+
got = fetch(URL, body, timeout)
|
|
47
|
+
if got is None:
|
|
48
|
+
return skipped("unreachable")
|
|
49
|
+
status, raw = got
|
|
50
|
+
if status != 200:
|
|
51
|
+
return skipped(status_reason(status))
|
|
52
|
+
try:
|
|
53
|
+
data = json.loads(raw)
|
|
54
|
+
rows = data[0] if isinstance(data, list) and data and isinstance(data[0], list) else None
|
|
55
|
+
except ValueError:
|
|
56
|
+
rows = None
|
|
57
|
+
if rows is None:
|
|
58
|
+
return skipped("unexpected answer")
|
|
59
|
+
hits = []
|
|
60
|
+
for row in rows[:LIMIT]:
|
|
61
|
+
r = row.get("result") if isinstance(row, dict) else None
|
|
62
|
+
if not isinstance(r, dict) or not _name(r.get("name")):
|
|
63
|
+
continue
|
|
64
|
+
name = _name(r["name"])
|
|
65
|
+
hits.append(hit(name, r.get("informal_name") or r.get("docstring") or r.get("signature"),
|
|
66
|
+
docs_url(name), kind=r.get("kind"), module=_name(r.get("module_name")),
|
|
67
|
+
distance=row.get("distance")))
|
|
68
|
+
return ok(revision(), hits)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Loogle (https://loogle.lean-lang.org): type-shaped search over Mathlib master."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.parse
|
|
7
|
+
|
|
8
|
+
from . import docs_url, hit, http_get, ok, skipped
|
|
9
|
+
|
|
10
|
+
NAME = "loogle"
|
|
11
|
+
URL = "https://loogle.lean-lang.org/json?q={q}"
|
|
12
|
+
LIMIT = 20
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def fetch(url: str, timeout: float = 10):
|
|
16
|
+
return http_get(url, timeout=timeout)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def revision() -> str:
|
|
20
|
+
return "live (Mathlib master)"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def search(term: str, timeout: float = 10) -> dict:
|
|
24
|
+
got = fetch(URL.format(q=urllib.parse.quote(term, safe="")), timeout)
|
|
25
|
+
if got is None:
|
|
26
|
+
return skipped("unreachable")
|
|
27
|
+
status, body = got
|
|
28
|
+
if status != 200:
|
|
29
|
+
return skipped(f"HTTP {status}")
|
|
30
|
+
try:
|
|
31
|
+
data = json.loads(body)
|
|
32
|
+
except ValueError:
|
|
33
|
+
return skipped("answer is not JSON")
|
|
34
|
+
if not isinstance(data, dict):
|
|
35
|
+
return skipped("unexpected answer")
|
|
36
|
+
if data.get("error"):
|
|
37
|
+
return skipped("query not understood: " + str(data["error"]).splitlines()[0][:120])
|
|
38
|
+
rows = [h for h in data.get("hits") or [] if isinstance(h, dict) and h.get("name")]
|
|
39
|
+
hits = [hit(h["name"], h.get("doc") or h.get("type"), docs_url(h["name"]),
|
|
40
|
+
module=h.get("module"), type=" ".join(str(h.get("type") or "").split()))
|
|
41
|
+
for h in rows[:LIMIT]]
|
|
42
|
+
count = data.get("count")
|
|
43
|
+
total = count if isinstance(count, int) and not isinstance(count, bool) else len(rows)
|
|
44
|
+
# More matches than listed (Loogle's count, or rows past LIMIT) is a capped answer, not a full one.
|
|
45
|
+
return ok(revision(), hits, None, total=max(total, len(rows)))
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Palomar results API (https://data.palomar-registry.org), paged with `cursor`.
|
|
2
|
+
|
|
3
|
+
All pages are cached as one file per registry revision under
|
|
4
|
+
$XDG_CACHE_HOME/lean-pkg/palomar/snapshots-v1/<revision>.json, so a repeat search costs one
|
|
5
|
+
request; offline, the newest cached revision is searched and named as cached.
|
|
6
|
+
Titles, abstracts, theorem names and source repositories are searched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import pathlib
|
|
15
|
+
import tempfile
|
|
16
|
+
import urllib.parse
|
|
17
|
+
|
|
18
|
+
from . import cache_dir, hit, http_get, matches, note_cache_write, ok, skipped
|
|
19
|
+
|
|
20
|
+
NAME = "palomar"
|
|
21
|
+
URL = "https://data.palomar-registry.org/api/v1/results?order=registered"
|
|
22
|
+
ENTRY_BASE = "https://data.palomar-registry.org/"
|
|
23
|
+
MAX_PAGES = 200
|
|
24
|
+
LIMIT = 30
|
|
25
|
+
CACHE_SCHEMA = "lean-pkg-palomar-cache/1"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cache_file(revision: int) -> pathlib.Path:
|
|
29
|
+
# Keep envelopes separate from old bare-list caches, including old running clients.
|
|
30
|
+
return cache_dir("palomar", "snapshots-v1", f"{revision}.json")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def fetch(url: str, timeout: float = 10):
|
|
34
|
+
return http_get(url, timeout=timeout)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _page(url: str, timeout: float):
|
|
38
|
+
got = fetch(url, timeout)
|
|
39
|
+
if got is None or got[0] != 200:
|
|
40
|
+
return None
|
|
41
|
+
try:
|
|
42
|
+
data = json.loads(got[1])
|
|
43
|
+
except ValueError:
|
|
44
|
+
return None
|
|
45
|
+
return data if isinstance(data, dict) and _valid_rows(data.get("entries")) else None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _valid_rows(rows) -> bool:
|
|
49
|
+
return isinstance(rows, list) and all(
|
|
50
|
+
isinstance(row, dict) and isinstance(row.get("id"), str) and bool(row["id"].strip())
|
|
51
|
+
for row in rows)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _valid_revision(value) -> bool:
|
|
55
|
+
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _valid_cursor(page: dict) -> bool:
|
|
59
|
+
return "next" in page and (page["next"] is None or
|
|
60
|
+
isinstance(page["next"], str) and bool(page["next"].strip()))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _read_cache(path: pathlib.Path) -> list | None:
|
|
64
|
+
try:
|
|
65
|
+
payload = json.loads(path.read_text())
|
|
66
|
+
except (ValueError, OSError):
|
|
67
|
+
return None
|
|
68
|
+
if not isinstance(payload, dict) or payload.get("schema") != CACHE_SCHEMA:
|
|
69
|
+
return None # old bare lists have no snapshot-consistency evidence
|
|
70
|
+
rev, pages, rows = payload.get("revision"), payload.get("pages"), payload.get("entries")
|
|
71
|
+
if not _valid_revision(rev) or str(rev) != path.stem or \
|
|
72
|
+
not isinstance(pages, int) or isinstance(pages, bool) or pages < 1 or \
|
|
73
|
+
payload.get("complete") is not True or not _valid_rows(rows):
|
|
74
|
+
return None
|
|
75
|
+
return rows if payload.get("entries_sha256") == _rows_hash(rows) else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _rows_hash(rows: list) -> str:
|
|
79
|
+
return hashlib.sha256(json.dumps(rows, sort_keys=True).encode("utf-8")).hexdigest()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _cached() -> list[tuple[int, list]]:
|
|
83
|
+
base = cache_dir("palomar", "snapshots-v1")
|
|
84
|
+
out = []
|
|
85
|
+
if base.is_dir():
|
|
86
|
+
for f in base.glob("*.json"):
|
|
87
|
+
if f.stem.isdigit():
|
|
88
|
+
rows = _read_cache(f)
|
|
89
|
+
if rows is not None:
|
|
90
|
+
out.append((int(f.stem), rows))
|
|
91
|
+
return sorted(out, reverse=True)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def entries(timeout: float = 10) -> tuple[list | None, str | None, str | None]:
|
|
95
|
+
"""(entries, revision, reason when unavailable)."""
|
|
96
|
+
first = _page(URL, timeout)
|
|
97
|
+
if first is None:
|
|
98
|
+
cached = _cached()
|
|
99
|
+
if cached:
|
|
100
|
+
return cached[0][1], f"{cached[0][0]} (cached)", None
|
|
101
|
+
return None, None, "unreachable, and no cached results"
|
|
102
|
+
rev = first.get("revision")
|
|
103
|
+
if not _valid_revision(rev):
|
|
104
|
+
return None, None, "invalid registry revision"
|
|
105
|
+
if not _valid_cursor(first):
|
|
106
|
+
return None, str(rev), "invalid paging cursor"
|
|
107
|
+
f = _cache_file(rev)
|
|
108
|
+
cached = _read_cache(f) if f.is_file() else None
|
|
109
|
+
if cached is not None and cached[:len(first["entries"])] == first["entries"]:
|
|
110
|
+
return cached, str(rev), None
|
|
111
|
+
rows, page, pages = list(first["entries"]), first, 1
|
|
112
|
+
cursors = set()
|
|
113
|
+
while page["next"] is not None:
|
|
114
|
+
if pages >= MAX_PAGES:
|
|
115
|
+
return None, str(rev), "too many pages"
|
|
116
|
+
cursor = page["next"]
|
|
117
|
+
if not isinstance(cursor, str) or cursor in cursors:
|
|
118
|
+
return None, str(rev), "invalid or repeated paging cursor"
|
|
119
|
+
cursors.add(cursor)
|
|
120
|
+
page = _page(URL + "&cursor=" + urllib.parse.quote(cursor, safe=""), timeout)
|
|
121
|
+
if page is None:
|
|
122
|
+
return None, str(rev), "paging interrupted"
|
|
123
|
+
if not _valid_revision(page.get("revision")) or page["revision"] != rev:
|
|
124
|
+
return None, str(rev), "registry revision changed while paging"
|
|
125
|
+
if not _valid_cursor(page):
|
|
126
|
+
return None, str(rev), "invalid paging cursor"
|
|
127
|
+
rows += page["entries"]
|
|
128
|
+
pages += 1
|
|
129
|
+
tmp = None
|
|
130
|
+
try:
|
|
131
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
132
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=f.parent,
|
|
133
|
+
prefix=f.name + ".", suffix=".tmp", delete=False) as handle:
|
|
134
|
+
tmp = pathlib.Path(handle.name)
|
|
135
|
+
json.dump({"schema": CACHE_SCHEMA, "revision": rev, "pages": pages,
|
|
136
|
+
"complete": True, "entries": rows, "entries_sha256": _rows_hash(rows)}, handle)
|
|
137
|
+
os.replace(tmp, f)
|
|
138
|
+
note_cache_write("palomar", "snapshots-v1", f.name)
|
|
139
|
+
except OSError:
|
|
140
|
+
# A complete live result remains useful even when the cache is unwritable.
|
|
141
|
+
pass
|
|
142
|
+
finally:
|
|
143
|
+
if tmp is not None:
|
|
144
|
+
try:
|
|
145
|
+
tmp.unlink(missing_ok=True)
|
|
146
|
+
except OSError:
|
|
147
|
+
pass
|
|
148
|
+
return rows, str(rev), None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def revision() -> str | None:
|
|
152
|
+
cached = _cached()
|
|
153
|
+
return str(cached[0][0]) if cached else None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def search(term: str, timeout: float = 10) -> dict:
|
|
157
|
+
rows, rev, reason = entries(timeout)
|
|
158
|
+
if rows is None:
|
|
159
|
+
return skipped(reason, rev)
|
|
160
|
+
found = []
|
|
161
|
+
for e in rows:
|
|
162
|
+
if not isinstance(e, dict):
|
|
163
|
+
continue
|
|
164
|
+
src = e.get("source") if isinstance(e.get("source"), dict) else {}
|
|
165
|
+
thms = (e.get("formalization") or {}).get("theorem_names") if isinstance(e.get("formalization"), dict) else []
|
|
166
|
+
if matches(term, e.get("title"), e.get("abstract"), " ".join(str(t) for t in thms or []),
|
|
167
|
+
src.get("repository")):
|
|
168
|
+
found.append(hit(e.get("id"), e.get("title"), ENTRY_BASE + str(e.get("path") or ""),
|
|
169
|
+
repository=src.get("repository"), theorem_names=list(thms or [])))
|
|
170
|
+
return ok(rev, found[:LIMIT], f"{len(rows)} results searched", total=len(found))
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Reservoir, searched through its index data, never the site's name-only box.
|
|
2
|
+
|
|
3
|
+
The `leanprover/reservoir-index` tarball is cached under
|
|
4
|
+
$XDG_CACHE_HOME/lean-pkg/reservoir-index/<commit>/ (fetched with `gh api`), and
|
|
5
|
+
descriptions, keywords and names in every metadata.json are searched. Tests and
|
|
6
|
+
offline users can point LEAN_PKG_RESERVOIR_INDEX at an unpacked index directory.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import pathlib
|
|
15
|
+
import re
|
|
16
|
+
import shutil
|
|
17
|
+
import tarfile
|
|
18
|
+
|
|
19
|
+
from . import cache_dir, hit, matches, note_cache_write, ok, run_cmd, skipped
|
|
20
|
+
|
|
21
|
+
NAME = "reservoir"
|
|
22
|
+
ENV = "LEAN_PKG_RESERVOIR_INDEX"
|
|
23
|
+
REPO = "leanprover/reservoir-index"
|
|
24
|
+
LIMIT = 30
|
|
25
|
+
_SHA = re.compile(r"^[0-9a-f]{40}$")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def runner(argv: list[str], timeout: float = 120):
|
|
29
|
+
return run_cmd(argv, timeout)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def head_commit() -> str | None:
|
|
33
|
+
r = runner(["gh", "api", f"repos/{REPO}/commits/HEAD", "--jq", ".sha"], 30)
|
|
34
|
+
if r is None or r[0] != 0:
|
|
35
|
+
return None
|
|
36
|
+
sha = r[1].decode("utf-8", errors="replace").strip()
|
|
37
|
+
return sha if _SHA.match(sha) else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cached_dirs() -> list[pathlib.Path]:
|
|
41
|
+
base = cache_dir("reservoir-index")
|
|
42
|
+
if not base.is_dir():
|
|
43
|
+
return []
|
|
44
|
+
dirs = [p for p in base.iterdir() if p.is_dir() and _SHA.match(p.name)]
|
|
45
|
+
return sorted(dirs, key=lambda p: p.stat().st_mtime, reverse=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def extract(blob: bytes, dest: pathlib.Path) -> None:
|
|
49
|
+
"""Unpack a GitHub tarball (one top directory) into dest. Only regular files and
|
|
50
|
+
directories are written, by hand, below dest; any other member refuses the tarball."""
|
|
51
|
+
tmp = dest.with_name(dest.name + ".tmp")
|
|
52
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
53
|
+
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tf:
|
|
54
|
+
for m in tf.getmembers():
|
|
55
|
+
parts = pathlib.PurePosixPath(m.name).parts[1:]
|
|
56
|
+
if not parts:
|
|
57
|
+
continue
|
|
58
|
+
if m.name.startswith("/") or ".." in parts or not (m.isfile() or m.isdir()):
|
|
59
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
60
|
+
raise ValueError(f"unsafe tarball member {m.name!r}")
|
|
61
|
+
target = tmp.joinpath(*parts)
|
|
62
|
+
if m.isdir():
|
|
63
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
else:
|
|
65
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
target.write_bytes(tf.extractfile(m).read())
|
|
67
|
+
tmp.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
os.replace(tmp, dest)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def index_dir() -> tuple[pathlib.Path | None, str | None, str | None]:
|
|
72
|
+
"""(directory, revision, reason when unavailable)."""
|
|
73
|
+
env = os.environ.get(ENV, "").strip()
|
|
74
|
+
if env:
|
|
75
|
+
p = pathlib.Path(env).expanduser()
|
|
76
|
+
return (p, p.name, None) if p.is_dir() else (None, None, f"{ENV} is not a directory")
|
|
77
|
+
sha = head_commit()
|
|
78
|
+
if sha is None:
|
|
79
|
+
cached = cached_dirs()
|
|
80
|
+
if cached:
|
|
81
|
+
return cached[0], cached[0].name[:8] + " (cached)", None
|
|
82
|
+
return None, None, "gh unavailable or offline, and no cached index"
|
|
83
|
+
dest = cache_dir("reservoir-index", sha)
|
|
84
|
+
if not dest.is_dir():
|
|
85
|
+
r = runner(["gh", "api", f"repos/{REPO}/tarball/{sha}"])
|
|
86
|
+
if r is None or r[0] != 0:
|
|
87
|
+
return None, None, "index tarball download failed"
|
|
88
|
+
try:
|
|
89
|
+
extract(r[1], dest)
|
|
90
|
+
except (ValueError, tarfile.TarError, OSError) as e:
|
|
91
|
+
return None, None, f"index tarball refused: {type(e).__name__}"
|
|
92
|
+
note_cache_write("reservoir-index", sha)
|
|
93
|
+
return dest, sha[:8], None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def revision() -> str | None:
|
|
97
|
+
env = os.environ.get(ENV, "").strip()
|
|
98
|
+
if env:
|
|
99
|
+
return pathlib.Path(env).name
|
|
100
|
+
cached = cached_dirs()
|
|
101
|
+
return cached[0].name[:8] if cached else None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def search(term: str, timeout: float = 10) -> dict:
|
|
105
|
+
d, rev, reason = index_dir()
|
|
106
|
+
if d is None:
|
|
107
|
+
return skipped(reason)
|
|
108
|
+
found, n = [], 0
|
|
109
|
+
for f in sorted(d.rglob("metadata.json")):
|
|
110
|
+
try:
|
|
111
|
+
m = json.loads(f.read_text())
|
|
112
|
+
except (ValueError, OSError):
|
|
113
|
+
continue
|
|
114
|
+
if not isinstance(m, dict):
|
|
115
|
+
continue
|
|
116
|
+
n += 1
|
|
117
|
+
if not matches(term, m.get("fullName"), m.get("name"), m.get("description"),
|
|
118
|
+
" ".join(str(k) for k in m.get("keywords") or [])):
|
|
119
|
+
continue
|
|
120
|
+
srcs = [s for s in m.get("sources") or [] if isinstance(s, dict)]
|
|
121
|
+
repo = (srcs[0].get("repoUrl") if srcs else None) or f"https://github.com/{m.get('fullName')}"
|
|
122
|
+
found.append(hit(m.get("fullName") or m.get("name"), m.get("description"), repo,
|
|
123
|
+
stars=m.get("stars") or 0, license=m.get("license"),
|
|
124
|
+
keywords=list(m.get("keywords") or []),
|
|
125
|
+
reservoir=f"https://reservoir.lean-lang.org/@{m.get('owner')}/{m.get('name')}"))
|
|
126
|
+
found.sort(key=lambda h: (-int(h["extra"]["stars"] or 0), h["name"].lower()))
|
|
127
|
+
return ok(rev, found[:LIMIT], f"{n} packages searched", total=len(found))
|