Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(scripts): implement triage-bot module #24911

Merged
merged 3 commits into from
Sep 26, 2022
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
21 changes: 21 additions & 0 deletions .github/triage-bot.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "../scripts/triage-bot/triage-bot.schema.json",
"params": [
{
"keyword": "(@fluentui/react-northstar)",
"labels": ["Fluent UI react-northstar (v0)"],
"assignees": []
},
{ "keyword": "(@fluentui/react)", "labels": ["Fluent UI react (v8)"], "assignees": [] },
{
"keyword": "(@fluentui/react-components)",
"labels": ["Fluent UI react-components (v9)"],
"assignees": []
},
{
"keyword": "(@fluentui/web-components)",
"labels": ["web-components"],
"assignees": ["chrisdholt"]
}
]
}
15 changes: 6 additions & 9 deletions .github/workflows/issues.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@ jobs:
triage-issue:
runs-on: ubuntu-latest
steps:
- uses: Naturalclar/[email protected]
- uses: actions/checkout@v2
- uses: actions/github-script@v6
with:
title-or-body: 'body'
parameters: '[
{"keywords": ["@fluentui/react-northstar"], "labels": ["Fluent UI react-northstar (v0)"], "assignees": []},
{"keywords": ["@fluentui/react"], "labels": ["Fluent UI react (v8)"], "assignees": []},
{"keywords": ["@fluentui/react-components"], "labels": ["Fluent UI react-components (v9)"], "assignees": []},
{"keywords": ["@fluentui/web-components"],"labels": ["web-components"],"assignees": ["@chrisdholt"]}
]'
github-token: '${{ secrets.GITHUB_TOKEN }}'
script: |
const config = require('./.github/triage-bot.config.json');
const run = require('./scripts/triage-bot');
await run({github,context,core,config});
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@
"update-snapshots": "lage update-snapshots --verbose"
},
"devDependencies": {
"@actions/core": "1.9.1",
"@actions/github": "5.0.3",
"@azure/data-tables": "13.0.0",
"@babel/core": "7.14.8",
"@babel/plugin-proposal-class-properties": "7.14.5",
Expand Down
56 changes: 56 additions & 0 deletions scripts/triage-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Triage Bot

Package for automated issues triage.

> Note: contains logic which needs to be used from within https://github.com/actions/github-script

## Setup

1. Create bot config file `.github/triage-bot.config.json`

```json
{
"$schema": "../scripts/triage-bot/triage-bot.schema.json",
"params": [
{
"keyword": "(@fluentui/react-northstar)",
"labels": ["Fluent UI react-northstar (v0)"],
"assignees": ["team-1"]
},
{ "keyword": "(@fluentui/react)", "labels": ["Fluent UI react (v8)"], "assignees": ["team-2"] },
{
"keyword": "(@fluentui/react-components)",
"labels": ["Fluent UI react-components (v9)"],
"assignees": ["team-3"]
}
]
}
```

2. Create GH workflow

```yml
name: Triage Bot
on:
issues:
types:
- opened

jobs:
triage-issue-manual:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/github-script@v6
with:
script: |
const config = require('./.github/triage-bot.config.json');
const run = require('./scripts/triage-bot');
await run({github,context,core,config});
```

### Outcome

Now on every issue creation, based on project we have chosen, bot will label and add assignees defined by our config automatically

<img width="584" alt="picking library during issue creation" src="https://user-images.githubusercontent.com/1223799/191800000-f73df978-b389-4218-9da7-288cacd32874.png">
1 change: 1 addition & 0 deletions scripts/triage-bot/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./triage-bot').main;
81 changes: 81 additions & 0 deletions scripts/triage-bot/triage-bot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/** @typedef {import('./types').Api} Api */

/**
*
* @param {Api} options
*/
async function main(options) {
const { context, github, core, config } = options;

/** @type {string[]} */
const logs = [];

const issue = context.payload.issue;
if (!issue) {
throw new Error('CONTEXT error. Issue not found');
}
const issueContent = issue.body?.trim() ?? '';

if (!issueContent) {
core.notice('issue body is empty! Exit early');
return;
}

const processedData = config.params.filter(param => {
return issueContent.indexOf(param.keyword) !== -1;
})[0];

if (!processedData) {
logs.push('No keywords match!');
logSummary({ core, logs });
return;
}

await callApi({ context, github, data: processedData, logs });

logSummary({ core, logs });
}

/**
*
* @param {{logs:string[];core:import('@actions/core')}} options
*/
function logSummary(options) {
const { core, logs } = options;
core.startGroup('Summary:');
logs.forEach(log => core.info(log));
core.endGroup();
}

/**
*
* @param {Pick<Api,'context'|'github'> & {data: Api['config']['params'][number]; logs:string[]}} options
*/
async function callApi(options) {
const { context, data, github, logs } = options;

const labelActionResult = await github.rest.issues.addLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: data.labels,
});
if (labelActionResult.status === 200) {
logs.push(`Label set: ${data.labels}`);
}

