@@ -2,6 +2,7 @@ package com.soberg.kotlin.aoc.api
22
33import io.ktor.client.statement.HttpResponse
44import io.ktor.client.statement.bodyAsText
5+ import kotlinx.coroutines.runBlocking
56import java.nio.file.Files
67import kotlin.io.path.Path
78import kotlin.io.path.createFile
@@ -12,6 +13,18 @@ import kotlin.io.path.writeLines
1213class AdventOfCodeInputApi (
1314 private val cachingStrategy : CachingStrategy ,
1415) {
16+ /* * Blocking (non-coroutine) version of [readInput]. */
17+ fun blockingReadInput (
18+ year : Int ,
19+ day : Int ,
20+ sessionToken : String ,
21+ ) = runBlocking {
22+ readInput(
23+ year = year,
24+ day = day,
25+ sessionToken = sessionToken,
26+ )
27+ }
1528
1629 /* * Attempts to read from cache based on the specified [cachingStrategy].
1730 * If no cache is read, this will read from network and attempt to store in cache.
@@ -49,9 +62,9 @@ class AdventOfCodeInputApi(
4962 )
5063 if (response.status.value in 200 .. 299 ) {
5164 return response.bodyAsText()
65+ // Trim to remove trailing next-line chars.
66+ .trim()
5267 .lines()
53- // Filter on non-blank lines to remove trailing next-line chars
54- .filter { line -> line.isNotBlank() }
5568 } else {
5669 error(" Unexpected response code ${response.status.value} " )
5770 }
@@ -78,19 +91,21 @@ class AdventOfCodeInputApi(
7891 data class LocalTextFile (
7992 val cacheDirPath : String ,
8093 ) : CachingStrategy {
81- /* * Attempts to read from a local cache file in the format <cacheDirPath>/year/ day.txt */
94+ /* * Attempts to read from a local cache file in the format <cacheDirPath>/< year>/Day< day> .txt */
8295 override fun tryRead (year : Int , day : Int ): List <String >? {
83- val path = Path (cacheDirPath, " $year " , " $ day.txt " )
96+ val path = Path (cacheDirPath, " $year " , filenameForDay( day) )
8497 return if (path.exists()) {
8598 path.readLines()
8699 } else {
87100 null
88101 }
89102 }
90103
91- /* * Attempts to write to a local cache file in the format <cacheDirPath>/year/day.txt */
104+ private fun filenameForDay (day : Int ) = " Day${" %02d" .format(day)} .txt"
105+
106+ /* * Attempts to write to a local cache file in the format <cacheDirPath>/<year>/Day<day>.txt */
92107 override fun write (year : Int , day : Int , lines : List <String >) {
93- val path = Path (cacheDirPath, " $year " , " $ day.txt " )
108+ val path = Path (cacheDirPath, " $year " , filenameForDay( day) )
94109 if (! path.exists()) {
95110 Files .createDirectories(path.parent)
96111 path.createFile()
0 commit comments