Home > Back-end >  Azure CLI creating a new branch from a task
Azure CLI creating a new branch from a task

Time:07-06

I'm tring to automate task and branch creation on Azure boards- but am stuggling to programtically create a branch, once the task is created. I'm using the Azure/Azure Devops extensions in PowerShell, but can't see anything in the docs that would replicate the 'create branch' link pictured below:

create branch pic

Any help appreciated

CodePudding user response:

To programmatically create a branch, here are two methods :

Az CLI : run

az repos ref create --name refs/heads/{branch name} --object-id {Id of the object to create the reference from} --organization https://dev.azure.com/{org name} --project {project name} --repository {repos name}

Rest API :

  1. Get the repository ID in project setting >> your repo or use REST API Repositories - List and use REST API Refs - List with filter=<BranchName> to get the oldObjectId for your specific branch:

    GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter=heads/master&api-version=5.1
    
  2. Use the Initial commit (Create a new branch) to create a branch from a specific branch with the following Request Body.

{
  "refUpdates": [
    {
      "name": "refs/heads/{DefineNewBranchName}",
      "oldObjectId": "{oldObjectId}"
    }
  ],
  "commits": [
    {
      "comment": "Initial commit.",
      "changes": [
        {
          "changeType": "add",
          "item": {
            "path": "/readme.md"
          },
          "newContent": {
            "content": "My first file!",
            "contentType": "rawtext"
          }
        }
      ]
    }
  ]
}

Next, you could link the work item with the existing Branch by using the Rest API: Work Items - Update.

PATCH https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=5.1

Request Body:

[
  {
    "op": "add",
    "path": "/relations/-",
    "value": {
      "rel": "ArtifactLink",
      "url": "vstfs:///Git/Ref/{ProjectID}/{RepoId}/GB{BranchName}",
      "attributes": {
        "name": "Branch",
        "comment": "test link branch"
      }
    }
  }
]

Here is a similar ticket about your question.

  • Related