|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Fetch from conda database all available versions of dependencies and their |
| 3 | +publication date. Compare it against requirements/min-core-deps.yml to verify the |
| 4 | +policy on obsolete dependencies is being followed. Print a pretty report :) |
| 5 | +
|
| 6 | +Adapted from xarray: |
| 7 | +https://github.com/pydata/xarray/blob/a04d857a03d1fb04317d636a7f23239cb9034491/ci/min_deps_check.py |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import itertools |
| 13 | +import sys |
| 14 | +from collections.abc import Iterator |
| 15 | +from datetime import datetime |
| 16 | + |
| 17 | +import conda.api # type: ignore[import] |
| 18 | +import yaml |
| 19 | +from dateutil.relativedelta import relativedelta |
| 20 | + |
| 21 | +CHANNELS = ["conda-forge", "defaults"] |
| 22 | +IGNORE_DEPS = {} |
| 23 | + |
| 24 | +POLICY_MONTHS = {"python": 3 * 12} |
| 25 | +POLICY_MONTHS_DEFAULT = 24 |
| 26 | +POLICY_OVERRIDE: dict[str, tuple[int, int]] = {} |
| 27 | +errors = [] |
| 28 | + |
| 29 | + |
| 30 | +def error(msg: str) -> None: |
| 31 | + global errors |
| 32 | + errors.append(msg) |
| 33 | + print("ERROR:", msg) |
| 34 | + |
| 35 | + |
| 36 | +def warning(msg: str) -> None: |
| 37 | + print("WARNING:", msg) |
| 38 | + |
| 39 | + |
| 40 | +def parse_requirements(fname) -> Iterator[tuple[str, int, int, int | None]]: |
| 41 | + """Load requirements/min-all-deps.yml |
| 42 | +
|
| 43 | + Yield (package name, major version, minor version, [patch version]) |
| 44 | + """ |
| 45 | + global errors |
| 46 | + |
| 47 | + with open(fname) as fh: |
| 48 | + contents = yaml.safe_load(fh) |
| 49 | + for row in contents["dependencies"]: |
| 50 | + if isinstance(row, dict) and list(row) == ["pip"]: |
| 51 | + continue |
| 52 | + pkg, eq, version = row.partition("=") |
| 53 | + if pkg.rstrip("<>") in IGNORE_DEPS: |
| 54 | + continue |
| 55 | + if pkg.endswith("<") or pkg.endswith(">") or eq != "=": |
| 56 | + error("package should be pinned with exact version: " + row) |
| 57 | + continue |
| 58 | + |
| 59 | + try: |
| 60 | + version_tup = tuple(int(x) for x in version.split(".")) |
| 61 | + except ValueError: |
| 62 | + raise ValueError("non-numerical version: " + row) |
| 63 | + |
| 64 | + if len(version_tup) == 2: |
| 65 | + yield (pkg, *version_tup, None) # type: ignore[misc] |
| 66 | + elif len(version_tup) == 3: |
| 67 | + yield (pkg, *version_tup) # type: ignore[misc] |
| 68 | + else: |
| 69 | + raise ValueError("expected major.minor or major.minor.patch: " + row) |
| 70 | + |
| 71 | + |
| 72 | +def query_conda(pkg: str) -> dict[tuple[int, int], datetime]: |
| 73 | + """Query the conda repository for a specific package |
| 74 | +
|
| 75 | + Return map of {(major version, minor version): publication date} |
| 76 | + """ |
| 77 | + |
| 78 | + def metadata(entry): |
| 79 | + version = entry.version |
| 80 | + |
| 81 | + time = datetime.fromtimestamp(entry.timestamp) |
| 82 | + major, minor = map(int, version.split(".")[:2]) |
| 83 | + |
| 84 | + return (major, minor), time |
| 85 | + |
| 86 | + raw_data = conda.api.SubdirData.query_all(pkg, channels=CHANNELS) |
| 87 | + data = sorted(metadata(entry) for entry in raw_data if entry.timestamp != 0) |
| 88 | + |
| 89 | + release_dates = { |
| 90 | + version: [time for _, time in group if time is not None] |
| 91 | + for version, group in itertools.groupby(data, key=lambda x: x[0]) |
| 92 | + } |
| 93 | + out = {version: min(dates) for version, dates in release_dates.items() if dates} |
| 94 | + |
| 95 | + # Hardcoded fix to work around incorrect dates in conda |
| 96 | + if pkg == "python": |
| 97 | + out.update( |
| 98 | + { |
| 99 | + (2, 7): datetime(2010, 6, 3), |
| 100 | + (3, 5): datetime(2015, 9, 13), |
| 101 | + (3, 6): datetime(2016, 12, 23), |
| 102 | + (3, 7): datetime(2018, 6, 27), |
| 103 | + (3, 8): datetime(2019, 10, 14), |
| 104 | + (3, 9): datetime(2020, 10, 5), |
| 105 | + (3, 10): datetime(2021, 10, 4), |
| 106 | + (3, 11): datetime(2022, 10, 24), |
| 107 | + } |
| 108 | + ) |
| 109 | + |
| 110 | + return out |
| 111 | + |
| 112 | + |
| 113 | +def process_pkg(pkg: str, req_major: int, req_minor: int, req_patch: int | None) -> tuple[str, str, str, str, str, str]: |
| 114 | + """Compare package version from requirements file to available versions in conda. |
| 115 | + Return row to build pandas dataframe: |
| 116 | +
|
| 117 | + - package name |
| 118 | + - major.minor.[patch] version in requirements file |
| 119 | + - publication date of version in requirements file (YYYY-MM-DD) |
| 120 | + - major.minor version suggested by policy |
| 121 | + - publication date of version suggested by policy (YYYY-MM-DD) |
| 122 | + - status ("<", "=", "> (!)") |
| 123 | + """ |
| 124 | + print(f"Analyzing {pkg}...") |
| 125 | + versions = query_conda(pkg) |
| 126 | + |
| 127 | + try: |
| 128 | + req_published = versions[req_major, req_minor] |
| 129 | + except KeyError: |
| 130 | + error("not found in conda: " + pkg) |
| 131 | + return pkg, fmt_version(req_major, req_minor, req_patch), "-", "-", "-", "(!)" |
| 132 | + |
| 133 | + policy_months = POLICY_MONTHS.get(pkg, POLICY_MONTHS_DEFAULT) |
| 134 | + policy_published = datetime.now() - relativedelta(months=policy_months) |
| 135 | + |
| 136 | + filtered_versions = [version for version, published in versions.items() if published < policy_published] |
| 137 | + policy_major, policy_minor = max(filtered_versions, default=(req_major, req_minor)) |
| 138 | + |
| 139 | + try: |
| 140 | + policy_major, policy_minor = POLICY_OVERRIDE[pkg] |
| 141 | + except KeyError: |
| 142 | + pass |
| 143 | + policy_published_actual = versions[policy_major, policy_minor] |
| 144 | + |
| 145 | + if (req_major, req_minor) < (policy_major, policy_minor): |
| 146 | + status = "<" |
| 147 | + elif (req_major, req_minor) > (policy_major, policy_minor): |
| 148 | + status = "> (!)" |
| 149 | + delta = relativedelta(datetime.now(), req_published).normalized() |
| 150 | + n_months = delta.years * 12 + delta.months |
| 151 | + warning( |
| 152 | + f"Package is too new: {pkg}={req_major}.{req_minor} was " |
| 153 | + f"published on {req_published:%Y-%m-%d} " |
| 154 | + f"which was {n_months} months ago (policy is {policy_months} months)" |
| 155 | + ) |
| 156 | + else: |
| 157 | + status = "=" |
| 158 | + |
| 159 | + if req_patch is not None: |
| 160 | + warning("patch version should not appear in requirements file: " + pkg) |
| 161 | + status += " (w)" |
| 162 | + |
| 163 | + return ( |
| 164 | + pkg, |
| 165 | + fmt_version(req_major, req_minor, req_patch), |
| 166 | + req_published.strftime("%Y-%m-%d"), |
| 167 | + fmt_version(policy_major, policy_minor), |
| 168 | + policy_published_actual.strftime("%Y-%m-%d"), |
| 169 | + status, |
| 170 | + ) |
| 171 | + |
| 172 | + |
| 173 | +def fmt_version(major: int, minor: int, patch: int | None = None) -> str: |
| 174 | + if patch is None: |
| 175 | + return f"{major}.{minor}" |
| 176 | + else: |
| 177 | + return f"{major}.{minor}.{patch}" |
| 178 | + |
| 179 | + |
| 180 | +def main() -> None: |
| 181 | + fname = sys.argv[1] |
| 182 | + rows = [process_pkg(pkg, major, minor, patch) for pkg, major, minor, patch in parse_requirements(fname)] |
| 183 | + |
| 184 | + print("\nPackage Required Policy Status") |
| 185 | + print("----------------- -------------------- -------------------- ------") |
| 186 | + fmt = "{:17} {:7} ({:10}) {:7} ({:10}) {}" |
| 187 | + for row in rows: |
| 188 | + print(fmt.format(*row)) |
| 189 | + |
| 190 | + if errors: |
| 191 | + print("\nErrors:") |
| 192 | + print("-------") |
| 193 | + for i, e in enumerate(errors): |
| 194 | + print(f"{i+1}. {e}") |
| 195 | + sys.exit(1) |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + main() |
0 commit comments