Skip to content
Open
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
4 changes: 4 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ inputs:
max-comment-bytes:
description: "Interdiffs are truncated to keep the comment under this size; GitHub's limit is 65536."
default: "65000"
wrap-width:
description: "Interdiff lines in the comment longer than this are hard wrapped, repeating their diff markers; at least 4, or empty to never wrap."
default: "120"
hide-after-days:
description: "On a force push, hide as outdated the earlier range-diff comments that are at least this many days old; empty keeps them all."
default: "3"
Expand Down Expand Up @@ -55,4 +58,5 @@ runs:
MAX_COMMENT_BYTES: ${{ inputs.max-comment-bytes }}
POST_COMMENT: ${{ inputs.post-comment }}
HIDE_AFTER_DAYS: ${{ inputs.hide-after-days }}
WRAP_WIDTH: ${{ inputs.wrap-width }}
run: bash "$GITHUB_ACTION_PATH/post-range-diff-comment.sh"
9 changes: 6 additions & 3 deletions post-range-diff-comment.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# MAX_COMMENT_BYTES cap on the comment body
# POST_COMMENT "false" to render without posting
# HIDE_AFTER_DAYS hide earlier range-diff comments at least this old
# WRAP_WIDTH optional, hard wrap interdiff lines longer than this
set -euo pipefail

: "${BEFORE:?}" "${AFTER:?}" "${BASE_REF:?}" "${PR_NUMBER:?}"
Expand Down Expand Up @@ -99,11 +100,13 @@ render() {
--old-base "$old_base" --new-base "$new_base" \
--base-behind "$base_behind" --base-ahead "$base_ahead" \
--stats "$WORK/stats.txt" \
--pushed-at "$PUSHED_AT" --max-bytes "$1" <"$WORK/range-diff.txt"
--pushed-at "$PUSHED_AT" --max-bytes "$1" \
${WRAP_WIDTH:+--wrap-width "$WRAP_WIDTH"} <"$WORK/range-diff.txt"
}
render "${MAX_COMMENT_BYTES:-65000}" >"$WORK/comment.md"
# Job summaries allow 1 MiB, so the summary usually holds the untruncated text.
render 1000000 >>"$SUMMARY"
# Job summaries allow 1 MiB, so the summary usually holds the full text.
# Wrapping is left out there because it lengthens the text it would hold.
WRAP_WIDTH='' render 1000000 >>"$SUMMARY"

if [[ ${POST_COMMENT:-true} == false ]]; then
cat "$WORK/comment.md"
Expand Down
52 changes: 52 additions & 0 deletions render.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
r"(?: (?P<subject>.*))?$"
)
BODY_INDENT = " "
# A body line starts with up to two diff markers (none on a range-diff hunk
# header, one on a commit message line) and then its indentation.
HANG = re.compile(r"[ +-]{0,2}[ \t]*")
# Half of this width holds both diff markers, and the other half holds text.
MIN_WRAP_WIDTH = 4
SHORT_SHA = 10
OP_LABEL = {"!": "modified", "=": "unchanged", "<": "dropped", ">": "added"}

