Compare commits

..

23 Commits

Author SHA1 Message Date
Ross Brodbeck
23a7120f76 Update the readme on how to build it 2020-04-16 14:18:06 -04:00
Ross Brodbeck
7e52e0cdc1 Add a test to days = -1 2020-04-16 14:15:34 -04:00
Ross Brodbeck
78921b6863 one more fix to the actions yml 2020-04-16 14:05:24 -04:00
Ross Brodbeck
29c3838f9a Fix parsing issues with action.yml 2020-04-16 14:03:58 -04:00
Ross Brodbeck
ae12f32ff1 Create test.yml 2020-04-16 13:58:47 -04:00
Ross Brodbeck
aad6ffa865 Refactor issue processor (#45)
* Refctor into an issue processor, add debug mode
* Move processor to use its own types so testing is easier
* Add more tests
2020-04-16 13:57:59 -04:00
Ryan Wilson-Perkin
6127f8ef7a Allow multiple exempt labels (#19)
* Update description to clarify exempt labels

* [breaking change] Use array for exempt labels

* Switch to a comma separated string for exempt labels

* Update descriptions for multiple labels

* Update examples for exempt labels

* lint: apply fixes

* Re-generate transpiled output
2020-04-15 21:33:09 -04:00
Ross Brodbeck
e78f171ed1 Fix main entrypoint in action yml (#43) 2020-04-14 14:02:29 -04:00
Ross Brodbeck
60b5a6b134 Cleanup release (#42)
Fix up the release pipeline, add linting and clean up a bit.
2020-04-14 13:28:00 -04:00
Ross Brodbeck
d179b42b05 Fix closing tag in only-labels description
Fix closing tag in only-labels description
2020-04-14 13:23:46 -04:00
Tobias Diez
7ba95148ac Update action.yml 2020-04-14 11:44:58 +02:00
Tobias Diez
e9da8a66a5 Fix closing tag in only-labels description
The `only-labels` description was missing the closing tag `'`.
2020-04-14 11:43:56 +02:00
Ross Brodbeck
3d5d474504 Merge pull request #22 from yuya-takeyama/only-labels-pr
Add only-labels option
2020-04-13 07:19:13 -04:00
Ross Brodbeck
54897a34f9 Fix labelsOnly description so it is easier to understand
Co-Authored-By: Stephan Miehe <49914758+stephanmiehe@users.noreply.github.com>
2020-04-13 07:17:15 -04:00
Ross Brodbeck
c5c8bac9c4 Merge pull request #16 from actions/dont-close-option
Add option to not close stale issues/prs
2020-04-13 07:12:39 -04:00
Ross Brodbeck
ee2e3ba115 Merge pull request #25 from actions/IAmHughes/update-docs
Update README.md example workflows to latest release version
2020-04-13 07:11:27 -04:00
Chris Patterson
0d6a8e5314 Merge pull request #26 from actions/ethomson/update_description
Update description
2019-12-10 11:22:42 -05:00
Chris Patterson
eb8d275a4a Merge pull request #29 from actions/add-syntax-highlighting
Add syntax highlighting to examples
2019-12-10 11:22:23 -05:00
Edward Thomson
d6c1b70646 Update description 2019-11-08 16:47:32 +00:00
Thomas Hughes
1a8e37e7ad Update README to latest release version 2019-11-01 13:43:25 +01:00
Yuya Takeyama
8588c16319 Add only-labels 2019-09-27 22:50:35 +09:00
Danny McCormick
b8e29997c6 Clean up 2019-09-05 09:57:15 -04:00
damccorm
2521dbb244 Add option to not close stale 2019-09-04 16:38:09 -04:00
18 changed files with 28850 additions and 1680 deletions

3
.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
dist/
lib/
node_modules/

55
.eslintrc.json Normal file
View File

@@ -0,0 +1,55 @@
{
"plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/es6"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-ignore": "error",
"camelcase": "off",
"@typescript-eslint/class-name-casing": "error",
"@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-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@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-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-interface": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"semi": "off",
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "off"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

26
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: "Build"
on: # rebuild any PRs and main branch changes
pull_request:
push:
branches:
- master
- 'releases/*'
jobs:
build: # make sure build/ci work properly
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: |
npm install
npm run all
test: # make sure the action works on a clean machine without building
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: ./
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue is stale'
stale-pr-message: 'This PR is stale'
debug-only: true

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
.DS_Store
node_modules/
lib/
__tests__/runner/*

View File

@@ -2,6 +2,23 @@
Warns and then closes issues and PRs that have had no activity for a specified amount of time.
### Building and testing
Install the dependencies
```bash
$ npm install
```
Build the typescript and package it for distribution
```bash
$ npm run build && npm run pack
```
Run the tests :heavy_check_mark:
```bash
$ npm test
```
### Usage
See [action.yml](./action.yml) For comprehensive list of options.
@@ -17,7 +34,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
- uses: actions/stale@v1.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'Message to comment on stale issues. If none provided, will not mark issues stale'
@@ -35,7 +52,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
- uses: actions/stale@v1.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days'
@@ -54,13 +71,17 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
- uses: actions/stale@v1.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'Stale issue message'
stale-pr-message: 'Stale issue message'
stale-issue-label: 'no-issue-activity'
exempt-issue-label: 'awaiting-approval'
exempt-issue-labels: 'awaiting-approval,work-in-progress'
stale-pr-label: 'no-pr-activity'
exempt-pr-label: 'awaiting-approval'
exempt-pr-labels: 'awaiting-approval,work-in-progress'
```
### Debugging
To see debug ouput from this action, you must set the secret `ACTIONS_STEP_DEBUG` to `true` in your repository. You can run this action in debug only mode (no actions will be taken on your issues) by passing `debug-only` `true` as an argument to the action.

View File

@@ -1,3 +1,202 @@
describe('TODO - Add a test suite', () => {
it('TODO - Add a test', async () => {});
import * as core from '@actions/core';
import * as github from '@actions/github';
import {Octokit} from '@octokit/rest';
import {
IssueProcessor,
Issue,
Label,
IssueProcessorOptions
} from '../src/IssueProcessor';
function generateIssue(
id: number,
title: string,
updatedAt: string,
isPullRequest: boolean = false,
labels: string[] = []
): Issue {
return {
number: id,
labels: labels.map(l => {
return {name: l};
}),
title: title,
updated_at: updatedAt,
pull_request: isPullRequest ? {} : null
};
}
const DefaultProcessorOptions: IssueProcessorOptions = {
repoToken: 'none',
staleIssueMessage: 'This issue is stale',
stalePrMessage: 'This PR is stale',
daysBeforeStale: 1,
daysBeforeClose: 1,
staleIssueLabel: 'Stale',
exemptIssueLabels: '',
stalePrLabel: 'Stale',
exemptPrLabels: '',
onlyLabels: '',
operationsPerRun: 100,
debugOnly: true
};
test('empty issue list results in 1 operation', async () => {
const processor = new IssueProcessor(DefaultProcessorOptions, async () => []);
// process our fake issue list
const operationsLeft = await processor.processIssues(1);
// processing an empty issue list should result in 1 operation
expect(operationsLeft).toEqual(99);
});
test('processing an issue with no label will make it stale', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z')
];
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(1);
expect(processor.closedIssues.length).toEqual(0);
});
test('processing a stale issue will close it', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, ['Stale'])
];
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// 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', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first PR', '2020-01-01T17:00:00Z', true, ['Stale'])
];
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(1);
});
test('exempt issue labels will not be marked stale', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, [
'Exempt'
])
];
let opts = DefaultProcessorOptions;
opts.exemptIssueLabels = 'Exempt';
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(0);
});
test('exempt issue labels will not be marked stale (multi issue label with spaces)', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, ['Cool'])
];
let opts = DefaultProcessorOptions;
opts.exemptIssueLabels = 'Exempt, Cool, None';
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(0);
});
test('exempt issue labels will not be marked stale (multi issue label)', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, ['Cool'])
];
let opts = DefaultProcessorOptions;
opts.exemptIssueLabels = 'Exempt,Cool,None';
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(0);
expect(processor.closedIssues.length).toEqual(0);
});
test('exempt pr labels will not be marked stale', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, ['Cool']),
generateIssue(2, 'My first PR', '2020-01-01T17:00:00Z', true, ['Cool']),
generateIssue(3, 'Another issue', '2020-01-01T17:00:00Z', false)
];
let opts = DefaultProcessorOptions;
opts.exemptIssueLabels = 'Cool';
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.staleIssues.length).toEqual(2); // PR should get processed even though it has an exempt **issue** label
});
test('stale issues should not be closed if days is set to -1', async () => {
const TestIssueList: Issue[] = [
generateIssue(1, 'My first issue', '2020-01-01T17:00:00Z', false, [
'Stale'
]),
generateIssue(2, 'My first PR', '2020-01-01T17:00:00Z', true, ['Stale']),
generateIssue(3, 'Another issue', '2020-01-01T17:00:00Z', false, ['Stale'])
];
let opts = DefaultProcessorOptions;
opts.daysBeforeClose = -1;
const processor = new IssueProcessor(DefaultProcessorOptions, async p =>
p == 1 ? TestIssueList : []
);
// process our fake issue list
await processor.processIssues(1);
expect(processor.closedIssues.length).toEqual(0);
});

View File

@@ -1,33 +1,41 @@
name: 'Close Stale Issues'
description: 'Action to close stale issues'
description: 'Close issues and pull requests with no recent activity'
author: 'GitHub'
inputs:
repo-token:
description: 'Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }}'
description: 'Token for the repository. Can be passed in using `{{ secrets.GITHUB_TOKEN }}`.'
required: true
stale-issue-message:
description: 'The message to post on the issue when tagging it. If none provided, will not mark issues stale.'
stale-pr-message:
description: 'The message to post on the pr when tagging it. If none provided, will not mark pull requests stale.'
days-before-stale:
description: 'The number of days old an issue can be before marking it stale'
description: 'The number of days old an issue can be before marking it stale.'
default: 60
days-before-close:
description: 'The number of days to wait to close an issue or pull request after it being marked stale'
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.'
default: 7
stale-issue-label:
description: 'The label to apply when an issue is stale'
description: 'The label to apply when an issue is stale.'
default: 'Stale'
exempt-issue-label:
description: 'The label to apply when an issue is exempt from being marked stale'
exempt-issue-labels:
description: 'The labels to apply when an issue is exempt from being marked stale. Separate multiple labels with commas (eg. "label1,label2")'
default: ''
stale-pr-label:
description: 'The label to apply when a pull request is stale'
description: 'The label to apply when a pull request is stale.'
default: 'Stale'
exempt-pr-label:
description: 'The label to apply when a pull request is exempt from being marked stale'
exempt-pr-labels:
description: 'The labels to apply when a pull request is exempt from being marked stale. Separate multiple labels with commas (eg. "label1,label2")'
default: ''
only-labels:
description: 'Only issues or pull requests with all of these labels are checked if stale. Defaults to `[]` (disabled) and can be a comma-separated list of labels.'
default: ''
operations-per-run:
description: 'The maximum number of operations per run, used to control rate limiting'
description: 'The maximum number of operations per run, used to control rate limiting.'
default: 30
debug-only:
description: 'Run the processor in debug mode without actually performing any operations on live issues.'
default: false
runs:
using: 'node12'
main: 'lib/main.js'
main: 'dist/index.js'

25542
dist/index.js vendored Normal file

File diff suppressed because it is too large Load Diff

4158
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "stale-action",
"version": "1.0.0",
"version": "2.0.0",
"private": true,
"description": "Marks old issues and PRs as stale",
"main": "lib/main.js",
@@ -8,7 +8,10 @@
"build": "tsc",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"test": "jest"
"lint": "eslint src/**/*.ts",
"pack": "ncc build",
"test": "jest",
"all": "npm run build && npm run format && npm run lint && npm run pack && npm test"
},
"repository": {
"type": "git",
@@ -22,29 +25,25 @@
"author": "GitHub",
"license": "MIT",
"dependencies": {
"@actions/core": "file:toolkit/actions-core-0.0.0.tgz",
"@actions/exec": "file:toolkit/actions-exec-0.0.0.tgz",
"@actions/github": "file:toolkit/actions-github-0.0.0.tgz",
"@actions/io": "file:toolkit/actions-io-0.0.0.tgz",
"@actions/tool-cache": "file:toolkit/actions-tool-cache-0.0.0.tgz",
"@actions/core": "^1.2.3",
"@actions/github": "^2.1.1",
"@octokit/rest": "^16.43.1",
"semver": "^6.1.1"
},
"devDependencies": {
"@types/jest": "^24.0.13",
"@types/node": "^12.6.8",
"@types/semver": "^6.0.0",
"husky": "^2.3.0",
"jest": "^24.8.0",
"jest-circus": "^24.7.1",
"prettier": "^1.17.1",
"ts-jest": "^24.0.2",
"typescript": "^3.5.1"
},
"husky": {
"skipCI": true,
"hooks": {
"pre-commit": "npm run build && npm run format",
"post-commit": "npm prune --production && git add node_modules/* && git commit -m \"Husky commit correct node modules\""
}
"@types/jest": "^24.0.23",
"@types/node": "^12.7.12",
"@typescript-eslint/parser": "^2.8.0",
"@zeit/ncc": "^0.20.5",
"eslint": "^5.16.0",
"eslint-plugin-github": "^2.0.0",
"eslint-plugin-jest": "^22.21.0",
"jest": "^24.9.0",
"jest-circus": "^24.9.0",
"js-yaml": "^3.13.1",
"prettier": "^1.19.1",
"ts-jest": "^24.2.0",
"typescript": "^3.6.4"
}
}

230
src/IssueProcessor.ts Normal file
View File

@@ -0,0 +1,230 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import {Octokit} from '@octokit/rest';
type OcotoKitIssueList = Octokit.Response<Octokit.IssuesListForRepoResponse>;
export interface Issue {
title: string;
number: number;
updated_at: string;
labels: Label[];
pull_request: any;
}
export interface Label {
name: string;
}
export interface IssueProcessorOptions {
repoToken: string;
staleIssueMessage: string;
stalePrMessage: string;
daysBeforeStale: number;
daysBeforeClose: number;
staleIssueLabel: string;
exemptIssueLabels: string;
stalePrLabel: string;
exemptPrLabels: string;
onlyLabels: string;
operationsPerRun: number;
debugOnly: boolean;
}
/***
* Handle processing of issues for staleness/closure.
*/
export class IssueProcessor {
readonly client: github.GitHub;
readonly options: IssueProcessorOptions;
private operationsLeft: number = 0;
readonly staleIssues: Issue[] = [];
readonly closedIssues: Issue[] = [];
constructor(
options: IssueProcessorOptions,
getIssues?: (page: number) => Promise<Issue[]>
) {
this.options = options;
this.operationsLeft = options.operationsPerRun;
this.client = new github.GitHub(options.repoToken);
if (getIssues) {
this.getIssues = getIssues;
}
if (this.options.debugOnly) {
core.warning(
'Executing in debug mode. Debug output will be written but no issues will be processed.'
);
}
}
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
const issues: Issue[] = await this.getIssues(page);
this.operationsLeft -= 1;
if (issues.length <= 0) {
core.debug('No more issues found to process. Exiting.');
return this.operationsLeft;
}
for (const issue of issues.values()) {
const isPr = !!issue.pull_request;
core.debug(
`Found issue: issue #${issue.number} - ${issue.title} last updated ${issue.updated_at} (is pr? ${isPr})`
);
// calculate string based messages for this issue
const staleMessage: string = isPr
? this.options.stalePrMessage
: this.options.staleIssueMessage;
const staleLabel: string = isPr
? this.options.stalePrLabel
: this.options.staleIssueLabel;
const exemptLabels = IssueProcessor.parseCommaSeparatedString(
isPr ? this.options.exemptPrLabels : this.options.exemptIssueLabels
);
const issueType: string = isPr ? 'pr' : 'issue';
if (!staleMessage) {
core.debug(`Skipping ${issueType} due to empty stale message`);
continue;
}
if (
exemptLabels.some((exemptLabel: string) =>
IssueProcessor.isLabeled(issue, exemptLabel)
)
) {
core.debug(`Skipping ${issueType} because it has an exempt label`);
continue; // don't process exempt issues
}
if (IssueProcessor.isLabeled(issue, staleLabel)) {
core.debug(`Found a stale ${issueType}`);
if (
this.options.daysBeforeClose >= 0 &&
IssueProcessor.wasLastUpdatedBefore(
issue,
this.options.daysBeforeClose
)
) {
core.debug(
`Closing ${issueType} because it was last updated on ${issue.updated_at}`
);
await this.closeIssue(issue);
this.operationsLeft -= 1;
} else {
core.debug(
`Ignoring stale ${issueType} because it was updated recenlty`
);
}
} else if (
IssueProcessor.wasLastUpdatedBefore(issue, this.options.daysBeforeStale)
) {
core.debug(
`Marking ${issueType} stale because it was last updated on ${issue.updated_at}`
);
await this.markStale(issue, staleMessage, staleLabel);
this.operationsLeft -= 2;
}
}
// do the next batch
return this.processIssues(page + 1);
}
// grab issues from github in baches of 100
private async getIssues(page: number): Promise<Issue[]> {
const issueResult: OcotoKitIssueList = await this.client.issues.listForRepo(
{
owner: github.context.repo.owner,
repo: github.context.repo.repo,
state: 'open',
labels: this.options.onlyLabels,
per_page: 100,
page
}
);
return issueResult.data;
}
// Mark an issue as stale with a comment and a label
private async markStale(
issue: Issue,
staleMessage: string,
staleLabel: string
): Promise<void> {
core.debug(`Marking issue #${issue.number} - ${issue.title} as stale`);
this.staleIssues.push(issue);
if (this.options.debugOnly) {
return;
}
await this.client.issues.createComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
body: staleMessage
});
await this.client.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
labels: [staleLabel]
});
}
/// Close an issue based on staleness
private async closeIssue(issue: Issue): Promise<void> {
core.debug(
`Closing issue #${issue.number} - ${issue.title} for being stale`
);
this.closedIssues.push(issue);
if (this.options.debugOnly) {
return;
}
await this.client.issues.update({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
state: 'closed'
});
}
private static isLabeled(issue: Issue, label: string): boolean {
const labelComparer: (l: Label) => boolean = l =>
label.localeCompare(l.name, undefined, {sensitivity: 'accent'}) === 0;
return issue.labels.filter(labelComparer).length > 0;
}
private static wasLastUpdatedBefore(issue: Issue, num_days: number): boolean {
const daysInMillis = 1000 * 60 * 60 * 24 * num_days;
const millisSinceLastUpdated =
new Date().getTime() - new Date(issue.updated_at).getTime();
return millisSinceLastUpdated >= daysInMillis;
}
private static parseCommaSeparatedString(s: string): string[] {
// String.prototype.split defaults to [''] when called on an empty string
// In this case, we'd prefer to just return an empty array indicating no labels
if (!s.length) return [];
return s.split(',').map(l => l.trim());
}
}

View File

@@ -1,150 +1,19 @@
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as Octokit from '@octokit/rest';
import {IssueProcessor, IssueProcessorOptions} from './IssueProcessor';
type Issue = Octokit.IssuesListForRepoResponseItem;
type IssueLabel = Octokit.IssuesListForRepoResponseItemLabelsItem;
type Args = {
repoToken: string;
staleIssueMessage: string;
stalePrMessage: string;
daysBeforeStale: number;
daysBeforeClose: number;
staleIssueLabel: string;
exemptIssueLabel: string;
stalePrLabel: string;
exemptPrLabel: string;
operationsPerRun: number;
};
async function run() {
async function run(): Promise<void> {
try {
const args = getAndValidateArgs();
const client = new github.GitHub(args.repoToken);
await processIssues(client, args, args.operationsPerRun);
const processor: IssueProcessor = new IssueProcessor(args);
await processor.processIssues();
} catch (error) {
core.error(error);
core.setFailed(error.message);
}
}
async function processIssues(
client: github.GitHub,
args: Args,
operationsLeft: number,
page: number = 1
): Promise<number> {
const issues = await client.issues.listForRepo({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
state: 'open',
per_page: 100,
page: page
});
operationsLeft -= 1;
if (issues.data.length === 0 || operationsLeft === 0) {
return operationsLeft;
}
for (var issue of issues.data.values()) {
core.debug(`found issue: ${issue.title} last updated ${issue.updated_at}`);
let isPr = !!issue.pull_request;
let staleMessage = isPr ? args.stalePrMessage : args.staleIssueMessage;
if (!staleMessage) {
core.debug(`skipping ${isPr ? 'pr' : 'issue'} due to empty message`);
continue;
}
let staleLabel = isPr ? args.stalePrLabel : args.staleIssueLabel;
let exemptLabel = isPr ? args.exemptPrLabel : args.exemptIssueLabel;
if (exemptLabel && isLabeled(issue, exemptLabel)) {
continue;
} else if (isLabeled(issue, staleLabel)) {
if (wasLastUpdatedBefore(issue, args.daysBeforeClose)) {
operationsLeft -= await closeIssue(client, issue);
} else {
continue;
}
} else if (wasLastUpdatedBefore(issue, args.daysBeforeStale)) {
operationsLeft -= await markStale(
client,
issue,
staleMessage,
staleLabel
);
}
if (operationsLeft <= 0) {
core.warning(
`performed ${args.operationsPerRun} operations, exiting to avoid rate limit`
);
return 0;
}
}
return await processIssues(client, args, operationsLeft, page + 1);
}
function isLabeled(issue: Issue, label: string): boolean {
const labelComparer: (l: IssueLabel) => boolean = l =>
label.localeCompare(l.name, undefined, {sensitivity: 'accent'}) === 0;
return issue.labels.filter(labelComparer).length > 0;
}
function wasLastUpdatedBefore(issue: Issue, num_days: number): boolean {
const daysInMillis = 1000 * 60 * 60 * 24 * num_days;
const millisSinceLastUpdated =
new Date().getTime() - new Date(issue.updated_at).getTime();
return millisSinceLastUpdated >= daysInMillis;
}
async function markStale(
client: github.GitHub,
issue: Issue,
staleMessage: string,
staleLabel: string
): Promise<number> {
core.debug(`marking issue${issue.title} as stale`);
await client.issues.createComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
body: staleMessage
});
await client.issues.addLabels({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
labels: [staleLabel]
});
return 2; // operations performed
}
async function closeIssue(
client: github.GitHub,
issue: Issue
): Promise<number> {
core.debug(`closing issue ${issue.title} for being stale`);
await client.issues.update({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
issue_number: issue.number,
state: 'closed'
});
return 1; // operations performed
}
function getAndValidateArgs(): Args {
function getAndValidateArgs(): IssueProcessorOptions {
const args = {
repoToken: core.getInput('repo-token', {required: true}),
staleIssueMessage: core.getInput('stale-issue-message'),
@@ -156,15 +25,17 @@ function getAndValidateArgs(): Args {
core.getInput('days-before-close', {required: true})
),
staleIssueLabel: core.getInput('stale-issue-label', {required: true}),
exemptIssueLabel: core.getInput('exempt-issue-label'),
exemptIssueLabels: core.getInput('exempt-issue-labels'),
stalePrLabel: core.getInput('stale-pr-label', {required: true}),
exemptPrLabel: core.getInput('exempt-pr-label'),
exemptPrLabels: core.getInput('exempt-pr-labels'),
onlyLabels: core.getInput('only-labels'),
operationsPerRun: parseInt(
core.getInput('operations-per-run', {required: true})
)
),
debugOnly: core.getInput('debug-only') === 'true'
};
for (var numberInput of [
for (const numberInput of [
'days-before-stale',
'days-before-close',
'operations-per-run'

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,63 +1,12 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./lib", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}
}