Created
October 21, 2023 17:57
-
-
Save piense/83efc8ee24a0741db2543dea9444a43d to your computer and use it in GitHub Desktop.
Azure Devops Push
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import json | |
import urllib | |
import requests | |
org_name = "your org" | |
project_name = "your project" | |
repo_name = "test" | |
PAT = "a_pat" | |
branch = "master" | |
new_file = { | |
"name": "test_file2.txt", | |
"contents": "A new file" | |
} | |
def azdo_request(urlAddress, payload = "", method="GET", contentType="application/json"): | |
headers = {} | |
headers['Content-type'] = contentType | |
headers['Authorization'] = b'Basic ' + base64.b64encode((":" + PAT).encode('utf-8')) | |
data = json.dumps(payload) | |
data = data.encode("utf-8") | |
if payload == "" and method == "GET": | |
req = urllib.request.Request(urlAddress, headers = headers) | |
else: | |
req = urllib.request.Request(urlAddress, data = data, headers = headers, method = method) | |
response = urllib.request.urlopen(req) | |
if response.code == 204 or response.code == 201: | |
return {} | |
if response.code != 200: | |
raise Exception("Bad response code: " + str(response.code)) | |
data = response.read() | |
encoding = response.info().get_content_charset('utf-8') | |
returnData = json.loads(data.decode(encoding)) | |
return returnData | |
repo_id = azdo_request(f"https://dev.azure.com/{org_name}/{project_name}/_apis/git/repositories/{repo_name}?api-version=4.1")["id"] | |
refs = azdo_request(f"https://dev.azure.com/{org_name}/{project_name}/_apis/git/repositories/{repo_id}/refs?api-version=5.0")['value'] | |
repoRefName = f"refs/heads/{branch.lower()}" | |
for refs in refs: | |
if repoRefName in refs['name'].lower(): | |
repoRefId = refs['objectId'] | |
break | |
if len(repoRefId) == 0: | |
print("ERROR: Couldn't find ref Id") | |
exit | |
content = { "refUpdates" : [ { "name" : repoRefName, "oldObjectId": repoRefId}], | |
"commits" : [ { | |
"comment" : "Another commit", | |
"changes" : [ | |
{ | |
"changeType": "add", | |
"item":{ | |
"path": new_file["name"] | |
}, | |
"newContent" : { | |
"content": new_file["contents"], | |
"contentType": "rawtext" | |
} | |
} | |
]}]} | |
azdo_request(f'https://dev.azure.com/{org_name}/_apis/git/repositories/{repo_id}/pushes?api-version=5.0',content, method="POST") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment