Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active July 29, 2022 01:20
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 xuwei-k/62e303b543540a08ea00460105c50171 to your computer and use it in GitHub Desktop.
Save xuwei-k/62e303b543540a08ea00460105c50171 to your computer and use it in GitHub Desktop.
import scalafix.Diagnostic
import scalafix.Patch
import scalafix.lint.LintSeverity
import scalafix.v1.SyntacticDocument
import scalafix.v1.SyntacticRule
import scala.meta.Defn
import scala.meta.Tree
import scala.meta.inputs.Input
import scala.meta.inputs.Position
class TooLarge extends SyntacticRule("TooLarge") {
private def classLimit = 500
private val treeToLimit: PartialFunction[Tree, (Int, String)] = {
case _: Defn.Def => (100, "method")
case _: Defn.Trait => (classLimit, "trait")
case _: Defn.Object => (classLimit, "object")
case _: Defn.Class => (classLimit, "class")
}
private val pf: PartialFunction[Tree, Patch] = Function.unlift { (t: Tree) =>
treeToLimit.lift.apply(t).map {
case (limit, name) =>
val size = t.pos.endLine - t.pos.startLine
if (limit < size) {
Patch.lint(TooLargeWarn(position = t.pos, name = name, size = size))
} else {
Patch.empty
}
}
}
override def fix(implicit doc: SyntacticDocument): Patch = {
val scalaSourcePathOpt = PartialFunction.condOpt(doc.input) {
case f: Input.VirtualFile =>
f.path
case f: Input.File =>
f.path.toString
}
// TODO support Windows
if (!scala.util.Properties.isWin && scalaSourcePathOpt.exists(_.contains("/src/main/"))) {
doc.tree.collect(pf).asPatch
} else {
Patch.empty
}
}
}
case class TooLargeWarn(override val position: Position, name: String, size: Int) extends Diagnostic {
override def message = s"${name} is too large! ${size}"
override def severity = LintSeverity.Warning
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment