Repository navigation
Expand file tree
/
Copy pathtodogrep
More file actions
executable file
·208 lines (184 loc) · 8.16 KB
/
Copy pathtodogrep
File metadata and controls
executable file
·208 lines (184 loc) · 8.16 KB
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
#!/usr/bin/python
import aiohttp
import argparse
import asyncio
import colorlog
import json
import logging
import os
import pyalpm
import re
import sys
import tempfile
import time
from urllib.parse import quote
ARCHWEB = "https://archlinux.org"
MIRROR = "https://mirror.pkgbuild.com/"
REPOSITORIES = (
"core-staging", "extra-staging", "multilib-staging",
"core-testing", "extra-testing", "multilib-testing",
)
TODO_CACHE_DIR = os.path.expanduser('~/.cache/todogrep')
TODO_CACHE_TTL = 24 * 60 * 60
logger = colorlog.getLogger()
logger.setLevel(colorlog.INFO)
class ProgressHandler(colorlog.StreamHandler):
progress = ''
def show_progress(self, text):
if self.stream.isatty():
self.progress = text
self.stream.write('\r\033[K' + text)
self.flush()
def emit(self, record):
if self.progress:
self.stream.write('\r\033[K')
super().emit(record)
if self.progress:
self.show_progress(self.progress)
handler = ProgressHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(colorlog.ColoredFormatter())
logger.addHandler(handler)
def read_todo_cache(cache_path):
try:
with open(cache_path, encoding='utf-8') as f:
if not 0 <= time.time() - os.fstat(f.fileno()).st_mtime < TODO_CACHE_TTL:
return None
todo = json.load(f)
if not isinstance(todo, dict) or not isinstance(todo.get('packages'), list):
raise ValueError('expected a todo with a package list')
return todo
except FileNotFoundError:
return None
except (OSError, ValueError) as exc:
logger.debug("Ignoring todo cache: %s", exc)
return None
def write_todo_cache(cache_path, todo):
try:
directory = os.path.dirname(cache_path)
os.makedirs(directory, exist_ok=True)
# Avoid partial cache reads from concurrent invocations.
with tempfile.TemporaryDirectory(dir=directory) as tmpdirname:
with open(f'{tmpdirname}/todo.json', 'w', encoding='utf-8') as f:
json.dump(todo, f)
os.replace(f'{tmpdirname}/todo.json', cache_path)
except OSError as exc:
logger.warning("Cannot save todo cache: %s", exc)
async def get_db(db, session, callback):
full_url = f"{MIRROR}{db}/os/x86_64/{db}.db"
logger.debug(f"Fetching {full_url}")
async with session.get(full_url) as resp:
db_content = await resp.read()
await callback(db, db_content)
async def get_todo(todo_url, session, callback):
full_url = f'{ARCHWEB}/api/v1{todo_url}'
cache_path = os.path.join(TODO_CACHE_DIR, quote(todo_url, safe='') + '.json')
todo = read_todo_cache(cache_path)
if todo is not None:
logger.debug("Using cached %s", full_url)
await callback(todo)
return
logger.debug(f"Fetching {full_url}")
async with session.get(full_url) as resp:
todo = await resp.json()
todo["url"] = todo_url
await callback(todo)
write_todo_cache(cache_path, todo)
async def analyze_overlaps(todo_callback, db_callback):
logger.info("Fetching todo lists")
# Avoid a burst of connections that triggers archlinux.org's firewall.
connector = aiohttp.TCPConnector(limit_per_host=2)
async with aiohttp.ClientSession(connector=connector, raise_for_status=True,
timeout=aiohttp.ClientTimeout(total=60)) as session:
async with session.get(f'{ARCHWEB}/todo/') as resp:
todolist_page = await resp.text()
todolist = re.findall('(/todo/.*?)"', todolist_page)
completelist = re.findall('span class="(complete|incomplete)"', todolist_page)
if 'id="dev-todo-lists"' not in todolist_page or len(todolist) != len(completelist):
raise ValueError(f"{resp.url}: expected a todo list, possibly blocked by the firewall")
tasks = [get_db(db, session, db_callback) for db in REPOSITORIES]
tasks.extend(get_todo(todo_url, session, todo_callback)
for todo_url, iscomplete in zip(todolist, completelist)
if iscomplete == "incomplete")
completed = 0
async def with_progress(task):
nonlocal completed
result = await task
completed += 1
handler.show_progress(f'[{completed}/{len(tasks)}] Checking todos and repositories')
return result
handler.show_progress(f'[0/{len(tasks)}] Checking todos and repositories')
try:
return await asyncio.gather(*(with_progress(task) for task in tasks))
finally:
handler.show_progress('')
async def main(argv=None):
parser = argparse.ArgumentParser(
description='Grep for packages in ongoing todos',
epilog='Individual todo details are cached for 24 hours in ~/.cache/todogrep/; '
'the todo index and repositories are always fetched live. With no positional '
'arguments, read one package or pkgbase per line from standard input. '
'Exit status: 0 if no overlaps are found, 1 if any are found, 2 if the check fails.')
parser.add_argument('-b', '--pkgbase', action='store_true', help='Look for pkgbases instead of pkgnames')
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging')
parser.add_argument('--log-file', metavar='PATH', help='Save debug output and failure tracebacks to a file')
parser.add_argument('package', nargs='*', help='Packages or pkgbases to look for')
args = parser.parse_args(argv)
if not args.package:
if sys.stdin.isatty():
parser.error('at least one package or pkgbase is required')
args.package = [line.strip() for line in sys.stdin if line.strip()]
if not args.package:
parser.error('standard input did not contain any packages or pkgbases')
logger.setLevel(logging.DEBUG if args.debug or args.log_file else logging.INFO)
handler.setLevel(logging.DEBUG if args.debug else logging.INFO)
if args.log_file:
try:
file_handler = logging.FileHandler(args.log_file, encoding='utf-8')
except OSError as exc:
parser.error(f"cannot open log file: {exc}")
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))
logger.addHandler(file_handler)
matched = False
async def check_todo(todo):
nonlocal matched
for p in args.package:
for package in todo["packages"]:
if package is None:
# Package was removed
continue
if ((args.pkgbase and package["pkgbase"] == p)
or (not args.pkgbase and package["pkgname"] == p)):
matched = True
if todo["kind"] == "Rebuild":
logger.error(f"{p} overlaps with {todo['url']}: {todo['name']}")
else:
logger.warning(f"{p} overlaps with {todo['url']}: {todo['name']}")
async def check_db(db, db_content):
nonlocal matched
with tempfile.TemporaryDirectory() as tmpdirname:
os.mkdir(f'{tmpdirname}/sync')
with open(f"{tmpdirname}/sync/{db}.db", "wb") as f:
f.write(db_content)
handle = pyalpm.Handle(".", tmpdirname)
db_handle = handle.register_syncdb(db, 0)
for package in db_handle.search(""):
for p in args.package:
if ((args.pkgbase and package.base == p)
or (not args.pkgbase and package.name == p)):
matched = True
logger.error(f"{p} is already in [{db}]")
try:
logger.debug("Checking packages: %s", ' '.join(args.package))
await analyze_overlaps(check_todo, check_db)
except Exception as exc:
logger.debug("Overlap check failed", exc_info=True)
logger.error("Overlap check failed: %s", exc)
return 2
finally:
if args.log_file:
logger.removeHandler(file_handler)
file_handler.close()
return 1 if matched else 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))