-
Notifications
You must be signed in to change notification settings - Fork 2
/
update_package_list.py
142 lines (126 loc) · 4.89 KB
/
update_package_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import gzip
import json
import logging
import os
import sqlite3
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
import lastversion
import requests
from google.api_core.exceptions import Forbidden, GoogleAPIError
from google.cloud import bigquery
from packaging.utils import canonicalize_name
_LOGGER = logging.getLogger(__name__)
BIGQUERY_TOKEN = "BIGQUERY_TOKEN"
class _Item:
def __init__(self, value: str):
self.value = value
self.value_ = canonicalize_name(value)
def __hash__(self):
return self.value_.__hash__()
def __eq__(self, other):
return self.value_.__eq__(other.value_)
def _merge(source: str, new_packages: set[str], packages_set: set[str]):
_LOGGER.debug(f"{source}: merging {len(new_packages)} package names")
# need to handle canonicalize_name
dst = {_Item(value) for value in packages_set}
src = {_Item(value) for value in new_packages}
subset = src - dst
packages_set |= {item.value for item in subset}
_LOGGER.debug(f"{source}: now using {len(packages_set)} package names")
def _update_bigquery(bigquery_credentials: Path | None, packages_set: set[str]) -> None:
_LOGGER.info("bigquery: fetching packages")
today = datetime.fromisocalendar(*datetime.now(timezone.utc).isocalendar())
table_suffix = (today - timedelta(days=1)).strftime("%Y-%m-%d")
query = (
"SELECT file.project AS project FROM "
"bigquery-public-data.pypi.file_downloads WHERE "
f'timestamp BETWEEN TIMESTAMP("{table_suffix} 00:00:00 UTC") AND '
f'TIMESTAMP("{table_suffix} 23:59:59.999999 UTC") AND '
"REGEXP_CONTAINS(file.filename"
', "-[0-9A-Za-z_.]*manylinux[0-9A-Za-z_.]+\\\\.whl$") '
"GROUP BY project"
)
with TemporaryDirectory() as temp:
if bigquery_credentials is None:
bigquery_credentials = Path(temp) / "key.json"
bigquery_credentials.write_text(os.environ[BIGQUERY_TOKEN])
with open(bigquery_credentials) as f:
try:
project = json.load(f)["project_id"]
invalid = False
except ValueError:
invalid = True
if invalid:
raise ValueError("BIGQUERY_TOKEN is invalid")
client = bigquery.Client.from_service_account_json(
bigquery_credentials, project=project
)
query_job = client.query(query)
try:
rows = query_job.result()
except Forbidden as e:
if hasattr(e, "errors") and len(e.errors) > 0 and "message" in e.errors[0]:
_LOGGER.warning(f'bigquery: {e.errors[0]["message"]}')
else:
_LOGGER.warning(f"bigquery: {e}")
return
except GoogleAPIError as e:
_LOGGER.warning(f"bigquery: {e}")
return
if query_job.cache_hit:
_LOGGER.debug("bigquery: using cached results")
_merge("bigquery", {row.project for row in rows}, packages_set)
def _update_top_packages(packages_set: set[str]) -> None:
_LOGGER.info("top pypi: fetching packages")
response = requests.get(
"https://hugovk.github.io/top-pypi-packages/"
"top-pypi-packages-30-days.min.json"
)
response.raise_for_status()
top_packages_data = response.json()
top_packages = {row["project"] for row in top_packages_data["rows"]}
_merge("top pypi", top_packages, packages_set)
def _update_pypi_data(packages_set: set[str]) -> None:
_LOGGER.info("pypi data: fetching packages")
query = (
'SELECT package_name FROM wheels WHERE platform LIKE "%manylinux%" '
"GROUP BY package_name;"
)
db_url = lastversion.latest(
"https://github.com/sethmlarson/pypi-data",
output_format="assets",
having_asset="pypi.db.gz",
)[0]
_LOGGER.debug("pypi data: download database")
response = requests.get(db_url)
response.raise_for_status()
with NamedTemporaryFile() as f:
_LOGGER.debug("pypi data: decompress database")
f.write(gzip.decompress(response.content))
_LOGGER.debug("pypi data: execute database query")
con = sqlite3.connect(f.name)
try:
cur = con.execute(query)
try:
new_packages = {row[0] for row in cur.fetchall()}
finally:
cur.close()
finally:
con.close()
_merge("pypi data", new_packages, packages_set)
def update(
packages: list[str],
use_top_packages: bool,
use_sethmlarson_pypi_data: bool,
bigquery_credentials: Path | None,
) -> list[str]:
packages_set = set(packages)
if use_top_packages:
_update_top_packages(packages_set)
if use_sethmlarson_pypi_data:
_update_pypi_data(packages_set)
if bigquery_credentials or os.environ.get(BIGQUERY_TOKEN, "") != "":
_update_bigquery(bigquery_credentials, packages_set)
return list(sorted(packages_set))