RoboFile.php 15.5 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 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
<?php
use Symfony\Component\Finder\Finder;

class RoboFile extends \Robo\Tasks
{
    /**
     * Run the Robo unit tests.
     */
    public function test(array $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->run();
     }

    /**
     * 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 --exclude=Squiz.Classes.ValidClassName {$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 --exclude=Squiz.Classes.ValidClassName {$file}")->run();
            }
        }
        return $result;
    }

    /**
     * Generate a new Robo task that wraps an existing utility class.
     *
     * @param string $className The name of the existing utility class to wrap.
     * @param string $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)->run();
    }

    /**
     * Release Robo.
     */
    public function release($opts = ['beta' => false])
    {
        $this->checkPharReadonly();

        $version = \Robo\Robo::VERSION;
        $stable = !$opts['beta'];
        if ($stable) {
            $version = preg_replace('/-.*/', '', $version);
        }
        else {
            $version = $this->incrementVersion($version, 'beta');
        }
        $this->writeVersion($version);
        $this->yell("Releasing Robo $version");

        $this->docs();
        $this->taskGitStack()
            ->add('-A')
            ->commit("Robo release $version")
            ->pull()
            ->push()
            ->run();

        $this->publish();
        $this->taskGitStack()
            ->tag($version)
            ->push('origin 1.x --tags')
            ->run();

        if ($stable) {
            $this->pharPublish();
            $version = $this->incrementVersion($version) . '-dev';
            $this->writeVersion($version);

            $this->taskGitStack()
                ->add('-A')
                ->commit("Prepare for $version")
                ->push()
                ->run();
        }
    }

