Skip to content

Commit e4e31dc

Browse files
authored
fix: refuse config values of the wrong type (#624)
1 parent aacf8d4 commit e4e31dc

4 files changed

Lines changed: 172 additions & 10 deletions

File tree

‎commit_check/main.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -833,7 +833,9 @@ def main() -> int:
833833
print(f"Error: {e}", file=sys.stderr)
834834
return EXIT_CONFIG_ERROR
835835
except Exception as e: # noqa: BLE001 - last resort: report it, no traceback
836-
print(f"Error: {e}", file=sys.stderr)
836+
# Some exceptions carry no text (MemoryError, a bare KeyError()), and
837+
# "Error: " on its own says nothing; name the type instead.
838+
print(f"Error: {str(e) or type(e).__name__}", file=sys.stderr)
837839
return EXIT_FAIL
838840

839841

‎commit_check/rule_builder.py‎

Lines changed: 72 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,46 @@ def _checked_regex(pattern: str, setting: str) -> str:
154154
return pattern
155155

156156

157+
def _string_setting(value: Any, setting: str) -> str:
158+
"""*value*, once it is known to be a string, stripped.
159+
160+
A number or a boolean used to reach ``.strip()`` and come back from
161+
main's catch-all as "'int' object has no attribute 'strip'" under exit
162+
code 1, the code a rejected commit gets.
163+
"""
164+
if not isinstance(value, str):
165+
raise ConfigError(f"{setting} must be a string, got {value!r}", setting=setting)
166+
return value.strip()
167+
168+
169+
def _string_list(
170+
section: dict[str, Any], key: str, default: list[str], setting: str
171+
) -> list[str]:
172+
"""``section[key]`` as a list of strings, a comma-separated string split.
173+
174+
``--allow-commit-types`` and ``CCHK_ALLOW_COMMIT_TYPES`` already split
175+
on commas; the same string in the TOML file was iterated letter by
176+
letter, so ``"feat,fix"`` allowed a type called ``f``. Anything else
177+
that is not a list of strings is refused rather than guessed at.
178+
"""
179+
value = section.get(key, default)
180+
# The built-in default needs no checking, and this runs on every rule
181+
# set built, so it is returned as is.
182+
if value is default:
183+
return value
184+
if isinstance(value, list):
185+
for item in value:
186+
if not isinstance(item, str):
187+
break
188+
else:
189+
return value
190+
elif isinstance(value, str):
191+
return [item.strip() for item in value.split(",") if item.strip()]
192+
raise ConfigError(
193+
f"{setting} must be a list of strings, got {value!r}", setting=setting
194+
)
195+
196+
157197
class RuleBuilder:
158198
"""Builds validation rules from config and catalog entries."""
159199

@@ -446,7 +486,9 @@ def _build_conventional_commit_rule(
446486
enforce custom formats such as JIRA smart commits
447487
(``PROJ-123: description``).
448488
"""
449-
custom_pattern = self.commit_config.get("message_pattern", "").strip()
489+
custom_pattern = _string_setting(
490+
self.commit_config.get("message_pattern", ""), "[commit] message_pattern"
491+
)
450492
if custom_pattern:
451493
custom_pattern = _checked_regex(custom_pattern, "[commit] message_pattern")
452494
# A team that opted out of Conventional Commits must not be told
@@ -507,8 +549,14 @@ def _build_length_rule(
507549
) -> ValidationRule | None:
508550
"""Build subject length validation rule."""
509551
length = self.commit_config.get(config_key)
510-
if not isinstance(length, int):
552+
if length is None:
511553
return None
554+
# bool is an int: ``true`` used to become a limit of 1 character.
555+
if isinstance(length, bool) or not isinstance(length, int):
556+
setting = f"[commit] {config_key}"
557+
raise ConfigError(
558+
f"{setting} must be a whole number, got {length!r}", setting=setting
559+
)
512560

513561
# The suggestion is templated on the same values as the error: naming
514562
# the configured length is the whole point of the advice, and "the
@@ -548,10 +596,10 @@ def _build_author_pattern_rule(
548596
) -> ValidationRule | None:
549597
"""Build author name or email validation rule."""
550598
regex = catalog_entry.regex
551-
if self.commit_config.get(config_key, ""):
552-
regex = _checked_regex(
553-
self.commit_config.get(config_key, "").strip(), f"[commit] {config_key}"
554-
)
599+
setting = f"[commit] {config_key}"
600+
configured = _string_setting(self.commit_config.get(config_key, ""), setting)
601+
if configured:
602+
regex = _checked_regex(configured, setting)
555603

556604
return ValidationRule(
557605
check=catalog_entry.check,
@@ -720,17 +768,32 @@ def _build_boolean_rule(
720768

721769
def _get_allowed_commit_types(self) -> list[str]:
722770
"""Get deduplicated list of allowed commit types."""
723-
types = self.commit_config.get("allow_commit_types", DEFAULT_COMMIT_TYPES)
771+
types = _string_list(
772+
self.commit_config,
773+
"allow_commit_types",
774+
DEFAULT_COMMIT_TYPES,
775+
"[commit] allow_commit_types",
776+
)
724777
return list(dict.fromkeys(types)) # Preserve order, remove duplicates
725778

726779
def _get_allowed_branch_types(self) -> list[str]:
727780
"""Get deduplicated list of allowed branch types."""
728-
types = self.branch_config.get("allow_branch_types", DEFAULT_BRANCH_TYPES)
781+
types = _string_list(
782+
self.branch_config,
783+
"allow_branch_types",
784+
DEFAULT_BRANCH_TYPES,
785+
"[branch] allow_branch_types",
786+
)
729787
return list(dict.fromkeys(types)) # Preserve order, remove duplicates
730788

731789
def _get_allowed_branch_names(self) -> list[str]:
732790
"""Get deduplicated list of allowed branch names."""
733-
names = self.branch_config.get("allow_branch_names", DEFAULT_BRANCH_NAMES)
791+
names = _string_list(
792+
self.branch_config,
793+
"allow_branch_names",
794+
DEFAULT_BRANCH_NAMES,
795+
"[branch] allow_branch_names",
796+
)
734797
return list(dict.fromkeys(names)) # Preserve order, remove duplicates
735798

736799
def _build_conventional_commit_regex(self, allowed_types: list[str]) -> str:

‎tests/main_test.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2099,3 +2099,41 @@ def test_a_bad_pattern_from_a_flag_exits_two(
20992099
err = capsys.readouterr().err
21002100
assert rc == 2
21012101
assert "Error: [commit] ai_disclosure_pattern is not a valid regex: '^('" in err
2102+
2103+
2104+
class TestWrongTypeSettingIsAConfigError:
2105+
"""A setting of the wrong type exits 2 and names the setting."""
2106+
2107+
def test_numeric_message_pattern_exits_two(
2108+
self, mocker, capsys, monkeypatch, tmp_path
2109+
):
2110+
mocker.patch("sys.stdin.isatty", return_value=False)
2111+
mocker.patch("sys.stdin.read", return_value="feat: add x\n")
2112+
cfg = tmp_path / "cchk.toml"
2113+
cfg.write_text("[commit]\nmessage_pattern = 5\n")
2114+
monkeypatch.setattr("sys.argv", [CMD, "-m", "--config", str(cfg)])
2115+
rc = main()
2116+
err = capsys.readouterr().err
2117+
assert rc == 2
2118+
assert "Error: [commit] message_pattern must be a string, got 5" in err
2119+
2120+
2121+
class TestLastResortErrorIsNeverBlank:
2122+
"""An exception with no text is reported by its type, not as "Error: "."""
2123+
2124+
@pytest.mark.parametrize(
2125+
("exc", "expected"),
2126+
[
2127+
(MemoryError(), "Error: MemoryError\n"),
2128+
(RuntimeError("boom"), "Error: boom\n"),
2129+
],
2130+
)
2131+
def test_the_message_or_the_type_is_printed(
2132+
self, mocker, capsys, monkeypatch, exc, expected
2133+
):
2134+
mocker.patch("sys.stdin.isatty", return_value=False)
2135+
mocker.patch("sys.stdin.read", return_value="feat: add x\n")
2136+
mocker.patch("commit_check.main.RuleBuilder.build_all_rules", side_effect=exc)
2137+
monkeypatch.setattr("sys.argv", [CMD, "-m", "--no-banner"])
2138+
assert main() == 1
2139+
assert capsys.readouterr().err == expected

‎tests/rule_builder_test.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1110,3 +1110,62 @@ def test_an_empty_tag_regex_still_disables_the_match(self):
11101110
rules = RuleBuilder({"tag": {"regex": ""}}).build_all_rules()
11111111
tag_rule = next(r for r in rules if r.check == "tag")
11121112
assert tag_rule.regex is None
1113+
1114+
1115+
class TestWrongTypeSettings:
1116+
"""A setting of the wrong type is a broken policy, not a bad commit.
1117+
1118+
A number where a pattern belongs reached ``.strip()`` and crashed under
1119+
exit code 1; ``true`` as a length became a limit of 1; and a string of
1120+
commit types was iterated letter by letter.
1121+
"""
1122+
1123+
@pytest.mark.parametrize(
1124+
"key", ["message_pattern", "author_name_pattern", "author_email_pattern"]
1125+
)
1126+
@pytest.mark.parametrize("value", [5, True, ["^feat"]])
1127+
def test_a_non_string_pattern_names_the_setting(self, key, value):
1128+
setting = f"[commit] {key}"
1129+
with pytest.raises(ConfigError, match="must be a string") as excinfo:
1130+
RuleBuilder({"commit": {key: value}}).build_all_rules()
1131+
assert setting in str(excinfo.value)
1132+
assert excinfo.value.setting == setting
1133+
1134+
@pytest.mark.parametrize("key", ["subject_max_length", "subject_min_length"])
1135+
@pytest.mark.parametrize("value", [True, False, "50", 5.5])
1136+
def test_a_non_integer_length_names_the_setting(self, key, value):
1137+
with pytest.raises(ConfigError, match="must be a whole number") as excinfo:
1138+
RuleBuilder({"commit": {key: value}}).build_all_rules()
1139+
assert excinfo.value.setting == f"[commit] {key}"
1140+
1141+
def test_an_unset_length_builds_no_rule(self):
1142+
checks = {r.check for r in RuleBuilder({"commit": {}}).build_all_rules()}
1143+
assert "subject_max_length" not in checks
1144+
assert "subject_min_length" not in checks
1145+
1146+
@pytest.mark.parametrize(
1147+
("section", "key", "check"),
1148+
[
1149+
("commit", "allow_commit_types", "message"),
1150+
("branch", "allow_branch_types", "branch"),
1151+
("branch", "allow_branch_names", "branch"),
1152+
],
1153+
)
1154+
def test_a_comma_separated_string_is_split_like_the_flag(self, section, key, check):
1155+
from_string = RuleBuilder({section: {key: "feat, fix"}}).build_all_rules()
1156+
from_list = RuleBuilder({section: {key: ["feat", "fix"]}}).build_all_rules()
1157+
rule = next(r for r in from_string if r.check == check)
1158+
assert rule == next(r for r in from_list if r.check == check)
1159+
1160+
def test_a_string_of_commit_types_no_longer_allows_single_letters(self):
1161+
rules = RuleBuilder({"commit": {"allow_commit_types": "feat,fix"}})
1162+
rule = next(r for r in rules.build_all_rules() if r.check == "message")
1163+
assert rule.allowed == ["feat", "fix"]
1164+
assert re.match(rule.regex, "feat: add x")
1165+
assert not re.match(rule.regex, "f: add x")
1166+
1167+
@pytest.mark.parametrize("value", [5, ["feat", 1], {"feat": True}])
1168+
def test_a_list_setting_of_another_type_names_the_setting(self, value):
1169+
with pytest.raises(ConfigError, match="must be a list of strings") as excinfo:
1170+
RuleBuilder({"commit": {"allow_commit_types": value}}).build_all_rules()
1171+
assert excinfo.value.setting == "[commit] allow_commit_types"

0 commit comments

Comments
 (0)