Refactoring

This commit is contained in:
gamonoid
2017-09-03 20:39:22 +02:00
parent af40881847
commit a7274d3cfd
5075 changed files with 238202 additions and 16291 deletions

View File

@@ -0,0 +1,250 @@
# Collection Builders
Robo provides task collections as a means of making error detection and recovery easier. When Robo tasks are added to a collection, their execution is deferred until the `$collection->run()` method is called. If one of the tasks fail, then the operation will be aborted; rollback tasks may also be defined to restore the system to its original condition.
When using collections, a Robo script will go through three phases:
1. Determine which tasks will need to be run, and create a task builder.
- Assign values to variables.
- Do not alter the state of the system.
2. Create the necessary tasks via the task builder.
- Use variables calculated in the first phase in task parameters.
3. Run the tasks via the `run()` method.
- Check and report errors once after `run()` returns.
Following this pattern will keep your code linear and easy to understand.
## Collections API
Collections are made up of a combination of tasks and/or `callable` functions / method pointers, such as:
- A task (implements TaskInterface)
- A function name (string)
- A closure (inline function)
- A method reference (array with object and method name)
Examples of adding different kinds of tasks to a collection are provided below.
### TaskInterface Objects
```php
<?php
$collection->add(
$this->taskExec('ls')
);
?>
```
### Functions
```php
<?php
$collection->addCode('mytaskfunction');
?>
```
### Closures
```php
<?php
$collection->addCode(
function() use ($work)
{
// do something with $work
});
?>
```
### Methods
```php
<?php
$collection->addCode([$myobject, 'mymethod']);
?>
```
## Using a Collection Builder
To manage a collection of tasks, a collection builder. Collection builders allow tasks to be created via chained methods. All of the tasks created by the same builder are added to a collection; when the `run()` method is called, all of the tasks in the collection run.
The 'publish' command from Robo's own RoboFile is shown below. It uses a collection builder to run some git and filesystem operations. The "completion" tasks are run after all other tasks complete, or during rollback processing when an operation fails.
``` php
<?php
class RoboFile extends \Robo\Tasks
{
public function publish()
{
$current_branch = exec('git rev-parse --abbrev-ref HEAD');
$collection = $this->collectionBuilder();
$collection->taskGitStack()
->checkout('site')
->merge('master')
->completion($this->taskGitStack()->checkout($current_branch))
->taskFilesystemStack()
->copy('CHANGELOG.md', 'docs/changelog.md')
->completion($this->taskFilesystemStack()->remove('docs/changelog.md'))
->taskExec('mkdocs gh-deploy');
return $collection;
}
}
?>
```
The example above also adds a couple of tasks as "completions"; these are run when the collection completes execution, as explained below.
## Rollbacks and Completions
Robo also provides rollbacks and completions, special tasks that are eligible to run only if all of the tasks added to the collection before them succeed. The section below explains the circumstances under which these tasks will run.
### Completion Tasks
Completions run whenever their collection completes or fails, but only if all of the tasks that come before it succeed. An example of this is shown in the first example above. A filesystem stack task copies CHANDELOG.md to docs/changelog.md; after this task is added to the collection, another filesystem stack task is added as a completion to delete docs/changelog.md. This is done because docs/changelog.md is only intended to exist long enough to be used by the `mkdocs` task, which is added later.
### Rollback Tasks
In addition to completions, Robo also supports rollbacks. Rollback tasks can be used to clean up after failures, so the state of the system does not change when execution is interrupted by an error. A rollback task is executed if all of the tasks that come before it succeed, and at least one of the tasks that come after it fails. If all tasks succeed, then no rollback tasks are executed.
### Rollback and Completion Methods
Any task may also implement \Robo\Contract\RollbackInterface; if this is done, then its `rollback()` method will be called if the task is `run()` on a collection that later fails.
Use `addAsCompletion($collection)` in place of `addAsRollback($collection)`, or implement \Robo\Contract\CompletionInterface. Completions otherwise work exactly like rollbacks.
## Temporary Objects
Since the concept of temporary objects that are cleaned up on failure is a common pattern, Robo provides built-in support for them. Temporary directories and files are provided out of the box; other kinds of temporary objects can be easily created using the Temporary global collection.
### Temporary Directories
It is recommended that operations that perform multiple filesystem operations should, whenever possible, do most of their work in a temporary directory. Temporary directories are created by `$this->taskTmpDir()`, and are automatically be removed when the collection completes or rolls back. As an added convenience, the CollectionBuilder class has a `tmpDir()` method that creates a temporary directory via `taskTmpDir()`, and then returns the path to the temporary directory.
``` php
<?php
class RoboFile extends \Robo\Tasks
{
function myOperation()
{
$collection = $this->collectionBuilder();
// Create a temporary directory, and fetch its path.
$work = $collection->tmpDir();
$collection
->taskWriteToFile("$work/README.md")
->line('-----')
->line(date('Y-m-d').' Generated file: do not edit.')
->line('----');
// If all of the preceding tasks succeed, then rename the temporary
// directory to its final name.
$collection->taskFilesystemStack()
->rename($work, 'destination');
return $collection->run();
}
}
?>
```
In the previous example, the path to the temporary directory is stored in the variable `$work`, and is passed as needed to the parameters of the other tasks as they are added to the collection. After the task collection is run, the temporary directory will be automatically deleted. In the example above, the temporary directory is renamed by the last task in the collection. This allows the working directory to persist; the collection will still attempt to remove the working directory, but no errors will be thrown if it no longer exists in its original location. Following this pattern allows Robo scripts to easily and safely do work that cleans up after itself on failure, without introducing a lot of branching or additional error recovery code. This paradigm is common enough to warrant a shortcut method of accomplishing the same thing. The example below is identical to the one above, save for the fact that it uses the `workDir()` method instead of `tmpDir()`. `workDir()` renames the temporary directory to its final name if the collection completes; any directory that exists in the same location will be overwritten at that time, but will persist if the collection roles back.
``` php
<?php
class RoboFile extends \Robo\Tasks
{
function myOperation()
{
$collection = $this->collectionBuilder();
// Create a temporary directory, and fetch its path.
// If all of the tasks succeed, then rename the temporary directory
// to its final name.
$work = $collection->workDir('destination');
$collection
->taskWriteToFile("$work/README.md")
->line('-----')
->line(date('Y-m-d').' Generated file: do not edit.')
->line('----');
return $collection->run();
}
}
?>
```
Temporary directories may also be created via the shortcut `$this->_tmpDir();`. Temporary directories created in this way are deleted when the script terminates.
### Temporary Files
Robo also provides an API for creating temporary files. They may be created via `$this->taskTmpFile()`; they are used exactly like `$this->taskWrite()`, except they are given a random name on creation, and are deleted when their collection completes. If they are not added to a collection, then they are deleted when the script terminates.
### The Temporary Global Collection
Robo maintains a special collection called the Temporary global collection. This collection is used to keep track of temporary objects that are not part of any collection. For example, Robo temporary directories and temporary files are managed by the Temporary global collection. These temporary objects are cleaned up automatically when the script terminates.
It is easy to create your own temporary tasks that behave in the same way as the provided temporary directory and temporary file tasks. There are two steps required:
- Implement \Robo\Contract\CompletionInterface
- Wrap the task via Temporary::wrap()
For example, the implementation of taskTmpFile() looks like this:
``` php
<?php
protected function taskTmpFile($filename = 'tmp', $extension = '', $baseDir = '', $includeRandomPart = true)
{
return Temporary::wrap(new TmpFile($filename, $extension, $baseDir, $includeRandomPart));
}
?>
```
The `complete()` method of the task will be called once the Collection the temporary object is attached to finishes running. If the temporary is not added to a collection, then its `complete()` method will be called when the script terminates.
## Named Tasks
It is also possible to provide names for the tasks added to a collection. This has two primary benefits:
1. Any result data returned from a named task is stored in the Result object under the task name.
2. It is possible for other code to add more tasks before or after any named task.
This feature is useful if you have functions that create task collections, and return them as a function results. The original caller can then use the `$collection->before()` or `$collection->after()` to insert sequenced tasks into the set of operations to be performed. One reason this might be done would be to define a base set of operations to perform (e.g. in a deploy), and then apply modifications for other environments (e.g. dev or stage).
```php
<?php
$collection->addCode(
function() use ($work)
{
// do something with $work
},
"taskname");
?>
```
Given a collection with named tasks, it is possible to insert more tasks before or after a task of a given name.
```php
<?php
$collection->after("taskname",
function() use ($work)
{
// do something with $work after "taskname" executes, if it succeeds.
});
?>
```
```php
<?php
$collection->before("taskname",
function() use ($work)
{
// do something with $work before "taskname" executes.
});
?>
```
It is recommended that named tasks be avoided unless specifically needed.

View File

