@@ -2,6 +2,7 @@ package com.soberg.kotlin.aoc.api
2
2
3
3
import io.ktor.client.statement.HttpResponse
4
4
import io.ktor.client.statement.bodyAsText
5
+ import kotlinx.coroutines.runBlocking
5
6
import java.nio.file.Files
6
7
import kotlin.io.path.Path
7
8
import kotlin.io.path.createFile
@@ -12,6 +13,18 @@ import kotlin.io.path.writeLines
12
13
class AdventOfCodeInputApi (
13
14
private val cachingStrategy : CachingStrategy ,
14
15
) {
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
+ }
15
28
16
29
/* * Attempts to read from cache based on the specified [cachingStrategy].
17
30
* If no cache is read, this will read from network and attempt to store in cache.
@@ -49,9 +62,9 @@ class AdventOfCodeInputApi(
49
62
)
50
63
if (response.status.value in 200 .. 299 ) {
51
64
return response.bodyAsText()
65
+ // Trim to remove trailing next-line chars.
66
+ .trim()
52
67
.lines()
53
- // Filter on non-blank lines to remove trailing next-line chars
54
- .filter { line -> line.isNotBlank() }
55
68
} else {
56
69
error(" Unexpected response code ${response.status.value} " )
57
70
}
@@ -78,19 +91,21 @@ class AdventOfCodeInputApi(
78
91
data class LocalTextFile (
79
92
val cacheDirPath : String ,
80
93
) : 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 */
82
95
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) )
84
97
return if (path.exists()) {
85
98
path.readLines()
86
99
} else {
87
100
null
88
101
}
89
102
}
90
103
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 */
92
107
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) )
94
109
if (! path.exists()) {
95
110
Files .createDirectories(path.parent)
96
111
path.createFile()
0 commit comments