Expand Down Expand Up @@ -93,6 +98,11 @@ def main(argv: list[str]) -> int:
default=65000,
help="GitHub caps comment bodies at 65536 bytes",
)
ap.add_argument(
"--wrap-width",
type=wrap_width,
help=f"hard wrap interdiff lines longer than this, at least {MIN_WRAP_WIDTH}; omit to never wrap",
)
ap.add_argument(
"--pushed-at", required=True, help="when the push happened, ISO 8601 UTC"
)
Expand All @@ -114,6 +124,7 @@ def main(argv: list[str]) -> int:
stats=parse_stats(args.stats.read_text()),
max_bytes=args.max_bytes,
pushed_at=args.pushed_at,
wrap_width=args.wrap_width,
)
)
return 0
Expand Down Expand Up @@ -178,6 +189,7 @@ def render(
base_behind: int,
base_ahead: int,
stats: dict[str, Stat],
wrap_width: int | None = None,
) -> str:
counts = {op: sum(1 for p in pairs if p.op == op) for op in OP_LABEL}
tally = (
Expand All @@ -199,6 +211,12 @@ def render(
"",
f"<sup>reproduce: <code>git range-diff {html.escape(old_range)} {html.escape(new_range)}</code></sup>",
]
pairs = [
replace(
p, body=tuple(part for line in p.body for part in wrap(line, wrap_width))
Comment thread
bc1cindy marked this conversation as resolved.
Resolved
)
for p in pairs
]
note = "<i>Some interdiffs were truncated to fit; the full range-diff is in the job summary.</i>"

def assemble(pairs: list[Pair], truncated: bool) -> str:
Expand Down Expand Up @@ -272,6 +290,40 @@ def render_interdiffs(pairs: list[Pair]) -> str:
return "\n\n".join(blocks)


def wrap(line: str, width: int | None) -> list[str]:
"""Split a body line, for reading, into pieces at most `width` long.

Each piece starts with the line's diff markers and indentation, cut to half
of `width` so they cannot fill a piece with spaces. A piece ends after the
last space that fits, and a word longer than the rest of the piece is cut at
the width. `width` is None to keep the line whole, or at least
`MIN_WRAP_WIDTH`.
"""
if width is None or len(line) <= width:
return [line]
markers = hang(line, width)
text = line[HANG.match(line).end() :]
room = width - len(markers)
pieces = []
while len(text) > room:
space = text.rfind(" ", 0, room)
cut = space + 1 if space >= 0 else room
pieces.append(markers + text[:cut])
text = text[cut:]
Comment thread
bc1cindy marked this conversation as resolved.
Resolved
return pieces + [markers + text]


def wrap_width(arg: str) -> int:
width = int(arg)
if width < MIN_WRAP_WIDTH:
raise argparse.ArgumentTypeError(f"must be at least {MIN_WRAP_WIDTH}")
return width


def hang(line: str, width: int) -> str:
return HANG.match(line)[0][: width // 2]
Comment thread
bc1cindy marked this conversation as resolved.
Resolved


def describe_series(pairs: list[Pair]) -> str:
old = sum(p.lnum != "-" for p in pairs)
new = sum(p.rnum != "-" for p in pairs)
Expand Down
12 changes: 11 additions & 1 deletion tests/test_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def run_action(
rewound=(),
comments=None,
post_fails=False,
wrap_width="",
):
# Stands in for GitHub: the old tips of the base branch, the comments
# of the pull request, and a record of the ones it was asked to hide.
Expand Down Expand Up @@ -99,6 +100,7 @@ def run_action(
POST_COMMENT=str(posting).lower(),
GH_TOKEN="token",
HIDE_AFTER_DAYS="3",
WRAP_WIDTH=wrap_width,
PATH=f"{stub}{os.pathsep}{os.environ['PATH']}",
)
command = (
Expand All @@ -125,7 +127,8 @@ def run_action(
self.assertIn("<b>range-diff</b>", result.stdout)
self.assertIn(self.before, result.stdout)
self.assertIn(self.after, result.stdout)
self.assertTrue(result.stdout.endswith(summary.read_text()))
if not wrap_width:
self.assertTrue(result.stdout.endswith(summary.read_text()))
return result.stdout

def test_force_push_full_checkout(self):
Expand Down Expand Up @@ -189,6 +192,13 @@ def test_a_failed_post_hides_nothing(self):
self.run_action(comments=[old], post_fails=True)
self.assertFalse((self.root / "stub" / "hidden").exists())

def test_wrap_width_reaches_the_comment(self):
self.after = self.commit("old\n" + "x" * 40 + "\n", "change", amend=True)
out = self.run_action(wrap_width="20")
self.assertIn("\n++" + "x" * 18 + "\n++" + "x" * 18 + "\n++xxxx\n", out)
summary = (self.root / "summary").read_text()
self.assertIn("\n++" + "x" * 40 + "\n", summary)

def test_force_push_shallow_checkout(self):
self.run_action(shallow=True)

Expand Down
73 changes: 73 additions & 0 deletions tests/test_render.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import argparse
import itertools
import pathlib
import sys
import unittest
Expand Down Expand Up @@ -116,6 +118,77 @@ def test_fence_grows_past_backticks_in_body(self):
self.assertIn("\n````diff\n", out)
self.assertIn("\n````\n", out)

def test_long_lines_wrap_with_their_markers(self):
self.assertEqual(render.wrap("++abcdefgh", 6), ["++abcd", "++efgh"])
self.assertEqual(render.wrap(" -abcd", 6), [" -abcd"])
self.assertEqual(render.wrap("++ab cdef", 6), ["++ab ", "++cdef"])
self.assertEqual(render.wrap("++ab cdefgh", 6), ["++ab ", "++cdef", "++gh"])
self.assertEqual(render.wrap("++ abcdef", 8), ["++ abcd", "++ ef"])
self.assertEqual(render.wrap("- ab cd", 6), ["- ab ", "- cd"])
self.assertEqual(render.wrap("@@ ab cd", 6), ["@@ ab ", "cd"])
self.assertEqual(render.wrap("+ abcdef", 4), ["+ ab", "+ cd", "+ ef"])
self.assertEqual(
render.wrap("++a" + " " * 10 + "abc", 6),
["++a ", "++ ", "++ ", "++abc"],
)
self.assertEqual(render.wrap("++abcdefgh", None), ["++abcdefgh"])

def test_wrap_width_leaves_room_for_markers(self):
self.assertEqual(render.wrap_width("4"), 4)
for arg in ("3", "0", "-1"):
with self.assertRaises(argparse.ArgumentTypeError):
render.wrap_width(arg)

def test_wrapping_keeps_the_text(self):
# Every line up to 7 characters over a small alphabet, at every width:
# the pieces fit, start with the markers and indentation, and rejoin
# to the line, less the indentation past half the width.
# Every piece but the last ends at a space or is cut at the width, and
# a cut at the width splits only a word longer than a piece holds.
for n in range(8):
for chars in itertools.product(" +-@a", repeat=n):
line = "".join(chars)
for width in range(render.MIN_WRAP_WIDTH, 9):
pieces = render.wrap(line, width)
markers = render.hang(line, width)
self.assertTrue(all(len(p) <= width for p in pieces))
self.assertTrue(all(p.startswith(markers) for p in pieces))
if pieces == [line]:
continue
rest = line[render.HANG.match(line).end() :]
self.assertEqual("".join(p[len(markers) :] for p in pieces), rest)
for p in pieces[:-1]:
self.assertTrue(p.endswith(" ") or len(p) == width)
texts = [p[len(markers) :] for p in pieces]
for a, b in itertools.pairwise(texts):
if not a.endswith(" ") and not b.startswith(" "):
word = a.rsplit(" ", 1)[-1] + b.split(" ", 1)[0]
self.assertGreater(len(word), width - len(markers))

def test_wrapped_lines_are_truncated_by_line(self):
# The line fits unwrapped, but its wrapped pieces do not. Halving
# them keeps the fence closed, which a byte cut would not.
text = "1: aaaaaaa ! 1: bbbbbbb s\n ++" + "x" * 63500 + "\n"
out = render.render(
render.parse(text),
repo_url=REPO,
before=BEFORE,
after=AFTER,
old_range="a..b",
new_range="a..c",
max_bytes=65000,
pushed_at="2026-09-17T00:10:17Z",
old_base="",
new_base="",
base_behind=0,
base_ahead=0,
stats={},
wrap_width=80,
)
self.assertLessEqual(len(out.encode()), 65000)
self.assertIn("Some interdiffs were truncated", out)
self.assertEqual(out.count("```"), 2)

def test_truncation_fits_and_is_noted(self):
full = render_basic()
cap = len(full.encode()) - 100
Expand Down
Loading