You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bitbucket API统计组织内所有用户的PR评论数?

How to Count PR Comments Across All Repos in a Bitbucket Organization

Got it, let's walk through exactly how to build this productivity metric using Bitbucket's REST API. I've tackled similar tasks before, so here's a practical, step-by-step approach that should get you the data you need:

1. First, Set Up Your API Access

Before diving into requests, you'll need valid credentials to access Bitbucket's API:

  • For Bitbucket Cloud: Create an App Password in your Bitbucket account settings. Make sure to grant these permissions:
    • repository:read (to list repos)
    • pullrequest:read (to fetch PRs)
    • comment:read (to access PR comments)
  • For Bitbucket Server/Data Center: Generate a personal access token with equivalent read permissions for repos, PRs, and comments.

2. Step 1: Fetch All Repositories in Your Organization

First, you need to get a list of every repo in your workspace. Use this API endpoint:

GET https://api.bitbucket.org/2.0/workspaces/{WORKSPACE_SLUG}/repositories
  • Replace {WORKSPACE_SLUG} with your organization's Bitbucket workspace name.
  • Handle Pagination: Bitbucket returns 10 repos per page by default. Check the next field in the response; if it exists, make another request to that URL to get the next set of repos.

Example curl command (replace placeholders):

curl -u YOUR_USERNAME:YOUR_APP_PASSWORD "https://api.bitbucket.org/2.0/workspaces/your-workspace/repositories?pagelen=100"

Using pagelen=100 reduces the number of pagination requests needed.

3. Step 2: Fetch All Pull Requests for Each Repository

For every repo you retrieved in step 1, fetch all its pull requests (including closed ones if you want full history):

GET https://api.bitbucket.org/2.0/repositories/{WORKSPACE_SLUG}/{REPO_SLUG}/pullrequests?state=all
  • {REPO_SLUG} is the repo's short name from the repo list response.
  • Again, handle pagination here—PRs can be numerous, so follow the next links until there are no more pages.

4. Step 3: Fetch Comments for Each PR & Count Them Per User

For each PR, call the comments endpoint to get all user comments (including inline comments on code):

GET https://api.bitbucket.org/2.0/repositories/{WORKSPACE_SLUG}/{REPO_SLUG}/pullrequests/{PR_ID}/comments
  • {PR_ID} is the numeric ID of the pull request from the PR list response.

As you fetch comments, keep a running tally (like a dictionary) where the key is the user's username or uuid (use uuid to avoid conflicts with identical usernames) and the value is the total number of comments they've made across all PRs.

Example Python Script (Simplified)

Here's a quick script to automate this process (requires the requests library):

import requests
from collections import defaultdict
import time

WORKSPACE = "your-workspace-slug"
USERNAME = "your-bitbucket-username"
APP_PASSWORD = "your-app-password"

# Initialize comment count dictionary
comment_counts = defaultdict(int)
user_details = {}  # To map UUIDs to readable names

# Step 1: Get all repos
repo_url = f"https://api.bitbucket.org/2.0/workspaces/{WORKSPACE}/repositories?pagelen=100"
while repo_url:
    response = requests.get(repo_url, auth=(USERNAME, APP_PASSWORD))
    response.raise_for_status()
    repos = response.json()["values"]
    
    for repo in repos:
        repo_slug = repo["slug"]
        # Step 2: Get all PRs for this repo
        pr_url = f"https://api.bitbucket.org/2.0/repositories/{WORKSPACE}/{repo_slug}/pullrequests?state=all&pagelen=100"
        while pr_url:
            pr_response = requests.get(pr_url, auth=(USERNAME, APP_PASSWORD))
            pr_response.raise_for_status()
            prs = pr_response.json()["values"]
            
            for pr in prs:
                pr_id = pr["id"]
                # Step 3: Get all comments for this PR
                comment_url = f"https://api.bitbucket.org/2.0/repositories/{WORKSPACE}/{repo_slug}/pullrequests/{pr_id}/comments?pagelen=100"
                while comment_url:
                    comment_response = requests.get(comment_url, auth=(USERNAME, APP_PASSWORD))
                    comment_response.raise_for_status()
                    comments = comment_response.json()["values"]
                    
                    for comment in comments:
                        user = comment["user"]
                        user_uuid = user["uuid"]
                        comment_counts[user_uuid] += 1
                        # Store user details if not already saved
                        if user_uuid not in user_details:
                            user_details[user_uuid] = user["display_name"]
                    
                    # Check for next page of comments
                    comment_url = comment_response.json().get("next")
                    time.sleep(0.5)  # Avoid hitting rate limits
            
            # Check for next page of PRs
            pr_url = pr_response.json().get("next")
            time.sleep(0.5)
    
    # Check for next page of repos
    repo_url = response.json().get("next")
    time.sleep(0.5)

# Print readable results
print("PR Comment Counts Per User:")
for user_uuid, count in comment_counts.items():
    print(f"- {user_details[user_uuid]}: {count} comments")

Key Notes to Avoid Headaches

  • Rate Limiting: Bitbucket Cloud allows 1000 requests per hour for authenticated users. Adding small delays between requests (like time.sleep(0.5)) helps avoid 429 "too many requests" errors.
  • User Identification: Using uuid instead of username is safer because usernames can change, but the script above maps UUIDs to display names for readability.
  • Bitbucket Server Differences: If you're using Server/Data Center, the API endpoints follow a different structure (e.g., http://your-bitbucket-server/rest/api/1.0/workspaces/{WORKSPACE}/repos), but the core flow—list repos → list PRs → list comments → count—stays the same.

内容的提问来源于stack exchange,提问作者Sandeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:29:21