Skip to content

Commit

Permalink
User createReviewComment instead of createComment
Browse files Browse the repository at this point in the history
  • Loading branch information
rehlma committed Apr 11, 2024
1 parent af7b6f8 commit f79ab8b
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 80 deletions.
96 changes: 54 additions & 42 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29015,26 +29015,22 @@ const core = __importStar(__nccwpck_require__(2186));
const github = __importStar(__nccwpck_require__(5438));
function run() {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
try {
const token = core.getInput('token');
const octokit = github.getOctokit(token);
const base = core.getInput('base');
const head = core.getInput('head');
const baseRef = base || ((_a = github.context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.base.sha);
const headRef = head || ((_b = github.context.payload.pull_request) === null || _b === void 0 ? void 0 : _b.head.sha);
if (!baseRef || !headRef) {
throw new Error('Base or head ref not found');
const pr = github.context.payload.pull_request;
if (!pr) {
throw new Error('This action can only be run on pull requests');
}
const prDiff = yield getPrDiff(octokit, baseRef, headRef);
const prDiff = yield getPrDiff(octokit, pr.base.sha, pr.head.sha);
const todos = findTodos(prDiff);
console.log('Todos:', todos);
console.log('Todos:', JSON.stringify(todos));
const useOutput = core.getInput('use-output');
if (useOutput === 'true') {
core.setOutput('todos', todos);
}
else {
yield commentPr(octokit, headRef, todos);
yield commentPr(octokit, pr.number, todos);
// core.setOutput('comment', comment)
}
}
Expand Down Expand Up @@ -29104,12 +29100,12 @@ function getTodoIfFound(line) {
const regex = /[/*#]+.*(TODO.*)/gi;
const matches = [...line.matchAll(regex)];
if (matches === undefined || matches.length === 0)
return '';
return;
return matches[0][1];
}
function commentPr(octokit, headSha, todos) {
function commentPr(octokit, prNumber, todos) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
var _a, _b;
const { owner, repo } = github.context.repo;
const issueNumber = (_a = github.context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number;
if (!issueNumber)
Expand All @@ -29120,34 +29116,49 @@ function commentPr(octokit, headSha, todos) {
repo,
issue_number: issueNumber
});
const headSha = (_b = github.context.payload.pull_request) === null || _b === void 0 ? void 0 : _b.head.sha;
// Find the comment created by this action
const existingComment = comments.find(entry => {
var _a, _b;
return ((_a = entry.user) === null || _a === void 0 ? void 0 : _a.login) === 'github-actions[bot]' &&
((_b = entry.body) === null || _b === void 0 ? void 0 : _b.startsWith('**New TODOs found in this PR:**'));
});
// const existingComment = comments.find(
// entry =>
// entry.user?.login === 'github-actions[bot]' &&
// entry.body?.startsWith('**New TODOs found in this PR:**')
// )
// If the comment exists, update it; otherwise, create a new comment
if (existingComment) {
// console.log(`Update existing comment #${existingComment.id}`)
// await octokit.rest.issues.updateComment({
// owner,
// repo,
// comment_id: existingComment.id,
// body: comment
// })
}
if (false) {}
else {
console.log(`Create new comment`);
for (const todo of todos) {
const comment = generateComment(todo.todos.map(t => t.content), []);
yield octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: comment,
path: todo.filename,
position: todo.todos[todo.todos.length - 1].line
});
const addedTodos = todo.todos.filter(todo => todo.added);
const removedTodos = todo.todos.filter(todo => !todo.added);
const comment = generateComment(addedTodos.map(todo => todo.content), removedTodos.map(todo => todo.content));
if (addedTodos.length !== 0) {
yield octokit.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
body: comment.newComment,
commit_id: headSha,
path: todo.filename,
start_side: 'RIGHT',
side: 'RIGHT',
start_line: addedTodos[0].line,
line: addedTodos[addedTodos.length - 1].line
});
}
if (removedTodos.length !== 0) {
yield octokit.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
body: comment.newComment,
commit_id: headSha,
path: todo.filename,
start_side: 'LEFT',
side: 'LEFT',
start_line: removedTodos[0].line,
line: removedTodos[removedTodos.length - 1].line
});
}
}
}
console.log('Current head sha is:', headSha);
Expand All @@ -29173,16 +29184,17 @@ function sum(numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
function generateComment(newTodos, removedTodos) {
let comment = '**New TODOs found in this PR:**\n';
let newComment = '**New TODOs:**\n';
for (const todo of newTodos) {
comment += `- [ ] ${todo}\n`;
newComment += `- [ ] ${todo}\n`;
}
comment += '\n**Solved TODOs found in this PR:**\n';
let solvedComment = '**Solved TODOs**\n';
for (const todo of removedTodos) {
comment += `- [x] ${todo}\n`;
solvedComment += `- [x] ${todo}\n`;
}
console.log('Comment:', comment);
return comment;
console.log('New Tdods comment:', newComment);
console.log('Solved Tdods comment:', solvedComment);
return { newComment, solvedComment };
}


Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

99 changes: 62 additions & 37 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
import * as core from '@actions/core'
import * as github from '@actions/github'
import { PrDiff, Todo, InnerTodo } from './types'
import { start } from 'repl'

Check failure on line 4 in src/main.ts

View workflow job for this annotation

GitHub Actions / Lint Codebase

'start' is defined but never used

Check failure on line 4 in src/main.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests

'start' is defined but never used

export async function run(): Promise<void> {
try {
const token = core.getInput('token')
const octokit = github.getOctokit(token)

const base = core.getInput('base')
const head = core.getInput('head')

const baseRef = base || github.context.payload.pull_request?.base.sha
const headRef = head || github.context.payload.pull_request?.head.sha

if (!baseRef || !headRef) {
throw new Error('Base or head ref not found')
const pr = github.context.payload.pull_request
if (!pr) {
throw new Error('This action can only be run on pull requests')
}

const prDiff = await getPrDiff(octokit, baseRef, headRef)
const prDiff = await getPrDiff(octokit, pr.base.sha, pr.head.sha)

const todos = findTodos(prDiff)
console.log('Todos:', JSON.stringify(todos))
Expand All @@ -26,7 +21,7 @@ export async function run(): Promise<void> {
if (useOutput === 'true') {
core.setOutput('todos', todos)
} else {
await commentPr(octokit, headRef, todos)
await commentPr(octokit, pr.number, todos)
// core.setOutput('comment', comment)
}
} catch (error) {
Expand Down Expand Up @@ -94,16 +89,16 @@ export function findTodos(prDiff: PrDiff): Todo[] {
return todos
}

function getTodoIfFound(line: string): string {
function getTodoIfFound(line: string): string | undefined {
const regex = /[/*#]+.*(TODO.*)/gi
const matches = [...line.matchAll(regex)]
if (matches === undefined || matches.length === 0) return ''
if (matches === undefined || matches.length === 0) return
return matches[0][1]
}

async function commentPr(
octokit: ReturnType<typeof github.getOctokit>,
headSha: string,
prNumber: number,
todos: Todo[]
): Promise<void> {
const { owner, repo } = github.context.repo
Expand All @@ -118,15 +113,17 @@ async function commentPr(
issue_number: issueNumber
})

const headSha = github.context.payload.pull_request?.head.sha

// Find the comment created by this action
const existingComment = comments.find(
entry =>
entry.user?.login === 'github-actions[bot]' &&
entry.body?.startsWith('**New TODOs found in this PR:**')
)
// const existingComment = comments.find(
// entry =>
// entry.user?.login === 'github-actions[bot]' &&
// entry.body?.startsWith('**New TODOs found in this PR:**')
// )

// If the comment exists, update it; otherwise, create a new comment
if (existingComment) {
if (false) {

Check failure on line 126 in src/main.ts

View workflow job for this annotation

GitHub Actions / Lint Codebase

Unexpected constant condition

Check failure on line 126 in src/main.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests

Unexpected constant condition
// console.log(`Update existing comment #${existingComment.id}`)
// await octokit.rest.issues.updateComment({
// owner,
Expand All @@ -137,18 +134,42 @@ async function commentPr(
} else {
console.log(`Create new comment`)
for (const todo of todos) {
const addedTodos = todo.todos.filter(todo => todo.added)

Check failure on line 137 in src/main.ts

View workflow job for this annotation

GitHub Actions / Lint Codebase

'todo' is already declared in the upper scope on line 136 column 16

Check failure on line 137 in src/main.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests

'todo' is already declared in the upper scope on line 136 column 16
const removedTodos = todo.todos.filter(todo => !todo.added)

Check failure on line 138 in src/main.ts

View workflow job for this annotation

GitHub Actions / Lint Codebase

'todo' is already declared in the upper scope on line 136 column 16

Check failure on line 138 in src/main.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests

'todo' is already declared in the upper scope on line 136 column 16
const comment = generateComment(
todo.todos.map(t => t.content),
[]
addedTodos.map(todo => todo.content),
removedTodos.map(todo => todo.content)
)
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: comment,
path: todo.filename,
position: todo.todos[todo.todos.length - 1].line
})

if (addedTodos.length !== 0) {
await octokit.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
body: comment.newComment,
commit_id: headSha,
path: todo.filename,
start_side: 'RIGHT',
side: 'RIGHT',
start_line: addedTodos[0].line,
line: addedTodos[addedTodos.length - 1].line
})
}

if (removedTodos.length !== 0) {
await octokit.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
body: comment.newComment,
commit_id: headSha,
path: todo.filename,
start_side: 'LEFT',
side: 'LEFT',
start_line: removedTodos[0].line,
line: removedTodos[removedTodos.length - 1].line
})
}
}
}

Expand Down Expand Up @@ -178,16 +199,20 @@ function sum(numbers: number[]): number {
return numbers.reduce((acc, curr) => acc + curr, 0)
}

function generateComment(newTodos: string[], removedTodos: string[]): string {
let comment = '**New TODOs found in this PR:**\n'
function generateComment(
newTodos: string[],
removedTodos: string[]
): { newComment: string; solvedComment: string } {
let newComment = '**New TODOs:**\n'
for (const todo of newTodos) {
comment += `- [ ] ${todo}\n`
newComment += `- [ ] ${todo}\n`
}
comment += '\n**Solved TODOs found in this PR:**\n'
let solvedComment = '**Solved TODOs**\n'
for (const todo of removedTodos) {
comment += `- [x] ${todo}\n`
solvedComment += `- [x] ${todo}\n`
}

console.log('Comment:', comment)
return comment
console.log('New Tdods comment:', newComment)
console.log('Solved Tdods comment:', solvedComment)
return { newComment, solvedComment }
}

0 comments on commit f79ab8b

Please sign in to comment.