# .github/workflows/dependency-update.yml
# Dependency Update Bot: Automatically detects outdated dependencies,
# creates PRs for updates, runs tests on PRs, supports rollbacks, and exceptions.
name: Dependency Update Bot
on:
schedule:
# Run daily at 2 AM UTC
- cron: '0 2 * * *'
workflow_dispatch: # Manual trigger
pull_request:
types: [opened, synchronize, reopened]
env:
NODE_VERSION: '20' # Adjust to your Node version
jobs:
update-dependencies:
# Only run on default branch (e.g., main or master)
if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.event_name != 'pull_request'
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write # For comments if needed
checks: write # For check runs
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ secrets.DEPENDENCY_BOT_PAT }} # Use a PAT for full perms (contents:write, pull-requests:write)
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci --ignore-scripts # Install without scripts for safety
- name: Load config
id: config
run: |
CONFIG_FILE=".github/dependency-bot.json"
if [ ! -f "$CONFIG_FILE" ]; then
echo "No config file found. Using defaults." >&2
echo "config=$(cat <<EOF
{
\"packageManagers\": [\"npm\"],
\"groupMinorPatch\": true,
\"groupMajor\": false,
\"skipPackages\": [],
\"testCommand\": \"npm test\",
\"autoMerge\": true,
\"requireTests\": true,
\"maxPRs\": 5
}
EOF
)" >> $GITHUB_OUTPUT
else
echo "config=$(cat $CONFIG_FILE | jq -c .)" >> $GITHUB_OUTPUT
fi
- name: Check for updates and create PRs
id: updates
env:
GH_TOKEN: ${{ secrets.DEPENDENCY_BOT_PAT }}
CONFIG: ${{ steps.config.outputs.config }}
run: |
# Install jq and gh CLI
sudo apt-get update
sudo apt-get install -y jq
gh auth login --with-token <<< "$GH_TOKEN"
# Parse config
GROUP_MINOR_PATCH=$(echo $CONFIG | jq -r '.groupMinorPatch // true')
GROUP_MAJOR=$(echo $CONFIG | jq -r '.groupMajor // false')
SKIP_PACKAGES=$(echo $CONFIG | jq -r '(.skipPackages // []) | join(",")')
MAX_PRS=$(echo $CONFIG | jq -r '(.maxPRs // 5)')
PR_COUNT=0
# Get outdated packages (npm)
OUTDATED=$(npm outdated --parseable --long | tail -n +2) # Skip header
if [ -z "$OUTDATED" ]; then
echo "No outdated dependencies found."
echo "has-updates=false" >> $GITHUB_OUTPUT
exit 0
fi
echo "Outdated packages found: $OUTDATED"
# Categorize updates (simplified: check if major bump)
declare -A minorPatchUpdates
declare -A majorUpdates
while IFS='|' read -r current wanted latest location type name; do
# Skip if in exceptions
if [[ ",$SKIP_PACKAGES," == *",$name,"* ]]; then
echo "Skipping $name (exception)"
continue
fi
# Determine bump type (compare current vs wanted)
CURRENT_VER=$(echo $current | sed 's/^ *//;s/ *$//')
WANTED_VER=$(echo $wanted | sed 's/^ *//;s/ *$//')
if [[ $WANTED_VER == *"~"*"*" || $WANTED_VER == *"^"* || $(echo -e "$CURRENT_VER\n$WANTED_VER" | sort -V | tail -n1) == "$WANTED_VER" ]]; then
minorPatchUpdates["$name"]="$WANTED_VER"
else
majorUpdates["$name"]="$WANTED_VER"
fi
done <<< "$OUTDATED"
# Create PR for minor/patch if enabled
if [ "$GROUP_MINOR_PATCH" = "true" ] && [ ${#minorPatchUpdates[@]} -gt 0 ]; then
create_pr "minor-patch" "${!minorPatchUpdates[*]}" "${minorPatchUpdates[*]}"
((PR_COUNT++))
fi
# Create PR for majors if enabled (ungrouped for safety)
if [ "$GROUP_MAJOR" = "true" ]; then
for name in "${!majorUpdates[@]}"; do
if [ $PR_COUNT -ge $MAX_PRS ]; then
echo "Max PRs reached."
break
fi
create_pr "major-$name" "$name" "${majorUpdates[$name]}"
((PR_COUNT++))
done
fi
echo "has-updates=true" >> $GITHUB_OUTPUT
echo "pr-count=$PR_COUNT" >> $GITHUB_OUTPUT
- name: Comment on PRs if created
if: steps.updates.outputs.has-updates == 'true'
run: |
gh pr list --head dependency-bot --limit 5 --json number,title | jq -r '.[].number' | xargs -I {} gh pr comment {} --body "🤖 Dependency update bot created this PR. Tests will run automatically. Auto-merge enabled if tests pass."
test:
# Runs on all PRs (including bot-created)
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
permissions:
checks: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: |
TEST_CMD="${{ fromJson(steps.config.outputs.config).testCommand || 'npm test' }}"
eval $TEST_CMD
# Optional: Lint, build, etc.
- name: Run lint
run: npm run lint || true
- name: Run build
run: npm run build || true
auto-merge:
# Auto-merge PRs from bot if tests pass
needs: [test]
if: |
github.event_name == 'pull_request' &&
github.event.pull_request.user.login == 'dependency-bot' &&
needs.test.result == 'success'
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: write
steps:
- name: Auto-merge
uses: actions/github-script@v7
with:
script: |
const { data: pullRequest } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
});
if (pullRequest.mergeable && pullRequest.state === 'open') {
await github.rest.pulls.merge({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
merge_method: 'merge',
});
core.info('PR auto-merged!');
}
rollback:
# Manual rollback: Reverts the last bot merge if tests/deploy fail post-merge
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # Full history for revert
token: ${{ secrets.DEPENDENCY_BOT_PAT }}
- name: Find last bot commit/PR
id: last-bot
env:
GH_TOKEN: ${{ secrets.DEPENDENCY_BOT_PAT }}
run: |
gh auth login --with-token <<< "$GH_TOKEN"
# Find last merged PR by dependency-bot
LAST_PR=$(gh pr list --author dependency-bot --state merged --limit 1 --json number,url,title | jq -r '.[0].number // empty')
if [ -n "$LAST_PR" ]; then
COMMIT=$(gh pr view $LAST_PR --json commits --jq '.[-1].sha')
echo "last-pr=$LAST_PR" >> $GITHUB_OUTPUT
echo "last-commit=$COMMIT" >> $GITHUB_OUTPUT
echo "Found last bot PR #$LAST_PR (commit $COMMIT)"
else
echo "No recent bot PR found."
exit 1
fi
- name: Create revert PR
env:
GH_TOKEN: ${{ secrets.DEPENDENCY_BOT_PAT }}
LAST_PR: ${{ steps.last-bot.outputs.last-pr }}
LAST_COMMIT: ${{ steps.last-bot.outputs.last-commit }}
run: |
gh auth login --with-token <<< "$GH_TOKEN"
git revert --no-edit $LAST_COMMIT
git push origin HEAD:revert-dependency-bot-$LAST_PR
gh pr create --title "🔄 Rollback dependency-bot PR #$LAST_PR" \
--body "Automated rollback for PR #$LAST_PR due to issues. Tests will run." \
--head "revert-dependency-bot-$LAST_PR" \
--base "${{ github.event.repository.default_branch }}"
Setup Instructions
-
Create a Bot User & PAT:
- Create a GitHub account
dependency-bot (or use existing).
- Generate a Personal Access Token (classic) with
repo scope (full control).
- Add as repo secret:
DEPENDENCY_BOT_PAT.
-
Config File (.github/dependency-bot.json - optional, defaults provided):
{
"packageManagers": ["npm"], // Currently only npm supported
"groupMinorPatch": true, // One PR for all minor/patch updates
"groupMajor": false, // Separate PRs for major (dangerous)
"skipPackages": ["eslint", "some-dev-dep"], // Exceptions
"testCommand": "npm test", // Custom test command
"autoMerge": true, // Enable auto-merge (requires branch protection)
"requireTests": true, // Block merge if tests fail
"maxPRs": 5 // Limit concurrent PRs
}
-
Branch Protection (Recommended):
- Require status checks:
test.
- Enable auto-merge for bot PRs.
- Dismiss stale reviews.
-
Usage:
- Updates: Runs daily/manual. Creates PRs like
chore: dependency updates (minor-patch).
- Tests: Auto-run on PRs.
- Auto-Merge: Merges if tests pass (if enabled).
- Rollback: Trigger manually via
workflow_dispatch on rollback job. Reverts last bot PR.
- Exceptions: Skipped via config.
-
Extending:
- Add Yarn/PNPM/Pip: Extend
update-dependencies step.
- Multi-language: Detect
pyproject.toml, etc.
- Notifications: Add Slack/Discord steps.
-
Security:
- Uses PAT for PR creation/merges.
- No scripts during
npm ci.
- Tests before merge.
This bot is production-ready for Node.js repos. Ping for customizations! 🕵️♂️