Compare commits

..

1 Commits

Author SHA1 Message Date
b5e4210e6e fix: cleanup-duplicate-prs.sh — fix AUTH bug, add stale branch cleanup (#1453)
Some checks failed
CI / test (pull_request) Failing after 1m24s
Review Approval Gate / verify-review (pull_request) Failing after 9s
CI / validate (pull_request) Failing after 1m22s
Bug fix:
- Line 38: AUTH variable was corrupted ('***'), now correctly reads
  'Authorization: token '

New feature: stale branch cleanup
- Added cleanup of branches from closed (unmerged) PRs
- Added cleanup of branches from merged PRs (where auto-delete failed)
- Both respect --dry-run / --close mode

Actual cleanup performed:
- Deleted whip/1127-1776128804 (closed PR #1409)
- Deleted whip/1127-1776127532 (merged PR #1403)
Both were stale branches from the duplicate #1127 PRs.
2026-04-14 22:05:18 -04:00
3 changed files with 46 additions and 148 deletions

View File

@@ -1,24 +0,0 @@
# PR Backlog Report — Timmy_Foundation/timmy-config
Generated: 2026-04-14 23:23:33
## Summary
- **Total Open PRs**: 50
- **Stale (>30 days)**: 0
- **Recent (<7 days)**: 50
## Recommendations
### Immediate Actions
1. **Review stale PRs**: 0 PRs are >30 days old
2. **Close duplicates**: Check for duplicate PRs on same issues
3. **Assign reviewers**: Ensure each PR has a reviewer
### Process Improvements
1. **Set SLAs**: Review within 48 hours, merge within 7 days
2. **Weekly cleanup**: Run this analyzer weekly
3. **Automate**: Add CI checks to prevent backlog
## Stale PRs (>30 days)

View File

@@ -35,7 +35,7 @@ for arg in "$@"; do
done
API="$GITEA_URL/api/v1"
AUTH="token $GITEA_TOKEN"
AUTH="Authorization: token $GITEA_TOKEN"
log() { echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"; }
@@ -148,6 +148,51 @@ if [ "$DUPLICATES_FOUND" -eq 0 ]; then
log "No duplicate PRs found"
fi
# ─── Additional cleanup: Stale branches from closed/merged PRs ───
log "Checking for stale branches from closed/merged PRs..."
ALL_PRS=$(curl -s -H "$AUTH" "$API/repos/$REPO/pulls?state=closed&limit=100")
STALE_BRANCHES_DELETED=0
if [ -n "$ALL_PRS" ] && [ "$ALL_PRS" != "null" ]; then
echo "$ALL_PRS" | jq -r '.[] | select(.merged == false) | "\(.number)\t(.head.ref)\t\(.state)"' | while IFS=$'\t' read -r pr_num pr_branch pr_state; do
[ -z "$pr_branch" ] && continue
# Skip if branch doesn't exist
branch_check=$(curl -s -o /dev/null -w "%{http_code}" -H "$AUTH" "$API/repos/$REPO/branches/$pr_branch")
if [ "$branch_check" != "200" ]; then
continue
fi
log "Stale branch from closed PR #$pr_num: $pr_branch"
if [ "$DRY_RUN" = "true" ]; then
log "DRY RUN: Would delete branch $pr_branch"
else
curl -s -X DELETE -H "$AUTH" "$API/repos/$REPO/branches/$pr_branch" > /dev/null
log "Deleted branch $pr_branch"
STALE_BRANCHES_DELETED=$((STALE_BRANCHES_DELETED + 1))
fi
done
fi
# ─── Additional cleanup: Stale branches from merged PRs ───
log "Checking for stale branches from merged PRs..."
if [ -n "$ALL_PRS" ] && [ "$ALL_PRS" != "null" ]; then
echo "$ALL_PRS" | jq -r '.[] | select(.merged == true) | "\(.number)\t\(.head.ref)"' | while IFS=$'\t' read -r pr_num pr_branch; do
[ -z "$pr_branch" ] && continue
branch_check=$(curl -s -o /dev/null -w "%{http_code}" -H "$AUTH" "$API/repos/$REPO/branches/$pr_branch")
if [ "$branch_check" != "200" ]; then
continue
fi
log "Stale branch from merged PR #$pr_num: $pr_branch"
if [ "$DRY_RUN" = "true" ]; then
log "DRY RUN: Would delete branch $pr_branch"
else
curl -s -X DELETE -H "$AUTH" "$API/repos/$REPO/branches/$pr_branch" > /dev/null
log "Deleted branch $pr_branch"
fi
done
fi
# ─── Additional cleanup: Stale PRs ────────────────────────
# Check for PRs older than 30 days with no activity
log "Checking for stale PRs (older than 30 days)..."

View File

@@ -1,123 +0,0 @@
#!/usr/bin/env python3
"""
PR Backlog Analyzer for timmy-config
Analyzes open PRs and provides recommendations for cleanup.
Issue: #1470
"""
import json
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
def get_open_prs(repo: str, token: str) -> list:
"""Get all open PRs from a repository."""
result = subprocess.run([
"curl", "-s", "-H", f"Authorization: token {token}",
f"https://forge.alexanderwhitestone.com/api/v1/repos/{repo}/pulls?state=open&limit=100"
], capture_output=True, text=True)
if result.returncode != 0:
print(f"Error fetching PRs: {result.stderr}")
return []
return json.loads(result.stdout)
def analyze_pr(pr: dict) -> dict:
"""Analyze a single PR."""
created = datetime.fromisoformat(pr['created_at'].replace('Z', '+00:00'))
age_days = (datetime.now(created.tzinfo) - created).days
labels = [l['name'] for l in pr.get('labels', [])]
return {
'number': pr['number'],
'title': pr['title'],
'branch': pr['head']['ref'],
'created': pr['created_at'],
'age_days': age_days,
'user': pr['user']['login'],
'labels': labels,
'url': pr['html_url'],
}
def generate_report(repo: str, prs: list) -> str:
"""Generate a markdown report."""
stale = [p for p in prs if p['age_days'] > 30]
recent = [p for p in prs if p['age_days'] <= 7]
report = f"""# PR Backlog Report — {repo}
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
## Summary
- **Total Open PRs**: {len(prs)}
- **Stale (>30 days)**: {len(stale)}
- **Recent (<7 days)**: {len(recent)}
## Recommendations
### Immediate Actions
1. **Review stale PRs**: {len(stale)} PRs are >30 days old
2. **Close duplicates**: Check for duplicate PRs on same issues
3. **Assign reviewers**: Ensure each PR has a reviewer
### Process Improvements
1. **Set SLAs**: Review within 48 hours, merge within 7 days
2. **Weekly cleanup**: Run this analyzer weekly
3. **Automate**: Add CI checks to prevent backlog
## Stale PRs (>30 days)
"""
for pr in sorted(stale, key=lambda x: x['age_days'], reverse=True):
report += f"- **#{pr['number']}**: {pr['title']}\n"
report += f" - Age: {pr['age_days']} days\n"
report += f" - Author: {pr['user']}\n"
report += f" - URL: {pr['url']}\n\n"
return report
def main():
"""Main function."""
token_path = Path.home() / '.config' / 'gitea' / 'token'
if not token_path.exists():
print("Error: Gitea token not found")
sys.exit(1)
token = token_path.read_text().strip()
repo = "Timmy_Foundation/timmy-config"
print(f"Fetching PRs for {repo}...")
prs = get_open_prs(repo, token)
if not prs:
print("No open PRs found")
return
print(f"Found {len(prs)} open PRs")
analyzed = [analyze_pr(pr) for pr in prs]
report = generate_report(repo, analyzed)
output_dir = Path("reports")
output_dir.mkdir(exist_ok=True)
report_file = output_dir / f"pr-backlog-{datetime.now().strftime('%Y%m%d')}.md"
report_file.write_text(report)
print(f"Report saved to: {report_file}")
print(f"Total PRs: {len(prs)}")
print(f"Stale (>30 days): {len([p for p in analyzed if p['age_days'] > 30])}")
if __name__ == "__main__":
main()