Skip to content

Commit

Permalink
fix(scripts): do not run notifications on forks (#3295)
Browse files Browse the repository at this point in the history
  • Loading branch information
shortcuts authored Jul 1, 2024
1 parent 0052b1f commit cd6bb82
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 339 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,24 @@ concurrency:
# ACTIONS_RUNNER_DEBUG: true

jobs:
notification:
runs-on: ubuntu-22.04
timeout-minutes: 1
if: ${{ !github.event.pull_request.head.repo.fork && github.event.number }}
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4

- uses: marocchino/sticky-pull-request-comment@v2
with:
message: |
### 🔨 The generated code will be pushed at the end of the CI.
Action triggered by commit `${{ github.sha}}`.
_Please do not push any generated code to this pull request._
setup:
runs-on: ubuntu-22.04
timeout-minutes: 10
Expand Down Expand Up @@ -369,6 +387,8 @@ jobs:
(needs.swift_cts_macos.result == 'success' || needs.swift_cts_macos.result == 'skipped') &&
!contains(needs.*.result, 'cancelled') &&
!contains(needs.*.result, 'failure')
permissions:
pull-requests: write
outputs:
success: ${{ steps.setoutput.outputs.success }}
steps:
Expand All @@ -377,6 +397,7 @@ jobs:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
token: ${{ secrets.ALGOLIA_BOT_TOKEN }}
repository: ${{ github.event.pull_request.head.repo.full_name }}

- name: Download all artifacts
uses: ./scripts/ci/actions/restore-artifacts
Expand Down Expand Up @@ -419,6 +440,17 @@ jobs:
GITHUB_TOKEN: ${{ secrets.ALGOLIA_BOT_TOKEN }}
PR_NUMBER: ${{ github.event.number }}

- name: update generation commend
uses: marocchino/sticky-pull-request-comment@v2
with:
message: |
### ✔️ Code generated!
| Name | Link |
|---------------------------------|------------------------|
| 🔨 Triggered by | [`${{ github.sha }}`](${{ github.pull_request.html_url }}/commits/${{ github.sha }}) |
| 🌲 Generated branch | [`generated/${{ github.head_ref }}`](${{ github.pull_request.base.repo.html_url }}/tree/generated/${{ github.head_ref }}) |
- name: Spread generation to each repository
id: spreadGeneration
if: github.ref == 'refs/heads/main'
Expand Down
16 changes: 16 additions & 0 deletions .github/workflows/cleanup.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: Cleanup generated branch

on:
pull_request:
types: closed

jobs:
cleanup:
runs-on: ubuntu-22.04
timeout-minutes: 10
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4

- run: git push -d origin generated/${{ github.head_ref }} || true
52 changes: 0 additions & 52 deletions .github/workflows/codegen.yml

This file was deleted.

122 changes: 7 additions & 115 deletions scripts/ci/codegen/__tests__/codegen.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { cleanGeneratedBranch } from '../cleanGeneratedBranch.js';
import { describe, expect, it, vi } from "vitest";
import { pushGeneratedCode } from '../pushGeneratedCode.js';
import { upsertGenerationComment, getCommentBody } from '../upsertGenerationComment.js';
import commentText from '../text.js';

vi.mock('../../../common.js', async () => {
const mod = await vi.importActual<typeof import('../../../common.js')>('../../../common.js')
Expand All @@ -12,116 +9,11 @@ vi.mock('../../../common.js', async () => {
}
});

describe('codegen', () => {

describe('cleanGeneratedBranch', () => {
it('throws without parameters', async () => {
await expect(
// @ts-expect-error a parameter is required
cleanGeneratedBranch()
).rejects.toThrow(
'The base branch should be passed as a cli parameter of the `cleanGeneratedBranch` script.'
);
});
});

describe('pushGeneratedCode', () => {
it('throws without GITHUB_TOKEN environment variable', async () => {
process.env.GITHUB_TOKEN = '';
await expect(pushGeneratedCode()).rejects.toThrow(
'Environment variable `GITHUB_TOKEN` does not exist.'
);
});
});

describe('upsertGenerationComment', () => {
beforeAll(() => {
process.env.GITHUB_TOKEN = 'mocked';
});

it('throws without parameter', async () => {
await expect(
// @ts-expect-error a parameter is required
upsertGenerationComment()
).rejects.toThrow(
"'upsertGenerationComment' requires a 'trigger' parameter (notification | codegen | noGen | cleanup)."
);
});

it('throws without PR_NUMBER environment variable', async () => {
await expect(upsertGenerationComment('codegen')).rejects.toThrow(
'`upsertGenerationComment` requires a `PR_NUMBER` environment variable.'
);
});
});

describe('getCommentBody', () => {
describe('setup', () => {
it('returns the right comment for a `notification` trigger', async () => {
expect(await getCommentBody('notification')).toMatchInlineSnapshot(`
"### 🔨 The codegen job will run at the end of the CI.
_Make sure your last commit does not contain generated code, it will be automatically pushed by our CI._"
`);
});

it('returns the right comment for a `noGen` trigger', async () => {
expect(await getCommentBody('noGen')).toMatchInlineSnapshot(`
"### ✗ No code generated.
_If you believe this is an issue on our side, please [open an issue](https://github.com/algolia/api-clients-automation/issues/new?template=Bug_report.md)._"
`);
});
});

describe('cleanup', () => {
afterEach(() => {
vi.clearAllMocks();
});

it('returns the right comment for a `cleanup` trigger', async () => {
vi.spyOn(await import('../../../common.js'), 'run').mockResolvedValue('mocked');

expect(await getCommentBody('cleanup')).toMatchInlineSnapshot(`
"### ✗ The generated branch has been deleted.
If the PR has been merged, you can check the generated code on the [\`main\` branch](https://github.com/algolia/api-clients-automation/tree/main).
You can still access the code generated on \`mocked\` via [this commit](https://github.com/algolia/api-clients-automation/commit/mocked)."
`);
});

it('fallbacks to the env variable HEAD_BRANCH if found when we are on `main`', async () => {
process.env.HEAD_BRANCH = 'myFakeBranch';
vi.spyOn(await import('../../../common.js'), 'run').mockResolvedValue('main');

expect(await getCommentBody('cleanup')).toMatchInlineSnapshot(`
"### ✗ The generated branch has been deleted.
If the PR has been merged, you can check the generated code on the [\`main\` branch](https://github.com/algolia/api-clients-automation/tree/main).
You can still access the code generated on \`generated/myFakeBranch\` via [this commit](https://github.com/algolia/api-clients-automation/commit/main)."
`);
});
});

describe('text', () => {
it('creates a comment body for the parameters', () => {
expect(
commentText.codegen.body(
'theGeneratedCommit',
'myBranch',
'myCommit',
42
)
).toMatchInlineSnapshot(`
"
| Name | Link |
|---------------------------------|------------------------|
| 🔨 Triggered by | [\`myCommit\`](https://github.com/algolia/api-clients-automation/pull/42/commits/myCommit) |
| 🔍 Generated code | [\`theGeneratedCommit\`](https://github.com/algolia/api-clients-automation/commit/theGeneratedCommit) |
| 🌲 Generated branch | [\`myBranch\`](https://github.com/algolia/api-clients-automation/tree/myBranch) |
"
`);
});
});
describe('pushGeneratedCode', () => {
it('throws without GITHUB_TOKEN environment variable', async () => {
process.env.GITHUB_TOKEN = '';
await expect(pushGeneratedCode()).rejects.toThrow(
'Environment variable `GITHUB_TOKEN` does not exist.'
);
});
});
32 changes: 0 additions & 32 deletions scripts/ci/codegen/cleanGeneratedBranch.ts

This file was deleted.

12 changes: 1 addition & 11 deletions scripts/ci/codegen/pushGeneratedCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { getNbGitDiff } from '../utils.js';

import text, { commitStartPrepareRelease } from './text.js';

const PR_NUMBER = parseInt(process.env.PR_NUMBER || '0', 10);

async function isUpToDate(baseBranch: string): Promise<boolean> {
await run('git fetch origin');
return (await run(`git pull origin ${baseBranch}`)).includes('Already up to date.');
Expand Down Expand Up @@ -34,10 +32,6 @@ export async function pushGeneratedCode(): Promise<void> {
if (nbDiff === 0) {
console.log(`No generated code changes found for '${baseBranch}'.`);

if (PR_NUMBER) {
await run(`yarn workspace scripts upsertGenerationComment noGen`);
}

return;
}

Expand All @@ -47,7 +41,7 @@ export async function pushGeneratedCode(): Promise<void> {
const branchToPush = isMainBranch ? baseBranch : `generated/${baseBranch}`;

if (!isMainBranch) {
await run(`yarn workspace scripts cleanGeneratedBranch ${baseBranch}`);
await run(`git push -d generated/${baseBranch} || true`);

console.log(`Creating branch for generated code: '${branchToPush}'`);
await run(`git checkout -b ${branchToPush}`);
Expand Down Expand Up @@ -82,10 +76,6 @@ Co-authored-by: %an <%ae>
await run('git add .');
await run(`git commit -m "${message}"`);
await run(`git push origin ${branchToPush}`);

if (PR_NUMBER) {
await run(`yarn workspace scripts upsertGenerationComment codegen`);
}
}

if (import.meta.url.endsWith(process.argv[1])) {
Expand Down
35 changes: 1 addition & 34 deletions scripts/ci/codegen/text.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MAIN_BRANCH, REPO_URL, TODAY } from '../../common.js';
import { TODAY } from '../../common.js';

export const commitStartPrepareRelease = 'chore: prepare release';
export const commitStartRelease = 'chore: release';
Expand All @@ -7,37 +7,4 @@ export default {
commitStartMessage: 'chore: generated code for commit',
commitPrepareReleaseMessage: `${commitStartPrepareRelease} ${TODAY}`,
commitReleaseMessage: `${commitStartRelease} ${TODAY}`,
notification: {
header: '### 🔨 The codegen job will run at the end of the CI.',
body: (): string =>
'_Make sure your last commit does not contain generated code, it will be automatically pushed by our CI._',
},
noGen: {
header: '### ✗ No code generated.',
body: (): string =>
`_If you believe this is an issue on our side, please [open an issue](${REPO_URL}/issues/new?template=Bug_report.md)._`,
},
cleanup: {
header: '### ✗ The generated branch has been deleted.',
body: (
generatedCommit: string,
branch: string,
): string => `If the PR has been merged, you can check the generated code on the [\`${MAIN_BRANCH}\` branch](${REPO_URL}/tree/${MAIN_BRANCH}).
You can still access the code generated on \`${branch}\` via [this commit](${REPO_URL}/commit/${generatedCommit}).`,
},
codegen: {
header: '### ✔️ Code generated!',
body: (
generatedCommit: string,
branch: string,
commit: string,
eventNumber: number,
): string => `
| Name | Link |
|---------------------------------|------------------------|
| 🔨 Triggered by | [\`${commit}\`](${REPO_URL}/pull/${eventNumber}/commits/${commit}) |
| 🔍 Generated code | [\`${generatedCommit}\`](${REPO_URL}/commit/${generatedCommit}) |
| 🌲 Generated branch | [\`${branch}\`](${REPO_URL}/tree/${branch}) |
`,
},
};
Loading

0 comments on commit cd6bb82

Please sign in to comment.