Last active
July 16, 2022 16:41
-
-
Save beigirad/0d8797833da24e19278872021f5fa7ba to your computer and use it in GitHub Desktop.
Moshi to kotlinx.serialization model convertor script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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