All files / ado-api pull-requests.ts

97.02% Statements 98/101
72% Branches 54/75
100% Functions 17/17
97.87% Lines 92/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                      5x       1x       2x 2x       1x 1x       1x 1x         1x         1x           29x 29x                     9x 32x   24x 24x 24x         16x 16x 16x 16x 8x 8x   16x                         8x 8x 16x   8x     8x 8x 8x 8x 8x 8x 8x 8x 8x     8x 8x 8x 8x 1x 1x       8x 8x 7x 14x 14x     1x       8x 8x 1x   7x 14x         8x 8x 5x 5x       8x 8x 20x   15x 15x   8x 5x 5x 15x 15x 15x   15x 5x 5x     15x   15x 15x 15x 15x 15x 15x   15x         15x 15x 5x           8x 8x 8x 8x     8x 1x 1x 1x     8x    
import { AdoClient } from './client';
 
// Types
export interface PrDetails {
    pullRequestId: number;
    title: string;
    status: string;
    repository: { name: string };
    sourceRefName: string;
    targetRefName: string;
    isDraft: boolean;
    mergeStatus: string;
    description: string;
    createdBy: { displayName: string; uniqueName: string };
    creationDate: string;
    closedBy?: { displayName: string };
    closedDate?: string;
    reviewers: Array<{
        displayName: string;
        vote: number;
        isRequired: boolean;
    }>;
}
 
export interface PrThread {
    id: number;
    status: string;
    threadContext?: {
        filePath?: string;
        rightFileStart?: { line: number };
        leftFileStart?: { line: number };
    };
    comments: Array<{
        id: number;
        content: string;
        commentType: string;
        author: { displayName: string; uniqueName: string };
        publishedDate: string;
    }>;
}
 
export interface PrIteration {
    id: number;
    createdDate: string;
    updatedDate: string;
    sourceRefCommit?: { commitId: string };
    targetRefCommit?: { commitId: string };
}
 
export interface PrCommit {
    commitId: string;
    comment: string;
    author: { name: string; date: string };
}
 
export interface CopilotThread {
    threadId: number;
    status: string;
    filePath: string | null;
    startLine: number | null;
    content: string;
    replies: Array<{ author: string; content: string; publishedDate: string }>;
}
 
// API Fetchers
 
function prPath(repo: string, prId: number): string {
    return `git/repositories/${encodeURIComponent(repo)}/pullrequests/${prId}`;
}
 
export async function fetchPrDetails(client: AdoClient, repo: string, prId: number): Promise<PrDetails> {
    return client.get<PrDetails>(prPath(repo, prId));
}
 
export async function fetchPrIterations(client: AdoClient, repo: string, prId: number): Promise<PrIteration[]> {
    const result = await client.get<{ value: PrIteration[] }>(`${prPath(repo, prId)}/iterations`);
    return result.value ?? [];
}
 
export async function fetchPrThreads(client: AdoClient, repo: string, prId: number): Promise<PrThread[]> {
    const result = await client.get<{ value: PrThread[] }>(`${prPath(repo, prId)}/threads`);
    return result.value ?? [];
}
 
export async function fetchPrCommits(client: AdoClient, repo: string, prId: number): Promise<PrCommit[]> {
    const result = await client.get<{ value: PrCommit[] }>(`${prPath(repo, prId)}/commits`);
    return result.value ?? [];
}
 
// Helpers
 
const VOTE_LABELS: Record<number, string> = {
    10: 'Approved', 5: 'Approved with suggestions', 0: 'No vote',
    [-5]: 'Waiting for author', [-10]: 'Rejected',
};
 
const THREAD_STATUS_LABELS: Record<string, string> = {
    active: 'Active', fixed: 'Resolved', closed: 'Closed',
    wontFix: "Won't Fix", pending: 'Pending', byDesign: 'By Design',
};
 
function formatDate(dateStr: string): string {
    Iif (!dateStr) return 'N/A';
    try { return new Date(dateStr).toISOString().replace('T', ' ').substring(0, 16); }
    catch { return dateStr; }
}
 
// Copilot Thread Filtering
 
/**
 * Filters threads to those created by the Copilot review agent.
 * Matches by Build Service author OR comment containing a known attribution tag.
 */
export function filterCopilotThreads(threads: PrThread[]): CopilotThread[] {
    return threads
        .filter(t => t.comments?.length > 0 && t.comments[0].commentType !== 'system')
        .filter(t => {
            const first = t.comments[0];
            const authorLower = `${first.author.displayName} ${first.author.uniqueName}`.toLowerCase();
            return authorLower.includes('build service')
                || (first.content ?? '').includes('[Generated by GitHub Copilot]')
                || (first.content ?? '').includes('[Generated by Claude Code]');
        })
        .map(t => {
            const first = t.comments[0];
            const filePath = t.threadContext?.filePath ?? null;
            const startLine = t.threadContext?.rightFileStart?.line ?? t.threadContext?.leftFileStart?.line ?? null;
            const replies = t.comments.slice(1)
                .filter(c => c.commentType !== 'system')
                .map(c => ({ author: c.author.displayName, content: c.content, publishedDate: c.publishedDate }));
 
            return { threadId: t.id, status: t.status, filePath, startLine, content: first.content, replies };
        });
}
 
