84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Report npm latest tags for dependencies referenced by template CDN URLs."""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import quote
|
|
from urllib.request import Request, urlopen
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
CDN_URL = re.compile(
|
|
r"https://(?:cdn\.jsdelivr\.net/npm/|unpkg\.com/)"
|
|
r"(?P<name>@[\w.-]+/[\w.-]+|[\w.-]+)"
|
|
r"@(?P<version>[^/\s\"'<>?#]+)/"
|
|
)
|
|
|
|
|
|
def dependencies(root):
|
|
found = {}
|
|
for path in sorted((root / "layouts").rglob("*.html")):
|
|
for match in CDN_URL.finditer(path.read_text()):
|
|
key = (match["name"], match["version"])
|
|
found.setdefault(key, set()).add(str(path.relative_to(root)))
|
|
return found
|
|
|
|
|
|
def latest_version(name):
|
|
url = "https://registry.npmjs.org/" + quote(name, safe="") + "/latest"
|
|
request = Request(url, headers={"Accept": "application/json"})
|
|
with urlopen(request, timeout=15) as response:
|
|
version = json.load(response)["version"]
|
|
if not isinstance(version, str) or not version:
|
|
raise ValueError("registry returned an invalid version")
|
|
return version
|
|
|
|
|
|
def comparison(current, latest):
|
|
if current == latest:
|
|
return "matches latest"
|
|
if re.fullmatch(r"\d+(?:\.\d+)?", current):
|
|
if latest.startswith(current + "."):
|
|
return "floating pin includes latest"
|
|
return "floating pin differs from latest"
|
|
return "differs from latest"
|
|
|
|
|
|
def main():
|
|
found = dependencies(ROOT)
|
|
if not found:
|
|
print("No versioned npm CDN references found in layouts/*.html.")
|
|
return 0
|
|
|
|
failed = False
|
|
versions = {}
|
|
rows = []
|
|
for (name, current), paths in sorted(found.items()):
|
|
if name not in versions:
|
|
try:
|
|
versions[name] = latest_version(name)
|
|
except (HTTPError, URLError, TimeoutError, OSError, ValueError, KeyError) as error:
|
|
print(f"Could not check {name}: {error}", file=sys.stderr)
|
|
versions[name] = None
|
|
failed = True
|
|
latest = versions[name]
|
|
status = comparison(current, latest) if latest else "lookup failed"
|
|
rows.append((name, current, latest or "?", status))
|
|
|
|
headings = ("Package", "Template version", "npm latest", "Status")
|
|
widths = [max(len(row[i]) for row in [headings, *rows]) for i in range(4)]
|
|
for row in [headings, *rows]:
|
|
print(" ".join(value.ljust(width) for value, width in zip(row, widths)).rstrip())
|
|
print("\nReferences:")
|
|
for (name, current), paths in sorted(found.items()):
|
|
print(f" {name}@{current}: {', '.join(sorted(paths))}")
|
|
print("\nReport only; no files changed. Review compatibility before updating.")
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|