Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/adapter/cli/reports.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Buffer } from 'node:buffer';
import { createHash } from 'node:crypto';
import { stripVTControlCharacters, styleText } from 'node:util';

import { applyEdits, format, visit } from 'jsonc-parser';
Expand Down Expand Up @@ -678,6 +679,14 @@ export function countViolations(reports: readonly RuleReport[]): number {
return total;
}

function violationSignature(rule: string, subject: Subject): string {
const context = ({ filepath, source, data, captures }: ScopeSubject) => ({ filepath, source, data, captures });
const evaluated = subject.kind === 'scope'
? context(subject)
: { group: subject.group, members: subject.members.map(context) };
return `${createHash('sha256').update(JSON.stringify(evaluated)).digest('hex')}_${rule}`;
}

export async function renderViolationComments(
reports: readonly RuleReport[],
redact: TextRedactor,
Expand Down Expand Up @@ -753,7 +762,7 @@ export async function renderViolationComments(
seen.add(key);
locations.push({ filepath: candidate.filepath, lines: candidate.lines });
}
comments.push({ body, locations });
comments.push({ body, signature: violationSignature(report.name, subject), locations });
}
}
return comments;
Expand Down
72 changes: 69 additions & 3 deletions src/adapter/github/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ import { isolatedGitEnvironment } from '../git/environment.js';
import { createGithubApi, mapping } from './api.js';
import { originRepository, pullNumber, repositoryName, type PullRequest } from './pull-request.js';

type GithubRequest = (path: string, method: 'GET' | 'POST', payload?: object) => Promise<Response>;

const REVIEW_THREADS = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewThreads(first: 100, after: $cursor) {
nodes { isResolved path comments(first: 1) { nodes { body } } }
pageInfo { hasNextPage endCursor }
}
}
}
}`;

async function git(
root: string,
args: readonly string[],
Expand Down Expand Up @@ -145,6 +158,53 @@ async function matchingFile(
}
}

async function unresolvedThreadBodies(
request: GithubRequest,
pull: PullRequest,
): Promise<ReadonlyMap<string, readonly string[]>> {
const [owner, name] = pull.repository.split('/');
const bodies = new Map<string, string[]>();
let cursor: string | null = null;
while (true) {
const response = await request('/graphql', 'POST', {
query: REVIEW_THREADS,
variables: { owner, name, number: pull.number, cursor },
});
const payload = mapping(await response.json().catch(() => undefined));
const data = mapping(payload?.data);
const repository = mapping(data?.repository);
const pullRequest = mapping(repository?.pullRequest);
const threads = mapping(pullRequest?.reviewThreads);
const nodes = threads?.nodes;
const pageInfo = mapping(threads?.pageInfo);
if (!threads || !Array.isArray(nodes) || typeof pageInfo?.hasNextPage !== 'boolean'
|| (pageInfo.hasNextPage && typeof pageInfo.endCursor !== 'string')) {
throw new Error('GitHub API returned an invalid review threads response.');
}
for (const value of nodes) {
const thread = mapping(value);
const comments = mapping(thread?.comments);
const commentNodes = comments?.nodes;
if (!thread || typeof thread.isResolved !== 'boolean' || typeof thread.path !== 'string' || !Array.isArray(commentNodes)) {
throw new Error('GitHub API returned an invalid review threads response.');
}
const firstComment = commentNodes[0];
if (firstComment !== undefined) {
const comment = mapping(firstComment);
if (typeof comment?.body !== 'string') throw new Error('GitHub API returned an invalid review threads response.');
if (!thread.isResolved) {
const pathBodies = bodies.get(thread.path);
if (pathBodies) pathBodies.push(comment.body);
else bodies.set(thread.path, [comment.body]);
}
}
}
if (!pageInfo.hasNextPage) return bodies;
cursor = pageInfo.endCursor as string;
}
}


export function createGithubCommenter(
env: Readonly<Record<string, string | undefined>>,
): (root: string, comments: readonly ViolationComment[], pullRequest?: PullRequest) => Promise<void> {
Expand Down Expand Up @@ -194,9 +254,10 @@ export function createGithubCommenter(
const repository = comments.some(comment => comment.locations.length > 0) ? await repositoryPaths(root, gitEnv) : undefined;
const matched = new Map<string, Promise<PullFile | undefined>>();
const patches = new Map<string, readonly DiffRun[]>();
const inline: ReviewComment[] = [];
const planned: { readonly marker: string; readonly comment: ReviewComment }[] = [];
const fallback: string[] = [];
for (const finding of comments) {
const marker = `<!-- coderuler:${finding.signature} -->`;
const anchors = new Set<string>();
for (const location of finding.locations) {
if (!repository || !Number.isSafeInteger(location.lines.start) || !Number.isSafeInteger(location.lines.end)
Expand All @@ -218,12 +279,17 @@ export function createGithubCommenter(
const key = JSON.stringify([file.filename, start, end]);
if (anchors.has(key)) continue;
anchors.add(key);
inline.push({ path: file.filename, body: finding.body, line: end, side: 'RIGHT',
...(start < end ? { start_line: start, start_side: 'RIGHT' as const } : {}) });
planned.push({ marker, comment: { path: file.filename, body: `${finding.body}\n\n${marker}`, line: end, side: 'RIGHT',
...(start < end ? { start_line: start, start_side: 'RIGHT' as const } : {}) } });
}
if (anchors.size === 0) fallback.push(finding.body);
}

const unresolved = planned.length === 0 ? new Map<string, readonly string[]>() : await unresolvedThreadBodies(request, pull);
const inline = planned
.filter(({ marker, comment }) => !unresolved.get(comment.path)?.some(body => body.includes(marker)))
.map(({ comment }) => comment);

if (await readHead() !== head) throw new Error('GitHub pull request head changed during comment planning; refusing stale findings.');
if (inline.length > 0) {
for (let index = 0; index < inline.length; index += 100) {
Expand Down
1 change: 1 addition & 0 deletions src/app/violation-comments.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export interface ViolationComment {
readonly body: string;
readonly signature: string;
readonly locations: readonly {
readonly filepath: string;
readonly lines: {
Expand Down
43 changes: 40 additions & 3 deletions tests/cli-auto-comment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ interface Review {
}[];
}

async function github(context: TestContext, target: Fixture, postStatus = 201) {
async function github(context: TestContext, target: Fixture, postStatus = 201, threads: unknown[] = []) {
const requests: RequestRecord[] = [];
const files = ['one', 'two', 'good'].map(name => {
const filename = `src/${name}.txt`;
Expand All @@ -117,6 +117,8 @@ async function github(context: TestContext, target: Fixture, postStatus = 201) {
response.end(JSON.stringify(files));
} else if (request.method === 'GET' && url === '/repos/owner/project/pulls/42') {
response.end(JSON.stringify({ head: { sha: target.head } }));
} else if (request.method === 'POST' && url === '/graphql') {
response.end(JSON.stringify({ data: { repository: { pullRequest: { reviewThreads: { nodes: threads, pageInfo: { hasNextPage: false, endCursor: null } } } } } }));
} else if (request.method === 'POST' && ['/repos/owner/project/pulls/42/reviews', '/repos/owner/project/issues/42/comments'].includes(url)) {
response.statusCode = postStatus;
response.end(JSON.stringify(postStatus === 201 ? { id: 1 } : { message: `Rejected ${TOKEN} ${API_KEY}` }));
Expand All @@ -143,12 +145,20 @@ async function github(context: TestContext, target: Fixture, postStatus = 201) {
}

function posts(requests: readonly RequestRecord[]) {
return requests.filter(request => request.method === 'POST');
return requests.filter(request => request.method === 'POST' && request.url !== '/graphql');
}
const MARKER = /\n\n<!-- coderuler:[0-9a-f]{64}_[\w-]+ -->$/;
function review(requests: readonly RequestRecord[]): Review {
const matching = posts(requests).filter(request => request.url.endsWith('/reviews'));
assert.equal(matching.length, 1);
return JSON.parse(matching[0]!.body) as Review;
const payload = JSON.parse(matching[0]!.body) as Review;
return {
...payload,
comments: payload.comments.map(comment => {
assert.match(comment.body, MARKER);
return { ...comment, body: comment.body.replace(MARKER, '') };
}),
};
}
function fallback(requests: readonly RequestRecord[]): string {
const matching = posts(requests).filter(request => request.url.endsWith('/issues/42/comments'));
Expand Down Expand Up @@ -196,6 +206,33 @@ for (const diff of ['--diff', '--diff-only']) {
});
}

test('repeated runs skip unresolved marked threads and repost after resolution', async context => {
const target = repository('repeated');
const threads: { isResolved: boolean; path: string; comments: { nodes: { body: string }[] } }[] = [];
const requests = await github(context, target, 201, threads);
const args = ['--diff', '--base', target.base, '--auto-comment', '--json'];

const first = await check(target, args);
assert.equal(first.status, 1, first.stderr);
assert.equal(first.stderr, '');
assert.equal(posts(requests).length, 1);
const raw = JSON.parse(posts(requests)[0]!.body) as Review;
threads.push(...raw.comments.map(({ path, body }) => ({ isResolved: false, path, comments: { nodes: [{ body }] } })));

const second = await check(target, args);
assert.equal(second.status, 1, second.stderr);
assert.equal(second.stderr, '');
assert.equal(posts(requests).length, 1, 'unresolved marked threads must suppress a repeat');

for (const thread of threads) thread.isResolved = true;
const third = await check(target, args);
assert.equal(third.status, 1, third.stderr);
assert.equal(third.stderr, '');
assert.equal(posts(requests).length, 2);
assert.deepEqual(JSON.parse(posts(requests)[1]!.body).comments, raw.comments);
assert.equal(requests.filter(request => request.url === '/graphql').length, 3);
});

const CUSTOM = '**Policy** — follow [the guide](https://example.invalid/guide) and keep `snake_case`.\n\n- mention @scope';
for (const kind of ['sync', 'async'] as const) {
test(`subject-based comments (${kind})`, async context => {
Expand Down
16 changes: 12 additions & 4 deletions tests/cli-pr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function evaluations(reports: readonly CheckReportShape[]) {
}

function posts(requests: readonly RequestRecord[]) {
return requests.filter(request => request.method === 'POST');
return requests.filter(request => request.method === 'POST' && request.url !== '/graphql');
}

test('--pr uses current committed base and global policy only on PR changes', async context => {
Expand Down Expand Up @@ -383,13 +383,21 @@ function commentPolicy(target: PrFixture): PrFixture {

function assertCommentTarget(requests: readonly RequestRecord[], target: PrFixture): void {
assert.equal(requests.some(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/pulls?`)), false, 'explicit PR identity must not discover a branch');
assert.ok(requests.every(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/`)), 'unrelated Actions identity must never redirect requests');
const graphql = requests.filter(request => request.url === '/graphql');
assert.ok(graphql.length > 0, 'comment placement must check GraphQL review threads');
for (const request of graphql) assert.deepEqual(JSON.parse(request.body).variables, { owner: 'owner', name: 'project', number: 42, cursor: null });
assert.ok(requests.filter(request => request.url !== '/graphql').every(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/`)), 'unrelated Actions identity must never redirect requests');
const review = posts(requests).filter(request => request.url.endsWith('/pulls/42/reviews'));
assert.equal(review.length, 1);
const payload = JSON.parse(review[0]!.body);
const payload = JSON.parse(review[0]!.body) as { commit_id: string; event: string; comments: { body: string }[] };
assert.equal(payload.commit_id, target.head);
assert.equal(payload.event, 'COMMENT');
assert.deepEqual(payload.comments, [
const marker = /\n\n<!-- coderuler:[0-9a-f]{64}_base -->$/;
const comments = payload.comments.map(({ body, ...comment }) => {
assert.match(body, marker);
return { ...comment, body: body.replace(marker, '') };
});
assert.deepEqual(comments, [
{ path: 'src/changed.txt', body: CUSTOM_COMMENT, line: 1, side: 'RIGHT' },
], 'inline placement requires the PR-head blob to match the analyzed file');
const fallback = posts(requests).filter(request => request.url.endsWith('/issues/42/comments'));
Expand Down
Loading