Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 67 additions & 28 deletions src/main/scala/sbtghactions/GenerativePlugin.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1019,8 +1019,8 @@ ${indent(jobs.map(compileJob(_, sbt)).mkString("\n\n"), 1)}
}

def reportMismatch(file: File, expected: String, actual: String): Unit = {
log.error(s"Expected:\n$expected")
log.error(s"Actual:\n${diff(expected, actual)}")
log.error(s"Differences between ${file.getName} (-) and the generated workflow (+):")
log.error(colorDiff(diff(actual, expected)))
sys.error(s"${file.getName} does not contain contents that would have been generated by sbt-github-actions; try running githubWorkflowGenerate")
}

Expand Down Expand Up @@ -1051,32 +1051,71 @@ ${indent(jobs.map(compileJob(_, sbt)).mkString("\n\n"), 1)}
},
githubWorkflowDir := baseDirectory.value / ".github")

private[sbtghactions] def diff(expected: String, actual: String): String = {
val expectedLines = expected.split("\n", -1)
val actualLines = actual.split("\n", -1)
val (lines, _) = expectedLines.zipAll(actualLines, "", "").foldLeft((Vector.empty[String], false)) {
case ((acc, foundDifference), (expectedLine, actualLine)) if expectedLine == actualLine =>
(acc :+ actualLine, foundDifference)
case ((acc, false), ("", actualLine)) =>
val previousLineLength = acc.lastOption.map(_.length).getOrElse(0)
val padding = " " * previousLineLength
val highlight = s"$padding^ (additional lines)"
(acc :+ highlight :+ actualLine, true)
case ((acc, false), (_, "")) =>
val previousLineLength = acc.lastOption.map(_.length).getOrElse(0)
val padding = " " * previousLineLength
val highlight = s"$padding^ (missing lines)"
(acc :+ highlight, true)
case ((acc, false), (expectedLine, actualLine)) =>
val sameCount = expectedLine.zip(actualLine).takeWhile({ case (a, b) => a == b }).length
val padding = " " * sameCount
val highlight = s"$padding^ (different character)"
(acc :+ actualLine :+ highlight, true)
case ((acc, true), (_, "")) =>
(acc, true)
case ((acc, true), (_, actualLine)) =>
(acc :+ actualLine, true)
/**
* The hunks of a unified diff of `from` to `to`, with three unchanged lines
* of context around each change. Lines are compared including their line
* terminators, so line ending differences show up as changed lines. Empty
* if `from` and `to` are equal.
*/
private[sbtghactions] def diff(from: String, to: String): String = {
val context = 3
val fromLines = from.linesWithSeparators.toVector
val toLines = to.linesWithSeparators.toVector

// longestCommon(i)(j) is the length of the longest common subsequence of
// fromLines.drop(i) and toLines.drop(j)
val longestCommon = Array.ofDim[Int](fromLines.length + 1, toLines.length + 1)
for (i <- fromLines.indices.reverse; j <- toLines.indices.reverse)
longestCommon(i)(j) =
if (fromLines(i) == toLines(j)) longestCommon(i + 1)(j + 1) + 1
else math.max(longestCommon(i + 1)(j), longestCommon(i)(j + 1))

// Each edit is a line prefixed with ' ' (unchanged), '-' (only in from) or
// '+' (only in to), along with the index of the next line in from and in to
@tailrec
def edits(i: Int, j: Int, acc: Vector[(String, Int, Int)]): Vector[(String, Int, Int)] =
if (i < fromLines.length && j < toLines.length && fromLines(i) == toLines(j))
edits(i + 1, j + 1, acc :+ ((" " + fromLines(i).stripLineEnd, i, j)))
else if (i < fromLines.length && (j == toLines.length || longestCommon(i + 1)(j) >= longestCommon(i)(j + 1)))
edits(i + 1, j, acc :+ (("-" + fromLines(i).stripLineEnd, i, j)))
else if (j < toLines.length)
edits(i, j + 1, acc :+ (("+" + toLines(j).stripLineEnd, i, j)))
else
acc

val allEdits = edits(0, 0, Vector.empty)
val changes = allEdits.indices.filterNot(allEdits(_)._1.startsWith(" "))

// Changes whose context would overlap are shown in the same hunk
val hunks = changes.foldLeft(Vector.empty[(Int, Int)]) {
case (init :+ ((first, last)), change) if change - last <= 2 * context + 1 =>
init :+ ((first, change))
case (acc, change) =>
acc :+ ((change, change))
}
lines.mkString("\n")

hunks.flatMap { case (first, last) =>
val hunk = allEdits.slice(math.max(first - context, 0), last + context + 1)
val (_, fromStart, toStart) = hunk.head
val fromCount = hunk.count(!_._1.startsWith("+"))
val toCount = hunk.count(!_._1.startsWith("-"))
// As in diff -u, an empty range starts at the line before it
def start(index: Int, count: Int) = if (count == 0) index else index + 1
s"@@ -${start(fromStart, fromCount)},$fromCount +${start(toStart, toCount)},$toCount @@" +:
hunk.map(_._1)
}.mkString("\n")
}

/** Colors the lines of a [[diff]] the way git does. */
private[sbtghactions] def colorDiff(diff: String): String = {
import scala.Console.{CYAN, GREEN, RED, RESET}
diff.linesIterator.map { line =>
line.headOption match {
case Some('-') => s"$RED$line$RESET"
case Some('+') => s"$GREEN$line$RESET"
case Some('@') => s"$CYAN$line$RESET"
case _ => line
}
}.mkString("\n")
}
}
153 changes: 101 additions & 52 deletions src/test/scala/sbtghactions/GenerativePluginSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1109,62 +1109,111 @@ class GenerativePluginSpec extends Specification {
}

"diff" should {
"highlight the first different character" in {
val expected =
"""abc
|
|def
|
|ghi""".stripMargin
val actual =
"""abc
|
|df
|
|ghi""".stripMargin
"show a changed line with its context" in {
val from =
"""a
|b
|c
|d
|e
|f
|g
|h
|""".stripMargin
val to =
"""a
|b
|c
|d
|E
|f
|g
|h
|""".stripMargin
val expectedDiff =
"""abc
|
|df
| ^ (different character)
|
|ghi""".stripMargin
val actualDiff = GenerativePlugin.diff(expected, actual)
expectedDiff mustEqual actualDiff
}
"highlight the missing lines" in {
val expected =
"""abc
|def
|ghi""".stripMargin
val actual =
"""abc
|def""".stripMargin
"""@@ -2,7 +2,7 @@
| b
| c
| d
|-e
|+E
| f
| g
| h""".stripMargin
diff(from, to) mustEqual expectedDiff
}

"show missing and additional lines" in {
val from =
"""a
|b
|c
|""".stripMargin
val to =
"""b
|c
|d
|""".stripMargin
val expectedDiff =
"""@@ -1,3 +1,3 @@
|-a
| b
| c
|+d""".stripMargin
diff(from, to) mustEqual expectedDiff
}

"show changes that are far apart as separate hunks" in {
val numbers = (1 to 20).map(_.toString)
val from = numbers.map(_ + "\n").mkString
val to = numbers.map {
case "3" => "three\n"
case "18" => "eighteen\n"
case n => n + "\n"
}.mkString
val expectedDiff =
"""abc
|def
| ^ (missing lines)""".stripMargin
val actualDiff = GenerativePlugin.diff(expected, actual)
expectedDiff mustEqual actualDiff
"""@@ -1,6 +1,6 @@
| 1
| 2
|-3
|+three
| 4
| 5
| 6
|@@ -15,6 +15,6 @@
| 15
| 16
| 17
|-18
|+eighteen
| 19
| 20""".stripMargin
diff(from, to) mustEqual expectedDiff
}

"show a missing final line terminator as a changed line" in {
val expectedDiff =
"""@@ -1,2 +1,2 @@
| a
|-b
|+b""".stripMargin
diff("a\nb", "a\nb\n") mustEqual expectedDiff
}
"highlight the additionl lines" in {

"be empty for equal contents" in {
diff("a\nb\n", "a\nb\n") mustEqual ""
}
}

"colorDiff" should {
"color removed lines red, added lines green and hunk headers cyan" in {
import scala.Console.{CYAN, GREEN, RED, RESET}
val expected =
"""abc
|def
|ghi""".stripMargin
val actual =
"""abc
|def
|ghi
|jkl""".stripMargin
val expectedDiff =
"""abc
|def
|ghi
| ^ (additional lines)
|jkl""".stripMargin
val actualDiff = GenerativePlugin.diff(expected, actual)
expectedDiff mustEqual actualDiff
s"""$CYAN@@ -1,2 +1,2 @@$RESET
| a
|$RED-b$RESET
|$GREEN+B$RESET""".stripMargin
colorDiff(diff("a\nb\n", "a\nB\n")) mustEqual expected
}
}

Expand Down
Loading