import kong.unirest.Unirest import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.SourceSetContainer import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.getByType import java.io.File import java.time.LocalDateTime open class AdventOfCodeExtension { var session: String? = null var year: Int = 2020 } class AdventOfCodePlugin : Plugin { override fun apply(project: Project) { project.tasks.create("aoc") { group = "Advent of Code" description = "Download the input of the day" val extension = project.extensions.create("adventOfCode") doLast { if (extension.session == null) { throw GradleException("advent of code session not set") } val resourceDir: File = project .project(":days") .extensions .getByType() .getByName("main") .resources .srcDirs .first() val currentDay = LocalDateTime.now().dayOfMonth.toString() val outFile = File(resourceDir, "day" + currentDay.padStart(length = 2, padChar = '0') + ".txt") val url = "https://adventofcode.com/${extension.year}/day/$currentDay/input" Unirest.get(url) .cookie("session", extension.session) .header("Accept", "text/plain") .asString() .ifFailure { throw GradleException("Failed to get input, got status ${it.status}") } .ifSuccess { outFile.writeText(it.body) println("Saved input for day $currentDay") } } } } }