Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
220 lines (196 loc) · 9.62 KB
/
Copy pathProgram.cs
File metadata and controls
220 lines (196 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using Mono.Options;
using Octokit;
namespace GitMergeBot
{
class Program
{
static int Main(string[] args)
{
var exeName = Assembly.GetExecutingAssembly().GetName().Name;
var options = new Options();
// default to using an environment variable, but allow an explicitly provided value to override
options.AuthToken = Environment.GetEnvironmentVariable("AUTH_CODE");
var parameters = new OptionSet()
{
$"Usage: {exeName} [options]",
"Create a pull request from the specified user and branch to another specified user and branch.",
"",
"Options:",
{ "a|auth=", "The GitHub authentication token.", value => options.AuthToken = value },
{ "r|repo=", "The name of the remote repository.", value => options.RepoName = value },
{ "s|source=", "The source branch of the merge operation.", value => options.SourceBranch = value },
{ "d|dest=", "The destination branch of the merge operation.", value => options.DestinationBranch = value },
{ "su|sourceuser=", "The user hosting the source branch of the merge operation.", value => options.SourceUser = value },
{ "du|destuser=", "The user hosting the destination branch of the merge operation.", value => options.DestinationUser = value },
{ "f|force", "Force the creation of the PR even if an open PR already exists.", value => options.Force = value != null },
{ "debug", "Print debugging information about the merge but don't actually create the pull request.", value => options.Debug = value != null },
{ "h|help", "Show this message and exit.", value => options.ShowHelp = value != null }
};
try
{
parameters.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine($"{exeName}: {e.Message}");
Console.WriteLine($"Try `{exeName} --help` for more information.");
return 1;
}
if (options.ShowHelp || !options.AreValid)
{
parameters.WriteOptionDescriptions(Console.Out);
return options.AreValid ? 0 : 1;
}
else
{
var github = new GitHubClient(new ProductHeaderValue(options.SourceUser));
github.Credentials = new Credentials(options.AuthToken);
new Program(options).MakePullRequest().GetAwaiter().GetResult();
return 0;
}
}
private Options _options;
private GitHubClient _client;
private Program(Options options)
{
_options = options;
}
public async Task MakePullRequest()
{
_client = new GitHubClient(new ProductHeaderValue(_options.SourceUser));
_client.Credentials = new Credentials(_options.AuthToken);
var remoteIntoBranch = await GetShaFromBranch(_options.DestinationUser, _options.RepoName, _options.SourceBranch);
var newBranchPrefix = $"merge-{_options.SourceBranch}-into-{_options.DestinationBranch}";
if (!_options.Force && await DoesOpenPrAlreadyExist(newBranchPrefix))
{
Console.WriteLine("Existing merge PRs exist; aboring creation. Use `--force` option to override.");
return;
}
var newBranchName = await MakePrBranch(_options.SourceUser, _options.RepoName, remoteIntoBranch, newBranchPrefix);
var pullRequest = await SubmitPullRequest(newBranchName);
// pullRequest could be null if we are running in debug mode.
// Only write the comment if the pull request can be automatically merged.
if ((pullRequest?.Mergeable).HasValue && pullRequest.Mergeable.Value)
{
// The reason for this delay is twofold:
//
// * Github has a bug in which it can "create" a pull request without that pull request
// being able to be commented on for a short period of time.
// * The Jenkins "comment watcher" has a bug whereby any comment posted shortly after
// pull-request creation is ignored.
//
// Thus, this delay sidesteps both of those bugs by asking for a VSI test 30 seconds after
// the creation of the PR. Ugly, yes; but the only *real* way to sidestep this would be to
// 1) Fix github, 2) Fix jenkins, and while those might be lofty goals, they are not in the
// scope of this PR.
await Task.Delay(TimeSpan.FromSeconds(30.0));
await _client.Issue.Comment.Create(_options.DestinationUser, _options.RepoName, pullRequest.Number, "@dotnet-bot test vsi please");
}
return;
}
/// <returns> The SHA at the tip of `branchName` in the repository `user/repo` </returns>
private async Task<string> GetShaFromBranch(string user, string repo, string branchName)
{
var refs = await _client.GitDatabase.Reference.Get(user, repo, $"heads/{branchName}");
return refs.Object.Sha;
}
/// <returns>True if an existing auto merge PR is still open.</returns>
private async Task<bool> DoesOpenPrAlreadyExist(string newBranchPrefix)
{
return (await GetExistingMergePrs(newBranchPrefix)).Count > 0;
}
/// <returns>The existing open merge PRs.</returns>
private async Task<IList<PullRequest>> GetExistingMergePrs(string newBranchPrefix)
{
var allPullRequests = await _client.PullRequest.GetAllForRepository(_options.DestinationUser, _options.RepoName);
var openPrs = allPullRequests.Where(pr => pr.Head.Ref.StartsWith(newBranchPrefix) && pr.User.Login == _options.SourceUser).ToList();
Console.WriteLine($"Found {openPrs.Count} existing open merge pull requests.");
foreach (var pr in openPrs)
{
Console.WriteLine($" Open PR: {pr.HtmlUrl}");
}
return openPrs;
}
/// <summary>
/// Creates a PR branch on the bot account with the branch head at `sha`.
/// </summary>
/// <returns> The name of the branch that was created </returns>
private async Task<string> MakePrBranch(string user, string repo, string sha, string branchNamePrefix)
{
var branchName = branchNamePrefix + DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
if (_options.Debug)
{
WriteDebugLine($"Create remote branch '{user}/{repo}/{branchName}' at {sha}");
}
else
{
var resp = await _client.Connection.Post<string>(
uri: new Uri($"https://api.github.com/repos/{user}/{repo}/git/refs"),
body: $"{{\"ref\": \"refs/heads/{branchName}\", \"sha\": \"{sha}\"}}",
accepts: "*/*",
contentType: "application/json");
var statusCode = resp.HttpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
throw new Exception($"Failed creating a new branch {branchName} on {user}/{repo} with code {statusCode}");
}
}
return branchName;
}
/// <summary>
/// Creates a pull request
/// </summary>
private async Task<PullRequest> SubmitPullRequest(string newBranchName)
{
var remoteName = $"{_options.SourceUser}-{_options.RepoName}";
var prTitle = $"Merge {_options.SourceBranch} into {_options.DestinationBranch}";
var prMessage = $@"
This is an automatically generated pull request from {_options.SourceBranch} into {_options.DestinationBranch}.
@dotnet/roslyn-infrastructure:
``` bash
git remote add {remoteName} ""https://github.com/{_options.SourceUser}/{_options.RepoName}.git""
git fetch {remoteName}
git fetch upstream
git checkout {newBranchName}
git reset --hard upstream/{_options.DestinationBranch}
git merge upstream/{_options.SourceBranch}
# Fix merge conflicts
git commit
git push {remoteName} {newBranchName} --force
```
Once the merge can be made and all the tests pass, you are free to merge the pull request.
".Trim();
if (_options.Debug)
{
WriteDebugLine($"Create PR with title: {prTitle}.");
WriteDebugLine($"Create PR with body:\r\n{prMessage}");
return null;
}
else
{
return await _client.PullRequest.Create(
owner: _options.DestinationUser,
name: _options.RepoName,
newPullRequest: new NewPullRequest(
title: prTitle,
head: $"{_options.SourceUser}:{newBranchName}",
baseRef: _options.DestinationBranch)
{
Body = prMessage
}
);
}
}
private void WriteDebugLine(string line)
{
Console.WriteLine("Debug: " + line);
}
}
}