1
0
Fork 0

Cleanups of IOInterface

pull/219/merge
Jordi Boggiano 2012-01-17 23:07:33 +01:00
parent edf948454b
commit 434c9ecdeb
7 changed files with 92 additions and 156 deletions

View File

@ -22,7 +22,7 @@ use Symfony\Component\Finder\Finder;
use Composer\Command; use Composer\Command;
use Composer\Composer; use Composer\Composer;
use Composer\Factory; use Composer\Factory;
use Composer\IO\IOInterface; use Composer\IO\IOInterface;
use Composer\IO\ConsoleIO; use Composer\IO\ConsoleIO;
/** /**
@ -77,7 +77,7 @@ class Application extends BaseApplication
try { try {
$this->composer = Factory::create($this->io); $this->composer = Factory::create($this->io);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->io->writeln($e->getMessage()); $this->io->write($e->getMessage());
exit(1); exit(1);
} }
} }

View File

@ -66,7 +66,7 @@ abstract class FileDownloader implements DownloaderInterface
$fileName = rtrim($path.'/'.md5(time().rand()).'.'.pathinfo($url, PATHINFO_EXTENSION), '.'); $fileName = rtrim($path.'/'.md5(time().rand()).'.'.pathinfo($url, PATHINFO_EXTENSION), '.');
$this->io->writeln(" - Package <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)"); $this->io->write(" - Package <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)");
if (!extension_loaded('openssl') && (0 === strpos($url, 'https:') || 0 === strpos($url, 'http://github.com'))) { if (!extension_loaded('openssl') && (0 === strpos($url, 'https:') || 0 === strpos($url, 'http://github.com'))) {
// bypass https for github if openssl is disabled // bypass https for github if openssl is disabled
@ -77,27 +77,27 @@ abstract class FileDownloader implements DownloaderInterface
} }
} }
// Handle system proxy // Handle system proxy
$params = array('http' => array()); $params = array('http' => array());
if (isset($_SERVER['HTTP_PROXY'])) { if (isset($_SERVER['HTTP_PROXY'])) {
// http(s):// is not supported in proxy // http(s):// is not supported in proxy
$proxy = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $_SERVER['HTTP_PROXY']); $proxy = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $_SERVER['HTTP_PROXY']);
if (0 === strpos($proxy, 'ssl:') && !extension_loaded('openssl')) { if (0 === strpos($proxy, 'ssl:') && !extension_loaded('openssl')) {
throw new \RuntimeException('You must enable the openssl extension to use a proxy over https'); throw new \RuntimeException('You must enable the openssl extension to use a proxy over https');
} }
$params['http'] = array( $params['http'] = array(
'proxy' => $proxy, 'proxy' => $proxy,
'request_fulluri' => true, 'request_fulluri' => true,
); );
} }
if ($this->io->hasAuthorization($package->getSourceUrl())) { if ($this->io->hasAuthorization($package->getSourceUrl())) {
$auth = $this->io->getAuthorization($package->getSourceUrl()); $auth = $this->io->getAuthorization($package->getSourceUrl());
$authStr = base64_encode($auth['username'] . ':' . $auth['password']); $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
$params['http'] = array_merge($params['http'], array('header' => "Authorization: Basic $authStr\r\n")); $params['http'] = array_merge($params['http'], array('header' => "Authorization: Basic $authStr\r\n"));
} }
$ctx = stream_context_create($params); $ctx = stream_context_create($params);
@ -105,7 +105,7 @@ abstract class FileDownloader implements DownloaderInterface
$this->io->overwrite(" Downloading: <comment>connection...</comment>", 80); $this->io->overwrite(" Downloading: <comment>connection...</comment>", 80);
copy($url, $fileName, $ctx); copy($url, $fileName, $ctx);
$this->io->overwriteln(" Downloading", 80); $this->io->overwrite(" Downloading", 80);
if (!file_exists($fileName)) { if (!file_exists($fileName)) {
throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the' throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
@ -116,11 +116,11 @@ abstract class FileDownloader implements DownloaderInterface
throw new \UnexpectedValueException('The checksum verification of the archive failed (downloaded from '.$url.')'); throw new \UnexpectedValueException('The checksum verification of the archive failed (downloaded from '.$url.')');
} }
$this->io->writeln(' Unpacking archive'); $this->io->write(' Unpacking archive');
$this->extract($fileName, $path); $this->extract($fileName, $path);
$this->io->writeln(' Cleaning up'); $this->io->write(' Cleaning up');
unlink($fileName); unlink($fileName);
// If we have only a one dir inside it suppose to be a package itself // If we have only a one dir inside it suppose to be a package itself
@ -135,7 +135,7 @@ abstract class FileDownloader implements DownloaderInterface
rmdir($contentDir); rmdir($contentDir);
} }
$this->io->writeln(''); $this->io->write('');
} }
/** /**

View File

@ -18,10 +18,10 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Formatter\OutputFormatterInterface; use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\HelperSet;
/** /**
* The Input/Output helper. * The Input/Output helper.
* *
* @author François Pluchino <francois.pluchino@opendisplay.com> * @author François Pluchino <francois.pluchino@opendisplay.com>
*/ */
class ConsoleIO implements IOInterface class ConsoleIO implements IOInterface
{ {
@ -57,17 +57,9 @@ class ConsoleIO implements IOInterface
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function write($messages, $newline = false, $type = 0) public function write($messages, $newline = true)
{ {
$this->output->write($messages, $newline, $type); $this->output->write($messages, $newline);
}
/**
* {@inheritDoc}
*/
public function writeln($messages, $type = 0)
{
$this->output->writeln($messages, $type);
} }
/** /**
@ -95,62 +87,6 @@ class ConsoleIO implements IOInterface
} }
} }
/**
* {@inheritDoc}
*/
public function overwriteln($messages, $size = 80, $type = 0)
{
$this->overwrite($messages, $size, true, $type);
}
/**
* {@inheritDoc}
*/
public function setVerbosity($level)
{
$this->output->setVerbosity($level);
}
/**
* {@inheritDoc}
*/
public function getVerbosity()
{
return $this->output->getVerbosity();
}
/**
* {@inheritDoc}
*/
public function setDecorated($decorated)
{
$this->output->setDecorated($decorated);
}
/**
* {@inheritDoc}
*/
public function isDecorated()
{
return $this->output->isDecorated();
}
/**
* {@inheritDoc}
*/
public function setFormatter(OutputFormatterInterface $formatter)
{
$this->output->setFormatter($formatter);
}
/**
* {@inheritDoc}
*/
public function getFormatter()
{
return $this->output->getFormatter();
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -167,6 +103,9 @@ class ConsoleIO implements IOInterface
return $this->helperSet->get('dialog')->askConfirmation($this->output, $question, $default); return $this->helperSet->get('dialog')->askConfirmation($this->output, $question, $default);
} }
/**
* {@inheritDoc}
*/
public function askAndValidate($question, $validator, $attempts = false, $default = null) public function askAndValidate($question, $validator, $attempts = false, $default = null)
{ {
return $this->helperSet->get('dialog')->askAndValidate($this->output, $question, $validator, $attempts, $default); return $this->helperSet->get('dialog')->askAndValidate($this->output, $question, $validator, $attempts, $default);
@ -201,19 +140,19 @@ class ConsoleIO implements IOInterface
// for other OS with shell_exec (hide the answer) // for other OS with shell_exec (hide the answer)
if (rtrim(shell_exec($command)) === 'OK') { if (rtrim(shell_exec($command)) === 'OK') {
$command = "/usr/bin/env bash -c 'echo OK'"; $command = "/usr/bin/env bash -c 'echo OK'";
$this->write($question); $this->write($question);
$command = "/usr/bin/env bash -c 'read -s mypassword && echo \$mypassword'"; $command = "/usr/bin/env bash -c 'read -s mypassword && echo \$mypassword'";
$value = rtrim(shell_exec($command)); $value = rtrim(shell_exec($command));
for ($i = 0; $i < strlen($value); ++$i) { for ($i = 0; $i < strlen($value); ++$i) {
$this->write('*'); $this->write('*');
} }
$this->writeln(''); $this->writeln('');
return $value; return $value;
} }

View File

@ -21,32 +21,30 @@ use Symfony\Component\Console\Helper\HelperSet;
* @author François Pluchino <francois.pluchino@opendisplay.com> * @author François Pluchino <francois.pluchino@opendisplay.com>
*/ */
interface IOInterface extends OutputInterface interface IOInterface extends OutputInterface
{ {
/** /**
* Is this input means interactive? * Is this input means interactive?
* *
* @return Boolean * @return Boolean
*/ */
function isInteractive(); function isInteractive();
/**
* Writes a message to the output.
*
* @param string|array $messages The message as an array of lines or a single string
* @param Boolean $newline Whether to add a newline or not
*/
function write($messages, $newline = true);
/** /**
* Overwrites a previous message to the output. * Overwrites a previous message to the output.
* *
* @param string|array $messages The message as an array of lines of a single string * @param string|array $messages The message as an array of lines or a single string
* @param integer $size The size of line * @param integer $size The size of line
* @param Boolean $newline Whether to add a newline or not * @param Boolean $newline Whether to add a newline or not
* @param integer $type The type of output
*/ */
function overwrite($messages, $size = 80, $newline = false, $type = 0); function overwrite($messages, $size = 80, $newline = true);
/**
* Overwrites a previous message to the output and adds a newline at the end.
*
* @param string|array $messages The message as an array of lines of a single string
* @param integer $size The size of line
* @param integer $type The type of output
*/
function overwriteln($messages, $size = 80, $type = 0);
/** /**
* Asks a question to the user. * Asks a question to the user.

View File

@ -140,7 +140,7 @@ class LibraryInstaller implements InstallerInterface
foreach ($package->getBinaries() as $bin) { foreach ($package->getBinaries() as $bin) {
$link = $this->binDir.'/'.basename($bin); $link = $this->binDir.'/'.basename($bin);
if (file_exists($link)) { if (file_exists($link)) {
$this->io->writeln('Skipped installation of '.$bin.' for package '.$package->getName().', name conflicts with an existing file'); $this->io->write('Skipped installation of '.$bin.' for package '.$package->getName().', name conflicts with an existing file');
continue; continue;
} }
$bin = $this->getInstallPath($package).'/'.$bin; $bin = $this->getInstallPath($package).'/'.$bin;

View File

@ -41,7 +41,9 @@ abstract class VcsDriver
} }
/** /**
* Get the https or http protocol. * Get the https or http protocol depending on SSL support.
*
* Call this only if you know that the server supports both.
* *
* @return string The correct type of protocol * @return string The correct type of protocol
*/ */
@ -70,7 +72,6 @@ abstract class VcsDriver
if ($this->io->hasAuthorization($this->url)) { if ($this->io->hasAuthorization($this->url)) {
$authStr = base64_encode($auth['username'] . ':' . $auth['password']); $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
$params['http'] = array('header' => "Authorization: Basic $authStr\r\n"); $params['http'] = array('header' => "Authorization: Basic $authStr\r\n");
} else if (null !== $this->io->getLastUsername()) { } else if (null !== $this->io->getLastUsername()) {
$authStr = base64_encode($this->io->getLastUsername() . ':' . $this->io->getLastPassword()); $authStr = base64_encode($this->io->getLastUsername() . ':' . $this->io->getLastPassword());
$params['http'] = array('header' => "Authorization: Basic $authStr\r\n"); $params['http'] = array('header' => "Authorization: Basic $authStr\r\n");
@ -91,54 +92,52 @@ abstract class VcsDriver
return $content; return $content;
} }
/** /**
* Get notification action. * Get notification action.
* *
* @param integer $notificationCode The notification code * @param integer $notificationCode The notification code
* @param integer $severity The severity level * @param integer $severity The severity level
* @param string $message The message * @param string $message The message
* @param integer $messageCode The message code * @param integer $messageCode The message code
* @param integer $bytesTransferred The loaded size * @param integer $bytesTransferred The loaded size
* @param integer $bytesMax The total size * @param integer $bytesMax The total size
*/ */
protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
{ {
switch ($notificationCode) { switch ($notificationCode) {
case STREAM_NOTIFY_AUTH_REQUIRED: case STREAM_NOTIFY_AUTH_REQUIRED:
case STREAM_NOTIFY_FAILURE: case STREAM_NOTIFY_FAILURE:
// for private repository returning 404 error when the authorization is incorrect // for private repository returning 404 error when the authorization is incorrect
$auth = $this->io->getAuthorization($this->url); $auth = $this->io->getAuthorization($this->url);
$ps = $this->firstCall && 404 === $messageCode $ps = $this->firstCall && 404 === $messageCode
&& null === $this->io->getLastUsername() && null === $this->io->getLastUsername()
&& null === $auth['username']; && null === $auth['username'];
if (404 === $messageCode && !$this->firstCall) { if (404 === $messageCode && !$this->firstCall) {
throw new \RuntimeException("The '" . $this->contentUrl . "' URL not found"); throw new \RuntimeException("The '" . $this->contentUrl . "' URL not found");
}
if ($this->firstCall) {
$this->firstCall = false;
} }
$this->firstCall = false;
// get authorization informations // get authorization informations
if (401 === $messageCode || $ps) { if (401 === $messageCode || $ps) {
if (!$this->io->isInteractive()) { if (!$this->io->isInteractive()) {
$mess = "The '" . $this->contentUrl . "' URL not found"; $mess = "The '" . $this->contentUrl . "' URL not found";
if (401 === $code || $ps) { if (401 === $code || $ps) {
$mess = "The '" . $this->contentUrl . "' URL required the authorization.\nYou must be used the interactive console"; $mess = "The '" . $this->contentUrl . "' URL required the authorization.\nYou must be used the interactive console";
} }
throw new \RuntimeException($mess); throw new \RuntimeException($mess);
} }
$this->io->writeln("Authorization for <info>" . $this->contentUrl . "</info>:"); $this->io->write("Authorization for <info>" . $this->contentUrl . "</info>:");
$username = $this->io->ask(' Username: '); $username = $this->io->ask(' Username: ');
$password = $this->io->askAndHideAnswer(' Password: '); $password = $this->io->askAndHideAnswer(' Password: ');
$this->io->setAuthorization($this->url, $username, $password); $this->io->setAuthorization($this->url, $username, $password);
$this->content = $this->getContents($this->contentUrl); $this->content = $this->getContents($this->contentUrl);
} }
break; break;
default: default:

View File

@ -14,7 +14,7 @@ class VcsRepository extends ArrayRepository
{ {
protected $url; protected $url;
protected $packageName; protected $packageName;
protected $debug; protected $debug;
protected $io; protected $io;
public function __construct(array $config, IOInterface $io, array $drivers = null) public function __construct(array $config, IOInterface $io, array $drivers = null)
@ -88,7 +88,7 @@ class VcsRepository extends ArrayRepository
} catch (\Exception $e) { } catch (\Exception $e) {
if (strpos($e->getMessage(), 'JSON Parse Error') !== false) { if (strpos($e->getMessage(), 'JSON Parse Error') !== false) {
if ($debug) { if ($debug) {
$this->io->writeln('Skipped tag '.$tag.', '.$e->getMessage()); $this->io->write('Skipped tag '.$tag.', '.$e->getMessage());
} }
continue; continue;
} else { } else {
@ -112,18 +112,18 @@ class VcsRepository extends ArrayRepository
// broken package, version doesn't match tag // broken package, version doesn't match tag
if ($data['version_normalized'] !== $parsedTag) { if ($data['version_normalized'] !== $parsedTag) {
if ($debug) { if ($debug) {
$this->io->writeln('Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json'); $this->io->write('Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json');
} }
continue; continue;
} }
if ($debug) { if ($debug) {
$this->io->writeln('Importing tag '.$tag.' ('.$data['version_normalized'].')'); $this->io->write('Importing tag '.$tag.' ('.$data['version_normalized'].')');
} }
$this->addPackage($loader->load($this->preProcess($driver, $data, $identifier))); $this->addPackage($loader->load($this->preProcess($driver, $data, $identifier)));
} elseif ($debug) { } elseif ($debug) {
$this->io->writeln('Skipped tag '.$tag.', '.($parsedTag ? 'no composer file was found' : 'invalid name')); $this->io->write('Skipped tag '.$tag.', '.($parsedTag ? 'no composer file was found' : 'invalid name'));
} }
} }
@ -144,7 +144,7 @@ class VcsRepository extends ArrayRepository
$data['version_normalized'] = $parsedBranch; $data['version_normalized'] = $parsedBranch;
} else { } else {
if ($debug) { if ($debug) {
$this->io->writeln('Skipped branch '.$branch.', invalid name and no composer file was found'); $this->io->write('Skipped branch '.$branch.', invalid name and no composer file was found');
} }
continue; continue;
} }
@ -158,7 +158,7 @@ class VcsRepository extends ArrayRepository
foreach ($this->getPackages() as $package) { foreach ($this->getPackages() as $package) {
if ($normalizedStableVersion === $package->getVersion()) { if ($normalizedStableVersion === $package->getVersion()) {
if ($debug) { if ($debug) {
$this->io->writeln('Skipped branch '.$branch.', already tagged'); $this->io->write('Skipped branch '.$branch.', already tagged');
} }
continue 2; continue 2;
@ -166,12 +166,12 @@ class VcsRepository extends ArrayRepository
} }
if ($debug) { if ($debug) {
$this->io->writeln('Importing branch '.$branch.' ('.$data['version_normalized'].')'); $this->io->write('Importing branch '.$branch.' ('.$data['version_normalized'].')');
} }
$this->addPackage($loader->load($this->preProcess($driver, $data, $identifier))); $this->addPackage($loader->load($this->preProcess($driver, $data, $identifier)));
} elseif ($debug) { } elseif ($debug) {
$this->io->writeln('Skipped branch '.$branch.', no composer file was found'); $this->io->write('Skipped branch '.$branch.', no composer file was found');
} }
} }