Skip to content

[ISSUE #1345]🔨Update Github Actions CI #1346

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

Merged
merged 1 commit into from
Nov 26, 2024
Merged

[ISSUE #1345]🔨Update Github Actions CI #1346

merged 1 commit into from
Nov 26, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Nov 26, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1345

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for label management by ensuring operations depend on valid pull request data.
  • Refactor

    • Enhanced the logic for updating labels, including conditional checks for existing pull requests and labels.
  • Chores

    • Added a debugging step to output workflow context for better troubleshooting.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request involve modifications to the GitHub Actions workflow file .github/workflows/update-labels.yml. The updates enhance the logic for updating labels after a workflow run, including the addition of a debugging step and a refactored script for label management. The new script retrieves workflow run details, checks for associated pull requests, and conditionally manages label addition and removal based on the presence of valid pull request data.

Changes

File Change Summary
.github/workflows/update-labels.yml Enhanced label management logic, added debugging step, refactored script to check for pull requests, and improved error handling.

Assessment against linked issues

Objective Addressed Explanation
Enhance GitHub Actions CI (Issue #1345)

Possibly related issues

Possibly related PRs

Suggested labels

enhancement, approved, auto merge, ready to review

Suggested reviewers

  • TeslaRustor
  • SpaceXCN

Poem

In the land of code where rabbits play,
Labels hop along, brightening the day.
With a tweak here and a fix there,
Our workflows dance without a care.
Debugging steps, a clever sight,
Managing labels, all feels right! 🐇✨


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.

@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution 🎉. CodeRabbit(AI) will review your code first 🔥

@rocketmq-rust-robot rocketmq-rust-robot added the enhancement⚡️ New feature or request label Nov 26, 2024
@rocketmq-rust-bot rocketmq-rust-bot added AI review first Ai review pr first ready to review waiting-review waiting review this PR labels Nov 26, 2024
@rocketmq-rust-robot rocketmq-rust-robot added this to the v0.4.0 milestone Nov 26, 2024
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved auto merge and removed ready to review waiting-review waiting review this PR labels Nov 26, 2024
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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cb62fb1 and abb479e.

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

23-23: could not parse as YAML: yaml: line 23: mapping values are not allowed in this context

(syntax-check)

🪛 yamllint (1.35.1)
.github/workflows/update-labels.yml

[error] 23-23: syntax error: mapping values are not allowed here

(syntax)

🔇 Additional comments (1)
.github/workflows/update-labels.yml (1)

Line range hint 1-78: Verify security configuration and action versions

Please verify:

  1. The BOT_TOKEN has minimal required permissions
  2. The GitHub Actions versions are pinned to SHA for security
🧰 Tools
🪛 actionlint (1.7.4)

23-23: could not parse as YAML: yaml: line 23: mapping values are not allowed in this context

(syntax-check)

🪛 yamllint (1.35.1)

[error] 23-23: syntax error: mapping values are not allowed here

(syntax)

Comment on lines +22 to +24
- name: Debug Workflow Context
run: echo "Payload: $(cat $GITHUB_EVENT_PATH)"

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix YAML syntax and consider security implications

  1. The run command needs proper YAML indentation
  2. Exposing the full event payload in logs could leak sensitive information

Apply this fix for proper YAML syntax:

      - name: Debug Workflow Context
-        run: echo "Payload: $(cat $GITHUB_EVENT_PATH)"
+        run: |
+          # Filter sensitive information before logging
+          jq '. | del(.token) | del(.secrets)' $GITHUB_EVENT_PATH

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 actionlint (1.7.4)

23-23: could not parse as YAML: yaml: line 23: mapping values are not allowed in this context

(syntax-check)

🪛 yamllint (1.35.1)

[error] 23-23: syntax error: mapping values are not allowed here

(syntax)

Comment on lines +33 to +44
const workflowRunId = context.payload.workflow_run.id;
const { data: workflowRun } = await github.rest.actions.getWorkflowRun({
owner,
repo,
issue_number,
run_id: workflowRunId,
});

// Filter the labels that exist on the PR and are in the labelsToRemove list
const existingLabelsToRemove = labels
.filter(label => labelsToRemove.includes(label.name))
.map(label => label.name);

// Remove each label
for (const label of existingLabelsToRemove) {
await github.rest.issues.removeLabel({

if (workflowRun.pull_requests && workflowRun.pull_requests.length > 0) {
const issue_number = workflowRun.pull_requests[0].number;

console.log(`Processing PR #${issue_number} in repository '${owner}/${repo}'.`);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling for API calls

The workflow run retrieval lacks try-catch error handling, and assumes the first PR is always the target PR.

Consider this enhanced implementation:

-            const { data: workflowRun } = await github.rest.actions.getWorkflowRun({
-              owner,
-              repo,
-              run_id: workflowRunId,
-            });
+            try {
+              const { data: workflowRun } = await github.rest.actions.getWorkflowRun({
+                owner,
+                repo,
+                run_id: workflowRunId,
+              });
+
+              if (!workflowRun.pull_requests?.length) {
+                throw new Error('No associated pull requests found');
+              }
+              
+              // Verify we're targeting the correct PR
+              const targetPR = workflowRun.pull_requests.find(pr => 
+                pr.head.sha === context.payload.workflow_run.head_sha
+              );
+              
+              if (!targetPR) {
+                throw new Error('Could not find matching PR for this workflow run');
+              }
+              
+              const issue_number = targetPR.number;
+            } catch (error) {
+              core.setFailed(`Failed to process workflow run: ${error.message}`);
+              throw error;
+            }
📝 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
const workflowRunId = context.payload.workflow_run.id;
const { data: workflowRun } = await github.rest.actions.getWorkflowRun({
owner,
repo,
issue_number,
run_id: workflowRunId,
});
// Filter the labels that exist on the PR and are in the labelsToRemove list
const existingLabelsToRemove = labels
.filter(label => labelsToRemove.includes(label.name))
.map(label => label.name);
// Remove each label
for (const label of existingLabelsToRemove) {
await github.rest.issues.removeLabel({
if (workflowRun.pull_requests && workflowRun.pull_requests.length > 0) {
const issue_number = workflowRun.pull_requests[0].number;
console.log(`Processing PR #${issue_number} in repository '${owner}/${repo}'.`);
const workflowRunId = context.payload.workflow_run.id;
try {
const { data: workflowRun } = await github.rest.actions.getWorkflowRun({
owner,
repo,
run_id: workflowRunId,
});
if (!workflowRun.pull_requests?.length) {
throw new Error('No associated pull requests found');
}
// Verify we're targeting the correct PR
const targetPR = workflowRun.pull_requests.find(pr =>
pr.head.sha === context.payload.workflow_run.head_sha
);
if (!targetPR) {
throw new Error('Could not find matching PR for this workflow run');
}
const issue_number = targetPR.number;
console.log(`Processing PR #${issue_number} in repository '${owner}/${repo}'.`);

Comment on lines +45 to +78
const { data: labels } = await github.rest.issues.listLabelsOnIssue({
owner,
repo,
issue_number,
name: label,
});
console.log(`Label '${label}' has been removed.`);
}

if (existingLabelsToRemove.length === 0) {
console.log('No matching labels found to remove.');
}
github.rest.issues.addLabels({

const existingLabelsToRemove = labels
.filter(label => labelsToRemove.includes(label.name))
.map(label => label.name);

for (const label of existingLabelsToRemove) {
await github.rest.issues.removeLabel({
owner,
repo,
issue_number,
name: label,
});
console.log(`Label '${label}' has been removed.`);
}

if (existingLabelsToRemove.length === 0) {
console.log('No matching labels found to remove.');
}

await github.rest.issues.addLabels({
owner,
repo,
issue_number,
labels: ['approved','auto merge']
labels: ['approved', 'auto merge'],
});
console.log(`Labels 'approved' and 'auto merge' added.`);
} else {
throw new Error('No associated pull requests found for this workflow run.');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve label management robustness and maintainability

  1. Label names are hard-coded in multiple places
  2. No validation before adding new labels
  3. Label operations could partially fail

Consider this more robust implementation:

+            // Define labels configuration at the top
+            const LABELS_CONFIG = {
+              remove: ['waiting-review', 'ready to review'],
+              add: ['approved', 'auto merge']
+            };
+
+            async function validateLabels(github, owner, repo, labels) {
+              const { data: repoLabels } = await github.rest.issues.listLabelsForRepo({
+                owner,
+                repo,
+              });
+              const validLabels = repoLabels.map(l => l.name);
+              const invalidLabels = labels.filter(l => !validLabels.includes(l));
+              if (invalidLabels.length) {
+                throw new Error(`Invalid labels: ${invalidLabels.join(', ')}`);
+              }
+            }
+
             try {
+              // Validate all labels exist in repository
+              await validateLabels(github, owner, repo, [
+                ...LABELS_CONFIG.remove,
+                ...LABELS_CONFIG.add
+              ]);
+
               const { data: labels } = await github.rest.issues.listLabelsOnIssue({
                 owner,
                 repo,
                 issue_number,
               });

               const existingLabelsToRemove = labels
                 .filter(label => labelsToRemove.includes(label.name))
                 .map(label => label.name);

-              for (const label of existingLabelsToRemove) {
-                await github.rest.issues.removeLabel({
+              // Remove labels in parallel
+              await Promise.all(existingLabelsToRemove.map(label =>
+                github.rest.issues.removeLabel({
                   owner,
                   repo,
                   issue_number,
                   name: label,
-                });
-                console.log(`Label '${label}' has been removed.`);
-              }
+                }).then(() => console.log(`Label '${label}' removed`))
+                  .catch(e => console.warn(`Failed to remove label '${label}': ${e.message}`))
+              ));

               if (existingLabelsToRemove.length === 0) {
                 console.log('No matching labels found to remove.');
               }

-              await github.rest.issues.addLabels({
+              // Add new labels
+              const result = await github.rest.issues.addLabels({
                 owner,
                 repo,
                 issue_number,
-                labels: ['approved', 'auto merge'],
+                labels: LABELS_CONFIG.add,
               });
-              console.log(`Labels 'approved' and 'auto merge' added.`);
+              console.log(`Labels added: ${LABELS_CONFIG.add.join(', ')}`);
+            } catch (error) {
+              core.setFailed(`Label management failed: ${error.message}`);
+              throw error;
             }

Consider moving the label configuration to a repository-level configuration file (e.g., .github/label-workflow.yml) for better maintainability.

📝 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
const { data: labels } = await github.rest.issues.listLabelsOnIssue({
owner,
repo,
issue_number,
name: label,
});
console.log(`Label '${label}' has been removed.`);
}
if (existingLabelsToRemove.length === 0) {
console.log('No matching labels found to remove.');
}
github.rest.issues.addLabels({
const existingLabelsToRemove = labels
.filter(label => labelsToRemove.includes(label.name))
.map(label => label.name);
for (const label of existingLabelsToRemove) {
await github.rest.issues.removeLabel({
owner,
repo,
issue_number,
name: label,
});
console.log(`Label '${label}' has been removed.`);
}
if (existingLabelsToRemove.length === 0) {
console.log('No matching labels found to remove.');
}
await github.rest.issues.addLabels({
owner,
repo,
issue_number,
labels: ['approved','auto merge']
labels: ['approved', 'auto merge'],
});
console.log(`Labels 'approved' and 'auto merge' added.`);
} else {
throw new Error('No associated pull requests found for this workflow run.');
}
// Define labels configuration at the top
const LABELS_CONFIG = {
remove: ['waiting-review', 'ready to review'],
add: ['approved', 'auto merge']
};
async function validateLabels(github, owner, repo, labels) {
const { data: repoLabels } = await github.rest.issues.listLabelsForRepo({
owner,
repo,
});
const validLabels = repoLabels.map(l => l.name);
const invalidLabels = labels.filter(l => !validLabels.includes(l));
if (invalidLabels.length) {
throw new Error(`Invalid labels: ${invalidLabels.join(', ')}`);
}
}
try {
// Validate all labels exist in repository
await validateLabels(github, owner, repo, [
...LABELS_CONFIG.remove,
...LABELS_CONFIG.add
]);
const { data: labels } = await github.rest.issues.listLabelsOnIssue({
owner,
repo,
issue_number,
});
const existingLabelsToRemove = labels
.filter(label => labelsToRemove.includes(label.name))
.map(label => label.name);
// Remove labels in parallel
await Promise.all(existingLabelsToRemove.map(label =>
github.rest.issues.removeLabel({
owner,
repo,
issue_number,
name: label,
}).then(() => console.log(`Label '${label}' removed`))
.catch(e => console.warn(`Failed to remove label '${label}': ${e.message}`))
));
if (existingLabelsToRemove.length === 0) {
console.log('No matching labels found to remove.');
}
// Add new labels
const result = await github.rest.issues.addLabels({
owner,
repo,
issue_number,
labels: LABELS_CONFIG.add,
});
console.log(`Labels added: ${LABELS_CONFIG.add.join(', ')}`);
} catch (error) {
core.setFailed(`Label management failed: ${error.message}`);
throw error;
}

@rocketmq-rust-bot rocketmq-rust-bot merged commit 4c5ae22 into main Nov 26, 2024
28 checks passed
Copy link

codecov bot commented Nov 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 20.14%. Comparing base (cb62fb1) to head (abb479e).
Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1346   +/-   ##
=======================================
  Coverage   20.14%   20.14%           
=======================================
  Files         434      434           
  Lines       54724    54724           
=======================================
  Hits        11024    11024           
  Misses      43700    43700           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@mxsm mxsm deleted the op-1345 branch November 27, 2024 04:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
AI review first Ai review pr first approved PR has approved auto merge enhancement⚡️ New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Update Github Actions CI
4 participants