if (data.assignees.length) {
const assigneeActionResult = await github.rest.issues.addAssignees({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
assignees: data.assignees,
});

if (assigneeActionResult.status === 201) {
logs.push(`Assignees set: ${data.assignees}`);
}
}
}

module.exports = { main };
32 changes: 32 additions & 0 deletions scripts/triage-bot/triage-bot.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Triage Bot Config",
"type": "object",
"properties": {
"params": {
"type": "array",
"items": {
"type": "object",
"properties": {
"assignees": {
"items": {
"type": "string"
},
"type": "array"
},
"keyword": {
"type": "string"
},
"labels": {
"items": {
"type": "string"
},
"type": "array"
}
},
"additionalProperties": false,
"required": ["keyword", "labels", "assignees"]
}
}
}
}
85 changes: 85 additions & 0 deletions scripts/triage-bot/triage-bot.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { main } from './triage-bot';
import type { GithubScriptsParams } from './types';
describe(`triage bot`, () => {
function setup(options: { issueBody: string }) {
const coreSpy = {
startGroup: jest.fn(),
endGroup: jest.fn(),
notice: jest.fn(),
info: jest.fn(),
};
const githubSpy = {
rest: { issues: { addLabels: jest.fn(), addAssignees: jest.fn() } },
};
const contextSpy = {
payload: { issue: { body: options.issueBody } },
issue: { number: 1 },
repo: { owner: 'harold', repo: 'tools' },
} as GithubScriptsParams['context'];

return { core: coreSpy, github: githubSpy, context: contextSpy };
}
it(`should not do anything if no keyword matches issue content`, async () => {
const githubApi = setup({ issueBody: 'This is a bug about hello. For sure its wrong' });
const config = {
params: [
{
keyword: 'kekw',
labels: ['bug'],
assignees: [],
},
],
};

await main({ ...((githubApi as unknown) as GithubScriptsParams), config });

expect(githubApi.github.rest.issues.addLabels).not.toHaveBeenCalled();
expect(githubApi.github.rest.issues.addAssignees).not.toHaveBeenCalled();
});

it(`should assign label`, async () => {
const githubApi = setup({ issueBody: 'This is a bug about hello. For sure its wrong' });
const config = {
params: [
{
keyword: 'hello',
labels: ['bug'],
assignees: [],
},
],
};
githubApi.github.rest.issues.addLabels.mockReturnValueOnce(Promise.resolve({ status: 200 }));

await main({ ...((githubApi as unknown) as GithubScriptsParams), config });

expect(formatMockedCalls(githubApi.core.info.mock.calls)).toMatchInlineSnapshot(`"Label set: bug"`);
});

it(`should assign label and assignees`, async () => {
const githubApi = setup({ issueBody: 'This is a bug about hello. For sure its wrong' });
const config = {
params: [
{
keyword: 'hello',
labels: ['bug'],
assignees: ['harold'],
},
],
};
githubApi.github.rest.issues.addLabels.mockReturnValueOnce(Promise.resolve({ status: 200 }));
githubApi.github.rest.issues.addAssignees.mockReturnValueOnce(Promise.resolve({ status: 201 }));
await main({ ...((githubApi as unknown) as GithubScriptsParams), config });

expect(formatMockedCalls(githubApi.core.info.mock.calls)).toMatchInlineSnapshot(`
"Label set: bug
Assignees set: harold"
`);
});
});

function formatMockedCalls(values: string[][]) {
return values
.flat()
.map(line => line.trim())
.join('\n');
}
7 changes: 7 additions & 0 deletions scripts/triage-bot/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.scripts.json",
"compilerOptions": {
"types": ["node", "jest"]
},
"include": ["*"]
}
19 changes: 19 additions & 0 deletions scripts/triage-bot/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as Core from '@actions/core';
import Github from '@actions/github';

export interface Api extends GithubScriptsParams {
config: Schema;
}
export interface GithubScriptsParams {
context: typeof Github['context'];
github: ReturnType<typeof Github['getOctokit']>;
core: typeof Core;
}

export interface Schema {
params: Array<{
keyword: string;
labels: string[];
assignees: string[];
}>;
}
3 changes: 2 additions & 1 deletion scripts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"./update-release-notes/**",
"./prettier/**",
"./fluentui-publish/**",
"./puppeteer/**"
"./puppeteer/**",
"./triage-bot/**"
]
}
3 changes: 3 additions & 0 deletions scripts/tsconfig.scripts.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
"include": [],
"files": [],
"references": [
{
"path": "./triage-bot/tsconfig.json"
},
{
"path": "./cypress/tsconfig.json"
},
Expand Down
Loading