-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathbuild_directory.py
262 lines (244 loc) · 7.12 KB
/
build_directory.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import click
from github_to_sqlite.cli import (
releases as github_to_sqlite_releases,
repos as github_to_sqlite_repos,
)
from python_graphql_client import GraphqlClient
import sqlite_utils
REPO_FIELDS = """
fragment repoFields on Repository {
id
nameWithOwner
createdAt
openGraphImageUrl
usesCustomOpenGraphImage
defaultBranchRef {
target {
oid
}
}
repositoryTopics(first: 100) {
totalCount
nodes {
topic {
name
}
}
}
openIssueCount: issues(states: [OPEN]) {
totalCount
}
closedIssueCount: issues(states: [CLOSED]) {
totalCount
}
releases(orderBy: {field: CREATED_AT, direction: DESC}, first: 1) {
totalCount
nodes {
tagName
}
}
}
"""
def build_query(repos):
repo_fragments = []
for i, repo in enumerate(repos):
owner, name = repo.split("/")
repo_fragments.append(
"""
repo_{i}: repository(name: "{name}", owner: "{owner}") {open_curly}
...repoFields
{close_curly}
""".format(
REPO_FIELDS=REPO_FIELDS,
i=i,
name=name,
owner=owner,
open_curly="{",
close_curly="}",
)
)
return """
REPO_FIELDS
{ REPOS }
""".replace(
"REPOS", "\n".join(repo_fragments)
).replace(
"REPO_FIELDS", REPO_FIELDS
)
def transform_node(node):
releases = node.pop("releases")
node["releaseCount"] = releases["totalCount"]
for key in ("openIssueCount", "closedIssueCount"):
node[key] = node[key]["totalCount"]
repository_topics = node.pop("repositoryTopics")
node["topics"] = [n["topic"]["name"] for n in repository_topics["nodes"]]
default_branch_ref = node.pop("defaultBranchRef")
node["latest_commit"] = default_branch_ref["target"]["oid"]
return node, releases["nodes"]
client = GraphqlClient(endpoint="https://api.github.com/graphql")
def fetch_plugins(oauth_token, repos):
chunks = []
repos_copy = list(repos)
while repos_copy:
chunk, repos_copy = repos_copy[:20], repos_copy[20:]
chunks.append(chunk)
all_nodes = []
for chunk in chunks:
query = build_query(chunk)
print(query)
data = client.execute(
query=query,
headers={"Authorization": "Bearer {}".format(oauth_token)},
)
assert "errors" not in data, data["errors"]
nodes = []
for key in data["data"]:
if key.startswith("repo_"):
nodes.append(data["data"][key])
all_nodes.extend(nodes)
return all_nodes
@click.command()
@click.argument(
"db_filename",
type=click.Path(file_okay=True, dir_okay=False),
)
@click.option("--github-token", envvar="GITHUB_TOKEN", required=True)
@click.option("--fetch-missing-releases", is_flag=True)
@click.option("--always-fetch-releases-for-repo", multiple=True)
@click.option("--force-fetch-readmes", is_flag=True)
def cli(
db_filename,
github_token,
fetch_missing_releases,
always_fetch_releases_for_repo,
force_fetch_readmes,
):
db = sqlite_utils.Database(db_filename)
repos_to_fetch_releases_for = {"simonw/datasette"}
if "latest_commit" not in db["datasette_repos"].columns_dict:
previous_hashes = {
row["nameWithOwner"]: None for row in db["datasette_repos"].rows
}
else:
previous_hashes = {
row["nameWithOwner"]: row["latest_commit"]
for row in db["datasette_repos"].rows
}
repos = [
r[0]
for r in db.execute(
"select repo from tool_repos union select repo from plugin_repos"
).fetchall()
]
nodes = fetch_plugins(github_token, repos)
for node in nodes:
plugin, releases = transform_node(node)
db["datasette_repos"].insert(
plugin,
pk="id",
column_order=("id", "nameWithOwner"),
replace=True,
alter=True,
)
full_name = plugin["nameWithOwner"]
if fetch_missing_releases:
for release in releases:
tag_name = release["tagName"]
# Does this release exist for this repo?
if (
(full_name in always_fetch_releases_for_repo)
or not db["repos"].exists()
or not list(
db["releases"].rows_where(
"repo = (select id from repos where full_name = ?) and tag_name = ?",
[full_name, tag_name],
)
)
):
repos_to_fetch_releases_for.add(full_name)
if repos_to_fetch_releases_for:
github_to_sqlite_releases.callback(
db_filename, list(repos_to_fetch_releases_for), auth="auth.json"
)
# Fetch README for any repos that have changed since last time
repos_to_fetch_readme_for = []
for row in db["datasette_repos"].rows:
if (
row["latest_commit"] != previous_hashes.get(row["nameWithOwner"])
or force_fetch_readmes
or row["nameWithOwner"] == "simonw/datasette-atom"
):
repos_to_fetch_readme_for.append(row["nameWithOwner"])
if repos_to_fetch_readme_for:
print("Fetching README for {}".format(repos_to_fetch_readme_for))
github_to_sqlite_repos.callback(
db_filename,
usernames=[],
auth="auth.json",
repo=repos_to_fetch_readme_for,
load=None,
readme=True,
readme_html=True,
)
for view_name, repo_table in (("plugins", "plugin_repos"), ("tools", "tool_repos")):
db.create_view(
view_name,
"""
select
repos.name as name,
repos.full_name as full_name,
users.login as owner,
repos.description as description,
{repo_table}.extra_search as extra_search,
{repo_table}.tags as tags,
repos.stargazers_count,
pypi_versions.name as tag_name,
max(pypi_releases.upload_time) as latest_release_at,
repos.created_at as created_at,
datasette_repos.openGraphImageUrl,
datasette_repos.usesCustomOpenGraphImage,
(
select
sum(downloads)
from
stats
where
stats.package = repos.name
and stats.date > date('now', '-7 days')
) as downloads_this_week,
(
select
count(*)
from
plugin_repos
where
repo = repos.full_name
) as is_plugin,
(
select
count(*)
from
tool_repos
where
repo = repos.full_name
) as is_tool
from
datasette_repos
join repos on datasette_repos.id = repos.node_id
left join pypi_releases on (
pypi_releases.package = repos.name or pypi_releases.package = 'datasette-' || repos.name
)
left join pypi_versions on pypi_releases.version = pypi_versions.id
join users on users.id = repos.owner
join {repo_table} on {repo_table}.repo = datasette_repos.nameWithOwner
group by
repos.id
order by
latest_release_at desc;
""".format(
repo_table=repo_table
).strip(),
replace=True,
)
if __name__ == "__main__":
cli()