Created
February 24, 2023 01:52
-
-
Save dbuschman7/1bfa13c1e04d1f087ae79b6639cd3eb2 to your computer and use it in GitHub Desktop.
Parse Java system properties to extract jars from the class path
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
//> using scala "2.13" | |
//> using platform "jvm" | |
//> using lib "com.rabbitmq:amqp-client:5.16.0" | |
//> using lib "com.typesafe.play::play-json:2.7.4" | |
import play.api.libs.json.{Json, OFormat} | |
object SystemProperties extends App { | |
val sysProps = new SystemProperties(sys.props.get("java.class.path").getOrElse("")) | |
Console.println("Java Version : " + sysProps.javaVersion) | |
val libs = sysProps.jarDependencies() | |
// | |
libs.foreach(println) | |
} | |
final class SystemProperties(rawData: String) { | |
private lazy val rawLines: Seq[String] = rawData.split(":").toSeq | |
private val commonLibSplitKeys: Set[String] = Set("maven2", "jcenter.bintray.com") | |
def jarDependencies(extraSplitKeys: String*): Set[JarDependency] = { | |
val allKeys = commonLibSplitKeys ++ extraSplitKeys | |
rawLines.flatMap { l => | |
val key = allKeys.find(l.contains(_)).getOrElse("not.going.to.match") | |
val jarPath: Option[String] = l.split(key).tail.headOption | |
// println(s"Raw - $l - $key - JarPath - $jarPath") | |
jarPath.map(JarDependency.parse) | |
}.toSet | |
} | |
def javaVersion: String = sys.props.get("java.version").getOrElse("unknown") | |
} | |
case class JarDependency(group: String, artifact: String, version: String, scalaVersion: Option[String], jar: String) | |
object JarDependency { | |
val sVersions: Set[String] = Set("_2.11", "_2.12", "_2.13") | |
implicit class StringPimps(s: String) { | |
def notEmpty: Option[String] = | |
s match { | |
case "" => None | |
case _ => Option(s) | |
} | |
def notBlank: Option[String] = s.notEmpty.flatMap(_ => s.trim.notEmpty) | |
} | |
def parse(in: String): JarDependency = { | |
def stripVersion(in: String): (String, String) = | |
sVersions.find { v => | |
in.contains(v) | |
} match { | |
case None => ("", in) | |
case Some(sVer) => | |
in.indexOf(sVer) match { | |
case n if n < 1 => ("", in) | |
case n => (in.substring(n + 1), in.substring(0, n)) | |
} | |
} | |
val parts: Array[String] = in.split("/").reverse.filterNot(_.isEmpty) | |
val jar = parts.head | |
val version = parts.drop(1).head | |
val (scalaVersion, artifact) = stripVersion(parts.drop(2).head) | |
val group = parts.drop(3).toSeq.reverse.mkString(".") | |
JarDependency(group, artifact, version, scalaVersion.notBlank, jar) | |
} | |
implicit val __json: OFormat[JarDependency] = Json.format[JarDependency] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
scala-cli run SystemProperties.scala