Skip to content

Instantly share code, notes, and snippets.

@piense
Created October 21, 2023 17:57
Show Gist options
  • Save piense/83efc8ee24a0741db2543dea9444a43d to your computer and use it in GitHub Desktop.
Save piense/83efc8ee24a0741db2543dea9444a43d to your computer and use it in GitHub Desktop.
Azure Devops Push
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