Last active
April 9, 2016 21:49
-
-
Save williamho/862f9ff21531f9b503333f4f2d1d4141 to your computer and use it in GitHub Desktop.
sbt task to find class in classpath matching a specified name
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
lazy val allClasses = taskKey[Stream[String]]("Classes in classpath") | |
lazy val findClass = inputKey[Stream[String]]("Find classes matching name") | |
findClass := { | |
import complete.DefaultParsers._ | |
val any = ".*" | |
val parts: Seq[String] = spaceDelimited("<arg>").parsed | |
val caseSensitive: Boolean = parts.exists(_.matches(s"$any[A-Z]$any")) | |
val regex: String = (if (caseSensitive) "" else "(?i)") + | |
parts.mkString(any, any, any) | |
val matches: Stream[String] = allClasses.value.filter(_.matches(regex)) | |
matches.foreach(println) | |
matches | |
} | |
allClasses := { | |
import java.io.File | |
def isClass(path: String): Boolean = | |
path.endsWith(".class") && !path.contains("$") | |
fullClasspath.in(Compile).value.toStream.flatMap { attr => | |
val file: File = attr.data | |
val filePath: String = file.getAbsolutePath | |
def clean(path: String): String = path | |
.replaceAll(s"^$filePath", "") | |
.replaceAll(".class$", "") | |
.replaceAll("^/", "") | |
.replace("/", ".") | |
def getClassFileNames(f: File): Iterable[String] = { | |
if (f.isFile) { | |
val path: String = f.getAbsolutePath | |
if (isClass(path)) { | |
Seq(clean(path)) | |
} else if (path.endsWith(".jar")) { | |
// Could do this without an external command, but whatever | |
s"jar tf ${f.getAbsolutePath}" | |
.lines_! | |
.withFilter(isClass) | |
.map(clean) | |
} else Seq.empty | |
} else if (f.isDirectory) { | |
f.listFiles.flatMap(getClassFileNames) | |
} else { | |
Seq.empty | |
} | |
} | |
getClassFileNames(file) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment