Multiple Initial Branches in Azure DevOps Repositories

413 Views Asked by At

I was wondering if it is possible to make Azure DevOps to automatically create both master and develop branches upon creating a new repository. I want both branches protected.

If project level branch policies are set up for both, but only master is created by default, when creating develop manually via git push --set-upstream origin develop I am able to push a number of commits directly on the branch, the protective policies are only applied after.

1

There are 1 best solutions below

0
Suki Ji-MSFT On

You could use REST API to automatically create a new repo with two branch created at the same time. Use API to Create a repository first, and get repository Id from the response. Use the $RepoID in next API to Create new branch.

You could create two new branches with the oldObjectId "0000000000000000000000000000000000000000". Here is the PowerShell script that works for me. Need to replace orgName, PAT, NewRepoName, ProjectID, branch name.

$url = "https://dev.azure.com/<orgName>/_apis/git/repositories?api-version=7.0"
$AzureDevOpsPAT = '<PAT>'
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$body = "{`"name`": `"<NewRepoName>`", `"project`": {`"id`": `"<ProjectID>`"}}"
$response = Invoke-RestMethod -Uri $url -Method POST -Headers $AzureDevOpsAuthenicationHeader -ContentType "application/json" -Body $body
$response | ConvertTo-Json
$RepoID = $response.id

$url2 = "https://dev.azure.com/<orgName>/_apis/git/repositories/$RepoID/pushes?api-version=5.1"
$body2 = "{`"refUpdates`": [{`"name`": `"refs/heads/<master>`", `"oldObjectId`": `"0000000000000000000000000000000000000000`"}], `"commits`": [{`"comment`": `"Initial commit.`", `"changes`": [{`"changeType`": `"add`", `"item`": {`"path`": `"/readme.md`"}, `"newContent`": {`"content`": `"My first file!`", `"contentType`": `"rawtext`"}}]}]}"
Invoke-RestMethod -Uri $url2 -Method POST -Headers $AzureDevOpsAuthenicationHeader -ContentType "application/json" -Body $body2

$body3 = "{`"refUpdates`": [{`"name`": `"refs/heads/<develop>`", `"oldObjectId`": `"0000000000000000000000000000000000000000`"}], `"commits`": [{`"comment`": `"Initial commit.`", `"changes`": [{`"changeType`": `"add`", `"item`": {`"path`": `"/readm.md`"}, `"newContent`": {`"content`": `"My first file!`", `"contentType`": `"rawtext`"}}]}]}"
Invoke-RestMethod -Uri $url2 -Method POST -Headers $AzureDevOpsAuthenicationHeader -ContentType "application/json" -Body $body3