Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created December 21, 2020 11:46
Show Gist options
  • Save xuwei-k/6f2b86b0cfefe243aea2dd0a3098320d to your computer and use it in GitHub Desktop.
Save xuwei-k/6f2b86b0cfefe243aea2dd0a3098320d to your computer and use it in GitHub Desktop.
package fix
import scalafix.Diagnostic
import scalafix.Patch
import scalafix.lint.LintSeverity
import scalafix.v1.SyntacticDocument
import scalafix.v1.SyntacticRule
import scala.meta.Pkg
import scala.meta.inputs.Input
import scala.meta.inputs.Position
/**
* TODO Windowsで動かない可能性あり?
*/
class DirectoryAndPackageName extends SyntacticRule("DirectoryAndPackageName") {
override def isLinter = true
override def fix(implicit doc: SyntacticDocument): Patch = {
val packageOpt = doc.tree.collect { case x: Pkg => x }.headOption
val packageObjectOpt =
doc.tree.collect {
case x: Pkg.Object => x
}.headOption
// 以下の2つ以外の処理は、必要なのかよくわかってない
val scalaSourceOpt = PartialFunction
.condOpt(doc.input) {
case f: Input.VirtualFile =>
f.path
case f: Input.File =>
f.path.toString
}
{
for {
path <- scalaSourceOpt
// TODO とりあえずsbtのデフォルトの構成のみを想定して雑にハードコードしてあるが、ここをもっとちゃんとする
dirOpt = Seq(
"/src/main/scala/",
"/src/test/scala/"
).find { dir =>
path.contains(dir)
}.map { dir =>
path.split(dir).last.split('/').init.mkString("/")
}
dir <- dirOpt
pkg <- packageOpt // TODO packageがない場合もチェックする?
packageName = {
val x = pkg.ref.toString.replace('.', '/')
packageObjectOpt match {
case Some(value) =>
x + "/" + value.name.value
case None =>
x
}
}
if packageName != dir
} yield {
Patch.lint(
DirectoryPackageWarn(
path = path,
packageName = packageName,
position = pkg.pos
)
)
}
}.getOrElse(Patch.empty)
}
}
case class DirectoryPackageWarn(path: String, packageName: String, override val position: Position) extends Diagnostic {
override def message: String = s"packageとdirectoryが一致しません\n${path}\n${packageName}"
override def severity: LintSeverity = LintSeverity.Warning
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment