adventofcode/adventofcode.nim

64 lines
1.8 KiB
Nim
Raw Permalink Normal View History

2023-01-25 18:11:20 +01:00
#[
This file works by doing a lot of assumptions
about the project folder structure.
For instance, it assumes the executable
directory to be something in a "YYYY/DD"
format.
It also assumes the session key to be
available at the project root.
(in other words "../../session.key")
]#
2021-12-30 16:31:29 +01:00
import
2022-01-05 09:09:10 +01:00
std/httpclient,
std/os,
std/strformat,
std/strutils
2023-01-25 18:11:20 +01:00
when isMainModule:
stderr.writeLine "adventofcode> This can not be ran directly."
quit 1
let sessionKeyPath = os.getAppDir() / ".." / ".." / "session.key"
if not fileExists sessionKeyPath:
stderr.writeLine "adventofcode> secret.key could not be found."
let sessionKey = readFile sessionKeyPath
if sessionKey[0 ..< 10] == "\x00GITCRYPT\x00":
stderr.writeLine "adventofcode> secret.key is encrypted."
quit 1
2021-12-30 16:31:29 +01:00
proc getInput*(year, day: int): string =
2023-01-25 18:11:20 +01:00
## Automatically downloads the input from
## AdventOfCode, unless there is a local copy
## of the input as 'input.txt' in the app dir.
let inputPath = os.getAppDir() / "input.txt"
if fileExists inputPath:
echo "adventofcode> Proceeding with current input.txt file."
let input = readFile inputPath
2021-12-30 16:31:29 +01:00
2022-01-02 10:50:00 +01:00
return input.strip(chars = {'\n'})
2023-01-25 18:11:20 +01:00
else:
2022-01-01 13:56:01 +01:00
echo "adventofcode> Missing input.txt. Downloading..."
2021-12-30 16:31:29 +01:00
let client = newHttpClient()
2023-01-25 18:11:20 +01:00
client.headers = newHttpHeaders({ "Cookie": fmt"session={sessionKey}" })
2021-12-30 16:31:29 +01:00
let input = client.getContent fmt"https://adventofcode.com/{year}/day/{day}/input"
2023-01-25 18:11:20 +01:00
writeFile(inputPath, input)
2021-12-30 16:31:29 +01:00
2023-01-25 18:11:20 +01:00
return input.strip(chars = {'\n'})
proc getInput*(): string =
## Tries to determine year and date of
## day by looking at the app dir path.
let day = block:
let p = os.getAppDir().splitPath()
p.tail.parseInt()
let year = block:
let p = os.getAppDir().parentDir().splitPath()
p.tail.parseInt()
result = getInput(year, day)