Reputation: 21
I am performing a migration using the API from Azure DevOps Cloud to Azure DevOps Server.
When the Pull Request is created, it includes all the details except for the commit associated with the Pull Request.
I would appreciate your help in understanding how to create a pull request that includes the commit
import os
import requests
import base64
import json
# פרטי התחברות לפלטפורמה
organization = "XXXXX"
project = "XXXXXX"
pat = "XXXXXX" # Personal Access Token
url_api = "XXXXXXXX" # כתובת השרת
repositoryId = "XXXXXXX"
# הצפנת ה-PAT
encoded_pat = base64.b64encode(f":{pat}".encode()).decode()
headers = {
"Authorization": f"Basic {encoded_pat}",
"Content-Type": "application/json",
"Accept": "application/json"
}
# פונקציה לקישור PR ל-commit
def link_pr_to_commit(pull_request_id, commit_id):
try:
# URL לקישור ה-commit ל-PR
url = f"{url_api}/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests/{pull_request_id}/commits/{commit_id}?api-version=7.0"
# שליחת הבקשה
response = requests.post(
url,
headers=headers
)
if response.status_code in [200, 201]:
print(f"Commit {commit_id} linked to Pull Request {pull_request_id} successfully.")
print("Response:", response.json()) # הצגת תשובה במקרה של הצלחה
else:
print(
f"Failed to link commit {commit_id} to Pull Request {pull_request_id}. Status Code: {response.status_code}")
print("Response:", response.text)
except Exception as e:
print(f"Error: {e}")
# פונקציה ליצור Pull Request עם commit link
def create_pull_request_with_commit_link(json_file_path):
try:
# בדיקה אם הקובץ קיים
if not os.path.exists(json_file_path):
print(f"JSON file not found: {json_file_path}")
return
# טעינת תוכן JSON
with open(json_file_path, "r") as json_file:
pull_request_details = json.load(json_file)
# אם מדובר ברשימה, עובר על כל פריט
if isinstance(pull_request_details, list):
for pr_details in pull_request_details:
create_pr_and_link_commit(pr_details)
# אם מדובר באובייקט בודד, עובר על פרטי ה-PR אחד אחד
elif isinstance(pull_request_details, dict):
create_pr_and_link_commit(pull_request_details)
else:
print("Error: The JSON file does not contain a valid PR structure.")
except Exception as e:
print(f"Error: {e}")
# יצירת Pull Request
def create_pr_and_link_commit(pr_details):
# בדוק אם יש את הערכים sourceRefName ו- targetRefName
source_ref = pr_details.get("sourceRefName")
target_ref = pr_details.get("targetRefName")
# הוספת workItemRefs אם קיים
work_item_refs = pr_details.get("workItemRefs", [])
if not source_ref or not target_ref:
print("Error: sourceRefName or targetRefName is missing in the PR.")
return
# URL ליצירת Pull Request
url = f"{url_api}/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullrequests?api-version=7.0"
# יצירת Pull Request
response = requests.post(
url,
headers=headers,
json=pr_details
)
if response.status_code not in [200, 201]:
print(f"Failed to create Pull Request. Status Code: {response.status_code}")
print("Response:", response.text)
return
# משיגים את ה-Pull Request ID מהתשובה
pr_data = response.json()
pull_request_id = pr_data.get("pullRequestId")
print(f"Pull Request created successfully with ID: {pull_request_id}")
print("Response:", response.json()) # הצגת תשובה במקרה של הצלחה
# קישור ה-commit ל-PR
last_merge_commit = pr_details.get("lastMergeCommit", {}).get("commitId")
if last_merge_commit:
link_pr_to_commit(pull_request_id, last_merge_commit)
# הוספת workItemRefs בקובץ ה-PR אם ישנם
if work_item_refs:
pr_data["workItemRefs"] = work_item_refs
# הוספת שדה pullRequestId_new לאובייקט ה-PR
updated_pr_details = {
"pullRequestId": pr_details.get("pullRequestId"),
"pullRequestId_new": pull_request_id, # הוספתי את ה-id החדש
"workItemRefs": work_item_refs, # הוספתי את ה-workItemRefs
}
# עדכון ה-JSON בהתאם
update_json_file(updated_pr_details)
# עדכון קובץ ה-JSON
def update_json_file(updated_data):
try:
# קריאה לקובץ ה-JSON
with open("extracted_pull_requests.json", "r", encoding="utf-8") as json_file:
current_data = json.load(json_file)
# הוספת המידע החדש לקובץ
current_data.append(updated_data)
# שמירה בקובץ ה-JSON
with open("extracted_pull_requests.json", "w", encoding="utf-8") as json_file:
json.dump(current_data, json_file, ensure_ascii=False, indent=4)
print("JSON file updated successfully.")
except Exception as e:
print(f"Error updating JSON file: {e}")
# קריאה לפונקציה עם נתיב לקובץ JSON
json_file_path = "all_pull_requests.json" # הנתיב לקובץ ה-JSON
create_pull_request_with_commit_link(json_file_path)
is take from the json
{
"repository": {
"id": "f87dde0c-4a19-4693-81b6-44400390f5cf",
"name": "Nativ-Clearance-API",
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c",
"project": {
"id": "2379ab9f-dae0-4f6e-9f52-2e3f746d64d8",
"name": "Nativ-Clearance-API",
"description": "Nativ-Clearance-API\n powered by C# (webAPI) and Angular: \nclient folder - clearance client\nNativ-Clearance-API\nAPI folder for clearance and nativ ('api/clearance' requests for clearance and 'api/security' requests for nativ)\n\nBranches:\n- 'dev-new-api' - for fix global bugs\n- 'dev-elbit' - Elbit + Taas \n- 'dev-tomer-portal-client-api' - TomerPortalClientAPI for https://dev.azure.com/HMS-RD/TomerPortalClient \n\n- 'dev-updated' - new version, same as branch dev-new-api, but with .net 6.0\n- 'dev-foreign-affairs' - Ministry of foreign affairs (made from dev-updated + dev-elbit)",
"url": "https://dev.azure.com/HMS-RD/_apis/projects/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8",
"state": "wellFormed",
"revision": 225,
"visibility": "private",
"lastUpdateTime": "2024-07-14T11:23:47.547Z"
},
"size": 7032780,
"remoteUrl": "https://[email protected]/HMS-RD/Nativ-Clearance-API/_git/Nativ-Clearance-API",
"sshUrl": "[email protected]:v3/HMS-RD/Nativ-Clearance-API/Nativ-Clearance-API",
"webUrl": "https://dev.azure.com/HMS-RD/Nativ-Clearance-API/_git/Nativ-Clearance-API",
"isDisabled": false,
"isInMaintenance": false
},
"pullRequestId": 239,
"codeReviewId": 239,
"status": "completed",
"createdBy": {
"displayName": "Dima Nirenshteyn",
"url": "https://spsprodweu5.vssps.visualstudio.com/A899921fa-b797-4a03-a692-edb340cb2a40/_apis/Identities/0200e3f3-3bd6-6aec-902c-2338d007f115",
"_links": {
"avatar": {
"href": "https://dev.azure.com/HMS-RD/_apis/GraphProfile/MemberAvatars/aad.MDIwMGUzZjMtM2JkNi03YWVjLTkwMmMtMjMzOGQwMDdmMTE1"
}
},
"id": "0200e3f3-3bd6-6aec-902c-2338d007f115",
"uniqueName": "[email protected]",
"imageUrl": "https://dev.azure.com/HMS-RD/_api/_common/identityImage?id=0200e3f3-3bd6-6aec-902c-2338d007f115",
"descriptor": "aad.MDIwMGUzZjMtM2JkNi03YWVjLTkwMmMtMjMzOGQwMDdmMTE1"
},
"creationDate": "2024-11-10T10:39:15.7776892Z",
"closedDate": "2024-11-11T09:49:24.5736965Z",
"title": "created OrgUnit model",
"description": "- created OrgUnit and added it to personnel model\n- fixed personnel bug with mismatch between unit and site in post and put for tomer client ",
"sourceRefName": "refs/heads/dima_master",
"targetRefName": "refs/heads/master",
"mergeStatus": "succeeded",
"isDraft": false,
"mergeId": "469c0d32-848d-4af7-b8cc-dacd267e3f1a",
"lastMergeSourceCommit": {
"commitId": "6d2ad3cb11f2e19efadcfb04b5a1bfabc4340186",
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/commits/6d2ad3cb11f2e19efadcfb04b5a1bfabc4340186"
},
"lastMergeTargetCommit": {
"commitId": "fb96cd644f62020aa0f3861b809b2d7b2709412f",
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/commits/fb96cd644f62020aa0f3861b809b2d7b2709412f"
},
"lastMergeCommit": {
"commitId": "4c005203cfd334a27f9629b8eb5a599d3027cde2",
"author": {
"name": "Dima Nirenshteyn",
"email": "[email protected]",
"date": "2024-11-11T09:49:23Z"
},
"committer": {
"name": "Igor Kulyk",
"email": "[email protected]",
"date": "2024-11-11T09:49:23Z"
},
"comment": "Merged PR 239: created OrgUnit model",
"commentTruncated": true,
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/commits/4c005203cfd334a27f9629b8eb5a599d3027cde2"
},
"reviewers": [
{
"reviewerUrl": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/pullRequests/239/reviewers/5e8cb914-a7cf-61eb-a04f-a42abb248baa",
"hasDeclined": false,
"isFlagged": false,
"displayName": "Igor Kulyk",
"url": "https://spsprodweu5.vssps.visualstudio.com/A899921fa-b797-4a03-a692-edb340cb2a40/_apis/Identities/5e8cb914-a7cf-61eb-a04f-a42abb248baa",
"_links": {
"avatar": {
"href": "https://dev.azure.com/HMS-RD/_apis/GraphProfile/MemberAvatars/aad.NWU4Y2I5MTQtYTdjZi03MWViLWEwNGYtYTQyYWJiMjQ4YmFh"
}
},
"id": "40fcf470-a490-44a9-90cc-a870d07ada90",
"uniqueName": "[email protected]",
"imageUrl": "https://dev.azure.com/HMS-RD/_api/_common/identityImage?id=5e8cb914-a7cf-61eb-a04f-a42abb248baa"
}
],
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/pullRequests/239",
"completionOptions": {
"mergeCommitMessage": "Merged PR 239: created OrgUnit model\n\n- created OrgUnit and added it to personnel model\n- fixed personnel bug with mismatch between unit and site in post and put for tomer client \n\nRelated work items: #1346, #1347",
"mergeStrategy": "noFastForward",
"autoCompleteIgnoreConfigIds": []
},
"supportsIterations": true,
"completionQueueTime": "2024-11-11T09:49:23.6867969Z",
"closedBy": {
"displayName": "Igor Kulyk",
"url": "https://spsprodweu5.vssps.visualstudio.com/A899921fa-b797-4a03-a692-edb340cb2a40/_apis/Identities/5e8cb914-a7cf-61eb-a04f-a42abb248baa",
"_links": {
"avatar": {
"href": "https://dev.azure.com/HMS-RD/_apis/GraphProfile/MemberAvatars/aad.NWU4Y2I5MTQtYTdjZi03MWViLWEwNGYtYTQyYWJiMjQ4YmFh"
}
},
"id": "5e8cb914-a7cf-61eb-a04f-a42abb248baa",
"uniqueName": "[email protected]",
"imageUrl": "https://dev.azure.com/HMS-RD/_api/_common/identityImage?id=5e8cb914-a7cf-61eb-a04f-a42abb248baa",
"descriptor": "aad.NWU4Y2I5MTQtYTdjZi03MWViLWEwNGYtYTQyYWJiMjQ4YmFh"
},
"artifactId": "vstfs:///Git/PullRequestId/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8%2f0a149557-bd34-480c-b9de-37f972aca43c%2f239",
"workItemRefs": [
{
"id": 24797,
"url": "http://hms3azuremig/DefaultCollection/Nativ-Clearance-API/_workitems/24797"
},
{
"id": 24798,
"url": "http://hms3azuremig/DefaultCollection/Nativ-Clearance-API/_workitems/24798"
}
]
}
the original pull request from cloud
I am able to retrieve the commit that exists in the pull request. it's look like that
"mergeId": "469c0d32-848d-4af7-b8cc-dacd267e3f1a",
"lastMergeSourceCommit": {
"commitId": "6d2ad3cb11f2e19efadcfb04b5a1bfabc4340186",
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/commits/6d2ad3cb11f2e19efadcfb04b5a1bfabc4340186"
},
"lastMergeTargetCommit": {
"commitId": "fb96cd644f62020aa0f3861b809b2d7b2709412f",
"url": "https://dev.azure.com/HMS-RD/2379ab9f-dae0-4f6e-9f52-2e3f746d64d8/_apis/git/repositories/0a149557-bd34-480c-b9de-37f972aca43c/commits/fb96cd644f62020aa0f3861b809b2d7b2709412f"
},
"lastMergeCommit": {
"commitId": "4c005203cfd334a27f9629b8eb5a599d3027cde2",
The issue is that when I create the pull request, it is created without the commit.
this is the output of response 'mergeId': '83551b66-0a84-43fa-979c-5dc796ef34e8', 'lastMergeSourceCommit': {'commitId': 'ecd549a6783324bf8c469332f260a1ba70ae3d0d'
It is associating a different commit ID than the one I specified in the JSON.
Upvotes: 1
Views: 33
Reputation: 13944
In the response of REST API "Pull Requests - Create", the list of all commits contained in the created pull request will not be returned. However, it will return the ID of the created pull request (pullRequestId
).
So, after calling the API "Pull Requests - Create" to get the ID of the created pull request, you can call the API "Pull Request Commits - Get Pull Request Commits" to list all the commits contained in the created pull request.
Upvotes: 1