-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_notes.py
More file actions
362 lines (326 loc) · 12.1 KB
/
Copy pathgithub_notes.py
File metadata and controls
362 lines (326 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
"""Import GitHub PRs and issues into rich notes (thread + file patches)."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import notes_store
import workspace as workspace_mod
TOOL_DIR = Path(__file__).resolve().parent
def _notes_path() -> Path:
return workspace_mod.get().notes_path
def _notes_db_path() -> Path:
return workspace_mod.get().notes_db_path
def _utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _gh_executable() -> str | None:
"""Resolve gh binary — PATH first, then common Windows install dirs."""
found = shutil.which("gh")
if found:
return found
env = (os.environ.get("GH_PATH") or os.environ.get("GITHUB_CLI_PATH") or "").strip().strip('"')
if env:
p = Path(env)
if p.is_file():
return str(p)
if (p / "gh.exe").is_file():
return str(p / "gh.exe")
for base in (
os.environ.get("ProgramFiles"),
os.environ.get("ProgramFiles(x86)"),
os.environ.get("LOCALAPPDATA"),
):
if not base:
continue
for rel in (
Path("GitHub CLI") / "gh.exe",
Path("Programs") / "GitHub CLI" / "gh.exe",
):
cand = Path(base) / rel
if cand.is_file():
return str(cand)
return None
def _gh_available() -> bool:
return _gh_executable() is not None
def _run_gh(args: list[str], *, cwd: Path | None = None) -> tuple[int, str, str]:
gh = _gh_executable()
if not gh:
return 1, "", "gh CLI not available"
cmd = [gh, *args]
try:
proc = subprocess.run(
cmd,
cwd=str(cwd) if cwd else None,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=120,
)
return proc.returncode, proc.stdout or "", proc.stderr or ""
except (OSError, subprocess.TimeoutExpired) as exc:
return 1, "", str(exc)
def status(repo: Path) -> dict[str, Any]:
ok = _gh_available()
remote = ""
if ok:
code, out, err = _run_gh(["repo", "view", "--json", "nameWithOwner,url"], cwd=repo)
if code == 0:
try:
data = json.loads(out)
remote = data.get("nameWithOwner") or data.get("url") or ""
except json.JSONDecodeError:
remote = out.strip()[:200]
else:
return {"ok": False, "gh": True, "error": err.strip() or "gh repo view failed", "repo": str(repo)}
return {
"ok": ok,
"gh": ok,
"repo": str(repo),
"remote": remote,
"hint": None if ok else "Install GitHub CLI (gh) and authenticate (gh auth login)",
}
def _map_issue(item: dict[str, Any], *, kind: str) -> dict[str, Any]:
number = item.get("number")
title = item.get("title") or f"{kind.upper()} #{number}"
body = item.get("body") or ""
url = item.get("url") or ""
state = (item.get("state") or "").lower()
author = ""
if isinstance(item.get("author"), dict):
author = item["author"].get("login") or ""
elif isinstance(item.get("user"), dict):
author = item["user"].get("login") or ""
labels = []
for lab in item.get("labels") or []:
if isinstance(lab, dict):
labels.append(lab.get("name") or "")
elif isinstance(lab, str):
labels.append(lab)
comments_raw = item.get("comments") or []
thread = []
if body:
thread.append({"author": author or "author", "at": item.get("createdAt") or item.get("created_at"), "body": body})
if isinstance(comments_raw, list):
for c in comments_raw:
if not isinstance(c, dict):
continue
c_author = ""
if isinstance(c.get("author"), dict):
c_author = c["author"].get("login") or ""
elif isinstance(c.get("user"), dict):
c_author = c["user"].get("login") or ""
thread.append(
{
"author": c_author,
"at": c.get("createdAt") or c.get("created_at"),
"body": c.get("body") or "",
}
)
files = []
for f in item.get("files") or []:
if not isinstance(f, dict):
continue
files.append(
{
"path": f.get("path") or f.get("filename") or "",
"status": f.get("status") or "",
"additions": f.get("additions"),
"deletions": f.get("deletions"),
"patch": f.get("patch") or "",
}
)
base = ""
head = ""
if kind == "pr":
base_ref = item.get("baseRefName") or (item.get("base") or {}).get("ref")
head_ref = item.get("headRefName") or (item.get("head") or {}).get("ref")
base = base_ref or ""
head = head_ref or ""
summary = f"# {title}\n\n{body}\n" if body else f"# {title}\n"
return {
"title": f"{'PR' if kind == 'pr' else 'Issue'} #{number}: {title}",
"body": summary,
"kind": f"github-{kind}",
"github": {
"number": number,
"state": state,
"url": url,
"base": base,
"head": head,
"author": author,
"labels": [x for x in labels if x],
"thread": thread,
"files": files,
"synced_at": _utc_now(),
},
"meta": {"source": "github-sync", "at": _utc_now()},
}
def sync(
repo: Path,
*,
types: list[str] | None = None,
state: str = "all",
limit: int = 30,
) -> dict[str, Any]:
if not _gh_available():
return {"ok": False, "error": "gh CLI not available"}
types = types or ["pr", "issue"]
state = state if state in ("all", "open", "closed") else "all"
notes = notes_store.load_notes_file(_notes_path())
imported = 0
errors: list[str] = []
if "pr" in types:
fields = (
"number,title,body,url,state,createdAt,author,labels,baseRefName,headRefName,"
"comments,files"
)
args = ["pr", "list", "--state", state, "--limit", str(limit), "--json", fields]
code, out, err = _run_gh(args, cwd=repo)
if code != 0:
errors.append(err.strip() or "pr list failed")
else:
try:
items = json.loads(out)
except json.JSONDecodeError:
items = []
errors.append("invalid pr JSON")
for item in items if isinstance(items, list) else []:
# Enrich files with patches via REST if missing
number = item.get("number")
if number and not any((f or {}).get("patch") for f in (item.get("files") or [])):
c2, o2, _ = _run_gh(
["api", f"repos/{{owner}}/{{repo}}/pulls/{number}/files", "--paginate"],
cwd=repo,
)
if c2 == 0:
try:
item["files"] = json.loads(o2)
except json.JSONDecodeError:
pass
# comments as list: gh may return count; fetch if needed
if isinstance(item.get("comments"), int) or not isinstance(item.get("comments"), list):
c3, o3, _ = _run_gh(
[
"api",
f"repos/{{owner}}/{{repo}}/issues/{number}/comments",
"--paginate",
],
cwd=repo,
)
if c3 == 0:
try:
item["comments"] = json.loads(o3)
except json.JSONDecodeError:
item["comments"] = []
else:
item["comments"] = []
note = _map_issue(item, kind="pr")
key = f"gh:pr:{number}"
notes[key] = note
imported += 1
if "issue" in types:
fields = "number,title,body,url,state,createdAt,author,labels,comments"
args = ["issue", "list", "--state", state, "--limit", str(limit), "--json", fields]
code, out, err = _run_gh(args, cwd=repo)
if code != 0:
errors.append(err.strip() or "issue list failed")
else:
try:
items = json.loads(out)
except json.JSONDecodeError:
items = []
errors.append("invalid issue JSON")
for item in items if isinstance(items, list) else []:
number = item.get("number")
if isinstance(item.get("comments"), int) or not isinstance(item.get("comments"), list):
c3, o3, _ = _run_gh(
[
"api",
f"repos/{{owner}}/{{repo}}/issues/{number}/comments",
"--paginate",
],
cwd=repo,
)
if c3 == 0:
try:
item["comments"] = json.loads(o3)
except json.JSONDecodeError:
item["comments"] = []
else:
item["comments"] = []
note = _map_issue(item, kind="issue")
key = f"gh:issue:{number}"
notes[key] = note
imported += 1
if imported:
notes_store.save_notes_with_history(_notes_path(), notes, db_path=_notes_db_path())
return {
"ok": len(errors) == 0,
"imported": imported,
"errors": errors,
"notes": notes,
"at": _utc_now(),
}
def list_branches(repo: Path) -> dict[str, Any]:
try:
proc = subprocess.run(
["git", "branch", "-a", "--format=%(refname:short)"],
cwd=str(repo),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"ok": False, "error": str(exc), "branches": []}
if proc.returncode != 0:
return {"ok": False, "error": proc.stderr.strip(), "branches": []}
branches = [b.strip() for b in (proc.stdout or "").splitlines() if b.strip()]
return {"ok": True, "branches": branches}
def git_status(repo: Path) -> dict[str, Any]:
import git_ops
return git_ops.status(repo)
def git_switch(repo: Path, branch: str, *, stash_if_dirty: bool = False) -> dict[str, Any]:
import git_ops
return git_ops.switch(repo, branch, stash_if_dirty=stash_if_dirty)
def diff_branch(repo: Path, ref: str, base: str = "HEAD") -> dict[str, Any]:
"""File list + patches for ref vs base (not a full tree swap)."""
try:
name_proc = subprocess.run(
["git", "diff", "--name-status", f"{base}...{ref}"],
cwd=str(repo),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60,
)
patch_proc = subprocess.run(
["git", "diff", f"{base}...{ref}", "--", "."],
cwd=str(repo),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"ok": False, "error": str(exc)}
files = []
for line in (name_proc.stdout or "").splitlines():
parts = line.split("\t")
if len(parts) >= 2:
files.append({"status": parts[0], "path": parts[-1], "patch": ""})
return {
"ok": name_proc.returncode == 0,
"base": base,
"head": ref,
"files": files,
"patch": (patch_proc.stdout or "")[:500_000],
"error": name_proc.stderr.strip() if name_proc.returncode else None,
}