forked from utopia-php/vcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitLab.php
More file actions
438 lines (356 loc) · 15.4 KB
/
GitLab.php
File metadata and controls
438 lines (356 loc) · 15.4 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
<?php
namespace Utopia\VCS\Adapter\Git;
use Exception;
use Utopia\Cache\Cache;
use Utopia\VCS\Adapter\Git;
use Utopia\VCS\Exception\RepositoryNotFound;
class GitLab extends Git
{
public const CONTENTS_FILE = 'file';
public const CONTENTS_DIRECTORY = 'dir';
protected string $endpoint = 'http://gitlab:80/api/v4';
protected string $gitlabUrl = 'http://gitlab:80';
protected string $accessToken;
protected Cache $cache;
/**
* @var array<string, string>
*/
protected $headers = ['content-type' => 'application/json'];
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
public function setEndpoint(string $endpoint): void
{
$this->gitlabUrl = rtrim($endpoint, '/');
$this->endpoint = $this->gitlabUrl . '/api/v4';
}
public function getName(): string
{
return 'gitlab';
}
public function initializeVariables(string $installationId, string $privateKey, ?string $appId = null, ?string $accessToken = null, ?string $refreshToken = null): void
{
if (!empty($accessToken)) {
$this->accessToken = $accessToken;
return;
}
throw new Exception("accessToken is required for this adapter.");
}
protected function generateAccessToken(string $privateKey, string $appId): void
{
return;
}
/**
* Create a new group/organization
* Returns "id:path" format so both numeric ID and path are available
*/
public function createOrganization(string $orgName): string
{
$url = "/groups";
$response = $this->call(self::METHOD_POST, $url, ['PRIVATE-TOKEN' => $this->accessToken], [
'name' => $orgName,
'path' => $orgName,
'visibility' => 'public',
]);
$responseBody = $response['body'] ?? [];
$responseHeaders = $response['headers'] ?? [];
$statusCode = $responseHeaders['status-code'] ?? 0;
if ($statusCode >= 400) {
throw new Exception("Creating organization {$orgName} failed with status code {$statusCode}");
}
return ($responseBody['id'] ?? '') . ':' . ($responseBody['path'] ?? '');
}
/**
* Extract owner path from "id:path" format
*/
private function getOwnerPath(string $owner): string
{
if (strstr($owner, ':') !== false) {
return substr($owner, strpos($owner, ':') + 1);
}
return $owner;
}
/**
* Extract namespace ID from "id:path" format
*/
private function getNamespaceId(string $owner): string
{
$pos = strpos($owner, ':');
if ($pos !== false) {
return substr($owner, 0, $pos);
}
return $owner;
}
public function createRepository(string $owner, string $repositoryName, bool $private): array
{
$namespaceId = (int) $this->getNamespaceId($owner);
$url = "/projects";
$response = $this->call(self::METHOD_POST, $url, ['PRIVATE-TOKEN' => $this->accessToken], [
'name' => $repositoryName,
'path' => $repositoryName,
'namespace_id' => $namespaceId,
'visibility' => $private ? 'private' : 'public',
]);
$body = $response['body'] ?? [];
$responseHeaders = $response['headers'] ?? [];
$statusCode = $responseHeaders['status-code'] ?? 0;
if ($statusCode >= 400) {
throw new Exception("Creating repository {$repositoryName} failed with status code {$statusCode}");
}
return is_array($body) ? $body : [];
}
public function deleteRepository(string $owner, string $repositoryName): bool
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$url = "/projects/{$projectPath}";
$response = $this->call(self::METHOD_DELETE, $url, ['PRIVATE-TOKEN' => $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;
}
public function getRepository(string $owner, string $repositoryName): array
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$url = "/projects/{$projectPath}";
$response = $this->call(self::METHOD_GET, $url, ['PRIVATE-TOKEN' => $this->accessToken]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new RepositoryNotFound("Repository not found");
}
return $response['body'] ?? [];
}
public function hasAccessToAllRepositories(): bool
{
return true;
}
public function getInstallationRepository(string $repositoryName): array
{
throw new Exception("getInstallationRepository is not applicable for this adapter");
}
public function searchRepositories(string $owner, int $page, int $per_page, string $search = ''): array
{
throw new Exception("Not implemented");
}
public function getRepositoryName(string $repositoryId): string
{
throw new Exception("Not implemented");
}
public function getRepositoryTree(string $owner, string $repositoryName, string $branch, bool $recursive = false): array
{
throw new Exception("Not implemented");
}
public function getRepositoryContent(string $owner, string $repositoryName, string $path, string $ref = ''): array
{
throw new Exception("Not implemented");
}
public function listRepositoryContents(string $owner, string $repositoryName, string $path = '', string $ref = ''): array
{
throw new Exception("Not implemented");
}
public function listRepositoryLanguages(string $owner, string $repositoryName): array
{
throw new Exception("Not implemented");
}
public function createFile(string $owner, string $repositoryName, string $filepath, string $content, string $message = 'Add file', string $branch = ''): array
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$encodedFilepath = urlencode($filepath);
$url = "/projects/{$projectPath}/repository/files/{$encodedFilepath}";
$payload = [
'branch' => empty($branch) ? 'main' : $branch,
'content' => base64_encode($content),
'encoding' => 'base64',
'commit_message' => $message,
'author_name' => 'utopia',
'author_email' => 'utopia@example.com',
];
$response = $this->call(self::METHOD_POST, $url, ['PRIVATE-TOKEN' => $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'] ?? [];
}
public function createBranch(string $owner, string $repositoryName, string $newBranchName, string $oldBranchName): array
{
throw new Exception("Not implemented");
}
public function createPullRequest(string $owner, string $repositoryName, string $title, string $head, string $base, string $body = ''): array
{
throw new Exception("Not implemented");
}
public function createWebhook(string $owner, string $repositoryName, string $url, string $secret, array $events = ['push', 'pull_request']): int
{
throw new Exception("Not implemented");
}
public function createComment(string $owner, string $repositoryName, int $pullRequestNumber, string $comment): string
{
throw new Exception("Not implemented");
}
public function getComment(string $owner, string $repositoryName, string $commentId): string
{
throw new Exception("Not implemented");
}
public function updateComment(string $owner, string $repositoryName, int $commentId, string $comment): string
{
throw new Exception("Not implemented");
}
public function getUser(string $username): array
{
throw new Exception("Not implemented");
}
public function getOwnerName(string $installationId, ?int $repositoryId = null): string
{
throw new Exception("Not implemented");
}
public function getPullRequest(string $owner, string $repositoryName, int $pullRequestNumber): array
{
throw new Exception("Not implemented");
}
public function getPullRequestFiles(string $owner, string $repositoryName, int $pullRequestNumber): array
{
throw new Exception("Not implemented");
}
public function getPullRequestFromBranch(string $owner, string $repositoryName, string $branch): array
{
throw new Exception("Not implemented");
}
public function listBranches(string $owner, string $repositoryName): array
{
throw new Exception("Not implemented");
}
public function getCommit(string $owner, string $repositoryName, string $commitHash): array
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$url = "/projects/{$projectPath}/repository/commits/" . urlencode($commitHash);
$response = $this->call(self::METHOD_GET, $url, ['PRIVATE-TOKEN' => $this->accessToken]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new Exception("Commit not found or inaccessible");
}
$commit = $response['body'] ?? [];
return [
'commitAuthor' => $commit['author_name'] ?? 'Unknown',
'commitMessage' => $commit['message'] ?? 'No message',
'commitHash' => $commit['id'] ?? '',
'commitUrl' => $commit['web_url'] ?? '',
'commitAuthorAvatar' => '',
'commitAuthorUrl' => '',
];
}
public function getLatestCommit(string $owner, string $repositoryName, string $branch): array
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$url = "/projects/{$projectPath}/repository/commits?ref_name=" . urlencode($branch) . "&per_page=1";
$response = $this->call(self::METHOD_GET, $url, ['PRIVATE-TOKEN' => $this->accessToken]);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new Exception("Failed to get latest commit: HTTP {$responseHeadersStatusCode}");
}
$responseBody = $response['body'] ?? [];
if (empty($responseBody[0])) {
throw new Exception("Latest commit response is missing required information.");
}
$commit = $responseBody[0];
return [
'commitAuthor' => $commit['author_name'] ?? 'Unknown',
'commitMessage' => $commit['message'] ?? 'No message',
'commitHash' => $commit['id'] ?? '',
'commitUrl' => $commit['web_url'] ?? '',
'commitAuthorAvatar' => '',
'commitAuthorUrl' => '',
];
}
public function updateCommitStatus(string $repositoryName, string $commitHash, string $owner, string $state, string $description = '', string $target_url = '', string $context = ''): void
{
throw new Exception("Not implemented");
}
public function generateCloneCommand(string $owner, string $repositoryName, string $version, string $versionType, string $directory, string $rootDirectory): string
{
if (empty($rootDirectory) || $rootDirectory === '/') {
$rootDirectory = '*';
}
$ownerPath = $this->getOwnerPath($owner);
// GitLab clone URL format: http://oauth2:{token}@host/owner/repo.git
$baseUrl = $this->gitlabUrl;
if (!empty($this->accessToken)) {
$baseUrl = str_replace('://', '://oauth2:' . urlencode($this->accessToken) . '@', $this->gitlabUrl);
}
$cloneUrl = escapeshellarg("{$baseUrl}/{$ownerPath}/{$repositoryName}.git");
$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",
"git config --add remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'",
"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/{$tagName} && git checkout FETCH_HEAD";
break;
default:
throw new Exception("Unsupported clone type: {$versionType}");
}
return implode(' && ', $commands);
}
public function getEvent(string $event, string $payload): array
{
throw new Exception("Not implemented");
}
public function validateWebhookEvent(string $payload, string $signature, string $signatureKey): bool
{
throw new Exception("Not implemented");
}
public function createTag(string $owner, string $repositoryName, string $tagName, string $target, string $message = ''): array
{
$ownerPath = $this->getOwnerPath($owner);
$projectPath = urlencode("{$ownerPath}/{$repositoryName}");
$url = "/projects/{$projectPath}/repository/tags";
$payload = [
'tag_name' => $tagName,
'ref' => $target,
];
if (!empty($message)) {
$payload['message'] = $message;
}
$response = $this->call(self::METHOD_POST, $url, ['PRIVATE-TOKEN' => $this->accessToken], $payload);
$responseHeaders = $response['headers'] ?? [];
$responseHeadersStatusCode = $responseHeaders['status-code'] ?? 0;
if ($responseHeadersStatusCode >= 400) {
throw new Exception("Failed to create tag {$tagName}: HTTP {$responseHeadersStatusCode}");
}
return $response['body'] ?? [];
}
public function getCommitStatuses(string $owner, string $repositoryName, string $commitHash): array
{
throw new Exception("Not implemented");
}
}