Created
June 2, 2025 03:11
-
-
Save xuwei-k/66e9aae68acdac5ab45a593188ff2ee8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 scala.meta._ | |
import scalafix.v1._ | |
class ThenReturn extends SyntacticRule("ThenReturn") { | |
val exclude = Seq("") | |
override def fix(implicit doc: SyntacticDocument): Patch = { | |
doc.input match { | |
case f: Input.VirtualFile if exclude.exists(f.path.contains) => | |
Patch.empty | |
case _ => | |
Option | |
.when(doc.tree.collect { case Term.Name("andThen") => | |
() | |
}.isEmpty) { | |
val result = doc.tree.collect { | |
case Term.ApplyInfix.After_4_6_0( | |
a, | |
returns @ Term.Name("returns"), | |
Type.ArgClause(Nil), | |
Term.ArgClause( | |
List( | |
b | |
), | |
None | |
) | |
) if Option(a).collect { | |
case Term.Select( | |
Term.Placeholder(), | |
_: Term.Name | |
) => | |
() | |
}.isEmpty && a.collect { case Term.Name("when") => () }.isEmpty && !b.is[Term.PartialFunction] => | |
Seq( | |
Patch.addAround(a, "Mockito.when(", ")."), | |
Patch.replaceTree(returns, "thenReturn("), | |
Patch.addRight(b, ")") | |
).asPatch | |
case Term.Apply.After_4_6_0( | |
Term.Select( | |
a, | |
returns @ Term.Name("returns") | |
), | |
Term.ArgClause( | |
List( | |
b | |
), | |
None | |
) | |
) if Option(a).collect { | |
case Term.Select( | |
Term.Placeholder(), | |
_: Term.Name | |
) => | |
() | |
}.isEmpty && a.collect { case Term.Name("when") => () }.isEmpty && !b.is[Term.PartialFunction] => | |
Seq( | |
Patch.addAround(a, "Mockito.when(", ")"), | |
Patch.replaceTree(returns, "thenReturn") | |
).asPatch | |
} | |
Option | |
.when(result.nonEmpty) { | |
Seq( | |
result.asPatch, | |
Option | |
.when(doc.tree.collect { case importer"org.mockito.Mockito" => | |
() | |
}.isEmpty) { | |
Patch.addGlobalImport(importer"org.mockito.Mockito") | |
} | |
.asPatch | |
).asPatch | |
} | |
.asPatch | |
} | |
.asPatch | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment