Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

test(issues): pin upstream inactivity clock regression [I1]

Corey Olson367a360b95b5
diff --git a/test/clarify-stale-fixture.js b/test/clarify-stale-fixture.js
new file mode 100644
index 00000000..72fbc9cd
--- /dev/null
+++ b/test/clarify-stale-fixture.js
@@ -0,0 +1,112 @@
+/** Execute the pinned upstream processor with isolated REST/clock adapters, never GitHub. */
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { stripTypeScriptTypes } from 'node:module';
+import vm from 'node:vm';
+import { createHash } from 'node:crypto';
+
+const manifest = JSON.parse(readFileSync(new URL('fixtures/actions-stale-v11/manifest.json', import.meta.url), 'utf8'));
+const DAY = 86400000, epoch = Date.parse('2026-01-01T00:00:00Z');
+let now = epoch;
+/** Preserve real Date parsing while injecting a deterministic wall clock. */
+class ClockDate extends Date {
+ constructor(...args) { super(...(args.length ? args : [now])); }
+ static now() { return now; }
+}
+/** Logging and quota accounting are outside this activity-policy contract. */
+class Logger {
+ info() {} warning() {} error() {}
+ createOptionLink(value) { return value; }
+}
+class Operations {
+ consumeOperation() {} getConsumedOperationsCount() { return 0; }
+}
+const context = vm.createContext({ Date: ClockDate, console,
+ Logger, IssueLogger: Logger, Operations, StaleOperations: Operations, retry: undefined,
+ LoggerService: new Proxy({}, { get: () => value => value }),
+ Option: new Proxy({}, { get: (_, key) => key }),
+ context: { repo: { owner: 'fixture', repo: 'fixture' } },
+ core: { setFailed(error) { throw error; } },
+ deburr: value => { assert.match(value, /^[\x00-\x7f]*$/u); return value; },
+ getHumanizedDate: date => date.toISOString(),
+ isValidDate: date => Number.isFinite(date.getTime()),
+});
+/** Only erase TypeScript/import/export syntax; retain complete upstream method bodies. */
+function load(file, name) {
+ const entry = manifest.sources.find(entry => entry.source === file);
+ assert.ok(entry, 'only a pinned upstream source is evaluated');
+ const bytes = readFileSync(new URL('fixtures/actions-stale-v11/' + entry.file, import.meta.url));
+ assert.equal(createHash('sha256').update(bytes).digest('hex'), entry.sha256, 'the exact pinned upstream bytes are intact');
+ const source = bytes.toString('utf8');
+ const plain = stripTypeScriptTypes(source).replace(/^import .*;\r?\n/gmu, '').replace(/^export /gmu, '');
+ vm.runInContext(plain + (name ? `\nglobalThis.${name} = ${name};` : ''), context, { filename: file });
+}
+for (const file of ['is-boolean', 'clean-label', 'words-to-list', 'is-labeled', 'is-pull-request', 'should-mark-when-stale']) {
+ load('src/functions/' + file + '.ts');
+}
+load('src/functions/dates/is-date-more-recent-than.ts');
+for (const [file, name] of [['ignore-updates', 'IgnoreUpdates'], ['assignees', 'Assignees'],
+ ['milestones', 'Milestones'], ['exempt-draft-pull-request', 'ExemptDraftPullRequest'], ['issue', 'Issue']]) {
+ load('src/classes/' + file + '.ts', name);
+}
+load('issues-processor-v11.ts', 'IssuesProcessor');
+
+/** Read the exact workflow's scalar action inputs; this is not a YAML general-purpose parser. */
+function inputs(text) {
+ const values = Object.fromEntries([...text.matchAll(/^ ([a-z-]+): (.+)$/gmu)].map(([, key, value]) => [key, value.replace(/^"|"$/gu, '')]));
+ return { daysBeforeStale: 60, daysBeforeClose: 7, onlyLabels: '', onlyPrLabels: '', onlyIssueLabels: values['only-issue-labels'],
+ anyOfLabels: '', anyOfIssueLabels: '', anyOfPrLabels: '', exemptIssueLabels: '', exemptPrLabels: '',
+ staleIssueLabel: values['stale-issue-label'], stalePrLabel: 'Stale', staleIssueMessage: '', stalePrMessage: '',
+ closeIssueMessage: values['close-issue-message'], closePrMessage: '', closeIssueLabel: '', closePrLabel: '',
+ daysBeforeIssueStale: Number(values['days-before-issue-stale']), daysBeforeIssueClose: Number(values['days-before-issue-close']),
+ daysBeforePrStale: Number(values['days-before-pr-stale']), daysBeforePrClose: Number(values['days-before-pr-close']),
+ removeStaleWhenUpdated: true, removeIssueStaleWhenUpdated: values['remove-issue-stale-when-updated'] === 'true',
+ removePrStaleWhenUpdated: false, ignoreUpdates: false, debugOnly: false,
+ exemptMilestones: '', exemptIssueMilestones: '', exemptPrMilestones: '',
+ exemptAssignees: '', exemptIssueAssignees: '', exemptPrAssignees: '', exemptDraftPr: false };
+}
+
+/** Advance one millisecond per synthetic REST request; adapter calls mutate only this in-memory issue. */
+async function scenario(text, expectedClose, { marked = false, labels = ['clarify'], pullRequest = false } = {}) {
+ const options = inputs(text), events = [{ event: 'labeled', label: { name: 'clarify' }, created_at: new Date(epoch).toISOString() }];
+ if (marked) events.push({ event: 'labeled', label: { name: options.staleIssueLabel }, created_at: new Date(epoch).toISOString() });
+ const comments = [{ user: { type: 'User' }, body: 'Clarification supplied.', created_at: new Date(epoch + 10 * DAY).toISOString() }];
+ const state = { number: 1, title: 'fixture', state: 'open', labels: [...labels, ...(marked ? [options.staleIssueLabel] : [])].map(name => ({ name })), pull_request: pullRequest ? {} : undefined, created_at: new Date(epoch).toISOString(),
+ updated_at: comments[0].created_at, locked: false, milestone: null, assignees: [] };
+ const writes = [];
+ const api = {
+ async listComments({ since }) { now++; return { data: comments.filter(comment => comment.created_at >= since) }; },
+ listEvents: { endpoint: { merge: value => value } },
+ async addLabels({ labels }) { now++; state.updated_at = new Date(now).toISOString(); writes.push(['add', ...labels]); for (const name of labels) {
+ if (!state.labels.some(label => label.name === name)) state.labels.push({ name });
+ events.push({ event: 'labeled', label: { name }, created_at: new Date(now).toISOString() });
+ } },
+ async removeLabel({ name }) { now++; state.updated_at = new Date(now).toISOString(); state.labels = state.labels.filter(label => label.name !== name); writes.push(['remove', name]); },
+ async createComment({ body }) { now++; state.updated_at = new Date(now).toISOString(); writes.push(['comment', body]); },
+ async update({ state: next }) { now++; state.updated_at = new Date(now).toISOString(); state.state = next; writes.push(['state', next]); },
+ };
+ context.getOctokit = () => ({ rest: { issues: api }, async paginate() { now++; return structuredClone(events); } });
+ const observations = [];
+ for (const day of marked ? [20, 24, 35] : [20, 24]) {
+ now = epoch + day * DAY + 1000;
+ const processor = new context.IssuesProcessor(options, {});
+ await processor.processIssue(new context.Issue(options, structuredClone(state)), [], [], []);
+ observations.push({ day, state: state.state, labels: state.labels.map(row => row.name) });
+ if (marked && day === 20) assert.deepEqual(state.labels.map(row => row.name), ['clarify'], 'activity removes only the inactive marker');
+ assert.equal(state.state, expectedClose && day === (marked ? 35 : 24) ? 'closed' : 'open');
+ }
+ if (expectedClose) assert.deepEqual(writes.filter(row => row[0] === 'comment'),
+ [['comment', "Closing for now since we haven't heard back. Reply to reopen."]]);
+ if (!expectedClose) assert.deepEqual(writes, [], 'excluded or still-active records receive no REST writes');
+ return { observations, writes };
+}
+
+/** Prove the committed workflow's inactivity behavior using the pinned upstream implementation. */
+export async function assertClarificationQuietPeriod(after) {
+ const before = readFileSync(new URL('fixtures/actions-stale-v11/before-stale.yml', import.meta.url), 'utf8');
+ return { before: await scenario(before, false), after: await scenario(after, true),
+ activityResetsMarker: await scenario(after, true, { marked: true }),
+ unlabelledIssue: await scenario(after, false, { labels: ['bug'] }),
+ pullRequest: await scenario(after, false, { pullRequest: true }),
+ scope: 'Complete pinned upstream processor, deterministic clock and simulated REST only; no network or scheduler.' };
+}
diff --git a/test/clarify-workflows.test.js b/test/clarify-workflows.test.js
index d6ffc0f9..f393c735 100644
--- a/test/clarify-workflows.test.js
+++ b/test/clarify-workflows.test.js
@@ -2,6 +2,7 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
+import { assertClarificationQuietPeriod } from './clarify-stale-fixture.js';
const staleWorkflow = readFileSync(new URL('../.github/workflows/stale.yml', import.meta.url), 'utf8');
const reopenWorkflow = readFileSync(new URL('../.github/workflows/reopen-clarify.yml', import.meta.url), 'utf8');
@@ -91,3 +92,12 @@ test('non-authors, pull requests, reopened issues, and missing clarify labels do
await runReopenScript(changedAuthor.github, changedAuthor.context);
assert.deepEqual(changedAuthor.calls, [['get', { owner: 'pullboard-dev', repo: 'pullboard', issue_number: 12 }]]);
});
+
+test('the pinned stale processor closes after fourteen quiet days since a day-ten comment [I1]', async t => {
+ const result = await assertClarificationQuietPeriod(staleWorkflow);
+ assert.equal(result.before.observations.at(-1).state, 'open', 'the former config reproduces the permanent-comment bug');
+ assert.deepEqual(result.after.observations.map(({ day, state }) => ({ day, state })), [
+ { day: 20, state: 'open' }, { day: 24, state: 'closed' },
+ ]);
+ t.diagnostic(result.scope);
+});
diff --git a/test/fixtures/actions-stale-v11/LICENSE b/test/fixtures/actions-stale-v11/LICENSE
new file mode 100644
index 00000000..5dad4d23
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/LICENSE
@@ -0,0 +1,18 @@
+Copyright (c) 2025, cache
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/test/fixtures/actions-stale-v11/README.md b/test/fixtures/actions-stale-v11/README.md
new file mode 100644
index 00000000..34921cee
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/README.md
@@ -0,0 +1,3 @@
+Pinned MIT-licensed actions/stale v11.0.0 source, retained byte for byte as test data. manifest.json records the original URLs and SHA-256 digests. No package is installed and tests make no network requests.
+
+clarify-stale-fixture.js strips TypeScript and module syntax, then executes the complete upstream processor, Issue and policy-helper bodies against deterministic clock and REST adapters. Logging, quota counting and ASCII-only label normalization are adapters; no authorization, scheduler, real GitHub or elapsed-fourteen-day behavior is claimed. before-stale.yml is the former Pullboard configuration used as the regression control.
diff --git a/test/fixtures/actions-stale-v11/assignees.ts.txt b/test/fixtures/actions-stale-v11/assignees.ts.txt
new file mode 100644
index 00000000..f816ec64
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/assignees.ts.txt
@@ -0,0 +1,290 @@
+import deburr from 'lodash.deburr';
+import {Option} from '../enums/option.js';
+import {wordsToList} from '../functions/words-to-list.js';
+import {Assignee} from '../interfaces/assignee.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {Issue} from './issue.js';
+import {IssueLogger} from './loggers/issue-logger.js';
+import {LoggerService} from '../services/logger.service.js';
+
+type CleanAssignee = string;
+
+export class Assignees {
+ private readonly _options: IIssuesProcessorOptions;
+ private readonly _issue: Issue;
+ private readonly _issueLogger: IssueLogger;
+
+ constructor(options: Readonly<IIssuesProcessorOptions>, issue: Issue) {
+ this._options = options;
+ this._issue = issue;
+ this._issueLogger = new IssueLogger(issue);
+ }
+
+ private static _cleanAssignee(assignee: Readonly<string>): CleanAssignee {
+ return deburr(assignee.toLowerCase());
+ }
+
+ shouldExemptAssignees(): boolean {
+ if (!this._issue.hasAssignees) {
+ this._issueLogger.info('This $$type has no assignee');
+ this._logSkip();
+
+ return false;
+ }
+
+ if (this._shouldExemptAllAssignees()) {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skipping this $$type because it has an exempt assignee'
+ );
+
+ return true;
+ }
+
+ const exemptAssignees: string[] = this._getExemptAssignees();
+
+ if (exemptAssignees.length === 0) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `No assignee option was specified to skip the stale process for this $$type`
+ );
+ this._logSkip();
+
+ return false;
+ }
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `Found ${LoggerService.cyan(exemptAssignees.length)} assignee${
+ exemptAssignees.length > 1 ? 's' : ''
+ } that can exempt stale on this $$type`
+ );
+
+ const hasExemptAssignee: boolean = exemptAssignees.some(
+ (exemptAssignee: Readonly<string>): boolean =>
+ this._hasAssignee(exemptAssignee)
+ );
+
+ if (!hasExemptAssignee) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ 'No assignee on this $$type can exempt the stale process'
+ );
+ this._logSkip();
+ } else {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skipping this $$type because it has an exempt assignee'
+ );
+ }
+
+ return hasExemptAssignee;
+ }
+
+ private _getExemptAssignees(): string[] {
+ return this._issue.isPullRequest
+ ? this._getExemptPullRequestAssignees()
+ : this._getExemptIssueAssignees();
+ }
+
+ private _getExemptIssueAssignees(): string[] {
+ if (this._options.exemptIssueAssignees === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptIssueAssignees
+ )} is disabled. No specific assignee can skip the stale process for this $$type`
+ );
+
+ if (this._options.exemptAssignees === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAssignees
+ )} is disabled. No specific assignee can skip the stale process for this $$type`
+ );
+
+ return [];
+ }
+
+ const exemptAssignees: string[] = wordsToList(
+ this._options.exemptAssignees
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAssignees
+ )} is set. ${LoggerService.cyan(exemptAssignees.length)} assignee${
+ exemptAssignees.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptAssignees;
+ }
+
+ const exemptAssignees: string[] = wordsToList(
+ this._options.exemptIssueAssignees
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptIssueAssignees
+ )} is set. ${LoggerService.cyan(exemptAssignees.length)} assignee${
+ exemptAssignees.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptAssignees;
+ }
+
+ private _getExemptPullRequestAssignees(): string[] {
+ if (this._options.exemptPrAssignees === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptPrAssignees
+ )} is disabled. No specific assignee can skip the stale process for this $$type`
+ );
+
+ if (this._options.exemptAssignees === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAssignees
+ )} is disabled. No specific assignee can skip the stale process for this $$type`
+ );
+
+ return [];
+ }
+
+ const exemptAssignees: string[] = wordsToList(
+ this._options.exemptAssignees
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAssignees
+ )} is set. ${LoggerService.cyan(exemptAssignees.length)} assignee${
+ exemptAssignees.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptAssignees;
+ }
+
+ const exemptAssignees: string[] = wordsToList(
+ this._options.exemptPrAssignees
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptPrAssignees
+ )} is set. ${LoggerService.cyan(exemptAssignees.length)} assignee${
+ exemptAssignees.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptAssignees;
+ }
+
+ private _hasAssignee(assignee: Readonly<string>): boolean {
+ const cleanAssignee: CleanAssignee = Assignees._cleanAssignee(assignee);
+
+ return this._issue.assignees.some(
+ (issueAssignee: Readonly<Assignee>): boolean => {
+ const isSameAssignee: boolean =
+ cleanAssignee === Assignees._cleanAssignee(issueAssignee.login);
+
+ if (isSameAssignee) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `@${issueAssignee.login} is assigned on this $$type and is an exempt assignee`
+ );
+ }
+
+ return isSameAssignee;
+ }
+ );
+ }
+
+ private _shouldExemptAllAssignees(): boolean {
+ return this._issue.isPullRequest
+ ? this._shouldExemptAllPullRequestAssignees()
+ : this._shouldExemptAllIssueAssignees();
+ }
+
+ private _shouldExemptAllIssueAssignees(): boolean {
+ if (this._options.exemptAllIssueAssignees === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllIssueAssignees
+ )} is enabled. Any assignee on this $$type will skip the stale process`
+ );
+
+ return true;
+ } else if (this._options.exemptAllIssueAssignees === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllIssueAssignees
+ )} is disabled. Only some specific assignees on this $$type will skip the stale process`
+ );
+
+ return false;
+ }
+
+ this._logExemptAllAssigneesOption();
+
+ return this._options.exemptAllAssignees;
+ }
+
+ private _shouldExemptAllPullRequestAssignees(): boolean {
+ if (this._options.exemptAllPrAssignees === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllPrAssignees
+ )} is enabled. Any assignee on this $$type will skip the stale process`
+ );
+
+ return true;
+ } else if (this._options.exemptAllPrAssignees === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllPrAssignees
+ )} is disabled. Only some specific assignees on this $$type will skip the stale process`
+ );
+
+ return false;
+ }
+
+ this._logExemptAllAssigneesOption();
+
+ return this._options.exemptAllAssignees;
+ }
+
+ private _logExemptAllAssigneesOption(): void {
+ if (this._options.exemptAllAssignees) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllAssignees
+ )} is enabled. Any assignee on this $$type will skip the stale process`
+ );
+ } else {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllAssignees
+ )} is disabled. Only some specific assignees on this $$type will skip the stale process`
+ );
+ }
+ }
+
+ private _logSkip(): void {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skip the assignees checks'
+ );
+ }
+}
diff --git a/test/fixtures/actions-stale-v11/before-stale.yml b/test/fixtures/actions-stale-v11/before-stale.yml
new file mode 100644
index 00000000..c3090230
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/before-stale.yml
@@ -0,0 +1,26 @@
+name: Close inactive clarification issues
+
+on:
+ schedule:
+ - cron: '23 4 * * *'
+
+permissions:
+ issues: write
+ pull-requests: read
+
+jobs:
+ close-clarification-issues:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/[email protected]
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
+ only-issue-labels: clarify
+ stale-issue-label: clarify
+ days-before-issue-stale: -1
+ days-before-issue-close: 14
+ remove-issue-stale-when-updated: false
+ close-issue-message: "Closing for now since we haven't heard back. Reply to reopen."
+ days-before-pr-stale: -1
+ days-before-pr-close: -1
+ remove-pr-stale-when-updated: false
diff --git a/test/fixtures/actions-stale-v11/clean-label.ts.txt b/test/fixtures/actions-stale-v11/clean-label.ts.txt
new file mode 100644
index 00000000..0966bd52
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/clean-label.ts.txt
@@ -0,0 +1,14 @@
+import deburr from 'lodash.deburr';
+import {CleanLabel} from '../types/clean-label.js';
+
+/**
+ * @description
+ * Clean a label by lowercasing it and deburring it for consistency
+ *
+ * @param {string} label A raw GitHub label
+ *
+ * @return {string} A lowercased, deburred version of the passed in label
+ */
+export function cleanLabel(label?: Readonly<string>): CleanLabel {
+ return deburr(label?.toLowerCase());
+}
diff --git a/test/fixtures/actions-stale-v11/exempt-draft-pull-request.ts.txt b/test/fixtures/actions-stale-v11/exempt-draft-pull-request.ts.txt
new file mode 100644
index 00000000..ab8595af
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/exempt-draft-pull-request.ts.txt
@@ -0,0 +1,56 @@
+import {Option} from '../enums/option.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {IPullRequest} from '../interfaces/pull-request.js';
+import {LoggerService} from '../services/logger.service.js';
+import {Issue} from './issue.js';
+import {IssueLogger} from './loggers/issue-logger.js';
+
+export class ExemptDraftPullRequest {
+ private readonly _options: IIssuesProcessorOptions;
+ private readonly _issue: Issue;
+ private readonly _issueLogger: IssueLogger;
+
+ constructor(options: Readonly<IIssuesProcessorOptions>, issue: Issue) {
+ this._options = options;
+ this._issue = issue;
+ this._issueLogger = new IssueLogger(issue);
+ }
+
+ async shouldExemptDraftPullRequest(
+ // keep this for backward compatibility
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ pullRequestCallback: () => Promise<IPullRequest | undefined | void>
+ ): Promise<boolean> {
+ if (this._issue.isPullRequest) {
+ if (this._options.exemptDraftPr) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptDraftPr
+ )} is enabled`
+ );
+
+ /* This code was used until Jun 15 2022 - it is unclear why they had to call API for getting pull request
+ const pullRequest: IPullRequest | undefined | void =
+ await pullRequestCallback();
+
+ if (pullRequest?.draft === true) {
+ */
+ if (this._issue?.draft === true) {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ `Skip the $$type draft checks`
+ );
+
+ return true;
+ } else {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ `Continuing the process for this $$type because it is not a draft`
+ );
+ }
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/test/fixtures/actions-stale-v11/ignore-updates.ts.txt b/test/fixtures/actions-stale-v11/ignore-updates.ts.txt
new file mode 100644
index 00000000..f44b59aa
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/ignore-updates.ts.txt
@@ -0,0 +1,90 @@
+import {Option} from '../enums/option.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {Issue} from './issue.js';
+import {IssueLogger} from './loggers/issue-logger.js';
+
+export class IgnoreUpdates {
+ private readonly _options: IIssuesProcessorOptions;
+ private readonly _issue: Issue;
+ private readonly _issueLogger: IssueLogger;
+
+ constructor(options: Readonly<IIssuesProcessorOptions>, issue: Issue) {
+ this._options = options;
+ this._issue = issue;
+ this._issueLogger = new IssueLogger(issue);
+ }
+
+ shouldIgnoreUpdates(): boolean {
+ return this._shouldIgnoreUpdates();
+ }
+
+ private _shouldIgnoreUpdates(): boolean {
+ return this._issue.isPullRequest
+ ? this._shouldIgnorePullRequestUpdates()
+ : this._shouldIgnoreIssueUpdates();
+ }
+
+ private _shouldIgnorePullRequestUpdates(): boolean {
+ if (this._options.ignorePrUpdates === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnorePrUpdates
+ )} is enabled. The stale counter will ignore any updates or comments on this $$type and will use the creation date as a reference ignoring any kind of update`
+ );
+
+ return true;
+ } else if (this._options.ignorePrUpdates === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnorePrUpdates
+ )} is disabled. The stale counter will take into account updates and comments on this $$type to avoid to stale when there is some update`
+ );
+
+ return false;
+ }
+
+ this._logIgnoreUpdates();
+
+ return this._options.ignoreUpdates;
+ }
+
+ private _shouldIgnoreIssueUpdates(): boolean {
+ if (this._options.ignoreIssueUpdates === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnoreIssueUpdates
+ )} is enabled. The stale counter will ignore any updates or comments on this $$type and will use the creation date as a reference ignoring any kind of update`
+ );
+
+ return true;
+ } else if (this._options.ignoreIssueUpdates === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnoreIssueUpdates
+ )} is disabled. The stale counter will take into account updates and comments on this $$type to avoid to stale when there is some update`
+ );
+
+ return false;
+ }
+
+ this._logIgnoreUpdates();
+
+ return this._options.ignoreUpdates;
+ }
+
+ private _logIgnoreUpdates(): void {
+ if (this._options.ignoreUpdates) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnoreUpdates
+ )} is enabled. The stale counter will ignore any updates or comments on this $$type and will use the creation date as a reference ignoring any kind of update`
+ );
+ } else {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.IgnoreUpdates
+ )} is disabled. The stale counter will take into account updates and comments on this $$type to avoid to stale when there is some update`
+ );
+ }
+ }
+}
diff --git a/test/fixtures/actions-stale-v11/is-boolean.ts.txt b/test/fixtures/actions-stale-v11/is-boolean.ts.txt
new file mode 100644
index 00000000..4721bc50
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/is-boolean.ts.txt
@@ -0,0 +1,3 @@
+export function isBoolean(value: unknown): value is boolean {
+ return value === true || value === false;
+}
diff --git a/test/fixtures/actions-stale-v11/is-date-more-recent-than.ts.txt b/test/fixtures/actions-stale-v11/is-date-more-recent-than.ts.txt
new file mode 100644
index 00000000..ee7dbda9
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/is-date-more-recent-than.ts.txt
@@ -0,0 +1,31 @@
+/// returns false if the dates are equal within the `equalityToleranceInSeconds` number of seconds
+/// otherwise returns true if `comparedDate` is after `date`
+
+export function isDateMoreRecentThan(
+ date: Readonly<Date>,
+ comparedDate: Readonly<Date>,
+ equalityToleranceInSeconds = 0
+): boolean {
+ if (equalityToleranceInSeconds > 0) {
+ const areDatesEqual = isDateEqualTo(
+ date,
+ comparedDate,
+ equalityToleranceInSeconds
+ );
+
+ return !areDatesEqual && date > comparedDate;
+ }
+
+ return date > comparedDate;
+}
+
+export function isDateEqualTo(
+ date: Date,
+ otherDate: Date,
+ toleranceInSeconds: number
+): boolean {
+ const timestamp = date.getTime();
+ const otherTimestamp = otherDate.getTime();
+ const deltaInSeconds = Math.abs(timestamp - otherTimestamp) / 1000;
+ return deltaInSeconds <= toleranceInSeconds;
+}
diff --git a/test/fixtures/actions-stale-v11/is-labeled.ts.txt b/test/fixtures/actions-stale-v11/is-labeled.ts.txt
new file mode 100644
index 00000000..4de98182
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/is-labeled.ts.txt
@@ -0,0 +1,21 @@
+import {Issue} from '../classes/issue.js';
+import {ILabel} from '../interfaces/label.js';
+import {cleanLabel} from './clean-label.js';
+
+/**
+ * @description
+ * Check if the given label is listed as a label of the given issue
+ *
+ * @param {Readonly<Issue>} issue A GitHub issue containing some labels
+ * @param {Readonly<string>} label The label to check the presence with
+ *
+ * @return {boolean} Return true when the given label is also in the given issue labels
+ */
+export function isLabeled(
+ issue: Readonly<Issue>,
+ label: Readonly<string>
+): boolean {
+ return !!issue.labels.find((issueLabel: Readonly<ILabel>): boolean => {
+ return cleanLabel(label) === cleanLabel(issueLabel.name);
+ });
+}
diff --git a/test/fixtures/actions-stale-v11/is-pull-request.ts.txt b/test/fixtures/actions-stale-v11/is-pull-request.ts.txt
new file mode 100644
index 00000000..69aa922e
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/is-pull-request.ts.txt
@@ -0,0 +1,5 @@
+import {Issue} from '../classes/issue.js';
+
+export function isPullRequest(issue: Readonly<Issue>): boolean {
+ return !!issue.pull_request;
+}
diff --git a/test/fixtures/actions-stale-v11/issue.ts.txt b/test/fixtures/actions-stale-v11/issue.ts.txt
new file mode 100644
index 00000000..2d170ac0
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/issue.ts.txt
@@ -0,0 +1,86 @@
+import {isLabeled} from '../functions/is-labeled.js';
+import {isPullRequest} from '../functions/is-pull-request.js';
+import {Assignee} from '../interfaces/assignee.js';
+import {IIssue, OctokitIssue} from '../interfaces/issue.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {ILabel} from '../interfaces/label.js';
+import {IMilestone} from '../interfaces/milestone.js';
+import {IsoDateString} from '../types/iso-date-string.js';
+import {Operations} from './operations.js';
+
+export class Issue implements IIssue {
+ readonly title: string;
+ readonly number: number;
+ created_at: IsoDateString;
+ updated_at: IsoDateString;
+ readonly draft: boolean;
+ readonly labels: ILabel[];
+ readonly pull_request: object | null | undefined;
+ readonly state: string | 'closed' | 'open';
+ readonly locked: boolean;
+ readonly milestone?: IMilestone | null;
+ readonly assignees: Assignee[];
+ isStale: boolean;
+ markedStaleThisRun: boolean;
+ operations = new Operations();
+ private readonly _options: IIssuesProcessorOptions;
+ readonly issue_type?: string;
+
+ constructor(
+ options: Readonly<IIssuesProcessorOptions>,
+ issue: Readonly<OctokitIssue> | Readonly<IIssue>
+ ) {
+ this._options = options;
+ this.title = issue.title;
+ this.number = issue.number;
+ this.created_at = issue.created_at;
+ this.updated_at = issue.updated_at;
+ this.draft = Boolean(issue.draft);
+ this.labels = mapLabels(issue.labels);
+ this.pull_request = issue.pull_request;
+ this.state = issue.state;
+ this.locked = issue.locked;
+ this.milestone = issue.milestone;
+ this.assignees = issue.assignees || [];
+ this.isStale = isLabeled(this, this.staleLabel);
+ this.markedStaleThisRun = false;
+
+ if (
+ typeof (issue as any).type === 'object' &&
+ (issue as any).type !== null
+ ) {
+ this.issue_type = (issue as any).type.name;
+ } else {
+ this.issue_type = undefined;
+ }
+ }
+
+ get isPullRequest(): boolean {
+ return isPullRequest(this);
+ }
+
+ get staleLabel(): string {
+ return this._getStaleLabel();
+ }
+
+ get hasAssignees(): boolean {
+ return this.assignees.length > 0;
+ }
+
+ private _getStaleLabel(): string {
+ return this.isPullRequest
+ ? this._options.stalePrLabel
+ : this._options.staleIssueLabel;
+ }
+}
+
+function mapLabels(labels: (string | ILabel)[] | ILabel[]): ILabel[] {
+ return labels.map(label => {
+ if (typeof label == 'string') {
+ return {
+ name: label
+ };
+ }
+ return label;
+ });
+}
diff --git a/test/fixtures/actions-stale-v11/issues-processor-v11.ts.txt b/test/fixtures/actions-stale-v11/issues-processor-v11.ts.txt
new file mode 100644
index 00000000..62189bf1
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/issues-processor-v11.ts.txt
@@ -0,0 +1,1385 @@
+import * as core from '@actions/core';
+import {context, getOctokit} from '@actions/github';
+import {Option} from '../enums/option.js';
+import {getHumanizedDate} from '../functions/dates/get-humanized-date.js';
+import {isDateMoreRecentThan} from '../functions/dates/is-date-more-recent-than.js';
+import {isValidDate} from '../functions/dates/is-valid-date.js';
+import {isBoolean} from '../functions/is-boolean.js';
+import {isLabeled} from '../functions/is-labeled.js';
+import {cleanLabel} from '../functions/clean-label.js';
+import {shouldMarkWhenStale} from '../functions/should-mark-when-stale.js';
+import {wordsToList} from '../functions/words-to-list.js';
+import {IComment} from '../interfaces/comment.js';
+import {IIssueEvent} from '../interfaces/issue-event.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {IPullRequest} from '../interfaces/pull-request.js';
+import {Assignees} from './assignees.js';
+import {IgnoreUpdates} from './ignore-updates.js';
+import {ExemptDraftPullRequest} from './exempt-draft-pull-request.js';
+import {Issue} from './issue.js';
+import {IssueLogger} from './loggers/issue-logger.js';
+import {Logger} from './loggers/logger.js';
+import {Milestones} from './milestones.js';
+import {StaleOperations} from './stale-operations.js';
+import {Statistics} from './statistics.js';
+import {LoggerService} from '../services/logger.service.js';
+import {OctokitIssue} from '../interfaces/issue.js';
+import {retry} from '@octokit/plugin-retry';
+import {IState} from '../interfaces/state/state.js';
+import {IRateLimit} from '../interfaces/rate-limit.js';
+import {RateLimit} from './rate-limit.js';
+import {getSortField} from '../functions/get-sort-field.js';
+
+/***
+ * Handle processing of issues for staleness/closure.
+ */
+
+export class IssuesProcessor {
+ private static _updatedSince(timestamp: string, num_days: number): boolean {
+ const daysInMillis = 1000 * 60 * 60 * 24 * num_days;
+ const millisSinceLastUpdated =
+ new Date().getTime() - new Date(timestamp).getTime();
+
+ return millisSinceLastUpdated <= daysInMillis;
+ }
+
+ private static _endIssueProcessing(issue: Issue): void {
+ const consumedOperationsCount: number =
+ issue.operations.getConsumedOperationsCount();
+
+ if (consumedOperationsCount > 0) {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ LoggerService.cyan(consumedOperationsCount),
+ `operation${
+ consumedOperationsCount > 1 ? 's' : ''
+ } consumed for this $$type`
+ );
+ }
+ }
+
+ private static _getCloseLabelUsedOptionName(
+ issue: Readonly<Issue>
+ ): Option.ClosePrLabel | Option.CloseIssueLabel {
+ return issue.isPullRequest ? Option.ClosePrLabel : Option.CloseIssueLabel;
+ }
+
+ readonly operations: StaleOperations;
+ readonly client: ReturnType<typeof getOctokit>;
+ readonly options: IIssuesProcessorOptions;
+ readonly staleIssues: Issue[] = [];
+ readonly closedIssues: Issue[] = [];
+ readonly deletedBranchIssues: Issue[] = [];
+ readonly removedLabelIssues: Issue[] = [];
+ readonly addedLabelIssues: Issue[] = [];
+ readonly addedCloseCommentIssues: Issue[] = [];
+ readonly statistics: Statistics | undefined;
+ private readonly _logger: Logger = new Logger();
+ private readonly state: IState;
+
+ constructor(options: IIssuesProcessorOptions, state: IState) {
+ this.options = options;
+ this.state = state;
+ this.client = getOctokit(this.options.repoToken, undefined, retry);
+ this.operations = new StaleOperations(this.options);
+
+ this._logger.info(
+ LoggerService.yellow(`Starting the stale action process...`)
+ );
+
+ if (this.options.debugOnly) {
+ this._logger.warning(
+ LoggerService.yellowBright(`Executing in debug mode!`)
+ );
+ this._logger.warning(
+ LoggerService.yellowBright(
+ `The debug output will be written but no issues/PRs will be processed.`
+ )
+ );
+ }
+
+ if (this.options.enableStatistics) {
+ this.statistics = new Statistics();
+ }
+ }
+
+ async processIssues(page: Readonly<number> = 1): Promise<number> {
+ // get the next batch of issues
+ const issues: Issue[] = await this.getIssues(page);
+
+ if (issues.length <= 0) {
+ this._logger.info(
+ LoggerService.green(`No more issues found to process. Exiting...`)
+ );
+ this.statistics
+ ?.setOperationsCount(this.operations.getConsumedOperationsCount())
+ .logStats();
+
+ this.state.reset();
+
+ return this.operations.getRemainingOperationsCount();
+ } else {
+ this._logger.info(
+ `${LoggerService.yellow(
+ 'Processing the batch of issues '
+ )} ${LoggerService.cyan(`#${page}`)} ${LoggerService.yellow(
+ ' containing '
+ )} ${LoggerService.cyan(issues.length)} ${LoggerService.yellow(
+ ` issue${issues.length > 1 ? 's' : ''}...`
+ )}`
+ );
+ }
+
+ const labelsToRemoveWhenStale: string[] = wordsToList(
+ this.options.labelsToRemoveWhenStale
+ );
+
+ const labelsToAddWhenUnstale: string[] = wordsToList(
+ this.options.labelsToAddWhenUnstale
+ );
+ const labelsToRemoveWhenUnstale: string[] = wordsToList(
+ this.options.labelsToRemoveWhenUnstale
+ );
+
+ for (const issue of issues.values()) {
+ // Stop the processing if no more operations remains
+ if (!this.operations.hasRemainingOperations()) {
+ break;
+ }
+
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+ if (this.state.isIssueProcessed(issue)) {
+ issueLogger.info(
+ ' $$type skipped due being processed during the previous run'
+ );
+ continue;
+ }
+ await issueLogger.grouping(`$$type #${issue.number}`, async () => {
+ await this.processIssue(
+ issue,
+ labelsToAddWhenUnstale,
+ labelsToRemoveWhenUnstale,
+ labelsToRemoveWhenStale
+ );
+ });
+ this.state.addIssueToProcessed(issue);
+ }
+
+ if (!this.operations.hasRemainingOperations()) {
+ this._logger.warning(
+ LoggerService.yellowBright(`No more operations left! Exiting...`)
+ );
+ this._logger.warning(
+ `${LoggerService.yellowBright(
+ 'If you think that not enough issues were processed you could try to increase the quantity related to the '
+ )} ${this._logger.createOptionLink(
+ Option.OperationsPerRun
+ )} ${LoggerService.yellowBright(
+ ' option which is currently set to '
+ )} ${LoggerService.cyan(this.options.operationsPerRun)}`
+ );
+ this.statistics
+ ?.setOperationsCount(this.operations.getConsumedOperationsCount())
+ .logStats();
+
+ return 0;
+ }
+
+ this._logger.info(
+ `${LoggerService.green('Batch ')} ${LoggerService.cyan(
+ `#${page}`
+ )} ${LoggerService.green(' processed.')}`
+ );
+
+ // Do the next batch
+ return this.processIssues(page + 1);
+ }
+
+ async processIssue(
+ issue: Issue,
+ labelsToAddWhenUnstale: Readonly<string>[],
+ labelsToRemoveWhenUnstale: Readonly<string>[],
+ labelsToRemoveWhenStale: Readonly<string>[]
+ ): Promise<void> {
+ this.statistics?.incrementProcessedItemsCount(issue);
+
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+ issueLogger.info(
+ `Found this $$type last updated at: ${LoggerService.cyan(
+ issue.updated_at
+ )}`
+ );
+
+ // calculate string based messages for this issue
+ const staleMessage: string = issue.isPullRequest
+ ? this.options.stalePrMessage
+ : this.options.staleIssueMessage;
+ const closeMessage: string = issue.isPullRequest
+ ? this.options.closePrMessage
+ : this.options.closeIssueMessage;
+ const staleLabel: string = issue.isPullRequest
+ ? this.options.stalePrLabel
+ : this.options.staleIssueLabel;
+ const closeLabel: string = issue.isPullRequest
+ ? this.options.closePrLabel
+ : this.options.closeIssueLabel;
+ const skipMessage = issue.isPullRequest
+ ? this.options.stalePrMessage.length === 0
+ : this.options.staleIssueMessage.length === 0;
+ const daysBeforeStale: number = issue.isPullRequest
+ ? this._getDaysBeforePrStale()
+ : this._getDaysBeforeIssueStale();
+
+ if (issue.state === 'closed') {
+ issueLogger.info(`Skipping this $$type because it is closed`);
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process closed issues
+ }
+
+ if (issue.locked) {
+ issueLogger.info(`Skipping this $$type because it is locked`);
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process locked issues
+ }
+
+ if (this._isIncludeOnlyAssigned(issue)) {
+ issueLogger.info(
+ `Skipping this $$type because its assignees list is empty`
+ );
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // If the issue has an 'include-only-assigned' option set, process only issues with nonempty assignees list
+ }
+
+ if (this.options.onlyIssueTypes && !issue.isPullRequest) {
+ const allowedTypes = this.options.onlyIssueTypes
+ .split(',')
+ .map(t => t.trim().toLowerCase())
+ .filter(Boolean);
+ const issueType = (issue.issue_type || '').toLowerCase();
+ if (!allowedTypes.includes(issueType)) {
+ issueLogger.info(
+ `Skipping this $$type because its type ('${
+ issue.issue_type
+ }') is not in onlyIssueTypes (${allowedTypes.join(', ')})`
+ );
+ IssuesProcessor._endIssueProcessing(issue);
+ return;
+ }
+ }
+
+ const onlyLabels: string[] = wordsToList(this._getOnlyLabels(issue));
+
+ if (onlyLabels.length > 0) {
+ issueLogger.info(
+ `The option ${issueLogger.createOptionLink(
+ Option.OnlyLabels
+ )} was specified to only process issues and pull requests with all those labels (${LoggerService.cyan(
+ onlyLabels.length
+ )})`
+ );
+
+ const hasAllWhitelistedLabels: boolean = onlyLabels.every(
+ (label: Readonly<string>): boolean => {
+ return isLabeled(issue, label);
+ }
+ );
+
+ if (!hasAllWhitelistedLabels) {
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Skipping this $$type because it doesn't have all the required labels`
+ );
+
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process issues without all of the required labels
+ } else {
+ issueLogger.info(
+ LoggerService.white('├──'),
+ `All the required labels are present on this $$type`
+ );
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Continuing the process for this $$type`
+ );
+ }
+ } else {
+ issueLogger.info(
+ `The option ${issueLogger.createOptionLink(
+ Option.OnlyLabels
+ )} was not specified`
+ );
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Continuing the process for this $$type`
+ );
+ }
+
+ issueLogger.info(
+ `Days before $$type stale: ${LoggerService.cyan(daysBeforeStale)}`
+ );
+
+ const shouldMarkAsStale: boolean = shouldMarkWhenStale(daysBeforeStale);
+
+ // Try to remove the close label when not close/locked issue or PR
+ await this._removeCloseLabel(issue, closeLabel);
+
+ if (this.options.startDate) {
+ const startDate: Date = new Date(this.options.startDate);
+ const createdAt: Date = new Date(issue.created_at);
+
+ issueLogger.info(
+ `A start date was specified for the ${getHumanizedDate(
+ startDate
+ )} (${LoggerService.cyan(this.options.startDate)})`
+ );
+
+ // Expecting that GitHub will always set a creation date on the issues and PRs
+ // But you never know!
+ if (!isValidDate(createdAt)) {
+ IssuesProcessor._endIssueProcessing(issue);
+ core.setFailed(
+ new Error(`Invalid issue field: "created_at". Expected a valid date`)
+ );
+ }
+
+ issueLogger.info(
+ `$$type created the ${getHumanizedDate(
+ createdAt
+ )} (${LoggerService.cyan(issue.created_at)})`
+ );
+
+ if (!isDateMoreRecentThan(createdAt, startDate)) {
+ issueLogger.info(
+ `Skipping this $$type because it was created before the specified start date`
+ );
+
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process issues which were created before the start date
+ }
+ }
+
+ if (issue.isStale) {
+ issueLogger.info(`This $$type includes a stale label`);
+ } else {
+ issueLogger.info(`This $$type does not include a stale label`);
+ }
+
+ const exemptLabels: string[] = wordsToList(
+ issue.isPullRequest
+ ? this.options.exemptPrLabels
+ : this.options.exemptIssueLabels
+ );
+
+ const hasExemptLabel = exemptLabels.some((exemptLabel: Readonly<string>) =>
+ isLabeled(issue, exemptLabel)
+ );
+
+ if (hasExemptLabel) {
+ issueLogger.info(
+ `Skipping this $$type because it contains an exempt label, see ${issueLogger.createOptionLink(
+ issue.isPullRequest ? Option.ExemptPrLabels : Option.ExemptIssueLabels
+ )} for more details`
+ );
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process exempt issues
+ }
+
+ const anyOfLabels: string[] = wordsToList(this._getAnyOfLabels(issue));
+
+ if (anyOfLabels.length > 0) {
+ issueLogger.info(
+ `The option ${issueLogger.createOptionLink(
+ Option.AnyOfLabels
+ )} was specified to only process the issues and pull requests with one of those labels (${LoggerService.cyan(
+ anyOfLabels.length
+ )})`
+ );
+
+ const hasOneOfWhitelistedLabels: boolean = anyOfLabels.some(
+ (label: Readonly<string>): boolean => {
+ return isLabeled(issue, label);
+ }
+ );
+
+ if (!hasOneOfWhitelistedLabels) {
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Skipping this $$type because it doesn't have one of the required labels`
+ );
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process issues without any of the required labels
+ } else {
+ issueLogger.info(
+ LoggerService.white('├──'),
+ `One of the required labels is present on this $$type`
+ );
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Continuing the process for this $$type`
+ );
+ }
+ } else {
+ issueLogger.info(
+ `The option ${issueLogger.createOptionLink(
+ Option.AnyOfLabels
+ )} was not specified`
+ );
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Continuing the process for this $$type`
+ );
+ }
+
+ const milestones: Milestones = new Milestones(this.options, issue);
+
+ if (milestones.shouldExemptMilestones()) {
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process exempt milestones
+ }
+
+ const assignees: Assignees = new Assignees(this.options, issue);
+
+ if (assignees.shouldExemptAssignees()) {
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process exempt assignees
+ }
+
+ // Ignore draft PR
+ // Note that this check is so far below because it cost one read operation
+ // So it's simply better to do all the stale checks which don't cost more operation before this one
+ const exemptDraftPullRequest: ExemptDraftPullRequest =
+ new ExemptDraftPullRequest(this.options, issue);
+
+ if (
+ await exemptDraftPullRequest.shouldExemptDraftPullRequest(
+ async (): Promise<IPullRequest | undefined | void> => {
+ return this.getPullRequest(issue);
+ }
+ )
+ ) {
+ IssuesProcessor._endIssueProcessing(issue);
+ return; // Don't process draft PR
+ }
+
+ // Determine if this issue needs to be marked stale first
+ if (!issue.isStale) {
+ issueLogger.info(`This $$type is not stale`);
+
+ const shouldIgnoreUpdates: boolean = new IgnoreUpdates(
+ this.options,
+ issue
+ ).shouldIgnoreUpdates();
+
+ // Should this issue be marked as stale?
+ let shouldBeStale: boolean;
+
+ // Ignore the last update and only use the creation date
+ if (shouldIgnoreUpdates) {
+ shouldBeStale = !IssuesProcessor._updatedSince(
+ issue.created_at,
+ daysBeforeStale
+ );
+ }
+ // Use the last update to check if we need to stale
+ else {
+ shouldBeStale = !IssuesProcessor._updatedSince(
+ issue.updated_at,
+ daysBeforeStale
+ );
+ }
+
+ if (shouldBeStale) {
+ if (shouldIgnoreUpdates) {
+ issueLogger.info(
+ `This $$type should be stale based on the creation date the ${getHumanizedDate(
+ new Date(issue.created_at)
+ )} (${LoggerService.cyan(issue.created_at)})`
+ );
+ } else {
+ issueLogger.info(
+ `This $$type should be stale based on the last update date the ${getHumanizedDate(
+ new Date(issue.updated_at)
+ )} (${LoggerService.cyan(issue.updated_at)})`
+ );
+ }
+
+ if (shouldMarkAsStale) {
+ issueLogger.info(
+ `This $$type should be marked as stale based on the option ${issueLogger.createOptionLink(
+ this._getDaysBeforeStaleUsedOptionName(issue)
+ )} (${LoggerService.cyan(daysBeforeStale)})`
+ );
+ await this._markStale(issue, staleMessage, staleLabel, skipMessage);
+ issue.isStale = true; // This issue is now considered stale
+ issue.markedStaleThisRun = true;
+ issueLogger.info(`This $$type is now stale`);
+ } else {
+ issueLogger.info(
+ `This $$type should not be marked as stale based on the option ${issueLogger.createOptionLink(
+ this._getDaysBeforeStaleUsedOptionName(issue)
+ )} (${LoggerService.cyan(daysBeforeStale)})`
+ );
+ }
+ } else {
+ if (shouldIgnoreUpdates) {
+ issueLogger.info(
+ `This $$type should not be stale based on the creation date the ${getHumanizedDate(
+ new Date(issue.created_at)
+ )} (${LoggerService.cyan(issue.created_at)})`
+ );
+ } else {
+ issueLogger.info(
+ `This $$type should not be stale based on the last update date the ${getHumanizedDate(
+ new Date(issue.updated_at)
+ )} (${LoggerService.cyan(issue.updated_at)})`
+ );
+ }
+ }
+ }
+
+ // Process the issue if it was marked stale
+ if (issue.isStale) {
+ issueLogger.info(`This $$type is already stale`);
+ await this._processStaleIssue(
+ issue,
+ staleLabel,
+ staleMessage,
+ labelsToAddWhenUnstale,
+ labelsToRemoveWhenUnstale,
+ labelsToRemoveWhenStale,
+ closeMessage,
+ closeLabel
+ );
+ }
+
+ IssuesProcessor._endIssueProcessing(issue);
+ }
+
+ // Grab comments for an issue since a given date
+ async listIssueComments(
+ issue: Readonly<Issue>,
+ sinceDate: Readonly<string>
+ ): Promise<IComment[]> {
+ // Find any comments since date on the given issue
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementFetchedItemsCommentsCount();
+ const comments = await this.client.rest.issues.listComments({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ since: sinceDate
+ });
+ return comments.data;
+ } catch (error) {
+ this._logger.error(`List issue comments error: ${error.message}`);
+ return Promise.resolve([]);
+ }
+ }
+
+ // grab issues from github in batches of 100
+ async getIssues(page: number): Promise<Issue[]> {
+ try {
+ this.operations.consumeOperation();
+ const issueResult = await this.client.rest.issues.listForRepo({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ state: 'open',
+ per_page: 100,
+ direction: this.options.ascending ? 'asc' : 'desc',
+ sort: getSortField(this.options.sortBy),
+ page
+ });
+ this.statistics?.incrementFetchedItemsCount(issueResult.data.length);
+
+ return issueResult.data.map(
+ (issue): Issue =>
+ new Issue(this.options, issue as Readonly<OctokitIssue>)
+ );
+ } catch (error) {
+ throw Error(`Getting issues was blocked by the error: ${error.message}`, {
+ cause: error
+ });
+ }
+ }
+
+ // returns the creation date of a given label on an issue (or nothing if no label existed)
+ ///see https://developer.github.com/v3/activity/events/
+ async getLabelCreationDate(
+ issue: Issue,
+ label: string
+ ): Promise<{creationDate?: string; events: IIssueEvent[]}> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(`Checking for label on this $$type`);
+
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementFetchedItemsEventsCount();
+ const options = this.client.rest.issues.listEvents.endpoint.merge({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ per_page: 100,
+ issue_number: issue.number
+ });
+
+ const events: IIssueEvent[] = await this.client.paginate(options);
+
+ const reversedEvents = events.reverse();
+
+ const staleLabeledEvent = reversedEvents.find(
+ event =>
+ event.event === 'labeled' &&
+ cleanLabel(event.label.name) === cleanLabel(label)
+ );
+
+ if (!staleLabeledEvent) {
+ // Must be old rather than labeled
+ return {creationDate: undefined, events};
+ }
+
+ return {creationDate: staleLabeledEvent.created_at, events};
+ }
+
+ protected async hasOnlyStaleLabelingEventsSince(
+ issue: Issue,
+ sinceDate: string,
+ staleLabel: string,
+ events: IIssueEvent[]
+ ): Promise<boolean> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `Checking if only stale label added events on $$type since: ${LoggerService.cyan(
+ sinceDate
+ )}`
+ );
+
+ if (!sinceDate) {
+ return false;
+ }
+
+ const sinceTimestamp = new Date(sinceDate).getTime();
+ if (Number.isNaN(sinceTimestamp)) {
+ return false;
+ }
+
+ const relevantEvents = events.filter(event => {
+ const eventTimestamp = new Date(event.created_at).getTime();
+ return !Number.isNaN(eventTimestamp) && eventTimestamp >= sinceTimestamp;
+ });
+
+ if (relevantEvents.length === 0) {
+ return false;
+ }
+
+ return relevantEvents.every(event => {
+ if (event.event !== 'labeled') {
+ return false;
+ }
+
+ return cleanLabel(event.label.name) === cleanLabel(staleLabel);
+ });
+ }
+
+ async getPullRequest(issue: Issue): Promise<IPullRequest | undefined | void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementFetchedPullRequestsCount();
+
+ const pullRequest = await this.client.rest.pulls.get({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ pull_number: issue.number
+ });
+
+ return pullRequest.data;
+ } catch (error) {
+ issueLogger.error(`Error when getting this $$type: ${error.message}`);
+ }
+ }
+
+ async getRateLimit(): Promise<IRateLimit | undefined> {
+ const logger: Logger = new Logger();
+
+ try {
+ const rateLimitResult = await this.client.rest.rateLimit.get();
+ return new RateLimit(rateLimitResult.data.rate);
+ } catch (error: unknown) {
+ const status = (error as {status?: number})?.status;
+ const message = (error as {message?: string})?.message ?? String(error);
+
+ if (status === 404 && message.includes('Rate limiting is not enabled')) {
+ logger.warning(
+ 'Rate limiting is not enabled on this instance. Proceeding without rate limit checks.'
+ );
+ return undefined;
+ }
+
+ logger.error(`Error when getting rateLimit: ${message}`);
+ }
+ }
+
+ // handle all of the stale issue logic when we find a stale issue
+ private async _processStaleIssue(
+ issue: Issue,
+ staleLabel: string,
+ staleMessage: string,
+ labelsToAddWhenUnstale: Readonly<string>[],
+ labelsToRemoveWhenUnstale: Readonly<string>[],
+ labelsToRemoveWhenStale: Readonly<string>[],
+ closeMessage?: string,
+ closeLabel?: string
+ ) {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+ const {creationDate, events} = await this.getLabelCreationDate(
+ issue,
+ staleLabel
+ );
+ const markedStaleOn: string = creationDate || issue.updated_at;
+ issueLogger.info(
+ `$$type marked stale on: ${LoggerService.cyan(markedStaleOn)}`
+ );
+
+ const issueHasCommentsSinceStale: boolean = await this._hasCommentsSince(
+ issue,
+ markedStaleOn,
+ staleMessage
+ );
+ issueLogger.info(
+ `$$type has been commented on: ${LoggerService.cyan(
+ issueHasCommentsSinceStale
+ )}`
+ );
+
+ const daysBeforeClose: number = issue.isPullRequest
+ ? this._getDaysBeforePrClose()
+ : this._getDaysBeforeIssueClose();
+
+ issueLogger.info(
+ `Days before $$type close: ${LoggerService.cyan(daysBeforeClose)}`
+ );
+
+ const shouldRemoveStaleWhenUpdated: boolean =
+ this._shouldRemoveStaleWhenUpdated(issue);
+
+ issueLogger.info(
+ `The option ${issueLogger.createOptionLink(
+ this._getRemoveStaleWhenUpdatedUsedOptionName(issue)
+ )} is: ${LoggerService.cyan(shouldRemoveStaleWhenUpdated)}`
+ );
+
+ if (shouldRemoveStaleWhenUpdated) {
+ issueLogger.info(`The stale label should not be removed`);
+ } else {
+ issueLogger.info(
+ `The stale label should be removed if all conditions met`
+ );
+ }
+
+ if (issue.markedStaleThisRun) {
+ issueLogger.info(`marked stale this run, so don't check for updates`);
+ await this._removeLabelsOnStatusTransition(
+ issue,
+ labelsToRemoveWhenStale,
+ Option.LabelsToRemoveWhenStale
+ );
+ }
+
+ // The issue.updated_at and markedStaleOn are not always exactly in sync (they can be off by a second or 2)
+ // isDateMoreRecentThan makes sure they are not the same date within a certain tolerance (15 seconds in this case)
+ let issueHasUpdateSinceStale = isDateMoreRecentThan(
+ new Date(issue.updated_at),
+ new Date(markedStaleOn),
+ 15
+ );
+
+ // Check if the only update was the stale label being added
+ if (
+ issueHasUpdateSinceStale &&
+ shouldRemoveStaleWhenUpdated &&
+ !issue.markedStaleThisRun
+ ) {
+ const onlyStaleLabelAdded = await this.hasOnlyStaleLabelingEventsSince(
+ issue,
+ markedStaleOn,
+ staleLabel,
+ events
+ );
+
+ if (onlyStaleLabelAdded) {
+ issueHasUpdateSinceStale = false;
+ issueLogger.info(
+ `Ignoring $$type update since only the stale label was added`
+ );
+ }
+ }
+
+ issueLogger.info(
+ `$$type has been updated since it was marked stale: ${LoggerService.cyan(
+ issueHasUpdateSinceStale
+ )}`
+ );
+
+ // Should we un-stale this issue?
+ if (
+ shouldRemoveStaleWhenUpdated &&
+ (issueHasUpdateSinceStale || issueHasCommentsSinceStale) &&
+ !issue.markedStaleThisRun
+ ) {
+ issueLogger.info(
+ `Remove the stale label since the $$type has been updated and the workflow should remove the stale label when updated`
+ );
+ await this._removeStaleLabel(issue, staleLabel);
+
+ // Are there labels to remove or add when an issue is no longer stale?
+ await this._removeLabelsOnStatusTransition(
+ issue,
+ labelsToRemoveWhenUnstale,
+ Option.LabelsToRemoveWhenUnstale
+ );
+ await this._addLabelsWhenUnstale(issue, labelsToAddWhenUnstale);
+
+ issueLogger.info(`Skipping the process since the $$type is now un-stale`);
+
+ return; // Nothing to do because it is no longer stale
+ }
+
+ // Now start closing logic
+ if (daysBeforeClose < 0) {
+ return; // Nothing to do because we aren't closing stale issues
+ }
+
+ const issueHasUpdateInCloseWindow: boolean = IssuesProcessor._updatedSince(
+ issue.updated_at,
+ daysBeforeClose
+ );
+ issueLogger.info(
+ `$$type has been updated in the last ${daysBeforeClose} days: ${LoggerService.cyan(
+ issueHasUpdateInCloseWindow
+ )}`
+ );
+
+ if (!issueHasCommentsSinceStale && !issueHasUpdateInCloseWindow) {
+ issueLogger.info(
+ `Closing $$type because it was last updated on: ${LoggerService.cyan(
+ issue.updated_at
+ )}`
+ );
+ await this._closeIssue(issue, closeMessage, closeLabel);
+
+ if (this.options.deleteBranch && issue.pull_request) {
+ issueLogger.info(
+ `Deleting the branch since the option ${issueLogger.createOptionLink(
+ Option.DeleteBranch
+ )} is enabled`
+ );
+ await this._deleteBranch(issue);
+ this.deletedBranchIssues.push(issue);
+ }
+ } else {
+ issueLogger.info(
+ `Stale $$type is not old enough to close yet (hasComments? ${issueHasCommentsSinceStale}, hasUpdate? ${issueHasUpdateInCloseWindow})`
+ );
+ }
+ }
+
+ // checks to see if a given issue is still stale (has had activity on it)
+ private async _hasCommentsSince(
+ issue: Issue,
+ sinceDate: string,
+ staleMessage: string
+ ): Promise<boolean> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `Checking for comments on $$type since: ${LoggerService.cyan(sinceDate)}`
+ );
+
+ if (!sinceDate) {
+ return true;
+ }
+
+ // find any comments since the date
+ const comments = await this.listIssueComments(issue, sinceDate);
+
+ const filteredComments = comments.filter(
+ comment =>
+ comment.user?.type === 'User' &&
+ comment.body?.toLowerCase() !== staleMessage.toLowerCase()
+ );
+
+ issueLogger.info(
+ `Comments that are not the stale comment or another bot: ${LoggerService.cyan(
+ filteredComments.length
+ )}`
+ );
+
+ // if there are any user comments returned
+ return filteredComments.length > 0;
+ }
+
+ // Mark an issue as stale with a comment and a label
+ private async _markStale(
+ issue: Issue,
+ staleMessage: string,
+ staleLabel: string,
+ skipMessage: boolean
+ ): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(`Marking this $$type as stale`);
+ this.staleIssues.push(issue);
+
+ // 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 (!skipMessage) {
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementAddedItemsComment(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ body: staleMessage
+ });
+ }
+ } catch (error) {
+ issueLogger.error(`Error when creating a comment: ${error.message}`);
+ }
+ }
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementAddedItemsLabel(issue);
+ this.statistics?.incrementStaleItemsCount(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.addLabels({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ labels: [staleLabel]
+ });
+ }
+ } catch (error) {
+ issueLogger.error(`Error when adding a label: ${error.message}`);
+ }
+ }
+
+ // Close an issue based on staleness
+ private async _closeIssue(
+ issue: Issue,
+ closeMessage?: string,
+ closeLabel?: string
+ ): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(`Closing $$type for being stale`);
+ this.closedIssues.push(issue);
+
+ if (closeMessage) {
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementAddedItemsComment(issue);
+ this.addedCloseCommentIssues.push(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ body: closeMessage
+ });
+ }
+ } catch (error) {
+ issueLogger.error(`Error when creating a comment: ${error.message}`);
+ }
+ }
+
+ if (closeLabel) {
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementAddedItemsLabel(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.addLabels({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ labels: [closeLabel]
+ });
+ }
+ } catch (error) {
+ issueLogger.error(`Error when adding a label: ${error.message}`);
+ }
+ }
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementClosedItemsCount(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.update({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ state: 'closed',
+ state_reason: (this.options.closeIssueReason || undefined) as
+ 'completed' | 'reopened' | 'not_planned' | null | undefined
+ });
+ }
+ } catch (error) {
+ issueLogger.error(`Error when updating this $$type: ${error.message}`);
+ }
+ }
+
+ // Delete the branch on closed pull request
+ private async _deleteBranch(issue: Issue): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(`Delete
+ branch from closed $
+ $type
+ -
+ ${issue.title}`);
+
+ const pullRequest: IPullRequest | undefined | void =
+ await this.getPullRequest(issue);
+
+ if (!pullRequest) {
+ issueLogger.info(
+ `Not deleting this branch as no pull request was found for this $$type`
+ );
+ return;
+ }
+
+ const branch = pullRequest.head.ref;
+
+ if (
+ pullRequest.head.repo === null ||
+ pullRequest.head.repo.full_name ===
+ `${context.repo.owner}/${context.repo.repo}`
+ ) {
+ issueLogger.info(
+ `Deleting the branch "${LoggerService.cyan(branch)}" from closed $$type`
+ );
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementDeletedBranchesCount();
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.git.deleteRef({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ ref: `heads/${branch}`
+ });
+ }
+ } catch (error) {
+ issueLogger.error(
+ `Error when deleting the branch "${LoggerService.cyan(
+ branch
+ )}" from $$type: ${error.message}`
+ );
+ }
+ } else {
+ issueLogger.warning(
+ `Deleting the branch "${LoggerService.cyan(
+ branch
+ )}" has skipped because it belongs to other repo ${
+ pullRequest.head.repo.full_name
+ }`
+ );
+ }
+ }
+
+ // Remove a label from an issue or a pull request
+ private async _removeLabel(
+ issue: Issue,
+ label: string,
+ isSubStep: Readonly<boolean> = false
+ ): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `${
+ isSubStep ? LoggerService.white('├── ') : ''
+ }Removing the label "${LoggerService.cyan(label)}" from this $$type...`
+ );
+ this.removedLabelIssues.push(issue);
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementDeletedItemsLabelsCount(issue);
+
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.removeLabel({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ name: label
+ });
+ }
+
+ issueLogger.info(
+ `${
+ isSubStep ? LoggerService.white('└── ') : ''
+ }The label "${LoggerService.cyan(label)}" was removed`
+ );
+ } catch (error) {
+ issueLogger.error(
+ `${
+ isSubStep ? LoggerService.white('└── ') : ''
+ }Error when removing the label: "${LoggerService.cyan(error.message)}"`
+ );
+ }
+ }
+
+ private _getDaysBeforeIssueStale(): number {
+ return isNaN(this.options.daysBeforeIssueStale)
+ ? this.options.daysBeforeStale
+ : this.options.daysBeforeIssueStale;
+ }
+
+ private _getDaysBeforePrStale(): number {
+ return isNaN(this.options.daysBeforePrStale)
+ ? this.options.daysBeforeStale
+ : this.options.daysBeforePrStale;
+ }
+
+ private _getDaysBeforeIssueClose(): number {
+ return isNaN(this.options.daysBeforeIssueClose)
+ ? this.options.daysBeforeClose
+ : this.options.daysBeforeIssueClose;
+ }
+
+ private _getDaysBeforePrClose(): number {
+ return isNaN(this.options.daysBeforePrClose)
+ ? this.options.daysBeforeClose
+ : this.options.daysBeforePrClose;
+ }
+
+ private _getOnlyLabels(issue: Issue): string {
+ if (issue.isPullRequest) {
+ if (this.options.onlyPrLabels !== '') {
+ return this.options.onlyPrLabels;
+ }
+ } else {
+ if (this.options.onlyIssueLabels !== '') {
+ return this.options.onlyIssueLabels;
+ }
+ }
+
+ return this.options.onlyLabels;
+ }
+
+ private _isIncludeOnlyAssigned(issue: Issue): boolean {
+ return this.options.includeOnlyAssigned && !issue.hasAssignees;
+ }
+
+ private _getAnyOfLabels(issue: Issue): string {
+ if (issue.isPullRequest) {
+ if (this.options.anyOfPrLabels !== '') {
+ return this.options.anyOfPrLabels;
+ }
+ } else {
+ if (this.options.anyOfIssueLabels !== '') {
+ return this.options.anyOfIssueLabels;
+ }
+ }
+
+ return this.options.anyOfLabels;
+ }
+
+ private _shouldRemoveStaleWhenUpdated(issue: Issue): boolean {
+ if (issue.isPullRequest) {
+ if (isBoolean(this.options.removePrStaleWhenUpdated)) {
+ return this.options.removePrStaleWhenUpdated;
+ }
+
+ return this.options.removeStaleWhenUpdated;
+ }
+
+ if (isBoolean(this.options.removeIssueStaleWhenUpdated)) {
+ return this.options.removeIssueStaleWhenUpdated;
+ }
+
+ return this.options.removeStaleWhenUpdated;
+ }
+
+ private async _removeLabelsOnStatusTransition(
+ issue: Issue,
+ removeLabels: Readonly<string>[],
+ staleStatus: Option
+ ): Promise<void> {
+ if (!removeLabels.length) {
+ return;
+ }
+
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `Removing all the labels specified via the ${this._logger.createOptionLink(
+ staleStatus
+ )} option.`
+ );
+
+ for (const label of removeLabels.values()) {
+ await this._removeLabel(issue, label);
+ }
+ }
+
+ private async _addLabelsWhenUnstale(
+ issue: Issue,
+ labelsToAdd: Readonly<string>[]
+ ): Promise<void> {
+ if (!labelsToAdd.length) {
+ return;
+ }
+
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `Adding all the labels specified via the ${this._logger.createOptionLink(
+ Option.LabelsToAddWhenUnstale
+ )} option.`
+ );
+
+ this.addedLabelIssues.push(issue);
+
+ try {
+ this._consumeIssueOperation(issue);
+ this.statistics?.incrementAddedItemsLabel(issue);
+ if (!this.options.debugOnly) {
+ await this.client.rest.issues.addLabels({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issue.number,
+ labels: labelsToAdd
+ });
+ }
+ } catch (error) {
+ this._logger.error(
+ `Error when adding labels after updated from stale: ${error.message}`
+ );
+ }
+ }
+
+ private async _removeStaleLabel(
+ issue: Issue,
+ staleLabel: Readonly<string>
+ ): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `The $$type is no longer stale. Removing the stale label...`
+ );
+
+ await this._removeLabel(issue, staleLabel);
+ this.statistics?.incrementUndoStaleItemsCount(issue);
+ }
+
+ private async _removeCloseLabel(
+ issue: Issue,
+ closeLabel: Readonly<string | undefined>
+ ): Promise<void> {
+ const issueLogger: IssueLogger = new IssueLogger(issue);
+
+ issueLogger.info(
+ `The $$type is not closed nor locked. Trying to remove the close label...`
+ );
+
+ if (!closeLabel) {
+ issueLogger.info(
+ LoggerService.white('├──'),
+ `The ${issueLogger.createOptionLink(
+ IssuesProcessor._getCloseLabelUsedOptionName(issue)
+ )} option was not set`
+ );
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `Skipping the removal of the close label`
+ );
+
+ return Promise.resolve();
+ }
+
+ if (isLabeled(issue, closeLabel)) {
+ issueLogger.info(
+ LoggerService.white('├──'),
+ `The $$type has a close label "${LoggerService.cyan(
+ closeLabel
+ )}". Removing the close label...`
+ );
+
+ await this._removeLabel(issue, closeLabel, true);
+ this.statistics?.incrementDeletedCloseItemsLabelsCount(issue);
+ } else {
+ issueLogger.info(
+ LoggerService.white('└──'),
+ `There is no close label on this $$type. Skipping`
+ );
+
+ return Promise.resolve();
+ }
+ }
+
+ private _consumeIssueOperation(issue: Readonly<Issue>): void {
+ this.operations.consumeOperation();
+ issue.operations.consumeOperation();
+ }
+
+ private _getDaysBeforeStaleUsedOptionName(
+ issue: Readonly<Issue>
+ ):
+ | Option.DaysBeforeStale
+ | Option.DaysBeforeIssueStale
+ | Option.DaysBeforePrStale {
+ return issue.isPullRequest
+ ? this._getDaysBeforePrStaleUsedOptionName()
+ : this._getDaysBeforeIssueStaleUsedOptionName();
+ }
+
+ private _getDaysBeforeIssueStaleUsedOptionName():
+ Option.DaysBeforeStale | Option.DaysBeforeIssueStale {
+ return isNaN(this.options.daysBeforeIssueStale)
+ ? Option.DaysBeforeStale
+ : Option.DaysBeforeIssueStale;
+ }
+
+ private _getDaysBeforePrStaleUsedOptionName():
+ Option.DaysBeforeStale | Option.DaysBeforePrStale {
+ return isNaN(this.options.daysBeforePrStale)
+ ? Option.DaysBeforeStale
+ : Option.DaysBeforePrStale;
+ }
+
+ private _getRemoveStaleWhenUpdatedUsedOptionName(
+ issue: Readonly<Issue>
+ ):
+ | Option.RemovePrStaleWhenUpdated
+ | Option.RemoveStaleWhenUpdated
+ | Option.RemoveIssueStaleWhenUpdated {
+ if (issue.isPullRequest) {
+ if (isBoolean(this.options.removePrStaleWhenUpdated)) {
+ return Option.RemovePrStaleWhenUpdated;
+ }
+
+ return Option.RemoveStaleWhenUpdated;
+ }
+
+ if (isBoolean(this.options.removeIssueStaleWhenUpdated)) {
+ return Option.RemoveIssueStaleWhenUpdated;
+ }
+
+ return Option.RemoveStaleWhenUpdated;
+ }
+}
diff --git a/test/fixtures/actions-stale-v11/manifest.json b/test/fixtures/actions-stale-v11/manifest.json
new file mode 100644
index 00000000..b1c87594
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/manifest.json
@@ -0,0 +1,83 @@
+{
+ "version": "v11.0.0",
+ "sources": [
+ {
+ "file": "issues-processor-v11.ts.txt",
+ "source": "issues-processor-v11.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/issues-processor.ts",
+ "sha256": "9545917e652b88e06a64c8c9c10645b25cba5659a91901ef5981a2a227c920d1"
+ },
+ {
+ "file": "assignees.ts.txt",
+ "source": "src/classes/assignees.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/assignees.ts",
+ "sha256": "4622503d2c5cecdf91c3e22eb292c02d1cf903f61dbf31ef85246926f6a591ef"
+ },
+ {
+ "file": "exempt-draft-pull-request.ts.txt",
+ "source": "src/classes/exempt-draft-pull-request.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/exempt-draft-pull-request.ts",
+ "sha256": "1984f7cf2c914c4149d1d8264611cf4d30bce93d101e28f83e0feade17c4ce01"
+ },
+ {
+ "file": "ignore-updates.ts.txt",
+ "source": "src/classes/ignore-updates.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/ignore-updates.ts",
+ "sha256": "6783c1a9c43250fa8d81f0a2745d32b55acd6e1590cb59de42364cd9a04c4bde"
+ },
+ {
+ "file": "issue.ts.txt",
+ "source": "src/classes/issue.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/issue.ts",
+ "sha256": "8a4a6d49eafe1f3892f45fe706b317466d0657d38c3a39258a64d56e3068a8d7"
+ },
+ {
+ "file": "milestones.ts.txt",
+ "source": "src/classes/milestones.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/classes/milestones.ts",
+ "sha256": "df67de489cc64f5d7c4a5a13867c76fb8d17f066c0ee162eb398be3f4e838ea0"
+ },
+ {
+ "file": "clean-label.ts.txt",
+ "source": "src/functions/clean-label.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/clean-label.ts",
+ "sha256": "df072e23023427f2c57e1f97268fb1c95b8946da3943d1a05c12ac6d318eedae"
+ },
+ {
+ "file": "is-date-more-recent-than.ts.txt",
+ "source": "src/functions/dates/is-date-more-recent-than.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/dates/is-date-more-recent-than.ts",
+ "sha256": "f4bbd5da44a0ecf45795729181436c17bc16ded2d991706397f892d7c05d1070"
+ },
+ {
+ "file": "is-boolean.ts.txt",
+ "source": "src/functions/is-boolean.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/is-boolean.ts",
+ "sha256": "0503dbd40107520d932383ae11571cdfbe89318bde4bb29d0df564df6d4af212"
+ },
+ {
+ "file": "is-labeled.ts.txt",
+ "source": "src/functions/is-labeled.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/is-labeled.ts",
+ "sha256": "e37c4efadbf5e1069ad031e192492a865900bc62979b86ad1ec7434ab6c69376"
+ },
+ {
+ "file": "is-pull-request.ts.txt",
+ "source": "src/functions/is-pull-request.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/is-pull-request.ts",
+ "sha256": "e8a3668a5d976e2834cb123d5d51babd7a3b2c17088feb4d9cf7c276aaaa9f38"
+ },
+ {
+ "file": "should-mark-when-stale.ts.txt",
+ "source": "src/functions/should-mark-when-stale.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/should-mark-when-stale.ts",
+ "sha256": "b838994ce92077230fbc0afd61487e3544ef7bd58c0fe543a4bffbbd7c513f00"
+ },
+ {
+ "file": "words-to-list.ts.txt",
+ "source": "src/functions/words-to-list.ts",
+ "url": "https://raw.githubusercontent.com/actions/stale/v11.0.0/src/functions/words-to-list.ts",
+ "sha256": "478393dccda38190f042c2e2230e0333299d57699bc0e83b00614147d270aa82"
+ }
+ ]
+}
diff --git a/test/fixtures/actions-stale-v11/milestones.ts.txt b/test/fixtures/actions-stale-v11/milestones.ts.txt
new file mode 100644
index 00000000..53ae1bf6
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/milestones.ts.txt
@@ -0,0 +1,297 @@
+import deburr from 'lodash.deburr';
+import {Option} from '../enums/option.js';
+import {wordsToList} from '../functions/words-to-list.js';
+import {IIssuesProcessorOptions} from '../interfaces/issues-processor-options.js';
+import {Issue} from './issue.js';
+import {IssueLogger} from './loggers/issue-logger.js';
+import {LoggerService} from '../services/logger.service.js';
+
+type CleanMilestone = string;
+
+export class Milestones {
+ private static _cleanMilestone(milestone: Readonly<string>): CleanMilestone {
+ return deburr(milestone.toLowerCase());
+ }
+
+ private readonly _options: IIssuesProcessorOptions;
+ private readonly _issue: Issue;
+ private readonly _issueLogger: IssueLogger;
+
+ constructor(options: Readonly<IIssuesProcessorOptions>, issue: Issue) {
+ this._options = options;
+ this._issue = issue;
+ this._issueLogger = new IssueLogger(issue);
+ }
+
+ shouldExemptMilestones(): boolean {
+ if (!this._issue.milestone) {
+ this._issueLogger.info('This $$type has no milestone');
+ this._logSkip();
+
+ return false;
+ }
+
+ if (this._shouldExemptAllMilestones()) {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skipping this $$type because it has a milestone'
+ );
+
+ return true;
+ }
+
+ const exemptMilestones: string[] = this._getExemptMilestones();
+
+ if (exemptMilestones.length === 0) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `No milestone option was specified to skip the stale process for this $$type`
+ );
+ this._logSkip();
+
+ return false;
+ }
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `Found ${LoggerService.cyan(exemptMilestones.length)} milestone${
+ exemptMilestones.length > 1 ? 's' : ''
+ } that can exempt stale on this $$type`
+ );
+
+ const hasExemptMilestone: boolean = exemptMilestones.some(
+ (exemptMilestone: Readonly<string>): boolean =>
+ this._hasMilestone(exemptMilestone)
+ );
+
+ if (!hasExemptMilestone) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ 'No milestone on this $$type can exempt the stale process'
+ );
+ this._logSkip();
+ } else {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skipping this $$type because it has an exempt milestone'
+ );
+ }
+
+ return hasExemptMilestone;
+ }
+
+ private _getExemptMilestones(): string[] {
+ return this._issue.isPullRequest
+ ? this._getExemptPullRequestMilestones()
+ : this._getExemptIssueMilestones();
+ }
+
+ private _getExemptIssueMilestones(): string[] {
+ if (this._options.exemptIssueMilestones === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptIssueMilestones
+ )} is disabled. No specific milestone can skip the stale process for this $$type`
+ );
+
+ if (this._options.exemptMilestones === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptMilestones
+ )} is disabled. No specific milestone can skip the stale process for this $$type`
+ );
+
+ return [];
+ }
+
+ const exemptMilestones: string[] = wordsToList(
+ this._options.exemptMilestones
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptMilestones
+ )} is set. ${LoggerService.cyan(exemptMilestones.length)} milestone${
+ exemptMilestones.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptMilestones;
+ }
+
+ const exemptMilestones: string[] = wordsToList(
+ this._options.exemptIssueMilestones
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptIssueMilestones
+ )} is set. ${LoggerService.cyan(exemptMilestones.length)} milestone${
+ exemptMilestones.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptMilestones;
+ }
+
+ private _getExemptPullRequestMilestones(): string[] {
+ if (this._options.exemptPrMilestones === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptPrMilestones
+ )} is disabled. No specific milestone can skip the stale process for this $$type`
+ );
+
+ if (this._options.exemptMilestones === '') {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptMilestones
+ )} is disabled. No specific milestone can skip the stale process for this $$type`
+ );
+
+ return [];
+ }
+
+ const exemptMilestones: string[] = wordsToList(
+ this._options.exemptMilestones
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptMilestones
+ )} is set. ${LoggerService.cyan(exemptMilestones.length)} milestone${
+ exemptMilestones.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptMilestones;
+ }
+
+ const exemptMilestones: string[] = wordsToList(
+ this._options.exemptPrMilestones
+ );
+
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptPrMilestones
+ )} is set. ${LoggerService.cyan(exemptMilestones.length)} milestone${
+ exemptMilestones.length === 1 ? '' : 's'
+ } can skip the stale process for this $$type`
+ );
+
+ return exemptMilestones;
+ }
+
+ private _hasMilestone(milestone: Readonly<string>): boolean {
+ if (!this._issue.milestone) {
+ return false;
+ }
+
+ const cleanMilestone: CleanMilestone =
+ Milestones._cleanMilestone(milestone);
+
+ const isSameMilestone: boolean =
+ cleanMilestone ===
+ Milestones._cleanMilestone(this._issue.milestone.title);
+
+ if (isSameMilestone) {
+ this._issueLogger.info(
+ LoggerService.white('├──'),
+ `The milestone "${LoggerService.cyan(
+ milestone
+ )}" is set on this $$type and is an exempt milestone`
+ );
+ }
+
+ return isSameMilestone;
+ }
+
+ private _shouldExemptAllMilestones(): boolean {
+ if (this._issue.milestone) {
+ return this._issue.isPullRequest
+ ? this._shouldExemptAllPullRequestMilestones()
+ : this._shouldExemptAllIssueMilestones();
+ }
+
+ return false;
+ }
+
+ private _shouldExemptAllIssueMilestones(): boolean {
+ if (this._options.exemptAllIssueMilestones === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllIssueMilestones
+ )} is enabled. Any milestone on this $$type will skip the stale process`
+ );
+
+ return true;
+ } else if (this._options.exemptAllIssueMilestones === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllIssueMilestones
+ )} is disabled. Only some specific milestones on this $$type will skip the stale process`
+ );
+
+ return false;
+ }
+
+ this._logExemptAllMilestonesOption();
+
+ return this._options.exemptAllMilestones;
+ }
+
+ private _shouldExemptAllPullRequestMilestones(): boolean {
+ if (this._options.exemptAllPrMilestones === true) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllPrMilestones
+ )} is enabled. Any milestone on this $$type will skip the stale process`
+ );
+
+ return true;
+ } else if (this._options.exemptAllPrMilestones === false) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllPrMilestones
+ )} is disabled. Only some specific milestones on this $$type will skip the stale process`
+ );
+
+ return false;
+ }
+
+ this._logExemptAllMilestonesOption();
+
+ return this._options.exemptAllMilestones;
+ }
+
+ private _logExemptAllMilestonesOption(): void {
+ if (this._options.exemptAllMilestones) {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllMilestones
+ )} is enabled. Any milestone on this $$type will skip the stale process`
+ );
+ } else {
+ this._issueLogger.info(
+ `The option ${this._issueLogger.createOptionLink(
+ Option.ExemptAllMilestones
+ )} is disabled. Only some specific milestones on this $$type will skip the stale process`
+ );
+ }
+ }
+
+ private _logSkip(): void {
+ this._issueLogger.info(
+ LoggerService.white('└──'),
+ 'Skip the milestones checks'
+ );
+ }
+}
diff --git a/test/fixtures/actions-stale-v11/should-mark-when-stale.ts.txt b/test/fixtures/actions-stale-v11/should-mark-when-stale.ts.txt
new file mode 100644
index 00000000..c8f16936
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/should-mark-when-stale.ts.txt
@@ -0,0 +1,5 @@
+export function shouldMarkWhenStale(
+ daysBeforeStale: Readonly<number>
+): boolean {
+ return daysBeforeStale >= 0;
+}
diff --git a/test/fixtures/actions-stale-v11/words-to-list.ts.txt b/test/fixtures/actions-stale-v11/words-to-list.ts.txt
new file mode 100644
index 00000000..8eb3701d
--- /dev/null
+++ b/test/fixtures/actions-stale-v11/words-to-list.ts.txt
@@ -0,0 +1,23 @@
+/**
+ * @description
+ * Transform a string of comma separated words
+ * to an array of words
+ *
+ * @example
+ * wordsToList('label') => ['label']
+ * wordsToList('label,label') => ['label', 'label']
+ * wordsToList('kebab-label') => ['kebab-label']
+ * wordsToList('kebab%20label') => ['kebab%20label']
+ * wordsToList('label with words') => ['label with words']
+ *
+ * @param {Readonly<string>} words A string of comma separated words
+ *
+ * @return {string[]} A list of words
+ */
+export function wordsToList(words: Readonly<string>): string[] {
+ if (!words.length) {
+ return [];
+ }
+
+ return words.split(',').map((word: Readonly<string>): string => word.trim());
+}