Skip to content

feat: add automatic PR labeler workflow#115

Open
SIDDHANTCOOKIE wants to merge 3 commits intoAOSSIE-Org:mainfrom
SIDDHANTCOOKIE:feat/pr-labeler
Open

feat: add automatic PR labeler workflow#115
SIDDHANTCOOKIE wants to merge 3 commits intoAOSSIE-Org:mainfrom
SIDDHANTCOOKIE:feat/pr-labeler

Conversation

@SIDDHANTCOOKIE
Copy link
Contributor

@SIDDHANTCOOKIE SIDDHANTCOOKIE commented Mar 16, 2026

Addressed Issues:

  • Adds .github/workflows/pr-labeler.yml using actions/github-script
  • Triggers on PR opened, reopened, synchronized, and edited events
  • Parses PR descriptions to link issues using common keywords including
    "addresses #N", with or without spacing (e.g., "fixes#N").
  • Automatically evaluates if linked issues have an assignee and applies
    issue-assigned or issue-unassigned labels.
  • Adds no-linked-issue label if no issue is detected.
  • Checks against open PRs to prevent duplicate PRs from targeting the
    same issue, applying potential-duplicate to the newer ones.

Screenshots/Recordings:

TODO: If applicable, add screenshots or recordings that demonstrate the interface before and after the changes.

Additional Notes:

AI Usage Disclosure:

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact. AI slop is strongly discouraged and may lead to banning and blocking. Do not spam our repos with AI slop.

Check one of the checkboxes below:

  • This PR does not contain AI-generated code at all.
  • This PR contains AI-generated code. I have read the AI Usage Policy and this PR complies with this policy. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: used gemini and github actions docs to make this

Checklist

  • My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • My code follows the project's code style and conventions
  • If applicable, I have made corresponding changes or additions to the documentation
  • If applicable, I have made corresponding changes or additions to tests
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contribution Guidelines
  • Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.
  • I have filled this PR template completely and carefully, and I understand that my PR may be closed without review otherwise.

Summary by CodeRabbit

  • Chores

    • Added an automated PR labeling workflow to tag PRs based on linked issues (assigned/unassigned/no-linked-issue/potential-duplicate) and keep labels up to date.
  • Bug Fixes

    • Made analytics error handling explicit to prevent silent failures when dispatching tracking events.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 16, 2026

Walkthrough

Adds a new GitHub Actions workflow that labels PRs based on linked issues, assignee status, and potential duplicate PRs; also tightens error handling in analytics delivery paths of the social share button module.

Changes

Cohort / File(s) Summary
PR Labeler workflow
.​github/workflows/pr-labeler.yml
New GitHub Actions workflow triggered on pull_request_target events. Parses PR body for linked issues, ensures labels (issue-assigned, issue-unassigned, no-linked-issue, potential-duplicate) exist (creates them if missing), determines which labels to add/remove by inspecting linked issues and other open PRs, and applies/removes labels via GitHub REST API with logging and error handling.
Analytics error handling
src/social-share-button.js
Replaces empty catch blocks with explicit // ignore comments, adds a guard to ensure analyticsPlugins is an array before iterating, and keeps per-plugin track calls wrapped in try/catch that ignore failures. Minor behavioral-preserving changes to analytics error handling.

Sequence Diagram(s)

sequenceDiagram
  participant PR as "Pull Request (event)"
  participant Action as "GitHub Action (pr-labeler)"
  participant Script as "github-script JS"
  participant GHAPI as "GitHub REST API"

  PR->>Action: pr opened/reopened/synchronize/edited
  Action->>Script: run labeling script
  Script->>GHAPI: GET PR body
  Script->>Script: parse linked issues (regex)
  alt no linked issues
    Script->>GHAPI: ensure `no-linked-issue` label exists
    Script->>GHAPI: add `no-linked-issue` to PR
  else linked issues present
    Script->>GHAPI: for each issue -> GET issue details (assignees)
    Script->>GHAPI: list open PRs -> map linked issues (detect duplicates)
    Script->>GHAPI: ensure `issue-assigned`/`issue-unassigned`/`potential-duplicate` exist
    Script->>GHAPI: add appropriate labels to PR
  end
  Script->>GHAPI: remove stale labels from PR
  Script->>Action: finish (logs/results)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Typescript Lang, Linter

Poem

