From acd034f9678dd0bc0dd0faf4beb390f23aa4cf4e Mon Sep 17 00:00:00 2001 From: Mothblocks <35135081+Mothblocks@users.noreply.github.com> Date: Sun, 30 Oct 2022 01:46:48 -0700 Subject: [PATCH] Remove guide comments action (#70739) Removes all default comments after a PR is opened (and only when it is opened). Means that I can turn on the pr body merge option without keeping all the cruft --- .github/workflows/remove_guide_comments.yml | 18 ++++++++++ .../pull_request_hooks/removeGuideComments.js | 36 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 .github/workflows/remove_guide_comments.yml create mode 100644 tools/pull_request_hooks/removeGuideComments.js diff --git a/.github/workflows/remove_guide_comments.yml b/.github/workflows/remove_guide_comments.yml new file mode 100644 index 00000000000..230c66713e8 --- /dev/null +++ b/.github/workflows/remove_guide_comments.yml @@ -0,0 +1,18 @@ +# Removes guide comments from PRs when opened, so that when we merge them +# and reuse the pull request description, the clutter is not left behind +name: Remove guide comments +on: + pull_request: + types: [opened] +jobs: + remove_guide_comments: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Remove guide comments + uses: actions/github-script@v6 + with: + script: | + const { removeGuideComments } = await import('${{ github.workspace }}/tools/pull_request_hooks/removeGuideComments.js') + await removeGuideComments({ github, context }) diff --git a/tools/pull_request_hooks/removeGuideComments.js b/tools/pull_request_hooks/removeGuideComments.js new file mode 100644 index 00000000000..5f05dacd10c --- /dev/null +++ b/tools/pull_request_hooks/removeGuideComments.js @@ -0,0 +1,36 @@ +import fs from "fs"; + +const REGEX_COMMENT = //g; + +// Make sure we only remove default comments +const comments = []; + +for (const match of fs + .readFileSync(".github/PULL_REQUEST_TEMPLATE.md", { encoding: "utf8" }) + .matchAll(REGEX_COMMENT)) { + comments.push(match[0]); +} + +function escapeRegex(string) { + return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); +} + +export async function removeGuideComments({ github, context }) { + let newBody = context.payload.pull_request.body; + + for (const comment of comments) { + newBody = newBody.replace( + new RegExp(`^\\s*${escapeRegex(comment)}\\s*`, "gm"), + "\n" + ); + } + + if (newBody !== context.payload.pull_request.body) { + await github.rest.pulls.update({ + pull_number: context.payload.pull_request.number, + repo: context.repo.repo, + owner: context.repo.owner, + body: newBody, + }); + } +}