Created
March 11, 2021 05:24
-
-
Save xuwei-k/512617fb44851939cb6d7eb6b8f4d8aa to your computer and use it in GitHub Desktop.
This file contains 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
package fix | |
import scalafix.Diagnostic | |
import scalafix.Patch | |
import scalafix.lint.LintSeverity | |
import scalafix.v1.SyntacticDocument | |
import scalafix.v1.SyntacticRule | |
import java.io.File | |
import java.nio.file.Path | |
import scala.meta.Pkg | |
import scala.meta.inputs.Input | |
import scala.meta.inputs.Position | |
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 | |
val scalaSourceOpt = PartialFunction | |
.condOpt(doc.input) { | |
case f: Input.VirtualFile => | |
f.path | |
case f: Input.File => | |
// sbt 1.4以降だとおそらく必ず VirtualFile になって、こちらは必要ないが、一応定義しておく | |
f.path.toString | |
} | |
{ | |
for { | |
path <- scalaSourceOpt | |
// Windowsの場合は動かない可能性がある雑コードなので、実行しない | |
if !scala.util.Properties.isWin | |
// TODO 他にいい方法が思いつかないので、とりあえずsbtのデフォルトの構成のみを想定して雑にハードコードしてある | |
(baseDir, dir) <- Seq( | |
"/src/main/scala/", | |
"/src/test/scala/" | |
).find { dir => | |
path.contains(dir) | |
}.map { dir => | |
dir -> path.split(dir).last.split('/').init.mkString("/") | |
} | |
pkg <- packageOpt // TODO packageがない場合もチェックする? | |
if packageObjectOpt.isEmpty // package objectは一旦除く | |
packageName = pkg.ref.toString.replace('.', '/') | |
if packageName != dir | |
} yield { | |
val fileName = path.split('/').last | |
val from = new File(path).toPath | |
val to = { | |
val dir = path.split(baseDir).head + "/" + baseDir + "/" + packageName | |
java.nio.file.Files.createDirectories(new File(dir).toPath) | |
new File(dir + "/" + fileName).toPath | |
} | |
java.nio.file.Files.move(from, to) | |
Patch.lint( | |
DirectoryPackageWarn( | |
path = path, | |
packageName = packageName, | |
from = from, | |
to = to, | |
position = pkg.pos | |
) | |
) | |
} | |
}.getOrElse(Patch.empty) | |
} | |
} | |
case class DirectoryPackageWarn( | |
path: String, | |
packageName: String, | |
from: Path, | |
to: Path, | |
override val position: Position | |
) extends Diagnostic { | |
override def message: String = s"packageとdirectoryが一致しません\n${path}\n${packageName}\n${from}から${to}に移動します" | |
override def severity: LintSeverity = LintSeverity.Warning | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment