import fs from "node:fs"; import path from "node:path"; import { hasHeaderOption, readHeaderOptionValue, readHeaderOptionValues, type RegenerationCommand } from "../parsers/requirements-header.js"; import { normalizePep503PackageName } from "../utils/version.js"; import { isRequirementsFormat } from "../parsers/requirements-limit-sources.js"; import { normalizeExtraName } from "../utils/versions/pep508.js"; export type UploadCutoff = | { kind: "none" } | { kind: "before"; at: Date; raw: string } | { kind: "unknown"; raw: string }; const HOUR_MS = 3_600_000; const DAY_PATTERN = /^P(\d+)([DW])$/; const HOURS_PATTERN = /^PT(\d+)H$/; const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; // The earliest any time zone reaches a calendar date is UTC+14, so a bare date means midnight there. const EARLIEST_ZONE_OFFSET_HOURS = 14; /** The instant a cutoff value names, or null when the value is not a form read here. */ function parseCutoffValue(value: string, now: Date): Date | null { const days = DAY_PATTERN.exec(value); if (days) return new Date(now.getTime() - Number(days[1]) * (days[2] === "W" ? 7 : 1) * 24 * HOUR_MS); const hours = HOURS_PATTERN.exec(value); if (hours) return new Date(now.getTime() - Number(hours[1]) * HOUR_MS); if (DATE_ONLY.test(value)) { const at = new Date(`${value}T00:00:00Z`); return Number.isNaN(at.getTime()) ? null : new Date(at.getTime() - EARLIEST_ZONE_OFFSET_HOURS * HOUR_MS); } if (!/^\d{4}-\d{2}-\d{2}T/.test(value)) return null; const at = new Date(value); return Number.isNaN(at.getTime()) ? null : at; } function packageCutoffValue(command: string, packageName: string): string | null { const wanted = normalizePep503PackageName(packageName); for (const entry of readHeaderOptionValues(command, "--exclude-newer-package")) { const split = entry.indexOf("="); if (split > 0 && normalizePep503PackageName(entry.slice(0, split)) === wanted) return entry.slice(split + 1); } return null; } /** How advice shows a cutoff: a bare date as the header wrote it, anything else as its UTC date. */ export function describeCutoff(cutoff: { at: Date; raw: string }): string { return DATE_ONLY.test(cutoff.raw) ? cutoff.raw : cutoff.at.toISOString().slice(0, 10); } /** The upload-time cutoff a header command applies to one package. */ export function readUploadCutoff(regeneration: RegenerationCommand, packageName: string, now: Date): UploadCutoff { const { command, tool } = regeneration; const raw = tool === "pip-compile" ? readHeaderOptionValue(command, "--uploaded-prior-to") : (packageCutoffValue(command, packageName) ?? readHeaderOptionValue(command, "--exclude-newer")); if (raw === null) return { kind: "none" }; const at = parseCutoffValue(raw, now); return at ? { kind: "before", at, raw } : { kind: "unknown", raw }; } const INDEX_OPTIONS = ["--index-url", "--extra-index-url", "--default-index", "--index", "-i"]; // Options that read packages from somewhere other than an index: none at all, or local files and pages. const NON_INDEX_SOURCES = ["--no-index", "--find-links", "-f"]; function isPypiIndex(url: string): boolean { try { const parsed = new URL(url); return parsed.hostname === "pypi.org" && parsed.pathname.replace(/\/+$/, "") === "/simple"; } catch { return false; } } /** Whether options in `text` (a header command or one line of a requirements file) read from a source other than PyPI. */ function optionsUseNonPypiSource(text: string): boolean { if (NON_INDEX_SOURCES.some(option => hasHeaderOption(text, option))) return true; return INDEX_OPTIONS.some(option => readHeaderOptionValues(text, option).some(value => !isPypiIndex(value))); } /** Whether the command reads packages from any source other than PyPI's own index. */ export function usesNonPypiIndex(regeneration: RegenerationCommand): boolean { return optionsUseNonPypiSource(regeneration.command); } const REQUIREMENT_WITH_EXTRAS = /([A-Za-z0-9][A-Za-z0-9._-]*)[ \t]*\[([^\]\n]*)\]/g; /** The normalised extras any of `files` writes on a requirement for `name`, such as `doh` from `dnspython[doh]>=2`. */ export function extrasWrittenFor(files: string[], name: string): string[] { const wanted = normalizePep503PackageName(name); const extras = new Set(); for (const file of files) { let content: string; try { content = fs.readFileSync(file, "utf8"); } catch { continue; } for (const match of content.matchAll(REQUIREMENT_WITH_EXTRAS)) { if (normalizePep503PackageName(match[1]!) !== wanted) continue; for (const extra of match[2]!.split(",")) if (extra.trim() !== "") extras.add(normalizeExtraName(extra)); } } return [...extras]; } /** The first requirements-format file among `files` whose option lines read from a source other than PyPI, or null. */ export function nonPypiSourceFile(files: string[]): string | null { for (const file of files.filter(isRequirementsFormat)) { let content: string; try { content = fs.readFileSync(file, "utf8"); } catch { continue; // an unreadable input is already reported as an unknown limit } const lines = content.replace(/\\\r?\n/g, " ").split(/\r?\n/).map(line => line.replace(/(^|\s)#.*$/, "").trim()); if (lines.some(line => line.startsWith("-") && optionsUseNonPypiSource(line))) return file; } return null; } const PROJECT_TABLE = /^\[project\]\s*$/m; const ANY_TABLE = /^\s*\[/m; const REQUIRES_PYTHON = /^\s*requires-python\s*=\s*["']\s*(?:>=|~=)\s*(\d+(?:\.\d+){1,2})/m; /** The lowest Python a project's pyproject.toml `[project] requires-python` allows, for `>=` and `~=`; else null. */ export function readProjectPythonFloor(folder: string): string | null { let text: string; try { text = fs.readFileSync(path.join(folder, "pyproject.toml"), "utf8"); } catch { return null; } const start = PROJECT_TABLE.exec(text); if (!start) return null; const body = text.slice(start.index + start[0].length); const next = ANY_TABLE.exec(body); return REQUIRES_PYTHON.exec(next ? body.slice(0, next.index) : body)?.[1] ?? null; }