-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbuild_winloss_digest.py
More file actions
240 lines (200 loc) · 7.23 KB
/
build_winloss_digest.py
File metadata and controls
240 lines (200 loc) · 7.23 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
"""Build the quarterly win/loss digest published under /builders/enablement.
Aggregates every ``kind: win-loss`` entry under the curated source path
(default ``docs/enablement``) whose ``last_reviewed`` falls in the requested
quarter, and emits a Markdown digest at
``docs/enablement/win-loss/digest/<YYYY-Q>/index.md``.
Win/loss entries are immutable. Corrections must be authored as **new**
entries that reference the original by slug; the digest preserves both.
Usage
-----
::
python scripts/ops/build_winloss_digest.py
python scripts/ops/build_winloss_digest.py --quarter 2025-Q4
python scripts/ops/build_winloss_digest.py --check
"""
from __future__ import annotations
import argparse
import re
import sys
from dataclasses import dataclass
from datetime import date
from pathlib import Path
# Reuse the canonical front-matter parser/validator from the index builder so
# the two scripts cannot drift.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_enablement_index import ( # noqa: E402 pylint: disable=wrong-import-position
DEFAULT_SOURCE_DIR,
REPO_ROOT,
_iter_markdown,
_parse_front_matter,
_parse_iso_date,
_safe_relative,
_validate_front_matter,
)
QUARTER_RE = re.compile(r"^(?P<year>\d{4})-Q(?P<q>[1-4])$")
@dataclass(frozen=True)
class WinLossEntry:
"""A single win-loss entry as parsed from disk."""
slug: str
title: str
owner: str
last_reviewed: date
rel_path: str
body: str
def _quarter_bounds(label: str) -> tuple[date, date]:
match = QUARTER_RE.match(label)
if match is None:
raise ValueError(f"invalid quarter '{label}'; expected format YYYY-QN (e.g. 2025-Q4)")
year = int(match.group("year"))
quarter = int(match.group("q"))
start_month = 3 * (quarter - 1) + 1
start = date(year, start_month, 1)
if quarter == 4:
end = date(year, 12, 31)
else:
end = date(year, start_month + 3, 1).fromordinal(
date(year, start_month + 3, 1).toordinal() - 1
)
return start, end
def _quarter_for(today: date) -> str:
quarter = (today.month - 1) // 3 + 1
return f"{today.year}-Q{quarter}"
def _strip_front_matter(text: str) -> str:
"""Return the Markdown body after the front-matter block."""
if not text.startswith("---"):
return text.strip()
# Find the closing fence after the opening fence.
closing = text.find("\n---", 3)
if closing == -1:
return text.strip()
after = text[closing + len("\n---") :].lstrip("\r\n")
return after.strip()
def collect_entries(
source_dir: Path,
quarter: tuple[date, date],
repo_root: Path = REPO_ROOT,
) -> tuple[list[WinLossEntry], list[str]]:
"""Return the win/loss entries inside *quarter* plus any validation errors."""
start, end = quarter
entries: list[WinLossEntry] = []
errors: list[str] = []
for md_path in _iter_markdown(source_dir):
rel_path = _safe_relative(md_path, repo_root)
try:
text = md_path.read_text(encoding="utf-8")
except OSError as exc:
errors.append(f"{rel_path}: cannot read ({exc})")
continue
fm = _parse_front_matter(text)
if fm is None or fm.get("kind") != "win-loss":
continue
validation = _validate_front_matter(fm, rel_path)
if validation:
for v in validation:
errors.append(f"{v.file} [{v.field}] {v.message}")
continue
reviewed = _parse_iso_date(fm["last_reviewed"])
if reviewed is None or reviewed < start or reviewed > end:
continue
entries.append(
WinLossEntry(
slug=md_path.stem,
title=fm["title"],
owner=fm["owner"],
last_reviewed=reviewed,
rel_path=rel_path,
body=_strip_front_matter(text),
)
)
entries.sort(key=lambda e: (e.last_reviewed, e.slug))
return entries, errors
def render_digest(quarter_label: str, entries: list[WinLossEntry]) -> str:
"""Render the Markdown digest for *quarter_label* given *entries*."""
lines: list[str] = []
lines.append(f"# Win/Loss digest ÔÇö {quarter_label}")
lines.append("")
lines.append(
"Auto-generated by `scripts/ops/build_winloss_digest.py`. "
"Win/loss entries are immutable; corrections appear as later entries "
"that reference the original by slug."
)
lines.append("")
if not entries:
lines.append(f"_No win/loss entries authored in {quarter_label}._")
lines.append("")
return "\n".join(lines)
lines.append(f"_{len(entries)} entries this quarter._")
lines.append("")
for entry in entries:
lines.append(f"## {entry.title}")
lines.append("")
lines.append(f"- **Owner.** `{entry.owner}`")
lines.append(f"- **Last reviewed.** {entry.last_reviewed.isoformat()}")
lines.append(
"- **Source.** "
f"[`{entry.rel_path}`]"
f"(https://github.com/Azure-Samples/holiday-peak-hub/blob/main/"
f"{entry.rel_path})"
)
lines.append("")
lines.append(entry.body if entry.body else "_(no body content)_")
lines.append("")
return "\n".join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--source",
type=Path,
default=DEFAULT_SOURCE_DIR,
help="curated source directory containing enablement Markdown files",
)
parser.add_argument(
"--output-root",
type=Path,
default=DEFAULT_SOURCE_DIR / "win-loss" / "digest",
help=(
"root directory for the digest output; the script writes " "<root>/<quarter>/index.md"
),
)
parser.add_argument(
"--quarter",
default=None,
help=(
"quarter to render in YYYY-QN format (default: current quarter " "based on local time)"
),
)
parser.add_argument(
"--check",
action="store_true",
help="validate inputs and render the digest in-memory; do not write",
)
args = parser.parse_args(argv)
quarter_label = args.quarter or _quarter_for(date.today())
try:
bounds = _quarter_bounds(quarter_label)
except ValueError as exc:
print(f"winloss-digest: {exc}", file=sys.stderr)
return 1
entries, errors = collect_entries(args.source, bounds)
if errors:
print(f"winloss-digest: {len(errors)} validation error(s):", file=sys.stderr)
for err in errors:
print(f" - {err}", file=sys.stderr)
return 1
digest = render_digest(quarter_label, entries)
if args.check:
print(
f"winloss-digest: OK ({len(entries)} entries in {quarter_label})",
file=sys.stderr,
)
return 0
target = args.output_root / quarter_label / "index.md"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(digest + "\n", encoding="utf-8")
print(
f"winloss-digest: wrote {target} " f"({len(entries)} entries in {quarter_label})",
file=sys.stderr,
)
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())