// Text Formatting
 
export function formatPrDetailsText(
    pr: PrDetails,
    threads: PrThread[],
    iterations: PrIteration[],
    copilotThreads: CopilotThread[],
    collectionUri: string
): string {
    const sep = '='.repeat(80);
    const lines: string[] = [];
    const branch = (ref: string) => (ref ?? '').replace(/^refs\/heads\//, '');
 
    lines.push('', sep, 'PULL REQUEST DETAILS', sep);
 
    // Basic Information
    lines.push('', '[Basic Information]');
    lines.push(`  ID:              #${pr.pullRequestId}`);
    lines.push(`  Title:           ${pr.title}`);
    lines.push(`  Status:          ${(pr.status ?? '').toUpperCase()}`);
    lines.push(`  Repository:      ${pr.repository?.name ?? ''}`);
    lines.push(`  Source Branch:   ${branch(pr.sourceRefName)}`);
    lines.push(`  Target Branch:   ${branch(pr.targetRefName)}`);
    lines.push(`  Is Draft:        ${pr.isDraft}`);
    lines.push(`  Merge Status:    ${pr.mergeStatus ?? ''}`);
 
    // People
    lines.push('', '[People]');
    lines.push(`  Created By:      ${pr.createdBy?.displayName ?? ''} <${pr.createdBy?.uniqueName ?? ''}>`);
    lines.push(`  Created Date:    ${formatDate(pr.creationDate)}`);
    if (pr.closedBy) {
        lines.push(`  Closed By:       ${pr.closedBy.displayName}`);
        Eif (pr.closedDate) lines.push(`  Closed Date:     ${formatDate(pr.closedDate)}`);
    }
 
    // Reviewers
    lines.push('', '[Reviewers]');
    if (pr.reviewers?.length > 0) {
        for (const r of pr.reviewers) {
            const required = r.isRequired ? ' (Required)' : '';
            lines.push(`  - ${r.displayName}${required} : ${VOTE_LABELS[r.vote] ?? 'Unknown'}`);
        }
    } else {
        lines.push('  No reviewers assigned');
    }
 
    // Description
    lines.push('', '[Description]');
    if (!pr.description) {
        lines.push('  (No description provided)');
    } else {
        for (const line of pr.description.replace(/\r\n/g, '\n').split('\n')) {
            lines.push(`  ${line}`);
        }
    }
 
    // Iterations
    lines.push('', '[Iterations/Updates]');
    if (iterations?.length > 0) {
        lines.push(`  Total iterations: ${iterations.length}`);
        lines.push(`  Last updated:     ${formatDate(iterations[iterations.length - 1].updatedDate)}`);
    }
 
    // Comment Threads
    lines.push('', '[Comments/Threads]');
    const commentThreads = threads.filter(t =>
        t.comments?.length > 0 && t.comments[0].commentType !== 'system'
    );
    lines.push(`  Active threads:   ${commentThreads.filter(t => t.status === 'active').length}`);
    lines.push(`  Resolved threads: ${commentThreads.filter(t => t.status === 'fixed' || t.status === 'closed').length}`);
 
    if (commentThreads.length > 0) {
        lines.push('', '  --- Top-Level Comments ---');
        for (const thread of commentThreads) {
            const first = thread.comments[0];
            lines.push('');
            lines.push(`  Thread #${thread.id} [${THREAD_STATUS_LABELS[thread.status] ?? thread.status ?? ''}]`);
 
            if (thread.threadContext?.filePath) {
                const lineNum = thread.threadContext.rightFileStart?.line ?? thread.threadContext.leftFileStart?.line;
                lines.push(`  File: ${thread.threadContext.filePath}${lineNum ? ` (Line ${lineNum})` : ''}`);
            }
 
            lines.push(`  Author: ${first.author.displayName} | ${formatDate(first.publishedDate)}`);
 
            Eif (first.content) {
                const contentLines = first.content.split('\n');
                const display = contentLines.slice(0, 30);
                for (const l of display) {
                    const trimmed = l.trim();
                    Eif (trimmed) lines.push(`    ${trimmed}`);
                }
                Iif (display.length < contentLines.length) {
                    lines.push(`    ... (${contentLines.length - display.length} more lines)`);
                }
            }
 
            const replyCount = thread.comments.length - 1;
            if (replyCount > 0) {
                lines.push(`    [${replyCount} ${replyCount === 1 ? 'reply' : 'replies'}]`);
            }
        }
    }
 
    // Links
    const collectionBase = collectionUri.replace(/\/+$/, '');
    lines.push('', '[Links]');
    lines.push(`  Web URL: ${collectionBase}/${pr.repository?.name ?? ''}/pullrequest/${pr.pullRequestId}`);
    lines.push('', sep);
 
    // Copilot Comment Threads JSON section
    if (copilotThreads.length > 0) {
        lines.push('', '=== COPILOT COMMENT THREADS (JSON) ===');
        lines.push(JSON.stringify(copilotThreads));
        lines.push('=== END COPILOT COMMENT THREADS ===');
    }
 
    return lines.join('\n');
}