forked from luyadev/luya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepoController.php
377 lines (317 loc) · 11.8 KB
/
RepoController.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
<?php
namespace luya\dev;
use Curl\Curl;
use GitWrapper\GitWrapper;
use yii\console\widgets\Table;
use yii\console\Markdown;
use yii\helpers\Console;
use luya\helpers\FileHelper;
use Nadar\PhpComposerReader\ComposerReader;
use Nadar\PhpComposerReader\AutoloadSection;
use Nadar\PhpComposerReader\Autoload;
/**
* Dev Env cloning and updating.
*
* Provides functions to clone and update the repos.
*
* Usage
*
* ```sh
* ./vendor/bin/luyadev repo/init
* ./vendor/bin/luyadev repo/update
* ```
*
* Or clone a custom repo into the repos folder:
*
* ```sh
* ./venodr/bin/luyadev repo/clone luya-module-news luyadev
* ```
*
* In order to remove an existing repo from update list
*
* ```sh
* ./vendor/bin/luyadev repo/remove luya-module-news
* ```
*
* @author Basil Suter <basil@nadar.io>
* @since 1.0.1
*/
class RepoController extends BaseDevCommand
{
const CONFIG_VAR_USERNAME = 'username';
const CONFIG_VAR_CLONETYPE = 'cloneType';
const CONFIG_VAR_CUSTOMCLONES = 'customClones';
/**
* @var string Default action is actionInit();
*/
public $defaultAction = 'init';
/**
* @var array The default repos from luyadev
*/
public $repos = [
'luya',
'luya-module-admin',
'luya-module-cms',
];
public $text = <<<EOT
**CLONE REPOS**
We've detected that you don't have all module repos forked to your account. You can only push changes to the forked repos, all others are **READ ONLY**.
If you want to work on a specific repo, make sure that repo is forked to your Github account.
You can also skip this command, fork the repos and rerun this command again.
**FORK ME**
EOT;
/**
* Initilize the main repos.
*
* @return number
*/
public function actionInit()
{
// username
$username = $this->getConfig(self::CONFIG_VAR_USERNAME);
if (!$username) {
$username = $this->prompt('Whats your Github username?');
$this->saveConfig(self::CONFIG_VAR_USERNAME, $username);
}
// clonetype
$cloneType = $this->getConfig(self::CONFIG_VAR_CLONETYPE);
if (!$cloneType) {
$cloneType = $this->select('Are you connected via ssh or https?', ['ssh' => 'ssh', 'http' => 'http']);
$this->saveConfig(self::CONFIG_VAR_CLONETYPE, $cloneType);
}
$summary = [];
$itemWithoutFork = false;
// generate summary overview
foreach ($this->repos as $repo) {
$newRepoHome = $this->getFilesystemRepoPath($repo);
if (file_exists($newRepoHome . DIRECTORY_SEPARATOR . '.git')) {
$summary[] = $this->summaryItem($repo, false, true);
} elseif ($this->forkExists($username, $repo)) {
$summary[] = $this->summaryItem($repo, true, false);
} else {
$itemWithoutFork = true;
$summary[] = $this->summaryItem($repo, false, false);
}
}
if ($itemWithoutFork) {
Console::clearScreen();
$this->outputInfo($this->markdown($this->text));
foreach ($summary as $sum) {
if (!$sum[2] && !$sum[1]) {
$this->outputInfo($this->markdown("**{$sum[0]}**: https://github.com/luyadev/{$sum[0]}/fork", true));
}
}
echo (new Table())->setHeaders(['Repo', 'Already initialized', 'Fork exists'])->setRows($summary)->run();
$this->outputError("Repos without fork detected. Those repos will be initialized as READ ONLY. It means you can not push any changes to them.");
if (!$this->confirm("Continue?")) {
return $this->outputError('Abort by User.');
}
}
// foreach summary and clone
foreach ($summary as $sum) {
$repo = $sum[0];
$hasFork = $sum[2];
$exists = $sum[1];
// continue already initialized repos.
if ($exists) {
continue;
}
$newRepoHome = $this->getFilesystemRepoPath($repo);
if ($hasFork) {
$cloneUrl = ($cloneType == 'ssh') ? "git@github.com:{$username}/{$repo}.git" : "https://github.com/{$username}/{$repo}.git";
} else {
$cloneUrl = ($cloneType == 'ssh') ? "git@github.com:luyadev/{$repo}.git" : "https://github.com/{$username}/{$repo}.git";
}
$this->cloneRepo($repo, $cloneUrl, $newRepoHome, 'luyadev');
}
return $this->outputSuccess("init complete.");
}
/**
* Update all repos to master branch from upstream.
*/
public function actionUpdate()
{
foreach ($this->repos as $repo) {
$this->rebaseRepo($repo, $this->getFilesystemRepoPath($repo));
}
foreach ($this->getConfig(self::CONFIG_VAR_CUSTOMCLONES, []) as $repo => $path) {
$this->rebaseRepo($repo, $path);
}
}
/**
* Clone a repo into the repos folder.
*
* @param string $repo
* @param string $vendor
*/
public function actionClone($vendor = null, $repo = null)
{
// if `vendor/repo` notation is provided
if ($vendor !== null && strpos($vendor, '/')) {
list($vendor, $repo) = explode("/", $vendor);
}
if (empty($vendor)) {
$vendor = $this->prompt("Enter the username/vendor for this repo (e.g. luyadev)");
}
if (empty($repo)) {
$repo = $this->prompt("Enter the name of the repo you like to clone (e.g. luya-module-news)");
}
$clones = $this->getConfig(self::CONFIG_VAR_CUSTOMCLONES, []);
$repoFileSystemPath = $this->getFilesystemRepoPath($repo);
$clones[$repo] = $repoFileSystemPath;
$this->cloneRepo($repo, $this->getCloneUrlBasedOnType($repo, $vendor), $repoFileSystemPath, $vendor);
$this->saveConfig(self::CONFIG_VAR_CUSTOMCLONES, $clones);
$composerReader = new ComposerReader($repoFileSystemPath . DIRECTORY_SEPARATOR . 'composer.json');
if ($composerReader->canRead()) {
$section = new AutoloadSection($composerReader);
$autoloaders = [];
foreach ($section as $autoload) {
$newSrc = $repoFileSystemPath . DIRECTORY_SEPARATOR . $autoload->source;
$autoloaders[] = ['autoload' => $autoload, 'src' => $newSrc];
}
if (!empty($autoloaders)) {
foreach ($autoloaders as $item) {
$projectComposer = $this->getProjectComposerReader();
if ($projectComposer->canWrite()) {
$new = new Autoload($projectComposer, $item['autoload']->namespace, $item['src'], $item['autoload']->type);
$section = new AutoloadSection($projectComposer);
$section->add($new)->save();
$this->outputSuccess("{$repo}: autoload ✔ (namespace '{$item['autoload']->namespace}' for '{$item['autoload']->source}')");
}
}
$projectComposer = $this->getProjectComposerReader();
$projectComposer->runCommand('dump-autoload');
}
}
}
/**
* Remove a given repo from filesystem.
*
* @param string $repo The repo name like `luya-module-cms` without vendor.
*/
public function actionRemove($repo)
{
FileHelper::removeDirectory($this->getFilesystemRepoPath($repo));
$clones = $this->getConfig(self::CONFIG_VAR_CUSTOMCLONES, []);
if (isset($clones[$repo])) {
unset($clones[$repo]);
$this->saveConfig(self::CONFIG_VAR_CUSTOMCLONES, $clones);
}
return $this->outputSuccess("Removed repo {$repo}.");
}
/**
*
* @return \Nadar\PhpComposerReader\ComposerReader
*/
protected function getProjectComposerReader()
{
return new ComposerReader(getcwd() . DIRECTORY_SEPARATOR . 'composer.json');
}
private $_gitWrapper;
/**
* @return \GitWrapper\GitWrapper
*/
protected function getGitWrapper()
{
if ($this->_gitWrapper === null) {
$this->_gitWrapper = new GitWrapper();
$this->_gitWrapper->setTimeout(300);
}
return $this->_gitWrapper;
}
/**
*
* @param string $repo
* @param string $isFork
* @param string $exists
* @return array
*/
private function summaryItem($repo, $isFork, $exists)
{
return [$repo, $exists, $isFork];
}
/**
*
* @param string $repo
* @return string
*/
private function getFilesystemRepoPath($repo)
{
return 'repos' . DIRECTORY_SEPARATOR . $repo;
}
/**
*
* @param string $username
* @param string $repo
* @return boolean
*/
private function forkExists($username, $repo)
{
return (new Curl())->get('https://api.github.com/repos/'.$username.'/'.$repo)->isSuccess();
}
/**
*
* @param string $text
* @param boolean $paragraph
* @return string
*/
private function markdown($text, $paragraph = false)
{
$parser = new Markdown();
if ($paragraph) {
return $parser->parseParagraph($text);
}
return $parser->parse($text);
}
/**
* Return the url to clone based on config clone type (ssh/https).
*
* @param string $repo
* @param string $username
* @return string
*/
private function getCloneUrlBasedOnType($repo, $username)
{
return ($this->getConfig(self::CONFIG_VAR_CLONETYPE) == 'ssh') ? "git@github.com:{$username}/{$repo}.git" : "https://github.com/{$username}/{$repo}.git";
}
/**
* Rebase existing repo.
*
* @param string $repo
* @param string $repoFileSystemPath
*/
private function rebaseRepo($repo, $repoFileSystemPath)
{
$wrapper = new GitWrapper();
try {
$wrapper->git('fetch upstream', $repoFileSystemPath);
$this->outputInfo("{$repo}: fetch upstream ✔");
$wrapper->git('checkout master', $repoFileSystemPath);
$this->outputInfo("{$repo}: checkout master ✔");
$wrapper->git('rebase upstream/master master', $repoFileSystemPath);
$this->outputInfo("{$repo}: rebase master ✔");
$wrapper->git('pull', $repoFileSystemPath);
$this->outputInfo("{$repo}: pull ✔");
} catch (\Exception $err) {
$this->outputError("{$repo}: error while updating ({$repoFileSystemPath}) with message: " . $err->getMessage());
}
}
/**
* Clone a repo into the repos folder.
*
* @param string $repo
* @param string $cloneUrl
* @param string $newRepoHome
* @param string $upstreamUsername The upstream vendor name of the repo if available.
*/
private function cloneRepo($repo, $cloneUrl, $newRepoHome, $upstreamUsername)
{
$this->outputSuccess("{$repo}: cloning {$cloneUrl} ...");
$this->getGitWrapper()->cloneRepository($cloneUrl, $newRepoHome);
if (!empty($upstreamUsername)) {
$this->getGitWrapper()->git('remote add upstream https://github.com/'.$upstreamUsername.'/'.$repo.'.git', $newRepoHome);
$this->outputInfo("{$repo}: Configure upstream https://github.com/{$upstreamUsername}/{$repo}.git ✔");
}
$this->outputSuccess("{$repo}: cloning ✔");
}
}