Skip to content
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

ci: automatically relate a backport PR to the backport issue #3255

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

yangchiu
Copy link
Member

@yangchiu yangchiu commented Nov 4, 2024

Which issue(s) this PR fixes:

Issue longhorn/longhorn#8002

What this PR does / why we need it:

automatically relate a backport PR to the backport issue

Special notes for your reviewer:

Additional documentation or context

@yangchiu yangchiu requested a review from a team November 4, 2024 06:26
@yangchiu yangchiu self-assigned this Nov 4, 2024
Copy link

coderabbitai bot commented Nov 4, 2024

Walkthrough

A new GitHub Actions workflow file named backport-pr.yml has been added to automate the linking of pull requests identified as backports to their corresponding issues. This workflow triggers when pull requests are opened against the master or version branches. It includes steps to check if the PR is a backport, extract relevant information, and link the PR to the original issue, thereby enhancing traceability.

Changes

File Path Change Summary
.github/workflows/backport-pr.yml Introduced a new workflow to automate linking backport PRs to their corresponding issues. Steps include checking PR title, extracting issue details, and commenting on backport issues.

Assessment against linked issues

Objective Addressed Explanation
Automate linking of backport PRs to corresponding issues (#8002)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

🧹 Outside diff range and nitpick comments (2)
.github/workflows/backport-pr.yml (2)

47-50: Add error handling for title encoding.

The current implementation could fail silently if the JSON parsing fails or if the title is missing.

Consider this improved version:

       - name: URL encode the original issue title
         if: env.BACKPORT == 'true'
-        run: echo "ORIGINAL_ISSUE_TITLE=$(node -e 'console.log(encodeURIComponent("${{ fromJson(steps.original-issue.outputs.data).title  }}"))')" >> $GITHUB_ENV
+        run: |
+          ISSUE_DATA='${{ steps.original-issue.outputs.data }}'
+          if ! TITLE=$(node -e 'try { 
+            const data = JSON.parse(process.argv[1]);
+            if (!data.title) throw new Error("No title found");
+            console.log(encodeURIComponent(data.title));
+          } catch (e) {
+            console.error(e);
+            process.exit(1);
+          }' "$ISSUE_DATA"); then
+            echo "Error: Failed to encode issue title"
+            exit 1
+          fi
+          echo "ORIGINAL_ISSUE_TITLE=$TITLE" >> $GITHUB_ENV
🧰 Tools
🪛 actionlint

49-49: shellcheck reported issue in this script: SC2086:info:1:138: Double quote to prevent globbing and word splitting

(shellcheck)


57-63: Add error handling for PR linking.

The current implementation doesn't handle potential failures when commenting on the issue.

Apply these improvements:

       - name: Link the PR with the corresponding backport issue
         if: env.BACKPORT == 'true'
         run: |
+          if [ -z "${{ env.BACKPORT_ISSUE_NUMBER }}" ]; then
+            echo "Error: Backport issue number is missing"
+            exit 1
+          fi
+          
           # Relate the pull request to the backport issue
-          gh issue comment --repo longhorn/longhorn ${{ env.BACKPORT_ISSUE_NUMBER }} --body "Related PR: ${{ github.event.pull_request.html_url }}"
+          if ! gh issue comment --repo longhorn/longhorn "${{ env.BACKPORT_ISSUE_NUMBER }}" --body "Related PR: ${{ github.event.pull_request.html_url }}"; then
+            echo "Error: Failed to comment on the backport issue"
+            exit 1
+          fi
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1925819 and 325c5ff.

📒 Files selected for processing (1)
  • .github/workflows/backport-pr.yml (1 hunks)
🧰 Additional context used
🪛 actionlint
.github/workflows/backport-pr.yml

18-18: shellcheck reported issue in this script: SC2086:info:2:27: Double quote to prevent globbing and word splitting

(shellcheck)


18-18: shellcheck reported issue in this script: SC2086:info:4:28: Double quote to prevent globbing and word splitting

(shellcheck)


18-18: "github.event.pull_request.title" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions for more details

(expression)


27-27: shellcheck reported issue in this script: SC2116:style:2:8: Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'

(shellcheck)


27-27: shellcheck reported issue in this script: SC2001:style:4:10: See if you can use ${variable//search/replace} instead

(shellcheck)


27-27: shellcheck reported issue in this script: SC2086:info:5:26: Double quote to prevent globbing and word splitting

(shellcheck)


27-27: shellcheck reported issue in this script: SC2086:info:9:56: Double quote to prevent globbing and word splitting

(shellcheck)


27-27: "github.event.pull_request.body" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions for more details

(expression)


49-49: shellcheck reported issue in this script: SC2086:info:1:138: Double quote to prevent globbing and word splitting

(shellcheck)


53-53: shellcheck reported issue in this script: SC2086:info:2:56: Double quote to prevent globbing and word splitting

(shellcheck)

🔇 Additional comments (3)
.github/workflows/backport-pr.yml (3)

1-9: LGTM! Workflow triggers are properly configured.

The workflow correctly triggers on PR open events for both master and version branches.


10-16: LGTM! Job setup follows best practices.

Using the latest Ubuntu runner and checkout@v4 is appropriate for this workflow.


38-46: LGTM! Secure and proper API usage.

The implementation correctly uses octokit/request-action with proper authentication.

Comment on lines +17 to +24
- name: Check if PR is a backport
run: |
if [[ "${{ github.event.pull_request.title }}" =~ "backport #" ]]; then
echo "BACKPORT=true" >> $GITHUB_ENV
else
echo "BACKPORT=false" >> $GITHUB_ENV
fi

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance security by properly handling untrusted input.

The PR title, which is user-controlled input, is being used directly in the shell script. This could potentially lead to command injection.

Apply this diff to handle the input more securely:

       - name: Check if PR is a backport
         run: |
-          if [[ "${{ github.event.pull_request.title }}" =~ "backport #" ]]; then
+          PR_TITLE='${{ github.event.pull_request.title }}'
+          if [[ "${PR_TITLE}" =~ backport[[:space:]]+#[0-9]+ ]]; then
             echo "BACKPORT=true" >> $GITHUB_ENV
           else
             echo "BACKPORT=false" >> $GITHUB_ENV
           fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Check if PR is a backport
run: |
if [[ "${{ github.event.pull_request.title }}" =~ "backport #" ]]; then
echo "BACKPORT=true" >> $GITHUB_ENV
else
echo "BACKPORT=false" >> $GITHUB_ENV
fi
- name: Check if PR is a backport
run: |
PR_TITLE='${{ github.event.pull_request.title }}'
if [[ "${PR_TITLE}" =~ backport[[:space:]]+#[0-9]+ ]]; then
echo "BACKPORT=true" >> $GITHUB_ENV
else
echo "BACKPORT=false" >> $GITHUB_ENV
fi
🧰 Tools
🪛 actionlint

18-18: shellcheck reported issue in this script: SC2086:info:2:27: Double quote to prevent globbing and word splitting

(shellcheck)


18-18: shellcheck reported issue in this script: SC2086:info:4:28: Double quote to prevent globbing and word splitting

(shellcheck)


18-18: "github.event.pull_request.title" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions for more details

(expression)

Comment on lines +25 to +37
- name: Extract backport branch and issue number
if: env.BACKPORT == 'true'
run: |
# Extract branch from the target branch of the PR
BRANCH=$(echo "${{ github.event.pull_request.base.ref }}")
BRANCH=${BRANCH%.x} # Remove the '.x' suffix
BRANCH=$(echo "${BRANCH}" | sed 's/\./\\./g') # Escape periods
echo "BRANCH=$BRANCH" >> $GITHUB_ENV

# Extract issue number from the PR description
ORIGINAL_ISSUE_NUMBER=$(echo "${{ github.event.pull_request.body }}" | grep -oE 'issues/[0-9]+' | cut -d'/' -f2)
echo "ORIGINAL_ISSUE_NUMBER=$ORIGINAL_ISSUE_NUMBER" >> $GITHUB_ENV

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and improve shell script robustness.

The current implementation lacks error handling and could be more robust:

  1. No validation of extracted issue number
  2. Shell commands could be improved
  3. Missing error handling for malformed PR body

Apply these improvements:

       - name: Extract backport branch and issue number
         if: env.BACKPORT == 'true'
         run: |
           # Extract branch from the target branch of the PR
-          BRANCH=$(echo "${{ github.event.pull_request.base.ref }}")
-          BRANCH=${BRANCH%.x}   # Remove the '.x' suffix
-          BRANCH=$(echo "${BRANCH}" | sed 's/\./\\./g')   # Escape periods
+          BRANCH="${{ github.event.pull_request.base.ref }}"
+          BRANCH="${BRANCH%.x}"   # Remove the '.x' suffix
+          BRANCH="${BRANCH//./\\.}"   # Escape periods
           echo "BRANCH=$BRANCH" >> $GITHUB_ENV

           # Extract issue number from the PR description
-          ORIGINAL_ISSUE_NUMBER=$(echo "${{ github.event.pull_request.body }}" | grep -oE 'issues/[0-9]+' | cut -d'/' -f2)
+          PR_BODY='${{ github.event.pull_request.body }}'
+          if [[ -z "${PR_BODY}" ]]; then
+            echo "Error: PR body is empty"
+            exit 1
+          fi
+          
+          ORIGINAL_ISSUE_NUMBER=$(echo "${PR_BODY}" | grep -oE 'issues/[0-9]+' | cut -d'/' -f2)
+          if [[ -z "${ORIGINAL_ISSUE_NUMBER}" ]]; then
+            echo "Error: Could not find original issue number in PR body"
+            exit 1
+          fi
+          
+          if ! [[ "${ORIGINAL_ISSUE_NUMBER}" =~ ^[0-9]+$ ]]; then
+            echo "Error: Invalid issue number format"
+            exit 1
+          fi
+          
           echo "ORIGINAL_ISSUE_NUMBER=$ORIGINAL_ISSUE_NUMBER" >> $GITHUB_ENV
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Extract backport branch and issue number
if: env.BACKPORT == 'true'
run: |
# Extract branch from the target branch of the PR
BRANCH=$(echo "${{ github.event.pull_request.base.ref }}")
BRANCH=${BRANCH%.x} # Remove the '.x' suffix
BRANCH=$(echo "${BRANCH}" | sed 's/\./\\./g') # Escape periods
echo "BRANCH=$BRANCH" >> $GITHUB_ENV
# Extract issue number from the PR description
ORIGINAL_ISSUE_NUMBER=$(echo "${{ github.event.pull_request.body }}" | grep -oE 'issues/[0-9]+' | cut -d'/' -f2)
echo "ORIGINAL_ISSUE_NUMBER=$ORIGINAL_ISSUE_NUMBER" >> $GITHUB_ENV
- name: Extract backport branch and issue number
if: env.BACKPORT == 'true'
run: |
# Extract branch from the target branch of the PR
BRANCH="${{ github.event.pull_request.base.ref }}"
BRANCH="${BRANCH%.x}" # Remove the '.x' suffix
BRANCH="${BRANCH//./\\.}" # Escape periods
echo "BRANCH=$BRANCH" >> $GITHUB_ENV
# Extract issue number from the PR description
PR_BODY='${{ github.event.pull_request.body }}'
if [[ -z "${PR_BODY}" ]]; then
echo "Error: PR body is empty"
exit 1
fi
ORIGINAL_ISSUE_NUMBER=$(echo "${PR_BODY}" | grep -oE 'issues/[0-9]+' | cut -d'/' -f2)
if [[ -z "${ORIGINAL_ISSUE_NUMBER}" ]]; then
echo "Error: Could not find original issue number in PR body"
exit 1
fi
if ! [[ "${ORIGINAL_ISSUE_NUMBER}" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid issue number format"
exit 1
fi
echo "ORIGINAL_ISSUE_NUMBER=$ORIGINAL_ISSUE_NUMBER" >> $GITHUB_ENV
🧰 Tools
🪛 actionlint

27-27: shellcheck reported issue in this script: SC2116:style:2:8: Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'

(shellcheck)


27-27: shellcheck reported issue in this script: SC2001:style:4:10: See if you can use ${variable//search/replace} instead

(shellcheck)


27-27: shellcheck reported issue in this script: SC2086:info:5:26: Double quote to prevent globbing and word splitting

(shellcheck)


27-27: shellcheck reported issue in this script: SC2086:info:9:56: Double quote to prevent globbing and word splitting

(shellcheck)


27-27: "github.event.pull_request.body" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions for more details

(expression)

Comment on lines +51 to +56
- name: Find corresponding backport issue number
if: env.BACKPORT == 'true'
run: |
BACKPORT_ISSUE_NUMBER=$(curl -s "https://api.github.com/search/issues?q=repo:longhorn/longhorn+is:open+is:issue+in:title+${{ env.BRANCH }}+${{ env.ORIGINAL_ISSUE_TITLE }}" | jq .items[0].number)
echo "BACKPORT_ISSUE_NUMBER=$BACKPORT_ISSUE_NUMBER" >> $GITHUB_ENV

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve reliability of backport issue search.

The current implementation has several potential failure points:

  1. No handling of API errors
  2. No validation of search results
  3. No handling of API rate limits

Apply these improvements:

       - name: Find corresponding backport issue number
         if: env.BACKPORT == 'true'
         run: |
-          BACKPORT_ISSUE_NUMBER=$(curl -s "https://api.github.com/search/issues?q=repo:longhorn/longhorn+is:open+is:issue+in:title+${{ env.BRANCH }}+${{ env.ORIGINAL_ISSUE_TITLE }}" | jq .items[0].number)
+          SEARCH_RESPONSE=$(curl -s -w "%{http_code}" "https://api.github.com/search/issues?q=repo:longhorn/longhorn+is:open+is:issue+in:title+${{ env.BRANCH }}+${{ env.ORIGINAL_ISSUE_TITLE }}")
+          HTTP_CODE=${SEARCH_RESPONSE: -3}
+          RESPONSE_BODY=${SEARCH_RESPONSE::-3}
+          
+          if [ "$HTTP_CODE" != "200" ]; then
+            echo "Error: GitHub API request failed with status $HTTP_CODE"
+            echo "Response: $RESPONSE_BODY"
+            exit 1
+          fi
+          
+          ITEMS_COUNT=$(echo "$RESPONSE_BODY" | jq '.total_count')
+          if [ "$ITEMS_COUNT" -eq 0 ]; then
+            echo "Error: No matching backport issue found"
+            exit 1
+          elif [ "$ITEMS_COUNT" -gt 1 ]; then
+            echo "Warning: Multiple matching issues found, using the first one"
+          fi
+          
+          BACKPORT_ISSUE_NUMBER=$(echo "$RESPONSE_BODY" | jq '.items[0].number')
+          if [ "$BACKPORT_ISSUE_NUMBER" = "null" ]; then
+            echo "Error: Failed to extract issue number from response"
+            exit 1
+          fi
+          
           echo "BACKPORT_ISSUE_NUMBER=$BACKPORT_ISSUE_NUMBER" >> $GITHUB_ENV
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Find corresponding backport issue number
if: env.BACKPORT == 'true'
run: |
BACKPORT_ISSUE_NUMBER=$(curl -s "https://api.github.com/search/issues?q=repo:longhorn/longhorn+is:open+is:issue+in:title+${{ env.BRANCH }}+${{ env.ORIGINAL_ISSUE_TITLE }}" | jq .items[0].number)
echo "BACKPORT_ISSUE_NUMBER=$BACKPORT_ISSUE_NUMBER" >> $GITHUB_ENV
- name: Find corresponding backport issue number
if: env.BACKPORT == 'true'
run: |
SEARCH_RESPONSE=$(curl -s -w "%{http_code}" "https://api.github.com/search/issues?q=repo:longhorn/longhorn+is:open+is:issue+in:title+${{ env.BRANCH }}+${{ env.ORIGINAL_ISSUE_TITLE }}")
HTTP_CODE=${SEARCH_RESPONSE: -3}
RESPONSE_BODY=${SEARCH_RESPONSE::-3}
if [ "$HTTP_CODE" != "200" ]; then
echo "Error: GitHub API request failed with status $HTTP_CODE"
echo "Response: $RESPONSE_BODY"
exit 1
fi
ITEMS_COUNT=$(echo "$RESPONSE_BODY" | jq '.total_count')
if [ "$ITEMS_COUNT" -eq 0 ]; then
echo "Error: No matching backport issue found"
exit 1
elif [ "$ITEMS_COUNT" -gt 1 ]; then
echo "Warning: Multiple matching issues found, using the first one"
fi
BACKPORT_ISSUE_NUMBER=$(echo "$RESPONSE_BODY" | jq '.items[0].number')
if [ "$BACKPORT_ISSUE_NUMBER" = "null" ]; then
echo "Error: Failed to extract issue number from response"
exit 1
fi
echo "BACKPORT_ISSUE_NUMBER=$BACKPORT_ISSUE_NUMBER" >> $GITHUB_ENV
🧰 Tools
🪛 actionlint

53-53: shellcheck reported issue in this script: SC2086:info:2:56: Double quote to prevent globbing and word splitting

(shellcheck)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant