2026-05-31Repository implementationIssue gh-forgejo-shim-vo2

Broadened Forgejo-backed gh compatibility where tools probe

The shim now handles the next practical GitHub CLI command surface for Forgejo repositories: PR checks, diffs, comments, checkout, basic issue workflows, and richer repository JSON.

Summary

Added Forgejo-backed support for common developer-tool probes around pull requests, issues, and repository metadata. The implementation keeps the existing focused-shim posture: allowlisted Forgejo repositories get GitHub-shaped responses, while unsupported commands continue to delegate to the real GitHub CLI.

Changes Made

Pull request probes

gh pr diff, gh pr comment, gh pr checkout, and gh pr checks now parse the common flags tools use. Diffs and comments call Forgejo API endpoints; checkout fetches the PR head through Git.

Issue workflows

gh issue list, gh issue view, gh issue create, plus ls and new aliases now route for allowlisted Forgejo hosts and return GitHub-shaped issue JSON.

Repository metadata

gh repo view --json ... now recognizes a broad set of GitHub CLI fields such as visibility, primaryLanguage, viewerPermission, merge method booleans, counts, and repository feature flags.

Project context

Added PRODUCT.md because the repository turn-document styling workflow now requires an explicit product-register context before using impeccable as the design authority.

Context

The previous focused PR and repository support was enough for core Codex.app PR status, but GitHub-oriented tools probe a wider set of commands once the basic repository shape is healthy. This work covers the next commands the user identified: gh pr checks, gh pr diff, gh pr comment, gh pr checkout, gh issue list/view/create, and richer gh repo view --json fields.

Forgejo's current OpenAPI document exposes matching endpoints for pull diffs, issue comments, repository issues, issue creation, labels, and repository metadata. The implementation uses those endpoints directly and keeps unsupported GitHub-only behaviors explicit.

Important Implementation Details

Relevant Diff Snippets

Rendered with Diffs server-side rendering via @pierre/diffs/ssr and preloadPatchFile, following diffs.com/docs. The saved document contains static diff markup and does not need JavaScript, a CDN, or remote modules to be readable.

