-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathci-status.ts
More file actions
1361 lines (1229 loc) · 36.7 KB
/
Copy pathci-status.ts
File metadata and controls
1361 lines (1229 loc) · 36.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Shared CI status utilities for GitHub CI integration
*
* Provides common functions for checking CI status, waiting for checks,
* extracting preview URLs, and formatting results. Used by:
* - commit-task-await-ci-status.ts (SubagentStop)
* - await-pr-status.ts (PostToolUse[Bash])
* - commit-session-await-ci-status.ts (Stop)
*
* @module ci-status
*/
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
/** Maximum output characters for CI status (prevents context bloat) */
const MAX_OUTPUT_CHARS = 500;
/** Default CI check timeout in milliseconds (10 minutes) */
const DEFAULT_TIMEOUT_MS = 600000;
/**
* Branch sync status result
*/
export interface BranchSyncResult {
/** Whether branch is in sync with main */
inSync: boolean;
/** Number of commits behind main */
behindCount: number;
/** Number of commits ahead of main */
aheadCount: number;
/** Error message if check failed */
error?: string;
}
/**
* Merge conflict check result
*/
export interface MergeConflictResult {
/** Whether PR has merge conflicts */
hasConflicts: boolean;
/** Mergeable state from GitHub */
mergeableState?: string;
/** Error message if check failed */
error?: string;
}
/**
* Fail-fast CI check result
*/
export interface FailFastResult {
/** Whether all checks passed */
success: boolean;
/** Blocking reason if failed */
blockReason?: string;
/** Failed check name if applicable */
failedCheck?: string;
/** All check statuses */
checks: CheckStatus[];
/** PR number if found */
prNumber?: number;
/** Error message if operation failed */
error?: string;
}
/**
* Result from a CI check operation
*/
export interface CICheckResult {
/** Whether all CI checks passed */
success: boolean;
/** Combined output from CI checks */
output: string;
/** Error message if operation failed */
error?: string;
}
/**
* CI run details from GitHub
*/
export interface CIRunDetails {
/** CI workflow URL */
url?: string;
/** CI status (queued, in_progress, completed) */
status?: string;
/** CI conclusion (success, failure, cancelled) */
conclusion?: string;
/** Workflow name */
name?: string;
}
/**
* Individual check status
*/
export interface CheckStatus {
/** Check name */
name: string;
/** Check status emoji */
emoji: string;
/** Check status (success, failure, pending) */
status: string;
/** Details URL */
url?: string;
}
/**
* PR existence check result
*/
export interface PRCheckResult {
/** Whether PR exists */
exists: boolean;
/** PR number if exists */
prNumber?: number;
/** PR URL if exists */
prUrl?: string;
/** Error message if check failed */
error?: string;
}
/**
* Preview URLs extracted from PR
*/
export interface PreviewUrls {
/** Web app preview URL */
webUrl?: string;
/** Marketing app preview URL */
marketingUrl?: string;
/** All preview URLs found */
allUrls: string[];
}
/**
* Information about an issue linked to a PR
*/
export interface LinkedIssueInfo {
/** Issue number */
number: number;
/** Issue title (if fetched) */
title?: string;
/** Full issue URL */
url: string;
/** Repository owner/name (extracted from URL) */
repo: string;
}
/**
* Grouped preview URLs by provider
*/
export interface GroupedPreviewUrls {
/** Vercel preview URLs */
vercel: string[];
/** Cloudflare Worker/Pages preview URLs */
cloudflare: string[];
/** Supabase preview branch URLs */
supabase: string[];
}
/**
* Execute a shell command with timeout
*
* @param command - Command to execute
* @param cwd - Working directory
* @param timeout - Timeout in milliseconds (default: 30s)
* @returns Command result with success flag and output
*
* @example
* ```typescript
* const result = await execCommand('gh pr list', '/path/to/repo');
* if (result.success) {
* console.log(result.stdout);
* }
* ```
*/
export async function execCommand(
command: string,
cwd: string,
timeout = 30000
): Promise<{ success: boolean; stdout: string; stderr: string }> {
try {
const { stdout, stderr } = await execAsync(command, { cwd, timeout });
return { success: true, stdout: stdout.trim(), stderr: stderr.trim() };
} catch (error: unknown) {
const err = error as { stdout?: string; stderr?: string; message?: string };
return {
success: false,
stdout: err.stdout?.trim() || '',
stderr: err.stderr?.trim() || err.message || '',
};
}
}
/**
* Check if a PR exists for the given branch
*
* @param branch - Branch name to check
* @param cwd - Working directory
* @returns PR check result with number and URL if exists
*
* @example
* ```typescript
* const prCheck = await checkPRExists('feature-branch', '/path/to/repo');
* if (prCheck.exists) {
* console.log(`PR #${prCheck.prNumber}: ${prCheck.prUrl}`);
* }
* ```
*/
export async function checkPRExists(
branch: string,
cwd: string
): Promise<PRCheckResult> {
// Check if gh CLI is available
const ghCheck = await execCommand('gh --version', cwd);
if (!ghCheck.success) {
return { exists: false, error: 'GitHub CLI not installed' };
}
// Check if gh is authenticated
const authCheck = await execCommand('gh auth status', cwd);
if (!authCheck.success) {
return { exists: false, error: 'GitHub CLI not authenticated' };
}
// List PRs for current branch
const prListResult = await execCommand(
`gh pr list --head ${branch} --json number,url --limit 1`,
cwd
);
if (!prListResult.success) {
return { exists: false, error: `gh pr list failed: ${prListResult.stderr}` };
}
try {
const prs = JSON.parse(prListResult.stdout);
if (Array.isArray(prs) && prs.length > 0) {
return {
exists: true,
prNumber: prs[0].number,
prUrl: prs[0].url,
};
}
return { exists: false };
} catch {
return { exists: false, error: 'Failed to parse gh output' };
}
}
/**
* Get PR number for the current branch
*
* @param cwd - Working directory
* @returns PR number or null if no PR exists
*
* @example
* ```typescript
* const prNumber = await getPRForCurrentBranch('/path/to/repo');
* if (prNumber) {
* const ciResult = await waitForCIChecks({ prNumber, cwd });
* }
* ```
*/
export async function getPRForCurrentBranch(cwd: string): Promise<number | null> {
const branchResult = await execCommand('git rev-parse --abbrev-ref HEAD', cwd);
if (!branchResult.success) {
return null;
}
const prCheck = await checkPRExists(branchResult.stdout, cwd);
return prCheck.exists ? (prCheck.prNumber ?? null) : null;
}
/**
* Wait for CI checks to complete on a PR
*
* Uses `gh pr checks --watch` to wait for all CI checks to finish.
* Blocks until all checks complete or timeout is reached.
*
* @param options - Wait options
* @param options.prNumber - PR number to check (required if no commitSha)
* @param options.commitSha - Commit SHA to check (alternative to prNumber)
* @param options.timeout - Timeout in milliseconds (default: 10 minutes)
* @param cwd - Working directory
* @returns CI check result with success status and output
*
* @example
* ```typescript
* const result = await waitForCIChecks({ prNumber: 123 }, '/path/to/repo');
* if (result.success) {
* console.log('All CI checks passed!');
* } else {
* console.log('CI failed:', result.output);
* }
* ```
*/
export async function waitForCIChecks(
options: {
prNumber?: number;
commitSha?: string;
timeout?: number;
},
cwd: string
): Promise<CICheckResult> {
const { prNumber, commitSha, timeout = DEFAULT_TIMEOUT_MS } = options;
if (!prNumber && !commitSha) {
return { success: false, output: '', error: 'Either prNumber or commitSha required' };
}
try {
// Build command based on what we have
const target = prNumber ? prNumber.toString() : commitSha!;
const command = `gh pr checks ${target} --watch`;
const { stdout, stderr } = await execAsync(command, { cwd, timeout });
const combinedOutput = `${stdout}\n${stderr}`.trim();
// Check if all checks passed
const hasFailures =
combinedOutput.includes('fail') ||
combinedOutput.includes('X ') ||
combinedOutput.includes('cancelled');
return {
success: !hasFailures,
output: combinedOutput,
};
} catch (error: unknown) {
const err = error as {
stdout?: string;
stderr?: string;
message?: string;
killed?: boolean;
};
const errorOutput = err.stdout || err.stderr || err.message || 'Unknown error';
if (err.killed) {
return {
success: false,
output: errorOutput,
error: `CI check timeout (${Math.round(timeout / 60000)} minutes)`,
};
}
return {
success: false,
output: errorOutput,
error: 'Failed to watch CI checks',
};
}
}
/**
* Get latest CI workflow run details
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns CI run details or null if not found
*
* @example
* ```typescript
* const ciRun = await getLatestCIRun(123, '/path/to/repo');
* if (ciRun?.conclusion === 'success') {
* console.log('CI passed:', ciRun.url);
* }
* ```
*/
export async function getLatestCIRun(
prNumber: number,
cwd: string
): Promise<CIRunDetails | null> {
// First, get the PR's HEAD commit SHA to filter CI runs correctly
const headShaResult = await execCommand(
`gh pr view ${prNumber} --json headRefOid --jq '.headRefOid'`,
cwd
);
if (!headShaResult.success || !headShaResult.stdout.trim()) {
// Fallback: if we can't get PR info, return null rather than wrong data
return null;
}
const headSha = headShaResult.stdout.trim();
// Get CI runs for THIS specific commit, not the most recent run globally
const result = await execCommand(
`gh run list --commit ${headSha} --limit 1 --json databaseId,displayTitle,status,conclusion,url`,
cwd
);
if (!result.success) {
return null;
}
try {
const runs = JSON.parse(result.stdout);
if (Array.isArray(runs) && runs.length > 0) {
const run = runs[0];
return {
url: run.url,
status: run.status,
conclusion: run.conclusion,
name: run.displayTitle,
};
}
return null;
} catch {
return null;
}
}
/**
* Extract Vercel preview URLs from PR comments
*
* Searches PR comments for Vercel bot URLs and categorizes them
* by app type (web, marketing, etc).
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Preview URLs object with categorized URLs
*
* @example
* ```typescript
* const urls = await extractPreviewUrls(123, '/path/to/repo');
* if (urls.webUrl) {
* console.log('Web preview:', urls.webUrl);
* }
* ```
*/
export async function extractPreviewUrls(
prNumber: number,
cwd: string
): Promise<PreviewUrls> {
const result = await execCommand(`gh pr view ${prNumber} --json comments`, cwd);
if (!result.success) {
return { allUrls: [] };
}
try {
const data = JSON.parse(result.stdout);
const comments = data.comments || [];
const vercelUrlPattern = /https:\/\/[a-z0-9-]+\.vercel\.app/g;
const allUrls: string[] = [];
for (const comment of comments) {
const matches = comment.body?.match(vercelUrlPattern) || [];
allUrls.push(...matches);
}
// Deduplicate URLs
const uniqueUrls = [...new Set(allUrls)];
// Identify web and marketing apps by URL pattern
const webUrl = uniqueUrls.find(
(url) =>
url.includes('-web-') || url.includes('web-') || url.match(/web\.vercel\.app/)
);
const marketingUrl = uniqueUrls.find(
(url) =>
url.includes('-marketing-') ||
url.includes('marketing-') ||
url.match(/marketing\.vercel\.app/)
);
return {
webUrl,
marketingUrl,
allUrls: uniqueUrls,
};
} catch {
return { allUrls: [] };
}
}
/**
* Extract linked issue numbers from PR body (simple version)
*
* Parses PR body for GitHub issue-closing keywords like:
* - Fixes #123, Closes #456, Resolves #789
* - Full URLs: github.com/owner/repo/issues/123
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Array of linked issue numbers (deduplicated and sorted)
*
* @example
* ```typescript
* const linkedIssues = await extractLinkedIssuesFromPR(42, '/path/to/repo');
* // Returns: [123, 456] if PR body contains "Fixes #123" and "Closes #456"
* ```
*/
export async function extractLinkedIssuesFromPR(
prNumber: number,
cwd: string
): Promise<number[]> {
const linkedIssues = await extractLinkedIssuesWithInfo(prNumber, cwd);
return linkedIssues.map((issue) => issue.number).sort((a, b) => a - b);
}
/**
* Extract linked issues with full info from PR body
*
* Parses PR body for GitHub issue-closing keywords and returns rich info:
* - Fixes #123, Closes #456, Resolves #789
* - Full URLs: github.com/owner/repo/issues/123
*
* For #123 references, constructs URL using the PR's repository.
* For full URLs, extracts the repo from the URL (supports cross-repo links).
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Array of LinkedIssueInfo with number, url, and repo
*
* @example
* ```typescript
* const linkedIssues = await extractLinkedIssuesWithInfo(42, '/path/to/repo');
* // Returns: [{ number: 123, url: 'https://github.com/owner/repo/issues/123', repo: 'owner/repo' }]
* ```
*/
export async function extractLinkedIssuesWithInfo(
prNumber: number,
cwd: string
): Promise<LinkedIssueInfo[]> {
// Get PR body and URL to extract repo info
const result = await execCommand(
`gh pr view ${prNumber} --json body,url`,
cwd
);
if (!result.success || !result.stdout) {
return [];
}
let body: string;
let prUrl: string;
try {
const data = JSON.parse(result.stdout);
body = data.body || '';
prUrl = data.url || '';
} catch {
return [];
}
// Extract repo from PR URL: https://github.com/owner/repo/pull/123
const prRepoMatch = prUrl.match(/github\.com\/([^/]+\/[^/]+)\/pull/);
const prRepo = prRepoMatch ? prRepoMatch[1] : '';
const linkedIssues: Map<string, LinkedIssueInfo> = new Map();
// Pattern 1: Issue-closing keywords with # reference (same repo)
// Matches: fix, fixes, fixed, close, closes, closed, resolve, resolves, resolved
const keywordPattern = /\b(?:fix|fixes|fixed|close|closes|closed|resolve|resolves|resolved)\s+#(\d+)/gi;
let match;
while ((match = keywordPattern.exec(body)) !== null) {
const num = parseInt(match[1], 10);
const url = prRepo ? `https://github.com/${prRepo}/issues/${num}` : '';
const key = `${prRepo}#${num}`;
if (!linkedIssues.has(key)) {
linkedIssues.set(key, {
number: num,
url,
repo: prRepo,
});
}
}
// Pattern 2: Full GitHub issue URLs (may be cross-repo)
// Matches: https://github.com/owner/repo/issues/123
const urlPattern = /https:\/\/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/g;
while ((match = urlPattern.exec(body)) !== null) {
const repo = match[1];
const num = parseInt(match[2], 10);
const url = `https://github.com/${repo}/issues/${num}`;
const key = `${repo}#${num}`;
if (!linkedIssues.has(key)) {
linkedIssues.set(key, {
number: num,
url,
repo,
});
}
}
// Return sorted by repo then number
return Array.from(linkedIssues.values()).sort((a, b) => {
if (a.repo !== b.repo) return a.repo.localeCompare(b.repo);
return a.number - b.number;
});
}
/**
* Extract Cloudflare Worker/Pages preview URLs from PR comments
*
* Searches PR comments for Cloudflare deployment URLs:
* - Workers: https://my-worker.workers.dev
* - Pages: https://my-project.pages.dev
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Array of Cloudflare preview URLs
*
* @example
* ```typescript
* const urls = await extractCloudflarePreviewUrls(42, '/path/to/repo');
* // Returns: ['https://my-api.workers.dev', 'https://my-site.pages.dev']
* ```
*/
export async function extractCloudflarePreviewUrls(
prNumber: number,
cwd: string
): Promise<string[]> {
const result = await execCommand(`gh pr view ${prNumber} --json comments`, cwd);
if (!result.success) {
return [];
}
try {
const data = JSON.parse(result.stdout);
const comments = data.comments || [];
const allUrls: string[] = [];
// Cloudflare Workers pattern: https://something.workers.dev
const workersPattern = /https:\/\/[a-z0-9-]+\.workers\.dev/gi;
// Cloudflare Pages pattern: https://something.pages.dev
const pagesPattern = /https:\/\/[a-z0-9-]+\.pages\.dev/gi;
for (const comment of comments) {
const body = comment.body || '';
const workersMatches = body.match(workersPattern) || [];
const pagesMatches = body.match(pagesPattern) || [];
allUrls.push(...workersMatches, ...pagesMatches);
}
// Deduplicate
return [...new Set(allUrls)];
} catch {
return [];
}
}
/**
* Extract Supabase preview branch URLs from PR comments
*
* Searches PR comments for Supabase preview URLs:
* - API: https://project-ref.supabase.co
* - Database: db.project-ref.supabase.co
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Array of Supabase preview URLs
*
* @example
* ```typescript
* const urls = await extractSupabasePreviewBranches(42, '/path/to/repo');
* // Returns: ['https://abcxyz-preview.supabase.co']
* ```
*/
export async function extractSupabasePreviewBranches(
prNumber: number,
cwd: string
): Promise<string[]> {
const result = await execCommand(`gh pr view ${prNumber} --json comments`, cwd);
if (!result.success) {
return [];
}
try {
const data = JSON.parse(result.stdout);
const comments = data.comments || [];
const allUrls: string[] = [];
// Supabase API URL pattern: https://something.supabase.co
const supabasePattern = /https:\/\/[a-z0-9-]+\.supabase\.co/gi;
// Supabase DB URL pattern: db.something.supabase.co (may or may not have https://)
const dbPattern = /(?:https?:\/\/)?db\.[a-z0-9-]+\.supabase\.co/gi;
for (const comment of comments) {
const body = comment.body || '';
const supabaseMatches = body.match(supabasePattern) || [];
const dbMatches = body.match(dbPattern) || [];
allUrls.push(...supabaseMatches, ...dbMatches);
}
// Deduplicate and normalize (ensure https://)
const uniqueUrls = [...new Set(allUrls)].map((url) => {
if (!url.startsWith('http')) {
return `https://${url}`;
}
return url;
});
return uniqueUrls;
} catch {
return [];
}
}
/**
* Extract all preview URLs grouped by provider
*
* Consolidates preview URLs from Vercel, Cloudflare, and Supabase.
*
* @param prNumber - PR number
* @param cwd - Working directory
* @returns Grouped preview URLs by provider
*
* @example
* ```typescript
* const previews = await extractAllPreviews(42, '/path/to/repo');
* // Returns: {
* // vercel: ['https://my-app-abc123.vercel.app'],
* // cloudflare: ['https://my-worker.workers.dev'],
* // supabase: ['https://abcxyz.supabase.co']
* // }
* ```
*/
export async function extractAllPreviews(
prNumber: number,
cwd: string
): Promise<GroupedPreviewUrls> {
// Fetch all previews in parallel
const [vercelResult, cloudflareUrls, supabaseUrls] = await Promise.all([
extractPreviewUrls(prNumber, cwd),
extractCloudflarePreviewUrls(prNumber, cwd),
extractSupabasePreviewBranches(prNumber, cwd),
]);
return {
vercel: vercelResult.allUrls,
cloudflare: cloudflareUrls,
supabase: supabaseUrls,
};
}
/**
* Format grouped preview URLs for display
*
* Formats preview URLs from all providers (Vercel, Cloudflare, Supabase)
* into a markdown-formatted string with provider sections.
*
* @param previews - Grouped preview URLs by provider
* @returns Formatted markdown string, empty if no previews
*
* @example
* ```typescript
* const previews = await extractAllPreviews(42, '/path/to/repo');
* const formatted = formatGroupedPreviews(previews);
* // Returns:
* // "
* // **Vercel Previews:**
* // - https://my-app-abc123.vercel.app
* //
* // **Cloudflare Previews:**
* // - https://my-worker.workers.dev
* // "
* ```
*/
export function formatGroupedPreviews(previews: GroupedPreviewUrls): string {
let message = '';
if (previews.vercel.length > 0) {
message += '\n\n**Vercel Previews:**';
for (const url of previews.vercel) {
message += `\n - ${url}`;
}
}
if (previews.cloudflare.length > 0) {
message += '\n\n**Cloudflare Previews:**';
for (const url of previews.cloudflare) {
message += `\n - ${url}`;
}
}
if (previews.supabase.length > 0) {
message += '\n\n**Supabase Previews:**';
for (const url of previews.supabase) {
message += `\n - ${url}`;
}
}
return message;
}
/**
* Parse CI checks output into structured format
*
* @param output - Raw output from `gh pr checks`
* @returns Array of parsed check statuses
*
* @example
* ```typescript
* const checks = parseCIChecks(ciOutput);
* for (const check of checks) {
* console.log(`${check.emoji} ${check.name}: ${check.status}`);
* }
* ```
*/
export function parseCIChecks(output: string): CheckStatus[] {
const checks: CheckStatus[] = [];
const lines = output.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
// Parse line format: "✓ check-name" or "X check-name" or "* check-name"
let emoji = '⏳';
let status = 'pending';
if (trimmed.startsWith('✓') || trimmed.includes('pass')) {
emoji = '✅';
status = 'success';
} else if (trimmed.startsWith('X') || trimmed.includes('fail')) {
emoji = '❌';
status = 'failure';
} else if (trimmed.includes('cancel')) {
emoji = '⚪';
status = 'cancelled';
}
// Extract check name (remove status indicator)
const name = trimmed.replace(/^[✓X*\s]+/, '').split('\t')[0].trim();
if (name) {
checks.push({ name, emoji, status });
}
}
return checks;
}
/**
* Format CI status result as concise string
*
* Truncates output to MAX_OUTPUT_CHARS to prevent context bloat.
*
* @param result - CI check result
* @param maxChars - Maximum output characters (default: 500)
* @returns Formatted status string
*
* @example
* ```typescript
* const ciResult = await waitForCIChecks({ prNumber: 123 }, cwd);
* const formatted = formatCIStatus(ciResult);
* console.log(formatted);
* ```
*/
export function formatCIStatus(
result: CICheckResult,
maxChars: number = MAX_OUTPUT_CHARS
): string {
let output = '';
if (result.success) {
output = '✅ All CI checks passed';
} else if (result.error) {
output = `⚠️ ${result.error}`;
} else {
output = '❌ CI checks failed';
}
// Add check details if available
if (result.output) {
const checks = parseCIChecks(result.output);
if (checks.length > 0) {
const checkLines = checks.map((c) => `${c.emoji} ${c.name}`).join('\n');
output += `\n\n${checkLines}`;
}
}
// Truncate if too long
if (output.length > maxChars) {
output = output.slice(0, maxChars - 20) + '\n... (truncated)';
}
return output;
}
/**
* Format full CI status with PR info and preview URLs
*
* @param prNumber - PR number
* @param prUrl - PR URL
* @param ciResult - CI check result
* @param ciRun - CI run details
* @param previewUrls - Preview URLs
* @param maxChars - Maximum output characters (default: 500)
* @returns Formatted status string
*
* @example
* ```typescript
* const status = formatFullCIStatus(
* 123, 'https://github.com/...', ciResult, ciRun, previewUrls
* );
* ```
*/
export function formatFullCIStatus(
prNumber: number,
prUrl: string,
ciResult: CICheckResult,
ciRun: CIRunDetails | null,
previewUrls: PreviewUrls,
maxChars: number = MAX_OUTPUT_CHARS
): string {
let output = `**PR #${prNumber}**\n`;
// CI status
if (ciResult.success) {
output += '✅ All CI checks passed\n';
} else if (ciResult.error) {
output += `⏱️ ${ciResult.error}\n`;
} else {
output += '❌ CI checks failed\n';
}
// CI run link
if (ciRun?.url) {
output += `🔗 [CI](${ciRun.url})\n`;
}
// Preview URLs
if (previewUrls.allUrls.length > 0) {
output += `🌐 ${previewUrls.allUrls[0]}`;
if (previewUrls.allUrls.length > 1) {
output += ` (+${previewUrls.allUrls.length - 1})`;
}
output += '\n';
}
// Truncate if too long
if (output.length > maxChars) {
output = output.slice(0, maxChars - 20) + '\n... (truncated)';
}
return output;
}
// ============================================================================
// Fail-Fast CI Checking
// ============================================================================
/**
* Check if PR has merge conflicts
*
* Queries GitHub API for the PR's mergeable state and returns immediately
* if conflicts are detected.
*
* @param prNumber - PR number to check
* @param cwd - Working directory
* @returns Merge conflict result
*
* @example
* ```typescript
* const conflicts = await checkMergeConflicts(123, '/path/to/repo');
* if (conflicts.hasConflicts) {
* console.log('PR has merge conflicts!');
* }
* ```
*/
export async function checkMergeConflicts(
prNumber: number,
cwd: string
): Promise<MergeConflictResult> {
const result = await execCommand(
`gh pr view ${prNumber} --json mergeable,mergeStateStatus`,
cwd
);
if (!result.success) {
return { hasConflicts: false, error: `Failed to check PR: ${result.stderr}` };
}
try {
const data = JSON.parse(result.stdout);
const mergeable = data.mergeable;
const mergeStateStatus = data.mergeStateStatus;
// CONFLICTING means merge conflicts exist
// UNKNOWN means GitHub is still calculating
const hasConflicts = mergeable === 'CONFLICTING' || mergeStateStatus === 'DIRTY';
return {
hasConflicts,
mergeableState: mergeStateStatus || mergeable,
};
} catch {
return { hasConflicts: false, error: 'Failed to parse PR data' };
}
}
/**
* Check if branch is behind main/master
*