Created
May 29, 2024 19:34
-
-
Save mjsabby/d67a5207ca7dc6d88e0da201654d0f04 to your computer and use it in GitHub Desktop.
Update ADO default branch
This file contains 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
namespace UpdateDefaultBranch | |
{ | |
using System; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Text; | |
using System.Text.Json; | |
using System.Threading.Tasks; | |
using Azure.Core; | |
using Azure.Identity; | |
internal static class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
const string organization = "YOUR_ADO_ORG"; | |
const string project = "YOUR_ADO_PROJECT"; | |
var credential = new DefaultAzureCredential(); | |
var token = await credential.GetTokenAsync(new TokenRequestContext(["499b84ac-1321-427f-aa17-267ca6975798/.default"])).ConfigureAwait(false); | |
try | |
{ | |
using (var client = new HttpClient()) | |
{ | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); | |
var reposUrl = $"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/?api-version=7.0"; | |
var reposResponse = await client.GetAsync(reposUrl).ConfigureAwait(false); | |
if (!reposResponse.IsSuccessStatusCode) | |
{ | |
Console.WriteLine($"Error: {reposResponse.ReasonPhrase}"); | |
} | |
var reposJson = JsonDocument.Parse(await reposResponse.Content.ReadAsStringAsync().ConfigureAwait(false)).RootElement; | |
var repos = reposJson.GetProperty("value").EnumerateArray(); | |
foreach (var repo in repos) | |
{ | |
var repoId = repo.GetProperty("id").GetString(); | |
var repoName = repo.GetProperty("name").GetString(); | |
var repoDetailsPatchUrl = $"https://dev.azure.com/{organization}/_apis/git/repositories/{repoId}?api-version=7.0"; | |
var patchContent = new StringContent("{\"defaultBranch\":\"refs/heads/main\"}", Encoding.UTF8, "application/json"); | |
var patchResponse = await client.PatchAsync(repoDetailsPatchUrl, patchContent).ConfigureAwait(false); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Error: {ex.Message}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment