Skip to content

Instantly share code, notes, and snippets.

@felipecsl felipecsl/extensions.kt
Last active Jan 30, 2018

Embed
What would you like to do?
Helpful Kotlin extension functions
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import org.gradle.api.Task
import org.gradle.api.Project
import org.gradle.api.UnknownTaskException
import org.gradle.api.GradleException
import org.gradle.api.plugins.ExtraPropertiesExtension
@SuppressWarnings("UNCHECKED_CAST")
fun <T> Project.ext(key: String): T {
val ext = extensions.getByName("ext") as ExtraPropertiesExtension
if (!ext.has(key)) {
throw GradleException("Project $project does not have ext property named $key")
} else {
return ext[key] as T
}
}
fun Task.runAfter(dependentTaskName: String) {
try {
val taskToFind = project.tasks.getByName(dependentTaskName)
taskToFind.finalizedBy(this)
} catch (e: UnknownTaskException) {
project.tasks.whenTaskAdded { dependentTask ->
if (dependentTask.name == dependentTaskName) {
dependentTask.finalizedBy(this)
}
}
}
}
fun Task.runBefore(dependentTaskName: String) {
try {
val taskToFind = project.tasks.getByName(dependentTaskName)
taskToFind.dependsOn(this)
} catch (e: UnknownTaskException) {
project.tasks.whenTaskAdded { dependentTask ->
if (dependentTask.name == dependentTaskName) {
dependentTask.dependsOn(this)
}
}
}
}
/** Creates a task with the provided name and klass if one doesn't already exist. */
inline fun <reified T : Task> Project.createTaskIfNeeded(name: String): T {
@Suppress("UNCHECKED_CAST")
return tasks.findByName(name) as T? ?: project.tasks.create(name, T::class.java)
}
fun Project.hasTask(name: String) = tasks.findByName(name) != null
fun File.makeExecutable() =
Files.setPosixFilePermissions(toPath(), setOf(PosixFilePermission.OWNER_EXECUTE))
fun String.execute(workingDir: File = project.projectDir): Process =
ProcessBuilder(*split(" ").toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.start()
fun String.executeAndCaptureStdout(workingDir: File) =
StringBuilder().let {
val process = execute(workingDir)
waitForProcessOutput(process, it, null)
it.toString()
}
fun <T> String.asJsonMap(): Map<String, T> {
val mapper = ObjectMapper()
val typeReference = object : TypeReference<Map<String, T>>() {}
val javaType = mapper.typeFactory.constructType(typeReference)
return mapper.readerFor(javaType).readValue<Map<String, T>>(this)
}
/** Splits the input iterable in groups of `groupSize` size */
fun <T> Iterable<T>.inGroupsOf(groupSize: Int) =
mapIndexed { index, t -> index to t }
.groupBy { (index, _) -> index / groupSize }
.map { it -> it.value.map { (_, el) -> el } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.