-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathrelease.py
More file actions
executable file
·1117 lines (912 loc) · 36.6 KB
/
Copy pathrelease.py
File metadata and controls
executable file
·1117 lines (912 loc) · 36.6 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""RHDH Release CLI — deterministic data gathering for release management.
Gathers facts from Jira, Google Sheets, and local config. The agent routes
to this CLI first, then adds judgment (flag risks, suggest actions).
Usage:
python scripts/release.py status 1.9.0
python scripts/release.py status 1.9.0 --json
python scripts/release.py check
"""
from __future__ import annotations
import argparse
import json
import re
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
_scripts_dir = Path(__file__).resolve().parent
if str(_scripts_dir) not in sys.path:
sys.path.insert(0, str(_scripts_dir))
import jql as jql_mod # noqa: E402
import slack_templates as slack_mod # noqa: E402
from formatters import OutputFormatter # noqa: E402
JIRA_BASE = "https://issues.redhat.com"
SCHEDULE_SHEET_ID = "1knVzlMW0l0X4c7gkoiuaGql1zuFgEGwHHBsj-ygUTnc"
TEAM_SHEET_ID = "1vQXfvID72qwqvLb17eyGOvnZXrZG7NBzTGv6RP9wvyM"
def _find_parse_issues() -> Path | None:
"""Discover parse_issues.py from installed rhdh-jira skill or sibling directory."""
candidates = [
Path.home() / ".claude/skills/rhdh-jira/scripts/parse_issues.py",
Path(__file__).resolve().parent / "../../rhdh-jira/scripts/parse_issues.py",
]
for p in candidates:
if p.exists():
return p
return None
ISSUE_TYPES = ["Feature", "Epic", "Story", "Task", "Sub-task", "Bug", "Vulnerability", "Weakness"]
def _normalize_team_name(name: str) -> str:
"""Normalize team name for comparison: strip 'RHDH ' prefix, lowercase."""
n = name.strip()
if n.lower().startswith("rhdh "):
n = n[5:]
return n.lower()
# ---------------------------------------------------------------------------
# Google Sheets helpers (via gog CLI)
# ---------------------------------------------------------------------------
def _gog_sheets_get(sheet_id: str, range_name: str) -> list[list[str]]:
"""Fetch sheet values via gog sheets get --json --results-only."""
result = subprocess.run(
["gog", "sheets", "get", sheet_id, range_name, "--json", "--results-only"],
capture_output=True,
text=True,
)
if result.returncode != 0:
raise RuntimeError(f"gog sheets get failed: {result.stderr.strip()}")
return json.loads(result.stdout)
def _gog_sheets_tabs(sheet_id: str) -> list[str]:
"""Fetch tab names via gog sheets metadata."""
result = subprocess.run(
["gog", "sheets", "metadata", sheet_id, "--json"],
capture_output=True,
text=True,
)
if result.returncode != 0:
raise RuntimeError(f"gog sheets metadata failed: {result.stderr.strip()}")
meta = json.loads(result.stdout)
return [s["properties"]["title"] for s in meta.get("sheets", [])]
# ---------------------------------------------------------------------------
# Team mapping (from Google Sheets)
# ---------------------------------------------------------------------------
def _parse_teams(
rows: list[list[str]], category_filter: str | None = None, include_all: bool = False
) -> list[dict]:
if not rows:
return []
header = [h.strip().lower() for h in rows[0]]
col = {}
for name in (
"category",
"team name",
"team id",
"description",
"status",
"leads",
"slack handles",
"cloud id",
):
for i, h in enumerate(header):
if h == name:
col[name] = i
break
teams = []
for row in rows[1:]:
def cell(name: str) -> str:
idx = col.get(name)
if idx is None or idx >= len(row):
return ""
return row[idx].strip()
status = cell("status")
if not include_all and status.lower() != "active":
continue
category = cell("category")
if category_filter and category.lower() != category_filter.lower():
continue
team_id: int | str = cell("team id")
try:
team_id = int(team_id)
except (ValueError, TypeError):
pass
slack_handles = cell("slack handles")
slack_list = (
[s.strip() for s in slack_handles.split(",") if s.strip()] if slack_handles else []
)
teams.append(
{
"category": category,
"team_name": cell("team name"),
"team_id": team_id,
"description": cell("description"),
"status": status,
"leads": cell("leads"),
"slack_handles": slack_list,
"cloud_id": cell("cloud id"),
}
)
return teams
# ---------------------------------------------------------------------------
# Schedule parsing (from Google Sheets)
# ---------------------------------------------------------------------------
def _normalize_version(v: str) -> str:
"""Extract major.minor from strings like 'RHDH 1.6', 'rhdh-1.6', 'v1.6', '1.6'."""
m = re.search(r"(\d+)\.(\d+)", v)
if m:
return f"{m.group(1)}.{m.group(2)}"
return v.strip()
def _parse_date(raw: str) -> str | None:
"""Try common date formats found in Google Sheets."""
raw = raw.strip()
for fmt in (
"%Y-%m-%d",
"%m/%d/%Y",
"%B %d, %Y",
"%b %d, %Y",
"%d %b %Y",
"%d %B %Y",
"%m/%d/%y",
):
try:
return datetime.strptime(raw, fmt).strftime("%Y-%m-%d")
except ValueError:
continue
return None
def _row_date(cells: list[str]) -> str | None:
"""Return the first parseable date found in a row's cells, or None."""
for cell in cells:
parsed = _parse_date(str(cell))
if parsed:
return parsed
return None
def _find_schedule_tab(tabs: list[str]) -> str | None:
"""Find the best 'Schedule' tab — tries current year, then next, then previous."""
current_year = datetime.now().year
for year in [current_year, current_year + 1, current_year - 1]:
candidates = [t for t in tabs if str(year) in t and "schedule" in t.lower()]
if candidates:
return candidates[0]
fallback = [t for t in tabs if "schedule" in t.lower()]
return fallback[0] if fallback else None
def _find_milestones(rows: list[list[str]], version: str) -> dict[str, str | None]:
"""Search sheet rows for RHDH version milestones.
Strategy:
1. Find the GA row for the target version.
2. Walk backwards to find Code Freeze and Feature Freeze rows.
"""
ver = _normalize_version(version)
ga_keywords = ["ga ", "ga\t", "ga\n", "ga announce", "general availability", "ga date"]
freeze_keywords = {
"code_freeze": ["code freeze", "code-freeze", "codefreeze"],
"feature_freeze": ["feature freeze", "feature-freeze", " ff "],
}
ga_index = None
for i, row in enumerate(rows):
cells = [str(c) for c in row]
row_text = " " + " ".join(cells).lower() + " "
version_match = ver in row_text or (version.lower().replace("rhdh", "").strip() in row_text)
ga_match = any(kw in row_text for kw in ga_keywords)
if version_match and ga_match:
ga_index = i
break
if ga_index is None:
return {}
ga_date = _row_date([str(c) for c in rows[ga_index]])
milestones: dict[str, str | None] = {"ga_date": ga_date} if ga_date else {}
found: dict[str, str] = {}
for i in range(ga_index - 1, -1, -1):
cells = [str(c) for c in rows[i]]
row_text = " " + " ".join(cells).lower() + " "
if any(kw in row_text for kw in ga_keywords):
break
for milestone, keywords in freeze_keywords.items():
if milestone in found:
continue
if any(kw in row_text for kw in keywords):
d = _row_date(cells)
if d:
found[milestone] = d
if len(found) == len(freeze_keywords):
break
milestones.update(found)
return milestones
def _fetch_schedule(sheet_id: str, version: str) -> dict:
"""Fetch milestones for a version from a Google Sheets schedule.
Returns dict with version, tab, feature_freeze, code_freeze, ga_date.
On error, returns dict with 'error' key.
"""
try:
tabs = _gog_sheets_tabs(sheet_id)
except RuntimeError as e:
return {"error": str(e)}
tab = _find_schedule_tab(tabs)
if not tab:
return {"error": "no_schedule_tab_found", "tabs": tabs, "spreadsheet_id": sheet_id}
try:
rows = _gog_sheets_get(sheet_id, tab)
except RuntimeError as e:
return {"error": str(e)}
milestones = _find_milestones(rows, version)
ver = _normalize_version(version)
if not milestones.get("code_freeze") and not milestones.get("ga_date"):
return {
"error": "version_not_found",
"version": ver,
"tab": tab,
"spreadsheet_id": sheet_id,
"hint": "Check that the version string matches the sheet exactly",
}
return {
"version": ver,
"tab": tab,
"feature_freeze": milestones.get("feature_freeze"),
"code_freeze": milestones.get("code_freeze"),
"ga_date": milestones.get("ga_date"),
}
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _run(
cmd: list[str], *, check: bool = True, capture: bool = True
) -> subprocess.CompletedProcess:
"""Run a subprocess, capturing output."""
return subprocess.run(
cmd,
capture_output=capture,
text=True,
check=check,
)
def _parse_acli_count(output: str) -> int:
"""Parse acli --count output like '✓ Number of work items in the search: 42'."""
for line in reversed(output.strip().splitlines()):
m = re.search(r"(\d+)\s*$", line)
if m:
return int(m.group(1))
raise ValueError(f"Could not parse count from acli output: {output!r}")
def _acli_count(jql: str, fmt: OutputFormatter) -> int:
"""Run acli --count and return the parsed integer."""
result = _run(["acli", "jira", "workitem", "search", "--jql", jql, "--count"])
if fmt.verbose:
fmt.add_debug("acli_cmd", f"acli jira workitem search --jql {jql!r} --count")
return _parse_acli_count(result.stdout)
def _acli_json_enriched(
jql: str,
*,
select: str = "key,summary,status,assignee,priority,team",
limit: int = 1000,
) -> list[dict]:
"""Run acli --json | parse_issues.py --enrich and return parsed list."""
parse_issues = _find_parse_issues()
if parse_issues is None:
raise RuntimeError(
"parse_issues.py not found. Install the rhdh-jira skill: npx skills add rhdh-jira"
)
acli = subprocess.Popen(
["acli", "jira", "workitem", "search", "--jql", jql, "--json", "--limit", str(limit)],
stdout=subprocess.PIPE,
text=True,
)
parse = subprocess.Popen(
[sys.executable, str(parse_issues), "--enrich", "-s", select, "--json"],
stdin=acli.stdout,
stdout=subprocess.PIPE,
text=True,
)
if acli.stdout:
acli.stdout.close()
stdout, _ = parse.communicate()
acli.wait()
if parse.returncode != 0:
raise RuntimeError(f"parse_issues.py failed (exit {parse.returncode})")
issues = json.loads(stdout)
if len(issues) >= limit:
print(f"WARNING: Results may be truncated at limit={limit}", file=sys.stderr)
return issues
def _acli_view_json(issue_key: str) -> dict:
"""Fetch a single Jira issue as JSON."""
result = _run(["acli", "jira", "workitem", "view", issue_key, "--json"])
return json.loads(result.stdout)
def _fetch_teams(category: str | None = None) -> list[dict]:
"""Fetch team mapping from Google Sheets via gog."""
rows = _gog_sheets_get(TEAM_SHEET_ID, "Team")
if not rows:
raise RuntimeError("Team sheet is empty")
return _parse_teams(rows, category_filter=category)
# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------
def cmd_check(_args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Verify prerequisites: acli, .jira-token, gog, gog-auth."""
checks = []
acli_path = shutil.which("acli")
checks.append(
{
"name": "acli",
"status": "pass" if acli_path else "fail",
"message": acli_path or "not found on PATH",
}
)
token_file = Path.home() / ".jira-token"
checks.append(
{
"name": ".jira-token",
"status": "pass" if token_file.exists() else "warn",
"message": str(token_file)
if token_file.exists()
else "missing (optional — acli may authenticate via other methods)",
}
)
gog_path = shutil.which("gog")
checks.append(
{
"name": "gog",
"status": "pass" if gog_path else "warn",
"message": gog_path or "not found (needed for Google Sheets/Docs)",
}
)
gog_auth_ok = False
if gog_path:
try:
result = _run(
["gog", "sheets", "metadata", TEAM_SHEET_ID, "--json"],
check=False,
)
gog_auth_ok = result.returncode == 0
except Exception:
gog_auth_ok = False
checks.append(
{
"name": "gog-auth",
"status": "pass" if gog_auth_ok else "warn",
"message": "authenticated" if gog_auth_ok else "run: gog auth add <email>",
}
)
if acli_path:
try:
result = _run(
["acli", "jira", "workitem", "search", "--jql", "project=RHIDP", "--count"],
check=False,
)
jira_ok = result.returncode == 0
except Exception:
jira_ok = False
checks.append(
{
"name": "jira-connectivity",
"status": "pass" if jira_ok else "fail",
"message": "connected" if jira_ok else "acli cannot reach Jira",
}
)
all_pass = all(c["status"] == "pass" for c in checks)
has_fail = any(c["status"] == "fail" for c in checks)
for c in checks:
if c["status"] == "pass":
fmt.log_ok(f"{c['name']}: {c['message']}")
elif c["status"] == "warn":
fmt.log_warn(f"{c['name']}: {c['message']}")
else:
fmt.log_fail(f"{c['name']}: {c['message']}")
next_steps = []
if has_fail:
next_steps.append("Fix failing checks before running other commands")
if not all_pass:
next_steps.append("See: references/config.md for setup instructions")
fmt.success({"checks": checks, "all_pass": all_pass}, next_steps=next_steps or None)
if has_fail:
sys.exit(1)
def cmd_dates(_args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Retrieve active release dates from Jira."""
jql = jql_mod.render("active_release")
result = _run(["acli", "jira", "workitem", "search", "--jql", jql, "--json"])
issues = json.loads(result.stdout)
releases = []
for issue in issues:
key = issue.get("key", "")
summary = issue.get("fields", {}).get("summary", "")
detail = _acli_view_json(key)
desc = ""
desc_field = detail.get("fields", {}).get("description", {})
if isinstance(desc_field, dict):
desc = json.dumps(desc_field)
elif isinstance(desc_field, str):
desc = desc_field
dates = {}
for label in ["Feature Freeze", "Code Freeze", "Doc Freeze", "Go/No Go", "GA Announce"]:
m = re.search(rf"{re.escape(label)}[:\s]*(\d{{4}}-\d{{2}}-\d{{2}})", desc)
dates[label.lower().replace(" ", "_").replace("/", "_")] = m.group(1) if m else "TBD"
version_m = re.search(r"(\d+\.\d+(?:\.\d+)?)", summary)
if not version_m:
continue
version = version_m.group(1)
releases.append(
{
"version": version,
"issue_key": key,
"issue_url": f"{JIRA_BASE}/browse/{key}",
**dates,
}
)
fmt.header("Active Release Dates")
for r in releases:
fmt.log_info(f"RHDH {r['version']} ({r['issue_key']})")
for dk in ["feature_freeze", "code_freeze", "doc_freeze", "go_no_go", "ga_announce"]:
label = dk.replace("_", " ").title()
fmt.log_ok(f" {label}: {r[dk]}") if r[dk] != "TBD" else fmt.log_warn(f" {label}: TBD")
fmt.success({"releases": releases})
def cmd_future_dates(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Retrieve future release dates from Google Sheets schedule."""
version = args.version
schedule = _fetch_schedule(SCHEDULE_SHEET_ID, version)
if "error" in schedule:
fmt.error(
"SCHEDULE_ERROR",
str(schedule["error"]),
next_steps=[
schedule.get("hint", "Check gog auth: gog auth add <email>"),
],
)
sys.exit(1)
fmt.header(f"RHDH {version} Schedule")
for key in ["feature_freeze", "code_freeze", "ga_date"]:
label = key.replace("_", " ").title()
val = schedule.get(key, "N/A")
fmt.log_info(f"{label}: {val}")
schedule["schedule_url"] = f"https://docs.google.com/spreadsheets/d/{SCHEDULE_SHEET_ID}/edit"
fmt.success({"schedule": schedule})
def cmd_status(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Show open issue counts by type for a release version."""
version = args.version
rows = []
fmt.header(f"RHDH {version} — Release Status")
total = 0
for issue_type in ISSUE_TYPES:
jql, url = jql_mod.render_with_url(
"open_issues_by_type", version=version, issue_type=issue_type
)
count = _acli_count(jql, fmt)
total += count
rows.append(
{
"issue_type": issue_type,
"count": count,
"jira_url": url,
}
)
fmt.log_info(f"{issue_type:<15} {count:>5} {url}")
_, total_url = jql_mod.render_with_url("open_issues", version=version)
fmt.log_info(f"{'Total':<15} {total:>5} {total_url}")
recently_jql, recently_url = jql_mod.render_with_url(
"features_added_to_release", version=version
)
recently_count = _acli_count(recently_jql, fmt)
fmt.success(
{
"version": version,
"issue_counts": rows,
"total": total,
"total_jira_url": total_url,
"recently_added_features": recently_count,
"recently_added_url": recently_url,
}
)
def cmd_teams(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""List teams and leads from Google Sheets."""
teams = _fetch_teams(category=args.category)
fmt.header("RHDH Teams")
for t in teams:
slack = ", ".join(t.get("slack_handles", []))
fmt.log_info(f"{t['team_name']:<25} {t.get('leads', ''):<20} {slack}")
fmt.success(
{
"teams": teams,
"count": len(teams),
"source_url": "https://docs.google.com/spreadsheets/d/1vQXfvID72qwqvLb17eyGOvnZXrZG7NBzTGv6RP9wvyM/edit",
}
)
def cmd_team_breakdown(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Per-team issue counts for a release using JQL team filter."""
version = args.version
teams = _fetch_teams(category="Engineering")
rows = []
for t in teams:
name = t["team_name"]
cid = t.get("cloud_id", "")
if not cid:
rows.append({"team_name": name, "cloud_id": "", "count": 0,
"leads": t.get("leads", ""), "slack_handles": t.get("slack_handles", [])})
continue
jql, url = jql_mod.render_with_url("open_issues_by_team", version=version, cloud_id=cid)
count = _acli_count(jql, fmt)
fmt.log_info(f"{name:<25} {count:>5}")
rows.append(
{
"team_name": name,
"cloud_id": cid,
"count": count,
"jira_url": url,
"leads": t.get("leads", ""),
"slack_handles": t.get("slack_handles", []),
}
)
fmt.header(f"RHDH {version} — Issues by Team")
for r in rows:
fmt.log_info(f"{r['team_name']:<25} {r['count']:>5}")
_, total_url = jql_mod.render_with_url("open_issues", version=version)
fmt.success(
{
"version": version,
"team_breakdown": rows,
"total": sum(r["count"] for r in rows),
"total_jira_url": total_url,
}
)
def cmd_blockers(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""List open blocker bugs for a release."""
version = args.version
jql, url = jql_mod.render_with_url("blockers", version=version)
issues = _acli_json_enriched(jql, select="key,summary,status,assignee,priority,team")
count = len(issues)
fmt.header(f"RHDH {version} — Blocker Bugs")
for issue in issues:
fmt.log_info(
f"[{issue['key']}]({JIRA_BASE}/browse/{issue['key']}) "
f"{issue.get('summary', '')[:60]} — {issue.get('assignee', 'Unassigned')}"
)
fmt.success(
{
"version": version,
"blockers": issues,
"count": count,
"jira_url": url,
}
)
def cmd_epics(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""List outstanding Engineering EPICs for a release."""
version = args.version
jql, url = jql_mod.render_with_url("epics", version=version)
issues = _acli_json_enriched(jql, select="key,summary,status,assignee")
count = len(issues)
fmt.header(f"RHDH {version} — Outstanding EPICs")
for issue in issues:
fmt.log_info(
f"[{issue['key']}]({JIRA_BASE}/browse/{issue['key']}) "
f"{issue.get('summary', '')[:60]} — {issue.get('status', '')}"
)
fmt.success(
{
"version": version,
"epics": issues,
"count": count,
"jira_url": url,
}
)
def cmd_cves(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""List CVE issues for a release."""
version = args.version
jql, url = jql_mod.render_with_url("cves", version=version)
issues = _acli_json_enriched(jql, select="key,summary,status,priority,assignee,issuetype")
count = len(issues)
fmt.header(f"RHDH {version} — CVEs")
for issue in issues:
fmt.log_info(
f"[{issue['key']}]({JIRA_BASE}/browse/{issue['key']}) "
f"{issue.get('summary', '')[:60]} — {issue.get('priority', '')}"
)
fmt.success(
{
"version": version,
"cves": issues,
"count": count,
"jira_url": url,
}
)
def cmd_notes(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Count issues missing Release Note Type."""
version = args.version
jql, url = jql_mod.render_with_url("release_notes", version=version)
count = _acli_count(jql, fmt)
dashboard_url = "https://issues.redhat.com/secure/Dashboard.jspa?selectPageId=12382090"
fmt.header(f"RHDH {version} — Release Notes")
fmt.log_info(f"Outstanding: {count} issues missing Release Note Type")
fmt.log_info(f"Dashboard: {dashboard_url}")
fmt.success(
{
"version": version,
"outstanding_count": count,
"jira_url": url,
"dashboard_url": dashboard_url,
}
)
# ---------------------------------------------------------------------------
# Slack subcommands
# ---------------------------------------------------------------------------
def _get_freeze_date(version: str, date_key: str) -> str:
"""Get a freeze date from active release issues. Returns date or 'TBD'."""
jql = jql_mod.render("active_release")
result = _run(["acli", "jira", "workitem", "search", "--jql", jql, "--json"])
issues = json.loads(result.stdout)
for issue in issues:
summary = issue.get("fields", {}).get("summary", "")
if version in summary:
detail = _acli_view_json(issue["key"])
desc_field = detail.get("fields", {}).get("description", {})
desc = json.dumps(desc_field) if isinstance(desc_field, dict) else str(desc_field or "")
m = re.search(rf"{re.escape(date_key)}[:\s]*(\d{{4}}-\d{{2}}-\d{{2}})", desc)
if m:
return m.group(1)
return "TBD"
def cmd_slack_feature_freeze_update(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Generate Feature Freeze Update Slack message."""
version = args.version
ff_date = _get_freeze_date(version, "Feature Freeze")
teams = _fetch_teams(category="Engineering")
rn_jql, rn_url = jql_mod.render_with_url("release_notes", version=version)
rn_count = _acli_count(rn_jql, fmt)
team_lines = []
for t in teams:
name = t["team_name"]
cid = t.get("cloud_id", "")
if not cid:
continue
jql, url = jql_mod.render_with_url(
"feature_freeze_issues_by_team", version=version, cloud_id=cid
)
count = _acli_count(jql, fmt)
slack_handles = t.get("slack_handles", [])
lead_slack = slack_handles[0] if slack_handles else t.get("leads", "")
team_lines.append(
{
"TEAM_NAME": name,
"ISSUE_COUNT": str(count),
"JIRA_LINK": url,
"LEAD_SLACK": lead_slack,
}
)
template = slack_mod.get_template("feature_freeze_update")
template = slack_mod.fill_placeholders(
template,
{
"RELEASE_VERSION": version,
"FEATURE_FREEZE_DATE": ff_date,
"OUTSTANDING_RELEASE_NOTES_ISSUE_COUNT": str(rn_count),
"RELEASE_NOTES_JIRA_LINK": rn_url,
},
)
message = slack_mod.expand_team_lines(template, team_lines)
fmt.render_raw(f"```slack\n{message}\n```")
fmt.success(
{
"version": version,
"feature_freeze_date": ff_date,
"outstanding_release_notes": rn_count,
"team_counts": {t["TEAM_NAME"]: int(t["ISSUE_COUNT"]) for t in team_lines},
"slack_message": message,
}
)
def cmd_slack_feature_freeze(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Generate Feature Freeze Announcement Slack message."""
version = args.version
epics_jql, epics_url = jql_mod.render_with_url("epics", version=version)
epics_count = _acli_count(epics_jql, fmt)
cves_jql, cves_url = jql_mod.render_with_url("cves", version=version)
cves_count = _acli_count(cves_jql, fmt)
rn_jql, rn_url = jql_mod.render_with_url("release_notes", version=version)
rn_count = _acli_count(rn_jql, fmt)
template = slack_mod.get_template("feature_freeze")
lines = template.splitlines()
filled: list[str] = []
for line in lines:
if "{{EPIC_ISSUE_COUNT}}" in line:
line = line.replace("{{EPIC_ISSUE_COUNT}}", str(epics_count))
line = line.replace("{{JIRA_LINK}}", epics_url)
elif "{{CVE_ISSUE_COUNT}}" in line:
line = line.replace("{{CVE_ISSUE_COUNT}}", str(cves_count))
line = line.replace("{{JIRA_LINK}}", cves_url)
elif "{{OUTSTANDING_RELEASE_NOTES_ISSUE_COUNT}}" in line:
line = line.replace("{{OUTSTANDING_RELEASE_NOTES_ISSUE_COUNT}}", str(rn_count))
line = line.replace("{{JIRA_LINK}}", rn_url)
line = line.replace("{{RELEASE_VERSION}}", version)
filled.append(line)
message = "\n".join(filled)
fmt.render_raw(f"```slack\n{message}\n```")
fmt.success(
{
"version": version,
"epics_count": epics_count,
"cves_count": cves_count,
"outstanding_release_notes": rn_count,
"slack_message": message,
}
)
def cmd_slack_code_freeze_update(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Generate Code Freeze Update Slack message."""
version = args.version
cf_date = _get_freeze_date(version, "Code Freeze")
teams = _fetch_teams(category="Engineering")
rn_jql, rn_url = jql_mod.render_with_url("release_notes", version=version)
rn_count = _acli_count(rn_jql, fmt)
fs_jql, fs_url = jql_mod.render_with_url("feature_subtasks", version=version)
fs_count = _acli_count(fs_jql, fmt)
team_lines = []
for t in teams:
name = t["team_name"]
cid = t.get("cloud_id", "")
if not cid:
continue
jql, url = jql_mod.render_with_url(
"code_freeze_issues_by_team", version=version, cloud_id=cid
)
count = _acli_count(jql, fmt)
slack_handles = t.get("slack_handles", [])
lead_slack = slack_handles[0] if slack_handles else t.get("leads", "")
team_lines.append(
{
"TEAM_NAME": name,
"TEAM_ISSUE_COUNT": str(count),
"JIRA_LINK": url,
"LEAD_SLACK": lead_slack,
}
)
template = slack_mod.get_template("code_freeze_update")
template = slack_mod.fill_placeholders(
template,
{
"RELEASE_VERSION": version,
"CODE_FREEZE_DATE": cf_date,
"OUTSTANDING_RELEASE_NOTES_ISSUE_COUNT": str(rn_count),
"RELEASE_NOTES_JIRA_LINK": rn_url,
"FEATURE_SUBTASK_ISSUE_COUNT": str(fs_count),
"FEATURE_SUBTASK_JIRA_LINK": fs_url,
},
)
message = slack_mod.expand_team_lines(template, team_lines)
fmt.render_raw(f"```slack\n{message}\n```")
fmt.success(
{
"version": version,
"code_freeze_date": cf_date,
"outstanding_release_notes": rn_count,
"feature_subtasks": fs_count,
"team_counts": {t["TEAM_NAME"]: int(t["TEAM_ISSUE_COUNT"]) for t in team_lines},
"slack_message": message,
}
)
def cmd_slack_code_freeze(args: argparse.Namespace, fmt: OutputFormatter) -> None:
"""Generate Code Freeze Announcement Slack message."""
version = args.version
blocker_jql, blocker_url = jql_mod.render_with_url("blockers", version=version)
blocker_count = _acli_count(blocker_jql, fmt)
demos_jql, demos_url = jql_mod.render_with_url("feature_demos", version=version)
demos_count = _acli_count(demos_jql, fmt)
testday_jql, testday_url = jql_mod.render_with_url("test_day_features", version=version)
testday_count = _acli_count(testday_jql, fmt)
open_jql, open_url = jql_mod.render_with_url("open_issues", version=version)
open_count = _acli_count(open_jql, fmt)
template = slack_mod.get_template("code_freeze")
lines = template.splitlines()
filled: list[str] = []
for line in lines:
if "{{BLOCKER_BUG_ISSUE_COUNT}}" in line:
line = line.replace("{{BLOCKER_BUG_ISSUE_COUNT}}", str(blocker_count))
line = line.replace("{{JIRA_LINK}}", blocker_url)
elif "{{FEATURE_DEMO_ISSUE_COUNT}}" in line:
line = line.replace("{{FEATURE_DEMO_ISSUE_COUNT}}", str(demos_count))
line = line.replace("{{JIRA_LINK}}", demos_url)
elif "{{TEST_DAY_FEATURE_ISSUE_COUNT}}" in line:
line = line.replace("{{TEST_DAY_FEATURE_ISSUE_COUNT}}", str(testday_count))
line = line.replace("{{JIRA_LINK}}", testday_url)
elif "{{OPEN_ISSUE_COUNT}}" in line:
line = line.replace("{{OPEN_ISSUE_COUNT}}", str(open_count))
line = line.replace("{{JIRA_LINK}}", open_url)
line = line.replace("{{RELEASE_VERSION}}", version)
filled.append(line)
message = "\n".join(filled)
fmt.render_raw(f"```slack\n{message}\n```")
fmt.success(
{
"version": version,
"blocker_bugs": blocker_count,
"feature_demos": demos_count,
"test_day_features": testday_count,
"open_issues": open_count,
"slack_message": message,
}
)
# ---------------------------------------------------------------------------
# CLI entrypoint
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="release",
description="RHDH Release CLI — deterministic data gathering for release management.",
)
parser.add_argument("--json", action="store_const", const="json", dest="output_mode")
parser.add_argument("--human", action="store_const", const="human", dest="output_mode")
parser.add_argument("--verbose", "-v", action="store_true")