如何用atlassian-python-api获取Bitbucket PR的代码变更行数?
使用atlassian-python-api获取Bitbucket PR的代码变更行数
atlassian-python-api确实没有直接封装获取PR代码变更行数的函数,但可以通过调用Bitbucket REST API的底层端点来实现,下面是两种可行方案:
方案一:利用Diffstat端点直接获取统计数据
Bitbucket的REST API提供了diffstat端点,返回每个文件的增减行数统计,无需手动解析完整diff,效率更高:
from atlassian import Bitbucket # 初始化Bitbucket客户端 bitbucket = Bitbucket( url="https://your-bitbucket-instance-url", username="your-username", password="your-app-password" # 或个人访问令牌 ) def get_pr_loc_changes(project_key, repo_slug, pr_id): # 构造diffstat API路径 diffstat_endpoint = f"/rest/api/1.0/projects/{project_key}/repos/{repo_slug}/pull-requests/{pr_id}/diffstat" # 调用API获取统计数据 diffstat_data = bitbucket.get(diffstat_endpoint) total_added = 0 total_removed = 0 # 累加所有文件的行数变更 for file_stat in diffstat_data: total_added += file_stat.get("linesAdded", 0) total_removed += file_stat.get("linesRemoved", 0) # 返回统计结果,可根据需求调整字段 return { "lines_added": total_added, "lines_removed": total_removed, "total_loc_changed": total_added + total_removed } # 示例调用 project_key = "PROJ" repo_slug = "my-repo" pr_id = 123 loc_stats = get_pr_loc_changes(project_key, repo_slug, pr_id) # 更新你的自定义PullRequest对象 # custom_pr.loc_changed = loc_stats["total_loc_changed"]
方案二:获取完整Diff并手动解析行数
如果需要更精细的控制(比如排除特定文件),可以获取PR的完整diff文本,再逐行解析增减行数:
def calculate_loc_from_diff(project_key, repo_slug, pr_id): diff_endpoint = f"/rest/api/1.0/projects/{project_key}/repos/{repo_slug}/pull-requests/{pr_id}/diff" # 请求纯文本格式的diff内容 diff_content = bitbucket.get(diff_endpoint, headers={"Accept": "text/plain"}) added_lines = 0 removed_lines = 0 for line in diff_content.splitlines(): # 排除diff头部的文件标识行(+++/---开头) if line.startswith("+") and not line.startswith("+++"): added_lines += 1 elif line.startswith("-") and not line.startswith("---"): removed_lines += 1 return { "lines_added": added_lines, "lines_removed": removed_lines, "total_loc_changed": added_lines + removed_lines }
说明
atlassian-python-api的核心优势是封装了常用操作,但对于这类细分需求,直接调用Bitbucket原生API端点是最灵活的方式。库提供的get()方法可以直接访问任意API路径,只需按照Bitbucket API文档构造正确的端点即可。
内容的提问来源于stack exchange,提问作者Bisrat
相关产品推荐
相关产品推荐

