-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.js
executable file
·300 lines (266 loc) · 8.33 KB
/
init.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
#!/usr/bin/env node
const https = require("https")
const fsp = require("fs/promises")
const fs = require("fs")
const path = require("path")
const {spawn} = require("child_process")
const readline = require("readline")
main()
async function main() {
const { envPath, envPairs } = await parseEnv();
const {day, paddedDay, year, onlyPuzzle} = await parseArgs()
console.log(onlyPuzzle)
const {folderName, folderPath} = await makePuzzleDirectory()
if(onlyPuzzle){
await writePuzzle();
process.exit(0)
}
await writePuzzle();
await writeInput();
await createSolution();
async function parseEnv() {
const envPath = path.resolve(__dirname, ".env");
const envData = await fsp.readFile(envPath, "utf-8");
const envPairs = envData.split("\n");
for (const pair of envPairs) {
const keyValDelimiter = pair.indexOf("=");
const key = pair.substring(0, keyValDelimiter);
const val = pair.substring(keyValDelimiter + 1);
if (!process.env[key]) {
process.env[key] = val;
}
}
return {
envPath,
envPairs
}
}
async function parseArgs() {
const [nodePath, selfPath, ...scriptArgs] = process.argv;
const argObj = parseScriptArgs()
const day = parseDay();
const paddedDay = padLeft(day);
const year = await parseYear();
const onlyPuzzle = argObj["only-puzzle"]
return {
day,
paddedDay,
year,
onlyPuzzle
};
function parseScriptArgs(){
return scriptArgs.reduce((out, curr) => {
const [key, val] = curr.split("=");
return {
...out,
[key.slice(2)]: val ? val : true,
};
}, {});
}
function parseDay() {
class InvalidDayException extends Error {
constructor() {
super("You must include a day, either as the sole numerical argument or as '--day=<NUM>'");
this.name = "InvalidDayError";
}
}
let day
if (!isNaN(scriptArgs[0]) && Number(scriptArgs[0]) < 26) {
day = scriptArgs[0];
} else if (argObj.day && !isNaN(argObj.day)) {
day = argObj.day;
} else {
throw new InvalidDayException();
}
return day
}
async function parseYear() {
class InvalidYearException extends Error {
constructor() {
super("You must include a valid year, either in the .env file or as '--year=<NUM>'");
this.name = "InvalidDayError";
}
}
let year
if (argObj.year && !isNaN(argObj.year)) {
year = argObj.year
if(Number(year) !== Number(process.env.YEAR)){
await updatePrompt()
}
} else if (process.env.YEAR) {
year = process.env.YEAR
} else {
throw new InvalidYearException()
}
return year
function updatePrompt(){
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve, reject) => {
rl.question("Would you like to update your .env with the new year? [y/n] > ", async (yOrN) => {
if(!["y", "n"].includes(yOrN.toLowerCase())){
rl.write("Invalid input - please input 'y' or 'n'")
rl.close()
reject()
await updatePrompt()
} else if(yOrN.toLowerCase() === "y") {
const entry = `YEAR=${year}`
if(!fs.existsSync(envPath)){
await fsp.writeFile(envPath, entry)
} else {
const yearIndex = envPairs.findIndex(ea => ea.startsWith("YEAR"))
envPairs[yearIndex] = entry
await fsp.writeFile(envPath, envPairs.join("\n"))
}
}
rl.close()
resolve()
})
})
}
}
}
async function makePuzzleDirectory() {
console.log("Create puzzle directory")
const folderName = `day-${paddedDay}`;
const folderPath = path.resolve(__dirname, year, folderName);
if (!fs.existsSync(folderPath)) {
console.log("Creating puzzle directory...")
await fsp.mkdir(folderPath, {recursive: true});
console.log("Puzzle directory created!")
} else {
console.log("Directory already exists")
}
return {folderName, folderPath}
}
function writePuzzle(){
console.log("Get puzzle.")
const fileName = `day-${paddedDay}.txt`;
const filePath = path.resolve(folderPath, fileName)
const fileStream = fs.createWriteStream(filePath, {flags: "w"})
return new Promise((resolve, reject) => {
const puzzleReqOptions = {
hostname: "adventofcode.com",
path: `/${year}/day/${day}`,
port: 443,
method: "GET",
headers: {
Cookie: [process.env.COOKIE],
},
};
const puzzleReq = https.request(puzzleReqOptions, res => {
console.log(`Requesting puzzle...received ${res.statusCode} response`)
res.on("error", e => {
console.error(e)
reject(e)
})
res.on("data", d => {
console.log("Writing response to puzzle file...")
fileStream.write(d)
})
})
puzzleReq.on("error", e => console.error(e))
puzzleReq.end()
console.log("Puzzle retrieved!")
resolve()
})
}
async function writeInput(){
console.log("Get puzzle input")
const fileName = `day-${paddedDay}-input.txt`
const filePath = path.resolve(folderPath, fileName)
const fileStream = fs.createWriteStream(filePath, {flags: "w"})
const inputReqOptions = {
hostname: "adventofcode.com",
path: `/${year}/day/${day}/input`,
port: 443,
method: "GET",
headers: {
Cookie: [process.env.COOKIE]
}
};
const inputReq = https.request(inputReqOptions, res => {
console.log(`Requesting puzzle input...received ${res.statusCode} status code`);
res.on("data", d => {
console.log("Writing puzzle input response to file...")
fileStream.write(d)
})
})
inputReq.on("error", e => console.error(e))
inputReq.end()
console.log("Puzzle input retrieved!")
}
async function createSolution(){
return new Promise(async (resolve, reject) => {
console.log("Create boilerplate solution file.")
const fileName = `day-${paddedDay}.js`
const filePath = path.resolve(folderPath, fileName)
console.log("Writing boilerplate solution file...")
if(fs.existsSync(filePath)){
await overwritePrompt()
} else {
await writeBoilerplate()
resolve()
}
async function overwritePrompt(){
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((innerResolve, innerReject) => {
rl.question("It appears this file already exists. Would you like to overwrite it? [y/n] > ", async (yOrN) => {
if(!["y", "n"].includes(yOrN.toLowerCase())){
rl.write("Invalid input - please input 'y' or 'n'")
rl.close()
innerReject()
await overwritePrompt()
} else if(yOrN.toLowerCase() === "y") {
await writeBoilerplate()
resolve()
}
rl.close()
innerResolve()
})
})
}
async function writeBoilerplate(){
await fsp.writeFile(
filePath,
`
const fsp = require("fs/promises")
const path = require("path")
main()
async function main(){
const input = await parseInput()
console.log("Part one:", partOne(input))
console.log("Part two:", partTwo(input))
}
async function parseInput(){
const rawInput = await fsp.readFile(path.resolve(__dirname, "day-${paddedDay}-input.txt"), "utf-8")
const input = rawInput.split("\\n").filter(Boolean)
return input
}
function partOne(input){
console.log(input)
}
function partTwo(input){
console.log(input)
}
`
);
}
console.log("Boilerplate solution file written! Testing input reading...")
const runBase = spawn(`node`, [`day-${paddedDay}.js`], {cwd: folderPath})
runBase.stdout.on("data", (d) => process.stdout.write(d));
})
}
function padLeft(num){
if(num < 10){
return `0${num}`
} else {
return num.toString()
}
}
}