Skip to content

Instantly share code, notes, and snippets.

@jeeger
Created December 14, 2022 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeeger/6e39fea94ce49e33d1fa43f40cc36630 to your computer and use it in GitHub Desktop.
Save jeeger/6e39fea94ce49e33d1fa43f40cc36630 to your computer and use it in GitHub Desktop.
Get Advent of Code input in babashka.
#!/bin/env bb
(require '[babashka.fs :as fs])
(require '[babashka.curl :as curl])
(defn get-day-component []
(let [components (fs/components (fs/cwd))]
(-> (filter #(str/starts-with? % "day") components)
first)))
(defn get-day-number [day-name]
(-> (str/replace day-name "day" "")
Integer/parseInt))
(defn build-url [day]
(format "https://adventofcode.com/2022/day/%s/input" day))
(defn get-day-url []
(let [day-name (get-day-component)]
(when day-name
(build-url (get-day-number day-name)))))
(def cookie-value (edn/read (java.io.PushbackReader. (io/reader (fs/file (fs/parent *file*) "aoc-cookie")))))
(defn fetch-input []
(let [url (get-day-url)]
(when url
(curl/get url {:raw-args ["-b" (format "session=%s" cookie-value)]}))))
(defn output-file []
(loop [comp (fs/components (fs/cwd))]
(if (str/starts-with? (last comp) "day")
(str (fs/file "/" (apply fs/file comp) "input.txt"))
(recur (butlast comp)))))
(let [out (output-file)]
(and (not (fs/exists? out))
(spit (io/writer out) (:body (fetch-input)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment