Skip to content

Instantly share code, notes, and snippets.

@wsargent
Created November 11, 2022 17:44
Show Gist options
  • Save wsargent/db0a928c07ce99bd4149a0577a2cb13a to your computer and use it in GitHub Desktop.
Save wsargent/db0a928c07ce99bd4149a0577a2cb13a to your computer and use it in GitHub Desktop.
package fix
import scalafix.v1._
import scala.meta._
class RewriteToStructured extends SemanticRule("RewriteToStructured") {
override def fix(implicit doc: SemanticDocument): Patch = {
doc.tree.collect {
case [email protected](Term.Select(loggerName, methodName), List(Term.Interpolate(Term.Name("s"), parts, args))) if matchesType(loggerName) =>
println(logger.structureLabeled)
Patch.replaceTree(logger, rewrite(loggerName, methodName, parts, args))
}.asPatch
}
private def matchesType(name: Term)(implicit doc: SemanticDocument): Boolean = {
name match {
case Term.Name(n) if n == "logger" =>
true
case _ =>
false
}
}
private def rewrite(loggerTerm: Term, methodTerm: Term, parts: List[Lit], args: List[Term]): String = {
// if the argument is a literal, like s"${3}" then don't switch it.
// if the argument is a method or function, then don't switch it.
// if the method is a field, then it's safe?
val values = args.map { arg =>
//println("arg = " + arg.structureLabeled)
s"""fb.value("$arg", $arg)"""
}
val literal = parts.map { p =>
p.value.toString
}.mkString("{}")
val statement = if (values.size > 1) {
s"""fb.list(${values.mkString(", ")})"""
} else {
values.mkString("")
}
s"""$loggerTerm.$methodTerm("$literal", fb => $statement)"""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment