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

Improvements in PR trigger #25

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

Conversation

josesimoes
Copy link
Member

@josesimoes josesimoes commented Dec 18, 2024

Description

  • Add git checkout step with parameters.
  • Update ref name to trigger actual PR.

Motivation and Context

  • Improve PR build trigger on AZDO.
  • Detailed explanation:
    Using refs/pull/PR_ID/head refers to the head branch of the pull request, which is the branch where the changes are being made. This allows to run the pipeline on the exact changes proposed in the pull request without merging them into the target branch.
    On the other hand, as it was being done before (refs/pull/PR_ID/merge) refers to a virtual merge branch that represents the result of merging the pull request changes into the target branch. This is useful for testing how the changes will integrate with the target branch, but it involves a merge operation.
    Since we want to trigger a build on a PR without making it like a merge, refs/pull/PR_ID/head is the appropriate reference to use.

How Has This Been Tested?

Screenshots

Types of changes

  • Improvement (non-breaking change that improves a feature, code or algorithm)
  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • New feature (non-breaking change which adds functionality to code)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Config and build (change in the configuration and build system, has no impact on code or features)
  • Dependencies (update dependencies and changes associated, has no impact on code or features)
  • Unit Tests (add new Unit Test(s) or improved existing one(s), has no impact on code or features)
  • Documentation (changes or updates in the documentation, has no impact on code or features)

Checklist:

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).
  • I have added new tests to cover my changes.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new checkout step to enhance the pipeline execution process.
    • Added a parameter for AZURE_POOL_NAME with a default value of TestStream.
    • Enhanced logic for fetching pull request details, including the title.
  • Bug Fixes

    • Improved error handling for pipeline triggering and monitoring.

@nfbot nfbot added the Type: enhancement New feature or request label Dec 18, 2024
Copy link

coderabbitai bot commented Dec 18, 2024

Walkthrough

The pull request modifies the bootstrap.yml file to enhance the Azure DevOps pipeline execution process. Changes include adding a new checkout step to clean the workspace and set a specific fetch depth, improving error handling for pipeline triggering and monitoring, and fetching pull request details from GitHub. A new variable, prTitle, is introduced to store the pull request title, which is included in the parameters sent when triggering the pipeline. Additionally, the default value for the AZURE_POOL_NAME parameter is updated to TestStream.

Changes

File Change Summary
bootstrap.yml - Added checkout step to clean workspace and set fetch depth to 1
- Enhanced error handling for pipeline triggering and monitoring
- Introduced variable prTitle to store pull request title
- Added parameter AZURE_POOL_NAME with default value TestStream

Possibly related PRs

  • Work CI-CD #23: The changes in this PR involve updating the checkout action version in GitHub Actions, which is relevant to the new checkout step introduced in the main PR's bootstrap.yml.

Suggested labels

Area: Config-and-Build


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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: 0

🧹 Nitpick comments (1)
bootstrap.yml (1)

Line range hint 119-164: Consider adding a timeout mechanism.

The monitoring loop is well-implemented with proper state checking and error handling. However, consider adding a timeout mechanism to prevent infinite waiting in case of pipeline delays or issues.

Here's a suggested implementation:

      # Loop to monitor the pipeline run status
+     start_time=$(date +%s)
+     timeout_minutes=60
      while true; do
+         current_time=$(date +%s)
+         elapsed_minutes=$(( (current_time - start_time) / 60 ))
+         
+         if [ $elapsed_minutes -ge $timeout_minutes ]; then
+             echo "Pipeline monitoring timed out after $timeout_minutes minutes"
+             exit 1
+         }
          response=$(curl -s -w "%{http_code}" -H "Authorization: Basic $(echo -n ":${AZURE_DEVOPS_PAT}" | base64)" -X GET "$url")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d98d3a and a16ac1c.

📒 Files selected for processing (1)
  • bootstrap.yml (2 hunks)
🔇 Additional comments (4)
bootstrap.yml (4)

Line range hint 1-13: LGTM! Well-structured parameter addition.

The new AZURE_POOL_NAME parameter is properly defined with appropriate type, display name, and default value.


18-20: LGTM! Optimized checkout configuration.

The checkout step is well configured with:

  • Clean workspace to prevent artifacts from previous runs
  • Shallow clone (fetchDepth: 1) to optimize performance

