Skip to content

Commit 9817088

Browse files
committed
fix: link rule IDs to their documentation in terminal output
The rule ID now carries an OSC 8 hyperlink to its section of the rules reference, the way ruff links its codes, so the ID itself is what you click. Where that renders, the separate "Docs:" line is dropped: it was repeating an address the reader already has. Where it does not — a pipe, a CI log, a terminal that would print the escape as junk — the line stays, because there it is the only way to reach the address at all. Three things the previous output got wrong, all visible in a two-failure run: The blank line closed the suggestion rather than the block, so "Docs:" was separated from the rule it belonged to and butted against the next one. It now closes the block. The name was printed as the config key, subject_min_length, while the rules reference titles its sections in kebab-case. Reading a name off the terminal and searching the documentation for it found nothing. Both now say subject-min-length. The advice for the two length rules named no length: "Provide a meaningful subject (>= configured min)", directly under an error that had already said "at least 5 characters". The suggestion is now templated on the same value as the error.
1 parent 631ae91 commit 9817088

4 files changed

Lines changed: 226 additions & 24 deletions

File tree

‎commit_check/rule_builder.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,16 +234,24 @@ def _build_length_rule(
234234
if not isinstance(length, int):
235235
return None
236236

237+
# The suggestion is templated on the same values as the error: naming
238+
# the configured length is the whole point of the advice, and "the
239+
# configured minimum" told the reader less than the error above it.
237240
error = (
238241
catalog_entry.error.format(max_len=length, min_len=length)
239242
if catalog_entry.error
240243
else None
241244
)
245+
suggest = (
246+
catalog_entry.suggest.format(max_len=length, min_len=length)
247+
if catalog_entry.suggest
248+
else None
249+
)
242250

243251
return ValidationRule(
244252
check=catalog_entry.check,
245253
error=error,
246-
suggest=catalog_entry.suggest,
254+
suggest=suggest,
247255
value=length,
248256
)
249257

‎commit_check/rules_catalog.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,14 @@ def docs_url(self) -> str | None:
7373
check="subject_max_length",
7474
regex=None,
7575
error="Subject must be at most {max_len} characters",
76-
suggest="Keep the subject concise (<= configured max)",
76+
suggest="Shorten the subject to {max_len} characters or fewer",
7777
),
7878
RuleCatalogEntry(
7979
rule_id="CC005",
8080
check="subject_min_length",
8181
regex=None,
8282
error="Subject must be at least {min_len} characters",
83-
suggest="Provide a meaningful subject (>= configured min)",
83+
suggest="Write a subject of at least {min_len} characters",
8484
),
8585
RuleCatalogEntry(
8686
rule_id="CC006",

‎commit_check/util.py‎

Lines changed: 67 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from __future__ import annotations
99
import os
1010
import subprocess
11+
import sys
1112
from subprocess import CalledProcessError
1213
from commit_check import RED, GREEN, YELLOW, RESET_COLOR
1314

@@ -27,17 +28,24 @@ def _print_failure(
2728
return
2829
if not no_banner and not print_error_header.has_been_called:
2930
print_error_header()
31+
docs_url = check.get("docs_url", "") or ""
3032
print_error_message(
3133
check["check"],
3234
check.get("error", ""),
3335
actual,
3436
rule_id=rule_id,
37+
docs_url=docs_url,
3538
)
3639
if check.get("suggest"):
3740
print_suggestion(check["suggest"])
38-
docs_url = check.get("docs_url", "")
39-
if docs_url:
41+
# When the ID above is already a link, repeating the URL only adds a line
42+
# to read. Without hyperlink support — a pipe, a CI log — it is the only
43+
# way the reader gets the address at all, so it stays.
44+
if docs_url and not (rule_id and supports_hyperlinks()):
4045
print(f"Docs: {docs_url}")
46+
# Blank line closes the whole block, rather than splitting it before the
47+
# documentation link.
48+
print()
4149

4250

4351
def get_branch_name() -> str:
@@ -294,22 +302,73 @@ def print_error_header():
294302
print(" ")
295303

296304

297-
def print_error_message(check_type: str, error: str, reason: str, rule_id: str = ""):
305+
#: Terminals known to render OSC 8 hyperlinks, by ``TERM_PROGRAM``.
306+
_HYPERLINK_TERM_PROGRAMS = frozenset(
307+
{"iTerm.app", "WezTerm", "vscode", "Hyper", "ghostty", "rio"}
308+
)
309+
310+
311+
def supports_hyperlinks() -> bool:
312+
"""Whether the terminal renders OSC 8 hyperlinks.
313+
314+
A terminal that does not understand the escape sequence may print its
315+
payload as visible junk, so this errs towards saying no. The signals are
316+
the ones the wider tooling ecosystem settled on, which is why a link that
317+
works in ``ruff`` works here too.
318+
319+
Piped or redirected output always says no: the sequence would end up in
320+
the file, and a CI log is read as plain text.
321+
"""
322+
if os.environ.get("FORCE_HYPERLINK"):
323+
return True
324+
if not sys.stdout.isatty():
325+
return False
326+
if os.environ.get("TERM") == "dumb":
327+
return False
328+
if os.environ.get("TERM_PROGRAM") in _HYPERLINK_TERM_PROGRAMS:
329+
return True
330+
if "kitty" in os.environ.get("TERM", ""):
331+
return True
332+
# GNOME Terminal and the other VTE-based terminals, from 0.50 onwards.
333+
try:
334+
return int(os.environ.get("VTE_VERSION", "0")) >= 5000
335+
except ValueError:
336+
return False
337+
338+
339+
def hyperlink(text: str, url: str) -> str:
340+
"""Wrap ``text`` in an OSC 8 hyperlink pointing at ``url``."""
341+
return f"\033]8;;{url}\033\\{text}\033]8;;\033\\"
342+
343+
344+
def print_error_message(
345+
check_type: str,
346+
error: str,
347+
reason: str,
348+
rule_id: str = "",
349+
docs_url: str = "",
350+
) -> None:
298351
"""Print error message.
299352
300353
:param check_type: the check that failed, e.g. ``subject_imperative``
301354
:param error: the human-readable explanation of the failure
302355
:param reason: the offending value
303356
:param rule_id: stable rule ID, e.g. ``CC003`` (omitted when empty)
357+
:param docs_url: the rule's documentation, linked from the ID when the
358+
terminal supports it
304359
305360
:returns: Give error messages to user
306361
"""
307-
prefix = f"{YELLOW}{rule_id}{RESET_COLOR} " if rule_id else ""
362+
# The kebab-case form is what the rules reference uses as its headings, so
363+
# the name printed here can be searched for there verbatim.
364+
name = check_type.replace("_", "-")
365+
label = rule_id
366+
if rule_id and docs_url and supports_hyperlinks():
367+
label = hyperlink(rule_id, docs_url)
368+
prefix = f"{YELLOW}{label}{RESET_COLOR} " if rule_id else ""
308369
print(
309-
f"{prefix}{YELLOW}{check_type}{RESET_COLOR} check failed ==> {RED}{reason}{RESET_COLOR} ",
310-
end="",
370+
f"{prefix}{YELLOW}{name}{RESET_COLOR} check failed ==> {RED}{reason}{RESET_COLOR}"
311371
)
312-
print("")
313372
if error:
314373
print(error)
315374

@@ -319,8 +378,4 @@ def print_suggestion(suggest: str) -> None:
319378
:param suggest: what message to print out
320379
"""
321380
if suggest:
322-
print(
323-
f"Suggest: {GREEN}{suggest}{RESET_COLOR} ",
324-
end="",
325-
)
326-
print("\n")
381+
print(f"Suggest: {GREEN}{suggest}{RESET_COLOR}")

‎tests/util_test.py‎

Lines changed: 148 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
print_error_header,
1616
print_error_message,
1717
print_suggestion,
18+
supports_hyperlinks,
19+
hyperlink,
20+
_print_failure,
1821
)
1922
from subprocess import CalledProcessError, PIPE
2023
from unittest.mock import MagicMock
@@ -577,26 +580,162 @@ def test_print_error_header(self, capfd):
577580

578581
@pytest.mark.benchmark
579582
@pytest.mark.parametrize(
580-
"check_type, type_failed_msg",
583+
"check_type, printed_name",
581584
[
582-
("message", "check failed ==>"),
583-
("branch", "check failed ==>"),
584-
("author_name", "check failed ==>"),
585-
("author_email", "check failed ==>"),
586-
("signoff", "check failed ==>"),
585+
("message", "message"),
586+
("branch", "branch"),
587+
# The config key is snake_case, but the rules reference titles
588+
# its sections in kebab-case. The output follows the reference,
589+
# so a name read here can be searched for there verbatim.
590+
("author_name", "author-name"),
591+
("author_email", "author-email"),
592+
("signoff", "signoff"),
587593
],
588594
)
589595
@pytest.mark.benchmark
590-
def test_print_error_message(self, capfd, check_type, type_failed_msg):
596+
def test_print_error_message(self, capfd, check_type, printed_name):
591597
# Must print on stdout with given argument.
592598
dummy_reason = "failure reason"
593599
dummy_error = "dummy error"
594600
print_error_message(check_type, dummy_error, dummy_reason)
595601
stdout, _ = capfd.readouterr()
596-
assert check_type in stdout
597-
assert type_failed_msg in stdout
602+
assert printed_name in stdout
603+
assert "_" not in stdout.split(" check failed")[0]
604+
assert "check failed ==>" in stdout
598605
assert dummy_error in stdout
599606

607+
class TestHyperlinks:
608+
"""The rule ID doubles as a link to its documentation.
609+
610+
Only where that renders: a terminal that does not understand OSC 8 may
611+
print the escape payload as visible junk, and in a CI log the sequence
612+
is noise around a URL the reader can no longer click anyway.
613+
"""
614+
615+
@pytest.mark.benchmark
616+
def test_hyperlink_wraps_text_in_osc8(self):
617+
assert hyperlink("CC001", "https://example.com/#cc001") == (
618+
"\033]8;;https://example.com/#cc001\033\\CC001\033]8;;\033\\"
619+
)
620+
621+
@pytest.mark.benchmark
622+
def test_not_supported_when_piped(self, mocker):
623+
mocker.patch.dict("os.environ", {}, clear=True)
624+
mocker.patch("sys.stdout.isatty", return_value=False)
625+
assert supports_hyperlinks() is False
626+
627+
@pytest.mark.benchmark
628+
def test_forced_even_when_piped(self, mocker):
629+
mocker.patch.dict("os.environ", {"FORCE_HYPERLINK": "1"}, clear=True)
630+
mocker.patch("sys.stdout.isatty", return_value=False)
631+
assert supports_hyperlinks() is True
632+
633+
@pytest.mark.benchmark
634+
@pytest.mark.parametrize(
635+
"env, expected",
636+
[
637+
({"TERM_PROGRAM": "WezTerm"}, True),
638+
({"TERM_PROGRAM": "iTerm.app"}, True),
639+
({"TERM_PROGRAM": "vscode"}, True),
640+
({"TERM": "xterm-kitty"}, True),
641+
({"VTE_VERSION": "6003"}, True),
642+
({"VTE_VERSION": "4000"}, False),
643+
# Malformed rather than absent; must not raise.
644+
({"VTE_VERSION": "not-a-number"}, False),
645+
({"TERM": "xterm"}, False),
646+
({"TERM": "dumb", "TERM_PROGRAM": "WezTerm"}, False),
647+
],
648+
)
649+
def test_terminal_detection(self, mocker, env, expected):
650+
mocker.patch.dict("os.environ", env, clear=True)
651+
mocker.patch("sys.stdout.isatty", return_value=True)
652+
assert supports_hyperlinks() is expected
653+
654+
@pytest.mark.benchmark
655+
def test_id_is_linked_when_supported(self, capfd, mocker):
656+
mocker.patch("commit_check.util.supports_hyperlinks", return_value=True)
657+
print_error_message(
658+
"subject_min_length",
659+
"too short",
660+
"hi",
661+
rule_id="CC005",
662+
docs_url="https://commit-check.com/rules/#cc005",
663+
)
664+
stdout, _ = capfd.readouterr()
665+
assert "\033]8;;https://commit-check.com/rules/#cc005\033\\" in stdout
666+
667+
@pytest.mark.benchmark
668+
def test_id_is_plain_when_unsupported(self, capfd, mocker):
669+
mocker.patch("commit_check.util.supports_hyperlinks", return_value=False)
670+
print_error_message(
671+
"subject_min_length",
672+
"too short",
673+
"hi",
674+
rule_id="CC005",
675+
docs_url="https://commit-check.com/rules/#cc005",
676+
)
677+
stdout, _ = capfd.readouterr()
678+
assert "\033]8;;" not in stdout
679+
assert "CC005" in stdout
680+
681+
@pytest.mark.benchmark
682+
def test_docs_line_kept_without_hyperlinks(self, capfd, mocker):
683+
"""A CI log is where the printed URL is the only way to reach it."""
684+
mocker.patch("commit_check.util.supports_hyperlinks", return_value=False)
685+
_print_failure(
686+
{
687+
"check": "subject_min_length",
688+
"error": "too short",
689+
"suggest": "write more",
690+
"rule_id": "CC005",
691+
"docs_url": "https://commit-check.com/rules/#cc005",
692+
},
693+
"hi",
694+
no_banner=True,
695+
)
696+
stdout, _ = capfd.readouterr()
697+
assert "Docs: https://commit-check.com/rules/#cc005" in stdout
698+
699+
@pytest.mark.benchmark
700+
def test_docs_line_dropped_when_id_is_the_link(self, capfd, mocker):
701+
"""Otherwise every failure spends a line repeating its own link."""
702+
mocker.patch("commit_check.util.supports_hyperlinks", return_value=True)
703+
_print_failure(
704+
{
705+
"check": "subject_min_length",
706+
"error": "too short",
707+
"suggest": "write more",
708+
"rule_id": "CC005",
709+
"docs_url": "https://commit-check.com/rules/#cc005",
710+
},
711+
"hi",
712+
no_banner=True,
713+
)
714+
stdout, _ = capfd.readouterr()
715+
assert "Docs: " not in stdout
716+
assert "\033]8;;" in stdout
717+
718+
@pytest.mark.benchmark
719+
def test_blank_line_closes_the_block(self, capfd, mocker):
720+
"""The separator belongs between rules, not inside one."""
721+
mocker.patch("commit_check.util.supports_hyperlinks", return_value=False)
722+
_print_failure(
723+
{
724+
"check": "subject_min_length",
725+
"error": "too short",
726+
"suggest": "write more",
727+
"rule_id": "CC005",
728+
"docs_url": "https://commit-check.com/rules/#cc005",
729+
},
730+
"hi",
731+
no_banner=True,
732+
)
733+
stdout, _ = capfd.readouterr()
734+
lines = stdout.splitlines()
735+
assert lines[-1] == ""
736+
assert lines[-2].startswith("Docs: ")
737+
assert "" not in lines[:-1]
738+
600739
class TestPrintSuggestion:
601740
@pytest.mark.benchmark
602741
def test_print_suggestion(self, capfd):

0 commit comments

Comments
 (0)