如何在Azure DevOps中获取Pull Request的Git Diff等效内容?
GitHub提供了形如 https://api.github.com/repos/{orgName}/{repoName}/pulls/{prId} 的接口,只需将请求头Accept设为application/vnd.github.diff,就能返回Pull Request的Git Diff内容,示例如下:
diff --git a/README b/README index c57eff55..980a0d5f 100644 --- a README +++ b/README @@ -1 +1 @@ -Hello World! \ No newline at end of file +Hello World!
问题
请问Azure DevOps是否有类似接口可获取Git Diff?若没有,有什么方法可生成该Diff?
我已尝试多种方法但未成功:比如按照社区建议调用/xxx/_apis/git/repositories/yyy/pullRequests/zzz/diffs接口,却收到错误:The controller for path '/xxx/_apis/git/repositories/yyy/pullRequests/zzz/diffs' was not found or does not implement IController.;另外微软官方REST API文档仅展示了获取变更文件列表的示例,未提供返回Diff的相关内容。
可行解决方案
1. 直接调用Git Diffs API生成标准Diff
Azure DevOps官方提供的Git Diffs API支持返回标准Git Diff格式,调用方式如下:
- 请求方法:GET
- URL:
https://dev.azure.com/{组织名}/{项目名}/_apis/git/repositories/{仓库ID}/diffs?baseVersion={基准提交SHA或分支名}&targetVersion={目标提交SHA或分支名}&api-version=7.1-preview.1
若用分支名而非SHA,需补充参数:baseVersionType=branch、targetVersionType=branch - 请求头添加:
Accept: text/plain
发送请求后,接口会直接返回和GitHub接口格式一致的Diff文本。
2. 基于PR ID获取Diff
如果需要通过PR ID来获取,可分两步操作:
- 调用PR详情接口:
https://dev.azure.com/{组织名}/{项目名}/_apis/git/repositories/{仓库ID}/pullRequests/{PR ID}?api-version=7.1-preview.1,提取PR的源分支(sourceRefName)、目标分支(targetRefName)或对应的提交SHA - 将上述提取的信息代入Git Diffs API,设置
baseVersion为目标分支/提交、targetVersion为源分支/提交,同时添加Accept: text/plain请求头,即可生成对应PR的Diff
关于接口错误说明
你之前尝试的/pullRequests/{prId}/diffs并非官方有效接口,因此会返回控制器不存在的错误,需使用上述标准的Git Diffs API路径。
内容的提问来源于stack exchange,提问作者Simon K

