如何使用 Azure DevOps REST 计算所有拉取请求 API
How to count all Pull Requests with Azure DevOps REST API
我正在尝试使用 Azure DevOps REST API 来计算我们存储库中的拉取请求总数,并最终希望使用它从 git 中获取一些更有用的信息数据。
我曾尝试使用对存储库的 GET 请求来 return 拉取请求列表,但 Azure API 将每个请求的响应限制为 101。您可以使用 $top 和 $skip 来更改 returned 的响应数量和哪些响应,并使用 $count 来计算 returned 的响应。然而,这仍然将结果限制在绝对最大值的 1,000 和 returns PR 中包含的整个数据集,当我真的只需要知道其中的实例数时,我不知道需要对其数据进行 return 编辑,因为这会在大型回购协议中产生巨大的结果。
这是我正在使用的 GET 请求:
https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}/pullrequests?$top=999&$count=true&searchCriteria.status=all&api-version=5.0
这里是我用来 return 项目计数的测试脚本,使用 Postman
var body = JSON.parse(responseBody);
tests[body.value.length + " Pull Requests in this Repository" ] = true;
此 return 的响应计数为 101,如预期但不理想。非常感谢任何提示和技巧!
The Azure API limits the responses to 101 per request
这是设计的默认限制。由于您可能会在单个 API 请求中检索数千条记录,并且它分页后每次调用仅提供一定数量的结果。因此,您需要使用 top
和 skip
对其余部分进行分页。
此外,如果您根本不想查看其返回的数据,因为这会在回购协议中产生巨大的结果,这里有一个脚本可以帮助您直接实现计数:
var body = JSON.parse(responseBody);
tests["Count: " + body.value.length] = true;
将此脚本添加到测试中,执行api后,结果会显示在测试结果中,参考下图:
这时候就不会被大数据的结果所困扰了
希望能对您有所帮助。
powershell简单示例代码:
function GetPullRequest{
param(
[string]$org,
[string]$project,
[string]$repo,
[string]$token
)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "test",$token)))
$count=0
$i=0
do{
$uri="https://dev.azure.com/$org/$project/_apis/git/repositories/$repo/pullRequests?api-version=5.0&`$top=100&`$skip=$i"
$i+=100
Write-Output $uri
$result= Invoke-RestMethod -Method Get -Uri $Uri -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $bodyJson
Write-Output $result.Count
$count+=$result.Count
if($result.Count-lt 100){
break;
}
}while($true)
write-output "Finish. Total Pull Request count: $count";
}
GetPullRequest -org "your organization" -project "your teamproject" -repo "your repository" -token "your personal access token"
我在 python 中提供了一个答案,因为我相信这对某些人来说可能比 powershell 或 postman 脚本更有用,因为这是我最终在最终实现中使用的。
希望对其他人有所帮助!
首先是代码...
def count_PRs():
skip = 0
count = 0
while True:
# Retrieve next Pull Requests based on pager value, or all remaining if less than value
req_url=("https://%s/%s//%s/_apis/git/repositories/%s/pullrequests?$top=%s&$skip=%s&searchCriteria.status=all&api-version=%s" % (instance, organization, project, repository, pager, skip, api_version))
response = requests.get(req_url, auth=(username, password)).json()
# If no data returned, break out of loop, otherwise count items returned
if len(response["value"]) == 0:
break
else:
count += len(response["value"])
skip += pager
return count
现在解释一下这里发生的事情,这样你就可以理解它,而不是盲目地使用它...
首先,请求 URL 是使用您之前应该定义的变量创建的。
req_url=("https://%s/%s//%s/_apis/git/repositories/%s/pullrequests?$top=%s&$skip=%s&searchCriteria.status=all&api-version=%s" % (instance, organization, project, repository, pager, skip, api_version))
它们是:实例、组织、项目、存储库、寻呼机、跳过,api_version
实例、组织、项目和存储库基于您的用例,因此我无法在这方面为您提供帮助。
"pager" 值是每次调用 returned 的项目数,根据我的使用,我注意到 Azure API 目前将此上限设置为 1,000,但这可能会改变将来,如果我注意到它,我会尝试更新它。
"skip"值表示已经统计了哪些pull requests,所以它从0开始,然后通过循环每次迭代增加pager值,这样就不会统计相同的PR倍数次。
下一行发送请求并将回复保存到响应变量:
response = requests.get(req_url, auth=(username, password)).json()
存在包含用户名和密码的身份验证header。我之前已经通过 Azure DevOps 页面设置了一个个人访问令牌,PAT 是您应该在此处用作密码的方式,这比尝试使用 OAuth2.0 进行身份验证要容易得多,我建议您先完成此操作。
此部分检查您是否仍在响应中收到新的拉取请求,如果没有,它会跳出 while 循环以 return 计数。
if len(response["value"]) == 0:
break
如果您确实收到回复,此部分会计算拉取请求并将其添加到计数中,然后在进入下一次迭代之前递增 skip 变量
else:
count += len(response["value"])
skip += pager
我花了很长时间才弄明白,我真的希望它能在未来对你有所帮助,如果是这样,请考虑投票!大家有什么问题可以在评论里留言,我会尽快帮助大家的。
以下代码可能会有所帮助。
在这里,我正在提取针对项目的所有拉取请求。输出将被推送到 excel。请关注内联评论
#+++Declaring all the parameters+++
Param(
[string]$collectionurl = "https://dev.azure.com/<organizationname>",
[string]$project = "<Projectname>",
[string]$token = "<PAT>",
[string]$Filename = '<local path>'
)
#++PassingToken as Base 64++
$auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$token)))
#++Generating Pull Request Base URL++
$pullRequestURL = "$collectionurl/$project/_apis/git/pullrequests?searchCriteria.status=all&&api-version=5.1"
#++Passing Respone in variable++
$pullRequest = (Invoke-RestMethod -Uri $pullRequestURL -Method Get -Headers @{Authorization=("Basic {0}" -f $auth)}).value
#++Displaying result on screen( this step can be avoided )++
Write-Output $pullRequest
#++Counting Active vs Completed Request++
Write-host "Count of active pull request:" ($pullRequest | where({$_.status -eq 'active'})).count
Write-host "Count of completed pull request:" ($pullRequest | where({$_.status -eq 'completed'})).count
#++Temporary Object to store varaible values"
$output = @()
Write-Output $output
#++Extracting Values and storing in Object++
foreach ($request in $pullRequest) {
$customObject = new-object PSObject -property @{
"RepositoryName" = $request.repository.name
"Status" = $request.status
"PullRequestId" = $request.pullRequestId
"SourceBranch" = $request.sourceRefName
"TargetBranch" = $request.targetRefName
"CreatedBy" = $request.createdBy.displayName
"Reviewers" = $request.reviewers.displayName
"CreatedDate" = $request.creationDate
"ClosedDate" = $request.closedDate
"MergeStrategy" = $request.completionOptions.mergeStrategy
}
$output += $customObject
}
#++Generating excel out of Object++
$output | Select `
RepositoryName,
Status,
PullRequestId,
SourceBranch,
TargetBranch,
CreatedBy,
Reviewers,
CreatedDate,
ClosedDate,
MergeStrategy | export-csv -Path $Filename -NoTypeInformation
我正在尝试使用 Azure DevOps REST API 来计算我们存储库中的拉取请求总数,并最终希望使用它从 git 中获取一些更有用的信息数据。
我曾尝试使用对存储库的 GET 请求来 return 拉取请求列表,但 Azure API 将每个请求的响应限制为 101。您可以使用 $top 和 $skip 来更改 returned 的响应数量和哪些响应,并使用 $count 来计算 returned 的响应。然而,这仍然将结果限制在绝对最大值的 1,000 和 returns PR 中包含的整个数据集,当我真的只需要知道其中的实例数时,我不知道需要对其数据进行 return 编辑,因为这会在大型回购协议中产生巨大的结果。
这是我正在使用的 GET 请求:
https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}/pullrequests?$top=999&$count=true&searchCriteria.status=all&api-version=5.0
这里是我用来 return 项目计数的测试脚本,使用 Postman
var body = JSON.parse(responseBody);
tests[body.value.length + " Pull Requests in this Repository" ] = true;
此 return 的响应计数为 101,如预期但不理想。非常感谢任何提示和技巧!
The Azure API limits the responses to 101 per request
这是设计的默认限制。由于您可能会在单个 API 请求中检索数千条记录,并且它分页后每次调用仅提供一定数量的结果。因此,您需要使用 top
和 skip
对其余部分进行分页。
此外,如果您根本不想查看其返回的数据,因为这会在回购协议中产生巨大的结果,这里有一个脚本可以帮助您直接实现计数:
var body = JSON.parse(responseBody);
tests["Count: " + body.value.length] = true;
将此脚本添加到测试中,执行api后,结果会显示在测试结果中,参考下图:
这时候就不会被大数据的结果所困扰了
希望能对您有所帮助。
powershell简单示例代码:
function GetPullRequest{
param(
[string]$org,
[string]$project,
[string]$repo,
[string]$token
)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "test",$token)))
$count=0
$i=0
do{
$uri="https://dev.azure.com/$org/$project/_apis/git/repositories/$repo/pullRequests?api-version=5.0&`$top=100&`$skip=$i"
$i+=100
Write-Output $uri
$result= Invoke-RestMethod -Method Get -Uri $Uri -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $bodyJson
Write-Output $result.Count
$count+=$result.Count
if($result.Count-lt 100){
break;
}
}while($true)
write-output "Finish. Total Pull Request count: $count";
}
GetPullRequest -org "your organization" -project "your teamproject" -repo "your repository" -token "your personal access token"
我在 python 中提供了一个答案,因为我相信这对某些人来说可能比 powershell 或 postman 脚本更有用,因为这是我最终在最终实现中使用的。
希望对其他人有所帮助!
首先是代码...
def count_PRs():
skip = 0
count = 0
while True:
# Retrieve next Pull Requests based on pager value, or all remaining if less than value
req_url=("https://%s/%s//%s/_apis/git/repositories/%s/pullrequests?$top=%s&$skip=%s&searchCriteria.status=all&api-version=%s" % (instance, organization, project, repository, pager, skip, api_version))
response = requests.get(req_url, auth=(username, password)).json()
# If no data returned, break out of loop, otherwise count items returned
if len(response["value"]) == 0:
break
else:
count += len(response["value"])
skip += pager
return count
现在解释一下这里发生的事情,这样你就可以理解它,而不是盲目地使用它...
首先,请求 URL 是使用您之前应该定义的变量创建的。
req_url=("https://%s/%s//%s/_apis/git/repositories/%s/pullrequests?$top=%s&$skip=%s&searchCriteria.status=all&api-version=%s" % (instance, organization, project, repository, pager, skip, api_version))
它们是:实例、组织、项目、存储库、寻呼机、跳过,api_version
实例、组织、项目和存储库基于您的用例,因此我无法在这方面为您提供帮助。
"pager" 值是每次调用 returned 的项目数,根据我的使用,我注意到 Azure API 目前将此上限设置为 1,000,但这可能会改变将来,如果我注意到它,我会尝试更新它。
"skip"值表示已经统计了哪些pull requests,所以它从0开始,然后通过循环每次迭代增加pager值,这样就不会统计相同的PR倍数次。
下一行发送请求并将回复保存到响应变量:
response = requests.get(req_url, auth=(username, password)).json()
存在包含用户名和密码的身份验证header。我之前已经通过 Azure DevOps 页面设置了一个个人访问令牌,PAT 是您应该在此处用作密码的方式,这比尝试使用 OAuth2.0 进行身份验证要容易得多,我建议您先完成此操作。
此部分检查您是否仍在响应中收到新的拉取请求,如果没有,它会跳出 while 循环以 return 计数。
if len(response["value"]) == 0:
break
如果您确实收到回复,此部分会计算拉取请求并将其添加到计数中,然后在进入下一次迭代之前递增 skip 变量
else:
count += len(response["value"])
skip += pager
我花了很长时间才弄明白,我真的希望它能在未来对你有所帮助,如果是这样,请考虑投票!大家有什么问题可以在评论里留言,我会尽快帮助大家的。
以下代码可能会有所帮助。 在这里,我正在提取针对项目的所有拉取请求。输出将被推送到 excel。请关注内联评论
#+++Declaring all the parameters+++
Param(
[string]$collectionurl = "https://dev.azure.com/<organizationname>",
[string]$project = "<Projectname>",
[string]$token = "<PAT>",
[string]$Filename = '<local path>'
)
#++PassingToken as Base 64++
$auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$token)))
#++Generating Pull Request Base URL++
$pullRequestURL = "$collectionurl/$project/_apis/git/pullrequests?searchCriteria.status=all&&api-version=5.1"
#++Passing Respone in variable++
$pullRequest = (Invoke-RestMethod -Uri $pullRequestURL -Method Get -Headers @{Authorization=("Basic {0}" -f $auth)}).value
#++Displaying result on screen( this step can be avoided )++
Write-Output $pullRequest
#++Counting Active vs Completed Request++
Write-host "Count of active pull request:" ($pullRequest | where({$_.status -eq 'active'})).count
Write-host "Count of completed pull request:" ($pullRequest | where({$_.status -eq 'completed'})).count
#++Temporary Object to store varaible values"
$output = @()
Write-Output $output
#++Extracting Values and storing in Object++
foreach ($request in $pullRequest) {
$customObject = new-object PSObject -property @{
"RepositoryName" = $request.repository.name
"Status" = $request.status
"PullRequestId" = $request.pullRequestId
"SourceBranch" = $request.sourceRefName
"TargetBranch" = $request.targetRefName
"CreatedBy" = $request.createdBy.displayName
"Reviewers" = $request.reviewers.displayName
"CreatedDate" = $request.creationDate
"ClosedDate" = $request.closedDate
"MergeStrategy" = $request.completionOptions.mergeStrategy
}
$output += $customObject
}
#++Generating excel out of Object++
$output | Select `
RepositoryName,
Status,
PullRequestId,
SourceBranch,
TargetBranch,
CreatedBy,
Reviewers,
CreatedDate,
ClosedDate,
MergeStrategy | export-csv -Path $Filename -NoTypeInformation