@@ -0,0 +1,191 @@
# Extending
Robo tasks can be added to your Robo application by using Composer to suppliment the set of built-in tasks that Robo provides by default. To find existing Robo task extensions, search in Packagist for projects of type [robo-tasks](https://packagist.org/search/?type=robo-tasks).
The convention used to add new tasks for use in your RoboFiles is to create a wrapper trait named `loadTasks` that instantiates the implementation class for each task. Each task method in the trait should start with the prefix `task`, and should use **chained method calls** for configuration. Task execution should be triggered by the method `run`.
To include additional tasks in your RoboFile, you must `use` the appropriate `loadTasks` in your RoboFile. See the section [Including Additional Tasks](#including-additional-tasks) below. To create your own Robo extension that provides tasks for use in RoboFiles, then you must write your own class that implements TaskInterface, and create a `loadTasks` trait for it as described in the section [Creating a Robo Extension](#creating-a-robo-extension).
## Including Additional Tasks
Additional tasks may be installed into projects that have included Robo via Composer. For example:
```
$ cd myproject
$ composer require boedah/robo-drush
```
If any of the tasks you include require external Composer projects themselves, then you must `composer require` these as well. See the `suggests` section of Robo's composer.json file for a list of some projects you might need to require.
Once the extension you wish to use has been added to your vendor directory, you may then include it from your RoboFile:
``` php
class RoboFile extends \Robo\Tasks
{
use \Boedah\Robo\Task\Drush\loadTasks;
public function test()
{
// ...
}
}
```
Once you have done this, all of the tasks defined in the extension you selected will be available for use in your commands.
Note that at the moment, it is not possible to extend Robo when using the robo.phar. This capability may be added in the future via [embedded composer](https://github.com/dflydev/dflydev-embedded-composer).
## Creating a Robo Extension
A Robo tasks extension is created by advertising a Composer package of type `robo-tasks` on [Packagist](https://packagist.org/). For an overview on how this is done, see the article [Creating your very own Composer Package](https://knpuniversity.com/screencast/question-answer-day/create-composer-package). Specific instructions for creating Robo task extensions are provided below.
### Create your composer.json File
Your composer.json file should look something like the example below:
```
{
"name": "boedah/robo-drush",
"description": "Drush CommandStack for Robo Task Runner",
"type": "robo-tasks",
"autoload": {
"psr-4": {
"Boedah\\Robo\\Task\\Drush\\": "src"
}
},
"require": {
"php": ">=5.5.0",
"consolidation/robo": "~1"
}
}
```
Customize the name and autoload paths as necessary, and add any additional required projects needed by the tasks that your extensions will provide. The type of your project should always be `robo-tasks`. Robo only supports php >= 5.5.0; you may require a higher version of php if necessary.
### Create the loadTasks.php Trait
It is recommended to place your trait-loading task in a `loadTasks` file in the same namespace as the task implementation.
```
namespace Boedah\Robo\Task\Drush;
use Robo\Container\SimpleServiceProvider;
trait loadTasks
{
/**
* @param string $pathToDrush
* @return DrushStack
*/
protected function taskDrushStack($pathToDrush = 'drush')
{
return $this->task(__FUNCTION__, $pathToDrush);
}
}
```
Note that the name of the service for a given task must start with the word "task", and must have the same name as the function used to call the task. `$this->task()` looks up the service by name; using the PHP built-in constant __FUNCTION__ for this parameter ensures that the names of these items remain in alignment.
### Task implementation
The implementation of each task class should extend \Robo\Task\BaseTask, or some class that extends the same, and should used chained initializer methods and defer all operations that alter the state of the system until its `run()` method. If you follow these patterns, then your task extensions will be usable via Robo collection builders, as explained in the [collections](collections.md) documentation.
There are many examples of task implementations in the Robo\Task namespace. A very basic task example is provided below. The namespace is `MyAssetTasks`, and the example task is `CompileAssets`. To customize to your purposes, choose an appropriate namespace, and then define as many tasks as you need.
``` php
<?php
namespace MyAssetTasks;
trait loadTasks
{
/**
* Example task to compile assets
*
* @param string $pathToCompileAssets
* @return \MyAssetTasks\CompileAssets
*/
protected function taskCompileAssets($path = null)
{
// Always construct your tasks with the `task()` task builder.
return $this->task(CompileAssets::class, $path);
}
}
class CompileAssets implements \Robo\Contract\TaskInterface
{
// configuration params
protected $path;
protected $to;
function __construct($path)
{
$this->path = $path;
}
function to($filename)
{
$this->to = $filename;
// must return $this
return $this;
}
// must implement Run
function run()
{
//....
}
}
?>
```
To use the tasks you define in a RoboFile, use its `loadTasks` trait as explained in the section [Including Additional Tasks](#including-additional-tasks), above.
### TaskIO
To allow tasks access IO, use the `Robo\Common\TaskIO` trait, or inherit your task class from `Robo\Task\BaseTask` (recommended).
Inside tasks you should print process details with `printTaskInfo`, `printTaskSuccess`, and `printTaskError`.
```
$this->printTaskInfo('Processing...');
```
The Task IO methods send all output through a PSR-3 logger. Tasks should use task IO exclusively; methods such as 'say' and 'ask' should reside in the command method. This allows tasks to be usable in any context that has a PSR-3 logger, including background or server processes where it is not possible to directly query the user.
### Tasks That Use Tasks
If one task implementation needs to use other tasks while it is running, it should do so via a `CollectionBuilder` object, as explained in the [Collections](collections.md) documentation.
To obtain access to a `CollectionBuilder`, a task should implement `BuilderAwareInterface` and use `BuilderAwareTrait`. It will then have access to a collection builder via the `$this->collectionBuilder()` method.
### Testing Extensions
If you wish to use the `task()` methods from your `loadTasks` trait in your unit tests, it is necessary to also use the Robo `TaskAccessor` trait, and define a `collectionBuilder()` method to provide a builder. Collection builders are used to initialize all Robo tasks. The easiest way to get a usable collection builder in your tests is to initialize Robo's default dependency injection container, and use it to request a new builder.
An example of how to do this in a PHPUnit test is shown below.
```
use League\Container\ContainerAwareInterface;
use League\Container\ContainerAwareTrait;
use Symfony\Component\Console\Output\NullOutput;
use Robo\TaskAccessor;
use Robo\Robo;
class DrushStackTest extends \PHPUnit_Framework_TestCase implements ContainerAwareInterface
{
use \Boedah\Robo\Task\Drush\loadTasks;
use TaskAccessor;
use ContainerAwareTrait;
// Set up the Robo container so that we can create tasks in our tests.
function setup()
{
$container = Robo::createDefaultContainer(null, new NullOutput());
$this->setContainer($container);
}
// Scaffold the collection builder
public function collectionBuilder()
{
$emptyRobofile = new \Robo\Tasks;
return $this->getContainer()->get('collectionBuilder', [$emptyRobofile]);
}
public function testYesIsAssumed()
{
$command = $this->taskDrushStack()
->drush('command')
->getCommand();
$this->assertEquals('drush command -y', $command);
}
}
```
To assert that the output of a command contains some value, use a `Symfony\Component\Console\Output\BufferedOutput` in place of null output when calling Robo::createDefaultContainer().

View File

@@ -0,0 +1,89 @@
# Robo as a Framework
There are multiple ways to use and package Robo scripts; a few of the alternatives are presented below.
## Creating a Standalone Phar with Robo
It is possible to create a standalone phar that is implemented with Robo; doing this does not require the RoboFile to be located in the current working directory, or any particular location within your project. To achieve this, first set up your project as shown in the section [Implementing Composer Scripts with Robo](getting-started.md#implementing-composer-scripts-with-robo). Use of the "scripts" section is optional.
Next, add an "autoload" section to your composer.json to provide a namespace for your Robo commands:
```
{
"name": "myorg/myproject",
"require": {
"consolidation/Robo": "~1"
},
"autoload":{
"psr-4":{
"MyProject\\":"src"
}
}
}
```
Create a new file for your Robo commands, e.g. `class RoboFile` in `namespace MyProject\Commands;` in the file `src\Commands\RoboFile.php`. Optionally, add more task libraries as described in the [extending](extending.md) document.
Create a startup script similar to the one below, and add it to the root of your project, or some other location of your choosing:
``` php
#!/usr/bin/env php
<?php
/**
* If we're running from phar load the phar autoload file.
*/
$pharPath = \Phar::running(true);
if ($pharPath) {
require_once "$pharPath/vendor/autoload.php";
} else {
if (file_exists(__DIR__.'/vendor/autoload.php')) {
require_once __DIR__.'/vendor/autoload.php';
} elseif (file_exists(__DIR__.'/../../autoload.php')) {
require_once __DIR__ . '/../../autoload.php';
}
}
$commandClasses = [ \MyProject\Commands\RoboFile::class ];
$statusCode = \Robo\Robo::run(
$_SERVER['argv'],
$commandClasses,
'MyAppName',
'0.0.0-alpha0'
);
exit($statusCode);
```
When using Robo as a framework, the Robo file should be included in the autoloader, as Robo does not include a `RoboFile.php` file when used in this mode. Instead, specify the class or classes to load as a parameter to the Robo::run() method. By default, all output will be sent to a Symfony ConsoleOutput() that Robo will create for you. If you would like to use some other OutputInterface to capture the output, it may be specified via an optional fifth parameter.
Use [box-project/box2](https://github.com/box-project/box2) to create a phar for your application. Note that if you use Robo's taskPackPhar to create your phar, then `\Phar::running()` will always return an empty string due to a bug in this phar builder. If you encounter any problems with this, then hardcode the path to your autoload file. See the [robo](https://github.com/consolidation-org/Robo/blob/master/robo) script for details.
## Using Multiple RoboFiles in a Standalone Application
It is possible to provide as many command classes as you wish to the Robo `Runner()` constructor. You might wish to separate your Robo command implementations into separate Robo files if you have a lot of commands, or if you wish to group similar commands together in the same source file. If you do this, you can simply add more class references to the `$commandClasses` variable shown above.
```
$commandClasses = [
\MyProject\Commands\BuildCommands::class,
\MyProject\Commands\DeployCommands::class
];
```
If your application has a large number of command files, or if it supports command extensions, then you might wish to use the Command Discovery class to locate your files. The `CommandFileDiscovery` class will use the Symfony Finder class to search for all filenames matching the provided search pattern. It will return a list of class names using the provided base namespace.
``` php
$discovery = new \Consolidation\AnnotatedCommand\CommandFileDiscovery();
$discovery->setSearchPattern('*Command.php');
$commandClasses = $discovery->discover('php/MyProject/Commands', '\MyProject\Commands');
```
Pass the resulting `$commandClasses` to the `Runner()` constructor as shown above. See the annotated-commands project for more information about the different options that the discovery command takes.
## Using Your Own Dependency Injection Container with Robo (Advanced)
It is also possible to completely replace the Robo application with your own. To do this, set up your project as described in the sections above, but replace the Robo runner with your own main event loop.
Create the Robo dependency injection container:
```
use League\Container\Container;
$input = new \Symfony\Component\Console\Input\ArgvInput($argv);
$output = new \Symfony\Component\Console\Output\ConsoleOutput();
$conf = new \Robo\Config(); \\ or use your own subclass
$app = new \My\Application();
$container = \Robo\Robo::createDefaultContainer($input, $output, $app, $conf);
```
If you are using League\Container (recommended), then you may simply add and share your own classes to the same container. If you are using some other DI container, then you should use [delegate lookup](https://github.com/container-interop/fig-standards/blob/master/proposed/container.md#14-additional-feature-delegate-lookup) to combine them.

View File

@@ -0,0 +1,418 @@
# Getting Started
To begin you need to create a RoboFile. Just run `robo init` in your project directory:
```
cd myproject
robo init
```
Your project directory may start out empty; Robo will create a new `RoboFile.php` for you. There will be RoboFile class which extends `\Robo\Tasks`, which includes all bundled tasks of Robo.
``` php
<?php
class RoboFile extends \Robo\Tasks
{
}
?>
```
## Commands
All public methods of the RoboFile class will be treated as **commands**. You can run them from the CLI and pass arguments.
``` php
<?php
class RoboFile extends \Robo\Tasks
{
function hello($world)
{
$this->say("Hello, $world");
}
}
?>
```
When we run:
```
robo hello davert
➜ Hello, davert
```
Method names should be camelCased. In CLI `camelCased` method will be available as `camel:cased` command.
`longCamelCased` method will be transformed to `long:camel-cased` command.
**Note:** This assumes you have installed Robo by downloading the [robo.phar](http://robo.li/robo.phar) file and copied it to a directory in your $PATH. For example, `cp robo.phar ~/bin/robo`.
### Arguments
All method parameters without default values are treated as required arguments. In our example command `hello` requires one argument.
If you pass a default value to parameter the argument becomes optional:
``` php
<?php
function hello($world = 'world')
{
$this->say("Hello, $world");
}
?>
```
```
robo hello
➜ Hello, world
```
To accept multiple, variable arguments, define a parameter as an `array`; Robo will then pass all CLI arguments in this variable:
``` php
<?php
function hello(array $world)
{
$this->say("Hello, " . implode(', ', $world));
}
?>
```
```
robo hello davert jon bill bob
➜ Hello, davert, jon, bill, bob
```
### Options
To define command options you should define the last method parameter as an associative array where the keys define the option names and the values provide each option's default values:
``` php
<?php
function hello($opts = ['silent' => false])
{
if (!$opts['silent']) $this->say("Hello, world");
}
?>
```
```
robo hello
➜ Hello, world
robo hello --silent
```
A one-character shortcut can be specified for option:
``` php
<?php
function hello($opts = ['silent|s' => false])
{
if (!$opts['silent']) $this->say("Hello, world");
}
?>
```
Now command can be executed with '-s' to run in silent mode:
```
robo hello -s
```
### Load From Other Directories
Robo can execute commands from a RoboFile located in different directory.
You can specify the path to another RoboFile by including the `--load-from` option:
```
robo run --load-from /path/to/my/other/project
```
### Pass-Through Arguments
Sometimes you need to pass arguments from your command into a task. A command line after the `--` characters is treated as one argument.
Any special character like `-` will be passed into without change.
``` php
<?php
function ls($args)
{
$this->taskExec('ls')->args($args)->run();
}
?>
```
```
robo ls -- Robo -c --all
[Robo\Task\ExecTask] running ls Robo -c --all
. .. CHANGELOG.md codeception.yml composer.json composer.lock docs .git .gitignore .idea LICENSE README.md robo RoboFile.php robo.phar src tests .travis.yml vendor
```
### Help
The help text for a command in a RoboFile may be provided in Doc-Block comments. An example help Doc-Block comment is shown below:
``` php
<?php
/**
* Calculate the fibonacci sequence between two numbers.
*
* Graphic output will look like
* +----+---+-------------+
* | | | |
* | |-+-| |
* |----+-+-+ |
* | | |
* | | |
* | | |
* +--------+-------------+
*
* @param int $start Number to start from
* @param int $steps Number of steps to perform
* @param array $opts
* @option $graphic Display the sequence graphically using cube
* representation
*/
public function fibonacci($start, $steps, $opts = ['graphic' => false])
{
}
?>
```
The corresponding help text produced is:
```
robo fibonacci --help
Usage:
fibonacci [--graphic] start steps
Arguments:
start Number to start from
steps Number of steps to perform
Options:
--graphic Display the sequence graphically using cube representation
Help:
Graphic output will look like
+----+---+-------------+
| | | |
| |-+-| |
|----+-+-+ |
| | |
| | |
| | |
+--------+-------------+
```
Arguments and options are populated from annotations.
Initially added with [PR by @jonsa](https://github.com/consolidation/Robo/pull/71); now provided by the [consolidation/annotated-command](https://github.com/consolidation/annotated-command) project, which was factored out from Robo.
### Ignored methods
Robo ignores any method of your RoboFile that begins with `get` or `set`. These methods are presumed to be data accessors, not commands. To implement a command whose name contains `get` or `set`, use the `@command` annotation.
``` php
<?php
/**
* @command set-alignment
*/
function setAlignment($value)
{
...
}
?>
```
## Tasks
Robo commands typically divide the work they need to accomplish into **tasks**. The command first determines what needs to be done, inspecting current state if necessary, and then sets up and executes one or more tasks that make the actual changes needed by the command. (See also the documentation on [Collections](collections.md), which allow you to combine groups of tasks which can provide rollback functions to recover from failure situations.)
For details on how to add custom tasks to Robo, see the [extending](extending.md) document.
### Shortcuts
Some tasks may have shortcuts. If a task does not require multi-step configuration, it can be executed with a single line:
```php
<?php
$this->_exec('ps aux');
$this->_copy('config/env.example.yml','config/env.yml');
?>
```
### Result
Each task must return an instance of `Robo\Result`. A Robo Result contains the task instance, exit code, message, and any variable data that the task may wish to return.
The `run` method of `CompileAssets` class may look like this:
```
return new Robo\Result($this, $exitCode, "Assets compiled");
```
or
```
return Robo\Result::success($this, "Assets compiled");
return Robo\Result::error($this, "Failed to compile assets");
```
You can use this results to check if execution was successful, either using the `wasSuccessful()` method, or via the `invoke` shortcut. We will use the `Exec` task in next example to illustrate this:
``` php
<?php
class RoboFile
{
use Robo\Task\Base\loadShortcuts;
function test()
{
$res1 = $this->_exec('phpunit tests/integration');
$res2 = $this->_exec('phpunit tests/unit');
// print message when tests passed
if ($res1->wasSuccessful() and $res2->wasSuccessful()) $this->say("All tests passed");
}
}
?>
```
When making multi-step commands that call one task after another, it is best to use a collection to group the tasks together. The collection will handle error detection and rollback, and will return a single Result object when done. For more information, see the [Collections](collections.md) documentation.
Some tasks may also attach data to the Result object. If this is done, the data may be accessed as an array; for example, `$result['path'];`. This is not common.
Commands should return a Result object obtained from a task; this will ensure that the command exit code is set correctly. If a command does not have a Result object available, then it may use a ResultData object. ResultData objects are just like Result objects, except the do not contain a reference to a task.
return new Robo\ResultData($exitcode, 'Error message.');
If the command returns a TaskInterface instead of a result, then the task will be executed, and the result from that task will be used as the final result of the command. See also `Formatters`, below.
### Stack
Some tasks contain `Stack` in their name. These are called "stack" tasks, and they execute similar tasks one after the other. Each of the primary methods in a stack class executes an operation.
Stack tasks also contain a `stopOnFail` method which can be used to stop task execution if one of its commands was unsuccessful.
### Global StopOnFail
There is a global `stopOnFail` method as well, that can be used to stop a command on first failure of a task.
```
$this->stopOnFail(true);
```
### IO
As you noticed, you can print text via the `say` method, which is taken from the `Robo\Output` trait.
```
$this->say("Hello");
```
Also, you can ask for input from console:
```
$name = $this->ask("What is your name?");
```
There are also `askDefault`, `askHidden`, and `confirm` methods.
In addition, Robo makes all of the methods of Symfony Style available throgh the `io()` method:
$this->io()->title("Build all site assets");
This allows Robo scripts to follow the [Symfony Console Style Guide](http://symfony.com/blog/new-in-symfony-2-8-console-style-guide) if desired.
### Formatters
It is preferable for commands that look up and display information should avoid doing IO directly, and should instead return the data they wish to display as an array. This data can then be converted into different data formats, such as "table" and "json". The user may select which formatter to use via the --format option. For details on formatters, see the [consolidation/output-formatters](https://github.com/consolidation/output-formatters) project.
### Progress
Robo supports progress indicators via the Symfony ProgressBar class. Long-running tasks that wish to display the progress indicator may do so via four simple steps:
- Override the `progressIndicatorSteps()` method and return the number of "steps" in the operation.
- Call `$this->startProgressIndicator()` to begin the progress indicator running.
- Call `$this->advanceProgressIndicator()` a number of times equal to the result returned by `progressIndicatorSteps()`
- Call `$this->stopProgressIndicator()` when the operation is completed.
An example of this is shown below:
``` php
<?php
class MyTask extends BaseTask
{
protected $steps = 10;
public function progressIndicatorSteps()
{
return $this->steps;
}
public function run()
{
$exitCode = 0;
$errorMessage = "";
$this->startProgressIndicator();
for ($i = 0; $i < $this->steps; ++$i) {
$this->advanceProgressIndicator();
}
$this->stopProgressIndicator();
return new Result($this, $exitCode, $errorMessage, ['time' => $this->getExecutionTime()]);
}
}
?>
```
Tasks should not attempt to use a specific progress indicator (e.g. the Symfony ProgressBar class) directly, as the ProgressIndicatorAwareTrait allows for an appropriate progress indicator to be used (or omitted) as best suits the application.
Note that when using [Collections](collections.md), the progress bar will automatically be shown if the collection takes longer than two seconds to run. Each task in the collection will count for one "step"; if the task supports progress indicators as shown above, then it will add an additional number of steps as indicated by its `progressIndicatorSteps()` method.
## Working with Composer
### Adding a RoboFile to your Project
Robo is designed to work well with Composer. To use Robo scripts in your Composer-based project, simply add `robo` to your composer.json file:
```
$ cd myproject
$ composer require consolidation/Robo:~1
$ ./vendor/bin/robo mycommand
```
If you do not want to type the whole path to Robo, you may add `./vendor/bin` to your $PATH (relative paths work), or use `composer exec` to find and run Robo:
```
$ composer exec robo mycommand
```
### Implementing Composer Scripts with Robo
When using Robo in your project, it is convenient to define Composer scripts that call your Robo commands. Simply add the following to your composer.json file:
```
{
"name": "myorg/myproject",
"require": {
"consolidation/Robo": "~1"
},
"scripts": {
"test": "composer robo test",
"phar": "composer robo phar:build",
"robo": "robo --ansi --load-from $(pwd)/scripts/BuildCommands.php"
}
}
```
*Note*: When you include Robo as a library like this, some external projects used by certain core Robo tasks are not automatically included in your project. See the `"suggest":` section of Robo's composer.json for a list of external projects you might also want to require in your project.
Once you have set up your composer.json file (and ran `composer update` if you manually changed the `require` or `require-dev` sections), Composer will ensure that your project-local copy of Robo in the `vendor/bin` dir is in your $PATH when you run the additional Composer scripts that you declared:
```
$ cd myproject
$ composer test
$ composer phar
```
This will call the public methods `test()` and `phar()` in your RoboFile.php when using `composer test` and `composer phar`, respectively.
Advertising your build commands as Composer scripts is a useful way to provide the key commands used for testing, building or packaging your application. Also, if your application should happen to provide a commandline tool to perform the operations of the application itself, then defining your build commands in their own RoboFile provides desirable separation, keeping your build commands out of the help and list commands of your primary script.
If you would like to simplify the output of your script (e.g. when running on a CI service), replace the `--ansi` option in the example above with `--no-ansi`, and colored terminal output and progress bars will be disabled.
## Robo as a Framework
For an overview on how to turn your Robo scripts into standalone tools, see the example [robo.script](https://github.com/consolidation/Robo/blob/master/examples/robo.script), and the section [Robo as a Framework](framework.md).

View File

@@ -0,0 +1,24 @@
# Robo Documentation
* [Getting Started](getting-started.md)
* [Collections](collections.md)
* [Extending](extending.md)
* [Robo as a Framework](framework.md)
## Tasks
* [ApiGen](tasks/ApiGen.md)
* [Archive](tasks/Archive.md)
* [Assets](tasks/Assets.md)
* [Base](tasks/Base.md)
* [Bower](tasks/Bower.md)
* [Composer](tasks/Composer.md)
* [Development](tasks/Development.md)
* [Docker](tasks/Docker.md)
* [File](tasks/File.md)
* [Filesystem](tasks/Filesystem.md)
* [Gulp](tasks/Gulp.md)
* [Npm](tasks/Npm.md)
* [Remote](tasks/Remote.md)
* [Testing](tasks/Testing.md)
* [Vcs](tasks/Vcs.md)

View File

@@ -0,0 +1,56 @@
# ApiGen Tasks
## ApiGen
Executes ApiGen command to generate documentation
``` php
<?php
// ApiGen Command
$this->taskApiGen('./apigen.neon')
->templateConfig('vendor/apigen/apigen/templates/bootstrap/config.neon')
->wipeout(true)
->run();
?>
```
* `config($config)` * `param string` $config
* `source($src)` * `param array|string|Traversable` $src one or more source values
* `destination($dest)` * `param string` $dest
* `extensions($exts)` * `param array|string` $exts one or more extensions
* `exclude($exclude)` * `param array|string` $exclude one or more exclusions
* `skipDocPath($path)` * `param array|string|Traversable` $path one or more skip-doc-path values
* `skipDocPrefix($prefix)` * `param array|string|Traversable` $prefix one or more skip-doc-prefix values
* `charset($charset)` * `param array|string` $charset one or more charsets
* `mainProjectNamePrefix($name)` * `param string` $name
* `title($title)` * `param string` $title
* `baseUrl($baseUrl)` * `param string` $baseUrl
* `googleCseId($id)` * `param string` $id
* `googleAnalytics($trackingCode)` * `param string` $trackingCode
* `templateConfig($templateConfig)` * `param mixed` $templateConfig
* `allowedHtml($tags)` * `param array|string` $tags one or more supported html tags
* `groups($groups)` * `param string` $groups
* `autocomplete($types)` * `param array|string` $types or more supported autocomplete types
* `accessLevels($levels)` * `param array|string` $levels one or more access levels
* `internal($internal)` * `param boolean|string` $internal 'yes' or true if internal, 'no' or false if not
* `php($php)` * `param boolean|string` $php 'yes' or true to generate documentation for internal php classes,
* `tree($tree)` * `param bool|string` $tree 'yes' or true to generate a tree view of classes, 'no' or false otherwise
* `deprecated($dep)` * `param bool|string` $dep 'yes' or true to generate documentation for deprecated classes, 'no' or false otherwise
* `todo($todo)` * `param bool|string` $todo 'yes' or true to document tasks, 'no' or false otherwise
* `sourceCode($src)` * `param bool|string` $src 'yes' or true to generate highlighted source code, 'no' or false otherwise
* `download($zipped)` * `param bool|string` $zipped 'yes' or true to generate downloadable documentation, 'no' or false otherwise
* `report($path)`
* `wipeout($wipeout)` * `param bool|string` $wipeout 'yes' or true to clear out the destination directory, 'no' or false otherwise
* `quiet($quiet)` * `param bool|string` $quiet 'yes' or true for quiet, 'no' or false otherwise
* `progressbar($bar)` * `param bool|string` $bar 'yes' or true to display a progress bar, 'no' or false otherwise
* `colors($colors)` * `param bool|string` $colors 'yes' or true colorize the output, 'no' or false otherwise
* `updateCheck($check)` * `param bool|string` $check 'yes' or true to check for updates, 'no' or false otherwise
* `debug($debug)` * `param bool|string` $debug 'yes' or true to enable debug mode, 'no' or false otherwise
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,52 @@
# Archive Tasks
## Extract
Extracts an archive.
Note that often, distributions are packaged in tar or zip archives
where the topmost folder may contain variable information, such as
the release date, or the version of the package. This information
is very useful when unpacking by hand, but arbitrarily-named directories
are much less useful to scripts. Therefore, by default, Extract will
remove the top-level directory, and instead store all extracted files
into the directory specified by $archivePath.
To keep the top-level directory when extracting, use
`preserveTopDirectory(true)`.
``` php
<?php
$this->taskExtract($archivePath)
->to($destination)
->preserveTopDirectory(false) // the default
->run();
?>
```
* `to(string)` location to store extracted files
* `to($to)` Location to store extracted files.
* `preserveTopDirectory($preserve = null)` * `param bool` $preserve
## Pack
Creates a zip or tar archive.
``` php
<?php
$this->taskPack(
<archiveFile>)
->add('README') // Puts file 'README' in archive at the root
->add('project') // Puts entire contents of directory 'project' in archinve inside 'project'
->addFile('dir/file.txt', 'file.txt') // Takes 'file.txt' from cwd and puts it in archive inside 'dir'.
->run();
?>
```
* `archiveFile($archiveFile)` * `param string` $archiveFile
* `addFile($placementLocation, $filesystemLocation)` Add an item to the archive. Like file_exists(), the parameter
* `addDir($placementLocation, $filesystemLocation)` Alias for addFile, in case anyone has angst about using
* `add($item)` Add a file or directory, or list of same to the archive.

View File

@@ -0,0 +1,163 @@
# Assets Tasks
## ImageMinify
Minifies images. When the required minifier is not installed on the system
the task will try to download it from the [imagemin](https://github.com/imagemin) repository.
When the task is run without any specified minifier it will compress the images
based on the extension.
```php
$this->taskImageMinify('assets/images/*')
->to('dist/images/')
->run();
```
This will use the following minifiers:
- PNG: optipng
- GIF: gifsicle
- JPG, JPEG: jpegtran
- SVG: svgo
When the minifier is specified the task will use that for all the input files. In that case
it is useful to filter the files with the extension:
```php
$this->taskImageMinify('assets/images/*.png')
->to('dist/images/')
->minifier('pngcrush');
->run();
```
The task supports the following minifiers:
- optipng
- pngquant
- advpng
- pngout
- zopflipng
- pngcrush
- gifsicle
- jpegoptim
- jpeg-recompress
- jpegtran
- svgo (only minification, no downloading)
You can also specifiy extra options for the minifiers:
```php
$this->taskImageMinify('assets/images/*.jpg')
->to('dist/images/')
->minifier('jpegtran', ['-progressive' => null, '-copy' => 'none'])
->run();
```
This will execute as:
`jpegtran -copy none -progressive -optimize -outfile "dist/images/test.jpg" "/var/www/test/assets/images/test.jpg"`
* `to($target)` Sets the target directory where the files will be copied to.
* `minifier($minifier, array $options = Array ( ) )` Sets the minifier.
## Less
Compiles less files.
```php
<?php
$this->taskLess([
'less/default.less' => 'css/default.css'
])
->run();
?>
```
Use one of both less compilers in your project:
```
"leafo/lessphp": "~0.5",
"oyejorge/less.php": "~1.5"
```
Specify directory (string or array) for less imports lookup:
```php
<?php
$this->taskLess([
'less/default.less' => 'css/default.css'
])
->importDir('less')
->compiler('lessphp')
->run();
?>
```
You can implement additional compilers by extending this task and adding a
method named after them and overloading the lessCompilers() method to
inject the name there.
* `importDir($dirs)` Sets import directories
* `addImportPath($dir)` Adds import directory
* `setImportPaths($dirs)` Sets import directories
* `setFormatter($formatterName)` * `param string` $formatterName
* `compiler($compiler, array $options = Array ( ) )` Sets the compiler.
## Minify
Minifies asset file (CSS or JS).
``` php
<?php
$this->taskMinify( 'web/assets/theme.css' )
->run()
?>
```
Please install additional dependencies to use:
```
"patchwork/jsqueeze": "~1.0",
"natxet/CssMin": "~3.0"
```
* `to($dst)` Sets destination. Tries to guess type from it.
* `type($type)` Sets type with validation.
* `singleLine($singleLine)` Single line option for the JS minimisation.
* `keepImportantComments($keepImportantComments)` keepImportantComments option for the JS minimisation.
* `specialVarRx($specialVarRx)` specialVarRx option for the JS minimisation.
* `__toString()` @return string
## Scss
Compiles scss files.
```php
<?php
$this->taskScss([
'scss/default.scss' => 'css/default.css'
])
->importDir('assets/styles')
->run();
?>
```
Use the following scss compiler in your project:
```
"leafo/scssphp": "~0.1",
```
You can implement additional compilers by extending this task and adding a
method named after them and overloading the scssCompilers() method to
inject the name there.
* `setFormatter($formatterName)` Sets the formatter for scssphp
* `importDir($dirs)` Sets import directories
* `addImportPath($dir)` Adds import directory
* `setImportPaths($dirs)` Sets import directories
* `compiler($compiler, array $options = Array ( ) )` Sets the compiler.

View File

@@ -0,0 +1,126 @@
# Base Tasks
## Exec
Executes shell script. Closes it when running in background mode.
``` php
<?php
$this->taskExec('compass')->arg('watch')->run();
// or use shortcut
$this->_exec('compass watch');
$this->taskExec('compass watch')->background()->run();
if ($this->taskExec('phpunit .')->run()->wasSuccessful()) {
$this->say('tests passed');
}
?>
```
* `background()` Executes command in background mode (asynchronously)
* `timeout($timeout)` Stop command if it runs longer then $timeout in seconds
* `idleTimeout($timeout)` Stops command if it does not output something for a while
* `env(array $env)` Sets the environment variables for the command
* `simulate($context)` {@inheritdoc}
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## ExecStack
Execute commands one by one in stack.
Stack can be stopped on first fail if you call `stopOnFail()`.
```php
<?php
$this->taskExecStack()
->stopOnFail()
->exec('mkdir site')
->exec('cd site')
->run();
?>
```
* `$this stopOnFail()`
* `executable($executable)` * `param string` $executable
* `exec($command)` * `param string|string[]` $command
* `stopOnFail($stopOnFail = null)` * `param bool` $stopOnFail
* `result($result)`
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
## ParallelExec
Class ParallelExecTask
``` php
<?php
$this->taskParallelExec()
->process('php ~/demos/script.php hey')
->process('php ~/demos/script.php hoy')
->process('php ~/demos/script.php gou')
->run();
?>
```
* ` timeout(int $timeout)` stops process if it runs longer then `$timeout` (seconds)
* ` idleTimeout(int $timeout)` stops process if it does not output for time longer then `$timeout` (seconds)
* `printed($isPrinted = null)` * `param bool` $isPrinted
* `process($command)` * `param string|\Robo\Contract\CommandInterface` $command
* `timeout($timeout)` * `param int` $timeout
* `idleTimeout($idleTimeout)` * `param int` $idleTimeout
## SymfonyCommand
Executes Symfony Command
``` php
<?php
// Symfony Command
$this->taskSymfonyCommand(new \Codeception\Command\Run('run'))
->arg('suite','acceptance')
->opt('debug')
->run();
// Artisan Command
$this->taskSymfonyCommand(new ModelGeneratorCommand())
->arg('name', 'User')
->run();
?>
```
* `arg($arg, $value)` * `param string` $arg
* `opt($option, $value = null)`
## Watch
Runs task when specified file or dir was changed.
Uses Lurker library.
``` php
<?php
$this->taskWatch()
->monitor('composer.json', function() {
$this->taskComposerUpdate()->run();
})->monitor('src', function() {
$this->taskExec('phpunit')->run();
})->run();
?>
```
* `monitor($paths, $callable)` * `param string|string[]` $paths

View File

@@ -0,0 +1,60 @@
# Bower Tasks
## Install
Bower Install
``` php
<?php
// simple execution
$this->taskBowerInstall()->run();
// prefer dist with custom path
$this->taskBowerInstall('path/to/my/bower')
->noDev()
->run();
?>
```
* `allowRoot()` adds `allow-root` option to bower
* `forceLatest()` adds `force-latest` option to bower
* `noDev()` adds `production` option to bower
* `offline()` adds `offline` option to bower
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Update
Bower Update
``` php
<?php
// simple execution
$this->taskBowerUpdate->run();
// prefer dist with custom path
$this->taskBowerUpdate('path/to/my/bower')
->noDev()
->run();
?>
```
* `allowRoot()` adds `allow-root` option to bower
* `forceLatest()` adds `force-latest` option to bower
* `noDev()` adds `production` option to bower
* `offline()` adds `offline` option to bower
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,179 @@
# Composer Tasks
## DumpAutoload
Composer Dump Autoload
``` php
<?php
// simple execution
$this->taskComposerDumpAutoload()->run();
// dump auto loader with custom path
$this->taskComposerDumpAutoload('path/to/my/composer.phar')
->preferDist()
->run();
// optimize autoloader dump with custom path
$this->taskComposerDumpAutoload('path/to/my/composer.phar')
->optimize()
->run();
// optimize autoloader dump with custom path and no dev
$this->taskComposerDumpAutoload('path/to/my/composer.phar')
->optimize()
->noDev()
->run();
?>
```
* `optimize()` * `return` $this
* `preferDist()` adds `prefer-dist` option to composer
* `preferSource()` adds `prefer-source` option to composer
* `noDev()` adds `no-dev` option to composer
* `noAnsi()` adds `no-ansi` option to composer
* `ansi()` adds `ansi` option to composer
* `optimizeAutoloader()` adds `optimize-autoloader` option to composer
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Install
Composer Install
``` php
<?php
// simple execution
$this->taskComposerInstall()->run();
// prefer dist with custom path
$this->taskComposerInstall('path/to/my/composer.phar')
->preferDist()
->run();
// optimize autoloader with custom path
$this->taskComposerInstall('path/to/my/composer.phar')
->optimizeAutoloader()
->run();
?>
```
* `preferDist()` adds `prefer-dist` option to composer
* `preferSource()` adds `prefer-source` option to composer
* `noDev()` adds `no-dev` option to composer
* `noAnsi()` adds `no-ansi` option to composer
* `ansi()` adds `ansi` option to composer
* `optimizeAutoloader()` adds `optimize-autoloader` option to composer
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Remove
Composer Validate
``` php
<?php
// simple execution
$this->taskComposerValidate()->run();
?>
```
* `dev()` * `return` $this
* `noProgress()` * `return` $this
* `noUpdate()` * `return` $this
* `updateNoDev()` * `return` $this
* `noUpdateWithDependencies()` * `return` $this
* `preferDist()` adds `prefer-dist` option to composer
* `preferSource()` adds `prefer-source` option to composer
* `noDev()` adds `no-dev` option to composer
* `noAnsi()` adds `no-ansi` option to composer
* `ansi()` adds `ansi` option to composer
* `optimizeAutoloader()` adds `optimize-autoloader` option to composer
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Update
Composer Update
``` php
<?php
// simple execution
$this->taskComposerUpdate()->run();
// prefer dist with custom path
$this->taskComposerUpdate('path/to/my/composer.phar')
->preferDist()
->run();
// optimize autoloader with custom path
$this->taskComposerUpdate('path/to/my/composer.phar')
->optimizeAutoloader()
->run();
?>
```
* `preferDist()` adds `prefer-dist` option to composer
* `preferSource()` adds `prefer-source` option to composer
* `noDev()` adds `no-dev` option to composer
* `noAnsi()` adds `no-ansi` option to composer
* `ansi()` adds `ansi` option to composer
* `optimizeAutoloader()` adds `optimize-autoloader` option to composer
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Validate
Composer Validate
``` php
<?php
// simple execution
$this->taskComposerValidate()->run();
?>
```
* `noCheckAll()` * `return` $this
* `noCheckLock()` * `return` $this
* `noCheckPublish()` * `return` $this
* `withDependencies()` * `return` $this
* `strict()` * `return` $this
* `preferDist()` adds `prefer-dist` option to composer
* `preferSource()` adds `prefer-source` option to composer
* `noDev()` adds `no-dev` option to composer
* `noAnsi()` adds `no-ansi` option to composer
* `ansi()` adds `ansi` option to composer
* `optimizeAutoloader()` adds `optimize-autoloader` option to composer
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,282 @@
# Development Tasks
## Changelog
Helps to manage changelog file.
Creates or updates `changelog.md` file with recent changes in current version.
``` php
<?php
$version = "0.1.0";
$this->taskChangelog()
->version($version)
->change("released to github")
->run();
?>
```
Changes can be asked from Console
``` php
<?php
$this->taskChangelog()
->version($version)
->askForChanges()
->run();
?>
```
* `Development\Changelog filename(string $filename)`
* `Development\Changelog anchor(string $anchor)`
* `Development\Changelog version(string $version)`
* `filename($filename)` * `param string` $filename
* `log($item)` * `param string` $item
* `anchor($anchor)` * `param string` $anchor
* `version($version)` * `param string` $version
* `changes(array $data)` * `param array` $data
* `change($change)` * `param string` $change
* `getChanges()` @return array
## GenerateMarkdownDoc
Simple documentation generator from source files.
Takes classes, properties and methods with their docblocks and writes down a markdown file.
``` php
<?php
$this->taskGenDoc('models.md')
->docClass('Model\User') // take class Model\User
->docClass('Model\Post') // take class Model\Post
->filterMethods(function(\ReflectionMethod $r) {
return $r->isPublic() or $r->isProtected(); // process public and protected methods
})->processClass(function(\ReflectionClass $r, $text) {
return "Class ".$r->getName()."\n\n$text\n\n###Methods\n";
})->run();
```
By default this task generates a documentation for each public method of a class.
It combines method signature with a docblock. Both can be post-processed.
``` php
<?php
$this->taskGenDoc('models.md')
->docClass('Model\User')
->processClassSignature(false) // false can be passed to not include class signature
->processClassDocBlock(function(\ReflectionClass $r, $text) {
return "[This is part of application model]\n" . $text;
})->processMethodSignature(function(\ReflectionMethod $r, $text) {
return "#### {$r->name}()";
})->processMethodDocBlock(function(\ReflectionMethod $r, $text) {
return strpos($r->name, 'save')===0 ? "[Saves to the database]\n" . $text : $text;
})->run();
```
* ` docClass(string $classname)` put a class you want to be documented
* ` filterMethods(\Closure $func)` using callback function filter out methods that won't be documented
* ` filterClasses(\Closure $func)` using callback function filter out classes that won't be documented
* ` filterProperties(\Closure $func)` using callback function filter out properties that won't be documented
* ` processClass(\Closure $func)` post-process class documentation
* ` processClassSignature(\Closure $func)` post-process class signature. Provide *false* to skip.
* ` processClassDocBlock(\Closure $func)` post-process class docblock contents. Provide *false* to skip.
* ` processMethod(\Closure $func)` post-process method documentation. Provide *false* to skip.
* ` processMethodSignature(\Closure $func)` post-process method signature. Provide *false* to skip.
* ` processMethodDocBlock(\Closure $func)` post-process method docblock contents. Provide *false* to skip.
* ` processProperty(\Closure $func)` post-process property documentation. Provide *false* to skip.
* ` processPropertySignature(\Closure $func)` post-process property signature. Provide *false* to skip.
* ` processPropertyDocBlock(\Closure $func)` post-process property docblock contents. Provide *false* to skip.
* ` reorder(\Closure $func)` use a function to reorder classes
* ` reorderMethods(\Closure $func)` use a function to reorder methods in class
* ` prepend($text)` inserts text into beginning of markdown file
* ` append($text)` inserts text in the end of markdown file
* `docClass($item)` * `param string` $item
* `filterMethods($filterMethods)` * `param callable` $filterMethods
* `filterClasses($filterClasses)` * `param callable` $filterClasses
* `filterProperties($filterProperties)` * `param callable` $filterProperties
* `processClass($processClass)` * `param callable` $processClass
* `processClassSignature($processClassSignature)` * `param callable|false` $processClassSignature
* `processClassDocBlock($processClassDocBlock)` * `param callable|false` $processClassDocBlock
* `processMethod($processMethod)` * `param callable|false` $processMethod
* `processMethodSignature($processMethodSignature)` * `param callable|false` $processMethodSignature
* `processMethodDocBlock($processMethodDocBlock)` * `param callable|false` $processMethodDocBlock
* `processProperty($processProperty)` * `param callable|false` $processProperty
* `processPropertySignature($processPropertySignature)` * `param callable|false` $processPropertySignature
* `processPropertyDocBlock($processPropertyDocBlock)` * `param callable|false` $processPropertyDocBlock
* `reorder($reorder)` * `param callable` $reorder
* `reorderMethods($reorderMethods)` * `param callable` $reorderMethods
* `reorderProperties($reorderProperties)` * `param callable` $reorderProperties
* `filename($filename)` * `param string` $filename
* `prepend($prepend)` * `param string` $prepend
* `append($append)` * `param string` $append
* `text($text)` * `param string` $text
* `textForClass($item)` * `param string` $item
## Generate
Generate a Robo Task that is a wrapper around an existing class.
``` php
<?php
$this->taskGenerateTask('Symfony\Component\Filesystem\Filesystem', 'FilesystemStack')
->run();
```
## GitHubRelease
Publishes new GitHub release.
``` php
<?php
$this->taskGitHubRelease('0.1.0')
->uri('consolidation-org/Robo')
->description('Add stuff people need.')
->change('Fix #123')
->change('Add frobulation method to all widgets')
->run();
?>
```
* `tag($tag)` * `param string` $tag
* `draft($draft)` * `param bool` $draft
* `name($name)` * `param string` $name
* `description($description)` * `param string` $description
* `prerelease($prerelease)` * `param bool` $prerelease
* `comittish($comittish)` * `param string` $comittish
* `appendDescription($description)` * `param string` $description
* `changes(array $changes)`
* `change($change)` * `param string` $change
* `repo($repo)` * `param string` $repo
* `owner($owner)` * `param string` $owner
* `uri($uri)` * `param string` $uri
* `user($user)` * `param string` $user
* `password($password)` * `param` $password
## OpenBrowser
Opens the default's user browser
code inspired from openBrowser() function in https://github.com/composer/composer/blob/master/src/Composer/Command/HomeCommand.php
``` php
<?php
// open one browser window
$this->taskOpenBrowser('http://localhost')
->run();
// open two browser windows
$this->taskOpenBrowser([
'http://localhost/mysite',
'http://localhost/mysite2'
])
->run();
```
## PackPhar
Creates Phar.
``` php
<?php
$pharTask = $this->taskPackPhar('package/codecept.phar')
->compress()
->stub('package/stub.php');
$finder = Finder::create()
->name('*.php')
->in('src');
foreach ($finder as $file) {
$pharTask->addFile('src/'.$file->getRelativePathname(), $file->getRealPath());
}
$finder = Finder::create()->files()
->name('*.php')
->in('vendor');
foreach ($finder as $file) {
$pharTask->addStripped('vendor/'.$file->getRelativePathname(), $file->getRealPath());
}
$pharTask->run();
// verify Phar is packed correctly
$code = $this->_exec('php package/codecept.phar');
?>
```
* `compress($compress = null)` * `param bool` $compress
* `stub($stub)` * `param string` $stub
* `addStripped($path, $file)` * `param string` $path
* `addFile($path, $file)` * `param string` $path
* `addFiles($files)` * `param \Symfony\Component\Finder\SplFileInfo[]` $files
* `executable($file)` * `param string` $file
## PhpServer
Runs PHP server and stops it when task finishes.
``` php
<?php
// run server in /public directory
$this->taskServer(8000)
->dir('public')
->run();
// run with IP 0.0.0.0
$this->taskServer(8000)
->host('0.0.0.0')
->run();
// execute server in background
$this->taskServer(8000)
->background()
->run();
?>
```
* `host($host)` * `param string` $host
* `dir($path)` * `param string` $path
* `background()` Executes command in background mode (asynchronously)
* `timeout($timeout)` Stop command if it runs longer then $timeout in seconds
* `idleTimeout($timeout)` Stops command if it does not output something for a while
* `env(array $env)` Sets the environment variables for the command
* `simulate($context)` {@inheritdoc}
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## SemVer
Helps to maintain `.semver` file.
```php
<?php
$this->taskSemVer('.semver')
->increment()
->run();
?>
```
* `__toString()` @return string
* `setFormat($format)` * `param string` $format
* `setMetadataSeparator($separator)` * `param string` $separator
* `setPrereleaseSeparator($separator)` * `param string` $separator
* `increment($what = null)` * `param string` $what
* `prerelease($tag = null)` * `param string` $tag
* `metadata($data)` * `param array|string` $data

View File

@@ -0,0 +1,249 @@
# Docker Tasks
## Build
Builds Docker image
```php
<?php
$this->taskDockerBuild()->run();
$this->taskDockerBuild('path/to/dir')
->tag('database')
->run();
?>
```
Class Build
@package Robo\Task\Docker
* `tag($tag)` * `param string` $tag
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Commit
Commits docker container to an image
```
$this->taskDockerCommit($containerId)
->name('my/database')
->run();
// alternatively you can take the result from DockerRun task:
$result = $this->taskDockerRun('db')
->exec('./prepare_database.sh')
->run();
$task->dockerCommit($result)
->name('my/database')
->run();
```
* `name($name)` * `param` $name
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Exec
Executes command inside running Docker container
```php
<?php
$test = $this->taskDockerRun('test_env')
->detached()
->run();
$this->taskDockerExec($test)
->interactive()
->exec('./runtests')
->run();
// alternatively use commands from other tasks
$this->taskDockerExec($test)
->interactive()
->exec($this->taskCodecept()->suite('acceptance'))
->run();
?>
```
* `detached()` * `return` $this
* `interactive()` * `return` $this
* `exec($command)` * `param string|\Robo\Contract\CommandInterface` $command
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Pull
Pulls an image from DockerHub
```php
<?php
$this->taskDockerPull('wordpress')
->run();
?>
```
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Remove
Remove docker container
```php
<?php
$this->taskDockerRemove($container)
->run();
?>
```
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Run
Performs `docker run` on a container.
```php
<?php
$this->taskDockerRun('mysql')->run();
$result = $this->taskDockerRun('my_db_image')
->env('DB', 'database_name')
->volume('/path/to/data', '/data')
->detached()
->publish(3306)
->name('my_mysql')
->run();
// retrieve container's cid:
$this->say("Running container ".$result->getCid());
// execute script inside container
$result = $this->taskDockerRun('db')
->exec('prepare_test_data.sh')
->run();
$this->taskDockerCommit($result)
->name('test_db')
->run();
// link containers
$mysql = $this->taskDockerRun('mysql')
->name('wp_db') // important to set name for linked container
->env('MYSQL_ROOT_PASSWORD', '123456')
->run();
$this->taskDockerRun('wordpress')
->link($mysql)
->publish(80, 8080)
->detached()
->run();
?>
```
* `detached()` * `return` $this
* `interactive()` * `return` $this
* `exec($run)` * `param string|\Robo\Contract\CommandInterface` $run
* `volume($from, $to = null)` * `param string` $from
* `env($variable, $value = null)` * `param string` $variable
* `publish($port = null, $portTo = null)` * `param null|int` $port
* `containerWorkdir($dir)` * `param string` $dir
* `user($user)` * `param string` $user
* `privileged()` * `return` $this
* `name($name)` * `param string` $name
* `link($name, $alias)` * `param string|\Robo\Task\Docker\Result` $name
* `tmpDir($dir)` * `param string` $dir
* `getTmpDir()` @return string
* `getUniqId()` @return string
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Start
Starts Docker container
```php
<?php
$this->taskDockerStart($cidOrResult)
->run();
?>
```
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Stop
Stops Docker container
```php
<?php
$this->taskDockerStop($cidOrResult)
->run();
?>
```
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,129 @@
# File Tasks
## Concat
Merges files into one. Used for preparing assets.
``` php
<?php
$this->taskConcat([
'web/assets/screen.css',
'web/assets/print.css',
'web/assets/theme.css'
])
->to('web/assets/style.css')
->run()
?>
```
* `to($dst)` set the destination file
## Replace
Performs search and replace inside a files.
``` php
<?php
$this->taskReplaceInFile('VERSION')
->from('0.2.0')
->to('0.3.0')
->run();
$this->taskReplaceInFile('README.md')
->from(date('Y')-1)
->to(date('Y'))
->run();
$this->taskReplaceInFile('config.yml')
->regex('~^service:~')
->to('services:')
->run();
$this->taskReplaceInFile('box/robo.txt')
->from(array('##dbname##', '##dbhost##'))
->to(array('robo', 'localhost'))
->run();
?>
```
* `regex(string)` regex to match string to be replaced
* `from(string|array)` string(s) to be replaced
* `to(string|array)` value(s) to be set as a replacement
* `filename($filename)` * `param string` $filename
* `from($from)` * `param string` $from
* `to($to)` * `param string` $to
* `regex($regex)` * `param string` $regex
## TmpFile
Create a temporary file that is automatically cleaned up
once the task collection is is part of completes. When created,
it is given a random filename.
This temporary file may be manipulated exacatly like taskWrite().
It is deleted as soon as the collection it is a part of completes
or rolls back.
``` php
<?php
$collection = $this->collectionBuilder();
$tmpFilePath = $collection->taskTmpFile()
->line('-----')
->line(date('Y-m-d').' '.$title)
->line('----')
->getPath();
$collection->run();
?>
```
* `complete()` Delete this file when our collection completes.
* `filename($filename)` * `param string` $filename
* `append($append = null)` * `param bool` $append
* `line($line)` add a line.
* `lines(array $lines)` add more lines.
* `text($text)` add a text.
* `textFromFile($filename)` add a text from a file.
* `place($name, $val)` substitute a placeholder with value, placeholder must be enclosed by `{}`.
* `replace($string, $replacement)` replace any string with value.
* `regexReplace($pattern, $replacement)` replace any string with value using regular expression.
* `appendIfMatches($pattern, $text)` Append the provided text to the end of the buffer if the provided
* `appendUnlessMatches($pattern, $text)` Append the provided text to the end of the buffer unless the provided
* `originalContents()` @return string
* `wouldChange()` @return bool
* `getPath()` @return string
## Write
Writes to file.
``` php
<?php
$this->taskWriteToFile('blogpost.md')
->line('-----')
->line(date('Y-m-d').' '.$title)
->line('----')
->run();
?>
```
* `append()`
* `filename($filename)` * `param string` $filename
* `append($append = null)` * `param bool` $append
* `line($line)` add a line.
* `lines(array $lines)` add more lines.
* `text($text)` add a text.
* `textFromFile($filename)` add a text from a file.
* `place($name, $val)` substitute a placeholder with value, placeholder must be enclosed by `{}`.
* `replace($string, $replacement)` replace any string with value.
* `regexReplace($pattern, $replacement)` replace any string with value using regular expression.
* `appendIfMatches($pattern, $text)` Append the provided text to the end of the buffer if the provided
* `appendUnlessMatches($pattern, $text)` Append the provided text to the end of the buffer unless the provided
* `originalContents()` @return string
* `wouldChange()` @return bool
* `getPath()` @return string

View File

@@ -0,0 +1,217 @@
# Filesystem Tasks
## CleanDir
Deletes all files from specified dir, ignoring git files.
``` php
<?php
$this->taskCleanDir(['tmp','logs'])->run();
// as shortcut
$this->_cleanDir('app/cache');
?>
```
## CopyDir
Copies one dir into another
``` php
<?php
$this->taskCopyDir(['dist/config' => 'config'])->run();
// as shortcut
$this->_copyDir('dist/config', 'config');
?>
```
* `dirPermissions($value)` Sets the default folder permissions for the destination if it doesn't exist
* `exclude($exclude = null)` List files to exclude.
## DeleteDir
Deletes dir
``` php
<?php
$this->taskDeleteDir('tmp')->run();
// as shortcut
$this->_deleteDir(['tmp', 'log']);
?>
```
## FilesystemStack
Wrapper for [Symfony Filesystem](http://symfony.com/doc/current/components/filesystem.html) Component.
Comands are executed in stack and can be stopped on first fail with `stopOnFail` option.
``` php
<?php
$this->taskFilesystemStack()
->mkdir('logs')
->touch('logs/.gitignore')
->chgrp('www', 'www-data')
->symlink('/var/log/nginx/error.log', 'logs/error.log')
->run();
// one line
$this->_touch('.gitignore');
$this->_mkdir('logs');
?>
```
* `$this mkdir($dir)`
* `$this touch($file)`
* `$this copy($from, $to, $force = null)`
* `$this chmod($file, $permissions, $umask = null, $recursive = null)`
* `$this chgrp($file, $group, $recursive = null)`
* `$this chown($file, $user, $recursive = null)`
* `$this remove($file)`
* `$this rename($from, $to)`
* `$this symlink($from, $to)`
* `$this mirror($from, $to)`
* `stopOnFail($stop = null)` * `param bool` $stop
## FlattenDir
Searches for files in a nested directory structure and copies them to
a target directory with or without the parent directories. The task was
inspired by [gulp-flatten](https://www.npmjs.com/package/gulp-flatten).
Example directory structure:
```
└── assets
├── asset-library1
│ ├── README.md
│ └── asset-library1.min.js
└── asset-library2
├── README.md
└── asset-library2.min.js
```
The following code will search the `*.min.js` files and copy them
inside a new `dist` folder:
``` php
<?php
$this->taskFlattenDir(['assets/*.min.js' => 'dist'])->run();
// or use shortcut
$this->_flattenDir('assets/*.min.js', 'dist');
?>
```
You can also define the target directory with an additional method, instead of
key/value pairs. More similar to the gulp-flatten syntax:
``` php
<?php
$this->taskFlattenDir(['assets/*.min.js'])
->to('dist')
->run();
?>
```
You can also append parts of the parent directories to the target path. If you give
the value `1` to the `includeParents()` method, then the top parent will be appended
to the target directory resulting in a path such as `dist/assets/asset-library1.min.js`.
If you give a negative number, such as `-1` (the same as specifying `array(0, 1)` then
the bottom parent will be appended, resulting in a path such as
`dist/asset-library1/asset-library1.min.js`.
The top parent directory will always be starting from the relative path to the current
directory. You can override that with the `parentDir()` method. If in the above example
you would specify `assets`, then the top parent directory would be `asset-library1`.
``` php
<?php
$this->taskFlattenDir(['assets/*.min.js' => 'dist'])
->parentDir('assets')
->includeParents(1)
->run();
?>
```
* `dirPermissions($permission)` Sets the default folder permissions for the destination if it does not exist.
* `includeParents($parents)` Sets the value from which direction and how much parent dirs should be included.
* `parentDir($dir)` Sets the parent directory from which the relative parent directories will be calculated.
* `to($target)` Sets the target directory where the files will be copied to.
## MirrorDir
Mirrors a directory to another
``` php
<?php
$this->taskMirrorDir(['dist/config/' => 'config/'])->run();
// or use shortcut
$this->_mirrorDir('dist/config/', 'config/');
?>
```
## TmpDir
Create a temporary directory that is automatically cleaned up
once the task collection is is part of completes.
Use WorkDir if you do not want the directory to be deleted.
``` php
<?php
// Delete on rollback or on successful completion.
// Note that in this example, everything is deleted at
// the end of $collection->run().
$collection = $this->collectionBuilder();
$tmpPath = $collection->tmpDir()->getPath();
$collection->taskFilesystemStack()
->mkdir("$tmpPath/log")
->touch("$tmpPath/log/error.txt");
$collection->run();
// as shortcut (deleted when program exits)
$tmpPath = $this->_tmpDir();
?>
```
* `cwd($shouldChangeWorkingDirectory = null)` Flag that we should cwd to the temporary directory when it is
* `complete()` Delete this directory when our collection completes.
* `getPath()` Get a reference to the path to the temporary directory, so that
## WorkDir
Create a temporary working directory that is automatically renamed to its
final desired location if all of the tasks in the collection succeed. If
there is a rollback, then the working directory is deleted.
``` php
<?php
$collection = $this->collectionBuilder();
$workingPath = $collection->workDir("build")->getPath();
$collection->taskFilesystemStack()
->mkdir("$workingPath/log")
->touch("$workingPath/log/error.txt");
$collection->run();
?>
```
* `complete()` Move our working directory into its final destination once the
* `rollback()` Delete our working directory
* `getPath()` Get a reference to the path to the temporary directory, so that
* `cwd($shouldChangeWorkingDirectory = null)` Flag that we should cwd to the temporary directory when it is

View File

@@ -0,0 +1,31 @@
# Gulp Tasks
## Run
Gulp Run
``` php
<?php
// simple execution
$this->taskGulpRun()->run();
// run task 'clean' with --silent option
$this->taskGulpRun('clean')
->silent()
->run();
?>
```
* `silent()` adds `silent` option to gulp
* `noColor()` adds `--no-color` option to gulp
* `color()` adds `--color` option to gulp
* `simple()` adds `--tasks-simple` option to gulp
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,54 @@
# Npm Tasks
## Install
Npm Install
``` php
<?php
// simple execution
$this->taskNpmInstall()->run();
// prefer dist with custom path
$this->taskNpmInstall('path/to/my/npm')
->noDev()
->run();
?>
```
* `noDev()` adds `production` option to npm
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Update
Npm Update
```php
<?php
// simple execution
$this->taskNpmUpdate()->run();
// prefer dist with custom path
$this->taskNpmUpdate('path/to/my/npm')
->noDev()
->run();
?>
```
* `noDev()` adds `production` option to npm
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,143 @@
# Remote Tasks
## Rsync
Executes rsync in a flexible manner.
``` php
$this->taskRsync()
->fromPath('src/')
->toHost('localhost')
->toUser('dev')
->toPath('/var/www/html/app/')
->remoteShell('ssh -i public_key')
->recursive()
->excludeVcs()
->checksum()
->wholeFile()
->verbose()
->progress()
->humanReadable()
->stats()
->run();
```
You could also clone the task and do a dry-run first:
``` php
$rsync = $this->taskRsync()
->fromPath('src/')
->toPath('example.com:/var/www/html/app/')
->archive()
->excludeVcs()
->progress()
->stats();
$dryRun = clone $rsync;
$dryRun->dryRun()->run();
if ('y' === $this->ask('Do you want to run (y/n)')) {
$rsync->run();
}
```
* ` fromUser(string $user)`
* ` fromHost(string $hostname)`
* ` toUser(string $user)`
* ` toHost(string $hostname)`
* `fromPath($path)` This can either be a full rsync path spec (user@host:path) or just a path.
* `toPath($path)` This can either be a full rsync path spec (user@host:path) or just a path.
* `fromUser($fromUser)` * `param string` $fromUser
* `fromHost($fromHost)` * `param string` $fromHost
* `toUser($toUser)` * `param string` $toUser
* `toHost($toHost)` * `param string` $toHost
* `progress()` * `return` $this
* `stats()` * `return` $this
* `recursive()` * `return` $this
* `verbose()` * `return` $this
* `checksum()` * `return` $this
* `archive()` * `return` $this
* `compress()` * `return` $this
* `owner()` * `return` $this
* `group()` * `return` $this
* `times()` * `return` $this
* `delete()` * `return` $this
* `timeout($seconds)` * `param int` $seconds
* `humanReadable()` * `return` $this
* `wholeFile()` * `return` $this
* `dryRun()` * `return` $this
* `itemizeChanges()` * `return` $this
* `excludeVcs()` Excludes .git, .svn and .hg items at any depth.
* `exclude($pattern)` * `param array|string` $pattern
* `excludeFrom($file)` * `param string` $file
* `includeFilter($pattern)` * `param array|string` $pattern
* `filter($pattern)` * `param array|string` $pattern
* `filesFrom($file)` * `param string` $file
* `remoteShell($command)` * `param string` $command
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Ssh
Runs multiple commands on a remote server.
Per default, commands are combined with &&, unless stopOnFail is false.
```php
<?php
$this->taskSshExec('remote.example.com', 'user')
->remoteDir('/var/www/html')
->exec('ls -la')
->exec('chmod g+x logs')
->run();
```
You can even exec other tasks (which implement CommandInterface):
```php
$gitTask = $this->taskGitStack()
->checkout('master')
->pull();
$this->taskSshExec('remote.example.com')
->remoteDir('/var/www/html/site')
->exec($gitTask)
->run();
```
You can configure the remote directory for all future calls:
```php
::configure('remoteDir', '/some-dir');
```
* `$this stopOnFail(bool $stopOnFail)` Whether or not to chain commands together with &&
and stop the chain if one command fails
* `$this remoteDir(string $remoteWorkingDirectory)` Changes to the given directory before running commands
* `hostname($hostname)` * `param string` $hostname
* `user($user)` * `param string` $user
* `stopOnFail($stopOnFail = null)` * `param bool` $stopOnFail
* `remoteDir($remoteDir)` * `param string` $remoteDir
* `identityFile($filename)` * `param string` $filename
* `port($port)` * `param int` $port
* `forcePseudoTty()` * `return` $this
* `quiet()` * `return` $this
* `verbose()` * `return` $this
* `exec($command)` * `param string|string[]|CommandInterface` $command
* `simulate($context)` {@inheritdoc}
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,171 @@
# Testing Tasks
## Atoum
Runs [atoum](http://atoum.org/) tests
``` php
<?php
$this->taskAtoum()
->files('path/to/test.php')
->configFile('config/dev.php')
->run()
?>
```
* `tags($tags)` Tag or Tags to filter.
* `lightReport()` Display result using the light reporter.
* `tap()` Display result using the tap reporter.
* `bootstrap($file)` Path to the bootstrap file.
* `configFile($file)` Path to the config file.
* `debug()` Use atoum's debug mode.
* `files($files)` Test file or test files to run.
* `directories($directories)` Test directory or directories to run.
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Behat
Executes Behat tests
``` php
<?php
$this->taskBehat()
->format('pretty')
->noInteraction()
->run();
?>
```
* `stopOnFail()` * `return` $this
* `noInteraction()` * `return` $this
* `config($config_file)` * `param` $config_file
* `colors()` * `return` $this
* `noColors()` * `return` $this
* `suite($suite)` * `param string` $suite
* `verbose($level = null)` * `param string` $level
* `format($formater)` * `param string` $formater
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Codecept
Executes Codeception tests
``` php
<?php
// config
$this->taskCodecept()
->suite('acceptance')
->env('chrome')
->group('admin')
->xml()
->html()
->run();
?>
```
* `suite($suite)` * `param string` $suite
* `test($testName)` * `param string` $testName
* `group($group)` set group option. Can be called multiple times
* `excludeGroup($group)` * `param string` $group
* `json($file = null)` generate json report
* `xml($file = null)` generate xml JUnit report
* `html($dir = null)` Generate html report
* `tap($file = null)` generate tap report
* `configFile($file)` provides config file other then default `codeception.yml` with `-c` option
* `coverage($cov = null)` collect codecoverage in raw format. You may pass name of cov file to save results
* `silent()` execute in silent mode
* `coverageXml($xml = null)` collect code coverage in xml format. You may pass name of xml file to save results
* `coverageHtml($html = null)` collect code coverage and generate html report. You may pass
* `env($env)` * `param string` $env
* `debug()` * `return` $this
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## PHPUnit
Runs PHPUnit tests
``` php
<?php
$this->taskPHPUnit()
->group('core')
->bootstrap('test/bootstrap.php')
->run()
?>
```
* `filter($filter)` * `param string` $filter
* `group($group)` * `param string` $group
* `excludeGroup($group)` * `param string` $group
* `json($file = null)` adds `log-json` option to runner
* `xml($file = null)` adds `log-junit` option
* `tap($file = null)` * `param string` $file
* `bootstrap($file)` * `param string` $file
* `configFile($file)` * `param string` $file
* `debug()` * `return` $this
* `files($files)` Directory of test files or single test file to run.
* `file($file)` Test the provided file.
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.
## Phpspec
Executes Phpspec tests
``` php
<?php
$this->taskPhpspec()
->format('pretty')
->noInteraction()
->run();
?>
```
* `stopOnFail()`
* `noCodeGeneration()`
* `quiet()`
* `verbose($level = null)`
* `noAnsi()`
* `noInteraction()`
* `config($config_file)`
* `format($formater)`
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
* `arg($arg)` Pass argument to executable. Its value will be automatically escaped.
* `args($args)` Pass methods parameters as arguments to executable. Argument values
* `rawArg($arg)` Pass the provided string in its raw (as provided) form as an argument to executable.
* `option($option, $value = null)` Pass option to executable. Options are prefixed with `--` , value can be provided in second parameter.
* `optionList($option, $value = null)` Pass multiple options to executable. Value can be a string or array.

View File

@@ -0,0 +1,108 @@
# Vcs Tasks
## GitStack
Runs Git commands in stack. You can use `stopOnFail()` to point that stack should be terminated on first fail.
``` php
<?php
$this->taskGitStack()
->stopOnFail()
->add('-A')
->commit('adding everything')
->push('origin','master')
->tag('0.6.0')
->push('origin','0.6.0')
->run()
$this->taskGitStack()
->stopOnFail()
->add('doc/*')
->commit('doc updated')
->push()
->run();
?>
```
* `cloneRepo($repo, $to = null)` Executes `git clone`
* `add($pattern)` Executes `git add` command with files to add pattern
* `commit($message, $options = null)` Executes `git commit` command with a message
* `pull($origin = null, $branch = null)` Executes `git pull` command.
* `push($origin = null, $branch = null)` Executes `git push` command
* `merge($branch)` Performs git merge
* `checkout($branch)` Executes `git checkout` command
* `tag($tag_name, $message = null)` Executes `git tag` command
* `executable($executable)` * `param string` $executable
* `exec($command)` * `param string|string[]` $command
* `stopOnFail($stopOnFail = null)` * `param bool` $stopOnFail
* `result($result)`
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
## HgStack
Runs hg commands in stack. You can use `stopOnFail()` to point that stack should be terminated on first fail.
``` php
<?php
$this->hgStack
->cloneRepo('https://bitbucket.org/durin42/hgsubversion')
->pull()
->add()
->commit('changed')
->push()
->tag('0.6.0')
->push('0.6.0')
->run();
?>
```
* `cloneRepo($repo, $to = null)` Executes `hg clone`
* `add($include = null, $exclude = null)` Executes `hg add` command with files to add by pattern
* `commit($message, $options = null)` Executes `hg commit` command with a message
* `pull($branch = null)` Executes `hg pull` command.
* `push($branch = null)` Executes `hg push` command
* `merge($revision = null)` Performs hg merge
* `tag($tag_name, $message = null)` Executes `hg tag` command
* `executable($executable)` * `param string` $executable
* `exec($command)` * `param string|string[]` $command
* `stopOnFail($stopOnFail = null)` * `param bool` $stopOnFail
* `result($result)`
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed
## SvnStack
Runs Svn commands in stack. You can use `stopOnFail()` to point that stack should be terminated on first fail.
``` php
<?php
$this->taskSvnStack()
->checkout('http://svn.collab.net/repos/svn/trunk')
->run()
// alternatively
$this->_svnCheckout('http://svn.collab.net/repos/svn/trunk');
$this->taskSvnStack('username', 'password')
->stopOnFail()
->update()
->add('doc/*')
->commit('doc updated')
->run();
?>
```
* `update($path = null)` Updates `svn update` command
* `add($pattern = null)` Executes `svn add` command with files to add pattern
* `commit($message, $options = null)` Executes `svn commit` command with a message
* `checkout($branch)` Executes `svn checkout` command
* `executable($executable)` * `param string` $executable
* `exec($command)` * `param string|string[]` $command
* `stopOnFail($stopOnFail = null)` * `param bool` $stopOnFail
* `result($result)`
* `dir($dir)` Changes working directory of command
* `printed($arg)` Should command output be printed