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

feat: mastodonbot #185

Merged
merged 10 commits into from
Jan 16, 2025
Merged

feat: mastodonbot #185

merged 10 commits into from
Jan 16, 2025

Conversation

cmeesters
Copy link
Member

@cmeesters cmeesters commented Jan 16, 2025

like #183 - there is a mismatch in the allowed commands

Summary by CodeRabbit

  • New Features

    • Added an automated script to post release announcements to Mastodon
    • Implemented a GitHub Actions workflow to trigger Mastodon announcements after pull request merges
  • Chores

    • Updated .gitignore to include new file exclusion patterns
    • Refined release announcement process with improved error handling and messaging

Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Walkthrough

This pull request introduces a new Bash script and updates a GitHub Actions workflow to automate Mastodon release announcements. The post_to_mastodon.sh script handles version extraction, message creation, and API posting, while the corresponding workflow file has been modified to use this script. Additionally, the .gitignore file was updated to include poetry.lock and ignore .aider* files.

Changes

File Change Summary
.github/workflows/post_to_mastodon.sh New Bash script for automated Mastodon release announcements, with version extraction, message creation, and API posting logic
.github/workflows/post_to_mastodon.yml Updated workflow to use new post_to_mastodon.sh script instead of inline curl command
.gitignore Removed #poetry.lock comment, added .aider* to ignored files

Sequence Diagram

sequenceDiagram
    participant PR as Pull Request
    participant Workflow as GitHub Actions
    participant Script as post_to_mastodon.sh
    participant Mastodon as Mastodon API

    PR ->> Workflow: Trigger on PR close
    Workflow ->> Script: Execute with PR details
    Script ->> Script: Extract version
    Script ->> Script: Validate version
    Script ->> Script: Create message
    Script ->> Mastodon: POST announcement
    Mastodon -->> Script: Response
    Script ->> Workflow: Return status
Loading

Possibly related PRs

Poem

🐰 A rabbit's release tale, oh so bright!
Mastodon posts now take flight
Version numbers dance with glee
Automation sets our messages free
Hop, hop, hooray for code delight! 🚀


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4d218d3 and a9358e0.

📒 Files selected for processing (3)
  • .github/workflows/post_to_mastodon.sh (1 hunks)
  • .github/workflows/post_to_mastodon.yml (1 hunks)
  • .gitignore (2 hunks)
🔇 Additional comments (1)
.gitignore (1)

102-102: LGTM! Changes align with best practices.

  • Including poetry.lock in version control ensures reproducible builds
  • Ignoring .aider* files is appropriate for tool-specific temporary files

Also applies to: 162-162


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.

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
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 4

🧹 Nitpick comments (1)
.github/workflows/post_to_mastodon.sh (1)

12-34: Extract repository URL as variable and encode URLs.

The script has hardcoded repository URLs and lacks URL encoding for special characters in URLs.

Improve message construction:

+# Repository details
+REPO_URL="https://github.com/snakemake/snakemake-executor-plugin-slurm"
+
 # Construct changelog URL with proper quoting
-changelog="https://github.com/snakemake/snakemake-executor-plugin-slurm/releases/tag/v${version}"
+changelog="${REPO_URL}/releases/tag/v${version}"
+
+# URL encode the changelog URL
+changelog=$(echo "$changelog" | sed 's/ /%20/g' | sed 's/\[/%5B/g' | sed 's/\]/%5D/g')

 read -d '\n' message << EndOfText
...
-If you find any issues, please report them on https://github.com/snakemake/snakemake-executor-plugin-slurm/issues
+If you find any issues, please report them on ${REPO_URL}/issues
🛑 Comments failed to post (4)
.github/workflows/post_to_mastodon.yml (1)

24-27: ⚠️ Potential issue

Add repository checkout and script permissions.

The workflow needs two additional steps before executing the script:

  1. Checkout the repository to access the script
  2. Make the script executable

Add these steps before the current "Post to Mastodon" step:

    steps:
+     - uses: actions/checkout@v4
+     - name: Make script executable
+       run: chmod +x .github/workflows/post_to_mastodon.sh
      - name: Post to Mastodon
        uses: nick-fields/retry@v2

Also, update the script path to be relative to the repository root:

-           ./post_to_mastodon.sh
+           .github/workflows/post_to_mastodon.sh

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

.github/workflows/post_to_mastodon.sh (3)

36-46: 🛠️ Refactor suggestion

Enhance validation checks.

Add validation for token format and empty message content.

Add these validations:

 # Validate message length
