Repository navigation
Expand file tree
/
Copy pathai-code-github.el
More file actions
587 lines (533 loc) · 29.7 KB
/
Copy pathai-code-github.el
File metadata and controls
587 lines (533 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
;;; ai-code-github.el --- GitHub review and PR workflow for AI Code -*- lexical-binding: t; -*-
;; Author: Kang Tu <tninja@gmail.com>
;; SPDX-License-Identifier: Apache-2.0
;;; Commentary:
;; This file provides GitHub-specific PR and issue review workflows for the AI Code package.
;;; Code:
(require 'magit)
(require 'ai-code-input)
(require 'ai-code-prompt-mode)
(require 'which-func nil t)
(declare-function ai-code-read-string "ai-code-input")
(declare-function ai-code--insert-prompt "ai-code-prompt-mode"
(prompt-text &optional send-function))
(declare-function magit-git-string "magit-git" (&rest args))
(declare-function difftastic-magit-diff "difftastic" ())
(declare-function ai-code--validate-git-repository "ai-code-git" ())
(declare-function ai-code--require-current-branch "ai-code-git" ())
(declare-function ai-code--default-pr-target-branch "ai-code-git" (current-branch))
(declare-function ai-code--magit-generate-feature-branch-diff-file "ai-code-git" ())
(declare-function ai-code--generate-staged-diff "ai-code-git" (diff-file))
(declare-function ai-code--generate-branch-or-commit-diff "ai-code-git" (diff-params diff-file))
(declare-function ai-code--open-diff-file "ai-code-git" (diff-file))
(declare-function ai-code-git-commit-current-changes "ai-code-git" ())
(declare-function ai-code--explain-code-change "ai-code-discussion" (&optional review-source))
(declare-function ai-code--get-context-files-string "ai-code-utils" ())
(declare-function ai-code--format-repo-context-info "ai-code-utils" ())
(declare-function ai-code--current-line-scope-context "ai-code-utils" ())
(declare-function ai-code--scope-context-for-region "ai-code-utils" (beg end))
(declare-function ai-code--format-scope-context "ai-code-utils" (context))
(declare-function ai-code--get-region-location-info "ai-code-discussion" (region-beginning region-end))
(defcustom ai-code-default-review-source nil
"Default review source for pull request and issue analysis.
When set, `ai-code--pull-or-review-action-choice' returns this value
directly without prompting. Valid values are `github-mcp', `gh-cli',
or nil (prompt the user)."
:type '(choice (const :tag "Prompt user" nil)
(const :tag "GitHub MCP server" github-mcp)
(const :tag "gh CLI tool" gh-cli))
:group 'ai-code)
(defvar ai-code-pr-title-history nil
"Minibuffer history for optional PR titles.")
(defvar ai-code--grill-me-workflow)
(defconst ai-code-github--analysis-only-note
"No need to make code change. Provide analysis only."
"Prompt note marking a GitHub workflow as analysis without code changes.")
(defconst ai-code-github--resolution-analysis-only-note
"Do not make code changes. Provide analysis and resolution suggestions only."
"Prompt note marking a resolution workflow as analysis without code changes.")
(defconst ai-code-github--pr-creation-no-code-change-note
"No need to make code change. Only create the pull request and report its details."
"Prompt note marking PR creation as a workflow without code changes.")
(defconst ai-code-github--analysis-only-notes
(list ai-code-github--analysis-only-note
ai-code-github--resolution-analysis-only-note
ai-code-github--pr-creation-no-code-change-note)
"Generated prompt notes that mark a GitHub workflow as analysis only.
Send-time prompt classification treats these as non-code-change markers, so
editing the note out of a prompt restores normal code-change routing.")
(defun ai-code--extract-url-from-region ()
"Return the first URL found in the active region, or nil."
(when (use-region-p)
(let ((text (buffer-substring-no-properties (region-beginning) (region-end))))
(when (string-match "https?://[^ \t\n]+" text)
(match-string 0 text)))))
(defun ai-code--pull-or-review-action-choice ()
"Prompt user for action in `ai-code-pull-or-review-diff-file'.
When `ai-code-default-review-source' is set, return it directly."
(or ai-code-default-review-source
(let* ((action-alist '(("Use GitHub MCP server" . github-mcp)
("Use gh CLI tool" . gh-cli)))
(choice (completing-read "Select review source: "
action-alist
nil t nil nil "Use GitHub MCP server")))
(alist-get choice action-alist nil nil #'string=))))
(defun ai-code--message-review-source-config-hint ()
"Message a minibuffer hint about configuring `ai-code-default-review-source'."
(message
"Tip: set ai-code-default-review-source to github-mcp or gh-cli to skip this review-source prompt in future C-c a v runs."))
(defun ai-code--pull-or-review-source-instruction (review-source &optional review-mode)
"Return source instruction string for REVIEW-SOURCE and REVIEW-MODE."
(pcase review-mode
('investigate-issue
(pcase review-source
('github-mcp
"Use GitHub MCP server to inspect the GitHub issue and relevant repository context.")
('gh-cli
"Use gh CLI tool to inspect the GitHub issue and relevant repository context.")
(_ "Investigate this GitHub issue using the repository as context.")))
('review-ci-checks
(pcase review-source
('github-mcp
"Use GitHub MCP server to fetch pull request details and CI checks.")
('gh-cli
"Use gh CLI tool to fetch pull request details and CI checks.")
(_ "Review the GitHub CI checks for this pull request.")))
('resolve-merge-conflict
(pcase review-source
('github-mcp
"Use GitHub MCP server to fetch pull request branch details and merge status.")
('gh-cli
"Use gh CLI tool to fetch pull request branch details and merge status.")
(_ "Resolve merge conflicts for this pull request.")))
('explain-code-change
(pcase review-source
('github-mcp
"Use GitHub MCP server to inspect the pull request diff, changed files, commits, and relevant metadata.")
('gh-cli
"Use gh CLI tool to inspect the pull request diff, changed files, commits, and relevant metadata.")
(_ "Inspect the pull request diff and relevant metadata to understand the change.")))
(_
(pcase review-source
('github-mcp
"Use GitHub MCP server to fetch pull request details and review comments.")
('gh-cli
"Use gh CLI tool to fetch pull request details and review comments.")
(_ "Review this pull request.")))))
(defun ai-code--build-pr-review-init-prompt (review-source pr-url)
"Build an evidence-backed, read-only PR review for REVIEW-SOURCE and PR-URL."
(let ((source-instruction
(ai-code--pull-or-review-source-instruction review-source)))
(format
(concat
"Review pull request: %s\n\n"
"%s\n\n"
"Evidence-backed PR review steps:\n"
"1. Intent and scope: Verify the implementation against requirements. "
"Inspect the exact PR base/head diff and relevant "
"surrounding code. Trace original human requirements and decisions in "
"linked issues or discussions where accessible; treat an AI-generated "
"PR description or summary as a lead, not the source of truth. "
"Name missing or inaccessible references.\n"
"2. Value: Is this PR genuinely useful to the repository, or "
"redundant? Weigh its benefits against complexity and maintenance "
"cost; consider simpler alternatives or no change.\n"
"3. Bug hunting: Prioritize real correctness regressions, security, "
"data loss, and significant performance or code quality problems. "
"Trace the actual "
"control flow, callers, safeguards, and root cause; identify a "
"concrete failure scenario rather than guessing from a name.\n"
"4. Regression check: Compare suspected failures with the PR base. "
"Label each finding Introduced by PR, Pre-existing, or Unknown, with "
"supporting reasoning. Do not attribute old behavior to this PR "
"without evidence.\n"
"5. Challenge findings: Try to disprove each hypothesis using "
"nearby code, existing tests, and existing CI results. Avoid duplicate "
"findings and do not claim to have run checks or read sources that "
"were not inspected.\n"
"6. Actionable findings only: For each credible defect, provide "
"priority, precise file:line in the reviewed revision, the incorrect "
"behavior and failure scenario, code or test evidence, regression "
"status, confidence with reasons, and a specific verification or "
"fix suggestion. Distinguish direct evidence from inference.\n"
"7. Noise control: Skip style-only nits, formatting, speculative "
"cleanup, and routine diagnostics already handled by existing CI "
"unless they cause a material behavioral risk. Do not inflate a "
"low-confidence possibility into a definite bug.\n"
"8. Uncertainty: Put potentially important but unproven problems "
"under needs confirmation with the missing evidence or next check; "
"do not mix them with established findings.\n"
"9. Result: Start with the number of actionable findings. If none "
"were established, say no actionable findings discovered (not a "
"guarantee of correctness). Summarize residual risks, checks "
"actually performed, and checks not performed. End with an overall "
"assessment, including whether to merge, simplify, or close the "
"PR.\n"
"10. %s")
pr-url source-instruction ai-code-github--analysis-only-note)))
(defun ai-code--build-send-current-branch-pr-init-prompt
(review-source current-branch target-branch &optional pr-title)
"Build a PR creation prompt.
REVIEW-SOURCE, CURRENT-BRANCH, TARGET-BRANCH, and PR-TITLE
define the PR request."
;; DONE: it should ask user if this is a draft PR or not (y/n). If yes, the PR should be created as a draft PR. If no, the PR should be created as a normal PR.
(let* ((source-instruction
(ai-code--send-current-branch-pr-source-instruction review-source))
(draft-pr-p
(y-or-n-p "Create this PR as a draft? "))
(pr-type-instruction
(if draft-pr-p
"Create a draft pull request. If you use GitHub CLI, pass `--draft`.\n"
"Create a normal pull request, not a draft.\n"))
(title-instruction
(if (string-empty-p (or pr-title ""))
"2. Generate a concise PR title based on the code change.\n"
(format "2. Use this PR title exactly: %s\n" pr-title))))
(format "Create a pull request from branch %s into %s.
%s
PR Creation Steps:
1. Inspect the exact committed branch diff against %s (base/head and changed files). Keep staged, unstaged, and unrelated work separate; do not describe them as part of the PR.
%s
%s3. Trace the intended behavior to original human-authored requirements when available (issue, task notes, decisions, or discussion); cite the original links. Do not treat AI summaries or an unverified PR description as the source of truth. If requirements are unavailable, say so instead of claiming coverage.
4. Check reviewability of the actual diff: flag material unrelated changes, excessive formatting, redundant generated tests, or risk-heavy areas. Suggest a smaller/split PR only if it materially improves review; do not silently rewrite code or split branches.
5. Gather existing verification evidence from the current AI coding session, linked task notes, actual test commands/results, CI for the relevant commit, and any completed deployment checks. Cite commands or links where useful; distinguish passed, failed, not run, not accessible, and unverified. Never invent test results, source links, or proof of correctness.
6. Write a short, author-voiced PR description covering why, what changed, and verified evidence (with exact commands/links where useful). Call out material gaps, risks, and review hotspots without boilerplate or a large checklist for trivial changes.
7. Create the requested PR using the chosen tool and draft/normal setting. Do not modify code, tests, Git commits, or branch contents as part of PR creation.
8. Return the final PR URL, exact title, and exact description, plus any material reviewability concerns that could not be resolved.
9. %s"
current-branch
target-branch
source-instruction
target-branch
pr-type-instruction
title-instruction
ai-code-github--pr-creation-no-code-change-note)))
(defun ai-code--build-pr-feedback-check-init-prompt (review-source pr-url)
"Build unresolved feedback check prompt for REVIEW-SOURCE with PR-URL."
(let ((source-instruction
(ai-code--pull-or-review-source-instruction review-source)))
(format "Check unresolved feedback for pull request: %s
%s
Feedback Check Steps:
1. Find unresolved feedback or unresolved review comments in this PR.
2. For each unresolved feedback, explain whether it makes sense and why.
3. If a feedback does not make sense, explain why it may not be necessary.
4. %s"
pr-url source-instruction
ai-code-github--analysis-only-note)))
(defun ai-code--github-editor-context ()
"Return a local editor context block, or nil when none is available.
Use a file reference for an Org task so another agent can inspect the
original requirements without copying the entire task into the prompt."
(when (or buffer-file-name (use-region-p))
(let* ((region-text (when (use-region-p)
(buffer-substring-no-properties
(region-beginning) (region-end))))
(region-location-info (when region-text
(ai-code--get-region-location-info
(region-beginning) (region-end))))
(semantic-scope
(ai-code--format-scope-context
(if region-text
(ai-code--scope-context-for-region
(region-beginning) (region-end))
(ai-code--current-line-scope-context))))
(files-context-string (ai-code--get-context-files-string))
(repo-context-string (ai-code--format-repo-context-info))
(context-blocks nil))
(push (if buffer-file-name
(format "Current file: %s" buffer-file-name)
(format "Current buffer: %s" (buffer-name)))
context-blocks)
(when (and buffer-file-name (derived-mode-p 'org-mode))
(push (format
(concat "Current task file: @%s\n"
"Read original human-authored requirements and "
"decisions here; distinguish them from AI-generated "
"intermediate summaries.")
buffer-file-name)
context-blocks))
(unless (string-empty-p semantic-scope)
(push semantic-scope context-blocks))
(when region-text
(push (concat "Selected region:\n"
(when region-location-info
(concat region-location-info "\n"))
region-text)
context-blocks))
(when (and files-context-string
(not (string-empty-p files-context-string)))
(push files-context-string context-blocks))
(when (and repo-context-string
(not (string-empty-p repo-context-string)))
(push repo-context-string context-blocks))
(concat "Local Context:\n"
(mapconcat #'identity (nreverse context-blocks) "\n\n")))))
(defun ai-code--github-append-editor-context (prompt include-context)
"Append current editor context to PROMPT when INCLUDE-CONTEXT is non-nil."
(if-let* ((context (and include-context (ai-code--github-editor-context))))
(concat prompt "\n\n" context)
prompt))
(defun ai-code--build-issue-investigation-init-prompt (review-source issue-url &optional include-context)
"Build issue investigation prompt for REVIEW-SOURCE with ISSUE-URL.
If INCLUDE-CONTEXT is non-nil, append current editor context to the prompt."
(let* ((source-instruction
(ai-code--pull-or-review-source-instruction review-source 'investigate-issue))
(prompt
(format "Investigate issue: %s
%s
Issue Investigation Steps:
1. Understand the issue description, reproduction details, and expected behavior.
2. Analyze relevant code in this repository as context and identify likely root causes.
3. Provide concrete insights on how to fix it, including likely files or areas to change.
4. %s"
issue-url source-instruction
ai-code-github--analysis-only-note)))
(ai-code--github-append-editor-context prompt include-context)))
(defun ai-code--build-pr-description-init-prompt (review-source pr-url)
"Build PR description prompt for REVIEW-SOURCE with PR-URL."
(let ((source-instruction
(ai-code--pull-or-review-source-instruction review-source)))
(format "Prepare a pull request description for: %s
%s
PR Description Steps:
1. Add a summary of the problem and the approach taken in the PR.
2. Highlight the most important code changes and user-visible impact.
3. Add a testing section with relevant verification details.
4. Format the result as a concise PR description ready to share with reviewers,
written in the voice of the author or maintainer.
5. %s"
pr-url source-instruction
ai-code-github--analysis-only-note)))
(defun ai-code--build-pr-ci-check-init-prompt (review-source pr-url)
"Build a CI check review prompt for REVIEW-SOURCE with PR-URL."
(let ((source-instruction
(ai-code--pull-or-review-source-instruction review-source 'review-ci-checks)))
(format "Review GitHub CI checks for pull request: %s
%s
CI Checks Review Steps:
1. Review the GitHub CI checks for this pull request.
2. If there is a failing or error state, inspect the failing checks and relevant details.
3. Analyze the likely root cause of each failure.
4. %s"
pr-url source-instruction
ai-code-github--analysis-only-note)))
(defun ai-code--build-resolve-merge-conflict-init-prompt (review-source pr-url)
"Build merge conflict resolution prompt for REVIEW-SOURCE with PR-URL."
(let ((source-instruction
(ai-code--pull-or-review-source-instruction review-source 'resolve-merge-conflict)))
(format "Resolve merge conflict for pull request: %s
%s
Merge Conflict Resolution Steps:
1. Identify the current working branch and the target branch from the PR.
2. Verify the current working branch matches the PR source branch.
3. Update the local target branch to the latest remote version.
4. Attempt to merge the target branch into the current working branch.
5. If there are merge conflicts, analyze each conflict and provide detailed instructions on how to resolve them, including which files to change and how.
6. %s
7. If there are no merge conflicts, report that the merge would succeed and return a success message."
pr-url source-instruction
ai-code-github--resolution-analysis-only-note)))
(defun ai-code--pull-or-review-url-prompt (review-mode)
"Return the URL prompt string for REVIEW-MODE."
(if (eq review-mode 'investigate-issue)
"GitHub issue URL: "
"Pull request URL: "))
;; DONE: sub-command here should take ai-code-use-compose-buffer into consideration. when it is non-nil, it should use a compose buffer for multi-lines prompt, just like other command.
(defconst ai-code-github--pull-or-review-pr-mode-alist
'(("Review the PR" . review-pr)
("Check unresolved feedback" . check-feedback)
("Prepare PR description" . prepare-pr-description)
("Send out PR for current branch" . send-current-branch-pr)
("Commit current changes" . commit-current-changes)
("Review current branch with difftastic"
. review-current-branch-with-difftastic)
("Investigate issue" . investigate-issue)
("Review GitHub CI checks" . review-ci-checks)
("Explain code change" . explain-code-change)
("Resolve merge conflict" . resolve-merge-conflict)
("Generate diff file" . generate-diff-file))
"Analysis modes offered for a pull request, issue, or local Git action.
Every mode that builds a send prompt must mark the prompt with one of
`ai-code-github--analysis-only-notes' unless it really requests code changes.")
(defun ai-code--pull-or-review-pr-mode-choice ()
"Prompt user to choose analysis mode for a pull request, issue, or Git action."
(let* ((review-mode-alist ai-code-github--pull-or-review-pr-mode-alist)
(review-mode (completing-read "Select analysis mode (PR, issue, or Git): "
review-mode-alist
nil t nil nil "Review the PR")))
(or (alist-get review-mode review-mode-alist nil nil #'string=)
'review-pr)))
(defun ai-code--review-current-branch-with-difftastic ()
"Review the current branch with `difftastic-magit-diff'.
Signal a helpful error when difftastic is unavailable."
(require 'difftastic nil t)
(unless (fboundp 'difftastic-magit-diff)
(user-error
(concat
"The package difftastic is not installed. "
"Install it from MELPA or https://github.com/pkryger/difftastic.el")))
(call-interactively #'difftastic-magit-diff))
(defun ai-code--send-current-branch-pr-source-instruction (review-source)
"Return PR creation instructions for REVIEW-SOURCE."
(pcase review-source
('gh-cli
(concat
"Use GitHub CLI to create the pull request. "
"Run `gh pr create` with the current branch as the head branch, "
"target the requested base branch, and include the final title and body."))
('github-mcp
(concat
"Use GitHub MCP tools to create the pull request directly. "
"Do not fetch review comments before the PR exists; "
"create the PR first, then return the resulting PR URL."))
(_
(concat
"Create the pull request using the backend's PR creation capability. "
"Do not treat this as a PR review flow before the PR exists."))))
(defun ai-code--build-pr-init-prompt (review-source target-url review-mode &optional include-context)
"Build initial prompt for REVIEW-SOURCE, TARGET-URL and REVIEW-MODE.
If INCLUDE-CONTEXT is non-nil, append current editor context to the prompt."
(pcase review-mode
('investigate-issue
(ai-code--build-issue-investigation-init-prompt review-source target-url include-context))
('review-pr
(ai-code--github-append-editor-context
(ai-code--build-pr-review-init-prompt review-source target-url)
include-context))
('check-feedback
(ai-code--build-pr-feedback-check-init-prompt review-source target-url))
('review-ci-checks
(ai-code--build-pr-ci-check-init-prompt review-source target-url))
('prepare-pr-description
(ai-code--build-pr-description-init-prompt review-source target-url))
('resolve-merge-conflict
(ai-code--build-resolve-merge-conflict-init-prompt review-source target-url))
(_
(ai-code--build-pr-review-init-prompt review-source target-url))))
(defun ai-code--pull-or-review-pr-with-source (review-source &optional arg)
"Prompt for a mode and send a prompt for REVIEW-SOURCE to AI.
ARG is the optional prefix argument to force including context."
(require 'ai-code-git nil t)
(let ((review-mode (ai-code--pull-or-review-pr-mode-choice)))
(cond
((eq review-mode 'commit-current-changes)
(call-interactively #'ai-code-git-commit-current-changes))
((eq review-mode 'generate-diff-file)
(ai-code--magit-generate-feature-branch-diff-file))
((eq review-mode 'review-current-branch-with-difftastic)
(ai-code--review-current-branch-with-difftastic))
((eq review-mode 'explain-code-change)
(unless (fboundp 'ai-code--explain-code-change)
(require 'ai-code-discussion nil t))
(unless (fboundp 'ai-code--explain-code-change)
(user-error "Code change explanation support is not available"))
(ai-code--explain-code-change review-source))
(t
(let* ((init-prompt
(if (eq review-mode 'send-current-branch-pr)
(progn
(unless (magit-toplevel)
(user-error "Not inside a Git repository"))
(let* ((current-branch (ai-code--require-current-branch))
(default-target-branch
(ai-code--default-pr-target-branch current-branch))
(target-branch
(ai-code-read-string "Target branch to merge into: "
default-target-branch))
(pr-title
(read-string
"PR title (optional, leave empty for AI to generate): "
nil
'ai-code-pr-title-history)))
(ai-code--build-send-current-branch-pr-init-prompt
review-source current-branch target-branch pr-title)))
(let* ((url-prompt (ai-code--pull-or-review-url-prompt review-mode))
(region-url (ai-code--extract-url-from-region))
(target-url (ai-code-read-string url-prompt region-url))
(has-context (or buffer-file-name (use-region-p)))
(include-context
(and (memq review-mode '(investigate-issue review-pr))
has-context
(or arg
(y-or-n-p "Include active buffer and editor context? ")))))
(ai-code--build-pr-init-prompt review-source target-url review-mode include-context))))
(prompt-label (if (eq review-mode 'send-current-branch-pr)
"Enter PR creation prompt: "
"Enter review prompt: ")))
(let ((ai-code--grill-me-workflow review-mode))
(ai-code--confirm-and-send prompt-label init-prompt)))))))
(defun ai-code--get-git-web-repo-url ()
"Get Git repository web URL from git remote.
Returns the HTTPS URL of the repository for web browsing.
Supports GitHub, GitLab, Bitbucket, and other Git hosting services.
Accepts HTTPS, SCP-style SSH, and ssh:// remotes, including SSH ports.
Returns nil if unable to construct a web URL."
(let* ((remote-url (magit-git-string "config" "--get" "remote.origin.url")))
(when (and remote-url (stringp remote-url) (not (string-empty-p remote-url)))
(cond
;; HTTPS URL: https://host.com/user/repo.git or https://host.com/user/repo
((string-match "\\`https://\\([^/]+\\)/\\(.+\\)\\'" remote-url)
(let ((host (match-string 1 remote-url))
(path (match-string 2 remote-url)))
(format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path))))
;; SSH URI: ssh://git@host.com[:port]/user/repo.git
;; An SSH transport port is not the web server's HTTPS port.
((string-match
"\\`ssh://\\(?:[^/@]+@\\)?\\([^/:]+\\)\\(?::[0-9]+\\)?/\\(.+\\)\\'"
remote-url)
(let ((host (match-string 1 remote-url))
(path (match-string 2 remote-url)))
(format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path))))
;; SCP-style SSH: git@host.com:user/repo.git
((string-match "\\`git@\\([^/:]+\\):\\(.+\\)\\'" remote-url)
(let ((host (match-string 1 remote-url))
(path (match-string 2 remote-url)))
(format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path))))
(t nil)))))
(defun ai-code--open-git-web-compare (start end)
"Open Git web compare page for START..END in browser.
Works with GitHub, GitLab, Bitbucket, and other Git hosting services."
(let ((repo-url (ai-code--get-git-web-repo-url)))
(if repo-url
(let ((compare-url (format "%s/compare/%s...%s" repo-url start end)))
(browse-url compare-url)
(message "Opened web compare: %s" compare-url))
(message "Unable to determine repository web URL"))))
(defun ai-code--open-git-web-commit (commit)
"Open Git web commit page for COMMIT in browser.
Works with GitHub, GitLab, Bitbucket, and other Git hosting services."
(let ((repo-url (ai-code--get-git-web-repo-url)))
(if repo-url
(let ((commit-url (format "%s/commit/%s" repo-url commit)))
(browse-url commit-url)
(message "Opened web commit: %s" commit-url))
(message "Unable to determine repository web URL"))))
(defun ai-code-pull-or-review-diff-file (&optional arg)
"Review a diff file with AI Code or choose a PR review workflow.
If current buffer is a .diff file, ask AI Code to review it.
Otherwise, prompt for a review source and analysis mode.
ARG is the optional prefix argument to force including context."
(interactive "P")
(if (and buffer-file-name (string-match-p "\\.diff$" buffer-file-name))
(let* ((file-name (file-name-nondirectory buffer-file-name))
(base-prompt (format "Code review for %s. Use relevant file in repository as context.
**Review Steps**:
1. **Requirement Fit** (Top Priority): Verify if the code change fulfills the requirement below. Identify gaps or missing implementations.
2. **Code Quality**: Check for quality, security, performance, and coding patterns.
3. **Issues Found**: For each issue: Location, Issue, Solution, Priority (High/Medium/Low)
4. %s
Provide overall assessment." file-name
ai-code-github--analysis-only-note))
(init-prompt (concat (ai-code--github-append-editor-context base-prompt arg)
"\n\n**Requirement**: ")))
(ai-code--confirm-and-send
"Enter review prompt (type requirement at end): "
init-prompt))
;; For non-diff files, let user choose PR review via MCP/gh CLI.
(unless ai-code-default-review-source
(ai-code--message-review-source-config-hint))
(let ((review-source (ai-code--pull-or-review-action-choice)))
(ai-code--pull-or-review-pr-with-source review-source arg))))
(provide 'ai-code-github)
;;; ai-code-github.el ends here