-
Notifications
You must be signed in to change notification settings - Fork 1
Add daily PR tracking with Slack notifications #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Add GitHub Action workflow to count and report daily PRs - Create script to fetch merged PRs in the last 24 hours - Enhance Slack notifications with dynamic emojis and messages based on PR count - Add clickable PR links in Slack messages - Implement custom bot name configuration for Slack messages - Add different message styles based on team productivity (PR count)
- Add GitHub Action workflow to count and report daily PRs - Create script to fetch merged PRs in the last 24 hours - Enhance Slack notifications with dynamic emojis and messages based on PR count - Add clickable PR links in Slack messages - Implement custom bot name configuration for Slack messages - Add different message styles based on team productivity (PR count)
WalkthroughA new GitHub Actions workflow and a supporting Node.js script have been introduced to automate the daily counting of merged pull requests in a repository. The workflow is scheduled to run every day at 20:00 UTC and can also be triggered manually. It sets up the environment, makes the script executable, and runs it with necessary environment variables. The script queries the GitHub API for pull requests merged in the last 24 hours, formats a summary message, and posts it to a specified Slack channel using a webhook. Changes
Sequence Diagram(s)sequenceDiagram
participant GitHub Actions
participant Node.js Script
participant GitHub API
participant Slack Webhook
GitHub Actions->>Node.js Script: Run merged-prs-last-24h.js with env vars
Node.js Script->>GitHub API: Request merged PRs from last 24h
GitHub API-->>Node.js Script: Return PR data
Node.js Script->>Node.js Script: Format summary message
Node.js Script->>Slack Webhook: Post summary message
Slack Webhook-->>Node.js Script: Acknowledge post
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR adds daily PR tracking with smart Slack notifications by implementing a Node.js script to fetch merged PRs over the last 24 hours and a GitHub Actions workflow to run the script on schedule.
- Introduces a Node.js script to filter merged PRs and send styled Slack notifications.
- Adds a GitHub Actions workflow to schedule the daily execution of the script.
- Enhances Slack messages with clickable links and custom bot configuration.
Reviewed Changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| scripts/merged-prs-last-24h.js | Node.js script to fetch recent PRs, build styled messages, and post to Slack |
| .github/workflows/daily-pr-count.yml | Workflow file to schedule and run the PR counter script daily |
🔍 Vulnerabilities of
|
| digest | sha256:83b18750ff07f827fd74b38f42e76e2eeccdb1b5f07cc705132ea437a24abcce |
| vulnerabilities | |
| platform | linux/amd64 |
| size | 280 MB |
| packages | 930 |
📦 Base Image node:23-alpine
Description
| ||||||||||||
Description
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Nitpick comments (7)
scripts/merged-prs-last-24h.js (5)
18-32: Add handling for GitHub API rate limiting.The script doesn't handle GitHub API rate limiting, which could cause failures if the rate limit is exceeded.
Add error handling for rate limit responses:
const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { if (res.statusCode !== 200) { + // Check for rate limiting + if (res.statusCode === 403 && res.headers['x-ratelimit-remaining'] === '0') { + const resetTime = new Date(parseInt(res.headers['x-ratelimit-reset']) * 1000); + console.error(`Error: GitHub API rate limit exceeded. Rate limit will reset at ${resetTime.toLocaleString()}`); + } else { console.error(`Error: Received status code ${res.statusCode}`); + } console.error(data); process.exit(1); }
35-47: Consider making PR count threshold configurable.The threshold of 4 PRs for determining the message style is hardcoded, which might not be appropriate for all teams or repositories.
Make the threshold configurable via an environment variable:
// Configuration - replace these values with your own const GITHUB_TOKEN = process.env.GITHUB_TOKEN; // Set your GitHub token as an environment variable const OWNER = process.env.GITHUB_OWNER || 'your-organization-or-username'; const REPO = process.env.GITHUB_REPO || 'your-repository-name'; const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL; // Slack webhook URL const SLACK_CHANNEL = process.env.SLACK_CHANNEL; // Optional specific Slack channel to post to const BOT_NAME = process.env.BOT_NAME || 'PRs_bot'; // Custom bot name for Slack messages +const PR_COUNT_THRESHOLD = parseInt(process.env.PR_COUNT_THRESHOLD || '4', 10); // Threshold for PR count message // Function to get emoji and message based on PR count function getMessageStyle(count) { - if (count < 4) { + if (count < PR_COUNT_THRESHOLD) { return { emoji: ':disappointed:', message: `Only ${count} PRs merged in the last 24 hours. We need to pick up the pace! Let's aim for more productivity tomorrow.` }; } else {
107-164: Implement pagination to handle repositories with high PR volume.The script fetches up to 100 PRs, but if more than 100 PRs were merged or closed in the time period, some might be missed.
For most repositories, 100 PRs per day is sufficient, but consider implementing pagination for completeness:
// Build the GitHub API request options const options = { hostname: 'api.github.com', path: `/repos/${OWNER}/${REPO}/pulls?state=closed&sort=updated&direction=desc&per_page=100`, method: 'GET', headers: { 'User-Agent': 'PR-Counter-Script', 'Accept': 'application/vnd.github.v3+json', } }; // Add Authorization header only if GITHUB_TOKEN is provided if (GITHUB_TOKEN) { options.headers.Authorization = `token ${GITHUB_TOKEN}`; } +// Function to handle GitHub API pagination +function fetchAllClosedPRs(page = 1, allPRs = []) { + return new Promise((resolve, reject) => { + const pageOptions = {...options}; + pageOptions.path = `${options.path}&page=${page}`; + + const pageReq = https.request(pageOptions, (res) => { + let data = ''; + + res.on('data', (chunk) => { + data += chunk; + }); + + res.on('end', () => { + if (res.statusCode !== 200) { + reject(`Error: Received status code ${res.statusCode}\n${data}`); + return; + } + + try { + const pulls = JSON.parse(data); + const combinedPRs = [...allPRs, ...pulls]; + + // If we got a full page of results and the oldest PR is newer than 24h ago, get the next page + if (pulls.length === 100 && new Date(pulls[pulls.length - 1].updated_at) >= twentyFourHoursAgo) { + fetchAllClosedPRs(page + 1, combinedPRs).then(resolve).catch(reject); + } else { + resolve(combinedPRs); + } + } catch (error) { + reject(`Error parsing response: ${error.message}`); + } + }); + }); + + pageReq.on('error', (error) => { + reject(`Error making request: ${error.message}`); + }); + + pageReq.end(); + }); +}And modify the main execution flow to use this function instead of the direct request.
126-128: Improve PR filtering to ensure only merged PRs are counted.The current filtering is correct, but it could be more explicit to ensure only merged PRs (not just closed) are counted.
Make the merged PR filtering more explicit:
// Filter PRs merged in the last 24 hours const recentlyMergedPRs = pulls.filter(pr => { - return pr.merged_at && pr.merged_at >= timestamp; + // Explicitly check for merged_at to ensure we're only counting merged PRs, not just closed ones + return pr.merged_at !== null && new Date(pr.merged_at) >= twentyFourHoursAgo; });
133-154: The PR summary formatting looks good, but make empty state message more informative.The script handles the case where no PRs were merged appropriately, but the message could be more informative.
Consider making the "no PRs" message more informative:
if (count === 0) { - message += "\n:warning: *No PRs were merged in the last 24 hours* :warning:"; + message += "\n:warning: *No PRs were merged in the last 24 hours* :warning:\nThis might be due to team focus on other activities, planning, or documentation work that doesn't require code changes."; }.github/workflows/daily-pr-count.yml (2)
26-32: Consider environment-specific configuration.The workflow hardcodes the GitHub repository and Slack channel, which limits reusability.
Consider using repository variables or a configuration file for environment-specific values:
- name: Run PR counter script run: | chmod +x ./scripts/merged-prs-last-24h.js ./scripts/merged-prs-last-24h.js env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_OWNER: speedandfunction - GITHUB_REPO: website + GITHUB_OWNER: ${{ vars.REPO_OWNER || github.repository_owner }} + GITHUB_REPO: ${{ vars.REPO_NAME || github.event.repository.name }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - SLACK_CHANNEL: "#spdfn-website" + SLACK_CHANNEL: ${{ vars.SLACK_CHANNEL || '#spdfn-website' }} BOT_NAME: "PRs Report Bot"🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 32-32: no new line character at the end of file
(new-line-at-end-of-file)
[error] 32-32: trailing spaces
(trailing-spaces)
🪛 GitHub Check: CodeQL
[warning] 11-32: Workflow does not contain permissions
Actions Job or Workflow does not set permissions
23-32: Add script failure handling.The workflow doesn't handle script failures gracefully.
Add error handling and notifications for script failures:
- name: Run PR counter script + id: run_script run: | chmod +x ./scripts/merged-prs-last-24h.js - ./scripts/merged-prs-last-24h.js + ./scripts/merged-prs-last-24h.js || echo "::error::PR counter script failed" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_OWNER: speedandfunction GITHUB_REPO: website SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} SLACK_CHANNEL: "#spdfn-website" BOT_NAME: "PRs Report Bot" + + - name: Notify on failure + if: failure() + run: | + curl -X POST -H 'Content-type: application/json' --data '{"text":"⚠️ Daily PR count workflow failed! Please check the logs: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"}' ${{ secrets.SLACK_WEBHOOK_URL }}🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 32-32: no new line character at the end of file
(new-line-at-end-of-file)
[error] 32-32: trailing spaces
(trailing-spaces)
🪛 GitHub Check: CodeQL
[warning] 11-32: Workflow does not contain permissions
Actions Job or Workflow does not set permissions
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
.github/workflows/daily-pr-count.yml(1 hunks)scripts/merged-prs-last-24h.js(1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/daily-pr-count.yml
15-15: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
18-18: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
🪛 YAMLlint (1.35.1)
.github/workflows/daily-pr-count.yml
[error] 12-12: trailing spaces
(trailing-spaces)
[error] 16-16: trailing spaces
(trailing-spaces)
[error] 21-21: trailing spaces
(trailing-spaces)
[error] 32-32: no new line character at the end of file
(new-line-at-end-of-file)
[error] 32-32: trailing spaces
(trailing-spaces)
🪛 GitHub Check: CodeQL
.github/workflows/daily-pr-count.yml
[warning] 11-32: Workflow does not contain permissions
Actions Job or Workflow does not set permissions
🔇 Additional comments (1)
scripts/merged-prs-last-24h.js (1)
159-162: Good error handling for JSON parsing.The script properly handles JSON parsing errors, which is good practice.
- Add explicit GitHub permissions in daily PR count workflow - Format PR counter script with Prettier - Add lint and format npm scripts for PR counter - Fix object formatting consistency in the PR counter script
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
.github/workflows/daily-pr-count.yml (1)
19-23: 🛠️ Refactor suggestionUpgrade GitHub Actions to supported versions
actions/checkout@v3andactions/setup-node@v3are flagged as outdated. To ensure compatibility and leverage the latest features/security patches, bump them to@v4:- - name: Checkout repository - uses: actions/checkout@v3 + - name: Checkout repository + uses: actions/checkout@v4 - - name: Set up Node.js - uses: actions/setup-node@v3 + - name: Set up Node.js + uses: actions/setup-node@v4 with: node-version: 16🧰 Tools
🪛 actionlint (1.7.4)
19-19: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
22-22: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
🪛 YAMLlint (1.35.1)
[error] 20-20: trailing spaces
(trailing-spaces)
🧹 Nitpick comments (2)
.github/workflows/daily-pr-count.yml (2)
5-6: Sync schedule comment with actual cron
The comment reads “Run at 10 PM CET (8 PM UTC)” but the cron'0 20 * * *'fires at 20:00 UTC (21:00 CET or 22:00 CEST). Either update the comment to reflect “20:00 UTC” or adjust the cron if you truly need 10 PM CET.
36-36: Remove trailing whitespace and add final newline
Trailing spaces on theBOT_NAMEline and the missing newline at EOF can cause YAML lint errors. Apply this diff:- BOT_NAME: "PRs Report Bot" + BOT_NAME: "PRs Report Bot"Then ensure the file ends with a single newline character.
🧰 Tools
🪛 YAMLlint (1.35.1)
[error] 36-36: no new line character at the end of file
(new-line-at-end-of-file)
[error] 36-36: trailing spaces
(trailing-spaces)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
.github/workflows/daily-pr-count.yml(1 hunks)scripts/merged-prs-last-24h.js(1 hunks)website/package.json(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- scripts/merged-prs-last-24h.js
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/daily-pr-count.yml
19-19: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
22-22: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
🪛 YAMLlint (1.35.1)
.github/workflows/daily-pr-count.yml
[error] 16-16: trailing spaces
(trailing-spaces)
[error] 20-20: trailing spaces
(trailing-spaces)
[error] 25-25: trailing spaces
(trailing-spaces)
[error] 36-36: no new line character at the end of file
(new-line-at-end-of-file)
[error] 36-36: trailing spaces
(trailing-spaces)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: security-scan
🔇 Additional comments (1)
website/package.json (1)
14-16:✅ Verification successful
Verify new npm scripts target and flags
The newly addedlint:pr-scriptandformat:pr-scriptrely on the relative path../scripts/merged-prs-last-24h.jsand specific CLI flags. Please confirm that:
- The file exists at that path relative to website/package.json.
- The ESLint
--parser-options=ecmaVersion:2022syntax is accepted by your CLI version.- Running these scripts produces the expected lint/format behavior (no errors).
🏁 Script executed:
#!/bin/bash # Verify existence and basic execution of the new npm scripts # Navigate to the website package directory cd website # Check that the PR summary script exists if [ ! -f ../scripts/merged-prs-last-24h.js ]; then echo "Error: ../scripts/merged-prs-last-24h.js not found" >&2 exit 1 fi # Run lint script in dry-run/check mode npm run lint:pr-script -- --max-warnings=0 # Run format script in check mode npm run format:pr-script -- --checkLength of output: 462
🏁 Script executed:
#!/bin/bash # Check for ESLint and Prettier in website/package.json cd website echo "Checking devDependencies and dependencies for ESLint and Prettier in package.json..." grep -E '"(eslint|prettier)"' package.json || echo "No ESLint or Prettier entries found in package.json" # Optionally inspect lockfile for installed versions if [ -f package-lock.json ]; then echo "Inspecting package-lock.json for ESLint and Prettier versions..." grep -E '"name": "eslint"| "name": "prettier"' -A2 package-lock.json || echo "No entries in package-lock.json" elif [ -f yarn.lock ]; then echo "Inspecting yarn.lock for ESLint and Prettier..." grep -E 'eslint@|prettier@' yarn.lock || echo "No entries in yarn.lock" else echo "No lockfile found to verify installed versions." fiLength of output: 601
Verified lint & format scripts
- The file
../scripts/merged-prs-last-24h.jsexists relative towebsite/package.json.eslint(^8.57.1) andprettier(^3.5.3) are declared inwebsite/package.jsonand will be installed vianpm install.- ESLint 8.x supports
--parser-options=ecmaVersion:2022, and Prettier 3.x supports--check.Once you’ve run
npm install,npm run lint:pr-scriptandnpm run format:pr-scriptshould execute without errors.
|
VitalyyP
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
Anton-88
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM



Summary by CodeRabbit