Skip to content

Commit

Permalink
feat: add action parameter for comment title
Browse files Browse the repository at this point in the history
  • Loading branch information
gkampitakis committed Nov 8, 2021
1 parent 66bb914 commit 62a4fbc
Show file tree
Hide file tree
Showing 14 changed files with 134 additions and 97 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ jobs:
---
License MIT
> For releasing and versioning the github action https://github.com/actions/toolkit/blob/master/docs/action-versioning.md#recommendations.
**License MIT**
16 changes: 10 additions & 6 deletions action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,18 @@ inputs:
description: Github Token for Github API requests.
review-message:
required: false
description: >
You can specify a message at the end of the comment.
It will tag the creator of pull request
description: >
[String] You can specify a message at the end of the comment.
It will tag the creator of pull request.
tags:
required: false
description: >
Keywords that the parser will try to identify for creating comments.
description: >
[String comma separate] Keywords that the parser will try to identify for creating comments.
Default tags are TODO:,FIXME:,BUG:
ignore-pattern:
required: false
description: Regex used for filtering files out from parsing.
description: '[Regex] Regex used for filtering files out from parsing.'
comment-title:
required: false
description: >
[String] The title of the comment. Default value is Todo Commenter.
4 changes: 2 additions & 2 deletions lib/index.js

Large diffs are not rendered by default.

26 changes: 8 additions & 18 deletions src/action-parameters.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,25 @@
import { getInput } from '@actions/core';
import { Context } from '@actions/github/lib/context';

export function getInputs(): {
token: string;
reviewMsg: string;
ignoreFilesPattern: string;
tags: string[];
} {
import { GetInputParams, GetActionParams } from './types';

export function getInputs(): GetInputParams {
const tags = getInput('tags') || 'TODO:,FIXME:,BUG:';
const reviewMsg = getInput('review-message');
const ignoreFilesPattern = getInput('ignore-pattern');
const token = getInput('github-token') || '';

if (token === '') {
throw new Error(`Action needs 'GITHUB_TOKEN' in order to work correctly`);
}
const token = getInput('github-token', { required: true });
const commentTitle = getInput('comment-title') || 'Todo Commenter';

return {
tags: tags.split(','),
reviewMsg,
token,
ignoreFilesPattern
ignoreFilesPattern,
commentTitle
};
}

export function getActionParameters(ctx: Context): {
actor: string;
owner: string;
repo: string;
prNumber: number;
} {
export function getActionParameters(ctx: Context): GetActionParams {
const {
actor,
repo: { owner, repo },
Expand Down
36 changes: 18 additions & 18 deletions src/action-reviewer.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import { ActionReviewerConstructor, Octokit } from './types';
import { info } from 'console';
import { ActionReviewerOptions, Octokit } from './types';

export class ActionReviewer {
private octokit: Octokit;
private owner: string;
private repo: string;
private prNumber: number;
private options: ActionReviewerOptions;

constructor({ octokit, owner, repo, prNumber }: ActionReviewerConstructor) {
constructor(octokit: Octokit, options: ActionReviewerOptions) {
this.octokit = octokit;
this.owner = owner;
this.repo = repo;
this.prNumber = prNumber;
this.options = options;
}

public async createReview(body: string) {
const { id, body: oldReviewBody } = await this.reviewExists();

if (oldReviewBody === body) return;
if (oldReviewBody === body) {
info('No new changes detected since last commit');
return;
}

if (id) {
await this.deleteReview(id);
}

await this.octokit.rest.issues.createComment({
owner: this.owner,
repo: this.repo,
issue_number: this.prNumber,
owner: this.options.owner,
repo: this.options.repo,
issue_number: this.options.prNumber,
body
});

Expand All @@ -34,17 +34,17 @@ export class ActionReviewer {

public async deleteReview(id: number) {
return this.octokit.rest.issues.deleteComment({
owner: this.owner,
repo: this.repo,
owner: this.options.owner,
repo: this.options.repo,
comment_id: id
});
}

public async reviewExists(): Promise<{ id?: number; body?: string }> {
const { data: allReviews } = await this.octokit.rest.issues.listComments({
owner: this.owner,
repo: this.repo,
issue_number: this.prNumber
owner: this.options.owner,
repo: this.options.repo,
issue_number: this.options.prNumber
});

if (allReviews.length === 0) {
Expand All @@ -54,7 +54,7 @@ export class ActionReviewer {
const review = allReviews.find(item => {
return (
item.user?.login === 'github-actions[bot]' &&
item.body?.startsWith('## Todo Commenter\n')
item.body?.startsWith(`## ${this.options.commentTitle}`)
);
});

Expand Down
15 changes: 10 additions & 5 deletions src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { formatComment } from './format-comment';

export async function run() {
try {
const { tags, reviewMsg, token, ignoreFilesPattern } = getInputs();
const { tags, reviewMsg, token, ignoreFilesPattern, commentTitle } =
getInputs();
const { actor, owner, prNumber, repo } = getActionParameters(context);
const octokit = getOctokit(token);

Expand All @@ -21,11 +22,11 @@ export async function run() {
ignoreFilesPattern
});
const analyzedComments = await fileAnalyzer(files, tags);
const actionReviewer = new ActionReviewer({
const actionReviewer = new ActionReviewer(octokit, {
owner,
repo,
octokit,
prNumber
prNumber,
commentTitle
});

if (analyzedComments.length === 0) {
Expand All @@ -38,7 +39,11 @@ export async function run() {
return;
}

const comment = formatComment(analyzedComments, { actor, reviewMsg });
const comment = formatComment(analyzedComments, {
actor,
reviewMsg,
title: commentTitle
});

await actionReviewer.createReview(comment);
} catch (error: any) {
Expand Down
6 changes: 3 additions & 3 deletions src/format-comment.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { FileAnalyzerResults } from './types';
import { FileAnalyzerResults, FormatCommentOptions } from './types';

export function formatComment(
analyzedCommentsPerFile: FileAnalyzerResults,
{ actor, reviewMsg }: { actor?: string; reviewMsg?: string }
{ actor, reviewMsg, title }: FormatCommentOptions
) {
let message = '## Todo Commenter\n';
let message = `## ${title}\n`;

analyzedCommentsPerFile.forEach(({ comments, file }) => {
message += `<details>\n`;
Expand Down
10 changes: 2 additions & 8 deletions src/pr-files.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { Octokit } from './types';
import { GetFilesParams } from './types';

export async function getFiles({
octokit,
owner,
repo,
prNumber,
ignoreFilesPattern
}: {
octokit: Octokit;
owner: string;
repo: string;
prNumber: number;
ignoreFilesPattern?: string;
}): Promise<string[]> {
}: GetFilesParams) {
const { data: prFiles } = await octokit.rest.pulls.listFiles({
owner,
repo,
Expand Down
35 changes: 32 additions & 3 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,51 @@ import { getOctokit } from '@actions/github';

export type Octokit = ReturnType<typeof getOctokit>;
export type Comments = Record<
string,
string, // This is the tag
{
comment: string;
line: number;
}[]
>;
export type EnhancedTag = { tag: string; regex: RegExp };

export type ActionReviewerConstructor = {
octokit: Octokit;
export type ActionReviewerOptions = {
owner: string;
repo: string;
prNumber: number;
commentTitle: string;
};

export type FileAnalyzerResults = {
file: string;
comments: Comments;
}[];

export type GetInputParams = {
token: string;
reviewMsg: string;
ignoreFilesPattern: string;
tags: string[];
commentTitle: string;
};

export type GetActionParams = {
actor: string;
owner: string;
repo: string;
prNumber: number;
};

export type FormatCommentOptions = {
actor?: string;
reviewMsg?: string;
title: string;
};

export type GetFilesParams = {
octokit: Octokit;
owner: string;
repo: string;
prNumber: number;
ignoreFilesPattern?: string;
};
24 changes: 24 additions & 0 deletions tests/__snapshots__/action-paramaters.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`getActionParameters should return action parameters 1`] = `
Object {
"actor": "mock-actor",
"owner": "mock-owner",
"prNumber": 10,
"repo": "mock-repo",
}
`;

exports[`getInputs should return all inputs 1`] = `
Object {
"commentTitle": "my title",
"ignoreFilesPattern": "mock-pattern",
"reviewMsg": "hello world",
"tags": Array [
"test:",
"data:",
"more",
],
"token": "mock-token",
}
`;
12 changes: 6 additions & 6 deletions tests/__snapshots__/format-comment.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`FormatComment should format comment consistently 1`] = `
"## Todo Commenter
"## mock title
<details>
<summary><strong>./tests/mockFiles/mockFile0.js</strong></summary>
<summary><strong>tests/mockFiles/mockFile0.js</strong></summary>
##### FIXME:
Expand All @@ -24,7 +24,7 @@ exports[`FormatComment should format comment consistently 1`] = `
</details>
<details>
<summary><strong>./tests/mockFiles/mockFile2.js</strong></summary>
<summary><strong>tests/mockFiles/mockFile2.js</strong></summary>
##### FIXME:
Expand All @@ -44,9 +44,9 @@ exports[`FormatComment should format comment consistently 1`] = `
`;
exports[`FormatComment should tag actor with reviewMsg 1`] = `
"## Todo Commenter
"## mock title
<details>
<summary><strong>./tests/mockFiles/mockFile0.js</strong></summary>
<summary><strong>tests/mockFiles/mockFile0.js</strong></summary>
##### FIXME:
Expand All @@ -67,7 +67,7 @@ exports[`FormatComment should tag actor with reviewMsg 1`] = `
</details>
<details>
<summary><strong>./tests/mockFiles/mockFile2.js</strong></summary>
<summary><strong>tests/mockFiles/mockFile2.js</strong></summary>
##### FIXME:
Expand Down
23 changes: 4 additions & 19 deletions tests/action-paramaters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ describe('getActionParameters', () => {
}
} as Context;

expect(getActionParameters(ctx)).toEqual({
actor: 'mock-actor',
owner: 'mock-owner',
repo: 'mock-repo',
prNumber: 10
});
expect(getActionParameters(ctx)).toMatchSnapshot();
});

it("should throw error if event != 'pull_request'", () => {
Expand Down Expand Up @@ -66,21 +61,11 @@ describe('getInputs', () => {
'github-token': 'mock-token',
tags: 'test:,data:,more',
'review-message': 'hello world',
'ignore-pattern': 'mock-pattern'
'ignore-pattern': 'mock-pattern',
'comment-title': 'my title'
};
const inputs = getInputs();

expect(inputs).toEqual({
token: 'mock-token',
tags: ['test:', 'data:', 'more'],
reviewMsg: 'hello world',
ignoreFilesPattern: 'mock-pattern'
});
});

it("should throw error if 'GITHUB_TOKEN' is not provided", () => {
expect(() => getInputs()).toThrowError(
"Action needs 'GITHUB_TOKEN' in order to work correctly"
);
expect(inputs).toMatchSnapshot();
});
});
Loading

0 comments on commit 62a4fbc

Please sign in to comment.