Big refactoring. Use of Namespaces and codestyles. PSR-0, PSR-1, PSR-2.

This commit is contained in:
Andrés Montañez 2013-11-06 12:44:05 -02:00
parent 8329b53f22
commit f961a51c37
57 changed files with 1801 additions and 978 deletions

View file

@ -8,25 +8,46 @@
* file that was distributed with this source code.
*/
class Mage_Autoload
namespace Mage;
/**
* Magallanes custom Autoload for BuiltIn and Userspace Commands and Tasks.
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Autoload
{
/**
* Autoload a Class by it's Class Name
* @param string $className
*/
public static function autoload($className)
{
$baseDir = dirname(dirname(__FILE__));
$classFile = $baseDir . '/' . str_replace('_', '/', $className . '.php');
$classFile = $baseDir . '/' . str_replace(array('_', '\\'), '/', $className . '.php');
require_once $classFile;
}
/**
* Checks if a Class can be loaded.
* @param string $className
* @return boolean
*/
public static function isLoadable($className)
{
$baseDir = dirname(dirname(__FILE__));
$classFile = $baseDir . '/' . str_replace('_', '/', $className . '.php');
$classFile = $baseDir . '/' . str_replace(array('_', '\\'), '/', $className . '.php');
return (file_exists($classFile) && is_readable($classFile));
}
/**
* Loads a User's Tasks
* @param string $taskName
*/
public static function loadUserTask($taskName)
{
$classFile = '.mage/tasks/' . ucfirst($taskName) . '.php';
require_once $classFile;
}
}

View file

@ -0,0 +1,54 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command;
use Mage\Config;
/**
* Abstract Class for a Magallanes Command
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
abstract class AbstractCommand
{
/**
* Instance of the loaded Configuration.
*
* @var Mage\Config
*/
protected $config = null;
/**
* Runs the Command
* @throws Exception
*/
public abstract function run();
/**
* Sets the Loaded Configuration.
*
* @param Config $config
*/
public function setConfig(Config $config)
{
$this->config = $config;
}
/**
* Gets the Loaded Configuration.
*
* @return Config
*/
public function getConfig()
{
return $this->config;
}
}

View file

@ -8,9 +8,27 @@
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Add
extends Mage_Command_CommandAbstract
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Command for Adding elements to the Configuration.
* Currently elements allowed to add:
* - environments
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class AddCommand extends AbstractCommand
{
/**
* Adds new Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
public function run()
{
$subCommand = $this->getConfig()->getArgument(1);
@ -18,15 +36,24 @@ class Mage_Command_BuiltIn_Add
try {
switch ($subCommand) {
case 'environment':
$this->_environment();
$this->addEnvironment();
break;
default;
throw new Exception('The Type of Add is needed.');
break;
}
} catch (Exception $e) {
Mage_Console::output('<red>' . $e->getMessage() . '</red>', 1, 2);
} catch (Exception $exception) {
Console::output('<red>' . $exception->getMessage() . '</red>', 1, 2);
}
}
private function _environment()
/**
* Adds an Environment
*
* @throws Exception
*/
protected function addEnvironment()
{
$withReleases = $this->getConfig()->getParameter('enableReleases', false);
$environmentName = strtolower($this->getConfig()->getParameter('name'));
@ -41,7 +68,7 @@ class Mage_Command_BuiltIn_Add
throw new Exception('The environment already exists.');
}
Mage_Console::output('Adding new environment: <dark_gray>' . $environmentName . '</dark_gray>');
Console::output('Adding new environment: <dark_gray>' . $environmentName . '</dark_gray>');
$releasesConfig = 'releases:' . PHP_EOL
. ' enabled: true' . PHP_EOL
@ -67,10 +94,10 @@ class Mage_Command_BuiltIn_Add
$result = file_put_contents($environmentConfigFile, $baseConfig);
if ($result) {
Mage_Console::output('<light_green>Success!!</light_green> Environment config file for <dark_gray>' . $environmentName . '</dark_gray> created successfully at <blue>' . $environmentConfigFile . '</blue>');
Mage_Console::output('<dark_gray>So please! Review and adjust its configuration.</dark_gray>', 2, 2);
Console::output('<light_green>Success!!</light_green> Environment config file for <dark_gray>' . $environmentName . '</dark_gray> created successfully at <blue>' . $environmentConfigFile . '</blue>');
Console::output('<dark_gray>So please! Review and adjust its configuration.</dark_gray>', 2, 2);
} else {
Mage_Console::output('<light_red>Error!!</light_red> Unable to create config file for environment called <dark_gray>' . $environmentName . '</dark_gray>', 1, 2);
Console::output('<light_red>Error!!</light_red> Unable to create config file for environment called <dark_gray>' . $environmentName . '</dark_gray>', 1, 2);
}
}
}

View file

@ -1,31 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Class Mage_Command_BuiltIn_Compile
*
* @author Ismael Ambrosi<ismaambrosi@gmail.com>
*/
class Mage_Command_BuiltIn_Compile
extends Mage_Command_CommandAbstract
{
/**
* @see Mage_Compile::compile()
*/
public function run ()
{
Mage_Console::output('Compiling <dark_gray>Magallanes</dark_gray>... ', 1, 0);
$compiler = new Mage_Compiler();
$compiler->compile();
Mage_Console::output('Mage compiled successfully');
}
}

View file

@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Mage\Compiler;
use Exception;
/**
* Command for Compile Magallanes into a PHAR executable
*
* @author Ismael Ambrosi<ismaambrosi@gmail.com>
*/
class CompileCommand extends AbstractCommand
{
/**
* @see \Mage\Compile::compile()
*/
public function run ()
{
Console::output('Compiling <dark_gray>Magallanes</dark_gray>... ', 1, 0);
$compiler = new Compiler;
$compiler->compile();
Console::output('Mage compiled successfully');
}
}

View file

@ -8,42 +8,96 @@
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Deploy
extends Mage_Command_CommandAbstract
implements Mage_Command_RequiresEnvironment
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Command\RequiresEnvironment;
use Mage\Task\Factory;
use Mage\Task\Releases\SkipOnOverride;
use Mage\Task\ErrorWithMessageException;
use Mage\Task\SkipException;
use Mage\Console;
use Mage\Config;
use Exception;
/**
* Command for Deploying
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class DeployCommand extends AbstractCommand implements RequiresEnvironment
{
/**
* Deploy has Failed
* @var string
*/
const FAILED = 'failed';
/**
* Deploy has Succeded
* @var string
*/
const SUCCEDED = 'succeded';
/**
* Deploy is in progress
* @var string
*/
const IN_PROGRESS = 'in_progress';
private $_startTime = null;
private $_startTimeHosts = null;
private $_endTimeHosts = null;
private $_hostsCount = 0;
/**
* Time the Deployment has Started
* @var integer
*/
protected $startTime = null;
private static $_deployStatus = 'in_progress';
/**
* Time the Deployment has Started to the current Host
* @var integer
*/
protected $startTimeHosts = null;
public function __construct()
{
}
/**
* Time the Deployment to the Hosts has Finished
* @var integer
*/
protected $endTimeHosts = null;
/**
* Quantity of Hosts to Deploy to.
* @var integer
*/
protected $hostsCount = 0;
protected static $deployStatus = 'in_progress';
/**
* Returns the Status of the Deployment
*
* @return string
*/
public static function getStatus()
{
return self::$_deployStatus;
return self::$deployStatus;
}
/**
* Deploys the Application
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
// Check if Environment is not Locked
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
Mage_Console::output('<red>This environment is locked!</red>', 1, 2);
Console::output('<red>This environment is locked!</red>', 1, 2);
return;
}
// Check for running instance and Lock
if (file_exists('.mage/~working.lock')) {
Mage_Console::output('<red>There is already an instance of Magallanes running!</red>', 1, 2);
Console::output('<red>There is already an instance of Magallanes running!</red>', 1, 2);
return;
} else {
touch('.mage/~working.lock');
@ -54,48 +108,48 @@ class Mage_Command_BuiltIn_Deploy
$failedTasks = 0;
// Deploy Summary
Mage_Console::output('<dark_gray>Deploy summary</dark_gray>', 1, 1);
Console::output('<dark_gray>Deploy summary</dark_gray>', 1, 1);
// Deploy Summary - Environment
Mage_Console::output('<dark_gray>Environment:</dark_gray> <purple>' . $this->getConfig()->getEnvironment() . '</purple>', 2, 1);
Console::output('<dark_gray>Environment:</dark_gray> <purple>' . $this->getConfig()->getEnvironment() . '</purple>', 2, 1);
// Deploy Summary - Releases
if ($this->getConfig()->release('enabled', false)) {
Mage_Console::output('<dark_gray>Release ID:</dark_gray> <purple>' . $this->getConfig()->getReleaseId() . '</purple>', 2, 1);
Console::output('<dark_gray>Release ID:</dark_gray> <purple>' . $this->getConfig()->getReleaseId() . '</purple>', 2, 1);
}
// Deploy Summary - SCM
if ($this->getConfig()->deployment('scm', false)) {
$scmConfig = $this->getConfig()->deployment('scm');
if (isset($scmConfig['branch'])) {
Mage_Console::output('<dark_gray>SCM Branch:</dark_gray> <purple>' . $scmConfig['branch'] . '</purple>', 2, 1);
Console::output('<dark_gray>SCM Branch:</dark_gray> <purple>' . $scmConfig['branch'] . '</purple>', 2, 1);
}
}
// Deploy Summary - Separator Line
Mage_Console::output('', 0, 1);
Console::output('', 0, 1);
$this->_startTime = time();
$this->startTime = time();
// Run Pre-Deployment Tasks
$this->_runNonDeploymentTasks('pre-deploy', $this->getConfig(), 'Pre-Deployment');
$this->runNonDeploymentTasks('pre-deploy', $this->getConfig(), 'Pre-Deployment');
// Run Tasks for Deployment
$hosts = $this->getConfig()->getHosts();
$this->_hostsCount = count($hosts);
$this->hostsCount = count($hosts);
if ($this->_hostsCount == 0) {
Mage_Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, skipping deployment tasks.</dark_gray>', 1, 3);
if ($this->hostsCount == 0) {
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, skipping deployment tasks.</dark_gray>', 1, 3);
} else {
$this->_startTimeHosts = time();
foreach ($hosts as $_hostKey => $host) {
$this->startTimeHosts = time();
foreach ($hosts as $hostKey => $host) {
// Check if Host has specific configuration
$hostConfig = null;
if (is_array($host)) {
$hostConfig = $host;
$host = $_hostKey;
$host = $hostKey;
}
// Set Host and Host Specific Config
@ -106,21 +160,21 @@ class Mage_Command_BuiltIn_Deploy
$tasks = 0;
$completedTasks = 0;
Mage_Console::output('Deploying to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
Console::output('Deploying to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
$tasksToRun = $this->getConfig()->getTasks();
array_unshift($tasksToRun, 'deployment/rsync');
if (count($tasksToRun) == 0) {
Mage_Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Mage_Console::output('Deployment to <dark_gray>' . $host . '</dark_gray> skipped!', 1, 3);
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Console::output('Deployment to <dark_gray>' . $host . '</dark_gray> skipped!', 1, 3);
} else {
foreach ($tasksToRun as $taskData) {
$tasks++;
$task = Mage_Task_Factory::get($taskData, $this->getConfig(), false, 'deploy');
$task = Factory::get($taskData, $this->getConfig(), false, 'deploy');
if ($this->_runTask($task)) {
if ($this->runTask($task)) {
$completedTasks++;
} else {
$failedTasks++;
@ -133,34 +187,34 @@ class Mage_Command_BuiltIn_Deploy
$tasksColor = 'red';
}
Mage_Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> completed: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
// Reset Host Config
$this->getConfig()->setHostConfig(null);
}
$this->_endTimeHosts = time();
$this->endTimeHosts = time();
if ($failedTasks > 0) {
self::$_deployStatus = self::FAILED;
Mage_Console::output('A total of <dark_gray>' . $failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
self::$deployStatus = self::FAILED;
Console::output('A total of <dark_gray>' . $failedTasks . '</dark_gray> deployment tasks failed: <red>ABORTING</red>', 1, 2);
} else {
self::$_deployStatus = self::SUCCEDED;
self::$deployStatus = self::SUCCEDED;
}
// Releasing
if (self::$_deployStatus == self::SUCCEDED && $this->getConfig()->release('enabled', false) == true) {
if (self::$deployStatus == self::SUCCEDED && $this->getConfig()->release('enabled', false) == true) {
// Execute the Releases
Mage_Console::output('Starting the <dark_gray>Releaseing</dark_gray>');
Console::output('Starting the <dark_gray>Releaseing</dark_gray>');
foreach ($hosts as $host) {
$this->getConfig()->setHost($host);
$task = Mage_Task_Factory::get('deployment/release', $this->getConfig(), false, 'deploy');
$task = Factory::get('deployment/release', $this->getConfig(), false, 'deploy');
if ($this->_runTask($task, 'Releasing on host <purple>' . $host . '</purple> ... ')) {
if ($this->runTask($task, 'Releasing on host <purple>' . $host . '</purple> ... ')) {
$completedTasks++;
}
}
Mage_Console::output('Finished the <dark_gray>Releaseing</dark_gray>', 1, 3);
Console::output('Finished the <dark_gray>Releaseing</dark_gray>', 1, 3);
// Execute the Post-Release Tasks
foreach ($hosts as $host) {
@ -170,12 +224,12 @@ class Mage_Command_BuiltIn_Deploy
$completedTasks = 0;
if (count($tasksToRun) > 0) {
Mage_Console::output('Starting <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>:');
Console::output('Starting <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>:');
foreach ($tasksToRun as $task) {
$task = Mage_Task_Factory::get($task, $this->getConfig(), false, 'post-release');
$task = Factory::get($task, $this->getConfig(), false, 'post-release');
if ($this->_runTask($task)) {
if ($this->runTask($task)) {
$completedTasks++;
}
}
@ -185,30 +239,30 @@ class Mage_Command_BuiltIn_Deploy
} else {
$tasksColor = 'red';
}
Mage_Console::output('Finished <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
Console::output('Finished <dark_gray>Post-Release</dark_gray> tasks for <dark_gray>' . $host . '</dark_gray>: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
}
}
}
// Run Post-Deployment Tasks
$this->_runNonDeploymentTasks('post-deploy', $this->getConfig(), 'Post-Deployment');
$this->runNonDeploymentTasks('post-deploy', $this->getConfig(), 'Post-Deployment');
// Time Information Hosts
if ($this->_hostsCount > 0) {
$timeTextHost = $this->_transcurredTime($this->_endTimeHosts - $this->_startTimeHosts);
Mage_Console::output('Time for deployment: <dark_gray>' . $timeTextHost . '</dark_gray>.');
if ($this->hostsCount > 0) {
$timeTextHost = $this->transcurredTime($this->endTimeHosts - $this->startTimeHosts);
Console::output('Time for deployment: <dark_gray>' . $timeTextHost . '</dark_gray>.');
$timeTextPerHost = $this->_transcurredTime(round(($this->_endTimeHosts - $this->_startTimeHosts) / $this->_hostsCount));
Mage_Console::output('Average time per host: <dark_gray>' . $timeTextPerHost . '</dark_gray>.');
$timeTextPerHost = $this->transcurredTime(round(($this->endTimeHosts - $this->startTimeHosts) / $this->hostsCount));
Console::output('Average time per host: <dark_gray>' . $timeTextPerHost . '</dark_gray>.');
}
// Time Information General
$timeText = $this->_transcurredTime(time() - $this->_startTime);
Mage_Console::output('Total time: <dark_gray>' . $timeText . '</dark_gray>.', 1, 2);
$timeText = $this->transcurredTime(time() - $this->startTime);
Console::output('Total time: <dark_gray>' . $timeText . '</dark_gray>.', 1, 2);
// Send Notifications
$this->_sendNotification();
$this->sendNotification();
// Unlock
if (file_exists('.mage/~working.lock')) {
@ -220,22 +274,22 @@ class Mage_Command_BuiltIn_Deploy
* Execute Pre and Post Deployment Tasks
*
* @param string $stage
* @param Mage_Config $config
* @param Config $config
* @param string $title
*/
private function _runNonDeploymentTasks($stage, Mage_Config $config, $title)
protected function runNonDeploymentTasks($stage, Config $config, $title)
{
$tasksToRun = $config->getTasks($stage);
// PreDeployment Hook
if ($stage == 'pre-deploy') {
// Look for Remote Source
if (is_array($this->_config->deployment('source', null))) {
if (is_array($config->deployment('source', null))) {
array_unshift($tasksToRun, 'scm/clone');
}
// Change Branch
if ($this->getConfig()->deployment('scm', false)) {
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
}
}
@ -243,36 +297,36 @@ class Mage_Command_BuiltIn_Deploy
// PostDeployment Hook
if ($stage == 'post-deploy') {
// If Deploy failed, clear post deploy tasks
if (self::$_deployStatus == self::FAILED) {
if (self::$deployStatus == self::FAILED) {
$tasksToRun = array();
}
// Change Branch Back
if ($this->getConfig()->deployment('scm', false)) {
if ($config->deployment('scm', false)) {
array_unshift($tasksToRun, 'scm/change-branch');
$config->addParameter('_changeBranchRevert');
}
// Remove Remote Source
if (is_array($this->_config->deployment('source', null))) {
if (is_array($config->deployment('source', null))) {
array_push($tasksToRun, 'scm/remove-clone');
}
}
if (count($tasksToRun) == 0) {
Mage_Console::output('<dark_gray>No </dark_gray><light_cyan>' . $title . '</light_cyan> <dark_gray>tasks defined.</dark_gray>', 1, 3);
Console::output('<dark_gray>No </dark_gray><light_cyan>' . $title . '</light_cyan> <dark_gray>tasks defined.</dark_gray>', 1, 3);
} else {
Mage_Console::output('Starting <dark_gray>' . $title . '</dark_gray> tasks:');
Console::output('Starting <dark_gray>' . $title . '</dark_gray> tasks:');
$tasks = 0;
$completedTasks = 0;
foreach ($tasksToRun as $taskData) {
$tasks++;
$task = Mage_Task_Factory::get($taskData, $config, false, $stage);
$task = Factory::get($taskData, $config, false, $stage);
if ($this->_runTask($task)) {
if ($this->runTask($task)) {
$completedTasks++;
}
}
@ -283,21 +337,28 @@ class Mage_Command_BuiltIn_Deploy
$tasksColor = 'red';
}
Mage_Console::output('Finished <dark_gray>' . $title . '</dark_gray> tasks: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
Console::output('Finished <dark_gray>' . $title . '</dark_gray> tasks: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
}
private function _runTask($task, $title = null)
/**
* Runs a Task
*
* @param string $task
* @param string $title
* @return boolean
*/
protected function runTask($task, $title = null)
{
$task->init();
if ($title == null) {
$title = 'Running <purple>' . $task->getName() . '</purple> ... ';
}
Mage_Console::output($title, 2, 0);
Console::output($title, 2, 0);
$runTask = true;
if (($task instanceOf Mage_Task_Releases_SkipOnOverride) && $this->getConfig()->getParameter('overrideRelease', false)) {
if (($task instanceOf SkipOnOverride) && $this->getConfig()->getParameter('overrideRelease', false)) {
$runTask == false;
}
@ -307,27 +368,27 @@ class Mage_Command_BuiltIn_Deploy
$result = $task->run();
if ($result == true) {
Mage_Console::output('<green>OK</green>', 0);
Console::output('<green>OK</green>', 0);
$result = true;
} else {
Mage_Console::output('<red>FAIL</red>', 0);
Console::output('<red>FAIL</red>', 0);
$result = false;
}
} catch (Mage_Task_ErrorWithMessageException $e) {
Mage_Console::output('<red>FAIL</red> [Message: ' . $e->getMessage() . ']', 0);
} catch (ErrorWithMessageException $e) {
Console::output('<red>FAIL</red> [Message: ' . $e->getMessage() . ']', 0);
$result = false;
} catch (Mage_Task_SkipException $e) {
Mage_Console::output('<yellow>SKIPPED</yellow>', 0);
} catch (SkipException $e) {
Console::output('<yellow>SKIPPED</yellow>', 0);
$result = true;
} catch (Exception $e) {
Mage_Console::output('<red>FAIL</red>', 0);
Console::output('<red>FAIL</red>', 0);
$result = false;
}
} else {
Mage_Console::output('<yellow>SKIPPED</yellow>', 0);
Console::output('<yellow>SKIPPED</yellow>', 0);
$result = true;
}
@ -336,10 +397,11 @@ class Mage_Command_BuiltIn_Deploy
/**
* Humanize Transcurred time
*
* @param integer $time
* @return string
*/
private function _transcurredTime($time)
protected function transcurredTime($time)
{
$hours = floor($time / 3600);
$minutes = floor(($time - ($hours * 3600)) / 60);
@ -354,7 +416,7 @@ class Mage_Command_BuiltIn_Deploy
$timeText[] = $minutes . ' minutes';
}
if ($seconds > 0) {
if ($seconds >= 0) {
$timeText[] = $seconds . ' seconds';
}
@ -364,7 +426,7 @@ class Mage_Command_BuiltIn_Deploy
/**
* Send Email Notification if enabled
*/
private function _sendNotification()
protected function sendNotification()
{
$projectName = $this->getConfig()->general('name', false);
$projectEmail = $this->getConfig()->general('email', false);
@ -375,4 +437,5 @@ class Mage_Command_BuiltIn_Deploy
return false;
}
}
}

View file

@ -8,27 +8,34 @@
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Init
extends Mage_Command_CommandAbstract
{
protected $generalTemplate = <<<'YML'
# global settings
name: %projectName%
email: %notificationEmail%
notifications: %notificationEnabled%
logging: %loggingEnabled%
maxlogs: %maxlogs%
YML;
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Initializes a Magallanes Configuration into a Proyect
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class InitCommand extends AbstractCommand
{
/**
* Command for Initalize a new Configuration Proyect
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$configDir = '.mage';
Mage_Console::output('Initiating managing process for application with <dark_gray>Magallanes</dark_gray>');
Console::output('Initiating managing process for application with <dark_gray>Magallanes</dark_gray>');
// Check if there is already a config dir
if (file_exists($configDir)) {
Mage_Console::output('<light_red>Error!!</light_red> Already exists <dark_gray>.mage</dark_gray> directory.', 1, 2);
Console::output('<light_red>Error!!</light_red> Already exists <dark_gray>.mage</dark_gray> directory.', 1, 2);
} else {
$results = array();
$results[] = mkdir($configDir);
@ -42,14 +49,18 @@ YML;
$results[] = file_put_contents($configDir . '/config/general.yml', $this->getGeneralConfig());
if (!in_array(false, $results)) {
Mage_Console::output('<light_green>Success!!</light_green> The configuration for <dark_gray>Magallanes</dark_gray> has been generated at <blue>.mage</blue> directory.');
Mage_Console::output('<dark_gray>Please!! Review and adjust the configuration.</dark_gray>', 2, 2);
Console::output('<light_green>Success!!</light_green> The configuration for <dark_gray>Magallanes</dark_gray> has been generated at <blue>.mage</blue> directory.');
Console::output('<dark_gray>Please!! Review and adjust the configuration.</dark_gray>', 2, 2);
} else {
Mage_Console::output('<light_red>Error!!</light_red> Unable to generate the configuration.', 1, 2);
Console::output('<light_red>Error!!</light_red> Unable to generate the configuration.', 1, 2);
}
}
}
/**
* Returns the Global Configuration
* @return string
*/
protected function getGeneralConfig()
{
// Assamble Global Settings
@ -77,4 +88,20 @@ YML;
return $globalSettings;
}
/**
* Returns the YAML Template for the Global Configuration
* @return string
*/
protected function getGeneralConfigTemplate()
{
$template = '# global settings' . PHP_EOL
. 'name: %projectName%' . PHP_EOL
. 'email: %notificationEmail%' . PHP_EOL
. 'notifications: %notificationEnabled%' . PHP_EOL
. 'logging: %loggingEnabled%' . PHP_EOL
. 'maxlogs: %maxlogs%' . PHP_EOL;
return $template;
}
}

View file

@ -8,12 +8,27 @@
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Install
extends Mage_Command_CommandAbstract
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Installs Magallanes in the Local System
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class InstallCommand extends AbstractCommand
{
/**
* Installs Magallanes
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
Mage_Console::output('Installing <dark_gray>Magallanes</dark_gray>... ', 1, 0);
Console::output('Installing <dark_gray>Magallanes</dark_gray>... ', 1, 0);
// Vars
$installDir = $this->getConfig()->getParameter('installDir', '/opt/magallanes');
@ -25,11 +40,11 @@ class Mage_Command_BuiltIn_Install
// Check if install dir is available
if (!is_dir($baseDir) || !is_writable($baseDir)) {
Mage_Console::output('<red>Failure: install directory is invalid.</red>', 0, 2);
Console::output('<red>Failure: install directory is invalid.</red>', 0, 2);
// Chck if it is a system wide install the user is root
} else if ($systemWide && (getenv('LOGNAME') != 'root')) {
Mage_Console::output('<red>Failure: you have to be root to perform a system wide install.</red>', 0, 2);
Console::output('<red>Failure: you have to be root to perform a system wide install.</red>', 0, 2);
} else {
$destinationDir = $baseDir . '/' . $installDir;
@ -38,7 +53,7 @@ class Mage_Command_BuiltIn_Install
}
// Copy
$this->_recursiveCopy('./', $destinationDir . '/' . MAGALLANES_VERSION);
$this->recursiveCopy('./', $destinationDir . '/' . MAGALLANES_VERSION);
// Check if there is already a symlink
if (file_exists($destinationDir . '/' . 'latest')
@ -59,11 +74,17 @@ class Mage_Command_BuiltIn_Install
}
}
Mage_Console::output('<light_green>Success!</light_green>', 0, 2);
Console::output('<light_green>Success!</light_green>', 0, 2);
}
}
private function _recursiveCopy($from, $to)
/**
* Copy Files
* @param string $from
* @param string $to
* @return boolean
*/
protected function recursiveCopy($from, $to)
{
if (is_dir($from)) {
mkdir($to);
@ -76,7 +97,7 @@ class Mage_Command_BuiltIn_Install
}
if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
$this->_recursiveCopy(
$this->recursiveCopy(
$from . DIRECTORY_SEPARATOR . $file,
$to . DIRECTORY_SEPARATOR . $file
);

View file

@ -1,51 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_List
extends Mage_Command_CommandAbstract
{
public function run()
{
$subCommand = $this->getConfig()->getArgument(1);
try {
switch ($subCommand) {
case 'environments':
$this->_environment();
break;
}
} catch (Exception $e) {
Mage_Console::output('<red>' . $e->getMessage() . '</red>', 1, 2);
}
}
private function _environment()
{
$environments = array();
$content = scandir('.mage/config/environment/');
foreach ($content as $file) {
if (strpos($file, '.yml') !== false) {
$environments[] = str_replace('.yml', '', $file);
}
}
sort($environments);
if (count($environments) > 0) {
Mage_Console::output('<dark_gray>These are your configured environments:</dark_gray>', 1, 1);
foreach ($environments as $environment) {
Mage_Console::output('* <light_red>' . $environment . '</light_red>', 2, 1);
}
Mage_Console::output('', 1, 1);
} else {
Mage_Console::output('<dark_gray>You don\'t have any environment configured.</dark_gray>', 1, 2);
}
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Adds elements to the Configuration.
* Currently elements allowed to add:
* - environments
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ListCommand extends AbstractCommand
{
/**
* Command for Listing Configuration Elements
* @see \Mage\Command\AbstractCommand::run()
* @throws Exception
*/
public function run()
{
$subCommand = $this->getConfig()->getArgument(1);
try {
switch ($subCommand) {
case 'environments':
$this->listEnvironments();
break;
default;
throw new Exception('The Type of Elements to List is needed.');
break;
}
} catch (Exception $e) {
Console::output('<red>' . $e->getMessage() . '</red>', 1, 2);
}
}
/**
* Lists the Environments
*/
protected function listEnvironments()
{
$environments = array();
$content = scandir('.mage/config/environment/');
foreach ($content as $file) {
if (strpos($file, '.yml') !== false) {
$environments[] = str_replace('.yml', '', $file);
}
}
sort($environments);
if (count($environments) > 0) {
Console::output('<dark_gray>These are your configured environments:</dark_gray>', 1, 1);
foreach ($environments as $environment) {
Console::output('* <light_red>' . $environment . '</light_red>', 2, 1);
}
Console::output('', 1, 1);
} else {
Console::output('<dark_gray>You don\'t have any environment configured.</dark_gray>', 1, 2);
}
}
}

View file

@ -1,23 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Lock
extends Mage_Command_CommandAbstract
implements Mage_Command_RequiresEnvironment
{
public function run()
{
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
file_put_contents($lockFile, 'Locked environment at date: ' . date('Y-m-d H:i:s'));
Mage_Console::output('Locked deployment to <light_purple>' . $this->getConfig()->getEnvironment() . '</light_purple> environment', 1, 2);
}
}

View file

@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Command\RequiresEnvironment;
use Mage\Console;
use Exception;
/**
* Command for Locking the Deployment to an Environment
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class LockCommand extends AbstractCommand implements RequiresEnvironment
{
/**
* Locks the Deployment to a Environment
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
file_put_contents($lockFile, 'Locked environment at date: ' . date('Y-m-d H:i:s'));
Console::output('Locked deployment to <light_purple>' . $this->getConfig()->getEnvironment() . '</light_purple> environment', 1, 2);
}
}

View file

@ -8,18 +8,34 @@
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Releases
extends Mage_Command_CommandAbstract
implements Mage_Command_RequiresEnvironment
{
private $_release = null;
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Command\RequiresEnvironment;
use Mage\Task\Factory;
use Mage\Console;
use Exception;
/**
* Command for Managing the Releases
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ReleasesCommand extends AbstractCommand implements RequiresEnvironment
{
private $release = null;
/**
* List the Releases, Rollback to a Release
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$subcommand = $this->getConfig()->getArgument(1);
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile) && ($subcommand == 'rollback')) {
Mage_Console::output('<red>This environment is locked!</red>', 0, 2);
Console::output('<red>This environment is locked!</red>', 0, 2);
return;
}
@ -27,7 +43,7 @@ class Mage_Command_BuiltIn_Releases
$hosts = $this->getConfig()->getHosts();
if (count($hosts) == 0) {
Mage_Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, unable to get releases.</dark_gray>', 1, 3);
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No hosts defined, unable to get releases.</dark_gray>', 1, 3);
} else {
foreach ($hosts as $host) {
@ -35,14 +51,14 @@ class Mage_Command_BuiltIn_Releases
switch ($subcommand) {
case 'list':
$task = Mage_Task_Factory::get('releases/list', $this->getConfig());
$task = Factory::get('releases/list', $this->getConfig());
$task->init();
$result = $task->run();
break;
case 'rollback':
$releaseId = $this->getConfig()->getParameter('release', '');
$task = Mage_Task_Factory::get('releases/rollback', $this->getConfig());
$task = Factory::get('releases/rollback', $this->getConfig());
$task->init();
$task->setRelease($releaseId);
$result = $task->run();

View file

@ -1,25 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Unlock
extends Mage_Command_CommandAbstract
implements Mage_Command_RequiresEnvironment
{
public function run()
{
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
@unlink($lockFile);
}
Mage_Console::output('Unlocked deployment to <light_purple>' . $this->getConfig()->getEnvironment() . '</light_purple> environment', 1, 2);
}
}

View file

@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Command\RequiresEnvironment;
use Mage\Console;
use Exception;
/**
* Command for Unlocking an Environment
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class UnlockCommand
extends AbstractCommand implements RequiresEnvironment
{
/**
* Unlocks an Environment
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$lockFile = '.mage/' . $this->getConfig()->getEnvironment() . '.lock';
if (file_exists($lockFile)) {
@unlink($lockFile);
}
Console::output('Unlocked deployment to <light_purple>' . $this->getConfig()->getEnvironment() . '</light_purple> environment', 1, 2);
}
}

View file

@ -1,29 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Update
extends Mage_Command_CommandAbstract
{
public function run()
{
$task = Mage_Task_Factory::get('scm/update', $this->getConfig());
$task->init();
Mage_Console::output('Updating application via ' . $task->getName() . ' ... ', 1, 0);
$result = $task->run();
if ($result == true) {
Mage_Console::output('<green>OK</green>' . PHP_EOL, 0);
} else {
Mage_Console::output('<red>FAIL</red>' . PHP_EOL, 0);
}
}
}

View file

@ -0,0 +1,45 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Task\Factory;
use Mage\Console;
use Exception;
/**
* Updates the SCM Base Code
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class UpdateCommand extends AbstractCommand
{
/**
* Updates the SCM Base Code
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
$task = Factory::get('scm/update', $this->getConfig());
$task->init();
Console::output('Updating application via ' . $task->getName() . ' ... ', 1, 0);
$result = $task->run();
if ($result == true) {
Console::output('<green>OK</green>' . PHP_EOL, 0);
} else {
Console::output('<red>FAIL</red>' . PHP_EOL, 0);
}
}
}

View file

@ -1,124 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Upgrade
extends Mage_Command_CommandAbstract
{
const DOWNLOAD = 'https://github.com/andres-montanez/Magallanes/tarball/stable';
public function run ()
{
Mage_Console::output('Upgrading <dark_gray>Magallanes</dark_gray> ... ', 1, 0);
$user = '';
// Check if user is root
Mage_Console::executeCommand('whoami', $user);
if ($user != 'root') {
Mage_Console::output('<red>FAIL</red>', 0, 1);
Mage_Console::output('You need to be the <dark_gray>root</dark_gray> user to perform the upgrade.', 2);
} else {
// Download Package
$tarball = file_get_contents(self::DOWNLOAD);
$tarballFile = tempnam('/tmp', 'magallanes_download');
rename($tarballFile, $tarballFile . '.tar.gz');
$tarballFile .= '.tar.gz';
file_put_contents($tarballFile, $tarball);
// Unpackage
if (file_exists('/tmp/__magallanesDownload')) {
Mage_Console::executeCommand('rm -rf /tmp/__magallanesDownload');
}
Mage_Console::executeCommand('mkdir /tmp/__magallanesDownload');
Mage_Console::executeCommand('cd /tmp/__magallanesDownload && tar xfz ' . $tarballFile);
Mage_Console::executeCommand('rm -f ' . $tarballFile);
// Find Package
$tarballDir = opendir('/tmp/__magallanesDownload');
while (($file = readdir($tarballDir)) == true) {
if ($file == '.' || $file == '..') {
continue;
} else {
$packageDir = $file;
break;
}
}
// Get Version
$version = false;
if (file_exists('/tmp/__magallanesDownload/' . $packageDir . '/bin/mage')) {
list(, $version) = file('/tmp/__magallanesDownload/' . $packageDir . '/bin/mage');
$version = trim(str_replace('#VERSION:', '', $version));
}
if ($version != false) {
$versionCompare = version_compare(MAGALLANES_VERSION, $version);
if ($versionCompare == 0) {
Mage_Console::output('<yellow>SKIP</yellow>', 0, 1);
Mage_Console::output('Your current version is up to date.', 2);
} else if ($versionCompare > 0) {
Mage_Console::output('<yellow>SKIP</yellow>', 0, 1);
Mage_Console::output('Your current version is newer.', 2);
} else {
$this->_recursiveCopy('/tmp/__magallanesDownload/' . $packageDir, '/opt/magallanes-' . $version);
unlink('/opt/magallanes');
symlink('/opt/magallanes-' . $version, '/opt/magallanes');
chmod('/opt/magallanes/bin/mage', 0755);
Mage_Console::output('<green>OK</green>', 0, 1);
}
} else {
Mage_Console::output('<red>FAIL</red>', 0, 1);
Mage_Console::output('Corrupted download.', 2);
}
}
}
private function _recursiveCopy ($from, $to)
{
if (is_dir($from)) {
mkdir($to);
$files = scandir($from);
if (count($files) > 0) {
foreach ($files as $file) {
if (strpos($file, '.') === 0) {
continue;
}
if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
$this->_recursiveCopy(
$from . DIRECTORY_SEPARATOR . $file,
$to . DIRECTORY_SEPARATOR . $file
);
} else {
copy(
$from . DIRECTORY_SEPARATOR . $file,
$to . DIRECTORY_SEPARATOR . $file
);
}
}
}
return true;
} elseif (is_file($from)) {
return copy($from, $to);
} else {
return false;
}
}
}

View file

@ -0,0 +1,107 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Upgrades the Magallanes Version on the Local System
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class UpgradeCommand extends InstallCommand
{
/**
* GIT Source for downloading
* @var string
*/
const DOWNLOAD = 'https://github.com/andres-montanez/Magallanes/tarball/stable';
/**
* Command for Upgrading Magallanes
* @see \Mage\Command\BuiltIn\InstallCommand::run()
*/
public function run()
{
Console::output('Upgrading <dark_gray>Magallanes</dark_gray> ... ', 1, 0);
$user = '';
// Check if user is root
Console::executeCommand('whoami', $user);
if ($user != 'root') {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('You need to be the <dark_gray>root</dark_gray> user to perform the upgrade.', 2);
} else {
// Download Package
$tarball = file_get_contents(self::DOWNLOAD);
$tarballFile = tempnam('/tmp', 'magallanes_download');
rename($tarballFile, $tarballFile . '.tar.gz');
$tarballFile .= '.tar.gz';
file_put_contents($tarballFile, $tarball);
// Unpackage
if (file_exists('/tmp/__magallanesDownload')) {
Console::executeCommand('rm -rf /tmp/__magallanesDownload');
}
Console::executeCommand('mkdir /tmp/__magallanesDownload');
Console::executeCommand('cd /tmp/__magallanesDownload && tar xfz ' . $tarballFile);
Console::executeCommand('rm -f ' . $tarballFile);
// Find Package
$tarballDir = opendir('/tmp/__magallanesDownload');
while (($file = readdir($tarballDir)) == true) {
if ($file == '.' || $file == '..') {
continue;
} else {
$packageDir = $file;
break;
}
}
// Get Version
$version = false;
if (file_exists('/tmp/__magallanesDownload/' . $packageDir . '/bin/mage')) {
list(, $version) = file('/tmp/__magallanesDownload/' . $packageDir . '/bin/mage');
$version = trim(str_replace('#VERSION:', '', $version));
}
if ($version != false) {
$versionCompare = version_compare(MAGALLANES_VERSION, $version);
if ($versionCompare == 0) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is up to date.', 2);
} else if ($versionCompare > 0) {
Console::output('<yellow>SKIP</yellow>', 0, 1);
Console::output('Your current version is newer.', 2);
} else {
$this->recursiveCopy('/tmp/__magallanesDownload/' . $packageDir, '/opt/magallanes-' . $version);
unlink('/opt/magallanes');
symlink('/opt/magallanes-' . $version, '/opt/magallanes');
chmod('/opt/magallanes/bin/mage', 0755);
Console::output('<green>OK</green>', 0, 1);
}
} else {
Console::output('<red>FAIL</red>', 0, 1);
Console::output('Corrupted download.', 2);
}
}
}
}

View file

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Command_BuiltIn_Version
extends Mage_Command_CommandAbstract
{
public function run()
{
Mage_Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION .'</dark_gray>', 0, 2);
}
}

View file

@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Command\BuiltIn;
use Mage\Command\AbstractCommand;
use Mage\Console;
use Exception;
/**
* Command for displaying the Version of Magallanes
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class VersionCommand extends AbstractCommand
{
/**
* Display the Magallanes Version
* @see \Mage\Command\AbstractCommand::run()
*/
public function run()
{
Console::output('Running <blue>Magallanes</blue> version <dark_gray>' . MAGALLANES_VERSION .'</dark_gray>', 0, 2);
}
}

View file

@ -1,30 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
abstract class Mage_Command_CommandAbstract
{
protected $_config = null;
public abstract function run();
public function setConfig(Mage_Config $config)
{
$this->_config = $config;
}
/**
*
* @return Mage_Config
*/
public function getConfig()
{
return $this->_config;
}
}

View file

@ -8,39 +8,47 @@
* file that was distributed with this source code.
*/
class Mage_Command_Factory
namespace Mage\Command;
use Mage\Config;
use Mage\Autoload;
use Exception;
/**
* Loads a Magallanes Command.
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Factory
{
/**
*
* Gets an instance of a Command.
*
* @param string $commandName
* @param Mage_Config $config
* @return Mage_Command_CommandAbstract
* @param Config $config
* @return AbstractCommand
* @throws Exception
*/
public static function get($commandName, Mage_Config $config)
public static function get($commandName, Config $config)
{
$instance = null;
$commandName = ucwords(str_replace('-', ' ', $commandName));
$commandName = str_replace(' ', '', $commandName);
// if (strpos($commandName, '/') === false) {
// Mage_Autoload::loadUserTask($taskName);
// $className = 'Task_' . ucfirst($taskName);
// $instance = new $className($taskConfig, $inRollback, $stage);
$commandName = str_replace(' ', '_', ucwords(str_replace('/', ' ', $commandName)));
$className = 'Mage\\Command\\BuiltIn\\' . $commandName . 'Command';
if (Autoload::isLoadable($className)) {
$instance = new $className;
$instance->setConfig($config);
} else {
throw new Exception('Command not found.');
}
// } else {
$commandName = str_replace(' ', '_', ucwords(str_replace('/', ' ', $commandName)));
$className = 'Mage_Command_BuiltIn_' . $commandName;
if (Mage_Autoload::isLoadable($className)) {
$instance = new $className;
$instance->setConfig($config);
} else {
throw new Exception('Command not found.');
}
if(!($instance instanceOf AbstractCommand)) {
throw new Exception('The command ' . $commandName . ' must be an instance of Mage\Command\AbstractCommand.');
}
// }
assert($instance instanceOf Mage_Command_CommandAbstract);
return $instance;
}
}

View file

@ -8,6 +8,13 @@
* file that was distributed with this source code.
*/
interface Mage_Command_RequiresEnvironment
namespace Mage\Command;
/**
* Indicates that a Command depends of an Environment.
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
interface RequiresEnvironment
{
}

View file

@ -8,14 +8,18 @@
* file that was distributed with this source code.
*/
namespace Mage;
use Phar;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
/**
* Class Mage_Compiler
*
* Compiles the library into a .phar file
*
* @author Ismael Ambrosi<ismaambrosi@gmail.com>
*/
class Mage_Compiler
class Compiler
{
/**
@ -25,7 +29,6 @@ class Mage_Compiler
*/
public function compile($file = 'mage.phar')
{
if (file_exists($file)) {
unlink($file);
}

View file

@ -8,15 +8,58 @@
* file that was distributed with this source code.
*/
class Mage_Config
namespace Mage;
use Exception;
/**
* Magallanes Configuration
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Config
{
private $_arguments = array();
private $_parameters = array();
private $_environment = false;
private $_host = null;
private $_hostConfig = null;
private $_releaseId = null;
private $_config = array(
/**
* Arguments loaded
* @var array
*/
private $arguments = array();
/**
* Parameters loaded
* @var array
*/
private $parameters = array();
/**
* Environment
* @var string|boolean
*/
private $environment = false;
/**
* The current Host
* @var string
*/
private $host = null;
/**
* Custom Configuration for the current Host
* @var array
*/
private $hostConfig = array();
/**
* The Relase ID
* @var integer
*/
private $releaseId = null;
/**
* Magallanes Global and Environment configuration
* @var array
*/
private $config = array(
'general' => array(),
'environment' => array(),
);
@ -28,9 +71,9 @@ class Mage_Config
*/
public function load($arguments)
{
$this->_parse($arguments);
$this->_loadGeneral();
$this->_loadEnvironment();
$this->parse($arguments);
$this->loadGeneral();
$this->loadEnvironment();
}
/**
@ -42,8 +85,8 @@ class Mage_Config
*/
public function getArgument($position = 0)
{
if (isset($this->_arguments[$position])) {
return $this->_arguments[$position];
if (isset($this->arguments[$position])) {
return $this->arguments[$position];
} else {
return false;
}
@ -56,7 +99,7 @@ class Mage_Config
*/
public function getArguments()
{
return $this->_arguments;
return $this->arguments;
}
/**
@ -67,8 +110,8 @@ class Mage_Config
*/
public function getParameter($name, $default = null, $extraParameters = array())
{
if (isset($this->_parameters[$name])) {
return $this->_parameters[$name];
if (isset($this->parameters[$name])) {
return $this->parameters[$name];
} else if (isset($extraParameters[$name])) {
return $extraParameters[$name];
} else {
@ -83,7 +126,7 @@ class Mage_Config
*/
public function getParameters()
{
return $this->_parameters;
return $this->parameters;
}
/**
@ -93,7 +136,7 @@ class Mage_Config
*/
public function addParameter($name, $value = true)
{
$this->_parameters[$name] = $value;
$this->parameters[$name] = $value;
}
/**
@ -103,7 +146,7 @@ class Mage_Config
*/
public function getEnvironment()
{
return $this->_environment;
return $this->environment;
}
/**
@ -111,8 +154,8 @@ class Mage_Config
*/
public function reload()
{
$this->_loadGeneral();
$this->_loadEnvironment();
$this->loadGeneral();
$this->loadEnvironment();
}
/**
@ -124,12 +167,12 @@ class Mage_Config
public function getTasks($stage = 'on-deploy')
{
$tasks = array();
$config = $this->_getEnvironmentOption('tasks', array());
$config = $this->getEnvironmentOption('tasks', array());
// Host Config
if (is_array($this->_hostConfig) && isset($this->_hostConfig['tasks'])) {
if (isset($this->_hostConfig['tasks'][$stage])) {
$config[$stage] = $this->_hostConfig['tasks'][$stage];
if (is_array($this->hostConfig) && isset($this->hostConfig['tasks'])) {
if (isset($this->hostConfig['tasks'][$stage])) {
$config[$stage] = $this->hostConfig['tasks'][$stage];
}
}
@ -160,11 +203,11 @@ class Mage_Config
{
$hosts = array();
if (isset($this->_config['environment']['hosts'])) {
if (is_array($this->_config['environment']['hosts'])) {
$hosts = (array) $this->_config['environment']['hosts'];
} else if (is_string($this->_config['environment']['hosts']) && file_exists($this->_config['environment']['hosts']) && is_readable($this->_config['environment']['hosts'])) {
$fileContent = fopen($this->_config['environment']['hosts'], 'r');
if (isset($this->config['environment']['hosts'])) {
if (is_array($this->config['environment']['hosts'])) {
$hosts = (array) $this->config['environment']['hosts'];
} else if (is_string($this->config['environment']['hosts']) && file_exists($this->config['environment']['hosts']) && is_readable($this->config['environment']['hosts'])) {
$fileContent = fopen($this->config['environment']['hosts'], 'r');
while (($host = fgets($fileContent)) == true) {
$host = trim($host);
if ($host != '') {
@ -181,11 +224,11 @@ class Mage_Config
* Set the current host
*
* @param string $host
* @return Mage_Config
* @return \Mage\Config
*/
public function setHost($host)
{
$this->_host = $host;
$this->host = $host;
return $this;
}
@ -193,11 +236,11 @@ class Mage_Config
* Set the host specific configuration
*
* @param array $hostConfig
* @return Mage_Config
* @return \Mage\Config
*/
public function setHostConfig($hostConfig = null)
{
$this->_hostConfig = $hostConfig;
$this->hostConfig = $hostConfig;
return $this;
}
@ -208,18 +251,18 @@ class Mage_Config
*/
public function getHostName()
{
$info = explode(':', $this->_host);
$info = explode(':', $this->host);
return $info[0];
}
/**
* Get the current Host Port
*
* @return unknown
* @return integer
*/
public function getHostPort()
{
$info = explode(':', $this->_host);
$info = explode(':', $this->host);
$info[] = $this->deployment('port', '22');
return $info[1];
}
@ -231,7 +274,7 @@ class Mage_Config
*/
public function getHost()
{
return $this->_host;
return $this->host;
}
/**
@ -243,7 +286,7 @@ class Mage_Config
*/
public function general($option, $default = false)
{
$config = $this->_config['general'];
$config = $this->config['general'];
if (isset($config[$option])) {
if (is_array($default) && ($config[$option] == '')) {
return $default;
@ -265,14 +308,14 @@ class Mage_Config
public function deployment($option, $default = false)
{
// Host Config
if (is_array($this->_hostConfig) && isset($this->_hostConfig['deployment'])) {
if (isset($this->_hostConfig['deployment'][$option])) {
return $this->_hostConfig['deployment'][$option];
if (is_array($this->hostConfig) && isset($this->hostConfig['deployment'])) {
if (isset($this->hostConfig['deployment'][$option])) {
return $this->hostConfig['deployment'][$option];
}
}
// Global Config
$config = $this->_getEnvironmentOption('deployment', array());
$config = $this->getEnvironmentOption('deployment', array());
if (isset($config[$option])) {
if (is_array($default) && ($config[$option] == '')) {
return $default;
@ -294,13 +337,13 @@ class Mage_Config
public function release($option, $default = false)
{
// Host Config
if (is_array($this->_hostConfig) && isset($this->_hostConfig['releases'])) {
if (isset($this->_hostConfig['releases'][$option])) {
return $this->_hostConfig['releases'][$option];
if (is_array($this->hostConfig) && isset($this->hostConfig['releases'])) {
if (isset($this->hostConfig['releases'][$option])) {
return $this->hostConfig['releases'][$option];
}
}
$config = $this->_getEnvironmentOption('releases', array());
$config = $this->getEnvironmentOption('releases', array());
if (isset($config[$option])) {
if (is_array($default) && ($config[$option] == '')) {
return $default;
@ -316,11 +359,11 @@ class Mage_Config
* Set From Deployment Path
*
* @param string $from
* @return Mage_Config
* @return \Mage\Config
*/
public function setFrom($from)
{
$this->_config['environment']['deployment']['from'] = $from;
$this->config['environment']['deployment']['from'] = $from;
return $this;
}
@ -328,11 +371,11 @@ class Mage_Config
* Sets the Current Release ID
*
* @param integer $id
* @return Mage_Config
* @return \Mage\Config
*/
public function setReleaseId($id)
{
$this->_releaseId = $id;
$this->releaseId = $id;
return $this;
}
@ -343,34 +386,34 @@ class Mage_Config
*/
public function getReleaseId()
{
return $this->_releaseId;
return $this->releaseId;
}
/**
* Parse the Command Line options
* @return boolean
*/
private function _parse($arguments)
protected function parse($arguments)
{
foreach ($arguments as $argument) {
if (preg_match('/to:[\w]+/i', $argument)) {
$this->_environment = str_replace('to:', '', $argument);
$this->environment = str_replace('to:', '', $argument);
} else if (preg_match('/--[\w]+/i', $argument)) {
$optionValue = explode('=', substr($argument, 2));
if (count($optionValue) == 1) {
$this->_parameters[$optionValue[0]] = true;
$this->parameters[$optionValue[0]] = true;
} else if (count($optionValue) == 2) {
if (strtolower($optionValue[1]) == 'true') {
$this->_parameters[$optionValue[0]] = true;
$this->parameters[$optionValue[0]] = true;
} else if (strtolower($optionValue[1]) == 'false') {
$this->_parameters[$optionValue[0]] = false;
$this->parameters[$optionValue[0]] = false;
} else {
$this->_parameters[$optionValue[0]] = $optionValue[1];
$this->parameters[$optionValue[0]] = $optionValue[1];
}
}
} else {
$this->_arguments[] = $argument;
$this->arguments[] = $argument;
}
}
}
@ -378,10 +421,10 @@ class Mage_Config
/**
* Loads the General Configuration
*/
private function _loadGeneral()
protected function loadGeneral()
{
if (file_exists('.mage/config/general.yml')) {
$this->_config['general'] = spyc_load_file('.mage/config/general.yml');
$this->config['general'] = spyc_load_file('.mage/config/general.yml');
}
}
@ -391,20 +434,20 @@ class Mage_Config
* @throws Exception
* @return boolean
*/
private function _loadEnvironment()
protected function loadEnvironment()
{
$environment = $this->getEnvironment();
if (($environment != false) && file_exists('.mage/config/environment/' . $environment . '.yml')) {
$this->_config['environment'] = spyc_load_file('.mage/config/environment/' . $environment . '.yml');
$this->config['environment'] = spyc_load_file('.mage/config/environment/' . $environment . '.yml');
// Create temporal directory for clone
if (isset($this->_config['environment']['deployment']['source']) && is_array($this->_config['environment']['deployment']['source'])) {
if (trim($this->_config['environment']['deployment']['source']['temporal']) == '') {
$this->_config['environment']['deployment']['source']['temporal'] = '/tmp';
if (isset($this->config['environment']['deployment']['source']) && is_array($this->config['environment']['deployment']['source'])) {
if (trim($this->config['environment']['deployment']['source']['temporal']) == '') {
$this->config['environment']['deployment']['source']['temporal'] = '/tmp';
}
$newTemporal = rtrim($this->_config['environment']['deployment']['source']['temporal'], '/')
$newTemporal = rtrim($this->config['environment']['deployment']['source']['temporal'], '/')
. '/' . md5(microtime()) . '/';
$this->_config['environment']['deployment']['source']['temporal'] = $newTemporal;
$this->config['environment']['deployment']['source']['temporal'] = $newTemporal;
}
return true;
@ -422,9 +465,9 @@ class Mage_Config
* @param mixed $default
* @return mixed
*/
private function _getEnvironmentOption($option, $default = array())
protected function getEnvironmentOption($option, $default = array())
{
$config = $this->_config['environment'];
$config = $this->config['environment'];
if (isset($config[$option])) {
return $config[$option];
} else {

View file

@ -8,12 +8,41 @@
* file that was distributed with this source code.
*/
class Mage_Console
namespace Mage;
use Exception;
use RecursiveDirectoryIterator;
/**
* Magallanes interface between the Tasks and Commands and the User's Console.
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Console
{
private static $_log = null;
private static $_logEnabled = true;
private static $_screenBuffer = '';
private static $_commandsOutput = '';
/**
* Handler to the current Log File.
* @var handler
*/
private static $log = null;
/**
* Enables or Disables Logging
* @var boolean
*/
private static $logEnabled = true;
/**
* String Buffer for the screen output
* @var string
*/
private static $screenBuffer = '';
/**
* Output of executed commands
* @var string
*/
private static $commandsOutput = '';
/**
* Runns a Magallanes Command
@ -21,6 +50,7 @@ class Mage_Console
*/
public function run($arguments)
{
// Declare a Shutdown Closure
register_shutdown_function(function() {
// Only Unlock if there was an error
if (error_get_last() !== null) {
@ -30,15 +60,16 @@ class Mage_Console
}
});
// Load configuration
$configError = false;
try {
// Load Config
$config = new Mage_Config;
$config = new Config;
$config->load($arguments);
$configLoadedOk = true;
} catch (Exception $e) {
$configError = $e->getMessage();
} catch (Exception $exception) {
$configError = $exception->getMessage();
}
// Command Option
@ -47,46 +78,51 @@ class Mage_Console
// Logging
$showGrettings = true;
if (in_array($commandName, array('install', 'upgrade', 'version'))) {
self::$_logEnabled = false;
self::$logEnabled = false;
$showGrettings = false;
} else {
self::$_logEnabled = $config->general('logging', false);
self::$logEnabled = $config->general('logging', false);
}
// Grettings
if ($showGrettings) {
Mage_Console::output('Starting <blue>Magallanes</blue>', 0, 2);
self::output('Starting <blue>Magallanes</blue>', 0, 2);
}
// Run Command
// Run Command - Check if there is a Configuration Error
if ($configError !== false) {
Mage_Console::output('<red>' . $configError . '</red>', 1, 2);
self::output('<red>' . $configError . '</red>', 1, 2);
} else {
// Run Command and check for Command Requirements
try {
$command = Mage_Command_Factory::get($commandName, $config);
$command = Command\Factory::get($commandName, $config);
if ($command instanceOf Mage_Command_RequiresEnvironment) {
if ($command instanceOf Command\RequiresEnvironment) {
if ($config->getEnvironment() == false) {
throw new Exception('You must specify an environment for this command.');
}
}
$command->run();
} catch (Exception $e) {
Mage_Console::output('<red>' . $e->getMessage() . '</red>', 1, 2);
} catch (Exception $exception) {
self::output('<red>' . $exception->getMessage() . '</red>', 1, 2);
}
}
if ($showGrettings) {
Mage_Console::output('Finished <blue>Magallanes</blue>', 0, 2);
self::output('Finished <blue>Magallanes</blue>', 0, 2);
if (file_exists('.mage/~working.lock')) {
unlink('.mage/~working.lock');
}
}
self::_checkLogs($config);
// Check if logs need to be deleted
self::checkLogs($config);
}
/**
* Outputs a message to the user screen
* Outputs a message to the user's screen.
*
* @param string $message
* @param integer $tabs
@ -96,12 +132,12 @@ class Mage_Console
{
self::log(strip_tags($message));
self::$_screenBuffer .= str_repeat("\t", $tabs)
self::$screenBuffer .= str_repeat("\t", $tabs)
. strip_tags($message)
. str_repeat(PHP_EOL, $newLine);
$output = str_repeat("\t", $tabs)
. Mage_Console_Colors::color($message)
. Console\Colors::color($message)
. str_repeat(PHP_EOL, $newLine);
echo $output;
@ -127,7 +163,7 @@ class Mage_Console
if (!$return) {
$output = trim($log);
}
self::$_commandsOutput .= PHP_EOL . trim($log) . PHP_EOL;
self::$commandsOutput .= PHP_EOL . trim($log) . PHP_EOL;
self::log($log);
self::log('---------------------------------');
@ -143,23 +179,23 @@ class Mage_Console
*/
public static function log($message, $continuation = false)
{
if (self::$_logEnabled) {
if (self::$_log == null) {
self::$_log = fopen('.mage/logs/log-' . date('Ymd-His') . '.log', 'w');
if (self::$logEnabled) {
if (self::$log == null) {
self::$log = fopen('.mage/logs/log-' . date('Ymd-His') . '.log', 'w');
}
$message = date('Y-m-d H:i:s -- ') . $message;
fwrite(self::$_log, $message . PHP_EOL);
fwrite(self::$log, $message . PHP_EOL);
}
}
/**
* Check Logs
* @param Mage_Config $config
* @param \Mage\Config $config
*/
private static function _checkLogs(Mage_Config $config)
private static function checkLogs(Config $config)
{
if (self::$_logEnabled) {
if (self::$logEnabled) {
$maxLogs = $config->general('maxlogs', 30);
$logs = array();

View file

@ -8,36 +8,53 @@
* file that was distributed with this source code.
*/
class Mage_Console_Colors
namespace Mage\Console;
/**
* Parses the different colors available for the Terminal or Console.
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Colors
{
private static $foreground_colors = array(
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
/**
* List of Colors and they Terminal/Console representation.
* @var array
*/
private static $foregroundColors = array(
'black' => '0;30',
'dark_gray' => '1;30',
'blue' => '0;34',
'light_blue' => '1;34',
'green' => '0;32',
'light_green' => '1;32',
'cyan' => '0;36',
'light_cyan' => '1;36',
'red' => '0;31',
'light_red' => '1;31',
'purple' => '0;35',
'light_purple' => '1;35',
'brown' => '0;33',
'yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37'
'brown' => '0;33',
'yellow' => '1;33',
'light_gray' => '0;37',
'white' => '1;37'
);
// Returns colored string
/**
* Parses a Text to represent Colors in the Terminal/Console.
*
* @param string $string
* @return string
*/
public static function color($string)
{
foreach (self::$foreground_colors as $key => $code) {
foreach (self::$foregroundColors as $key => $code) {
$replaceFrom = array(
'<' . $key . '>',
'</' . $key . '>'
);
$replaceTo = array(
"\033[" . $code . 'm',
"\033[0m"

175
Mage/Task/AbstractTask.php Normal file
View file

@ -0,0 +1,175 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Task;
use Mage\Console;
use Mage\Config;
use Mage\Task\ErrorWithMessageException;
use Mage\Task\SkipException;
use Mage\Task\Releases\IsReleaseAware;
use Exception;
/**
* Abstract Class for a Magallanes Task
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
abstract class AbstractTask
{
/**
* Configuration
* @var Config;
*/
protected $config = null;
/**
* Indicates if the Task is running in a Rollback
* @var boolean
*/
protected $inRollback = false;
/**
* Indicates the Stage the Task is running ing
* @var string
*/
protected $stage = null;
/**
* Extra parameters
* @var array
*/
protected $parameters = array();
/**
* Returns the Title of the Task
* @return string
*/
public abstract function getName();
/**
* Runs the task
*
* @return boolean
* @throws Exception
* @throws ErrorWithMessageException
* @throws SkipException
*/
public abstract function run();
/**
* Task Constructor
*
* @param Config $config
* @param boolean $inRollback
* @param string $stage
* @param array $parameters
*/
public final function __construct(Config $config, $inRollback = false, $stage = null, $parameters = array())
{
$this->config = $config;
$this->inRollback = $inRollback;
$this->stage = $stage;
$this->parameters = $parameters;
}
/**
* Indicates if the Task is running in a Rollback operation
* @return boolean
*/
public function inRollback()
{
return $this->inRollback;
}
/**
* Gets the Stage of the Deployment:
* - pre-deploy
* - deploy
* - post-deploy
* - post-release
* @return string
*/
public function getStage()
{
return $this->stage;
}
/**
* Gets the Configuration
* @return Config;
*/
public function getConfig()
{
return $this->config;
}
/**
* Initializes the Task, optional to implement
*/
public function init()
{
}
/**
* Returns a Parameter, or a default if not found
*
* @param string $name
* @return mixed
*/
public function getParameter($name, $default = null)
{
return $this->getConfig()->getParameter($name, $default, $this->parameters);
}
/**
* Runs a Shell Command Locally
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommandLocal($command, &$output = null)
{
return Console::executeCommand($command, $output);
}
/**
* Runs a Shell Command on the Remote Host
* @param string $command
* @param string $output
* @return boolean
*/
protected final function runCommandRemote($command, &$output = null)
{
if ($this->getConfig()->release('enabled', false) == true) {
if ($this instanceOf IsReleaseAware) {
$releasesDirectory = '';
} else {
$releasesDirectory = '/'
. $this->getConfig()->release('directory', 'releases')
. '/'
. $this->getConfig()->getReleaseId();
}
} else {
$releasesDirectory = '';
}
$localCommand = 'ssh -p ' . $this->getConfig()->getHostPort() . ' '
. '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ' '
. '"cd ' . rtrim($this->getConfig()->deployment('to'), '/') . $releasesDirectory . ' && '
. str_replace('"', '\"', $command) . '"';
return $this->runCommandLocal($localCommand, $output);
}
}

View file

@ -8,15 +8,34 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Deployment_Release
extends Mage_Task_TaskAbstract
implements Mage_Task_Releases_BuiltIn, Mage_Task_Releases_SkipOnOverride
namespace Mage\Task\BuiltIn\Deployment;
use Mage\Task\AbstractTask;
use Mage\Task\Releases\IsReleaseAware;
use Mage\Task\Releases\SkipOnOverride;
use Exception;
/**
* Task for Releasing a Deploy
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ReleaseTask extends AbstractTask implements IsReleaseAware, SkipOnOverride
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Releasing [built-in]';
}
/**
* Releases a Deployment: points the current symbolic link to the release directory
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
@ -29,9 +48,9 @@ class Mage_Task_BuiltIn_Deployment_Release
$currentCopy = $releasesDirectory . '/' . $this->getConfig()->getReleaseId();
// Fetch the user and group from base directory
// Fetch the user and group from base directory; defaults usergroup to 33:33
$userGroup = '33:33';
$resultFetch = $this->_runRemoteCommand('ls -ld . | awk \'{print \$3":"\$4}\'', $userGroup);
$resultFetch = $this->runCommandRemote('ls -ld . | awk \'{print \$3":"\$4}\'', $userGroup);
// Remove symlink if exists; create new symlink and change owners
$command = 'rm -f ' . $symlink
@ -41,7 +60,10 @@ class Mage_Task_BuiltIn_Deployment_Release
. 'chown -h ' . $userGroup . ' ' . $symlink
. ' && '
. 'chown -R ' . $userGroup . ' ' . $currentCopy;
$result = $this->_runRemoteCommand($command);
$result = $this->runCommandRemote($command);
// Set Directory Releases to same owner
$result = $this->runCommandRemote('chown ' . $userGroup . ' ' . $releasesDirectory);
return $result;

View file

@ -8,10 +8,24 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Deployment_Rsync
extends Mage_Task_TaskAbstract
implements Mage_Task_Releases_BuiltIn
namespace Mage\Task\BuiltIn\Deployment;
use Mage\Task\AbstractTask;
use Mage\Task\Releases\IsReleaseAware;
use Exception;
/**
* Task for Sync the Local Code to the Remote Hosts via RSYNC
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class RsyncTask extends AbstractTask implements IsReleaseAware
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
if ($this->getConfig()->release('enabled', false) == true) {
@ -25,13 +39,17 @@ class Mage_Task_BuiltIn_Deployment_Rsync
}
}
/**
* Syncs the Local Code to the Remote Host
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
$overrideRelease = $this->getParameter('overrideRelease', false);
if ($overrideRelease == true) {
$releaseToOverride = false;
$resultFetch = $this->_runRemoteCommand('ls -ld current | cut -d"/" -f2', $releaseToOverride);
$resultFetch = $this->runCommandRemote('ls -ld current | cut -d"/" -f2', $releaseToOverride);
if (is_numeric($releaseToOverride)) {
$this->getConfig()->setReleaseId($releaseToOverride);
}
@ -41,7 +59,9 @@ class Mage_Task_BuiltIn_Deployment_Rsync
'.git',
'.svn',
'.mage',
'.gitignore'
'.gitignore',
'.gitkeep',
'nohup.out'
);
// Look for User Excludes
@ -55,16 +75,16 @@ class Mage_Task_BuiltIn_Deployment_Rsync
$deployToDirectory = rtrim($this->getConfig()->deployment('to'), '/')
. '/' . $releasesDirectory
. '/' . $this->getConfig()->getReleaseId();
$this->_runRemoteCommand('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
$this->runCommandRemote('mkdir -p ' . $releasesDirectory . '/' . $this->getConfig()->getReleaseId());
}
$command = 'rsync -avz '
. '--rsh="ssh -p' . $this->getConfig()->getHostPort() . '" '
. $this->_excludes(array_merge($excludes, $userExcludes)) . ' '
. $this->excludes(array_merge($excludes, $userExcludes)) . ' '
. $this->getConfig()->deployment('from') . ' '
. $this->getConfig()->deployment('user') . '@' . $this->getConfig()->getHostName() . ':' . $deployToDirectory;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
// Count Releases
if ($this->getConfig()->release('enabled', false) == true) {
@ -78,7 +98,7 @@ class Mage_Task_BuiltIn_Deployment_Rsync
$maxReleases = $this->getConfig()->release('max', false);
if (($maxReleases !== false) && ($maxReleases > 0)) {
$releasesList = '';
$countReleasesFetch = $this->_runRemoteCommand('ls -1 ' . $releasesDirectory, $releasesList);
$countReleasesFetch = $this->runCommandRemote('ls -1 ' . $releasesDirectory, $releasesList);
$releasesList = trim($releasesList);
if ($releasesList != '') {
@ -93,7 +113,7 @@ class Mage_Task_BuiltIn_Deployment_Rsync
$directoryToDelete = $releasesDirectory . '/' . $releaseIdToDelete;
if ($directoryToDelete != '/') {
$command = 'rm -rf ' . $directoryToDelete;
$result = $result && $this->_runRemoteCommand($command);
$result = $result && $this->runCommandRemote($command);
}
}
}
@ -104,7 +124,12 @@ class Mage_Task_BuiltIn_Deployment_Rsync
return $result;
}
private function _excludes(Array $excludes)
/**
* Generates the Excludes for rsync
* @param array $excludes
* @return string
*/
protected function excludes(Array $excludes)
{
$excludesRsync = '';
foreach ($excludes as $exclude) {

View file

@ -8,35 +8,52 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Releases_List
extends Mage_Task_TaskAbstract
implements Mage_Task_Releases_BuiltIn
namespace Mage\Task\BuiltIn\Releases;
use Mage\Console;
use Mage\Task\AbstractTask;
use Mage\Task\Releases\IsReleaseAware;
use DateTime;
use Exception;
/**
* Task for Listing Available Releases on an Environment
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ListTask extends AbstractTask implements IsReleaseAware
{
public function getName()
{
return 'Listing releases [built-in]';
}
/**
* List the Available Releases on an Environment
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
$releasesDirectory = $this->getConfig()->release('directory', 'releases');
$symlink = $this->getConfig()->release('symlink', 'current');
Mage_Console::output('Releases available on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
Console::output('Releases available on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
// Get Releases
$output = '';
$result = $this->_runRemoteCommand('ls -1 ' . $releasesDirectory, $output);
$result = $this->runCommandRemote('ls -1 ' . $releasesDirectory, $output);
$releases = ($output == '') ? array() : explode(PHP_EOL, $output);
// Get Current
$result = $this->_runRemoteCommand('ls -l ' . $symlink, $output);
$result = $this->runCommandRemote('ls -l ' . $symlink, $output);
$currentRelease = explode('/', $output);
$currentRelease = trim(array_pop($currentRelease));
if (count($releases) == 0) {
Mage_Console::output('<dark_gray>No releases available</dark_gray> ... ', 2);
Console::output('<dark_gray>No releases available</dark_gray> ... ', 2);
} else {
rsort($releases);
$releases = array_slice($releases, 0, 10);
@ -61,25 +78,30 @@ class Mage_Task_BuiltIn_Releases_List
$isCurrent = ' <- current';
}
$dateDiff = $this->_dateDiff($releaseDate);
$dateDiff = $this->dateDiff($releaseDate);
Mage_Console::output(
Console::output(
'Release: <purple>' . $release . '</purple> '
. '- Date: <dark_gray>' . $releaseDate . '</dark_gray> '
. '- Index: <dark_gray>' . $releaseIndex . '</dark_gray>' . $dateDiff . $isCurrent, 2);
}
}
Mage_Console::output('');
Console::output('');
return $result;
} else {
Mage_Console::output('');
Console::output('');
return false;
}
}
private function _dateDiff($releaseDate)
/**
* Calculates a Human Readable Time Difference
* @param string $releaseDate
* @return string
*/
protected function dateDiff($releaseDate)
{
$textDiff = '';
$releaseDate = new DateTime($releaseDate);

View file

@ -8,28 +8,62 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Releases_Rollback
extends Mage_Task_TaskAbstract
implements Mage_Task_Releases_BuiltIn
{
private $_release = null;
namespace Mage\Task\BuiltIn\Releases;
use Mage\Console;
use Mage\Task\Factory;
use Mage\Task\AbstractTask;
use Mage\Task\Releases\BuiltIn as ReleaseTask;
use Mage\Task\Releases\RollbackAware;
use Exception;
/**
* Task for Performing a Rollback Operation
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class RollbackTask extends AbstractTask implements ReleaseTask
{
/**
* The Relase ID to Rollback To
* @var integer
*/
protected $release = null;
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Rollback release [built-in]';
}
/**
* Sets the Release ID to Rollback To
* @param integer $releaseId
* @return \Mage\Task\BuiltIn\Releases\RollbackTask
*/
public function setRelease($releaseId)
{
$this->_release = $releaseId;
$this->release = $releaseId;
return $this;
}
/**
* Gets the Release ID to Rollback To
* @return integer
*/
public function getRelease()
{
return $this->_release;
return $this->release;
}
/**
* Performs a Rollback Operation
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
if ($this->getConfig()->release('enabled', false) == true) {
@ -37,11 +71,11 @@ class Mage_Task_BuiltIn_Releases_Rollback
$symlink = $this->getConfig()->release('symlink', 'current');
$output = '';
$result = $this->_runRemoteCommand('ls -1 ' . $releasesDirectory, $output);
$result = $this->runCommandRemote('ls -1 ' . $releasesDirectory, $output);
$releases = ($output == '') ? array() : explode(PHP_EOL, $output);
if (count($releases) == 0) {
Mage_Console::output('Release are not available for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
Console::output('Release are not available for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
} else {
rsort($releases);
@ -65,10 +99,10 @@ class Mage_Task_BuiltIn_Releases_Rollback
}
if (!$releaseIsAvailable) {
Mage_Console::output('Release <dark_gray>' . $this->getRelease() . '</dark_gray> is invalid or unavailable for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
Console::output('Release <dark_gray>' . $this->getRelease() . '</dark_gray> is invalid or unavailable for <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> ... <red>FAIL</red>');
} else {
Mage_Console::output('Rollback release on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
Console::output('Rollback release on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray>');
$rollbackTo = $releasesDirectory . '/' . $releaseId;
// Tasks
@ -78,48 +112,48 @@ class Mage_Task_BuiltIn_Releases_Rollback
$this->getConfig()->setReleaseId($releaseId);
if (count($tasksToRun) == 0) {
Mage_Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Mage_Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> skipped!', 1, 3);
Console::output('<light_purple>Warning!</light_purple> <dark_gray>No </dark_gray><light_cyan>Deployment</light_cyan> <dark_gray>tasks defined.</dark_gray>', 2);
Console::output('Deployment to <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> skipped!', 1, 3);
} else {
foreach ($tasksToRun as $taskData) {
$task = Mage_Task_Factory::get($taskData, $this->getConfig(), true, 'deploy');
$task = Factory::get($taskData, $this->getConfig(), true, 'deploy');
$task->init();
Mage_Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
Console::output('Running <purple>' . $task->getName() . '</purple> ... ', 2, false);
if ($task instanceOf Mage_Task_Releases_RollbackAware) {
if ($task instanceOf RollbackAware) {
$tasks++;
$result = $task->run();
if ($result == true) {
Mage_Console::output('<green>OK</green>', 0);
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Mage_Console::output('<red>FAIL</red>', 0);
Console::output('<red>FAIL</red>', 0);
}
} else {
Mage_Console::output('<yellow>SKIPPED</yellow>', 0);
Console::output('<yellow>SKIPPED</yellow>', 0);
}
}
}
// Changing Release
Mage_Console::output('Running <purple>Rollback Release [id=' . $releaseId . ']</purple> ... ', 2, false);
Console::output('Running <purple>Rollback Release [id=' . $releaseId . ']</purple> ... ', 2, false);
$userGroup = '';
$resultFetch = $this->_runRemoteCommand('ls -ld ' . $rollbackTo . ' | awk \'{print \$3":"\$4}\'', $userGroup);
$resultFetch = $this->runCommandRemote('ls -ld ' . $rollbackTo . ' | awk \'{print \$3":"\$4}\'', $userGroup);
$command = 'rm -f ' . $symlink
. ' && '
. 'ln -sf ' . $rollbackTo . ' ' . $symlink
. ' && '
. 'chown -h ' . $userGroup . ' ' . $symlink;
$result = $this->_runRemoteCommand($command);
$result = $this->runCommandRemote($command);
if ($result) {
Mage_Console::output('<green>OK</green>', 0);
Console::output('<green>OK</green>', 0);
$completedTasks++;
} else {
Mage_Console::output('<red>FAIL</red>', 0);
Console::output('<red>FAIL</red>', 0);
}
if ($completedTasks == $tasks) {
@ -128,11 +162,12 @@ class Mage_Task_BuiltIn_Releases_Rollback
$tasksColor = 'red';
}
Mage_Console::output('Release rollback on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
Console::output('Release rollback on <dark_gray>' . $this->getConfig()->getHost() . '</dark_gray> compted: <' . $tasksColor . '>' . $completedTasks . '/' . $tasks . '</' . $tasksColor . '> tasks done.', 1, 3);
}
}
return $result;
} else {
return false;
}

View file

@ -8,30 +8,61 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Scm_ChangeBranch
extends Mage_Task_TaskAbstract
{
protected static $startingBranch = 'master';
private $_name = 'SCM Changing branch [built-in]';
namespace Mage\Task\BuiltIn\Scm;
use Mage\Task\AbstractTask;
use Mage\Task\SkipException;
use Mage\Task\ErrorWithMessageException;
use Exception;
/**
* Task for Changing the Branch of the SCM
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ChangeBranchTask extends AbstractTask
{
/**
* Branch the executiong began with
* @var string
*/
protected static $startingBranch = 'master';
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Changing branch [built-in]';
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return $this->_name;
return $this->name;
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::init()
*/
public function init()
{
switch ($this->getConfig()->general('scm')) {
case 'git':
$this->_name = 'SCM Changing branch (GIT) [built-in]';
break;
$scmType = $this->getConfig()->general('scm');
case 'svn':
$this->_name = 'SCM Changing branch (Subversion) [built-in]';
switch ($scmType) {
case 'git':
$this->name = 'SCM Changing branch (GIT) [built-in]';
break;
}
}
/**
* Changes the Branch of the SCM
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
$scmConfig = $this->getConfig()->general('scm', array());
@ -39,41 +70,40 @@ class Mage_Task_BuiltIn_Scm_ChangeBranch
case 'git':
if ($this->getParameter('_changeBranchRevert', false)) {
$command = 'git checkout ' . self::$startingBranch;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
} else {
$command = 'git branch | grep \'*\' | cut -d\' \' -f 2';
$currentBranch = 'master';
$result = $this->_runLocalCommand($command, $currentBranch);
$result = $this->runCommandLocal($command, $currentBranch);
$scmData = $this->getConfig()->deployment('scm', false);
if ($result && is_array($scmData) && isset($scmData['branch']) && $scmData['branch'] != $currentBranch) {
$command = 'git branch | grep \'' . $scmData['branch'] . '\' | tr -s \' \' | sed \'s/^[ ]//g\'';
$isBranchTracked = '';
$result = $this->_runLocalCommand($command, $isBranchTracked);
$result = $this->runCommandLocal($command, $isBranchTracked);
if ($isBranchTracked == '') {
throw new Mage_Task_ErrorWithMessageException('The branch <purple>' . $scmData['branch'] . '</purple> must be tracked.');
throw new ErrorWithMessageException('The branch <purple>' . $scmData['branch'] . '</purple> must be tracked.');
}
$branch = $this->getParameter('branch', $scmData['branch']);
$command = 'git checkout ' . $branch;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
self::$startingBranch = $currentBranch;
} else {
throw new Mage_Task_SkipException;
throw new SkipException;
}
}
break;
default:
throw new Mage_Task_SkipException;
throw new SkipException;
break;
}
$this->getConfig()->reload();
return $result;

View file

@ -1,61 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Scm_Clone
extends Mage_Task_TaskAbstract
{
private $_name = 'SCM Clone [built-in]';
private $_source = null;
public function getName()
{
return $this->_name;
}
public function init()
{
$this->_source = $this->getConfig()->deployment('source');
switch ($this->_source['type']) {
case 'git':
$this->_name = 'SCM Clone (GIT) [built-in]';
break;
case 'svn':
$this->_name = 'SCM Clone (Subversion) [built-in]';
break;
}
}
public function run()
{
$this->_runLocalCommand('mkdir -p ' . $this->_source['temporal']);
switch ($this->_source['type']) {
case 'git':
// Clone Repo
$command = 'cd ' . $this->_source['temporal'] . ' ; '
. 'git clone ' . $this->_source['repository'] . ' . ';
$result = $this->_runLocalCommand($command);
// Checkout Branch
$command = 'cd ' . $this->_source['temporal'] . ' ; '
. 'git checkout ' . $this->_source['from'];
$result = $result && $this->_runLocalCommand($command);
$this->getConfig()->setFrom($this->_source['temporal']);
break;
case 'svn':
throw new Mage_Task_SkipException;
break;
}
return $result;
}
}

View file

@ -0,0 +1,89 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Task\BuiltIn\Scm;
use Mage\Task\AbstractTask;
use Mage\Task\SkipException;
use Exception;
/**
* Task for Clonning a Repository
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class CloneTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Clone [built-in]';
/**
* Source of the Repo
* @var string
*/
private $source = null;
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return $this->name;
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::init()
*/
public function init()
{
$this->source = $this->getConfig()->deployment('source');
switch ($this->source['type']) {
case 'git':
$this->name = 'SCM Clone (GIT) [built-in]';
break;
}
}
/**
* Clones a Repository
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
$this->runCommandLocal('mkdir -p ' . $this->source['temporal']);
switch ($this->source['type']) {
case 'git':
// Clone Repo
$command = 'cd ' . $this->source['temporal'] . ' ; '
. 'git clone ' . $this->source['repository'] . ' . ';
$result = $this->runCommandLocal($command);
// Checkout Branch
$command = 'cd ' . $this->source['temporal'] . ' ; '
. 'git checkout ' . $this->source['from'];
$result = $result && $this->runCommandLocal($command);
$this->getConfig()->setFrom($this->source['temporal']);
break;
default:
throw new SkipException;
break;
}
return $result;
}
}

View file

@ -1,31 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Scm_RemoveClone
extends Mage_Task_TaskAbstract
{
private $_name = 'SCM Remove Clone [built-in]';
private $_source = null;
public function getName()
{
return $this->_name;
}
public function init()
{
$this->_source = $this->getConfig()->deployment('source');
}
public function run()
{
return $this->_runLocalCommand('rm -rf ' . $this->_source['temporal']);
}
}

View file

@ -0,0 +1,64 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Task\BuiltIn\Scm;
use Mage\Task\AbstractTask;
use Mage\Task\SkipException;
use Exception;
/**
* Task for Removing an used Cloned Repository
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class RemoveCloneTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Remove Clone [built-in]';
/**
* Source of the Repo
* @var string
*/
private $source = null;
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return $this->name;
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::init()
*/
public function init()
{
$this->source = $this->getConfig()->deployment('source');
switch ($this->source['type']) {
case 'git':
$this->name = 'SCM Remove Clone (GIT) [built-in]';
break;
}
}
public function run()
{
return $this->runCommandLocal('rm -rf ' . $this->source['temporal']);
}
}

View file

@ -1,55 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Scm_Update
extends Mage_Task_TaskAbstract
{
private $_name = 'SCM Update [built-in]';
public function getName()
{
return $this->_name;
}
public function init()
{
switch ($this->getConfig()->general('scm')) {
case 'git':
$this->_name = 'SCM Update (GIT) [built-in]';
break;
case 'svn':
$this->_name = 'SCM Update (Subversion) [built-in]';
break;
}
}
public function run()
{
switch ($this->getConfig()->general('scm')) {
case 'git':
$command = 'git pull';
break;
case 'svn':
$command = 'svn update';
break;
default:
throw new Mage_Task_SkipException;
break;
}
$result = $this->_runLocalCommand($command);
$this->getConfig()->reload();
return $result;
}
}

View file

@ -0,0 +1,74 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mage\Task\BuiltIn\Scm;
use Mage\Task\AbstractTask;
use Mage\Task\SkipException;
use Exception;
/**
* Task for Updating a Working Copy
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class UpdateTask extends AbstractTask
{
/**
* Name of the Task
* @var string
*/
private $name = 'SCM Update [built-in]';
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return $this->name;
}
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::init()
*/
public function init()
{
switch ($this->getConfig()->general('scm')) {
case 'git':
$this->name = 'SCM Update (GIT) [built-in]';
break;
}
}
/**
* Updates the Working Copy
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
switch ($this->getConfig()->general('scm')) {
case 'git':
$command = 'git pull';
break;
default:
throw new SkipException;
break;
}
$result = $this->runCommandLocal($command);
$this->getConfig()->reload();
return $result;
}
}

View file

@ -8,21 +8,39 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Symfony2_AsseticDump
extends Mage_Task_TaskAbstract
namespace Mage\Task\BuiltIn\Symfony2;
use Mage\Task\AbstractTask;
use Exception;
/**
* Task for Dumping Assetics
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class AsseticDumpTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Assetic Dump [built-in]';
}
/**
* Dumps Assetics
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console assetic:dump --env=' . $env;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
return $result;
}

View file

@ -8,14 +8,32 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Symfony2_AssetsInstall
extends Mage_Task_TaskAbstract
namespace Mage\Task\BuiltIn\Symfony2;
use Mage\Task\AbstractTask;
use Exception;
/**
* Task for Installing Assets
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class AssetsInstallTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Assets Install [built-in]';
}
/**
* Installs Assets
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
// Options
@ -29,7 +47,7 @@ class Mage_Task_BuiltIn_Symfony2_AssetsInstall
}
$command = 'app/console assets:install ' . ($symlink ? '--symlink' : '') . ' ' . ($relative ? '--relative' : '') . ' --env=' . $env . ' ' . $target;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
return $result;
}

View file

@ -8,21 +8,39 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Symfony2_CacheClear
extends Mage_Task_TaskAbstract
namespace Mage\Task\BuiltIn\Symfony2;
use Mage\Task\AbstractTask;
use Exception;
/**
* Task for Clearing the Cache
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class CacheClearTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Cache Clear [built-in]';
}
/**
* Clears the Cache
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console cache:clear --env=' . $env;
$result = $this->_runLocalCommand($command);
$result = $this->runCommandLocal($command);
return $result;
}

View file

@ -8,21 +8,39 @@
* file that was distributed with this source code.
*/
class Mage_Task_BuiltIn_Symfony2_CacheWarmup
extends Mage_Task_TaskAbstract
namespace Mage\Task\BuiltIn\Symfony2;
use Mage\Task\AbstractTask;
use Exception;
/**
* Task for Warming Up the Cache
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class CacheWarmupTask extends AbstractTask
{
/**
* (non-PHPdoc)
* @see \Mage\Task\AbstractTask::getName()
*/
public function getName()
{
return 'Symfony v2 - Cache Warmup [built-in]';
}
/**
* Warms Up Cache
* @see \Mage\Task\AbstractTask::run()
*/
public function run()
{
// Options
$env = $this->getParameter('env', 'dev');
$command = 'app/console cache:warmup --env=' . $env;
$result = $this->runCommand($command);
$result = $this->runCommandLocal($command);
return $result;
}

View file

@ -8,8 +8,15 @@
* file that was distributed with this source code.
*/
class Mage_Task_ErrorWithMessageException
extends Exception
{
namespace Mage\Task;
}
use Exception;
/**
* Exception that indicates that the Task has an Error and also a Message indicating the Error
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class ErrorWithMessageException extends Exception
{
}

View file

@ -8,16 +8,29 @@
* file that was distributed with this source code.
*/
class Mage_Task_Factory
namespace Mage\Task;
use Mage\Config;
use Mage\Autoload;
use Mage\Task\ErrorWithMessageException;
use Exception;
/**
* Task Factory
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class Factory
{
/**
*
* Gets an instance of a Task.
*
* @param string|array $taskData
* @param boolean $inRollback
* @return Mage_Task_TaskAbstract
* @return \Mage\Task\AbstractTask
*/
public static function get($taskData, Mage_Config $taskConfig, $inRollback = false, $stage = null)
public static function get($taskData, Config $taskConfig, $inRollback = false, $stage = null)
{
if (is_array($taskData)) {
$taskName = $taskData['name'];
@ -32,17 +45,25 @@ class Mage_Task_Factory
$taskName = str_replace(' ', '', $taskName);
if (strpos($taskName, '/') === false) {
Mage_Autoload::loadUserTask($taskName);
$className = 'Task_' . ucfirst($taskName);
$instance = new $className($taskConfig, $inRollback, $stage, $taskParameters);
Autoload::loadUserTask($taskName);
$className = 'Task\\' . ucfirst($taskName);
} else {
$taskName = str_replace(' ', '_', ucwords(str_replace('/', ' ', $taskName)));
$className = 'Mage_Task_BuiltIn_' . $taskName;
$instance = new $className($taskConfig, $inRollback, $stage, $taskParameters);
$taskName = str_replace(' ', '\\', ucwords(str_replace('/', ' ', $taskName)));
$className = 'Mage\\Task\\BuiltIn\\' . $taskName . 'Task';
}
if (class_exists($className) || Autoload::isLoadable($className)) {
$instance = new $className($taskConfig, $inRollback, $stage, $taskParameters);
} else {
throw new ErrorWithMessageException('The Task "' . $taskName . '" doesn\'t exists.');
}
if (!($instance instanceOf AbstractTask)) {
throw new Exception('The Task ' . $taskName . ' must be an instance of Mage\Task\AbstractTask.');
}
assert($instance instanceOf Mage_Task_TaskAbstract);
return $instance;
}
}

View file

@ -8,6 +8,13 @@
* file that was distributed with this source code.
*/
interface Mage_Task_Releases_BuiltIn
namespace Mage\Task\Releases;
/**
* Indicates that the Task is Relase Aware/Dependant
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
interface IsReleaseAware
{
}
}

View file

@ -8,6 +8,13 @@
* file that was distributed with this source code.
*/
interface Mage_Task_Releases_RollbackAware
namespace Mage\Task\Releases;
/**
* Indicates that the Task is Aware of Rollbacks
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
interface RollbackAware
{
}
}

View file

@ -8,6 +8,13 @@
* file that was distributed with this source code.
*/
interface Mage_Task_Releases_SkipOnOverride
namespace Mage\Task\Releases;
/**
* Indicates that the Task will be Skipped on Relase Override
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
interface SkipOnOverride
{
}
}

View file

@ -8,8 +8,15 @@
* file that was distributed with this source code.
*/
class Mage_Task_SkipException
extends Exception
{
namespace Mage\Task;
use Exception;
/**
* Exception that indicates that the Task was Skipped
*
* @author Andrés Montañez <andres@andresmontanez.com>
*/
class SkipException extends Exception
{
}

View file

@ -1,99 +0,0 @@
<?php
/*
* This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
abstract class Mage_Task_TaskAbstract
{
protected $_config = null;
protected $_inRollback = false;
protected $_stage = null;
protected $_parameters = array();
public abstract function getName();
public abstract function run();
public final function __construct(Mage_Config $config, $inRollback = false, $stage = null, $parameters = array())
{
$this->_config = $config;
$this->_inRollback = $inRollback;
$this->_stage = $stage;
$this->_parameters = $parameters;
}
public function inRollback()
{
return $this->_inRollback;
}
public function getStage()
{
return $this->_stage;
}
public function getConfig()
{
return $this->_config;
}
public function init()
{
}
/**
* Return the a parameter
*
* @param string $name
* @return mixed
*/
public function getParameter($name, $default = null)
{
return $this->getConfig()->getParameter($name, $default, $this->_parameters);
}
protected final function runCommand($command, &$output = null)
{
if ($this->getStage() == 'deploy') {
return $this->_runRemoteCommand($command, $output);
} else {
return $this->_runLocalCommand($command, $output);
}
}
protected final function _runLocalCommand($command, &$output = null)
{
return Mage_Console::executeCommand($command, $output);
}
protected final function _runRemoteCommand($command, &$output = null)
{
if ($this->_config->release('enabled', false) == true) {
if ($this instanceOf Mage_Task_Releases_BuiltIn) {
$releasesDirectory = '';
} else {
$releasesDirectory = '/'
. $this->_config->release('directory', 'releases')
. '/'
. $this->_config->getReleaseId();
}
} else {
$releasesDirectory = '';
}
$localCommand = 'ssh -p ' . $this->_config->getHostPort() . ' '
. '-q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '
. $this->_config->deployment('user') . '@' . $this->_config->getHostName() . ' '
. '"cd ' . rtrim($this->_config->deployment('to'), '/') . $releasesDirectory . ' && '
. str_replace('"', '\"', $command) . '"';
return $this->_runLocalCommand($localCommand, $output);
}
}

View file

@ -18,11 +18,11 @@ define('MAGALLANES_VERSION', '0.9.14');
// Preload
require_once $baseDir . '/Mage/spyc.php';
require_once $baseDir . '/Mage/Autoload.php';
spl_autoload_register(array('Mage_Autoload', 'autoload'));
spl_autoload_register(array('Mage\\Autoload', 'autoload'));
// Clean arguments
array_shift($argv);
// Run Magallanes
$console = new Mage_Console;
$console = new Mage\Console;
$console->run($argv);

View file

@ -1,6 +1,9 @@
<?php
class Task_Permissions
extends Mage_Task_TaskAbstract
namespace Task;
use Mage\Task\AbstractTask;
class Permissions extends AbstractTask
{
public function getName()
{
@ -10,7 +13,7 @@ class Task_Permissions
public function run()
{
$command = 'chmod 755 . -R';
$result = $this->_runRemoteCommand($command);
$result = $this->runCommandRemote($command);
return $result;
}

View file

@ -1,6 +1,9 @@
<?php
class Task_Privileges
extends Mage_Task_TaskAbstract
namespace Task;
use Mage\Task\AbstractTask;
class Privileges extends AbstractTask
{
public function getName()
{
@ -10,8 +13,8 @@ class Task_Privileges
public function run()
{
$command = 'chown 33:33 . -R';
$result = $this->_runRemoteCommand($command);
$result = $this->runCommandRemote($command);
return $result;
}
}

View file

@ -1,6 +1,9 @@
<?php
class Task_SampleTask
extends Mage_Task_TaskAbstract
namespace Task;
use Mage\Task\AbstractTask;
class SampleTask extends AbstractTask
{
public function getName()
{

View file

@ -1,7 +1,10 @@
<?php
class Task_SampleTaskRollbackAware
extends Mage_Task_TaskAbstract
implements Mage_Task_Releases_RollbackAware
namespace Task;
use Mage\Task\AbstractTask;
use Mage\Task\Releases\RollbackAware;
class SampleTaskRollbackAware extends AbstractTask implements RollbackAware
{
public function getName()
{

View file

@ -1,6 +1,9 @@
<?php
class Task_TaskWithParameters
extends Mage_Task_TaskAbstract
namespace Task;
use Mage\Task\AbstractTask;
class TaskWithParameters extends AbstractTask
{
public function getName()
{