README.md
-5+38
73 unmodified lines
74
75
76
77
78
79
80
81
35 unmodified lines
117
118
119
120
121
122
5 unmodified lines
128
129
130
131
132
133
134
135
136
137
138
29 unmodified lines
168
169
170
171
172
173
174
175
176
177
178
73 unmodified lines
- Repository discovery from local Git remotes.
- Default branch discovery through `origin/HEAD`.
- Current branch and upstream tracking for branch status, ahead/behind counts, and commit or push UI.
- Repository metadata through `gh repo view`.
- Pull request creation, listing, viewing, and current-branch status through `gh pr ...`.
- GUI-launched macOS tools that need a usable PATH to find the shim and the real `gh`.
- Forgejo auth discovery from environment variables or common `fj`, `tea`, and `gitea` config files.
35 unmodified lines
git status --short --branch
gh repo view --json nameWithOwner,url,defaultBranchRef,sshUrl
gh pr status --json number,title,url,headRefName,state
```
`gfj bootstrap` checks these same basics and prints the matching commands when something is missing.
5 unmodified lines
Only these commands are routed for allowlisted Forgejo repositories:
```sh
gh pr create
gh pr list
gh pr new
gh pr status
gh pr view
gh repo view
```
29 unmodified lines
statusCheckRollup
```
`gh repo view --json ...` supports a small repository metadata subset:
```text
description, defaultBranchRef, isPrivate, name, nameWithOwner,
owner, sshUrl, url
```
`gh pr status --json ...` follows the GitHub CLI status envelope:
73 unmodified lines
74
75
76
77
78
79
80
81
82
35 unmodified lines
118
119
120
121
122
123
124
5 unmodified lines
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
29 unmodified lines
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
73 unmodified lines
- Repository discovery from local Git remotes.
- Default branch discovery through `origin/HEAD`.
- Current branch and upstream tracking for branch status, ahead/behind counts, and commit or push UI.
- Repository metadata through `gh repo view`, including a broad set of GitHub-shaped JSON fields.
- Pull request creation, listing, viewing, current-branch status, diffs, comments, checks, and checkout through `gh pr ...`.
- Basic issue listing, viewing, and creation through `gh issue ...`.
- GUI-launched macOS tools that need a usable PATH to find the shim and the real `gh`.
- Forgejo auth discovery from environment variables or common `fj`, `tea`, and `gitea` config files.
35 unmodified lines
git status --short --branch
gh repo view --json nameWithOwner,url,defaultBranchRef,sshUrl
gh pr status --json number,title,url,headRefName,state
gh issue list --json number,title,state,url
```
`gfj bootstrap` checks these same basics and prints the matching commands when something is missing.
5 unmodified lines
Only these commands are routed for allowlisted Forgejo repositories:
```sh
gh pr checks
gh pr checkout
gh pr comment
gh pr create
gh pr diff
gh pr list
gh pr new
gh pr status
gh pr view
gh issue create
gh issue list
gh issue new
gh issue view
gh repo view
```
29 unmodified lines
statusCheckRollup
```
`gh issue list --json ...` and `gh issue view --json ...` support the common GitHub CLI issue fields:
```text
assignees, author, body, closed, closedAt,
closedByPullRequestsReferences, comments, createdAt, id, isPinned,
labels, milestone, number, projectCards, projectItems, reactionGroups,
state, stateReason, title, updatedAt, url
```
`gh repo view --json ...` supports the fields GitHub-oriented tools commonly probe:
```text
archivedAt, assignableUsers, codeOfConduct, contactLinks, createdAt,
defaultBranchRef, deleteBranchOnMerge, description, diskUsage, forkCount,
fundingLinks, hasDiscussionsEnabled, hasIssuesEnabled, hasProjectsEnabled,
hasWikiEnabled, homepageUrl, id, isArchived, isBlankIssuesEnabled,
isEmpty, isFork, isInOrganization, isMirror, isPrivate,
isSecurityPolicyEnabled, isTemplate, isUserConfigurationRepository,
issueTemplates, issues, labels, languages, latestRelease, licenseInfo,
mentionableUsers, mergeCommitAllowed, milestones, mirrorUrl, name,
nameWithOwner, openGraphImageUrl, owner, parent, primaryLanguage,
projects, projectsV2, pullRequestTemplates, pullRequests, pushedAt,
rebaseMergeAllowed, repositoryTopics, securityPolicyUrl,
squashMergeAllowed, sshUrl, stargazerCount, templateRepository,
updatedAt, url, usesCustomOpenGraphImage, viewerCanAdminister,
viewerDefaultCommitEmail, viewerDefaultMergeMethod, viewerHasStarred,
viewerPermission, viewerPossibleCommitEmails, viewerSubscription,
visibility, watchers
```
`gh pr status --json ...` follows the GitHub CLI status envelope:
src/gh_forgejo_shim/external.py
+16
84 unmodified lines
85
86
87
84 unmodified lines
return None
value = completed.stdout.strip()
return value or None
84 unmodified lines
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
84 unmodified lines
return None
value = completed.stdout.strip()
return value or None
def git_run(args: list[str], *, cwd: str | None = None) -> tuple[int, str]:
try:
completed = subprocess.run(
["git", *args],
cwd=cwd,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
except OSError as exc:
return 127, str(exc)
message = completed.stderr.strip() or completed.stdout.strip()
return completed.returncode, message
src/gh_forgejo_shim/forgejo.py
-7+104
53 unmodified lines
54
55
56
57
58
59
60
61
62
19 unmodified lines
82
83
84
85
86
87
88
89
90
10 unmodified lines
101
102
103
104
105
106
107
108
109
110
111
112
53 unmodified lines
def get_pull(self, repo: RepoRef, number: int) -> dict[str, Any]:
return self._request_json("GET", f"{repo.api_base_url}/pulls/{number}", None)
def get_repo(self, repo: RepoRef) -> dict[str, Any]:
return self._request_json("GET", repo.api_base_url, None)
def list_pulls(
self,
repo: RepoRef,
19 unmodified lines
url: str,
payload: dict[str, Any] | None,
) -> Any:
data = None if payload is None else json.dumps(payload).encode("utf-8")
headers = {
"Accept": "application/json",
"User-Agent": "gh-forgejo-shim",
}
if data is not None:
10 unmodified lines
except urllib.error.URLError as exc:
raise ForgejoError(f"Forgejo API request failed: {exc.reason}") from exc
if not response_data:
return {}
try:
return json.loads(response_data.decode("utf-8"))
except json.JSONDecodeError as exc:
raise ForgejoError("Forgejo API returned invalid JSON") from exc
def _quote(value: str) -> str:
53 unmodified lines
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
19 unmodified lines
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
10 unmodified lines
203
204
205
206
207
208
209
53 unmodified lines
def get_pull(self, repo: RepoRef, number: int) -> dict[str, Any]:
return self._request_json("GET", f"{repo.api_base_url}/pulls/{number}", None)
def get_pull_diff(self, repo: RepoRef, number: int, *, patch: bool = False) -> str:
diff_type = "patch" if patch else "diff"
return self._request_text("GET", f"{repo.api_base_url}/pulls/{number}.{diff_type}", None)
def list_pull_files(self, repo: RepoRef, number: int) -> list[dict[str, Any]]:
files = self._request_json("GET", f"{repo.api_base_url}/pulls/{number}/files", None)
if not isinstance(files, list):
return []
return [item for item in files if isinstance(item, dict)]
def get_repo(self, repo: RepoRef) -> dict[str, Any]:
return self._request_json("GET", repo.api_base_url, None)
def list_issues(
self,
repo: RepoRef,
*,
state: str = "open",
labels: tuple[str, ...] = (),
query: str | None = None,
milestone: str | None = None,
author: str | None = None,
assignee: str | None = None,
mentioned: str | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
params: dict[str, object] = {"state": state, "type": "issues"}
if labels:
params["labels"] = ",".join(labels)
if query:
params["q"] = query
if milestone:
params["milestones"] = milestone
if author and author != "@me":
params["created_by"] = author
if assignee and assignee != "@me":
params["assigned_by"] = assignee
if mentioned and mentioned != "@me":
params["mentioned_by"] = mentioned
if limit is not None:
params["limit"] = limit
query_string = urllib.parse.urlencode(params)
issues = self._request_json("GET", f"{repo.api_base_url}/issues?{query_string}", None)
if not isinstance(issues, list):
return []
return [item for item in issues if isinstance(item, dict)]
def get_issue(self, repo: RepoRef, number: int) -> dict[str, Any]:
return self._request_json("GET", f"{repo.api_base_url}/issues/{number}", None)
def list_labels(self, repo: RepoRef) -> list[dict[str, Any]]:
labels = self._request_json("GET", f"{repo.api_base_url}/labels", None)
if not isinstance(labels, list):
return []
return [item for item in labels if isinstance(item, dict)]
def create_issue(
self,
repo: RepoRef,
*,
title: str,
body: str = "",
assignees: tuple[str, ...] = (),
labels: tuple[int, ...] = (),
milestone: int | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"title": title,
"body": body,
}
if assignees:
payload["assignees"] = list(assignees)
if labels:
payload["labels"] = list(labels)
if milestone is not None:
payload["milestone"] = milestone
return self._request_json("POST", f"{repo.api_base_url}/issues", payload)
def create_issue_comment(self, repo: RepoRef, number: int, *, body: str) -> dict[str, Any]:
return self._request_json("POST", f"{repo.api_base_url}/issues/{number}/comments", {"body": body})
def list_pulls(
self,
repo: RepoRef,
19 unmodified lines
url: str,
payload: dict[str, Any] | None,
) -> Any:
response_data = self._request(method, url, payload, accept="application/json")
if not response_data:
return {}
try:
return json.loads(response_data.decode("utf-8"))
except json.JSONDecodeError as exc:
raise ForgejoError("Forgejo API returned invalid JSON") from exc
def _request_text(
self,
method: str,
url: str,
payload: dict[str, Any] | None,
) -> str:
return self._request(method, url, payload, accept="text/plain").decode("utf-8", errors="replace")
def _request(
self,
method: str,
url: str,
payload: dict[str, Any] | None,
*,
accept: str,
) -> bytes:
data = None if payload is None else json.dumps(payload).encode("utf-8")
headers = {
"Accept": accept,
"User-Agent": "gh-forgejo-shim",
}
if data is not None:
10 unmodified lines
except urllib.error.URLError as exc:
raise ForgejoError(f"Forgejo API request failed: {exc.reason}") from exc
return response_data
def _quote(value: str) -> str:
src/gh_forgejo_shim/normalize.py
-2+267
22 unmodified lines
23
24
25
26
27
28
29
30
31
32
33
34
35
68 unmodified lines
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
3 unmodified lines
125
126
127
128
129
130
4 unmodified lines
135
136
137
22 unmodified lines
)
SUPPORTED_REPO_JSON_FIELDS = (
"description",
"defaultBranchRef",
"isPrivate",
"name",
"nameWithOwner",
"owner",
"sshUrl",
"url",
)
68 unmodified lines
owner_login = owner.get("login") or owner.get("username") or getattr(fallback, "owner")
name = repo.get("name") or getattr(fallback, "repo")
default_branch = repo.get("default_branch")
return {
"description": repo.get("description"),
"defaultBranchRef": {"name": default_branch} if default_branch else None,
"isPrivate": bool(repo.get("private", False)),
"name": name,
"nameWithOwner": repo.get("full_name") or f"{owner_login}/{name}",
"owner": {
"login": owner_login,
"type": owner.get("type"),
},
"sshUrl": repo.get("ssh_url"),
"url": repo.get("html_url") or getattr(fallback, "web_base_url"),
}
3 unmodified lines
return {field: data.get(field) for field in fields if field in SUPPORTED_REPO_JSON_FIELDS}
def status_for_current_branch(
pull: dict[str, Any] | None,
fields: tuple[str, ...],
4 unmodified lines
"createdBy": [],
"needsReview": [],
}
22 unmodified lines
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
68 unmodified lines
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
3 unmodified lines
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
4 unmodified lines
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
22 unmodified lines
)
SUPPORTED_REPO_JSON_FIELDS = (
"archivedAt",
"assignableUsers",
"codeOfConduct",
"contactLinks",
"createdAt",
"defaultBranchRef",
"deleteBranchOnMerge",
"description",
"diskUsage",
"forkCount",
"fundingLinks",
"hasDiscussionsEnabled",
"hasIssuesEnabled",
"hasProjectsEnabled",
"hasWikiEnabled",
"homepageUrl",
"id",
"isArchived",
"isBlankIssuesEnabled",
"isEmpty",
"isFork",
"isInOrganization",
"isMirror",
"isPrivate",
"isSecurityPolicyEnabled",
"isTemplate",
"isUserConfigurationRepository",
"issueTemplates",
"issues",
"labels",
"languages",
"latestRelease",
"licenseInfo",
"mentionableUsers",
"mergeCommitAllowed",
"milestones",
"mirrorUrl",
"name",
"nameWithOwner",
"openGraphImageUrl",
"owner",
"parent",
"primaryLanguage",
"projects",
"projectsV2",
"pullRequestTemplates",
"pullRequests",
"pushedAt",
"rebaseMergeAllowed",
"repositoryTopics",
"securityPolicyUrl",
"squashMergeAllowed",
"sshUrl",
"stargazerCount",
"templateRepository",
"updatedAt",
"url",
"usesCustomOpenGraphImage",
"viewerCanAdminister",
"viewerDefaultCommitEmail",
"viewerDefaultMergeMethod",
"viewerHasStarred",
"viewerPermission",
"viewerPossibleCommitEmails",
"viewerSubscription",
"visibility",
"watchers",
)
SUPPORTED_ISSUE_JSON_FIELDS = (
"assignees",
"author",
"body",
"closed",
"closedAt",
"closedByPullRequestsReferences",
"comments",
"createdAt",
"id",
"isPinned",
"labels",
"milestone",
"number",
"projectCards",
"projectItems",
"reactionGroups",
"state",
"stateReason",
"title",
"updatedAt",
"url",
)
68 unmodified lines
owner_login = owner.get("login") or owner.get("username") or getattr(fallback, "owner")
name = repo.get("name") or getattr(fallback, "repo")
default_branch = repo.get("default_branch")
language = repo.get("language")
topics = repo.get("topics") if isinstance(repo.get("topics"), list) else []
permissions = repo.get("permissions") if isinstance(repo.get("permissions"), dict) else {}
is_private = bool(repo.get("private", False))
is_internal = bool(repo.get("internal", False))
return {
"archivedAt": repo.get("archived_at"),
"assignableUsers": [],
"codeOfConduct": None,
"contactLinks": [],
"createdAt": repo.get("created_at"),
"description": repo.get("description"),
"defaultBranchRef": {"name": default_branch} if default_branch else None,
"deleteBranchOnMerge": bool(repo.get("default_delete_branch_after_merge", False)),
"diskUsage": _normalize_count(repo.get("size")),
"forkCount": _normalize_count(repo.get("forks_count")),
"fundingLinks": [],
"hasDiscussionsEnabled": False,
"hasIssuesEnabled": bool(repo.get("has_issues", False)),
"hasProjectsEnabled": bool(repo.get("has_projects", False)),
"hasWikiEnabled": bool(repo.get("has_wiki", False)),
"homepageUrl": repo.get("website") or None,
"id": repo.get("id"),
"isArchived": bool(repo.get("archived", False)),
"isBlankIssuesEnabled": bool(repo.get("has_issues", False)),
"isEmpty": bool(repo.get("empty", False)),
"isFork": bool(repo.get("fork", False)),
"isInOrganization": _is_organization(owner),
"isMirror": bool(repo.get("mirror", False)),
"isPrivate": is_private,
"isSecurityPolicyEnabled": False,
"isTemplate": bool(repo.get("template", False)),
"isUserConfigurationRepository": False,
"issueTemplates": [],
"issues": _connection(_normalize_count(repo.get("open_issues_count"))),
"labels": _connection(0),
"languages": {
"nodes": [{"name": language}] if isinstance(language, str) and language else [],
"totalSize": 0,
},
"latestRelease": None,
"licenseInfo": None,
"mentionableUsers": [],
"mergeCommitAllowed": bool(repo.get("allow_merge_commits", False)),
"milestones": _connection(0),
"mirrorUrl": repo.get("original_url") or None,
"name": name,
"nameWithOwner": repo.get("full_name") or f"{owner_login}/{name}",
"openGraphImageUrl": repo.get("avatar_url"),
"owner": {
"login": owner_login,
"type": owner.get("type"),
},
"parent": _normalize_parent(repo.get("parent")),
"primaryLanguage": {"name": language} if isinstance(language, str) and language else None,
"projects": _connection(0),
"projectsV2": _connection(0),
"pullRequestTemplates": [],
"pullRequests": _connection(_normalize_count(repo.get("open_pr_counter"))),
"pushedAt": repo.get("updated_at"),
"rebaseMergeAllowed": bool(repo.get("allow_rebase", False)),
"repositoryTopics": {
"nodes": [{"topic": {"name": topic}} for topic in topics if isinstance(topic, str)],
"totalCount": len([topic for topic in topics if isinstance(topic, str)]),
},
"securityPolicyUrl": None,
"squashMergeAllowed": bool(repo.get("allow_squash_merge", False)),
"sshUrl": repo.get("ssh_url"),
"stargazerCount": _normalize_count(repo.get("stars_count")),
"templateRepository": None,
"updatedAt": repo.get("updated_at"),
"url": repo.get("html_url") or getattr(fallback, "web_base_url"),
"usesCustomOpenGraphImage": False,
"viewerCanAdminister": bool(permissions.get("admin", False)),
"viewerDefaultCommitEmail": None,
"viewerDefaultMergeMethod": repo.get("default_merge_style"),
"viewerHasStarred": False,
"viewerPermission": _viewer_permission(permissions),
"viewerPossibleCommitEmails": [],
"viewerSubscription": None,
"visibility": _visibility(is_private=is_private, is_internal=is_internal),
"watchers": _connection(_normalize_count(repo.get("watchers_count"))),
}
3 unmodified lines
return {field: data.get(field) for field in fields if field in SUPPORTED_REPO_JSON_FIELDS}
def normalize_issue(issue: dict[str, Any]) -> dict[str, Any]:
user = issue.get("user") if isinstance(issue.get("user"), dict) else {}
milestone = issue.get("milestone") if isinstance(issue.get("milestone"), dict) else None
state = str(issue.get("state") or "").upper() or None
closed = state == "CLOSED"
return {
"assignees": [_normalize_user(item) for item in _list_of_dicts(issue.get("assignees"))],
"author": _normalize_user(user),
"body": issue.get("body") or "",
"closed": closed,
"closedAt": issue.get("closed_at"),
"closedByPullRequestsReferences": [],
"comments": _normalize_count(issue.get("comments")),
"createdAt": issue.get("created_at"),
"id": issue.get("id"),
"isPinned": _normalize_count(issue.get("pin_order")) > 0,
"labels": [_normalize_label(item) for item in _list_of_dicts(issue.get("labels"))],
"milestone": _normalize_milestone(milestone),
"number": issue.get("number") or issue.get("id"),
"projectCards": [],
"projectItems": [],
"reactionGroups": [],
"state": state,
"stateReason": None,
"title": issue.get("title"),
"updatedAt": issue.get("updated_at"),
"url": issue.get("html_url") or issue.get("url"),
}
def filter_issue_fields(data: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]:
if not fields:
return data
return {field: data.get(field) for field in fields if field in SUPPORTED_ISSUE_JSON_FIELDS}
def status_for_current_branch(
pull: dict[str, Any] | None,
fields: tuple[str, ...],
4 unmodified lines
"createdBy": [],
"needsReview": [],
}
def _connection(total_count: int, nodes: list[dict[str, Any]] | None = None) -> dict[str, Any]:
return {
"nodes": [] if nodes is None else nodes,
"totalCount": total_count,
}
def _is_organization(owner: dict[str, Any]) -> bool:
owner_type = str(owner.get("type") or "").lower()
return owner_type in {"organization", "org"}
def _normalize_parent(parent: Any) -> dict[str, Any] | None:
if not isinstance(parent, dict):
return None
owner = parent.get("owner") if isinstance(parent.get("owner"), dict) else {}
name = parent.get("name")
owner_login = owner.get("login") or owner.get("username")
name_with_owner = parent.get("full_name")
if not name_with_owner and owner_login and name:
name_with_owner = f"{owner_login}/{name}"
return {
"name": name,
"nameWithOwner": name_with_owner,
"url": parent.get("html_url") or parent.get("url"),
}
def _viewer_permission(permissions: dict[str, Any]) -> str | None:
if permissions.get("admin"):
return "ADMIN"
if permissions.get("push"):
return "WRITE"
if permissions.get("pull"):
return "READ"
return None
def _visibility(*, is_private: bool, is_internal: bool) -> str:
if is_internal:
return "INTERNAL"
return "PRIVATE" if is_private else "PUBLIC"
def _normalize_user(user: dict[str, Any]) -> dict[str, Any]:
return {
"login": user.get("login") or user.get("username"),
"name": user.get("full_name") or user.get("name"),
}
def _normalize_label(label: dict[str, Any]) -> dict[str, Any]:
return {
"color": label.get("color"),
"description": label.get("description"),
"id": label.get("id"),
"name": label.get("name"),
}
def _normalize_milestone(milestone: dict[str, Any] | None) -> dict[str, Any] | None:
if milestone is None:
return None
return {
"number": milestone.get("id") or milestone.get("number"),
"title": milestone.get("title"),
"state": str(milestone.get("state") or "").upper() or None,
}
def _list_of_dicts(value: Any) -> list[dict[str, Any]]:
if not isinstance(value, list):
return []
return [item for item in value if isinstance(item, dict)]
src/gh_forgejo_shim/repo.py
+15
25 unmodified lines
26
27
28
29
30
31
27 unmodified lines
59
60
61
62
63
64
43 unmodified lines
108
109
110
111
112
113
25 unmodified lines
if parsed.scheme in {"http", "https", "ssh", "git"} and parsed.netloc:
host = parsed.hostname or parsed.netloc.split("@")[-1]
parts = _path_parts(parsed.path)
if len(parts) >= 2:
return RepoRef(normalize_host(host), parts[-2], _strip_git(parts[-1]))
return None
27 unmodified lines
if repo:
return Detection(repo, "-R/--repo")
gh_repo = values.get("GH_REPO")
if gh_repo:
repo = parse_repo_spec(gh_repo, default_host=values.get("GH_HOST"))
43 unmodified lines
return None
def current_branch(*, cwd: str | None = None) -> str | None:
return git_output(["branch", "--show-current"], cwd=cwd)
25 unmodified lines
26
27
28
29
30
31
32
33
27 unmodified lines
61
62
63
64
65
66
67
68
69
70
71
72
43 unmodified lines
116
117
118
119
120
121
122
123
124
125
126
127
128
25 unmodified lines
if parsed.scheme in {"http", "https", "ssh", "git"} and parsed.netloc:
host = parsed.hostname or parsed.netloc.split("@")[-1]
parts = _path_parts(parsed.path)
if len(parts) >= 4 and parts[2] in {"issue", "issues", "pull", "pulls"}:
return RepoRef(normalize_host(host), parts[0], _strip_git(parts[1]))
if len(parts) >= 2:
return RepoRef(normalize_host(host), parts[-2], _strip_git(parts[-1]))
return None
27 unmodified lines
if repo:
return Detection(repo, "-R/--repo")
url_repo = extract_repo_url_arg(argv)
if url_repo:
repo = parse_repo_spec(url_repo, default_host=values.get("GH_HOST"))
if repo:
return Detection(repo, "command URL")
gh_repo = values.get("GH_REPO")
if gh_repo:
repo = parse_repo_spec(gh_repo, default_host=values.get("GH_HOST"))
43 unmodified lines
return None
def extract_repo_url_arg(argv: list[str]) -> str | None:
for arg in argv:
if urllib.parse.urlparse(arg).scheme in {"http", "https", "ssh", "git"}:
return arg
return None
def current_branch(*, cwd: str | None = None) -> str | None:
return git_output(["branch", "--show-current"], cwd=cwd)
src/gh_forgejo_shim/routing.py
-64+987
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
7 unmodified lines
28
29
30
31
32
33
34
12 unmodified lines
47
48
49
50
51
52
73 unmodified lines
126
127
128
129
130
131
13 unmodified lines
145
146
147
148
149
150
20 unmodified lines
171
172
173
174
175
176
89 unmodified lines
266
267
268
269
270
271
84 unmodified lines
356
357
358
359
360
361
34 unmodified lines
396
397
398
399
400
401
124 unmodified lines
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
4 unmodified lines
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
1 unmodified line
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
2 unmodified lines
654
655
656
657
658
659
9 unmodified lines
669
670
671
672
673
674
62 unmodified lines
737
738
739
from __future__ import annotations
import json
import os
import sys
import webbrowser
from dataclasses import dataclass
from typing import Callable, Mapping, TextIO
from .auth import discover_fj_token
from .config import Config, load_config
from .create import CreateParseError, parse_create_args
from .external import find_program, run_program
from .forgejo import ForgejoClient, ForgejoError, RepoRef
from .normalize import (
filter_fields,
filter_repo_fields,
normalize_pull,
normalize_repo,
status_for_current_branch,
7 unmodified lines
parse_repo_spec,
)
SUPPORTED_PR_COMMANDS = {"checks", "create", "list", "new", "status", "view"}
SUPPORTED_REPO_COMMANDS = {"view"}
12 unmodified lines
return False
if argv[0] == "pr":
return argv[1] in SUPPORTED_PR_COMMANDS
if argv[0] == "repo":
return argv[1] in SUPPORTED_REPO_COMMANDS
return False
73 unmodified lines
) -> int:
if argv[0] == "repo":
return run_forgejo_repo(argv, repo, client, stdout=stdout, stderr=stderr)
return run_forgejo_pr(argv, repo, client, cwd=cwd, stdout=stdout, stderr=stderr, stdin=stdin)
13 unmodified lines
return _run_create(rest, repo, client, cwd=cwd, stdout=stdout, stdin=stdin)
if command == "checks":
return _run_checks(rest, stdout=stdout)
if command == "list":
return _run_list(rest, repo, client, stdout=stdout)
if command == "view":
20 unmodified lines
return 1
def _run_create(
argv: list[str],
repo: RepoRef,
89 unmodified lines
return 0
def _run_view(
argv: list[str],
repo: RepoRef,
84 unmodified lines
return 0
@dataclass(frozen=True)
class ViewStatusArgs:
json_fields: tuple[str, ...] = ()
34 unmodified lines
number: int | None = None
def _parse_list_args(argv: list[str]) -> ListArgs:
json_fields: tuple[str, ...] = ()
repo = None
124 unmodified lines
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--watch", "--fail-fast", "--required"}:
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR checks flag: {arg}")
else:
if arg.isdigit():
number = int(arg)
index += 1
return ChecksArgs(json_fields=json_fields, repo=repo, jq=jq, number=number)
def _parse_view_status_args(argv: list[str]) -> ViewStatusArgs:
json_fields: tuple[str, ...] = ()
repo = None
web = False
jq = None
template = None
number = None
branch = None
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
4 unmodified lines
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR flag: {arg}")
else:
if arg.isdigit():
number = int(arg)
else:
branch = arg
index += 1
return ViewStatusArgs(
json_fields=json_fields,
repo=repo,
web=web,
jq=jq,
template=template,
number=number,
branch=branch,
)
def _parse_repo_view_args(argv: list[str]) -> RepoViewArgs:
json_fields: tuple[str, ...] = ()
repo = None
web = False
jq = None
template = None
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
1 unmodified line
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo repo view flag: {arg}")
else:
2 unmodified lines
return RepoViewArgs(json_fields=json_fields, repo=repo, web=web, jq=jq, template=template)
def _format_pull_text(data: dict[str, object]) -> str:
number = data.get("number")
title = data.get("title") or ""
9 unmodified lines
return f"{number}\t{title}\t{branch}".rstrip()
def _print_json_or_jq(data: dict[str, object], jq: str | None, stdout: TextIO) -> None:
if jq:
value = _apply_simple_jq(data, jq)
62 unmodified lines
if normalized not in {"open", "closed", "merged", "all"}:
raise ValueError("--state must be one of: open, closed, merged, all")
return normalized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
7 unmodified lines
32
33
34
35
36
37
38
39
12 unmodified lines
52
53
54
55
56
57
58
59
73 unmodified lines
133
134
135
136
137
138
139
140
13 unmodified lines
154
155
156
157
158
159
160
161
162
163
164
165
20 unmodified lines
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
89 unmodified lines
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
84 unmodified lines
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
34 unmodified lines
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
124 unmodified lines
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
4 unmodified lines
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
1 unmodified line
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
2 unmodified lines
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
9 unmodified lines
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
62 unmodified lines
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
from __future__ import annotations
import fnmatch
import json
import os
import sys
import urllib.parse
import webbrowser
from dataclasses import dataclass
from typing import Callable, Mapping, TextIO
from .auth import discover_fj_token
from .config import Config, load_config
from .create import CreateParseError, body_from_file, parse_create_args
from .external import find_program, git_run, run_program
from .forgejo import ForgejoClient, ForgejoError, RepoRef
from .normalize import (
filter_issue_fields,
filter_fields,
filter_repo_fields,
normalize_issue,
normalize_pull,
normalize_repo,
status_for_current_branch,
7 unmodified lines
parse_repo_spec,
)
SUPPORTED_PR_COMMANDS = {"checks", "checkout", "co", "comment", "create", "diff", "list", "new", "status", "view"}
SUPPORTED_ISSUE_COMMANDS = {"create", "list", "ls", "new", "view"}
SUPPORTED_REPO_COMMANDS = {"view"}
12 unmodified lines
return False
if argv[0] == "pr":
return argv[1] in SUPPORTED_PR_COMMANDS
if argv[0] == "issue":
return argv[1] in SUPPORTED_ISSUE_COMMANDS
if argv[0] == "repo":
return argv[1] in SUPPORTED_REPO_COMMANDS
return False
73 unmodified lines
) -> int:
if argv[0] == "repo":
return run_forgejo_repo(argv, repo, client, stdout=stdout, stderr=stderr)
if argv[0] == "issue":
return run_forgejo_issue(argv, repo, client, stdout=stdout, stderr=stderr, stdin=stdin)
return run_forgejo_pr(argv, repo, client, cwd=cwd, stdout=stdout, stderr=stderr, stdin=stdin)
13 unmodified lines
return _run_create(rest, repo, client, cwd=cwd, stdout=stdout, stdin=stdin)
if command == "checks":
return _run_checks(rest, stdout=stdout)
if command in {"checkout", "co"}:
return _run_checkout(rest, repo, client, cwd=cwd, stdout=stdout, stderr=stderr)
if command == "comment":
return _run_pr_comment(rest, repo, client, cwd=cwd, stdout=stdout, stdin=stdin)
if command == "diff":
return _run_diff(rest, repo, client, cwd=cwd, stdout=stdout)
if command == "list":
return _run_list(rest, repo, client, stdout=stdout)
if command == "view":
20 unmodified lines
return 1
def run_forgejo_issue(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
stdout: TextIO,
stderr: TextIO,
stdin: TextIO | None = None,
) -> int:
command = argv[1]
rest = argv[2:]
if command in {"create", "new"}:
return _run_issue_create(rest, repo, client, stdout=stdout, stdin=stdin)
if command in {"list", "ls"}:
return _run_issue_list(rest, repo, client, stdout=stdout)
if command == "view":
return _run_issue_view(rest, repo, client, stdout=stdout)
print(f"gh-forgejo-shim: unsupported Forgejo issue command: {command}", file=stderr)
return 1
def _run_create(
argv: list[str],
repo: RepoRef,
89 unmodified lines
return 0
def _run_diff(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
cwd: str | None,
stdout: TextIO,
) -> int:
parsed = _parse_diff_args(argv)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
pull = _resolve_pull(target_repo, client, number=parsed.number, branch=parsed.branch, cwd=cwd)
if pull is None:
return 0
number = _pull_number(pull)
if number is None:
return 0
if parsed.web:
url = str(normalize_pull(pull).get("url") or f"{target_repo.web_base_url}/pulls/{number}") + "/files"
webbrowser.open(url)
print(url, file=stdout)
return 0
if parsed.name_only:
for name in _filtered_file_names(client.list_pull_files(target_repo, number), parsed.excludes):
print(name, file=stdout)
return 0
text = client.get_pull_diff(target_repo, number, patch=parsed.patch)
print(text, end="" if text.endswith("\n") else "\n", file=stdout)
return 0
def _run_pr_comment(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
cwd: str | None,
stdout: TextIO,
stdin: TextIO | None,
) -> int:
parsed = _parse_comment_args(argv, stdin=stdin)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
pull = _resolve_pull(target_repo, client, number=parsed.number, branch=parsed.branch, cwd=cwd)
if pull is None:
raise ValueError("could not find pull request to comment on")
number = _pull_number(pull)
if number is None:
raise ValueError("could not determine pull request number")
if parsed.web:
url = str(normalize_pull(pull).get("url") or f"{target_repo.web_base_url}/pulls/{number}") + "#new-comment"
webbrowser.open(url)
print(url, file=stdout)
return 0
if parsed.body is None:
raise ValueError("Forgejo PR comment requires --body or --body-file")
client.create_issue_comment(target_repo, number, body=parsed.body)
return 0
def _run_checkout(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
cwd: str | None,
stdout: TextIO,
stderr: TextIO,
) -> int:
parsed = _parse_checkout_args(argv)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
pull = _resolve_pull(target_repo, client, number=parsed.number, branch=parsed.branch, cwd=cwd)
if pull is None:
raise ValueError("could not find pull request to check out")
number = _pull_number(pull)
head_ref = _pull_head_ref(pull)
fetch_refs = []
if head_ref:
fetch_refs.append(head_ref)
if number is not None:
fetch_refs.append(f"refs/pull/{number}/head")
fetched = False
fetch_error = ""
for fetch_ref in dict.fromkeys(fetch_refs):
code, message = git_run(["fetch", "origin", fetch_ref], cwd=cwd)
if code == 0:
fetched = True
break
fetch_error = message
if not fetched:
print(fetch_error or "git fetch failed", file=stderr)
return 1
if parsed.detach:
code, message = git_run(["checkout", "--detach", "FETCH_HEAD"], cwd=cwd)
if code != 0:
print(message or "git checkout failed", file=stderr)
return code
print("checked out FETCH_HEAD", file=stdout)
return 0
branch = parsed.local_branch or head_ref or (f"pull-{number}" if number is not None else None)
if branch is None:
raise ValueError("could not determine local branch name")
if parsed.force:
checkout_args = ["checkout", "-B", branch, "FETCH_HEAD"]
else:
exists, _ = git_run(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=cwd)
checkout_args = ["checkout", branch] if exists == 0 else ["checkout", "-b", branch, "FETCH_HEAD"]
code, message = git_run(checkout_args, cwd=cwd)
if code != 0:
print(message or "git checkout failed", file=stderr)
return code
if parsed.recurse_submodules:
code, message = git_run(["submodule", "update", "--init", "--recursive"], cwd=cwd)
if code != 0:
print(message or "git submodule update failed", file=stderr)
return code
print(f"checked out {branch}", file=stdout)
return 0
def _run_view(
argv: list[str],
repo: RepoRef,
84 unmodified lines
return 0
def _run_issue_list(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
stdout: TextIO,
) -> int:
parsed = _parse_issue_list_args(argv)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
if parsed.web:
url = f"{target_repo.web_base_url}/issues"
webbrowser.open(url)
print(url, file=stdout)
return 0
issues = client.list_issues(
target_repo,
state=parsed.state,
labels=parsed.labels,
query=parsed.query,
milestone=parsed.milestone,
author=parsed.author,
assignee=parsed.assignee,
mentioned=parsed.mentioned,
limit=parsed.limit,
)
if parsed.limit is not None:
issues = issues[: parsed.limit]
normalized = [filter_issue_fields(normalize_issue(issue), parsed.json_fields) for issue in issues]
if parsed.json_fields:
_print_json_or_jq_list(normalized, parsed.jq, stdout)
else:
for issue in normalized:
print(_format_issue_list_item(issue), file=stdout)
return 0
def _run_issue_view(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
stdout: TextIO,
) -> int:
parsed = _parse_issue_view_args(argv)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
if parsed.number is None:
raise ValueError("Forgejo issue view requires an issue number or URL")
issue = client.get_issue(target_repo, parsed.number)
normalized = normalize_issue(issue)
if parsed.web:
url = str(normalized.get("url") or f"{target_repo.web_base_url}/issues/{parsed.number}")
webbrowser.open(url)
print(url, file=stdout)
return 0
if parsed.json_fields:
_print_json_or_jq(filter_issue_fields(normalized, parsed.json_fields), parsed.jq, stdout)
else:
print(_format_issue_text(normalized), file=stdout)
return 0
def _run_issue_create(
argv: list[str],
repo: RepoRef,
client: ForgejoClient,
*,
stdout: TextIO,
stdin: TextIO | None,
) -> int:
parsed = _parse_issue_create_args(argv, stdin=stdin)
target_repo = parse_repo_spec(parsed.repo, default_host=repo.host) if parsed.repo else repo
if target_repo is None:
raise ValueError("could not parse --repo value")
if parsed.web:
url = f"{target_repo.web_base_url}/issues/new"
webbrowser.open(url)
print(url, file=stdout)
return 0
if not parsed.title:
raise ValueError("Forgejo issue create requires --title")
issue = client.create_issue(
target_repo,
title=parsed.title,
body=parsed.body or "",
assignees=parsed.assignees,
labels=_resolve_label_ids(client, target_repo, parsed.labels),
milestone=parsed.milestone,
)
normalized = normalize_issue(issue)
print(normalized.get("url") or issue.get("html_url") or issue.get("url") or "", file=stdout)
return 0
@dataclass(frozen=True)
class ViewStatusArgs:
json_fields: tuple[str, ...] = ()
34 unmodified lines
number: int | None = None
@dataclass(frozen=True)
class DiffArgs:
repo: str | None = None
number: int | None = None
branch: str | None = None
web: bool = False
name_only: bool = False
patch: bool = False
excludes: tuple[str, ...] = ()
@dataclass(frozen=True)
class CommentArgs:
repo: str | None = None
number: int | None = None
branch: str | None = None
body: str | None = None
web: bool = False
@dataclass(frozen=True)
class CheckoutArgs:
repo: str | None = None
number: int | None = None
branch: str | None = None
local_branch: str | None = None
detach: bool = False
force: bool = False
recurse_submodules: bool = False
@dataclass(frozen=True)
class IssueListArgs:
json_fields: tuple[str, ...] = ()
repo: str | None = None
jq: str | None = None
template: str | None = None
state: str = "open"
limit: int | None = 30
labels: tuple[str, ...] = ()
query: str | None = None
author: str | None = None
assignee: str | None = None
mentioned: str | None = None
milestone: str | None = None
web: bool = False
@dataclass(frozen=True)
class IssueViewArgs:
json_fields: tuple[str, ...] = ()
repo: str | None = None
jq: str | None = None
template: str | None = None
number: int | None = None
web: bool = False
comments: bool = False
@dataclass(frozen=True)
class IssueCreateArgs:
title: str | None = None
body: str | None = None
repo: str | None = None
web: bool = False
assignees: tuple[str, ...] = ()
labels: tuple[str, ...] = ()
milestone: int | None = None
def _parse_list_args(argv: list[str]) -> ListArgs:
json_fields: tuple[str, ...] = ()
repo = None
124 unmodified lines
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t", "--interval", "-i"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
index += 2
elif arg.startswith(("--template=", "-t=", "--interval=", "-i=")):
index += 1
elif arg in {"--web", "-w"}:
index += 1
elif arg in {"--watch", "--fail-fast", "--required"}:
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR checks flag: {arg}")
else:
parsed_number, _ = _parse_number_or_branch(arg, kind="pull")
if parsed_number is not None:
number = parsed_number
index += 1
return ChecksArgs(json_fields=json_fields, repo=repo, jq=jq, number=number)
def _parse_diff_args(argv: list[str]) -> DiffArgs:
repo = None
number = None
branch = None
web = False
name_only = False
patch = False
excludes: list[str] = []
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
4 unmodified lines
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg == "--name-only":
name_only = True
index += 1
elif arg == "--patch":
patch = True
index += 1
elif arg == "--color":
if index + 1 >= len(argv):
raise ValueError("missing value for --color")
index += 2
elif arg.startswith("--color="):
index += 1
elif arg in {"--exclude", "-e"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
excludes.append(argv[index + 1])
index += 2
elif arg.startswith("--exclude=") or arg.startswith("-e="):
excludes.append(arg.split("=", 1)[1])
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR diff flag: {arg}")
else:
number, branch = _parse_number_or_branch(arg, kind="pull")
index += 1
return DiffArgs(repo=repo, number=number, branch=branch, web=web, name_only=name_only, patch=patch, excludes=tuple(excludes))
def _parse_comment_args(argv: list[str], *, stdin: TextIO | None = None) -> CommentArgs:
repo = None
number = None
branch = None
body = None
web = False
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
1 unmodified line
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--body", "-b"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
body = argv[index + 1]
index += 2
elif arg.startswith("--body=") or arg.startswith("-b="):
body = arg.split("=", 1)[1]
index += 1
elif arg in {"--body-file", "-F"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
body = body_from_file(argv[index + 1], stdin=stdin)
index += 2
elif arg.startswith("--body-file=") or arg.startswith("-F="):
body = body_from_file(arg.split("=", 1)[1], stdin=stdin)
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--create-if-none", "--delete-last", "--edit-last", "--editor", "-e", "--yes"}:
raise ValueError(f"unsupported Forgejo PR comment flag: {arg}")
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR comment flag: {arg}")
else:
number, branch = _parse_number_or_branch(arg, kind="pull")
index += 1
return CommentArgs(repo=repo, number=number, branch=branch, body=body, web=web)
def _parse_checkout_args(argv: list[str]) -> CheckoutArgs:
repo = None
number = None
branch = None
local_branch = None
detach = False
force = False
recurse_submodules = False
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--branch", "-b"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
local_branch = argv[index + 1]
index += 2
elif arg.startswith("--branch=") or arg.startswith("-b="):
local_branch = arg.split("=", 1)[1]
index += 1
elif arg == "--detach":
detach = True
index += 1
elif arg in {"--force", "-f"}:
force = True
index += 1
elif arg == "--recurse-submodules":
recurse_submodules = True
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR checkout flag: {arg}")
else:
number, branch = _parse_number_or_branch(arg, kind="pull")
index += 1
return CheckoutArgs(
repo=repo,
number=number,
branch=branch,
local_branch=local_branch,
detach=detach,
force=force,
recurse_submodules=recurse_submodules,
)
def _parse_view_status_args(argv: list[str]) -> ViewStatusArgs:
json_fields: tuple[str, ...] = ()
repo = None
web = False
jq = None
template = None
number = None
branch = None
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo PR flag: {arg}")
else:
number, branch = _parse_number_or_branch(arg, kind="pull")
index += 1
return ViewStatusArgs(
json_fields=json_fields,
repo=repo,
web=web,
jq=jq,
template=template,
number=number,
branch=branch,
)
def _parse_repo_view_args(argv: list[str]) -> RepoViewArgs:
json_fields: tuple[str, ...] = ()
repo = None
web = False
jq = None
template = None
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg in {"--branch", "-b"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
index += 2
elif arg.startswith("--branch=") or arg.startswith("-b="):
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo repo view flag: {arg}")
else:
2 unmodified lines
return RepoViewArgs(json_fields=json_fields, repo=repo, web=web, jq=jq, template=template)
def _parse_issue_list_args(argv: list[str]) -> IssueListArgs:
json_fields: tuple[str, ...] = ()
repo = None
jq = None
template = None
state = "open"
limit: int | None = 30
labels: list[str] = []
query = None
author = None
assignee = None
mentioned = None
milestone = None
web = False
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg in {"--state", "-s"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
state = _normalize_issue_state(argv[index + 1])
index += 2
elif arg.startswith("--state=") or arg.startswith("-s="):
state = _normalize_issue_state(arg.split("=", 1)[1])
index += 1
elif arg in {"--limit", "-L"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
limit = _parse_limit(argv[index + 1])
index += 2
elif arg.startswith("--limit=") or arg.startswith("-L="):
limit = _parse_limit(arg.split("=", 1)[1])
index += 1
elif arg in {"--label", "-l"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
labels.extend(_split_label_values(argv[index + 1]))
index += 2
elif arg.startswith("--label=") or arg.startswith("-l="):
labels.extend(_split_label_values(arg.split("=", 1)[1]))
index += 1
elif arg in {"--search", "-S"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
query = argv[index + 1]
index += 2
elif arg.startswith("--search=") or arg.startswith("-S="):
query = arg.split("=", 1)[1]
index += 1
elif arg in {"--author", "-A"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
author = argv[index + 1]
index += 2
elif arg.startswith("--author=") or arg.startswith("-A="):
author = arg.split("=", 1)[1]
index += 1
elif arg in {"--assignee", "-a"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
assignee = argv[index + 1]
index += 2
elif arg.startswith("--assignee=") or arg.startswith("-a="):
assignee = arg.split("=", 1)[1]
index += 1
elif arg == "--mention":
if index + 1 >= len(argv):
raise ValueError("missing value for --mention")
mentioned = argv[index + 1]
index += 2
elif arg.startswith("--mention="):
mentioned = arg.split("=", 1)[1]
index += 1
elif arg in {"--milestone", "-m"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
milestone = argv[index + 1]
index += 2
elif arg.startswith("--milestone=") or arg.startswith("-m="):
milestone = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg == "--app":
if index + 1 >= len(argv):
raise ValueError("missing value for --app")
index += 2
elif arg.startswith("--app="):
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo issue list flag: {arg}")
else:
index += 1
return IssueListArgs(
json_fields=json_fields,
repo=repo,
jq=jq,
template=template,
state=state,
limit=limit,
labels=tuple(labels),
query=query,
author=author,
assignee=assignee,
mentioned=mentioned,
milestone=milestone,
web=web,
)
def _parse_issue_view_args(argv: list[str]) -> IssueViewArgs:
json_fields: tuple[str, ...] = ()
repo = None
jq = None
template = None
number = None
web = False
comments = False
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--json"}:
if index + 1 >= len(argv):
raise ValueError("missing value for --json")
json_fields = _split_fields(argv[index + 1])
index += 2
elif arg.startswith("--json="):
json_fields = _split_fields(arg.split("=", 1)[1])
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--jq", "-q"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
jq = argv[index + 1]
index += 2
elif arg.startswith("--jq=") or arg.startswith("-q="):
jq = arg.split("=", 1)[1]
index += 1
elif arg in {"--template", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
template = argv[index + 1]
index += 2
elif arg.startswith("--template=") or arg.startswith("-t="):
template = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--comments", "-c"}:
comments = True
index += 1
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo issue view flag: {arg}")
else:
parsed_number, _ = _parse_number_or_branch(arg, kind="issue")
number = parsed_number
index += 1
return IssueViewArgs(json_fields=json_fields, repo=repo, jq=jq, template=template, number=number, web=web, comments=comments)
def _parse_issue_create_args(argv: list[str], *, stdin: TextIO | None = None) -> IssueCreateArgs:
title = None
body = None
repo = None
web = False
assignees: list[str] = []
labels: list[str] = []
milestone = None
index = 0
while index < len(argv):
arg = argv[index]
if arg in {"--title", "-t"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
title = argv[index + 1]
index += 2
elif arg.startswith("--title=") or arg.startswith("-t="):
title = arg.split("=", 1)[1]
index += 1
elif arg in {"--body", "-b"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
body = argv[index + 1]
index += 2
elif arg.startswith("--body=") or arg.startswith("-b="):
body = arg.split("=", 1)[1]
index += 1
elif arg in {"--body-file", "-F"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
body = body_from_file(argv[index + 1], stdin=stdin)
index += 2
elif arg.startswith("--body-file=") or arg.startswith("-F="):
body = body_from_file(arg.split("=", 1)[1], stdin=stdin)
index += 1
elif arg in {"-R", "--repo"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
repo = argv[index + 1]
index += 2
elif arg.startswith("--repo="):
repo = arg.split("=", 1)[1]
index += 1
elif arg in {"--web", "-w"}:
web = True
index += 1
elif arg in {"--assignee", "-a"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
assignees.extend(_split_label_values(argv[index + 1]))
index += 2
elif arg.startswith("--assignee=") or arg.startswith("-a="):
assignees.extend(_split_label_values(arg.split("=", 1)[1]))
index += 1
elif arg in {"--label", "-l"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
labels.extend(_split_label_values(argv[index + 1]))
index += 2
elif arg.startswith("--label=") or arg.startswith("-l="):
labels.extend(_split_label_values(arg.split("=", 1)[1]))
index += 1
elif arg in {"--milestone", "-m"}:
if index + 1 >= len(argv):
raise ValueError(f"missing value for {arg}")
milestone = _optional_int(argv[index + 1])
index += 2
elif arg.startswith("--milestone=") or arg.startswith("-m="):
milestone = _optional_int(arg.split("=", 1)[1])
index += 1
elif arg in {"--editor", "-e", "--project", "-p", "--recover", "--template", "-T"}:
raise ValueError(f"unsupported Forgejo issue create flag: {arg}")
elif arg.startswith(("--project=", "-p=", "--recover=", "--template=", "-T=")):
raise ValueError(f"unsupported Forgejo issue create flag: {arg.split('=', 1)[0]}")
elif arg.startswith("-"):
raise ValueError(f"unsupported Forgejo issue create flag: {arg}")
else:
raise ValueError(f"unexpected positional argument for Forgejo issue create: {arg}")
return IssueCreateArgs(
title=title,
body=body,
repo=repo,
web=web,
assignees=tuple(assignee for assignee in assignees if assignee != "@me"),
labels=tuple(labels),
milestone=milestone,
)
def _format_pull_text(data: dict[str, object]) -> str:
number = data.get("number")
title = data.get("title") or ""
9 unmodified lines
return f"{number}\t{title}\t{branch}".rstrip()
def _format_issue_text(data: dict[str, object]) -> str:
number = data.get("number")
title = data.get("title") or ""
state = data.get("state") or "UNKNOWN"
url = data.get("url") or ""
body = data.get("body") or ""
return f"#{number} {title}\nstate: {state}\nurl: {url}\n\n{body}".rstrip()
def _format_issue_list_item(data: dict[str, object]) -> str:
number = data.get("number")
title = data.get("title") or ""
state = data.get("state") or ""
return f"{number}\t{title}\t{state}".rstrip()
def _print_json_or_jq(data: dict[str, object], jq: str | None, stdout: TextIO) -> None:
if jq:
value = _apply_simple_jq(data, jq)
62 unmodified lines
if normalized not in {"open", "closed", "merged", "all"}:
raise ValueError("--state must be one of: open, closed, merged, all")
return normalized
def _normalize_issue_state(value: str) -> str:
normalized = value.lower()
if normalized not in {"open", "closed", "all"}:
raise ValueError("--state must be one of: open, closed, all")
return normalized
def _split_label_values(value: str) -> list[str]:
return [item.strip() for item in value.split(",") if item.strip()]
def _optional_int(value: str) -> int | None:
try:
return int(value)
except ValueError:
return None
def _resolve_label_ids(client: ForgejoClient, repo: RepoRef, labels: tuple[str, ...]) -> tuple[int, ...]:
if not labels:
return ()
result: list[int] = []
unresolved = [label for label in labels if _optional_int(label) is None]
label_map: dict[str, int] = {}
if unresolved:
for label in client.list_labels(repo):
raw_name = label.get("name")
raw_id = label.get("id")
if isinstance(raw_name, str) and isinstance(raw_id, int):
label_map[raw_name] = raw_id
for label in labels:
parsed = _optional_int(label)
if parsed is not None:
result.append(parsed)
elif label in label_map:
result.append(label_map[label])
else:
raise ValueError(f"could not resolve Forgejo issue label: {label}")
return tuple(result)
def _parse_number_or_branch(value: str, *, kind: str) -> tuple[int | None, str | None]:
number = _number_from_url(value, kind=kind)
if number is not None:
return number, None
if value.isdigit():
return int(value), None
return None, value
def _number_from_url(value: str, *, kind: str) -> int | None:
parsed = urllib.parse.urlparse(value)
if parsed.scheme not in {"http", "https"}:
return None
parts = [part for part in parsed.path.strip("/").split("/") if part]
markers = ("pulls", "pull") if kind == "pull" else ("issues", "issue")
for index, part in enumerate(parts):
if part in markers and index + 1 < len(parts) and parts[index + 1].isdigit():
return int(parts[index + 1])
return None
def _resolve_pull(
repo: RepoRef,
client: ForgejoClient,
*,
number: int | None,
branch: str | None,
cwd: str | None,
) -> dict[str, object] | None:
if number is not None:
return client.get_pull(repo, number)
target_branch = branch or current_branch(cwd=cwd)
if not target_branch:
return None
pulls = client.list_pulls(repo, state="open", head=target_branch)
return pulls[0] if pulls else None
def _pull_number(pull: dict[str, object]) -> int | None:
raw = pull.get("number") or pull.get("id")
if isinstance(raw, bool):
return None
if isinstance(raw, int):
return raw
if isinstance(raw, str) and raw.isdigit():
return int(raw)
return None
def _pull_head_ref(pull: dict[str, object]) -> str | None:
head = pull.get("head")
if not isinstance(head, dict):
return None
ref = head.get("ref")
return ref if isinstance(ref, str) and ref else None
def _filtered_file_names(files: list[dict[str, object]], excludes: tuple[str, ...]) -> list[str]:
names = []
for item in files:
raw = item.get("filename") or item.get("name") or item.get("path")
if not isinstance(raw, str) or _matches_any(raw, excludes):
continue
names.append(raw)
return names
def _matches_any(value: str, patterns: tuple[str, ...]) -> bool:
return any(fnmatch.fnmatch(value, pattern) for pattern in patterns)
tests/test_repo.py
+12
38 unmodified lines
39
40
41
42
43
44
38 unmodified lines
def test_plain_owner_repo_without_default_host_is_unknown(self) -> None:
self.assertIsNone(parse_repo_spec("owner/repo"))
if __name__ == "__main__":
unittest.main()
38 unmodified lines
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
38 unmodified lines
def test_plain_owner_repo_without_default_host_is_unknown(self) -> None:
self.assertIsNone(parse_repo_spec("owner/repo"))
def test_web_pull_url_uses_repository_path_not_trailing_segments(self) -> None:
repo = parse_repo_spec("https://git.example.com/owner/repo/pulls/7")
self.assertIsNotNone(repo)
assert repo is not None
self.assertEqual((repo.host, repo.owner, repo.repo), ("git.example.com", "owner", "repo"))
def test_web_issue_url_uses_repository_path_not_trailing_segments(self) -> None:
repo = parse_repo_spec("https://git.example.com/owner/repo/issues/13")
self.assertIsNotNone(repo)
assert repo is not None
self.assertEqual((repo.host, repo.owner, repo.repo), ("git.example.com", "owner", "repo"))
if __name__ == "__main__":
unittest.main()
tests/test_routing.py
-2+319
11 unmodified lines
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
24 unmodified lines
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
219 unmodified lines
291
292
293
294
295
296
21 unmodified lines
318
319
320
321
322
323
110 unmodified lines
434
435
436
437
438
439
11 unmodified lines
class FakeClient(ForgejoClient):
def __init__(self, pulls: list[dict] | None = None) -> None:
super().__init__(None)
self.pulls = pulls or []
self.created: dict | None = None
self.repo_view = {
"name": "repo",
"full_name": "owner/repo",
"html_url": "https://git.example.com/owner/repo",
"ssh_url": "git@git.example.com:owner/repo.git",
"default_branch": "main",
"private": False,
"owner": {"login": "owner"},
}
24 unmodified lines
return pull
raise ValueError("not found")
def get_repo(self, repo: RepoRef): # type: ignore[no-untyped-def]
return self.repo_view
class RoutingTests(unittest.TestCase):
def test_delegates_non_pr_command(self) -> None:
decision = decide_route(
["issue", "list"],
config=Config(hosts=("git.example.com",)),
env={},
)
self.assertEqual(decision.kind, "delegate")
def test_routes_pr_list_for_allowlisted_host(self) -> None:
decision = decide_route(
["pr", "list", "-R", "git.example.com/owner/repo"],
219 unmodified lines
self.assertEqual(code, 0)
self.assertEqual(json.loads(out.getvalue()), [])
def test_repo_view_outputs_github_shaped_json(self) -> None:
out = io.StringIO()
code = run_forgejo(
21 unmodified lines
},
)
def test_no_current_branch_view_returns_empty_json_success(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
cwd = Path(tmp)
110 unmodified lines
subprocess.run(["git", *args], cwd=cwd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if __name__ == "__main__":
unittest.main()
11 unmodified lines
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
24 unmodified lines
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
219 unmodified lines
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
21 unmodified lines
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
110 unmodified lines
746
747
748
749
750
751
752
753
754
755
756
11 unmodified lines
class FakeClient(ForgejoClient):
def __init__(self, pulls: list[dict] | None = None, issues: list[dict] | None = None) -> None:
super().__init__(None)
self.pulls = pulls or []
self.issues = issues or []
self.created: dict | None = None
self.created_issue: dict | None = None
self.comments: list[dict] = []
self.diff_text = "diff --git a/README.md b/README.md\n"
self.pull_files = [{"filename": "README.md"}, {"filename": "generated/output.txt"}]
self.repo_view = {
"id": 99,
"name": "repo",
"full_name": "owner/repo",
"html_url": "https://git.example.com/owner/repo",
"ssh_url": "git@git.example.com:owner/repo.git",
"default_branch": "main",
"private": False,
"has_issues": True,
"has_projects": True,
"has_wiki": False,
"allow_merge_commits": True,
"allow_rebase": True,
"allow_squash_merge": True,
"forks_count": 2,
"stars_count": 3,
"watchers_count": 4,
"open_issues_count": 5,
"open_pr_counter": 6,
"language": "Python",
"permissions": {"pull": True, "push": True, "admin": False},
"owner": {"login": "owner"},
}
24 unmodified lines
return pull
raise ValueError("not found")
def get_pull_diff(self, repo: RepoRef, number: int, *, patch: bool = False): # type: ignore[no-untyped-def]
return self.diff_text
def list_pull_files(self, repo: RepoRef, number: int): # type: ignore[no-untyped-def]
return self.pull_files
def get_repo(self, repo: RepoRef): # type: ignore[no-untyped-def]
return self.repo_view
def list_issues(self, repo: RepoRef, **kwargs): # type: ignore[no-untyped-def]
return self.issues
def get_issue(self, repo: RepoRef, number: int): # type: ignore[no-untyped-def]
for issue in self.issues:
if issue.get("number") == number:
return issue
raise ValueError("not found")
def list_labels(self, repo: RepoRef): # type: ignore[no-untyped-def]
return [{"id": 2, "name": "bug"}, {"id": 3, "name": "help wanted"}]
def create_issue(self, repo: RepoRef, **kwargs): # type: ignore[no-untyped-def]
self.created_issue = {"repo": repo, **kwargs}
return {
"number": 14,
"title": kwargs["title"],
"body": kwargs.get("body", ""),
"state": "open",
"html_url": "https://git.example.com/owner/repo/issues/14",
"user": {"login": "alice"},
}
def create_issue_comment(self, repo: RepoRef, number: int, *, body: str): # type: ignore[no-untyped-def]
comment = {"repo": repo, "number": number, "body": body}
self.comments.append(comment)
return comment
class RoutingTests(unittest.TestCase):
def test_delegates_non_pr_command(self) -> None:
decision = decide_route(
["api", "repos/owner/repo"],
config=Config(hosts=("git.example.com",)),
env={},
)
self.assertEqual(decision.kind, "delegate")
def test_routes_issue_list_for_allowlisted_host(self) -> None:
decision = decide_route(
["issue", "list", "-R", "git.example.com/owner/repo"],
config=Config(hosts=("git.example.com",)),
env={},
)
self.assertEqual(decision.kind, "forgejo")
def test_routes_issue_view_url_for_allowlisted_host(self) -> None:
decision = decide_route(
["issue", "view", "https://git.example.com/owner/repo/issues/13"],
config=Config(hosts=("git.example.com",)),
env={},
)
self.assertEqual(decision.kind, "forgejo")
self.assertIsNotNone(decision.repo)
assert decision.repo is not None
self.assertEqual((decision.repo.owner, decision.repo.repo), ("owner", "repo"))
def test_routes_pr_list_for_allowlisted_host(self) -> None:
decision = decide_route(
["pr", "list", "-R", "git.example.com/owner/repo"],
219 unmodified lines
self.assertEqual(code, 0)
self.assertEqual(json.loads(out.getvalue()), [])
def test_pr_diff_outputs_forgejo_diff(self) -> None:
out = io.StringIO()
code = run_forgejo_pr(
["pr", "diff", "8"],
RepoRef("git.example.com", "owner", "repo"),
FakeClient(
[
{
"number": 8,
"title": "Make Codex happy",
"state": "open",
"html_url": "https://git.example.com/owner/repo/pulls/8",
"head": {"ref": "feature"},
}
]
),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertIn("diff --git", out.getvalue())
def test_pr_diff_name_only_filters_excluded_files(self) -> None:
out = io.StringIO()
code = run_forgejo_pr(
["pr", "diff", "8", "--name-only", "--exclude", "generated/*"],
RepoRef("git.example.com", "owner", "repo"),
FakeClient([{"number": 8, "head": {"ref": "feature"}}]),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(out.getvalue().splitlines(), ["README.md"])
def test_pr_comment_posts_body_to_issue_comments(self) -> None:
client = FakeClient([{"number": 8, "head": {"ref": "feature"}}])
out = io.StringIO()
code = run_forgejo_pr(
["pr", "comment", "8", "--body", "Looks good"],
RepoRef("git.example.com", "owner", "repo"),
client,
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(out.getvalue(), "")
self.assertEqual(client.comments[0]["number"], 8)
self.assertEqual(client.comments[0]["body"], "Looks good")
def test_pr_checkout_fetches_and_checks_out_head_branch(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
remote = root / "remote.git"
seed = root / "seed"
work = root / "work"
self._git(root, "init", "--bare", str(remote))
seed.mkdir()
self._git(seed, "init")
self._git(seed, "config", "user.email", "test@example.com")
self._git(seed, "config", "user.name", "Test User")
(seed / "README.md").write_text("main\n", encoding="utf-8")
self._git(seed, "add", "README.md")
self._git(seed, "commit", "-m", "initial")
self._git(seed, "branch", "-M", "main")
self._git(seed, "remote", "add", "origin", str(remote))
self._git(seed, "push", "-u", "origin", "main")
self._git(seed, "checkout", "-b", "feature")
(seed / "README.md").write_text("feature\n", encoding="utf-8")
self._git(seed, "commit", "-am", "feature")
self._git(seed, "push", "origin", "feature")
self._git(root, "--git-dir", str(remote), "symbolic-ref", "HEAD", "refs/heads/main")
self._git(root, "clone", str(remote), str(work))
self._git(work, "checkout", "main")
out = io.StringIO()
code = run_forgejo_pr(
["pr", "checkout", "8"],
RepoRef("git.example.com", "owner", "repo"),
FakeClient([{"number": 8, "head": {"ref": "feature"}}]),
cwd=str(work),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(self._git_output(work, "branch", "--show-current"), "feature")
def test_repo_view_outputs_github_shaped_json(self) -> None:
out = io.StringIO()
code = run_forgejo(
21 unmodified lines
},
)
def test_repo_view_outputs_richer_github_json_fields(self) -> None:
out = io.StringIO()
code = run_forgejo(
[
"repo",
"view",
"-R",
"git.example.com/owner/repo",
"--json",
"id,hasIssuesEnabled,hasProjectsEnabled,hasWikiEnabled,forkCount,stargazerCount,watchers,primaryLanguage,viewerPermission,visibility,pullRequests,issues,mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed",
],
RepoRef("git.example.com", "owner", "repo"),
FakeClient(),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(
json.loads(out.getvalue()),
{
"forkCount": 2,
"hasIssuesEnabled": True,
"hasProjectsEnabled": True,
"hasWikiEnabled": False,
"id": 99,
"issues": {"nodes": [], "totalCount": 5},
"mergeCommitAllowed": True,
"primaryLanguage": {"name": "Python"},
"pullRequests": {"nodes": [], "totalCount": 6},
"rebaseMergeAllowed": True,
"squashMergeAllowed": True,
"stargazerCount": 3,
"viewerPermission": "WRITE",
"visibility": "PUBLIC",
"watchers": {"nodes": [], "totalCount": 4},
},
)
def test_issue_list_outputs_github_shaped_json(self) -> None:
out = io.StringIO()
code = run_forgejo(
[
"issue",
"list",
"-R",
"git.example.com/owner/repo",
"--state",
"all",
"--json",
"number,title,state,url,author,comments",
],
RepoRef("git.example.com", "owner", "repo"),
FakeClient(
issues=[
{
"number": 13,
"title": "Fix it",
"state": "open",
"html_url": "https://git.example.com/owner/repo/issues/13",
"user": {"login": "alice"},
"comments": 2,
}
]
),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(
json.loads(out.getvalue()),
[
{
"author": {"login": "alice", "name": None},
"comments": 2,
"number": 13,
"state": "OPEN",
"title": "Fix it",
"url": "https://git.example.com/owner/repo/issues/13",
}
],
)
def test_issue_view_outputs_github_shaped_json(self) -> None:
out = io.StringIO()
code = run_forgejo(
[
"issue",
"view",
"13",
"-R",
"git.example.com/owner/repo",
"--json",
"number,title,body,state,closed",
],
RepoRef("git.example.com", "owner", "repo"),
FakeClient(
issues=[
{
"number": 13,
"title": "Fix it",
"body": "Details",
"state": "closed",
"html_url": "https://git.example.com/owner/repo/issues/13",
}
]
),
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertEqual(
json.loads(out.getvalue()),
{
"body": "Details",
"closed": True,
"number": 13,
"state": "CLOSED",
"title": "Fix it",
},
)
def test_issue_create_calls_forgejo_client(self) -> None:
client = FakeClient()
out = io.StringIO()
code = run_forgejo(
[
"issue",
"create",
"-R",
"git.example.com/owner/repo",
"--title",
"Bug",
"--body",
"It broke",
"--assignee",
"alice,bob",
"--label",
"bug,3",
],
RepoRef("git.example.com", "owner", "repo"),
client,
stdout=out,
stderr=io.StringIO(),
)
self.assertEqual(code, 0)
self.assertIsNotNone(client.created_issue)
assert client.created_issue is not None
self.assertEqual(client.created_issue["title"], "Bug")
self.assertEqual(client.created_issue["body"], "It broke")
self.assertEqual(client.created_issue["assignees"], ("alice", "bob"))
self.assertEqual(client.created_issue["labels"], (2, 3))
self.assertEqual(out.getvalue().strip(), "https://git.example.com/owner/repo/issues/14")
def test_no_current_branch_view_returns_empty_json_success(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
cwd = Path(tmp)
110 unmodified lines
subprocess.run(["git", *args], cwd=cwd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def _git_output(self, cwd: Path, *args: str) -> str:
import subprocess
return subprocess.check_output(["git", *args], cwd=cwd, text=True, stderr=subprocess.DEVNULL).strip()
if __name__ == "__main__":
unittest.main()

Expected Impact for End-Users

GitHub-oriented tools should get farther in Forgejo repositories before deciding that GitHub CLI support is missing. Users can now list and inspect Forgejo issues, create issues, comment on PRs, view PR diffs, check out PR branches, and request richer repository JSON through familiar gh commands.

Validation

Issues, Limitations, and Mitigations

Follow-up Work

No follow-up Beads issue was required for this task. Useful future work would be live Forgejo integration coverage for the new issue and checkout commands, plus broader support if a real tool starts probing PR reviews, release data, or issue comments.