-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGitHub.php
More file actions
687 lines (572 loc) · 23.5 KB
/
GitHub.php
File metadata and controls
687 lines (572 loc) · 23.5 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
<?php
namespace Utopia\VCS\Adapter\Git;
use Ahc\Jwt\JWT;
use Exception;
use Utopia\Cache\Cache;
use Utopia\VCS\Adapter\Git;
use Utopia\VCS\Exception\RepositoryNotFound;
class GitHub extends Git
{
public const EVENT_PUSH = 'push';
public const EVENT_PULL_REQUEST = 'pull_request';
public const EVENT_INSTALLATION = 'installation';
public const CONTENTS_DIRECTORY = 'dir';
public const CONTENTS_FILE = 'file';
protected string $endpoint = 'https://api.github.com';
protected string $accessToken;
protected string $jwtToken;
protected string $installationId;
protected Cache $cache;
/**
* Global Headers
*
* @var array<string, string>
*/
protected $headers = ['content-type' => 'application/json'];
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* Get Adapter Name
*
* @return string
*/
public function getName(): string
{
return 'github';
}
/**
* GitHub Initialisation with access token generation.
*/
public function initializeVariables(string $installationId, string $privateKey, string $githubAppId): void
{
$this->installationId = $installationId;
$response = $this->cache->load($installationId, 60 * 9); // 10 minutes, but 1 minute earlier to be safe
if ($response == false) {
$this->generateAccessToken($privateKey, $githubAppId);
$tokens = \json_encode([
'jwtToken' => $this->jwtToken,
'accessToken' => $this->accessToken,
]) ?: '{}';
$this->cache->save($installationId, $tokens);
} else {
$parsed = \json_decode($response, true);
$this->jwtToken = $parsed['jwtToken'] ?? '';
$this->accessToken = $parsed['accessToken'] ?? '';
}
}
/**
* Create new repository
*
* @return array<mixed> Details of new repository
*/
public function createRepository(string $owner, string $repositoryName, bool $private): array
{
$url = "/orgs/{$owner}/repos";
$response = $this->call(self::METHOD_POST, $url, ['Authorization' => "Bearer $this->accessToken"], [
'name' => $repositoryName,
'private' => $private,
]);
return $response['body'] ?? [];
}
/**
* Search repositories for GitHub App
* @param string $owner Name of user or org
* @param int $page page number
* @param int $per_page number of results per page
* @param string $search Query to be searched to filter repo names
* @return array<mixed>
*
* @throws Exception
*/
public function searchRepositories(string $owner, int $page, int $per_page, string $search = ''): array
{
$url = '/search/repositories';
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'q' => "{$search} user:{$owner} fork:true",
'per_page' => $per_page,
'sort' => 'updated'
]);
if (!isset($response['body']['items'])) {
throw new Exception("Repositories list missing in the response.");
}
return $response['body']['items'];
}
/**
* Get GitHub repository
*
* @return array<mixed>
*
* @throws Exception
*/
public function getRepository(string $owner, string $repositoryName): array
{
$url = "/repos/{$owner}/{$repositoryName}";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
return $response['body'] ?? [];
}
/**
* Fetches repository name using repository id
*
* @param string $repositoryId ID of GitHub Repository
* @return string name of GitHub repository
*/
public function getRepositoryName(string $repositoryId): string
{
$url = "/repositories/$repositoryId";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if (!isset($response['body']['name'])) {
throw new RepositoryNotFound("Repository not found");
}
return $response['body']['name'];
}
/**
* Get repository tree
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @param string $branch Name of the branch
* @param bool $recursive Whether to fetch the tree recursively
* @return array<string> List of files in the repository
*/
public function getRepositoryTree(string $owner, string $repositoryName, string $branch, bool $recursive = false): array
{
// if recursive is true, add optional query param to url
$url = "/repos/$owner/$repositoryName/git/trees/$branch" . ($recursive ? '?recursive=1' : '');
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if ($response['headers']['status-code'] == 404) {
return [];
}
return array_column($response['body']['tree'], 'path');
}
/**
* List repositories accessible to the GitHub app
*
* @param int $page page number
* @param int $per_page number of results per page
* @return array<mixed> List of repositories
*/
public function listRepositoriesForGitHubApp(int $page, int $per_page): array
{
$url = '/installation/repositories';
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'per_page' => $per_page,
'page' => $page,
]);
if (!isset($response['body']['repositories'])) {
throw new Exception("Repositories list missing in the response.");
}
return $response['body']['repositories'];
}
/**
* Get repository languages
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @return array<mixed> List of repository languages
*/
public function listRepositoryLanguages(string $owner, string $repositoryName): array
{
$url = "/repos/$owner/$repositoryName/languages";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if (isset($response['body'])) {
return array_keys($response['body']);
}
return [];
}
/**
* List contents of the specified root directory.
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @param string $path Path to list contents from
* @return array<mixed> List of contents at the specified path
*/
public function listRepositoryContents(string $owner, string $repositoryName, string $path = ''): array
{
$url = "/repos/$owner/$repositoryName/contents";
if (!empty($path)) {
$url .= "/$path";
}
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if (($response['headers']['status-code'] == 404)) {
return [];
}
$items = [];
if (!empty($response['body'][0])) {
$items = $response['body'];
} elseif (!empty($response['body'])) {
$items = [$response['body']];
}
$contents = [];
foreach ($items as $item) {
$type = $item['type'] ?? 'file';
$contents[] = [
'name' => $item['name'] ?? '',
'size' => $item['size'] ?? 0,
'type' => $type === 'file' ? self::CONTENTS_FILE : self::CONTENTS_DIRECTORY
];
}
return $contents;
}
public function deleteRepository(string $owner, string $repositoryName): bool
{
$url = "/repos/{$owner}/{$repositoryName}";
$response = $this->call(self::METHOD_DELETE, $url, ['Authorization' => "Bearer $this->accessToken"]);
$statusCode = $response['headers']['status-code'];
if ($statusCode >= 400) {
throw new Exception("Deleting repository $repositoryName failed with status code $statusCode");
}
return true;
}
/**
* Add Comment to Pull Request
*
* @return string
*
* @throws Exception
*/
public function createComment(string $owner, string $repositoryName, int $pullRequestNumber, string $comment): string
{
$url = '/repos/' . $owner . '/' . $repositoryName . '/issues/' . $pullRequestNumber . '/comments';
$response = $this->call(self::METHOD_POST, $url, ['Authorization' => "Bearer $this->accessToken"], ['body' => $comment]);
if (!isset($response['body']['id'])) {
throw new Exception("Comment creation response is missing comment ID.");
}
$commentId = $response['body']['id'];
return $commentId;
}
/**
* Get Comment of Pull Request
*
* @param string $owner The owner of the repository
* @param string $repositoryName The name of the repository
* @param string $commentId The ID of the comment to retrieve
* @return string The retrieved comment
*
* @throws Exception
*/
public function getComment(string $owner, string $repositoryName, string $commentId): string
{
$url = '/repos/' . $owner . '/' . $repositoryName . '/issues/comments/' . $commentId;
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
$comment = $response['body']['body'] ?? '';
return $comment;
}
/**
* Update Pull Request Comment
*
* @param string $owner The owner of the repository
* @param string $repositoryName The name of the repository
* @param int $commentId The ID of the comment to update
* @param string $comment The updated comment content
* @return string The ID of the updated comment
*
* @throws Exception
*/
public function updateComment(string $owner, string $repositoryName, int $commentId, string $comment): string
{
$url = '/repos/' . $owner . '/' . $repositoryName . '/issues/comments/' . $commentId;
$response = $this->call(self::METHOD_PATCH, $url, ['Authorization' => "Bearer $this->accessToken"], ['body' => $comment]);
if (!isset($response['body']['id'])) {
throw new Exception("Comment update response is missing comment ID.");
}
$commentId = $response['body']['id'];
return $commentId;
}
/**
* Generate Access Token
*/
protected function generateAccessToken(string $privateKey, string $githubAppId): void
{
/**
* @var resource $privateKeyObj
*/
$privateKeyObj = \openssl_pkey_get_private($privateKey);
$appIdentifier = $githubAppId;
$iat = time();
$exp = $iat + 10 * 60;
$payload = [
'iat' => $iat,
'exp' => $exp,
'iss' => $appIdentifier,
];
// generate access token
$jwt = new JWT($privateKeyObj, 'RS256');
$token = $jwt->encode($payload);
$this->jwtToken = $token;
$res = $this->call(self::METHOD_POST, '/app/installations/' . $this->installationId . '/access_tokens', ['Authorization' => 'Bearer ' . $token]);
if (!isset($res['body']['token'])) {
throw new Exception('Failed to retrieve access token from GitHub API.');
}
$this->accessToken = $res['body']['token'];
}
/**
* Get user
*
* @return array<mixed>
*
* @throws Exception
*/
public function getUser(string $username): array
{
$response = $this->call(self::METHOD_GET, '/users/' . $username);
return $response;
}
/**
* Get owner name of the GitHub installation
*
* @return string
*/
public function getOwnerName(string $installationId): string
{
$url = '/app/installations/' . $installationId;
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->jwtToken"]);
if (!isset($response['body']['account']['login'])) {
throw new Exception("Owner name retrieval response is missing account login.");
}
return $response['body']['account']['login'];
}
/**
* Get Pull Request
*
* @return array<mixed> The retrieved pull request
*/
public function getPullRequest(string $owner, string $repositoryName, int $pullRequestNumber): array
{
$url = "/repos/{$owner}/{$repositoryName}/pulls/{$pullRequestNumber}";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
return $response['body'] ?? [];
}
/**
* Get latest opened pull request with specific base branch
* @return array<mixed>
*/
public function getPullRequestFromBranch(string $owner, string $repositoryName, string $branch): array
{
$head = "{$owner}:{$branch}";
$url = "/repos/{$owner}/{$repositoryName}/pulls?head={$head}&state=open&sort=updated&per_page=1";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
return $response['body'][0] ?? [];
}
/**
* Lists branches for a given repository
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @return array<string> List of branch names as array
*/
public function listBranches(string $owner, string $repositoryName): array
{
$url = "/repos/$owner/$repositoryName/branches";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
$names = [];
foreach ($response['body'] as $subarray) {
$names[] = $subarray['name'];
}
return $names;
}
/**
* Get details of a commit using commit hash
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @param string $commitHash SHA of the commit
* @return array<mixed> Details of the commit
*/
public function getCommit(string $owner, string $repositoryName, string $commitHash): array
{
$url = "/repos/$owner/$repositoryName/commits/$commitHash";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if (!isset($response['body']['commit']['author']['name']) || !isset($response['body']['commit']['message'])) {
throw new Exception("Commit author or message information missing.");
}
return [
'commitAuthor' => $response['body']['commit']['author']['name'],
'commitMessage' => $response['body']['commit']['message'],
];
}
/**
* Get latest commit of a branch
*
* @param string $owner Owner name of the repository
* @param string $repositoryName Name of the GitHub repository
* @param string $branch Name of the branch
* @return array<mixed> Details of the commit
*/
public function getLatestCommit(string $owner, string $repositoryName, string $branch): array
{
$url = "/repos/$owner/$repositoryName/commits/$branch?per_page=1";
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
if (
!isset($response['body']['commit']['author']['name']) ||
!isset($response['body']['commit']['message']) ||
!isset($response['body']['sha']) ||
!isset($response['body']['html_url'])
) {
throw new Exception("Latest commit response is missing required information.");
}
return [
'commitAuthor' => $response['body']['commit']['author']['name'],
'commitMessage' => $response['body']['commit']['message'],
'commitHash' => $response['body']['sha'],
'commitUrl' => $response['body']['html_url']
];
}
/**
* Updates status check of each commit
* state can be one of: error, failure, pending, success
*/
public function updateCommitStatus(string $repositoryName, string $commitHash, string $owner, string $state, string $description = '', string $target_url = '', string $context = ''): void
{
$url = "/repos/$owner/$repositoryName/statuses/$commitHash";
$body = [
'state' => $state,
'target_url' => $target_url,
'description' => $description,
'context' => $context,
];
$this->call(self::METHOD_POST, $url, ['Authorization' => "Bearer $this->accessToken"], $body);
}
/**
* Generates a clone command using app access token
*/
public function generateCloneCommand(string $owner, string $repositoryName, string $version, string $versionType, string $directory, string $rootDirectory): string
{
if (empty($rootDirectory)) {
$rootDirectory = '*';
}
// URL encode the components for the clone URL
$owner = urlencode($owner);
$repositoryName = urlencode($repositoryName);
$accessToken = !empty($this->accessToken) ? ':' . urlencode($this->accessToken) : '';
$cloneUrl = "https://{$owner}{$accessToken}@github.com/{$owner}/{$repositoryName}";
$directory = escapeshellarg($directory);
$rootDirectory = escapeshellarg($rootDirectory);
$commands = [
"mkdir -p {$directory}",
"cd {$directory}",
"git config --global init.defaultBranch main",
"git init",
"git remote add origin {$cloneUrl}",
"git config core.sparseCheckout true",
"echo {$rootDirectory} >> .git/info/sparse-checkout",
];
switch ($versionType) {
case self::CLONE_TYPE_BRANCH:
$branchName = escapeshellarg($version);
$commands[] = "if git ls-remote --exit-code --heads origin {$branchName}; then git pull origin {$branchName} && git checkout {$branchName}; else git checkout -b {$branchName}; fi";
break;
case self::CLONE_TYPE_COMMIT:
$commitHash = escapeshellarg($version);
$commands[] = "git pull origin {$commitHash}";
break;
case self::CLONE_TYPE_TAG:
$tagName = escapeshellarg($version);
$commands[] = "git pull origin $(git ls-remote --tags origin {$tagName} | tail -n 1 | awk -F '/' '{print $3}')";
break;
}
$fullCommand = implode(" && ", $commands);
return $fullCommand;
}
/**
* Parses webhook event payload
*
* @param string $event Type of event: push, pull_request etc
* @param string $payload The webhook payload received from GitHub
* @return array<mixed> Parsed payload as a json object
*/
public function getEvent(string $event, string $payload): array
{
$payload = json_decode($payload, true);
if ($payload === null || !is_array($payload)) {
throw new Exception("Invalid payload.");
}
$installationId = strval($payload['installation']['id']);
switch ($event) {
case 'push':
$branchCreated = isset($payload['created']) ? $payload['created'] : false;
$ref = $payload['ref'] ?? '';
$repositoryId = strval($payload['repository']['id'] ?? '');
$repositoryName = $payload['repository']['name'] ?? '';
$branch = str_replace('refs/heads/', '', $ref);
$branchUrl = $payload['repository']['url'] . "/tree/" . $branch;
$repositoryUrl = $payload['repository']['url'];
$commitHash = $payload['after'] ?? '';
$owner = $payload['repository']['owner']['name'] ?? '';
$authorUrl = $payload['sender']['html_url'];
$headCommitAuthor = $payload['head_commit']['author']['name'] ?? '';
$headCommitMessage = $payload['head_commit']['message'] ?? '';
$headCommitUrl = $payload['head_commit']['url'] ?? '';
return [
'branchCreated' => $branchCreated,
'branch' => $branch,
'branchUrl' => $branchUrl,
'repositoryId' => $repositoryId,
'repositoryName' => $repositoryName,
'repositoryUrl' => $repositoryUrl,
'installationId' => $installationId,
'commitHash' => $commitHash,
'owner' => $owner,
'authorUrl' => $authorUrl,
'headCommitAuthor' => $headCommitAuthor,
'headCommitMessage' => $headCommitMessage,
'headCommitUrl' => $headCommitUrl,
'external' => false,
'pullRequestNumber' => '',
'action' => '',
];
case 'pull_request':
$repositoryId = strval($payload['repository']['id'] ?? '');
$branch = $payload['pull_request']['head']['ref'] ?? '';
$repositoryName = $payload['repository']['name'] ?? '';
$repositoryUrl = $payload['repository']['html_url'] ?? '';
$branchUrl = "$repositoryUrl/tree/$branch";
$pullRequestNumber = $payload['number'] ?? '';
$action = $payload['action'] ?? '';
$owner = $payload['repository']['owner']['login'] ?? '';
$authorUrl = $payload['sender']['html_url'];
$commitHash = $payload['pull_request']['head']['sha'] ?? '';
$headCommitUrl = $repositoryUrl . "/commits/" . $commitHash;
$external = $payload['pull_request']['head']['user']['login'] !== $payload['pull_request']['base']['user']['login'];
return [
'branch' => $branch,
'branchUrl' => $branchUrl,
'repositoryId' => $repositoryId,
'repositoryName' => $repositoryName,
'repositoryUrl' => $repositoryUrl,
'installationId' => $installationId,
'commitHash' => $commitHash,
'owner' => $owner,
'authorUrl' => $authorUrl,
'headCommitUrl' => $headCommitUrl,
'external' => $external,
'pullRequestNumber' => $pullRequestNumber,
'action' => $action,
];
case 'installation':
case 'installation_repositories':
$action = $payload['action'] ?? '';
$userName = $payload['installation']['account']['login'] ?? '';
return [
'action' => $action,
'installationId' => $installationId,
'userName' => $userName,
];
}
return [];
}
/**
* Validate webhook event
*
* @param string $payload Raw body of HTTP request
* @param string $signature Signature provided by GitHub in header
* @param string $signatureKey Webhook secret configured on GitHub
* @return bool
*/
public function validateWebhookEvent(string $payload, string $signature, string $signatureKey): bool
{
return $signature === ('sha256=' . hash_hmac('sha256', $payload, $signatureKey));
}
}