-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·404 lines (334 loc) · 12.8 KB
/
index.js
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env node
import path from 'path';
import fs from 'fs/promises';
import commander from 'commander';
import makeDir from 'make-dir';
import { LiveContainer } from 'clui-live';
import timeSpan from 'time-span';
import chalk from 'chalk';
import {
processYearDayArgument, processYearDayPartArgument,
validateYear, validateDay, validatePart, parsePuzzleString
} from '#lib/puzzle-string';
import configurePuzzleLogging from '#lib/log';
import { ConsoleRenderer, AttemptState, AnimationState } from '#lib/puzzle-renderer';
import { isAsyncFunction, isAsyncGeneratorFunction } from '#lib/is-function';
import delay from '#lib/delay';
import { downloadPuzzleInput, submitPuzzleAnswer } from '#lib/aoc-api';
import dotenv from 'dotenv-safe';
dotenv.config({ allowEmptyValues: true });
const __filename = import.meta.url.replace('file://', '');
const __dirname = path.dirname(__filename);
main().catch(
e => { console.error(e); process.exit(process.exitCode === 0 ? 1 : process.exitCode); }
);
async function main() {
const program = new commander.Command();
// new
program
.command('new')
.description('Create a new puzzle folder.')
.argument(
'[puzzle]',
'The puzzle to create a folder for, formatted as `YEAR/DAY`. If omitted, it will create the next puzzle in the current year.',
processYearDayArgument,
'latest'
)
.action(handleNewSubcommand);
// run
program
.command('run')
.description('Run a puzzle solution.')
.argument(
'<puzzle>',
'The puzzle to run, formatted as `PART` or `YEAR/DAY/PART`. If omitted, it will run the latest puzzle.',
processYearDayPartArgument,
'latest'
)
.option('--tests', 'run test cases instead of the real puzzle input')
.option('--debug', 'enable debug logging within puzzles (implied by --tests)')
.option('--silent', 'disable debug logging within puzzles')
.option('--submit', 'submit the answer to adventofcode.com after the puzzle is run (has no effect when used with --tests)')
.action(handleRunSubcommand);
// test
program
.command('test')
.description('Run puzzle test cases. Alias for using --tests with the `run` command.')
.argument(
'<puzzle>',
'The puzzle to run, formatted as `PART` or `YEAR/DAY/PART`. If omitted, it will run the latest puzzle.',
processYearDayPartArgument,
'latest'
)
.option('--silent', 'disable debug logging within puzzles')
.action(async (puzzle, options, command) => {
options.tests = true;
return handleRunSubcommand(puzzle, options, command);
});
// submit
program
.command('submit')
.description('Run the puzzle and submit the answer to adventofcode.com. Alias for using --submit with the `run` command.')
.argument(
'<puzzle>',
'The puzzle to run, formatted as `PART` or `YEAR/DAY/PART`. If omitted, it will run the latest puzzle.',
processYearDayPartArgument,
'latest'
)
.option('--debug', 'enable debug logging within puzzles')
.action(async (puzzle, options, command) => {
options.submit = true;
return handleRunSubcommand(puzzle, options, command);
});
program.parse(process.argv);
}
async function handleNewSubcommand(puzzle, options, command) {
let year = null, day = null;
if(puzzle === 'latest') {
year = await getLatestYear();
day = await getLatestDay(year);
day += 1; // we want to create the NEXT day after the latest one
if(!validateDay(day)) {
console.error(`Cowardly refusing to create ${year}/${day}. Try giving a specific YEAR/DAY.`);
process.exitCode = 1;
return;
}
} else {
let parsed = parsePuzzleString(puzzle);
year = parsed.year;
day = parsed.day;
}
createPuzzle(year, day);
}
async function handleRunSubcommand(puzzle, options, command) {
const runTests = options.tests;
const submitAnswer = runTests ? false : options.submit;
const logLevel = runTests ?
(options.silent ? 'silent' : 'debug') :
(options.debug ? 'debug' : 'silent');
configurePuzzleLogging(logLevel);
let year = null, day = null, part = null;
if(puzzle !== 'latest') {
let parsed = parsePuzzleString(puzzle);
year = parsed.year;
day = parsed.day;
part = parsed.part;
}
if(year === null) {
year = await getLatestYear();
}
if(day === null) {
day = await getLatestDay(year);
}
if(part === null) {
part = 1;
}
// run the puzzle
run(year, day, part, {
inputs: { real: !runTests, tests: runTests, file: null }, // TODO: remove file
submit: submitAnswer,
});
}
async function getLatestYear() {
const entries = await fs.readdir(path.join(__dirname, 'puzzles'));
const EXCLUDE = process.env.EXCLUDE_YEARS ? process.env.EXCLUDE_YEARS.split(',') : [];
const years = entries.filter(name => validateYear(name)).filter(name => !EXCLUDE.includes(name)).map(x => +x);
return Math.max(...years);
}
async function getLatestDay(year) {
try {
const entries = await fs.readdir(path.join(__dirname, 'puzzles', year.toString(10)));
const days = entries.filter(name => validateDay(name)).map(x => +x);
return Math.max(...days);
} catch (ex) {
// we're here if the year directory doesn't exist yet
return 0;
}
}
async function run(year, day, part, options = { inputs: { file: null, real: true, tests: false }, submit: false }) {
// gather everything we'll need
const PUZZLE_DIR = path.join(__dirname, `puzzles/${year}/${day}`);
const fn = await getPuzzleFn(PUZZLE_DIR, part);
const attempts = await gatherAttempts(PUZZLE_DIR, part, options.inputs);
console.log(`Running puzzle 📯 ${year} 🌅 ${day} 🧩 ${part}:`);
// first, run the tests
for(let attempt of attempts.tests) {
await runAttempt(fn, attempt);
}
// then run the real thing
if(attempts.real) {
const answer = await runAttempt(fn, attempts.real);
if(options.submit) {
await delay(100); // XXX: papering over a bug where clui-live won't flush when areas are closed
await submitPuzzle(year, day, part, answer);
}
}
}
async function getPuzzleFn(puzzleDir, part) {
const parts = await import(path.join(puzzleDir, 'puzzle.js'));
const fn = parts.default['part' + part];
if(!isAsyncFunction(fn) && !isAsyncGeneratorFunction(fn)) {
throw new Error(`Puzzle ${year}/${day} part ${part} is not an async function or an async generator function! (This may mean it doesn't exist or isn't getting exported.)`);
}
return fn;
}
async function gatherAttempts(puzzleDir, part, inputTypes = { file: null, real: true, tests: false }) {
const attempts = { real: null, tests: [] };
if(inputTypes.real || inputTypes.file) {
const filename = inputTypes.file || 'input.txt';
const contents = await fs.readFile(path.join(puzzleDir, filename), { encoding: 'utf-8' });
attempts.real = {
name: filename,
isTest: false,
input: contents,
expected: null,
options: null,
};
}
if(inputTypes.tests) {
const expected = (await gatherExpectedValues(puzzleDir)).filter(obj => obj.part === part);
for(let entry of expected) {
const contents = await fs.readFile(path.join(puzzleDir, entry.file), { encoding: 'utf-8' });
attempts.tests.push({
name: entry.file,
isTest: true,
input: contents,
expected: entry.output === undefined ? null : entry.output,
options: entry.options === undefined ? null : entry.options,
});
}
}
return attempts;
}
async function gatherExpectedValues(puzzleDir) {
let expected = [];
try {
const expectedContents = await fs.readFile(path.join(puzzleDir, 'expected.json'), { encoding: 'utf-8' });
expected = JSON.parse(expectedContents);
} catch(e) {
console.warn(`Could not load or parse expected.json (${e.message}). Continuing without it...`);
}
return expected;
}
async function runAttempt(fn, attempt) {
const attemptState = new AttemptState(attempt.name, attempt.isTest, attempt.expected);
const statusRenderer = new ConsoleRenderer(attemptState);
statusRenderer.open(true);
statusRenderer.render();
let result, elapsed;
if(isAsyncGeneratorFunction(fn)) {
({ result, elapsed } = await runGeneratorFn(fn, attempt, statusRenderer));
} else if(isAsyncFunction(fn)) {
({ result, elapsed } = await runAsyncFn(fn, attempt));
} else {
throw new Error('Unknown puzzle function type! Use an async function or an async generator function.');
}
attemptState.finish(result, elapsed);
statusRenderer.render();
statusRenderer.close();
return result;
}
async function runAsyncFn(fn, attempt) {
const end = timeSpan();
const result = await fn(attempt.input, attempt.options || undefined);
const elapsed = end();
return {
result,
elapsed
};
}
const UPDATE_DELAY_MS = 100;
async function runGeneratorFn(fn, attempt, statusRenderer) {
const animationState = new AnimationState();
const animationRenderer = new ConsoleRenderer(animationState);
animationRenderer.open();
const end = timeSpan();
const generator = fn(attempt.input, attempt.options || undefined);
let next, result;
while(next = await generator.next()) {
if(next.done) {
result = next.value;
break;
}
const { frame, msg } = next.value;
animationRenderer.update(frame);
statusRenderer.update(msg);
await delay(UPDATE_DELAY_MS);
}
const elapsed = end();
animationRenderer.close();
return { result, elapsed };
}
async function submitPuzzle(year, day, part, answer) {
const container = new LiveContainer().hook();
const submitArea = container.createLiveArea().pin();
submitArea.write(`📡 Submitting answer for 📯 ${year} 🌅 ${day} 🧩 ${part}...`);
try {
const result = await submitPuzzleAnswer(year, day, part, answer);
if(result.success) {
submitArea.write(chalk.green(`📡 The answer for 📯 ${year} 🌅 ${day} 🧩 ${part} has been submitted!`));
} else {
const UNSUCCESSFUL_SUBMISSION_MESSAGES = {
'incorrect': chalk.yellow(`📡 The answer for 📯 ${year} 🌅 ${day} 🧩 ${part} was not accepted as correct.`),
'timeout': chalk.redBright(`⏲ The answer for 📯 ${year} 🌅 ${day} 🧩 ${part} could not be submitted due to rate-limiting.`),
'solved': chalk.green(`💾 The answer for 📯 ${year} 🌅 ${day} 🧩 ${part} was already submitted and accepted. Move on to the next puzzle!`),
'unknown': chalk.yellow(`💾 The answer for 📯 ${year} 🌅 ${day} 🧩 ${part} could not be submitted (not sure why).`),
};
submitArea.write(UNSUCCESSFUL_SUBMISSION_MESSAGES[result.reason]);
}
} catch(err) {
console.error(err);
submitArea.write(chalk.redBright(`📡 Submitting answer for 📯 ${year} 🌅 ${day} 🧩 ${part} failed.`));
}
submitArea.close();
}
async function createPuzzle(year, day) {
const SKELETON_DIR = path.join(__dirname, 'skel');
const YEAR_DIR = path.join(__dirname, 'puzzles', year.toString(), day.toString());
const PUZZLE_DIR = path.join(__dirname, 'puzzles', year.toString(), day.toString());
const container = new LiveContainer().hook();
// first, determine if the desired puzzle already exists
const checkArea = container.createLiveArea();
checkArea.write(`Checking if the puzzle directory for ${year}/${day} (${PUZZLE_DIR}) exists...`);
try {
await fs.access(YEAR_DIR);
await fs.access(PUZZLE_DIR);
// if we're still here, the directory exists, so warn and bail
checkArea.write(`Checking if the puzzle directory for ${year}/${day} (${PUZZLE_DIR}) exists... it does! Nothing left to do.`);
checkArea.close();
return;
} catch(x) {
// the directory does not exist, so keep going
checkArea.write(`Checking if the puzzle directory for ${year}/${day} (${PUZZLE_DIR}) exists... nope. Good!`);
checkArea.close();
}
const createArea = container.createLiveArea();
createArea.write(`Creating ${PUZZLE_DIR}...`);
await makeDir(PUZZLE_DIR);
createArea.write(`Creating ${PUZZLE_DIR}... done!`);
createArea.close();
const cloneArea = container.createLiveArea();
cloneArea.write(`Cloning the puzzle skeleton into ${PUZZLE_DIR}...`);
const skelFiles = await fs.opendir(SKELETON_DIR);
for await(let file of skelFiles) {
if(file.isFile()) {
console.log(` - ${file.name}`);
await fs.copyFile(path.join(SKELETON_DIR, file.name), path.join(PUZZLE_DIR, file.name));
}
}
cloneArea.write(`Cloning the puzzle skeleton into ${PUZZLE_DIR}... done!`);
cloneArea.close();
if(process.env.DOWNLOAD_INPUTS === '1') {
const downloadArea = container.createLiveArea();
downloadArea.write(`Downloading input for ${year}/${day}...`);
try {
const puzzleInput = await downloadPuzzleInput(year, day);
await fs.writeFile(path.join(PUZZLE_DIR, 'input.txt'), puzzleInput);
downloadArea.write(`Downloading input for ${year}/${day}... done!`);
} catch(err) {
downloadArea.append(err.message);
} finally {
downloadArea.close();
}
}
}