-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcli.php
executable file
·555 lines (482 loc) · 16.4 KB
/
cli.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
550
551
552
553
554
555
#!/usr/bin/env php
<?php
use dokuwiki\Extension\CLIPlugin;
use dokuwiki\Extension\PluginController;
use dokuwiki\plugin\dev\LangProcessor;
use dokuwiki\plugin\dev\Skeletor;
use dokuwiki\plugin\dev\SVGIcon;
use splitbrain\phpcli\Exception as CliException;
use splitbrain\phpcli\Options;
/**
* @license GPL2
* @author Andreas Gohr <andi@splitbrain.org>
*/
class cli_plugin_dev extends CLIPlugin
{
/**
* Register options and arguments on the given $options object
*
* @param Options $options
* @return void
*/
protected function setup(Options $options)
{
$options->useCompactHelp();
$options->setHelp(
"CLI to help with DokuWiki plugin and template development.\n\n" .
"Run this script from within the extension's directory."
);
$options->registerCommand('init', 'Initialize a new plugin or template in the current directory.');
$options->registerCommand('addTest', 'Add the testing framework files and a test. (_test/)');
$options->registerArgument('test', 'Optional name of the new test. Defaults to the general test.', false,
'addTest');
$options->registerCommand('addConf', 'Add the configuration files. (conf/)');
$options->registerCommand('addLang', 'Add the language files. (lang/)');
$types = PluginController::PLUGIN_TYPES;
array_walk(
$types,
function (&$item) {
$item = $this->colors->wrap($item, $this->colors::C_BROWN);
}
);
$options->registerCommand('addComponent', 'Add a new plugin component.');
$options->registerArgument('type', 'Type of the component. Needs to be one of ' . join(', ', $types), true,
'addComponent');
$options->registerArgument('name', 'Optional name of the component. Defaults to a base component.', false,
'addComponent');
$options->registerCommand('deletedFiles', 'Create the list of deleted files based on the git history.');
$options->registerCommand('rmObsolete', 'Delete obsolete files.');
$prefixes = array_keys(SVGIcon::SOURCES);
array_walk(
$prefixes,
function (&$item) {
$item = $this->colors->wrap($item, $this->colors::C_BROWN);
}
);
$options->registerCommand('downloadSvg', 'Download an SVG file from a known icon repository.');
$options->registerArgument('prefix:name',
'Colon-prefixed name of the icon. Available prefixes: ' . join(', ', $prefixes), true, 'downloadSvg');
$options->registerArgument('output', 'File to save, defaults to <name>.svg in current dir', false,
'downloadSvg');
$options->registerOption('keep-ns', 'Keep the SVG namespace. Use when the file is not inlined into HTML.', 'k',
false, 'downloadSvg');
$options->registerCommand('cleanSvg', 'Clean a existing SVG files to reduce their file size.');
$options->registerArgument('files...', 'The files to clean (will be overwritten)', true, 'cleanSvg');
$options->registerOption('keep-ns', 'Keep the SVG namespace. Use when the file is not inlined into HTML.', 'k',
false, 'cleanSvg');
$options->registerCommand('cleanLang',
'Clean language files from unused language strings. Detecting which strings are truly in use may ' .
'not always correctly work. Use with caution.');
$options->registerCommand('test', 'Run the unit tests for this extension.');
$options->registerCommand('check', 'Check for code style violations.');
$options->registerArgument('files...', 'The files to check. Defaults to the whole extension.', false, 'check');
$options->registerCommand('fix', 'Fix code style violations and refactor outdated code.');
$options->registerArgument('files...', 'The files to check. Defaults to the whole extension.', false, 'fix');
}
/** @inheritDoc */
protected function main(Options $options)
{
$args = $options->getArgs();
switch ($options->getCmd()) {
case 'init':
return $this->cmdInit();
case 'addTest':
$test = array_shift($args);
return $this->cmdAddTest($test);
case 'addConf':
return $this->cmdAddConf();
case 'addLang':
return $this->cmdAddLang();
case 'addComponent':
$type = array_shift($args);
$component = array_shift($args);
return $this->cmdAddComponent($type, $component);
case 'deletedFiles':
return $this->cmdDeletedFiles();
case 'rmObsolete':
return $this->cmdRmObsolete();
case 'downloadSvg':
$ident = array_shift($args);
$save = array_shift($args);
$keep = $options->getOpt('keep-ns');
return $this->cmdDownloadSVG($ident, $save, $keep);
case 'cleanSvg':
$keep = $options->getOpt('keep-ns');
return $this->cmdCleanSVG($args, $keep);
case 'cleanLang':
return $this->cmdCleanLang();
case 'test':
return $this->cmdTest();
case 'check':
return $this->cmdCheck($args);
case 'fix':
return $this->cmdFix();
default:
$this->error('Unknown command');
echo $options->help();
return 0;
}
}
/**
* Get the extension name from the current working directory
*
* @throws CliException if something's wrong
* @param string $dir
* @return string[] name, type
*/
protected function getTypedNameFromDir($dir)
{
$pdir = fullpath(DOKU_PLUGIN);
$tdir = fullpath(tpl_incdir() . '../');
if (strpos($dir, $pdir) === 0) {
$ldir = substr($dir, strlen($pdir));
$type = 'plugin';
} elseif (strpos($dir, $tdir) === 0) {
$ldir = substr($dir, strlen($tdir));
$type = 'template';
} else {
throw new CliException('Current directory needs to be in plugin or template directory');
}
$ldir = trim($ldir, '/');
if (strpos($ldir, '/') !== false) {
throw new CliException('Current directory has to be main extension directory');
}
return [$ldir, $type];
}
/**
* Interactively ask for a value from the user
*
* @param string $prompt
* @param bool $cache cache given value for next time?
* @return string
*/
protected function readLine($prompt, $cache = false)
{
$value = '';
$default = '';
$cachename = getCacheName($prompt, '.readline');
if ($cache && file_exists($cachename)) {
$default = file_get_contents($cachename);
}
while ($value === '') {
echo $prompt;
if ($default) echo ' [' . $default . ']';
echo ': ';
$fh = fopen('php://stdin', 'r');
$value = trim(fgets($fh));
fclose($fh);
if ($value === '') $value = $default;
}
if ($cache) {
file_put_contents($cachename, $value);
}
return $value;
}
/**
* Create the given files with their given content
*
* Ignores all files that already exist
*
* @param array $files A File array as created by Skeletor::getFiles()
*/
protected function createFiles($files)
{
foreach ($files as $path => $content) {
if (file_exists($path)) {
$this->error($path . ' already exists');
continue;
}
io_makeFileDir($path);
file_put_contents($path, $content);
$this->success($path . ' created');
}
}
/**
* Delete the given file if it exists
*
* @param string $file
*/
protected function deleteFile($file)
{
if (!file_exists($file)) return;
if (@unlink($file)) {
$this->success('Delete ' . $file);
}
}
/**
* Run git with the given arguments and return the output
*
* @throws CliException when the command can't be run
* @param string ...$args
* @return string[]
*/
protected function git(...$args)
{
$args = array_map('escapeshellarg', $args);
$cmd = 'git ' . join(' ', $args);
$output = [];
$result = 0;
$this->info($cmd);
$last = exec($cmd, $output, $result);
if ($last === false || $result !== 0) {
throw new CliException('Running git failed');
}
return $output;
}
// region Commands
/**
* Intialize the current directory as a plugin or template
*
* @return int
*/
protected function cmdInit()
{
$dir = fullpath(getcwd());
if ((new FilesystemIterator($dir))->valid()) {
// existing directory, initialize from info file
$skeletor = Skeletor::fromDir($dir);
} else {
// new directory, ask for info
[$base, $type] = $this->getTypedNameFromDir($dir);
$user = $this->readLine('Your Name', true);
$mail = $this->readLine('Your E-Mail', true);
$desc = $this->readLine('Short description');
$skeletor = new Skeletor($type, $base, $desc, $user, $mail);
}
$skeletor->addBasics();
$this->createFiles($skeletor->getFiles());
if (!is_dir("$dir/.git")) {
try {
$this->git('init');
} catch (CliException $e) {
$this->error($e->getMessage());
}
}
return 0;
}
/**
* Add test framework
*
* @param string $test Name of the Test to add
* @return int
*/
protected function cmdAddTest($test = '')
{
$skeletor = Skeletor::fromDir(getcwd());
$skeletor->addTest($test);
$this->createFiles($skeletor->getFiles());
return 0;
}
/**
* Add configuration
*
* @return int
*/
protected function cmdAddConf()
{
$skeletor = Skeletor::fromDir(getcwd());
$skeletor->addConf(is_dir('lang'));
$this->createFiles($skeletor->getFiles());
return 0;
}
/**
* Add language
*
* @return int
*/
protected function cmdAddLang()
{
$skeletor = Skeletor::fromDir(getcwd());
$skeletor->addLang(is_dir('conf'));
$this->createFiles($skeletor->getFiles());
return 0;
}
/**
* Add another component to the plugin
*
* @param string $type
* @param string $component
*/
protected function cmdAddComponent($type, $component = '')
{
$skeletor = Skeletor::fromDir(getcwd());
$skeletor->addComponent($type, $component);
$this->createFiles($skeletor->getFiles());
return 0;
}
/**
* Generate a list of deleted files from git
*
* @link https://stackoverflow.com/a/6018049/172068
*/
protected function cmdDeletedFiles()
{
if (!is_dir('.git')) throw new CliException('This extension seems not to be managed by git');
$output = $this->git('log', '--no-renames', '--pretty=format:', '--name-only', '--diff-filter=D');
$output = array_map('trim', $output);
$output = array_filter($output);
$output = array_unique($output);
$output = array_filter($output, function ($item) {
return !file_exists($item);
});
sort($output);
if (!count($output)) {
$this->info('No deleted files found');
return 0;
}
$content = "# This is a list of files that were present in previous releases\n" .
"# but were removed later. They should not exist in your installation.\n" .
join("\n", $output) . "\n";
file_put_contents('deleted.files', $content);
$this->success('written deleted.files');
return 0;
}
/**
* Remove files that shouldn't be here anymore
*/
protected function cmdRmObsolete()
{
$this->deleteFile('_test/general.test.php');
$this->deleteFile('.travis.yml');
$this->deleteFile('.github/workflows/phpTestLinux.yml');
return 0;
}
/**
* Download a remote icon
*
* @param string $ident
* @param string $save
* @param bool $keep
* @return int
* @throws Exception
*/
protected function cmdDownloadSVG($ident, $save = '', $keep = false)
{
$svg = new SVGIcon($this);
$svg->keepNamespace($keep);
return (int)$svg->downloadRemoteIcon($ident, $save);
}
/**
* @param string[] $files
* @param bool $keep
* @return int
* @throws Exception
*/
protected function cmdCleanSVG($files, $keep = false)
{
$svg = new SVGIcon($this);
$svg->keepNamespace($keep);
$ok = true;
foreach ($files as $file) {
$ok = $ok && $svg->cleanSVGFile($file);
}
return (int)$ok;
}
/**
* @return int
*/
protected function cmdCleanLang()
{
$lp = new LangProcessor($this);
$files = glob('./lang/*/lang.php');
foreach ($files as $file) {
$lp->processLangFile($file);
}
$files = glob('./lang/*/settings.php');
foreach ($files as $file) {
$lp->processSettingsFile($file);
}
return 0;
}
/**
* @return int
*/
protected function cmdTest()
{
$dir = fullpath(getcwd());
[$base, $type] = $this->getTypedNameFromDir($dir);
if ($this->colors->isEnabled()) {
$colors = 'always';
} else {
$colors = 'never';
}
$args = [
fullpath(__DIR__ . '/../../../_test/vendor/bin/phpunit'),
'--verbose',
"--colors=$colors",
'--configuration', fullpath(__DIR__ . '/../../../_test/phpunit.xml'),
'--group', $type . '_' . $base,
];
$cmd = join(' ', array_map('escapeshellarg', $args));
$this->info("Running $cmd");
$result = 0;
passthru($cmd, $result);
return $result;
}
/**
* @return int
*/
protected function cmdCheck($files = [])
{
$dir = fullpath(getcwd());
$args = [
fullpath(__DIR__ . '/../../../_test/vendor/bin/phpcs'),
'--standard=' . fullpath(__DIR__ . '/../../../_test/phpcs.xml'),
($this->colors->isEnabled()) ? '--colors' : '--no-colors',
'--',
];
if ($files) {
$args = array_merge($args, $files);
} else {
$args[] = fullpath($dir);
}
$cmd = join(' ', array_map('escapeshellarg', $args));
$this->info("Running $cmd");
$result = 0;
passthru($cmd, $result);
return $result;
}
/**
* @return int
*/
protected function cmdFix($files = [])
{
$dir = fullpath(getcwd());
// first run rector to refactor outdated code
$args = [
fullpath(__DIR__ . '/../../../_test/vendor/bin/rector'),
($this->colors->isEnabled()) ? '--ansi' : '--no-ansi',
'--config=' . fullpath(__DIR__ . '/../../../_test/rector.php'),
'--no-diffs',
'process',
];
if ($files) {
$args = array_merge($args, $files);
} else {
$args[] = fullpath($dir);
}
$cmd = join(' ', array_map('escapeshellarg', $args));
$this->info("Running $cmd");
$result = 0;
passthru($cmd, $result);
if($result !== 0) return $result;
// now run phpcbf to clean up code style
$args = [
fullpath(__DIR__ . '/../../../_test/vendor/bin/phpcbf'),
'--standard=' . fullpath(__DIR__ . '/../../../_test/phpcs.xml'),
($this->colors->isEnabled()) ? '--colors' : '--no-colors',
'--',
];
if ($files) {
$args = array_merge($args, $files);
} else {
$args[] = fullpath($dir);
}
$cmd = join(' ', array_map('escapeshellarg', $args));
$this->info("Running $cmd");
$result = 0;
passthru($cmd, $result);
return $result;
}
//endregion
}