-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGitHub.php
More file actions
1017 lines (847 loc) · 37.2 KB
/
GitHub.php
File metadata and controls
1017 lines (847 loc) · 37.2 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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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\FileNotFound;
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 $appId = null, ?string $accessToken = null, ?string $refreshToken = null): 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, $appId);
$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'] ?? [];
}
/**
* Create a pull request
*
* @param string $owner Owner of the repository
* @param string $repositoryName Name of the repository
* @param string $title PR title
* @param string $head Source branch
* @param string $base Target branch
* @param string $body PR description (optional)
* @return array<mixed> Created PR details
*/
public function createPullRequest(string $owner, string $repositoryName, string $title, string $head, string $base, string $body = ''): array
{
throw new Exception('Not implemented');
}
/**
* Create a webhook on a repository
*
* Note: Not applicable for GitHub - webhooks are managed via GitHub Apps
*/
public function createWebhook(string $owner, string $repositoryName, string $url, string $secret, array $events = ['push', 'pull_request']): int
{
throw new Exception('Not applicable for GitHub - webhooks are managed via GitHub Apps');
}
/**
* Create a file in a repository
*
* @param string $owner Owner of the repository
* @param string $repositoryName Name of the repository
* @param string $filepath Path where file should be created
* @param string $content Content of the file
* @param string $message Commit message
* @param string $branch Branch to create file on (optional)
* @return array<mixed> Response from API
*/
public function createFile(string $owner, string $repositoryName, string $filepath, string $content, string $message = 'Add file', string $branch = ''): array
{
$url = "/repos/{$owner}/{$repositoryName}/contents/{$filepath}";
$payload = [
'message' => $message,
'content' => base64_encode($content),
];
// GitHub supports branch parameter
if (! empty($branch)) {
$payload['branch'] = $branch;
}
$response = $this->call(
self::METHOD_PUT,
$url,
['Authorization' => "Bearer $this->accessToken"],
$payload
);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new Exception("Failed to create file {$filepath}: HTTP {$responseHeadersStatusCode}");
}
return $response['body'] ?? [];
}
/**
* Create a branch in a repository
*
* @param string $owner Owner of the repository
* @param string $repositoryName Name of the repository
* @param string $newBranchName Name of the new branch
* @param string $oldBranchName Name of the branch to branch from
* @return array<mixed> Response from API
*/
public function createBranch(string $owner, string $repositoryName, string $newBranchName, string $oldBranchName): array
{
throw new Exception("Not implemented");
}
/**
* Determines whether the installation has access to all repositories or specific repositories
*
* @return bool True if installation has access to all repositories, false if it has access to specific repositories
*
* @throws Exception
*/
public function hasAccessToAllRepositories(): bool
{
$url = '/app/installations/' . $this->installationId;
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->jwtToken"]);
$responseBody = $response['body'] ?? [];
return ($responseBody['repository_selection'] ?? '') === 'all';
}
/**
* 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
{
// Installation has access to all repositories, use the search API which supports filtering.
if ($this->hasAccessToAllRepositories()) {
$url = '/search/repositories';
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'q' => "{$search} user:{$owner} fork:true",
'page' => $page,
'per_page' => $per_page,
'sort' => 'updated'
]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('items', $responseBody)) {
throw new Exception("Repositories list missing in the response.");
}
return [
'items' => $responseBody['items'] ?? [],
'total' => $responseBody['total_count'] ?? 0,
];
}
// Installation has access to specific repositories, we need to perform client-side filtering.
$url = '/installation/repositories';
$repositories = [];
// When no search query is provided, delegate pagination to the GitHub API.
if (empty($search)) {
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'page' => $page,
'per_page' => $per_page,
]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('repositories', $responseBody)) {
throw new Exception("Repositories list missing in the response.");
}
return [
'items' => $responseBody['repositories'] ?? [],
'total' => $responseBody['total_count'] ?? 0,
];
}
// When search query is provided, fetch all repositories accessible by the installation and filter them locally.
$currentPage = 1;
while (true) {
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'page' => $currentPage,
'per_page' => 100, // Maximum allowed by GitHub API
]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('repositories', $responseBody)) {
throw new Exception("Repositories list missing in the response.");
}
// Filter repositories to only include those that match the search query.
$filteredRepositories = array_filter($responseBody['repositories'] ?? [], fn ($repo) => stripos($repo['name'] ?? '', $search) !== false);
// Merge with result so far.
$repositories = array_merge($repositories, $filteredRepositories);
// If less than 100 repositories are returned, we have fetched all repositories.
if (\count($responseBody['repositories'] ?? []) < 100) {
break;
}
// Increment page number to fetch next page.
$currentPage++;
}
$repositoriesInRequestedPage = \array_slice($repositories, ($page - 1) * $per_page, $per_page);
return [
'items' => $repositoriesInRequestedPage,
'total' => \count($repositories),
];
}
public function getInstallationRepository(string $repositoryName): array
{
$currentPage = 1;
$perPage = 100;
$totalRepositories = 0;
$maxRepositories = 1000;
$url = '/installation/repositories';
while ($totalRepositories < $maxRepositories) {
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"], [
'page' => $currentPage,
'per_page' => $perPage,
]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('repositories', $responseBody)) {
throw new Exception("Repositories list missing in the response.");
}
foreach (($responseBody['repositories'] ?? []) as $repo) {
if (\strtolower($repo['name'] ?? '') === \strtolower($repositoryName)) {
return $repo;
}
}
if (\count($responseBody['repositories'] ?? []) < $perPage) {
break;
}
$currentPage++;
$totalRepositories += $perPage;
}
throw new RepositoryNotFound("Repository not found.");
}
/**
* 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"]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('name', $responseBody)) {
throw new RepositoryNotFound("Repository not found");
}
return $responseBody['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"]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode == 404) {
return [];
}
$responseBody = $response['body'] ?? [];
return array_column($responseBody['tree'] ?? [], 'path');
}
/**
* 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"]);
$responseBody = $response['body'] ?? [];
if (!empty($responseBody)) {
return array_keys($responseBody);
}
return [];
}
/**
* Get contents of the specified file.
*
* @param string $owner Owner name
* @param string $repositoryName Name of the repository
* @param string $path Path to the file
* @param string $ref The name of the commit/branch/tag
* @return array<string, mixed> File details
*/
public function getRepositoryContent(string $owner, string $repositoryName, string $path, string $ref = ''): array
{
$url = "/repos/$owner/$repositoryName/contents/" . $path;
if (!empty($ref)) {
$url .= "?ref=$ref";
}
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode !== 200) {
throw new FileNotFound();
}
$responseBody = $response['body'] ?? [];
$encoding = $responseBody['encoding'] ?? '';
$content = '';
if ($encoding === 'base64') {
$content = base64_decode($responseBody['content'] ?? '');
} else {
throw new FileNotFound();
}
$output = [
'sha' => $responseBody['sha'] ?? '',
'size' => $responseBody['size'] ?? 0,
'content' => $content
];
return $output;
}
/**
* 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
* @param string $ref The name of the commit/branch/tag
* @return array<mixed> List of contents at the specified path
*/
public function listRepositoryContents(string $owner, string $repositoryName, string $path = '', string $ref = ''): array
{
$url = "/repos/$owner/$repositoryName/contents";
if (!empty($path)) {
$url .= "/$path";
}
if (!empty($ref)) {
$url .= "?ref=$ref";
}
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->accessToken"]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode == 404) {
return [];
}
$responseBody = $response['body'] ?? [];
$items = [];
if (!empty($responseBody[0] ?? [])) {
$items = $responseBody;
} elseif (!empty($responseBody)) {
$items = [$responseBody];
}
$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"]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new Exception("Deleting repository $repositoryName failed with status code $responseHeadersStatusCode");
}
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]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('id', $responseBody)) {
throw new Exception("Comment creation response is missing comment ID.");
}
$commentId = $responseBody['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"]);
$responseBody = $response['body'] ?? [];
$comment = $responseBody['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]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('id', $responseBody)) {
throw new Exception("Comment update response is missing comment ID.");
}
$commentId = $responseBody['id'] ?? '';
return $commentId;
}
/**
* Generate Access Token
*/
protected function generateAccessToken(string $privateKey, ?string $appId): void
{
/**
* @var resource $privateKeyObj
*/
$privateKeyObj = \openssl_pkey_get_private($privateKey);
$appIdentifier = $appId;
$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;
$response = $this->call(self::METHOD_POST, '/app/installations/' . $this->installationId . '/access_tokens', ['Authorization' => 'Bearer ' . $token]);
$responseBody = $response['body'] ?? [];
if (!array_key_exists('token', $responseBody)) {
throw new Exception('Failed to retrieve access token from GitHub API.');
}
$this->accessToken = $responseBody['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
*
* @param string $installationId GitHub App installation ID
* @param int|null $repositoryId Not used by GitHub (parameter exists for this adapter compatibility)
* @return string Owner login/username
*/
public function getOwnerName(string $installationId, ?int $repositoryId = null): string
{
// GitHub doesn't use $repositoryId - only installationId
$url = '/app/installations/' . $installationId;
$response = $this->call(self::METHOD_GET, $url, ['Authorization' => "Bearer $this->jwtToken"]);
$responseBody = $response['body'] ?? [];
$responseBodyAccount = $responseBody['account'] ?? [];
if (!array_key_exists('login', $responseBodyAccount)) {
throw new Exception("Owner name retrieval response is missing account login.");
}
return $responseBodyAccount['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"]);
$responseBody = $response['body'] ?? [];
return $responseBody[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"]);
$responseBody = $response['body'] ?? [];
$names = [];
foreach ($responseBody 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"]);
$responseBody = $response['body'] ?? [];
$responseBodyAuthor = $responseBody['author'] ?? [];
$responseBodyCommit = $responseBody['commit'] ?? [];
$responseBodyCommitAuthor = $responseBodyCommit['author'] ?? [];
return [
'commitAuthor' => $responseBodyCommitAuthor['name'] ?? 'Unknown',
'commitMessage' => $responseBodyCommit['message'] ?? 'No message',
'commitAuthorAvatar' => $responseBodyAuthor['avatar_url'] ?? '',
'commitAuthorUrl' => $responseBodyAuthor['html_url'] ?? '',
'commitHash' => $responseBody['sha'] ?? '',
'commitUrl' => $responseBody['html_url'] ?? '',
];
}
/**
* 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"]);
$responseBody = $response['body'] ?? [];
$responseBodyCommit = $responseBody['commit'] ?? [];
$responseBodyCommitAuthor = $responseBodyCommit['author'] ?? [];
$responseBodyAuthor = $responseBody['author'] ?? [];
if (
!array_key_exists('name', $responseBodyCommitAuthor) ||
!array_key_exists('message', $responseBodyCommit) ||
!array_key_exists('sha', $responseBody) ||
!array_key_exists('html_url', $responseBody) ||
!array_key_exists('avatar_url', $responseBodyAuthor) ||
!array_key_exists('html_url', $responseBodyAuthor)
) {
throw new Exception("Latest commit response is missing required information.");
}
return [
'commitAuthor' => $responseBodyCommitAuthor['name'] ?? '',
'commitMessage' => $responseBodyCommit['message'] ?? '',
'commitHash' => $responseBody['sha'] ?? '',
'commitUrl' => $responseBody['html_url'] ?? '',
'commitAuthorAvatar' => $responseBodyAuthor['avatar_url'] ?? '',
'commitAuthorUrl' => $responseBodyAuthor['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}",
// Enable sparse checkout
"git config core.sparseCheckout true",
"echo {$rootDirectory} >> .git/info/sparse-checkout",
// Disable fetching of refs we don't need
"git config --add remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'",
// Disable fetching of tags
"git config remote.origin.tagopt --no-tags",
];
switch ($versionType) {
case self::CLONE_TYPE_BRANCH:
$branchName = escapeshellarg($version);
$commands[] = "if git ls-remote --exit-code --heads origin {$branchName}; then git pull --depth=1 origin {$branchName} && git checkout {$branchName}; else git checkout -b {$branchName}; fi";
break;
case self::CLONE_TYPE_COMMIT:
$commitHash = escapeshellarg($version);
$commands[] = "git fetch --depth=1 origin {$commitHash} && git checkout {$commitHash}";
break;
case self::CLONE_TYPE_TAG:
$tagName = escapeshellarg($version);
$commands[] = "git fetch --depth=1 origin refs/tags/$(git ls-remote --tags origin {$tagName} | tail -n 1 | awk -F '/' '{print $3}') && git checkout FETCH_HEAD";
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.");
}
$payloadInstallation = $payload['installation'] ?? [];
$installationId = strval($payloadInstallation['id'] ?? '');
switch ($event) {
case 'push':
$payloadRepository = $payload['repository'] ?? [];
$payloadRepositoryOwner = $payloadRepository['owner'] ?? [];
$payloadSender = $payload['sender'] ?? [];
$payloadHeadCommit = $payload['head_commit'] ?? [];
$payloadHeadCommitAuthor = $payloadHeadCommit['author'] ?? [];
$branchCreated = $payload['created'] ?? false;
$branchDeleted = $payload['deleted'] ?? false;
$repositoryId = strval($payloadRepository['id'] ?? '');
$repositoryName = $payloadRepository['name'] ?? '';
$branch = str_replace('refs/heads/', '', $payload['ref'] ?? '');
$repositoryUrl = $payloadRepository['html_url'] ?? '';
$branchUrl = !empty($repositoryUrl) && !empty($branch) ? $repositoryUrl . "/tree/" . $branch : '';
$commitHash = $payload['after'] ?? '';
$owner = $payloadRepositoryOwner['name'] ?? '';
$authorUrl = $payloadSender['html_url'] ?? '';
$authorAvatarUrl = $payloadSender['avatar_url'] ?? '';
$headCommitAuthorName = $payloadHeadCommitAuthor['name'] ?? '';
$headCommitAuthorEmail = $payloadHeadCommitAuthor['email'] ?? '';
$headCommitMessage = $payloadHeadCommit['message'] ?? '';
$headCommitUrl = $payloadHeadCommit['url'] ?? '';
$affectedFiles = [];
foreach (($payload['commits'] ?? []) as $commit) {
foreach (($commit['added'] ?? []) as $added) {
$affectedFiles[$added] = true;
}
foreach (($commit['removed'] ?? []) as $removed) {
$affectedFiles[$removed] = true;
}
foreach (($commit['modified'] ?? []) as $modified) {
$affectedFiles[$modified] = true;
}
}
return [
'branchCreated' => $branchCreated,
'branchDeleted' => $branchDeleted,
'branch' => $branch,
'branchUrl' => $branchUrl,
'repositoryId' => $repositoryId,
'repositoryName' => $repositoryName,
'repositoryUrl' => $repositoryUrl,
'installationId' => $installationId,
'commitHash' => $commitHash,
'owner' => $owner,
'authorUrl' => $authorUrl,
'authorAvatarUrl' => $authorAvatarUrl,
'headCommitAuthorName' => $headCommitAuthorName,
'headCommitAuthorEmail' => $headCommitAuthorEmail,
'headCommitMessage' => $headCommitMessage,
'headCommitUrl' => $headCommitUrl,
'external' => false,
'pullRequestNumber' => '',
'action' => '',
'affectedFiles' => \array_keys($affectedFiles),
];
case 'pull_request':
$payloadRepository = $payload['repository'] ?? [];
$payloadRepositoryOwner = $payloadRepository['owner'] ?? [];
$payloadSender = $payload['sender'] ?? [];
$payloadPullRequest = $payload['pull_request'] ?? [];
$payloadPullRequestHead = $payloadPullRequest['head'] ?? [];
$payloadPullRequestHeadUser = $payloadPullRequestHead['user'] ?? [];
$payloadPullRequestUser = $payloadPullRequest['user'] ?? [];
$payloadPullRequestBase = $payloadPullRequest['base'] ?? [];
$payloadPullRequestBaseUser = $payloadPullRequestBase['user'] ?? [];
$repositoryId = strval($payloadRepository['id'] ?? '');
$branch = $payloadPullRequestHead['ref'] ?? '';
$repositoryName = $payloadRepository['name'] ?? '';
$repositoryUrl = $payloadRepository['html_url'] ?? '';
$branchUrl = !empty($repositoryUrl) && !empty($branch) ? $repositoryUrl . "/tree/" . $branch : '';
$pullRequestNumber = $payload['number'] ?? '';
$action = $payload['action'] ?? '';
$owner = $payloadRepositoryOwner['login'] ?? '';
$authorUrl = $payloadSender['html_url'] ?? '';
$authorAvatarUrl = $payloadPullRequestUser['avatar_url'] ?? '';
$commitHash = $payloadPullRequestHead['sha'] ?? '';
$headCommitUrl = $repositoryUrl ? $repositoryUrl . "/commits/" . $commitHash : '';
$headLogin = $payloadPullRequestHeadUser['login'] ?? '';
$baseLogin = $payloadPullRequestBaseUser['login'] ?? '';
$external = $headLogin !== $baseLogin;
return [
'branch' => $branch,
'branchUrl' => $branchUrl,
'repositoryId' => $repositoryId,
'repositoryName' => $repositoryName,
'repositoryUrl' => $repositoryUrl,
'installationId' => $installationId,
'commitHash' => $commitHash,
'owner' => $owner,
'authorUrl' => $authorUrl,
'authorAvatarUrl' => $authorAvatarUrl,
'headCommitUrl' => $headCommitUrl,
'external' => $external,
'pullRequestNumber' => $pullRequestNumber,
'action' => $action,
];
case 'installation':
case 'installation_repositories':
$payloadInstallation = $payload['installation'] ?? [];
$payloadInstallationAccount = $payloadInstallation['account'] ?? [];
$action = $payload['action'] ?? '';
$userName = $payloadInstallationAccount['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