Compare commits

..

1 Commits

Author SHA1 Message Date
Ross Brodbeck
9aef1a0fb0 Fix an issue where the bot doesn't ignore its own comments 2020-05-18 20:31:11 -04:00
10 changed files with 22024 additions and 4587 deletions

View File

@@ -1,6 +1,6 @@
{ {
"plugins": ["jest", "@typescript-eslint"], "plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/recommended"], "extends": ["plugin:github/es6"],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
"ecmaVersion": 9, "ecmaVersion": 9,
@@ -16,10 +16,11 @@
"@typescript-eslint/no-require-imports": "error", "@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error", "@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error", "@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error", "@typescript-eslint/ban-ts-ignore": "error",
"camelcase": "off", "camelcase": "off",
"@typescript-eslint/consistent-type-assertions": "error", "@typescript-eslint/class-name-casing": "error",
"@typescript-eslint/func-call-spacing": ["error", "never"], "@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/generic-type-naming": ["error", "^[A-Z][A-Za-z]*$"],
"@typescript-eslint/no-array-constructor": "error", "@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error", "@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-explicit-any": "off",
@@ -29,6 +30,7 @@
"@typescript-eslint/no-misused-new": "error", "@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn", "@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-object-literal-type-assertion": "error",
"@typescript-eslint/no-unnecessary-qualifier": "error", "@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error", "@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error", "@typescript-eslint/no-useless-constructor": "error",
@@ -36,6 +38,7 @@
"@typescript-eslint/prefer-for-of": "warn", "@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn", "@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error", "@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-interface": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error", "@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error", "@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error", "@typescript-eslint/require-array-sort-compare": "error",

View File

@@ -1,9 +0,0 @@
version: 2
updates:
# Enable version updates for npm
- package-ecosystem: 'npm'
# Look for `package.json` and `lock` files in the `root` directory
directory: '/'
# Check the npm registry for updates every day (weekdays)
schedule:
interval: 'daily'

View File

@@ -3,7 +3,7 @@ on: # rebuild any PRs and main branch changes
pull_request: pull_request:
push: push:
branches: branches:
- main - master
- 'releases/*' - 'releases/*'
jobs: jobs:

View File

@@ -31,12 +31,10 @@ function generateIssue(
}; };
} }
const DefaultProcessorOptions: IssueProcessorOptions = Object.freeze({ const DefaultProcessorOptions: IssueProcessorOptions = {
repoToken: 'none', repoToken: 'none',
staleIssueMessage: 'This issue is stale', staleIssueMessage: 'This issue is stale',
stalePrMessage: 'This PR is stale', stalePrMessage: 'This PR is stale',
closeIssueMessage: 'This issue is being closed',
closePrMessage: 'This PR is being closed',
daysBeforeStale: 1, daysBeforeStale: 1,
daysBeforeClose: 30, daysBeforeClose: 30,
staleIssueLabel: 'Stale', staleIssueLabel: 'Stale',
@@ -46,11 +44,8 @@ const DefaultProcessorOptions: IssueProcessorOptions = Object.freeze({
onlyLabels: '', onlyLabels: '',
operationsPerRun: 100, operationsPerRun: 100,
debugOnly: true, debugOnly: true,
removeStaleWhenUpdated: false, removeStaleWhenUpdated: false
ascending: false, };
skipStaleIssueMessage: false,
skipStalePrMessage: false
});
test('empty issue list results in 1 operation', async () => { test('empty issue list results in 1 operation', async () => {
const processor = new IssueProcessor( const processor = new IssueProcessor(
@@ -67,36 +62,11 @@ test('empty issue list results in 1 operation', async () => {
expect(operationsLeft).toEqual(99); expect(operationsLeft).toEqual(99);
}); });
test('processing an issue with no label will make it stale and close it, if it is old enough only if days-before-close is set to 0', async () => { test('processing an issue with no label will make it stale and close it, if it is old enough', async () => {
const TestIssueList: Issue[] = [ const TestIssueList: Issue[] = [
generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z') generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z')
]; ];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeClose = 0;
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(1);
expect(processor.closedIssues.length).toEqual(1);
});
test('processing an issue with no label will make it stale and not close it if days-before-close is set to > 0', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z')
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeClose = 15;
const processor = new IssueProcessor( const processor = new IssueProcessor(
DefaultProcessorOptions, DefaultProcessorOptions,
async p => (p == 1 ? TestIssueList : []), async p => (p == 1 ? TestIssueList : []),
@@ -108,32 +78,7 @@ test('processing an issue with no label will make it stale and not close it if d
await processor.processIssues(1); await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(1); expect(processor.staleIssues.length).toEqual(1);
expect(processor.closedIssues.length).toEqual(0); expect(processor.closedIssues.length).toEqual(1);
});
test('processing an issue with no label will not make it stale if days-before-stale is set to -1', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z')
];
const opts = {
...DefaultProcessorOptions,
staleIssueMessage: '',
daysBeforeStale: -1
};
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(0);
}); });
test('processing an issue with no label will make it stale but not close it', async () => { test('processing an issue with no label will make it stale but not close it', async () => {
@@ -210,60 +155,6 @@ test('processing a stale PR will close it', async () => {
expect(processor.closedIssues.length).toEqual(1); expect(processor.closedIssues.length).toEqual(1);
}); });
test('processing a stale issue will close it even if configured not to mark as stale', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z', false, [
'Stale'
])
];
const opts = {
...DefaultProcessorOptions,
daysBeforeStale: -1,
staleIssueMessage: ''
};
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(1);
});
test('processing a stale PR will close it even if configured not to mark as stale', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'An issue with no label', '2020-01-01T17:00:00Z', true, [
'Stale'
])
];
const opts = {
...DefaultProcessorOptions,
daysBeforeStale: -1,
stalePrMessage: ''
};
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(1);
});
test('closed issues will not be marked stale', async () => { test('closed issues will not be marked stale', async () => {
const TestIssueList: Issue[] = [ const TestIssueList: Issue[] = [
generateIssue( generateIssue(
@@ -535,7 +426,6 @@ test('exempt issue labels will not be marked stale (multi issue label)', async (
expect(processor.staleIssues.length).toEqual(0); expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(0); expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
}); });
test('exempt pr labels will not be marked stale', async () => { test('exempt pr labels will not be marked stale', async () => {
@@ -584,7 +474,6 @@ test('stale issues should not be closed if days is set to -1', async () => {
await processor.processIssues(1); await processor.processIssues(1);
expect(processor.closedIssues.length).toEqual(0); expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
}); });
test('stale label should be removed if a comment was added to a stale issue', async () => { test('stale label should be removed if a comment was added to a stale issue', async () => {
@@ -598,7 +487,7 @@ test('stale label should be removed if a comment was added to a stale issue', as
) )
]; ];
const opts = {...DefaultProcessorOptions}; const opts = DefaultProcessorOptions;
opts.removeStaleWhenUpdated = true; opts.removeStaleWhenUpdated = true;
const processor = new IssueProcessor( const processor = new IssueProcessor(
@@ -628,7 +517,7 @@ test('stale label should not be removed if a comment was added by the bot (and t
) )
]; ];
const opts = {...DefaultProcessorOptions}; const opts = DefaultProcessorOptions;
opts.removeStaleWhenUpdated = true; opts.removeStaleWhenUpdated = true;
const processor = new IssueProcessor( const processor = new IssueProcessor(
@@ -658,7 +547,7 @@ test('stale issues should not be closed until after the closed number of days',
) )
]; ];
const opts = {...DefaultProcessorOptions}; const opts = DefaultProcessorOptions;
opts.daysBeforeStale = 5; // stale after 5 days opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 1; // closes after 6 days opts.daysBeforeClose = 1; // closes after 6 days
@@ -673,7 +562,6 @@ test('stale issues should not be closed until after the closed number of days',
await processor.processIssues(1); await processor.processIssues(1);
expect(processor.closedIssues.length).toEqual(0); expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(1); expect(processor.staleIssues.length).toEqual(1);
}); });
@@ -690,7 +578,7 @@ test('stale issues should be closed if the closed nubmer of days (additive) is a
) )
]; ];
const opts = {...DefaultProcessorOptions}; const opts = DefaultProcessorOptions;
opts.daysBeforeStale = 5; // stale after 5 days opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 1; // closes after 6 days opts.daysBeforeClose = 1; // closes after 6 days
@@ -705,191 +593,5 @@ test('stale issues should be closed if the closed nubmer of days (additive) is a
await processor.processIssues(1); await processor.processIssues(1);
expect(processor.closedIssues.length).toEqual(1); expect(processor.closedIssues.length).toEqual(1);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(0);
});
test('stale issues should not be closed until after the closed number of days (long)', async () => {
let lastUpdate = new Date();
lastUpdate.setDate(lastUpdate.getDate() - 10);
const TestIssueList: Issue[] = [
generateIssue(
1,
'An issue that should be marked stale but not closed',
lastUpdate.toString(),
false
)
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 20; // closes after 25 days
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(1);
});
test('skips stale message on issues when skip-stale-issue-message is set', async () => {
let lastUpdate = new Date();
lastUpdate.setDate(lastUpdate.getDate() - 10);
const TestIssueList: Issue[] = [
generateIssue(
1,
'An issue that should be marked stale but not closed',
lastUpdate.toString(),
false
)
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 20; // closes after 25 days
opts.skipStaleIssueMessage = true;
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// for sake of testing, mocking private function
const markSpy = jest.spyOn(processor as any, 'markStale');
await processor.processIssues(1);
// issue should be staled
expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(1);
// comment should not be created
expect(markSpy).toHaveBeenCalledWith(
TestIssueList[0],
opts.staleIssueMessage,
opts.staleIssueLabel,
// this option is skipMessage
true
);
});
test('skips stale message on prs when skip-stale-pr-message is set', async () => {
let lastUpdate = new Date();
lastUpdate.setDate(lastUpdate.getDate() - 10);
const TestIssueList: Issue[] = [
generateIssue(
1,
'An issue that should be marked stale but not closed',
lastUpdate.toString(),
true
)
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 20; // closes after 25 days
opts.skipStalePrMessage = true;
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
// for sake of testing, mocking private function
const markSpy = jest.spyOn(processor as any, 'markStale');
await processor.processIssues(1);
// issue should be staled
expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(1);
// comment should not be created
expect(markSpy).toHaveBeenCalledWith(
TestIssueList[0],
opts.stalePrMessage,
opts.stalePrLabel,
// this option is skipMessage
true
);
});
test('not providing state takes precedence over skipStaleIssueMessage', async () => {
let lastUpdate = new Date();
lastUpdate.setDate(lastUpdate.getDate() - 10);
const TestIssueList: Issue[] = [
generateIssue(
1,
'An issue that should be marked stale but not closed',
lastUpdate.toString(),
false
)
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 20; // closes after 25 days
opts.skipStalePrMessage = true;
opts.staleIssueMessage = '';
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
await processor.processIssues(1);
// issue should be staled
expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(0);
});
test('not providing stalePrMessage takes precedence over skipStalePrMessage', async () => {
let lastUpdate = new Date();
lastUpdate.setDate(lastUpdate.getDate() - 10);
const TestIssueList: Issue[] = [
generateIssue(
1,
'An issue that should be marked stale but not closed',
lastUpdate.toString(),
true
)
];
const opts = {...DefaultProcessorOptions};
opts.daysBeforeStale = 5; // stale after 5 days
opts.daysBeforeClose = 20; // closes after 25 days
opts.skipStalePrMessage = true;
opts.stalePrMessage = '';
const processor = new IssueProcessor(
opts,
async p => (p == 1 ? TestIssueList : []),
async (num, dt) => [],
async (issue, label) => new Date().toDateString()
);
await processor.processIssues(1);
// issue should be staled
expect(processor.closedIssues.length).toEqual(0);
expect(processor.removedLabelIssues.length).toEqual(0);
expect(processor.staleIssues.length).toEqual(0); expect(processor.staleIssues.length).toEqual(0);
}); });

View File

@@ -9,12 +9,8 @@ inputs:
description: 'The message to post on the issue when tagging it. If none provided, will not mark issues stale.' description: 'The message to post on the issue when tagging it. If none provided, will not mark issues stale.'
stale-pr-message: stale-pr-message:
description: 'The message to post on the pr when tagging it. If none provided, will not mark pull requests stale.' description: 'The message to post on the pr when tagging it. If none provided, will not mark pull requests stale.'
close-issue-message:
description: 'The message to post on the issue when closing it. If none provided, will not comment when closing an issue.'
close-pr-message:
description: 'The message to post on the pr when closing it. If none provided, will not comment when closing a pull requests.'
days-before-stale: days-before-stale:
description: 'The number of days old an issue can be before marking it stale. Set to -1 to never mark issues or pull requests as stale automatically.' description: 'The number of days old an issue can be before marking it stale.'
default: 60 default: 60
days-before-close: days-before-close:
description: 'The number of days to wait to close an issue or pull request after it being marked stale. Set to -1 to never close stale issues.' description: 'The number of days to wait to close an issue or pull request after it being marked stale. Set to -1 to never close stale issues.'
@@ -43,15 +39,6 @@ inputs:
debug-only: debug-only:
description: 'Run the processor in debug mode without actually performing any operations on live issues.' description: 'Run the processor in debug mode without actually performing any operations on live issues.'
default: false default: false
ascending:
description: 'The order to get issues or pull requests. Defaults to false, which is descending'
default: false
skip-stale-pr-message:
description: 'Skip adding stale message when marking a pull request as stale.'
default: false
skip-stale-issue-message:
description: 'Skip adding stale message when marking an issue as stale.'
default: false
runs: runs:
using: 'node12' using: 'node12'
main: 'dist/index.js' main: 'dist/index.js'

22952
dist/index.js vendored

File diff suppressed because it is too large Load Diff

2952
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -26,24 +26,24 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/core": "^1.2.4", "@actions/core": "^1.2.4",
"@actions/github": "^4.0.0", "@actions/github": "^2.2.0",
"@octokit/rest": "^18.0.2", "@octokit/rest": "^16.43.1",
"semver": "^7.3.2" "semver": "^6.1.1"
}, },
"devDependencies": { "devDependencies": {
"@types/semver": "^7.3.1", "@types/semver": "^6.0.0",
"@types/jest": "^26.0.5", "@types/jest": "^24.0.23",
"@types/node": "^14.0.25", "@types/node": "^12.7.12",
"@typescript-eslint/parser": "^3.7.0", "@typescript-eslint/parser": "^2.8.0",
"@zeit/ncc": "^0.20.5", "@zeit/ncc": "^0.20.5",
"eslint": "^5.16.0", "eslint": "^5.16.0",
"eslint-plugin-github": "^4.0.1", "eslint-plugin-github": "^2.0.0",
"eslint-plugin-jest": "^23.18.0", "eslint-plugin-jest": "^22.21.0",
"jest": "^24.9.0", "jest": "^24.9.0",
"jest-circus": "^26.1.0", "jest-circus": "^24.9.0",
"js-yaml": "^3.13.1", "js-yaml": "^3.13.1",
"prettier": "^1.19.1", "prettier": "^1.19.1",
"ts-jest": "^24.2.0", "ts-jest": "^24.2.0",
"typescript": "^3.9.7" "typescript": "^3.6.4"
} }
} }

View File

@@ -1,6 +1,8 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import {context, getOctokit} from '@actions/github'; import * as github from '@actions/github';
import {GetResponseTypeFromEndpointMethod} from '@octokit/types'; import {Octokit} from '@octokit/rest';
type OctoKitIssueList = Octokit.Response<Octokit.IssuesListForRepoResponse>;
export interface Issue { export interface Issue {
title: string; title: string;
@@ -35,8 +37,6 @@ export interface IssueProcessorOptions {
repoToken: string; repoToken: string;
staleIssueMessage: string; staleIssueMessage: string;
stalePrMessage: string; stalePrMessage: string;
closeIssueMessage: string;
closePrMessage: string;
daysBeforeStale: number; daysBeforeStale: number;
daysBeforeClose: number; daysBeforeClose: number;
staleIssueLabel: string; staleIssueLabel: string;
@@ -47,18 +47,15 @@ export interface IssueProcessorOptions {
operationsPerRun: number; operationsPerRun: number;
removeStaleWhenUpdated: boolean; removeStaleWhenUpdated: boolean;
debugOnly: boolean; debugOnly: boolean;
ascending: boolean;
skipStaleIssueMessage: boolean;
skipStalePrMessage: boolean;
} }
/*** /***
* Handle processing of issues for staleness/closure. * Handle processing of issues for staleness/closure.
*/ */
export class IssueProcessor { export class IssueProcessor {
readonly client: any; // need to make this the correct type readonly client: github.GitHub;
readonly options: IssueProcessorOptions; readonly options: IssueProcessorOptions;
private operationsLeft = 0; private operationsLeft: number = 0;
readonly staleIssues: Issue[] = []; readonly staleIssues: Issue[] = [];
readonly closedIssues: Issue[] = []; readonly closedIssues: Issue[] = [];
@@ -78,7 +75,7 @@ export class IssueProcessor {
) { ) {
this.options = options; this.options = options;
this.operationsLeft = options.operationsPerRun; this.operationsLeft = options.operationsPerRun;
this.client = getOctokit(options.repoToken); this.client = new github.GitHub(options.repoToken);
if (getIssues) { if (getIssues) {
this.getIssues = getIssues; this.getIssues = getIssues;
@@ -99,20 +96,25 @@ export class IssueProcessor {
} }
} }
async processIssues(page = 1): Promise<number> { async processIssues(page: number = 1): Promise<number> {
if (this.operationsLeft <= 0) {
core.warning('Reached max number of operations to process. Exiting.');
return 0;
}
// get the next batch of issues // get the next batch of issues
const issues: Issue[] = await this.getIssues(page); const issues: Issue[] = await this.getIssues(page);
this.operationsLeft -= 1; this.operationsLeft -= 1;
if (issues.length <= 0) { if (issues.length <= 0) {
core.info('No more issues found to process. Exiting.'); core.debug('No more issues found to process. Exiting.');
return this.operationsLeft; return this.operationsLeft;
} }
for (const issue of issues.values()) { for (const issue of issues.values()) {
const isPr = !!issue.pull_request; const isPr = !!issue.pull_request;
core.info( core.debug(
`Found issue: issue #${issue.number} - ${issue.title} last updated ${issue.updated_at} (is pr? ${isPr})` `Found issue: issue #${issue.number} - ${issue.title} last updated ${issue.updated_at} (is pr? ${isPr})`
); );
@@ -120,33 +122,26 @@ export class IssueProcessor {
const staleMessage: string = isPr const staleMessage: string = isPr
? this.options.stalePrMessage ? this.options.stalePrMessage
: this.options.staleIssueMessage; : this.options.staleIssueMessage;
const closeMessage: string = isPr
? this.options.closePrMessage
: this.options.closeIssueMessage;
const staleLabel: string = isPr const staleLabel: string = isPr
? this.options.stalePrLabel ? this.options.stalePrLabel
: this.options.staleIssueLabel; : this.options.staleIssueLabel;
const exemptLabels = IssueProcessor.parseCommaSeparatedString( const exemptLabels = IssueProcessor.parseCommaSeparatedString(
isPr ? this.options.exemptPrLabels : this.options.exemptIssueLabels isPr ? this.options.exemptPrLabels : this.options.exemptIssueLabels
); );
const skipMessage = isPr
? this.options.skipStalePrMessage
: this.options.skipStaleIssueMessage;
const issueType: string = isPr ? 'pr' : 'issue'; const issueType: string = isPr ? 'pr' : 'issue';
const shouldMarkWhenStale = this.options.daysBeforeStale > -1;
if (!staleMessage && shouldMarkWhenStale) { if (!staleMessage) {
core.info(`Skipping ${issueType} due to empty stale message`); core.debug(`Skipping ${issueType} due to empty stale message`);
continue; continue;
} }
if (issue.state === 'closed') { if (issue.state === 'closed') {
core.info(`Skipping ${issueType} because it is closed`); core.debug(`Skipping ${issueType} because it is closed`);
continue; // don't process closed issues continue; // don't process closed issues
} }
if (issue.locked) { if (issue.locked) {
core.info(`Skipping ${issueType} because it is locked`); core.debug(`Skipping ${issueType} because it is locked`);
continue; // don't process locked issues continue; // don't process locked issues
} }
@@ -155,45 +150,36 @@ export class IssueProcessor {
IssueProcessor.isLabeled(issue, exemptLabel) IssueProcessor.isLabeled(issue, exemptLabel)
) )
) { ) {
core.info(`Skipping ${issueType} because it has an exempt label`); core.debug(`Skipping ${issueType} because it has an exempt label`);
continue; // don't process exempt issues continue; // don't process exempt issues
} }
// does this issue have a stale label? // does this issue have a stale label?
let isStale = IssueProcessor.isLabeled(issue, staleLabel); let isStale = IssueProcessor.isLabeled(issue, staleLabel);
// should this issue be marked stale?
const shouldBeStale = !IssueProcessor.updatedSince(
issue.updated_at,
this.options.daysBeforeStale
);
// determine if this issue needs to be marked stale first // determine if this issue needs to be marked stale first
if (!isStale && shouldBeStale && shouldMarkWhenStale) { if (
core.info( !isStale &&
!IssueProcessor.updatedSince(
issue.updated_at,
this.options.daysBeforeStale
)
) {
core.debug(
`Marking ${issueType} stale because it was last updated on ${issue.updated_at} and it does not have a stale label` `Marking ${issueType} stale because it was last updated on ${issue.updated_at} and it does not have a stale label`
); );
await this.markStale(issue, staleMessage, staleLabel, skipMessage); await this.markStale(issue, staleMessage, staleLabel);
this.operationsLeft -= 2;
isStale = true; // this issue is now considered stale isStale = true; // this issue is now considered stale
} }
// process the issue if it was marked stale // process any issues marked stale (including the issue above, if it was marked)
if (isStale) { if (isStale) {
core.info(`Found a stale ${issueType}`); core.debug(`Found a stale ${issueType}`);
await this.processStaleIssue( await this.processStaleIssue(issue, issueType, staleLabel);
issue,
issueType,
staleLabel,
closeMessage
);
} }
} }
if (this.operationsLeft <= 0) {
core.warning('Reached max number of operations to process. Exiting.');
return 0;
}
// do the next batch // do the next batch
return this.processIssues(page + 1); return this.processIssues(page + 1);
} }
@@ -202,79 +188,76 @@ export class IssueProcessor {
private async processStaleIssue( private async processStaleIssue(
issue: Issue, issue: Issue,
issueType: string, issueType: string,
staleLabel: string, staleLabel: string
closeMessage?: string
) { ) {
const markedStaleOn: string =
(await this.getLabelCreationDate(issue, staleLabel)) || issue.updated_at;
core.info(`Issue #${issue.number} marked stale on: ${markedStaleOn}`);
const issueHasComments: boolean = await this.hasCommentsSince(
issue,
markedStaleOn
);
core.info(
`Issue #${issue.number} has been commented on: ${issueHasComments}`
);
const issueHasUpdate: boolean = IssueProcessor.updatedSince(
issue.updated_at,
this.options.daysBeforeClose
);
core.info(`Issue #${issue.number} has been updated: ${issueHasUpdate}`);
// should we un-stale this issue?
if (this.options.removeStaleWhenUpdated && issueHasComments) {
core.info(
`Issue #${issue.number} is no longer stale. Removing stale label.`
);
await this.removeLabel(issue, staleLabel);
}
// now start closing logic
if (this.options.daysBeforeClose < 0) { if (this.options.daysBeforeClose < 0) {
return; // nothing to do because we aren't closing stale issues return; // nothing to do because we aren't closing stale issues
} }
const markedStaleOn: string | undefined = await this.getLabelCreationDate(
issue,
staleLabel
);
const issueHasComments: boolean = await this.isIssueStillStale(
issue,
markedStaleOn || issue.updated_at
);
const issueHasUpdate: boolean = IssueProcessor.updatedSince(
issue.updated_at,
this.options.daysBeforeClose + (this.options.daysBeforeStale ?? 0)
);
if (markedStaleOn) {
core.debug(`Issue #${issue.number} marked stale on: ${markedStaleOn}`);
} else {
core.debug(
`Issue #${issue.number} is not marked stale, but last update of ${issue.updated_at} is older than ${this.options.daysBeforeStale} days`
);
}
core.debug(`Issue #${issue.number} has been updated: ${issueHasUpdate}`);
core.debug(
`Issue #${issue.number} has been commented on: ${issueHasComments}`
);
if (!issueHasComments && !issueHasUpdate) { if (!issueHasComments && !issueHasUpdate) {
core.info( core.debug(
`Closing ${issueType} because it was last updated on ${issue.updated_at}` `Closing ${issueType} because it was last updated on ${issue.updated_at}`
); );
await this.closeIssue(issue, closeMessage); await this.closeIssue(issue);
} else { } else {
core.info( if (this.options.removeStaleWhenUpdated) {
`Stale ${issueType} is not old enough to close yet (hasComments? ${issueHasComments}, hasUpdate? ${issueHasUpdate}` await this.removeLabel(issue, staleLabel);
); }
core.debug(`Ignoring stale ${issueType} because it was updated recently`);
} }
} }
// checks to see if a given issue is still stale (has had activity on it) // checks to see if a given issue is still stale (has had activity on it)
private async hasCommentsSince( private async isIssueStillStale(
issue: Issue, issue: Issue,
sinceDate: string sinceDate: string
): Promise<boolean> { ): Promise<boolean> {
core.info( core.debug(
`Checking for comments on issue #${issue.number} since ${sinceDate}` `Checking for comments on issue #${issue.number} since ${sinceDate} to see if it is still stale`
); );
if (!sinceDate) { if (!sinceDate) {
return true; return true; // if no date was provided then the issue was marked stale a long time ago
} }
// find any comments since the date this.operationsLeft -= 1;
// find any comments since the stale label
const comments = await this.listIssueComments(issue.number, sinceDate); const comments = await this.listIssueComments(issue.number, sinceDate);
const filteredComments = comments.filter( // if there are any user comments returned, and they were not by this bot, the issue is not stale anymore
comment => return (
comment.user.type === 'User' && comment.user.login !== context.actor comments.filter(
comment =>
comment.user.type === 'User' &&
comment.user.login !== github.context.actor
).length > 0
); );
core.info(
`Comments not made by ${context.actor} or another bot: ${filteredComments.length}`
);
// if there are any user comments returned
return filteredComments.length > 0;
} }
// grab comments for an issue since a given date // grab comments for an issue since a given date
@@ -283,95 +266,64 @@ export class IssueProcessor {
sinceDate: string sinceDate: string
): Promise<Comment[]> { ): Promise<Comment[]> {
// find any comments since date on the given issue // find any comments since date on the given issue
try { const comments = await this.client.issues.listComments({
const comments = await this.client.issues.listComments({ owner: github.context.repo.owner,
owner: context.repo.owner, repo: github.context.repo.repo,
repo: context.repo.repo, issue_number: issueNumber,
issue_number: issueNumber, since: sinceDate
since: sinceDate });
});
return comments.data; return comments.data;
} catch (error) {
core.error(`List issue comments error: ${error.message}`);
return Promise.resolve([]);
}
} }
// grab issues from github in baches of 100 // grab issues from github in baches of 100
private async getIssues(page: number): Promise<Issue[]> { private async getIssues(page: number): Promise<Issue[]> {
// generate type for response const issueResult: OctoKitIssueList = await this.client.issues.listForRepo({
const endpoint = this.client.issues.listForRepo; owner: github.context.repo.owner,
type OctoKitIssueList = GetResponseTypeFromEndpointMethod<typeof endpoint>; repo: github.context.repo.repo,
state: 'open',
labels: this.options.onlyLabels,
per_page: 100,
page
});
try { return issueResult.data;
const issueResult: OctoKitIssueList = await this.client.issues.listForRepo(
{
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
labels: this.options.onlyLabels,
per_page: 100,
direction: this.options.ascending ? 'asc' : 'desc',
page
}
);
return issueResult.data;
} catch (error) {
core.error(`Get issues for repo error: ${error.message}`);
return Promise.resolve([]);
}
} }
// Mark an issue as stale with a comment and a label // Mark an issue as stale with a comment and a label
private async markStale( private async markStale(
issue: Issue, issue: Issue,
staleMessage: string, staleMessage: string,
staleLabel: string, staleLabel: string
skipMessage: boolean
): Promise<void> { ): Promise<void> {
core.info(`Marking issue #${issue.number} - ${issue.title} as stale`); core.debug(`Marking issue #${issue.number} - ${issue.title} as stale`);
this.staleIssues.push(issue); this.staleIssues.push(issue);
this.operationsLeft -= 2; this.operationsLeft -= 2;
// if the issue is being marked stale, the updated date should be changed to right now
// so that close calculations work correctly
const newUpdatedAtDate: Date = new Date();
issue.updated_at = newUpdatedAtDate.toString();
if (this.options.debugOnly) { if (this.options.debugOnly) {
return; return;
} }
if (!skipMessage) { await this.client.issues.createComment({
try { owner: github.context.repo.owner,
await this.client.issues.createComment({ repo: github.context.repo.repo,
owner: context.repo.owner, issue_number: issue.number,
repo: context.repo.repo, body: staleMessage
issue_number: issue.number, });
body: staleMessage
});
} catch (error) {
core.error(`Error creating a comment: ${error.message}`);
}
}
try { await this.client.issues.addLabels({
await this.client.issues.addLabels({ owner: github.context.repo.owner,
owner: context.repo.owner, repo: github.context.repo.repo,
repo: context.repo.repo, issue_number: issue.number,
issue_number: issue.number, labels: [staleLabel]
labels: [staleLabel] });
});
} catch (error) {
core.error(`Error adding a label: ${error.message}`);
}
} }
// Close an issue based on staleness // Close an issue based on staleness
private async closeIssue(issue: Issue, closeMessage?: string): Promise<void> { private async closeIssue(issue: Issue): Promise<void> {
core.info( core.debug(
`Closing issue #${issue.number} - ${issue.title} for being stale` `Closing issue #${issue.number} - ${issue.title} for being stale`
); );
@@ -383,34 +335,17 @@ export class IssueProcessor {
return; return;
} }
if (closeMessage) { await this.client.issues.update({
try { owner: github.context.repo.owner,
await this.client.issues.createComment({ repo: github.context.repo.repo,
owner: context.repo.owner, issue_number: issue.number,
repo: context.repo.repo, state: 'closed'
issue_number: issue.number, });
body: closeMessage
});
} catch (error) {
core.error(`Error creating a comment: ${error.message}`);
}
}
try {
await this.client.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
state: 'closed'
});
} catch (error) {
core.error(`Error updating an issue: ${error.message}`);
}
} }
// Remove a label from an issue // Remove a label from an issue
private async removeLabel(issue: Issue, label: string): Promise<void> { private async removeLabel(issue: Issue, label: string): Promise<void> {
core.info( core.debug(
`Removing label ${label} from issue #${issue.number} - ${issue.title}` `Removing label ${label} from issue #${issue.number} - ${issue.title}`
); );
@@ -422,16 +357,12 @@ export class IssueProcessor {
return; return;
} }
try { await this.client.issues.removeLabel({
await this.client.issues.removeLabel({ owner: github.context.repo.owner,
owner: context.repo.owner, repo: github.context.repo.repo,
repo: context.repo.repo, issue_number: issue.number,
issue_number: issue.number, name: encodeURIComponent(label) // A label can have a "?" in the name
name: encodeURIComponent(label) // A label can have a "?" in the name });
});
} catch (error) {
core.error(`Error removing a label: ${error.message}`);
}
} }
// returns the creation date of a given label on an issue (or nothing if no label existed) // returns the creation date of a given label on an issue (or nothing if no label existed)
@@ -440,13 +371,13 @@ export class IssueProcessor {
issue: Issue, issue: Issue,
label: string label: string
): Promise<string | undefined> { ): Promise<string | undefined> {
core.info(`Checking for label ${label} on issue #${issue.number}`); core.debug(`Checking for label ${label} on issue #${issue.number}`);
this.operationsLeft -= 1; this.operationsLeft -= 1;
const options = this.client.issues.listEvents.endpoint.merge({ const options = this.client.issues.listEvents.endpoint.merge({
owner: context.repo.owner, owner: github.context.repo.owner,
repo: context.repo.repo, repo: github.context.repo.repo,
per_page: 100, per_page: 100,
issue_number: issue.number issue_number: issue.number
}); });
@@ -477,7 +408,7 @@ export class IssueProcessor {
const millisSinceLastUpdated = const millisSinceLastUpdated =
new Date().getTime() - new Date(timestamp).getTime(); new Date().getTime() - new Date(timestamp).getTime();
return millisSinceLastUpdated <= daysInMillis; return millisSinceLastUpdated < daysInMillis;
} }
private static parseCommaSeparatedString(s: string): string[] { private static parseCommaSeparatedString(s: string): string[] {

View File

@@ -18,8 +18,6 @@ function getAndValidateArgs(): IssueProcessorOptions {
repoToken: core.getInput('repo-token', {required: true}), repoToken: core.getInput('repo-token', {required: true}),
staleIssueMessage: core.getInput('stale-issue-message'), staleIssueMessage: core.getInput('stale-issue-message'),
stalePrMessage: core.getInput('stale-pr-message'), stalePrMessage: core.getInput('stale-pr-message'),
closeIssueMessage: core.getInput('close-issue-message'),
closePrMessage: core.getInput('close-pr-message'),
daysBeforeStale: parseInt( daysBeforeStale: parseInt(
core.getInput('days-before-stale', {required: true}) core.getInput('days-before-stale', {required: true})
), ),
@@ -37,10 +35,7 @@ function getAndValidateArgs(): IssueProcessorOptions {
removeStaleWhenUpdated: !( removeStaleWhenUpdated: !(
core.getInput('remove-stale-when-updated') === 'false' core.getInput('remove-stale-when-updated') === 'false'
), ),
debugOnly: core.getInput('debug-only') === 'true', debugOnly: core.getInput('debug-only') === 'true'
ascending: core.getInput('ascending') === 'true',
skipStalePrMessage: core.getInput('skip-stale-pr-message') === 'true',
skipStaleIssueMessage: core.getInput('skip-stale-issue-message') === 'true'
}; };
for (const numberInput of [ for (const numberInput of [