@bbcsoftwarefactory/commands 0.0.0-stage → 0.1.1
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.
- package/dist/commands/daily/SKILL.md +112 -0
- package/dist/commands/daily/adapters/command.md +17 -0
- package/dist/commands/daily/adapters/gemini.toml +17 -0
- package/dist/commands/issue-clean-and-close/SKILL.md +86 -0
- package/dist/commands/issue-clean-and-close/adapters/command.md +17 -0
- package/dist/commands/issue-clean-and-close/adapters/gemini.toml +17 -0
- package/dist/commands/issue-clean-and-close/references/policy.md +87 -0
- package/dist/commands/issue-clean-and-close/scripts/sweep-github.py +347 -0
- package/dist/commands/issue-clean-and-close/scripts/sweep-issues.py +487 -0
- package/dist/commands/issue-clean-and-close/scripts/sweep.py +231 -0
- package/dist/commands/issue-clean-and-close/tests/sweep-github.test.sh +156 -0
- package/dist/commands/issue-clean-and-close/tests/sweep-issues.test.sh +269 -0
- package/dist/commands/issue-clean-and-close/tests/sweep.test.sh +181 -0
- package/dist/commands/recap/SKILL.md +90 -0
- package/dist/commands/recap/adapters/command.md +17 -0
- package/dist/commands/recap/adapters/gemini.toml +17 -0
- package/dist/commands/recap/scripts/recap.py +1610 -0
- package/dist/commands/recap/tests/recap.test.sh +275 -0
- package/dist/index.json +54 -0
- package/package.json +30 -6
- package/README.md +0 -3
|
@@ -0,0 +1,1610 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Daily progress recap and optional GitHub Project board sync.
|
|
3
|
+
|
|
4
|
+
LAYER: Application
|
|
5
|
+
Contains: Daily progress collector, Project v2 board analyzer/syncer, and HUD formatter
|
|
6
|
+
Rules: Read-only by default; board mutations require explicit --sync-board flag.
|
|
7
|
+
BigO: O(n) score:3
|
|
8
|
+
keywords: [RecapReport, LocalGitCollector, GitHubRestCollector, ProjectBoardSync]
|
|
9
|
+
GOAL: Compute a verified daily progress summary and optionally sync a Project v2 board.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
from datetime import datetime, timedelta, timezone
|
|
14
|
+
import json
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import re
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import urllib.parse
|
|
20
|
+
|
|
21
|
+
REPO_RE = re.compile(r'^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$')
|
|
22
|
+
REL_SINCE_RE = re.compile(r'^(\d+)([hd])$', re.IGNORECASE)
|
|
23
|
+
DATE_ONLY_RE = re.compile(r'^\d{4}-\d{2}-\d{2}$')
|
|
24
|
+
ORIGIN_SSH_RE = re.compile(r'^git@[^:]+:([^/]+/[^/]+?)(?:\.git)?$')
|
|
25
|
+
ORIGIN_HTTPS_RE = re.compile(r'^https?://[^/]+/([^/]+/[^/]+?)(?:\.git)?/?$')
|
|
26
|
+
CLOSES_ISSUE_RE = re.compile(r'(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)', re.IGNORECASE)
|
|
27
|
+
PROJECT_URL_RE = re.compile(
|
|
28
|
+
r'^https?://github\.com/(orgs|users)/([A-Za-z0-9_.-]+)/projects/(\d+)(?:/views/(\d+))?/?$'
|
|
29
|
+
)
|
|
30
|
+
PROJECT_SHORT_RE = re.compile(r'^([A-Za-z0-9_.-]+)/(\d+)$')
|
|
31
|
+
|
|
32
|
+
STANDARD_STATUS_COLORS = {
|
|
33
|
+
'backlog': 'GRAY',
|
|
34
|
+
'todo': 'GRAY',
|
|
35
|
+
'ready': 'BLUE',
|
|
36
|
+
'in progress': 'YELLOW',
|
|
37
|
+
'in review': 'PURPLE',
|
|
38
|
+
'done': 'GREEN',
|
|
39
|
+
}
|
|
40
|
+
PALETTE_COLORS = ('BLUE', 'PURPLE', 'PINK', 'ORANGE', 'YELLOW', 'GREEN', 'RED')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def local_tz():
|
|
44
|
+
return datetime.now().astimezone().tzinfo or timezone.utc
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_ts(raw):
|
|
48
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
49
|
+
return None
|
|
50
|
+
cleaned = raw.strip()
|
|
51
|
+
if cleaned.endswith('Z'):
|
|
52
|
+
cleaned = cleaned[:-1] + '+00:00'
|
|
53
|
+
try:
|
|
54
|
+
dt = datetime.fromisoformat(cleaned)
|
|
55
|
+
except ValueError:
|
|
56
|
+
return None
|
|
57
|
+
if dt.tzinfo is None:
|
|
58
|
+
return dt.replace(tzinfo=local_tz())
|
|
59
|
+
return dt
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse_since(value=None, now=None):
|
|
63
|
+
ref = now or datetime.now().astimezone()
|
|
64
|
+
tz = ref.tzinfo or local_tz()
|
|
65
|
+
if value is None or not str(value).strip():
|
|
66
|
+
return ref.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
67
|
+
|
|
68
|
+
raw = str(value).strip()
|
|
69
|
+
rel = REL_SINCE_RE.fullmatch(raw)
|
|
70
|
+
if rel:
|
|
71
|
+
amount = int(rel.group(1))
|
|
72
|
+
unit = rel.group(2).lower()
|
|
73
|
+
if unit == 'h':
|
|
74
|
+
if amount < 1 or amount > 24 * 30:
|
|
75
|
+
raise ValueError('--since hours must be between 1h and 720h.')
|
|
76
|
+
return ref - timedelta(hours=amount)
|
|
77
|
+
if amount < 1 or amount > 90:
|
|
78
|
+
raise ValueError('--since days must be between 1d and 90d.')
|
|
79
|
+
return ref - timedelta(days=amount)
|
|
80
|
+
|
|
81
|
+
if DATE_ONLY_RE.fullmatch(raw):
|
|
82
|
+
day = datetime.strptime(raw, '%Y-%m-%d')
|
|
83
|
+
return day.replace(tzinfo=tz)
|
|
84
|
+
|
|
85
|
+
parsed = parse_ts(raw)
|
|
86
|
+
if parsed is None:
|
|
87
|
+
raise ValueError(f'Invalid --since value: {value!r}. Use YYYY-MM-DD, <N>h, <N>d, or ISO-8601.')
|
|
88
|
+
return parsed
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def in_window(ts_raw, since_dt):
|
|
92
|
+
dt = parse_ts(ts_raw)
|
|
93
|
+
if dt is None:
|
|
94
|
+
return False
|
|
95
|
+
return dt >= since_dt
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def parse_repo_from_remote(url):
|
|
99
|
+
text = (url or '').strip()
|
|
100
|
+
for pattern in (ORIGIN_SSH_RE, ORIGIN_HTTPS_RE):
|
|
101
|
+
match = pattern.match(text)
|
|
102
|
+
if match and REPO_RE.fullmatch(match.group(1)):
|
|
103
|
+
return match.group(1)
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def parse_project_ref(value):
|
|
108
|
+
text = (value or '').strip()
|
|
109
|
+
if not text:
|
|
110
|
+
return None
|
|
111
|
+
url_match = PROJECT_URL_RE.match(text)
|
|
112
|
+
if url_match:
|
|
113
|
+
scope, owner, num_s, view_s = url_match.groups()
|
|
114
|
+
return {
|
|
115
|
+
'owner_type': 'organization' if scope == 'orgs' else 'user',
|
|
116
|
+
'owner': owner,
|
|
117
|
+
'number': int(num_s),
|
|
118
|
+
'view': int(view_s) if view_s else None,
|
|
119
|
+
}
|
|
120
|
+
short_match = PROJECT_SHORT_RE.match(text)
|
|
121
|
+
if short_match:
|
|
122
|
+
owner, num_s = short_match.groups()
|
|
123
|
+
return {
|
|
124
|
+
'owner_type': 'organization',
|
|
125
|
+
'owner': owner,
|
|
126
|
+
'number': int(num_s),
|
|
127
|
+
'view': None,
|
|
128
|
+
}
|
|
129
|
+
raise ValueError(
|
|
130
|
+
f'Invalid --project {value!r}; use a GitHub Project URL or <owner>/<number>.'
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def run_cmd(cmd, cwd=None, timeout=20):
|
|
135
|
+
try:
|
|
136
|
+
proc = subprocess.run(
|
|
137
|
+
cmd,
|
|
138
|
+
cwd=str(cwd) if cwd else None,
|
|
139
|
+
capture_output=True,
|
|
140
|
+
text=True,
|
|
141
|
+
check=False,
|
|
142
|
+
timeout=timeout,
|
|
143
|
+
)
|
|
144
|
+
return proc.returncode, proc.stdout, proc.stderr
|
|
145
|
+
except (OSError, subprocess.SubprocessError) as err:
|
|
146
|
+
return 1, '', str(err)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def collect_local_git(cwd, since_dt, author_pattern=None):
|
|
150
|
+
code, top_out, _ = run_cmd(['git', 'rev-parse', '--show-toplevel'], cwd=cwd)
|
|
151
|
+
if code != 0 or not top_out.strip():
|
|
152
|
+
return {'available': False, 'reason': 'Not inside a Git working tree'}
|
|
153
|
+
|
|
154
|
+
root = Path(top_out.strip())
|
|
155
|
+
_, branch_out, _ = run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=root)
|
|
156
|
+
branch = branch_out.strip() or 'HEAD'
|
|
157
|
+
|
|
158
|
+
_, remote_out, _ = run_cmd(['git', 'remote', 'get-url', 'origin'], cwd=root)
|
|
159
|
+
detected_repo = parse_repo_from_remote(remote_out)
|
|
160
|
+
|
|
161
|
+
_, name_out, _ = run_cmd(['git', 'config', 'user.name'], cwd=root)
|
|
162
|
+
display_name = name_out.strip()
|
|
163
|
+
|
|
164
|
+
author = (author_pattern or '').strip()
|
|
165
|
+
if not author:
|
|
166
|
+
_, email_out, _ = run_cmd(['git', 'config', 'user.email'], cwd=root)
|
|
167
|
+
author = email_out.strip()
|
|
168
|
+
if not author:
|
|
169
|
+
author = display_name
|
|
170
|
+
if not display_name and author:
|
|
171
|
+
display_name = author.split('@', 1)[0]
|
|
172
|
+
|
|
173
|
+
log_cmd = [
|
|
174
|
+
'git', 'log', '--branches', '--no-merges',
|
|
175
|
+
f'--since={since_dt.isoformat()}',
|
|
176
|
+
'--numstat',
|
|
177
|
+
'--format=__COMMIT__%x09%H%x09%s%x09%aI',
|
|
178
|
+
]
|
|
179
|
+
if author:
|
|
180
|
+
log_cmd.append(f'--author={author}')
|
|
181
|
+
|
|
182
|
+
log_code, log_out, _ = run_cmd(log_cmd, cwd=root)
|
|
183
|
+
commits = 0
|
|
184
|
+
insertions = 0
|
|
185
|
+
deletions = 0
|
|
186
|
+
touched_files = set()
|
|
187
|
+
seen_shas = set()
|
|
188
|
+
active_sha = None
|
|
189
|
+
|
|
190
|
+
if log_code == 0:
|
|
191
|
+
for line in log_out.splitlines():
|
|
192
|
+
if line.startswith('__COMMIT__\t'):
|
|
193
|
+
parts = line.split('\t', 3)
|
|
194
|
+
sha = parts[1] if len(parts) > 1 else ''
|
|
195
|
+
if sha and sha not in seen_shas:
|
|
196
|
+
seen_shas.add(sha)
|
|
197
|
+
commits += 1
|
|
198
|
+
active_sha = sha
|
|
199
|
+
else:
|
|
200
|
+
active_sha = None
|
|
201
|
+
continue
|
|
202
|
+
if active_sha is None or not line.strip():
|
|
203
|
+
continue
|
|
204
|
+
cols = line.split('\t', 2)
|
|
205
|
+
if len(cols) != 3:
|
|
206
|
+
continue
|
|
207
|
+
ins_s, del_s, path_s = cols
|
|
208
|
+
if ins_s.isdigit():
|
|
209
|
+
insertions += int(ins_s)
|
|
210
|
+
if del_s.isdigit():
|
|
211
|
+
deletions += int(del_s)
|
|
212
|
+
if path_s.strip():
|
|
213
|
+
touched_files.add(path_s.strip())
|
|
214
|
+
|
|
215
|
+
ahead_commits = 0
|
|
216
|
+
up_code, up_out, _ = run_cmd(['git', 'rev-list', '--count', '@{u}..HEAD'], cwd=root)
|
|
217
|
+
if up_code == 0 and up_out.strip().isdigit():
|
|
218
|
+
ahead_commits = int(up_out.strip())
|
|
219
|
+
elif branch != 'HEAD':
|
|
220
|
+
rem_code, rem_out, _ = run_cmd(
|
|
221
|
+
['git', 'rev-list', '--count', branch, '--not', '--remotes'], cwd=root
|
|
222
|
+
)
|
|
223
|
+
if rem_code == 0 and rem_out.strip().isdigit():
|
|
224
|
+
ahead_commits = int(rem_out.strip())
|
|
225
|
+
|
|
226
|
+
_, st_out, _ = run_cmd(['git', 'status', '--porcelain'], cwd=root)
|
|
227
|
+
working_changes = len([ln for ln in st_out.splitlines() if ln.strip()])
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
'available': True,
|
|
231
|
+
'repo': detected_repo,
|
|
232
|
+
'branch': branch,
|
|
233
|
+
'author': display_name or None,
|
|
234
|
+
'commits': commits,
|
|
235
|
+
'files_changed': len(touched_files),
|
|
236
|
+
'insertions': insertions,
|
|
237
|
+
'deletions': deletions,
|
|
238
|
+
'ahead_commits': ahead_commits,
|
|
239
|
+
'working_changes': working_changes,
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def gh_api_json(endpoint, method='GET', body=None):
|
|
244
|
+
cmd = ['gh', 'api']
|
|
245
|
+
stdin_text = None
|
|
246
|
+
if method != 'GET':
|
|
247
|
+
cmd.extend(['-X', method])
|
|
248
|
+
cmd.append(endpoint)
|
|
249
|
+
if body is not None:
|
|
250
|
+
cmd.extend(['--input', '-'])
|
|
251
|
+
stdin_text = json.dumps(body)
|
|
252
|
+
try:
|
|
253
|
+
proc = subprocess.run(
|
|
254
|
+
cmd,
|
|
255
|
+
input=stdin_text,
|
|
256
|
+
capture_output=True,
|
|
257
|
+
text=True,
|
|
258
|
+
encoding='utf-8',
|
|
259
|
+
check=False,
|
|
260
|
+
timeout=25,
|
|
261
|
+
)
|
|
262
|
+
except (OSError, subprocess.SubprocessError) as err:
|
|
263
|
+
raise RuntimeError(str(err))
|
|
264
|
+
if proc.returncode != 0:
|
|
265
|
+
raise RuntimeError(proc.stderr.strip() or f'gh api failed for {endpoint}')
|
|
266
|
+
return json.loads(proc.stdout) if proc.stdout.strip() else {}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def gh_graphql(query, variables=None):
|
|
270
|
+
payload = json.dumps({'query': query, 'variables': variables or {}})
|
|
271
|
+
try:
|
|
272
|
+
proc = subprocess.run(
|
|
273
|
+
['gh', 'api', 'graphql', '--input', '-'],
|
|
274
|
+
input=payload,
|
|
275
|
+
capture_output=True,
|
|
276
|
+
text=True,
|
|
277
|
+
encoding='utf-8',
|
|
278
|
+
check=False,
|
|
279
|
+
timeout=30,
|
|
280
|
+
)
|
|
281
|
+
except (OSError, subprocess.SubprocessError) as err:
|
|
282
|
+
raise RuntimeError(str(err))
|
|
283
|
+
if proc.returncode != 0:
|
|
284
|
+
raise RuntimeError(proc.stderr.strip() or 'gh api graphql failed')
|
|
285
|
+
data = json.loads(proc.stdout)
|
|
286
|
+
if data.get('errors'):
|
|
287
|
+
msg = '; '.join(e.get('message', 'GraphQL error') for e in data['errors'])
|
|
288
|
+
raise RuntimeError(msg)
|
|
289
|
+
return data.get('data') or {}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def search_items(query):
|
|
293
|
+
encoded = urllib.parse.quote(query, safe='')
|
|
294
|
+
data = gh_api_json(f'search/issues?q={encoded}&per_page=100')
|
|
295
|
+
items = data.get('items', []) if isinstance(data, dict) else []
|
|
296
|
+
return [it for it in items if isinstance(it, dict)]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def repo_from_api_item(item):
|
|
300
|
+
repo_url = item.get('repository_url') or ''
|
|
301
|
+
if '/repos/' in repo_url:
|
|
302
|
+
return repo_url.split('/repos/', 1)[1]
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def summarize_ci(repo_slug, head_sha):
|
|
307
|
+
if not repo_slug or not head_sha:
|
|
308
|
+
return 'unknown'
|
|
309
|
+
try:
|
|
310
|
+
data = gh_api_json(f'repos/{repo_slug}/commits/{head_sha}/check-runs?per_page=100')
|
|
311
|
+
except (RuntimeError, ValueError):
|
|
312
|
+
return 'unknown'
|
|
313
|
+
runs = data.get('check_runs', []) if isinstance(data, dict) else []
|
|
314
|
+
if not runs:
|
|
315
|
+
return 'none'
|
|
316
|
+
has_pending = False
|
|
317
|
+
for run in runs:
|
|
318
|
+
if not isinstance(run, dict):
|
|
319
|
+
continue
|
|
320
|
+
if run.get('status') != 'completed':
|
|
321
|
+
has_pending = True
|
|
322
|
+
continue
|
|
323
|
+
conclusion = run.get('conclusion')
|
|
324
|
+
if conclusion not in ('success', 'skipped', 'neutral'):
|
|
325
|
+
return 'failing'
|
|
326
|
+
return 'pending' if has_pending else 'success'
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def enrich_pr_item(item, fallback_repo=None):
|
|
330
|
+
repo_slug = repo_from_api_item(item) or fallback_repo
|
|
331
|
+
number = item.get('number')
|
|
332
|
+
pr_meta = item.get('pull_request') if isinstance(item.get('pull_request'), dict) else {}
|
|
333
|
+
merged_at = item.get('merged_at') or pr_meta.get('merged_at')
|
|
334
|
+
draft = bool(item.get('draft', False))
|
|
335
|
+
ci_status = 'unknown'
|
|
336
|
+
|
|
337
|
+
if repo_slug and number:
|
|
338
|
+
try:
|
|
339
|
+
detail = gh_api_json(f'repos/{repo_slug}/pulls/{number}')
|
|
340
|
+
merged_at = detail.get('merged_at') or merged_at
|
|
341
|
+
draft = bool(detail.get('draft', draft))
|
|
342
|
+
head = detail.get('head') if isinstance(detail.get('head'), dict) else {}
|
|
343
|
+
ci_status = summarize_ci(repo_slug, head.get('sha'))
|
|
344
|
+
except (RuntimeError, ValueError):
|
|
345
|
+
pass
|
|
346
|
+
|
|
347
|
+
return {
|
|
348
|
+
'repo': repo_slug,
|
|
349
|
+
'number': number,
|
|
350
|
+
'title': item.get('title', ''),
|
|
351
|
+
'state': item.get('state', 'open'),
|
|
352
|
+
'draft': draft,
|
|
353
|
+
'created_at': item.get('created_at'),
|
|
354
|
+
'updated_at': item.get('updated_at'),
|
|
355
|
+
'merged_at': merged_at,
|
|
356
|
+
'ci_status': ci_status,
|
|
357
|
+
'url': item.get('html_url'),
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _extract_linked_issues(body_text):
|
|
362
|
+
return {int(m) for m in CLOSES_ISSUE_RE.findall(body_text or '')}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _assignee_logins(item):
|
|
366
|
+
raw = item.get('assignees')
|
|
367
|
+
if not isinstance(raw, list):
|
|
368
|
+
return set()
|
|
369
|
+
return {a.get('login') for a in raw if isinstance(a, dict) and a.get('login')}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _collect_merged_prs(login, scope_filter, search_date, since_dt, repo):
|
|
373
|
+
raw_merged = search_items(f'is:pr author:{login} is:merged merged:>={search_date}{scope_filter}')
|
|
374
|
+
prs_merged = []
|
|
375
|
+
linked_issues = set()
|
|
376
|
+
for it in raw_merged:
|
|
377
|
+
pr_meta = it.get('pull_request') if isinstance(it.get('pull_request'), dict) else {}
|
|
378
|
+
merged_at = it.get('merged_at') or pr_meta.get('merged_at')
|
|
379
|
+
if not merged_at and repo:
|
|
380
|
+
merged_at = enrich_pr_item(it, repo).get('merged_at')
|
|
381
|
+
if not in_window(merged_at, since_dt):
|
|
382
|
+
continue
|
|
383
|
+
prs_merged.append({
|
|
384
|
+
'repo': repo_from_api_item(it) or repo,
|
|
385
|
+
'number': it.get('number'),
|
|
386
|
+
'title': it.get('title', ''),
|
|
387
|
+
'merged_at': merged_at,
|
|
388
|
+
'url': it.get('html_url'),
|
|
389
|
+
})
|
|
390
|
+
linked_issues.update(_extract_linked_issues(it.get('body')))
|
|
391
|
+
return prs_merged, linked_issues
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _collect_closed_issues(login, repo, all_repos, search_date, since_dt, linked_issues):
|
|
395
|
+
if all_repos or not repo:
|
|
396
|
+
raw_closed = search_items(f'is:issue involves:{login} is:closed closed:>={search_date}')
|
|
397
|
+
return [
|
|
398
|
+
{
|
|
399
|
+
'repo': repo_from_api_item(it),
|
|
400
|
+
'number': it.get('number'),
|
|
401
|
+
'title': it.get('title', ''),
|
|
402
|
+
'closed_at': it.get('closed_at'),
|
|
403
|
+
'url': it.get('html_url'),
|
|
404
|
+
}
|
|
405
|
+
for it in raw_closed
|
|
406
|
+
if in_window(it.get('closed_at'), since_dt)
|
|
407
|
+
]
|
|
408
|
+
|
|
409
|
+
since_utc = since_dt.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
410
|
+
closed_list = gh_api_json(f'repos/{repo}/issues?state=closed&since={since_utc}&per_page=100')
|
|
411
|
+
results = []
|
|
412
|
+
for it in closed_list:
|
|
413
|
+
if not isinstance(it, dict) or 'pull_request' in it:
|
|
414
|
+
continue
|
|
415
|
+
if not in_window(it.get('closed_at'), since_dt):
|
|
416
|
+
continue
|
|
417
|
+
closed_by = (it.get('closed_by') or {}).get('login') if isinstance(it.get('closed_by'), dict) else None
|
|
418
|
+
author_login = (it.get('user') or {}).get('login') if isinstance(it.get('user'), dict) else None
|
|
419
|
+
assignees = _assignee_logins(it)
|
|
420
|
+
if closed_by == login or author_login == login or login in assignees or it.get('number') in linked_issues:
|
|
421
|
+
results.append({
|
|
422
|
+
'repo': repo,
|
|
423
|
+
'number': it.get('number'),
|
|
424
|
+
'title': it.get('title', ''),
|
|
425
|
+
'closed_at': it.get('closed_at'),
|
|
426
|
+
'url': it.get('html_url'),
|
|
427
|
+
})
|
|
428
|
+
return results
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _collect_peer_review_count(login, scope_filter, search_date, since_dt):
|
|
432
|
+
raw_commented = search_items(f'is:pr commenter:{login} updated:>={search_date}{scope_filter}')
|
|
433
|
+
raw_reviewed = search_items(f'is:pr reviewed-by:{login} updated:>={search_date}{scope_filter}')
|
|
434
|
+
peer_prs = set()
|
|
435
|
+
for it in raw_commented + raw_reviewed:
|
|
436
|
+
if not in_window(it.get('updated_at'), since_dt):
|
|
437
|
+
continue
|
|
438
|
+
author_login = (it.get('user') or {}).get('login') if isinstance(it.get('user'), dict) else None
|
|
439
|
+
if author_login == login:
|
|
440
|
+
continue
|
|
441
|
+
key = it.get('html_url') or f'{repo_from_api_item(it)}#{it.get("number")}'
|
|
442
|
+
peer_prs.add(key)
|
|
443
|
+
return len(peer_prs)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def collect_github(repo, all_repos, since_dt, user_override=None):
|
|
447
|
+
auth_code, _, auth_err = run_cmd(['gh', 'auth', 'status'], timeout=15)
|
|
448
|
+
if auth_code != 0:
|
|
449
|
+
return {
|
|
450
|
+
'available': False,
|
|
451
|
+
'gap': auth_err.strip() or 'gh CLI not installed or not authenticated',
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
login = (user_override or '').strip()
|
|
455
|
+
if not login:
|
|
456
|
+
try:
|
|
457
|
+
user_data = gh_api_json('user')
|
|
458
|
+
login = (user_data.get('login') or '').strip()
|
|
459
|
+
except (RuntimeError, ValueError) as err:
|
|
460
|
+
return {'available': False, 'gap': f'Could not resolve GitHub user: {err}'}
|
|
461
|
+
if not login:
|
|
462
|
+
return {'available': False, 'gap': 'GitHub user login is empty'}
|
|
463
|
+
|
|
464
|
+
if not all_repos and not repo:
|
|
465
|
+
return {
|
|
466
|
+
'available': False,
|
|
467
|
+
'user': login,
|
|
468
|
+
'gap': 'No GitHub repository detected; pass --repo owner/repo or --all-repos',
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
scope_filter = '' if all_repos else f' repo:{repo}'
|
|
472
|
+
search_date = (since_dt.astimezone(timezone.utc) - timedelta(days=1)).strftime('%Y-%m-%d')
|
|
473
|
+
gaps = []
|
|
474
|
+
|
|
475
|
+
try:
|
|
476
|
+
raw_created = search_items(f'is:issue author:{login} created:>={search_date}{scope_filter}')
|
|
477
|
+
issues_created = [
|
|
478
|
+
{
|
|
479
|
+
'repo': repo_from_api_item(it) or repo,
|
|
480
|
+
'number': it.get('number'),
|
|
481
|
+
'title': it.get('title', ''),
|
|
482
|
+
'state': it.get('state', 'open'),
|
|
483
|
+
'created_at': it.get('created_at'),
|
|
484
|
+
'url': it.get('html_url'),
|
|
485
|
+
}
|
|
486
|
+
for it in raw_created
|
|
487
|
+
if in_window(it.get('created_at'), since_dt)
|
|
488
|
+
]
|
|
489
|
+
|
|
490
|
+
prs_merged, linked_issues = _collect_merged_prs(login, scope_filter, search_date, since_dt, repo)
|
|
491
|
+
issues_closed = _collect_closed_issues(login, repo, all_repos, search_date, since_dt, linked_issues)
|
|
492
|
+
|
|
493
|
+
raw_opened = search_items(f'is:pr author:{login} created:>={search_date}{scope_filter}')
|
|
494
|
+
opened_filtered = [it for it in raw_opened if in_window(it.get('created_at'), since_dt)]
|
|
495
|
+
prs_opened = [enrich_pr_item(it, repo) for it in opened_filtered[:20]]
|
|
496
|
+
if len(opened_filtered) > 20:
|
|
497
|
+
gaps.append(f'PR details capped at 20 of {len(opened_filtered)} opened PRs')
|
|
498
|
+
|
|
499
|
+
raw_open_upd = search_items(f'is:pr is:open author:{login} updated:>={search_date}{scope_filter}')
|
|
500
|
+
open_upd_filtered = [it for it in raw_open_upd if in_window(it.get('updated_at'), since_dt)]
|
|
501
|
+
prs_in_progress = [enrich_pr_item(it, repo) for it in open_upd_filtered[:20]]
|
|
502
|
+
|
|
503
|
+
reviews_count = _collect_peer_review_count(login, scope_filter, search_date, since_dt)
|
|
504
|
+
except (RuntimeError, ValueError) as err:
|
|
505
|
+
return {'available': False, 'user': login, 'gap': f'GitHub REST error: {err}'}
|
|
506
|
+
|
|
507
|
+
return {
|
|
508
|
+
'available': True,
|
|
509
|
+
'user': login,
|
|
510
|
+
'issues_created': issues_created,
|
|
511
|
+
'issues_closed': issues_closed,
|
|
512
|
+
'prs_opened': prs_opened,
|
|
513
|
+
'prs_merged': prs_merged,
|
|
514
|
+
'prs_in_progress': prs_in_progress,
|
|
515
|
+
'reviews_and_comments': reviews_count,
|
|
516
|
+
'gaps': gaps,
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _extract_board_item(node):
|
|
521
|
+
content = node.get('content') if isinstance(node.get('content'), dict) else {}
|
|
522
|
+
repo_info = content.get('repository') if isinstance(content.get('repository'), dict) else {}
|
|
523
|
+
repo = repo_info.get('nameWithOwner')
|
|
524
|
+
number = content.get('number')
|
|
525
|
+
fields = {}
|
|
526
|
+
for fv in (node.get('fieldValues') or {}).get('nodes') or []:
|
|
527
|
+
if not isinstance(fv, dict):
|
|
528
|
+
continue
|
|
529
|
+
fld = fv.get('field') if isinstance(fv.get('field'), dict) else {}
|
|
530
|
+
fname = fld.get('name')
|
|
531
|
+
if fname and fv.get('name') is not None:
|
|
532
|
+
fields[fname] = fv.get('name')
|
|
533
|
+
|
|
534
|
+
assignees = [
|
|
535
|
+
a.get('login')
|
|
536
|
+
for a in ((content.get('assignees') or {}).get('nodes') or [])
|
|
537
|
+
if isinstance(a, dict) and a.get('login')
|
|
538
|
+
]
|
|
539
|
+
labels = [
|
|
540
|
+
l.get('name')
|
|
541
|
+
for l in ((content.get('labels') or {}).get('nodes') or [])
|
|
542
|
+
if isinstance(l, dict) and l.get('name')
|
|
543
|
+
]
|
|
544
|
+
return {
|
|
545
|
+
'id': node.get('id'),
|
|
546
|
+
'repo': repo,
|
|
547
|
+
'number': number,
|
|
548
|
+
'type': 'PullRequest' if 'merged' in content else ('Issue' if number else 'DraftIssue'),
|
|
549
|
+
'title': content.get('title', ''),
|
|
550
|
+
'state': content.get('state'),
|
|
551
|
+
'merged': bool(content.get('merged', False)),
|
|
552
|
+
'url': content.get('url'),
|
|
553
|
+
'status': fields.get('Status') or 'Sin estado',
|
|
554
|
+
'priority': fields.get('Priority'),
|
|
555
|
+
'fields': fields,
|
|
556
|
+
'assignees': assignees,
|
|
557
|
+
'labels': labels,
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def collect_project_board(project_ref):
|
|
562
|
+
auth_code, _, auth_err = run_cmd(['gh', 'auth', 'status'], timeout=15)
|
|
563
|
+
if auth_code != 0:
|
|
564
|
+
return {
|
|
565
|
+
'available': False,
|
|
566
|
+
'gap': auth_err.strip() or 'gh CLI not installed or not authenticated',
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
owner_field = project_ref['owner_type']
|
|
570
|
+
query = f'''query($owner: String!, $number: Int!, $cursor: String) {{
|
|
571
|
+
{owner_field}(login: $owner) {{
|
|
572
|
+
projectV2(number: $number) {{
|
|
573
|
+
id
|
|
574
|
+
title
|
|
575
|
+
url
|
|
576
|
+
views(first: 20) {{
|
|
577
|
+
nodes {{ id number name layout filter }}
|
|
578
|
+
}}
|
|
579
|
+
fields(first: 30) {{
|
|
580
|
+
nodes {{
|
|
581
|
+
... on ProjectV2FieldCommon {{ id name dataType }}
|
|
582
|
+
... on ProjectV2SingleSelectField {{
|
|
583
|
+
id name dataType
|
|
584
|
+
options {{ id name color description }}
|
|
585
|
+
}}
|
|
586
|
+
}}
|
|
587
|
+
}}
|
|
588
|
+
items(first: 100, after: $cursor) {{
|
|
589
|
+
pageInfo {{ hasNextPage endCursor }}
|
|
590
|
+
nodes {{
|
|
591
|
+
id
|
|
592
|
+
fieldValues(first: 20) {{
|
|
593
|
+
nodes {{
|
|
594
|
+
... on ProjectV2ItemFieldSingleSelectValue {{
|
|
595
|
+
name
|
|
596
|
+
field {{ ... on ProjectV2FieldCommon {{ name }} }}
|
|
597
|
+
}}
|
|
598
|
+
}}
|
|
599
|
+
}}
|
|
600
|
+
content {{
|
|
601
|
+
... on Issue {{
|
|
602
|
+
number title state url
|
|
603
|
+
repository {{ nameWithOwner }}
|
|
604
|
+
assignees(first: 10) {{ nodes {{ login }} }}
|
|
605
|
+
labels(first: 10) {{ nodes {{ name }} }}
|
|
606
|
+
}}
|
|
607
|
+
... on PullRequest {{
|
|
608
|
+
number title state merged url
|
|
609
|
+
repository {{ nameWithOwner }}
|
|
610
|
+
assignees(first: 10) {{ nodes {{ login }} }}
|
|
611
|
+
labels(first: 10) {{ nodes {{ name }} }}
|
|
612
|
+
}}
|
|
613
|
+
... on DraftIssue {{ title }}
|
|
614
|
+
}}
|
|
615
|
+
}}
|
|
616
|
+
}}
|
|
617
|
+
}}
|
|
618
|
+
}}
|
|
619
|
+
}}'''
|
|
620
|
+
|
|
621
|
+
items = []
|
|
622
|
+
cursor = None
|
|
623
|
+
project_id = None
|
|
624
|
+
title = None
|
|
625
|
+
url = None
|
|
626
|
+
views = []
|
|
627
|
+
fields = []
|
|
628
|
+
try:
|
|
629
|
+
while True:
|
|
630
|
+
data = gh_graphql(
|
|
631
|
+
query,
|
|
632
|
+
{
|
|
633
|
+
'owner': project_ref['owner'],
|
|
634
|
+
'number': project_ref['number'],
|
|
635
|
+
'cursor': cursor,
|
|
636
|
+
},
|
|
637
|
+
)
|
|
638
|
+
owner_obj = data.get(owner_field) or {}
|
|
639
|
+
proj = owner_obj.get('projectV2')
|
|
640
|
+
if not proj:
|
|
641
|
+
return {
|
|
642
|
+
'available': False,
|
|
643
|
+
'gap': f'Project {project_ref["owner"]}/{project_ref["number"]} not found',
|
|
644
|
+
}
|
|
645
|
+
project_id = proj.get('id')
|
|
646
|
+
title = proj.get('title')
|
|
647
|
+
url = proj.get('url')
|
|
648
|
+
views = (proj.get('views') or {}).get('nodes') or []
|
|
649
|
+
fields = (proj.get('fields') or {}).get('nodes') or []
|
|
650
|
+
page = proj.get('items') or {}
|
|
651
|
+
for node in page.get('nodes') or []:
|
|
652
|
+
if isinstance(node, dict):
|
|
653
|
+
items.append(_extract_board_item(node))
|
|
654
|
+
page_info = page.get('pageInfo') or {}
|
|
655
|
+
if not page_info.get('hasNextPage') or not page_info.get('endCursor'):
|
|
656
|
+
break
|
|
657
|
+
cursor = page_info['endCursor']
|
|
658
|
+
except (RuntimeError, ValueError) as err:
|
|
659
|
+
return {'available': False, 'gap': f'GitHub Project error: {err}'}
|
|
660
|
+
|
|
661
|
+
target_view = None
|
|
662
|
+
view_name = None
|
|
663
|
+
if project_ref.get('view'):
|
|
664
|
+
for v in views:
|
|
665
|
+
if v.get('number') == project_ref['view']:
|
|
666
|
+
target_view = v
|
|
667
|
+
view_name = v.get('name')
|
|
668
|
+
break
|
|
669
|
+
if url:
|
|
670
|
+
url = f'{url.rstrip("/")}/views/{project_ref["view"]}'
|
|
671
|
+
|
|
672
|
+
return {
|
|
673
|
+
'available': True,
|
|
674
|
+
'project_id': project_id,
|
|
675
|
+
'title': title,
|
|
676
|
+
'url': url,
|
|
677
|
+
'view': project_ref.get('view'),
|
|
678
|
+
'view_name': view_name,
|
|
679
|
+
'target_view': target_view,
|
|
680
|
+
'fields': fields,
|
|
681
|
+
'items': items,
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def collect_team_members(org, users_arg=None):
|
|
686
|
+
if users_arg:
|
|
687
|
+
return [u.strip() for u in users_arg.split(',') if u.strip()]
|
|
688
|
+
if not org:
|
|
689
|
+
return []
|
|
690
|
+
try:
|
|
691
|
+
members = gh_api_json(f'orgs/{org}/members?per_page=100')
|
|
692
|
+
except (RuntimeError, ValueError):
|
|
693
|
+
return []
|
|
694
|
+
if not isinstance(members, list):
|
|
695
|
+
return []
|
|
696
|
+
return [m.get('login') for m in members if isinstance(m, dict) and m.get('login')]
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def infer_board_status(item, status_options):
|
|
700
|
+
by_name = {
|
|
701
|
+
opt['name'].strip().lower(): opt
|
|
702
|
+
for opt in (status_options or [])
|
|
703
|
+
if isinstance(opt, dict) and opt.get('name') and opt.get('id')
|
|
704
|
+
}
|
|
705
|
+
state = (item.get('state') or item.get('github_state') or '').strip().lower()
|
|
706
|
+
is_pr = bool(
|
|
707
|
+
item.get('is_pr')
|
|
708
|
+
or item.get('merged_at')
|
|
709
|
+
or item.get('type') == 'PullRequest'
|
|
710
|
+
or '/pull/' in (item.get('url') or '')
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
if state in ('closed', 'merged') or item.get('merged'):
|
|
714
|
+
candidates = ('done',)
|
|
715
|
+
elif is_pr:
|
|
716
|
+
candidates = ('in review', 'in progress', 'ready')
|
|
717
|
+
else:
|
|
718
|
+
candidates = ('ready', 'backlog', 'in progress')
|
|
719
|
+
|
|
720
|
+
for name in candidates:
|
|
721
|
+
if name in by_name:
|
|
722
|
+
return by_name[name]
|
|
723
|
+
return None
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def infer_repo_label(title, existing_labels):
|
|
727
|
+
available = {str(lbl).strip().lower(): lbl for lbl in (existing_labels or [])}
|
|
728
|
+
low = (title or '').strip().lower()
|
|
729
|
+
if low.startswith('fix') and 'bug' in available:
|
|
730
|
+
return available['bug']
|
|
731
|
+
if low.startswith('feat') and 'enhancement' in available:
|
|
732
|
+
return available['enhancement']
|
|
733
|
+
if low.startswith('docs') and 'documentation' in available:
|
|
734
|
+
return available['documentation']
|
|
735
|
+
return None
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def _build_field_color_update(fld):
|
|
739
|
+
if not isinstance(fld, dict) or fld.get('dataType') != 'SINGLE_SELECT':
|
|
740
|
+
return None
|
|
741
|
+
options = [o for o in (fld.get('options') or []) if isinstance(o, dict) and o.get('id')]
|
|
742
|
+
if not options:
|
|
743
|
+
return None
|
|
744
|
+
|
|
745
|
+
fname = (fld.get('name') or '').strip().lower()
|
|
746
|
+
if fname == 'status':
|
|
747
|
+
new_opts = [
|
|
748
|
+
{
|
|
749
|
+
'id': opt['id'],
|
|
750
|
+
'name': opt['name'],
|
|
751
|
+
'color': STANDARD_STATUS_COLORS.get(opt['name'].strip().lower()) or opt.get('color') or 'GRAY',
|
|
752
|
+
'description': opt.get('description') or '',
|
|
753
|
+
}
|
|
754
|
+
for opt in options
|
|
755
|
+
]
|
|
756
|
+
if any(n['color'] != o.get('color') for n, o in zip(new_opts, options)):
|
|
757
|
+
return {'field_id': fld['id'], 'field_name': fld.get('name'), 'options': new_opts}
|
|
758
|
+
return None
|
|
759
|
+
|
|
760
|
+
if all((o.get('color') or 'GRAY') == 'GRAY' for o in options):
|
|
761
|
+
new_opts = [
|
|
762
|
+
{
|
|
763
|
+
'id': opt['id'],
|
|
764
|
+
'name': opt['name'],
|
|
765
|
+
'color': PALETTE_COLORS[idx % len(PALETTE_COLORS)],
|
|
766
|
+
'description': opt.get('description') or '',
|
|
767
|
+
}
|
|
768
|
+
for idx, opt in enumerate(options)
|
|
769
|
+
]
|
|
770
|
+
return {'field_id': fld['id'], 'field_name': fld.get('name'), 'options': new_opts}
|
|
771
|
+
return None
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _build_color_updates(fields):
|
|
775
|
+
updates = []
|
|
776
|
+
for fld in fields or []:
|
|
777
|
+
upd = _build_field_color_update(fld)
|
|
778
|
+
if upd:
|
|
779
|
+
updates.append(upd)
|
|
780
|
+
return updates
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def _build_board_view_fields(fields, target_view):
|
|
784
|
+
if not isinstance(target_view, dict) or target_view.get('layout') != 'BOARD_LAYOUT':
|
|
785
|
+
return None
|
|
786
|
+
by_name = {
|
|
787
|
+
(f.get('name') or '').strip().lower(): f.get('id')
|
|
788
|
+
for f in (fields or [])
|
|
789
|
+
if isinstance(f, dict) and f.get('id') and f.get('name')
|
|
790
|
+
}
|
|
791
|
+
desired = []
|
|
792
|
+
for key in ('title', 'assignees', 'labels', 'linked pull requests', 'priority'):
|
|
793
|
+
if key in by_name:
|
|
794
|
+
desired.append(by_name[key])
|
|
795
|
+
for fld in fields or []:
|
|
796
|
+
if not isinstance(fld, dict):
|
|
797
|
+
continue
|
|
798
|
+
name = (fld.get('name') or '').strip().lower()
|
|
799
|
+
if fld.get('dataType') == 'SINGLE_SELECT' and name not in ('status', 'priority', 'size'):
|
|
800
|
+
if fld.get('id') and fld['id'] not in desired:
|
|
801
|
+
desired.append(fld['id'])
|
|
802
|
+
return {'view_id': target_view['id'], 'visible_field_ids': desired} if desired else None
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def plan_board_sync(board_summary, project_meta, fix_colors=False):
|
|
806
|
+
fields = (project_meta or {}).get('fields') or []
|
|
807
|
+
status_field = next(
|
|
808
|
+
(f for f in fields if isinstance(f, dict) and (f.get('name') or '').strip().lower() == 'status'),
|
|
809
|
+
None,
|
|
810
|
+
)
|
|
811
|
+
status_options = (status_field or {}).get('options') or []
|
|
812
|
+
status_field_id = (status_field or {}).get('id')
|
|
813
|
+
|
|
814
|
+
adds = []
|
|
815
|
+
for miss in (board_summary or {}).get('missing_from_board') or []:
|
|
816
|
+
opt = infer_board_status(miss, status_options)
|
|
817
|
+
adds.append({
|
|
818
|
+
'repo': miss.get('repo'),
|
|
819
|
+
'number': miss.get('number'),
|
|
820
|
+
'title': miss.get('title', ''),
|
|
821
|
+
'state': miss.get('state', ''),
|
|
822
|
+
'is_pr': bool(miss.get('is_pr')),
|
|
823
|
+
'url': miss.get('url'),
|
|
824
|
+
'target_status': opt['name'] if opt else None,
|
|
825
|
+
'status_option_id': opt['id'] if opt else None,
|
|
826
|
+
})
|
|
827
|
+
|
|
828
|
+
moves = []
|
|
829
|
+
for mm in (board_summary or {}).get('status_mismatches') or []:
|
|
830
|
+
if mm.get('github_state') not in ('closed', 'merged'):
|
|
831
|
+
continue
|
|
832
|
+
opt = infer_board_status({'state': mm.get('github_state'), 'url': mm.get('url')}, status_options)
|
|
833
|
+
if not opt or opt['name'] == mm.get('board_status'):
|
|
834
|
+
continue
|
|
835
|
+
moves.append({
|
|
836
|
+
'item_id': mm.get('item_id'),
|
|
837
|
+
'repo': mm.get('repo'),
|
|
838
|
+
'number': mm.get('number'),
|
|
839
|
+
'title': mm.get('title', ''),
|
|
840
|
+
'from_status': mm.get('board_status'),
|
|
841
|
+
'target_status': opt['name'],
|
|
842
|
+
'status_option_id': opt['id'],
|
|
843
|
+
'url': mm.get('url'),
|
|
844
|
+
})
|
|
845
|
+
|
|
846
|
+
color_updates = _build_color_updates(fields) if fix_colors else []
|
|
847
|
+
view_update = _build_board_view_fields(fields, (project_meta or {}).get('target_view')) if fix_colors else None
|
|
848
|
+
|
|
849
|
+
return {
|
|
850
|
+
'project_id': (project_meta or {}).get('project_id'),
|
|
851
|
+
'status_field_id': status_field_id,
|
|
852
|
+
'adds': adds,
|
|
853
|
+
'moves': moves,
|
|
854
|
+
'color_updates': color_updates,
|
|
855
|
+
'view_update': view_update,
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def _resolve_content_node_id(repo_slug, number):
|
|
860
|
+
if not repo_slug or '/' not in repo_slug or number is None:
|
|
861
|
+
return None
|
|
862
|
+
owner, name = repo_slug.split('/', 1)
|
|
863
|
+
q = '''query($owner: String!, $name: String!, $number: Int!) {
|
|
864
|
+
repository(owner: $owner, name: $name) {
|
|
865
|
+
issueOrPullRequest(number: $number) {
|
|
866
|
+
... on Issue { id }
|
|
867
|
+
... on PullRequest { id }
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}'''
|
|
871
|
+
data = gh_graphql(q, {'owner': owner, 'name': name, 'number': int(number)})
|
|
872
|
+
node = ((data.get('repository') or {}).get('issueOrPullRequest') or {})
|
|
873
|
+
return node.get('id')
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def apply_board_sync(plan, dry_run=False, apply_labels=False):
|
|
877
|
+
if dry_run:
|
|
878
|
+
return {
|
|
879
|
+
'dry_run': True,
|
|
880
|
+
'planned_adds': len(plan['adds']),
|
|
881
|
+
'planned_moves': len(plan['moves']),
|
|
882
|
+
'planned_color_updates': len(plan['color_updates']),
|
|
883
|
+
'planned_view_update': bool(plan['view_update']),
|
|
884
|
+
'adds': plan['adds'],
|
|
885
|
+
'moves': plan['moves'],
|
|
886
|
+
'color_updates': [c['field_name'] for c in plan['color_updates']],
|
|
887
|
+
'errors': [],
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
project_id = plan.get('project_id')
|
|
891
|
+
status_field_id = plan.get('status_field_id')
|
|
892
|
+
if not project_id:
|
|
893
|
+
return {'dry_run': False, 'errors': ['Missing project_id for board sync']}
|
|
894
|
+
|
|
895
|
+
m_add = '''mutation($p: ID!, $cid: ID!) {
|
|
896
|
+
addProjectV2ItemById(input: {projectId: $p, contentId: $cid}) { item { id } }
|
|
897
|
+
}'''
|
|
898
|
+
m_set = '''mutation($p: ID!, $i: ID!, $f: ID!, $v: String!) {
|
|
899
|
+
updateProjectV2ItemFieldValue(input: {projectId: $p, itemId: $i, fieldId: $f, value: {singleSelectOptionId: $v}}) {
|
|
900
|
+
projectV2Item { id }
|
|
901
|
+
}
|
|
902
|
+
}'''
|
|
903
|
+
m_fld = '''mutation($fieldId: ID!, $opts: [ProjectV2SingleSelectFieldOptionInput!]!) {
|
|
904
|
+
updateProjectV2Field(input: {fieldId: $fieldId, singleSelectOptions: $opts}) {
|
|
905
|
+
projectV2Field { ... on ProjectV2SingleSelectField { id } }
|
|
906
|
+
}
|
|
907
|
+
}'''
|
|
908
|
+
m_view = '''mutation($viewId: ID!, $fields: [ID!]!) {
|
|
909
|
+
updateProjectV2View(input: {viewId: $viewId, configuration: {visibleFieldIds: $fields}}) {
|
|
910
|
+
projectV2View { id }
|
|
911
|
+
}
|
|
912
|
+
}'''
|
|
913
|
+
|
|
914
|
+
added = []
|
|
915
|
+
moved = []
|
|
916
|
+
colors_updated = []
|
|
917
|
+
labels_added = []
|
|
918
|
+
view_updated = False
|
|
919
|
+
errors = []
|
|
920
|
+
|
|
921
|
+
for cu in plan.get('color_updates') or []:
|
|
922
|
+
try:
|
|
923
|
+
gh_graphql(m_fld, {'fieldId': cu['field_id'], 'opts': cu['options']})
|
|
924
|
+
colors_updated.append(cu['field_name'])
|
|
925
|
+
except (RuntimeError, ValueError) as err:
|
|
926
|
+
errors.append(f'color {cu["field_name"]}: {err}')
|
|
927
|
+
|
|
928
|
+
vu = plan.get('view_update')
|
|
929
|
+
if vu:
|
|
930
|
+
try:
|
|
931
|
+
gh_graphql(m_view, {'viewId': vu['view_id'], 'fields': vu['visible_field_ids']})
|
|
932
|
+
view_updated = True
|
|
933
|
+
except (RuntimeError, ValueError) as err:
|
|
934
|
+
errors.append(f'view: {err}')
|
|
935
|
+
|
|
936
|
+
repo_labels_cache = {}
|
|
937
|
+
for item in plan.get('adds') or []:
|
|
938
|
+
try:
|
|
939
|
+
cid = _resolve_content_node_id(item['repo'], item['number'])
|
|
940
|
+
if not cid:
|
|
941
|
+
errors.append(f'node_id not found for {item["repo"]}#{item["number"]}')
|
|
942
|
+
continue
|
|
943
|
+
res = gh_graphql(m_add, {'p': project_id, 'cid': cid})
|
|
944
|
+
new_id = ((res.get('addProjectV2ItemById') or {}).get('item') or {}).get('id')
|
|
945
|
+
if new_id and status_field_id and item.get('status_option_id'):
|
|
946
|
+
gh_graphql(m_set, {
|
|
947
|
+
'p': project_id,
|
|
948
|
+
'i': new_id,
|
|
949
|
+
'f': status_field_id,
|
|
950
|
+
'v': item['status_option_id'],
|
|
951
|
+
})
|
|
952
|
+
added.append(f'{item["repo"]}#{item["number"]} -> {item.get("target_status")}')
|
|
953
|
+
|
|
954
|
+
if apply_labels and item.get('repo') and item.get('number') is not None:
|
|
955
|
+
repo_slug = item['repo']
|
|
956
|
+
if repo_slug not in repo_labels_cache:
|
|
957
|
+
raw_lbls = gh_api_json(f'repos/{repo_slug}/labels?per_page=100')
|
|
958
|
+
repo_labels_cache[repo_slug] = [
|
|
959
|
+
l.get('name') for l in (raw_lbls if isinstance(raw_lbls, list) else []) if l.get('name')
|
|
960
|
+
]
|
|
961
|
+
lbl = infer_repo_label(item.get('title'), repo_labels_cache[repo_slug])
|
|
962
|
+
if lbl:
|
|
963
|
+
gh_api_json(
|
|
964
|
+
f'repos/{repo_slug}/issues/{item["number"]}/labels',
|
|
965
|
+
method='POST',
|
|
966
|
+
body={'labels': [lbl]},
|
|
967
|
+
)
|
|
968
|
+
labels_added.append(f'{repo_slug}#{item["number"]}:{lbl}')
|
|
969
|
+
except (RuntimeError, ValueError) as err:
|
|
970
|
+
errors.append(f'add {item["repo"]}#{item["number"]}: {err}')
|
|
971
|
+
|
|
972
|
+
for mv in plan.get('moves') or []:
|
|
973
|
+
if not mv.get('item_id') or not status_field_id or not mv.get('status_option_id'):
|
|
974
|
+
continue
|
|
975
|
+
try:
|
|
976
|
+
gh_graphql(m_set, {
|
|
977
|
+
'p': project_id,
|
|
978
|
+
'i': mv['item_id'],
|
|
979
|
+
'f': status_field_id,
|
|
980
|
+
'v': mv['status_option_id'],
|
|
981
|
+
})
|
|
982
|
+
moved.append(f'{mv["repo"]}#{mv["number"]}: {mv["from_status"]} -> {mv["target_status"]}')
|
|
983
|
+
except (RuntimeError, ValueError) as err:
|
|
984
|
+
errors.append(f'move {mv["repo"]}#{mv["number"]}: {err}')
|
|
985
|
+
|
|
986
|
+
return {
|
|
987
|
+
'dry_run': False,
|
|
988
|
+
'added': added,
|
|
989
|
+
'moved': moved,
|
|
990
|
+
'colors_updated': colors_updated,
|
|
991
|
+
'view_updated': view_updated,
|
|
992
|
+
'labels_added': labels_added,
|
|
993
|
+
'errors': errors,
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def _ratio_entry(numerator, denominator, zero_denom_label=None):
|
|
998
|
+
if numerator is None or denominator is None:
|
|
999
|
+
return {'numerator': numerator, 'denominator': denominator, 'pct': None, 'status': 'gap', 'display': 'N/A'}
|
|
1000
|
+
if denominator == 0:
|
|
1001
|
+
if numerator > 0 and zero_denom_label:
|
|
1002
|
+
return {'numerator': numerator, 'denominator': 0, 'pct': None, 'status': 'green', 'display': zero_denom_label}
|
|
1003
|
+
return {'numerator': numerator, 'denominator': 0, 'pct': None, 'status': 'na', 'display': 'N/A'}
|
|
1004
|
+
pct = round((numerator / denominator) * 100)
|
|
1005
|
+
status = 'green' if pct >= 70 else 'yellow' if pct >= 40 else 'red'
|
|
1006
|
+
return {
|
|
1007
|
+
'numerator': numerator,
|
|
1008
|
+
'denominator': denominator,
|
|
1009
|
+
'pct': pct,
|
|
1010
|
+
'status': status,
|
|
1011
|
+
'display': f'{numerator}/{denominator} ({pct}%)',
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def summarize_project_board(project_data, activity_items=None, default_repo=None):
|
|
1016
|
+
if not isinstance(project_data, dict) or not project_data.get('available'):
|
|
1017
|
+
return {
|
|
1018
|
+
'available': False,
|
|
1019
|
+
'gap': (project_data or {}).get('gap') if isinstance(project_data, dict) else 'Project unavailable',
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
items = [it for it in (project_data.get('items') or []) if isinstance(it, dict)]
|
|
1023
|
+
status_counts = {}
|
|
1024
|
+
by_assignee = {}
|
|
1025
|
+
board_keys = set()
|
|
1026
|
+
status_mismatches = []
|
|
1027
|
+
|
|
1028
|
+
for it in items:
|
|
1029
|
+
status = it.get('status') or 'Sin estado'
|
|
1030
|
+
status_counts[status] = status_counts.get(status, 0) + 1
|
|
1031
|
+
|
|
1032
|
+
assignees = it.get('assignees') or ['unassigned']
|
|
1033
|
+
for login in assignees:
|
|
1034
|
+
by_assignee.setdefault(login, {})
|
|
1035
|
+
by_assignee[login][status] = by_assignee[login].get(status, 0) + 1
|
|
1036
|
+
|
|
1037
|
+
repo = it.get('repo')
|
|
1038
|
+
num = it.get('number')
|
|
1039
|
+
if repo and num is not None:
|
|
1040
|
+
board_keys.add((repo, num))
|
|
1041
|
+
|
|
1042
|
+
gh_state = (it.get('state') or '').upper()
|
|
1043
|
+
if gh_state in ('CLOSED', 'MERGED') and status != 'Done':
|
|
1044
|
+
status_mismatches.append({
|
|
1045
|
+
'item_id': it.get('id'),
|
|
1046
|
+
'repo': repo,
|
|
1047
|
+
'number': num,
|
|
1048
|
+
'title': it.get('title', ''),
|
|
1049
|
+
'github_state': gh_state.lower(),
|
|
1050
|
+
'board_status': status,
|
|
1051
|
+
'url': it.get('url'),
|
|
1052
|
+
})
|
|
1053
|
+
elif gh_state == 'OPEN' and status == 'Done':
|
|
1054
|
+
status_mismatches.append({
|
|
1055
|
+
'item_id': it.get('id'),
|
|
1056
|
+
'repo': repo,
|
|
1057
|
+
'number': num,
|
|
1058
|
+
'title': it.get('title', ''),
|
|
1059
|
+
'github_state': 'open',
|
|
1060
|
+
'board_status': status,
|
|
1061
|
+
'url': it.get('url'),
|
|
1062
|
+
})
|
|
1063
|
+
|
|
1064
|
+
missing_from_board = []
|
|
1065
|
+
seen_missing = set()
|
|
1066
|
+
for act in activity_items or []:
|
|
1067
|
+
if not isinstance(act, dict):
|
|
1068
|
+
continue
|
|
1069
|
+
repo = act.get('repo') or default_repo
|
|
1070
|
+
num = act.get('number')
|
|
1071
|
+
if not repo or num is None:
|
|
1072
|
+
continue
|
|
1073
|
+
key = (repo, num)
|
|
1074
|
+
if key in board_keys or key in seen_missing:
|
|
1075
|
+
continue
|
|
1076
|
+
seen_missing.add(key)
|
|
1077
|
+
missing_from_board.append({
|
|
1078
|
+
'repo': repo,
|
|
1079
|
+
'number': num,
|
|
1080
|
+
'title': act.get('title', ''),
|
|
1081
|
+
'state': act.get('state') or ('closed' if act.get('closed_at') else ''),
|
|
1082
|
+
'is_pr': bool(act.get('is_pr') or act.get('merged_at') or '/pull/' in (act.get('url') or '')),
|
|
1083
|
+
'merged_at': act.get('merged_at'),
|
|
1084
|
+
'url': act.get('url'),
|
|
1085
|
+
})
|
|
1086
|
+
|
|
1087
|
+
return {
|
|
1088
|
+
'available': True,
|
|
1089
|
+
'title': project_data.get('title'),
|
|
1090
|
+
'url': project_data.get('url'),
|
|
1091
|
+
'view': project_data.get('view'),
|
|
1092
|
+
'view_name': project_data.get('view_name'),
|
|
1093
|
+
'total_items': len(items),
|
|
1094
|
+
'status_counts': status_counts,
|
|
1095
|
+
'by_assignee': by_assignee,
|
|
1096
|
+
'missing_from_board': missing_from_board,
|
|
1097
|
+
'status_mismatches': status_mismatches,
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _collect_team_recaps(members, target_repo, all_repos, since_dt, cached_gh=None):
|
|
1102
|
+
member_reports = []
|
|
1103
|
+
combined_items = []
|
|
1104
|
+
cached_user = cached_gh.get('user') if isinstance(cached_gh, dict) and cached_gh.get('available') else None
|
|
1105
|
+
for login in members:
|
|
1106
|
+
gh = cached_gh if (cached_user and login == cached_user) else collect_github(
|
|
1107
|
+
target_repo, all_repos, since_dt, user_override=login
|
|
1108
|
+
)
|
|
1109
|
+
if not gh.get('available'):
|
|
1110
|
+
member_reports.append({
|
|
1111
|
+
'user': login,
|
|
1112
|
+
'available': False,
|
|
1113
|
+
'gap': gh.get('gap'),
|
|
1114
|
+
})
|
|
1115
|
+
continue
|
|
1116
|
+
member_reports.append({
|
|
1117
|
+
'user': login,
|
|
1118
|
+
'available': True,
|
|
1119
|
+
'issues_created': len(gh.get('issues_created') or []),
|
|
1120
|
+
'issues_closed': len(gh.get('issues_closed') or []),
|
|
1121
|
+
'prs_opened': len(gh.get('prs_opened') or []),
|
|
1122
|
+
'prs_merged': len(gh.get('prs_merged') or []),
|
|
1123
|
+
'prs_open_updated': len(gh.get('prs_in_progress') or []),
|
|
1124
|
+
'reviews_and_comments': int(gh.get('reviews_and_comments') or 0),
|
|
1125
|
+
'gaps': gh.get('gaps') or [],
|
|
1126
|
+
})
|
|
1127
|
+
combined_items.extend(gh.get('issues_created') or [])
|
|
1128
|
+
combined_items.extend(
|
|
1129
|
+
{**it, 'state': it.get('state') or 'closed'} for it in (gh.get('issues_closed') or [])
|
|
1130
|
+
)
|
|
1131
|
+
combined_items.extend({**pr, 'is_pr': True} for pr in (gh.get('prs_in_progress') or []))
|
|
1132
|
+
for pr in gh.get('prs_opened') or []:
|
|
1133
|
+
if pr.get('state') == 'open':
|
|
1134
|
+
combined_items.append({**pr, 'is_pr': True})
|
|
1135
|
+
return member_reports, combined_items
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
def compute_recap(payload):
|
|
1139
|
+
since_dt = parse_since(payload.get('since')) if payload.get('since') else parse_since()
|
|
1140
|
+
gh_ok = bool(payload.get('github_available'))
|
|
1141
|
+
local = payload.get('local_git') if isinstance(payload.get('local_git'), dict) else {'available': False}
|
|
1142
|
+
gaps = list(payload.get('gaps') or [])
|
|
1143
|
+
if not gh_ok and payload.get('github_gap'):
|
|
1144
|
+
gaps.append(str(payload['github_gap']))
|
|
1145
|
+
|
|
1146
|
+
if gh_ok:
|
|
1147
|
+
issues_created = [
|
|
1148
|
+
it for it in (payload.get('issues_created') or [])
|
|
1149
|
+
if isinstance(it, dict) and in_window(it.get('created_at'), since_dt)
|
|
1150
|
+
]
|
|
1151
|
+
issues_closed = [
|
|
1152
|
+
it for it in (payload.get('issues_closed') or [])
|
|
1153
|
+
if isinstance(it, dict) and in_window(it.get('closed_at'), since_dt)
|
|
1154
|
+
]
|
|
1155
|
+
prs_opened = [
|
|
1156
|
+
it for it in (payload.get('prs_opened') or [])
|
|
1157
|
+
if isinstance(it, dict) and in_window(it.get('created_at'), since_dt)
|
|
1158
|
+
]
|
|
1159
|
+
prs_merged = [
|
|
1160
|
+
it for it in (payload.get('prs_merged') or [])
|
|
1161
|
+
if isinstance(it, dict) and in_window(it.get('merged_at'), since_dt)
|
|
1162
|
+
]
|
|
1163
|
+
prs_in_progress = [
|
|
1164
|
+
it for it in (payload.get('prs_in_progress') or [])
|
|
1165
|
+
if isinstance(it, dict) and in_window(it.get('updated_at'), since_dt)
|
|
1166
|
+
]
|
|
1167
|
+
reviews_count = int(payload.get('reviews_and_comments') or 0)
|
|
1168
|
+
else:
|
|
1169
|
+
issues_created = None
|
|
1170
|
+
issues_closed = None
|
|
1171
|
+
prs_opened = None
|
|
1172
|
+
prs_merged = None
|
|
1173
|
+
prs_in_progress = None
|
|
1174
|
+
reviews_count = None
|
|
1175
|
+
|
|
1176
|
+
commits = local.get('commits') if local.get('available') else None
|
|
1177
|
+
files_changed = local.get('files_changed') if local.get('available') else None
|
|
1178
|
+
insertions = local.get('insertions') if local.get('available') else None
|
|
1179
|
+
deletions = local.get('deletions') if local.get('available') else None
|
|
1180
|
+
ahead_commits = local.get('ahead_commits') if local.get('available') else None
|
|
1181
|
+
working_changes = local.get('working_changes') if local.get('available') else None
|
|
1182
|
+
|
|
1183
|
+
if not local.get('available') and local.get('reason'):
|
|
1184
|
+
gaps.append(f'Local Git unavailable: {local["reason"]}')
|
|
1185
|
+
|
|
1186
|
+
created_count = len(issues_created) if issues_created is not None else None
|
|
1187
|
+
closed_count = len(issues_closed) if issues_closed is not None else None
|
|
1188
|
+
opened_count = len(prs_opened) if prs_opened is not None else None
|
|
1189
|
+
merged_count = len(prs_merged) if prs_merged is not None else None
|
|
1190
|
+
|
|
1191
|
+
solved_total = (closed_count + merged_count) if (closed_count is not None and merged_count is not None) else None
|
|
1192
|
+
|
|
1193
|
+
prs_open_updated = len(prs_in_progress) if prs_in_progress is not None else None
|
|
1194
|
+
prs_draft = sum(1 for pr in prs_in_progress if pr.get('draft')) if prs_in_progress is not None else None
|
|
1195
|
+
prs_ready = (prs_open_updated - prs_draft) if prs_open_updated is not None else None
|
|
1196
|
+
|
|
1197
|
+
if prs_opened is not None:
|
|
1198
|
+
checked_prs = [pr for pr in prs_opened if pr.get('ci_status') in ('success', 'failing')]
|
|
1199
|
+
green_prs = [pr for pr in checked_prs if pr.get('ci_status') == 'success']
|
|
1200
|
+
ci_pass = _ratio_entry(len(green_prs), len(checked_prs))
|
|
1201
|
+
else:
|
|
1202
|
+
ci_pass = _ratio_entry(None, None)
|
|
1203
|
+
|
|
1204
|
+
merge_ratio = _ratio_entry(
|
|
1205
|
+
merged_count,
|
|
1206
|
+
opened_count,
|
|
1207
|
+
zero_denom_label=f'{merged_count} merged (0 opened)' if merged_count else None,
|
|
1208
|
+
)
|
|
1209
|
+
close_ratio = _ratio_entry(
|
|
1210
|
+
closed_count,
|
|
1211
|
+
created_count,
|
|
1212
|
+
zero_denom_label=f'{closed_count} closed (0 created)' if closed_count else None,
|
|
1213
|
+
)
|
|
1214
|
+
|
|
1215
|
+
report = {
|
|
1216
|
+
'user': payload.get('user'),
|
|
1217
|
+
'repo': payload.get('repo') or 'all-repos',
|
|
1218
|
+
'since': since_dt.isoformat(),
|
|
1219
|
+
'github_available': gh_ok,
|
|
1220
|
+
'local_available': bool(local.get('available')),
|
|
1221
|
+
'branch': local.get('branch') if local.get('available') else None,
|
|
1222
|
+
'issues_created': {'count': created_count, 'items': issues_created or []},
|
|
1223
|
+
'issues_closed': {'count': closed_count, 'items': issues_closed or []},
|
|
1224
|
+
'prs_opened': {'count': opened_count, 'items': prs_opened or []},
|
|
1225
|
+
'contribution': {
|
|
1226
|
+
'commits': commits,
|
|
1227
|
+
'files_changed': files_changed,
|
|
1228
|
+
'insertions': insertions,
|
|
1229
|
+
'deletions': deletions,
|
|
1230
|
+
'reviews_and_comments': reviews_count,
|
|
1231
|
+
},
|
|
1232
|
+
'solved': {
|
|
1233
|
+
'issues_closed': closed_count,
|
|
1234
|
+
'prs_merged': merged_count,
|
|
1235
|
+
'total': solved_total,
|
|
1236
|
+
'merged_items': prs_merged or [],
|
|
1237
|
+
},
|
|
1238
|
+
'progress': {
|
|
1239
|
+
'prs_open_updated': prs_open_updated,
|
|
1240
|
+
'prs_ready': prs_ready,
|
|
1241
|
+
'prs_draft': prs_draft,
|
|
1242
|
+
'ahead_commits': ahead_commits,
|
|
1243
|
+
'working_changes': working_changes,
|
|
1244
|
+
},
|
|
1245
|
+
'effectiveness': {
|
|
1246
|
+
'pr_merge_ratio': merge_ratio,
|
|
1247
|
+
'ci_pass_rate': ci_pass,
|
|
1248
|
+
'issue_close_ratio': close_ratio,
|
|
1249
|
+
},
|
|
1250
|
+
'gaps': gaps,
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
if payload.get('team') is not None:
|
|
1254
|
+
report['team'] = payload['team']
|
|
1255
|
+
|
|
1256
|
+
raw_project = payload.get('project')
|
|
1257
|
+
if raw_project is not None:
|
|
1258
|
+
activity_items = list(payload.get('project_activity_items') or [])
|
|
1259
|
+
if not activity_items and gh_ok:
|
|
1260
|
+
activity_items = (
|
|
1261
|
+
(issues_created or [])
|
|
1262
|
+
+ [{**it, 'state': it.get('state') or 'closed'} for it in (issues_closed or [])]
|
|
1263
|
+
+ [{**pr, 'is_pr': True} for pr in (prs_in_progress or [])]
|
|
1264
|
+
+ [{**pr, 'is_pr': True} for pr in (prs_opened or []) if pr.get('state') == 'open']
|
|
1265
|
+
)
|
|
1266
|
+
proj_summary = summarize_project_board(
|
|
1267
|
+
raw_project,
|
|
1268
|
+
activity_items=activity_items,
|
|
1269
|
+
default_repo=payload.get('repo'),
|
|
1270
|
+
)
|
|
1271
|
+
if not proj_summary.get('available') and proj_summary.get('gap'):
|
|
1272
|
+
gaps.append(proj_summary['gap'])
|
|
1273
|
+
report['project'] = proj_summary
|
|
1274
|
+
|
|
1275
|
+
if payload.get('board_sync') is not None:
|
|
1276
|
+
report['board_sync'] = payload['board_sync']
|
|
1277
|
+
|
|
1278
|
+
return report
|
|
1279
|
+
|
|
1280
|
+
|
|
1281
|
+
def _light(status):
|
|
1282
|
+
return {'green': '🟢', 'yellow': '🟡', 'red': '🔴', 'na': '⚪', 'gap': '🟡'}.get(status, '⚪')
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def _fmt_num(val, gap_text='🟡 GAP'):
|
|
1286
|
+
return str(val) if val is not None else gap_text
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _format_team_lines(team, is_es):
|
|
1290
|
+
if not isinstance(team, list) or not team:
|
|
1291
|
+
return []
|
|
1292
|
+
header = '├── 👥 Equipo' if is_es else '├── 👥 Team'
|
|
1293
|
+
lines = [header]
|
|
1294
|
+
for idx, member in enumerate(team):
|
|
1295
|
+
branch_char = '└──' if idx == len(team) - 1 else '├──'
|
|
1296
|
+
login = member.get('user') or '?'
|
|
1297
|
+
if not member.get('available'):
|
|
1298
|
+
lines.append(f'│ {branch_char} @{login} · 🟡 GAP ({member.get("gap", "unavailable")})')
|
|
1299
|
+
continue
|
|
1300
|
+
if is_es:
|
|
1301
|
+
lines.append(
|
|
1302
|
+
f'│ {branch_char} @{login} · {member["issues_created"]} creados · '
|
|
1303
|
+
f'{member["issues_closed"]} cerrados · {member["prs_merged"]}/{member["prs_opened"]} PRs mergeados'
|
|
1304
|
+
)
|
|
1305
|
+
else:
|
|
1306
|
+
lines.append(
|
|
1307
|
+
f'│ {branch_char} @{login} · {member["issues_created"]} created · '
|
|
1308
|
+
f'{member["issues_closed"]} closed · {member["prs_merged"]}/{member["prs_opened"]} PRs merged'
|
|
1309
|
+
)
|
|
1310
|
+
return lines
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def _format_project_lines(proj, is_es):
|
|
1314
|
+
if not isinstance(proj, dict):
|
|
1315
|
+
return []
|
|
1316
|
+
if not proj.get('available'):
|
|
1317
|
+
label = '├── 📋 Tablero' if is_es else '├── 📋 Board'
|
|
1318
|
+
return [f'{label} · 🟡 GAP ({proj.get("gap", "unavailable")})']
|
|
1319
|
+
|
|
1320
|
+
title = proj.get('title') or 'Project'
|
|
1321
|
+
view_name = proj.get('view_name')
|
|
1322
|
+
view_tag = f' · {view_name}' if view_name else ''
|
|
1323
|
+
counts = proj.get('status_counts') or {}
|
|
1324
|
+
cols = ' · '.join(f'{k}: {v}' for k, v in counts.items()) or ('sin items' if is_es else 'empty')
|
|
1325
|
+
missing = len(proj.get('missing_from_board') or [])
|
|
1326
|
+
mismatches = len(proj.get('status_mismatches') or [])
|
|
1327
|
+
|
|
1328
|
+
if is_es:
|
|
1329
|
+
return [
|
|
1330
|
+
f'├── 📋 Tablero ─ {title}{view_tag} ({proj.get("total_items", 0)} tarjetas)',
|
|
1331
|
+
f'│ ├── Columnas ················ {cols}',
|
|
1332
|
+
f'│ └── Desfase ················· {missing} sin tarjeta · {mismatches} estado desfasado',
|
|
1333
|
+
]
|
|
1334
|
+
return [
|
|
1335
|
+
f'├── 📋 Board ─ {title}{view_tag} ({proj.get("total_items", 0)} items)',
|
|
1336
|
+
f'│ ├── Columns ················· {cols}',
|
|
1337
|
+
f'│ └── Sync diff ··············· {missing} missing · {mismatches} status mismatch',
|
|
1338
|
+
]
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def _format_sync_lines(sync_res, is_es):
|
|
1342
|
+
if not isinstance(sync_res, dict):
|
|
1343
|
+
return []
|
|
1344
|
+
if sync_res.get('dry_run'):
|
|
1345
|
+
if is_es:
|
|
1346
|
+
return [
|
|
1347
|
+
(
|
|
1348
|
+
f'├── 🔄 Plan tablero (dry-run) · '
|
|
1349
|
+
f'+{sync_res.get("planned_adds", 0)} añadir · '
|
|
1350
|
+
f'{sync_res.get("planned_moves", 0)} mover · '
|
|
1351
|
+
f'{sync_res.get("planned_color_updates", 0)} colores'
|
|
1352
|
+
)
|
|
1353
|
+
]
|
|
1354
|
+
return [
|
|
1355
|
+
(
|
|
1356
|
+
f'├── 🔄 Board plan (dry-run) ··· '
|
|
1357
|
+
f'+{sync_res.get("planned_adds", 0)} add · '
|
|
1358
|
+
f'{sync_res.get("planned_moves", 0)} move · '
|
|
1359
|
+
f'{sync_res.get("planned_color_updates", 0)} colors'
|
|
1360
|
+
)
|
|
1361
|
+
]
|
|
1362
|
+
|
|
1363
|
+
added_n = len(sync_res.get('added') or [])
|
|
1364
|
+
moved_n = len(sync_res.get('moved') or [])
|
|
1365
|
+
colors_n = len(sync_res.get('colors_updated') or [])
|
|
1366
|
+
labels_n = len(sync_res.get('labels_added') or [])
|
|
1367
|
+
if is_es:
|
|
1368
|
+
return [
|
|
1369
|
+
f'├── 🔄 Tablero organizado ····· +{added_n} añadidas · {moved_n} movidas · {colors_n} colores · {labels_n} etiquetas'
|
|
1370
|
+
]
|
|
1371
|
+
return [
|
|
1372
|
+
f'├── 🔄 Board synced ··········· +{added_n} added · {moved_n} moved · {colors_n} colors · {labels_n} labels'
|
|
1373
|
+
]
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def format_hud(report, lang='es'):
|
|
1377
|
+
is_es = lang == 'es'
|
|
1378
|
+
user = report.get('user') or 'local'
|
|
1379
|
+
repo = report.get('repo') or 'local'
|
|
1380
|
+
since = report.get('since', '')
|
|
1381
|
+
branch = report.get('branch') or '-'
|
|
1382
|
+
|
|
1383
|
+
ic = report['issues_created']['count']
|
|
1384
|
+
icl = report['issues_closed']['count']
|
|
1385
|
+
po = report['prs_opened']['count']
|
|
1386
|
+
contrib = report['contribution']
|
|
1387
|
+
solved = report['solved']
|
|
1388
|
+
prog = report['progress']
|
|
1389
|
+
eff = report['effectiveness']
|
|
1390
|
+
gaps = report.get('gaps') or []
|
|
1391
|
+
team_lines = _format_team_lines(report.get('team'), is_es)
|
|
1392
|
+
project_lines = _format_project_lines(report.get('project'), is_es)
|
|
1393
|
+
sync_lines = _format_sync_lines(report.get('board_sync'), is_es)
|
|
1394
|
+
|
|
1395
|
+
if is_es:
|
|
1396
|
+
lines = [
|
|
1397
|
+
f'📊 RECAP ─ {repo} (@{user} · desde {since})',
|
|
1398
|
+
f'│ 🌿 Rama actual: {branch}',
|
|
1399
|
+
'│',
|
|
1400
|
+
f'├── 📝 Issues creados ··········· {_fmt_num(ic)}',
|
|
1401
|
+
f'├── ✅ Issues cerrados ·········· {_fmt_num(icl)}',
|
|
1402
|
+
f'├── 🚀 PRs enviados ············· {_fmt_num(po)}',
|
|
1403
|
+
(
|
|
1404
|
+
f'├── 🧱 Aporte ··················· '
|
|
1405
|
+
f'{_fmt_num(contrib["commits"])} commits · '
|
|
1406
|
+
f'{_fmt_num(contrib["files_changed"])} archivos '
|
|
1407
|
+
f'(+{_fmt_num(contrib["insertions"])}/-{_fmt_num(contrib["deletions"])}) · '
|
|
1408
|
+
f'{_fmt_num(contrib["reviews_and_comments"])} PRs revisados/comentados'
|
|
1409
|
+
),
|
|
1410
|
+
(
|
|
1411
|
+
f'├── 🎯 Solucionado ·············· '
|
|
1412
|
+
f'{_fmt_num(solved["total"])} total '
|
|
1413
|
+
f'({_fmt_num(solved["prs_merged"])} PRs mergeados · {_fmt_num(solved["issues_closed"])} issues cerrados)'
|
|
1414
|
+
),
|
|
1415
|
+
(
|
|
1416
|
+
f'├── 🏃 Avance en curso ·········· '
|
|
1417
|
+
f'{_fmt_num(prog["prs_open_updated"])} PRs activos '
|
|
1418
|
+
f'({_fmt_num(prog["prs_ready"])} ready · {_fmt_num(prog["prs_draft"])} draft) · '
|
|
1419
|
+
f'{_fmt_num(prog["ahead_commits"])} commits sin push · '
|
|
1420
|
+
f'{_fmt_num(prog["working_changes"])} cambios locales'
|
|
1421
|
+
),
|
|
1422
|
+
*team_lines,
|
|
1423
|
+
*project_lines,
|
|
1424
|
+
*sync_lines,
|
|
1425
|
+
'└── ⚡ Efectividad',
|
|
1426
|
+
f' ├── PRs mergeados/enviados ·· {_light(eff["pr_merge_ratio"]["status"])} {eff["pr_merge_ratio"]["display"]}',
|
|
1427
|
+
f' ├── CI en verde ············· {_light(eff["ci_pass_rate"]["status"])} {eff["ci_pass_rate"]["display"]}',
|
|
1428
|
+
f' └── Issues cerrados/creados · {_light(eff["issue_close_ratio"]["status"])} {eff["issue_close_ratio"]["display"]}',
|
|
1429
|
+
]
|
|
1430
|
+
if gaps:
|
|
1431
|
+
lines.append('')
|
|
1432
|
+
lines.append('🟡 Gaps: ' + ' | '.join(gaps))
|
|
1433
|
+
else:
|
|
1434
|
+
lines.append('')
|
|
1435
|
+
lines.append('🏁 STAGE CLEAR ─ Resumen de solo lectura completado.')
|
|
1436
|
+
return '\n'.join(lines)
|
|
1437
|
+
|
|
1438
|
+
lines = [
|
|
1439
|
+
f'📊 RECAP ─ {repo} (@{user} · since {since})',
|
|
1440
|
+
f'│ 🌿 Current branch: {branch}',
|
|
1441
|
+
'│',
|
|
1442
|
+
f'├── 📝 Issues created ··········· {_fmt_num(ic)}',
|
|
1443
|
+
f'├── ✅ Issues closed ············ {_fmt_num(icl)}',
|
|
1444
|
+
f'├── 🚀 PRs opened ··············· {_fmt_num(po)}',
|
|
1445
|
+
(
|
|
1446
|
+
f'├── 🧱 Contribution ············· '
|
|
1447
|
+
f'{_fmt_num(contrib["commits"])} commits · '
|
|
1448
|
+
f'{_fmt_num(contrib["files_changed"])} files '
|
|
1449
|
+
f'(+{_fmt_num(contrib["insertions"])}/-{_fmt_num(contrib["deletions"])}) · '
|
|
1450
|
+
f'{_fmt_num(contrib["reviews_and_comments"])} peer PRs reviewed/commented'
|
|
1451
|
+
),
|
|
1452
|
+
(
|
|
1453
|
+
f'├── 🎯 Solved ··················· '
|
|
1454
|
+
f'{_fmt_num(solved["total"])} total '
|
|
1455
|
+
f'({_fmt_num(solved["prs_merged"])} PRs merged · {_fmt_num(solved["issues_closed"])} issues closed)'
|
|
1456
|
+
),
|
|
1457
|
+
(
|
|
1458
|
+
f'├── 🏃 Work in progress ········· '
|
|
1459
|
+
f'{_fmt_num(prog["prs_open_updated"])} active PRs '
|
|
1460
|
+
f'({_fmt_num(prog["prs_ready"])} ready · {_fmt_num(prog["prs_draft"])} draft) · '
|
|
1461
|
+
f'{_fmt_num(prog["ahead_commits"])} unpushed commits · '
|
|
1462
|
+
f'{_fmt_num(prog["working_changes"])} local changes'
|
|
1463
|
+
),
|
|
1464
|
+
*team_lines,
|
|
1465
|
+
*project_lines,
|
|
1466
|
+
*sync_lines,
|
|
1467
|
+
'└── ⚡ Effectiveness',
|
|
1468
|
+
f' ├── PR merge ratio ·········· {_light(eff["pr_merge_ratio"]["status"])} {eff["pr_merge_ratio"]["display"]}',
|
|
1469
|
+
f' ├── CI pass rate ············ {_light(eff["ci_pass_rate"]["status"])} {eff["ci_pass_rate"]["display"]}',
|
|
1470
|
+
f' └── Issue close ratio ······· {_light(eff["issue_close_ratio"]["status"])} {eff["issue_close_ratio"]["display"]}',
|
|
1471
|
+
]
|
|
1472
|
+
if gaps:
|
|
1473
|
+
lines.append('')
|
|
1474
|
+
lines.append('🟡 Gaps: ' + ' | '.join(gaps))
|
|
1475
|
+
else:
|
|
1476
|
+
lines.append('')
|
|
1477
|
+
lines.append('🏁 STAGE CLEAR ─ Read-only summary complete.')
|
|
1478
|
+
return '\n'.join(lines)
|
|
1479
|
+
|
|
1480
|
+
|
|
1481
|
+
def parse_args(argv):
|
|
1482
|
+
parser = argparse.ArgumentParser(
|
|
1483
|
+
description='Generate a daily progress summary from local Git, GitHub REST, and Project v2 boards.'
|
|
1484
|
+
)
|
|
1485
|
+
parser.add_argument('--repo', help='Target GitHub repository (owner/repo).')
|
|
1486
|
+
parser.add_argument('--all-repos', action='store_true', help='Include all repositories for the GitHub user.')
|
|
1487
|
+
parser.add_argument('--since', help='Start time: YYYY-MM-DD, <N>h, <N>d, or ISO-8601 (default: local midnight today).')
|
|
1488
|
+
parser.add_argument('--user', help='GitHub login override (default: authenticated user).')
|
|
1489
|
+
parser.add_argument('--team', action='store_true', help='Collect summary across all organization members.')
|
|
1490
|
+
parser.add_argument('--users', help='Comma-separated GitHub logins for team summary.')
|
|
1491
|
+
parser.add_argument('--project', help='GitHub Project v2 URL or <owner>/<number> to inspect board progress.')
|
|
1492
|
+
parser.add_argument('--sync-board', action='store_true', help='Add missing items and move closed/merged items on --project.')
|
|
1493
|
+
parser.add_argument('--fix-colors', action='store_true', help='With --sync-board, normalize Status/field colors and board view fields.')
|
|
1494
|
+
parser.add_argument('--apply-labels', action='store_true', help='With --sync-board, add matching existing repo labels to added items.')
|
|
1495
|
+
parser.add_argument('--dry-run', action='store_true', help='With --sync-board, preview planned board changes without writing.')
|
|
1496
|
+
parser.add_argument('--git-author', help='Git author filter (default: git config user.email / user.name).')
|
|
1497
|
+
parser.add_argument('--cwd', help='Working directory of the target Git repository.')
|
|
1498
|
+
parser.add_argument('--lang', choices=('es', 'en'), default='es', help='HUD output language (default: es).')
|
|
1499
|
+
parser.add_argument('--no-github', action='store_true', help='Skip GitHub API queries and collect local Git only.')
|
|
1500
|
+
parser.add_argument('--json', action='store_true', help='Print structured JSON report instead of HUD.')
|
|
1501
|
+
parser.add_argument('--stdin', action='store_true', help='Read synthetic recap payload JSON from stdin.')
|
|
1502
|
+
return parser.parse_args(argv)
|
|
1503
|
+
|
|
1504
|
+
|
|
1505
|
+
def main(argv):
|
|
1506
|
+
try:
|
|
1507
|
+
args = parse_args(argv)
|
|
1508
|
+
except SystemExit as exc:
|
|
1509
|
+
return 2 if exc.code != 0 else 0
|
|
1510
|
+
|
|
1511
|
+
if args.repo and not REPO_RE.fullmatch(args.repo):
|
|
1512
|
+
print(json.dumps({'error': f'Invalid --repo {args.repo!r}; expected owner/repo.'}))
|
|
1513
|
+
return 2
|
|
1514
|
+
|
|
1515
|
+
try:
|
|
1516
|
+
since_dt = parse_since(args.since)
|
|
1517
|
+
except ValueError as err:
|
|
1518
|
+
print(json.dumps({'error': str(err)}))
|
|
1519
|
+
return 2
|
|
1520
|
+
|
|
1521
|
+
try:
|
|
1522
|
+
project_ref = parse_project_ref(args.project) if args.project else None
|
|
1523
|
+
except ValueError as err:
|
|
1524
|
+
print(json.dumps({'error': str(err)}))
|
|
1525
|
+
return 2
|
|
1526
|
+
|
|
1527
|
+
if args.sync_board and not project_ref and not args.stdin:
|
|
1528
|
+
print(json.dumps({'error': '--sync-board requires --project <url|owner/number>.'}))
|
|
1529
|
+
return 2
|
|
1530
|
+
|
|
1531
|
+
if args.stdin:
|
|
1532
|
+
try:
|
|
1533
|
+
payload = json.load(sys.stdin)
|
|
1534
|
+
except ValueError as err:
|
|
1535
|
+
print(json.dumps({'error': f'Invalid JSON on stdin: {err}'}))
|
|
1536
|
+
return 2
|
|
1537
|
+
if args.since and 'since' not in payload:
|
|
1538
|
+
payload['since'] = since_dt.isoformat()
|
|
1539
|
+
report = compute_recap(payload)
|
|
1540
|
+
else:
|
|
1541
|
+
cwd = Path(args.cwd).resolve() if args.cwd else Path.cwd()
|
|
1542
|
+
local = collect_local_git(cwd, since_dt, author_pattern=args.git_author)
|
|
1543
|
+
target_repo = args.repo or local.get('repo')
|
|
1544
|
+
|
|
1545
|
+
if args.no_github:
|
|
1546
|
+
gh = {'available': False, 'gap': 'GitHub skipped (--no-github)'}
|
|
1547
|
+
project_data = {'available': False, 'gap': 'GitHub skipped (--no-github)'} if project_ref else None
|
|
1548
|
+
team_reports = None
|
|
1549
|
+
team_activity = []
|
|
1550
|
+
else:
|
|
1551
|
+
gh = collect_github(target_repo, args.all_repos, since_dt, user_override=args.user)
|
|
1552
|
+
project_data = collect_project_board(project_ref) if project_ref else None
|
|
1553
|
+
team_reports = None
|
|
1554
|
+
team_activity = []
|
|
1555
|
+
if args.team or args.users:
|
|
1556
|
+
org_name = (
|
|
1557
|
+
(project_ref or {}).get('owner')
|
|
1558
|
+
or (target_repo.split('/', 1)[0] if target_repo and '/' in target_repo else None)
|
|
1559
|
+
)
|
|
1560
|
+
members = collect_team_members(org_name, users_arg=args.users)
|
|
1561
|
+
if members:
|
|
1562
|
+
team_reports, team_activity = _collect_team_recaps(
|
|
1563
|
+
members, target_repo, args.all_repos, since_dt, cached_gh=gh
|
|
1564
|
+
)
|
|
1565
|
+
else:
|
|
1566
|
+
team_reports = []
|
|
1567
|
+
|
|
1568
|
+
payload = {
|
|
1569
|
+
'user': gh.get('user') or args.user or local.get('author'),
|
|
1570
|
+
'repo': 'all-repos' if args.all_repos else target_repo,
|
|
1571
|
+
'since': since_dt.isoformat(),
|
|
1572
|
+
'github_available': gh.get('available', False),
|
|
1573
|
+
'github_gap': gh.get('gap'),
|
|
1574
|
+
'issues_created': gh.get('issues_created', []),
|
|
1575
|
+
'issues_closed': gh.get('issues_closed', []),
|
|
1576
|
+
'prs_opened': gh.get('prs_opened', []),
|
|
1577
|
+
'prs_merged': gh.get('prs_merged', []),
|
|
1578
|
+
'prs_in_progress': gh.get('prs_in_progress', []),
|
|
1579
|
+
'reviews_and_comments': gh.get('reviews_and_comments', 0),
|
|
1580
|
+
'gaps': gh.get('gaps', []),
|
|
1581
|
+
'local_git': local,
|
|
1582
|
+
}
|
|
1583
|
+
if team_reports is not None:
|
|
1584
|
+
payload['team'] = team_reports
|
|
1585
|
+
if project_data is not None:
|
|
1586
|
+
payload['project'] = project_data
|
|
1587
|
+
if team_activity:
|
|
1588
|
+
payload['project_activity_items'] = team_activity
|
|
1589
|
+
|
|
1590
|
+
report = compute_recap(payload)
|
|
1591
|
+
if args.sync_board and project_data and project_data.get('available'):
|
|
1592
|
+
sync_plan = plan_board_sync(
|
|
1593
|
+
report['project'], project_data, fix_colors=args.fix_colors
|
|
1594
|
+
)
|
|
1595
|
+
sync_res = apply_board_sync(
|
|
1596
|
+
sync_plan, dry_run=args.dry_run, apply_labels=args.apply_labels
|
|
1597
|
+
)
|
|
1598
|
+
report['board_sync'] = sync_res
|
|
1599
|
+
if sync_res.get('errors'):
|
|
1600
|
+
report['gaps'].extend(sync_res['errors'])
|
|
1601
|
+
|
|
1602
|
+
if args.json:
|
|
1603
|
+
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
1604
|
+
else:
|
|
1605
|
+
print(format_hud(report, lang=args.lang))
|
|
1606
|
+
return 0
|
|
1607
|
+
|
|
1608
|
+
|
|
1609
|
+
if __name__ == '__main__':
|
|
1610
|
+
sys.exit(main(sys.argv[1:]))
|