-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
356 lines (331 loc) · 9.47 KB
/
cli.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
const { parse } = require('url');
const http = require('https');
const fs = require('fs');
const { basename } = require('path');
const CONFIG = require('./config.json');
const TIMEOUT = 10000;
(async () => {
/** @type string[] */
const arglist = process.argv.slice(2, process.argv.length);
const args = { _: [] };
for (let i = 0; i < arglist.length; i++) {
if (arglist[i].includes('-')) {
args[arglist[i]] = arglist[i + 1];
i++;
} else {
args['_'].push(arglist[i]);
}
}
// Parse options
const options = parseOptions(args);
const { year, day } = options;
const commands = args['_'];
if (commands.length === 0) {
console.log('No commands given');
printHelp();
return;
}
switch (commands[0]) {
case 'download': {
await downloadInput(year, day, options);
break;
}
case 'copy':
copyFile(year, day, commands[1], options);
break;
case 'submit': {
let result = await submit(year, day, commands[1], commands[2]);
if (result) console.log(`Submit ${year} ${day}: ${parseSubmit(result)}`);
break;
}
case 'prompt': {
await downloadPrompt(year, day, options);
await cleanPrompt(year, day);
break;
}
case 'help':
printHelp();
break;
default:
throw new Error(`Invalid command: ${key}`);
}
})();
// ----------------- COMMANDS -----------------
function copyFile(year, day, ext, options) {
if (!ext) {
console.log('No ext given');
return;
}
const directory = getDirectory(year, day);
maybeCreateDirectory(year, day);
const currentPath = `${directory}/day${day}.${ext}`;
let previousDay = day - 1;
let isComplete = false;
while (previousDay >= 1) {
const file = `day${previousDay}.${ext}`;
const previousPath = `./${year}/day${previousDay}/${file}`;
if (!options.overwrite && fs.existsSync(currentPath)) {
console.log(`File already exists: ${currentPath} (Use to overwrite option to overwrite)`);
isComplete = true;
break;
}
if (fs.existsSync(previousPath)) {
fs.copyFileSync(previousPath, currentPath);
console.log(`Copied file ${previousPath} to ${currentPath}`);
isComplete = true;
break;
}
previousDay--;
}
if (!isComplete) {
console.log('No previous file to copy this year');
}
}
function printHelp() {
console.log(`
Usage: node cli.js [OPTIONS] [COMMAND]
Commands:
download Download puzzle input for the given day
copy <ext> Copies file with given extension from previous day
submit <part> <answer> Submit puzzle answer
prompt Get prompt
help Print this message
Options:
-d, --day <DAY> Puzzle day [default: current day if in December]
-y, --year <YEAR> Puzzle year [default: current year]
-o, --overwrite yes Overwrite file if they already exist
`);
}
// ----------------- UTILS -----------------
function parseOptions(args) {
let today = new Date();
// Provide defaults
let options = {
year: today.getFullYear(),
day: today.getDate(),
overwrite: false,
};
// Puzzle day come out at 9pm PST
if (today.getHours() >= 21) {
options.day += 1;
console.log(`Puzzle day is ${options.day}`);
}
// Puzzles comes out in December (month 11)
if (today.getMonth() < 11) {
options.year -= 1;
console.log(`Puzzle year is ${options.year}`);
}
for (const key of Object.keys(args)) {
if (key === '_') continue;
switch (key) {
case '-d':
case '--day':
options.day = parseInt(args[key], 10);
break;
case '-y':
case '--year':
options.year = parseInt(args[key], 10);
break;
case '-o':
case '--overwrite':
options.overwrite = true;
break;
case '-h':
case '--help':
printHelp();
break;
default:
throw new Error(`Invalid option: ${key}`);
break;
}
}
return options;
}
function getDirectory(year, day) {
return `./${year}/day${day}`;
}
function maybeCreateDirectory(year, day) {
const yearDirectory = `./${year}`;
if (!fs.existsSync(yearDirectory)) {
fs.mkdirSync(yearDirectory);
}
const directory = getDirectory(year, day);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
function downloadInput(year, day, options) {
const directory = getDirectory(year, day);
maybeCreateDirectory(year, day);
let path = `${directory}/input.txt`;
if (!options.overwrite && fs.existsSync(path)) {
console.log(`Input already exists: ${path} (Use to overwrite option to overwrite)`);
return;
}
let url = `https://adventofcode.com/${year}/day/${day}/input`;
const uri = parse(url);
if (!path) {
path = basename(uri.path);
}
const file = fs.createWriteStream(path);
return new Promise(function (resolve, reject) {
const httpOptions = {
headers: {
cookie: `session=${CONFIG.SESSION_ID}`,
},
};
if (CONFIG.USER_AGENT) {
httpOptions.headers['user-agent'] = CONFIG.USER_AGENT;
}
const request = http.get(uri.href, httpOptions).on('response', function (res) {
if (res.statusCode !== 200) {
console.log(`Status code: ${res.statusCode}`);
return reject(new Error('Error fetching input'));
}
const len = parseInt(res.headers['content-length'], 10);
let downloaded = 0;
let percent = 0;
res
.on('data', function (chunk) {
file.write(chunk);
downloaded += chunk.length;
percent = ((100.0 * downloaded) / len).toFixed(2);
process.stdout.write(`Downloading ${percent}% ${downloaded} bytes\r`);
})
.on('end', function () {
file.end();
file.on('finish', () => {
console.log(`${year} ${day} downloaded to: ${path}`);
resolve();
});
})
.on('error', function (err) {
fs.unlink(path);
reject(err);
});
});
request.setTimeout(TIMEOUT, function () {
fs.unlink(path);
request.destroy();
reject(new Error(`request timeout after ${TIMEOUT / 1000.0}s`));
});
});
}
function downloadPrompt(year, day, options) {
const directory = getDirectory(year, day);
maybeCreateDirectory(year, day);
let path = `${directory}/README.md`;
if (!options.overwrite && fs.existsSync(path)) {
console.log(`Prompt already exists: ${path} (Use to overwrite option to overwrite)`);
return;
}
let url = `https://adventofcode.com/${year}/day/${day}`;
const uri = parse(url);
if (!path) {
path = basename(uri.path);
}
const file = fs.createWriteStream(path);
return new Promise(function (resolve, reject) {
const httpOptions = {
headers: {
cookie: `session=${CONFIG.SESSION_ID}`,
},
};
if (CONFIG.USER_AGENT) {
httpOptions.headers['user-agent'] = CONFIG.USER_AGENT;
}
const request = http.get(uri.href, httpOptions).on('response', function (res) {
if (res.statusCode !== 200) {
console.log(`Status code: ${res.statusCode}`);
return reject(new Error('Error fetching prompt'));
}
res.on('error', function (err) {
fs.unlink(path);
reject(err);
});
file.on('finish', () => {
console.log(`${year} ${day} downloaded to: ${path}`);
resolve({});
});
res.pipe(file);
});
request.setTimeout(TIMEOUT, function () {
fs.unlink(path);
request.destroy();
reject(new Error(`request timeout after ${TIMEOUT / 1000.0}s`));
});
});
}
function cleanPrompt(year, day) {
const directory = getDirectory(year, day);
maybeCreateDirectory(year, day);
let path = `${directory}/README.md`;
if (!fs.existsSync(path)) {
console.log(`Prompt does not exist: ${path}`);
return;
}
let file = fs.readFileSync(path, 'utf8');
let lines = file.split('\n');
let isMain = false;
for (let i = 0; i < lines.length; ) {
if (lines[i].includes('main>')) isMain = !isMain;
if (!isMain) lines.splice(i, 1);
else i++;
}
lines.push('</main>', '');
fs.writeFileSync(path, lines.join('\n'));
}
function submit(year, day, part, answer) {
if (!part || !answer) {
console.log('No part or answer given');
return;
}
return new Promise(function (resolve, reject) {
let body = `level=${part}&answer=${answer}`;
const options = {
host: 'adventofcode.com',
path: `/${year}/day/${day}/answer`,
headers: {
accept: 'text/html',
'content-type': 'application/x-www-form-urlencoded',
'content-length': Buffer.byteLength(body),
cookie: `session=${CONFIG.SESSION_ID}`,
},
method: 'POST',
};
if (CONFIG.USER_AGENT) {
options.headers['user-agent'] = CONFIG.USER_AGENT;
}
let request = http.request(options, res => {
res.setEncoding('utf8');
if (res.statusCode !== 200) {
console.log(`Status code: ${res.statusCode}`);
return reject(new Error('Error submitting'));
}
let str = '';
res
.on('data', function (chunk) {
str += chunk;
})
.on('end', function () {
resolve(str);
})
.on('error', function (err) {
reject(err);
});
});
request.write(body);
request.end();
});
}
function parseSubmit(result) {
try {
let [, matches] = [
...result.replaceAll('\n', '').matchAll(/.*\<article\>(.*)\<\/article\>/g),
][0];
return matches;
} catch (error) {
console.log(result);
throw error;
}
}