You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by sj...@apache.org on 2026/10/03 09:21:59 UTC

(maven-gh-actions-shared) branch v5 updated: Add PR check workflow with license declaration job (#326)

This is an automated email from the ASF dual-hosted git repository.

slawekjaranowski pushed a commit to branch v5
in repository https://gitbox.apache.org/repos/asf/maven-gh-actions-shared.git


The following commit(s) were added to refs/heads/v5 by this push:
     new 592b666  Add PR check workflow with license declaration job (#326)
592b666 is described below

commit 592b66614dbf57b6e55490afd68351383a87b91c
Author: Slawomir Jaranowski <s....@gmail.com>
AuthorDate: Sat Oct 3 11:21:54 2026 +0200

    Add PR check workflow with license declaration job (#326)
    
    * Add PR check workflow with license declaration job
    
    Co-Authored-By: Claude Opus 5 (1M context) <no...@anthropic.com>
    
    * Address review comments in pr-check license job
    
    Stop fetching every comment on the PR: iterate pages with
    github.paginate.iterator and break as soon as the marker is found.
    The bot comment is created on the first failing run, so it is normally
    on the first page - one request instead of one per 100 comments.
    
    Guard the three GraphQL calls that address the existing comment with
    try/catch. The comment may be deleted between listing it and reading or
    mutating it, which made the step throw. A warning is enough: hiding or
    restoring the comment is not what the check itself verifies.
    
    On a failed isMinimized query the comment is deliberately kept in
    `existing`. Dropping it would take a transient error into the
    "no comment yet" branch and post a duplicate warning that later runs
    would never hide.
    
    Co-Authored-By: Claude Opus 5 (1M context) <no...@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Opus 5 (1M context) <no...@anthropic.com>
---
 .github/workflows/pr-check.yml | 170 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 170 insertions(+)

diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml
new file mode 100644
index 0000000..6455bf3
--- /dev/null
+++ b/.github/workflows/pr-check.yml
@@ -0,0 +1,170 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Reusable workflow grouping the checks run against a pull request.
+name: PR check
+
+on:
+  workflow_call:
+
+# clear all permissions for GITHUB_TOKEN
+permissions: {}
+
+jobs:
+  # The PR description must contain at least one CHECKED Apache license declaration
+  # ("- [x] I hereby declare ...").
+  # - Missing       -> adds ONE comment and fails.
+  # - Fixed         -> hides the comment as outdated and passes.
+  # - Removed again -> unhides the same comment (no duplicates).
+  license-declaration:
+    permissions:
+      pull-requests: write
+      issues: write # PR comments are "issue comments" in the API
+    runs-on: ubuntu-slim
+    # Skip (a skipped job counts as successful, so a required check doesn't block the merge):
+    # - PRs opened by bots (Dependabot, Renovate, other GitHub Apps),
+    # - PRs opened by members of the organization owning the repository (apache).
+    if: >-
+      github.event.pull_request.user.type != 'Bot' &&
+      !contains(fromJSON('["OWNER", "MEMBER"]'), github.event.pull_request.author_association)
+    # Prevents races (e.g. opened + edited in quick succession => two comments).
+    # Do NOT define the same concurrency group in the caller – it would deadlock.
+    concurrency:
+      group: license-declaration-check-${{ github.repository }}-${{ github.event.pull_request.number }}
+      cancel-in-progress: false
+    steps:
+      - name: Check license declaration
+        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
+        with:
+          script: |
+            const MARKER = '<!-- license-declaration-check -->';
+
+            // At least one of these lines must be present with a checked box
+            const DECLARATIONS = [
+              'I hereby declare this contribution to be licensed under the [Apache License Version 2.0, January 2004](https://www.apache.org/licenses/LICENSE-2.0)',
+              'I hereby declare that I have filed an [Apache Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).',
+            ];
+
+            const { owner, repo } = context.repo;
+
+            // The workflow only makes sense for pull request events
+            const prNumber = context.payload.pull_request?.number;
+            if (!prNumber) {
+              core.setFailed(`This workflow must be called from pull_request or pull_request_target events (got "${context.eventName}").`);
+              return;
+            }
+
+            // "- [x] <declaration>" or "* [X] <declaration>", one per line, optional indentation/trailing spaces.
+            // Links may use either http:// or https://.
+            const escape = s => s
+              .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+              .replace(/https?:\/\//g, 'https?://');
+            const regex = new RegExp(
+              `^[ \\t]*[-*][ \\t]+\\[[xX]\\][ \\t]+(?:${DECLARATIONS.map(escape).join('|')})[ \\t]*\\r?$`,
+              'm'
+            );
+
+            // Fetch the current description from the API (the event payload may be stale on "Re-run jobs")
+            const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
+            const hasDeclaration = regex.test(pr.body || '');
+
+            // Find our comment: author must be a bot and the comment must contain the marker.
+            // Iterate page by page and stop as soon as it is found - it is usually one of the first comments.
+            let existing;
+            for await (const { data: page } of github.paginate.iterator(github.rest.issues.listComments, {
+              owner, repo, issue_number: prNumber, per_page: 100,
+            })) {
+              existing = page.find(c => c.user?.type === 'Bot' && c.body?.includes(MARKER));
+              if (existing) break;
+            }
+
+            // Check whether the comment is already hidden
+            let isMinimized = false;
+            if (existing) {
+              try {
+                const res = await github.graphql(
+                  `query($id: ID!) {
+                     node(id: $id) { ... on IssueComment { isMinimized } }
+                   }`,
+                  { id: existing.node_id }
+                );
+                isMinimized = res.node?.isMinimized ?? false;
+              } catch (err) {
+                // The comment may have been deleted in the meantime - continue without hiding/unhiding it
+                core.warning(`Cannot read the state of the existing comment: ${err.message}`);
+              }
+            }
+
+            // ---------- Declaration OK ----------
+            if (hasDeclaration) {
+              if (existing && !isMinimized) {
+                try {
+                  await github.graphql(
+                    `mutation($id: ID!) {
+                       minimizeComment(input: { subjectId: $id, classifier: OUTDATED }) {
+                         minimizedComment { isMinimized }
+                       }
+                     }`,
+                    { id: existing.node_id }
+                  );
+                  core.info('Comment marked as outdated (hidden).');
+                } catch (err) {
+                  // The comment may have been deleted in the meantime - not a reason to fail the check
+                  core.warning(`Cannot hide the existing comment: ${err.message}`);
+                }
+              }
+              core.info('✅ PR description contains a checked license declaration.');
+              return;
+            }
+
+            // ---------- Declaration missing ----------
+            if (!existing) {
+              // The comment is added only once
+              await github.rest.issues.createComment({
+                owner, repo, issue_number: prNumber,
+                body: [
+                  MARKER,
+                  '### ⚠️ License declaration missing',
+                  '',
+                  'The pull request description must contain at least one of the following lines with a **checked** box (`[x]`):',
+                  '',
+                  '```markdown',
+                  ...DECLARATIONS.map(d => `- [ ] ${d}`),
+                  '```',
+                  '',
+                  'This comment will be hidden automatically once the description is fixed.',
+                ].join('\n'),
+              });
+              core.info('Comment added.');
+            } else if (isMinimized) {
+              // The declaration was removed again – unhide the existing comment instead of adding a new one
+              try {
+                await github.graphql(
+                  `mutation($id: ID!) {
+                     unminimizeComment(input: { subjectId: $id }) {
+                       unminimizedComment { isMinimized }
+                     }
+                   }`,
+                  { id: existing.node_id }
+                );
+                core.info('Existing comment restored (unhidden).');
+              } catch (err) {
+                core.warning(`Cannot restore the existing comment: ${err.message}`);
+              }
+            }
+
+            core.setFailed('❌ PR description does not contain a checked license declaration.');