Esempio n. 1
0
 public function run($args)
 {
     $cli = new CLImate();
     $backup_dir = Setting::getSetting('consh:db_backup_folder');
     if (!file_exists($backup_dir)) {
         if (!mkdir($backup_dir, 0777, true)) {
             $cli->error("Could not create database backup folder: {$backup_dir}");
             return false;
         }
     }
     if (count($args) != 1) {
         $cli->error("Please pass along the filename to import");
         if ($handle = opendir($backup_dir)) {
             $cli->out("possible files:");
             while (false !== ($entry = readdir($handle))) {
                 if ($entry != '.' && $entry != '..') {
                     $cli->out($entry);
                 }
             }
         } else {
             $cli->error("Could not open database backup folder");
         }
         return false;
     }
     $file = $args[0];
     $path = $backup_dir . "/" . $file;
     if (!file_exists($path)) {
         $cli->error("{$file} does not exist");
         return false;
     }
     $sql = file($path);
     $db = new LocalDB();
     $templine = '';
     $size = count($sql);
     $cli->out("Restoring database");
     $progress = $cli->progress()->total($size);
     $current = 0;
     foreach ($sql as $line) {
         $current++;
         // Skip it if it's a comment
         if (substr($line, 0, 2) == '--' || $line == '') {
             continue;
         }
         $templine .= $line;
         if (substr(trim($line), -1, 1) == ';') {
             $db->execute($templine);
             $progress->current($current);
             $templine = '';
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function process()
 {
     $msg = 'Processing workflow';
     if ($this->workflow instanceof Workflow and $name = $this->workflow->getName()) {
         $msg .= ': ' . $name;
     }
     $this->climate->write($msg . "\n");
     $result = $this->workflow->process();
     $this->climate->info('Time elapsed: ' . $result->getElapsed()->format('%i minute(s) %s second(s)'));
     $this->climate->info('Total processed: ' . $result->getTotalProcessedCount() . ' row(s)');
     if ($errorCount = $result->getErrorCount() > 0) {
         $this->climate->error('Errors: ' . $errorCount);
     }
     return $result;
 }
Esempio n. 3
0
 /**
  * Execute the command.
  *
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  *
  * @return mixed
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $climate = new CLImate();
     $climate->br();
     try {
         $packages = $this->ladder->getOutdatedPackages();
         if (!$packages) {
             $climate->write('All dependencies match the latest package versions <green>:)</green>')->br();
             return;
         }
         $outdated = [];
         $upgradable = [];
         foreach ($packages as $name => list($constraint, $version, $latest)) {
             if (Version::satisfies($latest, $constraint)) {
                 $latest = $this->diff($version, $latest);
                 $upgradable[] = [$name, $version, '→', $latest];
             } else {
                 $latest = $this->diff($version, $latest);
                 $outdated[] = [$name, $version, '→', $latest];
             }
         }
         if ($outdated) {
             $climate->columns($outdated, 3)->br();
         }
         if ($upgradable) {
             $climate->write('The following dependencies are satisfied by their declared version constraint, but the installed versions are behind. You can install the latest versions without modifying your composer.json file by using \'composer update\'.')->br();
             $climate->columns($upgradable, 3)->br();
         }
     } catch (ClimbException $exception) {
         $climate->error($exception->getMessage())->br();
     }
 }
 /**
  * @param CLImate $cli
  * @param array $arguments
  * @return void
  */
 public function execute(CLImate $cli, $arguments)
 {
     if (!$arguments['trackingNumber']) {
         $cli->error('ERROR. No tracking number provided.');
         return null;
     }
     $chronopostAdapter = new ChronopostAdapter();
     $deliveryTracking = new DeliveryTracking($chronopostAdapter);
     $cli->br();
     try {
         $status = $deliveryTracking->getDeliveryStatus($arguments['trackingNumber']);
         $cli->out(sprintf('Delivery #%s is <green>%s</green>', $arguments['trackingNumber'], $status));
     } catch (\Exception $e) {
         $cli->error(sprintf('ERROR. %s', $e->getMessage()));
     }
     $cli->br();
 }
Esempio n. 5
0
 /**
  * connect to the remote server
  * @return bool|\Net_SSH2
  */
 private function connect()
 {
     $ssh = new \Net_SSH2(Setting::getSetting('remote:host'));
     $key = new Crypt_RSA();
     $key->loadKey(file_get_contents(Setting::getSetting('ssh:priv_key')));
     if (!$ssh->login(Setting::getSetting('remote:user'), $key)) {
         $cli = new CLImate();
         $cli->error("Could not connect to server");
         return false;
     }
     return $ssh;
 }
 /**
  * @param CLImate $cli
  * @param array $arguments
  * @return void
  */
 public function execute(CLImate $cli, $arguments)
 {
     if (!$arguments['reference']) {
         $cli->error('ERROR. No reference provided.');
         return null;
     }
     $cli->comment('Warning: this command may be slow. It may download and parse a lot of file.');
     $cli->comment('I you know the tracking number, you may want to use the `tracking:status [trackingNumber]` command');
     $chronopostAdapter = new ChronopostFtpAdapter(['host' => 'ftpserv.chronopost.fr', 'username' => 'arconseil', 'password' => '!arcnsl$']);
     $deliveryTracking = new DeliveryTracking($chronopostAdapter);
     $cli->br();
     try {
         $status = $deliveryTracking->getDeliveryStatusByInternalReference($arguments['reference']);
         $cli->out(sprintf('Delivery #%s is <green>%s</green>', $arguments['reference'], $status));
         $trackingNumber = $deliveryTracking->getTrackingNumberByInternalReference($arguments['reference']);
         $cli->whisper(sprintf('The associated tracking Number is %s.', $trackingNumber));
     } catch (\Exception $e) {
         $cli->error(sprintf('ERROR. %s', $e->getMessage()));
     }
     $cli->br();
 }
 /**
  * Receives the messages and pass them to sender
  */
 public function handle()
 {
     $this->channel->basic_consume($this->listenQueue, '', false, true, false, false, function ($msg) {
         $this->climate->br();
         $this->climate->info('Received: ' . $msg->body);
         $input = json_decode($msg->body, true);
         try {
             $output = $this->interestCalculator->caculateInterest($input);
             $output['token'] = $this->token;
             $output = json_encode($output);
             $this->climate->out('Sending back: ' . $output);
             $this->channel->basic_publish($this->amqpFactory->buildMessage($output), '', $this->broadcastQueue);
         } catch (Exception $e) {
             $this->climate->error('Unable to handle the message: ' . $e->getMessage());
             return false;
         }
         return true;
     });
     while (count($this->channel->callbacks)) {
         $this->channel->wait();
     }
     $this->channel->close();
     $this->connection->close();
 }
Esempio n. 8
0
 public function run($args)
 {
     $cli = new CLImate();
     $origin = Setting::getSetting('remote:user') . '@' . Setting::getSetting('remote:host') . ':' . Remote::getFilesPath();
     $dest = Local::getFilesPath();
     if (!file_exists($dest)) {
         if (!mkdir($dest, 0777, true)) {
             $cli->error('Could not create local files directory');
             return false;
         }
     }
     $rsync = new Rsync();
     $rsync->setVerbose(true);
     $rsync->setExclude(Setting::getSetting('rsync:excludes'));
     $rsync->sync($origin, $dest);
 }
Esempio n. 9
0
 public function run($args)
 {
     $cli = new CLImate();
     $file_name = 'db_' . time() . '.sql';
     $remote_file = Remote::getHomePath() . $file_name;
     $local_file = Setting::getSetting('consh:db_backup_folder') . "/{$file_name}";
     if (!file_exists(Setting::getSetting('consh:db_backup_folder'))) {
         if (!mkdir(Setting::getSetting('consh:db_backup_folder'), 0777, true)) {
             $cli->error("Could not create database backup folder: " . Setting::getSetting('consh:db_backup_folder'));
             return false;
         }
     }
     $ssh = SSHConnection::getInstance();
     $ssh->exec('mysqldump -h ' . Setting::getSetting('mysql:host') . ' -u ' . Setting::getSetting('mysql:user') . ' -p' . addslashes(Setting::getSetting('mysql:pass')) . ' ' . Setting::getSetting('mysql:db') . " > " . $remote_file);
     $ssh->scpRemoteLocal($remote_file, $local_file);
     $ssh->rmRemoteFile($remote_file);
     $cli->out("File saved to {$local_file}");
 }
Esempio n. 10
0
 /**
  * Returns CLImate error output
  *
  * @param  string $string Output
  * @return mixed
  */
 public function error($string)
 {
     return $this->climate->error($string);
 }
Esempio n. 11
0
define('TASK_PATH', __DIR__ . '/app/tasks');
define('TASK_LOG_PATH', __DIR__ . '/app/logs');
define('ROOTPATH', __DIR__ . '/');
use League\CLImate\CLImate;
use alexlvcom\TaskRunner\CommandContext;
use alexlvcom\TaskRunner\ParamValidator;
use alexlvcom\ServiceContainer\Container as ServiceContainer;
$climate = new CLImate();
$container = new ServiceContainer();
$climate->out('<green>Task Runner by AlexLV. (c) 2015 .</green> <white>Version <yellow>' . ALEXLVCOM_TASK_RUNNER_VERSION . '</yellow>');
$climate->br();
$climate->arguments->add(['name' => ['longPrefix' => 'name', 'description' => 'Task Name', 'required' => true]]);
try {
    $climate->arguments->parse();
} catch (Exception $e) {
    $climate->error($e->getMessage())->br()->usage();
    $climate->br();
    exit;
}
if ($climate->arguments->defined('name') === false || $climate->arguments->get('name') === '') {
    $climate->usage();
    exit;
}
$time_start = microtime(true);
$taskName = $climate->arguments->get('name');
if (substr($taskName, 0, 1) === '\\') {
    // Absolute namespace provided
    $className = substr($taskName, 1);
} else {
    // relative path goes with prepended alexlvcom\TaskRunner\Tasks namespace
    $className = 'alexlvcom\\TaskRunner\\Tasks\\' . $climate->arguments->get('name');
Esempio n. 12
0
 /**
  * Update the current remote server with the array of files provided.
  *
  * @param array $files 2-dimensional array with 2 indices: 'upload' and 'delete'
  *                     Each of these contains an array of filenames and paths (relative to repository root)
  */
 public function push($files, $localRevision = null)
 {
     if (empty($localRevision)) {
         // We will write this in the server
         $localRevision = $this->currentRevision();
     }
     $initialBranch = $this->currentBranch();
     // If revision is not HEAD, the current one, it means this is a rollback.
     // So, we have to revert the files the the state they were in that revision.
     if ($this->revision != 'HEAD') {
         $this->cli->out('   Rolling back working copy');
         // BUG: This does NOT work correctly for submodules & subsubmodules (and leaves them in an incorrect state)
         //      It technically should do a submodule update in the parent, not a checkout inside the submodule
         $this->git->command('checkout ' . $this->revision, $this->repo);
     }
     $filesToDelete = $files['delete'];
     // Add deleted directories to the list of files to delete. Git does not handle this.
     $dirsToDelete = [];
     if (count($filesToDelete) > 0) {
         $dirsToDelete = $this->hasDeletedDirectories($filesToDelete);
     }
     $filesToUpload = $files['upload'];
     unset($files);
     // No longer needed
     // Upload Files
     if (count($filesToUpload) > 0) {
         foreach ($filesToUpload as $fileNo => $file) {
             if ($this->currentSubmoduleName) {
                 $file = $this->currentSubmoduleName . '/' . $file;
             }
             // Make sure the folder exists in the FTP server.
             $dir = explode('/', dirname($file));
             $path = '';
             $ret = true;
             // Skip mkdir if dir is basedir
             if ($dir[0] !== '.') {
                 // Loop through each folder in the path /a/b/c/d.txt to ensure that it exists
                 // @TODO Can be improved by using: $filesystem->write('path/to/file.txt', 'contents');
                 for ($i = 0, $count = count($dir); $i < $count; ++$i) {
                     $path .= $dir[$i] . '/';
                     if (!isset($pathsThatExist[$path])) {
                         if (!$this->connection->has($path)) {
                             $this->connection->createDir($path);
                             $this->cli->out(" + Created directory '{$path}'.");
                             $pathsThatExist[$path] = true;
                         } else {
                             $pathsThatExist[$path] = true;
                         }
                     }
                 }
             }
             $filePath = $this->repo . '/' . ($this->currentSubmoduleName ? str_replace($this->currentSubmoduleName . '/', '', $file) : $file);
             $data = @file_get_contents($filePath);
             // It can happen the path is wrong, especially with included files.
             if ($data === false) {
                 $this->cli->error(' ! File not found - please check path: ' . $filePath);
                 continue;
             }
             $remoteFile = $file;
             $uploaded = $this->connection->put($remoteFile, $data);
             if (!$uploaded) {
                 $this->cli->error(" ! Failed to upload {$file}.");
             } else {
                 $this->deploymentSize += filesize($this->repo . '/' . ($this->currentSubmoduleName ? str_replace($this->currentSubmoduleName . '/', '', $file) : $file));
             }
             $numberOfFilesToUpdate = count($filesToUpload);
             $fileNo = str_pad(++$fileNo, strlen($numberOfFilesToUpdate), ' ', STR_PAD_LEFT);
             $this->cli->lightGreen(" ^ {$fileNo} of {$numberOfFilesToUpdate} <white>{$file}");
         }
     }
     // Delete files
     if (count($filesToDelete) > 0) {
         foreach ($filesToDelete as $fileNo => $file) {
             if ($this->currentSubmoduleName) {
                 $file = $this->currentSubmoduleName . '/' . $file;
             }
             $numberOfFilesToDelete = count($filesToDelete);
             $fileNo = str_pad(++$fileNo, strlen($numberOfFilesToDelete), ' ', STR_PAD_LEFT);
             if ($this->connection->has($file)) {
                 $this->connection->delete($file);
                 $this->cli->out("<red> × {$fileNo} of {$numberOfFilesToDelete} <white>{$file}");
             } else {
                 $this->cli->out("<red> ! {$fileNo} of {$numberOfFilesToDelete} <white>{$file} not found");
             }
         }
     }
     // Delete Directories
     if (count($dirsToDelete) > 0) {
         foreach ($dirsToDelete as $dirNo => $dir) {
             if ($this->currentSubmoduleName) {
                 $dir = $this->currentSubmoduleName . '/' . $dir;
             }
             $numberOfdirsToDelete = count($dirsToDelete);
             $dirNo = str_pad(++$dirNo, strlen($numberOfdirsToDelete), ' ', STR_PAD_LEFT);
             if ($this->connection->has($dir)) {
                 $this->connection->deleteDir($dir);
                 $this->cli->out("<red> × {$dirNo} of {$numberOfdirsToDelete} <white>{$dir}");
             } else {
                 $this->cli->out("<red> ! {$dirNo} of {$numberOfdirsToDelete} <white>{$dir} not found");
             }
         }
     }
     if (count($filesToUpload) > 0 or count($filesToDelete) > 0) {
         $this->setRevision($localRevision);
     } else {
         $this->cli->gray()->out('   No files to upload or delete.');
     }
     // If $this->revision is not HEAD, it means the rollback command was provided
     // The working copy was rolled back earlier to run the deployment, and we
     // now want to return the working copy back to its original state.
     if ($this->revision != 'HEAD') {
         $this->git->command('checkout ' . ($initialBranch ?: 'master'));
     }
     $this->log('[SHA: ' . $localRevision . '] Deployment to server: "' . $this->currentlyDeploying . '" from branch "' . $initialBranch . '". ' . count($filesToUpload) . ' files uploaded; ' . count($filesToDelete) . ' files deleted.');
 }
Esempio n. 13
0
 /**
  * Call cli
  *
  * @param array $argv
  *
  * @throws BaseException
  * @throws MissingMethodException
  */
 private function callCli(array $argv)
 {
     if ($this->getRouter()->isMatched()) {
         $cliMethod = 'cliMethod';
         $cliConfig = 'cliConfig';
         $actionNamespace = $this->getRouter()->getActionNamespace();
         $reflection = new ReflectionClass($actionNamespace);
         if (!$reflection->implementsInterface('App\\Action\\AppAction')) {
             throw new BaseException(sprintf('"%s" action must extend "App\\Action\\AppAction"', $actionNamespace));
         }
         // Check Action::cliMethod exist or callable
         if (method_exists($actionNamespace, $cliMethod) && is_callable([$actionNamespace, $cliMethod])) {
             $responderNamespace = $this->getRouter()->getResponderNamespace();
             $responder = null;
             $reflection = new ReflectionClass($responderNamespace);
             if (class_exists($responderNamespace) && $reflection->implementsInterface('App\\Responder\\AppResponder')) {
                 $responder = new $responderNamespace();
             }
             /** @var ContainerAwareInterface|EventSubscriberInterface $actionInstance */
             $actionInstance = new $actionNamespace($responder);
             $actionInstance->setContainer($this->container);
             $this->getEventManager()->addSubscriber($actionInstance);
             $climate = new CLImate();
             if (method_exists($actionNamespace, $cliConfig) && is_callable([$actionNamespace, $cliConfig])) {
                 $argumentManager = new Manager();
                 $climate->setArgumentManager($argumentManager);
                 $this->getEventManager()->dispatch(Action::EVENT_BEFORE_CLI_CONFIG);
                 call_user_func([$actionInstance, 'cliConfig'], $argumentManager);
                 $this->getEventManager()->dispatch(Action::EVENT_AFTER_CLI_CONFIG);
                 try {
                     $argumentManager->parse($argv);
                 } catch (\Exception $e) {
                     $climate->error($e->getMessage());
                     $climate->usage();
                 }
             }
             $this->getEventManager()->dispatch(Action::EVENT_BEFORE_CLI_METHOD);
             call_user_func([$actionInstance, $cliMethod], $climate);
             $this->getEventManager()->dispatch(Action::EVENT_AFTER_CLI_METHOD);
             // Check Responder::cliMethod exist or callable
             if (method_exists($responder, $cliMethod) && is_callable([$responder, $cliMethod])) {
                 $this->getEventManager()->dispatch(self::EVENT_BEFORE_RESPONDER);
                 call_user_func([$responder, $cliMethod]);
                 $this->getEventManager()->dispatch(self::EVENT_AFTER_RESPONDER);
             }
         } else {
             throw new MissingMethodException(sprintf('Method %s::%s() could not be found, or is not accessible.', $actionNamespace, $cliMethod));
         }
     } else {
         throw new BaseException(sprintf('Route "%s" does not found', $argv[0]));
     }
 }