Skip to content

Instantly share code, notes, and snippets.

@scalway
Last active August 4, 2023 09:49
Show Gist options
  • Save scalway/2923bb71983ca94dfc18969b6ad9ab64 to your computer and use it in GitHub Desktop.
Save scalway/2923bb71983ca94dfc18969b6ad9ab64 to your computer and use it in GitHub Desktop.
scala ammonite script that implement `watch -d ""` that shows only diffs. I was using it to see changes in `lsof -p SOMEPROCID` to watch if there are any leaks in my app.
//> using toolkit latest
//> using dep io.github.java-diff-utils:java-diff-utils:4.12
//> using dep com.lihaoyi::fansi::0.4.0
// use like this: scala-cli run . -- 200 lsof -p 28482
import com.github.difflib.*
import com.github.difflib.patch.*
import fansi.*
import os.*
import java.util.stream.Collectors
import java.util.{ArrayList, Arrays, Date, List as JList}
import scala.collection.mutable.Buffer
import scala.reflect.ClassTag
extension (s: String)
def linesJList: JList[String] = s.lines().collect(Collectors.toList())
extension [T <: AnyRef: ClassTag](s: JList[T])
def array: Array[T] = s.toArray[T](new Array[T](s.size()))
def str(p: String, color: EscapeAttr)(target: Array[String]): Array[Str] =
target.map(s => color(p + ": " + s))
def text(d: AbstractDelta[String]): Array[Str] =
def target = d.getTarget.getLines.array
def source = d.getSource.getLines.array
d match
case _: InsertDelta[String] => str(" +", Color.Blue)(target)
case _: ChangeDelta[String] =>
str("~-", Color.LightYellow)(source) ++ str("~+", Color.LightGreen)(target)
case _ => str(" -", Color.Red)(source)
@main def lines(time: Int, cmd: String*): Unit =
def call() = os.proc(cmd).call().toString()
val initState = call()
val cmdStr = cmd.mkString(" ")
while true do
Thread.sleep(time)
val newState = call()
val diffs = DiffUtils.diff(initState.linesJList, newState.linesJList)
print("\u001b[2J\u001b[;H")
val cmdLine = s"CMD: ${cmdStr} TIME:${Date()}"
println(cmdLine)
println("-" * cmdLine.length)
diffs.getDeltas.asScala.flatMap(text).foreach(println)
@scalway
Copy link
Author

scalway commented Jun 10, 2020

Example usage:

amm ./watchDiff.scala 200 lsof -p 1119701

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment