forked from consolidation/robo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoboFile.php
549 lines (496 loc) · 16.8 KB
/
RoboFile.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
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
<?php
use Symfony\Component\Finder\Finder;
use Robo\Result;
use Robo\ResultData;
use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
class RoboFile extends \Robo\Tasks
{
/**
* Run the Robo unit tests.
*/
public function test($args = "", $options =
[
'coverage-html' => false,
'coverage' => false
])
{
$taskCodecept = $this->taskCodecept()
->args($args);
if ($options['coverage']) {
$taskCodecept->coverageXml('../../build/logs/clover.xml');
}
if ($options['coverage-html']) {
$taskCodecept->coverageHtml('../../build/logs/coverage');
}
return $taskCodecept;
}
/**
* Code sniffer.
*
* Run the PHP Codesniffer on a file or directory.
*
* @param string $file
* A file or directory to analyze.
* @option $autofix Whether to run the automatic fixer or not.
* @option $strict Show warnings as well as errors.
* Default is to show only errors.
*/
public function sniff(
$file = 'src/',
$options = [
'autofix' => false,
'strict' => false,
]
) {
$strict = $options['strict'] ? '' : '-n';
$result = $this->taskExec("./vendor/bin/phpcs --standard=PSR2 {$strict} {$file}")->run();
if (!$result->wasSuccessful()) {
if (!$options['autofix']) {
$options['autofix'] = $this->confirm('Would you like to run phpcbf to fix the reported errors?');
}
if ($options['autofix']) {
$result = $this->taskExec("./vendor/bin/phpcbf --standard=PSR2 {$file}")->run();
}
}
return $result;
}
/**
* Generate a new Robo task that wraps an existing utility class.
*
* @param $className The name of the existing utility class to wrap.
* @param $wrapperClassName The name of the wrapper class to create. Optional.
* @usage generate:task 'Symfony\Component\Filesystem\Filesystem' FilesystemStack
*/
public function generateTask($className, $wrapperClassName = "")
{
return $this->taskGenTask($className, $wrapperClassName);
}
/**
* Release Robo.
*/
public function release($opts = ['beta' => false])
{
$this->yell("Releasing Robo");
if ($opts['beta']) {
$stable = false;
$this->say('non-stable release');
}
$releaseDescription = $this->ask("Description of Release\n");
$this->docs();
$this->taskGitStack()
->add('-A')
->commit("auto-update")
->pull()
->push()
->run();
if ($stable) $this->pharPublish();
$this->publish();
$this->taskGitHubRelease(\Robo\Runner::VERSION)
->user($this->ask('User releasing'))
->password($this->askHidden('Password'))
->uri('Codegyre/Robo')
->description($releaseDescription)
->run();
if ($stable) $this->versionBump();
}
/**
* Update changelog.
*
* Add an entry to the Robo CHANGELOG.md file.
*
* @param string $addition The text to add to the change log.
*/
public function changed($addition)
{
return $this->taskChangelog()
->version(\Robo\Runner::VERSION)
->change($addition);
}
/**
* Update the version of Robo.
*
* @param string $version The new verison for Robo.
* Defaults to the next minor (bugfix) version after the current relelase.
*/
public function versionBump($version = '')
{
if (empty($version)) {
$versionParts = explode('.', \Robo\Runner::VERSION);
$versionParts[count($versionParts)-1]++;
$version = implode('.', $versionParts);
}
return $this->taskReplaceInFile(__DIR__.'/src/Runner.php')
->from("VERSION = '".\Robo\Runner::VERSION."'")
->to("VERSION = '".$version."'");
}
/**
* Generate the Robo documentation files.
*/
public function docs()
{
$collection = $this->collection();
$collection->progressMessage('Generate documentation from source code.');
$files = Finder::create()->files()->name('*.php')->in('src/Task');
$docs = [];
foreach ($files as $file) {
if ($file->getFileName() == 'loadTasks.php') {
continue;
}
if ($file->getFileName() == 'loadShortcuts.php') {
continue;
}
$ns = $file->getRelativePath();
if (!$ns) {
continue;
}
$class = basename(substr($file, 0, -4));
class_exists($class = "Robo\\Task\\$ns\\$class");
$docs[$ns][] = $class;
}
ksort($docs);
foreach ($docs as $ns => $tasks) {
$taskGenerator = $this->taskGenDoc("docs/tasks/$ns.md");
$taskGenerator->filterClasses(function (\ReflectionClass $r) {
return !($r->isAbstract() || $r->isTrait()) && $r->implementsInterface('Robo\Contract\TaskInterface');
})->prepend("# $ns Tasks");
sort($tasks);
foreach ($tasks as $class) {
$taskGenerator->docClass($class);
}
$taskGenerator->filterMethods(
function (\ReflectionMethod $m) {
if ($m->isConstructor() || $m->isDestructor() || $m->isStatic()) {
return false;
}
return !in_array($m->name, ['run', '', '__call', 'getCommand', 'getPrinted']) && $m->isPublic(); // methods are not documented
}
)->processClassSignature(
function ($c) {
return "## " . preg_replace('~Task$~', '', $c->getShortName()) . "\n";
}
)->processClassDocBlock(
function (\ReflectionClass $c, $doc) {
$doc = preg_replace('~@method .*?(.*?)\)~', '* `$1)` ', $doc);
$doc = str_replace('\\'.$c->name, '', $doc);
return $doc;
}
)->processMethodSignature(
function (\ReflectionMethod $m, $text) {
return str_replace('#### *public* ', '* `', $text) . '`';
}
)->processMethodDocBlock(
function (\ReflectionMethod $m, $text) {
return $text ? ' ' . trim(strtok($text, "\n"), "\n") : '';
}
)->addToCollection($collection);
}
$collection->progressMessage('Documentation generation complete.');
return $collection;
}
/**
* Publish Robo.
*
* Builds a site in gh-pages branch. Uses mkdocs
*/
public function publish()
{
$current_branch = exec('git rev-parse --abbrev-ref HEAD');
$collection = $this->collection();
$this->taskGitStack()
->checkout('site')
->merge('master')
->addToCollection($collection);
$this->taskGitStack()
->checkout($current_branch)
->addAsCompletion($collection);
$this->taskFilesystemStack()
->copy('CHANGELOG.md', 'docs/changelog.md')
->addToCollection($collection);
$this->taskFilesystemStack()
->remove('docs/changelog.md')
->addAsCompletion($collection);
$this->taskExec('mkdocs gh-deploy')
->addToCollection($collection);
return $collection;
}
/**
* Build the Robo phar executable.
*/
public function pharBuild()
{
$collection = $this->collection();
$this->taskComposerInstall()
->noDev()
->printed(false)
->addToCollection($collection);
$packer = $this->taskPackPhar('robo.phar');
$files = Finder::create()->ignoreVCS(true)
->files()
->name('*.php')
->path('src')
->path('vendor')
->exclude('symfony/config/Tests')
->exclude('symfony/console/Tests')
->exclude('symfony/event-dispatcher/Tests')
->exclude('symfony/filesystem/Tests')
->exclude('symfony/finder/Tests')
->exclude('symfony/process/Tests')
->exclude('henrikbjorn/lurker/tests')
->in(__DIR__);
foreach ($files as $file) {
$packer->addFile($file->getRelativePathname(), $file->getRealPath());
}
$packer->addFile('robo', 'robo')
->executable('robo')
->addToCollection($collection);
$this->taskComposerInstall()
->printed(false)
->addToCollection($collection);
return $collection;
}
/**
* Install Robo phar.
*
* Installs the Robo phar executable in /usr/bin. Uses 'sudo'.
*/
public function pharInstall()
{
return $this->taskExec('sudo cp')
->arg('robo.phar')
->arg('/usr/bin/robo');
}
/**
* Publish Robo phar.
*
* Commits the phar executable to Robo's GitHub pages site.
*/
public function pharPublish()
{
$this->pharBuild()->run();
$this->_rename('robo.phar', 'robo-release.phar');
$this->taskGitStack()->checkout('gh-pages')->run();
$this->taskFilesystemStack()
->remove('robo.phar')
->rename('robo-release.phar', 'robo.phar')
->run();
$this->taskGitStack()
->add('robo.phar')
->commit('robo.phar published')
->push('origin', 'gh-pages')
->checkout('master')
->run();
}
/**
* Watch a file.
*
* Demonstrates the 'watch' command. Runs 'composer update' any time
* composer.json changes.
*/
public function tryWatch()
{
$this->taskWatch()->monitor(['composer.json', 'composer.lock'], function () {
$this->taskComposerUpdate()->run();
})->run();
}
/**
* Demonstrates Robo input APIs.
*/
public function tryInput()
{
$answer = $this->ask('how are you?');
$this->say('You are '.$answer);
$yes = $this->confirm('Do you want one more question?');
if (!$yes) {
return Result::cancelled();
}
$lang = $this->askDefault('what is your favorite scripting language?', 'PHP');
$this->say($lang);
$pin = $this->askHidden('Ok, now tell your PIN code (it is hidden)');
$this->yell('Ha-ha, your pin code is: '.$pin);
$this->say('Bye!');
}
/**
* Demonstrates parallel execution.
*
* @option $printed Print the output of each process.
* @option $error Include an extra process that fails.
*/
public function tryPara($options = ['printed' => false, 'error' => false])
{
$dir = __DIR__;
$para = $this->taskParallelExec()
->printed($options['printed'])
->process("php $dir/tests/_data/parascript.php hey 4")
->process("php $dir/tests/_data/parascript.php hoy 3")
->process("php $dir/tests/_data/parascript.php gou 2")
->process("php $dir/tests/_data/parascript.php die 1");
if ($options['error']) {
$para->process("ls $dir/tests/_data/filenotfound");
}
return $para;
}
/**
* Demonstrates Robo argument passing.
*
* @param string $a The first parameter. Required.
* @param string $b The second parameter. Optional.
*/
public function tryArgs($a, $b = 'default')
{
$this->say("The parameter a is $a and b is $b");
}
/**
* Demonstrate Robo variable argument passing.
*
* @param $a A list of commandline parameters.
*/
public function tryArrayArgs(array $a)
{
$this->say("The parameters passed are:\n" . var_export($a, true));
}
/**
* Demonstrate Robo boolean options.
*
* @option boolean $silent Supress output.
*/
public function tryOptbool($opts = ['silent|s' => false])
{
if (!$opts['silent']) {
$this->say("Hello, world");
}
}
/**
* Demonstrate the use of the PHP built-in webserver.
*/
public function tryServer()
{
return $this->taskServer(8000)
->dir('site')
->arg('site/index.php');
}
/**
* Demonstrate the use of the Robo open-browser task.
*/
public function tryOpenBrowser()
{
return $this->taskOpenBrowser([
'http://robo.li',
'https://github.com/Codegyre/Robo'
]);
}
/**
* Demonstrate Robo error output and command failure.
*/
public function tryError()
{
return $this->taskExec('ls xyzzy' . date('U'))->dir('/tmp');
}
/**
* Demonstrate Robo standard output and command success.
*/
public function trySuccess()
{
return $this->taskExec('pwd');
}
/**
* Demonstrate Robo formatters. Default format is 'table'.
*
* @field-labels
* first: I
* second: II
* third: III
* @usage try:formatters --format=yaml
* @usage try:formatters --format=csv
* @usage try:formatters --fields=first,third
* @usage try:formatters --fields=III,II
*/
public function tryFormatters($options = ['format' => 'table', 'fields' => ''])
{
$outputData = [
[ 'first' => 'One', 'second' => 'Two', 'third' => 'Three' ],
[ 'first' => 'Eins', 'second' => 'Zwei', 'third' => 'Drei' ],
[ 'first' => 'Ichi', 'second' => 'Ni', 'third' => 'San' ],
[ 'first' => 'Uno', 'second' => 'Dos', 'third' => 'Tres' ],
];
// Note that we can also simply return the output data array here.
return ResultData::message(new RowsOfFields($outputData));
}
/**
* Demonstrate what happens when a command or a task
* throws an exception. Note that typically, Robo commands
* should return Result objects rather than throw exceptions.
*/
public function tryException($options = ['task' => false])
{
if (!$options['task']) {
throw new RuntimeException('Command failed with an exception.');
}
return new ExceptionTask('Task failed with an exception.');
}
/**
* Demonstrate deprecated task behavior.
*
* Demonstrate what happens when using a task that is created via
* direct instantiation, which omits initialization done by the
* container. Emits a warning message.
*/
public function tryDeprecated()
{
// Calling 'new' directly without manually setting
// up dependencies will result in a deprecation warning.
// @see RoboFile::trySuccess()
return new \Robo\Task\Base\Exec('pwd');
}
/**
* Demonstrates Robo temporary directory usage.
*/
public function tryTmpDir()
{
// Set up a collection to add tasks to
$collection = $this->collection();
// Get a temporary directory to work in. Note that we get a
// name back, but the directory is not created until the task
// runs. This technically is not thread-safe, but we create
// a random name, so it is unlikely to conflict.
$tmpPath = $this->taskTmpDir()
->addToCollection($collection)
->getPath();
$this->taskWriteToFile("$tmpPath/file.txt")
->line('Example file')
->addToCollection($collection);
// We can create the temporary directory early by running
// 'runWithoutCompletion()'. n.b. if we called 'run()' at
// this point, the collection's 'complete()' method would be
// called, and the temporary directory would be deleted.
$mktmpResult = $collection->runWithoutCompletion();
if (!$mktmpResult->wasSuccessful()) {
$this->say("Could not create temporary directory.");
return 1;
}
if (is_dir($tmpPath)) {
$this->say("Created a temporary directory at $tmpPath");
} else {
$this->say("Requested a temporary directory at $tmpPath, but it was not created");
}
// Run the task collection
$result = $collection->run();
if (is_dir($tmpPath)) {
$this->say("The temporary directory at $tmpPath was not cleaned up after the collection completed.");
} else {
$this->say("The temporary directory at $tmpPath was automatically deleted.");
}
return $result;
}
}
class ExceptionTask extends \Robo\Task\BaseTask
{
protected $message;
public function __construct($message)
{
$this->message = $message;
}
public function run()
{
throw new RuntimeException($this->message);
}
}