/
GitLabDriver.php
438 lines (362 loc) · 12.2 KB
/
GitLabDriver.php
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
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Repository\Vcs;
use Composer\Config;
use Composer\Cache;
use Composer\IO\IOInterface;
use Composer\Json\JsonFile;
use Composer\Downloader\TransportException;
use Composer\Util\RemoteFilesystem;
use Composer\Util\GitLab;
/**
* Driver for GitLab API, use the Git driver for local checkouts.
*
* @author Henrik Bjørnskov <henrik@bjrnskov.dk>
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*/
class GitLabDriver extends VcsDriver
{
private $scheme;
private $owner;
private $repository;
/**
* @var array Project data returned by GitLab API
*/
private $project;
/**
* @var array Keeps commits returned by GitLab API
*/
private $commits = array();
/**
* @var array List of tag => reference
*/
private $tags;
/**
* @var array List of branch => reference
*/
private $branches;
/**
* Git Driver
*
* @var GitDriver
*/
protected $gitDriver;
/**
* Defaults to true unless we can make sure it is public
*
* @var bool defines whether the repo is private or not
*/
private $isPrivate = true;
const URL_REGEX = '#^(?:(?P<scheme>https?)://(?P<domain>.+?)/|git@(?P<domain2>[^:]+):)(?P<owner>[^/]+)/(?P<repo>[^/]+?)(?:\.git|/)?$#';
/**
* Extracts information from the repository url.
*
* SSH urls use https by default. Set "secure-http": false on the repository config to use http instead.
*
* {@inheritDoc}
*/
public function initialize()
{
if (!preg_match(self::URL_REGEX, $this->url, $match)) {
throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.');
}
$this->scheme = !empty($match['scheme']) ? $match['scheme'] : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https');
$this->originUrl = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
$this->owner = $match['owner'];
$this->repository = preg_replace('#(\.git)$#', '', $match['repo']);
$this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
$this->fetchProject();
}
/**
* Updates the RemoteFilesystem instance.
* Mainly useful for tests.
*
* @internal
*/
public function setRemoteFilesystem(RemoteFilesystem $remoteFilesystem)
{
$this->remoteFilesystem = $remoteFilesystem;
}
/**
* {@inheritdoc}
*/
public function getFileContent($file, $identifier)
{
if ($this->gitDriver) {
return $this->gitDriver->getFileContent($file, $identifier);
}
// Convert the root identifier to a cachable commit id
if (!preg_match('{[a-f0-9]{40}}i', $identifier)) {
$branches = $this->getBranches();
if (isset($branches[$identifier])) {
$identifier = $branches[$identifier];
}
}
$resource = $this->getApiUrl().'/repository/blobs/'.$identifier.'?filepath=' . $file;
try {
$content = $this->getContents($resource);
} catch (TransportException $e) {
if ($e->getCode() !== 404) {
throw $e;
}
return null;
}
return $content;
}
/**
* {@inheritdoc}
*/
public function getChangeDate($identifier)
{
if ($this->gitDriver) {
return $this->gitDriver->getChangeDate($identifier);
}
if (isset($this->commits[$identifier])) {
return new \DateTime($this->commits[$identifier]['committed_date']);
}
return new \DateTime();
}
/**
* {@inheritDoc}
*/
public function getRepositoryUrl()
{
return $this->isPrivate ? $this->project['ssh_url_to_repo'] : $this->project['http_url_to_repo'];
}
/**
* {@inheritDoc}
*/
public function getUrl()
{
if ($this->gitDriver) {
return $this->gitDriver->getUrl();
}
return $this->project['web_url'];
}
/**
* {@inheritDoc}
*/
public function getDist($identifier)
{
$url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier;
return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
}
/**
* {@inheritDoc}
*/
public function getSource($identifier)
{
if ($this->gitDriver) {
return $this->gitDriver->getSource($identifier);
}
return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier);
}
/**
* {@inheritDoc}
*/
public function getRootIdentifier()
{
if ($this->gitDriver) {
return $this->gitDriver->getRootIdentifier();
}
return $this->project['default_branch'];
}
/**
* {@inheritDoc}
*/
public function getBranches()
{
if ($this->gitDriver) {
return $this->gitDriver->getBranches();
}
if (!$this->branches) {
$this->branches = $this->getReferences('branches');
}
return $this->branches;
}
/**
* {@inheritDoc}
*/
public function getTags()
{
if ($this->gitDriver) {
return $this->gitDriver->getTags();
}
if (!$this->tags) {
$this->tags = $this->getReferences('tags');
}
return $this->tags;
}
/**
* @return string Base URL for GitLab API v3
*/
public function getApiUrl()
{
return $this->scheme.'://'.$this->originUrl.'/api/v3/projects/'.$this->urlEncodeAll($this->owner).'%2F'.$this->urlEncodeAll($this->repository);
}
/**
* Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.`
*
* @param string $string
* @return string
*/
private function urlEncodeAll($string)
{
$encoded = '';
for ($i = 0; isset($string[$i]); $i++) {
$character = $string[$i];
if (!ctype_alnum($character) && !in_array($character, array('-', '_'), true)) {
$character = '%' . sprintf('%02X', ord($character));
}
$encoded .= $character;
}
return $encoded;
}
/**
* @param string $type
*
* @return string[] where keys are named references like tags or branches and the value a sha
*/
protected function getReferences($type)
{
$resource = $this->getApiUrl().'/repository/'.$type;
$data = JsonFile::parseJson($this->getContents($resource), $resource);
$references = array();
foreach ($data as $datum) {
$references[$datum['name']] = $datum['commit']['id'];
// Keep the last commit date of a reference to avoid
// unnecessary API call when retrieving the composer file.
$this->commits[$datum['commit']['id']] = $datum['commit'];
}
return $references;
}
protected function fetchProject()
{
// we need to fetch the default branch from the api
$resource = $this->getApiUrl();
$this->project = JsonFile::parseJson($this->getContents($resource, true), $resource);
$this->isPrivate = !$this->project['public'];
}
protected function attemptCloneFallback()
{
try {
if ($this->isPrivate === false) {
$url = $this->generatePublicUrl();
} else {
$url = $this->generateSshUrl();
}
// If this repository may be private and we
// cannot ask for authentication credentials (because we
// are not interactive) then we fallback to GitDriver.
$this->setupGitDriver($url);
return;
} catch (\RuntimeException $e) {
$this->gitDriver = null;
$this->io->writeError('<error>Failed to clone the '.$url.' repository, try running in interactive mode so that you can enter your credentials</error>');
throw $e;
}
}
/**
* Generate an SSH URL
*
* @return string
*/
protected function generateSshUrl()
{
return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
}
protected function generatePublicUrl()
{
return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
}
protected function setupGitDriver($url)
{
$this->gitDriver = new GitDriver(
array('url' => $url),
$this->io,
$this->config,
$this->process,
$this->remoteFilesystem
);
$this->gitDriver->initialize();
}
/**
* {@inheritDoc}
*/
protected function getContents($url, $fetchingRepoData = false)
{
try {
$res = parent::getContents($url);
if ($fetchingRepoData) {
$json = JsonFile::parseJson($res, $url);
// force auth as the unauthenticated version of the API is broken
if (!isset($json['default_branch'])) {
if (!empty($json['id'])) {
$this->isPrivate = false;
}
throw new TransportException('GitLab API seems to not be authenticated as it did not return a default_branch', 401);
}
}
return $res;
} catch (TransportException $e) {
$gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->remoteFilesystem);
switch ($e->getCode()) {
case 401:
case 404:
// try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
if (!$fetchingRepoData) {
throw $e;
}
if ($gitLabUtil->authorizeOAuth($this->originUrl)) {
return parent::getContents($url);
}
if (!$this->io->isInteractive()) {
return $this->attemptCloneFallback();
}
$this->io->writeError('<warning>Failed to download ' . $this->owner . '/' . $this->repository . ':' . $e->getMessage() . '</warning>');
$gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
return parent::getContents($url);
case 403:
if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) {
return parent::getContents($url);
}
if (!$this->io->isInteractive() && $fetchingRepoData) {
return $this->attemptCloneFallback();
}
throw $e;
default:
throw $e;
}
}
}
/**
* Uses the config `gitlab-domains` to see if the driver supports the url for the
* repository given.
*
* {@inheritDoc}
*/
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
if (!preg_match(self::URL_REGEX, $url, $match)) {
return false;
}
$scheme = !empty($match['scheme']) ? $match['scheme'] : null;
$originUrl = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
if (!in_array($originUrl, (array) $config->get('gitlab-domains'))) {
return false;
}
if ('https' === $scheme && !extension_loaded('openssl')) {
$io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
return false;
}
return true;
}
}