Line range hint 22-81: LGTM! Robust error handling implementation.

The script includes comprehensive error handling:

  • Validates required environment variables upfront
  • Proper HTTP status code checking
  • Detailed error reporting with response content

83-83: Verify the refName format change impact.

The change from refName: $branch to refName: $branch/head modifies how the PR branch is referenced. While this change aligns with Git's reference format for pull requests, we should verify it works consistently across different PR scenarios.

✅ Verification successful

The refName format change is safe to proceed

The change to refName: $branch/head is consistent with Git's reference format and aligns with the repository's workflow configuration. The repository uses standard GitHub Actions workflows that operate on pull requests targeting the main branch, and this reference format is the correct way to point to the HEAD of a PR branch. The old format would not work correctly with GitHub's PR reference structure.

Key observations:

  • The repository uses pull request triggers in its CI workflow
  • No other conflicting refName patterns were found in the codebase
  • The format $branch/head is the canonical way to reference PR heads in GitHub
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the repository has any existing PR builds using the old format
gh api graphql -f query='
query($owner:String!, $name:String!) {
  repository(owner:$owner, name:$name) {
    pullRequests(last:10, states:OPEN) {
      nodes {
        headRefName
        commits(last:1) {
          nodes {
            commit {
              statusCheckRollup {
                contexts(first:10) {
                  nodes {
                    context
                    state
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}' -F owner='nanoframework' -F name='nanoFramework.IoT.TestStream'

Length of output: 1461


Script:

#!/bin/bash
# Let's check the pipeline configuration files for refName patterns
rg -A 3 "refName:" --type yaml

# Also check for any other branch reference patterns
rg -A 3 "ref:" --type yaml

# Look for workflow files to understand the trigger patterns
fd -e yml -e yaml . .github/workflows --exec cat {}

Length of output: 2760

@josesimoes josesimoes force-pushed the improvements-in-pr-trigger branch from a16ac1c to 8d98df6 Compare December 18, 2024 15:18
josesimoes added a commit to nanoframework/nf-tools that referenced this pull request Dec 18, 2024
@josesimoes josesimoes force-pushed the improvements-in-pr-trigger branch from 8d98df6 to 130b3e1 Compare December 18, 2024 15:46
- Add git checkout step with parameters.
- Update ref name to trigger PR.
@josesimoes josesimoes force-pushed the improvements-in-pr-trigger branch from 130b3e1 to 94189bb Compare December 18, 2024 15:57
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

🧹 Nitpick comments (1)
bootstrap.yml (1)

Line range hint 21-49: Consider extracting GitHub API logic to a separate script

The script is growing in complexity with the addition of GitHub API integration. Consider:

  1. Moving GitHub API logic to a separate script file
  2. Adding retry logic for API calls
  3. Implementing proper logging with different verbosity levels

Example structure:

# github-utils.sh
#!/bin/bash
get_pr_details() {
    local repo=$1
    local pr_number=$2
    local token=$3
    
    # Add retry logic
    local max_attempts=3
    local attempt=1
    while [ $attempt -le $max_attempts ]; do
        # API call logic here
        attempt=$((attempt+1))
    done
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 130b3e1 and 94189bb.

📒 Files selected for processing (1)
  • bootstrap.yml (3 hunks)
🔇 Additional comments (1)
bootstrap.yml (1)

18-20: LGTM! Efficient checkout configuration.

The checkout step with clean: true and fetchDepth: 1 is well configured for PR builds:

  • Clean workspace prevents interference from previous builds
  • Shallow clone with depth 1 optimizes checkout performance

Comment on lines +41 to +42
auth=$(echo -n ":$GITHUB_TOKEN" | base64)
auth="basic $auth"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Avoid exposing encoded credentials in logs

The base64 encoding of credentials should be handled more securely:

  1. Avoid echoing credentials, even if encoded
  2. Consider using a more secure authentication method like OAuth tokens
-auth=$(echo -n ":$GITHUB_TOKEN" | base64)
-auth="basic $auth"
+auth="token $GITHUB_TOKEN"
📝 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
auth=$(echo -n ":$GITHUB_TOKEN" | base64)
auth="basic $auth"
auth="token $GITHUB_TOKEN"

Comment on lines +44 to +47
prUrl="https://api.github.com/repos/$env:Build_Repository_Name/pulls/$env:System_PullRequest_PullRequestNumber"
prResponse=$(curl -s -H "Authorization: $auth" -X GET "$prUrl")
prTitle=$(echo "$prResponse" | jq -r '.title')

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix environment variable syntax and add error handling

There are several issues in the PR details fetching:

  1. Inconsistent environment variable syntax ($env: is PowerShell syntax)
  2. Missing error handling for GitHub API response
-prUrl="https://api.github.com/repos/$env:Build_Repository_Name/pulls/$env:System_PullRequest_PullRequestNumber"
-prResponse=$(curl -s -H "Authorization: $auth" -X GET "$prUrl")
-prTitle=$(echo "$prResponse" | jq -r '.title')
+prUrl="https://api.github.com/repos/$BUILD_REPOSITORY_NAME/pulls/$SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"
+response=$(curl -s -w "%{http_code}" -H "Authorization: $auth" -X GET "$prUrl")
+http_code=${response: -3}
+content=${response::-3}
+
+if [ $http_code -eq 200 ]; then
+    prTitle=$(echo "$content" | jq -r '.title')
+    if [ "$prTitle" = "null" ]; then
+        echo "Error: Failed to extract PR title from response"
+        exit 1
+    fi
+else
+    echo "Error: Failed to fetch PR details. Status code: $http_code"
+    echo "Response: $content"
+    exit 1
+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
prUrl="https://api.github.com/repos/$env:Build_Repository_Name/pulls/$env:System_PullRequest_PullRequestNumber"
prResponse=$(curl -s -H "Authorization: $auth" -X GET "$prUrl")
prTitle=$(echo "$prResponse" | jq -r '.title')
prUrl="https://api.github.com/repos/$BUILD_REPOSITORY_NAME/pulls/$SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"
response=$(curl -s -w "%{http_code}" -H "Authorization: $auth" -X GET "$prUrl")
http_code=${response: -3}
content=${response::-3}
if [ $http_code -eq 200 ]; then
prTitle=$(echo "$content" | jq -r '.title')
if [ "$prTitle" = "null" ]; then
echo "Error: Failed to extract PR title from response"
exit 1
fi
else
echo "Error: Failed to fetch PR details. Status code: $http_code"
echo "Response: $content"
exit 1
fi

@@ -65,7 +81,7 @@
echo "Unique userCapabilities names: \"$capabilityNames\""

# Prepare the parameters
parametersJson=$(jq -n --arg appComponents "- $capabilityNames" '{templateParameters: {appComponents: $appComponents}}')
parametersJson=$(jq -n --arg appComponents "- $capabilityNames" --arg prTitle "$prTitle" '{templateParameters: {appComponents: $appComponents, prTitle: $prTitle}}')
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Update pipeline template to handle PR title parameter

The verification reveals that while the PR title is being included in the parameters JSON (bootstrap.yml), it's not defined as an expected parameter in any of the pipeline templates (multi-stage.yaml, test.yml). This needs to be addressed to ensure proper parameter handling:

  • Add prTitle parameter definition in multi-stage.yaml where other parameters are defined
  • Update any stages or jobs that need to use this parameter
🔗 Analysis chain

Verify PR title parameter handling

The PR title is now included in pipeline parameters. Ensure that:

  1. Special characters in PR title are properly escaped
  2. Pipeline template is updated to handle the new parameter

Let me gather more information about the pipeline templates to verify if they handle the PR title parameter.


Let me try a different approach to find the pipeline templates and parameter definitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if pipeline template handles prTitle parameter
rg -A 5 'parameters:.*prTitle' --type yaml

# Look for template parameter usage
rg 'prTitle' --type yaml

Length of output: 367


Script:

#!/bin/bash
# Search for pipeline template files
fd -e yaml -e yml template

# Check content of pipeline template files for parameter definitions
fd -e yaml -e yml template --exec cat {}

Length of output: 73


Script:

#!/bin/bash
# Search for yaml/yml files that might contain pipeline definitions
fd -e yaml -e yml

# Look for files containing pipeline parameter definitions
rg -A 5 'parameters:|templateParameters:' --type yaml

Length of output: 2208

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants