如何用PowerShell脚本在Azure DevOps中创建Fork仓库以自动化PR流程?
使用PowerShell脚本创建Fork仓库并自动化PR流程
我正在编写将NuGet包内容添加至仓库的逻辑,希望实现向原仓库提交代码并创建Pull Request的自动化流程,该流程会在Pipeline中运行。想请教如何通过PowerShell脚本创建Fork仓库?我已经能通过Rest API从Fork创建Pull Request,代码如下:
$pullRequestUri = "$orgUri/_apis/git/repositories/$repositoryId/pullrequests?api-version=6.0" $body = @{ "sourceRefName" = "refs/heads/main" "targetRefName" = "refs/heads/main" "forkSource" = @{ "repository" = @{ "id" = $forkRepositoryId } } "title" = "Add $PackageName package" "isDraft" = $True }
创建Fork仓库的PowerShell实现
你可以通过调用Azure DevOps的REST API来创建Fork,以下是具体的PowerShell脚本示例:
# 配置基础参数 $orgUri = "https://dev.azure.com/你的组织名" $sourceRepoId = "原仓库的ID" $targetProjectId = "存放Fork仓库的目标项目ID" $forkRepoName = "自定义的Fork仓库名称" $pat = "你的个人访问令牌(PAT)" # 构建创建Fork的API请求地址 $forkApiUri = "$orgUri/_apis/git/repositories/$sourceRepoId/forks?api-version=6.0" # 构造请求体 $forkRequestBody = @{ name = $forkRepoName project = @{ id = $targetProjectId } } | ConvertTo-Json # 发送POST请求创建Fork $forkResult = Invoke-RestMethod -Uri $forkApiUri ` -Method Post ` -Headers @{Authorization = "Basic $([System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("`:$pat")))"} ` -Body $forkRequestBody ` -ContentType "application/json" # 提取创建后的Fork仓库ID,用于后续PR创建 $forkRepositoryId = $forkResult.id
注意事项
- 确保你的PAT拥有Git仓库读写的权限,权限不足会导致请求失败
- 在Pipeline中运行时,建议将PAT存储为安全变量,避免硬编码在脚本中
- 创建Fork成功后,直接将获取到的
$forkRepositoryId传入你已有的PR创建代码即可完成流程串联
内容的提问来源于stack exchange,提问作者Dzmitry Chamiareuski
相关产品推荐
相关产品推荐

