Build a dependency update bot: PRs, auto-rollback, and owners.
- User
Build a dependency update bot: PRs, auto-rollback, and owners.
Assistant
Build a dependency update bot: PRs, auto-rollback, and owners.
The user wants to build a "dependency update bot." This is a software engineering task involving automation around updating libraries/packages in a codebase. The prompt specifies three key features:
CODEOWNERS file or a custom config) to request reviews or notify the right people.Intent Analysis: The user is asking for software architecture or code to automate a standard DevOps/MLOps process (dependency management). This is a common request in software development contexts. Is there anything malicious here?
There are no requests for malware, exploits, PII, hate speech, or any other prohibited content. The request is purely technical and constructive.
Safety Evaluation: The request is safe. It promotes code quality and security (by keeping dependencies up to date).
Constructing the Response: I need to provide a high-level architectural guide or a simplified implementation example (likely in Python or a shell script interacting with the GitHub API) to demonstrate how these components fit together.
Key Components to Cover:
requirements.txt or package.json, checking registries).CODEOWNERS) to assign reviewers.Structure of the Output:
PyGithub library would be the most illustrative way to show the logic.Refining the "Auto-Rollback" aspect:
Usually, bots don't "rollback" in the sense of git revert immediately. They usually just close the PR or mark it as "Failing." However, if the PR was merged and then broke main, that's a rollback. I will assume the scenario where the bot creates a PR, CI runs, and if CI fails, the bot might close the PR (preventing merge) or if the user meant "merge automatically and revert if monitoring fails," that's more complex.
Correction: Most dependency bots (like Renovate) use "Automerge" only if tests pass. If tests fail, they don't merge.
However, the prompt says "auto-rollback." This implies a scenario where:
Refining "Owners":
I'll demonstrate reading a simple OWNERS file or using the GitHub CODEOWNERS feature.
Plan:
DependencyManager class.check_updates()create_pr()monitor_ci()assign_owners()Let's write the code skeleton. I'll use Python and PyGithub.
Self-Correction during drafting: I shouldn't write a full production bot because it's too long. I should write a "Core Logic" script that demonstrates the specific requested features.
Feature 1: PRs.
Need a function update_dependency(package, version) which creates a branch, edits the file, commits, and opens a PR.
Feature 2: Owners.
Need a function get_owner(package) which looks up a config file.
Feature 3: Auto-Rollback.
Need a function check_pr_status(pr) which looks at CI status. If failed, revert_pr(pr).
Summary of Response: I will provide a Python-based architectural blueprint using the GitHub API as an example. This will cover the specific requirements: creating PRs, assigning owners based on a config, and monitoring CI for auto-rollback/revert logic. Building a custom dependency update bot (similar to Dependabot or Renovate) is a great way to automate maintenance. Below is an architectural guide and a Python-based reference implementation using the GitHub API.
requirements.txt, package.json) against the latest registry versions.OWNERS file to assign the correct reviewers.This example uses PyGithub. You will need a GitHub Personal Access Token (PAT) with repo scope.
First, define how to find owners. We will use a simple OWNERS file in the repo root.
File: OWNERS
# Format: dependency_pattern @github_username
requests @alice
numpy @bob
* @charlie # Default fallback
File: bot.py
import os
import re
import time
from github import Github, GithubException
# Configuration
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
REPO_NAME = "your-org/your-repo"
MAIN_BRANCH = "main"
OWNERS_FILE = "OWNERS"
# Initialize Github Client
g = Github(GITHUB_TOKEN)
repo = g.get_repo(REPO_NAME)
def get_owners_map():
"""Parses the OWNERS file to map dependencies to reviewers."""
try:
content = repo.get_contents(OWNERS_FILE)
lines = content.decoded_content.decode().splitlines()
owners_map = []
for line in lines:
if line.strip() and not line.startswith("#"):
pattern, user = line.split(maxsplit=1)
owners_map.append((pattern, user.strip()))
return owners_map
except GithubException:
print("No OWNERS file found.")
return []
def find_reviewer(dep_name, owners_map):
"""Finds the appropriate reviewer based on dependency name."""
for pattern, user in owners_map:
if pattern == "*" or re.match(pattern, dep_name):
return user
return None # Or a default team
def create_dependency_pr(dep_name, current_version, new_version):
"""Creates a PR for the update."""
# 1. Get current file
file_path = f"requirements.txt" # Simplified for example
contents = repo.get_contents(file_path, ref=MAIN_BRANCH)
decoded_content = contents.decoded_content.decode()
# 2. Update content
new_content = decoded_content.replace(
f"{dep_name}=={current_version}",
f"{dep_name}=={new_version}"
)
if new_content == decoded_content:
print("No changes detected.")
return None
# 3. Create Branch
branch_name = f"bot/update-{dep_name}-{new_version}"
try:
repo.create_git_ref(ref=f"refs/heads/{branch_name}", sha=repo.get_branch(MAIN_BRANCH).commit.sha)
except GithubException as e:
if "Reference already exists" in str(e):
print("Branch already exists.")
return None
raise e
# 4. Commit Change
repo.update_file(
path=file_path,
message=f"Bump {dep_name} from {current_version} to {new_version}",
content=new_content,
sha=contents.sha,
branch=branch_name
)
# 5. Create PR and Assign Owners
owners_map = get_owners_map()
reviewer = find_reviewer(dep_name, owners_map)
pr = repo.create_pull(
title=f"Bump {dep_name} to {new_version}",
body=f"Automated update for {dep_name}.\n\n**Auto-Rollback**: If CI fails within 1 hour, this will be reverted.",
head=branch_name,
base=MAIN_BRANCH
)
if reviewer:
# Note: add_to_assignees is for assignees, create_review_request is for reviewers
pr.create_review_request(reviewers=[reviewer.replace("@", "")])
print(f"PR #{pr.number} created. Assigned to {reviewer}.")
return pr
def monitor_and_rollback():
"""Checks open PRs for CI failures."""
print("Monitoring PRs for failures...")
for pr in repo.get_pulls(state="open"):
# Check if this is a bot PR (simple heuristic)
if not pr.title.startswith("Bump "):
continue
# Get the last commit status/checks
# Note: In production, use the 'Checks' API (Commit.get_check_runs)
# Here we use the older 'Status' API for simplicity
commit = repo.get_commit(pr.head.sha)
status = commit.get_combined_status()
if status.state == "failure":
print(f"CI Failed for PR #{pr.number}. Initiating Rollback...")
# Close PR
pr.edit(state="closed")
# Post comment
pr.create_issue_comment("⚠️ **Auto-Rollback Triggered**: CI checks failed. Closing PR.")
# Optional: Revert commit if it was already merged to a non-protected branch
# repo.create_commit(...)
elif status.state == "success":
# Optional: Auto-merge logic here
pass
if __name__ == "__main__":
# Example workflow
# 1. Logic to check PyPI for new versions goes here
# 2. Create PR
# create_dependency_pr("requests", "2.25.1", "2.26.0")
# 3. Monitor loop
while True:
monitor_and_rollback()
time.sleep(300) # Check every 5 minutes
Most bots allow you to define a CODEOWNERS file (standard in GitHub/GitLab) or a custom config (like renovate.json).
get_owners_map function parses a flat file.find_reviewer does a regex match. If requests is updated, it looks for a line starting with requests and assigns that user. This prevents the entire engineering team from being notified about a library they don't care about."Rollback" depends on the state of the PR:
repo.revert_commit) to create a new PR that undoes the changes.The monitor_and_rollback function acts as a watchdog. It looks at the Combined Status of the commit. If the state is failure, it triggers the closure.
In a real-world scenario, step 1 of __main__ needs intelligence.
requirements.txt, parse versions, query PyPI/NPM API for the latest version.pip's internal commands or poetry to check for updates.This bot should run as a service:
monitor_and_rollback), set up a server to listen for GitHub Webhooks (status or check_run events).
check_run completes with conclusion: failure, the webhook triggers the rollback logic immediately. This is faster and more efficient than polling.