diff --git a/tools/@aws-cdk/prlint/lint.ts b/tools/@aws-cdk/prlint/lint.ts index 7f367705eb692..0f16e78ed746a 100644 --- a/tools/@aws-cdk/prlint/lint.ts +++ b/tools/@aws-cdk/prlint/lint.ts @@ -11,6 +11,8 @@ export type GitHubPr = export const CODE_BUILD_CONTEXT = 'AWS CodeBuild us-east-1 (AutoBuildv2Project1C6BFA3F-wQm2hXv2jqQv)'; +const PR_FROM_MAIN_ERROR = 'Pull requests from `main` branch of a fork cannot be accepted. Please reopen this contribution from another branch on your fork. For more information, see https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md#step-4-pull-request.'; + /** * Types of exemption labels in aws-cdk project. */ @@ -268,6 +270,16 @@ export class PullRequestLinter { body, }); + // Commenting this code to first test that linter rule works + // since this can lead to other PRs closing if not setup correctly + // // Closing the PR if it is opened from main branch of author's fork + // if (failureMessages.includes(PR_FROM_MAIN_ERROR)) { + // await this.client.pulls.update({ + // ...this.prParams, + // state: 'closed', + // }); + // } + throw new LinterError(body); } @@ -508,6 +520,9 @@ export class PullRequestLinter { validationCollector.validateRuleSet({ testRuleSet: [{ test: validateTitleScope }], }); + validationCollector.validateRuleSet({ + testRuleSet: [{ test: validateBranch }], + }) validationCollector.validateRuleSet({ exemption: shouldExemptBreakingChange, @@ -687,6 +702,22 @@ function validateTitleScope(pr: GitHubPr): TestResult { return result; } +/** + * Check that the PR is not opened from main branch of author's fork + * + * @param pr github pr + * @returns test result + */ +function validateBranch(pr: GitHubPr): TestResult { + const result = new TestResult(); + + if (pr.head && pr.head.ref) { + result.assessFailure(pr.head.ref === 'main', PR_FROM_MAIN_ERROR); + } + + return result; +} + function assertStability(pr: GitHubPr, _files: GitHubFile[]): TestResult { const title = pr.title; const body = pr.body; diff --git a/tools/@aws-cdk/prlint/test/lint.test.ts b/tools/@aws-cdk/prlint/test/lint.test.ts index 50bd81b2c7f2b..42185b50f7368 100644 --- a/tools/@aws-cdk/prlint/test/lint.test.ts +++ b/tools/@aws-cdk/prlint/test/lint.test.ts @@ -93,6 +93,24 @@ describe('breaking changes format', () => { }); }); +test('disallow PRs from main branch of fork', async () => { + const issue: Subset = { + number: 1, + title: 'chore: some title', + body: 'making a pr from main of my fork', + labels: [{ name: 'pr-linter/exempt-test' }, { name: 'pr-linter/exempt-readme' }], + user: { + login: 'author', + }, + head: { + label: 'author:main', + ref: 'main' + } + }; + const prLinter = configureMock(issue, undefined); + await expect(prLinter.validatePullRequestTarget(SHA)).rejects.toThrow(/Pull requests from `main` branch of a fork cannot be accepted. Please reopen this contribution from another branch on your fork./); +}); + describe('commit message format', () => { test('valid scope', async () => { const issue = {