🐇 I hopped through diffs with nimble paws,
Found labels, regex, and API laws.
I guard the tracks and quietly cheer,
Ignoring small errors — no need for fear.
A tidy PR garden — now bring the carrots near! 🥕

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add automatic PR labeler workflow' directly and clearly describes the main change: introducing a new GitHub Actions workflow for automatic PR labeling, which matches the primary objective of adding the pr-labeler.yml file.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/pr-labeler.yml:
- Around line 36-60: The ensureLabel function currently swallows non-404
getLabel errors and doesn't handle a createLabel race condition; update
ensureLabel to rethrow any getLabel errors whose error.status !== 404 instead of
just console.log, and wrap the github.rest.issues.createLabel call in its own
try-catch that treats error.status === 422 as a no-op (label already created by
a concurrent run) while rethrowing any other createLabel errors; keep using the
same labelsEnsured set and github.rest.issues.getLabel/createLabel symbols to
locate where to add these checks.
- Around line 3-12: The workflow currently uses the pull_request event which
cannot label forked PRs because GITHUB_TOKEN is read-only; change the trigger
from pull_request to pull_request_target (replace "pull_request" with
"pull_request_target" at the top) so the job "label-pr" runs in the base repo
context where "permissions: issues: write" is honored, and ensure the "label-pr"
job remains metadata-only by removing any steps that checkout or run PR code (do
not run actions that use the PR repository code) to avoid executing untrusted
code in the trusted context.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 347a1284-1d5b-47ea-ba96-a45b4f7c8927

📥 Commits

Reviewing files that changed from the base of the PR and between 9e7e113 and a975496.

📒 Files selected for processing (1)
  • .github/workflows/pr-labeler.yml

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/social-share-button.js (2)

766-788: ⚠️ Potential issue | 🟡 Minor

Replace // ignore comments with debug-conditional warnings.

The // ignore comments in these catch blocks do not meet the established pattern for this file. Analytics failures should emit a debug warning when this.options.debug is enabled to help developers diagnose issues during integration.

🛠️ Proposed fix using a consolidated debug helper

Add a private helper method (per prior learnings, consolidate debug logging to one location):

// Add near other private methods
_debugWarn(message, err) {
  if (this.options.debug) {
    // eslint-disable-next-line no-console
    console.warn(`[SocialShareButton Analytics] ${message}`, err);
  }
}

Then update the catch blocks:

      } catch (_) {
-       // ignore
+       this._debugWarn('DOM CustomEvent dispatch failed', _);
      }
      } catch (_) {
-       // ignore
+       this._debugWarn('onAnalytics callback failed', _);
      }
          } catch (_) {
-           // ignore
+           this._debugWarn('analyticsPlugin.track() failed', _);
          }

Based on learnings: "replace empty catch blocks in _emit() around DOM CustomEvent dispatch, onAnalytics callback, and analyticsPlugins loop with debug-conditional console.warn calls... plain comments inside catch blocks are not sufficient" and "consolidate debugging logs to a single helper... _debugWarn(message, err) function."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/social-share-button.js` around lines 766 - 788, The empty catch blocks
inside _emit() (around the CustomEvent dispatch, the this.options.onAnalytics
call, and the analyticsPlugins loop) should be replaced with debug-conditional
warnings that surface errors when this.options.debug is true; add a private
helper _debugWarn(message, err) that logs a formatted console.warn when debug is
enabled, and call _debugWarn with a clear message and the caught error in each
catch block (referencing the CustomEvent dispatch, this.options.onAnalytics, and
plugin.track payloads) so failures are visible during integration while
remaining silent in production.

781-791: 🧹 Nitpick | 🔵 Trivial

Consider warning when analyticsPlugins is misconfigured.

The Array.isArray guard is a good defensive check. However, if a consumer mistakenly passes the entire window.SocialShareAnalytics adapters object or a single adapter class instead of an array of instances, this will silently skip all plugins with no feedback.

💡 Suggested improvement
    // Path 3 — plugin / adapter registry (supports multiple simultaneous consumers)
-   if (Array.isArray(this.options.analyticsPlugins)) {
+   const plugins = this.options.analyticsPlugins;
+   if (Array.isArray(plugins)) {
      for (const plugin of this.options.analyticsPlugins) {
        if (plugin && typeof plugin.track === "function") {
          try {
            plugin.track(payload);
          } catch (_) {
            // ignore
          }
        }
      }
+   } else if (plugins && this.options.debug) {
+     this._debugWarn('analyticsPlugins should be an array of adapter instances', null);
    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/social-share-button.js` around lines 781 - 791, The current
Array.isArray(this.options.analyticsPlugins) check silently skips misconfigured
values; update the logic around this.options.analyticsPlugins to emit a clear
warning when analyticsPlugins is provided but not an array (include actual
typeof/constructor info in the message), and also emit a warning when an array
element is present but does not expose a callable track method (reference
plugin.track) so consumers know which entries were ignored; keep the existing
try/catch for plugin.track invocation but add these targeted console.warn/log
calls that mention analyticsPlugins and plugin.track.
♻️ Duplicate comments (1)
.github/workflows/pr-labeler.yml (1)

78-104: ⚠️ Potential issue | 🟠 Major

Invalid or PR-only references are still mislabeled as issue-unassigned.

If all parsed issue numbers turn out to be PRs (skipped via issue.data.pull_request check) or fail to fetch (404/errors), the code still enters the else branch and adds issue-unassigned. This should be treated as "no linked issue" since no valid issues were found.

Track valid issue numbers separately and check if any remain after filtering:

,

🛠️ Suggested fix
            } else {
              // Rules 2: Assigned vs Unassigned Label
              let isAssigned = false;
+             const validIssueNumbers = new Set();
              for (const issueNumber of Array.from(issueNumbers)) {
                try {
                  const issue = await github.rest.issues.get({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    issue_number: parseInt(issueNumber, 10)
                  });
-                 // Ignore if it's actually referencing another PR instead of an Issue
-                 if (!issue.data.pull_request && issue.data.assignees && issue.data.assignees.length > 0) {
+                 // Skip if it's actually a PR, not an issue
+                 if (issue.data.pull_request) continue;
+                 validIssueNumbers.add(issueNumber);
+                 if (issue.data.assignees && issue.data.assignees.length > 0) {
                    isAssigned = true;
                  }
                } catch (e) {
                  console.log(`Could not fetch issue #${issueNumber}: ${e.message}`);
                }
              }

-             if (isAssigned) {
+             if (validIssueNumbers.size === 0) {
+               labelsToAdd.add('no-linked-issue');
+             } else if (isAssigned) {
                labelsToAdd.add('issue-assigned');
              } else {
                labelsToAdd.add('issue-unassigned');
              }

Also update the duplicate detection to use validIssueNumbers:

-             for (const issueNumber of Array.from(issueNumbers)) {
+             for (const issueNumber of Array.from(validIssueNumbers)) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/pr-labeler.yml around lines 78 - 104, The loop over
issueNumbers can end up with zero valid issues (all references were PRs or fetch
failed) but the code still labels the PR as issue-unassigned; fix by tracking
validIssueNumbers (e.g., a Set or array) alongside isAssigned: inside the try
block, after fetching via github.rest.issues.get and confirming
!issue.data.pull_request, add the issueNumber to validIssueNumbers and set
isAssigned if assignees exist; after the loop, if validIssueNumbers is empty add
'no-linked-issue' to labelsToAdd, else add 'issue-assigned' or
'issue-unassigned' based on isAssigned. Ensure references to issueNumbers,
validIssueNumbers, isAssigned, labelsToAdd and the issue.data.pull_request check
are updated accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/pr-labeler.yml:
- Around line 19-31: The current getLinkedIssues helper uses a regex that treats
bare “#N” mentions as linked issues (regex in getLinkedIssues), causing false
positives; update the regex so it requires a linking keyword (make the leading
group mandatory instead of optional) or provide a configuration flag to toggle
permissive matching, then adjust the regex used in getLinkedIssues accordingly
and ensure the while loop still extracts group 1 for the issue number.
- Around line 106-134: The duplicate-detection loop currently iterates over
issueNumbers which can contain invalid or non-issue references; change the loop
to iterate over validIssueNumbers instead so only confirmed issue IDs are
considered (update the for (const issueNumber of Array.from(issueNumbers)) to
use validIssueNumbers), leaving the rest of the logic that uses getLinkedIssues,
relatedPulls, isDuplicate and labelsToAdd intact.

---

Outside diff comments:
In `@src/social-share-button.js`:
- Around line 766-788: The empty catch blocks inside _emit() (around the
CustomEvent dispatch, the this.options.onAnalytics call, and the
analyticsPlugins loop) should be replaced with debug-conditional warnings that
surface errors when this.options.debug is true; add a private helper
_debugWarn(message, err) that logs a formatted console.warn when debug is
enabled, and call _debugWarn with a clear message and the caught error in each
catch block (referencing the CustomEvent dispatch, this.options.onAnalytics, and
plugin.track payloads) so failures are visible during integration while
remaining silent in production.
- Around line 781-791: The current Array.isArray(this.options.analyticsPlugins)
check silently skips misconfigured values; update the logic around
this.options.analyticsPlugins to emit a clear warning when analyticsPlugins is
provided but not an array (include actual typeof/constructor info in the
message), and also emit a warning when an array element is present but does not
expose a callable track method (reference plugin.track) so consumers know which
entries were ignored; keep the existing try/catch for plugin.track invocation
but add these targeted console.warn/log calls that mention analyticsPlugins and
plugin.track.

---

Duplicate comments:
In @.github/workflows/pr-labeler.yml:
- Around line 78-104: The loop over issueNumbers can end up with zero valid
issues (all references were PRs or fetch failed) but the code still labels the
PR as issue-unassigned; fix by tracking validIssueNumbers (e.g., a Set or array)
alongside isAssigned: inside the try block, after fetching via
github.rest.issues.get and confirming !issue.data.pull_request, add the
issueNumber to validIssueNumbers and set isAssigned if assignees exist; after
the loop, if validIssueNumbers is empty add 'no-linked-issue' to labelsToAdd,
else add 'issue-assigned' or 'issue-unassigned' based on isAssigned. Ensure
references to issueNumbers, validIssueNumbers, isAssigned, labelsToAdd and the
issue.data.pull_request check are updated accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 289f60f4-1b08-40ee-9f44-1e35055f5afd

📥 Commits

Reviewing files that changed from the base of the PR and between a975496 and c9f9846.

📒 Files selected for processing (2)
  • .github/workflows/pr-labeler.yml
  • src/social-share-button.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant