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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/git_commit_guard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,28 @@ class Level(StrEnum):
ERROR = "error"
WARN = "warn"
INFO = "info"
OK = "ok"


PREFIXES = {
Level.ERROR: "\033[31m✗\033[0m",
Level.WARN: "\033[33m⚠\033[0m",
Level.INFO: "\033[34mi\033[0m",
Level.ERROR: "✗",
Level.WARN: "⚠",
Level.INFO: "i",
Level.OK: "✓",
}

COLORS = {
Level.ERROR: "31",
Level.WARN: "33",
Level.INFO: "34",
Level.OK: "32",
}


def _prefix(level, *, color=True):
sym = PREFIXES[level]
return f"\033[{COLORS[level]}m{sym}\033[0m" if color else sym


@dataclass
class Result:
Expand Down Expand Up @@ -504,12 +518,13 @@ def _report_jsonl(result, sha, subject):


def _report_text(result):
color = sys.stdout.isatty()
for check, level, msg in result.errors:
prefix = f"[{check}] " if check else ""
print(f" {PREFIXES[level]} {prefix}{msg}")
print(f" {_prefix(level, color=color)} {prefix}{msg}")

if result.ok:
print(" \033[32m✓\033[0m all checks passed")
print(f" {_prefix(Level.OK, color=color)} all checks passed")

return 0 if result.ok else 1

Expand Down
20 changes: 20 additions & 0 deletions tests/test_git_commit_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,26 @@ def test_with_warning_returns_zero(self, capsys):
assert "heads up" in captured
assert "all checks passed" in captured

def test_no_ansi_when_not_tty(self, capsys):
r = Result()
r.error("something broke")
with patch("sys.stdout.isatty", return_value=False):
_report_text(r)
assert "\033[" not in capsys.readouterr().out

def test_ansi_when_tty(self, capsys):
r = Result()
r.error("something broke")
with patch("sys.stdout.isatty", return_value=True):
_report_text(r)
assert "\033[" in capsys.readouterr().out

def test_ok_no_ansi_when_not_tty(self, capsys):
r = Result()
with patch("sys.stdout.isatty", return_value=False):
_report_text(r)
assert "\033[" not in capsys.readouterr().out


class TestReportJsonl:
def test_ok_commit(self, capsys):
Expand Down
Loading