+if [ -z "$message" ]; then
+    echo "Error: Message content is empty"
+    exit 1
+fi
+
 if [ ${#message} -gt $MAX_TOOT_LENGTH ]; then
     echo "Error: Message exceeds Fediscience's character limit"
     exit 1
 fi

 # Validate Mastodon token
 if [ -z "${MASTODONBOT}" ]; then
     echo "Error: MASTODONBOT secret is not set"
     exit 1
 fi
+# Validate token format (should be 40+ characters)
+if ! [[ $MASTODONBOT =~ ^[a-zA-Z0-9_-]{40,}$ ]]; then
+    echo "Error: MASTODONBOT token has invalid format"
+    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.

# Validate message length
if [ -z "$message" ]; then
    echo "Error: Message content is empty"
    exit 1
fi

if [ ${#message} -gt $MAX_TOOT_LENGTH ]; then
    echo "Error: Message exceeds Fediscience's character limit"
    exit 1
fi

# Validate Mastodon token
if [ -z "${MASTODONBOT}" ]; then
    echo "Error: MASTODONBOT secret is not set"
    exit 1
fi
# Validate token format (should be 40+ characters)
if ! [[ $MASTODONBOT =~ ^[a-zA-Z0-9_-]{40,}$ ]]; then
    echo "Error: MASTODONBOT token has invalid format"
    exit 1
fi

3-10: 🛠️ Refactor suggestion

Improve version extraction robustness.

The current version extraction is fragile as it:

  1. Assumes the version is the last word in the PR title
  2. Doesn't handle PR titles with 'v' prefix (e.g., "Release v1.2.3")

Improve version extraction:

-# Extract version from PR title passed as environment variable
-version="${PR_TITLE##* }"
+# Extract version from PR title, handling optional 'v' prefix
+if [[ $PR_TITLE =~ v?([0-9]+\.[0-9]+\.[0-9]+) ]]; then
+    version="${BASH_REMATCH[1]}"
+else
+    echo "Error: Could not find version in PR title: $PR_TITLE"
+    exit 1
+fi

-# Validate version format
-if ! [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
-    echo "Error: Invalid version format in PR title: $version"
-    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.

# Extract version from PR title, handling optional 'v' prefix
if [[ $PR_TITLE =~ v?([0-9]+\.[0-9]+\.[0-9]+) ]]; then
    version="${BASH_REMATCH[1]}"
else
    echo "Error: Could not find version in PR title: $PR_TITLE"
    exit 1
fi

48-63: 🛠️ Refactor suggestion

Enhance API request handling.

Add timeout, retry mechanism, and rate limit handling to the API request.

Improve API request handling:

+# Function to handle API request with retries
+post_to_mastodon() {
+    local retries=3
+    local wait_time=5
+    
+    for ((i=1; i<=retries; i++)); do
+        response=$(curl -s -w "\n%{http_code}" \
+            --connect-timeout 10 \
+            --max-time 20 \
+            -X POST \
+            -H "Authorization: Bearer ${MASTODONBOT}" \
+            -F "status=${message}" \
+            "https://fediscience.org/api/v1/statuses")
+        
+        status_code=$(echo "$response" | tail -n1)
+        response_body=$(echo "$response" | sed '$d')
+        
+        case $status_code in
+            200) return 0 ;;  # Success
+            429) # Rate limit
+                wait_time=$((wait_time * 2))
+                echo "Rate limited. Waiting ${wait_time}s before retry $i of $retries"
+                sleep $wait_time
+                continue
+                ;;
+            5*) # Server error, retry
+                echo "Server error (HTTP ${status_code}). Retrying in ${wait_time}s ($i of $retries)"
+                sleep $wait_time
+                continue
+                ;;
+            *) # Other errors
+                echo "Error: Failed to post to Mastodon (HTTP ${status_code})"
+                echo "Response: ${response_body}"
+                return 1
+                ;;
+        esac
+    done
+    
+    echo "Error: Failed to post after $retries retries"
+    return 1
+}
+
-# Send post to Mastodon with proper quoting and error handling
-response=$(curl -s -w "\n%{http_code}" -X POST \
-    -H "Authorization: Bearer ${MASTODONBOT}" \
-    -F "status=${message}" \
-    "https://fediscience.org/api/v1/statuses")
-
-status_code=$(echo "$response" | tail -n1)
-response_body=$(echo "$response" | sed '$d')
-
-if [ "$status_code" -ne 200 ]; then
-    echo "Error: Failed to post to Mastodon (HTTP ${status_code})"
-    echo "Response: ${response_body}"
-    exit 1
+# Post to Mastodon
+if ! post_to_mastodon; then
+    exit 1
 fi

 echo "Successfully posted to Mastodon"
📝 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.

# Function to handle API request with retries
post_to_mastodon() {
    local retries=3
    local wait_time=5
    
    for ((i=1; i<=retries; i++)); do
        response=$(curl -s -w "\n%{http_code}" \
            --connect-timeout 10 \
            --max-time 20 \
            -X POST \
            -H "Authorization: Bearer ${MASTODONBOT}" \
            -F "status=${message}" \
            "https://fediscience.org/api/v1/statuses")
        
        status_code=$(echo "$response" | tail -n1)
        response_body=$(echo "$response" | sed '$d')
        
        case $status_code in
            200) return 0 ;;  # Success
            429) # Rate limit
                wait_time=$((wait_time * 2))
                echo "Rate limited. Waiting ${wait_time}s before retry $i of $retries"
                sleep $wait_time
                continue
                ;;
            5*) # Server error, retry
                echo "Server error (HTTP ${status_code}). Retrying in ${wait_time}s ($i of $retries)"
                sleep $wait_time
                continue
                ;;
            *) # Other errors
                echo "Error: Failed to post to Mastodon (HTTP ${status_code})"
                echo "Response: ${response_body}"
                return 1
                ;;
        esac
    done
    
    echo "Error: Failed to post after $retries retries"
    return 1
}

# Post to Mastodon
if ! post_to_mastodon; then
    exit 1
fi

echo "Successfully posted to Mastodon"

@cmeesters cmeesters merged commit 4051273 into main Jan 16, 2025
5 checks passed
@cmeesters cmeesters deleted the feat/Mastodonbot branch January 16, 2025 17:24
cmeesters pushed a commit that referenced this pull request Jan 16, 2025
🤖 I have created a release *beep* *boop*
---


##
[0.14.0](v0.13.0...v0.14.0)
(2025-01-16)


### Features

* mastodonbot
([#185](#185))
([4051273](4051273))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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