# Copyright (C) 2025 The Android Open Source Project
#
# Licensed 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.

name: Chromium Copybara import

on:
  pull_request:
    types: [opened, synchronize, reopened, edited]
    branches:
      - main  # Only apply to pull requests TO main.

permissions:
  pull-requests: write  # Required to edit PR body and read PR data
  contents: read        # Required to read commit history

jobs:
  include-git-origin-rev-id:
    runs-on: ubuntu-latest
    if: github.head_ref == 'dev/copybara/chromium_tmp'
    steps:
      - name: Include GitOrigin-RevId in Copybara PR body
        uses: actions/github-script@v6
        with:
          script: |
            const revIdRegex = /GitOrigin-RevId: \w+/;
            const pr = context.payload.pull_request;

            // STEP 1: Find the GitOrigin-RevId in commits.
            const { data: commits } = await github.rest.pulls.listCommits({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: pr.number,
            });

            let revId = null;
            for (const item of commits) {
              const match = item.commit.message.match(revIdRegex);
              if (match) {
                revId = match[0];
                console.log(`Found GitOrigin-RevId in commit ${item.sha}: ${revId}`);
                break;
              }
            }

            if (!revId) {
              core.setFailed('No "GitOrigin-RevId" found in any commit.');
              return;
            }

            // STEP 2: Update the PR body to include GitOrigin-RevId (if missing).
            const prBody = pr.body || '';
            let prBodyWithRevId;
            if (!prBody.includes(revId)) {
              console.log("GitOrigin-RevId not found in PR body. Appending it now.");
              prBodyWithRevId = prBody ? prBody.trim() + `\n\n${revId}` : revId;
              await github.rest.pulls.update({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: pr.number,
                body: prBodyWithRevId,
              });
              console.log("Successfully updated PR body.");
            } else {
              prBodyWithRevId = prBody;
              console.log("PR body already contains the GitOrigin-RevId.");
            }

            // STEP 3: Verify that the merge commit will contain GitOrigin-RevId.
            console.log("Verifying that the merge commit will contain GitOrigin-RevId...");
            const { data: updatedPr } = await github.rest.pulls.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: pr.number,
            });
            const defaultMergeCommitMessage = `${updatedPr.title}\n\n${updatedPr.body}`;
            if (defaultMergeCommitMessage.includes(revId)) {
              console.log(`Verification successful: The default merge commit message contains "${revId}".`);
            } else {
              const errorLines = [
                  `Verification FAILED: The default merge commit message does not contain "${revId}".`,
                  'The default merge commit message is:',
                  '---',
                  defaultMergeCommitMessage,
                  '---'
              ];
              core.setFailed(errorLines.join('\n'));
            }
