anjalib
anjalib

Reputation: 41

Azure devops Python API - how to check if there is already an existing commit or PR on a file?

I am building automation for people in our team to upload certain files, then after some conditions are fulfilled they can click on a create PR button to create a pull request. However we often get this:

Error: AzureDevOpsServiceError at line 54 of /tmp/8dd54eaca7647d4/app.py: Multiple operations were attempted on file 'src/xyz.yml' within the same request. Only a single operation may be applied to each file within the same commit. Parameter name: newPush

Which means a PR or commit already existed on the file. Is there an ADO API endpoint that can check this for us? Whether a commit or PR exists for the given file?

Upvotes: 0

Views: 33

Answers (1)

Suresh Chikkam
Suresh Chikkam

Reputation: 3448

The above issues arrive when multiple operations on the same file within the same request and also check that commit or PR does not already exist for the file you are trying to update before you proceed.

As I mentioned in the comment use the Get Commits API to check if a commit already exists for a particular file in a repository.

GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits?searchCriteria.itemVersion.version={commitId}&$top=10&api-version=6.0

Here is the py code to check for commits:

import requests

organization = "your_organization"
project = "your_project"
repository_id = "your_repository_id"
file_path = "src/xyz.yml"  # Specify the file path you're checking

url = f"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository_id}/commits?searchCriteria.itemVersion.version={file_path}&$top=10&api-version=6.0"
headers = {
    "Authorization": "Basic <Your_Personal_Access_Token>"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    commits = response.json()
    if commits['count'] > 0:
        print(f"Commits found for {file_path}")
    else:
        print(f"No commits found for {file_path}")
else:
    print(f"Error: {response.status_code}, {response.text}")
  • Use the Get Pull Requests API to check if any pull requests are associated with the file:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests?searchCriteria.itemVersion.version={file_path}&api-version=6.0

Note: Azure DevOps restricts you from making multiple changes to the same file within a single commit or PR request.

As @Alvin Zhao - MSFT mentioned If you push changes to the same file across different branches (which are later merged through separate PRs), Azure DevOps might detect that you are attempting to modify the file multiple times in the same operation, it leads to the error.

If you are working with multiple branches, try to merge them locally first and then push a single PR.

Upvotes: 0

Related Questions