-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathGitHubStorage.cs
More file actions
427 lines (370 loc) · 15.3 KB
/
Copy pathGitHubStorage.cs
File metadata and controls
427 lines (370 loc) · 15.3 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
using Octokit;
using Platform.Exceptions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Octokit.Internal;
using Platform.Threading;
using File = Storage.Local.File;
namespace Storage.Remote.GitHub
{
/// <summary>
/// <para>
/// Represents the git hub storage.
/// </para>
/// <para></para>
/// </summary>
public class GitHubStorage
{
public Octokit.GraphQL.ProductHeaderValue ProductInformation;
public Octokit.GraphQL.Connection GraphQlClient;
/// <summary>
/// <para>
/// The client.
/// </para>
/// <para></para>
/// </summary>
public readonly GitHubClient Client;
/// <summary>
/// <para>
/// The owner.
/// </para>
/// <para></para>
/// </summary>
public readonly string Owner;
public const int DependabotId = 49699333;
/// <summary>
/// <para>
/// Gets the minimum interaction interval value.
/// </para>
/// <para></para>
/// </summary>
public TimeSpan MinimumInteractionInterval { get; }
private DateTimeOffset lastIssue = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(14));
/// <summary>
/// <para>
/// Initializes a new <see cref="GitHubStorage"/> instance.
/// </para>
/// <para></para>
/// </summary>
/// <param name="owner">
/// <para>A owner.</para>
/// <para></para>
/// </param>
/// <param name="token">
/// <para>A token.</para>
/// <para></para>
/// </param>
/// <param name="name">
/// <para>A name.</para>
/// <para></para>
/// </param>
public GitHubStorage(string owner, string token, string name)
{
Owner = owner;
var credentials = new Credentials(token);
Client = new GitHubClient(new ProductHeaderValue(name))
{
Credentials = credentials
};
MinimumInteractionInterval = new(0, 0, 0, 0, 1200);
ProductInformation = new Octokit.GraphQL.ProductHeaderValue("LinksPlatform", "1.0.0");
GraphQlClient = new Octokit.GraphQL.Connection(ProductInformation, token);
}
/// <summary>
/// <para>
/// Gets the issues.
/// </para>
/// <para></para>
/// </summary>
/// <returns>
/// <para>A read only list of issue</para>
/// <para></para>
/// </returns>
public IReadOnlyList<Issue> GetIssues()
{
IssueRequest request = new()
{
Filter = IssueFilter.All,
State = ItemStateFilter.Open,
Since = lastIssue
};
var issues = Client.Issue.GetAllForCurrent(request).Result;
if (issues.Count != 0)
{
lastIssue = issues.Max(x => x.CreatedAt);
return issues;
}
return new List<Issue>();
}
public Task<IReadOnlyList<GitHubCommit>> GetCommits(long repositoryId, CommitRequest commitRequest) => Client.Repository.Commit.GetAll(repositoryId, commitRequest);
public IReadOnlyList<User> GetOrganizationMembers(string organization)
{
return Client.Organization.Member.GetAll(organization).Result;
}
/// <summary>
/// <para>
/// Gets the pull requests using the specified owner.
/// </para>
/// <para></para>
/// </summary>
/// <param name="owner">
/// <para>The owner.</para>
/// <para></para>
/// </param>
/// <param name="reposiroty">
/// <para>The repository.</para>
/// <para></para>
/// </param>
/// <returns>
/// <para>A read only list of pull request</para>
/// <para></para>
/// </returns>
public IReadOnlyList<PullRequest> GetPullRequests(string owner, string reposiroty) => Client.PullRequest.GetAllForRepository(owner, reposiroty).AwaitResult();
public Task<IReadOnlyList<PullRequest>> GetPullRequests(long repositoryId) => Client.PullRequest.GetAllForRepository(repositoryId);
public Task<IReadOnlyList<PullRequest>> GetPullRequests(long repositoryId, ApiOptions apiOptions) => Client.PullRequest.GetAllForRepository(repositoryId, apiOptions);
public PullRequest GetPullRequest(int repositoryId, int number) => Client.PullRequest.Get(repositoryId, number).AwaitResult();
/// <summary>
/// <para>
/// Gets the issues using the specified owner.
/// </para>
/// <para></para>
/// </summary>
/// <param name="owner">
/// <para>The owner.</para>
/// <para></para>
/// </param>
/// <param name="reposiroty">
/// <para>The repository.</para>
/// <para></para>
/// </param>
/// <returns>
/// <para>A read only list of issue</para>
/// <para></para>
/// </returns>
public IReadOnlyList<Issue> GetIssues(string owner, string reposiroty)
{
var date = DateTime.Today.AddMonths(-1);
return Client.Issue.GetAllForRepository(owner, reposiroty, new RepositoryIssueRequest() { Since = date }).Result;
}
/// <summary>
/// <para>
/// Creates the or update file using the specified repository.
/// </para>
/// <para></para>
/// </summary>
/// <param name="filePath">
/// <para>The file path.</para>
/// <para></para>
/// </param>
/// <param name="fileContent">
/// <para>The file content.</para>
/// <para></para>
/// </param>
/// <param name="repository">
/// <para>The repository.</para>
/// <para></para>
/// </param>
/// <param name="branchName">
/// <para>The branch.</para>
/// <para></para>
/// </param>
/// <param name="commitMessage">
/// <para>The commit message.</para>
/// <para></para>
/// </param>
public async Task<RepositoryContentChangeSet> CreateOrUpdateFile(string fileContent, Repository repository, string branchName, string filePath, string commitMessage)
{
var repositoryContent = Client.Repository.Content;
var branch = await Client.Repository.Branch.Get(repository.Id, branchName);
var tree = await Client.Git.Tree.GetRecursive(repository.Id, branch.Commit.Sha);
var isFileExists = false;
var fileToUpdateSha = "";
foreach (var treeItem in tree.Tree)
{
if (treeItem.Path == filePath)
{
isFileExists = true;
fileToUpdateSha = treeItem.Sha;
}
}
if (isFileExists)
{
var fileToUpdate = repositoryContent.GetAllContentsByRef(repository.Id, filePath, branchName);
fileToUpdate.Wait();
return await repositoryContent.UpdateFile(repository.Id, filePath, new UpdateFileRequest(commitMessage, fileContent, fileToUpdateSha));
}
else
{
return await repositoryContent.CreateFile(repository.Id, filePath, new CreateFileRequest(commitMessage, fileContent, branchName));
}
}
/// <summary>
/// <para>
/// Closes the issue using the specified issue.
/// </para>
/// <para></para>
/// </summary>
/// <param name="issue">
/// <para>The issue.</para>
/// <para></para>
/// </param>
public void CloseIssue(Issue issue)
{
IssueUpdate issueUpdate = new()
{
State = ItemState.Closed
};
Client.Issue.Update(issue.Repository.Owner.Login, issue.Repository.Name, issue.Number, issueUpdate);
}
#region Repository
public async Task<List<int>> GetAuthorIdsOfCommits(long repositoryId, CommitRequest commitRequest)
{
var commits = await Client.Repository.Commit.GetAll(repositoryId, commitRequest);
return commits.Select(commit => commit.Author.Id).ToList();
}
public Task<IReadOnlyList<Repository>> GetAllRepositories(string ownerName) => Client.Repository.GetAllForOrg(ownerName);
#region Content
// public async Task<RepositoryContentChangeSet> CreateOrUpdateFile(string fileContent, string filePath, Repository repository, string branchName, string commitMessage)
// {
// try
// {
// var fileToUpdateContents = Client.Repository.Content.GetAllContents(repository.Id, filePath).Result;
// }
// catch (NotFoundException e)
// {
// return await Client.Repository.Content.UpdateFile(repository.Id, filePath, new UpdateFileRequest(commitMessage, fileContent, fileToUpdateContents.First().Sha, branchName));
// }
// }
#endregion
#endregion
#region Migrations
public IReadOnlyList<Migration> GetAllMigrations(string organizationName) => Client.Migration.Migrations.GetAll(organizationName).AwaitResult();
public void CreateMigration(string organizationName, params string[] repositoryNames)
{
CreateMigration(organizationName, new ReadOnlyCollection<string>(repositoryNames));
}
public Task<Migration?> CreateMigration(string organizationName, IReadOnlyList<string> repositoryNames)
{
var startMigrationRequest = new StartMigrationRequest(repositoryNames); ;
return Client.Migration.Migrations.Start(organizationName, startMigrationRequest);
}
public Task SaveMigrationArchive(string organizationName, int migrationId, string filePath) => new Task(() =>
{
var migrationArchive = Client.Migration.Migrations.GetArchive(organizationName, migrationId).AwaitResult();
System.IO.File.WriteAllBytes(filePath, migrationArchive);
});
#endregion
#region Reference
public Task<Reference> CreateReference(long repositoryId, NewReference reference)
{
return Client.Git.Reference.Create(repositoryId, reference);
}
#endregion
#region Issue
public Task<IssueComment> CreateIssueComment(long repositoryId, int issueNumber, string message)
{
return Client.Issue.Comment.Create(repositoryId, issueNumber, message);
}
public async Task<Issue> SendPrivateMessage(string userLogin, string subject, string message, string botCommunicationRepoName = "bot-communications")
{
try
{
var repo = await Client.Repository.Get(Owner, botCommunicationRepoName);
var issueTitle = $"Message for @{userLogin}: {subject}";
var issueBody = $"@{userLogin}\n\n{message}";
var newIssue = new NewIssue(issueTitle)
{
Body = issueBody
};
return await Client.Issue.Create(repo.Id, newIssue);
}
catch (NotFoundException)
{
throw new InvalidOperationException($"Bot communication repository '{botCommunicationRepoName}' not found. Please create this repository first.");
}
}
public async Task<IssueComment> CreateMinimalIssueComment(long repositoryId, int issueNumber, string userLogin, string subject, Issue privateMessageIssue)
{
var message = $"@{userLogin} Bot message sent privately: [{subject}]({privateMessageIssue.HtmlUrl})";
return await Client.Issue.Comment.Create(repositoryId, issueNumber, message);
}
#endregion
#region Branch
public Task<Branch> GetBranch(long repositoryId, string branchName)
{
return Client.Repository.Branch.Get(repositoryId, branchName);
}
#endregion
#region Workflow
public void RemoveLanguageSpecificWorkflowIfFolderDoesNotExist(long repositoryId, string branchName, List<string> languages)
{
var branch = Client.Repository.Branch.Get(repositoryId, branchName).Result;
var treeResponse = Client.Git.Tree.GetRecursive(repositoryId, branch.Commit.Sha).Result;
List<string> languageWithoutFolderList = languages;
Dictionary<string, string?> languageWorkflowShaDictionary = new ();
foreach (var treeItem in treeResponse.Tree)
{
for (var i = 0; i < languageWithoutFolderList.Count; i++)
{
var languageWithoutFolder = languageWithoutFolderList[i];
var hasFolder = treeItem.Path.StartsWith($"{languageWithoutFolder}/");
if (hasFolder)
{
languageWithoutFolderList.Remove(languageWithoutFolder);
--i;
continue;
}
var workflowPath = $".github/workflows/{languageWithoutFolder}.yml";
if (treeItem.Path == workflowPath)
{
languageWorkflowShaDictionary[languageWithoutFolder] = treeItem.Sha;
continue;
}
}
}
foreach (var languageWithoutFolder in languageWithoutFolderList)
{
languageWorkflowShaDictionary.TryGetValue(languageWithoutFolder, out var workflowSha);
if (workflowSha == null)
{
continue;
}
var blob = Client.Git.Blob.Get(repositoryId, languageWorkflowShaDictionary[languageWithoutFolder]).Result;
Client.Repository.Content.DeleteFile(repositoryId, $".github/workflows/{languageWithoutFolder}.yml", new DeleteFileRequest("Remove redundand workflow cause of its folder lack.", blob.Sha)).Wait();
}
}
#endregion
#region Organization
#region Member
public async Task<List<User>> GetAllOrganizationMembers(string organizationName)
{
var allMembers = new List<User>();
var options = new ApiOptions
{
// Here you can specify the number of items per page (up to 100).
// You may want to tweak this to balance between the number of requests and the memory consumption.
PageSize = 100,
PageCount = 1,
StartPage = 1,
};
while (true)
{
var pageOfUsers = await Client.Organization.Member.GetAll(organizationName, OrganizationMembersRole.All, options);
if (!pageOfUsers.Any())
{
break;
}
allMembers.AddRange(pageOfUsers);
options.StartPage++;
}
return allMembers;
}
#endregion
#endregion
}
}