esys-gitlog 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,380 @@
1
+ """Layered tool preference documents (CADR-0012 / SADR-0009)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field, replace
7
+ from pathlib import Path
8
+ from typing import Any, Literal
9
+
10
+ from esys_gitlog.tool_paths import (
11
+ preference_roots_low_to_high,
12
+ user_preferences_path,
13
+ )
14
+
15
+ QaMode = Literal["strict", "permissive"]
16
+ DisplayMode = Literal["subject-precedence", "trailer-precedence"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class LinkPreferences:
21
+ ref_links: dict[str, str] = field(default_factory=dict)
22
+ commit_link: str | None = None
23
+
24
+
25
+ DEFAULT_REF_ID_WIDTH = 10
26
+ DEFAULT_TYPE_WIDTH = 10
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class PreferenceDefaults:
31
+ profile: str | None = None
32
+ qa: QaMode | None = None
33
+ display: DisplayMode | None = None
34
+ # Human output: fixed character width for the reference-id column (None → default).
35
+ ref_id_width: int | None = None
36
+ # Human output: minimum width for Type(Scope)[!]; longer values are not truncated.
37
+ type_width: int | None = None
38
+ # Human detail lines under each commit (None → false).
39
+ show_author: bool | None = None
40
+ show_date: bool | None = None
41
+ show_body: bool | None = None
42
+ # Human summary columns (None → true): ticket/Jira refs, Type(Scope).
43
+ show_id: bool | None = None
44
+ show_conventional: bool | None = None
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class DetectionSettings:
49
+ """``None`` means unset at this layer (fall through)."""
50
+
51
+ cli: bool | None = None
52
+ git_remote: bool | None = None
53
+ persist_user_config: bool | None = None
54
+
55
+ def resolved(
56
+ self,
57
+ ) -> tuple[bool, bool, bool]:
58
+ return (
59
+ True if self.cli is None else self.cli,
60
+ True if self.git_remote is None else self.git_remote,
61
+ False if self.persist_user_config is None else self.persist_user_config,
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Preferences:
67
+ schema_version: int = 1
68
+ links: LinkPreferences = field(default_factory=LinkPreferences)
69
+ defaults: PreferenceDefaults = field(default_factory=PreferenceDefaults)
70
+ detection: DetectionSettings = field(default_factory=DetectionSettings)
71
+
72
+
73
+ def empty_preferences() -> Preferences:
74
+ return Preferences()
75
+
76
+
77
+ def _parse_links(data: dict[str, Any]) -> LinkPreferences:
78
+ raw = data.get("links")
79
+ if not isinstance(raw, dict):
80
+ return LinkPreferences()
81
+ ref_raw = raw.get("refLinks", {})
82
+ ref_links = (
83
+ {str(key): str(value) for key, value in ref_raw.items()}
84
+ if isinstance(ref_raw, dict)
85
+ else {}
86
+ )
87
+ commit = raw.get("commitLink")
88
+ return LinkPreferences(
89
+ ref_links=ref_links,
90
+ commit_link=str(commit) if commit else None,
91
+ )
92
+
93
+
94
+ def _parse_defaults(data: dict[str, Any]) -> PreferenceDefaults:
95
+ raw = data.get("defaults")
96
+ if not isinstance(raw, dict):
97
+ return PreferenceDefaults()
98
+ qa = raw.get("qa")
99
+ display = raw.get("display")
100
+ profile = raw.get("profile")
101
+ qa_mode: QaMode | None = None
102
+ if qa in ("strict", "permissive"):
103
+ qa_mode = qa
104
+ display_mode: DisplayMode | None = None
105
+ if display in ("subject-precedence", "trailer-precedence"):
106
+ display_mode = display
107
+ ref_id_width: int | None = None
108
+ width_raw = raw.get("refIdWidth")
109
+ if isinstance(width_raw, int) and not isinstance(width_raw, bool) and width_raw >= 0:
110
+ ref_id_width = width_raw
111
+ type_width: int | None = None
112
+ type_width_raw = raw.get("typeWidth")
113
+ if (
114
+ isinstance(type_width_raw, int)
115
+ and not isinstance(type_width_raw, bool)
116
+ and type_width_raw >= 0
117
+ ):
118
+ type_width = type_width_raw
119
+
120
+ def optional_bool(key: str) -> bool | None:
121
+ if key not in raw:
122
+ return None
123
+ value = raw[key]
124
+ return value if isinstance(value, bool) else None
125
+
126
+ return PreferenceDefaults(
127
+ profile=str(profile) if profile else None,
128
+ qa=qa_mode,
129
+ display=display_mode,
130
+ ref_id_width=ref_id_width,
131
+ type_width=type_width,
132
+ show_author=optional_bool("showAuthor"),
133
+ show_date=optional_bool("showDate"),
134
+ show_body=optional_bool("showBody"),
135
+ show_id=optional_bool("showId"),
136
+ show_conventional=optional_bool("showConventional"),
137
+ )
138
+
139
+
140
+ def resolved_ref_id_width(defaults: PreferenceDefaults) -> int:
141
+ """Character width for the human refs column; default 10 when unset."""
142
+ if defaults.ref_id_width is None:
143
+ return DEFAULT_REF_ID_WIDTH
144
+ return defaults.ref_id_width
145
+
146
+
147
+ def resolved_type_width(defaults: PreferenceDefaults) -> int:
148
+ """Minimum character width for Type(Scope); default 10 when unset."""
149
+ if defaults.type_width is None:
150
+ return DEFAULT_TYPE_WIDTH
151
+ return defaults.type_width
152
+
153
+
154
+ def resolved_show_author(defaults: PreferenceDefaults) -> bool:
155
+ return False if defaults.show_author is None else defaults.show_author
156
+
157
+
158
+ def resolved_show_date(defaults: PreferenceDefaults) -> bool:
159
+ return False if defaults.show_date is None else defaults.show_date
160
+
161
+
162
+ def resolved_show_body(defaults: PreferenceDefaults) -> bool:
163
+ return False if defaults.show_body is None else defaults.show_body
164
+
165
+
166
+ def resolved_show_id(defaults: PreferenceDefaults) -> bool:
167
+ """Ticket / Jira reference-id column; default true when unset."""
168
+ return True if defaults.show_id is None else defaults.show_id
169
+
170
+
171
+ def resolved_show_conventional(defaults: PreferenceDefaults) -> bool:
172
+ """Type(Scope)[!] column; default true when unset."""
173
+ return True if defaults.show_conventional is None else defaults.show_conventional
174
+
175
+
176
+ def _parse_detection(data: dict[str, Any]) -> DetectionSettings:
177
+ raw = data.get("detection")
178
+ if not isinstance(raw, dict):
179
+ return DetectionSettings()
180
+ return DetectionSettings(
181
+ cli=bool(raw["cli"]) if "cli" in raw else None,
182
+ git_remote=bool(raw["gitRemote"]) if "gitRemote" in raw else None,
183
+ persist_user_config=(
184
+ bool(raw["persistUserConfig"]) if "persistUserConfig" in raw else None
185
+ ),
186
+ )
187
+
188
+
189
+ def preferences_from_object(data: dict[str, Any]) -> Preferences:
190
+ version = data.get("schemaVersion", 1)
191
+ if version != 1:
192
+ raise ValueError(f"unsupported preference schemaVersion: {version}")
193
+ return Preferences(
194
+ schema_version=1,
195
+ links=_parse_links(data),
196
+ defaults=_parse_defaults(data),
197
+ detection=_parse_detection(data),
198
+ )
199
+
200
+
201
+ def load_preference_file(path: Path) -> Preferences:
202
+ payload = json.loads(path.read_text(encoding="utf-8"))
203
+ if not isinstance(payload, dict):
204
+ raise ValueError("preference config must be a JSON object")
205
+ return preferences_from_object(payload)
206
+
207
+
208
+ def merge_preferences(base: Preferences, overlay: Preferences) -> Preferences:
209
+ """Overlay wins for set scalars; ``refLinks`` merges per key."""
210
+ ref_links = {**base.links.ref_links, **overlay.links.ref_links}
211
+ commit_link = (
212
+ overlay.links.commit_link
213
+ if overlay.links.commit_link is not None
214
+ else base.links.commit_link
215
+ )
216
+ defaults = PreferenceDefaults(
217
+ profile=overlay.defaults.profile or base.defaults.profile,
218
+ qa=overlay.defaults.qa or base.defaults.qa,
219
+ display=overlay.defaults.display or base.defaults.display,
220
+ ref_id_width=(
221
+ overlay.defaults.ref_id_width
222
+ if overlay.defaults.ref_id_width is not None
223
+ else base.defaults.ref_id_width
224
+ ),
225
+ type_width=(
226
+ overlay.defaults.type_width
227
+ if overlay.defaults.type_width is not None
228
+ else base.defaults.type_width
229
+ ),
230
+ show_author=(
231
+ overlay.defaults.show_author
232
+ if overlay.defaults.show_author is not None
233
+ else base.defaults.show_author
234
+ ),
235
+ show_date=(
236
+ overlay.defaults.show_date
237
+ if overlay.defaults.show_date is not None
238
+ else base.defaults.show_date
239
+ ),
240
+ show_body=(
241
+ overlay.defaults.show_body
242
+ if overlay.defaults.show_body is not None
243
+ else base.defaults.show_body
244
+ ),
245
+ show_id=(
246
+ overlay.defaults.show_id
247
+ if overlay.defaults.show_id is not None
248
+ else base.defaults.show_id
249
+ ),
250
+ show_conventional=(
251
+ overlay.defaults.show_conventional
252
+ if overlay.defaults.show_conventional is not None
253
+ else base.defaults.show_conventional
254
+ ),
255
+ )
256
+ detection = DetectionSettings(
257
+ cli=(overlay.detection.cli if overlay.detection.cli is not None else base.detection.cli),
258
+ git_remote=(
259
+ overlay.detection.git_remote
260
+ if overlay.detection.git_remote is not None
261
+ else base.detection.git_remote
262
+ ),
263
+ persist_user_config=(
264
+ overlay.detection.persist_user_config
265
+ if overlay.detection.persist_user_config is not None
266
+ else base.detection.persist_user_config
267
+ ),
268
+ )
269
+ return Preferences(
270
+ schema_version=max(base.schema_version, overlay.schema_version),
271
+ links=LinkPreferences(ref_links=ref_links, commit_link=commit_link),
272
+ defaults=defaults,
273
+ detection=detection,
274
+ )
275
+
276
+
277
+ def load_layered_preferences(
278
+ cwd: Path,
279
+ *,
280
+ preferences_path: Path | None = None,
281
+ ) -> Preferences:
282
+ """Load user → `.tools` → `.tools_local` → optional explicit file."""
283
+ merged = empty_preferences()
284
+ for root in preference_roots_low_to_high(cwd):
285
+ path = root / "config.json"
286
+ if path.is_file():
287
+ merged = merge_preferences(merged, load_preference_file(path))
288
+ if preferences_path is not None:
289
+ merged = merge_preferences(merged, load_preference_file(preferences_path))
290
+ return merged
291
+
292
+
293
+ def preferences_to_object(prefs: Preferences) -> dict[str, Any]:
294
+ """Serialize for writing the user config file."""
295
+ cli, git_remote, persist = prefs.detection.resolved()
296
+ payload: dict[str, Any] = {"schemaVersion": 1}
297
+ links: dict[str, Any] = {}
298
+ if prefs.links.ref_links:
299
+ links["refLinks"] = dict(prefs.links.ref_links)
300
+ if prefs.links.commit_link:
301
+ links["commitLink"] = prefs.links.commit_link
302
+ if links:
303
+ payload["links"] = links
304
+ defaults: dict[str, Any] = {}
305
+ if prefs.defaults.profile:
306
+ defaults["profile"] = prefs.defaults.profile
307
+ if prefs.defaults.qa:
308
+ defaults["qa"] = prefs.defaults.qa
309
+ if prefs.defaults.display:
310
+ defaults["display"] = prefs.defaults.display
311
+ if prefs.defaults.ref_id_width is not None:
312
+ defaults["refIdWidth"] = prefs.defaults.ref_id_width
313
+ if prefs.defaults.type_width is not None:
314
+ defaults["typeWidth"] = prefs.defaults.type_width
315
+ if prefs.defaults.show_author is not None:
316
+ defaults["showAuthor"] = prefs.defaults.show_author
317
+ if prefs.defaults.show_date is not None:
318
+ defaults["showDate"] = prefs.defaults.show_date
319
+ if prefs.defaults.show_body is not None:
320
+ defaults["showBody"] = prefs.defaults.show_body
321
+ if prefs.defaults.show_id is not None:
322
+ defaults["showId"] = prefs.defaults.show_id
323
+ if prefs.defaults.show_conventional is not None:
324
+ defaults["showConventional"] = prefs.defaults.show_conventional
325
+ if defaults:
326
+ payload["defaults"] = defaults
327
+ payload["detection"] = {
328
+ "cli": cli,
329
+ "gitRemote": git_remote,
330
+ "persistUserConfig": persist,
331
+ }
332
+ return payload
333
+
334
+
335
+ def merge_missing_links_into_user_file(
336
+ *,
337
+ discovered: LinkPreferences,
338
+ user_path: Path | None = None,
339
+ ) -> Preferences:
340
+ """Write discovered link keys that are unset in the user file. Return new user prefs."""
341
+ path = user_path or user_preferences_path()
342
+ if path.is_file():
343
+ existing = load_preference_file(path)
344
+ else:
345
+ existing = empty_preferences()
346
+
347
+ new_refs = dict(existing.links.ref_links)
348
+ for key, value in discovered.ref_links.items():
349
+ if key not in new_refs:
350
+ new_refs[key] = value
351
+ new_commit = existing.links.commit_link
352
+ if new_commit is None and discovered.commit_link is not None:
353
+ new_commit = discovered.commit_link
354
+
355
+ updated = replace(
356
+ existing,
357
+ links=LinkPreferences(ref_links=new_refs, commit_link=new_commit),
358
+ )
359
+ path.parent.mkdir(parents=True, exist_ok=True)
360
+ path.write_text(
361
+ json.dumps(preferences_to_object(updated), indent=2) + "\n",
362
+ encoding="utf-8",
363
+ )
364
+ return updated
365
+
366
+
367
+ def fill_link_gaps(
368
+ prefs: Preferences,
369
+ discovered: LinkPreferences,
370
+ ) -> Preferences:
371
+ """Apply detection only where preference links are still unset."""
372
+ ref_links = dict(prefs.links.ref_links)
373
+ for key, value in discovered.ref_links.items():
374
+ if key not in ref_links:
375
+ ref_links[key] = value
376
+ commit_link = prefs.links.commit_link or discovered.commit_link
377
+ return replace(
378
+ prefs,
379
+ links=LinkPreferences(ref_links=ref_links, commit_link=commit_link),
380
+ )
esys_gitlog/qa.py ADDED
@@ -0,0 +1,196 @@
1
+ """QA evaluation for strict and permissive modes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+
7
+ from esys_gitlog.config import AnalysisConfig
8
+ from esys_gitlog.identifiers import matches_family, ref_identity_key
9
+ from esys_gitlog.model import Claim, CommitResult, Diagnostic
10
+
11
+
12
+ def evaluate_qa(result: CommitResult, config: AnalysisConfig) -> None:
13
+ """Append diagnostics. Mutates ``result``."""
14
+ family = config.profile.identifier_family
15
+ strict = config.qa == "strict"
16
+
17
+ for claim in result.claims:
18
+ if claim.field == "trailer" and claim.value == "" and claim.key is not None:
19
+ result.diagnostics.append(
20
+ Diagnostic(
21
+ code="metadata.trailer.empty",
22
+ severity="error",
23
+ field="trailer",
24
+ claims=(claim,),
25
+ )
26
+ )
27
+
28
+ _evaluate_refs(result, family, strict)
29
+ _evaluate_field_pairs(result, "type", strict)
30
+ _evaluate_field_pairs(result, "scope", strict)
31
+ _evaluate_breaking(result)
32
+ _evaluate_repeated_generic(result)
33
+ _evaluate_mixed(result)
34
+ _evaluate_profile(result)
35
+
36
+
37
+ def _evaluate_refs(result: CommitResult, family: str, strict: bool) -> None:
38
+ ref_claims = result.claims_for("refs")
39
+ seen: dict[str, Claim] = {}
40
+ by_source: dict[str, list[Claim]] = defaultdict(list)
41
+ for claim in ref_claims:
42
+ by_source[claim.source].append(claim)
43
+ if not matches_family(claim.value, family):
44
+ result.diagnostics.append(
45
+ Diagnostic(
46
+ code="metadata.refs.unexpected",
47
+ severity="error",
48
+ field="refs",
49
+ claims=(claim,),
50
+ )
51
+ )
52
+ continue
53
+ identity = ref_identity_key(claim.value)
54
+ prior = seen.get(identity)
55
+ if prior is not None:
56
+ result.diagnostics.append(
57
+ Diagnostic(
58
+ code="metadata.refs.repeated",
59
+ severity="error",
60
+ field="refs",
61
+ claims=(prior, claim),
62
+ )
63
+ )
64
+ else:
65
+ seen[identity] = claim
66
+
67
+ if strict and len(by_source) > 1:
68
+ mixed = tuple(claim for claims in by_source.values() for claim in claims)
69
+ result.diagnostics.append(
70
+ Diagnostic(
71
+ code="metadata.refs.placement",
72
+ severity="error",
73
+ field="refs",
74
+ claims=mixed,
75
+ )
76
+ )
77
+
78
+
79
+ def _evaluate_field_pairs(result: CommitResult, field: str, strict: bool) -> None:
80
+ claims = result.claims_for(field)
81
+ if not claims:
82
+ return
83
+
84
+ by_source: dict[str, list[Claim]] = defaultdict(list)
85
+ for claim in claims:
86
+ by_source[claim.source].append(claim)
87
+
88
+ for source_claims in by_source.values():
89
+ if len(source_claims) > 1:
90
+ result.diagnostics.append(
91
+ Diagnostic(
92
+ code=f"metadata.{field}.repeated",
93
+ severity="error",
94
+ field=field,
95
+ claims=tuple(source_claims),
96
+ )
97
+ )
98
+
99
+ subject = by_source.get("subject", [])
100
+ trailer = by_source.get("trailer", [])
101
+ if subject and trailer:
102
+ subject_value = subject[0].value
103
+ trailer_value = trailer[0].value
104
+ pair = (subject[0], trailer[0])
105
+ if subject_value != trailer_value:
106
+ result.diagnostics.append(
107
+ Diagnostic(
108
+ code=f"metadata.{field}.conflict",
109
+ severity="warning",
110
+ field=field,
111
+ claims=pair,
112
+ )
113
+ )
114
+ elif strict:
115
+ result.diagnostics.append(
116
+ Diagnostic(
117
+ code=f"metadata.{field}.redundancy",
118
+ severity="warning",
119
+ field=field,
120
+ claims=pair,
121
+ )
122
+ )
123
+
124
+
125
+ def _evaluate_breaking(result: CommitResult) -> None:
126
+ claims = result.claims_for("breaking")
127
+ trailer = [claim for claim in claims if claim.source == "trailer"]
128
+ if len(trailer) > 1:
129
+ result.diagnostics.append(
130
+ Diagnostic(
131
+ code="metadata.breaking.repeated",
132
+ severity="error",
133
+ field="breaking",
134
+ claims=tuple(trailer),
135
+ )
136
+ )
137
+
138
+
139
+ def _evaluate_repeated_generic(result: CommitResult) -> None:
140
+ by_key: dict[str, list[Claim]] = defaultdict(list)
141
+ for claim in result.claims:
142
+ if claim.field != "trailer" or claim.key is None:
143
+ continue
144
+ if claim.value == "":
145
+ continue
146
+ by_key[claim.key.casefold()].append(claim)
147
+ for claims in by_key.values():
148
+ if len(claims) > 1:
149
+ result.diagnostics.append(
150
+ Diagnostic(
151
+ code="metadata.trailer.repeated",
152
+ severity="error",
153
+ field="trailer",
154
+ claims=tuple(claims),
155
+ )
156
+ )
157
+
158
+
159
+ def _evaluate_mixed(result: CommitResult) -> None:
160
+ type_claims = result.claims_for("type")
161
+ scope_claims = result.claims_for("scope")
162
+ sources = {claim.source for claim in (*type_claims, *scope_claims)}
163
+ if "subject" in sources and "trailer" in sources:
164
+ mixed_claims = tuple(claim for claim in (*type_claims, *scope_claims))
165
+ result.diagnostics.append(
166
+ Diagnostic(
167
+ code="metadata.conventional.mixed",
168
+ severity="warning",
169
+ field="conventional",
170
+ claims=mixed_claims,
171
+ )
172
+ )
173
+
174
+
175
+ def _evaluate_profile(result: CommitResult) -> None:
176
+ conventional = result.conventional_matched
177
+ references = result.references_matched
178
+ ref_claims = result.claims_for("refs")
179
+ if not conventional and not references:
180
+ result.diagnostics.append(
181
+ Diagnostic(
182
+ code="metadata.profile.miss",
183
+ severity="warning",
184
+ field="profile",
185
+ claims=(),
186
+ )
187
+ )
188
+ elif references and not conventional:
189
+ result.diagnostics.append(
190
+ Diagnostic(
191
+ code="metadata.profile.partial",
192
+ severity="error",
193
+ field="profile",
194
+ claims=tuple(ref_claims),
195
+ )
196
+ )