Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Last active October 19, 2020 09:43
Show Gist options
  • Save PaulWoitaschek/e63a766e35921e7fd1df47f7f81df811 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/e63a766e35921e7fd1df47f7f81df811 to your computer and use it in GitHub Desktop.
#!/usr/bin/env kotlin
@file:DependsOn("com.github.ajalt.clikt:clikt-jvm:3.0.1")
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.output.TermUi
class App : CliktCommand() {
enum class DaemonType {
Gradle, Kotlin
}
data class Daemon(
val type: DaemonType,
val processId: Int,
val version: String
)
override fun run() {
val daemons = Runtime.getRuntime().exec("ps aux").inputStream.bufferedReader()
.readLines()
.filter { line -> line.contains("gradle") || line.contains("kotlin") }
.mapNotNull { line ->
val processId = "[ \\t]+(.*?)[ ]".toRegex().find(line)!!.groupValues.drop(1).first().toInt()
val gradleVersion =
"org.gradle.launcher.daemon.bootstrap.GradleDaemon (.*)".toRegex().find(line)?.groupValues?.drop(1)?.firstOrNull()
if (gradleVersion == null) {
val kotlinVersion = "kotlin-compiler-embeddable\\/(.*?)\\/".toRegex().find(line)?.groupValues?.drop(1)?.firstOrNull()
if (kotlinVersion != null) {
Daemon(type = DaemonType.Kotlin, version = kotlinVersion, processId = processId)
} else {
null
}
} else {
Daemon(type = DaemonType.Gradle, version = gradleVersion, processId = processId)
}
}
.groupBy { it.type }
.mapValues { it.value.sortedByDescending { it.version } }
.flatMap { it.value }
val promptItems = daemons
.mapIndexed { index, daemon ->
"[${index + 1}]\t${daemon.type}\t${daemon.version}"
}
.joinToString(separator = "\n")
TermUi.echo(promptItems)
val selectedDaemons = TermUi.prompt("Enter the numbers, separated by commas you want to kill") { input ->
input.split(",").map { rawNumber ->
val index = (rawNumber.toIntOrNull() ?: -1) - 1
daemons.getOrElse(index) {
throw UsageError("Invalid input")
}
}
}!!
selectedDaemons.forEach { daemon ->
Runtime.getRuntime().exec("kill -9 ${daemon.processId}")
}
}
}
App().main(args)
@Kardelio
Copy link

Can I ask abit of a silly question....
This file, does it need to be part of a gradle project itself with a build.gradle to get the clikt dependency?
Or I guess the question is how does one run it from the terminal whilst grabbing the dependencies needed?
Thanks!

@PaulWoitaschek
Copy link
Author

I created a repo for this:
https://github.com/PaulWoitaschek/AndroidDaemonKiller/blob/main/README.md

You just execute it, the kotlin compiler will fetch the dependencies and cache the compilation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment