scai
Version:
> **AI-powered CLI for local code analysis, commit message suggestions, and natural-language queries.** 100% local, private, GDPR-friendly, made in Denmark/EU with ❤️.
70 lines (69 loc) • 2.75 kB
JavaScript
import { Octokit } from '@octokit/rest';
/**
* Parses the PR diff to determine the correct position for inline comments.
* The position is the "index" of the changed line in the diff.
* @param diff The diff content of the PR
* @param lineNumber The line number to convert to a position in the diff
*/
function getLinePositionFromDiff(diff, lineNumber) {
const lines = diff.split('\n');
let currentLine = 0;
// Iterate through the lines and determine the correct position for the lineNumber
for (let i = 0; i < lines.length; i++) {
// Only count the lines that are part of a diff chunk
if (lines[i].startsWith('+') || lines[i].startsWith('-')) {
currentLine++;
if (currentLine === lineNumber) {
return i; // Position is the index of the changed line in the diff
}
}
}
return null; // Return null if lineNumber is not found in the diff
}
/**
* Posts an inline review comment on a specific line of a PR.
*
* @param token GitHub personal access token
* @param owner Repository owner (e.g. 'my-org')
* @param repo Repository name (e.g. 'my-repo')
* @param prNumber Pull Request number
* @param fileName Path to the file in the PR (relative to repo root)
* @param lineNumber Line number to comment on in the file (not in the diff)
* @param comment Text of the comment
*/
export async function postReviewComment(token, owner, repo, prNumber, fileName, lineNumber, comment) {
const octokit = new Octokit({ auth: `token ${token}` });
// First, get PR details so we can retrieve the head commit SHA
const pr = await octokit.pulls.get({
owner,
repo,
pull_number: prNumber,
});
const commitId = pr.data.head.sha;
// Fetch the PR diff by getting the full diff URL from the PR
const diffUrl = pr.data.diff_url;
const diffRes = await fetch(diffUrl);
const diff = await diffRes.text();
// Get the position of the line in the diff
const position = getLinePositionFromDiff(diff, lineNumber);
if (position === null) {
console.error(`❌ Unable to find line ${lineNumber} in the diff for PR #${prNumber}.`);
return;
}
// Now, post the inline comment
try {
await octokit.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
commit_id: commitId,
path: fileName,
body: comment,
position: position, // Use the position calculated from the diff
});
console.log(`✅ Inline comment posted to ${fileName} at diff position ${position}.`);
}
catch (err) {
console.error(`❌ Error posting inline comment: ${err.message}`);
}
}