Skip to content

Instantly share code, notes, and snippets.

@fourlastor
Created March 7, 2023 08:21
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 fourlastor/d2156f59f5c71824d054c1ef421f5bac to your computer and use it in GitHub Desktop.
Save fourlastor/d2156f59f5c71824d054c1ef421f5bac to your computer and use it in GitHub Desktop.
Class public api comparator
import spoon.Launcher
import spoon.reflect.declaration.CtClass
import spoon.reflect.declaration.CtNamedElement
import java.io.File
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.size < 2) {
println("You need to pass two paths")
exitProcess(1)
}
val f0 = File(args[0]).readText()
val f1 = File(args[1]).readText()
val c1 = Launcher.parseClass(f0)
val c0 = Launcher.parseClass(f1)
c0.compare(c1) { publicFields() }
c0.compare(c1) { publicMethods() }
}
private inline fun CtClass<*>.compare(other: CtClass<*>, extractor: CtClass<*>.() -> Sequence<CtNamedElement>) {
val thisListOfElements = extractor()
val otherListOfElements = other.extractor()
if (thisListOfElements.count() != otherListOfElements.count()) {
println("Different methods/fields count in classes $simpleName and ${other.simpleName}")
exitProcess(1)
}
if (thisListOfElements.zip(otherListOfElements).any { (first, second) -> first.simpleName != second.simpleName }) {
println("Different named methods/fields in classes $simpleName and ${other.simpleName}")
exitProcess(1)
}
}
private fun CtClass<*>.publicMethods() = methods.asSequence().filter { !it.isPrivate }.sortedBy { it.simpleName }
private fun CtClass<*>.publicFields() = fields.asSequence().filter { !it.isPrivate }.sortedBy { it.simpleName }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment