From b8edc131254b8de66f8bf067e7e5adf7a0185fd8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:37:44 +0000 Subject: [PATCH 1/5] Add a one-sentence-per-line checker for blog posts --- scripts/sentence_per_line.py | 665 ++++++++++++++++++++++++++++++ scripts/test_sentence_per_line.py | 641 ++++++++++++++++++++++++++++ 2 files changed, 1306 insertions(+) create mode 100755 scripts/sentence_per_line.py create mode 100644 scripts/test_sentence_per_line.py diff --git a/scripts/sentence_per_line.py b/scripts/sentence_per_line.py new file mode 100755 index 00000000..6b2f3ec4 --- /dev/null +++ b/scripts/sentence_per_line.py @@ -0,0 +1,665 @@ +#!/usr/bin/env python3 +"""Check, and optionally fix, "one sentence per line" in blog Markdown. + +Rule 1 of CONTRIBUTING-BLOG-POST.md asks for one sentence per line in the +Markdown source, because GitHub anchors review suggestions to lines. +Sentences can be any length; this only looks for lines that hold more than one. + + python3 scripts/sentence_per_line.py [PATH ...] # check + python3 scripts/sentence_per_line.py --fix [PATH ...] # rewrite in place + python3 scripts/sentence_per_line.py --github [PATH ...] # GitHub annotations + +PATH defaults to content/blog; directories are searched for *.md files. +Exit status is 0 when clean, 1 when violations exist, 2 on a usage error. + +--fix only replaces the whitespace between two sentences with a line break +plus the prefix the new line needs to stay in the same list item or +blockquote, so the rendered page does not change. + +Standard library only, Python 3.9 or newer. +""" + +import argparse +import os +import re +import sys +from collections import namedtuple + +# Words that end with a period without ending the sentence. +# Compared case-insensitively against the word before the period. +# Single-letter initials ("J. Smith") and letter-dot runs ("U.S.", "a.m.") +# are also recognized by shape, so unlisted ones of that form are covered. +ABBREVIATIONS = frozenset( + """ + e.g. i.e. etc. vs. cf. viz. al. approx. ca. esp. resp. incl. + mr. mrs. ms. dr. prof. sr. jr. st. mt. + no. nos. fig. figs. vol. ch. sec. pp. eq. ref. ver. dept. + jan. feb. mar. apr. jun. jul. aug. sep. sept. oct. nov. dec. + u.s. u.k. e.u. a.m. p.m. ph.d. + """.split() +) + +Violation = namedtuple("Violation", "line col sentences excerpt") + +# A sentence end: terminators, optional closing quotes/brackets/emphasis, +# then horizontal whitespace. What follows is checked by _starts_sentence. +END_RE = re.compile(r"([.!?]+)([\"'\u201d\u2019)\]*_~]*)([ \t]+)") +OPENERS = "\"'\u201c\u2018([*_~" +INITIALISM_RE = re.compile(r"(?:[A-Za-z]\.)+[A-Za-z]") + +# Text that would turn into a block construct if it started a line. +BLOCK_START_RE = re.compile(r"\d{1,9}[.)](?:[ \t]|$)|`{3,}|~{3,}|\[[^\]]+\]:") + +# Block-level patterns. Most are applied to a line with its container +# prefix (blockquote markers, list markers, indentation) removed. +BQ_RE = re.compile(r"[ \t]*>[ ]?") +MARKER_RE = re.compile(r"[ \t]*([-*+]|(\d{1,9})[.)])(?:[ \t]+|$)") +HR_RE = re.compile(r"[ \t]*(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$") +SETEXT_RE = re.compile(r"(?:=+|-{2,})[ \t]*$") +ATX_RE = re.compile(r"#{1,6}(?:[ \t]|$)") +FENCE_RE = re.compile(r"(`{3,}|~{3,})(.*)$") +TAG_LINE_RE = re.compile(r"\{[{%#]") +LINK_DEF_RE = re.compile(r"\[(?:[^\]\\]|\\.)+\]:") +TABLE_DELIM_RE = re.compile(r"\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$") +RAW_START_RE = re.compile(r"\{%-?\s*raw\s*-?%\}") +RAW_END_RE = re.compile(r"\{%-?\s*endraw\s*-?%\}") + +# CommonMark HTML block start conditions 1-7, with the end condition of each. +# None means the block ends at a blank line. +_BLOCK_TAGS = ( + "address|article|aside|base|basefont|blockquote|body|caption|center|col|" + "colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|" + "footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|" + "link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|" + "section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul" +) +HTML_BLOCKS = [ + (re.compile(r"<(?:script|pre|style|textarea)(?:[\s>]|$)", re.I), + re.compile(r"", re.I)), + (re.compile(r"")), + (re.compile(r"<\?"), re.compile(r"\?>")), + (re.compile(r"")), + (re.compile(r"")), + (re.compile(r"]|$)" % _BLOCK_TAGS, re.I), None), +] +_ATTR = r"""(?:\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)""" +HTML_BLOCK_7 = re.compile( + r"(?:<[A-Za-z][A-Za-z0-9-]*%s*\s*/?>|)\s*$" % _ATTR +) + +# Inline spans that must never be split. +AUTOLINK_RE = re.compile( + r"<(?:[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*|[\w.!#$%&'*+/=?^`{|}~-]+@[A-Za-z0-9.-]+)>" +) +HTML_COMMENT_RE = re.compile(r"", re.S) +INLINE_TAG_RE = re.compile( + r""""']|"[^"]*"|'[^']*')*)?/?>""" +) +BARE_URL_RE = re.compile(r"(?:https?://|www\.)[^\s<>]*", re.I) + + +# --------------------------------------------------------------------------- +# Block structure + + +def _width(s): + """Display width of leading whitespace, with tabs stopping every 4 columns.""" + col = 0 + for ch in s: + col = col + 4 - col % 4 if ch == "\t" else col + 1 + return col + + +def _strip_quotes(line, max_depth=None): + """Return (index after blockquote markers, number of markers).""" + pos = depth = 0 + while max_depth is None or depth < max_depth: + m = BQ_RE.match(line, pos) + if not m: + break + pos, depth = m.end(), depth + 1 + return pos, depth + + +def _list_item(line, pos): + """Parse list markers (and quotes nested in them) starting at pos. + + Returns (content start, marker spans, first marker match) or None. + """ + first = MARKER_RE.match(line, pos) + if not first or HR_RE.match(line, pos): + return None + spans = [] + m = first + while m and not HR_RE.match(line, pos): + spans.append(m.span(1)) + pos = m.end() + q = BQ_RE.match(line, pos) + while q: + pos = q.end() + q = BQ_RE.match(line, pos) + m = MARKER_RE.match(line, pos) + while pos < len(line) and line[pos] in " \t": + pos += 1 + return pos, spans, first + + +def _html_block(content, in_para): + """Return (True, end pattern) if content starts an HTML block.""" + for start, end in HTML_BLOCKS: + if start.match(content): + return True, end + if not in_para and HTML_BLOCK_7.match(content): + return True, None + return False, None + + +PROSE, SKIP = "prose", "skip" + + +def _classify(lines): + """Return per-line (kind, content start, continuation prefix, paragraph id).""" + n = len(lines) + info = [(SKIP, 0, "", -1)] * n + i = 0 + if n and lines[0].strip() in ("+++", "---"): + closers = ("+++",) if lines[0].strip() == "+++" else ("---", "...") + i = 1 + while i < n and lines[i].strip() not in closers: + i += 1 + i += 1 + + fence = None # (char, length, quote depth) + raw = False + html_end = False # False: not in HTML block; None: ends at blank; else regex + in_table = False + in_para = False + para_id = -1 + para_lines = [] + para_depth = 0 + stack = [] # content columns of open list items + + def close_para(): + nonlocal in_para, para_lines + in_para = False + para_lines = [] + + while i < n: + line = lines[i] + idx = i + i += 1 + + if raw: + if RAW_END_RE.search(line): + raw = False + continue + + if fence: + char, length, depth = fence + q_end, _ = _strip_quotes(line, depth) + rest = line[q_end:].lstrip(" \t") + if re.match(re.escape(char) + "{%d,}[ \t]*$" % length, rest): + fence = None + continue + + q_end, depth = _strip_quotes(line) + rest = line[q_end:] + lst = rest.lstrip(" \t") + blank = not lst.strip() + + if html_end is not False: + if html_end is None: + if blank: + html_end = False + elif html_end.search(line): + html_end = False + close_para() + continue + + if in_table: + if blank: + in_table = False + close_para() + continue + + if blank: + close_para() + continue + + m = RAW_START_RE.search(line) + if m and not RAW_END_RE.search(line, m.end()): + raw = True + close_para() + continue + + indent = _width(rest[: len(rest) - len(lst)]) + if not in_para: + if depth: + # " > x" is code, not a quote, unless a list item holds it. + lead = _width(line[: len(line) - len(line.lstrip(" \t"))]) + if lead >= (stack[-1] if stack else 0) + 4: + continue + while stack and stack[-1] > indent: + stack.pop() + base = stack[-1] if stack else 0 + if indent >= base + 4: + continue # indented code block + + if in_para and SETEXT_RE.match(lst) and (not stack or indent >= stack[-1]): + for j in para_lines: + info[j] = (SKIP, 0, "", -1) + close_para() + continue + + if HR_RE.match(lst): + while stack and stack[-1] > indent: + stack.pop() + close_para() + continue + + item = _list_item(line, q_end) + if item and in_para: + ordered = item[2].group(2) + empty = item[0] >= len(line) + if empty or (not stack and ordered is not None and int(ordered) != 1): + item = None + if item: + start = item[0] + else: + start = len(line) - len(lst) + content = line[start:] + fm = FENCE_RE.match(content) + if fm and fm.group(1)[0] == "`" and "`" in fm.group(2): + fm = None # a backtick fence's info string cannot hold a backtick + + kind = PROSE + if not content.strip(): + kind = SKIP # an empty list item + elif fm: + fence = (fm.group(1)[0], len(fm.group(1)), depth) + kind = SKIP + elif ATX_RE.match(content) or TAG_LINE_RE.match(content): + kind = SKIP + elif content.startswith("|"): + in_table = True + kind = SKIP + elif LINK_DEF_RE.match(content) or HR_RE.match(content): + kind = SKIP + else: + is_html, end = _html_block(content, in_para) + if is_html: + if end is None or not end.search(content): + html_end = end + kind = SKIP + elif "|" in content and i < n: + nq, _ = _strip_quotes(lines[i]) + nxt = lines[i][nq:].strip() + if "|" in nxt and TABLE_DELIM_RE.match(nxt): + in_table = True + kind = SKIP + + if item or kind == SKIP or not in_para: + while stack and stack[-1] > indent: + stack.pop() + if item: + stack.append(_width(line[q_end:item[0]]) if content.strip() + else _width(line[q_end:item[2].end(1)]) + 1) + + if kind == SKIP: + close_para() + continue + + if item: + prefix = list(line[:start]) + for a, b in item[1]: + prefix[a:b] = " " * (b - a) + cont = "".join(prefix) + else: + cont = line[:start] + if not in_para or item or depth != para_depth: + para_id += 1 + para_lines = [] + para_lines.append(idx) + para_depth = depth + in_para = True + info[idx] = (PROSE, start, cont, para_id) + return info + + +# --------------------------------------------------------------------------- +# Inline structure + + +def _code_span_end(s, i): + """End of the code span opening at s[i], or None if the run is unmatched.""" + n = len(s) + j = i + while j < n and s[j] == "`": + j += 1 + run = j - i + while True: + k = s.find("`", j) + if k < 0: + return None + e = k + while e < n and s[e] == "`": + e += 1 + if e - k == run: + return e + j = e + + +def _bracket_end(s, i, open_ch, close_ch): + """Index after the bracket matching s[i], honoring escapes and code spans.""" + depth = 0 + j, n = i, len(s) + while j < n: + c = s[j] + if c == "\\": + j += 2 + continue + if c == "`": + e = _code_span_end(s, j) + if e: + j = e + continue + while j < n and s[j] == "`": + j += 1 + continue + if c == open_ch: + depth += 1 + elif c == close_ch: + depth -= 1 + if depth == 0: + return j + 1 + j += 1 + return None + + +def _template_end(s, i): + m = RAW_START_RE.match(s, i) + if m: + e = RAW_END_RE.search(s, m.end()) + return e.end() if e else len(s) + close = {"{": "}}", "%": "%}", "#": "#}"}[s[i + 1]] + e = s.find(close, i + 2) + return e + 2 if e >= 0 else len(s) + + +def _trim_url(s, a, b): + """Drop trailing punctuation from a bare URL, as GitHub's autolinker does.""" + while b > a: + ch = s[b - 1] + if ch in "?!.,:;*_~'\"": + b -= 1 + elif ch == ")" and s.count("(", a, b) < s.count(")", a, b): + b -= 1 + else: + break + return b + + +def _protected(s): + """Mark characters inside spans that a split must not touch.""" + n = len(s) + mask = bytearray(n) + + def mark(a, b): + mask[a:b] = b"\x01" * (min(b, n) - a) + + i = 0 + while i < n: + c = s[i] + end = None + if c == "\\": + end = i + 2 + elif c == "`": + end = _code_span_end(s, i) + if end is None: + while i < n and s[i] == "`": + i += 1 + continue + elif c == "{" and i + 1 < n and s[i + 1] in "{%#": + end = _template_end(s, i) + elif c == "<": + m = AUTOLINK_RE.match(s, i) or HTML_COMMENT_RE.match(s, i) or INLINE_TAG_RE.match(s, i) + if m: + end = m.end() + elif c == "[" or (c == "!" and s.startswith("[", i + 1)): + b = _bracket_end(s, i + (c == "!"), "[", "]") + if b: + end = b + if b < n and s[b] == "(": + end = _bracket_end(s, b, "(", ")") or b + elif b < n and s[b] == "[": + end = _bracket_end(s, b, "[", "]") or b + elif c in "hHwW" and (i == 0 or not s[i - 1].isalnum()): + m = BARE_URL_RE.match(s, i) + if m: + end = _trim_url(s, i, m.end()) + if end and end > i: + mark(i, end) + i = end + else: + i += 1 + return mask + + +def _starts_sentence(rest): + if not rest or BLOCK_START_RE.match(rest): + return False + c = rest[0] + if c.isupper() or c in "0123456789`": + return True + j = 0 + while j < len(rest) and j < 4 and rest[j] in OPENERS: + j += 1 + return 0 < j < len(rest) and (rest[j].isupper() or rest[j] == "`") + + +def _is_boundary(s, mask, m): + term_a, term_b = m.span(1) + ws_a, ws_b = m.span(3) + if any(mask[term_a:term_b]) or any(mask[ws_a:ws_b]): + return False + term = m.group(1) + if ".." in term: + return False # ellipsis + # "**e.g.**" is still an abbreviation; "(etc.)" ends a sentence. + if term == "." and not m.group(2).strip("*_~"): + k = term_a + while k > 0 and not s[k - 1].isspace(): + k -= 1 + word = s[k:term_a].lstrip(OPENERS) + if (word.lower() + ".") in ABBREVIATIONS: + return False + if len(word) == 1 and word.isalpha(): + return False # an initial, as in "J. Smith" + if INITIALISM_RE.fullmatch(word): + return False + return _starts_sentence(s[ws_b:ws_b + 200]) + + +def _splits(lines, info): + """Return {line index: [(cut, resume), ...]} for every sentence boundary.""" + groups = {} + for idx, (kind, start, _, pid) in enumerate(info): + if kind == PROSE: + groups.setdefault(pid, []).append(idx) + result = {} + for idxs in groups.values(): + contents = [lines[k][info[k][1]:] for k in idxs] + joined = "\n".join(contents) + mask = _protected(joined) + offset = 0 + for k, content in zip(idxs, contents): + start = info[k][1] + cuts = [] + for m in END_RE.finditer(joined, offset, offset + len(content)): + if m.end(3) < offset + len(content) and _is_boundary(joined, mask, m): + cuts.append((start + m.start(3) - offset, start + m.end(3) - offset)) + if cuts: + result[k] = cuts + offset += len(content) + 1 + return result + + +# --------------------------------------------------------------------------- +# Text-level API + + +def _split_lines(text): + """Split into (lines, endings); endings are '\\n', '\\r\\n' or ''.""" + parts = text.split("\n") + lines, endings = [], [] + for k, part in enumerate(parts): + last = k == len(parts) - 1 + if last and part == "": + break + if not last and part.endswith("\r"): + lines.append(part[:-1]) + endings.append("\r\n") + else: + lines.append(part) + endings.append("" if last else "\n") + return lines, endings + + +def _excerpt(line, cut, resume, width=36): + left = line[max(0, cut - width):cut] + right = line[resume:resume + width] + pre = "..." if cut > width else "" + post = "..." if resume + width < len(line) else "" + return pre + left.lstrip() + " " + right.rstrip() + post + + +def check_text(text): + """Return a list of Violations for Markdown text.""" + if text.startswith("\ufeff"): + text = text[1:] + lines, _ = _split_lines(text) + found = _splits(lines, _classify(lines)) + out = [] + for k in sorted(found): + cuts = found[k] + cut, resume = cuts[0] + out.append(Violation(k + 1, resume + 1, len(cuts) + 1, _excerpt(lines[k], cut, resume))) + return out + + +def fix_text(text): + """Return text with every sentence starting on its own line.""" + bom = "" + if text.startswith("\ufeff"): + bom, text = "\ufeff", text[1:] + lines, endings = _split_lines(text) + info = _classify(lines) + found = _splits(lines, info) + if not found: + return bom + text + default_nl = next((e for e in endings if e), "\n") + out = [] + for k, line in enumerate(lines): + cuts = found.get(k) + if not cuts: + out.append(line + endings[k]) + continue + nl = endings[k] or default_nl + cont = info[k][2] + pos = 0 + pieces = [] + for cut, resume in cuts: + pieces.append(line[pos:cut]) + pos = resume + pieces.append(line[pos:]) + out.append(pieces[0] + nl) + for piece in pieces[1:-1]: + out.append(cont + piece + nl) + out.append(cont + pieces[-1] + endings[k]) + return bom + "".join(out) + + +# --------------------------------------------------------------------------- +# Command line + + +def _gh_escape(s, prop=False): + s = s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + if prop: + s = s.replace(":", "%3A").replace(",", "%2C") + return s + + +def _collect(paths): + files, missing = [], [] + for path in paths: + if os.path.isdir(path): + for root, dirs, names in os.walk(path): + dirs.sort() + files.extend(os.path.join(root, f) for f in sorted(names) if f.endswith(".md")) + elif os.path.isfile(path): + files.append(path) + else: + missing.append(path) + return files, missing + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Check that blog Markdown has one sentence per line.") + parser.add_argument("paths", nargs="*", metavar="PATH", + help="files or directories to check (default: content/blog)") + parser.add_argument("--fix", action="store_true", + help="rewrite files in place, one sentence per line") + parser.add_argument("--github", action="store_true", + help="print GitHub Actions annotations instead of plain lines") + args = parser.parse_args(argv) + + files, missing = _collect(args.paths or ["content/blog"]) + if missing: + for path in missing: + print("%s: no such file or directory" % path, file=sys.stderr) + return 2 + + errors = violating_files = violations = fixed_files = fixed_lines = 0 + for path in files: + try: + with open(path, encoding="utf-8", newline="") as f: + text = f.read() + except (OSError, UnicodeDecodeError) as e: + print("%s: %s" % (path, e), file=sys.stderr) + errors += 1 + continue + if args.fix: + fixed = fix_text(text) + if fixed != text: + fixed_lines += len(check_text(text)) + fixed_files += 1 + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(fixed) + text = fixed + found = check_text(text) + if found: + violating_files += 1 + violations += len(found) + for v in found: + msg = "%d sentences on one line: %s" % (v.sentences, v.excerpt) + if args.github: + print("::warning file=%s,line=%d,col=%d,title=One sentence per line::%s" + % (_gh_escape(path, True), v.line, v.col, _gh_escape(msg))) + else: + print("%s:%d:%d: %s" % (path, v.line, v.col, msg)) + + if args.fix: + print("fixed %d lines in %d of %d files" % (fixed_lines, fixed_files, len(files)), + file=sys.stderr) + if violations: + print("%d lines with more than one sentence in %d of %d files" + % (violations, violating_files, len(files)), file=sys.stderr) + if errors: + return 2 + return 1 if violations else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test_sentence_per_line.py b/scripts/test_sentence_per_line.py new file mode 100644 index 00000000..a0874397 --- /dev/null +++ b/scripts/test_sentence_per_line.py @@ -0,0 +1,641 @@ +#!/usr/bin/env python3 +"""Tests for sentence_per_line.py. + +Run with either of: + python3 -m unittest scripts/test_sentence_per_line.py + python3 scripts/test_sentence_per_line.py +""" + +import contextlib +import io +import os +import re +import shutil +import sys +import tempfile +import textwrap +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +sys.dont_write_bytecode = True # keep scripts/ free of __pycache__ + +import sentence_per_line as spl # noqa: E402 + +REPO = os.path.dirname(HERE) + + +def md(s): + return textwrap.dedent(s).lstrip("\n") + + +class Base(unittest.TestCase): + def assertFix(self, before, after): + before, after = md(before), md(after) + self.assertEqual(spl.fix_text(before), after) + self.assertEqual(spl.fix_text(after), after, "fix is not idempotent") + self.assertEqual(spl.check_text(after), [], "check fails after fix") + + def assertClean(self, text): + text = md(text) + self.assertEqual(spl.check_text(text), []) + self.assertEqual(spl.fix_text(text), text) + + def assertSplits(self, text, count=2): + found = spl.check_text(md(text)) + self.assertEqual(len(found), 1, found) + self.assertEqual(found[0].sentences, count) + + +class Boundaries(Base): + def test_simple(self): + self.assertFix("One here. Two here.\n", "One here.\nTwo here.\n") + + def test_many_on_one_line(self): + self.assertFix("A one. B two! C three? D four.\n", + "A one.\nB two!\nC three?\nD four.\n") + + def test_report(self): + (v,) = spl.check_text("First line.\nOne here. Two here. Three.\n") + self.assertEqual((v.line, v.col, v.sentences), (2, 11, 3)) + self.assertIn("One here. Two here.", v.excerpt) + + def test_sentence_starts(self): + for start in ["Upper", "42 things", '"Quoted', "\u201cCurly", "'Single", + "(Paren", "[Link](u)", "`code` is", "*Emph*", "**Bold**", + "_Under_", "\u00c9lan"]: + with self.subTest(start=start): + self.assertSplits("End here. %s rest.\n" % start) + + def test_closers_before_space(self): + for end in ['here."', "here.\u201d", "here.)", "here.]", "here.**", + "here.*", "here._", "here?\u2019", "here!)"]: + with self.subTest(end=end): + self.assertSplits("Some text %s Next one.\n" % end) + + def test_bold_lead_in(self): + self.assertFix("**Note.** The rest follows.\n", "**Note.**\nThe rest follows.\n") + + def test_lowercase_is_not_a_start(self): + self.assertClean("Ends here. but this is lowercase.\n") + self.assertClean('Ends here. "quoted lowercase" too.\n') + self.assertClean("Ends here. (lowercase) too.\n") + + def test_abbreviations(self): + for abbr in ["e.g.", "i.e.", "etc.", "vs.", "cf.", "Mr.", "Mrs.", "Ms.", "Dr.", + "St.", "No.", "Fig.", "approx.", "U.S.", "a.m.", "p.m.", + "E.g.", "VS.", "Sr.", "Jan.", "Ph.D."]: + with self.subTest(abbr=abbr): + self.assertClean("Some words %s Then more words.\n" % abbr) + + def test_abbreviation_in_parens_and_emphasis(self): + self.assertClean("Use a type (e.g. Hash or Set) for this.\n") + self.assertClean("**P.S.** If you need help, ask.\n") + + def test_abbreviation_closing_a_parenthetical(self): + self.assertSplits("Lists, sets (and so on, etc.) The next one.\n") + + def test_abbreviation_list_is_lowercase(self): + for abbr in spl.ABBREVIATIONS: + self.assertEqual(abbr, abbr.lower()) + self.assertTrue(abbr.endswith(".")) + + def test_unlisted_initialisms(self): + self.assertClean("It shipped in the U.K. Then it spread.\n") + self.assertClean("It shipped in the U.S.A. Then it spread.\n") + + def test_initials(self): + self.assertClean("Written by J. Smith and K. R. Jones.\n") + + def test_ellipsis(self): + self.assertClean("Wait a second... These are worse.\n") + self.assertClean("Wait a second\u2026 These are worse.\n") + + def test_decimals_and_versions(self): + self.assertClean("Valkey 9.2 and 8.1.4 and 3.14 are numbers.\n") + self.assertSplits("Released in Valkey 9.2. The next one.\n") + + def test_no_space_no_split(self): + self.assertClean("A file.Name and end.\n") + + def test_number_that_would_start_a_list(self): + # A line starting with "1. " would become an ordered list. + self.assertClean("Steps follow. 1. do this.\n") + self.assertClean("Steps follow. 1) do this.\n") + self.assertSplits("Steps follow. 1st place.\n") + + def test_text_that_would_start_a_fence_or_definition(self): + self.assertClean("Like this. ```code``` here.\n") + self.assertClean("Like this. [Foo]: is odd.\n") + + def test_multiple_spaces_and_tabs_between(self): + self.assertFix("One here. Two here.\t Three.\n", "One here.\nTwo here.\nThree.\n") + + +class InlineSpans(Base): + def test_code_span(self): + self.assertClean("Run `make test. Then go` now.\n") + self.assertClean("Run ``a ` b. Then c`` now.\n") + self.assertSplits("Run `make`. Then go.\n") + + def test_code_span_across_lines(self): + self.assertClean("Run `make\ntest. Then go` now.\n") + + def test_unmatched_backtick_is_literal(self): + self.assertSplits("A ` tick. Then more.\n") + + def test_link_and_image_text(self): + self.assertClean("See [the docs. They help](https://x.io) now.\n") + self.assertClean("See ![Alt one. Alt two](a.png) now.\n") + self.assertClean("See [nested [brackets. Here]](u) now.\n") + self.assertClean("See [ref text. Here][ref] now.\n") + + def test_link_text_across_lines(self): + self.assertClean("See [the docs. They\nhelp](https://x.io) now.\n") + + def test_link_url(self): + self.assertClean("See [docs](https://x.io/a?b=1. Then) now.\n") + self.assertSplits("See [docs](https://x.io/a_(b)). Then more.\n") + + def test_bare_url_trailing_period(self): + self.assertFix("See https://valkey.io. Then more.\n", + "See https://valkey.io.\nThen more.\n") + + def test_autolink(self): + self.assertClean("See Then more.\n") + self.assertClean("Mail Then more.\n") + + def test_inline_html(self): + self.assertClean('An x here.\n') + self.assertClean("A here.\n") + self.assertSplits("A bold. Then more.\n") + + def test_zola_inline(self): + self.assertClean('A {{ link(text="One. Two") }} here.\n') + self.assertClean("A {% if x. Y %} here.\n") + self.assertClean("A {% raw %}{{ x. Y }}{% endraw %} here.\n") + + def test_escaped_period(self): + self.assertClean("Year 2024\\. Then more.\n") + + +class Skips(Base): + def test_toml_frontmatter(self): + self.assertClean(''' + +++ + title = "One. Two." + description = "A. B. C." + +++ + + Body. + ''') + + def test_yaml_frontmatter(self): + self.assertClean(''' + --- + title: One. Two. + --- + + Body. + ''') + + def test_frontmatter_only_at_start(self): + self.assertSplits(''' + Body. + + +++ + One here. Two here. + ''') + + def test_backtick_fence(self): + self.assertClean(''' + ```bash + echo One. Two. + ``` + ''') + + def test_tilde_fence(self): + self.assertClean(''' + ~~~ + One. Two. + ~~~ + ''') + + def test_fence_length_and_char(self): + self.assertClean(''' + ````markdown + ``` + One. Two. + ``` + Three. Four. + ```` + ''') + self.assertClean(''' + ~~~ + ``` + One. Two. + ~~~ + ''') + self.assertSplits(''' + ``` + One. Two. + ``` + Three. Four. + ''') + + def test_fence_in_list_and_quote(self): + self.assertClean(''' + - Item: + ``` + One. Two. + ``` + ''') + self.assertClean(''' + > ``` + > One. Two. + > ``` + ''') + + def test_quote_marker_does_not_close_outer_fence(self): + self.assertClean(''' + ``` + > ``` + One. Two. + ``` + ''') + + def test_unclosed_fence_runs_to_end(self): + self.assertClean("```\nOne. Two.\n") + + def test_backtick_fence_info_cannot_hold_backticks(self): + self.assertSplits("```A``` one. Two.\n") + + def test_indented_code(self): + self.assertClean(''' + Para. + + code. Code. + ''') + self.assertClean(''' + Para. + + \tcode. Code. + ''') + + def test_indented_line_in_paragraph_is_not_code(self): + self.assertSplits(''' + Para. + still para. More para. + ''') + + def test_indented_paragraph_in_list_is_not_code(self): + self.assertFix(''' + 1. Item. + + Inside item. Still inside. + ''', ''' + 1. Item. + + Inside item. + Still inside. + ''') + + def test_html_blocks(self): + self.assertClean(''' +
+ One. Two. +
+ ''') + self.assertClean(''' + + ''') + self.assertClean(''' + + ''') + self.assertClean(''' + + One. Two. + ''') + + def test_html_block_ends_at_blank_line(self): + self.assertSplits(''' +
+ One. Two. + + Three. Four. + +
+ ''') + + def test_tables(self): + self.assertClean(''' + | A. B | C. D | + | --- | --- | + | One. Two. | Three. Four. | + ''') + self.assertClean("Para.\n\n| One. Two. |\n") + self.assertClean(''' + A. B | C. D + --- | --- + One. Two. | Three. Four. + ''') + + def test_headings(self): + self.assertClean("# One. Two.\n\n### Three? Four.\n") + self.assertClean("One. Two.\n===\n") + self.assertClean("One. Two.\n---\n") + + def test_shortcode_lines(self): + self.assertClean('{{ youtube(id="x", title="One. Two.") }}\n') + self.assertClean('{{< youtube id="x" title="One. Two." />}}\n') + self.assertClean('{% note(title="One. Two.") %}\n') + + def test_shortcode_body_is_checked(self): + self.assertSplits(''' + {% note() %} + One. Two. + {% end %} + ''') + + def test_raw_block(self): + self.assertClean(''' + {% raw %} + One. Two. + + Three. Four. + {% endraw %} + ''') + self.assertClean(''' + Before. {% raw %} + One. Two. + {% endraw %} + ''') + + def test_link_reference_definitions(self): + self.assertClean('[ref]: https://x.io "One. Two."\n') + self.assertClean("[^1]: One. Two.\n") + + def test_horizontal_rules(self): + self.assertClean("Para.\n\n---\n\n* * *\n\n___\n") + + +class Containers(Base): + def test_bullet_list(self): + self.assertFix(''' + - One here. Two here. + * Three. Four. + + Five. Six. + ''', ''' + - One here. + Two here. + * Three. + Four. + + Five. + Six. + ''') + + def test_ordered_list(self): + self.assertFix(''' + 1. One. Two. + 10) Three. Four. + ''', ''' + 1. One. + Two. + 10) Three. + Four. + ''') + + def test_wide_marker_spacing(self): + self.assertFix("- One. Two.\n", "- One.\n Two.\n") + + def test_nested_list(self): + self.assertFix(''' + 1. Outer. Still outer. + 1. Inner. Still inner. + Inner lazy. Again. + ''', ''' + 1. Outer. + Still outer. + 1. Inner. + Still inner. + Inner lazy. + Again. + ''') + + def test_continuation_and_lazy_lines(self): + self.assertFix(''' + - Item. + Continued. More. + Lazy. Lazier. + ''', ''' + - Item. + Continued. + More. + Lazy. + Lazier. + ''') + + def test_task_list(self): + # The checkbox is paragraph text, so the item's content starts at "[". + self.assertFix("- [ ] One. Two.\n", "- [ ] One.\n Two.\n") + + def test_blockquote(self): + self.assertFix("> One. Two.\n", "> One.\n> Two.\n") + self.assertFix(">One. Two.\n", ">One.\n>Two.\n") + + def test_nested_blockquote(self): + self.assertFix("> > One. Two.\n", "> > One.\n> > Two.\n") + self.assertFix(">> One. Two.\n", ">> One.\n>> Two.\n") + + def test_list_in_blockquote(self): + self.assertFix("> * One. Two.\n", "> * One.\n> Two.\n") + self.assertFix("> 1. One. Two.\n", "> 1. One.\n> Two.\n") + + def test_blockquote_in_list(self): + self.assertFix(''' + - Item. + + > One. Two. + ''', ''' + - Item. + + > One. + > Two. + ''') + self.assertFix("- > One. Two.\n", "- > One.\n > Two.\n") + + def test_quote_after_four_spaces_is_code(self): + self.assertClean("Para.\n\n > One. Two.\n") + + +class Layout(Base): + def test_hard_break_spaces(self): + self.assertFix("One. Two. \nThree.\n", "One.\nTwo. \nThree.\n") + + def test_hard_break_backslash(self): + self.assertFix("One. Two.\\\nThree.\n", "One.\nTwo.\\\nThree.\n") + + def test_no_new_hard_breaks(self): + out = spl.fix_text("One. Two.\n") + self.assertEqual(out, "One.\nTwo.\n") + + def test_crlf(self): + self.assertFix("One. Two.\r\n\r\n- Three. Four.\r\n", + "One.\r\nTwo.\r\n\r\n- Three.\r\n Four.\r\n") + + def test_mixed_line_endings(self): + self.assertEqual(spl.fix_text("One. Two.\r\nThree. Four.\n"), + "One.\r\nTwo.\r\nThree.\nFour.\n") + + def test_no_trailing_newline(self): + self.assertEqual(spl.fix_text("One. Two."), "One.\nTwo.") + self.assertEqual(spl.fix_text("x\r\nOne. Two."), "x\r\nOne.\r\nTwo.") + + def test_trailing_whitespace_kept_on_last_piece(self): + self.assertEqual(spl.fix_text("One. Two. \n"), "One.\nTwo. \n") + + def test_bom(self): + self.assertEqual(spl.fix_text("\ufeff+++\nt = 1\n+++\nOne. Two.\n"), + "\ufeff+++\nt = 1\n+++\nOne.\nTwo.\n") + + def test_clean_text_unchanged(self): + text = "+++\ntitle = \"x\"\n+++\n\nOne.\nTwo.\n" + self.assertIs(spl.fix_text(text), text) + + def test_example_post_is_clean(self): + path = os.path.join(REPO, "content", "blog", "example-post.md.example") + if not os.path.exists(path): + self.skipTest("example post not found") + with open(path, encoding="utf-8") as f: + self.assertEqual(spl.check_text(f.read()), []) + + +class RealContent(Base): + """Run the fixer over every Markdown file under content/, in memory.""" + + def test_fix_only_moves_whitespace(self): + root = os.path.join(REPO, "content") + if not os.path.isdir(root): + self.skipTest("content/ not found") + files, _ = spl._collect([root]) + self.assertTrue(files) + for path in files: + with open(path, encoding="utf-8", newline="") as f: + before = f.read() + after = spl.fix_text(before) + with self.subTest(path=path): + # Every change is whitespace, plus ">" repeated on quote lines. + a = re.sub(r"\s+", "", before) + b = re.sub(r"\s+", "", after) + self.assertTrue(_only_inserts(a, b, ">"), "non-whitespace change") + self.assertEqual(spl.fix_text(after), after) + self.assertEqual(spl.check_text(after), []) + + +def _only_inserts(a, b, allowed): + """True if b is a with only characters from allowed inserted.""" + i = 0 + for ch in b: + if i < len(a) and ch == a[i]: + i += 1 + elif ch not in allowed: + return False + return i == len(a) + + +class CommandLine(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.dir) + + def write(self, rel, text): + path = os.path.join(self.dir, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(text) + return path + + def run_main(self, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + code = spl.main(list(args)) + except SystemExit as e: + code = e.code + return code, out.getvalue(), err.getvalue() + + def test_clean_exits_zero(self): + self.write("a.md", "One.\nTwo.\n") + code, out, _ = self.run_main(self.dir) + self.assertEqual((code, out), (0, "")) + + def test_violation_exits_one(self): + path = self.write("post/index.md", "+++\n+++\nOne. Two. Three.\n") + code, out, _ = self.run_main(self.dir) + self.assertEqual(code, 1) + self.assertTrue(out.startswith("%s:3:6: 3 sentences on one line: " % path), out) + + def test_walks_only_markdown(self): + self.write("a.txt", "One. Two.\n") + self.write("b.md.example", "One. Two.\n") + self.assertEqual(self.run_main(self.dir)[0], 0) + + def test_explicit_file_of_any_name(self): + path = self.write("a.txt", "One. Two.\n") + self.assertEqual(self.run_main(path)[0], 1) + + def test_missing_path_exits_two(self): + code, _, err = self.run_main(os.path.join(self.dir, "nope")) + self.assertEqual(code, 2) + self.assertIn("no such file", err) + + def test_bad_option_exits_two(self): + self.assertEqual(self.run_main("--nope")[0], 2) + + def test_default_path(self): + self.write("content/blog/a.md", "One. Two.\n") + cwd = os.getcwd() + os.chdir(self.dir) + self.addCleanup(os.chdir, cwd) + code, out, _ = self.run_main() + self.assertEqual(code, 1) + self.assertIn(os.path.join("content", "blog", "a.md") + ":1:6:", out) + + def test_github_annotations(self): + path = self.write("a,b.md", "One. Two.\n") + code, out, _ = self.run_main("--github", path) + self.assertEqual(code, 1) + expected = "::warning file=%s,line=1,col=6,title=One sentence per line::" % ( + path.replace(":", "%3A").replace(",", "%2C")) + self.assertTrue(out.startswith(expected), out) + self.assertIn("2 sentences on one line", out) + + def test_fix_rewrites_in_place(self): + path = self.write("a.md", "One. Two.\r\n") + other = self.write("b.md", "Clean.\n") + mtime = os.path.getmtime(other) + code, out, err = self.run_main("--fix", self.dir) + self.assertEqual((code, out), (0, "")) + self.assertIn("fixed 1 lines in 1 of 2 files", err) + with open(path, encoding="utf-8", newline="") as f: + self.assertEqual(f.read(), "One.\r\nTwo.\r\n") + self.assertEqual(os.path.getmtime(other), mtime) + self.assertEqual(self.run_main(self.dir)[0], 0) + + def test_undecodable_file_exits_two(self): + path = os.path.join(self.dir, "bad.md") + with open(path, "wb") as f: + f.write(b"\xff\xfe One. Two.\n") + self.assertEqual(self.run_main(path)[0], 2) + + +if __name__ == "__main__": + unittest.main() From 3e3b7935defe5abd7b20961c0ec015d01b616888 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:37:44 +0000 Subject: [PATCH 2/5] Point the blog guide at the sentence-per-line checker --- CONTRIBUTING-BLOG-POST.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING-BLOG-POST.md b/CONTRIBUTING-BLOG-POST.md index 8a8d1178..61a398f3 100644 --- a/CONTRIBUTING-BLOG-POST.md +++ b/CONTRIBUTING-BLOG-POST.md @@ -63,8 +63,8 @@ Copy it as a starting point. Markdown joins the lines back into a paragraph, so nothing changes about how the post renders. GitHub anchors suggestions to lines, so a reviewer can rewrite one sentence instead of rewriting the paragraph. This is a convention for the source file, not a style directive: write sentences of whatever length the idea needs. - 1. If you have already written a draft in paragraphs, `sed -E 's/([.!?]) +/\1\n/g' post.md` splits it for you. - It breaks on abbreviations like “e.g.”, so read the result before you commit it. + 1. To find lines that hold more than one sentence, run `python3 scripts/sentence_per_line.py content/blog/YYYY-MM-DD-your-slug.md`. + If you have already written a draft in paragraphs, add `--fix` to split those lines in place. 2. Cut weasel words. "Significantly faster" and "various improvements" imply a claim without making one. Replace them with the number, name, or link they stood in for, or delete them. From 4b173956b701d8a6c00257f59493acfab7f08c12 Mon Sep 17 00:00:00 2001 From: Madelyn Olson Date: Mon, 30 Nov 2026 07:53:37 +0000 Subject: [PATCH 3/5] Move the sentence-per-line checker to madolson/sentence-per-line The workflow added next runs it as an action, so the script, its tests and the guide change come back out. Signed-off-by: Madelyn Olson --- CONTRIBUTING-BLOG-POST.md | 4 +- scripts/sentence_per_line.py | 665 ------------------------------ scripts/test_sentence_per_line.py | 641 ---------------------------- 3 files changed, 2 insertions(+), 1308 deletions(-) delete mode 100755 scripts/sentence_per_line.py delete mode 100644 scripts/test_sentence_per_line.py diff --git a/CONTRIBUTING-BLOG-POST.md b/CONTRIBUTING-BLOG-POST.md index 61a398f3..8a8d1178 100644 --- a/CONTRIBUTING-BLOG-POST.md +++ b/CONTRIBUTING-BLOG-POST.md @@ -63,8 +63,8 @@ Copy it as a starting point. Markdown joins the lines back into a paragraph, so nothing changes about how the post renders. GitHub anchors suggestions to lines, so a reviewer can rewrite one sentence instead of rewriting the paragraph. This is a convention for the source file, not a style directive: write sentences of whatever length the idea needs. - 1. To find lines that hold more than one sentence, run `python3 scripts/sentence_per_line.py content/blog/YYYY-MM-DD-your-slug.md`. - If you have already written a draft in paragraphs, add `--fix` to split those lines in place. + 1. If you have already written a draft in paragraphs, `sed -E 's/([.!?]) +/\1\n/g' post.md` splits it for you. + It breaks on abbreviations like “e.g.”, so read the result before you commit it. 2. Cut weasel words. "Significantly faster" and "various improvements" imply a claim without making one. Replace them with the number, name, or link they stood in for, or delete them. diff --git a/scripts/sentence_per_line.py b/scripts/sentence_per_line.py deleted file mode 100755 index 6b2f3ec4..00000000 --- a/scripts/sentence_per_line.py +++ /dev/null @@ -1,665 +0,0 @@ -#!/usr/bin/env python3 -"""Check, and optionally fix, "one sentence per line" in blog Markdown. - -Rule 1 of CONTRIBUTING-BLOG-POST.md asks for one sentence per line in the -Markdown source, because GitHub anchors review suggestions to lines. -Sentences can be any length; this only looks for lines that hold more than one. - - python3 scripts/sentence_per_line.py [PATH ...] # check - python3 scripts/sentence_per_line.py --fix [PATH ...] # rewrite in place - python3 scripts/sentence_per_line.py --github [PATH ...] # GitHub annotations - -PATH defaults to content/blog; directories are searched for *.md files. -Exit status is 0 when clean, 1 when violations exist, 2 on a usage error. - ---fix only replaces the whitespace between two sentences with a line break -plus the prefix the new line needs to stay in the same list item or -blockquote, so the rendered page does not change. - -Standard library only, Python 3.9 or newer. -""" - -import argparse -import os -import re -import sys -from collections import namedtuple - -# Words that end with a period without ending the sentence. -# Compared case-insensitively against the word before the period. -# Single-letter initials ("J. Smith") and letter-dot runs ("U.S.", "a.m.") -# are also recognized by shape, so unlisted ones of that form are covered. -ABBREVIATIONS = frozenset( - """ - e.g. i.e. etc. vs. cf. viz. al. approx. ca. esp. resp. incl. - mr. mrs. ms. dr. prof. sr. jr. st. mt. - no. nos. fig. figs. vol. ch. sec. pp. eq. ref. ver. dept. - jan. feb. mar. apr. jun. jul. aug. sep. sept. oct. nov. dec. - u.s. u.k. e.u. a.m. p.m. ph.d. - """.split() -) - -Violation = namedtuple("Violation", "line col sentences excerpt") - -# A sentence end: terminators, optional closing quotes/brackets/emphasis, -# then horizontal whitespace. What follows is checked by _starts_sentence. -END_RE = re.compile(r"([.!?]+)([\"'\u201d\u2019)\]*_~]*)([ \t]+)") -OPENERS = "\"'\u201c\u2018([*_~" -INITIALISM_RE = re.compile(r"(?:[A-Za-z]\.)+[A-Za-z]") - -# Text that would turn into a block construct if it started a line. -BLOCK_START_RE = re.compile(r"\d{1,9}[.)](?:[ \t]|$)|`{3,}|~{3,}|\[[^\]]+\]:") - -# Block-level patterns. Most are applied to a line with its container -# prefix (blockquote markers, list markers, indentation) removed. -BQ_RE = re.compile(r"[ \t]*>[ ]?") -MARKER_RE = re.compile(r"[ \t]*([-*+]|(\d{1,9})[.)])(?:[ \t]+|$)") -HR_RE = re.compile(r"[ \t]*(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$") -SETEXT_RE = re.compile(r"(?:=+|-{2,})[ \t]*$") -ATX_RE = re.compile(r"#{1,6}(?:[ \t]|$)") -FENCE_RE = re.compile(r"(`{3,}|~{3,})(.*)$") -TAG_LINE_RE = re.compile(r"\{[{%#]") -LINK_DEF_RE = re.compile(r"\[(?:[^\]\\]|\\.)+\]:") -TABLE_DELIM_RE = re.compile(r"\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$") -RAW_START_RE = re.compile(r"\{%-?\s*raw\s*-?%\}") -RAW_END_RE = re.compile(r"\{%-?\s*endraw\s*-?%\}") - -# CommonMark HTML block start conditions 1-7, with the end condition of each. -# None means the block ends at a blank line. -_BLOCK_TAGS = ( - "address|article|aside|base|basefont|blockquote|body|caption|center|col|" - "colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|" - "footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|" - "link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|" - "section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul" -) -HTML_BLOCKS = [ - (re.compile(r"<(?:script|pre|style|textarea)(?:[\s>]|$)", re.I), - re.compile(r"", re.I)), - (re.compile(r"")), - (re.compile(r"<\?"), re.compile(r"\?>")), - (re.compile(r"")), - (re.compile(r"")), - (re.compile(r"]|$)" % _BLOCK_TAGS, re.I), None), -] -_ATTR = r"""(?:\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)""" -HTML_BLOCK_7 = re.compile( - r"(?:<[A-Za-z][A-Za-z0-9-]*%s*\s*/?>|)\s*$" % _ATTR -) - -# Inline spans that must never be split. -AUTOLINK_RE = re.compile( - r"<(?:[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*|[\w.!#$%&'*+/=?^`{|}~-]+@[A-Za-z0-9.-]+)>" -) -HTML_COMMENT_RE = re.compile(r"", re.S) -INLINE_TAG_RE = re.compile( - r""""']|"[^"]*"|'[^']*')*)?/?>""" -) -BARE_URL_RE = re.compile(r"(?:https?://|www\.)[^\s<>]*", re.I) - - -# --------------------------------------------------------------------------- -# Block structure - - -def _width(s): - """Display width of leading whitespace, with tabs stopping every 4 columns.""" - col = 0 - for ch in s: - col = col + 4 - col % 4 if ch == "\t" else col + 1 - return col - - -def _strip_quotes(line, max_depth=None): - """Return (index after blockquote markers, number of markers).""" - pos = depth = 0 - while max_depth is None or depth < max_depth: - m = BQ_RE.match(line, pos) - if not m: - break - pos, depth = m.end(), depth + 1 - return pos, depth - - -def _list_item(line, pos): - """Parse list markers (and quotes nested in them) starting at pos. - - Returns (content start, marker spans, first marker match) or None. - """ - first = MARKER_RE.match(line, pos) - if not first or HR_RE.match(line, pos): - return None - spans = [] - m = first - while m and not HR_RE.match(line, pos): - spans.append(m.span(1)) - pos = m.end() - q = BQ_RE.match(line, pos) - while q: - pos = q.end() - q = BQ_RE.match(line, pos) - m = MARKER_RE.match(line, pos) - while pos < len(line) and line[pos] in " \t": - pos += 1 - return pos, spans, first - - -def _html_block(content, in_para): - """Return (True, end pattern) if content starts an HTML block.""" - for start, end in HTML_BLOCKS: - if start.match(content): - return True, end - if not in_para and HTML_BLOCK_7.match(content): - return True, None - return False, None - - -PROSE, SKIP = "prose", "skip" - - -def _classify(lines): - """Return per-line (kind, content start, continuation prefix, paragraph id).""" - n = len(lines) - info = [(SKIP, 0, "", -1)] * n - i = 0 - if n and lines[0].strip() in ("+++", "---"): - closers = ("+++",) if lines[0].strip() == "+++" else ("---", "...") - i = 1 - while i < n and lines[i].strip() not in closers: - i += 1 - i += 1 - - fence = None # (char, length, quote depth) - raw = False - html_end = False # False: not in HTML block; None: ends at blank; else regex - in_table = False - in_para = False - para_id = -1 - para_lines = [] - para_depth = 0 - stack = [] # content columns of open list items - - def close_para(): - nonlocal in_para, para_lines - in_para = False - para_lines = [] - - while i < n: - line = lines[i] - idx = i - i += 1 - - if raw: - if RAW_END_RE.search(line): - raw = False - continue - - if fence: - char, length, depth = fence - q_end, _ = _strip_quotes(line, depth) - rest = line[q_end:].lstrip(" \t") - if re.match(re.escape(char) + "{%d,}[ \t]*$" % length, rest): - fence = None - continue - - q_end, depth = _strip_quotes(line) - rest = line[q_end:] - lst = rest.lstrip(" \t") - blank = not lst.strip() - - if html_end is not False: - if html_end is None: - if blank: - html_end = False - elif html_end.search(line): - html_end = False - close_para() - continue - - if in_table: - if blank: - in_table = False - close_para() - continue - - if blank: - close_para() - continue - - m = RAW_START_RE.search(line) - if m and not RAW_END_RE.search(line, m.end()): - raw = True - close_para() - continue - - indent = _width(rest[: len(rest) - len(lst)]) - if not in_para: - if depth: - # " > x" is code, not a quote, unless a list item holds it. - lead = _width(line[: len(line) - len(line.lstrip(" \t"))]) - if lead >= (stack[-1] if stack else 0) + 4: - continue - while stack and stack[-1] > indent: - stack.pop() - base = stack[-1] if stack else 0 - if indent >= base + 4: - continue # indented code block - - if in_para and SETEXT_RE.match(lst) and (not stack or indent >= stack[-1]): - for j in para_lines: - info[j] = (SKIP, 0, "", -1) - close_para() - continue - - if HR_RE.match(lst): - while stack and stack[-1] > indent: - stack.pop() - close_para() - continue - - item = _list_item(line, q_end) - if item and in_para: - ordered = item[2].group(2) - empty = item[0] >= len(line) - if empty or (not stack and ordered is not None and int(ordered) != 1): - item = None - if item: - start = item[0] - else: - start = len(line) - len(lst) - content = line[start:] - fm = FENCE_RE.match(content) - if fm and fm.group(1)[0] == "`" and "`" in fm.group(2): - fm = None # a backtick fence's info string cannot hold a backtick - - kind = PROSE - if not content.strip(): - kind = SKIP # an empty list item - elif fm: - fence = (fm.group(1)[0], len(fm.group(1)), depth) - kind = SKIP - elif ATX_RE.match(content) or TAG_LINE_RE.match(content): - kind = SKIP - elif content.startswith("|"): - in_table = True - kind = SKIP - elif LINK_DEF_RE.match(content) or HR_RE.match(content): - kind = SKIP - else: - is_html, end = _html_block(content, in_para) - if is_html: - if end is None or not end.search(content): - html_end = end - kind = SKIP - elif "|" in content and i < n: - nq, _ = _strip_quotes(lines[i]) - nxt = lines[i][nq:].strip() - if "|" in nxt and TABLE_DELIM_RE.match(nxt): - in_table = True - kind = SKIP - - if item or kind == SKIP or not in_para: - while stack and stack[-1] > indent: - stack.pop() - if item: - stack.append(_width(line[q_end:item[0]]) if content.strip() - else _width(line[q_end:item[2].end(1)]) + 1) - - if kind == SKIP: - close_para() - continue - - if item: - prefix = list(line[:start]) - for a, b in item[1]: - prefix[a:b] = " " * (b - a) - cont = "".join(prefix) - else: - cont = line[:start] - if not in_para or item or depth != para_depth: - para_id += 1 - para_lines = [] - para_lines.append(idx) - para_depth = depth - in_para = True - info[idx] = (PROSE, start, cont, para_id) - return info - - -# --------------------------------------------------------------------------- -# Inline structure - - -def _code_span_end(s, i): - """End of the code span opening at s[i], or None if the run is unmatched.""" - n = len(s) - j = i - while j < n and s[j] == "`": - j += 1 - run = j - i - while True: - k = s.find("`", j) - if k < 0: - return None - e = k - while e < n and s[e] == "`": - e += 1 - if e - k == run: - return e - j = e - - -def _bracket_end(s, i, open_ch, close_ch): - """Index after the bracket matching s[i], honoring escapes and code spans.""" - depth = 0 - j, n = i, len(s) - while j < n: - c = s[j] - if c == "\\": - j += 2 - continue - if c == "`": - e = _code_span_end(s, j) - if e: - j = e - continue - while j < n and s[j] == "`": - j += 1 - continue - if c == open_ch: - depth += 1 - elif c == close_ch: - depth -= 1 - if depth == 0: - return j + 1 - j += 1 - return None - - -def _template_end(s, i): - m = RAW_START_RE.match(s, i) - if m: - e = RAW_END_RE.search(s, m.end()) - return e.end() if e else len(s) - close = {"{": "}}", "%": "%}", "#": "#}"}[s[i + 1]] - e = s.find(close, i + 2) - return e + 2 if e >= 0 else len(s) - - -def _trim_url(s, a, b): - """Drop trailing punctuation from a bare URL, as GitHub's autolinker does.""" - while b > a: - ch = s[b - 1] - if ch in "?!.,:;*_~'\"": - b -= 1 - elif ch == ")" and s.count("(", a, b) < s.count(")", a, b): - b -= 1 - else: - break - return b - - -def _protected(s): - """Mark characters inside spans that a split must not touch.""" - n = len(s) - mask = bytearray(n) - - def mark(a, b): - mask[a:b] = b"\x01" * (min(b, n) - a) - - i = 0 - while i < n: - c = s[i] - end = None - if c == "\\": - end = i + 2 - elif c == "`": - end = _code_span_end(s, i) - if end is None: - while i < n and s[i] == "`": - i += 1 - continue - elif c == "{" and i + 1 < n and s[i + 1] in "{%#": - end = _template_end(s, i) - elif c == "<": - m = AUTOLINK_RE.match(s, i) or HTML_COMMENT_RE.match(s, i) or INLINE_TAG_RE.match(s, i) - if m: - end = m.end() - elif c == "[" or (c == "!" and s.startswith("[", i + 1)): - b = _bracket_end(s, i + (c == "!"), "[", "]") - if b: - end = b - if b < n and s[b] == "(": - end = _bracket_end(s, b, "(", ")") or b - elif b < n and s[b] == "[": - end = _bracket_end(s, b, "[", "]") or b - elif c in "hHwW" and (i == 0 or not s[i - 1].isalnum()): - m = BARE_URL_RE.match(s, i) - if m: - end = _trim_url(s, i, m.end()) - if end and end > i: - mark(i, end) - i = end - else: - i += 1 - return mask - - -def _starts_sentence(rest): - if not rest or BLOCK_START_RE.match(rest): - return False - c = rest[0] - if c.isupper() or c in "0123456789`": - return True - j = 0 - while j < len(rest) and j < 4 and rest[j] in OPENERS: - j += 1 - return 0 < j < len(rest) and (rest[j].isupper() or rest[j] == "`") - - -def _is_boundary(s, mask, m): - term_a, term_b = m.span(1) - ws_a, ws_b = m.span(3) - if any(mask[term_a:term_b]) or any(mask[ws_a:ws_b]): - return False - term = m.group(1) - if ".." in term: - return False # ellipsis - # "**e.g.**" is still an abbreviation; "(etc.)" ends a sentence. - if term == "." and not m.group(2).strip("*_~"): - k = term_a - while k > 0 and not s[k - 1].isspace(): - k -= 1 - word = s[k:term_a].lstrip(OPENERS) - if (word.lower() + ".") in ABBREVIATIONS: - return False - if len(word) == 1 and word.isalpha(): - return False # an initial, as in "J. Smith" - if INITIALISM_RE.fullmatch(word): - return False - return _starts_sentence(s[ws_b:ws_b + 200]) - - -def _splits(lines, info): - """Return {line index: [(cut, resume), ...]} for every sentence boundary.""" - groups = {} - for idx, (kind, start, _, pid) in enumerate(info): - if kind == PROSE: - groups.setdefault(pid, []).append(idx) - result = {} - for idxs in groups.values(): - contents = [lines[k][info[k][1]:] for k in idxs] - joined = "\n".join(contents) - mask = _protected(joined) - offset = 0 - for k, content in zip(idxs, contents): - start = info[k][1] - cuts = [] - for m in END_RE.finditer(joined, offset, offset + len(content)): - if m.end(3) < offset + len(content) and _is_boundary(joined, mask, m): - cuts.append((start + m.start(3) - offset, start + m.end(3) - offset)) - if cuts: - result[k] = cuts - offset += len(content) + 1 - return result - - -# --------------------------------------------------------------------------- -# Text-level API - - -def _split_lines(text): - """Split into (lines, endings); endings are '\\n', '\\r\\n' or ''.""" - parts = text.split("\n") - lines, endings = [], [] - for k, part in enumerate(parts): - last = k == len(parts) - 1 - if last and part == "": - break - if not last and part.endswith("\r"): - lines.append(part[:-1]) - endings.append("\r\n") - else: - lines.append(part) - endings.append("" if last else "\n") - return lines, endings - - -def _excerpt(line, cut, resume, width=36): - left = line[max(0, cut - width):cut] - right = line[resume:resume + width] - pre = "..." if cut > width else "" - post = "..." if resume + width < len(line) else "" - return pre + left.lstrip() + " " + right.rstrip() + post - - -def check_text(text): - """Return a list of Violations for Markdown text.""" - if text.startswith("\ufeff"): - text = text[1:] - lines, _ = _split_lines(text) - found = _splits(lines, _classify(lines)) - out = [] - for k in sorted(found): - cuts = found[k] - cut, resume = cuts[0] - out.append(Violation(k + 1, resume + 1, len(cuts) + 1, _excerpt(lines[k], cut, resume))) - return out - - -def fix_text(text): - """Return text with every sentence starting on its own line.""" - bom = "" - if text.startswith("\ufeff"): - bom, text = "\ufeff", text[1:] - lines, endings = _split_lines(text) - info = _classify(lines) - found = _splits(lines, info) - if not found: - return bom + text - default_nl = next((e for e in endings if e), "\n") - out = [] - for k, line in enumerate(lines): - cuts = found.get(k) - if not cuts: - out.append(line + endings[k]) - continue - nl = endings[k] or default_nl - cont = info[k][2] - pos = 0 - pieces = [] - for cut, resume in cuts: - pieces.append(line[pos:cut]) - pos = resume - pieces.append(line[pos:]) - out.append(pieces[0] + nl) - for piece in pieces[1:-1]: - out.append(cont + piece + nl) - out.append(cont + pieces[-1] + endings[k]) - return bom + "".join(out) - - -# --------------------------------------------------------------------------- -# Command line - - -def _gh_escape(s, prop=False): - s = s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") - if prop: - s = s.replace(":", "%3A").replace(",", "%2C") - return s - - -def _collect(paths): - files, missing = [], [] - for path in paths: - if os.path.isdir(path): - for root, dirs, names in os.walk(path): - dirs.sort() - files.extend(os.path.join(root, f) for f in sorted(names) if f.endswith(".md")) - elif os.path.isfile(path): - files.append(path) - else: - missing.append(path) - return files, missing - - -def main(argv=None): - parser = argparse.ArgumentParser( - description="Check that blog Markdown has one sentence per line.") - parser.add_argument("paths", nargs="*", metavar="PATH", - help="files or directories to check (default: content/blog)") - parser.add_argument("--fix", action="store_true", - help="rewrite files in place, one sentence per line") - parser.add_argument("--github", action="store_true", - help="print GitHub Actions annotations instead of plain lines") - args = parser.parse_args(argv) - - files, missing = _collect(args.paths or ["content/blog"]) - if missing: - for path in missing: - print("%s: no such file or directory" % path, file=sys.stderr) - return 2 - - errors = violating_files = violations = fixed_files = fixed_lines = 0 - for path in files: - try: - with open(path, encoding="utf-8", newline="") as f: - text = f.read() - except (OSError, UnicodeDecodeError) as e: - print("%s: %s" % (path, e), file=sys.stderr) - errors += 1 - continue - if args.fix: - fixed = fix_text(text) - if fixed != text: - fixed_lines += len(check_text(text)) - fixed_files += 1 - with open(path, "w", encoding="utf-8", newline="") as f: - f.write(fixed) - text = fixed - found = check_text(text) - if found: - violating_files += 1 - violations += len(found) - for v in found: - msg = "%d sentences on one line: %s" % (v.sentences, v.excerpt) - if args.github: - print("::warning file=%s,line=%d,col=%d,title=One sentence per line::%s" - % (_gh_escape(path, True), v.line, v.col, _gh_escape(msg))) - else: - print("%s:%d:%d: %s" % (path, v.line, v.col, msg)) - - if args.fix: - print("fixed %d lines in %d of %d files" % (fixed_lines, fixed_files, len(files)), - file=sys.stderr) - if violations: - print("%d lines with more than one sentence in %d of %d files" - % (violations, violating_files, len(files)), file=sys.stderr) - if errors: - return 2 - return 1 if violations else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/test_sentence_per_line.py b/scripts/test_sentence_per_line.py deleted file mode 100644 index a0874397..00000000 --- a/scripts/test_sentence_per_line.py +++ /dev/null @@ -1,641 +0,0 @@ -#!/usr/bin/env python3 -"""Tests for sentence_per_line.py. - -Run with either of: - python3 -m unittest scripts/test_sentence_per_line.py - python3 scripts/test_sentence_per_line.py -""" - -import contextlib -import io -import os -import re -import shutil -import sys -import tempfile -import textwrap -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -sys.dont_write_bytecode = True # keep scripts/ free of __pycache__ - -import sentence_per_line as spl # noqa: E402 - -REPO = os.path.dirname(HERE) - - -def md(s): - return textwrap.dedent(s).lstrip("\n") - - -class Base(unittest.TestCase): - def assertFix(self, before, after): - before, after = md(before), md(after) - self.assertEqual(spl.fix_text(before), after) - self.assertEqual(spl.fix_text(after), after, "fix is not idempotent") - self.assertEqual(spl.check_text(after), [], "check fails after fix") - - def assertClean(self, text): - text = md(text) - self.assertEqual(spl.check_text(text), []) - self.assertEqual(spl.fix_text(text), text) - - def assertSplits(self, text, count=2): - found = spl.check_text(md(text)) - self.assertEqual(len(found), 1, found) - self.assertEqual(found[0].sentences, count) - - -class Boundaries(Base): - def test_simple(self): - self.assertFix("One here. Two here.\n", "One here.\nTwo here.\n") - - def test_many_on_one_line(self): - self.assertFix("A one. B two! C three? D four.\n", - "A one.\nB two!\nC three?\nD four.\n") - - def test_report(self): - (v,) = spl.check_text("First line.\nOne here. Two here. Three.\n") - self.assertEqual((v.line, v.col, v.sentences), (2, 11, 3)) - self.assertIn("One here. Two here.", v.excerpt) - - def test_sentence_starts(self): - for start in ["Upper", "42 things", '"Quoted', "\u201cCurly", "'Single", - "(Paren", "[Link](u)", "`code` is", "*Emph*", "**Bold**", - "_Under_", "\u00c9lan"]: - with self.subTest(start=start): - self.assertSplits("End here. %s rest.\n" % start) - - def test_closers_before_space(self): - for end in ['here."', "here.\u201d", "here.)", "here.]", "here.**", - "here.*", "here._", "here?\u2019", "here!)"]: - with self.subTest(end=end): - self.assertSplits("Some text %s Next one.\n" % end) - - def test_bold_lead_in(self): - self.assertFix("**Note.** The rest follows.\n", "**Note.**\nThe rest follows.\n") - - def test_lowercase_is_not_a_start(self): - self.assertClean("Ends here. but this is lowercase.\n") - self.assertClean('Ends here. "quoted lowercase" too.\n') - self.assertClean("Ends here. (lowercase) too.\n") - - def test_abbreviations(self): - for abbr in ["e.g.", "i.e.", "etc.", "vs.", "cf.", "Mr.", "Mrs.", "Ms.", "Dr.", - "St.", "No.", "Fig.", "approx.", "U.S.", "a.m.", "p.m.", - "E.g.", "VS.", "Sr.", "Jan.", "Ph.D."]: - with self.subTest(abbr=abbr): - self.assertClean("Some words %s Then more words.\n" % abbr) - - def test_abbreviation_in_parens_and_emphasis(self): - self.assertClean("Use a type (e.g. Hash or Set) for this.\n") - self.assertClean("**P.S.** If you need help, ask.\n") - - def test_abbreviation_closing_a_parenthetical(self): - self.assertSplits("Lists, sets (and so on, etc.) The next one.\n") - - def test_abbreviation_list_is_lowercase(self): - for abbr in spl.ABBREVIATIONS: - self.assertEqual(abbr, abbr.lower()) - self.assertTrue(abbr.endswith(".")) - - def test_unlisted_initialisms(self): - self.assertClean("It shipped in the U.K. Then it spread.\n") - self.assertClean("It shipped in the U.S.A. Then it spread.\n") - - def test_initials(self): - self.assertClean("Written by J. Smith and K. R. Jones.\n") - - def test_ellipsis(self): - self.assertClean("Wait a second... These are worse.\n") - self.assertClean("Wait a second\u2026 These are worse.\n") - - def test_decimals_and_versions(self): - self.assertClean("Valkey 9.2 and 8.1.4 and 3.14 are numbers.\n") - self.assertSplits("Released in Valkey 9.2. The next one.\n") - - def test_no_space_no_split(self): - self.assertClean("A file.Name and end.\n") - - def test_number_that_would_start_a_list(self): - # A line starting with "1. " would become an ordered list. - self.assertClean("Steps follow. 1. do this.\n") - self.assertClean("Steps follow. 1) do this.\n") - self.assertSplits("Steps follow. 1st place.\n") - - def test_text_that_would_start_a_fence_or_definition(self): - self.assertClean("Like this. ```code``` here.\n") - self.assertClean("Like this. [Foo]: is odd.\n") - - def test_multiple_spaces_and_tabs_between(self): - self.assertFix("One here. Two here.\t Three.\n", "One here.\nTwo here.\nThree.\n") - - -class InlineSpans(Base): - def test_code_span(self): - self.assertClean("Run `make test. Then go` now.\n") - self.assertClean("Run ``a ` b. Then c`` now.\n") - self.assertSplits("Run `make`. Then go.\n") - - def test_code_span_across_lines(self): - self.assertClean("Run `make\ntest. Then go` now.\n") - - def test_unmatched_backtick_is_literal(self): - self.assertSplits("A ` tick. Then more.\n") - - def test_link_and_image_text(self): - self.assertClean("See [the docs. They help](https://x.io) now.\n") - self.assertClean("See ![Alt one. Alt two](a.png) now.\n") - self.assertClean("See [nested [brackets. Here]](u) now.\n") - self.assertClean("See [ref text. Here][ref] now.\n") - - def test_link_text_across_lines(self): - self.assertClean("See [the docs. They\nhelp](https://x.io) now.\n") - - def test_link_url(self): - self.assertClean("See [docs](https://x.io/a?b=1. Then) now.\n") - self.assertSplits("See [docs](https://x.io/a_(b)). Then more.\n") - - def test_bare_url_trailing_period(self): - self.assertFix("See https://valkey.io. Then more.\n", - "See https://valkey.io.\nThen more.\n") - - def test_autolink(self): - self.assertClean("See Then more.\n") - self.assertClean("Mail Then more.\n") - - def test_inline_html(self): - self.assertClean('An x here.\n') - self.assertClean("A here.\n") - self.assertSplits("A bold. Then more.\n") - - def test_zola_inline(self): - self.assertClean('A {{ link(text="One. Two") }} here.\n') - self.assertClean("A {% if x. Y %} here.\n") - self.assertClean("A {% raw %}{{ x. Y }}{% endraw %} here.\n") - - def test_escaped_period(self): - self.assertClean("Year 2024\\. Then more.\n") - - -class Skips(Base): - def test_toml_frontmatter(self): - self.assertClean(''' - +++ - title = "One. Two." - description = "A. B. C." - +++ - - Body. - ''') - - def test_yaml_frontmatter(self): - self.assertClean(''' - --- - title: One. Two. - --- - - Body. - ''') - - def test_frontmatter_only_at_start(self): - self.assertSplits(''' - Body. - - +++ - One here. Two here. - ''') - - def test_backtick_fence(self): - self.assertClean(''' - ```bash - echo One. Two. - ``` - ''') - - def test_tilde_fence(self): - self.assertClean(''' - ~~~ - One. Two. - ~~~ - ''') - - def test_fence_length_and_char(self): - self.assertClean(''' - ````markdown - ``` - One. Two. - ``` - Three. Four. - ```` - ''') - self.assertClean(''' - ~~~ - ``` - One. Two. - ~~~ - ''') - self.assertSplits(''' - ``` - One. Two. - ``` - Three. Four. - ''') - - def test_fence_in_list_and_quote(self): - self.assertClean(''' - - Item: - ``` - One. Two. - ``` - ''') - self.assertClean(''' - > ``` - > One. Two. - > ``` - ''') - - def test_quote_marker_does_not_close_outer_fence(self): - self.assertClean(''' - ``` - > ``` - One. Two. - ``` - ''') - - def test_unclosed_fence_runs_to_end(self): - self.assertClean("```\nOne. Two.\n") - - def test_backtick_fence_info_cannot_hold_backticks(self): - self.assertSplits("```A``` one. Two.\n") - - def test_indented_code(self): - self.assertClean(''' - Para. - - code. Code. - ''') - self.assertClean(''' - Para. - - \tcode. Code. - ''') - - def test_indented_line_in_paragraph_is_not_code(self): - self.assertSplits(''' - Para. - still para. More para. - ''') - - def test_indented_paragraph_in_list_is_not_code(self): - self.assertFix(''' - 1. Item. - - Inside item. Still inside. - ''', ''' - 1. Item. - - Inside item. - Still inside. - ''') - - def test_html_blocks(self): - self.assertClean(''' -
- One. Two. -
- ''') - self.assertClean(''' - - ''') - self.assertClean(''' - - ''') - self.assertClean(''' - - One. Two. - ''') - - def test_html_block_ends_at_blank_line(self): - self.assertSplits(''' -
- One. Two. - - Three. Four. - -
- ''') - - def test_tables(self): - self.assertClean(''' - | A. B | C. D | - | --- | --- | - | One. Two. | Three. Four. | - ''') - self.assertClean("Para.\n\n| One. Two. |\n") - self.assertClean(''' - A. B | C. D - --- | --- - One. Two. | Three. Four. - ''') - - def test_headings(self): - self.assertClean("# One. Two.\n\n### Three? Four.\n") - self.assertClean("One. Two.\n===\n") - self.assertClean("One. Two.\n---\n") - - def test_shortcode_lines(self): - self.assertClean('{{ youtube(id="x", title="One. Two.") }}\n') - self.assertClean('{{< youtube id="x" title="One. Two." />}}\n') - self.assertClean('{% note(title="One. Two.") %}\n') - - def test_shortcode_body_is_checked(self): - self.assertSplits(''' - {% note() %} - One. Two. - {% end %} - ''') - - def test_raw_block(self): - self.assertClean(''' - {% raw %} - One. Two. - - Three. Four. - {% endraw %} - ''') - self.assertClean(''' - Before. {% raw %} - One. Two. - {% endraw %} - ''') - - def test_link_reference_definitions(self): - self.assertClean('[ref]: https://x.io "One. Two."\n') - self.assertClean("[^1]: One. Two.\n") - - def test_horizontal_rules(self): - self.assertClean("Para.\n\n---\n\n* * *\n\n___\n") - - -class Containers(Base): - def test_bullet_list(self): - self.assertFix(''' - - One here. Two here. - * Three. Four. - + Five. Six. - ''', ''' - - One here. - Two here. - * Three. - Four. - + Five. - Six. - ''') - - def test_ordered_list(self): - self.assertFix(''' - 1. One. Two. - 10) Three. Four. - ''', ''' - 1. One. - Two. - 10) Three. - Four. - ''') - - def test_wide_marker_spacing(self): - self.assertFix("- One. Two.\n", "- One.\n Two.\n") - - def test_nested_list(self): - self.assertFix(''' - 1. Outer. Still outer. - 1. Inner. Still inner. - Inner lazy. Again. - ''', ''' - 1. Outer. - Still outer. - 1. Inner. - Still inner. - Inner lazy. - Again. - ''') - - def test_continuation_and_lazy_lines(self): - self.assertFix(''' - - Item. - Continued. More. - Lazy. Lazier. - ''', ''' - - Item. - Continued. - More. - Lazy. - Lazier. - ''') - - def test_task_list(self): - # The checkbox is paragraph text, so the item's content starts at "[". - self.assertFix("- [ ] One. Two.\n", "- [ ] One.\n Two.\n") - - def test_blockquote(self): - self.assertFix("> One. Two.\n", "> One.\n> Two.\n") - self.assertFix(">One. Two.\n", ">One.\n>Two.\n") - - def test_nested_blockquote(self): - self.assertFix("> > One. Two.\n", "> > One.\n> > Two.\n") - self.assertFix(">> One. Two.\n", ">> One.\n>> Two.\n") - - def test_list_in_blockquote(self): - self.assertFix("> * One. Two.\n", "> * One.\n> Two.\n") - self.assertFix("> 1. One. Two.\n", "> 1. One.\n> Two.\n") - - def test_blockquote_in_list(self): - self.assertFix(''' - - Item. - - > One. Two. - ''', ''' - - Item. - - > One. - > Two. - ''') - self.assertFix("- > One. Two.\n", "- > One.\n > Two.\n") - - def test_quote_after_four_spaces_is_code(self): - self.assertClean("Para.\n\n > One. Two.\n") - - -class Layout(Base): - def test_hard_break_spaces(self): - self.assertFix("One. Two. \nThree.\n", "One.\nTwo. \nThree.\n") - - def test_hard_break_backslash(self): - self.assertFix("One. Two.\\\nThree.\n", "One.\nTwo.\\\nThree.\n") - - def test_no_new_hard_breaks(self): - out = spl.fix_text("One. Two.\n") - self.assertEqual(out, "One.\nTwo.\n") - - def test_crlf(self): - self.assertFix("One. Two.\r\n\r\n- Three. Four.\r\n", - "One.\r\nTwo.\r\n\r\n- Three.\r\n Four.\r\n") - - def test_mixed_line_endings(self): - self.assertEqual(spl.fix_text("One. Two.\r\nThree. Four.\n"), - "One.\r\nTwo.\r\nThree.\nFour.\n") - - def test_no_trailing_newline(self): - self.assertEqual(spl.fix_text("One. Two."), "One.\nTwo.") - self.assertEqual(spl.fix_text("x\r\nOne. Two."), "x\r\nOne.\r\nTwo.") - - def test_trailing_whitespace_kept_on_last_piece(self): - self.assertEqual(spl.fix_text("One. Two. \n"), "One.\nTwo. \n") - - def test_bom(self): - self.assertEqual(spl.fix_text("\ufeff+++\nt = 1\n+++\nOne. Two.\n"), - "\ufeff+++\nt = 1\n+++\nOne.\nTwo.\n") - - def test_clean_text_unchanged(self): - text = "+++\ntitle = \"x\"\n+++\n\nOne.\nTwo.\n" - self.assertIs(spl.fix_text(text), text) - - def test_example_post_is_clean(self): - path = os.path.join(REPO, "content", "blog", "example-post.md.example") - if not os.path.exists(path): - self.skipTest("example post not found") - with open(path, encoding="utf-8") as f: - self.assertEqual(spl.check_text(f.read()), []) - - -class RealContent(Base): - """Run the fixer over every Markdown file under content/, in memory.""" - - def test_fix_only_moves_whitespace(self): - root = os.path.join(REPO, "content") - if not os.path.isdir(root): - self.skipTest("content/ not found") - files, _ = spl._collect([root]) - self.assertTrue(files) - for path in files: - with open(path, encoding="utf-8", newline="") as f: - before = f.read() - after = spl.fix_text(before) - with self.subTest(path=path): - # Every change is whitespace, plus ">" repeated on quote lines. - a = re.sub(r"\s+", "", before) - b = re.sub(r"\s+", "", after) - self.assertTrue(_only_inserts(a, b, ">"), "non-whitespace change") - self.assertEqual(spl.fix_text(after), after) - self.assertEqual(spl.check_text(after), []) - - -def _only_inserts(a, b, allowed): - """True if b is a with only characters from allowed inserted.""" - i = 0 - for ch in b: - if i < len(a) and ch == a[i]: - i += 1 - elif ch not in allowed: - return False - return i == len(a) - - -class CommandLine(unittest.TestCase): - def setUp(self): - self.dir = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, self.dir) - - def write(self, rel, text): - path = os.path.join(self.dir, rel) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="") as f: - f.write(text) - return path - - def run_main(self, *args): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - try: - code = spl.main(list(args)) - except SystemExit as e: - code = e.code - return code, out.getvalue(), err.getvalue() - - def test_clean_exits_zero(self): - self.write("a.md", "One.\nTwo.\n") - code, out, _ = self.run_main(self.dir) - self.assertEqual((code, out), (0, "")) - - def test_violation_exits_one(self): - path = self.write("post/index.md", "+++\n+++\nOne. Two. Three.\n") - code, out, _ = self.run_main(self.dir) - self.assertEqual(code, 1) - self.assertTrue(out.startswith("%s:3:6: 3 sentences on one line: " % path), out) - - def test_walks_only_markdown(self): - self.write("a.txt", "One. Two.\n") - self.write("b.md.example", "One. Two.\n") - self.assertEqual(self.run_main(self.dir)[0], 0) - - def test_explicit_file_of_any_name(self): - path = self.write("a.txt", "One. Two.\n") - self.assertEqual(self.run_main(path)[0], 1) - - def test_missing_path_exits_two(self): - code, _, err = self.run_main(os.path.join(self.dir, "nope")) - self.assertEqual(code, 2) - self.assertIn("no such file", err) - - def test_bad_option_exits_two(self): - self.assertEqual(self.run_main("--nope")[0], 2) - - def test_default_path(self): - self.write("content/blog/a.md", "One. Two.\n") - cwd = os.getcwd() - os.chdir(self.dir) - self.addCleanup(os.chdir, cwd) - code, out, _ = self.run_main() - self.assertEqual(code, 1) - self.assertIn(os.path.join("content", "blog", "a.md") + ":1:6:", out) - - def test_github_annotations(self): - path = self.write("a,b.md", "One. Two.\n") - code, out, _ = self.run_main("--github", path) - self.assertEqual(code, 1) - expected = "::warning file=%s,line=1,col=6,title=One sentence per line::" % ( - path.replace(":", "%3A").replace(",", "%2C")) - self.assertTrue(out.startswith(expected), out) - self.assertIn("2 sentences on one line", out) - - def test_fix_rewrites_in_place(self): - path = self.write("a.md", "One. Two.\r\n") - other = self.write("b.md", "Clean.\n") - mtime = os.path.getmtime(other) - code, out, err = self.run_main("--fix", self.dir) - self.assertEqual((code, out), (0, "")) - self.assertIn("fixed 1 lines in 1 of 2 files", err) - with open(path, encoding="utf-8", newline="") as f: - self.assertEqual(f.read(), "One.\r\nTwo.\r\n") - self.assertEqual(os.path.getmtime(other), mtime) - self.assertEqual(self.run_main(self.dir)[0], 0) - - def test_undecodable_file_exits_two(self): - path = os.path.join(self.dir, "bad.md") - with open(path, "wb") as f: - f.write(b"\xff\xfe One. Two.\n") - self.assertEqual(self.run_main(path)[0], 2) - - -if __name__ == "__main__": - unittest.main() From 611d4fecbbc63119fc124836d6e0a4aad3268ebe Mon Sep 17 00:00:00 2001 From: Madelyn Olson Date: Mon, 30 Nov 2026 07:53:37 +0000 Subject: [PATCH 4/5] Check blog PRs for lines with more than one sentence Signed-off-by: Madelyn Olson --- .github/workflows/sentence-per-line.yml | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/sentence-per-line.yml diff --git a/.github/workflows/sentence-per-line.yml b/.github/workflows/sentence-per-line.yml new file mode 100644 index 00000000..59713f66 --- /dev/null +++ b/.github/workflows/sentence-per-line.yml @@ -0,0 +1,27 @@ +name: Sentence per line + +on: + pull_request: + branches: ["main"] + paths: + - "content/blog/**" + - ".github/workflows/sentence-per-line.yml" + +permissions: + contents: read + pull-requests: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + # Most existing posts have multi-sentence lines, so check only the lines a PR touches, and warn. + - name: Check one sentence per line + uses: madolson/sentence-per-line@a8a3ecebed791b3087fd6e0b94af1224f8cd1a20 # v1.0.0 + with: + paths: content/blog + scope: changed-lines + fail: false From 315554c51db6910a7783e4f9cb841644f146f7a9 Mon Sep 17 00:00:00 2001 From: Madelyn Olson Date: Mon, 30 Nov 2026 07:55:50 +0000 Subject: [PATCH 5/5] Test sentence-per-line annotations, do not merge Signed-off-by: Madelyn Olson --- content/blog/2026-10-15-ValkeyConf2026/index.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/content/blog/2026-10-15-ValkeyConf2026/index.md b/content/blog/2026-10-15-ValkeyConf2026/index.md index fb3f531e..9bd02792 100644 --- a/content/blog/2026-10-15-ValkeyConf2026/index.md +++ b/content/blog/2026-10-15-ValkeyConf2026/index.md @@ -87,4 +87,6 @@ More contributions, more ideas, and more code to review. A good problem to have, ## Made it this far and have opinions? -Great. Valkey is built by the community and there’s always room for someone ready to turn those opinions into contributions. So, don’t keep it cached. Bring it to the [Valkey Community](https://valkey.io/community/). \ No newline at end of file +Great. Valkey is built by the community and there’s always room for someone ready to turn those opinions into contributions. So, don’t keep it cached. Bring it to the [Valkey Community](https://valkey.io/community/). +This added line holds two sentences. It should be flagged. +This added line holds one sentence.