Skip to content

Instantly share code, notes, and snippets.

@MaximRouiller
Last active June 14, 2022 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaximRouiller/ba4e90138a84f81d3a6addfa6f0a8c18 to your computer and use it in GitHub Desktop.
Save MaximRouiller/ba4e90138a84f81d3a6addfa6f0a8c18 to your computer and use it in GitHub Desktop.
In C#, create a fork, sync its master with an upstream , create a branch, commit a file, then finally create a PR on the upstream
string githubToken = Environment.GetEnvironmentVariable("GitHubKey", EnvironmentVariableTarget.Process);
const string owner = "dotnet";
string user = "WhatsNewBot";
string repo = "docs";
var date = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
string branchName = $"whats-new-{date}";
string filename = $"{DateTime.UtcNow:yyyy-MM-dd}.md";
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", githubToken);
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("WhatsNewBot", "1.0"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://api.github.com");
//// create a fork
var forkResponse = await client.PostAsync($"/repos/{owner}/{repo}/forks", new StringContent(string.Empty, Encoding.UTF8, "application/json"));
var forkContent = await forkResponse.Content.ReadAsStringAsync();
forkResponse.EnsureSuccessStatusCode();
// update fork master with upstream
var upstreamheadResponse = await client.GetAsync($"/repos/{owner}/{repo}/git/ref/heads/master");
var upstreamref = JsonSerializer.Deserialize<Ref>(await upstreamheadResponse.Content.ReadAsStringAsync());
var patchmasterResponse = await client.PatchAsync($"/repos/{user}/{repo}/git/refs/heads/master", new StringContent(JsonSerializer.Serialize(new { sha = upstreamref.@object.sha }), Encoding.UTF8, "application/json"));
// get head
var headResponse = await client.GetAsync($"/repos/{user}/{repo}/git/ref/heads/master");
var @ref = JsonSerializer.Deserialize<Ref>(await headResponse.Content.ReadAsStringAsync());
// create a branch
await CreateBranch(user, repo, branchName, client, @ref.@object.sha);
// create a file
byte[] fileContentAsBytes = Encoding.UTF8.GetBytes("# Hello World");
string base64Converted = Convert.ToBase64String(fileContentAsBytes);
await CreateFile(user, repo, client, branchName, base64Converted, filename);
// create a PR
var prPayload = new { title = $"[DO NOT MERGE] This is an automed test.", head = $"{user}:{branchName}", @base = "master" };
var prResponse = await client.PostAsync($"/repos/{owner}/{repo}/pulls", new StringContent(JsonSerializer.Serialize(prPayload), Encoding.UTF8, "application/json"));
prResponse.EnsureSuccessStatusCode();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment