Repository navigation
Expand file tree
/
Copy pathconfig_merger.py
More file actions
322 lines (288 loc) · 13.1 KB
/
Copy pathconfig_merger.py
File metadata and controls
322 lines (288 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Configuration merger that combines CLI args, env vars, TOML config, and defaults."""
from __future__ import annotations
import argparse
import difflib
import os
import sys
from collections.abc import Callable
from typing import Any, ClassVar
from commit_check import (
DEFAULT_AI_ATTRIBUTION,
DEFAULT_AI_DISCLOSURE_PATTERN,
DEFAULT_AI_DISCLOSURE_TRAILERS,
DEFAULT_BOOLEAN_RULES,
DEFAULT_BRANCH_NAMES,
DEFAULT_BRANCH_TYPES,
DEFAULT_COMMIT_TYPES,
DEFAULT_PUSH_RULES,
DEFAULT_TAG_REGEX,
)
from commit_check.config import deep_merge
from commit_check.config import load_config as load_toml_config
def parse_bool(value: Any) -> bool:
"""Parse a boolean value from string, int, or bool.
Accepts: true/false, yes/no, 1/0, t/f, y/n (case-insensitive)
"""
if isinstance(value, bool):
return value
if isinstance(value, int):
return bool(value)
if isinstance(value, str):
normalized = value.lower().strip()
if normalized in ("true", "yes", "1", "t", "y"):
return True
if normalized in ("false", "no", "0", "f", "n"):
return False
raise ValueError(f"Cannot parse '{value}' as boolean")
raise TypeError(f"Cannot convert {type(value).__name__} to bool")
def parse_list(value: Any) -> list[str]:
"""Parse a list from comma-separated string or list."""
if isinstance(value, list):
return value
if isinstance(value, str):
# Split by comma and strip whitespace
return [item.strip() for item in value.split(",") if item.strip()]
raise TypeError(f"Cannot convert {type(value).__name__} to list")
def parse_int(value: Any) -> int:
"""Parse an integer value."""
if isinstance(value, int):
return value
if isinstance(value, str):
try:
return int(value.strip())
except ValueError:
raise ValueError(f"Cannot parse '{value}' as integer")
raise TypeError(f"Cannot convert {type(value).__name__} to int")
def get_default_config() -> dict[str, Any]:
"""Get the default configuration with all options."""
return {
"commit": {
"conventional_commits": True,
"message_pattern": "",
"subject_capitalized": DEFAULT_BOOLEAN_RULES["subject_capitalized"],
"subject_imperative": DEFAULT_BOOLEAN_RULES["subject_imperative"],
"subject_max_length": 80,
"subject_min_length": 5,
"allow_commit_types": DEFAULT_COMMIT_TYPES.copy(),
"allow_merge_commits": DEFAULT_BOOLEAN_RULES["allow_merge_commits"],
"allow_revert_commits": DEFAULT_BOOLEAN_RULES["allow_revert_commits"],
"allow_empty_commits": DEFAULT_BOOLEAN_RULES["allow_empty_commits"],
"allow_fixup_commits": DEFAULT_BOOLEAN_RULES["allow_fixup_commits"],
"allow_wip_commits": DEFAULT_BOOLEAN_RULES["allow_wip_commits"],
"require_body": DEFAULT_BOOLEAN_RULES["require_body"],
"require_signed_off_by": DEFAULT_BOOLEAN_RULES["require_signed_off_by"],
"ignore_authors": [],
"ai_attribution": DEFAULT_AI_ATTRIBUTION,
"ai_disclosure_trailers": DEFAULT_AI_DISCLOSURE_TRAILERS.copy(),
"ai_disclosure_pattern": DEFAULT_AI_DISCLOSURE_PATTERN,
"author_email_pattern": "^.+@.+$",
"author_name_pattern": "",
},
"branch": {
"conventional_branch": True,
"require_description_grammar": False,
"allow_branch_types": DEFAULT_BRANCH_TYPES.copy(),
"allow_branch_names": DEFAULT_BRANCH_NAMES.copy(),
"require_rebase_target": "",
"ignore_authors": [],
},
"push": {
"allow_force_push": DEFAULT_PUSH_RULES["allow_force_push"],
},
"tag": {
"regex": DEFAULT_TAG_REGEX,
},
"files": {
"max_size": "",
"prohibited_patterns": [],
"max_path_length": 0,
},
}
#: Read from the same file, but by other tools: ``warn`` by the rule builder,
#: ``[jira]`` and ``[pull_request]`` by the GitHub App.
_OTHER_KEYS = frozenset({"warn", "jira", "pull_request"})
def unknown_setting_warnings(config: dict[str, Any]) -> list[str]:
"""One line per setting in a config file that nothing reads.
A misspelt key used to be ignored in silence, leaving its rule off.
"""
defaults = get_default_config()
names = []
for section, value in config.items():
if section in _OTHER_KEYS:
continue
if section not in defaults:
names.append((f"[{section}]", section, [*defaults, *_OTHER_KEYS]))
elif isinstance(value, dict):
names.extend(
(f"[{section}] {key}", key, defaults[section])
for key in value
if key not in defaults[section]
)
warnings = []
for shown, name, known in names:
match = difflib.get_close_matches(name, list(known), n=1)
hint = f"; did you mean {match[0]}?" if match else ""
warnings.append(f"⚠ unknown setting {shown} is ignored{hint}")
return warnings
class ConfigMerger:
"""Merges configurations from multiple sources with priority: CLI > Env > TOML > Defaults."""
# Mapping of environment variable names to config keys
ENV_VAR_MAPPING: ClassVar[dict[str, tuple[str, str, Callable[[Any], Any]]]] = {
# Commit section
"CCHK_CONVENTIONAL_COMMITS": ("commit", "conventional_commits", parse_bool),
"CCHK_MESSAGE_PATTERN": ("commit", "message_pattern", str),
"CCHK_SUBJECT_CAPITALIZED": ("commit", "subject_capitalized", parse_bool),
"CCHK_SUBJECT_IMPERATIVE": ("commit", "subject_imperative", parse_bool),
"CCHK_SUBJECT_MAX_LENGTH": ("commit", "subject_max_length", parse_int),
"CCHK_SUBJECT_MIN_LENGTH": ("commit", "subject_min_length", parse_int),
"CCHK_ALLOW_COMMIT_TYPES": ("commit", "allow_commit_types", parse_list),
"CCHK_ALLOW_MERGE_COMMITS": ("commit", "allow_merge_commits", parse_bool),
"CCHK_ALLOW_REVERT_COMMITS": ("commit", "allow_revert_commits", parse_bool),
"CCHK_ALLOW_EMPTY_COMMITS": ("commit", "allow_empty_commits", parse_bool),
"CCHK_ALLOW_FIXUP_COMMITS": ("commit", "allow_fixup_commits", parse_bool),
"CCHK_ALLOW_WIP_COMMITS": ("commit", "allow_wip_commits", parse_bool),
"CCHK_REQUIRE_BODY": ("commit", "require_body", parse_bool),
"CCHK_REQUIRE_SIGNED_OFF_BY": ("commit", "require_signed_off_by", parse_bool),
"CCHK_IGNORE_AUTHORS": ("commit", "ignore_authors", parse_list),
"CCHK_AI_ATTRIBUTION": ("commit", "ai_attribution", str),
"CCHK_AI_DISCLOSURE_TRAILERS": (
"commit",
"ai_disclosure_trailers",
parse_list,
),
"CCHK_AI_DISCLOSURE_PATTERN": ("commit", "ai_disclosure_pattern", str),
"CCHK_AUTHOR_EMAIL_PATTERN": ("commit", "author_email_pattern", str),
"CCHK_AUTHOR_NAME_PATTERN": ("commit", "author_name_pattern", str),
# Branch section
"CCHK_CONVENTIONAL_BRANCH": ("branch", "conventional_branch", parse_bool),
"CCHK_REQUIRE_DESCRIPTION_GRAMMAR": (
"branch",
"require_description_grammar",
parse_bool,
),
"CCHK_ALLOW_BRANCH_TYPES": ("branch", "allow_branch_types", parse_list),
"CCHK_ALLOW_BRANCH_NAMES": ("branch", "allow_branch_names", parse_list),
"CCHK_REQUIRE_REBASE_TARGET": ("branch", "require_rebase_target", str),
"CCHK_BRANCH_IGNORE_AUTHORS": ("branch", "ignore_authors", parse_list),
# Push section
"CCHK_ALLOW_FORCE_PUSH": ("push", "allow_force_push", parse_bool),
# Tag section
"CCHK_TAG_REGEX": ("tag", "regex", str),
# Files section
"CCHK_FILES_MAX_SIZE": ("files", "max_size", str),
"CCHK_FILES_PROHIBITED_PATTERNS": ("files", "prohibited_patterns", parse_list),
"CCHK_FILES_MAX_PATH_LENGTH": ("files", "max_path_length", parse_int),
}
# Mapping of CLI argument names to config keys
CLI_ARG_MAPPING: ClassVar[dict[str, tuple[str, str]]] = {
# Commit section
"conventional_commits": ("commit", "conventional_commits"),
"subject_capitalized": ("commit", "subject_capitalized"),
"subject_imperative": ("commit", "subject_imperative"),
"subject_max_length": ("commit", "subject_max_length"),
"subject_min_length": ("commit", "subject_min_length"),
"allow_commit_types": ("commit", "allow_commit_types"),
"allow_merge_commits": ("commit", "allow_merge_commits"),
"allow_revert_commits": ("commit", "allow_revert_commits"),
"allow_empty_commits": ("commit", "allow_empty_commits"),
"allow_fixup_commits": ("commit", "allow_fixup_commits"),
"allow_wip_commits": ("commit", "allow_wip_commits"),
"require_body": ("commit", "require_body"),
"require_signed_off_by": ("commit", "require_signed_off_by"),
"ignore_authors": ("commit", "ignore_authors"),
"ai_attribution": ("commit", "ai_attribution"),
"ai_disclosure_trailers": ("commit", "ai_disclosure_trailers"),
"ai_disclosure_pattern": ("commit", "ai_disclosure_pattern"),
"author_email_pattern": ("commit", "author_email_pattern"),
"author_name_pattern": ("commit", "author_name_pattern"),
# Branch section
"conventional_branch": ("branch", "conventional_branch"),
"require_description_grammar": ("branch", "require_description_grammar"),
"allow_branch_types": ("branch", "allow_branch_types"),
"allow_branch_names": ("branch", "allow_branch_names"),
"require_rebase_target": ("branch", "require_rebase_target"),
"branch_ignore_authors": ("branch", "ignore_authors"),
# Push section
"allow_force_push": ("push", "allow_force_push"),
# Tag section
"tag_regex": ("tag", "regex"),
# Files section
"files_max_size": ("files", "max_size"),
"files_prohibited_patterns": ("files", "prohibited_patterns"),
"files_max_path_length": ("files", "max_path_length"),
}
@staticmethod
def parse_env_vars() -> dict[str, Any]:
"""Parse environment variables with CCHK_ prefix into config dict."""
config: dict[str, Any] = {
"commit": {},
"branch": {},
"push": {},
"tag": {},
"files": {},
}
for env_var, (section, key, parser) in ConfigMerger.ENV_VAR_MAPPING.items():
value = os.environ.get(env_var)
if value is not None:
try:
parsed_value = parser(value)
config[section][key] = parsed_value
except (ValueError, TypeError) as e:
# Log warning but don't fail - just skip invalid env vars.
# stderr, so --format json output stays parseable.
print(f"Warning: Invalid value for {env_var}: {e}", file=sys.stderr)
# Remove empty sections
config = {k: v for k, v in config.items() if v}
return config
@staticmethod
def parse_cli_args(args: argparse.Namespace) -> dict[str, Any]:
"""Parse CLI arguments into config dict."""
config: dict[str, Any] = {
"commit": {},
"branch": {},
"push": {},
"tag": {},
"files": {},
}
for arg_name, (section, key) in ConfigMerger.CLI_ARG_MAPPING.items():
if hasattr(args, arg_name):
value = getattr(args, arg_name)
if value is not None:
config[section][key] = value
# Remove empty sections
config = {k: v for k, v in config.items() if v}
return config
@staticmethod
def from_all_sources(
cli_args: argparse.Namespace, config_path: str | None = None
) -> dict[str, Any]:
"""Merge configs from all sources with priority: CLI > Env > TOML > Defaults.
Args:
cli_args: Parsed command line arguments
config_path: Optional path to TOML config file
Returns:
Merged configuration dictionary
"""
# 1. Start with defaults
config = get_default_config()
# 2. Merge TOML config (if exists)
try:
toml_config = load_toml_config(config_path or "")
if toml_config:
for warning in unknown_setting_warnings(toml_config):
print(warning, file=sys.stderr)
deep_merge(config, toml_config)
except FileNotFoundError:
# If a specific path was provided and not found, this error is already raised
# If no path provided and no default files exist, that's fine
if config_path:
raise
# 3. Merge environment variables
env_config = ConfigMerger.parse_env_vars()
if env_config:
deep_merge(config, env_config)
# 4. Merge CLI arguments (highest priority)
cli_config = ConfigMerger.parse_cli_args(cli_args)
if cli_config:
deep_merge(config, cli_config)
return config