Added once feature

This commit is contained in:
Alin Alexandru 2017-07-27 13:55:15 +03:00
parent da352b0c63
commit e506208b20
2 changed files with 71 additions and 0 deletions

View File

@ -61,6 +61,20 @@ class Task
*/
private $private = false;
/**
* Mark task to run only once, of the first node from the pool
*
* @var bool
*/
private $once = false;
/**
* Mark if the task has run at least once
*
* @var bool
*/
private $hasRun = false;
/**
* @param string $name Tasks name
* @param callable $callback Task code
@ -81,6 +95,10 @@ class Task
// Call task
call_user_func($this->callback);
if ($this->once) {
$this->hasRun = true;
}
// Clear working_path
if ($context->getConfig() !== null) {
$context->getConfig()->set('working_path', false);
@ -134,6 +152,17 @@ class Task
return $this->local;
}
public function once()
{
$this->once = true;
return $this;
}
public function isOnce()
{
return $this->once;
}
/**
* @param array $hosts
* @return $this
@ -172,6 +201,11 @@ class Task
*/
public function shouldBePerformed(...$hosts)
{
// don't allow to run again it the task has been marked to run only once
if ($this->once && $this->hasRun) {
return false;
}
foreach ($hosts as $host) {
$onHost = empty($this->on['hosts']) || in_array($host->getHostname(), $this->on['hosts'], true);

View File

@ -40,6 +40,9 @@ class TaskTest extends TestCase
$task->setPrivate();
self::assertTrue($task->isPrivate());
$task->once();
self::assertTrue($task->isOnce());
}
public function testShouldBePerformed()
@ -126,6 +129,40 @@ class TaskTest extends TestCase
$task3->run($context);
self::assertEquals(1, StubTask::$runned);
}
public function testOnce()
{
$a = (new Host('a'))->stage('prod')->roles('app');
$b = (new Host('b'))->stage('prod')->roles('app');
$context = self::getMockBuilder(Context::class)->disableOriginalConstructor()->getMock();
// Test create task with [$object, 'method']
$mock = self::getMockBuilder('stdClass')
->setMethods(['callback'])
->getMock();
$task1 = new Task('only:once', [$mock, 'callback']);
$task1
->onHosts('a','b')
->once();
self::assertTrue($task1->shouldBePerformed($a));
self::assertEquals([true, true], array_map([$task1, 'shouldBePerformed'], [$a, $b]));
$task1->run($context);
self::assertFalse($task1->shouldBePerformed($b));
self::assertEquals([false, false], array_map([$task1, 'shouldBePerformed'], [$a, $b]));
$task2 = new Task('multiple:runs', [$mock, 'callback']);
$task2
->onHosts('a','b');
self::assertTrue($task2->shouldBePerformed($a));
self::assertEquals([true, true], array_map([$task2, 'shouldBePerformed'], [$a, $b]));
$task2->run($context);
self::assertTrue($task2->shouldBePerformed($b));
self::assertEquals([true, true], array_map([$task2, 'shouldBePerformed'], [$a, $b]));
}
}
/**