    /**
     * 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)
    {
        $version = preg_replace('/-.*/', '', \Robo\Robo::VERSION);
        return $this->taskChangelog()
            ->version($version)
            ->change($addition)
            ->run();
    }

    /**
     * Update the version of Robo.
     *
     * @param string $version The new verison for Robo.
     *   Defaults to the next minor (bugfix) version after the current relelase.
     * @option stage The version stage: dev, alpha, beta or rc. Use empty for stable.
     */
    public function versionBump($version = '', $options = ['stage' => ''])
    {
        // If the user did not specify a version, then update the current version.
        if (empty($version)) {
            $version = $this->incrementVersion(\Robo\Robo::VERSION, $options['stage']);
        }
        return $this->writeVersion($version);
    }

    /**
     * Write the specified version string back into the Robo.php file.
     * @param string $version
     */
    protected function writeVersion($version)
    {
        // Write the result to a file.
        return $this->taskReplaceInFile(__DIR__.'/src/Robo.php')
            ->regex("#VERSION = '[^']*'#")
            ->to("VERSION = '".$version."'")
            ->run();
    }

    /**
     * Advance to the next SemVer version.
     *
     * The behavior depends on the parameter $stage.
     *   - If $stage is empty, then the patch or minor version of $version is incremented
     *   - If $stage matches the current stage in the current version, then add one
     *     to the stage (e.g. alpha3 -> alpha4)
     *   - If $stage does not match the current stage in the current version, then
     *     reset to '1' (e.g. alpha4 -> beta1)
     *
     * @param string $version A SemVer version
     * @param string $stage dev, alpha, beta, rc or an empty string for stable.
     * @return string
     */
    protected function incrementVersion($version, $stage = '')
    {
        $stable = empty($stage);
        $versionStageNumber = '0';
        preg_match('/-([a-zA-Z]*)([0-9]*)/', $version, $match);
        $match += ['', '', ''];
        $versionStage = $match[1];
        $versionStageNumber = $match[2];
        if ($versionStage != $stage) {
            $versionStageNumber = 0;
        }
        $version = preg_replace('/-.*/', '', $version);
        $versionParts = explode('.', $version);
        if ($stable) {
            $versionParts[count($versionParts)-1]++;
        }
        $version = implode('.', $versionParts);
        if (!$stable) {
            $version .= '-' . $stage;
            if ($stage != 'dev') {
                $versionStageNumber++;
                $version .= $versionStageNumber;
            }
        }
        return $version;
    }

    /**
     * Generate the Robo documentation files.
     */
    public function docs()
    {
        $collection = $this->collectionBuilder();
        $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 = $collection->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;
                    }
                    $undocumentedMethods =
                    [
                        '',
                        'run',
                        '__call',
                        'inflect',
                        'injectDependencies',
                        'getCommand',
                        'getPrinted',
                        'getConfig',
                        'setConfig',
                        'logger',
                        'setLogger',
                        'setProgressIndicator',
                        'progressIndicatorSteps',
                        'setBuilder',
                        'getBuilder',
                        'collectionBuilder',
                        'setVerbosityThreshold',
                        'verbosityThreshold',
                        'setOutputAdapter',
                        'outputAdapter',
                        'hasOutputAdapter',
                        'verbosityMeetsThreshold',
                        'writeMessage',
                        'detectInteractive',
                        'background',
                        'timeout',
                        'idleTimeout',
                        'env',
                        'envVars',
                        'setInput',
                        'interactive',
                        'silent',
                        'printed',
                        'printOutput',
                        'printMetadata',
                    ];
                    return !in_array($m->name, $undocumentedMethods) && $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") : '';
                }
            );
        }
        $collection->progressMessage('Documentation generation complete.');
        return $collection->run();
    }

    /**
     * Publish Robo.
     *
     * Builds a site in gh-pages branch. Uses mkdocs
     */
    public function publish()
    {
        $current_branch = exec('git rev-parse --abbrev-ref HEAD');

        return $this->collectionBuilder()
            ->taskGitStack()
                ->checkout('site')
                ->merge('1.x')
            ->completion($this->taskGitStack()->checkout($current_branch))
            ->taskFilesystemStack()
                ->copy('CHANGELOG.md', 'docs/changelog.md')
            ->completion($this->taskFilesystemStack()->remove('docs/changelog.md'))
            ->taskExec('mkdocs gh-deploy')
            ->run();
    }

    /**
     * Build the Robo phar executable.
     */
    public function pharBuild()
    {
        $this->checkPharReadonly();

        // Create a collection builder to hold the temporary
        // directory until the pack phar task runs.
        $collection = $this->collectionBuilder();

        $workDir = $collection->tmpDir();
        $roboBuildDir = "$workDir/robo";

        // Before we run `composer install`, we will remove the dev
        // dependencies that we only use in the unit tests.  Any dev dependency
        // that is in the 'suggested' section is used by a core task;
        // we will include all of those in the phar.
        $devProjectsToRemove = $this->devDependenciesToRemoveFromPhar();

        // We need to create our work dir and run `composer install`
        // before we prepare the pack phar task, so create a separate
        // collection builder to do this step in.
        $prepTasks = $this->collectionBuilder();

        $preparationResult = $prepTasks
            ->taskFilesystemStack()
                ->mkdir($workDir)
            ->taskRsync()
                ->fromPath(
                    [
                        __DIR__ . '/composer.json',
                        __DIR__ . '/scripts',
                        __DIR__ . '/src',
                        __DIR__ . '/data'
                    ]
                )
                ->toPath($roboBuildDir)
                ->recursive()
                ->progress()
                ->stats()
            ->taskComposerRemove()
                ->dir($roboBuildDir)
                ->dev()
                ->noUpdate()
                ->args($devProjectsToRemove)
            ->taskComposerInstall()
                ->dir($roboBuildDir)
                ->noScripts()
                ->printed(true)
                ->run();

        // Exit if the preparation step failed
        if (!$preparationResult->wasSuccessful()) {
            return $preparationResult;
        }

        // Decide which files we're going to pack
        $files = Finder::create()->ignoreVCS(true)
            ->files()
            ->name('*.php')
            ->name('*.exe') // for 1symfony/console/Resources/bin/hiddeninput.exe
            ->name('GeneratedWrapper.tmpl')
            ->path('src')
            ->path('vendor')
            ->notPath('docs')
            ->notPath('/vendor\/.*\/[Tt]est/')
            ->in(is_dir($roboBuildDir) ? $roboBuildDir : __DIR__);

        // Build the phar
        return $collection
            ->taskPackPhar('robo.phar')
                ->addFiles($files)
                ->addFile('robo', 'robo')
                ->executable('robo')
            ->taskFilesystemStack()
                ->chmod('robo.phar', 0777)
            ->run();
    }

    protected function checkPharReadonly()
    {
        if (ini_get('phar.readonly')) {
            throw new \Exception('Must set "phar.readonly = Off" in php.ini to build phars.');
        }
    }

    /**
     * The phar:build command removes the project requirements from the
     * 'require-dev' section that are not in the 'suggest' section.
     *
     * @return array
     */
    protected function devDependenciesToRemoveFromPhar()
    {
        $composerInfo = (array) json_decode(file_get_contents(__DIR__ . '/composer.json'));

        $devDependencies = array_keys((array)$composerInfo['require-dev']);
        $suggestedProjects = array_keys((array)$composerInfo['suggest']);

        return array_diff($devDependencies, $suggestedProjects);
    }

    /**
     * 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')
            ->run();
    }

    /**
     * Publish Robo phar.
     *
     * Commits the phar executable to Robo's GitHub pages site.
     */
    public function pharPublish()
    {
        $this->pharBuild();

        $this->collectionBuilder()
            ->taskFilesystemStack()
                ->rename('robo.phar', 'robo-release.phar')
            ->taskGitStack()
                ->checkout('site')
                ->pull('origin site')
            ->taskFilesystemStack()
                ->remove('robotheme/robo.phar')
                ->rename('robo-release.phar', 'robotheme/robo.phar')
            ->taskGitStack()
                ->add('robotheme/robo.phar')
                ->commit('Update robo.phar to ' . \Robo\Robo::VERSION)
                ->push('origin site')
                ->checkout('1.x')
                ->run();
    }
}