-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc.py
executable file
·360 lines (283 loc) · 10.4 KB
/
aoc.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python3
# I finally wrote the CLI as a wrapper of my own scripts and [aoc-cli](https://github.com/scarvalhojr/aoc-cli) 😎
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
import click
class AliasedGroup(click.Group):
"""This subclass of a group supports looking up aliases in a config
file and with a bit of magic.
"""
_aliases = {}
@classmethod
def aliases(cls, a):
class AliasedClass(cls):
_aliases = a
return AliasedClass
def get_command(self, ctx, cmd_name):
# Step one: bulitin commands as normal
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
# Step two: find the config object and ensure it's there. This
# will create the config object is missing.
# cfg = ctx.ensure_object(self.__class__)
cfg = self
# Step three: look up an explicit command alias in the config
if cmd_name in cfg._aliases:
actual_cmd = cfg._aliases[cmd_name]
return click.Group.get_command(self, ctx, actual_cmd)
# Alternative option: if we did not find an explicit alias we
# allow automatic abbreviation of the command. "status" for
# instance will match "st". We only allow that however if
# there is only one command.
matches = [x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")
def resolve_command(self, ctx, args):
# always return the command's name, not the alias
_, cmd, args = super().resolve_command(ctx, args)
return cmd.name, cmd, args
@dataclass
class AocProject:
scripts_dir: Path
aoc_root: Path
def pass_thru(self, tool: str, args: list, cwd=None):
if not Path(os.getcwd()).is_relative_to(self.aoc_root):
if Path(__file__).is_symlink():
cwd = Path(__file__).resolve().parent.parent
else:
raise click.ClickException("not in AoC project")
cmd = [self.scripts_dir / tool]
cmd.extend(args)
subprocess.call(cmd, cwd=cwd)
@click.group(
invoke_without_command=False,
cls=AliasedGroup.aliases(
{
"r": "run",
"p": "private-leaderboard",
"i": "inputs",
"in": "inputs",
}
),
)
@click.pass_context
def aoc(ctx: click.Context):
"""CLI for Advent of Code daily tasks."""
script = Path(__file__).resolve()
assert script.name == "aoc.py"
assert script.parent.name == "scripts"
ctx.obj = AocProject(script.parent, script.parent.parent)
if ctx.invoked_subcommand:
return
@aoc.command(name="install")
@click.pass_context
def aoc_install(ctx: click.Context):
"""
Install the CLI into ~/.local/bin .
"""
f = Path(__file__)
if f.is_symlink():
raise click.ClickException("Launch command with the real file, not the symlink.")
if os.getuid() == 0:
# probably into a container
cli = Path("/usr/local/bin/aoc").expanduser()
cli.unlink(True)
cli.parent.mkdir(parents=True, exist_ok=True)
cli.symlink_to(f)
click.echo("Command aoc has been installed in /usr/local/bin .")
else:
cli = Path("~/.local/bin/aoc").expanduser()
cli.unlink(True)
cli.parent.mkdir(parents=True, exist_ok=True)
cli.symlink_to(f)
click.echo("Command aoc has been installed in ~/.local/bin .")
@aoc.command(name="private-leaderboard")
@click.option("-y", "--year", type=int, help="Year")
@click.argument("id", type=int)
@click.pass_context
def aoc_private_leaderboard(ctx: click.Context, year: int, id: int):
"""
Show the state of a private leaderboard.
"""
cmd = ["aoc-cli", "private-leaderboard", str(id)]
if year:
cmd.extend(["--year", str(year)])
subprocess.run(cmd)
@aoc.command(name="calendar", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def aoc_calendar(ctx: click.Context):
"""
Show Advent of Code calendar and stars collected.
"""
subprocess.run(["aoc-cli", "calendar"] + ctx.args)
@aoc.command(name="download", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def aoc_download(ctx: click.Context):
"""
Save puzzle description and input to files.
"""
subprocess.run(["aoc-cli", "download"] + ctx.args)
@aoc.command(name="puzzle")
@click.argument("day", type=int, default=0)
@click.pass_context
def aoc_puzzle(ctx: click.Context, day: int):
"""
Get input and write templates.
"""
ctx.obj.pass_thru("puzzle.sh", [str(day)])
@aoc.command(name="run", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def aoc_run(ctx: click.Context):
"""
Run all puzzles.
"""
ctx.obj.pass_thru("runall.py", ctx.args)
@aoc.command(name="clippy")
@click.pass_context
def aoc_clippy(ctx: click.Context):
"""
Run the Rust clippy checker.
"""
cwd = Path(os.getcwd())
if cwd == ctx.obj.aoc_root:
for year in sorted(cwd.glob("*")):
if year.name.isdigit() and int(year.name) >= 2015:
print("--------------------------------")
print(f"| Year {year.name}")
print("--------------------------------")
sys.stdout.flush()
ctx.obj.pass_thru("lint_rust.sh", [], cwd=year)
else:
if not (cwd / "Cargo.toml").is_file():
raise click.ClickException("need a Cargo.toml file")
ctx.obj.pass_thru("lint_rust.sh", [])
@aoc.command(name="test")
@click.pass_context
def aoc_test(ctx: click.Context):
"""
Run cargo test.
"""
cwd = Path(os.getcwd())
if cwd == ctx.obj.aoc_root:
for year in sorted(cwd.glob("*")):
if year.name.isdigit() and int(year.name) >= 2015:
print("--------------------------------")
print(f"| Year {year.name}")
print("--------------------------------")
sys.stdout.flush()
subprocess.call(["cargo", "test", "--", "--test-threads", "4"], cwd=year)
else:
if not (cwd / "Cargo.toml").is_file():
raise click.ClickException("need a Cargo.toml file")
subprocess.call(["cargo", "test", "--", "--test-threads", "4"])
@aoc.command(name="answers", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def aoc_answers(ctx: click.Context):
"""
Submits answer or the them.
"""
ctx.obj.pass_thru("answers.py", ctx.args)
@aoc.command(name="readme")
@click.pass_context
def aoc_readme(ctx: click.Context):
"""
Make all the README.md.
"""
ctx.obj.pass_thru("answers.py", ["--readme", "-w"])
@aoc.command(name="inputs")
@click.pass_context
def aoc_inputs(ctx: click.Context):
"""
Show the number of available inputs.
"""
ctx.obj.pass_thru("inputs.py", [])
@aoc.command(name="scores")
@click.option("-y", "--year", type=int, help="Year")
@click.argument("id", type=int)
@click.pass_context
def aoc_scores(ctx: click.Context, year: int, id: int):
"""
Show details of a private leaderboard.
"""
args = [str(id)]
if year:
args.extend(["--year", str(year)])
ctx.obj.pass_thru("score.py", args)
@aoc.command(name="quality")
@click.option("-s", "--strict", is_flag=True, help="Forbid clippy rule")
@click.pass_context
def aoc_quality(ctx: click.Context, strict: bool):
"""
Run lints, tests, solutions for Rust solution.
"""
cwd = Path(os.getcwd())
dirs = []
if cwd == ctx.obj.aoc_root:
for year in sorted(cwd.glob("*")):
if year.name.isdigit() and int(year.name) >= 2015:
dirs.append(year)
elif Path("Cargo.toml").is_file():
dirs.append(".")
else:
raise click.ClickException("need a Cargo.toml file or root directory")
for d in dirs:
if d != ".":
sys.stdout.write("\033[1;31m")
print("--------------------------------")
print(f"| Year {d.name}")
print("--------------------------------")
sys.stdout.write("\033[0m")
sys.stdout.flush()
os.chdir(d)
try:
print("cargo fmt")
subprocess.check_output(["cargo", "fmt"])
print("cargo clippy")
if strict:
subprocess.check_output(
["cargo", "clippy", "-q", "--", "-Fclippy::all", "-Fclippy::pedantic", "-Fclippy::nursery"]
)
else:
subprocess.check_output(
["cargo", "clippy", "-q", "--", "-Dclippy::all", "-Dclippy::pedantic", "-Fclippy::nursery"]
)
print("cargo build")
subprocess.check_output(["cargo", "build", "--release", "--quiet"])
except subprocess.CalledProcessError:
pass
try:
print("cargo test")
subprocess.check_output(["cargo", "test", "--quiet", "--", "--test-threads", "4"])
except subprocess.CalledProcessError:
pass
# print("answers")
# output = subprocess.check_output([ctx.obj.scripts_dir / "answers.py"])
# for line in output.decode().splitlines():
# if " ok " not in line and " unknown " not in line: print(line)
try:
print("run all")
env = os.environ.copy()
env["CLICOLOR_FORCE"] = "1"
output = subprocess.check_output([ctx.obj.scripts_dir / "runall.py", "--me", "-l", "rust"], env=env)
print(output.decode())
# for line in output.decode().splitlines():
# if " ok " not in line and " unknown " not in line:
# print(line)
except subprocess.CalledProcessError:
pass
@aoc.command(name="timings", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def aoc_timings(ctx: click.Context):
"""
Show or browse elapsed time for each puzzle.
"""
ctx.obj.pass_thru("timings.py", ctx.args)
if __name__ == "__main__":
aoc()