Skip to content

Instantly share code, notes, and snippets.

@beigirad
Last active July 16, 2022 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beigirad/0d8797833da24e19278872021f5fa7ba to your computer and use it in GitHub Desktop.
Save beigirad/0d8797833da24e19278872021f5fa7ba to your computer and use it in GitHub Desktop.
Moshi to kotlinx.serialization model convertor script
import java.io.File
val importPattern = "import com\\.squareup\\.moshi\\.JsonClass".toRegex()
val jsonAttrPattern = "^(.*)\\@Json\\(name \\= (\".*\")\\)".toRegex()
val jsonClassPattern = "^(.*)\\@JsonClass\\(generateAdapter \\= true\\)".toRegex()
val root = File("/Users/farhad/Projects/Otgahak/Host")
root.walkTopDown()
.filter { it.extension == "kt" }
.filter { it.readText().contains(importPattern) }
.forEach { file ->
val text = file.readText()
println("$file")
println("BEFORE:")
println(text)
println()
println()
val lines = text.split("\n")
val after = lines.joinToString("") { line ->
buildString {
var wroteLine = false
importPattern.find(line)?.let {
appendLine(line)
wroteLine = true
appendLine("import kotlinx.serialization.SerialName")
appendLine("import kotlinx.serialization.Serializable")
}
jsonClassPattern.find(line)?.let {
val space = it.groupValues[1]
appendLine("$space@Serializable")
appendLine(line)
wroteLine = true
}
jsonAttrPattern.find(line)?.let {
val name = it.groupValues[2]
val space = it.groupValues[1]
appendLine("$space@SerialName($name)")
appendLine(line)
wroteLine = true
}
if (wroteLine.not())
appendLine(line)
}
}
println("AFTER:")
println(after)
file.writeText(after.trimEnd())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment