Merge origin/master

Conflicts:
	doc/03-cli.md
	doc/04-schema.md
	src/Composer/Factory.php
main
Nicolas Toniazzi 10 years ago
commit e6560c0462

@ -1,11 +1,27 @@
language: php
php:
php:
- 5.3.3
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
before_script: composer install
matrix:
allow_failures:
- php: hhvm
script: phpunit -c tests/complete.phpunit.xml
before_script:
- sudo apt-get install parallel
- rm -f ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini
- composer install --prefer-source
- bin/composer install --prefer-source
- git config --global user.name travis-ci
- git config --global user.email travis@example.com
script:
- ls -d tests/Composer/Test/* | parallel --gnu --keep-order 'echo "Running {} tests"; ./vendor/bin/phpunit -c tests/complete.phpunit.xml {};' || exit 1
git:
depth: 5

@ -1,4 +1,86 @@
* 1.0.0-alpha6 (2012-10-23)
### 1.0.0-alpha8 (2014-01-06)
* Break: The `install` command now has --dev enabled by default. --no-dev can be used to install without dev requirements
* Added `composer-plugin` package type to allow extensibility, and deprecated `composer-installer`
* Added `psr-4` autoloading support and deprecated `target-dir` since it is a better alternative
* Added --no-plugins flag to replace --no-custom-installers where available
* Added `global` command to operate Composer in a user-global directory
* Added `licenses` command to list the license of all your dependencies
* Added `pre-status-cmd` and `post-status-cmd` script events to the `status` command
* Added `post-root-package-install` and `post-create-project-cmd` script events to the `create-project` command
* Added `pre-autoload-dump` script event
* Added --rollback flag to self-update
* Added --no-install flag to create-project to skip installing the dependencies
* Added a `hhvm` platform package to require Facebook's HHVM implementation of PHP
* Added `github-domains` config option to allow using GitHub Enterprise with Composer's GitHub support
* Added `prepend-autoloader` config option to allow appending Composer's autoloader instead of the default prepend behavior
* Added Perforce support to the VCS repository
* Added a vendor/composer/autoload_files.php file that lists all files being included by the files autoloader
* Added support for the `no_proxy` env var and other proxy support improvements
* Added many robustness tweaks to make sure zip downloads work more consistently and corrupted caches are invalidated
* Added the release date to `composer -V` output
* Added `autoloader-suffix` config option to allow overriding the randomly generated autoloader class suffix
* Fixed BitBucket API usage
* Fixed parsing of inferred stability flags that are more stable than the minimum stability
* Fixed installation order of plugins/custom installers
* Fixed tilde and wildcard version constraints to be more intuitive regarding stabilities
* Fixed handling of target-dir changes when updating packages
* Improved performance of the class loader
* Improved memory usage and performance of solving dependencies
* Tons of minor bug fixes and improvements
### 1.0.0-alpha7 (2013-05-04)
* Break: For forward compatibility, you should change your deployment scripts to run `composer install --no-dev`. The install command will install dev dependencies by default starting in the next release
* Break: The `update` command now has --dev enabled by default. --no-dev can be used to update without dev requirements, but it will create an incomplete lock file and is discouraged
* Break: Removed support for lock files created before 2012-09-15 due to their outdated unusable format
* Added `prefer-stable` flag to pick stable packages over unstable ones when possible
* Added `preferred-install` config option to always enable --prefer-source or --prefer-dist
* Added `diagnose` command to to system/network checks and find common problems
* Added wildcard support in the update whitelist, e.g. to update all packages of a vendor do `composer update vendor/*`
* Added `archive` command to archive the current directory or a given package
* Added `run-script` command to manually trigger scripts
* Added `proprietary` as valid license identifier for non-free code
* Added a `php-64bit` platform package that you can require to force a 64bit php
* Added a `lib-ICU` platform package
* Added a new official package type `project` for project-bootstrapping packages
* Added zip/dist local cache to speed up repetitive installations
* Added `post-autoload-dump` script event
* Added `Event::getDevMode` to let script handlers know if dev requirements are being installed
* Added `discard-changes` config option to control the default behavior when updating "dirty" dependencies
* Added `use-include-path` config option to make the autoloader look for files in the include path too
* Added `cache-ttl`, `cache-files-ttl` and `cache-files-maxsize` config option
* Added `cache-dir`, `cache-files-dir`, `cache-repo-dir` and `cache-vcs-dir` config option
* Added support for using http(s) authentication to non-github repos
* Added support for using multiple autoloaders at once (e.g. PHPUnit + application both using Composer autoloader)
* Added support for .inc files for classmap autoloading (legacy support, do not do this on new projects!)
* Added support for version constraints in show command, e.g. `composer show monolog/monolog 1.4.*`
* Added support for svn repositories containing packages in a deeper path (see package-path option)
* Added an `artifact` repository to scan a directory containing zipped packages
* Added --no-dev flag to `install` and `update` commands
* Added --stability (-s) flag to create-project to lower the required stability
* Added --no-progress to `install` and `update` to hide the progress indicators
* Added --available (-a) flag to the `show` command to display only available packages
* Added --name-only (-N) flag to the `show` command to show only package names (one per line, no formatting)
* Added --optimize-autoloader (-o) flag to optimize the autoloader from the `install` and `update` commands
* Added -vv and -vvv flags to get more verbose output, can be useful to debug some issues
* Added COMPOSER_NO_INTERACTION env var to do the equivalent of --no-interaction (should be set on build boxes, CI, PaaS)
* Added PHP 5.2 compatibility to the autoloader configuration files so they can be used to configure another autoloader
* Fixed handling of platform requirements of the root package when installing from lock
* Fixed handling of require-dev dependencies
* Fixed handling of unstable packages that should be downgraded to stable packages when updating to new version constraints
* Fixed parsing of the `~` operator combined with unstable versions
* Fixed the `require` command corrupting the json if the new requirement was invalid
* Fixed support of aliases used together with `<version>#<reference>` constraints
* Improved output of dependency solver problems by grouping versions of a package together
* Improved performance of classmap generation
* Improved mercurial support in various places
* Improved lock file format to minimize unnecessary diffs
* Improved the `config` command to support all options
* Improved the coverage of the `validate` command
* Tons of minor bug fixes and improvements
### 1.0.0-alpha6 (2012-10-23)
* Schema: Added ability to pass additional options to repositories (i.e. ssh keys/client certificates to secure private repos)
* Schema: Added a new `~` operator that should be prefered over `>=`, see http://getcomposer.org/doc/01-basic-usage.md#package-versions
@ -23,7 +105,7 @@
* Improved performance of a few essential code paths
* Many bug small fixes and docs improvements
* 1.0.0-alpha5 (2012-08-18)
### 1.0.0-alpha5 (2012-08-18)
* Added `dump-autoload` command to only regenerate the autoloader
* Added --optimize to `dump-autoload` to generate a more performant classmap-based autoloader for production
@ -41,7 +123,7 @@
* Improved error reporting on network failures and some other edge cases
* Various minor bug fixes and docs improvements
* 1.0.0-alpha4 (2012-07-04)
### 1.0.0-alpha4 (2012-07-04)
* Break: The default `minimum-stability` is now `stable`, [read more](https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion)
* Break: Custom installers now receive the IO instance and a Composer instance in their constructor
@ -69,7 +151,7 @@
* Cleaned up / refactored the dependency solver code as well as the output for unsolvable requirements
* Various bug fixes and docs improvements
* 1.0.0-alpha3 (2012-05-13)
### 1.0.0-alpha3 (2012-05-13)
* Schema: Added `require-dev` for development-time requirements (tests, etc), install with --dev
* Schema: Added author.role to list the author's role in the project
@ -91,7 +173,7 @@
* Fixed various bugs relating to package aliasing, proxy configuration, binaries
* Various bug fixes and docs improvements
* 1.0.0-alpha2 (2012-04-03)
### 1.0.0-alpha2 (2012-04-03)
* Added `create-project` command to install a project from scratch with composer
* Added automated `classmap` autoloading support for non-PSR-0 compliant projects
@ -106,6 +188,6 @@
* Removed dependency on filter_var
* Various robustness & error handling improvements, docs fixes and more bug fixes
* 1.0.0-alpha1 (2012-03-01)
### 1.0.0-alpha1 (2012-03-01)
* Initial release

@ -1,7 +1,7 @@
Composer - Dependency Management for PHP
========================================
Composer is a dependency manager tracking local dependencies of your projects and libraries.
Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere.
See [https://getcomposer.org/](https://getcomposer.org/) for more information and documentation.
@ -13,13 +13,13 @@ Installation / Usage
1. Download the [`composer.phar`](https://getcomposer.org/composer.phar) executable or use the installer.
``` sh
$ curl -s https://getcomposer.org/installer | php
$ curl -sS https://getcomposer.org/installer | php
```
2. Create a composer.json defining your dependencies. Note that this example is
a short version for applications that are not meant to be published as packages
themselves. To create libraries/packages please read the [guidelines](https://packagist.org/about).
themselves. To create libraries/packages please read the
[documentation](http://getcomposer.org/doc/02-libraries.md).
``` json
{
@ -47,24 +47,7 @@ You can now run Composer by executing the `bin/composer` script: `php /path/to/c
Global installation of Composer (manual)
----------------------------------------
Since Composer works with the current working directory it is possible to install it
in a system wide way.
1. Change into a directory in your path like `cd /usr/local/bin`
2. Get Composer `curl -s https://getcomposer.org/installer | php`
3. Make the phar executable `chmod a+x composer.phar`
4. Change into a project directory `cd /path/to/my/project`
5. Use Composer as you normally would `composer.phar install`
6. Optionally you can rename the composer.phar to composer to make it easier
Global installation of Composer (via homebrew)
----------------------------------------------
Composer is part of the homebrew-php project.
1. Tap the homebrew-php repository into your brew installation if you haven't done yet: `brew tap josegonzalez/homebrew-php`
2. Run `brew install josegonzalez/php/composer`.
3. Use Composer with the `composer` command.
Follow instructions [in the documentation](http://getcomposer.org/doc/00-intro.md#globally)
Updating Composer
-----------------
@ -82,7 +65,7 @@ merged. This is to ensure proper review of all the code.
Fork the project, create a feature branch, and send us a pull request.
To ensure a consistent code base, you should make sure the code follows
the [Coding Standards](http://symfony.com/doc/2.0/contributing/code/standards.html)
the [Coding Standards](http://symfony.com/doc/current/contributing/code/standards.html)
which we borrowed from Symfony.
If you would like to help take a look at the [list of issues](http://github.com/composer/composer/issues).
@ -123,4 +106,4 @@ Acknowledgments
- This project's Solver started out as a PHP port of openSUSE's
[Libzypp satsolver](http://en.opensuse.org/openSUSE:Libzypp_satsolver).
- This project uses hiddeninput.exe to prompt for passwords on windows, sources
and details can be found on the [github page of the project](https://github.com/Seldaek/hidden-input).
and details can be found on the [github page of the project](https://github.com/Seldaek/hidden-input).

@ -8,5 +8,10 @@ use Composer\Compiler;
error_reporting(-1);
ini_set('display_errors', 1);
$compiler = new Compiler();
$compiler->compile();
try {
$compiler = new Compiler();
$compiler->compile();
} catch (\Exception $e) {
echo 'Failed to compile phar: ['.get_class($e).'] '.$e->getMessage().' at '.$e->getFile().':'.$e->getLine();
exit(1);
}

@ -1,6 +1,10 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli') {
echo 'Warning: Composer should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
}
require __DIR__.'/../src/bootstrap.php';
use Composer\Console\Application;
@ -16,8 +20,10 @@ if (function_exists('ini_set')) {
switch($unit) {
case 'g':
$value *= 1024;
// no break (cumulative multiplier)
case 'm':
$value *= 1024;
// no break (cumulative multiplier)
case 'k':
$value *= 1024;
}

@ -67,7 +67,7 @@ class JsonPrinter
$line = &$lines[0];
$last = count($array) - 1;
foreach ($array as $item => $code) {
$code = sprintf('"%s"%s', $code, $item === $last ? '' : ', ');
$code = sprintf('"%s"%s', trim($code), $item === $last ? '' : ', ');
$length = strlen($line) + strlen($code) - 1;
if ($length > 76) {
$line = rtrim($line);

@ -1,6 +1,6 @@
{
"name": "composer/composer",
"description": "Dependency Manager",
"description": "Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere.",
"keywords": ["package", "dependency", "autoload"],
"homepage": "http://getcomposer.org/",
"type": "library",
@ -23,11 +23,14 @@
},
"require": {
"php": ">=5.3.2",
"justinrainbow/json-schema": "1.1.*",
"justinrainbow/json-schema": "~1.1",
"seld/jsonlint": "1.*",
"symfony/console": "~2.1@dev",
"symfony/finder": "~2.1",
"symfony/process": "~2.1@dev"
"symfony/console": "~2.3",
"symfony/finder": "~2.2",
"symfony/process": "~2.1"
},
"require-dev": {
"phpunit/phpunit": "~3.7"
},
"suggest": {
"ext-zip": "Enabling the zip extension allows you to unzip archives, and allows gzip compression of all internet traffic",
@ -36,10 +39,16 @@
"autoload": {
"psr-0": { "Composer": "src/" }
},
"autoload-dev": {
"psr-0": { "Composer\\Test": "tests/" }
},
"bin": ["bin/composer"],
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"scripts": {
"test": "phpunit"
}
}

602
composer.lock generated

@ -1,60 +1,104 @@
{
"hash": "f13f9a6a377c842c36fda6109bbbc465",
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "eeb4afc3be46412ec15842ce4af01f0b",
"packages": [
{
"name": "justinrainbow/json-schema",
"version": "1.1.0",
"version": "1.3.7",
"source": {
"type": "git",
"url": "git://github.com/justinrainbow/json-schema.git",
"reference": "v1.1.0"
"url": "https://github.com/justinrainbow/json-schema.git",
"reference": "87b54b460febed69726c781ab67462084e97a105"
},
"dist": {
"type": "zip",
"url": "https://github.com/justinrainbow/json-schema/zipball/v1.1.0",
"reference": "v1.1.0",
"url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/87b54b460febed69726c781ab67462084e97a105",
"reference": "87b54b460febed69726c781ab67462084e97a105",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2012-01-02 21:33:17",
"require-dev": {
"json-schema/json-schema-test-suite": "1.1.0",
"phpdocumentor/phpdocumentor": "~2",
"phpunit/phpunit": "~3.7"
},
"bin": [
"bin/validate-json"
],
"type": "library",
"installation-source": "dist",
"extra": {
"branch-alias": {
"dev-master": "1.4.x-dev"
}
},
"autoload": {
"psr-0": {
"JsonSchema": "src/"
}
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Bruno Prieto Reis",
"email": "bruno.p.reis@gmail.com"
},
{
"name": "Justin Rainbow",
"email": "justin.rainbow@gmail.com"
},
{
"name": "Igor Wiedler",
"email": "igor@wiedler.ch"
},
{
"name": "Robert Schönthal",
"email": "seroscho@googlemail.com"
}
],
"description": "A library to validate a json schema.",
"homepage": "https://github.com/justinrainbow/json-schema",
"keywords": [
"json",
"schema"
],
"time": "2014-08-25 02:48:14"
},
{
"name": "seld/jsonlint",
"version": "1.0.1",
"version": "1.3.0",
"source": {
"type": "git",
"url": "http://github.com/Seldaek/jsonlint",
"reference": "1.0.1"
"url": "https://github.com/Seldaek/jsonlint.git",
"reference": "a7bc2ec9520ad15382292591b617c43bdb1fec35"
},
"dist": {
"type": "zip",
"url": "https://github.com/Seldaek/jsonlint/zipball/1.0.1",
"reference": "1.0.1",
"url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/a7bc2ec9520ad15382292591b617c43bdb1fec35",
"reference": "a7bc2ec9520ad15382292591b617c43bdb1fec35",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2012-08-13 07:00:11",
"bin": [
"bin/jsonlint"
],
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"Seld\\JsonLint": "src/"
"psr-4": {
"Seld\\JsonLint\\": "src/Seld/JsonLint/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
@ -62,167 +106,589 @@
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be",
"role": "Developer"
"homepage": "http://seld.be"
}
],
"description": "JSON Linter",
"keywords": [
"json",
"parser",
"linter",
"parser",
"validator"
]
],
"time": "2014-09-05 15:36:20"
},
{
"name": "symfony/console",
"version": "dev-master",
"version": "v2.5.4",
"target-dir": "Symfony/Component/Console",
"source": {
"type": "git",
"url": "https://github.com/symfony/Console",
"reference": "003a487a674175a1d2e62f205ecd91ffe85554b1"
"url": "https://github.com/symfony/Console.git",
"reference": "748beed2a1e73179c3f5154d33fe6ae100c1aeb1"
},
"dist": {
"type": "zip",
"url": "https://github.com/symfony/Console/archive/003a487a674175a1d2e62f205ecd91ffe85554b1.zip",
"reference": "003a487a674175a1d2e62f205ecd91ffe85554b1",
"url": "https://api.github.com/repos/symfony/Console/zipball/748beed2a1e73179c3f5154d33fe6ae100c1aeb1",
"reference": "748beed2a1e73179c3f5154d33fe6ae100c1aeb1",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"time": "2012-11-19 12:58:52",
"require-dev": {
"psr/log": "~1.0",
"symfony/event-dispatcher": "~2.1"
},
"suggest": {
"psr/log": "For using the console logger",
"symfony/event-dispatcher": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.5-dev"
}
},
"installation-source": "source",
"autoload": {
"psr-0": {
"Symfony\\Component\\Console\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"description": "Symfony Console Component",
"homepage": "http://symfony.com"
"homepage": "http://symfony.com",
"time": "2014-08-14 16:10:54"
},
{
"name": "symfony/finder",
"version": "v2.1.3",
"version": "v2.5.4",
"target-dir": "Symfony/Component/Finder",
"source": {
"type": "git",
"url": "https://github.com/symfony/Finder",
"reference": "v2.1.3"
"url": "https://github.com/symfony/Finder.git",
"reference": "f40854d1a19c339c7f969f8f6d6d6e9153311c4c"
},
"dist": {
"type": "zip",
"url": "https://github.com/symfony/Finder/zipball/v2.1.3",
"reference": "v2.1.3",
"url": "https://api.github.com/repos/symfony/Finder/zipball/f40854d1a19c339c7f969f8f6d6d6e9153311c4c",
"reference": "f40854d1a19c339c7f969f8f6d6d6e9153311c4c",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"time": "2012-10-20 00:10:30",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.1-dev"
"dev-master": "2.5-dev"
}
},
"installation-source": "source",
"autoload": {
"psr-0": {
"Symfony\\Component\\Finder": ""
"Symfony\\Component\\Finder\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"description": "Symfony Finder Component",
"homepage": "http://symfony.com"
"homepage": "http://symfony.com",
"time": "2014-09-03 09:00:14"
},
{
"name": "symfony/process",
"version": "dev-master",
"version": "v2.5.5",
"target-dir": "Symfony/Component/Process",
"source": {
"type": "git",
"url": "https://github.com/symfony/Process",
"reference": "a11b312f99a5a8bf88c0ea5e7660c13af79f964f"
"url": "https://github.com/symfony/Process.git",
"reference": "8a1ec96c4e519cee0fb971ea48a1eb7369dda54b"
},
"dist": {
"type": "zip",
"url": "https://github.com/symfony/Process/archive/a11b312f99a5a8bf88c0ea5e7660c13af79f964f.zip",
"reference": "a11b312f99a5a8bf88c0ea5e7660c13af79f964f",
"url": "https://api.github.com/repos/symfony/Process/zipball/8a1ec96c4e519cee0fb971ea48a1eb7369dda54b",
"reference": "8a1ec96c4e519cee0fb971ea48a1eb7369dda54b",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"time": "2012-11-13 14:08:04",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.5-dev"
}
},
"installation-source": "source",
"autoload": {
"psr-0": {
"Symfony\\Component\\Process\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
}
],
"description": "Symfony Process Component",
"homepage": "http://symfony.com",
"time": "2014-09-23 05:25:11"
}
],
"packages-dev": [
{
"name": "phpunit/php-code-coverage",
"version": "1.2.18",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b",
"reference": "fe2466802556d3fe4e4d1d58ffd3ccfd0a19be0b",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-file-iterator": ">=1.3.0@stable",
"phpunit/php-text-template": ">=1.2.0@stable",
"phpunit/php-token-stream": ">=1.1.3,<1.3.0"
},
"require-dev": {
"phpunit/phpunit": "3.7.*@dev"
},
"suggest": {
"ext-dom": "*",
"ext-xdebug": ">=2.0.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
}
},
"autoload": {
"classmap": [
"PHP/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.",
"homepage": "https://github.com/sebastianbergmann/php-code-coverage",
"keywords": [
"coverage",
"testing",
"xunit"
],
"time": "2014-09-02 10:13:14"
},
{
"name": "phpunit/php-file-iterator",
"version": "1.3.4",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"File/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "FilterIterator implementation that filters files based on a list of suffixes.",
"homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
"keywords": [
"filesystem",
"iterator"
],
"time": "2013-10-10 15:34:57"
},
{
"name": "phpunit/php-text-template",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-text-template.git",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"Text/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Simple template engine.",
"homepage": "https://github.com/sebastianbergmann/php-text-template/",
"keywords": [
"template"
],
"time": "2014-01-30 17:20:04"
},
{
"name": "phpunit/php-timer",
"version": "1.0.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-timer.git",
"reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/19689d4354b295ee3d8c54b4f42c3efb69cbc17c",
"reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"autoload": {
"classmap": [
"PHP/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Utility class for timing",
"homepage": "https://github.com/sebastianbergmann/php-timer/",
"keywords": [
"timer"
],
"time": "2013-08-02 07:42:54"
},
{
"name": "phpunit/php-token-stream",
"version": "1.2.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-token-stream.git",
"reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/ad4e1e23ae01b483c16f600ff1bebec184588e32",
"reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32",
"shasum": ""
},
"require": {
"ext-tokenizer": "*",
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2-dev"
}
},
"autoload": {
"classmap": [
"PHP/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Wrapper around PHP's tokenizer extension.",
"homepage": "https://github.com/sebastianbergmann/php-token-stream/",
"keywords": [
"tokenizer"
],
"time": "2014-03-03 05:10:30"
},
{
"name": "phpunit/phpunit",
"version": "3.7.37",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ae6cefd7cc84586a5ef27e04bae11ee940ec63dc",
"reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"ext-dom": "*",
"ext-json": "*",
"ext-pcre": "*",
"ext-reflection": "*",
"ext-spl": "*",
"php": ">=5.3.3",
"phpunit/php-code-coverage": "~1.2",
"phpunit/php-file-iterator": "~1.3",
"phpunit/php-text-template": "~1.1",
"phpunit/php-timer": "~1.0",
"phpunit/phpunit-mock-objects": "~1.2",
"symfony/yaml": "~2.0"
},
"require-dev": {
"pear-pear.php.net/pear": "1.9.4"
},
"suggest": {
"phpunit/php-invoker": "~1.1"
},
"bin": [
"composer/bin/phpunit"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.7.x-dev"
}
},
"autoload": {
"classmap": [
"PHPUnit/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
"",
"../../symfony/yaml/"
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "The PHP Unit Testing framework.",
"homepage": "http://www.phpunit.de/",
"keywords": [
"phpunit",
"testing",
"xunit"
],
"time": "2014-04-30 12:24:19"
},
{
"name": "phpunit/phpunit-mock-objects",
"version": "1.2.3",
"source": {
"type": "git",
"url": "git://github.com/sebastianbergmann/phpunit-mock-objects.git",
"reference": "1.2.3"
},
"dist": {
"type": "zip",
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects/archive/1.2.3.zip",
"reference": "1.2.3",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-text-template": ">=1.1.1@stable"
},
"suggest": {
"ext-soap": "*"
},
"type": "library",
"autoload": {
"classmap": [
"PHPUnit/"
]
},
"notification-url": "https://packagist.org/downloads/",
"include-path": [
""
],
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sb@sebastian-bergmann.de",
"role": "lead"
}
],
"description": "Mock Object library for PHPUnit",
"homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/",
"keywords": [
"mock",
"xunit"
],
"time": "2013-01-13 10:24:48"
},
{
"name": "symfony/yaml",
"version": "v2.5.4",
"target-dir": "Symfony/Component/Yaml",
"source": {
"type": "git",
"url": "https://github.com/symfony/Yaml.git",
"reference": "01a7695bcfb013d0a15c6757e15aae120342986f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/Yaml/zipball/01a7695bcfb013d0a15c6757e15aae120342986f",
"reference": "01a7695bcfb013d0a15c6757e15aae120342986f",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.5-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\Yaml\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"description": "Symfony Process Component",
"homepage": "http://symfony.com"
"description": "Symfony Yaml Component",
"homepage": "http://symfony.com",
"time": "2014-08-31 03:22:04"
}
],
"packages-dev": null,
"aliases": [
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {
"symfony/console": 20,
"symfony/process": 20
}
"stability-flags": [],
"prefer-stable": false,
"platform": {
"php": ">=5.3.2"
},
"platform-dev": []
}

@ -19,9 +19,9 @@ The problem that Composer solves is this:
a) You have a project that depends on a number of libraries.
b) Some of those libraries depend on other libraries .
b) Some of those libraries depend on other libraries.
c) You declare the things you depend on
c) You declare the things you depend on.
d) Composer finds out which versions of which packages need to be installed, and
installs them (meaning it downloads them into your project).
@ -33,15 +33,29 @@ You decide to use [monolog](https://github.com/Seldaek/monolog). In order to
add it to your project, all you need to do is create a `composer.json` file
which describes the project's dependencies.
{
"require": {
"monolog/monolog": "1.2.*"
}
```json
{
"require": {
"monolog/monolog": "1.2.*"
}
}
```
We are simply stating that our project requires some `monolog/monolog` package,
any version beginning with `1.2`.
## System Requirements
Composer requires PHP 5.3.2+ to run. A few sensitive php settings and compile
flags are also required, but the installer will warn you about any
incompatibilities.
To install packages from sources instead of simple zip archives, you will need
git, svn or hg depending on how the package is version-controlled.
Composer is multi-platform and we strive to make it run equally well on Windows,
Linux and OSX.
## Installation - *nix
### Downloading the Composer Executable
@ -51,7 +65,16 @@ any version beginning with `1.2`.
To actually get Composer, we need to do two things. The first one is installing
Composer (again, this means downloading it into your project):
$ curl -s https://getcomposer.org/installer | php
```sh
curl -sS https://getcomposer.org/installer | php
```
> **Note:** If the above fails for some reason, you can download the installer
> with `php` instead:
```sh
php -r "readfile('https://getcomposer.org/installer');" | php
```
This will just check a few PHP settings and then download `composer.phar` to
your working directory. This file is the Composer binary. It is a PHAR (PHP
@ -61,7 +84,9 @@ line, amongst other things.
You can install Composer to a specific directory by using the `--install-dir`
option and providing a target directory (it can be an absolute or relative path):
$ curl -s https://getcomposer.org/installer | php -- --install-dir=bin
```sh
curl -sS https://getcomposer.org/installer | php -- --install-dir=bin
```
#### Globally
@ -71,11 +96,27 @@ executable and invoke it without `php`.
You can run these commands to easily access `composer` from anywhere on your system:
$ curl -s https://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer
```sh
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
```
> **Note:** If the above fails due to permissions, run the `mv` line
> again with sudo.
Then, just run `composer` in order to run Composer instead of `php composer.phar`.
#### Globally (on OSX via homebrew)
Composer is part of the homebrew-php project.
```sh
brew update
brew tap homebrew/dupes
brew tap homebrew/php
brew install composer
```
## Installation - Windows
### Using the Installer
@ -91,38 +132,47 @@ just call `composer` from any directory in your command line.
Change to a directory on your `PATH` and run the install snippet to download
composer.phar:
C:\Users\username>cd C:\bin
C:\bin>php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
```sh
C:\Users\username>cd C:\bin
C:\bin>php -r "readfile('https://getcomposer.org/installer');" | php
```
Create a new `.bat` file alongside composer:
> **Note:** If the above fails due to readfile, use the `http` url or enable php_openssl.dll in php.ini
C:\bin>notepad composer.bat
Create a new `composer.bat` file alongside `composer.phar`:
Paste the following in, it simply proxies all arguments to composer:
```sh
C:\bin>echo @php "%~dp0composer.phar" %*>composer.bat
```
@ECHO OFF
SET composerScript=composer.phar
php "%~dp0%composerScript%" %*
Close your current terminal. Test usage with a new terminal:
Save the file. Close your current terminal. Test usage with a new terminal:
C:\Users\username>composer -V
Composer version 27d8904
C:\Users\username>
```sh
C:\Users\username>composer -V
Composer version 27d8904
```
## Using Composer
Next, run the `install` command to resolve and download dependencies:
We will now use Composer to install the dependencies of the project. If you
don't have a `composer.json` file in the current directory please skip to the
[Basic Usage](01-basic-usage.md) chapter.
To resolve and download dependencies, run the `install` command:
$ php composer.phar install
```sh
php composer.phar install
```
If you did a global install and do not have the phar in that directory
run this instead:
$ composer install
```sh
composer install
```
This will download monolog into the `vendor/monolog/monolog` directory.
Following the [example above](#declaring-dependencies), this will download
monolog into the `vendor/monolog/monolog` directory.
## Autoloading
@ -131,9 +181,11 @@ capable of autoloading all of the classes in any of the libraries that it
downloads. To use it, just add the following line to your code's bootstrap
process:
require 'vendor/autoload.php';
```php
require 'vendor/autoload.php';
```
Woh! Now start using monolog! To keep learning more about Composer, keep
Woah! Now start using monolog! To keep learning more about Composer, keep
reading the "Basic Usage" chapter.
[Basic Usage](01-basic-usage.md) &rarr;

@ -4,20 +4,26 @@
To install Composer, you just need to download the `composer.phar` executable.
$ curl -s https://getcomposer.org/installer | php
```sh
curl -sS https://getcomposer.org/installer | php
```
For the details, see the [Introduction](00-intro.md) chapter.
To check if Composer is working, just run the PHAR through `php`:
$ php composer.phar
```sh
php composer.phar
```
This should give you a list of available commands.
> **Note:** You can also perform the checks only without downloading Composer
> by using the `--check` option. For more information, just use `--help`.
>
> $ curl -s https://getcomposer.org/installer | php -- --help
> ```sh
> curl -sS https://getcomposer.org/installer | php -- --help
> ```
## `composer.json`: Project Setup
@ -34,11 +40,13 @@ The first (and often only) thing you specify in `composer.json` is the
`require` key. You're simply telling Composer which packages your project
depends on.
{
"require": {
"monolog/monolog": "1.0.*"
}
```json
{
"require": {
"monolog/monolog": "1.0.*"
}
}
```
As you can see, `require` takes an object that maps **package names** (e.g. `monolog/monolog`)
to **package versions** (e.g. `1.0.*`).
@ -58,28 +66,40 @@ smaller decoupled parts.
### Package Versions
We are requiring version `1.0.*` of monolog. This means any version in the `1.0`
development branch. It would match `1.0.0`, `1.0.2` or `1.0.20`.
In the previous example we were requiring version `1.0.*` of monolog. This
means any version in the `1.0` development branch. It would match `1.0.0`,
`1.0.2` or `1.0.20`.
Version constraints can be specified in a few different ways.
* **Exact version:** You can specify the exact version of a package, for
example `1.0.2`.
Name | Example | Description
-------------- | ------------------------------------------------------------------ | -----------
Exact version | `1.0.2` | You can specify the exact version of a package.
Range | `>=1.0` `>=1.0,<2.0` <code>&gt;=1.0,&lt;1.1 &#124; &gt;=1.2</code> | By using comparison operators you can specify ranges of valid versions. Valid operators are `>`, `>=`, `<`, `<=`, `!=`. <br />You can define multiple ranges. Ranges separated by a comma (`,`) will be treated as a **logical AND**. A pipe (<code>&#124;</code>) will be treated as a **logical OR**. AND has higher precedence than OR.
Wildcard | `1.0.*` | You can specify a pattern with a `*` wildcard. `1.0.*` is the equivalent of `>=1.0,<1.1`.
Tilde Operator | `~1.2` | Very useful for projects that follow semantic versioning. `~1.2` is equivalent to `>=1.2,<2.0`. For more details, read the next section below.
* **Range:** By using comparison operators you can specify ranges of valid
versions. Valid operators are `>`, `>=`, `<`, `<=`, `!=`. An example range
would be `>=1.0`. You can define multiple ranges, separated by a comma:
`>=1.0,<2.0`.
### Next Significant Release (Tilde Operator)
* **Wildcard:** You can specify a pattern with a `*` wildcard. `1.0.*` is the
equivalent of `>=1.0,<1.1`.
The `~` operator is best explained by example: `~1.2` is equivalent to
`>=1.2,<2.0`, while `~1.2.3` is equivalent to `>=1.2.3,<1.3`. As you can see
it is mostly useful for projects respecting [semantic
versioning](http://semver.org/). A common usage would be to mark the minimum
minor version you depend on, like `~1.2` (which allows anything up to, but not
including, 2.0). Since in theory there should be no backwards compatibility
breaks until 2.0, that works well. Another way of looking at it is that using
`~` specifies a minimum version, but allows the last digit specified to go up.
* **Next Significant Release (Tilde Operator):** The `~` operator is best
explained by example: `~1.2` is equivalent to `>=1.2,<2.0`, while `~1.2.3` is
equivalent to `>=1.2.3,<1.3`. As you can see it is mostly useful for projects
respecting semantic versioning. A common usage would be to mark the minimum
minor version you depend on, like `~1.2`, since in theory there should be no
backwards compatibility breaks until 2.0, that works well.
> **Note:** Though `2.0-beta.1` is strictly before `2.0`, a version constraint
> like `~1.2` would not install it. As said above `~1.2` only means the `.2`
> can change but the `1.` part is fixed.
> **Note:** The `~` operator has an exception on its behavior for the major
> release number. This means for example that `~1` is the same as `~1.0` as
> it will not allow the major number to increase trying to keep backwards
> compatibility.
### Stability
By default only stable releases are taken into consideration. If you would like
to also get RC, beta, alpha or dev versions of your dependencies you can do
@ -92,7 +112,9 @@ packages instead of doing per dependency you can also use the
To fetch the defined dependencies into your local project, just run the
`install` command of `composer.phar`.
$ php composer.phar install
```sh
php composer.phar install
```
This will find the latest version of `monolog/monolog` that matches the
supplied version constraint and download it into the `vendor` directory.
@ -116,18 +138,36 @@ to those specific versions.
This is important because the `install` command checks if a lock file is present,
and if it is, it downloads the versions specified there (regardless of what `composer.json`
says). This means that anyone who sets up the project will download the exact
same version of the dependencies.
says).
This means that anyone who sets up the project will download the exact
same version of the dependencies. Your CI server, production machines, other
developers in your team, everything and everyone runs on the same dependencies, which
mitigates the potential for bugs affecting only some parts of the deployments. Even if you
develop alone, in six months when reinstalling the project you can feel confident the
dependencies installed are still working even if your dependencies released
many new versions since then.
If no `composer.lock` file exists, Composer will read the dependencies and
versions from `composer.json` and create the lock file.
versions from `composer.json` and create the lock file after executing the `update` or the `install`
command.
This means that if any of the dependencies get a new version, you won't get the updates
automatically. To update to the new version, use `update` command. This will fetch
the latest matching versions (according to your `composer.json` file) and also update
the lock file with the new version.
$ php composer.phar update
```sh
php composer.phar update
```
> **Note:** Composer will display a Warning when executing an `install` command if
`composer.lock` and `composer.json` are not synchronized.
If you only want to install or update one dependency, you can whitelist them:
```sh
php composer.phar update monolog/monolog [...]
```
> **Note:** For libraries it is not necessarily recommended to commit the lock file,
> see also: [Libraries - Lock file](02-libraries.md#lock-file).
@ -153,33 +193,38 @@ For libraries that specify autoload information, Composer generates a
`vendor/autoload.php` file. You can simply include this file and you
will get autoloading for free.
require 'vendor/autoload.php';
```php
require 'vendor/autoload.php';
```
This makes it really easy to use third party code. For example: If your
project depends on monolog, you can just start using classes from it, and they
will be autoloaded.
$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));
```php
$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));
$log->addWarning('Foo');
$log->addWarning('Foo');
```
You can even add your own code to the autoloader by adding an `autoload` field
to `composer.json`.
{
"autoload": {
"psr-0": {"Acme": "src/"}
}
```json
{
"autoload": {
"psr-4": {"Acme\\": "src/"}
}
}
```
Composer will register a
[PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md)
autoloader for the `Acme` namespace.
Composer will register a [PSR-4](http://www.php-fig.org/psr/psr-4/) autoloader
for the `Acme` namespace.
You define a mapping from namespaces to directories. The `src` directory would
be in your project root, on the same level as `vendor` directory is. An example
filename would be `src/Acme/Foo.php` containing an `Acme\Foo` class.
filename would be `src/Foo.php` containing an `Acme\Foo` class.
After adding the `autoload` field, you have to re-run `install` to re-generate
the `vendor/autoload.php` file.
@ -188,15 +233,17 @@ Including that file will also return the autoloader instance, so you can store
the return value of the include call in a variable and add more namespaces.
This can be useful for autoloading classes in a test suite, for example.
$loader = require 'vendor/autoload.php';
$loader->add('Acme\Test', __DIR__);
```php
$loader = require 'vendor/autoload.php';
$loader->add('Acme\\Test\\', __DIR__);
```
In addition to PSR-0 autoloading, classmap is also supported. This allows
classes to be autoloaded even if they do not conform to PSR-0. See the
In addition to PSR-4 autoloading, classmap is also supported. This allows
classes to be autoloaded even if they do not conform to PSR-4. See the
[autoload reference](04-schema.md#autoload) for more details.
> **Note:** Composer provides its own autoloader. If you don't want to use
that one, you can just include `vendor/composer/autoload_namespaces.php`,
which returns an associative array mapping namespaces to directories.
that one, you can just include `vendor/composer/autoload_*.php` files,
which return associative arrays allowing you to configure your own autoloader.
&larr; [Intro](00-intro.md) | [Libraries](02-libraries.md) &rarr;

@ -1,6 +1,6 @@
# Libraries
This chapter will tell you how to make your library installable through composer.
This chapter will tell you how to make your library installable through Composer.
## Every project is a package
@ -12,12 +12,14 @@ libraries is that your project is a package without a name.
In order to make that package installable you need to give it a name. You do
this by adding a `name` to `composer.json`:
{
"name": "acme/hello-world",
"require": {
"monolog/monolog": "1.0.*"
}
```json
{
"name": "acme/hello-world",
"require": {
"monolog/monolog": "1.0.*"
}
}
```
In this case the project name is `acme/hello-world`, where `acme` is the
vendor name. Supplying a vendor name is mandatory.
@ -29,11 +31,15 @@ convention is all lowercase and dashes for word separation.
## Platform packages
Composer has platform packages, which are virtual packages for things that are
installed on the system but are not actually installable by composer. This
installed on the system but are not actually installable by Composer. This
includes PHP itself, PHP extensions and some system libraries.
* `php` represents the PHP version of the user, allowing you to apply
constraints, e.g. `>=5.4.0`.
constraints, e.g. `>=5.4.0`. To require a 64bit version of php, you can
require the `php-64bit` package.
* `hhvm` represents the version of the HHVM runtime (aka HipHop Virtual
Machine) and allows you to apply a constraint, e.g., '>=2.3.3'.
* `ext-<name>` allows you to require PHP extensions (includes core
extensions). Versioning can be quite inconsistent here, so it's often
@ -41,8 +47,8 @@ includes PHP itself, PHP extensions and some system libraries.
package name is `ext-gd`.
* `lib-<name>` allows constraints to be made on versions of libraries used by
PHP. The following are available: `curl`, `iconv`, `libxml`, `openssl`,
`pcre`, `uuid`, `xsl`.
PHP. The following are available: `curl`, `iconv`, `icu`, `libxml`,
`openssl`, `pcre`, `uuid`, `xsl`.
You can use `composer show --platform` to get a list of your locally available
platform packages.
@ -58,26 +64,34 @@ version numbers are extracted from these.
If you are creating packages by hand and really have to specify it explicitly,
you can just add a `version` field:
{
"version": "1.0.0"
}
```json
{
"version": "1.0.0"
}
```
> **Note:** You should avoid specifying the version field explicitly, because
> for tags the value must match the tag name.
### Tags
For every tag that looks like a version, a package version of that tag will be
created. It should match 'X.Y.Z' or 'vX.Y.Z', with an optional suffix for RC,
beta, alpha or patch.
created. It should match 'X.Y.Z' or 'vX.Y.Z', with an optional suffix
of `-patch`, `-alpha`, `-beta` or `-RC`. The suffixes can also be followed by
a number.
Here are a few examples of valid tag names:
1.0.0
v1.0.0
1.10.5-RC1
v4.4.4beta2
v2.0.0-alpha
v2.0.4-p1
- 1.0.0
- v1.0.0
- 1.10.5-RC1
- v4.4.4-beta2
- v2.0.0-alpha
- v2.0.4-p1
> **Note:** If you specify an explicit version in `composer.json`, the tag name must match the specified version.
> **Note:** Even if your tag is prefixed with `v`, a [version constraint](01-basic-usage.md#package-versions)
> in a `require` statement has to be specified without prefix
> (e.g. tag `v1.0.0` will result in version `1.0.0`).
### Branches
@ -91,15 +105,17 @@ like a version, it will be `dev-{branchname}`. `master` results in a
Here are some examples of version branch names:
1.x
1.0 (equals 1.0.x)
1.1.x
- 1.x
- 1.0 (equals 1.0.x)
- 1.1.x
> **Note:** When you install a dev version, it will install it from source.
> **Note:** When you install a development version, it will be automatically
> pulled from its `source`. See the [`install`](03-cli.md#install) command
> for more details.
### Aliases
It is possible alias branch names to versions. For example, you could alias
It is possible to alias branch names to versions. For example, you could alias
`dev-master` to `1.0.x-dev`, which would allow you to require `1.0.x-dev` in all
the packages.
@ -115,52 +131,27 @@ on it. It only has an effect on the main project.
If you do not want to commit the lock file and you are using git, add it to
the `.gitignore`.
## Light-weight distribution packages
Including the tests and other useless information like `.travis.yml` in
distributed packages is not a good idea.
The `.gitattributes` file is a git specific file like `.gitignore` also living
at the root directory of your library. It overrides local and global
configuration (`.git/config` and `~/.gitconfig` respectively) when present and
tracked by git.
Use `.gitattributes` to prevent unwanted files from bloating the zip
distribution packages.
// .gitattributes
/Tests export-ignore
phpunit.xml.dist export-ignore
Resources/doc/ export-ignore
.travis.yml export-ignore
Test it by inspecting the zip file generated manually:
git archive branchName --format zip -o file.zip
> **Note:** Files would be still tracked by git just not included in the
> distribution. This will only work for GitHub packages installed from
> dist (i.e. tagged releases) for now.
## Publishing to a VCS
Once you have a vcs repository (version control system, e.g. git) containing a
`composer.json` file, your library is already composer-installable. In this
example we will publish the `acme/hello-world` library on GitHub under
`github.com/composer/hello-world`.
`github.com/username/hello-world`.
Now, To test installing the `acme/hello-world` package, we create a new
Now, to test installing the `acme/hello-world` package, we create a new
project locally. We will call it `acme/blog`. This blog will depend on
`acme/hello-world`, which in turn depends on `monolog/monolog`. We can
accomplish this by creating a new `blog` directory somewhere, containing a
`composer.json`:
{
"name": "acme/blog",
"require": {
"acme/hello-world": "dev-master"
}
```json
{
"name": "acme/blog",
"require": {
"acme/hello-world": "dev-master"
}
}
```
The name is not needed in this case, since we don't want to publish the blog
as a library. It is added here to clarify which `composer.json` is being
@ -170,23 +161,25 @@ Now we need to tell the blog app where to find the `hello-world` dependency.
We do this by adding a package repository specification to the blog's
`composer.json`:
{
"name": "acme/blog",
"repositories": [
{
"type": "vcs",
"url": "https://github.com/composer/hello-world"
}
],
"require": {
"acme/hello-world": "dev-master"
```json
{
"name": "acme/blog",
"repositories": [
{
"type": "vcs",
"url": "https://github.com/username/hello-world"
}
],
"require": {
"acme/hello-world": "dev-master"
}
}
```
For more details on how package repositories work and what other types are
available, see [Repositories](05-repositories.md).
That's all. You can now install the dependencies by running composer's
That's all. You can now install the dependencies by running Composer's
`install` command!
**Recap:** Any git/svn/hg repository containing a `composer.json` can be added
@ -202,8 +195,8 @@ The other thing that you may have noticed is that we did not specify a package
repository for `monolog/monolog`. How did that work? The answer is packagist.
[Packagist](https://packagist.org/) is the main package repository for
composer, and it is enabled by default. Anything that is published on
packagist is available automatically through composer. Since monolog
Composer, and it is enabled by default. Anything that is published on
packagist is available automatically through Composer. Since monolog
[is on packagist](https://packagist.org/packages/monolog/monolog), we can depend
on it without having to specify any additional repositories.

@ -1,4 +1,4 @@
# Command-line interface
# Command-line interface / Commands
You've already learned how to use the command-line interface to do some
things. This chapter documents all the available commands.
@ -21,6 +21,12 @@ The following options are available with every command:
* **--no-ansi:** Disable ANSI output.
* **--version (-V):** Display this application version.
## Process Exit Codes
* **0:** OK
* **1:** Generic/unknown error code
* **2:** Dependency solving error code
## init
In the [Libraries](02-libraries.md) chapter we looked at how to create a
@ -30,7 +36,9 @@ it a bit easier to do this.
When you run the command it will interactively ask you to fill in the fields,
while using some smart defaults.
$ php composer.phar init
```sh
php composer.phar init
```
### Options
@ -48,7 +56,9 @@ while using some smart defaults.
The `install` command reads the `composer.json` file from the current
directory, resolves the dependencies, and installs them into `vendor`.
$ php composer.phar install
```sh
php composer.phar install
```
If there is a `composer.lock` file in the current directory, it will use the
exact versions from there instead of resolving them. This ensures that
@ -73,14 +83,13 @@ resolution.
* **--dry-run:** If you want to run through an installation without actually
installing a package, you can use `--dry-run`. This will simulate the
installation and show you what would happen.
* **--dev:** By default composer will only install required packages. By
passing this option you can also make it install packages referenced by
`require-dev`.
* **--dev:** Install packages listed in `require-dev` (this is the default behavior).
* **--no-dev:** Skip installing packages listed in `require-dev`.
* **--no-scripts:** Skips execution of scripts defined in `composer.json`.
* **--no-custom-installers:** Disables custom installers.
* **--no-plugins:** Disables plugins.
* **--no-progress:** Removes the progress display that can mess with some
terminals or scripts which don't handle backspace characters.
* **--optimize-autoloader (-o):** Convert PSR-0 autoloading to classmap to get a faster
* **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster
autoloader. This is recommended especially for production, but can take
a bit of time to run so it is currently not done by default.
@ -89,39 +98,52 @@ resolution.
In order to get the latest versions of the dependencies and to update the
`composer.lock` file, you should use the `update` command.
$ php composer.phar update
```sh
php composer.phar update
```
This will resolve all dependencies of the project and write the exact versions
into `composer.lock`.
If you just want to update a few packages and not all, you can list them as such:
$ php composer.phar update vendor/package vendor/package2
```sh
php composer.phar update vendor/package vendor/package2
```
You can also use wildcards to update a bunch of packages at once:
$ php composer.phar update vendor/*
```sh
php composer.phar update vendor/*
```
### Options
* **--prefer-source:** Install packages from `source` when available.
* **--prefer-dist:** Install packages from `dist` when available.
* **--dry-run:** Simulate the command without actually doing anything.
* **--dev:** Install packages listed in `require-dev`.
* **--dev:** Install packages listed in `require-dev` (this is the default behavior).
* **--no-dev:** Skip installing packages listed in `require-dev`.
* **--no-scripts:** Skips execution of scripts defined in `composer.json`.
* **--no-custom-installers:** Disables custom installers.
* **--no-plugins:** Disables plugins.
* **--no-progress:** Removes the progress display that can mess with some
terminals or scripts which don't handle backspace characters.
* **--optimize-autoloader (-o):** Convert PSR-0 autoloading to classmap to get a faster
* **--optimize-autoloader (-o):** Convert PSR-0/4 autoloading to classmap to get a faster
autoloader. This is recommended especially for production, but can take
a bit of time to run so it is currently not done by default.
* **--lock:** Only updates the lock file hash to suppress warning about the
lock file being out of date.
* **--with-dependencies** Add also all dependencies of whitelisted packages to the whitelist.
So all packages with their dependencies are updated recursively.
## require
The `require` command adds new packages to the `composer.json` file from
the current directory.
the current directory. If no file exists one will be created on the fly.
$ php composer.phar require
```sh
php composer.phar require
```
After adding/changing the requirements, the modified requirements will be
installed or updated.
@ -129,7 +151,9 @@ installed or updated.
If you do not want to choose requirements interactively, you can just pass them
to the command.
$ php composer.phar require vendor/package:2.* vendor/package2:dev-master
```sh
php composer.phar require vendor/package:2.* vendor/package2:dev-master
```
### Options
@ -139,6 +163,51 @@ to the command.
* **--no-update:** Disables the automatic update of the dependencies.
* **--no-progress:** Removes the progress display that can mess with some
terminals or scripts which don't handle backspace characters.
* **--update-no-dev** Run the dependency update with the --no-dev option.
* **--update-with-dependencies** Also update dependencies of the newly
required packages.
## remove
The `remove` command removes packages from the `composer.json` file from
the current directory.
```sh
php composer.phar remove vendor/package vendor/package2
```
After removing the requirements, the modified requirements will be
uninstalled.
### Options
* **--dev:** Remove packages from `require-dev`.
* **--no-update:** Disables the automatic update of the dependencies.
* **--no-progress:** Removes the progress display that can mess with some
terminals or scripts which don't handle backspace characters.
* **--update-no-dev** Run the dependency update with the --no-dev option.
* **--update-with-dependencies** Also update dependencies of the removed packages.
## global
The global command allows you to run other commands like `install`, `require`
or `update` as if you were running them from the [COMPOSER_HOME](#composer-home)
directory.
This can be used to install CLI utilities globally and if you add
`$COMPOSER_HOME/vendor/bin` to your `$PATH` environment variable. Here is an
example:
```sh
php composer.phar global require fabpot/php-cs-fixer:dev-master
```
Now the `php-cs-fixer` binary is available globally (assuming you adjusted
your PATH). If you wish to update the binary later on you can just run a
global update:
```sh
php composer.phar global update
```
## search
@ -146,7 +215,9 @@ The search command allows you to search through the current project's package
repositories. Usually this will be just packagist. You simply pass it the
terms you want to search for.
$ php composer.phar search monolog
```sh
php composer.phar search monolog
```
You can also search for more than one term by passing multiple arguments.
@ -158,39 +229,53 @@ You can also search for more than one term by passing multiple arguments.
To list all of the available packages, you can use the `show` command.
$ php composer.phar show
```sh
php composer.phar show
```
If you want to see the details of a certain package, you can pass the package
name.
$ php composer.phar show monolog/monolog
```sh
php composer.phar show monolog/monolog
name : monolog/monolog
versions : master-dev, 1.0.2, 1.0.1, 1.0.0, 1.0.0-RC1
type : library
names : monolog/monolog
source : [git] http://github.com/Seldaek/monolog.git 3d4e60d0cbc4b888fe5ad223d77964428b1978da
dist : [zip] http://github.com/Seldaek/monolog/zipball/3d4e60d0cbc4b888fe5ad223d77964428b1978da 3d4e60d0cbc4b888fe5ad223d77964428b1978da
license : MIT
name : monolog/monolog
versions : master-dev, 1.0.2, 1.0.1, 1.0.0, 1.0.0-RC1
type : library
names : monolog/monolog
source : [git] http://github.com/Seldaek/monolog.git 3d4e60d0cbc4b888fe5ad223d77964428b1978da
dist : [zip] http://github.com/Seldaek/monolog/zipball/3d4e60d0cbc4b888fe5ad223d77964428b1978da 3d4e60d0cbc4b888fe5ad223d77964428b1978da
license : MIT
autoload
psr-0
Monolog : src/
autoload
psr-0
Monolog : src/
requires
php >=5.3.0
requires
php >=5.3.0
```
You can even pass the package version, which will tell you the details of that
specific version.
$ php composer.phar show monolog/monolog 1.0.2
```sh
php composer.phar show monolog/monolog 1.0.2
```
### Options
* **--installed (-i):** List the packages that are installed.
* **--platform (-p):** List only platform packages (php & extensions).
* **--self (-s):** List the root package info.
* **--dev:** Include dev-required packages when combined with **--installed** or **--platform**.
## browse / home
The `browse` (aliased to `home`) opens a package's repository URL or homepage
in your browser.
### Options
* **--homepage (-H):** Open the homepage instead of the repository URL.
## depends
@ -198,13 +283,15 @@ The `depends` command tells you which other packages depend on a certain
package. You can specify which link types (`require`, `require-dev`)
should be included in the listing. By default both are used.
$ php composer.phar depends --link-type=require monolog/monolog
```sh
php composer.phar depends --link-type=require monolog/monolog
nrk/monolog-fluent
poc/poc
propel/propel
symfony/monolog-bridge
symfony/symfony
nrk/monolog-fluent
poc/poc
propel/propel
symfony/monolog-bridge
symfony/symfony
```
### Options
@ -217,7 +304,13 @@ You should always run the `validate` command before you commit your
`composer.json` file, and before you tag a release. It will check if your
`composer.json` is valid.
$ php composer.phar validate
```sh
php composer.phar validate
```
### Options
* **--no-check-all:** Wether or not composer do a complete validation.
## status
@ -225,34 +318,56 @@ If you often need to modify the code of your dependencies and they are
installed from source, the `status` command allows you to check if you have
local changes in any of them.
$ php composer.phar status
```sh
php composer.phar status
```
With the `--verbose` option you get some more information about what was
changed:
$ php composer.phar status -v
You have changes in the following dependencies:
vendor/seld/jsonlint:
M README.mdown
```sh
php composer.phar status -v
You have changes in the following dependencies:
vendor/seld/jsonlint:
M README.mdown
```
## self-update
To update composer itself to the latest version, just run the `self-update`
command. It will replace your `composer.phar` with the latest version.
$ php composer.phar self-update
```sh
php composer.phar self-update
```
If you would like to instead update to a specific release simply specify it:
```sh
php composer.phar self-update 1.0.0-alpha7
```
If you have installed composer for your entire system (see [global installation](00-intro.md#globally)),
you have to run the command with `root` privileges
you may have to run the command with `root` privileges
$ sudo composer self-update
```sh
sudo composer self-update
```
### Options
* **--rollback (-r):** Rollback to the last version you had installed.
* **--clean-backups:** Delete old backups during an update. This makes the current version of composer the only backup available after the update.
## config
The `config` command allows you to edit some basic composer settings in either
the local composer.json file or the global config.json file.
$ php composer.phar config --list
```sh
php composer.phar config --list
```
### Usage
@ -262,7 +377,7 @@ the local composer.json file or the global config.json file.
configuration value. For settings that can take an array of values (like
`github-protocols`), more than one setting-value arguments are allowed.
See the [config schema section](04-schema.md#config-root-only) for valid configuration
See the [config schema section](04-schema.md#config) for valid configuration
options.
### Options
@ -284,7 +399,9 @@ the global config file.
In addition to modifying the config section, the `config` command also supports making
changes to the repositories section by using it the following way:
$ php composer.phar config repositories.foo vcs http://github.com/foo/bar
```sh
php composer.phar config repositories.foo vcs http://github.com/foo/bar
```
## create-project
@ -303,9 +420,14 @@ To create a new project using composer you can use the "create-project" command.
Pass it a package name, and the directory to create the project in. You can also
provide a version as third argument, otherwise the latest version is used.
The directory is not allowed to exist, it will be created during installation.
If the directory does not currently exist, it will be created during installation.
```sh
php composer.phar create-project doctrine/orm path 2.2.*
```
php composer.phar create-project doctrine/orm path 2.2.0
It is also possible to run the command without params in a directory with an
existing `composer.json` file to bootstrap a project.
By default the command checks for the packages on packagist.org.
@ -318,7 +440,8 @@ By default the command checks for the packages on packagist.org.
* **--prefer-source:** Install packages from `source` when available.
* **--prefer-dist:** Install packages from `dist` when available.
* **--dev:** Install packages listed in `require-dev`.
* **--no-custom-installers:** Disables custom installers.
* **--no-install:** Disables installation of the vendors.
* **--no-plugins:** Disables plugins.
* **--no-scripts:** Disables the execution of the scripts defined in the root
package.
* **--no-progress:** Removes the progress display that can mess with some
@ -333,31 +456,70 @@ If you need to update the autoloader because of new classes in a classmap
package for example, you can use "dump-autoload" to do that without having to
go through an install or update.
Additionally, it can dump an optimized autoloader that converts PSR-0 packages
Additionally, it can dump an optimized autoloader that converts PSR-0/4 packages
into classmap ones for performance reasons. In large applications with many
classes, the autoloader can take up a substantial portion of every request's
time. Using classmaps for everything is less convenient in development, but
using this option you can still use PSR-0 for convenience and classmaps for
using this option you can still use PSR-0/4 for convenience and classmaps for
performance.
### Options
* **--optimize (-o):** Convert PSR-0 autoloading to classmap to get a faster
* **--optimize (-o):** Convert PSR-0/4 autoloading to classmap to get a faster
autoloader. This is recommended especially for production, but can take
a bit of time to run so it is currently not done by default.
* **--no-dev:** Disables autoload-dev rules.
## licenses
Lists the name, version and license of every package installed. Use
`--format=json` to get machine readable output.
## run-script
To run [scripts](articles/scripts.md) manually you can use this command,
just give it the script name and optionally --no-dev to disable the dev mode.
## diagnose
If you think you found a bug, or something is behaving strangely, you might
want to run the `diagnose` command to perform automated checks for many common
problems.
```sh
php composer.phar diagnose
```
## archive
This command is used to generate a zip/tar archive for a given package in a
given version. It can also be used to archive your entire project without
excluded/ignored files.
```sh
php composer.phar archive vendor/package 2.0.21 --format=zip
```
### Options
* **--format (-f):** Format of the resulting archive: tar or zip (default:
"tar")
* **--dir:** Write the archive to this directory (default: ".")
## help
To get more information about a certain command, just use `help`.
$ php composer.phar help install
```sh
php composer.phar help install
```
## Environment variables
You can set a number of environment variables that override certain settings.
Whenever possible it is recommended to specify these settings in the `config`
section of `composer.json` instead. It is worth noting that that the env vars
will always take precedence over the values specified in `composer.json`.
section of `composer.json` instead. It is worth noting that the env vars will
always take precedence over the values specified in `composer.json`.
### COMPOSER
@ -366,7 +528,9 @@ By setting the `COMPOSER` env variable it is possible to set the filename of
For example:
$ COMPOSER=composer-other.json php composer.phar install
```sh
COMPOSER=composer-other.json php composer.phar install
```
### COMPOSER_ROOT_VERSION
@ -380,7 +544,7 @@ directory other than `vendor`.
### COMPOSER_BIN_DIR
By setting this option you can change the `bin` ([Vendor Bins](articles/vendor-bins.md))
By setting this option you can change the `bin` ([Vendor Binaries](articles/vendor-binaries.md))
directory to something other than `vendor/bin`.
### http_proxy or HTTP_PROXY
@ -394,6 +558,28 @@ some tools like git or curl will only use the lower-cased `http_proxy` version.
Alternatively you can also define the git proxy using
`git config --global http.proxy <proxy url>`.
### no_proxy
If you are behind a proxy and would like to disable it for certain domains, you
can use the `no_proxy` env var. Simply set it to a comma separated list of
domains the proxy should *not* be used for.
The env var accepts domains, IP addresses, and IP address blocks in CIDR
notation. You can restrict the filter to a particular port (e.g. `:80`). You
can also set it to `*` to ignore the proxy for all HTTP requests.
### HTTP_PROXY_REQUEST_FULLURI
If you use a proxy but it does not support the request_fulluri flag, then you
should set this env var to `false` or `0` to prevent composer from setting the
request_fulluri option.
### HTTPS_PROXY_REQUEST_FULLURI
If you use a proxy but it does not support the request_fulluri flag for HTTPS
requests, then you should set this env var to `false` or `0` to prevent composer
from setting the request_fulluri option.
### COMPOSER_HOME
The `COMPOSER_HOME` var allows you to change the composer home directory. This
@ -418,9 +604,26 @@ This file allows you to set [configuration](04-schema.md#config) and
In case global configuration matches _local_ configuration, the _local_
configuration in the project's `composer.json` always wins.
### COMPOSER_CACHE_DIR
The `COMPOSER_CACHE_DIR` var allows you to change the composer cache directory,
which is also configurable via the [`cache-dir`](04-schema.md#config) option.
By default it points to $COMPOSER_HOME/cache on \*nix and OSX, and
`C:\Users\<user>\AppData\Local\Composer` (or `%LOCALAPPDATA%/Composer`) on Windows.
### COMPOSER_PROCESS_TIMEOUT
This env var controls the time composer waits for commands (such as git
commands) to finish executing. The default value is 300 seconds (5 minutes).
### COMPOSER_DISCARD_CHANGES
This env var controls the discard-changes [config option](04-schema.md#config).
### COMPOSER_NO_INTERACTION
If set to 1, this env var will make composer behave as if you passed the
`--no-interaction` flag to every command. This can be set on build boxes/CI.
&larr; [Libraries](02-libraries.md) | [Schema](04-schema.md) &rarr;

@ -1,4 +1,4 @@
# composer.json
# The composer.json Schema
This chapter will explain all of the fields available in `composer.json`.
@ -50,21 +50,23 @@ Required for published packages (libraries).
### version
The version of the package.
The version of the package. In most cases this is not required and should
be omitted (see below).
This must follow the format of `X.Y.Z` with an optional suffix of `-dev`,
`-alphaN`, `-betaN` or `-RCN`.
This must follow the format of `X.Y.Z` or `vX.Y.Z` with an optional suffix
of `-dev`, `-patch`, `-alpha`, `-beta` or `-RC`. The patch, alpha, beta and
RC suffixes can also be followed by a number.
Examples:
1.0.0
1.0.2
1.1.0
0.2.5
1.0.0-dev
1.0.0-alpha3
1.0.0-beta2
1.0.0-RC5
- 1.0.0
- 1.0.2
- 1.1.0
- 0.2.5
- 1.0.0-dev
- 1.0.0-alpha3
- 1.0.0-beta2
- 1.0.0-RC5
Optional if the package repository can infer the version from somewhere, such
as the VCS tag name in the VCS repository. In that case it is also recommended
@ -84,14 +86,20 @@ that needs some special logic, you can define a custom type. This could be a
all be specific to certain projects, and they will need to provide an
installer capable of installing packages of that type.
Out of the box, composer supports three types:
Out of the box, composer supports four types:
- **library:** This is the default. It will simply copy the files to `vendor`.
- **project:** This denotes a project rather than a library. For example
application shells like the [Symfony standard edition](https://github.com/symfony/symfony-standard),
CMSs like the [SilverStripe installer](https://github.com/silverstripe/silverstripe-installer)
or full fledged applications distributed as packages. This can for example
be used by IDEs to provide listings of projects to initialize when creating
a new workspace.
- **metapackage:** An empty package that contains requirements and will trigger
their installation, but contains no files and will not write anything to the
filesystem. As such, it does not require a dist or source key to be
installable.
- **composer-installer:** A package of type `composer-installer` provides an
- **composer-plugin:** A package of type `composer-plugin` may provide an
installer for other packages that have a custom type. Read more in the
[dedicated article](articles/custom-installers.md).
@ -105,11 +113,11 @@ searching and filtering.
Examples:
logging
events
database
redis
templating
- logging
- events
- database
- redis
- templating
Optional.
@ -133,47 +141,54 @@ The license of the package. This can be either a string or an array of strings.
The recommended notation for the most common licenses is (alphabetical):
Apache-2.0
BSD-2-Clause
BSD-3-Clause
BSD-4-Clause
GPL-2.0
GPL-2.0+
GPL-3.0
GPL-3.0+
LGPL-2.1
LGPL-2.1+
LGPL-3.0
LGPL-3.0+
MIT
- Apache-2.0
- BSD-2-Clause
- BSD-3-Clause
- BSD-4-Clause
- GPL-2.0
- GPL-2.0+
- GPL-3.0
- GPL-3.0+
- LGPL-2.1
- LGPL-2.1+
- LGPL-3.0
- LGPL-3.0+
- MIT
Optional, but it is highly recommended to supply this. More identifiers are
listed at the [SPDX Open Source License Registry](http://www.spdx.org/licenses/).
An Example:
For closed-source software, you may use `"proprietary"` as the license identifier.
{
"license": "MIT"
}
An Example:
```json
{
"license": "MIT"
}
```
For a package, when there is a choice between licenses ("disjunctive license"),
multiple can be specified as array.
An Example for disjunctive licenses:
{
"license": [
"LGPL-2.1",
"GPL-3.0+"
]
}
```json
{
"license": [
"LGPL-2.1",
"GPL-3.0+"
]
}
```
Alternatively they can be separated with "or" and enclosed in parenthesis;
{
"license": "(LGPL-2.1 or GPL-3.0+)"
}
```json
{
"license": "(LGPL-2.1 or GPL-3.0+)"
}
```
Similarly when multiple licenses need to be applied ("conjunctive license"),
they should be separated with "and" and enclosed in parenthesis.
@ -191,22 +206,24 @@ Each author object can have following properties:
An example:
{
"authors": [
{
"name": "Nils Adermann",
"email": "naderman@naderman.de",
"homepage": "http://www.naderman.de",
"role": "Developer"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be",
"role": "Developer"
}
]
}
```json
{
"authors": [
{
"name": "Nils Adermann",
"email": "naderman@naderman.de",
"homepage": "http://www.naderman.de",
"role": "Developer"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be",
"role": "Developer"
}
]
}
```
Optional, but highly recommended.
@ -225,12 +242,14 @@ Support information includes the following:
An example:
{
"support": {
"email": "support@example.org",
"irc": "irc://irc.freenode.org/composer"
}
```json
{
"support": {
"email": "support@example.org",
"irc": "irc://irc.freenode.org/composer"
}
}
```
Optional.
@ -241,11 +260,13 @@ All of the following take an object which maps package names to
Example:
{
"require": {
"monolog/monolog": "1.0.*"
}
```json
{
"require": {
"monolog/monolog": "1.0.*"
}
}
```
All links are optional fields.
@ -253,36 +274,58 @@ All links are optional fields.
These allow you to further restrict or expand the stability of a package beyond
the scope of the [minimum-stability](#minimum-stability) setting. You can apply
them to a constraint, or just apply them to an empty constraint if you want to
allow unstable packages of a dependency's dependency for example.
allow unstable packages of a dependency for example.
Example:
{
"require": {
"monolog/monolog": "1.0.*@beta",
"acme/foo": "@dev"
}
```json
{
"require": {
"monolog/monolog": "1.0.*@beta",
"acme/foo": "@dev"
}
}
```
If one of your dependencies has a dependency on an unstable package you need to
explicitly require it as well, along with its sufficient stability flag.
Example:
```json
{
"require": {
"doctrine/doctrine-fixtures-bundle": "dev-master",
"doctrine/data-fixtures": "@dev"
}
}
```
`require` and `require-dev` additionally support explicit references (i.e.
commit) for dev versions to make sure they are blocked to a given state, even
commit) for dev versions to make sure they are locked to a given state, even
when you run update. These only work if you explicitly require a dev version
and append the reference with `#<ref>`. Note that while this is convenient at
times, it should not really be how you use packages in the long term. You
should always try to switch to tagged releases as soon as you can, especially
if the project you work on will not be touched for a while.
and append the reference with `#<ref>`.
Example:
{
"require": {
"monolog/monolog": "dev-master#2eb0c0978d290a1c45346a1955188929cb4e5db7",
"acme/foo": "1.0.x-dev#abc123"
}
```json
{
"require": {
"monolog/monolog": "dev-master#2eb0c0978d290a1c45346a1955188929cb4e5db7",
"acme/foo": "1.0.x-dev#abc123"
}
It is possible to inline-alias a package constraint so that it matches a
constraint that it otherwise would not. For more information [see the
}
```
> **Note:** While this is convenient at times, it should not be how you use
> packages in the long term because it comes with a technical limitation. The
> composer.json metadata will still be read from the branch name you specify
> before the hash. Because of that in some cases it will not be a practical
> workaround, and you should always try to switch to tagged releases as soon
> as you can.
It is also possible to inline-alias a package constraint so that it matches
a constraint that it otherwise would not. For more information [see the
aliases article](articles/aliases.md).
#### require
@ -293,24 +336,20 @@ unless those requirements can be met.
#### require-dev <span>(root-only)</span>
Lists packages required for developing this package, or running
tests, etc. The dev requirements of the root package only will be installed
if `install` or `update` is ran with `--dev`.
Packages listed here and their dependencies can not overrule the resolution
found with the packages listed in require. This is even true if a different
version of a package would be installable and solve the conflict. The reason
is that `install --dev` produces the exact same state as just `install`, apart
from the additional dev packages.
If you run into such a conflict, you can specify the conflicting package in
the require section and require the right version number to resolve the
conflict.
tests, etc. The dev requirements of the root package are installed by default.
Both `install` or `update` support the `--no-dev` option that prevents dev
dependencies from being installed.
#### conflict
Lists packages that conflict with this version of this package. They
will not be allowed to be installed together with your package.
Note that when specifying ranges like `<1.0, >= 1.1` in a `conflict` link,
this will state a conflict with all versions that are less than 1.0 *and* equal
or newer than 1.1 at the same time, which is probably not what you want. You
probably want to go for `<1.0 | >= 1.1` in this case.
#### replace
Lists packages that are replaced by this package. This allows you to fork a
@ -348,69 +387,134 @@ and not version constraints.
Example:
{
"suggest": {
"monolog/monolog": "Allows more advanced logging of the application flow"
}
```json
{
"suggest": {
"monolog/monolog": "Allows more advanced logging of the application flow"
}
}
```
### autoload
Autoload mapping for a PHP autoloader.
Currently [`PSR-0`](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md)
autoloading, `classmap` generation and `files` are supported. PSR-0 is the recommended way though
since it offers greater flexibility (no need to regenerate the autoloader when you add
classes).
Currently [`PSR-0`](http://www.php-fig.org/psr/psr-0/) autoloading,
[`PSR-4`](http://www.php-fig.org/psr/psr-4/) autoloading, `classmap` generation and
`files` includes are supported. PSR-4 is the recommended way though since it offers
greater ease of use (no need to regenerate the autoloader when you add classes).
#### PSR-4
Under the `psr-4` key you define a mapping from namespaces to paths, relative to the
package root. When autoloading a class like `Foo\\Bar\\Baz` a namespace prefix
`Foo\\` pointing to a directory `src/` means that the autoloader will look for a
file named `src/Bar/Baz.php` and include it if present. Note that as opposed to
the older PSR-0 style, the prefix (`Foo\\`) is **not** present in the file path.
Namespace prefixes must end in `\\` to avoid conflicts between similar prefixes.
For example `Foo` would match classes in the `FooBar` namespace so the trailing
backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct.
The PSR-4 references are all combined, during install/update, into a single
key => value array which may be found in the generated file
`vendor/composer/autoload_psr4.php`.
Example:
```json
{
"autoload": {
"psr-4": {
"Monolog\\": "src/",
"Vendor\\Namespace\\": ""
}
}
}
```
If you need to search for a same prefix in multiple directories,
you can specify them as an array as such:
```json
{
"autoload": {
"psr-4": { "Monolog\\": ["src/", "lib/"] }
}
}
```
If you want to have a fallback directory where any namespace will be looked for,
you can use an empty prefix like:
```json
{
"autoload": {
"psr-4": { "": "src/" }
}
}
```
#### PSR-0
Under the `psr-0` key you define a mapping from namespaces to paths, relative to the
package root. Note that this also supports the PEAR-style non-namespaced convention.
Please note namespace declarations should end in `\\` to make sure the autoloader
responds exactly. For example `Foo` would match in `FooBar` so the trailing
backslashes solve the problem: `Foo\\` and `FooBar\\` are distinct.
The PSR-0 references are all combined, during install/update, into a single key => value
array which may be found in the generated file `vendor/composer/autoload_namespaces.php`.
Example:
{
"autoload": {
"psr-0": {
"Monolog": "src/",
"Vendor\\Namespace\\": "src/",
"Vendor_Namespace_": "src/"
}
```json
{
"autoload": {
"psr-0": {
"Monolog\\": "src/",
"Vendor\\Namespace\\": "src/",
"Vendor_Namespace_": "src/"
}
}
}
```
If you need to search for a same prefix in multiple directories,
you can specify them as an array as such:
{
"autoload": {
"psr-0": { "Monolog": ["src/", "lib/"] }
}
```json
{
"autoload": {
"psr-0": { "Monolog\\": ["src/", "lib/"] }
}
}
```
The PSR-0 style is not limited to namespace declarations only but may be
specified right down to the class level. This can be useful for libraries with
only one class in the global namespace. If the php source file is also located
in the root of the package, for example, it may be declared like this:
{
"autoload": {
"psr-0": { "UniqueGlobalClass": "" }
}
```json
{
"autoload": {
"psr-0": { "UniqueGlobalClass": "" }
}
}
```
If you want to have a fallback directory where any namespace can be, you can
use an empty prefix like:
{
"autoload": {
"psr-0": { "": "src/" }
}
```json
{
"autoload": {
"psr-0": { "": "src/" }
}
}
```
#### Classmap
@ -420,16 +524,18 @@ key => value array which may be found in the generated file
classes in all `.php` and `.inc` files in the given directories/files.
You can use the classmap generation support to define autoloading for all libraries
that do not follow PSR-0. To configure this you specify all directories or files
that do not follow PSR-0/4. To configure this you specify all directories or files
to search for classes.
Example:
{
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
```json
{
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
}
```
#### Files
@ -439,11 +545,37 @@ that cannot be autoloaded by PHP.
Example:
{
"autoload": {
"files": ["src/MyLibrary/functions.php"]
}
```json
{
"autoload": {
"files": ["src/MyLibrary/functions.php"]
}
}
```
### autoload-dev <span>(root-only)</span>
This section allows to define autoload rules for development purposes.
Classes needed to run the test suite should not be included in the main autoload
rules to avoid polluting the autoloader in production and when other people use
your package as a dependency.
Therefore, it is a good idea to rely on a dedicated path for your unit tests
and to add it within the autoload-dev section.
Example:
```json
{
"autoload": {
"psr-4": { "MyLibrary\\": "src/" }
},
"autoload-dev": {
"psr-4": { "MyLibrary\\Tests\\": "tests/" }
}
}
```
### include-path
@ -455,14 +587,20 @@ A list of paths which should get appended to PHP's `include_path`.
Example:
{
"include-path": ["lib/"]
}
```json
{
"include-path": ["lib/"]
}
```
Optional.
### target-dir
> **DEPRECATED**: This is only present to support legacy PSR-0 style autoloading,
> and all new code should preferably use PSR-4 without target-dir and projects
> using PSR-0 with PHP namespaces are encouraged to migrate to PSR-4 instead.
Defines the installation target.
In case the package root is below the namespace declaration you cannot
@ -477,12 +615,14 @@ it from `vendor/symfony/yaml`.
To do that, `autoload` and `target-dir` are defined as follows:
{
"autoload": {
"psr-0": { "Symfony\\Component\\Yaml": "" }
},
"target-dir": "Symfony/Component/Yaml"
}
```json
{
"autoload": {
"psr-0": { "Symfony\\Component\\Yaml\\": "" }
},
"target-dir": "Symfony/Component/Yaml"
}
```
Optional.
@ -501,6 +641,15 @@ a given package can be done in `require` or `require-dev` (see
Available options (in order of stability) are `dev`, `alpha`, `beta`, `RC`,
and `stable`.
### prefer-stable <span>(root-only)</span>
When this is enabled, Composer will prefer more stable packages over unstable
ones when finding compatible stable packages is possible. If you require a
dev version or only alphas are available for a package, those will still be
selected granted that the minimum-stability allows for it.
Use `"prefer-stable": true` to enable.
### repositories <span>(root-only)</span>
Custom package repositories to use.
@ -531,47 +680,49 @@ For more information on any of these, see [Repositories](05-repositories.md).
Example:
{
"repositories": [
{
"type": "composer",
"url": "http://packages.example.com"
},
{
"type": "composer",
"url": "https://packages.example.com",
"options": {
"ssl": {
"verify_peer": "true"
}
```json
{
"repositories": [
{
"type": "composer",
"url": "http://packages.example.com"
},
{
"type": "composer",
"url": "https://packages.example.com",
"options": {
"ssl": {
"verify_peer": "true"
}
},
{
"type": "vcs",
"url": "https://github.com/Seldaek/monolog"
},
{
"type": "pear",
"url": "http://pear2.php.net"
},
{
"type": "package",
"package": {
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
},
"source": {
"url": "http://smarty-php.googlecode.com/svn/",
"type": "svn",
"reference": "tags/Smarty_3_1_7/distribution/"
}
}
},
{
"type": "vcs",
"url": "https://github.com/Seldaek/monolog"
},
{
"type": "pear",
"url": "http://pear2.php.net"
},
{
"type": "package",
"package": {
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
},
"source": {
"url": "http://smarty-php.googlecode.com/svn/",
"type": "svn",
"reference": "tags/Smarty_3_1_7/distribution/"
}
}
]
}
}
]
}
```
> **Note:** Order is significant here. When looking for a package, Composer
will look from the first to the last repository, and pick the first match.
@ -584,20 +735,35 @@ A set of configuration options. It is only used for projects.
The following options are supported:
* **vendor-dir:** Defaults to `vendor`. You can install dependencies into a
different directory if you want to.
* **bin-dir:** Defaults to `vendor/bin`. If a project includes binaries, they
will be symlinked into this directory.
* **process-timeout:** Defaults to `300`. The duration processes like git clones
can run before Composer assumes they died out. You may need to make this
higher if you have a slow connection or huge vendors.
* **github-protocols:** Defaults to `["git", "https", "http"]`. A list of
protocols to use for github.com clones, in priority order. Use this if you are
behind a proxy or have somehow bad performances with the git protocol.
* **use-include-path:** Defaults to `false`. If true, the Composer autoloader
will also look for classes in the PHP include path.
* **preferred-install:** Defaults to `auto` and can be any of `source`, `dist` or
`auto`. This option allows you to set the install method Composer will prefer to
use.
* **store-auths:** What to do after prompting for authentication, one of:
`true` (always store), `false` (do not store) and `"prompt"` (ask every
time), defaults to `"prompt"`.
* **github-protocols:** Defaults to `["git", "https", "ssh"]`. A list of protocols to
use when cloning from github.com, in priority order. You can reconfigure it to
for example prioritize the https protocol if you are behind a proxy or have somehow
bad performances with the git protocol.
* **github-oauth:** A list of domain names and oauth keys. For example using
`{"github.com": "oauthtoken"}` as the value of this option will use `oauthtoken`
to access private repositories on github and to circumvent the low IP-based
rate limiting of their API.
[Read more](articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)
on how to get an OAuth token for GitHub.
* **http-basic:** A list of domain names and username/passwords to authenticate
against them. For example using
`{"example.org": {"username": "alice", "password": "foo"}` as the value of this option will let composer authenticate against example.org.
* **vendor-dir:** Defaults to `vendor`. You can install dependencies into a
different directory if you want to. `$HOME` and `~` will be replaced by your
home directory's path in vendor-dir and all `*-dir` options below.
* **bin-dir:** Defaults to `vendor/bin`. If a project includes binaries, they
will be symlinked into this directory.
* **cache-dir:** Defaults to `C:\Users\<user>\AppData\Local\Composer` on Windows,
`$XDG_CACHE_HOME/composer` on unix systems that follow the XDG Base Directory
Specifications, and `$home/cache` on other unix systems. Stores all the caches
@ -605,24 +771,49 @@ The following options are supported:
* **cache-files-dir:** Defaults to `$cache-dir/files`. Stores the zip archives
of packages.
* **cache-repo-dir:** Defaults to `$cache-dir/repo`. Stores repository metadata
for the `composer` type and the VCS repos of type `svn`, `github` and `*bitbucket`.
for the `composer` type and the VCS repos of type `svn`, `github` and `bitbucket`.
* **cache-vcs-dir:** Defaults to `$cache-dir/vcs`. Stores VCS clones for
loading VCS repository metadata for the `git`/`hg` types and to speed up installs.
* **cache-files-ttl:** Defaults to `15552000` (6 months). Composer caches all
dist (zip, tar, ..) packages that it downloads. Those are purged after six
months of being unused by default. This option allows you to tweak this
duration (in seconds) or disable it completely by setting it to 0.
* **cache-files-maxsize:** Defaults to `300MiB`. Composer caches all
dist (zip, tar, ..) packages that it downloads. When the garbage collection
is periodically ran, this is the maximum size the cache will be able to use.
Older (less used) files will be removed first until the cache fits.
* **prepend-autoloader:** Defaults to `true`. If false, the composer autoloader
will not be prepended to existing autoloaders. This is sometimes required to fix
interoperability issues with other autoloaders.
* **autoloader-suffix:** Defaults to `null`. String to be used as a suffix for
the generated Composer autoloader. When null a random one will be generated.
* **optimize-autoloader** Defaults to `false`. Always optimize when dumping
the autoloader.
* **github-domains:** Defaults to `["github.com"]`. A list of domains to use in
github mode. This is used for GitHub Enterprise setups.
* **notify-on-install:** Defaults to `true`. Composer allows repositories to
define a notification URL, so that they get notified whenever a package from
that repository is installed. This option allows you to disable that behaviour.
* **discard-changes:** Defaults to `false` and can be any of `true`, `false` or
`"stash"`. This option allows you to set the default style of handling dirty
updates when in non-interactive mode. `true` will always discard changes in
vendors, while `"stash"` will try to stash and reapply. Use this for CI
servers or deploy scripts if you tend to have modified vendors.
Example:
{
"config": {
"bin-dir": "bin"
}
```json
{
"config": {
"bin-dir": "bin"
}
}
```
> **Note:** Authentication-related config options like `http-basic` and
> `github-oauth` can also be specified inside a `auth.json` file that goes
> besides your `composer.json`. That way you can gitignore it and every
> developer can place their own credentials in there.
### scripts <span>(root-only)</span>
@ -638,7 +829,9 @@ Arbitrary extra data for consumption by `scripts`.
This can be virtually anything. To access it from within a script event
handler, you can do:
$extra = $event->getComposer()->getPackage()->getExtra();
```php
$extra = $event->getComposer()->getPackage()->getExtra();
```
Optional.
@ -647,7 +840,34 @@ Optional.
A set of files that should be treated as binaries and symlinked into the `bin-dir`
(from config).
See [Vendor Bins](articles/vendor-bins.md) for more details.
See [Vendor Binaries](articles/vendor-binaries.md) for more details.
Optional.
### archive
A set of options for creating package archives.
The following options are supported:
* **exclude:** Allows configuring a list of patterns for excluded paths. The
pattern syntax matches .gitignore files. A leading exclamation mark (!) will
result in any matching files to be included even if a previous pattern
excluded them. A leading slash will only match at the beginning of the project
relative path. An asterisk will not expand to a directory separator.
Example:
```json
{
"archive": {
"exclude": ["/foo/bar", "baz", "/*.test", "!/foo/bar/baz"]
}
}
```
The example will include `/dir/foo/bar/file`, `/foo/bar/baz`, `/file.php`,
`/foo/my.test` but it will exclude `/foo/bar/any`, `/foo/baz`, and `/my.test`.
Optional.

@ -66,16 +66,18 @@ repository URL would be `example.org`.
The only required field is `packages`. The JSON structure is as follows:
{
"packages": {
"vendor/package-name": {
"dev-master": { @composer.json },
"1.0.x-dev": { @composer.json },
"0.0.1": { @composer.json },
"1.0.0": { @composer.json }
}
```json
{
"packages": {
"vendor/package-name": {
"dev-master": { @composer.json },
"1.0.x-dev": { @composer.json },
"0.0.1": { @composer.json },
"1.0.0": { @composer.json }
}
}
}
```
The `@composer.json` marker would be the contents of the `composer.json` from
that package version including as a minimum:
@ -86,38 +88,44 @@ that package version including as a minimum:
Here is a minimal package definition:
{
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
}
```json
{
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
}
}
```
It may include any of the other fields specified in the [schema](04-schema.md).
#### notify_batch
#### notify-batch
The `notify_batch` field allows you to specify an URL that will be called
The `notify-batch` field allows you to specify an URL that will be called
every time a user installs a package. The URL can be either an absolute path
(that will use the same domain as the repository) or a fully qualified URL.
An example value:
{
"notify_batch": "/downloads/"
}
```json
{
"notify-batch": "/downloads/"
}
```
For `example.org/packages.json` containing a `monolog/monolog` package, this
would send a `POST` request to `example.org/downloads/` with following
JSON request body:
{
"downloads": [
{"name": "monolog/monolog", "version": "1.2.1.0"},
]
}
```json
{
"downloads": [
{"name": "monolog/monolog", "version": "1.2.1.0"},
]
}
```
The version field will contain the normalized representation of the version
number.
@ -126,25 +134,27 @@ This field is optional.
#### includes
For large repositories it is possible to split the `packages.json` into
For larger repositories it is possible to split the `packages.json` into
multiple files. The `includes` field allows you to reference these additional
files.
An example:
{
"includes": {
"packages-2011.json": {
"sha1": "525a85fb37edd1ad71040d429928c2c0edec9d17"
},
"packages-2012-01.json": {
"sha1": "897cde726f8a3918faf27c803b336da223d400dd"
},
"packages-2012-02.json": {
"sha1": "26f911ad717da26bbcac3f8f435280d13917efa5"
}
```json
{
"includes": {
"packages-2011.json": {
"sha1": "525a85fb37edd1ad71040d429928c2c0edec9d17"
},
"packages-2012-01.json": {
"sha1": "897cde726f8a3918faf27c803b336da223d400dd"
},
"packages-2012-02.json": {
"sha1": "26f911ad717da26bbcac3f8f435280d13917efa5"
}
}
}
```
The SHA-1 sum of the file allows it to be cached and only re-requested if the
hash changed.
@ -152,6 +162,56 @@ hash changed.
This field is optional. You probably don't need it for your own custom
repository.
#### provider-includes and providers-url
For very large repositories like packagist.org using the so-called provider
files is the preferred method. The `provider-includes` field allows you to
list a set of files that list package names provided by this repository. The
hash should be a sha256 of the files in this case.
The `providers-url` describes how provider files are found on the server. It
is an absolute path from the repository root.
An example:
```json
{
"provider-includes": {
"providers-a.json": {
"sha256": "f5b4bc0b354108ef08614e569c1ed01a2782e67641744864a74e788982886f4c"
},
"providers-b.json": {
"sha256": "b38372163fac0573053536f5b8ef11b86f804ea8b016d239e706191203f6efac"
}
},
"providers-url": "/p/%package%$%hash%.json"
}
```
Those files contain lists of package names and hashes to verify the file
integrity, for example:
```json
{
"providers": {
"acme/foo": {
"sha256": "38968de1305c2e17f4de33aea164515bc787c42c7e2d6e25948539a14268bb82"
},
"acme/bar": {
"sha256": "4dd24c930bd6e1103251306d6336ac813b563a220d9ca14f4743c032fb047233"
}
}
}
```
The file above declares that acme/foo and acme/bar can be found in this
repository, by loading the file referenced by `providers-url`, replacing
`%package%` by the package name and `%hash%` by the sha256 field. Those files
themselves just contain package definitions as described [above](#packages).
This field is optional. You probably don't need it for your own custom
repository.
#### stream options
The `packages.json` file is loaded using a PHP stream. You can set extra options
@ -179,41 +239,52 @@ point to your custom branch. For version constraint naming conventions see
Example assuming you patched monolog to fix a bug in the `bugfix` branch:
{
"repositories": [
{
"type": "vcs",
"url": "http://github.com/igorw/monolog"
}
],
"require": {
"monolog/monolog": "dev-bugfix"
```json
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/igorw/monolog"
}
],
"require": {
"monolog/monolog": "dev-bugfix"
}
}
```
When you run `php composer.phar update`, you should get your modified version
of `monolog/monolog` instead of the one from packagist.
It is possible to inline-alias a package constraint so that it matches a
constraint that it otherwise would not. For more information [see the
aliases article](articles/aliases.md).
Note that you should not rename the package unless you really intend to fork
it in the long term, and completely move away from the original package.
Composer will correctly pick your package over the original one since the
custom repository has priority over packagist. If you want to rename the
package, you should do so in the default (often master) branch and not in a
feature branch, since the package name is taken from the default branch.
If other dependencies rely on the package you forked, it is possible to
inline-alias it so that it matches a constraint that it otherwise would not.
For more information [see the aliases article](articles/aliases.md).
#### Using private repositories
Exactly the same solution allows you to work with your private repositories at
GitHub and BitBucket:
{
"require": {
"vendor/my-private-repo": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "git@bitbucket.org:vendor/my-private-repo.git"
}
]
}
```json
{
"require": {
"vendor/my-private-repo": "dev-master"
},
"repositories": [
{
"type": "vcs",
"url": "git@bitbucket.org:vendor/my-private-repo.git"
}
]
}
```
The only requirement is the installation of SSH keys for a git client.
@ -239,6 +310,11 @@ The VCS driver to be used is detected automatically based on the URL. However,
should you need to specify one for whatever reason, you can use `git`, `svn` or
`hg` as the repository type instead of `vcs`.
If you set the `no-api` key to `true` on a github repository it will clone the
repository as it would with any other git repository instead of using the
GitHub API. But unlike using the `git` driver directly, composer will still
attempt to use github's zip files.
#### Subversion Options
Since Subversion has no native concept of branches and tags, Composer assumes
@ -247,21 +323,59 @@ by default that code is located in `$url/trunk`, `$url/branches` and
values. For example if you used capitalized names you could configure the
repository like this:
{
"repositories": [
{
"type": "vcs",
"url": "http://svn.example.org/projectA/",
"trunk-path": "Trunk",
"branches-path": "Branches",
"tags-path": "Tags"
}
]
}
```json
{
"repositories": [
{
"type": "vcs",
"url": "http://svn.example.org/projectA/",
"trunk-path": "Trunk",
"branches-path": "Branches",
"tags-path": "Tags"
}
]
}
```
If you have no branches or tags directory you can disable them entirely by
setting the `branches-path` or `tags-path` to `false`.
If the package is in a sub-directory, e.g. `/trunk/foo/bar/composer.json` and
`/tags/1.0/foo/bar/composer.json`, then you can make composer access it by
setting the `"package-path"` option to the sub-directory, in this example it
would be `"package-path": "foo/bar/"`.
If you have a private Subversion repository you can save credentials in the
http-basic section of your config (See [Schema](04-schema.md)):
```json
{
"http-basic": {
"svn.example.org": {
"username": "username",
"password": "password"
}
}
}
```
If your Subversion client is configured to store credentials by default these
credentials will be saved for the current user and existing saved credentials
for this server will be overwritten. To change this behavior by setting the
`"svn-cache-credentials"` option in your repository configuration:
```json
{
"repositories": [
{
"type": "vcs",
"url": "http://svn.example.org/projectA/",
"svn-cache-credentials": false
}
]
}
```
### PEAR
It is possible to install packages from any PEAR channel by using the `pear`
@ -270,18 +384,20 @@ avoid conflicts. All packages are also aliased with prefix `pear-{channelAlias}/
Example using `pear2.php.net`:
{
"repositories": [
{
"type": "pear",
"url": "http://pear2.php.net"
}
],
"require": {
"pear-pear2.php.net/PEAR2_Text_Markdown": "*",
"pear-pear2/PEAR2_HTTP_Request": "*"
```json
{
"repositories": [
{
"type": "pear",
"url": "http://pear2.php.net"
}
],
"require": {
"pear-pear2.php.net/PEAR2_Text_Markdown": "*",
"pear-pear2/PEAR2_HTTP_Request": "*"
}
}
```
In this case the short name of the channel is `pear2`, so the
`PEAR2_HTTP_Request` package name becomes `pear-pear2/PEAR2_HTTP_Request`.
@ -324,23 +440,25 @@ To illustrate, the following example would get the `BasePackage`,
`TopLevelPackage1`, and `TopLevelPackage2` packages from your PEAR repository
and `IntermediatePackage` from a Github repository:
{
"repositories": [
{
"type": "git",
"url": "https://github.com/foobar/intermediate.git"
},
{
"type": "pear",
"url": "http://pear.foobar.repo",
"vendor-alias": "foobar"
}
],
"require": {
"foobar/TopLevelPackage1": "*",
"foobar/TopLevelPackage2": "*"
```json
{
"repositories": [
{
"type": "git",
"url": "https://github.com/foobar/intermediate.git"
},
{
"type": "pear",
"url": "http://pear.foobar.repo",
"vendor-alias": "foobar"
}
],
"require": {
"foobar/TopLevelPackage1": "*",
"foobar/TopLevelPackage2": "*"
}
}
```
### Package
@ -355,35 +473,45 @@ minimum required fields are `name`, `version`, and either of `dist` or
Here is an example for the smarty template engine:
{
"repositories": [
{
"type": "package",
"package": {
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
},
"source": {
"url": "http://smarty-php.googlecode.com/svn/",
"type": "svn",
"reference": "tags/Smarty_3_1_7/distribution/"
},
"autoload": {
"classmap": ["libs/"]
}
```json
{
"repositories": [
{
"type": "package",
"package": {
"name": "smarty/smarty",
"version": "3.1.7",
"dist": {
"url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
"type": "zip"
},
"source": {
"url": "http://smarty-php.googlecode.com/svn/",
"type": "svn",
"reference": "tags/Smarty_3_1_7/distribution/"
},
"autoload": {
"classmap": ["libs/"]
}
}
],
"require": {
"smarty/smarty": "3.1.*"
}
],
"require": {
"smarty/smarty": "3.1.*"
}
}
```
Typically you would leave the source part off, as you don't really need it.
> **Note**: This repository type has a few limitations and should be avoided
> whenever possible:
>
> - Composer will not update the package unless you change the `version` field.
> - Composer will not update the commit references, so if you use `master` as
> reference you will have to delete the package to force an update, and will
> have to deal with an unstable lock file.
## Hosting your own
While you will probably want to put your packages on packagist most of the time,
@ -397,8 +525,8 @@ there are some use cases for hosting your own repository.
might want to keep them separate to packagist. An example of this would be
wordpress plugins.
When hosting your own package repository it is recommended to use a `composer`
one. This is type that is native to composer and yields the best performance.
For hosting your own packages, a native `composer` type of repository is
recommended, which provides the best performance.
There are a few tools that can help you create a `composer` repository.
@ -432,18 +560,58 @@ Check [the satis GitHub repository](https://github.com/composer/satis) and
the [Satis article](articles/handling-private-packages-with-satis.md) for more
information.
### Artifact
There are some cases, when there is no ability to have one of the previously
mentioned repository types online, even the VCS one. Typical example could be
cross-organisation library exchange through built artifacts. Of course, most
of the times they are private. To simplify maintenance, one can simply use a
repository of type `artifact` with a folder containing ZIP archives of those
private packages:
```json
{
"repositories": [
{
"type": "artifact",
"url": "path/to/directory/with/zips/"
}
],
"require": {
"private-vendor-one/core": "15.6.2",
"private-vendor-two/connectivity": "*",
"acme-corp/parser": "10.3.5"
}
}
```
Each zip artifact is just a ZIP archive with `composer.json` in root folder:
```sh
unzip -l acme-corp-parser-10.3.5.zip
composer.json
...
```
If there are two archives with different versions of a package, they are both
imported. When an archive with a newer version is added in the artifact folder
and you run `update`, that version will be imported as well and Composer will
update to the latest version.
## Disabling Packagist
You can disable the default Packagist repository by adding this to your
`composer.json`:
{
"repositories": [
{
"packagist": false
}
]
}
```json
{
"repositories": [
{
"packagist": false
}
]
}
```
&larr; [Schema](04-schema.md) | [Community](06-community.md) &rarr;

@ -7,7 +7,7 @@
## Why aliases?
When you are using a VCS repository, you will only get comparable versions for
branches that look like versions, such as `2.0`. For your `master` branch, you
branches that look like versions, such as `2.0` or `2.0.x`. For your `master` branch, you
will get a `dev-master` version. For your `bugfix` branch, you will get a
`dev-bugfix` version.
@ -28,13 +28,15 @@ someone will want the latest master dev version. Thus, Composer allows you to
alias your `dev-master` branch to a `1.0.x-dev` version. It is done by
specifying a `branch-alias` field under `extra` in `composer.json`:
{
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
```json
{
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}
```
The branch version must begin with `dev-` (non-comparable version), the alias
must be a comparable dev version (i.e. start with numbers, and end with
@ -59,26 +61,29 @@ is a dependency of your local project.
For this reason, you can alias packages in your `require` and `require-dev`
fields. Let's say you found a bug in the `monolog/monolog` package. You cloned
Monolog on GitHub and fixed the issue in a branch named `bugfix`. Now you want
to install that version of monolog in your local project.
[Monolog](https://github.com/Seldaek/monolog) on GitHub and fixed the issue in
a branch named `bugfix`. Now you want to install that version of monolog in your
local project.
You are using `symfony/monolog-bundle` which requires `monolog/monolog` version
`1.*`. So you need your `dev-bugfix` to match that constraint.
Just add this to your project's root `composer.json`:
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/you/monolog"
}
],
"require": {
"symfony/monolog-bundle": "2.0",
"monolog/monolog": "dev-bugfix as 1.0.x-dev"
```json
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/you/monolog"
}
],
"require": {
"symfony/monolog-bundle": "2.0",
"monolog/monolog": "dev-bugfix as 1.0.x-dev"
}
}
```
That will fetch the `dev-bugfix` version of `monolog/monolog` from your GitHub
and alias it to `1.0.x-dev`.

@ -29,71 +29,102 @@ An example use-case would be:
> phpDocumentor features Templates that need to be installed outside of the
> default /vendor folder structure. As such they have chosen to adopt the
> `phpdocumentor-template` [type][1] and create a Custom Installer to send
> these templates to the correct folder.
> `phpdocumentor-template` [type][1] and create a plugin providing the Custom
> Installer to send these templates to the correct folder.
An example composer.json of such a template package would be:
{
"name": "phpdocumentor/template-responsive",
"type": "phpdocumentor-template",
"require": {
"phpdocumentor/template-installer": "*"
}
```json
{
"name": "phpdocumentor/template-responsive",
"type": "phpdocumentor-template",
"require": {
"phpdocumentor/template-installer-plugin": "*"
}
}
```
> **IMPORTANT**: to make sure that the template installer is present at the
> time the template package is installed, template packages should require
> the installer package.
> the plugin package.
## Creating an Installer
A Custom Installer is defined as a class that implements the
[`Composer\Installer\InstallerInterface`][3] and is contained in a Composer
package that has the [type][1] `composer-installer`.
[`Composer\Installer\InstallerInterface`][3] and is usually distributed in a
Composer Plugin.
A basic Installer would thus compose of two files:
A basic Installer Plugin would thus compose of three files:
1. the package file: composer.json
2. The Installer class, i.e.: `Composer\Installer\MyInstaller.php`
> **NOTE**: _The namespace does not need to be `Composer\Installer`, it must
> only implement the right interface._
2. The Plugin class, e.g.: `My\Project\Composer\Plugin.php`, containing a class that implements `Composer\Plugin\PluginInterface`.
3. The Installer class, e.g.: `My\Project\Composer\Installer.php`, containing a class that implements `Composer\Installer\InstallerInterface`.
### composer.json
The package file is the same as any other package file but with the following
requirements:
1. the [type][1] attribute must be `composer-installer`.
1. the [type][1] attribute must be `composer-plugin`.
2. the [extra][2] attribute must contain an element `class` defining the
class name of the installer (including namespace). If a package contains
multiple installers this can be array of class names.
class name of the plugin (including namespace). If a package contains
multiple plugins this can be array of class names.
Example:
{
"name": "phpdocumentor/template-installer",
"type": "composer-installer",
"license": "MIT",
"autoload": {
"psr-0": {"phpDocumentor\\Composer": "src/"}
},
"extra": {
"class": "phpDocumentor\\Composer\\TemplateInstaller"
}
```json
{
"name": "phpdocumentor/template-installer-plugin",
"type": "composer-plugin",
"license": "MIT",
"autoload": {
"psr-0": {"phpDocumentor\\Composer": "src/"}
},
"extra": {
"class": "phpDocumentor\\Composer\\TemplateInstallerPlugin"
},
"require": {
"composer-plugin-api": "1.0.0"
}
}
```
### The Custom Installer class
### The Plugin class
The class that executes the custom installation should implement the
[`Composer\Installer\InstallerInterface`][3] (or extend another installer that
implements that interface).
The class defining the Composer plugin must implement the
[`Composer\Plugin\PluginInterface`][3]. It can then register the Custom
Installer in its `activate()` method.
The class may be placed in any location and have any name, as long as it is
autoloadable and matches the `extra.class` element in the package definition.
It will also define the [type][1] string as it will be recognized by packages
that will use this installer in the `supports()` method.
Example:
```php
<?php
namespace phpDocumentor\Composer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class TemplateInstallerPlugin implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$installer = new TemplateInstaller($io, $composer);
$composer->getInstallationManager()->addInstaller($installer);
}
}
```
### The Custom Installer class
The class that executes the custom installation should implement the
[`Composer\Installer\InstallerInterface`][4] (or extend another installer that
implements that interface). It defines the [type][1] string as it will be
recognized by packages that will use this installer in the `supports()` method.
> **NOTE**: _choose your [type][1] name carefully, it is recommended to follow
> the format: `vendor-type`_. For example: `phpdocumentor-template`.
@ -115,41 +146,45 @@ source for the exact signature):
Example:
namespace phpDocumentor\Composer;
```php
<?php
namespace phpDocumentor\Composer;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;
use Composer\Installer\LibraryInstaller;
class TemplateInstaller extends LibraryInstaller
class TemplateInstaller extends LibraryInstaller
{
/**
* {@inheritDoc}
*/
public function getPackageBasePath(PackageInterface $package)
{
/**
* {@inheritDoc}
*/
public function getInstallPath(PackageInterface $package)
{
$prefix = substr($package->getPrettyName(), 0, 23);
if ('phpdocumentor/template-' !== $prefix) {
throw new \InvalidArgumentException(
'Unable to install template, phpdocumentor templates '
.'should always start their package name with '
.'"phpdocumentor/template-"'
);
}
return 'data/templates/'.substr($package->getPrettyName(), 23);
$prefix = substr($package->getPrettyName(), 0, 23);
if ('phpdocumentor/template-' !== $prefix) {
throw new \InvalidArgumentException(
'Unable to install template, phpdocumentor templates '
.'should always start their package name with '
.'"phpdocumentor/template-"'
);
}
/**
* {@inheritDoc}
*/
public function supports($packageType)
{
return 'phpdocumentor-template' === $packageType;
}
return 'data/templates/'.substr($package->getPrettyName(), 23);
}
/**
* {@inheritDoc}
*/
public function supports($packageType)
{
return 'phpdocumentor-template' === $packageType;
}
}
```
The example demonstrates that it is quite simple to extend the
[`Composer\Installer\LibraryInstaller`][4] class to strip a prefix
[`Composer\Installer\LibraryInstaller`][5] class to strip a prefix
(`phpdocumentor/template-`) and use the remaining part to assemble a completely
different installation path.
@ -158,5 +193,6 @@ different installation path.
[1]: ../04-schema.md#type
[2]: ../04-schema.md#extra
[3]: https://github.com/composer/composer/blob/master/src/Composer/Installer/InstallerInterface.php
[4]: https://github.com/composer/composer/blob/master/src/Composer/Installer/LibraryInstaller.php
[3]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/PluginInterface.php
[4]: https://github.com/composer/composer/blob/master/src/Composer/Installer/InstallerInterface.php
[5]: https://github.com/composer/composer/blob/master/src/Composer/Installer/LibraryInstaller.php

@ -2,55 +2,69 @@
tagline: Host your own composer repository
-->
# Handling private packages with Satis
# Handling private packages with Satis or Toran Proxy
Satis can be used to host the metadata of your company's private packages, or
your own. It basically acts as a micro-packagist. You can get it from
[GitHub](http://github.com/composer/satis) or install via CLI:
`composer.phar create-project composer/satis`.
# Toran Proxy
[Toran Proxy](https://toranproxy.com/) is a commercial alternative to Satis offering professional support as well as a web UI to manage everything and a better integration with Composer.
Toran's revenue is also used to pay for Composer and Packagist development and hosting so using it is a good way to support open source financially. You can find more information about how to set it up and use it on the [Toran Proxy](https://toranproxy.com/) website.
# Satis
Satis on the other hand is open source but only a static `composer`
repository generator. It is a bit like an ultra-lightweight, static file-based
version of packagist and can be used to host the metadata of your company's
private packages, or your own. You can get it from [GitHub](http://github.com/composer/satis)
or install via CLI:
`php composer.phar create-project composer/satis --stability=dev --keep-vcs`.
## Setup
For example let's assume you have a few packages you want to reuse across your
company but don't really want to open-source. You would first define a Satis
configuration file, which is basically a stripped-down version of a
`composer.json` file. It contains a few repositories, and then you use the require
key to say which packages it should dump in the static repository it creates, or
use require-all to select all of them.
configuration: a json file with an arbitrary name that lists your curated
[repositories](../05-repositories.md).
Here is an example configuration, you see that it holds a few VCS repositories,
but those could be any types of [repositories](../05-repositories.md). Then it
uses `"require-all": true` which selects all versions of all packages in the
repositories you defined.
{
"name": "My Repository",
"homepage": "http://packages.example.org",
"repositories": [
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo" },
{ "type": "vcs", "url": "http://svn.example.org/private/repo" },
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo2" }
],
"require-all": true
}
The default file Satis looks for is `satis.json` in the root of the repository.
```json
{
"name": "My Repository",
"homepage": "http://packages.example.org",
"repositories": [
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo" },
{ "type": "vcs", "url": "http://svn.example.org/private/repo" },
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo2" }
],
"require-all": true
}
```
If you want to cherry pick which packages you want, you can list all the packages
you want to have in your satis repository inside the classic composer `require` key,
using a `"*"` constraint to make sure all versions are selected, or another
constraint if you want really specific versions.
{
"repositories": [
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo" },
{ "type": "vcs", "url": "http://svn.example.org/private/repo" },
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo2" }
],
"require": {
"company/package": "*",
"company/package2": "*",
"company/package3": "2.0.0"
}
```json
{
"repositories": [
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo" },
{ "type": "vcs", "url": "http://svn.example.org/private/repo" },
{ "type": "vcs", "url": "http://github.com/mycompany/privaterepo2" }
],
"require": {
"company/package": "*",
"company/package2": "*",
"company/package3": "2.0.0"
}
}
```
Once you did this, you just run `php bin/satis build <configuration file> <build dir>`.
For example `php bin/satis build config.json web/` would read the `config.json`
@ -67,7 +81,8 @@ to ssh key authentication instead of prompting for a password. This is also a
good trick for continuous integration servers.
Set up a virtual-host that points to that `web/` directory, let's say it is
`packages.example.org`.
`packages.example.org`. Alternatively, with PHP >= 5.4.0, you can use the built-in
CLI server `php -S localhost:port -t satis-output-dir/` for a temporary solution.
## Usage
@ -77,14 +92,16 @@ everything should work smoothly. You don't need to copy all your repositories
in every project anymore. Only that one unique repository that will update
itself.
{
"repositories": [ { "type": "composer", "url": "http://packages.example.org/" } ],
"require": {
"company/package": "1.2.0",
"company/package2": "1.5.2",
"company/package3": "dev-master"
}
```json
{
"repositories": [ { "type": "composer", "url": "http://packages.example.org/" } ],
"require": {
"company/package": "1.2.0",
"company/package2": "1.5.2",
"company/package3": "dev-master"
}
}
```
### Security
@ -94,34 +111,101 @@ connection options for the server.
Example using a custom repository using SSH (requires the SSH2 PECL extension):
{
"repositories": [
{
"type": "composer",
"url": "ssh2.sftp://example.org",
"options": {
"ssh2": {
"username": "composer",
"pubkey_file": "/home/composer/.ssh/id_rsa.pub",
"privkey_file": "/home/composer/.ssh/id_rsa"
}
```json
{
"repositories": [
{
"type": "composer",
"url": "ssh2.sftp://example.org",
"options": {
"ssh2": {
"username": "composer",
"pubkey_file": "/home/composer/.ssh/id_rsa.pub",
"privkey_file": "/home/composer/.ssh/id_rsa"
}
}
]
}
}
]
}
```
> **Tip:** See [ssh2 context options](http://www.php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-options) for more information.
Example using HTTP over SSL using a client certificate:
{
"repositories": [
{
"type": "composer",
"url": "https://example.org",
"options": {
"ssl": {
"cert_file": "/home/composer/.ssl/composer.pem",
}
```json
{
"repositories": [
{
"type": "composer",
"url": "https://example.org",
"options": {
"ssl": {
"local_cert": "/home/composer/.ssl/composer.pem"
}
}
]
}
]
}
```
> **Tip:** See [ssl context options](http://www.php.net/manual/en/context.ssl.php) for more information.
### Downloads
When GitHub or BitBucket repositories are mirrored on your local satis, the build process will include
the location of the downloads these platforms make available. This means that the repository and your setup depend
on the availability of these services.
At the same time, this implies that all code which is hosted somewhere else (on another service or for example in
Subversion) will not have downloads available and thus installations usually take a lot longer.
To enable your satis installation to create downloads for all (Git, Mercurial and Subversion) your packages, add the
following to your `satis.json`:
```json
{
"archive": {
"directory": "dist",
"format": "tar",
"prefix-url": "https://amazing.cdn.example.org",
"skip-dev": true
}
}
```
#### Options explained
* `directory`: the location of the dist files (inside the `output-dir`)
* `format`: optional, `zip` (default) or `tar`
* `prefix-url`: optional, location of the downloads, homepage (from `satis.json`) followed by `directory` by default
* `skip-dev`: optional, `false` by default, when enabled (`true`) satis will not create downloads for branches
Once enabled, all downloads (include those from GitHub and BitBucket) will be replaced with a _local_ version.
#### prefix-url
Prefixing the URL with another host is especially helpful if the downloads end up in a private Amazon S3
bucket or on a CDN host. A CDN would drastically improve download times and therefore package installation.
Example: A `prefix-url` of `http://my-bucket.s3.amazonaws.com` (and `directory` set to `dist`) creates download URLs
which look like the following: `http://my-bucket.s3.amazonaws.com/dist/vendor-package-version-ref.zip`.
### Resolving dependencies
It is possible to make satis automatically resolve and add all dependencies for your projects. This can be used
with the Downloads functionality to have a complete local mirror of packages. Just add the following
to your `satis.json`:
```json
{
"require-dependencies": true,
"require-dev-dependencies": true
}
```
When searching for packages, satis will attempt to resolve all the required packages from the listed repositories.
Therefore, if you are requiring a package from Packagist, you will need to define it in your `satis.json`.
Dev dependencies are packaged only if the `require-dev-dependencies` parameter is set to true.

@ -0,0 +1,160 @@
<!--
tagline: Modify and extend Composer's functionality
-->
# Setting up and using plugins
## Synopsis
You may wish to alter or expand Composer's functionality with your own. For
example if your environment poses special requirements on the behaviour of
Composer which do not apply to the majority of its users or if you wish to
accomplish something with composer in a way that is not desired by most users.
In these cases you could consider creating a plugin to handle your
specific logic.
## Creating a Plugin
A plugin is a regular composer package which ships its code as part of the
package and may also depend on further packages.
### Plugin Package
The package file is the same as any other package file but with the following
requirements:
1. the [type][1] attribute must be `composer-plugin`.
2. the [extra][2] attribute must contain an element `class` defining the
class name of the plugin (including namespace). If a package contains
multiple plugins this can be array of class names.
Additionally you must require the special package called `composer-plugin-api`
to define which composer API versions your plugin is compatible with. The
current composer plugin API version is 1.0.0.
For example
```json
{
"name": "my/plugin-package",
"type": "composer-plugin",
"require": {
"composer-plugin-api": "1.0.0"
}
}
```
### Plugin Class
Every plugin has to supply a class which implements the
[`Composer\Plugin\PluginInterface`][3]. The `activate()` method of the plugin
is called after the plugin is loaded and receives an instance of
[`Composer\Composer`][4] as well as an instance of
[`Composer\IO\IOInterface`][5]. Using these two objects all configuration can
be read and all internal objects and state can be manipulated as desired.
Example:
```php
<?php
namespace phpDocumentor\Composer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class TemplateInstallerPlugin implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$installer = new TemplateInstaller($io, $composer);
$composer->getInstallationManager()->addInstaller($installer);
}
}
```
## Event Handler
Furthermore plugins may implement the
[`Composer\EventDispatcher\EventSubscriberInterface`][6] in order to have its
event handlers automatically registered with the `EventDispatcher` when the
plugin is loaded.
The events available for plugins are:
* **COMMAND**, is called at the beginning of all commands that load plugins.
It provides you with access to the input and output objects of the program.
* **PRE_FILE_DOWNLOAD**, is triggered before files are downloaded and allows
you to manipulate the `RemoteFilesystem` object prior to downloading files
based on the URL to be downloaded.
> A plugin can also subscribe to [script events][7].
Example:
```php
<?php
namespace Naderman\Composer\AWS;
use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PreFileDownloadEvent;
class AwsPlugin implements PluginInterface, EventSubscriberInterface
{
protected $composer;
protected $io;
public function activate(Composer $composer, IOInterface $io)
{
$this->composer = $composer;
$this->io = $io;
}
public static function getSubscribedEvents()
{
return array(
PluginEvents::PRE_FILE_DOWNLOAD => array(
array('onPreFileDownload', 0)
),
);
}
public function onPreFileDownload(PreFileDownloadEvent $event)
{
$protocol = parse_url($event->getProcessedUrl(), PHP_URL_SCHEME);
if ($protocol === 's3') {
$awsClient = new AwsClient($this->io, $this->composer->getConfig());
$s3RemoteFilesystem = new S3RemoteFilesystem($this->io, $event->getRemoteFilesystem()->getOptions(), $awsClient);
$event->setRemoteFilesystem($s3RemoteFilesystem);
}
}
}
```
## Using Plugins
Plugin packages are automatically loaded as soon as they are installed and will
be loaded when composer starts up if they are found in the current project's
list of installed packages. Additionally all plugin packages installed in the
`COMPOSER_HOME` directory using the composer global command are loaded before
local project plugins are loaded.
> You may pass the `--no-plugins` option to composer commands to disable all
> installed commands. This may be particularly helpful if any of the plugins
> causes errors and you wish to update or uninstall it.
[1]: ../04-schema.md#type
[2]: ../04-schema.md#extra
[3]: https://github.com/composer/composer/blob/master/src/Composer/Plugin/PluginInterface.php
[4]: https://github.com/composer/composer/blob/master/src/Composer/Composer.php
[5]: https://github.com/composer/composer/blob/master/src/Composer/IO/IOInterface.php
[6]: https://github.com/composer/composer/blob/master/src/Composer/EventDispatcher/EventSubscriberInterface.php
[7]: ./scripts.md#event-names

@ -11,9 +11,9 @@ static method) or any command-line executable command. Scripts are useful
for executing a package's custom code or package-specific commands during
the Composer execution process.
**NOTE: Only scripts defined in the root package's `composer.json` are
executed. If a dependency of the root package specifies its own scripts,
Composer does not execute those additional scripts.**
> **Note:** Only scripts defined in the root package's `composer.json` are
> executed. If a dependency of the root package specifies its own scripts,
> Composer does not execute those additional scripts.
## Event names
@ -24,13 +24,33 @@ Composer fires the following named events during its execution process:
- **post-install-cmd**: occurs after the `install` command is executed.
- **pre-update-cmd**: occurs before the `update` command is executed.
- **post-update-cmd**: occurs after the `update` command is executed.
- **pre-status-cmd**: occurs before the `status` command is executed.
- **post-status-cmd**: occurs after the `status` command is executed.
- **pre-dependencies-solving**: occurs before the dependencies are resolved.
- **post-dependencies-solving**: occurs after the dependencies are resolved.
- **pre-package-install**: occurs before a package is installed.
- **post-package-install**: occurs after a package is installed.
- **pre-package-update**: occurs before a package is updated.
- **post-package-update**: occurs after a package is updated.
- **pre-package-uninstall**: occurs before a package has been uninstalled.
- **post-package-uninstall**: occurs after a package has been uninstalled.
- **pre-autoload-dump**: occurs before the autoloader is dumped, either
during `install`/`update`, or via the `dump-autoload` command.
- **post-autoload-dump**: occurs after the autoloader is dumped, either
during `install`/`update`, or via the `dump-autoload` command.
- **post-root-package-install**: occurs after the root package has been
installed, during the `create-project` command.
- **post-create-project-cmd**: occurs after the `create-project` command is
executed.
- **pre-archive-cmd**: occurs before the `archive` command is executed.
- **post-archive-cmd**: occurs after the `archive` command is executed.
> **Note:** Composer makes no assumptions about the state of your dependencies
> prior to `install` or `update`. Therefore, you should not specify scripts
> that require Composer-managed dependencies in the `pre-update-cmd` or
> `pre-install-cmd` event hooks. If you need to execute scripts prior to
> `install` or `update` please make sure they are self-contained within your
> root package.
## Defining scripts
@ -43,54 +63,61 @@ For any given event:
- Scripts execute in the order defined when their corresponding event is fired.
- An array of scripts wired to a single event can contain both PHP callbacks
and command-line executables commands.
and command-line executable commands.
- PHP classes containing defined callbacks must be autoloadable via Composer's
autoload functionality.
Script definition example:
{
"scripts": {
"post-update-cmd": "MyVendor\\MyClass::postUpdate",
"post-package-install": [
"MyVendor\\MyClass::postPackageInstall"
]
"post-install-cmd": [
"MyVendor\\MyClass::warmCache",
"phpunit -c app/"
]
}
```json
{
"scripts": {
"post-update-cmd": "MyVendor\\MyClass::postUpdate",
"post-package-install": [
"MyVendor\\MyClass::postPackageInstall"
],
"post-install-cmd": [
"MyVendor\\MyClass::warmCache",
"phpunit -c app/"
],
"post-create-project-cmd" : [
"php -r \"copy('config/local-example.php', 'config/local.php');\""
]
}
}
```
Using the previous definition example, here's the class `MyVendor\MyClass`
that might be used to execute the PHP callbacks:
<?php
```php
<?php
namespace MyVendor;
namespace MyVendor;
use Composer\Script\Event;
use Composer\Script\Event;
class MyClass
{
public static function postUpdate(Event $event)
{
$composer = $event->getComposer();
// do stuff
}
class MyClass
public static function postPackageInstall(Event $event)
{
public static function postUpdate(Event $event)
{
$composer = $event->getComposer();
// do stuff
}
public static function postPackageInstall(Event $event)
{
$installedPackage = $event->getOperation()->getPackage();
// do stuff
}
public static function warmCache(Event $event)
{
// make cache toasty
}
$installedPackage = $event->getOperation()->getPackage();
// do stuff
}
public static function warmCache(Event $event)
{
// make cache toasty
}
}
```
When an event is fired, Composer's internal event handler receives a
`Composer\Script\Event` object, which is passed as the first argument to your
PHP callback. This `Event` object has getters for other contextual objects:
@ -99,3 +126,38 @@ PHP callback. This `Event` object has getters for other contextual objects:
- `getName()`: returns the name of the event being fired as a string
- `getIO()`: returns the current input/output stream which implements
`Composer\IO\IOInterface` for writing to the console
## Running scripts manually
If you would like to run the scripts for an event manually, the syntax is:
```sh
composer run-script [--dev] [--no-dev] script
```
For example `composer run-script post-install-cmd` will run any
**post-install-cmd** scripts that have been defined.
You can also give additional arguments to the script handler by appending `--`
followed by the handler arguments. e.g.
`composer run-script post-install-cmd -- --check` will pass`--check` along to
the script handler. Those arguments are received as CLI arg by CLI handlers,
and can be retrieved as an array via `$event->getArguments()` by PHP handlers.
## Writing custom commands
If you add custom scripts that do not fit one of the predefined event name
above, you can either run them with run-script or also run them as native
Composer commands. For example the handler defined below is executable by
simply running `composer test`:
```json
{
"scripts": {
"test": "phpunit"
}
}
```
> **Note:** Composer's bin-dir is pushed on top of the PATH so that binaries
> of dependencies are easily accessible as CLI commands when writing scripts.

@ -7,17 +7,22 @@ This is a list of common pitfalls on using Composer, and how to avoid them.
## General
1. When facing any kind of problems using Composer, be sure to **work with the
1. Before asking anyone, run [`composer diagnose`](../03-cli.md#diagnose) to check
for common problems. If it all checks out, proceed to the next steps.
2. When facing any kind of problems using Composer, be sure to **work with the
latest version**. See [self-update](../03-cli.md#self-update) for details.
2. Make sure you have no problems with your setup by running the installer's
checks via `curl -s https://getcomposer.org/installer | php -- --check`.
3. Make sure you have no problems with your setup by running the installer's
checks via `curl -sS https://getcomposer.org/installer | php -- --check`.
3. Ensure you're **installing vendors straight from your `composer.json`** via
4. Ensure you're **installing vendors straight from your `composer.json`** via
`rm -rf vendor && composer update -v` when troubleshooting, excluding any
possible interferences with existing vendor installations or `composer.lock`
entries.
5. Try clearing Composer's cache by running `composer clear-cache`.
## Package not found
1. Double-check you **don't have typos** in your `composer.json` or repository
@ -35,11 +40,50 @@ This is a list of common pitfalls on using Composer, and how to avoid them.
your repository, especially when maintaining a third party fork and using
`replace`.
5. If you are updating to a recently published version of a package, be aware that
Packagist has a delay of up to 1 minute before new packages are visible to Composer.
## Package not found on travis-ci.org
1. Check the ["Package not found"](#package-not-found) item above.
2. If the package tested is a dependency of one of its dependencies (cyclic
dependency), the problem might be that composer is not able to detect the version
of the package properly. If it is a git clone it is generally alright and Composer
will detect the version of the current branch, but travis does shallow clones so
that process can fail when testing pull requests and feature branches in general.
The best solution is to define the version you are on via an environment variable
called COMPOSER_ROOT_VERSION. You set it to `dev-master` for example to define
the root package's version as `dev-master`.
Use: `before_script: COMPOSER_ROOT_VERSION=dev-master composer install` to export
the variable for the call to composer.
## Need to override a package version
Let say your project depends on package A which in turn depends on a specific
version of package B (say 0.1) and you need a different version of that
package - version 0.11.
You can fix this by aliasing version 0.11 to 0.1:
composer.json:
```json
{
"require": {
"A": "0.2",
"B": "0.11 as 0.1"
}
}
```
See [aliases](aliases.md) for more information.
## Memory limit errors
If composer shows memory errors on some commands:
PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>
`PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>`
The PHP `memory_limit` should be increased.
@ -49,15 +93,66 @@ The PHP `memory_limit` should be increased.
To get the current `memory_limit` value, run:
php -r "echo ini_get('memory_limit').PHP_EOL;"
```sh
php -r "echo ini_get('memory_limit').PHP_EOL;"
```
Try increasing the limit in your `php.ini` file (ex. `/etc/php5/cli/php.ini` for
Debian-like systems):
; Use -1 for unlimited or define an explicit value like 512M
memory_limit = -1
```ini
; Use -1 for unlimited or define an explicit value like 512M
memory_limit = -1
```
Or, you can increase the limit with a command-line argument:
php -d memory_limit=-1 composer.phar <...>
```sh
php -d memory_limit=-1 composer.phar <...>
```
## "The system cannot find the path specified" (Windows)
1. Open regedit.
2. Search for an ```AutoRun``` key inside ```HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor```
or ```HKEY_CURRENT_USER\Software\Microsoft\Command Processor```.
3. Check if it contains any path to non-existent file, if it's the case, just remove them.
## API rate limit and OAuth tokens
Because of GitHub's rate limits on their API it can happen that Composer prompts
for authentication asking your username and password so it can go ahead with its work.
If you would prefer not to provide your GitHub credentials to Composer you can
manually create a token using the following procedure:
1. [Create](https://github.com/settings/applications) an OAuth token on GitHub.
[Read more](https://github.com/blog/1509-personal-api-tokens) on this.
2. Add it to the configuration running `composer config -g github-oauth.github.com <oauthtoken>`
Now Composer should install/update without asking for authentication.
## proc_open(): fork failed errors
If composer shows proc_open() fork failed on some commands:
`PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar`
This could be happening because the VPS runs out of memory and has no Swap space enabled.
```sh
free -m
total used free shared buffers cached
Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0
```
To enable the swap you can use for example:
```sh
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
```

@ -2,66 +2,71 @@
tagline: Expose command-line scripts from packages
-->
# bin and vendor/bin
# Vendor binaries and the `vendor/bin` directory
## What is a bin?
## What is a vendor binary?
Any command line script that a Composer package would like to pass along
to a user who installs the package should be listed as a bin.
to a user who installs the package should be listed as a vendor binary.
If a package contains other scripts that are not needed by the package
users (like build or compile scripts) that code should not be listed
as a bin.
as a vendor binary.
## How is it defined?
It is defined by adding the `bin` key to a project's `composer.json`.
It is specified as an array of files so multiple bins can be added
It is specified as an array of files so multiple binaries can be added
for any given project.
{
"bin": ["bin/my-script", "bin/my-other-script"]
}
```json
{
"bin": ["bin/my-script", "bin/my-other-script"]
}
```
## What does defining a bin in composer.json do?
## What does defining a vendor binary in composer.json do?
It instructs Composer to install the package's bins to `vendor/bin`
It instructs Composer to install the package's binaries to `vendor/bin`
for any project that **depends** on that project.
This is a convenient way to expose useful scripts that would
otherwise be hidden deep in the `vendor/` directory.
## What happens when Composer is run on a composer.json that defines bins?
## What happens when Composer is run on a composer.json that defines vendor binaries?
For the bins that a package defines directly, nothing happens.
For the binaries that a package defines directly, nothing happens.
## What happens when Composer is run on a composer.json that has dependencies with bins listed?
## What happens when Composer is run on a composer.json that has dependencies with vendor binaries listed?
Composer looks for the bins defined in all of the dependencies. A
symlink is created from each dependency's bins to `vendor/bin`.
Composer looks for the binaries defined in all of the dependencies. A
symlink is created from each dependency's binaries to `vendor/bin`.
Say package `my-vendor/project-a` has bins setup like this:
Say package `my-vendor/project-a` has binaries setup like this:
{
"name": "my-vendor/project-a",
"bin": ["bin/project-a-bin"]
}
```json
{
"name": "my-vendor/project-a",
"bin": ["bin/project-a-bin"]
}
```
Running `composer install` for this `composer.json` will not do
anything with `bin/project-a-bin`.
Say project `my-vendor/project-b` has requirements setup like this:
{
"name": "my-vendor/project-b",
"requires": {
"my-vendor/project-a": "*"
}
```json
{
"name": "my-vendor/project-b",
"require": {
"my-vendor/project-a": "*"
}
}
```
Running `composer install` for this `composer.json` will look at
all of project-b's dependencies and install them to `vendor/bin`.
@ -75,32 +80,36 @@ this is accomplished by creating a symlink.
Packages managed entirely by Composer do not *need* to contain any
`.bat` files for Windows compatibility. Composer handles installation
of bins in a special way when run in a Windows environment:
of binaries in a special way when run in a Windows environment:
* A `.bat` files is generated automatically to reference the bin
* A Unix-style proxy file with the same name as the bin is generated
* A `.bat` file is generated automatically to reference the binary
* A Unix-style proxy file with the same name as the binary is generated
automatically (useful for Cygwin or Git Bash)
Packages that need to support workflows that may not include Composer
are welcome to maintain custom `.bat` files. In this case, the package
should **not** list the `.bat` file as a bin as it is not needed.
should **not** list the `.bat` file as a binary as it is not needed.
## Can vendor bins be installed somewhere other than vendor/bin?
## Can vendor binaries be installed somewhere other than vendor/bin?
Yes, there are two ways that an alternate vendor bin location can be specified.
Yes, there are two ways an alternate vendor binary location can be specified:
* Setting the `bin-dir` configuration setting in `composer.json`
* Setting the environment variable `COMPOSER_BIN_DIR`
1. Setting the `bin-dir` configuration setting in `composer.json`
1. Setting the environment variable `COMPOSER_BIN_DIR`
An example of the former looks like this:
{
"config": {
"bin-dir": "scripts"
}
```json
{
"config": {
"bin-dir": "scripts"
}
}
```
Running `composer install` for this `composer.json` will result in
all of the vendor bins being installed in `scripts/` instead of
all of the vendor binaries being installed in `scripts/` instead of
`vendor/bin/`.
You can set `bin-dir` to `./` to put binaries in your project root.

@ -11,13 +11,15 @@ This is common if your package is intended for a specific framework such as
CakePHP, Drupal or WordPress. Here is an example composer.json file for a
WordPress theme:
{
"name": "you/themename",
"type": "wordpress-theme",
"require": {
"composer/installers": "*"
}
```json
{
"name": "you/themename",
"type": "wordpress-theme",
"require": {
"composer/installers": "~1.0"
}
}
```
Now when your theme is installed with Composer it will be placed into
`wp-content/themes/themename/` folder. Check the
@ -30,13 +32,15 @@ useful example would be for a Drupal multisite setup where the package should be
installed into your sites subdirectory. Here we are overriding the install path
for a module that uses composer/installers:
{
"extra": {
"installer-paths": {
"sites/example.com/modules/{$name}": ["vendor/package"]
}
```json
{
"extra": {
"installer-paths": {
"sites/example.com/modules/{$name}": ["vendor/package"]
}
}
}
```
Now the package would be installed to your folder location, rather than the default
composer/installers determined location.

@ -16,11 +16,16 @@ problems:
submodules. This is problematic because they are not real submodules, and you
will run into issues.
If you really feel like you must do this, you have two options:
If you really feel like you must do this, you have a few options:
- Limit yourself to installing tagged releases (no dev versions), so that you
only get zipped installs, and avoid problems with the git "submodules".
- Remove the `.git` directory of every dependency after the installation, then
you can add them to your git repo. You can do that with `rm -rf vendor/**/.git`
but this means you will have to delete those dependencies from disk before
running composer update.
1. Limit yourself to installing tagged releases (no dev versions), so that you
only get zipped installs, and avoid problems with the git "submodules".
2. Use --prefer-dist or set `preferred-install` to `dist` in your
[config](../04-schema.md#config).
3. Remove the `.git` directory of every dependency after the installation, then
you can add them to your git repo. You can do that with `rm -rf vendor/**/.git`
but this means you will have to delete those dependencies from disk before
running composer update.
4. Add a .gitignore rule (`vendor/.git`) to ignore all the vendor `.git` folders.
This approach does not require that you delete dependencies from disk prior to
running a composer update.

@ -0,0 +1,21 @@
# Why are unbound version constraints a bad idea?
A version constraint without an upper bound such as `*`, `>=3.4` or
`dev-master` will allow updates to any future version of the dependency.
This includes major versions breaking backward compatibility.
Once a release of your package is tagged, you cannot tweak its dependencies
anymore in case a dependency breaks BC - you have to do a new release but the
previous one stays broken.
The only good alternative is to define an upper bound on your constraints,
which you can increase in a new release after testing that your package is
compatible with the new major version of your dependency.
For example instead of using `>=3.4` you should use `~3.4` which allows all
versions up to `3.999` but does not include `4.0` and above. The `~` operator
works very well with libraries follow [semantic versioning](http://semver.org).
**Note:** As a package maintainer, you can make the life of your users easier
by providing an [alias version](../articles/aliases.md) for your development
branch to allow it to match bound constraints.

@ -9,7 +9,7 @@ that the main use of custom VCS & package repositories is to temporarily try
some things, or use a fork of a project until your pull request is merged, etc.
You should not use them to keep track of private packages. For that you should
look into [setting up Satis](../articles/handling-private-packages-with-satis.md)
for your company or even for yourself.
or getting a [Toran Proxy](https://toranproxy.com) license for your company.
There are three ways the dependency solver could work with custom repositories:

@ -9,11 +9,11 @@
"required": true
},
"type": {
"description": "Package type, either 'library' for common packages, 'composer-installer' for custom installers, 'metapackage' for empty packages, or a custom type ([a-z0-9-]+) defined by whatever project this package applies to.",
"description": "Package type, either 'library' for common packages, 'composer-plugin' for plugins, 'metapackage' for empty packages, or a custom type ([a-z0-9-]+) defined by whatever project this package applies to.",
"type": "string"
},
"target-dir": {
"description": "Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.",
"description": "DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.",
"type": "string"
},
"description": {
@ -39,7 +39,7 @@
},
"time": {
"type": "string",
"description": "Package release date, in 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' format."
"description": "Package release date, in 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DDTHH:MM:SSZ' format."
},
"license": {
"type": ["string", "array"],
@ -105,9 +105,46 @@
"additionalProperties": true
},
"config": {
"type": ["object"],
"type": "object",
"description": "Composer options.",
"properties": {
"process-timeout": {
"type": "integer",
"description": "The timeout in seconds for process executions, defaults to 300 (5mins)."
},
"use-include-path": {
"type": "boolean",
"description": "If true, the Composer autoloader will also look for classes in the PHP include path."
},
"preferred-install": {
"type": "string",
"description": "The install method Composer will prefer to use, defaults to auto and can be any of source, dist or auto."
},
"notify-on-install": {
"type": "boolean",
"description": "Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour, defaults to true."
},
"github-protocols": {
"type": "array",
"description": "A list of protocols to use for github.com clones, in priority order, defaults to [\"git\", \"https\", \"http\"].",
"items": {
"type": "string"
}
},
"github-oauth": {
"type": "object",
"description": "A hash of domain name => github API oauth tokens, typically {\"github.com\":\"<token>\"}.",
"additionalProperties": true
},
"http-basic": {
"type": "object",
"description": "A hash of domain name => {\"username\": \"...\", \"password\": \"...\"}.",
"additionalProperties": true
},
"store-auths": {
"type": ["string", "boolean"],
"description": "What to do after prompting for authentication, one of: true (store), false (do not store) or \"prompt\" (ask every time), defaults to prompt."
},
"vendor-dir": {
"type": "string",
"description": "The location where all packages are installed, defaults to \"vendor\"."
@ -116,17 +153,53 @@
"type": "string",
"description": "The location where all binaries are linked, defaults to \"vendor/bin\"."
},
"process-timeout": {
"cache-dir": {
"type": "string",
"description": "The location where all caches are located, defaults to \"~/.composer/cache\" on *nix and \"%LOCALAPPDATA%\\Composer\" on windows."
},
"cache-files-dir": {
"type": "string",
"description": "The location where files (zip downloads) are cached, defaults to \"{$cache-dir}/files\"."
},
"cache-repo-dir": {
"type": "string",
"description": "The location where repo (git/hg repo clones) are cached, defaults to \"{$cache-dir}/repo\"."
},
"cache-vcs-dir": {
"type": "string",
"description": "The location where vcs infos (git clones, github api calls, etc. when reading vcs repos) are cached, defaults to \"{$cache-dir}/vcs\"."
},
"cache-ttl": {
"type": "integer",
"description": "The timeout in seconds for process executions, defaults to 300 (5mins)."
"description": "The default cache time-to-live, defaults to 15552000 (6 months)."
},
"notify-on-install": {
"cache-files-ttl": {
"type": "integer",
"description": "The cache time-to-live for files, defaults to the value of cache-ttl."
},
"cache-files-maxsize": {
"type": ["string", "integer"],
"description": "The cache max size for the files cache, defaults to \"300MiB\"."
},
"discard-changes": {
"type": ["string", "boolean"],
"description": "The default style of handling dirty updates, defaults to false and can be any of true, false or \"stash\"."
},
"autoloader-suffix": {
"type": "string",
"description": "Optional string to be used as a suffix for the generated Composer autoloader. When null a random one will be generated."
},
"optimize-autoloader": {
"type": "boolean",
"description": "Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour, defaults to true."
"description": "Always optimize when dumping the autoloader."
},
"github-protocols": {
"prepend-autoloader": {
"type": "boolean",
"description": "If false, the composer autoloader will not be prepended to existing autoloaders, defaults to true."
},
"github-domains": {
"type": "array",
"description": "A list of protocols to use for github.com clones, in priority order, defaults to [\"git\", \"https\", \"http\"].",
"description": "A list of domains to use in github mode. This is used for GitHub Enterprise setups, defaults to [\"github.com\"].",
"items": {
"type": "string"
}
@ -135,7 +208,7 @@
},
"extra": {
"type": ["object", "array"],
"description": "Arbitrary extra data that can be used by custom installers, for example, package of type composer-installer must have a 'class' key defining the installer class name.",
"description": "Arbitrary extra data that can be used by plugins, for example, package of type composer-plugin may have a 'class' key defining an installer class name.",
"additionalProperties": true
},
"autoload": {
@ -147,6 +220,35 @@
"description": "This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.",
"additionalProperties": true
},
"psr-4": {
"type": "object",
"description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.",
"additionalProperties": true
},
"classmap": {
"type": "array",
"description": "This is an array of directories that contain classes to be included in the class-map generation process."
},
"files": {
"type": "array",
"description": "This is an array of files that are always required on every request."
}
}
},
"autoload-dev": {
"type": "object",
"description": "Description of additional autoload rules for development purpose (eg. a test suite).",
"properties": {
"psr-0": {
"type": "object",
"description": "This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.",
"additionalProperties": true
},
"psr-4": {
"type": "object",
"description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.",
"additionalProperties": true
},
"classmap": {
"type": "array",
"description": "This is an array of directories that contain classes to be included in the class-map generation process."
@ -157,6 +259,16 @@
}
}
},
"archive": {
"type": ["object"],
"description": "Options for creating package archives for distribution.",
"properties": {
"exclude": {
"type": "array",
"description": "A list of patterns for paths to exclude or include if prefixed with an exclamation mark."
}
}
},
"repositories": {
"type": ["object", "array"],
"description": "A set of additional repositories where packages can be found.",
@ -166,6 +278,10 @@
"type": ["string"],
"description": "The minimum stability the packages must have to be install-able. Possible values are: dev, alpha, beta, RC, stable."
},
"prefer-stable": {
"type": ["boolean"],
"description": "If set to true, stable packages will be prefered to dev packages when possible, even if the minimum-stability allows unstable packages."
},
"bin": {
"type": ["array"],
"description": "A set of files that should be treated as binaries and symlinked into bin-dir (from config).",
@ -186,43 +302,67 @@
"properties": {
"pre-install-cmd": {
"type": ["array", "string"],
"description": "Occurs before the install command is executed, contains one or more Class::method callables."
"description": "Occurs before the install command is executed, contains one or more Class::method callables or shell commands."
},
"post-install-cmd": {
"type": ["array", "string"],
"description": "Occurs after the install command is executed, contains one or more Class::method callables."
"description": "Occurs after the install command is executed, contains one or more Class::method callables or shell commands."
},
"pre-update-cmd": {
"type": ["array", "string"],
"description": "Occurs before the update command is executed, contains one or more Class::method callables."
"description": "Occurs before the update command is executed, contains one or more Class::method callables or shell commands."
},
"post-update-cmd": {
"type": ["array", "string"],
"description": "Occurs after the update command is executed, contains one or more Class::method callables."
"description": "Occurs after the update command is executed, contains one or more Class::method callables or shell commands."
},
"pre-status-cmd": {
"type": ["array", "string"],
"description": "Occurs before the status command is executed, contains one or more Class::method callables or shell commands."
},
"post-status-cmd": {
"type": ["array", "string"],
"description": "Occurs after the status command is executed, contains one or more Class::method callables or shell commands."
},
"pre-package-install": {
"type": ["array", "string"],
"description": "Occurs before a package is installed, contains one or more Class::method callables."
"description": "Occurs before a package is installed, contains one or more Class::method callables or shell commands."
},
"post-package-install": {
"type": ["array", "string"],
"description": "Occurs after a package is installed, contains one or more Class::method callables."
"description": "Occurs after a package is installed, contains one or more Class::method callables or shell commands."
},
"pre-package-update": {
"type": ["array", "string"],
"description": "Occurs before a package is updated, contains one or more Class::method callables."
"description": "Occurs before a package is updated, contains one or more Class::method callables or shell commands."
},
"post-package-update": {
"type": ["array", "string"],
"description": "Occurs after a package is updated, contains one or more Class::method callables."
"description": "Occurs after a package is updated, contains one or more Class::method callables or shell commands."
},
"pre-package-uninstall": {
"type": ["array", "string"],
"description": "Occurs before a package has been uninstalled, contains one or more Class::method callables."
"description": "Occurs before a package has been uninstalled, contains one or more Class::method callables or shell commands."
},
"post-package-uninstall": {
"type": ["array", "string"],
"description": "Occurs after a package has been uninstalled, contains one or more Class::method callables."
"description": "Occurs after a package has been uninstalled, contains one or more Class::method callables or shell commands."
},
"pre-autoload-dump": {
"type": ["array", "string"],
"description": "Occurs before the autoloader is dumped, contains one or more Class::method callables or shell commands."
},
"post-autoload-dump": {
"type": ["array", "string"],
"description": "Occurs after the autoloader is dumped, contains one or more Class::method callables or shell commands."
},
"post-root-package-install": {
"type": ["array", "string"],
"description": "Occurs after the root-package is installed, contains one or more Class::method callables or shell commands."
},
"post-create-project-cmd": {
"type": ["array", "string"],
"description": "Occurs after the create-project command is executed, contains one or more Class::method callables or shell commands."
}
}
},

@ -1,34 +1,44 @@
[
"AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "APL-1.0",
"AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "APL-1.0", "Aladdin",
"ANTLR-PD", "Apache-1.0", "Apache-1.1", "Apache-2.0", "APSL-1.0",
"APSL-1.1", "APSL-1.2", "APSL-2.0", "Artistic-1.0", "Artistic-2.0", "AAL",
"BSL-1.0", "BSD-2-Clause", "BSD-2-Clause-NetBSD", "BSD-2-Clause-FreeBSD",
"BSD-3-Clause", "BSD-4-Clause", "BSD-4-Clause-UC", "CECILL-1.0",
"CECILL-1.1", "CECILL-2.0", "CECILL-B", "CECILL-C", "ClArtistic",
"CNRI-Python-GPL-Compatible", "CNRI-Python", "CDDL-1.0", "CDDL-1.1",
"CPAL-1.0", "CPL-1.0", "CATOSL-1.1", "CC-BY-1.0", "CC-BY-2.0", "CC-BY-2.5",
"CC-BY-3.0", "CC-BY-ND-1.0", "CC-BY-ND-2.0", "CC-BY-ND-2.5", "CC-BY-ND-3.0",
"APSL-1.1", "APSL-1.2", "APSL-2.0", "Artistic-1.0", "Artistic-1.0-cl8",
"Artistic-1.0-Perl", "Artistic-2.0", "AAL", "BitTorrent-1.0",
"BitTorrent-1.1", "BSL-1.0", "BSD-2-Clause", "BSD-2-Clause-FreeBSD",
"BSD-2-Clause-NetBSD", "BSD-3-Clause", "BSD-3-Clause-Clear", "BSD-4-Clause",
"BSD-4-Clause-UC", "CECILL-1.0", "CECILL-1.1", "CECILL-2.0", "CECILL-B",
"CECILL-C", "ClArtistic", "CNRI-Python", "CNRI-Python-GPL-Compatible",
"CPOL-1.02", "CDDL-1.0", "CDDL-1.1", "CPAL-1.0", "CPL-1.0", "CATOSL-1.1",
"Condor-1.1", "CC-BY-1.0", "CC-BY-2.0", "CC-BY-2.5", "CC-BY-3.0",
"CC-BY-ND-1.0", "CC-BY-ND-2.0", "CC-BY-ND-2.5", "CC-BY-ND-3.0",
"CC-BY-NC-1.0", "CC-BY-NC-2.0", "CC-BY-NC-2.5", "CC-BY-NC-3.0",
"CC-BY-NC-ND-1.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-2.5", "CC-BY-NC-ND-3.0",
"CC-BY-NC-SA-1.0", "CC-BY-NC-SA-2.0", "CC-BY-NC-SA-2.5", "CC-BY-NC-SA-3.0",
"CC-BY-SA-1.0", "CC-BY-SA-2.0", "CC-BY-SA-2.5", "CC-BY-SA-3.0", "CC0-1.0",
"CUA-OPL-1.0", "EPL-1.0", "eCos-2.0", "ECL-1.0", "ECL-2.0", "EFL-1.0",
"EFL-2.0", "Entessa", "ErlPL-1.1", "EUDatagrid", "EUPL-1.0", "EUPL-1.1",
"Fair", "Frameworx-1.0", "AGPL-3.0", "GFDL-1.1", "GFDL-1.2", "GFDL-1.3",
"GPL-1.0", "GPL-1.0+", "GPL-2.0", "GPL-2.0+",
"GPL-2.0-with-autoconf-exception", "GPL-2.0-with-bison-exception",
"GPL-2.0-with-classpath-exception", "GPL-2.0-with-font-exception",
"GPL-2.0-with-GCC-exception", "GPL-3.0", "GPL-3.0+",
"GPL-3.0-with-autoconf-exception", "GPL-3.0-with-GCC-exception", "LGPL-2.1",
"LGPL-2.1+", "LGPL-3.0", "LGPL-3.0+", "LGPL-2.0", "LGPL-2.0+", "gSOAP-1.3b",
"HPND", "IPL-1.0", "IPA", "ISC", "LPPL-1.0", "LPPL-1.1", "LPPL-1.2",
"LPPL-1.3c", "Libpng", "LPL-1.0", "LPL-1.02", "MS-PL", "MS-RL", "MirOS",
"MIT", "Motosoto", "MPL-1.0", "MPL-1.1", "MPL-2.0", "Multics", "NASA-1.3",
"Naumen", "NGPL", "Nokia", "NPOSL-3.0", "NTP", "OCLC-2.0", "ODbL-1.0",
"PDDL-1.0", "OGTSL", "OSL-1.0", "OSL-2.0", "OSL-2.1", "OSL-3.0",
"OLDAP-2.8", "OpenSSL", "PHP-3.0", "PHP-3.01", "PostgreSQL", "Python-2.0",
"QPL-1.0", "RPSL-1.0", "RPL-1.5", "RHeCos-1.1", "RSCPL", "Ruby", "SAX-PD",
"OFL-1.0", "OFL-1.1", "SimPL-2.0", "Sleepycat", "SugarCRM-1.1.3", "SPL-1.0",
"Watcom-1.0", "NCSA", "VSL-1.0", "W3C", "WXwindows", "Xnet", "XFree86-1.1",
"YPL-1.0", "YPL-1.1", "Zimbra-1.3", "Zlib", "ZPL-1.1", "ZPL-2.0", "ZPL-2.1"
"CUA-OPL-1.0", "D-FSL-1.0", "WTFPL", "EPL-1.0", "eCos-2.0", "ECL-1.0",
"ECL-2.0", "EFL-1.0", "EFL-2.0", "Entessa", "ErlPL-1.1", "EUDatagrid",
"EUPL-1.0", "EUPL-1.1", "Fair", "Frameworx-1.0", "FTL", "AGPL-1.0",
"AGPL-3.0", "GFDL-1.1", "GFDL-1.2", "GFDL-1.3", "GPL-1.0", "GPL-1.0+",
"GPL-2.0", "GPL-2.0+", "GPL-2.0-with-autoconf-exception",
"GPL-2.0-with-bison-exception", "GPL-2.0-with-classpath-exception",
"GPL-2.0-with-font-exception", "GPL-2.0-with-GCC-exception", "GPL-3.0",
"GPL-3.0+", "GPL-3.0-with-autoconf-exception", "GPL-3.0-with-GCC-exception",
"LGPL-2.1", "LGPL-2.1+", "LGPL-3.0", "LGPL-3.0+", "LGPL-2.0", "LGPL-2.0+",
"gSOAP-1.3b", "HPND", "IBM-pibs", "IPL-1.0", "Imlib2", "IJG", "Intel",
"IPA", "ISC", "JSON", "LPPL-1.3a", "LPPL-1.0", "LPPL-1.1", "LPPL-1.2",
"LPPL-1.3c", "Libpng", "LPL-1.02", "LPL-1.0", "MS-PL", "MS-RL", "MirOS",
"MIT", "Motosoto", "MPL-1.0", "MPL-1.1", "MPL-2.0",
"MPL-2.0-no-copyleft-exception", "Multics", "NASA-1.3", "Naumen",
"NBPL-1.0", "NGPL", "NOSL", "NPL-1.0", "NPL-1.1", "Nokia", "NPOSL-3.0",
"NTP", "OCLC-2.0", "ODbL-1.0", "PDDL-1.0", "OGTSL", "OLDAP-2.2.2",
"OLDAP-1.1", "OLDAP-1.2", "OLDAP-1.3", "OLDAP-1.4", "OLDAP-2.0",
"OLDAP-2.0.1", "OLDAP-2.1", "OLDAP-2.2", "OLDAP-2.2.1", "OLDAP-2.3",
"OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.6", "OLDAP-2.7", "OPL-1.0", "OSL-1.0",
"OSL-2.0", "OSL-2.1", "OSL-3.0", "OLDAP-2.8", "OpenSSL", "PHP-3.0",
"PHP-3.01", "PostgreSQL", "Python-2.0", "QPL-1.0", "RPSL-1.0", "RPL-1.1",
"RPL-1.5", "RHeCos-1.1", "RSCPL", "Ruby", "SAX-PD", "SGI-B-1.0",
"SGI-B-1.1", "SGI-B-2.0", "OFL-1.0", "OFL-1.1", "SimPL-2.0", "Sleepycat",
"SMLNJ", "SugarCRM-1.1.3", "SISSL", "SISSL-1.2", "SPL-1.0", "Watcom-1.0",
"NCSA", "VSL-1.0", "W3C", "WXwindows", "Xnet", "X11", "XFree86-1.1",
"YPL-1.0", "YPL-1.1", "Zimbra-1.3", "Zlib", "ZPL-1.1", "ZPL-2.0", "ZPL-2.1",
"Unlicense"
]

@ -13,11 +13,14 @@
namespace Composer\Autoload;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Installer\InstallationManager;
use Composer\IO\IOInterface;
use Composer\Package\AliasPackage;
use Composer\Package\PackageInterface;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Util\Filesystem;
use Composer\Script\ScriptEvents;
/**
* @author Igor Wiedler <igor@wiedler.ch>
@ -25,57 +28,109 @@ use Composer\Util\Filesystem;
*/
class AutoloadGenerator
{
public function dump(Config $config, RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
/**
* @var EventDispatcher
*/
private $eventDispatcher;
/**
* @var IOInterface
*/
private $io;
private $devMode = false;
public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null)
{
$this->eventDispatcher = $eventDispatcher;
$this->io = $io;
}
public function setDevMode($devMode = true)
{
$this->devMode = (boolean) $devMode;
}
public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
{
$this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array(
'optimize' => (bool) $scanPsr0Packages
));
$filesystem = new Filesystem();
$filesystem->ensureDirectoryExists($config->get('vendor-dir'));
$vendorPath = strtr(realpath($config->get('vendor-dir')), '\\', '/');
$basePath = $filesystem->normalizePath(realpath(getcwd()));
$vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
$useGlobalIncludePath = (bool) $config->get('use-include-path');
$prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
$targetDir = $vendorPath.'/'.$targetDir;
$filesystem->ensureDirectoryExists($targetDir);
$relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
$vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
$vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
$vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
$appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
$appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
$appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
$namespacesFile = <<<EOF
<?php
// autoload_namespaces.php generated by Composer
// autoload_namespaces.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
EOF;
$packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
$psr4File = <<<EOF
<?php
// autoload_psr4.php @generated by Composer
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
EOF;
// Collect information from all packages.
$packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
$autoloads = $this->parseAutoloads($packageMap, $mainPackage);
// Process the 'psr-0' base directories.
foreach ($autoloads['psr-0'] as $namespace => $paths) {
$exportedPaths = array();
foreach ($paths as $path) {
$exportedPaths[] = $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path);
$exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
}
$exportedPrefix = var_export($namespace, true);
$namespacesFile .= " $exportedPrefix => ";
if (count($exportedPaths) > 1) {
$namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
} else {
$namespacesFile .= $exportedPaths[0].",\n";
}
$namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
}
$namespacesFile .= ");\n";
// Process the 'psr-4' base directories.
foreach ($autoloads['psr-4'] as $namespace => $paths) {
$exportedPaths = array();
foreach ($paths as $path) {
$exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
}
$exportedPrefix = var_export($namespace, true);
$psr4File .= " $exportedPrefix => ";
$psr4File .= "array(".implode(', ', $exportedPaths)."),\n";
}
$psr4File .= ");\n";
$classmapFile = <<<EOF
<?php
// autoload_classmap.php generated by Composer
// autoload_classmap.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$vendorDir = $vendorPathCode52;
\$baseDir = $appBaseDirCode;
return array(
@ -86,11 +141,11 @@ EOF;
$targetDirLoader = null;
$mainAutoload = $mainPackage->getAutoload();
if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
$levels = count(explode('/', trim(strtr($mainPackage->getTargetDir(), '\\', '/'), '/')));
$levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
$prefixes = implode(', ', array_map(function ($prefix) {
return var_export($prefix, true);
}, array_keys($mainAutoload['psr-0'])));
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, getcwd(), true);
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
$targetDirLoader = <<<EOF
@ -118,22 +173,25 @@ EOF;
// flatten array
$classMap = array();
if ($scanPsr0Packages) {
foreach ($autoloads['psr-0'] as $namespace => $paths) {
foreach ($paths as $dir) {
$dir = $this->getPath($filesystem, $relVendorPath, $vendorPath, $dir);
$whitelist = sprintf(
'{%s/%s.+(?<!(?<!/)Test\.php)$}',
preg_quote(rtrim($dir, '/')),
strpos($namespace, '_') === false ? preg_quote(strtr($namespace, '\\', '/')) : ''
);
if (!is_dir($dir)) {
continue;
}
foreach (ClassMapGenerator::createMap($dir, $whitelist) as $class => $path) {
if ('' === $namespace || 0 === strpos($class, $namespace)) {
$path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
// Scan the PSR-0/4 directories for class files, and add them to the class map
foreach (array('psr-0', 'psr-4') as $psrType) {
foreach ($autoloads[$psrType] as $namespace => $paths) {
foreach ($paths as $dir) {
$dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
if (!is_dir($dir)) {
continue;
}
$whitelist = sprintf(
'{%s/%s.+(?<!(?<!/)Test\.php)$}',
preg_quote($dir),
($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
);
$namespaceFilter = $namespace === '' ? null : $namespace;
foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) {
if (!isset($classMap[$class])) {
$classMap[$class] = '$baseDir . '.var_export($path, true).",\n";
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
}
}
}
@ -141,11 +199,10 @@ EOF;
}
}
$autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
foreach ($autoloads['classmap'] as $dir) {
foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
$path = '/'.$filesystem->findShortestPath(getcwd(), $path, true);
$classMap[$class] = '$baseDir . '.var_export($path, true).",\n";
foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
}
}
@ -155,24 +212,34 @@ EOF;
}
$classmapFile .= ");\n";
$filesCode = "";
$autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
foreach ($autoloads['files'] as $functionFile) {
$filesCode .= ' require '.$this->getPathCode($filesystem, $relVendorPath, $vendorPath, $functionFile).";\n";
}
if (!$suffix) {
$suffix = md5(uniqid('', true));
$suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
}
file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)) {
if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
file_put_contents($targetDir.'/include_paths.php', $includePathFile);
}
if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
file_put_contents($targetDir.'/autoload_files.php', $includeFilesFile);
}
file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, true, (bool) $includePathFile, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix));
copy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php');
file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
// use stream_copy_to_stream instead of copy
// to work around https://bugs.php.net/bug.php?id=64634
$sourceLoader = fopen(__DIR__.'/ClassLoader.php', 'r');
$targetLoader = fopen($targetDir.'/ClassLoader.php', 'w+');
stream_copy_to_stream($sourceLoader, $targetLoader);
fclose($sourceLoader);
fclose($targetLoader);
unset($sourceLoader, $targetLoader);
$this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
'optimize' => (bool) $scanPsr0Packages,
));
}
public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
@ -184,6 +251,7 @@ EOF;
if ($package instanceof AliasPackage) {
continue;
}
$this->validatePackage($package);
$packageMap[] = array(
$package,
@ -194,6 +262,28 @@ EOF;
return $packageMap;
}
/**
* @param PackageInterface $package
*
* @throws \InvalidArgumentException Throws an exception, if the package has illegal settings.
*/
protected function validatePackage(PackageInterface $package)
{
$autoload = $package->getAutoload();
if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
$name = $package->getName();
$package->getTargetDir();
throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
}
if (!empty($autoload['psr-4'])) {
foreach ($autoload['psr-4'] as $namespace => $dirs) {
if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
}
}
}
}
/**
* Compiles an ordered list of namespace => path mappings
*
@ -209,12 +299,14 @@ EOF;
array_unshift($packageMap, $mainPackageMap);
$psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
$psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
$classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
$files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
krsort($psr0);
krsort($psr4);
return array('psr-0' => $psr0, 'classmap' => $classmap, 'files' => $files);
return array('psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files);
}
/**
@ -233,10 +325,16 @@ EOF;
}
}
if (isset($autoloads['psr-4'])) {
foreach ($autoloads['psr-4'] as $namespace => $path) {
$loader->addPsr4($namespace, $path);
}
}
return $loader;
}
protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)
protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
{
$includePaths = array();
@ -257,59 +355,78 @@ EOF;
return;
}
$includePathsFile = <<<EOF
$includePathsCode = '';
foreach ($includePaths as $path) {
$includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
}
return <<<EOF
<?php
// include_paths.php generated by Composer
// include_paths.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$baseDir = $appBaseDirCode;
return array(
$includePathsCode);
EOF;
}
foreach ($includePaths as $path) {
$includePathsFile .= " " . $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path) . ",\n";
protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
{
$filesCode = '';
foreach ($files as $functionFile) {
$filesCode .= ' '.$this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile).",\n";
}
return $includePathsFile . ");\n";
if (!$filesCode) {
return FALSE;
}
return <<<EOF
<?php
// autoload_files.php @generated by Composer
\$vendorDir = $vendorPathCode;
\$baseDir = $appBaseDirCode;
return array(
$filesCode);
EOF;
}
protected function getPathCode(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
{
$path = strtr($path, '\\', '/');
$baseDir = '';
if (!$filesystem->isAbsolutePath($path)) {
if (strpos($path, $relVendorPath) === 0) {
// path starts with vendor dir
$path = substr($path, strlen($relVendorPath));
$baseDir = '$vendorDir . ';
} else {
$path = '/'.$path;
$baseDir = '$baseDir . ';
}
} elseif (strpos($path, $vendorPath) === 0) {
$path = substr($path, strlen($vendorPath));
$baseDir = '$vendorDir . ';
$path = $basePath . '/' . $path;
}
$path = $filesystem->normalizePath($path);
return $baseDir.var_export($path, true);
}
$baseDir = '';
if (strpos($path.'/', $vendorPath.'/') === 0) {
$path = substr($path, strlen($vendorPath));
$baseDir = '$vendorDir';
protected function getPath(Filesystem $filesystem, $relVendorPath, $vendorPath, $path)
{
$path = strtr($path, '\\', '/');
if (!$filesystem->isAbsolutePath($path)) {
if (strpos($path, $relVendorPath) === 0) {
// path starts with vendor dir
return $vendorPath . substr($path, strlen($relVendorPath));
if ($path !== false) {
$baseDir .= " . ";
}
} else {
$path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
if (!$filesystem->isAbsolutePath($path)) {
$baseDir = '$baseDir . ';
$path = '/' . $path;
}
}
return strtr(getcwd(), '\\', '/').'/'.$path;
if (preg_match('/\.phar$/', $path)) {
$baseDir = "'phar://' . " . $baseDir;
}
return $path;
return $baseDir . (($path !== false) ? var_export($path, true) : "");
}
protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
@ -317,7 +434,7 @@ EOF;
return <<<AUTOLOAD
<?php
// autoload.php generated by Composer
// autoload.php @generated by Composer
require_once $vendorPathToTargetDirCode . '/autoload_real.php';
@ -326,7 +443,7 @@ return ComposerAutoloaderInit$suffix::getLoader();
AUTOLOAD;
}
protected function getAutoloadRealFile($usePSR0, $useClassMap, $useIncludePath, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix)
protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader)
{
// TODO the class ComposerAutoloaderInit should be revert to a closure
// when APC has been fixed:
@ -335,14 +452,10 @@ AUTOLOAD;
// - https://bugs.php.net/bug.php?id=61576
// - https://bugs.php.net/bug.php?id=59298
if ($filesCode) {
$filesCode = "\n\n".rtrim($filesCode);
}
$file = <<<HEADER
<?php
// autoload_real.php generated by Composer
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit$suffix
{
@ -361,13 +474,10 @@ class ComposerAutoloaderInit$suffix
return self::\$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
\$vendorDir = $vendorPathCode;
\$baseDir = $appBaseDirCode;
HEADER;
@ -381,17 +491,24 @@ HEADER;
INCLUDE_PATH;
}
if ($usePSR0) {
$file .= <<<'PSR0'
$file .= <<<'PSR0'
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->add($namespace, $path);
$loader->set($namespace, $path);
}
PSR0;
$file .= <<<'PSR4'
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
PSR4;
if ($useClassMap) {
$file .= <<<'CLASSMAP'
$classMap = require __DIR__ . '/autoload_classmap.php';
@ -403,18 +520,41 @@ PSR0;
CLASSMAP;
}
if ($useGlobalIncludePath) {
$file .= <<<'INCLUDEPATH'
$loader->setUseIncludePath(true);
INCLUDEPATH;
}
if ($targetDirLoader) {
$file .= <<<REGISTER_AUTOLOAD
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'));
spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
REGISTER_AUTOLOAD;
}
$file .= <<<METHOD_FOOTER
\$loader->register();{$filesCode}
$file .= <<<REGISTER_LOADER
\$loader->register($prependAutoloader);
REGISTER_LOADER;
if ($useIncludeFiles) {
$file .= <<<INCLUDE_FILES
\$includeFiles = require __DIR__ . '/autoload_files.php';
foreach (\$includeFiles as \$file) {
composerRequire$suffix(\$file);
}
INCLUDE_FILES;
}
$file .= <<<METHOD_FOOTER
return \$loader;
}
@ -425,6 +565,11 @@ METHOD_FOOTER;
return $file . <<<FOOTER
}
function composerRequire$suffix(\$file)
{
require \$file;
}
FOOTER;
}
@ -437,6 +582,9 @@ FOOTER;
list($package, $installPath) = $item;
$autoload = $package->getAutoload();
if ($this->devMode && $package === $mainPackage) {
$autoload = array_merge_recursive($autoload, $package->getDevAutoload());
}
// skip misconfigured packages
if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
@ -448,13 +596,25 @@ FOOTER;
foreach ($autoload[$type] as $namespace => $paths) {
foreach ((array) $paths as $path) {
// remove target-dir from classmap entries of the root package
if ($type === 'classmap' && $package === $mainPackage && $package->getTargetDir()) {
$targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
$path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
if (($type === 'files' || $type === 'classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
// remove target-dir from file paths of the root package
if ($package === $mainPackage) {
$targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
$path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
} else {
// add target-dir from file paths that don't have it
$path = $package->getTargetDir() . '/' . $path;
}
}
$relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
if ($type === 'files' || $type === 'classmap') {
$autoloads[] = $relativePath;
continue;
}
$autoloads[$namespace][] = empty($installPath) ? $path : $installPath.'/'.$path;
$autoloads[$namespace][] = $relativePath;
}
}
}
@ -462,47 +622,93 @@ FOOTER;
return $autoloads;
}
/**
* Sorts packages by dependency weight
*
* Packages of equal weight retain the original order
*
* @param array $packageMap
* @return array
*/
protected function sortPackageMap(array $packageMap)
{
$positions = array();
$names = array();
$indexes = array();
foreach ($packageMap as $position => $item) {
$mainName = $item[0]->getName();
$names = array_merge(array_fill_keys($item[0]->getNames(), $mainName), $names);
$names[$mainName] = $mainName;
$indexes[$mainName] = $positions[$mainName] = $position;
}
$packages = array();
$paths = array();
$usageList = array();
foreach ($packageMap as $item) {
$position = $positions[$item[0]->getName()];
foreach (array_merge($item[0]->getRequires(), $item[0]->getDevRequires()) as $link) {
list($package, $path) = $item;
$name = $package->getName();
$packages[$name] = $package;
$paths[$name] = $path;
foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
$target = $link->getTarget();
if (!isset($names[$target])) {
continue;
}
$usageList[$target][] = $name;
}
}
$target = $names[$target];
if ($positions[$target] <= $position) {
continue;
}
$computing = array();
$computed = array();
$computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
// reusing computed importance
if (isset($computed[$name])) {
return $computed[$name];
}
foreach ($positions as $key => $value) {
if ($value >= $position) {
break;
}
$positions[$key]--;
}
// canceling circular dependency
if (isset($computing[$name])) {
return 0;
}
$positions[$target] = $position - 1;
$computing[$name] = true;
$weight = 0;
if (isset($usageList[$name])) {
foreach ($usageList[$name] as $user) {
$weight -= 1 - $computeImportance($user);
}
}
asort($positions);
unset($computing[$name]);
$computed[$name] = $weight;
return $weight;
};
$weightList = array();
foreach ($packages as $name => $package) {
$weight = $computeImportance($name);
$weightList[$name] = $weight;
}
$stable_sort = function (&$array) {
static $transform, $restore;
$i = 0;
if (!$transform) {
$transform = function (&$v, $k) use (&$i) {
$v = array($v, ++$i, $k, $v);
};
$restore = function (&$v, $k) {
$v = $v[3];
};
}
array_walk($array, $transform);
asort($array);
array_walk($array, $restore);
};
$stable_sort($weightList);
$sortedPackageMap = array();
foreach (array_keys($positions) as $packageName) {
$sortedPackageMap[] = $packageMap[$indexes[$packageName]];
foreach (array_keys($weightList) as $name) {
$sortedPackageMap[] = array($packages[$name], $paths[$name]);
}
return $sortedPackageMap;

@ -42,19 +42,36 @@ namespace Composer\Autoload;
*/
class ClassLoader
{
private $prefixes = array();
private $fallbackDirs = array();
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
public function getPrefixes()
{
return $this->prefixes;
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirs;
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
@ -75,27 +92,134 @@ class ClassLoader
}
/**
* Registers a set of classes
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The classes prefix
* @param array|string $paths The location(s) of the classes
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths)
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
foreach ((array) $paths as $path) {
$this->fallbackDirs[] = $path;
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
if (isset($this->prefixes[$prefix])) {
$this->prefixes[$prefix] = array_merge(
$this->prefixes[$prefix],
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-0 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixes[$prefix] = (array) $paths;
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
@ -142,12 +266,12 @@ class ClassLoader
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True, if loaded
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
include $file;
includeFile($file);
return true;
}
@ -158,50 +282,102 @@ class ClassLoader
*
* @param string $class The name of the class
*
* @return string|null The path, if found
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if ($file === null && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if ($file === null) {
// Remember that this class does not exist.
return $this->classMap[$class] = false;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
if (0 === strpos($class, $prefix)) {
foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
$className = substr($class, $pos + 1);
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$classPath = null;
$className = $class;
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
$classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
foreach ($this->prefixes as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) {
return $dir . DIRECTORY_SEPARATOR . $classPath;
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirs as $dir) {
if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) {
return $dir . DIRECTORY_SEPARATOR . $classPath;
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
if ($this->useIncludePath && $file = stream_resolve_include_path($classPath)) {
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return $this->classMap[$class] = false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

@ -13,18 +13,22 @@
namespace Composer\Autoload;
use Symfony\Component\Finder\Finder;
use Composer\IO\IOInterface;
/**
* ClassMapGenerator
*
* @author Gyula Sallai <salla016@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassMapGenerator
{
/**
* Generate a class map file
*
* @param Traversable $dirs Directories or a single path to search in
* @param string $file The name of the class map file
* @param \Traversable $dirs Directories or a single path to search in
* @param string $file The name of the class map file
*/
public static function dump($dirs, $file)
{
@ -40,20 +44,22 @@ class ClassMapGenerator
/**
* Iterate over all files in the given directory searching for classes
*
* @param Iterator|string $path The path to search in or an iterator
* @param string $whitelist Regex that matches against the file path
* @param \Iterator|string $path The path to search in or an iterator
* @param string $whitelist Regex that matches against the file path
* @param IOInterface $io IO object
* @param string $namespace Optional namespace prefix to filter by
*
* @return array A class map array
*
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path, $whitelist = null)
public static function createMap($path, $whitelist = null, IOInterface $io = null, $namespace = null)
{
if (is_string($path)) {
if (is_file($path)) {
$path = array(new \SplFileInfo($path));
} else if (is_dir($path)) {
$path = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
} elseif (is_dir($path)) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.
@ -65,13 +71,9 @@ class ClassMapGenerator
$map = array();
foreach ($path as $file) {
if (!$file->isFile()) {
continue;
}
$filePath = $file->getRealPath();
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc'))) {
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
continue;
}
@ -82,9 +84,20 @@ class ClassMapGenerator
$classes = self::findClasses($filePath);
foreach ($classes as $class) {
$map[$class] = $filePath;
// skip classes not within the given namespace prefix
if (null !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) {
$io->write(
'<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>'
);
}
}
}
return $map;
@ -93,32 +106,43 @@ class ClassMapGenerator
/**
* Extract the classes in the given file
*
* @param string $path The file to check
*
* @return array The found classes
* @param string $path The file to check
* @throws \RuntimeException
* @return array The found classes
*/
private static function findClasses($path)
{
$traits = version_compare(PHP_VERSION, '5.4', '<') ? '' : '|trait';
try {
$contents = php_strip_whitespace($path);
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
throw new \Exception('File does not exist');
}
if (!is_readable($path)) {
throw new \Exception('File is not readable');
}
}
} catch (\Exception $e) {
throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
}
// return early if there is no chance of matching anything in this file
if (!preg_match('{\b(?:class|interface'.$traits.')\b}i', $contents)) {
if (!preg_match('{\b(?:class|interface'.$traits.')\s}i', $contents)) {
return array();
}
// strip heredocs/nowdocs
$contents = preg_replace('{<<<\'?(\w+)\'?(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\1(?=\r\n|\n|\r|;)}s', 'null', $contents);
$contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
// strip strings
$contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}', 'null', $contents);
$contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}s', 'null', $contents);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents);
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
@ -130,7 +154,7 @@ class ClassMapGenerator
preg_match_all('{
(?:
\b(?<![\$:>])(?P<type>class|interface'.$traits.') \s+ (?P<name>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
\b(?<![\$:>])(?P<type>class|interface'.$traits.') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix', $contents, $matches);
@ -142,7 +166,12 @@ class ClassMapGenerator
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$classes[] = ltrim($namespace . $matches['name'][$i], '\\');
$name = $matches['name'][$i];
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
}
$classes[] = ltrim($namespace . $name, '\\');
}
}

@ -23,6 +23,7 @@ use Symfony\Component\Finder\Finder;
*/
class Cache
{
private static $cacheCollected = false;
private $io;
private $root;
private $enabled = true;
@ -31,8 +32,8 @@ class Cache
/**
* @param IOInterface $io
* @param string $cacheDir location of the cache
* @param string $whitelist List of characters that are allowed in path names (used in a regex character class)
* @param string $cacheDir location of the cache
* @param string $whitelist List of characters that are allowed in path names (used in a regex character class)
* @param Filesystem $filesystem optional filesystem instance
*/
public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
@ -63,6 +64,10 @@ class Cache
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
if ($this->io->isDebug()) {
$this->io->write('Reading '.$this->root . $file.' from cache');
}
return file_get_contents($this->root . $file);
}
@ -74,57 +79,97 @@ class Cache
if ($this->enabled) {
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->io->isDebug()) {
$this->io->write('Writing '.$this->root . $file.' into cache');
}
return file_put_contents($this->root . $file, $contents);
}
return false;
}
/**
* Copy a file into the cache
*/
public function copyFrom($file, $source)
{
if ($this->enabled) {
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
$this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
if ($this->io->isDebug()) {
$this->io->write('Writing '.$this->root . $file.' into cache');
}
return copy($source, $this->root . $file);
}
return false;
}
/**
* Copy a file out of the cache
*/
public function copyTo($file, $target)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
touch($this->root . $file);
if ($this->io->isDebug()) {
$this->io->write('Reading '.$this->root . $file.' from cache');
}
return copy($this->root . $file, $target);
}
return false;
}
public function gcIsNecessary()
{
return (!self::$cacheCollected && !mt_rand(0, 50));
}
public function remove($file)
{
$file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
if ($this->enabled && file_exists($this->root . $file)) {
return unlink($this->root . $file);
return $this->filesystem->unlink($this->root . $file);
}
return false;
}
public function gc($ttl)
public function gc($ttl, $maxSize)
{
$expire = new \DateTime();
$expire->modify('-'.$ttl.' seconds');
if ($this->enabled) {
$expire = new \DateTime();
$expire->modify('-'.$ttl.' seconds');
$finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
foreach ($finder as $file) {
$this->filesystem->unlink($file->getPathname());
}
$totalSize = $this->filesystem->size($this->root);
if ($totalSize > $maxSize) {
$iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
while ($totalSize > $maxSize && $iterator->valid()) {
$filepath = $iterator->current()->getPathname();
$totalSize -= $this->filesystem->size($filepath);
$this->filesystem->unlink($filepath);
$iterator->next();
}
}
self::$cacheCollected = true;
$finder = Finder::create()->files()->in($this->root)->date('until '.$expire->format('Y-m-d H:i:s'));
foreach ($finder as $file) {
unlink($file->getRealPath());
return true;
}
return true;
return false;
}
public function sha1($file)
@ -146,4 +191,9 @@ class Cache
return false;
}
protected function getFinder()
{
return Finder::create()->in($this->root)->files();
}
}

@ -0,0 +1,143 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Factory;
use Composer\IO\IOInterface;
use Composer\DependencyResolver\Pool;
use Composer\Package\LinkConstraint\VersionConstraint;
use Composer\Repository\CompositeRepository;
use Composer\Script\ScriptEvents;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Package\Version\VersionParser;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Creates an archive of a package for distribution.
*
* @author Nils Adermann <naderman@naderman.de>
*/
class ArchiveCommand extends Command
{
protected function configure()
{
$this
->setName('archive')
->setDescription('Create an archive of this composer package')
->setDefinition(array(
new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project'),
new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'),
new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar or zip', 'tar'),
new InputOption('dir', false, InputOption::VALUE_REQUIRED, 'Write the archive to this directory', '.'),
))
->setHelp(<<<EOT
The <info>archive</info> command creates an archive of the specified format
containing the files and directories of the Composer project or the specified
package in the specified version and writes it to the specified directory.
<info>php composer.phar archive [--format=zip] [--dir=/foo] [package [version]]</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD);
}
$returnCode = $this->archive(
$this->getIO(),
$input->getArgument('package'),
$input->getArgument('version'),
$input->getOption('format'),
$input->getOption('dir')
);
if (0 === $returnCode && $composer) {
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD);
}
return $returnCode;
}
protected function archive(IOInterface $io, $packageName = null, $version = null, $format = 'tar', $dest = '.')
{
$config = Factory::createConfig();
$factory = new Factory;
$downloadManager = $factory->createDownloadManager($io, $config);
$archiveManager = $factory->createArchiveManager($config, $downloadManager);
if ($packageName) {
$package = $this->selectPackage($io, $packageName, $version);
if (!$package) {
return 1;
}
} else {
$package = $this->getComposer()->getPackage();
}
$io->write('<info>Creating the archive.</info>');
$archiveManager->archive($package, $format, $dest);
return 0;
}
protected function selectPackage(IOInterface $io, $packageName, $version = null)
{
$io->write('<info>Searching for the specified package.</info>');
if ($composer = $this->getComposer(false)) {
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$io->write('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
$repos = new CompositeRepository($defaultRepos);
}
$pool = new Pool();
$pool->addRepository($repos);
$parser = new VersionParser();
$constraint = ($version) ? $parser->parseConstraints($version) : null;
$packages = $pool->whatProvides($packageName, $constraint, true);
if (count($packages) > 1) {
$package = reset($packages);
$io->write('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>');
$io->write('Alternatives were '.implode(', ', array_map(function ($p) { return $p->getPrettyString(); }, $packages)).'.');
$io->write('<comment>Please use a more specific constraint to pick a different package.</comment>');
} elseif ($packages) {
$package = reset($packages);
$io->write('<info>Found an exact match '.$package->getPrettyString().'.</info>');
} else {
$io->write('<error>Could not find a package matching '.$packageName.'.</error>');
return false;
}
return $package;
}
}

@ -0,0 +1,69 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Cache;
use Composer\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author David Neilsen <petah.p@gmail.com>
*/
class ClearCacheCommand extends Command
{
protected function configure()
{
$this
->setName('clear-cache')
->setAliases(array('clearcache'))
->setDescription('Clears composer\'s internal package cache.')
->setHelp(<<<EOT
The <info>clear-cache</info> deletes all cached packages from composer's
cache directory.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = Factory::createConfig();
$io = $this->getIO();
$cachePaths = array(
'cache-dir' => $config->get('cache-dir'),
'cache-files-dir' => $config->get('cache-files-dir'),
'cache-repo-dir' => $config->get('cache-repo-dir'),
'cache-vcs-dir' => $config->get('cache-vcs-dir'),
);
foreach ($cachePaths as $key => $cachePath) {
$cachePath = realpath($cachePath);
if (!$cachePath) {
$io->write("<info>Cache directory does not exist ($key): $cachePath</info>");
return;
}
$cache = new Cache($io, $cachePath);
if (!$cache->isEnabled()) {
$io->write("<info>Cache is not enabled ($key): $cachePath</info>");
return;
}
$io->write("<info>Clearing cache ($key): $cachePath</info>");
$cache->gc(0, 0);
}
$io->write('<info>All caches cleared.</info>');
}
}

@ -37,16 +37,18 @@ abstract class Command extends BaseCommand
private $io;
/**
* @param bool $required
* @param bool $required
* @param bool $disablePlugins
* @throws \RuntimeException
* @return Composer
*/
public function getComposer($required = true)
public function getComposer($required = true, $disablePlugins = false)
{
if (null === $this->composer) {
$application = $this->getApplication();
if ($application instanceof Application) {
/* @var $application Application */
$this->composer = $application->getComposer($required);
$this->composer = $application->getComposer($required, $disablePlugins);
} elseif ($required) {
throw new \RuntimeException(
'Could not create a Composer\Composer instance, you must inject '.

@ -53,6 +53,7 @@ class ConfigCommand extends Command
->setDefinition(array(
new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'),
new InputOption('editor', 'e', InputOption::VALUE_NONE, 'Open editor'),
new InputOption('auth', 'a', InputOption::VALUE_NONE, 'Affect auth config file (only used for --editor)'),
new InputOption('unset', null, InputOption::VALUE_NONE, 'Unset the given setting-key'),
new InputOption('list', 'l', InputOption::VALUE_NONE, 'List configuration settings'),
new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json', 'composer.json'),
@ -76,7 +77,7 @@ You can add a repository to the global config.json file by passing in the
To edit the file in an external editor:
<comment>%command.full_name% --edit</comment>
<comment>%command.full_name% --editor</comment>
To choose your editor you can set the "EDITOR" env variable.
@ -87,7 +88,7 @@ To get a list of configuration values in the file:
You can always pass more than one option. As an example, if you want to edit the
global config.json file.
<comment>%command.full_name% --edit --global</comment>
<comment>%command.full_name% --editor --global</comment>
EOT
)
;
@ -102,7 +103,7 @@ EOT
throw new \RuntimeException('--file and --global can not be combined');
}
$this->config = Factory::createConfig();
$this->config = Factory::createConfig($this->getIO());
// Get the local composer.json, global config.json, or if the user
// passed in a file to use
@ -113,11 +114,23 @@ EOT
$this->configFile = new JsonFile($configFile);
$this->configSource = new JsonConfigSource($this->configFile);
$authConfigFile = $input->getOption('global')
? ($this->config->get('home') . '/auth.json')
: dirname(realpath($input->getOption('file'))) . '/auth.json';
$this->authConfigFile = new JsonFile($authConfigFile);
$this->authConfigSource = new JsonConfigSource($this->authConfigFile, true);
// initialize the global file if it's not there
if ($input->getOption('global') && !$this->configFile->exists()) {
touch($this->configFile->getPath());
$this->configFile->write(array('config' => new \ArrayObject));
chmod($this->configFile->getPath(), 0600);
@chmod($this->configFile->getPath(), 0600);
}
if ($input->getOption('global') && !$this->authConfigFile->exists()) {
touch($this->authConfigFile->getPath());
$this->authConfigFile->write(array('http-basic' => new \ArrayObject, 'github-oauth' => new \ArrayObject));
@chmod($this->authConfigFile->getPath(), 0600);
}
if (!$this->configFile->exists()) {
@ -132,7 +145,7 @@ EOT
{
// Open file in editor
if ($input->getOption('editor')) {
$editor = getenv('EDITOR');
$editor = escapeshellcmd(getenv('EDITOR'));
if (!$editor) {
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$editor = 'notepad';
@ -146,18 +159,20 @@ EOT
}
}
system($editor . ' ' . $this->configFile->getPath() . (defined('PHP_WINDOWS_VERSION_BUILD') ? '': ' > `tty`'));
$file = $input->getOption('auth') ? $this->authConfigFile->getPath() : $this->configFile->getPath();
system($editor . ' ' . $file . (defined('PHP_WINDOWS_VERSION_BUILD') ? '': ' > `tty`'));
return 0;
}
if (!$input->getOption('global')) {
$this->config->merge($this->configFile->read());
$this->config->merge(array('config' => $this->authConfigFile->exists() ? $this->authConfigFile->read() : array()));
}
// List the configuration of the file settings
if ($input->getOption('list')) {
$this->listConfiguration($this->config->all(), $output);
$this->listConfiguration($this->config->all(), $this->config->raw(), $output);
return 0;
}
@ -235,17 +250,79 @@ EOT
));
}
// handle github-oauth
if (preg_match('/^(github-oauth|http-basic)\.(.+)/', $settingKey, $matches)) {
if ($input->getOption('unset')) {
$this->authConfigSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
return;
}
if ($matches[1] === 'github-oauth') {
if (1 !== count($values)) {
throw new \RuntimeException('Too many arguments, expected only one token');
}
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], $values[0]);
} elseif ($matches[1] === 'http-basic') {
if (2 !== count($values)) {
throw new \RuntimeException('Expected two arguments (username, password), got '.count($values));
}
$this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
$this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], array('username' => $values[0], 'password' => $values[1]));
}
return;
}
$booleanValidator = function ($val) { return in_array($val, array('true', 'false', '1', '0'), true); };
$booleanNormalizer = function ($val) { return $val !== 'false' && (bool) $val; };
// handle config values
$uniqueConfigValues = array(
'process-timeout' => array('is_numeric', 'intval'),
'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'),
'use-include-path' => array($booleanValidator, $booleanNormalizer),
'preferred-install' => array(
function ($val) { return in_array($val, array('auto', 'source', 'dist'), true); },
function ($val) { return $val; }
),
'store-auths' => array(
function ($val) { return in_array($val, array('true', 'false', 'prompt'), true); },
function ($val) {
if ('prompt' === $val) {
return 'prompt';
}
return $val !== 'false' && (bool) $val;
}
),
'notify-on-install' => array($booleanValidator, $booleanNormalizer),
'vendor-dir' => array('is_string', function ($val) { return $val; }),
'bin-dir' => array('is_string', function ($val) { return $val; }),
'notify-on-install' => array(
function ($val) { return true; },
function ($val) { return $val !== 'false' && (bool) $val; }
'cache-dir' => array('is_string', function ($val) { return $val; }),
'cache-files-dir' => array('is_string', function ($val) { return $val; }),
'cache-repo-dir' => array('is_string', function ($val) { return $val; }),
'cache-vcs-dir' => array('is_string', function ($val) { return $val; }),
'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'),
'cache-files-maxsize' => array(
function ($val) { return preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val) > 0; },
function ($val) { return $val; }
),
'discard-changes' => array(
function ($val) { return in_array($val, array('stash', 'true', 'false', '1', '0'), true); },
function ($val) {
if ('stash' === $val) {
return 'stash';
}
return $val !== 'false' && (bool) $val;
}
),
'autoloader-suffix' => array('is_string', function ($val) { return $val === 'null' ? null : $val; }),
'optimize-autoloader' => array($booleanValidator, $booleanNormalizer),
'prepend-autoloader' => array($booleanValidator, $booleanNormalizer),
);
$multiConfigValues = array(
'github-protocols' => array(
@ -255,8 +332,8 @@ EOT
}
foreach ($vals as $val) {
if (!in_array($val, array('git', 'https', 'http'))) {
return 'valid protocols include: git, https, http';
if (!in_array($val, array('git', 'https', 'ssh'))) {
return 'valid protocols include: git, https, ssh';
}
}
@ -266,6 +343,18 @@ EOT
return $vals;
}
),
'github-domains' => array(
function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
return $vals;
}
),
);
foreach ($uniqueConfigValues as $name => $callbacks) {
@ -315,10 +404,11 @@ EOT
* Display the contents of the file in a pretty formatted way
*
* @param array $contents
* @param array $rawContents
* @param OutputInterface $output
* @param string|null $k
*/
protected function listConfiguration(array $contents, OutputInterface $output, $k = null)
protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null)
{
$origK = $k;
foreach ($contents as $key => $value) {
@ -326,9 +416,11 @@ EOT
continue;
}
$rawVal = isset($rawContents[$key]) ? $rawContents[$key] : null;
if (is_array($value) && (!is_numeric(key($value)) || ($key === 'repositories' && null === $k))) {
$k .= preg_replace('{^config\.}', '', $key . '.');
$this->listConfiguration($value, $output, $k);
$this->listConfiguration($value, $rawVal, $output, $k);
if (substr_count($k, '.') > 1) {
$k = str_split($k, strrpos($k, '.', -2));
@ -352,7 +444,11 @@ EOT
$value = var_export($value, true);
}
$output->writeln('[<comment>' . $k . $key . '</comment>] <info>' . $value . '</info>');
if (is_string($rawVal) && $rawVal != $value) {
$output->writeln('[<comment>' . $k . $key . '</comment>] <info>' . $rawVal . ' (' . $value . ')</info>');
} else {
$output->writeln('[<comment>' . $k . $key . '</comment>] <info>' . $value . '</info>');
}
}
}
}

@ -19,19 +19,21 @@ use Composer\Installer\ProjectInstaller;
use Composer\Installer\InstallationManager;
use Composer\IO\IOInterface;
use Composer\Package\BasePackage;
use Composer\Package\LinkConstraint\VersionConstraint;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\Package\Version\VersionSelector;
use Composer\Repository\ComposerRepository;
use Composer\Repository\CompositeRepository;
use Composer\Repository\FilesystemRepository;
use Composer\Repository\InstalledFilesystemRepository;
use Composer\Script\ScriptEvents;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Composer\Json\JsonFile;
use Composer\Config\JsonConfigSource;
use Composer\Util\Filesystem;
use Composer\Util\RemoteFilesystem;
use Composer\Package\Version\VersionParser;
@ -41,6 +43,8 @@ use Composer\Package\Version\VersionParser;
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Tobias Munk <schmunk@usrbin.de>
* @author Nils Adermann <naderman@naderman.de>
*/
class CreateProjectCommand extends Command
{
@ -50,24 +54,29 @@ class CreateProjectCommand extends Command
->setName('create-project')
->setDescription('Create new project from a package into given directory.')
->setDefinition(array(
new InputArgument('package', InputArgument::REQUIRED, 'Package name to be installed'),
new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed'),
new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'),
new InputArgument('version', InputArgument::OPTIONAL, 'Version, will defaults to latest'),
new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).', 'stable'),
new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'),
new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'),
new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'Pick a different repository url to look for the package.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Whether to install dependencies for development.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'Whether to disable custom installers.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deletion vcs folder.'),
new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'),
))
->setHelp(<<<EOT
The <info>create-project</info> command creates a new project from a given
package into a new directory. You can use this command to bootstrap new
projects or setup a clean version-controlled installation
for developers of your project.
package into a new directory. If executed without params and in a directory
with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.
<info>php composer.phar create-project vendor/project target-directory [version]</info>
@ -77,9 +86,7 @@ To install unstable packages, either specify the version you want, or use the
--stability=dev (where dev can be one of RC, beta, alpha or dev).
To setup a developer workable version you should create the project using the source
controlled code by appending the <info>'--prefer-source'</info> flag. Also, it is
advisable to install all dependencies required for development by appending the
<info>'--dev'</info> flag.
controlled code by appending the <info>'--prefer-source'</info> flag.
To install a package from another repository than the default one you
can pass the <info>'--repository-url=http://myrepository.org'</info> flag.
@ -91,39 +98,144 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = Factory::createConfig();
$preferSource = false;
$preferDist = false;
$this->updatePreferredOptions($config, $input, $preferSource, $preferDist);
if ($input->getOption('no-custom-installers')) {
$output->writeln('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
$input->setOption('no-plugins', true);
}
return $this->installProject(
$this->getIO(),
$config,
$input->getArgument('package'),
$input->getArgument('directory'),
$input->getArgument('version'),
$input->getOption('stability'),
$input->getOption('prefer-source'),
$input->getOption('prefer-dist'),
$input->getOption('dev'),
$preferSource,
$preferDist,
!$input->getOption('no-dev'),
$input->getOption('repository-url'),
$input->getOption('no-custom-installers'),
$input->getOption('no-plugins'),
$input->getOption('no-scripts'),
$input->getOption('keep-vcs'),
$input->getOption('no-progress')
$input->getOption('no-progress'),
$input->getOption('no-install'),
$input
);
}
public function installProject(IOInterface $io, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disableCustomInstallers = false, $noScripts = false, $keepVcs = false, $noProgress = false)
public function installProject(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $noInstall = false, InputInterface $input)
{
$config = Factory::createConfig();
$oldCwd = getcwd();
// we need to manually load the configuration to pass the auth credentials to the io interface!
$io->loadConfiguration($config);
$stability = strtolower($stability);
if ($stability === 'rc') {
$stability = 'RC';
if ($packageName !== null) {
$installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositoryUrl, $disablePlugins, $noScripts, $keepVcs, $noProgress);
} else {
$installedFromVcs = false;
}
if (!isset(BasePackage::$stabilities[$stability])) {
throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
$composer = Factory::create($io, null, $disablePlugins);
$fs = new Filesystem();
if ($noScripts === false) {
// dispatch event
$composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages);
}
$rootPackageConfig = $composer->getConfig();
$this->updatePreferredOptions($rootPackageConfig, $input, $preferSource, $preferDist);
// install dependencies of the created project
if ($noInstall === false) {
$installer = Installer::create($io, $composer);
$installer->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode($installDevPackages)
->setRunScripts( ! $noScripts);
if ($disablePlugins) {
$installer->disablePlugins();
}
$status = $installer->run();
if (0 !== $status) {
return $status;
}
}
$hasVcs = $installedFromVcs;
if (!$keepVcs && $installedFromVcs
&& (
!$io->isInteractive()
|| $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
)
) {
$finder = new Finder();
$finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
$finder->name($vcsName);
}
try {
$dirs = iterator_to_array($finder);
unset($finder);
foreach ($dirs as $dir) {
if (!$fs->removeDirectory($dir)) {
throw new \RuntimeException('Could not remove '.$dir);
}
}
} catch (\Exception $e) {
$io->write('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
}
$hasVcs = false;
}
// rewriting self.version dependencies with explicit version numbers if the package's vcs metadata is gone
if (!$hasVcs) {
$package = $composer->getPackage();
$configSource = new JsonConfigSource(new JsonFile('composer.json'));
foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
foreach ($package->{'get'.$meta['method']}() as $link) {
if ($link->getPrettyConstraint() === 'self.version') {
$configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion());
}
}
}
}
if ($noScripts === false) {
// dispatch event
$composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages);
}
chdir($oldCwd);
$vendorComposerDir = $composer->getConfig()->get('vendor-dir').'/composer';
if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) {
@rmdir($vendorComposerDir);
$vendorDir = $composer->getConfig()->get('vendor-dir');
if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) {
@rmdir($vendorDir);
}
}
return 0;
}
protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
{
if (null === $repositoryUrl) {
$sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
} elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION)) {
$sourceRepo = new FilesystemRepository(new JsonFile($repositoryUrl, new RemoteFilesystem($io)));
$sourceRepo = new FilesystemRepository(new JsonFile($repositoryUrl, new RemoteFilesystem($io, $config)));
} elseif (0 === strpos($repositoryUrl, 'http')) {
$sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
} else {
@ -131,25 +243,34 @@ EOT
}
$parser = new VersionParser();
$candidates = array();
$requirements = $parser->parseNameVersionPairs(array($packageName));
$name = strtolower($requirements[0]['name']);
if (!$packageVersion && isset($requirements[0]['version'])) {
$packageVersion = $requirements[0]['version'];
}
$pool = new Pool($packageVersion ? 'dev' : $stability);
$pool->addRepository($sourceRepo);
$constraint = $packageVersion ? new VersionConstraint('=', $parser->normalize($packageVersion)) : null;
$candidates = $pool->whatProvides($name, $constraint);
foreach ($candidates as $key => $candidate) {
if ($candidate->getName() !== $name) {
unset($candidates[$key]);
if (null === $stability) {
if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) {
$stability = $match[1];
} else {
$stability = VersionParser::parseStability($packageVersion);
}
}
if (!$candidates) {
$stability = VersionParser::normalizeStability($stability);
if (!isset(BasePackage::$stabilities[$stability])) {
throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
}
$pool = new Pool($stability);
$pool->addRepository($sourceRepo);
// find the latest version if there are multiple
$versionSelector = new VersionSelector($pool);
$package = $versionSelector->findBestCandidate($name, $packageVersion);
if (!$package) {
throw new \InvalidArgumentException("Could not find package $name" . ($packageVersion ? " with version $packageVersion." : " with stability $stability."));
}
@ -158,19 +279,10 @@ EOT
$directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
}
// select highest version if we have many
$package = $candidates[0];
foreach ($candidates as $candidate) {
if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) {
$package = $candidate;
}
}
unset($candidates);
$io->write('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>');
if ($disableCustomInstallers) {
$io->write('<info>Custom installers have been disabled.</info>');
if ($disablePlugins) {
$io->write('<info>Plugins have been disabled.</info>');
}
if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
@ -195,53 +307,7 @@ EOT
putenv('COMPOSER_ROOT_VERSION='.$package->getPrettyVersion());
// clean up memory
unset($dm, $im, $config, $projectInstaller, $sourceRepo, $package);
// install dependencies of the created project
$composer = Factory::create($io);
$installer = Installer::create($io, $composer);
$installer->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode($installDevPackages)
->setRunScripts( ! $noScripts);
if ($disableCustomInstallers) {
$installer->disableCustomInstallers();
}
if (!$installer->run()) {
return 1;
}
if (!$keepVcs && $installedFromVcs
&& (
!$io->isInteractive()
|| $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
)
) {
$finder = new Finder();
$finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
$finder->name($vcsName);
}
try {
$fs = new Filesystem();
$dirs = iterator_to_array($finder);
unset($finder);
foreach ($dirs as $dir) {
if (!$fs->removeDirectory($dir)) {
throw new \RuntimeException('Could not remove '.$dir);
}
}
} catch (\Exception $e) {
$io->write('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
}
}
return 0;
return $installedFromVcs;
}
protected function createDownloadManager(IOInterface $io, Config $config)
@ -255,4 +321,35 @@ EOT
{
return new InstallationManager();
}
/**
* Updated preferSource or preferDist based on the preferredInstall config option
* @param Config $config
* @param InputInterface $input
* @param boolean $preferSource
* @param boolean $preferDist
*/
protected function updatePreferredOptions(Config $config, InputInterface $input, &$preferSource, &$preferDist)
{
switch ($config->get('preferred-install')) {
case 'source':
$preferSource = true;
$preferDist = false;
break;
case 'dist':
$preferSource = false;
$preferDist = true;
break;
case 'auto':
default:
// noop
break;
}
if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
$preferSource = $input->getOption('prefer-source');
$preferDist = $input->getOption('prefer-dist');
}
}
}

@ -13,6 +13,8 @@
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
@ -25,8 +27,8 @@ use Symfony\Component\Console\Output\OutputInterface;
class DependsCommand extends Command
{
protected $linkTypes = array(
'require' => 'requires',
'require-dev' => 'devRequires',
'require' => array('requires', 'requires'),
'require-dev' => array('devRequires', 'requires (dev)'),
);
protected function configure()
@ -50,13 +52,16 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$repos = $this->getComposer()->getRepositoryManager()->getLocalRepositories();
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'depends', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$repo = $composer->getRepositoryManager()->getLocalRepository();
$needle = $input->getArgument('package');
$pool = new Pool();
foreach ($repos as $repo) {
$pool->addRepository($repo);
}
$pool->addRepository($repo);
$packages = $pool->whatProvides($needle);
if (empty($packages)) {
@ -65,7 +70,6 @@ EOT
$linkTypes = $this->linkTypes;
$verbose = (bool) $input->getOption('verbose');
$types = array_map(function ($type) use ($linkTypes) {
$type = rtrim($type, 's');
if (!isset($linkTypes[$type])) {
@ -75,28 +79,25 @@ EOT
return $type;
}, $input->getOption('link-type'));
$dependsOnPackages = false;
foreach ($repos as $repo) {
$repo->filterPackages(function ($package) use ($needle, $types, $linkTypes, $output, $verbose, &$dependsOnPackages) {
static $outputPackages = array();
foreach ($types as $type) {
foreach ($package->{'get'.$linkTypes[$type]}() as $link) {
if ($link->getTarget() === $needle) {
$dependsOnPackages = true;
if ($verbose) {
$output->writeln($package->getPrettyName() . ' ' . $package->getPrettyVersion() . ' <info>' . $type . '</info> ' . $link->getPrettyConstraint());
} elseif (!isset($outputPackages[$package->getName()])) {
$output->writeln($package->getPrettyName());
$outputPackages[$package->getName()] = true;
}
$messages = array();
$outputPackages = array();
foreach ($repo->getPackages() as $package) {
foreach ($types as $type) {
foreach ($package->{'get'.$linkTypes[$type][0]}() as $link) {
if ($link->getTarget() === $needle) {
if (!isset($outputPackages[$package->getName()])) {
$messages[] = '<info>'.$package->getPrettyName() . '</info> ' . $linkTypes[$type][1] . ' ' . $needle .' (<info>' . $link->getPrettyConstraint() . '</info>)';
$outputPackages[$package->getName()] = true;
}
}
}
});
}
}
if (!$dependsOnPackages) {
if ($messages) {
sort($messages);
$output->writeln($messages);
} else {
$output->writeln('<info>There is no installed package depending on "'.$needle.'".</info>');
}
}

@ -0,0 +1,413 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Composer;
use Composer\Factory;
use Composer\Downloader\TransportException;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Util\ConfigValidator;
use Composer\Util\ProcessExecutor;
use Composer\Util\RemoteFilesystem;
use Composer\Util\StreamContextFactory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class DiagnoseCommand extends Command
{
protected $rfs;
protected $process;
protected $failures = 0;
protected function configure()
{
$this
->setName('diagnose')
->setDescription('Diagnoses the system to identify common errors.')
->setHelp(<<<EOT
The <info>diagnose</info> command checks common errors to help debugging problems.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$output->write('Checking composer.json: ');
$this->outputResult($output, $this->checkComposerSchema());
}
if ($composer) {
$config = $composer->getConfig();
} else {
$config = Factory::createConfig();
}
$this->rfs = new RemoteFilesystem($this->getIO(), $config);
$this->process = new ProcessExecutor($this->getIO());
$output->write('Checking platform settings: ');
$this->outputResult($output, $this->checkPlatform());
$output->write('Checking git settings: ');
$this->outputResult($output, $this->checkGit());
$output->write('Checking http connectivity: ');
$this->outputResult($output, $this->checkHttp());
$opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
if (!empty($opts['http']['proxy'])) {
$output->write('Checking HTTP proxy: ');
$this->outputResult($output, $this->checkHttpProxy());
$output->write('Checking HTTP proxy support for request_fulluri: ');
$this->outputResult($output, $this->checkHttpProxyFullUriRequestParam());
$output->write('Checking HTTPS proxy support for request_fulluri: ');
$this->outputResult($output, $this->checkHttpsProxyFullUriRequestParam());
}
if ($oauth = $config->get('github-oauth')) {
foreach ($oauth as $domain => $token) {
$output->write('Checking '.$domain.' oauth access: ');
$this->outputResult($output, $this->checkGithubOauth($domain, $token));
}
}
$output->write('Checking disk free space: ');
$this->outputResult($output, $this->checkDiskSpace($config));
$output->write('Checking composer version: ');
$this->outputResult($output, $this->checkVersion());
return $this->failures;
}
private function checkComposerSchema()
{
$validator = new ConfigValidator($this->getIO());
list($errors, $publishErrors, $warnings) = $validator->validate(Factory::getComposerFile());
if ($errors || $publishErrors || $warnings) {
$messages = array(
'error' => array_merge($errors, $publishErrors),
'warning' => $warnings,
);
$output = '';
foreach ($messages as $style => $msgs) {
foreach ($msgs as $msg) {
$output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
}
}
return rtrim($output);
}
return true;
}
private function checkGit()
{
$this->process->execute('git config color.ui', $output);
if (strtolower(trim($output)) === 'always') {
return '<warning>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</warning>';
}
return true;
}
private function checkHttp()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
try {
$json = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false);
} catch (\Exception $e) {
return $e;
}
return true;
}
private function checkHttpProxy()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
try {
$json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
$hash = reset($json['provider-includes']);
$hash = $hash['sha256'];
$path = str_replace('%hash%', $hash, key($json['provider-includes']));
$provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
if (hash('sha256', $provider) !== $hash) {
return 'It seems that your proxy is modifying http traffic on the fly';
}
} catch (\Exception $e) {
return $e;
}
return true;
}
/**
* Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
* and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
* This method will test, if you need to disable this parameter via setting extra environment variable in your system.
*
* @return bool|string
*/
private function checkHttpProxyFullUriRequestParam()
{
$url = 'http://packagist.org/packages.json';
try {
$this->rfs->getContents('packagist.org', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"';
}
return true;
}
/**
* Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
* and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
* This method will test, if you need to disable this parameter via setting extra environment variable in your system.
*
* @return bool|string
*/
private function checkHttpsProxyFullUriRequestParam()
{
if (!extension_loaded('openssl')) {
return 'You need the openssl extension installed for this check';
}
$url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
try {
$rfcResult = $this->rfs->getContents('github.com', $url, false);
} catch (TransportException $e) {
try {
$this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
} catch (TransportException $e) {
return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
}
return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
}
return true;
}
private function checkGithubOauth($domain, $token)
{
$this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
try {
$url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
return $this->rfs->getContents($domain, $url, false) ? true : 'Unexpected error';
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
return '<warning>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</warning>';
}
return $e;
}
}
private function checkDiskSpace($config)
{
$minSpaceFree = 1024*1024;
if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
|| (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
) {
return '<error>The disk hosting '.$dir.' is full</error>';
}
return true;
}
private function checkVersion()
{
$protocol = extension_loaded('openssl') ? 'https' : 'http';
$latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
return '<warning>Your are not running the latest version</warning>';
}
return true;
}
private function outputResult(OutputInterface $output, $result)
{
if (true === $result) {
$output->writeln('<info>OK</info>');
} else {
$this->failures++;
$output->writeln('<error>FAIL</error>');
if ($result instanceof \Exception) {
$output->writeln('['.get_class($result).'] '.$result->getMessage());
} elseif ($result) {
$output->writeln($result);
}
}
}
private function checkPlatform()
{
$output = '';
$out = function ($msg, $style) use (&$output) {
$output .= '<'.$style.'>'.$msg.'</'.$style.'>';
};
// code below taken from getcomposer.org/installer, any changes should be made there and replicated here
$errors = array();
$warnings = array();
$iniPath = php_ini_loaded_file();
$displayIniMessage = false;
if ($iniPath) {
$iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
} else {
$iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
}
$iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';
if (!ini_get('allow_url_fopen')) {
$errors['allow_url_fopen'] = true;
}
if (version_compare(PHP_VERSION, '5.3.2', '<')) {
$errors['php'] = PHP_VERSION;
}
if (!isset($errors['php']) && version_compare(PHP_VERSION, '5.3.4', '<')) {
$warnings['php'] = PHP_VERSION;
}
if (!extension_loaded('openssl')) {
$warnings['openssl'] = true;
}
if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
$warnings['apc_cli'] = true;
}
if (ini_get('xdebug.profiler_enabled')) {
$warnings['xdebug_profile'] = true;
} elseif (extension_loaded('xdebug')) {
$warnings['xdebug_loaded'] = true;
}
ob_start();
phpinfo(INFO_GENERAL);
$phpinfo = ob_get_clean();
if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
$configure = $match[1];
if (false !== strpos($configure, '--enable-sigchild')) {
$warnings['sigchild'] = true;
}
if (false !== strpos($configure, '--with-curlwrappers')) {
$warnings['curlwrappers'] = true;
}
}
if (!empty($errors)) {
foreach ($errors as $error => $current) {
switch ($error) {
case 'php':
$text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
break;
case 'allow_url_fopen':
$text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " allow_url_fopen = On";
$displayIniMessage = true;
break;
}
$out($text, 'error');
}
$output .= PHP_EOL;
}
if (!empty($warnings)) {
foreach ($warnings as $warning => $current) {
switch ($warning) {
case 'apc_cli':
$text = PHP_EOL."The apc.enable_cli setting is incorrect.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
$text .= " apc.enable_cli = Off";
$displayIniMessage = true;
break;
case 'sigchild':
$text = PHP_EOL."PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
$text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
$text .= " https://bugs.php.net/bug.php?id=22999";
break;
case 'curlwrappers':
$text = PHP_EOL."PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
$text .= "Recompile it without this flag if possible";
break;
case 'openssl':
$text = PHP_EOL."The openssl extension is missing, which will reduce the security and stability of Composer.".PHP_EOL;
$text .= "If possible you should enable it or recompile php with --with-openssl";
break;
case 'php':
$text = PHP_EOL."Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
$text .= "Composer works with 5.3.2+ for most people, but there might be edge case issues.";
break;
case 'xdebug_loaded':
$text = PHP_EOL."The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
$text .= "Disabling it when using Composer is recommended, but should not cause issues beyond slowness.";
break;
case 'xdebug_profile':
$text = PHP_EOL."The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
$text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
$text .= " xdebug.profiler_enabled = 0";
$displayIniMessage = true;
break;
}
$out($text, 'warning');
}
}
if ($displayIniMessage) {
$out($iniMessage, 'warning');
}
return !$warnings && !$errors ? true : $output;
}
}

@ -12,11 +12,11 @@
namespace Composer\Command;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Composer\Repository\CompositeRepository;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Autoload\AutoloadGenerator;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
@ -30,7 +30,8 @@ class DumpAutoloadCommand extends Command
->setAliases(array('dumpautoload'))
->setDescription('Dumps the autoloader')
->setDefinition(array(
new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 packages to be loaded with classmaps too, good for production.'),
new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables autoload-dev rules.'),
))
->setHelp(<<<EOT
<info>php composer.phar dump-autoload</info>
@ -41,15 +42,26 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Generating autoload files</info>');
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'dump-autoload', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$installationManager = $composer->getInstallationManager();
$localRepos = new CompositeRepository($composer->getRepositoryManager()->getLocalRepositories());
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$package = $composer->getPackage();
$config = $composer->getConfig();
$generator = new AutoloadGenerator();
$generator->dump($config, $localRepos, $package, $installationManager, 'composer', $input->getOption('optimize'));
$optimize = $input->getOption('optimize') || $config->get('optimize-autoloader');
if ($optimize) {
$output->writeln('<info>Generating optimized autoload files</info>');
} else {
$output->writeln('<info>Generating autoload files</info>');
}
$generator = $composer->getAutoloadGenerator();
$generator->setDevMode(!$input->getOption('no-dev'));
$generator->dump($config, $localRepo, $package, $installationManager, 'composer', $optimize);
}
}

@ -0,0 +1,82 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GlobalCommand extends Command
{
protected function configure()
{
$this
->setName('global')
->setDescription('Allows running commands in the global composer dir ($COMPOSER_HOME).')
->setDefinition(array(
new InputArgument('command-name', InputArgument::REQUIRED, ''),
new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
))
->setHelp(<<<EOT
Use this command as a wrapper to run other Composer commands
within the global context of COMPOSER_HOME.
You can use this to install CLI utilities globally, all you need
is to add the COMPOSER_HOME/vendor/bin dir to your PATH env var.
COMPOSER_HOME is c:\Users\<user>\AppData\Roaming\Composer on Windows
and /home/<user>/.composer on unix systems.
Note: This path may vary depending on customizations to bin-dir in
composer.json or the environmental variable COMPOSER_BIN_DIR.
EOT
)
;
}
public function run(InputInterface $input, OutputInterface $output)
{
// extract real command name
$tokens = preg_split('{\s+}', $input->__toString());
$args = array();
foreach ($tokens as $token) {
if ($token && $token[0] !== '-') {
$args[] = $token;
if (count($args) >= 2) {
break;
}
}
}
// show help for this command if no command was found
if (count($args) < 2) {
return parent::run($input, $output);
}
// change to global dir
$config = Factory::createConfig();
chdir($config->get('home'));
$output->writeln('<info>Changed current directory to '.$config->get('home').'</info>');
// create new input without "global" command prefix
$input = new StringInput(preg_replace('{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}', '', $input->__toString(), 1));
return $this->getApplication()->run($input, $output);
}
}

@ -0,0 +1,163 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Factory;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Loader\InvalidPackageException;
use Composer\Repository\CompositeRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Exception\InvalidArgumentException;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class HomeCommand extends Command
{
/**
* {@inheritDoc}
*/
protected function configure()
{
$this
->setName('browse')
->setAliases(array('home'))
->setDescription('Opens the package\'s repository URL or homepage in your browser.')
->setDefinition(array(
new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Package(s) to browse to.'),
new InputOption('homepage', 'H', InputOption::VALUE_NONE, 'Open the homepage instead of the repository URL.'),
))
->setHelp(<<<EOT
The home command opens a package's repository URL or
homepage in your default browser.
To open the homepage by default, use -H or --homepage.
EOT
);
}
/**
* {@inheritDoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$repo = $this->initializeRepo($input, $output);
$return = 0;
foreach ($input->getArgument('packages') as $packageName) {
$package = $this->getPackage($repo, $packageName);
if (!$package instanceof CompletePackageInterface) {
$return = 1;
$output->writeln('<warning>Package '.$packageName.' not found</warning>');
continue;
}
$support = $package->getSupport();
$url = isset($support['source']) ? $support['source'] : $package->getSourceUrl();
if (!$url || $input->getOption('homepage')) {
$url = $package->getHomepage();
}
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$return = 1;
$output->writeln('<warning>'.($input->getOption('homepage') ? 'Invalid or missing homepage' : 'Invalid or missing repository URL').' for '.$packageName.'</warning>');
continue;
}
$this->openBrowser($url);
}
return $return;
}
/**
* finds a package by name
*
* @param RepositoryInterface $repos
* @param string $name
* @return CompletePackageInterface
*/
protected function getPackage(RepositoryInterface $repos, $name)
{
$name = strtolower($name);
$pool = new Pool('dev');
$pool->addRepository($repos);
$matches = $pool->whatProvides($name);
foreach ($matches as $index => $package) {
// skip providers/replacers
if ($package->getName() !== $name) {
unset($matches[$index]);
continue;
}
return $package;
}
}
/**
* opens a url in your system default browser
*
* @param string $url
*/
private function openBrowser($url)
{
$url = ProcessExecutor::escape($url);
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
return passthru('start "web" explorer "' . $url . '"');
}
passthru('which xdg-open', $linux);
passthru('which open', $osx);
if (0 === $linux) {
passthru('xdg-open ' . $url);
} elseif (0 === $osx) {
passthru('open ' . $url);
} else {
$this->getIO()->write('no suitable browser opening command found, open yourself: ' . $url);
}
}
/**
* initializes the repo
*
* @param InputInterface $input
* @param OutputInterface $output
* @return CompositeRepository
*/
private function initializeRepo(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$repo = new CompositeRepository($composer->getRepositoryManager()->getRepositories());
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$repo = new CompositeRepository($defaultRepos);
}
return $repo;
}
}

@ -12,12 +12,15 @@
namespace Composer\Command;
use Composer\DependencyResolver\Pool;
use Composer\Json\JsonFile;
use Composer\Factory;
use Composer\Package\BasePackage;
use Composer\Package\Version\VersionSelector;
use Composer\Repository\CompositeRepository;
use Composer\Repository\PlatformRepository;
use Composer\Package\Version\VersionParser;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
@ -32,11 +35,12 @@ class InitCommand extends Command
{
private $gitConfig;
private $repos;
private $pool;
public function parseAuthorString($author)
{
if (preg_match('/^(?P<name>[- \.,\w\']+) <(?P<email>.+?)>$/u', $author, $match)) {
if (!function_exists('filter_var') || version_compare(PHP_VERSION, '5.3.3', '<') || $match['email'] === filter_var($match['email'], FILTER_VALIDATE_EMAIL)) {
if (preg_match('/^(?P<name>[- \.,\p{L}\']+) <(?P<email>.+?)>$/u', $author, $match)) {
if ($this->isValidEmail($match['email'])) {
return array(
'name' => trim($match['name']),
'email' => $match['email']
@ -64,6 +68,7 @@ class InitCommand extends Command
new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
))
->setHelp(<<<EOT
The <info>init</info> command creates a basic composer.json file
@ -80,7 +85,7 @@ EOT
{
$dialog = $this->getHelperSet()->get('dialog');
$whitelist = array('name', 'description', 'author', 'homepage', 'require', 'require-dev', 'stability');
$whitelist = array('name', 'description', 'author', 'homepage', 'require', 'require-dev', 'stability', 'license');
$options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
@ -207,7 +212,8 @@ EOT
$description = $input->getOption('description') ?: false;
$description = $dialog->ask(
$output,
$dialog->getQuestion('Description', $description)
$dialog->getQuestion('Description', $description),
$description
);
$input->setOption('description', $description);
@ -222,10 +228,7 @@ EOT
$output,
$dialog->getQuestion('Author', $author),
function ($value) use ($self, $author) {
if (null === $value) {
return $author;
}
$value = $value ?: $author;
$author = $self->parseAuthorString($value);
return sprintf('%s <%s>', $author['name'], $author['email']);
@ -254,6 +257,14 @@ EOT
);
$input->setOption('stability', $minimumStability);
$license = $input->getOption('license') ?: false;
$license = $dialog->ask(
$output,
$dialog->getQuestion('License', $license),
$license
);
$input->setOption('license', $license);
$output->writeln(array(
'',
'Define your dependencies.',
@ -274,9 +285,11 @@ EOT
protected function findPackages($name)
{
$packages = array();
return $this->getRepos()->search($name);
}
// init repos
protected function getRepos()
{
if (!$this->repos) {
$this->repos = new CompositeRepository(array_merge(
array(new PlatformRepository),
@ -284,15 +297,7 @@ EOT
));
}
$token = strtolower($name);
$this->repos->filterPackages(function ($package) use ($token, &$packages) {
if (false !== strpos($package->getName(), $token)) {
$packages[] = $package;
}
});
return $packages;
return $this->repos;
}
protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
@ -304,15 +309,18 @@ EOT
$requires = $this->normalizeRequirements($requires);
$result = array();
foreach ($requires as $key => $requirement) {
if (!isset($requirement['version']) && $input->isInteractive()) {
$question = $dialog->getQuestion('Please provide a version constraint for the '.$requirement['name'].' requirement');
if ($constraint = $dialog->ask($output, $question)) {
$requirement['version'] = $constraint;
}
}
foreach ($requires as $requirement) {
if (!isset($requirement['version'])) {
throw new \InvalidArgumentException('The requirement '.$requirement['name'].' must contain a version constraint');
// determine the best version automatically
$version = $this->findBestVersionForPackage($input, $requirement['name']);
$requirement['version'] = $version;
$output->writeln(sprintf(
'Using version <info>%s</info> for <info>%s</info>',
$requirement['version'],
$requirement['name']
));
}
$result[] = $requirement['name'] . ' ' . $requirement['version'];
@ -325,37 +333,74 @@ EOT
$matches = $this->findPackages($package);
if (count($matches)) {
$output->writeln(array(
'',
sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
''
));
foreach ($matches as $position => $package) {
$output->writeln(sprintf(' <info>%5s</info> %s <comment>%s</comment>', "[$position]", $package->getPrettyName(), $package->getPrettyVersion()));
$exactMatch = null;
$choices = array();
foreach ($matches as $position => $foundPackage) {
$choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $foundPackage['name']);
if ($foundPackage['name'] === $package) {
$exactMatch = true;
break;
}
}
$output->writeln('');
// no match, prompt which to pick
if (!$exactMatch) {
$output->writeln(array(
'',
sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
''
));
$validator = function ($selection) use ($matches) {
if ('' === $selection) {
return false;
}
$output->writeln($choices);
$output->writeln('');
if (!is_numeric($selection) && preg_match('{^\s*(\S+) +(\S.*)\s*}', $selection, $matches)) {
return $matches[1].' '.$matches[2];
}
$validator = function ($selection) use ($matches) {
if ('' === $selection) {
return false;
}
if (!isset($matches[(int) $selection])) {
throw new \Exception('Not a valid selection');
}
if (!is_numeric($selection) && preg_match('{^\s*(\S+)\s+(\S.*)\s*$}', $selection, $matches)) {
return $matches[1].' '.$matches[2];
}
if (!isset($matches[(int) $selection])) {
throw new \Exception('Not a valid selection');
}
$package = $matches[(int) $selection];
$package = $matches[(int) $selection];
return $package['name'];
};
return sprintf('%s %s', $package->getName(), $package->getPrettyVersion());
};
$package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or the complete package name if it is not listed', false, ':'), $validator, 3);
}
// no constraint yet, determine the best version automatically
if (false !== $package && false === strpos($package, ' ')) {
$validator = function ($input) {
$input = trim($input);
return $input ?: false;
};
$constraint = $dialog->askAndValidate(
$output,
$dialog->getQuestion('Enter the version constraint to require (or leave blank to use the latest version)', false, ':'),
$validator,
3)
;
if (false === $constraint) {
$constraint = $this->findBestVersionForPackage($input, $package);
$output->writeln(sprintf(
'Using version <info>%s</info> for <info>%s</info>',
$constraint,
$package
));
}
$package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or a "[package] [version]" couple if it is not listed', false, ':'), $validator, 3);
$package .= ' '.$constraint;
}
if (false !== $package) {
$requires[] = $package;
@ -391,7 +436,7 @@ EOT
$finder = new ExecutableFinder();
$gitBin = $finder->find('git');
$cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
$cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
$cmd->run();
if ($cmd->isSuccessful()) {
@ -429,10 +474,7 @@ EOT
return false;
}
$pattern = sprintf(
'~^/?%s(/|/\*)?$~',
preg_quote($vendor, '~')
);
$pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
$lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
@ -451,7 +493,7 @@ EOT
return $parser->parseNameVersionPairs($requirements);
}
protected function addVendorIgnore($ignoreFile, $vendor = 'vendor')
protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
{
$contents = "";
if (file_exists($ignoreFile)) {
@ -464,4 +506,72 @@ EOT
file_put_contents($ignoreFile, $contents . $vendor. "\n");
}
protected function isValidEmail($email)
{
// assume it's valid if we can't validate it
if (!function_exists('filter_var')) {
return true;
}
// php <5.3.3 has a very broken email validator, so bypass checks
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
return true;
}
return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
}
private function getPool(InputInterface $input)
{
if (!$this->pool) {
$this->pool = new Pool($this->getMinimumStability($input));
$this->pool->addRepository($this->getRepos());
}
return $this->pool;
}
private function getMinimumStability(InputInterface $input)
{
if ($input->hasOption('stability')) {
return $input->getOption('stability') ?: 'stable';
}
$file = Factory::getComposerFile();
if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
if (!empty($composer['minimum-stability'])) {
return $composer['minimum-stability'];
}
}
return 'stable';
}
/**
* Given a package name, this determines the best version to use in the require key.
*
* This returns a version with the ~ operator prefixed when possible.
*
* @param InputInterface $input
* @param string $name
* @return string
* @throws \InvalidArgumentException
*/
private function findBestVersionForPackage(InputInterface $input, $name)
{
// find the latest version allowed in this pool
$versionSelector = new VersionSelector($this->getPool($input));
$package = $versionSelector->findBestCandidate($name);
if (!$package) {
throw new \InvalidArgumentException(sprintf(
'Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability',
$name,
$this->getMinimumStability($input)
));
}
return $versionSelector->findRecommendedRequireVersion($package);
}
}

@ -13,14 +13,18 @@
namespace Composer\Command;
use Composer\Installer;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Ryan Weaver <ryan@knplabs.com>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class InstallCommand extends Command
{
@ -33,12 +37,15 @@ class InstallCommand extends Command
new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of dev-require packages.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'Disables all custom installers.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Disables all plugins.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('verbose', 'v', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump')
new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Should not be provided, use composer require instead to add a given package to composer.json.'),
))
->setHelp(<<<EOT
The <info>install</info> command reads the composer.lock file from
@ -55,25 +62,64 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
if ($args = $input->getArgument('packages')) {
$output->writeln('<error>Invalid argument '.implode(' ', $args).'. Use "composer require '.implode(' ', $args).'" instead to add packages to your composer.json.</error>');
return 1;
}
if ($input->getOption('no-custom-installers')) {
$output->writeln('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
$input->setOption('no-plugins', true);
}
$composer = $this->getComposer(true, $input->getOption('no-plugins'));
$composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
$io = $this->getIO();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'install', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$install = Installer::create($io, $composer);
$preferSource = false;
$preferDist = false;
$config = $composer->getConfig();
switch ($config->get('preferred-install')) {
case 'source':
$preferSource = true;
break;
case 'dist':
$preferDist = true;
break;
case 'auto':
default:
// noop
break;
}
if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
$preferSource = $input->getOption('prefer-source');
$preferDist = $input->getOption('prefer-dist');
}
$optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader');
$install
->setDryRun($input->getOption('dry-run'))
->setVerbose($input->getOption('verbose'))
->setPreferSource($input->getOption('prefer-source'))
->setPreferDist($input->getOption('prefer-dist'))
->setDevMode($input->getOption('dev'))
->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode(!$input->getOption('no-dev'))
->setRunScripts(!$input->getOption('no-scripts'))
->setOptimizeAutoloader($input->getOption('optimize-autoloader'))
->setOptimizeAutoloader($optimize)
;
if ($input->getOption('no-custom-installers')) {
$install->disableCustomInstallers();
if ($input->getOption('no-plugins')) {
$install->disablePlugins();
}
return $install->run() ? 0 : 1;
return $install->run();
}
}

@ -0,0 +1,105 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Json\JsonFile;
use Composer\Package\Version\VersionParser;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Helper\TableHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Benoît Merlet <benoit.merlet@gmail.com>
*/
class LicensesCommand extends Command
{
protected function configure()
{
$this
->setName('licenses')
->setDescription('Show information about licenses of dependencies')
->setDefinition(array(
new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'),
))
->setHelp(<<<EOT
The license command displays detailed information about the licenses of
the installed dependencies.
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'licenses', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$root = $composer->getPackage();
$repo = $composer->getRepositoryManager()->getLocalRepository();
$versionParser = new VersionParser;
$packages = array();
foreach ($repo->getPackages() as $package) {
$packages[$package->getName()] = $package;
}
ksort($packages);
switch ($format = $input->getOption('format')) {
case 'text':
$output->writeln('Name: <comment>'.$root->getPrettyName().'</comment>');
$output->writeln('Version: <comment>'.$versionParser->formatVersion($root).'</comment>');
$output->writeln('Licenses: <comment>'.(implode(', ', $root->getLicense()) ?: 'none').'</comment>');
$output->writeln('Dependencies:');
$table = $this->getHelperSet()->get('table');
$table->setLayout(TableHelper::LAYOUT_BORDERLESS);
$table->setHorizontalBorderChar('');
foreach ($packages as $package) {
$table->addRow(array(
$package->getPrettyName(),
$versionParser->formatVersion($package),
implode(', ', $package->getLicense()) ?: 'none',
));
}
$table->render($output);
break;
case 'json':
foreach ($packages as $package) {
$dependencies[$package->getPrettyName()] = array(
'version' => $versionParser->formatVersion($package),
'license' => $package->getLicense(),
);
}
$output->writeln(JsonFile::encode(array(
'name' => $root->getPrettyName(),
'version' => $versionParser->formatVersion($root),
'license' => $root->getLicense(),
'dependencies' => $dependencies,
)));
break;
default:
throw new \RuntimeException(sprintf('Unsupported format "%s". See help for supported formats.', $format));
}
}
}

@ -0,0 +1,118 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Config\JsonConfigSource;
use Composer\Installer;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Json\JsonFile;
use Composer\Factory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Pierre du Plessis <pdples@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RemoveCommand extends Command
{
protected function configure()
{
$this
->setName('remove')
->setDescription('Removes a package from the require or require-dev')
->setDefinition(array(
new InputArgument('packages', InputArgument::IS_ARRAY, 'Packages that should be removed.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Removes a package from the require-dev section.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies.'),
))
->setHelp(<<<EOT
The <info>remove</info> command removes a package from the current
list of installed packages
<info>php composer.phar remove</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$packages = $input->getArgument('packages');
$file = Factory::getComposerFile();
$jsonFile = new JsonFile($file);
$composer = $jsonFile->read();
$composerBackup = file_get_contents($jsonFile->getPath());
$json = new JsonConfigSource($jsonFile);
$type = $input->getOption('dev') ? 'require-dev' : 'require';
$altType = !$input->getOption('dev') ? 'require-dev' : 'require';
foreach ($packages as $package) {
if (isset($composer[$type][$package])) {
$json->removeLink($type, $package);
} elseif (isset($composer[$altType][$package])) {
$output->writeln('<warning>'.$package.' could not be found in '.$type.' but it is present in '.$altType.'</warning>');
$dialog = $this->getHelperSet()->get('dialog');
if ($this->getIO()->isInteractive()) {
if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to remove it from '.$altType, 'yes', '?'), true)) {
$json->removeLink($altType, $package);
}
}
} else {
$output->writeln('<warning>'.$package.' is not required in your composer.json and has not been removed</warning>');
}
}
if ($input->getOption('no-update')) {
return 0;
}
// Update packages
$composer = $this->getComposer();
$composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
$io = $this->getIO();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$install = Installer::create($io, $composer);
$updateDevMode = !$input->getOption('update-no-dev');
$install
->setVerbose($input->getOption('verbose'))
->setDevMode($updateDevMode)
->setUpdate(true)
->setUpdateWhitelist($packages)
->setWhitelistDependencies($input->getOption('update-with-dependencies'));
;
$status = $install->run();
if ($status !== 0) {
$output->writeln("\n".'<error>Removal failed, reverting '.$file.' to its original content.</error>');
file_put_contents($jsonFile->getPath(), $composerBackup);
}
return $status;
}
}

@ -20,6 +20,9 @@ use Composer\Factory;
use Composer\Installer;
use Composer\Json\JsonFile;
use Composer\Json\JsonManipulator;
use Composer\Package\Version\VersionParser;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
/**
* @author Jérémy Romey <jeremy@free-agent.fr>
@ -39,6 +42,8 @@ class RequireCommand extends InitCommand
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies.'),
))
->setHelp(<<<EOT
The require command adds required packages to your composer.json and installs them
@ -54,8 +59,9 @@ EOT
{
$file = Factory::getComposerFile();
if (!file_exists($file)) {
$output->writeln('<error>'.$file.' not found.</error>');
$newlyCreated = !file_exists($file);
if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
$output->writeln('<error>'.$file.' could not be created.</error>');
return 1;
}
@ -64,52 +70,84 @@ EOT
return 1;
}
if (!is_writable($file)) {
$output->writeln('<error>'.$file.' is not writable.</error>');
$dialog = $this->getHelperSet()->get('dialog');
return 1;
}
$json = new JsonFile($file);
$composer = $json->read();
$composerBackup = file_get_contents($json->getPath());
$requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'));
$requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
$removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
$baseRequirements = array_key_exists($requireKey, $composer) ? $composer[$requireKey] : array();
$requirements = $this->formatRequirements($requirements);
if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey)) {
// validate requirements format
$versionParser = new VersionParser();
foreach ($requirements as $constraint) {
$versionParser->parseConstraints($constraint);
}
if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey)) {
foreach ($requirements as $package => $version) {
$baseRequirements[$package] = $version;
if (isset($composer[$removeKey][$package])) {
unset($composer[$removeKey][$package]);
}
}
$composer[$requireKey] = $baseRequirements;
$json->write($composer);
}
$output->writeln('<info>'.$file.' has been updated</info>');
$output->writeln('<info>'.$file.' has been '.($newlyCreated ? 'created' : 'updated').'</info>');
if ($input->getOption('no-update')) {
return 0;
}
$updateDevMode = !$input->getOption('update-no-dev');
// Update packages
$composer = $this->getComposer();
$composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
$io = $this->getIO();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$install = Installer::create($io, $composer);
$install
->setVerbose($input->getOption('verbose'))
->setPreferSource($input->getOption('prefer-source'))
->setPreferDist($input->getOption('prefer-dist'))
->setDevMode($input->getOption('dev'))
->setDevMode($updateDevMode)
->setUpdate(true)
->setUpdateWhitelist($requirements);
->setUpdateWhitelist(array_keys($requirements))
->setWhitelistDependencies($input->getOption('update-with-dependencies'));
;
return $install->run() ? 0 : 1;
$status = $install->run();
if ($status !== 0) {
if ($newlyCreated) {
$output->writeln("\n".'<error>Installation failed, deleting '.$file.'.</error>');
unlink($json->getPath());
} else {
$output->writeln("\n".'<error>Installation failed, reverting '.$file.' to its original content.</error>');
file_put_contents($json->getPath(), $composerBackup);
}
}
return $status;
}
private function updateFileCleanly($json, array $base, array $new, $requireKey)
private function updateFileCleanly($json, array $base, array $new, $requireKey, $removeKey)
{
$contents = file_get_contents($json->getPath());
@ -119,6 +157,9 @@ EOT
if (!$manipulator->addLink($requireKey, $package, $constraint)) {
return false;
}
if (!$manipulator->removeSubNode($removeKey, $package)) {
return false;
}
}
file_put_contents($json->getPath(), $manipulator->getContents());

@ -0,0 +1,100 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Composer\Script\CommandEvent;
use Composer\Script\ScriptEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Fabien Potencier <fabien.potencier@gmail.com>
*/
class RunScriptCommand extends Command
{
/**
* @var array Array with command events
*/
protected $commandEvents = array(
ScriptEvents::PRE_INSTALL_CMD,
ScriptEvents::POST_INSTALL_CMD,
ScriptEvents::PRE_UPDATE_CMD,
ScriptEvents::POST_UPDATE_CMD,
ScriptEvents::PRE_STATUS_CMD,
ScriptEvents::POST_STATUS_CMD,
ScriptEvents::POST_ROOT_PACKAGE_INSTALL,
ScriptEvents::POST_CREATE_PROJECT_CMD
);
/**
* @var array Array with script events
*/
protected $scriptEvents = array(
ScriptEvents::PRE_ARCHIVE_CMD,
ScriptEvents::POST_ARCHIVE_CMD,
ScriptEvents::PRE_AUTOLOAD_DUMP,
ScriptEvents::POST_AUTOLOAD_DUMP
);
protected function configure()
{
$this
->setName('run-script')
->setDescription('Run the scripts defined in composer.json.')
->setDefinition(array(
new InputArgument('script', InputArgument::REQUIRED, 'Script name to run.'),
new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'),
))
->setHelp(<<<EOT
The <info>run-script</info> command runs scripts defined in composer.json:
<info>php composer.phar run-script post-update-cmd</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$script = $input->getArgument('script');
if (!in_array($script, $this->commandEvents) && !in_array($script, $this->scriptEvents)) {
if (defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
throw new \InvalidArgumentException(sprintf('Script "%s" cannot be run with this command', $script));
}
}
$composer = $this->getComposer();
$hasListeners = $composer->getEventDispatcher()->hasEventListeners(new CommandEvent($script, $composer, $this->getIO()));
if (!$hasListeners) {
throw new \InvalidArgumentException(sprintf('Script "%s" is not defined in this package', $script));
}
// add the bin dir to the PATH to make local binaries of deps usable in scripts
$binDir = $composer->getConfig()->get('bin-dir');
if (is_dir($binDir)) {
putenv('PATH='.realpath($binDir).PATH_SEPARATOR.getenv('PATH'));
}
$args = $input->getArgument('args');
if (in_array($script, $this->commandEvents)) {
return $composer->getEventDispatcher()->dispatchCommandEvent($script, $input->getOption('dev') || !$input->getOption('no-dev'), $args);
}
return $composer->getEventDispatcher()->dispatchScript($script, $input->getOption('dev') || !$input->getOption('no-dev'), $args);
}
}

@ -0,0 +1,67 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ScriptAliasCommand extends Command
{
private $script;
public function __construct($script)
{
$this->script = $script;
parent::__construct();
}
protected function configure()
{
$this
->setName($this->script)
->setDescription('Run the '.$this->script.' script as defined in composer.json.')
->setDefinition(array(
new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'),
new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
))
->setHelp(<<<EOT
The <info>run-script</info> command runs scripts defined in composer.json:
<info>php composer.phar run-script post-update-cmd</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
// add the bin dir to the PATH to make local binaries of deps usable in scripts
$binDir = $composer->getConfig()->get('bin-dir');
if (is_dir($binDir)) {
putenv('PATH='.realpath($binDir).PATH_SEPARATOR.getenv('PATH'));
}
$args = $input->getArguments();
return $composer->getEventDispatcher()->dispatchScript($this->script, $input->getOption('dev') || !$input->getOption('no-dev'), $args['args']);
}
}

@ -18,9 +18,10 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Repository\CompositeRepository;
use Composer\Repository\PlatformRepository;
use Composer\Package\CompletePackageInterface;
use Composer\Package\AliasPackage;
use Composer\Repository\RepositoryInterface;
use Composer\Factory;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
@ -66,79 +67,18 @@ EOT
$repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
}
$this->onlyName = $input->getOption('only-name');
$this->tokens = $input->getArgument('tokens');
$this->output = $output;
$repos->filterPackages(array($this, 'processPackage'), 'Composer\Package\CompletePackage');
foreach ($this->lowMatches as $details) {
$output->writeln($details['name'] . '<comment>:</comment> '. $details['description']);
}
}
public function processPackage($package)
{
if ($package instanceof AliasPackage || isset($this->matches[$package->getName()])) {
return;
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'search', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
}
foreach ($this->tokens as $token) {
if (!$score = $this->matchPackage($package, $token)) {
continue;
}
$onlyName = $input->getOption('only-name');
if (false !== ($pos = stripos($package->getName(), $token))) {
$name = substr($package->getPrettyName(), 0, $pos)
. '<highlight>' . substr($package->getPrettyName(), $pos, strlen($token)) . '</highlight>'
. substr($package->getPrettyName(), $pos + strlen($token));
} else {
$name = $package->getPrettyName();
}
$flags = $onlyName ? RepositoryInterface::SEARCH_NAME : RepositoryInterface::SEARCH_FULLTEXT;
$results = $repos->search(implode(' ', $input->getArgument('tokens')), $flags);
$description = strtok($package->getDescription(), "\r\n");
if (false !== ($pos = stripos($description, $token))) {
$description = substr($description, 0, $pos)
. '<highlight>' . substr($description, $pos, strlen($token)) . '</highlight>'
. substr($description, $pos + strlen($token));
}
if ($score >= 3) {
$this->output->writeln($name . '<comment>:</comment> '. $description);
$this->matches[$package->getName()] = true;
} else {
$this->lowMatches[$package->getName()] = array(
'name' => $name,
'description' => $description,
);
}
return;
foreach ($results as $result) {
$output->writeln($result['name'] . (isset($result['description']) ? ' '. $result['description'] : ''));
}
}
/**
* tries to find a token within the name/keywords/description
*
* @param CompletePackageInterface $package
* @param string $token
* @return boolean
*/
private function matchPackage(CompletePackageInterface $package, $token)
{
$score = 0;
if (false !== stripos($package->getName(), $token)) {
$score += 5;
}
if (!$this->onlyName && false !== stripos(join(',', $package->getKeywords() ?: array()), $token)) {
$score += 3;
}
if (!$this->onlyName && false !== stripos($package->getDescription(), $token)) {
$score += 1;
}
return $score;
}
}

@ -13,21 +13,37 @@
namespace Composer\Command;
use Composer\Composer;
use Composer\Factory;
use Composer\Util\Filesystem;
use Composer\Util\RemoteFilesystem;
use Composer\Downloader\FilesystemException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
/**
* @author Igor Wiedler <igor@wiedler.ch>
* @author Kevin Ran <kran@adobe.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class SelfUpdateCommand extends Command
{
const HOMEPAGE = 'getcomposer.org';
const OLD_INSTALL_EXT = '-old.phar';
protected function configure()
{
$this
->setName('self-update')
->setAliases(array('selfupdate'))
->setDescription('Updates composer.phar to the latest version.')
->setDefinition(array(
new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'),
new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'),
new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'),
))
->setHelp(<<<EOT
The <info>self-update</info> command checks getcomposer.org for newer
versions of composer and if found, installs the latest.
@ -41,35 +57,168 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$rfs = new RemoteFilesystem($this->getIO());
$latest = trim($rfs->getContents('getcomposer.org', 'http://getcomposer.org/version', false));
$baseUrl = (extension_loaded('openssl') ? 'https' : 'http') . '://' . self::HOMEPAGE;
$config = Factory::createConfig();
$remoteFilesystem = new RemoteFilesystem($this->getIO(), $config);
$cacheDir = $config->get('cache-dir');
$rollbackDir = $config->get('home');
$localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
// check if current dir is writable and if not try the cache dir from settings
$tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir;
// check for permissions in local filesystem before start connection process
if (!is_writable($tmpDir)) {
throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written');
}
if (!is_writable($localFilename)) {
throw new FilesystemException('Composer update failed: the "'.$localFilename.'" file could not be written');
}
if ($input->getOption('rollback')) {
return $this->rollback($output, $rollbackDir, $localFilename);
}
$latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl. '/version', false));
$updateVersion = $input->getArgument('version') ?: $latestVersion;
if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
$output->writeln('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>');
return 1;
}
if (Composer::VERSION === $updateVersion) {
$output->writeln('<info>You are already using composer version '.$updateVersion.'.</info>');
return 0;
}
$tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar';
$backupFile = sprintf(
'%s/%s-%s%s',
$rollbackDir,
strtr(Composer::RELEASE_DATE, ' :', '_-'),
preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION),
self::OLD_INSTALL_EXT
);
$output->writeln(sprintf("Updating to version <info>%s</info>.", $updateVersion));
$remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar");
$remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename);
if (!file_exists($tempFilename)) {
$output->writeln('<error>The download of the new composer version failed for an unexpected reason</error>');
return 1;
}
// remove saved installations of composer
if ($input->getOption('clean-backups')) {
$finder = $this->getOldInstallationFinder($rollbackDir);
$fs = new Filesystem;
foreach ($finder as $file) {
$file = (string) $file;
$output->writeln('<info>Removing: '.$file.'</info>');
$fs->remove($file);
}
}
if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) {
$output->writeln('<error>The file is corrupted ('.$err->getMessage().').</error>');
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
return 1;
}
if (file_exists($backupFile)) {
$output->writeln('Use <info>composer self-update --rollback</info> to return to version '.Composer::VERSION);
} else {
$output->writeln('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>');
}
}
protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
{
$rollbackVersion = $this->getLastBackupVersion($rollbackDir);
if (!$rollbackVersion) {
throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"');
}
if (!is_writable($rollbackDir)) {
throw new FilesystemException('Composer rollback failed: the "'.$rollbackDir.'" dir could not be written to');
}
if (Composer::VERSION !== $latest) {
$output->writeln(sprintf("Updating to version <info>%s</info>.", $latest));
$old = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT;
$remoteFilename = 'http://getcomposer.org/composer.phar';
$localFilename = $_SERVER['argv'][0];
$tempFilename = basename($localFilename, '.phar').'-temp.phar';
if (!is_file($old)) {
throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be found');
}
if (!is_readable($old)) {
throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be read');
}
$rfs->copy('getcomposer.org', $remoteFilename, $tempFilename);
$oldFile = $rollbackDir . "/{$rollbackVersion}" . self::OLD_INSTALL_EXT;
$output->writeln(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion));
if ($err = $this->setLocalPhar($localFilename, $oldFile)) {
$output->writeln('<error>The backup file was corrupted ('.$err->getMessage().') and has been removed.</error>');
try {
chmod($tempFilename, 0777 & ~umask());
return 1;
}
return 0;
}
protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
{
try {
@chmod($newFilename, 0777 & ~umask());
if (!ini_get('phar.readonly')) {
// test the phar validity
$phar = new \Phar($tempFilename);
$phar = new \Phar($newFilename);
// free the variable to unlock the file
unset($phar);
rename($tempFilename, $localFilename);
} catch (\Exception $e) {
@unlink($tempFilename);
if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
throw $e;
}
$output->writeln('<error>The download is corrupted ('.$e->getMessage().').</error>');
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
}
} else {
$output->writeln("<info>You are using the latest composer version.</info>");
// copy current file into installations dir
if ($backupTarget && file_exists($localFilename)) {
@copy($localFilename, $backupTarget);
}
rename($newFilename, $localFilename);
} catch (\Exception $e) {
if ($backupTarget) {
@unlink($newFilename);
}
if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
throw $e;
}
return $e;
}
}
protected function getLastBackupVersion($rollbackDir)
{
$finder = $this->getOldInstallationFinder($rollbackDir);
$finder->sortByName();
$files = iterator_to_array($finder);
if (count($files)) {
return basename(end($files), self::OLD_INSTALL_EXT);
}
return false;
}
protected function getOldInstallationFinder($rollbackDir)
{
$finder = Finder::create()
->depth(0)
->files()
->name('*' . self::OLD_INSTALL_EXT)
->in($rollbackDir);
return $finder;
}
}

@ -12,16 +12,20 @@
namespace Composer\Command;
use Composer\Composer;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\DefaultPolicy;
use Composer\Factory;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Version\VersionParser;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Repository\ArrayRepository;
use Composer\Repository\CompositeRepository;
use Composer\Repository\ComposerRepository;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;
@ -40,11 +44,13 @@ class ShowCommand extends Command
->setDescription('Show information about packages')
->setDefinition(array(
new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect'),
new InputArgument('version', InputArgument::OPTIONAL, 'Version to inspect'),
new InputArgument('version', InputArgument::OPTIONAL, 'Version or version constraint to inspect'),
new InputOption('installed', 'i', InputOption::VALUE_NONE, 'List installed packages only'),
new InputOption('platform', 'p', InputOption::VALUE_NONE, 'List platform packages only'),
new InputOption('available', 'a', InputOption::VALUE_NONE, 'List available packages only'),
new InputOption('self', 's', InputOption::VALUE_NONE, 'Show the root package information'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables display of dev-require packages.'),
new InputOption('name-only', 'N', InputOption::VALUE_NONE, 'List package names only'),
new InputOption('path', 'P', InputOption::VALUE_NONE, 'Show package paths'),
))
->setHelp(<<<EOT
The show command displays detailed information about a package, or
@ -61,34 +67,40 @@ EOT
// init repos
$platformRepo = new PlatformRepository;
$getRepositories = function (Composer $composer, $dev) {
$manager = $composer->getRepositoryManager();
$repos = new CompositeRepository(array($manager->getLocalRepository()));
if ($dev) {
$repos->addRepository($manager->getLocalDevRepository());
}
return $repos;
};
$composer = $this->getComposer(false);
if ($input->getOption('self')) {
$package = $this->getComposer(false)->getPackage();
$package = $this->getComposer()->getPackage();
$repos = $installedRepo = new ArrayRepository(array($package));
} elseif ($input->getOption('platform')) {
$repos = $installedRepo = $platformRepo;
} elseif ($input->getOption('installed')) {
$repos = $installedRepo = $getRepositories($this->getComposer(), $input->getOption('dev'));
} elseif ($composer = $this->getComposer(false)) {
$localRepo = $getRepositories($composer, $input->getOption('dev'));
$repos = $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository();
} elseif ($input->getOption('available')) {
$installedRepo = $platformRepo;
if ($composer) {
$repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories());
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$repos = new CompositeRepository($defaultRepos);
$output->writeln('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
}
} elseif ($composer) {
$localRepo = $composer->getRepositoryManager()->getLocalRepository();
$installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
$repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories()));
} else {
$defaultRepos = Factory::createDefaultRepositories($this->getIO());
$output->writeln('No composer.json found in the current directory, showing packages from ' . implode(', ', array_keys($defaultRepos)));
$output->writeln('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
$installedRepo = $platformRepo;
$repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
}
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'show', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
}
// show single package or single version
if ($input->getArgument('package') || !empty($package)) {
$versions = array();
@ -120,29 +132,100 @@ EOT
// list packages
$packages = array();
$repos->filterPackages(function ($package) use (&$packages, $platformRepo, $installedRepo) {
if ($platformRepo->hasPackage($package)) {
if ($repos instanceof CompositeRepository) {
$repos = $repos->getRepositories();
} elseif (!is_array($repos)) {
$repos = array($repos);
}
foreach ($repos as $repo) {
if ($repo === $platformRepo) {
$type = '<info>platform</info>:';
} elseif ($installedRepo->hasPackage($package)) {
} elseif (
$repo === $installedRepo
|| ($installedRepo instanceof CompositeRepository && in_array($repo, $installedRepo->getRepositories(), true))
) {
$type = '<info>installed</info>:';
} else {
$type = '<comment>available</comment>:';
}
if (!isset($packages[$type][$package->getName()])
|| version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<')
) {
$packages[$type][$package->getName()] = $package;
if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
foreach ($repo->getProviderNames() as $name) {
$packages[$type][$name] = $name;
}
} else {
foreach ($repo->getPackages() as $package) {
if (!isset($packages[$type][$package->getName()])
|| !is_object($packages[$type][$package->getName()])
|| version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<')
) {
$packages[$type][$package->getName()] = $package;
}
}
}
}, 'Composer\Package\CompletePackage');
}
$tree = !$input->getOption('platform') && !$input->getOption('installed') && !$input->getOption('available');
$indent = $tree ? ' ' : '';
foreach (array('<info>platform</info>:' => true, '<comment>available</comment>:' => false, '<info>installed</info>:' => true) as $type => $showVersion) {
if (isset($packages[$type])) {
$output->writeln($type);
if ($tree) {
$output->writeln($type);
}
ksort($packages[$type]);
$nameLength = $versionLength = 0;
foreach ($packages[$type] as $package) {
if (is_object($package)) {
$nameLength = max($nameLength, strlen($package->getPrettyName()));
$versionLength = max($versionLength, strlen($this->versionParser->formatVersion($package)));
} else {
$nameLength = max($nameLength, $package);
}
}
list($width) = $this->getApplication()->getTerminalDimensions();
if (null === $width) {
// In case the width is not detected, we're probably running the command
// outside of a real terminal, use space without a limit
$width = PHP_INT_MAX;
}
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$width--;
}
$writePath = !$input->getOption('name-only') && $input->getOption('path');
$writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion && ($nameLength + $versionLength + 3 <= $width);
$writeDescription = !$input->getOption('name-only') && !$input->getOption('path') && ($nameLength + ($showVersion ? $versionLength : 0) + 24 <= $width);
foreach ($packages[$type] as $package) {
$output->writeln(' '.$package->getPrettyName() .' '.($showVersion ? '['.$this->versionParser->formatVersion($package).']' : '').' <comment>:</comment> '. strtok($package->getDescription(), "\r\n"));
if (is_object($package)) {
$output->write($indent . str_pad($package->getPrettyName(), $nameLength, ' '), false);
if ($writeVersion) {
$output->write(' ' . str_pad($this->versionParser->formatVersion($package), $versionLength, ' '), false);
}
if ($writeDescription) {
$description = strtok($package->getDescription(), "\r\n");
$remaining = $width - $nameLength - $versionLength - 4;
if (strlen($description) > $remaining) {
$description = substr($description, 0, $remaining - 3) . '...';
}
$output->write(' ' . $description);
}
if ($writePath) {
$path = strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n");
$output->write(' ' . $path);
}
} else {
$output->write($indent . $package);
}
$output->writeln('');
}
if ($tree) {
$output->writeln('');
}
$output->writeln('');
}
}
}
@ -150,61 +233,50 @@ EOT
/**
* finds a package by name and version if provided
*
* @param RepositoryInterface $installedRepo
* @param RepositoryInterface $repos
* @param string $name
* @param string $version
* @param RepositoryInterface $installedRepo
* @param RepositoryInterface $repos
* @param string $name
* @param string $version
* @return array array(CompletePackageInterface, array of versions)
* @throws \InvalidArgumentException
*/
protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
{
$name = strtolower($name);
$constraint = null;
if ($version) {
$version = $this->versionParser->normalize($version);
$constraint = $this->versionParser->parseConstraints($version);
}
$match = null;
$matches = array();
$repos->filterPackages(function ($package) use ($name, $version, &$matches) {
if ($package->getName() === $name) {
$matches[] = $package;
}
}, 'Composer\Package\CompletePackage');
if (null === $version) {
// search for a locally installed version
foreach ($matches as $package) {
if ($installedRepo->hasPackage($package)) {
$match = $package;
break;
}
}
$policy = new DefaultPolicy();
$pool = new Pool('dev');
$pool->addRepository($repos);
if (!$match) {
// fallback to the highest version
foreach ($matches as $package) {
if (null === $match || version_compare($package->getVersion(), $match->getVersion(), '>=')) {
$match = $package;
}
}
$matchedPackage = null;
$versions = array();
$matches = $pool->whatProvides($name, $constraint);
foreach ($matches as $index => $package) {
// skip providers/replacers
if ($package->getName() !== $name) {
unset($matches[$index]);
continue;
}
} else {
// select the specified version
foreach ($matches as $package) {
if ($package->getVersion() === $version) {
$match = $package;
}
// select an exact match if it is in the installed repo and no specific version was required
if (null === $version && $installedRepo->hasPackage($package)) {
$matchedPackage = $package;
}
}
// build versions array
$versions = array();
foreach ($matches as $package) {
$versions[$package->getPrettyVersion()] = $package->getVersion();
$matches[$index] = $package->getId();
}
return array($match, $versions);
// select prefered package according to policy rules
if (!$matchedPackage && $matches && $prefered = $policy->selectPreferedPackages($pool, array(), $matches)) {
$matchedPackage = $pool->literalToPackage($prefered[0]);
}
return array($matchedPackage, $versions);
}
/**
@ -236,7 +308,11 @@ EOT
if ($type === 'psr-0') {
foreach ($autoloads as $name => $path) {
$output->writeln(($name ?: '*') . ' => ' . ($path ?: '.'));
$output->writeln(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
}
} elseif ($type === 'psr-4') {
foreach ($autoloads as $name => $path) {
$output->writeln(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
}
} elseif ($type === 'classmap') {
$output->writeln(implode(', ', $autoloads));
@ -254,12 +330,6 @@ EOT
*/
protected function printVersions(InputInterface $input, OutputInterface $output, CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, RepositoryInterface $repos)
{
if ($input->getArgument('version')) {
$output->writeln('<info>version</info> : ' . $package->getPrettyVersion());
return;
}
uasort($versions, 'version_compare');
$versions = array_keys(array_reverse($versions));

@ -15,7 +15,10 @@ namespace Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Downloader\VcsDownloader;
use Composer\Downloader\ChangeReportInterface;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Composer\Script\ScriptEvents;
/**
* @author Tiago Ribeiro <tiago.ribeiro@seegno.com>
@ -29,7 +32,7 @@ class StatusCommand extends Command
->setName('status')
->setDescription('Show a list of locally modified packages')
->setDefinition(array(
new InputOption('verbose', 'v', InputOption::VALUE_NONE, 'Show modified files for each directory that contains changes.'),
new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Show modified files for each directory that contains changes.'),
))
->setHelp(<<<EOT
The status command displays a list of dependencies that have
@ -44,21 +47,28 @@ EOT
{
// init repos
$composer = $this->getComposer();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'status', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$installedRepo = $composer->getRepositoryManager()->getLocalRepository();
$dm = $composer->getDownloadManager();
$im = $composer->getInstallationManager();
// Dispatch pre-status-command
$composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::PRE_STATUS_CMD, true);
$errors = array();
// list packages
foreach ($installedRepo->getPackages() as $package) {
$downloader = $dm->getDownloaderForInstalledPackage($package);
if ($downloader instanceof VcsDownloader) {
if ($downloader instanceof ChangeReportInterface) {
$targetDir = $im->getInstallPath($package);
if ($changes = $downloader->getLocalChanges($targetDir)) {
if ($changes = $downloader->getLocalChanges($package, $targetDir)) {
$errors[$targetDir] = $changes;
}
}
@ -87,6 +97,9 @@ EOT
$output->writeln('Use --verbose (-v) to see modified files');
}
// Dispatch post-status-command
$composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::POST_STATUS_CMD, true);
return $errors ? 1 : 0;
}
}

@ -13,6 +13,8 @@
namespace Composer\Command;
use Composer\Installer;
use Composer\Plugin\CommandEvent;
use Composer\Plugin\PluginEvents;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
@ -20,6 +22,7 @@ use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Nils Adermann <naderman@naderman.de>
*/
class UpdateCommand extends Command
{
@ -33,12 +36,16 @@ class UpdateCommand extends Command
new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of dev-require packages.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'Disables all custom installers.'),
new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
new InputOption('lock', null, InputOption::VALUE_NONE, 'Only updates the lock file hash to suppress warning about the lock file being out of date.'),
new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Disables all plugins.'),
new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
new InputOption('verbose', 'v', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump')
new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Add also all dependencies of whitelisted packages to the whitelist.'),
new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump.')
))
->setHelp(<<<EOT
The <info>update</info> command reads the composer.json file from the
@ -51,6 +58,11 @@ To limit the update operation to a few packages, you can list the package(s)
you want to update as such:
<info>php composer.phar update vendor/package1 foo/mypackage [...]</info>
You may also use an asterisk (*) pattern to limit the update operation to package(s)
from a specific vendor:
<info>php composer.phar update vendor/package1 foo/* [...]</info>
EOT
)
;
@ -58,27 +70,61 @@ EOT
protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer();
if ($input->getOption('no-custom-installers')) {
$output->writeln('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
$input->setOption('no-plugins', true);
}
$composer = $this->getComposer(true, $input->getOption('no-plugins'));
$composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
$io = $this->getIO();
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'update', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$install = Installer::create($io, $composer);
$preferSource = false;
$preferDist = false;
$config = $composer->getConfig();
switch ($config->get('preferred-install')) {
case 'source':
$preferSource = true;
break;
case 'dist':
$preferDist = true;
break;
case 'auto':
default:
// noop
break;
}
if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
$preferSource = $input->getOption('prefer-source');
$preferDist = $input->getOption('prefer-dist');
}
$optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader');
$install
->setDryRun($input->getOption('dry-run'))
->setVerbose($input->getOption('verbose'))
->setPreferSource($input->getOption('prefer-source'))
->setPreferDist($input->getOption('prefer-dist'))
->setDevMode($input->getOption('dev'))
->setPreferSource($preferSource)
->setPreferDist($preferDist)
->setDevMode(!$input->getOption('no-dev'))
->setRunScripts(!$input->getOption('no-scripts'))
->setOptimizeAutoloader($input->getOption('optimize-autoloader'))
->setOptimizeAutoloader($optimize)
->setUpdate(true)
->setUpdateWhitelist($input->getArgument('packages'))
->setUpdateWhitelist($input->getOption('lock') ? array('lock') : $input->getArgument('packages'))
->setWhitelistDependencies($input->getOption('with-dependencies'))
;
if ($input->getOption('no-custom-installers')) {
$install->disableCustomInstallers();
if ($input->getOption('no-plugins')) {
$install->disablePlugins();
}
return $install->run() ? 0 : 1;
return $install->run();
}
}

@ -12,9 +12,11 @@
namespace Composer\Command;
use Composer\Package\Loader\ValidatingArrayLoader;
use Composer\Util\ConfigValidator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
@ -34,6 +36,7 @@ class ValidateCommand extends Command
->setName('validate')
->setDescription('Validates a composer.json')
->setDefinition(array(
new InputOption('no-check-all', null, InputOption::VALUE_NONE, 'Do not make a complete validation'),
new InputArgument('file', InputArgument::OPTIONAL, 'path to composer.json file', './composer.json')
))
->setHelp(<<<EOT
@ -65,7 +68,8 @@ EOT
}
$validator = new ConfigValidator($this->getIO());
list($errors, $publishErrors, $warnings) = $validator->validate($file);
$checkAll = $input->getOption('no-check-all') ? 0 : ValidatingArrayLoader::CHECK_ALL;
list($errors, $publishErrors, $warnings) = $validator->validate($file, $checkAll);
// output errors/warnings
if (!$errors && !$publishErrors && !$warnings) {

@ -23,6 +23,9 @@ use Symfony\Component\Process\Process;
*/
class Compiler
{
private $version;
private $versionDate;
/**
* Compiles composer into a single phar file
*
@ -35,12 +38,20 @@ class Compiler
unlink($pharFile);
}
$process = new Process('git log --pretty="%h" -n1 HEAD', __DIR__);
$process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->version = trim($process->getOutput());
$process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$date = new \DateTime(trim($process->getOutput()));
$date->setTimezone(new \DateTimeZone('UTC'));
$this->versionDate = $date->format('Y-m-d H:i:s');
$process = new Process('git describe --tags HEAD');
if ($process->run() == 0) {
$this->version = trim($process->getOutput());
@ -92,8 +103,12 @@ class Compiler
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_psr4.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php'));
if (file_exists(__DIR__.'/../../vendor/composer/include_paths.php')) {
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/include_paths.php'));
}
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/ClassLoader.php'));
$this->addComposerBin($phar);
@ -112,7 +127,7 @@ class Compiler
private function addFile($phar, $file, $strip = true)
{
$path = str_replace(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR, '', $file->getRealPath());
$path = strtr(str_replace(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR, '', $file->getRealPath()), '\\', '/');
$content = file_get_contents($file);
if ($strip) {
@ -121,7 +136,10 @@ class Compiler
$content = "\n".$content."\n";
}
$content = str_replace('@package_version@', $this->version, $content);
if ($path === 'src/Composer/Composer.php') {
$content = str_replace('@package_version@', $this->version, $content);
$content = str_replace('@release_date@', $this->versionDate, $content);
}
$phar->addFromString($path, $content);
}

@ -16,15 +16,20 @@ use Composer\Package\RootPackageInterface;
use Composer\Package\Locker;
use Composer\Repository\RepositoryManager;
use Composer\Installer\InstallationManager;
use Composer\Plugin\PluginManager;
use Composer\Downloader\DownloadManager;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class Composer
{
const VERSION = '@package_version@';
const RELEASE_DATE = '@release_date@';
/**
* @var Package\RootPackageInterface
@ -51,11 +56,26 @@ class Composer
*/
private $installationManager;
/**
* @var Plugin\PluginManager
*/
private $pluginManager;
/**
* @var Config
*/
private $config;
/**
* @var EventDispatcher
*/
private $eventDispatcher;
/**
* @var Autoload\AutoloadGenerator
*/
private $autoloadGenerator;
/**
* @param Package\RootPackageInterface $package
* @return void
@ -152,4 +172,52 @@ class Composer
{
return $this->installationManager;
}
/**
* @param Plugin\PluginManager $manager
*/
public function setPluginManager(PluginManager $manager)
{
$this->pluginManager = $manager;
}
/**
* @return Plugin\PluginManager
*/
public function getPluginManager()
{
return $this->pluginManager;
}
/**
* @param EventDispatcher $eventDispatcher
*/
public function setEventDispatcher(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
/**
* @return EventDispatcher
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* @param Autoload\AutoloadGenerator $autoloadGenerator
*/
public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator)
{
$this->autoloadGenerator = $autoloadGenerator;
}
/**
* @return Autoload\AutoloadGenerator
*/
public function getAutoloadGenerator()
{
return $this->autoloadGenerator;
}
}

@ -21,27 +21,42 @@ class Config
{
public static $defaultConfig = array(
'process-timeout' => 300,
'cache-ttl' => 15552000, // 6 months
'use-include-path' => false,
'preferred-install' => 'auto',
'notify-on-install' => true,
'github-protocols' => array('git', 'https', 'ssh'),
'vendor-dir' => 'vendor',
'bin-dir' => '{$vendor-dir}/bin',
'notify-on-install' => true,
'github-protocols' => array('git', 'https', 'http'),
'cache-dir' => '{$home}/cache',
'cache-files-dir' => '{$cache-dir}/files',
'cache-repo-dir' => '{$cache-dir}/repo',
'cache-vcs-dir' => '{$cache-dir}/vcs',
'cache-ttl' => 15552000, // 6 months
'cache-files-ttl' => null, // fallback to cache-ttl
'cache-files-maxsize' => '300MiB',
'discard-changes' => false,
'autoloader-suffix' => null,
'optimize-autoloader' => false,
'prepend-autoloader' => true,
'github-domains' => array('github.com'),
'store-auths' => 'prompt',
// valid keys without defaults (auth config stuff):
// github-oauth
// http-basic
);
public static $defaultRepositories = array(
'packagist' => array(
'type' => 'composer',
'url' => 'https?://packagist.org',
'allow_ssl_downgrade' => true,
)
);
private $config;
private $repositories;
private $configSource;
private $authConfigSource;
public function __construct()
{
@ -60,17 +75,27 @@ class Config
return $this->configSource;
}
public function setAuthConfigSource(ConfigSourceInterface $source)
{
$this->authConfigSource = $source;
}
public function getAuthConfigSource()
{
return $this->authConfigSource;
}
/**
* Merges new config values with the existing ones (overriding)
*
* @param array $config
*/
public function merge(array $config)
public function merge($config)
{
// override defaults with given config
if (!empty($config['config']) && is_array($config['config'])) {
foreach ($config['config'] as $key => $val) {
if (in_array($key, array('github-oauth')) && isset($this->config[$key])) {
if (in_array($key, array('github-oauth', 'http-basic')) && isset($this->config[$key])) {
$this->config[$key] = array_merge($this->config[$key], $val);
} else {
$this->config[$key] = $val;
@ -116,7 +141,8 @@ class Config
/**
* Returns a setting
*
* @param string $key
* @param string $key
* @throws \RuntimeException
* @return mixed
*/
public function get($key)
@ -132,11 +158,37 @@ class Config
// convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
$env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
return rtrim($this->process(getenv($env) ?: $this->config[$key]), '/\\');
$val = rtrim($this->process(getenv($env) ?: $this->config[$key]), '/\\');
$val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $val);
return $val;
case 'cache-ttl':
return (int) $this->config[$key];
case 'cache-files-maxsize':
if (!preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $this->config[$key], $matches)) {
throw new \RuntimeException(
"Could not parse the value of 'cache-files-maxsize': {$this->config[$key]}"
);
}
$size = $matches[1];
if (isset($matches[2])) {
switch (strtolower($matches[2])) {
case 'g':
$size *= 1024;
// intentional fallthrough
case 'm':
$size *= 1024;
// intentional fallthrough
case 'k':
$size *= 1024;
break;
}
}
return $size;
case 'cache-files-ttl':
if (isset($this->config[$key])) {
return (int) $this->config[$key];
@ -147,6 +199,36 @@ class Config
case 'home':
return rtrim($this->process($this->config[$key]), '/\\');
case 'discard-changes':
if ($env = getenv('COMPOSER_DISCARD_CHANGES')) {
if (!in_array($env, array('stash', 'true', 'false', '1', '0'), true)) {
throw new \RuntimeException(
"Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash"
);
}
if ('stash' === $env) {
return 'stash';
}
// convert string value to bool
return $env !== 'false' && (bool) $env;
}
if (!in_array($this->config[$key], array(true, false, 'stash'), true)) {
throw new \RuntimeException(
"Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash"
);
}
return $this->config[$key];
case 'github-protocols':
if (reset($this->config['github-protocols']) === 'http') {
throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"');
}
return $this->config[$key];
default:
if (!isset($this->config[$key])) {
return null;
@ -168,6 +250,14 @@ class Config
return $all;
}
public function raw()
{
return array(
'repositories' => $this->getRepositories(),
'config' => $this->config,
);
}
/**
* Checks whether a setting exists
*
@ -182,7 +272,7 @@ class Config
/**
* Replaces {$refs} inside a config string
*
* @param string a config string that can contain {$refs-to-other-config}
* @param string $value a config string that can contain {$refs-to-other-config}
* @return string
*/
private function process($value)

@ -66,4 +66,11 @@ interface ConfigSourceInterface
* @param string $name Name
*/
public function removeLink($type, $name);
/**
* Gives a user-friendly name to this source (file path or so)
*
* @return string
*/
public function getName();
}

@ -23,17 +23,34 @@ use Composer\Json\JsonManipulator;
*/
class JsonConfigSource implements ConfigSourceInterface
{
/**
* @var \Composer\Json\JsonFile
*/
private $file;
private $manipulator;
/**
* @var bool
*/
private $authConfig;
/**
* Constructor
*
* @param JsonFile $file
* @param bool $authConfig
*/
public function __construct(JsonFile $file)
public function __construct(JsonFile $file, $authConfig = false)
{
$this->file = $file;
$this->authConfig = $authConfig;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->file->getPath();
}
/**
@ -62,7 +79,16 @@ class JsonConfigSource implements ConfigSourceInterface
public function addConfigSetting($name, $value)
{
$this->manipulateJson('addConfigSetting', $name, $value, function (&$config, $key, $val) {
$config['config'][$key] = $val;
if ($key === 'github-oauth' || $key === 'http-basic') {
list($key, $host) = explode('.', $key, 2);
if ($this->authConfig) {
$config[$key][$host] = $val;
} else {
$config['config'][$key][$host] = $val;
}
} else {
$config['config'][$key] = $val;
}
});
}
@ -72,7 +98,16 @@ class JsonConfigSource implements ConfigSourceInterface
public function removeConfigSetting($name)
{
$this->manipulateJson('removeConfigSetting', $name, function (&$config, $key) {
unset($config['config'][$key]);
if ($key === 'github-oauth' || $key === 'http-basic') {
list($key, $host) = explode('.', $key, 2);
if ($this->authConfig) {
unset($config[$key][$host]);
} else {
unset($config['config'][$key][$host]);
}
} else {
unset($config['config'][$key]);
}
});
}
@ -81,7 +116,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function addLink($type, $name, $value)
{
$this->manipulateJson('addLink', $type, $name, $value, function (&$config, $key) {
$this->manipulateJson('addLink', $type, $name, $value, function (&$config, $type, $name, $value) {
$config[$type][$name] = $value;
});
}
@ -91,7 +126,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function removeLink($type, $name)
{
$this->manipulateJson('removeSubNode', $type, $name, function (&$config, $key) {
$this->manipulateJson('removeSubNode', $type, $name, function (&$config, $type, $name) {
unset($config[$type][$name]);
});
}
@ -105,26 +140,55 @@ class JsonConfigSource implements ConfigSourceInterface
if ($this->file->exists()) {
$contents = file_get_contents($this->file->getPath());
} elseif ($this->authConfig) {
$contents = "{\n}\n";
} else {
$contents = "{\n \"config\": {\n }\n}\n";
}
$manipulator = new JsonManipulator($contents);
$newFile = !$this->file->exists();
// override manipulator method for auth config files
if ($this->authConfig && $method === 'addConfigSetting') {
$method = 'addSubNode';
list($mainNode, $name) = explode('.', $args[0], 2);
$args = array($mainNode, $name, $args[1]);
} elseif ($this->authConfig && $method === 'removeConfigSetting') {
$method = 'removeSubNode';
list($mainNode, $name) = explode('.', $args[0], 2);
$args = array($mainNode, $name);
}
// try to update cleanly
if (call_user_func_array(array($manipulator, $method), $args)) {
file_put_contents($this->file->getPath(), $manipulator->getContents());
} else {
// on failed clean update, call the fallback and rewrite the whole file
$config = $this->file->read();
array_unshift($args, $config);
$this->arrayUnshiftRef($args, $config);
call_user_func_array($fallback, $args);
$this->file->write($config);
}
if ($newFile) {
chmod($this->file->getPath(), 0600);
@chmod($this->file->getPath(), 0600);
}
}
/**
* Prepend a reference to an element to the beginning of an array.
*
* @param array $array
* @param mixed $value
* @return array
*/
private function arrayUnshiftRef(&$array, &$value)
{
$return = array_unshift($array, '');
$array[0] =& $value;
return $return;
}
}

@ -24,6 +24,8 @@ use Composer\Composer;
use Composer\Factory;
use Composer\IO\IOInterface;
use Composer\IO\ConsoleIO;
use Composer\Json\JsonValidationException;
use Composer\Json\JsonFile;
use Composer\Util\ErrorHandler;
/**
@ -45,13 +47,21 @@ class Application extends BaseApplication
*/
protected $io;
private static $logo = ' ______
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
/_/
';
public function __construct()
{
if (function_exists('ini_set')) {
if (function_exists('ini_set') && extension_loaded('xdebug')) {
ini_set('xdebug.show_exception_trace', false);
ini_set('xdebug.scream', false);
}
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
date_default_timezone_set(@date_default_timezone_get());
}
@ -85,22 +95,51 @@ class Application extends BaseApplication
$output->writeln('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.', upgrading is strongly recommended.</warning>');
}
if (defined('COMPOSER_DEV_WARNING_TIME') && $this->getCommandName($input) !== 'self-update') {
if (defined('COMPOSER_DEV_WARNING_TIME') && $this->getCommandName($input) !== 'self-update' && $this->getCommandName($input) !== 'selfupdate') {
if (time() > COMPOSER_DEV_WARNING_TIME) {
$output->writeln(sprintf('<warning>Warning: This development build of composer is over 30 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
}
}
if (getenv('COMPOSER_NO_INTERACTION')) {
$input->setInteractive(false);
}
// switch working dir
if ($newWorkDir = $this->getNewWorkingDir($input)) {
$oldWorkingDir = getcwd();
chdir($newWorkDir);
if ($output->getVerbosity() >= 4) {
$output->writeln('Changed CWD to ' . getcwd());
}
}
// add non-standard scripts as own commands
$file = Factory::getComposerFile();
if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
if (isset($composer['scripts']) && is_array($composer['scripts'])) {
foreach ($composer['scripts'] as $script => $dummy) {
if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
if ($this->has($script)) {
$output->writeln('<warning>A script named '.$script.' would override a native Composer function and has been skipped</warning>');
} else {
$this->add(new Command\ScriptAliasCommand($script));
}
}
}
}
}
if ($input->hasParameterOption('--profile')) {
$startTime = microtime(true);
$this->io->enableDebugging($startTime);
}
$oldWorkingDir = getcwd();
$this->switchWorkingDir($input);
$result = parent::doRun($input, $output);
chdir($oldWorkingDir);
if (isset($oldWorkingDir)) {
chdir($oldWorkingDir);
}
if (isset($startTime)) {
$output->writeln('<info>Memory usage: '.round(memory_get_usage() / 1024 / 1024, 2).'MB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MB), time: '.round(microtime(true) - $startTime, 2).'s');
@ -111,32 +150,63 @@ class Application extends BaseApplication
/**
* @param InputInterface $input
* @return string
* @throws \RuntimeException
*/
private function switchWorkingDir(InputInterface $input)
private function getNewWorkingDir(InputInterface $input)
{
$workingDir = $input->getParameterOption(array('--working-dir', '-d'), getcwd());
if (!is_dir($workingDir)) {
$workingDir = $input->getParameterOption(array('--working-dir', '-d'));
if (false !== $workingDir && !is_dir($workingDir)) {
throw new \RuntimeException('Invalid working directory specified.');
}
chdir($workingDir);
return $workingDir;
}
/**
* @param bool $required
* {@inheritDoc}
*/
public function renderException($exception, $output)
{
try {
$composer = $this->getComposer(false);
if ($composer) {
$config = $composer->getConfig();
$minSpaceFree = 1024*1024;
if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
|| (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
) {
$output->writeln('<error>The disk hosting '.$dir.' is full, this may be the cause of the following exception</error>');
}
}
} catch (\Exception $e) {}
return parent::renderException($exception, $output);
}
/**
* @param bool $required
* @param bool $disablePlugins
* @throws JsonValidationException
* @return \Composer\Composer
*/
public function getComposer($required = true)
public function getComposer($required = true, $disablePlugins = false)
{
if (null === $this->composer) {
try {
$this->composer = Factory::create($this->io);
$this->composer = Factory::create($this->io, null, $disablePlugins);
} catch (\InvalidArgumentException $e) {
if ($required) {
$this->io->write($e->getMessage());
exit(1);
}
} catch (JsonValidationException $e) {
$errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors());
$message = $e->getMessage() . ':' . PHP_EOL . $errors;
throw new JsonValidationException($message);
}
}
return $this->composer;
@ -150,6 +220,11 @@ class Application extends BaseApplication
return $this->io;
}
public function getHelp()
{
return self::$logo . parent::getHelp();
}
/**
* Initializes all the composer commands
*/
@ -169,6 +244,14 @@ class Application extends BaseApplication
$commands[] = new Command\RequireCommand();
$commands[] = new Command\DumpAutoloadCommand();
$commands[] = new Command\StatusCommand();
$commands[] = new Command\ArchiveCommand();
$commands[] = new Command\DiagnoseCommand();
$commands[] = new Command\RunScriptCommand();
$commands[] = new Command\LicensesCommand();
$commands[] = new Command\GlobalCommand();
$commands[] = new Command\ClearCacheCommand();
$commands[] = new Command\RemoveCommand();
$commands[] = new Command\HomeCommand();
if ('phar:' === substr(__FILE__, 0, 5)) {
$commands[] = new Command\SelfUpdateCommand();
@ -177,6 +260,14 @@ class Application extends BaseApplication
return $commands;
}
/**
* {@inheritDoc}
*/
public function getLongVersion()
{
return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE;
}
/**
* {@inheritDoc}
*/

@ -48,7 +48,7 @@ class HtmlOutputFormatter extends OutputFormatter
);
/**
* @param array $styles Array of "name => FormatterStyle" instances
* @param array $styles Array of "name => FormatterStyle" instances
*/
public function __construct(array $styles = array())
{

@ -14,26 +14,39 @@ namespace Composer\DependencyResolver;
use Composer\Package\PackageInterface;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\LinkConstraint\VersionConstraint;
/**
* @author Nils Adermann <naderman@naderman.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class DefaultPolicy implements PolicyInterface
{
private $preferStable;
public function __construct($preferStable = false)
{
$this->preferStable = $preferStable;
}
public function versionCompare(PackageInterface $a, PackageInterface $b, $operator)
{
if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) {
return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB];
}
$constraint = new VersionConstraint($operator, $b->getVersion());
$version = new VersionConstraint('==', $a->getVersion());
return $constraint->matchSpecific($version);
return $constraint->matchSpecific($version, true);
}
public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package)
public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package, $mustMatchName = false)
{
$packages = array();
foreach ($pool->whatProvides($package->getName()) as $candidate) {
foreach ($pool->whatProvides($package->getName(), null, $mustMatchName) as $candidate) {
if ($candidate !== $package) {
$packages[] = $candidate;
}
@ -47,14 +60,14 @@ class DefaultPolicy implements PolicyInterface
return $pool->getPriority($package->getRepository());
}
public function selectPreferedPackages(Pool $pool, array $installedMap, array $literals)
public function selectPreferedPackages(Pool $pool, array $installedMap, array $literals, $requiredPackage = null)
{
$packages = $this->groupLiteralsByNamePreferInstalled($pool, $installedMap, $literals);
foreach ($packages as &$literals) {
$policy = $this;
usort($literals, function ($a, $b) use ($policy, $pool, $installedMap) {
return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), true);
usort($literals, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) {
return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true);
});
}
@ -69,8 +82,8 @@ class DefaultPolicy implements PolicyInterface
$selected = call_user_func_array('array_merge', $packages);
// now sort the result across all packages to respect replaces across packages
usort($selected, function ($a, $b) use ($policy, $pool, $installedMap) {
return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b));
usort($selected, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) {
return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage);
});
return $selected;
@ -96,7 +109,10 @@ class DefaultPolicy implements PolicyInterface
return $packages;
}
public function compareByPriorityPreferInstalled(Pool $pool, array $installedMap, PackageInterface $a, PackageInterface $b, $ignoreReplace = false)
/**
* @protected
*/
public function compareByPriorityPreferInstalled(Pool $pool, array $installedMap, PackageInterface $a, PackageInterface $b, $requiredPackage = null, $ignoreReplace = false)
{
if ($a->getRepository() === $b->getRepository()) {
// prefer aliases to the original package
@ -119,6 +135,19 @@ class DefaultPolicy implements PolicyInterface
if ($this->replaces($b, $a)) {
return -1; // use a
}
// for replacers not replacing each other, put a higher prio on replacing
// packages with the same vendor as the required package
if ($requiredPackage && false !== ($pos = strpos($requiredPackage, '/'))) {
$requiredVendor = substr($requiredPackage, 0, $pos);
$aIsSameVendor = substr($a->getName(), 0, $pos) === $requiredVendor;
$bIsSameVendor = substr($b->getName(), 0, $pos) === $requiredVendor;
if ($bIsSameVendor !== $aIsSameVendor) {
return $aIsSameVendor ? -1 : 1;
}
}
}
// priority equal, sort by package id to make reproducible

@ -26,8 +26,8 @@ class MarkAliasInstalledOperation extends SolverOperation
/**
* Initializes operation.
*
* @param PackageInterface $package package instance
* @param string $reason operation reason
* @param AliasPackage $package package instance
* @param string $reason operation reason
*/
public function __construct(AliasPackage $package, $reason = null)
{

@ -26,8 +26,8 @@ class MarkAliasUninstalledOperation extends SolverOperation
/**
* Initializes operation.
*
* @param PackageInterface $package package instance
* @param string $reason operation reason
* @param AliasPackage $package package instance
* @param string $reason operation reason
*/
public function __construct(AliasPackage $package, $reason = null)
{

@ -15,15 +15,16 @@ namespace Composer\DependencyResolver;
use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
use Composer\Package\Version\VersionParser;
use Composer\Package\Link;
use Composer\Package\LinkConstraint\LinkConstraintInterface;
use Composer\Package\LinkConstraint\VersionConstraint;
use Composer\Package\LinkConstraint\EmptyConstraint;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\CompositeRepository;
use Composer\Repository\ComposerRepository;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Repository\StreamableRepositoryInterface;
use Composer\Repository\PlatformRepository;
use Composer\Package\PackageInterface;
/**
* A package pool contains repositories that provide packages.
@ -38,6 +39,7 @@ class Pool
const MATCH = 1;
const MATCH_PROVIDE = 2;
const MATCH_REPLACE = 3;
const MATCH_FILTERED = 4;
protected $repositories = array();
protected $providerRepos = array();
@ -47,9 +49,11 @@ class Pool
protected $stabilityFlags;
protected $versionParser;
protected $providerCache = array();
protected $filterRequires;
protected $whitelist = null;
protected $id = 1;
public function __construct($minimumStability = 'stable', array $stabilityFlags = array())
public function __construct($minimumStability = 'stable', array $stabilityFlags = array(), array $filterRequires = array())
{
$stabilities = BasePackage::$stabilities;
$this->versionParser = new VersionParser;
@ -60,6 +64,13 @@ class Pool
}
}
$this->stabilityFlags = $stabilityFlags;
$this->filterRequires = $filterRequires;
}
public function setWhitelist($whitelist)
{
$this->whitelist = $whitelist;
$this->providerCache = array();
}
/**
@ -90,27 +101,30 @@ class Pool
$name = $package['name'];
$version = $package['version'];
$stability = VersionParser::parseStability($version);
if ($exempt || $this->isPackageAcceptable($name, $stability)) {
$package['id'] = $this->id++;
$this->packages[] = $package;
// collect names
$names = array(
$name => true,
);
if (isset($package['provide'])) {
foreach ($package['provide'] as $target => $constraint) {
$names[$target] = true;
}
// collect names
$names = array(
$name => true,
);
if (isset($package['provide'])) {
foreach ($package['provide'] as $target => $constraint) {
$names[$target] = true;
}
if (isset($package['replace'])) {
foreach ($package['replace'] as $target => $constraint) {
$names[$target] = true;
}
}
if (isset($package['replace'])) {
foreach ($package['replace'] as $target => $constraint) {
$names[$target] = true;
}
}
$names = array_keys($names);
foreach (array_keys($names) as $provided) {
$this->packageByName[$provided][] =& $this->packages[$this->id - 2];
if ($exempt || $this->isPackageAcceptable($names, $stability)) {
$package['id'] = $this->id++;
$package['stability'] = $stability;
$this->packages[] = $package;
foreach ($names as $provided) {
$this->packageByName[$provided][$package['id']] = $this->packages[$this->id - 2];
}
// handle root package aliases
@ -131,8 +145,8 @@ class Pool
$alias['root_alias'] = true;
$this->packages[] = $alias;
foreach (array_keys($names) as $provided) {
$this->packageByName[$provided][] =& $this->packages[$this->id - 2];
foreach ($names as $provided) {
$this->packageByName[$provided][$alias['id']] = $this->packages[$this->id - 2];
}
}
@ -146,33 +160,36 @@ class Pool
$alias['id'] = $this->id++;
$this->packages[] = $alias;
foreach (array_keys($names) as $provided) {
$this->packageByName[$provided][] =& $this->packages[$this->id - 2];
foreach ($names as $provided) {
$this->packageByName[$provided][$alias['id']] = $this->packages[$this->id - 2];
}
}
}
}
} else {
foreach ($repo->getPackages() as $package) {
$name = $package->getName();
$names = $package->getNames();
$stability = $package->getStability();
if ($exempt || $this->isPackageAcceptable($name, $stability)) {
if ($exempt || $this->isPackageAcceptable($names, $stability)) {
$package->setId($this->id++);
$this->packages[] = $package;
foreach ($package->getNames() as $provided) {
foreach ($names as $provided) {
$this->packageByName[$provided][] = $package;
}
// handle root package aliases
$name = $package->getName();
if (isset($rootAliases[$name][$package->getVersion()])) {
$alias = $rootAliases[$name][$package->getVersion()];
$package->setAlias($alias['alias_normalized']);
$package->setPrettyAlias($alias['alias']);
$package->getRepository()->addPackage($aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']));
if ($package instanceof AliasPackage) {
$package = $package->getAliasOf();
}
$aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
$aliasPackage->setRootPackageAlias(true);
$aliasPackage->setId($this->id++);
$package->getRepository()->addPackage($aliasPackage);
$this->packages[] = $aliasPackage;
foreach ($aliasPackage->getNames() as $name) {
@ -204,32 +221,33 @@ class Pool
*/
public function packageById($id)
{
$this->ensurePackageIsLoaded($this->packages[$id - 1]);
return $this->packages[$id - 1];
return $this->ensurePackageIsLoaded($this->packages[$id - 1]);
}
/**
* Searches all packages providing the given package name and match the constraint
*
* @param string $name The package name to be searched for
* @param LinkConstraintInterface $constraint A constraint that all returned
* packages must match or null to return all
* @return array A set of packages
* @param string $name The package name to be searched for
* @param LinkConstraintInterface $constraint A constraint that all returned
* packages must match or null to return all
* @param bool $mustMatchName Whether the name of returned packages
* must match the given name
* @return PackageInterface[] A set of packages
*/
public function whatProvides($name, LinkConstraintInterface $constraint = null)
public function whatProvides($name, LinkConstraintInterface $constraint = null, $mustMatchName = false)
{
if (isset($this->providerCache[$name][(string) $constraint])) {
return $this->providerCache[$name][(string) $constraint];
$key = ((int) $mustMatchName).$constraint;
if (isset($this->providerCache[$name][$key])) {
return $this->providerCache[$name][$key];
}
return $this->providerCache[$name][(string) $constraint] = $this->computeWhatProvides($name, $constraint);
return $this->providerCache[$name][$key] = $this->computeWhatProvides($name, $constraint, $mustMatchName);
}
/**
* @see whatProvides
*/
private function computeWhatProvides($name, $constraint)
private function computeWhatProvides($name, $constraint, $mustMatchName = false)
{
$candidates = array();
@ -247,18 +265,25 @@ class Pool
$candidates = array_merge($candidates, $this->packageByName[$name]);
}
if (null === $constraint) {
foreach ($candidates as $key => $candidate) {
$candidates[$key] = $this->ensurePackageIsLoaded($candidate);
}
return $candidates;
}
$matches = $provideMatches = array();
$nameMatch = false;
foreach ($candidates as $candidate) {
$aliasOfCandidate = null;
// alias packages are not white listed, make sure that the package
// being aliased is white listed
if ($candidate instanceof AliasPackage) {
$aliasOfCandidate = $candidate->getAliasOf();
}
if ($this->whitelist !== null && (
(is_array($candidate) && isset($candidate['id']) && !isset($this->whitelist[$candidate['id']])) ||
(is_object($candidate) && !($candidate instanceof AliasPackage) && !isset($this->whitelist[$candidate->getId()])) ||
(is_object($candidate) && $candidate instanceof AliasPackage && !isset($this->whitelist[$aliasOfCandidate->getId()]))
)) {
continue;
}
switch ($this->match($candidate, $name, $constraint)) {
case self::MATCH_NONE:
break;
@ -280,11 +305,20 @@ class Pool
$matches[] = $this->ensurePackageIsLoaded($candidate);
break;
case self::MATCH_FILTERED:
break;
default:
throw new \UnexpectedValueException('Unexpected match type');
}
}
if ($mustMatchName) {
return array_filter($matches, function ($match) use ($name) {
return $match->getName() == $name;
});
}
// if a package with the required name exists, we ignore providers
if ($nameMatch) {
return $matches;
@ -320,14 +354,16 @@ class Pool
public function isPackageAcceptable($name, $stability)
{
// allow if package matches the global stability requirement and has no exception
if (!isset($this->stabilityFlags[$name]) && isset($this->acceptableStabilities[$stability])) {
return true;
}
foreach ((array) $name as $n) {
// allow if package matches the global stability requirement and has no exception
if (!isset($this->stabilityFlags[$n]) && isset($this->acceptableStabilities[$stability])) {
return true;
}
// allow if package matches the package-specific stability flag
if (isset($this->stabilityFlags[$name]) && BasePackage::$stabilities[$stability] <= $this->stabilityFlags[$name]) {
return true;
// allow if package matches the package-specific stability flag
if (isset($this->stabilityFlags[$n]) && BasePackage::$stabilities[$stability] <= $this->stabilityFlags[$n]) {
return true;
}
}
return false;
@ -344,8 +380,12 @@ class Pool
$package = $this->packages[$data['id'] - 1] = $data['repo']->loadPackage($data);
}
foreach ($package->getNames() as $name) {
$this->packageByName[$name][$data['id']] = $package;
}
$package->setId($data['id']);
$data = $package;
return $package;
}
return $data;
@ -360,20 +400,36 @@ class Pool
* @param LinkConstraintInterface $constraint The constraint to verify
* @return int One of the MATCH* constants of this class or 0 if there is no match
*/
private function match($candidate, $name, LinkConstraintInterface $constraint)
private function match($candidate, $name, LinkConstraintInterface $constraint = null)
{
// handle array packages
if (is_array($candidate)) {
$candidateName = $candidate['name'];
$candidateVersion = $candidate['version'];
$isDev = $candidate['stability'] === 'dev';
$isAlias = isset($candidate['alias_of']);
} else {
// handle object packages
$candidateName = $candidate->getName();
$candidateVersion = $candidate->getVersion();
$isDev = $candidate->getStability() === 'dev';
$isAlias = $candidate instanceof AliasPackage;
}
if (!$isDev && !$isAlias && isset($this->filterRequires[$name])) {
$requireFilter = $this->filterRequires[$name];
} else {
$requireFilter = new EmptyConstraint;
}
if ($candidateName === $name) {
return $constraint->matches(new VersionConstraint('==', $candidateVersion)) ? self::MATCH : self::MATCH_NAME;
$pkgConstraint = new VersionConstraint('==', $candidateVersion);
if ($constraint === null || $constraint->matches($pkgConstraint)) {
return $requireFilter->matches($pkgConstraint) ? self::MATCH : self::MATCH_FILTERED;
}
return self::MATCH_NAME;
}
if (is_array($candidate)) {
@ -388,29 +444,29 @@ class Pool
$replaces = $candidate->getReplaces();
}
// aliases create multiple replaces/provides for one target so they can not use the shortcut
// aliases create multiple replaces/provides for one target so they can not use the shortcut below
if (isset($replaces[0]) || isset($provides[0])) {
foreach ($provides as $link) {
if ($link->getTarget() === $name && $constraint->matches($link->getConstraint())) {
return self::MATCH_PROVIDE;
if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
return $requireFilter->matches($link->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED;
}
}
foreach ($replaces as $link) {
if ($link->getTarget() === $name && $constraint->matches($link->getConstraint())) {
return self::MATCH_REPLACE;
if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
return $requireFilter->matches($link->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED;
}
}
return self::MATCH_NONE;
}
if (isset($provides[$name]) && $constraint->matches($provides[$name]->getConstraint())) {
return self::MATCH_PROVIDE;
if (isset($provides[$name]) && ($constraint === null || $constraint->matches($provides[$name]->getConstraint()))) {
return $requireFilter->matches($provides[$name]->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED;
}
if (isset($replaces[$name]) && $constraint->matches($replaces[$name]->getConstraint())) {
return self::MATCH_REPLACE;
if (isset($replaces[$name]) && ($constraint === null || $constraint->matches($replaces[$name]->getConstraint()))) {
return $requireFilter->matches($replaces[$name]->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED;
}
return self::MATCH_NONE;

@ -66,7 +66,8 @@ class Problem
/**
* A human readable textual representation of the problem's reasons
*
* @param array $installedMap A map of all installed packages
* @param array $installedMap A map of all installed packages
* @return string
*/
public function getPrettyString(array $installedMap = array())
{
@ -79,20 +80,30 @@ class Problem
$rule = $reason['rule'];
$job = $reason['job'];
if ($job && $job['cmd'] === 'install' && empty($job['packages'])) {
if (isset($job['constraint'])) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
} else {
$packages = array();
}
if ($job && $job['cmd'] === 'install' && empty($packages)) {
// handle php extensions
if (0 === stripos($job['packageName'], 'ext-')) {
$ext = substr($job['packageName'], 4);
$error = extension_loaded($ext) ? 'has the wrong version ('.phpversion($ext).') installed' : 'is missing from your system';
$error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system';
return "\n - The requested PHP extension ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error.'.';
}
// handle linked libs
if (0 === stripos($job['packageName'], 'lib-')) {
$lib = substr($job['packageName'], 4);
if (strtolower($job['packageName']) === 'lib-icu') {
$error = extension_loaded('intl') ? 'has the wrong version installed, try upgrading the intl extension.' : 'is missing from your system, make sure the intl extension is loaded.';
return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' has the wrong version installed or is missing from your system, make sure to have the extension providing it.';
return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error;
}
return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' has the wrong version installed or is missing from your system, make sure to load the extension providing it.';
}
if (!preg_match('{^[A-Za-z0-9_./-]+$}', $job['packageName'])) {
@ -156,33 +167,45 @@ class Problem
{
switch ($job['cmd']) {
case 'install':
if (!$job['packages']) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
if (!$packages) {
return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']);
}
return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($job['packages']).'.';
return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.';
case 'update':
return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.';
case 'remove':
return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).'';
}
return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($job['packages']).'])';
if (isset($job['constraint'])) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
} else {
$packages = array();
}
return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])';
}
protected function getPackageList($packages)
{
return implode(', ', array_unique(array_map(function ($package) {
return $package->getPrettyString();
},
$packages
)));
$prepared = array();
foreach ($packages as $package) {
$prepared[$package->getName()]['name'] = $package->getPrettyName();
$prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion();
}
foreach ($prepared as $name => $package) {
$prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']';
}
return implode(', ', $prepared);
}
/**
* Turns a constraint into text usable in a sentence describing a job
*
* @param LinkConstraint $constraint
* @param \Composer\Package\LinkConstraint\LinkConstraintInterface $constraint
* @return string
*/
protected function constraintToText($constraint)

@ -46,10 +46,8 @@ class Request
protected function addJob($packageName, $cmd, LinkConstraintInterface $constraint = null)
{
$packageName = strtolower($packageName);
$packages = $this->pool->whatProvides($packageName, $constraint);
$this->jobs[] = array(
'packages' => $packages,
'cmd' => $cmd,
'packageName' => $packageName,
'constraint' => $constraint,
@ -58,7 +56,7 @@ class Request
public function updateAll()
{
$this->jobs[] = array('cmd' => 'update-all', 'packages' => array());
$this->jobs[] = array('cmd' => 'update-all');
}
public function getJobs()

@ -35,6 +35,8 @@ class Rule
protected $literals;
protected $type;
protected $id;
protected $reason;
protected $reasonData;
protected $job;
@ -80,6 +82,27 @@ class Rule
return $this->job;
}
public function getReason()
{
return $this->reason;
}
public function getReasonData()
{
return $this->reasonData;
}
public function getRequiredPackage()
{
if ($this->reason === self::RULE_JOB_INSTALL) {
return $this->reasonData;
}
if ($this->reason === self::RULE_PACKAGE_REQUIRES) {
return $this->reasonData->getTarget();
}
}
/**
* Checks if this rule is equal to another one
*
@ -171,7 +194,7 @@ class Rule
$package1 = $this->pool->literalToPackage($this->literals[0]);
$package2 = $this->pool->literalToPackage($this->literals[1]);
return $package1->getPrettyString().' conflicts with '.$package2->getPrettyString().'.';
return $package1->getPrettyString().' conflicts with '.$this->formatPackagesUnique(array($package2)).'.';
case self::RULE_PACKAGE_REQUIRES:
$literals = $this->literals;
@ -185,18 +208,14 @@ class Rule
$text = $this->reasonData->getPrettyString($sourcePackage);
if ($requires) {
$requireText = array();
foreach ($requires as $require) {
$requireText[] = $require->getPrettyString();
}
$text .= ' -> satisfiable by '.implode(', ', $requireText).'.';
$text .= ' -> satisfiable by ' . $this->formatPackagesUnique($requires) . '.';
} else {
$targetName = $this->reasonData->getTarget();
// handle php extensions
if (0 === strpos($targetName, 'ext-')) {
$ext = substr($targetName, 4);
$error = extension_loaded($ext) ? 'has the wrong version ('.phpversion($ext).') installed' : 'is missing from your system';
$error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system';
$text .= ' -> the requested PHP extension '.$ext.' '.$error.'.';
} elseif (0 === strpos($targetName, 'lib-')) {
@ -216,14 +235,7 @@ class Rule
case self::RULE_INSTALLED_PACKAGE_OBSOLETES:
return $ruleText;
case self::RULE_PACKAGE_SAME_NAME:
$text = "Can only install one of: ";
$packages = array();
foreach ($this->literals as $i => $literal) {
$packages[] = $this->pool->literalToPackage($literal)->getPrettyString();
}
return $text.implode(', ', $packages).'.';
return 'Can only install one of: ' . $this->formatPackagesUnique($this->literals) . '.';
case self::RULE_PACKAGE_IMPLICIT_OBSOLETES:
return $ruleText;
case self::RULE_LEARNED:
@ -233,6 +245,23 @@ class Rule
}
}
protected function formatPackagesUnique(array $packages)
{
$prepared = array();
foreach ($packages as $package) {
if (!is_object($package)) {
$package = $this->pool->literalToPackage($package);
}
$prepared[$package->getName()]['name'] = $package->getPrettyName();
$prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion();
}
foreach ($prepared as $name => $package) {
$prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']';
}
return implode(', ', $prepared);
}
/**
* Formats a rule as a string of the format (Literal1|Literal2|...)
*

@ -25,6 +25,8 @@ class RuleSetGenerator
protected $rules;
protected $jobs;
protected $installedMap;
protected $whitelistedMap;
protected $addedMap;
public function __construct(PolicyInterface $policy, Pool $pool)
{
@ -38,13 +40,13 @@ class RuleSetGenerator
* This rule is of the form (-A|B|C), where B and C are the providers of
* one requirement of the package A.
*
* @param PackageInterface $package The package with a requirement
* @param array $providers The providers of the requirement
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param mixed $reasonData Any data, e.g. the requirement name,
* that goes with the reason
* @return Rule The generated rule or null if tautological
* @param PackageInterface $package The package with a requirement
* @param array $providers The providers of the requirement
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param mixed $reasonData Any data, e.g. the requirement name,
* that goes with the reason
* @return Rule The generated rule or null if tautological
*/
protected function createRequireRule(PackageInterface $package, array $providers, $reason, $reasonData = null)
{
@ -67,10 +69,10 @@ class RuleSetGenerator
* The rule is (A|B|C) with A, B and C different packages. If the given
* set of packages is empty an impossible rule is generated.
*
* @param array $packages The set of packages to choose from
* @param int $reason A RULE_* constant describing the reason for
* generating this rule
* @param array $job The job this rule was created from
* @param array $packages The set of packages to choose from
* @param int $reason A RULE_* constant describing the reason for
* generating this rule
* @param array $job The job this rule was created from
* @return Rule The generated rule
*/
protected function createInstallOneOfRule(array $packages, $reason, $job)
@ -88,11 +90,11 @@ class RuleSetGenerator
*
* The rule for a package A is (-A).
*
* @param PackageInterface $package The package to be removed
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param array $job The job this rule was created from
* @return Rule The generated rule
* @param PackageInterface $package The package to be removed
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param array $job The job this rule was created from
* @return Rule The generated rule
*/
protected function createRemoveRule(PackageInterface $package, $reason, $job)
{
@ -105,13 +107,13 @@ class RuleSetGenerator
* The rule for conflicting packages A and B is (-A|-B). A is called the issuer
* and B the provider.
*
* @param PackageInterface $issuer The package declaring the conflict
* @param PackageInterface $provider The package causing the conflict
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param mixed $reasonData Any data, e.g. the package name, that
* goes with the reason
* @return Rule The generated rule
* @param PackageInterface $issuer The package declaring the conflict
* @param PackageInterface $provider The package causing the conflict
* @param int $reason A RULE_* constant describing the
* reason for generating this rule
* @param mixed $reasonData Any data, e.g. the package name, that
* goes with the reason
* @return Rule The generated rule
*/
protected function createConflictRule(PackageInterface $issuer, PackageInterface $provider, $reason, $reasonData = null)
{
@ -141,6 +143,41 @@ class RuleSetGenerator
$this->rules->add($newRule, $type);
}
protected function whitelistFromPackage(PackageInterface $package)
{
$workQueue = new \SplQueue;
$workQueue->enqueue($package);
while (!$workQueue->isEmpty()) {
$package = $workQueue->dequeue();
if (isset($this->whitelistedMap[$package->getId()])) {
continue;
}
$this->whitelistedMap[$package->getId()] = true;
foreach ($package->getRequires() as $link) {
$possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint(), true);
foreach ($possibleRequires as $require) {
$workQueue->enqueue($require);
}
}
$obsoleteProviders = $this->pool->whatProvides($package->getName(), null, true);
foreach ($obsoleteProviders as $provider) {
if ($provider === $package) {
continue;
}
if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) {
$workQueue->enqueue($provider);
}
}
}
}
protected function addRulesForPackage(PackageInterface $package)
{
$workQueue = new \SplQueue;
@ -225,7 +262,7 @@ class RuleSetGenerator
* Adds all rules for all update packages of a given package
*
* @param PackageInterface $package Rules for this package's updates are to
* be added
* be added
*/
private function addRulesForUpdatePackages(PackageInterface $package)
{
@ -236,26 +273,51 @@ class RuleSetGenerator
}
}
private function whitelistFromUpdatePackages(PackageInterface $package)
{
$updates = $this->policy->findUpdatePackages($this->pool, $this->installedMap, $package, true);
foreach ($updates as $update) {
$this->whitelistFromPackage($update);
}
}
protected function whitelistFromJobs()
{
foreach ($this->jobs as $job) {
switch ($job['cmd']) {
case 'install':
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint'], true);
foreach ($packages as $package) {
$this->whitelistFromPackage($package);
}
break;
}
}
}
protected function addRulesForJobs()
{
foreach ($this->jobs as $job) {
switch ($job['cmd']) {
case 'install':
if ($job['packages']) {
foreach ($job['packages'] as $package) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
if ($packages) {
foreach ($packages as $package) {
if (!isset($this->installedMap[$package->getId()])) {
$this->addRulesForPackage($package);
}
}
$rule = $this->createInstallOneOfRule($job['packages'], Rule::RULE_JOB_INSTALL, $job);
$rule = $this->createInstallOneOfRule($packages, Rule::RULE_JOB_INSTALL, $job);
$this->addRule(RuleSet::TYPE_JOB, $rule);
}
break;
case 'remove':
// remove all packages with this name including uninstalled
// ones to make sure none of them are picked as replacements
foreach ($job['packages'] as $package) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
foreach ($packages as $package) {
$rule = $this->createRemoveRule($package, Rule::RULE_JOB_REMOVE, $job);
$this->addRule(RuleSet::TYPE_JOB, $rule);
}
@ -270,6 +332,16 @@ class RuleSetGenerator
$this->rules = new RuleSet;
$this->installedMap = $installedMap;
$this->whitelistedMap = array();
foreach ($this->installedMap as $package) {
$this->whitelistFromPackage($package);
$this->whitelistFromUpdatePackages($package);
}
$this->whitelistFromJobs();
$this->pool->setWhitelist($this->whitelistedMap);
$this->addedMap = array();
foreach ($this->installedMap as $package) {
$this->addRulesForPackage($package);
$this->addRulesForUpdatePackages($package);

@ -69,11 +69,11 @@ class RuleWatchGraph
* above example the rule was (-A|+B), then A turning true means that
* B must now be decided true as well.
*
* @param int $decidedLiteral The literal which was decided (A in our example)
* @param int $level The level at which the decision took place and at which
* all resulting decisions should be made.
* @param Decisions $decisions Used to check previous decisions and to
* register decisions resulting from propagation
* @param int $decidedLiteral The literal which was decided (A in our example)
* @param int $level The level at which the decision took place and at which
* all resulting decisions should be made.
* @param Decisions $decisions Used to check previous decisions and to
* register decisions resulting from propagation
* @return Rule|null If a conflict is found the conflicting rule is returned
*/
public function propagateLiteral($decidedLiteral, $level, $decisions)
@ -127,9 +127,9 @@ class RuleWatchGraph
*
* The rule node's watched literals are updated accordingly.
*
* @param $fromLiteral A literal the node used to watch
* @param $toLiteral A literal the node should watch now
* @param $node The rule node to be moved
* @param $fromLiteral mixed A literal the node used to watch
* @param $toLiteral mixed A literal the node should watch now
* @param $node mixed The rule node to be moved
*/
protected function moveWatch($fromLiteral, $toLiteral, $node)
{

@ -54,7 +54,7 @@ class RuleWatchNode
$literals = $this->rule->getLiterals();
// if there are only 2 elements, both are being watched anyway
if ($literals < 3) {
if (count($literals) < 3) {
return;
}
@ -64,7 +64,7 @@ class RuleWatchNode
$level = $decisions->decisionLevel($literal);
if ($level > $watchLevel) {
$this->rule->watch2 = $literal;
$this->watch2 = $literal;
$watchLevel = $level;
}
}

@ -127,11 +127,15 @@ class Solver
foreach ($this->installed->getPackages() as $package) {
$this->installedMap[$package->getId()] = $package;
}
}
protected function checkForRootRequireProblems()
{
foreach ($this->jobs as $job) {
switch ($job['cmd']) {
case 'update':
foreach ($job['packages'] as $package) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
foreach ($packages as $package) {
if (isset($this->installedMap[$package->getId()])) {
$this->updateMap[$package->getId()] = true;
}
@ -145,7 +149,7 @@ class Solver
break;
case 'install':
if (!$job['packages']) {
if (!$this->pool->whatProvides($job['packageName'], $job['constraint'])) {
$problem = new Problem($this->pool);
$problem->addRule(new Rule($this->pool, array(), null, null, $job));
$this->problems[] = $problem;
@ -160,10 +164,9 @@ class Solver
$this->jobs = $request->getJobs();
$this->setupInstalledMap();
$this->decisions = new Decisions($this->pool);
$this->rules = $this->ruleSetGenerator->getRulesFor($this->jobs, $this->installedMap);
$this->checkForRootRequireProblems();
$this->decisions = new Decisions($this->pool);
$this->watchGraph = new RuleWatchGraph;
foreach ($this->rules as $rule) {
@ -204,7 +207,7 @@ class Solver
* Evaluates each term affected by the decision (linked through watches)
* If we find unit rules we make new decisions based on them
*
* @param integer $level
* @param integer $level
* @return Rule|null A rule on conflict, otherwise null.
*/
protected function propagate($level)
@ -321,7 +324,7 @@ class Solver
private function selectAndInstall($level, array $decisionQueue, $disableRules, Rule $rule)
{
// choose best package to install from decisionQueue
$literals = $this->policy->selectPreferedPackages($this->pool, $this->installedMap, $decisionQueue);
$literals = $this->policy->selectPreferedPackages($this->pool, $this->installedMap, $decisionQueue, $rule->getRequiredPackage());
$selectedLiteral = array_shift($literals);
@ -756,7 +759,6 @@ class Solver
if ($lastLiteral) {
unset($this->branches[$lastBranchIndex][self::BRANCH_LITERALS][$lastBranchOffset]);
array_values($this->branches[$lastBranchIndex][self::BRANCH_LITERALS]);
$level = $lastLevel;
$this->revert($level);

@ -25,7 +25,7 @@ class SolverProblemsException extends \RuntimeException
$this->problems = $problems;
$this->installedMap = $installedMap;
parent::__construct($this->createMessage());
parent::__construct($this->createMessage(), 2);
}
protected function createMessage()

@ -13,7 +13,6 @@
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\DependencyResolver\Operation;
/**
* @author Nils Adermann <naderman@naderman.de>
@ -79,6 +78,7 @@ class Transaction
foreach ($this->decisions as $i => $decision) {
$literal = $decision[Decisions::DECISION_LITERAL];
$reason = $decision[Decisions::DECISION_REASON];
$package = $this->pool->literalToPackage($literal);
if ($literal <= 0 &&

@ -13,6 +13,7 @@
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
use Symfony\Component\Finder\Finder;
/**
* Base downloader for archives
@ -28,53 +29,63 @@ abstract class ArchiveDownloader extends FileDownloader
*/
public function download(PackageInterface $package, $path)
{
parent::download($package, $path);
$temporaryDir = $this->config->get('vendor-dir').'/composer/'.substr(md5(uniqid('', true)), 0, 8);
$retries = 3;
while ($retries--) {
$fileName = parent::download($package, $path);
if ($this->io->isVerbose()) {
$this->io->write(' Extracting archive');
}
$fileName = $this->getFileName($package, $path);
if ($this->io->isVerbose()) {
$this->io->write(' Unpacking archive');
}
try {
try {
$this->extract($fileName, $path);
$this->filesystem->ensureDirectoryExists($temporaryDir);
try {
$this->extract($fileName, $temporaryDir);
} catch (\Exception $e) {
// remove cache if the file was corrupted
parent::clearCache($package, $path);
throw $e;
}
$this->filesystem->unlink($fileName);
$contentDir = $this->getFolderContent($temporaryDir);
// only one dir in the archive, extract its contents out of it
if (1 === count($contentDir) && is_dir(reset($contentDir))) {
$contentDir = $this->getFolderContent((string) reset($contentDir));
}
// move files back out of the temp dir
foreach ($contentDir as $file) {
$file = (string) $file;
$this->filesystem->rename($file, $path . '/' . basename($file));
}
$this->filesystem->removeDirectory($temporaryDir);
if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir').'/composer/')) {
$this->filesystem->removeDirectory($this->config->get('vendor-dir').'/composer/');
}
if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir'))) {
$this->filesystem->removeDirectory($this->config->get('vendor-dir'));
}
} catch (\Exception $e) {
// remove cache if the file was corrupted
parent::clearCache($package, $path);
// clean up
$this->filesystem->removeDirectory($path);
$this->filesystem->removeDirectory($temporaryDir);
// retry downloading if we have an invalid zip file
if ($retries && $e instanceof \UnexpectedValueException && class_exists('ZipArchive') && $e->getCode() === \ZipArchive::ER_NOZIP) {
$this->io->write(' Invalid zip file, retrying...');
usleep(500000);
continue;
}
throw $e;
}
if ($this->io->isVerbose()) {
$this->io->write(' Cleaning up');
}
unlink($fileName);
// If we have only a one dir inside it suppose to be a package itself
$contentDir = glob($path . '/*');
if (1 === count($contentDir)) {
$contentDir = $contentDir[0];
if (is_file($contentDir)) {
$this->filesystem->rename($contentDir, $path . '/' . basename($contentDir));
} else {
// Rename the content directory to avoid error when moving up
// a child folder with the same name
$temporaryDir = sys_get_temp_dir().'/'.md5(time().rand());
$this->filesystem->rename($contentDir, $temporaryDir);
$contentDir = $temporaryDir;
foreach (array_merge(glob($contentDir . '/.*'), glob($contentDir . '/*')) as $file) {
if (trim(basename($file), '.')) {
$this->filesystem->rename($file, $path . '/' . basename($file));
}
}
$this->filesystem->removeDirectory($contentDir);
}
}
} catch (\Exception $e) {
// clean up
$this->filesystem->removeDirectory($path);
throw $e;
break;
}
$this->io->write('');
@ -85,7 +96,7 @@ abstract class ArchiveDownloader extends FileDownloader
*/
protected function getFileName(PackageInterface $package, $path)
{
return rtrim($path.'/'.md5($path.spl_object_hash($package)).'.'.pathinfo($package->getDistUrl(), PATHINFO_EXTENSION), '.');
return rtrim($path.'/'.md5($path.spl_object_hash($package)).'.'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_EXTENSION), '.');
}
/**
@ -107,16 +118,7 @@ abstract class ArchiveDownloader extends FileDownloader
}
if (!extension_loaded('openssl') && (0 === strpos($url, 'https:') || 0 === strpos($url, 'http://github.com'))) {
// bypass https for github if openssl is disabled
if (preg_match('{^https://api\.github\.com/repos/([^/]+/[^/]+)/(zip|tar)ball/([^/]+)$}i', $url, $match)) {
$url = 'http://nodeload.github.com/'.$match[1].'/'.$match[2].'/'.$match[3];
} elseif (preg_match('{^https://github\.com/([^/]+/[^/]+)/(zip|tar)ball/([^/]+)$}i', $url, $match)) {
$url = 'http://nodeload.github.com/'.$match[1].'/'.$match[2].'/'.$match[3];
} elseif (preg_match('{^https://github\.com/([^/]+/[^/]+)/archive/([^/]+)\.(zip|tar\.gz)$}i', $url, $match)) {
$url = 'http://nodeload.github.com/'.$match[1].'/'.$match[3].'/'.$match[2];
} else {
throw new \RuntimeException('You must enable the openssl extension to download files via https');
}
throw new \RuntimeException('You must enable the openssl extension to download files via https');
}
return parent::processUrl($package, $url);
@ -131,4 +133,21 @@ abstract class ArchiveDownloader extends FileDownloader
* @throws \UnexpectedValueException If can not extract downloaded file to path
*/
abstract protected function extract($file, $path);
/**
* Returns the folder content, excluding dotfiles
*
* @param string $dir Directory
* @return \SplFileInfo[]
*/
private function getFolderContent($dir)
{
$finder = Finder::create()
->ignoreVCS(false)
->ignoreDotFiles(false)
->depth(0)
->in($dir);
return iterator_to_array($finder);
}
}

@ -0,0 +1,32 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
/**
* ChangeReport interface.
*
* @author Sascha Egerer <sascha.egerer@dkd.de>
*/
interface ChangeReportInterface
{
/**
* Checks for changes to the local copy
*
* @param PackageInterface $package package instance
* @param string $path package directory
* @return string|null changes or null
*/
public function getLocalChanges(PackageInterface $package, $path);
}

@ -13,7 +13,7 @@
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
use Composer\Downloader\DownloaderInterface;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
/**
@ -23,6 +23,7 @@ use Composer\Util\Filesystem;
*/
class DownloadManager
{
private $io;
private $preferDist = false;
private $preferSource = false;
private $filesystem;
@ -31,11 +32,13 @@ class DownloadManager
/**
* Initializes download manager.
*
* @param IOInterface $io The Input Output Interface
* @param bool $preferSource prefer downloading from source
* @param Filesystem|null $filesystem custom Filesystem object
*/
public function __construct($preferSource = false, Filesystem $filesystem = null)
public function __construct(IOInterface $io, $preferSource = false, Filesystem $filesystem = null)
{
$this->io = $io;
$this->preferSource = $preferSource;
$this->filesystem = $filesystem ?: new Filesystem();
}
@ -43,7 +46,8 @@ class DownloadManager
/**
* Makes downloader prefer source installation over the dist.
*
* @param bool $preferSource prefer downloading from source
* @param bool $preferSource prefer downloading from source
* @return DownloadManager
*/
public function setPreferSource($preferSource)
{
@ -55,7 +59,8 @@ class DownloadManager
/**
* Makes downloader prefer dist installation over the source.
*
* @param bool $preferDist prefer downloading from dist
* @param bool $preferDist prefer downloading from dist
* @return DownloadManager
*/
public function setPreferDist($preferDist)
{
@ -83,8 +88,9 @@ class DownloadManager
/**
* Sets installer downloader for a specific installation type.
*
* @param string $type installation type
* @param DownloaderInterface $downloader downloader instance
* @param string $type installation type
* @param DownloaderInterface $downloader downloader instance
* @return DownloadManager
*/
public function setDownloader($type, DownloaderInterface $downloader)
{
@ -97,17 +103,16 @@ class DownloadManager
/**
* Returns downloader for a specific installation type.
*
* @param string $type installation type
*
* @param string $type installation type
* @return DownloaderInterface
*
* @throws UnexpectedValueException if downloader for provided type is not registered
* @throws \InvalidArgumentException if downloader for provided type is not registered
*/
public function getDownloader($type)
{
$type = strtolower($type);
if (!isset($this->downloaders[$type])) {
throw new \InvalidArgumentException('Unknown downloader type: '.$type);
throw new \InvalidArgumentException(sprintf('Unknown downloader type: %s. Available types: %s.', $type, implode(', ', array_keys($this->downloaders))));
}
return $this->downloaders[$type];
@ -116,18 +121,21 @@ class DownloadManager
/**
* Returns downloader for already installed package.
*
* @param PackageInterface $package package instance
*
* @return DownloaderInterface
* @param PackageInterface $package package instance
* @return DownloaderInterface|null
*
* @throws InvalidArgumentException if package has no installation source specified
* @throws LogicException if specific downloader used to load package with
* wrong type
* @throws \InvalidArgumentException if package has no installation source specified
* @throws \LogicException if specific downloader used to load package with
* wrong type
*/
public function getDownloaderForInstalledPackage(PackageInterface $package)
{
$installationSource = $package->getInstallationSource();
if ('metapackage' === $package->getType()) {
return;
}
if ('dist' === $installationSource) {
$downloader = $this->getDownloader($package->getDistType());
} elseif ('source' === $installationSource) {
@ -155,7 +163,8 @@ class DownloadManager
* @param string $targetDir target dir
* @param bool $preferSource prefer installation from source
*
* @throws InvalidArgumentException if package have no urls to download from
* @throws \InvalidArgumentException if package have no urls to download from
* @throws \RuntimeException
*/
public function download(PackageInterface $package, $targetDir, $preferSource = null)
{
@ -163,18 +172,48 @@ class DownloadManager
$sourceType = $package->getSourceType();
$distType = $package->getDistType();
if ((!$package->isDev() || $this->preferDist || !$sourceType) && !($preferSource && $sourceType) && $distType) {
$package->setInstallationSource('dist');
} elseif ($sourceType) {
$package->setInstallationSource('source');
} else {
$sources = array();
if ($sourceType) {
$sources[] = 'source';
}
if ($distType) {
$sources[] = 'dist';
}
if (empty($sources)) {
throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified');
}
if ((!$package->isDev() || $this->preferDist) && !$preferSource) {
$sources = array_reverse($sources);
}
$this->filesystem->ensureDirectoryExists($targetDir);
$downloader = $this->getDownloaderForInstalledPackage($package);
$downloader->download($package, $targetDir);
foreach ($sources as $i => $source) {
if (isset($e)) {
$this->io->write('<warning>Now trying to download from ' . $source . '</warning>');
}
$package->setInstallationSource($source);
try {
$downloader = $this->getDownloaderForInstalledPackage($package);
if ($downloader) {
$downloader->download($package, $targetDir);
}
break;
} catch (\RuntimeException $e) {
if ($i == count($sources) - 1) {
throw $e;
}
$this->io->write(
'<warning>Failed to download '.
$package->getPrettyName().
' from ' . $source . ': '.
$e->getMessage().'</warning>'
);
}
}
}
/**
@ -184,11 +223,15 @@ class DownloadManager
* @param PackageInterface $target target package version
* @param string $targetDir target dir
*
* @throws InvalidArgumentException if initial package is not installed
* @throws \InvalidArgumentException if initial package is not installed
*/
public function update(PackageInterface $initial, PackageInterface $target, $targetDir)
{
$downloader = $this->getDownloaderForInstalledPackage($initial);
if (!$downloader) {
return;
}
$installationSource = $initial->getInstallationSource();
if ('dist' === $installationSource) {
@ -225,6 +268,8 @@ class DownloadManager
public function remove(PackageInterface $package, $targetDir)
{
$downloader = $this->getDownloaderForInstalledPackage($package);
$downloader->remove($package, $targetDir);
if ($downloader) {
$downloader->remove($package, $targetDir);
}
}
}

@ -17,8 +17,10 @@ use Composer\Cache;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionParser;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PreFileDownloadEvent;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\Filesystem;
use Composer\Util\GitHub;
use Composer\Util\RemoteFilesystem;
/**
@ -27,10 +29,10 @@ use Composer\Util\RemoteFilesystem;
* @author Kirill chEbba Chebunin <iam@chebba.org>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author François Pluchino <francois.pluchino@opendisplay.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class FileDownloader implements DownloaderInterface
{
private static $cacheCollected = false;
protected $io;
protected $config;
protected $rfs;
@ -41,24 +43,25 @@ class FileDownloader implements DownloaderInterface
/**
* Constructor.
*
* @param IOInterface $io The IO instance
* @param Config $config The config
* @param Cache $cache Optional cache instance
* @param RemoteFilesystem $rfs The remote filesystem
* @param Filesystem $filesystem The filesystem
* @param IOInterface $io The IO instance
* @param Config $config The config
* @param EventDispatcher $eventDispatcher The event dispatcher
* @param Cache $cache Optional cache instance
* @param RemoteFilesystem $rfs The remote filesystem
* @param Filesystem $filesystem The filesystem
*/
public function __construct(IOInterface $io, Config $config, Cache $cache = null, RemoteFilesystem $rfs = null, Filesystem $filesystem = null)
public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, RemoteFilesystem $rfs = null, Filesystem $filesystem = null)
{
$this->io = $io;
$this->config = $config;
$this->rfs = $rfs ?: new RemoteFilesystem($io);
$this->eventDispatcher = $eventDispatcher;
$this->rfs = $rfs ?: new RemoteFilesystem($io, $config);
$this->filesystem = $filesystem ?: new Filesystem();
$this->cache = $cache;
if ($this->cache && !self::$cacheCollected && !rand(0, 50)) {
$this->cache->gc($config->get('cache-ttl'));
if ($this->cache && $this->cache->gcIsNecessary()) {
$this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize'));
}
self::$cacheCollected = true;
}
/**
@ -74,50 +77,82 @@ class FileDownloader implements DownloaderInterface
*/
public function download(PackageInterface $package, $path)
{
$url = $package->getDistUrl();
if (!$url) {
if (!$package->getDistUrl()) {
throw new \InvalidArgumentException('The given package is missing url information');
}
$this->filesystem->ensureDirectoryExists($path);
$this->io->write(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
$fileName = $this->getFileName($package, $path);
$urls = $package->getDistUrls();
while ($url = array_shift($urls)) {
try {
return $this->doDownload($package, $path, $url);
} catch (\Exception $e) {
if ($this->io->isDebug()) {
$this->io->write('');
$this->io->write('Failed: ['.get_class($e).'] '.$e->getMessage());
} elseif (count($urls)) {
$this->io->write('');
$this->io->write(' Failed, trying the next URL');
}
$this->io->write(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
if (!count($urls)) {
throw $e;
}
}
}
$this->io->write('');
}
protected function doDownload(PackageInterface $package, $path, $url)
{
$this->filesystem->emptyDirectory($path);
$fileName = $this->getFileName($package, $path);
$processedUrl = $this->processUrl($package, $url);
$hostname = parse_url($processedUrl, PHP_URL_HOST);
if (strpos($hostname, '.github.com') === (strlen($hostname) - 11)) {
$hostname = 'github.com';
$preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl);
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
}
$rfs = $preFileDownloadEvent->getRemoteFilesystem();
try {
try {
if (!$this->cache || !$this->cache->copyTo($this->getCacheKey($package), $fileName)) {
$this->rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress);
if (!$this->outputProgress) {
$this->io->write(' Downloading');
}
if ($this->cache) {
$this->cache->copyFrom($this->getCacheKey($package), $fileName);
}
} else {
$this->io->write(' Loading from cache');
$checksum = $package->getDistSha1Checksum();
$cacheKey = $this->getCacheKey($package);
// download if we don't have it in cache or the cache is invalidated
if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) {
if (!$this->outputProgress) {
$this->io->write(' Downloading');
}
} catch (TransportException $e) {
if (404 === $e->getCode() && 'github.com' === $hostname) {
$message = "\n".'Could not fetch '.$processedUrl.', enter your GitHub credentials to access private repos';
$gitHubUtil = new GitHub($this->io, $this->config, null, $this->rfs);
if (!$gitHubUtil->authorizeOAuth($hostname)
&& (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($hostname, $message))
) {
throw $e;
// try to download 3 times then fail hard
$retries = 3;
while ($retries--) {
try {
$rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions());
break;
} catch (TransportException $e) {
// if we got an http response with a proper code, then requesting again will probably not help, abort
if ((0 !== $e->getCode() && !in_array($e->getCode(),array(500, 502, 503, 504))) || !$retries) {
throw $e;
}
if ($this->io->isVerbose()) {
$this->io->write(' Download failed, retrying...');
}
usleep(500000);
}
$this->rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress);
} else {
throw $e;
}
if ($this->cache) {
$this->cache->copyFrom($cacheKey, $fileName);
}
} else {
$this->io->write(' Loading from cache');
}
if (!file_exists($fileName)) {
@ -125,7 +160,6 @@ class FileDownloader implements DownloaderInterface
.' directory is writable and you have internet connectivity');
}
$checksum = $package->getDistSha1Checksum();
if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')');
}
@ -135,6 +169,8 @@ class FileDownloader implements DownloaderInterface
$this->clearCache($package, $path);
throw $e;
}
return $fileName;
}
/**

@ -0,0 +1,26 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
/**
* Exception thrown when issues exist on local filesystem
*
* @author Javier Spagnoletti <jspagnoletti@javierspagnoletti.com.ar>
*/
class FilesystemException extends \Exception
{
public function __construct($message = null, $code = null, \Exception $previous = null)
{
parent::__construct("Filesystem exception: \n".$message, $code, $previous);
}
}

@ -14,6 +14,11 @@ namespace Composer\Downloader;
use Composer\Package\PackageInterface;
use Composer\Util\GitHub;
use Composer\Util\Git as GitUtil;
use Composer\Util\ProcessExecutor;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Composer\Config;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
@ -21,64 +26,83 @@ use Composer\Util\GitHub;
class GitDownloader extends VcsDownloader
{
private $hasStashedChanges = false;
private $gitUtil;
public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null)
{
parent::__construct($io, $config, $process, $fs);
$this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem);
}
/**
* {@inheritDoc}
*/
public function doDownload(PackageInterface $package, $path)
public function doDownload(PackageInterface $package, $path, $url)
{
GitUtil::cleanEnv();
$path = $this->normalizePath($path);
$ref = $package->getSourceReference();
$command = 'git clone %s %s && cd %2$s && git remote add composer %1$s && git fetch composer';
$flag = defined('PHP_WINDOWS_VERSION_MAJOR') ? '/D ' : '';
$command = 'git clone --no-checkout %s %s && cd '.$flag.'%2$s && git remote add composer %1$s && git fetch composer';
$this->io->write(" Cloning ".$ref);
// added in git 1.7.1, prevents prompting the user
putenv('GIT_ASKPASS=echo');
$commandCallable = function($url) use ($ref, $path, $command) {
return sprintf($command, escapeshellarg($url), escapeshellarg($path), escapeshellarg($ref));
$commandCallable = function ($url) use ($ref, $path, $command) {
return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($ref));
};
$this->runCommand($commandCallable, $package->getSourceUrl(), $path);
$this->setPushUrl($package, $path);
$this->gitUtil->runCommand($commandCallable, $url, $path, true);
$this->setPushUrl($path, $url);
$this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate());
if ($newRef = $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate())) {
if ($package->getDistReference() === $package->getSourceReference()) {
$package->setDistReference($newRef);
}
$package->setSourceReference($newRef);
}
}
/**
* {@inheritDoc}
*/
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
{
GitUtil::cleanEnv();
$path = $this->normalizePath($path);
if (!is_dir($path.'/.git')) {
throw new \RuntimeException('The .git directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
}
$ref = $target->getSourceReference();
$this->io->write(" Checking out ".$ref);
$command = 'cd %s && git remote set-url composer %s && git fetch composer && git fetch --tags composer';
if (!$this->io->hasAuthentication('github.com')) {
// capture username/password from github URL if there is one
$this->process->execute(sprintf('cd %s && git remote -v', escapeshellarg($path)), $output);
if (preg_match('{^composer\s+https://(.+):(.+)@github.com/}im', $output, $match)) {
$this->io->setAuthentication('github.com', $match[1], $match[2]);
}
}
$command = 'git remote set-url composer %s && git fetch composer && git fetch --tags composer';
$commandCallable = function($url) use ($ref, $path, $command) {
return sprintf($command, escapeshellarg($path), escapeshellarg($url), escapeshellarg($ref));
$commandCallable = function ($url) use ($command) {
return sprintf($command, ProcessExecutor::escape ($url));
};
$this->runCommand($commandCallable, $target->getSourceUrl());
$this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate());
$this->gitUtil->runCommand($commandCallable, $url, $path);
if ($newRef = $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate())) {
if ($target->getDistReference() === $target->getSourceReference()) {
$target->setDistReference($newRef);
}
$target->setSourceReference($newRef);
}
}
/**
* {@inheritDoc}
*/
public function getLocalChanges($path)
public function getLocalChanges(PackageInterface $package, $path)
{
GitUtil::cleanEnv();
$path = $this->normalizePath($path);
if (!is_dir($path.'/.git')) {
return;
}
$command = sprintf('cd %s && git status --porcelain --untracked-files=no', escapeshellarg($path));
if (0 !== $this->process->execute($command, $output)) {
$command = 'git status --porcelain --untracked-files=no';
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}
@ -88,14 +112,28 @@ class GitDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
protected function cleanChanges($path, $update)
protected function cleanChanges(PackageInterface $package, $path, $update)
{
if (!$this->io->isInteractive()) {
return parent::cleanChanges($path, $update);
GitUtil::cleanEnv();
$path = $this->normalizePath($path);
if (!$changes = $this->getLocalChanges($package, $path)) {
return;
}
if (!$changes = $this->getLocalChanges($path)) {
return;
if (!$this->io->isInteractive()) {
$discardChanges = $this->config->get('discard-changes');
if (true === $discardChanges) {
return $this->discardChanges($path);
}
if ('stash' === $discardChanges) {
if (!$update) {
return parent::cleanChanges($package, $path, $update);
}
return $this->stashChanges($path);
}
return parent::cleanChanges($package, $path, $update);
}
$changes = array_map(function ($elem) {
@ -110,9 +148,7 @@ class GitDownloader extends VcsDownloader
while (true) {
switch ($this->io->ask(' <info>Discard changes [y,n,v,'.($update ? 's,' : '').'?]?</info> ', '?')) {
case 'y':
if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
}
$this->discardChanges($path);
break 2;
case 's':
@ -120,11 +156,7 @@ class GitDownloader extends VcsDownloader
goto help;
}
if (0 !== $this->process->execute('git stash', $output, $path)) {
throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
}
$this->hasStashedChanges = true;
$this->stashChanges($path);
break 2;
case 'n':
@ -156,15 +188,27 @@ class GitDownloader extends VcsDownloader
*/
protected function reapplyChanges($path)
{
$path = $this->normalizePath($path);
if ($this->hasStashedChanges) {
$this->hasStashedChanges = false;
$this->io->write(' <info>Re-applying stashed changes');
$this->io->write(' <info>Re-applying stashed changes</info>');
if (0 !== $this->process->execute('git stash pop', $output, $path)) {
throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
}
}
}
/**
* Updates the given path to the given commit ref
*
* @param string $path
* @param string $reference
* @param string $branch
* @param \DateTime $date
* @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found
*
* @throws \RuntimeException
*/
protected function updateToCommit($path, $reference, $branch, $date)
{
$template = 'git checkout %s && git reset --hard %1$s';
@ -179,9 +223,9 @@ class GitDownloader extends VcsDownloader
$gitRef = $reference;
if (!preg_match('{^[a-f0-9]{40}$}', $reference)
&& $branches
&& preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $output)
&& preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $branches)
) {
$command = sprintf('git checkout -B %s %s && git reset --hard %2$s', escapeshellarg($branch), escapeshellarg('composer/'.$reference));
$command = sprintf('git checkout -B %s %s && git reset --hard %2$s', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$reference));
if (0 === $this->process->execute($command, $output, $path)) {
return;
}
@ -194,19 +238,19 @@ class GitDownloader extends VcsDownloader
$branch = 'v' . $branch;
}
$command = sprintf('git checkout %s', escapeshellarg($branch));
$fallbackCommand = sprintf('git checkout -B %s %s', escapeshellarg($branch), escapeshellarg('composer/'.$branch));
$command = sprintf('git checkout %s', ProcessExecutor::escape($branch));
$fallbackCommand = sprintf('git checkout -B %s %s', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$branch));
if (0 === $this->process->execute($command, $output, $path)
|| 0 === $this->process->execute($fallbackCommand, $output, $path)
) {
$command = sprintf('git reset --hard %s', escapeshellarg($reference));
$command = sprintf('git reset --hard %s', ProcessExecutor::escape($reference));
if (0 === $this->process->execute($command, $output, $path)) {
return;
}
}
}
$command = sprintf($template, escapeshellarg($gitRef));
$command = sprintf($template, ProcessExecutor::escape($gitRef));
if (0 === $this->process->execute($command, $output, $path)) {
return;
}
@ -225,7 +269,7 @@ class GitDownloader extends VcsDownloader
foreach ($this->process->splitLines($output) as $line) {
if (preg_match('{^composer/'.preg_quote($branch).'(?:\.x)?$}i', trim($line))) {
// find the previous commit by date in the given branch
if (0 === $this->process->execute(sprintf($guessTemplate, $date, escapeshellarg(trim($line))), $output, $path)) {
if (0 === $this->process->execute(sprintf($guessTemplate, $date, ProcessExecutor::escape(trim($line))), $output, $path)) {
$newReference = trim($output);
}
@ -236,137 +280,96 @@ class GitDownloader extends VcsDownloader
if (empty($newReference)) {
// no matching branch found, find the previous commit by date in all commits
if (0 !== $this->process->execute(sprintf($guessTemplate, $date, '--all'), $output, $path)) {
throw new \RuntimeException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
throw new \RuntimeException('Failed to execute ' . GitUtil::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
}
$newReference = trim($output);
}
// checkout the new recovered ref
$command = sprintf($template, escapeshellarg($reference));
$command = sprintf($template, ProcessExecutor::escape($newReference));
if (0 === $this->process->execute($command, $output, $path)) {
$this->io->write(' '.$reference.' is gone (history was rewritten?), recovered by checking out '.$newReference);
return;
return $newReference;
}
}
throw new \RuntimeException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
throw new \RuntimeException('Failed to execute ' . GitUtil::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
}
/**
* Runs a command doing attempts for each protocol supported by github.
*
* @param callable $commandCallable A callable building the command for the given url
* @param string $url
* @param string $path The directory to remove for each attempt (null if not needed)
* @throws \RuntimeException
*/
protected function runCommand($commandCallable, $url, $path = null)
protected function setPushUrl($path, $url)
{
$handler = array($this, 'outputHandler');
if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) {
throw new \InvalidArgumentException('The source URL '.$url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
}
// public github, autoswitch protocols
if (preg_match('{^(?:https?|git)(://github.com/.*)}', $url, $match)) {
// set push url for github projects
if (preg_match('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) {
$protocols = $this->config->get('github-protocols');
if (!is_array($protocols)) {
throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
}
$messages = array();
foreach ($protocols as $protocol) {
$url = $protocol . $match[1];
if (0 === $this->process->execute(call_user_func($commandCallable, $url), $handler)) {
return;
}
$messages[] = '- ' . $url . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
if (null !== $path) {
$this->filesystem->removeDirectory($path);
}
$pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
if ($protocols[0] !== 'git') {
$pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git';
}
// failed to checkout, first check git accessibility
$this->throwException('Failed to clone ' . $this->sanitizeUrl($url) .' via git, https and http protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
$cmd = sprintf('git remote set-url --push origin %s', ProcessExecutor::escape($pushUrl));
$this->process->execute($cmd, $ignoredOutput, $path);
}
}
$command = call_user_func($commandCallable, $url);
if (0 !== $this->process->execute($command, $handler)) {
// private github repository without git access, try https with auth
if (preg_match('{^git@(github.com):(.+?)\.git$}i', $url, $match)) {
if (!$this->io->hasAuthentication($match[1])) {
$gitHubUtil = new GitHub($this->io, $this->config, $this->process);
$message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
$gitHubUtil->authorizeOAuthInteractively($match[1], $message);
}
}
if ($this->io->hasAuthentication($match[1])) {
$auth = $this->io->getAuthentication($match[1]);
$url = 'https://'.$auth['username'] . ':' . $auth['password'] . '@'.$match[1].'/'.$match[2].'.git';
$command = call_user_func($commandCallable, $url);
if (0 === $this->process->execute($command, $handler)) {
return;
}
}
}
/**
* {@inheritDoc}
*/
protected function getCommitLogs($fromReference, $toReference, $path)
{
$path = $this->normalizePath($path);
$command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference);
if (null !== $path) {
$this->filesystem->removeDirectory($path);
}
$this->throwException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput(), $url);
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}
return $output;
}
public function outputHandler($type, $buffer)
/**
* @param $path
* @throws \RuntimeException
*/
protected function discardChanges($path)
{
if ($type !== 'out') {
return;
}
if ($this->io->isVerbose()) {
$this->io->write($buffer, false);
$path = $this->normalizePath($path);
if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
}
}
protected function throwException($message, $url)
/**
* @param $path
* @throws \RuntimeException
*/
protected function stashChanges($path)
{
if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
throw new \RuntimeException('Failed to clone '.$this->sanitizeUrl($url).', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
$path = $this->normalizePath($path);
if (0 !== $this->process->execute('git stash', $output, $path)) {
throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
}
throw new \RuntimeException($message);
$this->hasStashedChanges = true;
}
protected function sanitizeUrl($message)
protected function normalizePath($path)
{
return preg_replace('{://(.+?):.+?@}', '://$1:***@', $message);
}
if (defined('PHP_WINDOWS_VERSION_MAJOR') && strlen($path) > 0) {
$basePath = $path;
$removed = array();
protected function setPushUrl(PackageInterface $package, $path)
{
// set push url for github projects
if (preg_match('{^(?:https?|git)://github.com/([^/]+)/([^/]+?)(?:\.git)?$}', $package->getSourceUrl(), $match)) {
$pushUrl = 'git@github.com:'.$match[1].'/'.$match[2].'.git';
$cmd = sprintf('git remote set-url --push origin %s', escapeshellarg($pushUrl));
$this->process->execute($cmd, $ignoredOutput, $path);
}
}
while (!is_dir($basePath) && $basePath !== '\\') {
array_unshift($removed, basename($basePath));
$basePath = dirname($basePath);
}
/**
* {@inheritDoc}
*/
protected function getCommitLogs($fromReference, $toReference, $path)
{
$command = sprintf('cd %s && git log %s..%s --pretty=format:"%%h - %%an: %%s"', escapeshellarg($path), $fromReference, $toReference);
if ($basePath === '\\') {
return $path;
}
if (0 !== $this->process->execute($command, $output)) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
$path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
}
return $output;
return $path;
}
}

@ -0,0 +1,70 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Config;
use Composer\Cache;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Package\PackageInterface;
use Composer\Util\ProcessExecutor;
use Composer\IO\IOInterface;
/**
* GZip archive downloader.
*
* @author Pavel Puchkin <i@neoascetic.me>
*/
class GzipDownloader extends ArchiveDownloader
{
protected $process;
public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
{
$this->process = $process ?: new ProcessExecutor($io);
parent::__construct($io, $config, $eventDispatcher, $cache);
}
protected function extract($file, $path)
{
$targetFilepath = $path . DIRECTORY_SEPARATOR . basename(substr($file, 0, -3));
// Try to use gunzip on *nix
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = 'gzip -cd ' . ProcessExecutor::escape($file) . ' > ' . ProcessExecutor::escape($targetFilepath);
if (0 === $this->process->execute($command, $ignoredOutput)) {
return;
}
$processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
throw new \RuntimeException($processError);
}
// Windows version of PHP has built-in support of gzip functions
$archiveFile = gzopen($file, 'rb');
$targetFile = fopen($targetFilepath, 'wb');
while ($string = gzread($archiveFile, 4096)) {
fwrite($targetFile, $string, strlen($string));
}
gzclose($archiveFile);
fclose($targetFile);
}
/**
* {@inheritdoc}
*/
protected function getFileName(PackageInterface $package, $path)
{
return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
}
}

@ -13,6 +13,7 @@
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
use Composer\Util\ProcessExecutor;
/**
* @author Per Bernhardt <plb@webfactory.de>
@ -22,29 +23,36 @@ class HgDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
public function doDownload(PackageInterface $package, $path)
public function doDownload(PackageInterface $package, $path, $url)
{
$url = escapeshellarg($package->getSourceUrl());
$ref = escapeshellarg($package->getSourceReference());
$path = escapeshellarg($path);
$url = ProcessExecutor::escape($url);
$ref = ProcessExecutor::escape($package->getSourceReference());
$this->io->write(" Cloning ".$package->getSourceReference());
$command = sprintf('hg clone %s %s && cd %2$s && hg up %s', $url, $path, $ref);
$command = sprintf('hg clone %s %s', $url, ProcessExecutor::escape($path));
if (0 !== $this->process->execute($command, $ignoredOutput)) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}
$command = sprintf('hg up %s', $ref);
if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}
}
/**
* {@inheritDoc}
*/
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
{
$url = escapeshellarg($target->getSourceUrl());
$ref = escapeshellarg($target->getSourceReference());
$path = escapeshellarg($path);
$url = ProcessExecutor::escape($url);
$ref = ProcessExecutor::escape($target->getSourceReference());
$this->io->write(" Updating to ".$target->getSourceReference());
$command = sprintf('cd %s && hg pull %s && hg up %s', $path, $url, $ref);
if (0 !== $this->process->execute($command, $ignoredOutput)) {
if (!is_dir($path.'/.hg')) {
throw new \RuntimeException('The .hg directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
}
$command = sprintf('hg pull %s && hg up %s', $url, $ref);
if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}
}
@ -52,13 +60,13 @@ class HgDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
public function getLocalChanges($path)
public function getLocalChanges(PackageInterface $package, $path)
{
if (!is_dir($path.'/.hg')) {
return;
}
$this->process->execute(sprintf('cd %s && hg st', escapeshellarg($path)), $output);
$this->process->execute('hg st', $output, realpath($path));
return trim($output) ?: null;
}
@ -68,9 +76,9 @@ class HgDownloader extends VcsDownloader
*/
protected function getCommitLogs($fromReference, $toReference, $path)
{
$command = sprintf('cd %s && hg log -r %s:%s --style compact', escapeshellarg($path), $fromReference, $toReference);
$command = sprintf('hg log -r %s:%s --style compact', $fromReference, $toReference);
if (0 !== $this->process->execute($command, $output)) {
if (0 !== $this->process->execute($command, $output, realpath($path))) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
}

@ -127,11 +127,11 @@ class PearPackageExtractor
/**
* Builds list of copy and list of remove actions that would transform extracted PEAR tarball into installed package.
*
* @param string $source string path to extracted files
* @param array $roles array [role => roleRoot] relative root for files having that role
* @param array $vars list of values can be used for replacement tasks
* @return array array of 'source' => 'target', where source is location of file in the tarball (relative to source
* path, and target is destination of file (also relative to $source path)
* @param string $source string path to extracted files
* @param array $roles array [role => roleRoot] relative root for files having that role
* @param array $vars list of values can be used for replacement tasks
* @return array array of 'source' => 'target', where source is location of file in the tarball (relative to source
* path, and target is destination of file (also relative to $source path)
* @throws \RuntimeException
*/
private function buildCopyActions($source, array $roles, $vars)
@ -194,7 +194,7 @@ class PearPackageExtractor
}
}
private function buildSourceList10($children, $targetRoles, $source = '', $target = '', $role = null, $packageName)
private function buildSourceList10($children, $targetRoles, $source, $target, $role, $packageName)
{
$result = array();
@ -224,7 +224,7 @@ class PearPackageExtractor
return $result;
}
private function buildSourceList20($children, $targetRoles, $source = '', $target = '', $role = null, $packageName)
private function buildSourceList20($children, $targetRoles, $source, $target, $role, $packageName)
{
$result = array();

@ -0,0 +1,107 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
use Composer\Repository\VcsRepository;
use Composer\Util\Perforce;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceDownloader extends VcsDownloader
{
protected $perforce;
/**
* {@inheritDoc}
*/
public function doDownload(PackageInterface $package, $path, $url)
{
$ref = $package->getSourceReference();
$label = $this->getLabelFromSourceReference($ref);
$this->io->write(' Cloning ' . $ref);
$this->initPerforce($package, $path, $url);
$this->perforce->setStream($ref);
$this->perforce->p4Login($this->io);
$this->perforce->writeP4ClientSpec();
$this->perforce->connectClient();
$this->perforce->syncCodeBase($label);
$this->perforce->cleanupClientSpec();
}
private function getLabelFromSourceReference($ref)
{
$pos = strpos($ref,'@');
if (false !== $pos) {
return substr($ref, $pos + 1);
}
return null;
}
public function initPerforce($package, $path, $url)
{
if (!empty($this->perforce)) {
$this->perforce->initializePath($path);
return;
}
$repository = $package->getRepository();
$repoConfig = null;
if ($repository instanceof VcsRepository) {
$repoConfig = $this->getRepoConfig($repository);
}
$this->perforce = Perforce::create($repoConfig, $url, $path, $this->process, $this->io);
}
private function getRepoConfig(VcsRepository $repository)
{
return $repository->getRepoConfig();
}
/**
* {@inheritDoc}
*/
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
{
$this->doDownload($target, $path, $url);
}
/**
* {@inheritDoc}
*/
public function getLocalChanges(PackageInterface $package, $path)
{
$this->io->write('Perforce driver does not check for local changes before overriding', true);
return;
}
/**
* {@inheritDoc}
*/
protected function getCommitLogs($fromReference, $toReference, $path)
{
$commitLogs = $this->perforce->getCommitLogs($fromReference, $toReference);
return $commitLogs;
}
public function setPerforce($perforce)
{
$this->perforce = $perforce;
}
}

@ -0,0 +1,94 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Config;
use Composer\Cache;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\ProcessExecutor;
use Composer\IO\IOInterface;
use RarArchive;
/**
* RAR archive downloader.
*
* Based on previous work by Jordi Boggiano ({@see ZipDownloader}).
*
* @author Derrick Nelson <drrcknlsn@gmail.com>
*/
class RarDownloader extends ArchiveDownloader
{
protected $process;
public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
{
$this->process = $process ?: new ProcessExecutor($io);
parent::__construct($io, $config, $eventDispatcher, $cache);
}
protected function extract($file, $path)
{
$processError = null;
// Try to use unrar on *nix
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = 'unrar x ' . ProcessExecutor::escape($file) . ' ' . ProcessExecutor::escape($path) . ' && chmod -R u+w ' . ProcessExecutor::escape($path);
if (0 === $this->process->execute($command, $ignoredOutput)) {
return;
}
$processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
}
if (!class_exists('RarArchive')) {
// php.ini path is added to the error message to help users find the correct file
$iniPath = php_ini_loaded_file();
if ($iniPath) {
$iniMessage = 'The php.ini used by your command-line PHP is: ' . $iniPath;
} else {
$iniMessage = 'A php.ini file does not exist. You will have to create one.';
}
$error = "Could not decompress the archive, enable the PHP rar extension or install unrar.\n"
. $iniMessage . "\n" . $processError;
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$error = "Could not decompress the archive, enable the PHP rar extension.\n" . $iniMessage;
}
throw new \RuntimeException($error);
}
$rarArchive = RarArchive::open($file);
if (false === $rarArchive) {
throw new \UnexpectedValueException('Could not open RAR archive: ' . $file);
}
$entries = $rarArchive->getEntries();
if (false === $entries) {
throw new \RuntimeException('Could not retrieve RAR archive entries');
}
foreach ($entries as $entry) {
if (false === $entry->extract($path)) {
throw new \RuntimeException('Could not extract entry');
}
}
$rarArchive->close();
}
}

@ -24,10 +24,10 @@ class SvnDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
public function doDownload(PackageInterface $package, $path)
public function doDownload(PackageInterface $package, $path, $url)
{
$url = $package->getSourceUrl();
$ref = $package->getSourceReference();
SvnUtil::cleanEnv();
$ref = $package->getSourceReference();
$this->io->write(" Checking out ".$package->getSourceReference());
$this->execute($url, "svn co", sprintf("%s/%s", $url, $ref), null, $path);
@ -36,19 +36,30 @@ class SvnDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
{
$url = $target->getSourceUrl();
SvnUtil::cleanEnv();
$ref = $target->getSourceReference();
if (!is_dir($path.'/.svn')) {
throw new \RuntimeException('The .svn directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
}
$flags = "";
if (0 === $this->process->execute('svn --version', $output)) {
if (preg_match('{(\d+(?:\.\d+)+)}', $output, $match) && version_compare($match[1], '1.7.0', '>=')) {
$flags .= ' --ignore-ancestry';
}
}
$this->io->write(" Checking out " . $ref);
$this->execute($url, "svn switch", sprintf("%s/%s", $url, $ref), $path);
$this->execute($url, "svn switch" . $flags, sprintf("%s/%s", $url, $ref), $path);
}
/**
* {@inheritDoc}
*/
public function getLocalChanges($path)
public function getLocalChanges(PackageInterface $package, $path)
{
if (!is_dir($path.'/.svn')) {
return;
@ -63,17 +74,17 @@ class SvnDownloader extends VcsDownloader
* Execute an SVN command and try to fix up the process with credentials
* if necessary.
*
* @param string $baseUrl Base URL of the repository
* @param string $command SVN command to run
* @param string $url SVN url
* @param string $cwd Working directory
* @param string $path Target for a checkout
*
* @param string $baseUrl Base URL of the repository
* @param string $command SVN command to run
* @param string $url SVN url
* @param string $cwd Working directory
* @param string $path Target for a checkout
* @throws \RuntimeException
* @return string
*/
protected function execute($baseUrl, $command, $url, $cwd = null, $path = null)
{
$util = new SvnUtil($baseUrl, $this->io);
$util = new SvnUtil($baseUrl, $this->io, $this->config);
try {
return $util->execute($command, $url, $cwd, $path, $this->io->isVerbose());
} catch (\RuntimeException $e) {
@ -86,14 +97,18 @@ class SvnDownloader extends VcsDownloader
/**
* {@inheritDoc}
*/
protected function cleanChanges($path, $update)
protected function cleanChanges(PackageInterface $package, $path, $update)
{
if (!$this->io->isInteractive()) {
return parent::cleanChanges($path, $update);
if (!$changes = $this->getLocalChanges($package, $path)) {
return;
}
if (!$changes = $this->getLocalChanges($path)) {
return;
if (!$this->io->isInteractive()) {
if (true === $this->config->get('discard-changes')) {
return $this->discardChanges($path);
}
return parent::cleanChanges($package, $path, $update);
}
$changes = array_map(function ($elem) {
@ -108,9 +123,7 @@ class SvnDownloader extends VcsDownloader
while (true) {
switch ($this->io->ask(' <info>Discard changes [y,n,v,?]?</info> ', '?')) {
case 'y':
if (0 !== $this->process->execute('svn revert -R .', $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
}
$this->discardChanges($path);
break 2;
case 'n':
@ -138,16 +151,29 @@ class SvnDownloader extends VcsDownloader
*/
protected function getCommitLogs($fromReference, $toReference, $path)
{
// strip paths from references and only keep the actual revision
$fromRevision = preg_replace('{.*@(\d+)$}', '$1', $fromReference);
$toRevision = preg_replace('{.*@(\d+)$}', '$1', $toReference);
if (preg_match('{.*@(\d+)$}', $fromReference) && preg_match('{.*@(\d+)$}', $toReference) ) {
// strip paths from references and only keep the actual revision
$fromRevision = preg_replace('{.*@(\d+)$}', '$1', $fromReference);
$toRevision = preg_replace('{.*@(\d+)$}', '$1', $toReference);
$command = sprintf('cd %s && svn log -r%s:%s --incremental', escapeshellarg($path), $fromRevision, $toRevision);
$command = sprintf('svn log -r%s:%s --incremental', $fromRevision, $toRevision);
if (0 !== $this->process->execute($command, $output)) {
throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException(
'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()
);
}
} else {
$output = "Could not retrieve changes between $fromReference and $toReference due to missing revision information";
}
return $output;
}
protected function discardChanges($path)
{
if (0 !== $this->process->execute('svn revert -R .', $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
}
}
}

@ -15,9 +15,10 @@ namespace Composer\Downloader;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class TransportException extends \Exception
class TransportException extends \RuntimeException
{
protected $headers;
protected $response;
public function setHeaders($headers)
{
@ -28,4 +29,14 @@ class TransportException extends \Exception
{
return $this->headers;
}
public function setResponse($response)
{
$this->response = $response;
}
public function getResponse()
{
return $this->response;
}
}

@ -22,7 +22,7 @@ use Composer\Util\Filesystem;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
abstract class VcsDownloader implements DownloaderInterface
abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterface
{
protected $io;
protected $config;
@ -33,7 +33,7 @@ abstract class VcsDownloader implements DownloaderInterface
{
$this->io = $io;
$this->config = $config;
$this->process = $process ?: new ProcessExecutor;
$this->process = $process ?: new ProcessExecutor($io);
$this->filesystem = $fs ?: new Filesystem;
}
@ -55,8 +55,28 @@ abstract class VcsDownloader implements DownloaderInterface
}
$this->io->write(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
$this->filesystem->removeDirectory($path);
$this->doDownload($package, $path);
$this->filesystem->emptyDirectory($path);
$urls = $package->getSourceUrls();
while ($url = array_shift($urls)) {
try {
if (Filesystem::isLocalPath($url)) {
$url = realpath($url);
}
$this->doDownload($package, $path, $url);
break;
} catch (\Exception $e) {
if ($this->io->isDebug()) {
$this->io->write('Failed: ['.get_class($e).'] '.$e->getMessage());
} elseif (count($urls)) {
$this->io->write(' Failed, trying the next URL');
}
if (!count($urls)) {
throw $e;
}
}
}
$this->io->write('');
}
@ -86,18 +106,32 @@ abstract class VcsDownloader implements DownloaderInterface
$this->io->write(" - Updating <info>" . $name . "</info> (<comment>" . $from . "</comment> => <comment>" . $to . "</comment>)");
$this->cleanChanges($path, true);
try {
$this->doUpdate($initial, $target, $path);
} catch (\Exception $e) {
// in case of failed update, try to reapply the changes before aborting
$this->reapplyChanges($path);
throw $e;
$this->cleanChanges($initial, $path, true);
$urls = $target->getSourceUrls();
while ($url = array_shift($urls)) {
try {
if (Filesystem::isLocalPath($url)) {
$url = realpath($url);
}
$this->doUpdate($initial, $target, $path, $url);
break;
} catch (\Exception $e) {
if ($this->io->isDebug()) {
$this->io->write('Failed: ['.get_class($e).'] '.$e->getMessage());
} elseif (count($urls)) {
$this->io->write(' Failed, trying the next URL');
} else {
// in case of failed update, try to reapply the changes before aborting
$this->reapplyChanges($path);
throw $e;
}
}
}
$this->reapplyChanges($path);
//print the commit logs if in verbose mode
// print the commit logs if in verbose mode
if ($this->io->isVerbose()) {
$message = 'Pulling in changes:';
$logs = $this->getCommitLogs($initial->getSourceReference(), $target->getSourceReference(), $path);
@ -126,7 +160,7 @@ abstract class VcsDownloader implements DownloaderInterface
public function remove(PackageInterface $package, $path)
{
$this->io->write(" - Removing <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)");
$this->cleanChanges($path, false);
$this->cleanChanges($package, $path, false);
if (!$this->filesystem->removeDirectory($path)) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
}
@ -144,15 +178,16 @@ abstract class VcsDownloader implements DownloaderInterface
/**
* Prompt the user to check if changes should be stashed/removed or the operation aborted
*
* @param string $path
* @param bool $update if true (update) the changes can be stashed and reapplied after an update,
* if false (remove) the changes should be assumed to be lost if the operation is not aborted
* @param PackageInterface $package
* @param string $path
* @param bool $update if true (update) the changes can be stashed and reapplied after an update,
* if false (remove) the changes should be assumed to be lost if the operation is not aborted
* @throws \RuntimeException in case the operation must be aborted
*/
protected function cleanChanges($path, $update)
protected function cleanChanges(PackageInterface $package, $path, $update)
{
// the default implementation just fails if there are any changes, override in child classes to provide stash-ability
if (null !== $this->getLocalChanges($path)) {
if (null !== $this->getLocalChanges($package, $path)) {
throw new \RuntimeException('Source directory ' . $path . ' has uncommitted changes.');
}
}
@ -172,8 +207,9 @@ abstract class VcsDownloader implements DownloaderInterface
*
* @param PackageInterface $package package instance
* @param string $path download path
* @param string $url package url
*/
abstract protected function doDownload(PackageInterface $package, $path);
abstract protected function doDownload(PackageInterface $package, $path, $url);
/**
* Updates specific package in specific folder from initial to target version.
@ -181,16 +217,9 @@ abstract class VcsDownloader implements DownloaderInterface
* @param PackageInterface $initial initial package
* @param PackageInterface $target updated package
* @param string $path download path
* @param string $url package url
*/
abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path);
/**
* Checks for changes to the local copy
*
* @param string $path package directory
* @return string|null changes or null
*/
abstract public function getLocalChanges($path);
abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url);
/**
* Fetches the commit logs between two commits

@ -14,6 +14,7 @@ namespace Composer\Downloader;
use Composer\Config;
use Composer\Cache;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\ProcessExecutor;
use Composer\IO\IOInterface;
use ZipArchive;
@ -25,14 +26,30 @@ class ZipDownloader extends ArchiveDownloader
{
protected $process;
public function __construct(IOInterface $io, Config $config, Cache $cache = null, ProcessExecutor $process = null)
public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
{
$this->process = $process ?: new ProcessExecutor;
parent::__construct($io, $config, $cache);
$this->process = $process ?: new ProcessExecutor($io);
parent::__construct($io, $config, $eventDispatcher, $cache);
}
protected function extract($file, $path)
{
$processError = null;
// try to use unzip on *nix
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = 'unzip '.ProcessExecutor::escape($file).' -d '.ProcessExecutor::escape($path) . ' && chmod -R u+w ' . ProcessExecutor::escape($path);
try {
if (0 === $this->process->execute($command, $ignoredOutput)) {
return;
}
$processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
} catch (\Exception $e) {
$processError = 'Failed to execute ' . $command . "\n\n" . $e->getMessage();
}
}
if (!class_exists('ZipArchive')) {
// php.ini path is added to the error message to help users find the correct file
$iniPath = php_ini_loaded_file();
@ -43,19 +60,11 @@ class ZipDownloader extends ArchiveDownloader
$iniMessage = 'A php.ini file does not exist. You will have to create one.';
}
$error = "You need the zip extension enabled to use the ZipDownloader.\n".
$iniMessage;
$error = "Could not decompress the archive, enable the PHP zip extension or install unzip.\n"
. $iniMessage . "\n" . $processError;
// try to use unzip on *nix
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = 'unzip '.escapeshellarg($file).' -d '.escapeshellarg($path);
if (0 === $this->process->execute($command, $ignoredOutput)) {
return;
}
$error = "Could not decompress the archive, enable the PHP zip extension or install unzip.\n".
$iniMessage . "\n" .
'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
$error = "Could not decompress the archive, enable the PHP zip extension.\n" . $iniMessage;
}
throw new \RuntimeException($error);
@ -64,7 +73,7 @@ class ZipDownloader extends ArchiveDownloader
$zipArchive = new ZipArchive();
if (true !== ($retval = $zipArchive->open($file))) {
throw new \UnexpectedValueException($this->getErrorMessage($retval, $file));
throw new \UnexpectedValueException($this->getErrorMessage($retval, $file), $retval);
}
if (true !== $zipArchive->extractTo($path)) {

@ -0,0 +1,103 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\EventDispatcher;
/**
* The base event class
*
* @author Nils Adermann <naderman@naderman.de>
*/
class Event
{
/**
* @var string This event's name
*/
protected $name;
/**
* @var array Arguments passed by the user, these will be forwarded to CLI script handlers
*/
protected $args;
/**
* @var array Flags usable in PHP script handlers
*/
protected $flags;
/**
* @var boolean Whether the event should not be passed to more listeners
*/
private $propagationStopped = false;
/**
* Constructor.
*
* @param string $name The event name
* @param array $args Arguments passed by the user
* @param array $flags Optional flags to pass data not as argument
*/
public function __construct($name, array $args = array(), array $flags = array())
{
$this->name = $name;
$this->args = $args;
$this->flags = $flags;
}
/**
* Returns the event's name.
*
* @return string The event name
*/
public function getName()
{
return $this->name;
}
/**
* Returns the event's arguments.
*
* @return array The event arguments
*/
public function getArguments()
{
return $this->args;
}
/**
* Returns the event's flags.
*
* @return array The event flags
*/
public function getFlags()
{
return $this->flags;
}
/**
* Checks if stopPropagation has been called
*
* @return boolean Whether propagation has been stopped
*/
public function isPropagationStopped()
{
return $this->propagationStopped;
}
/**
* Prevents the event from being passed to further listeners
*/
public function stopPropagation()
{
$this->propagationStopped = true;
}
}

@ -0,0 +1,314 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\EventDispatcher;
use Composer\DependencyResolver\PolicyInterface;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\Request;
use Composer\Installer\InstallerEvent;
use Composer\IO\IOInterface;
use Composer\Composer;
use Composer\DependencyResolver\Operation\OperationInterface;
use Composer\Repository\CompositeRepository;
use Composer\Script;
use Composer\Script\CommandEvent;
use Composer\Script\PackageEvent;
use Composer\Util\ProcessExecutor;
/**
* The Event Dispatcher.
*
* Example in command:
* $dispatcher = new EventDispatcher($this->getComposer(), $this->getApplication()->getIO());
* // ...
* $dispatcher->dispatch(ScriptEvents::POST_INSTALL_CMD);
* // ...
*
* @author François Pluchino <francois.pluchino@opendisplay.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Nils Adermann <naderman@naderman.de>
*/
class EventDispatcher
{
protected $composer;
protected $io;
protected $loader;
protected $process;
/**
* Constructor.
*
* @param Composer $composer The composer instance
* @param IOInterface $io The IOInterface instance
* @param ProcessExecutor $process
*/
public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null)
{
$this->composer = $composer;
$this->io = $io;
$this->process = $process ?: new ProcessExecutor($io);
}
/**
* Dispatch an event
*
* @param string $eventName An event name
* @param Event $event
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
*/
public function dispatch($eventName, Event $event = null)
{
if (null == $event) {
$event = new Event($eventName);
}
return $this->doDispatch($event);
}
/**
* Dispatch a script event.
*
* @param string $eventName The constant in ScriptEvents
* @param bool $devMode
* @param array $additionalArgs Arguments passed by the user
* @param array $flags Optional flags to pass data not as argument
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
*/
public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array())
{
return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags));
}
/**
* Dispatch a package event.
*
* @param string $eventName The constant in ScriptEvents
* @param boolean $devMode Whether or not we are in dev mode
* @param OperationInterface $operation The package being installed/updated/removed
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
*/
public function dispatchPackageEvent($eventName, $devMode, OperationInterface $operation)
{
return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $operation));
}
/**
* Dispatch a command event.
*
* @param string $eventName The constant in ScriptEvents
* @param boolean $devMode Whether or not we are in dev mode
* @param array $additionalArgs Arguments passed by the user
* @param array $flags Optional flags to pass data not as argument
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
*/
public function dispatchCommandEvent($eventName, $devMode, $additionalArgs = array(), $flags = array())
{
return $this->doDispatch(new CommandEvent($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags));
}
/**
* Dispatch a installer event.
*
* @param string $eventName The constant in InstallerEvents
* @param PolicyInterface $policy The policy
* @param Pool $pool The pool
* @param CompositeRepository $installedRepo The installed repository
* @param Request $request The request
* @param array $operations The list of operations
*
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
*/
public function dispatchInstallerEvent($eventName, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array())
{
return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $policy, $pool, $installedRepo, $request, $operations));
}
/**
* Triggers the listeners of an event.
*
* @param Event $event The event object to pass to the event handlers/listeners.
* @param string $additionalArgs
* @return int return code of the executed script if any, for php scripts a false return
* value is changed to 1, anything else to 0
* @throws \RuntimeException
* @throws \Exception
*/
protected function doDispatch(Event $event)
{
$listeners = $this->getListeners($event);
$return = 0;
foreach ($listeners as $callable) {
if (!is_string($callable) && is_callable($callable)) {
$return = false === call_user_func($callable, $event) ? 1 : 0;
} elseif ($this->isPhpScript($callable)) {
$className = substr($callable, 0, strpos($callable, '::'));
$methodName = substr($callable, strpos($callable, '::') + 2);
if (!class_exists($className)) {
$this->io->write('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>');
continue;
}
if (!is_callable($callable)) {
$this->io->write('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>');
continue;
}
try {
$return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0;
} catch (\Exception $e) {
$message = "Script %s handling the %s event terminated with an exception";
$this->io->write('<error>'.sprintf($message, $callable, $event->getName()).'</error>');
throw $e;
}
} else {
$args = implode(' ', array_map(array('Composer\Util\ProcessExecutor','escape'), $event->getArguments()));
if (0 !== ($exitCode = $this->process->execute($callable . ($args === '' ? '' : ' '.$args)))) {
$event->getIO()->write(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
}
}
if ($event->isPropagationStopped()) {
break;
}
}
return $return;
}
/**
* @param string $className
* @param string $methodName
* @param Event $event Event invoking the PHP callable
*/
protected function executeEventPhpScript($className, $methodName, Event $event)
{
return $className::$methodName($event);
}
/**
* Add a listener for a particular event
*
* @param string $eventName The event name - typically a constant
* @param Callable $listener A callable expecting an event argument
* @param integer $priority A higher value represents a higher priority
*/
protected function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[$eventName][$priority][] = $listener;
}
/**
* Adds object methods as listeners for the events in getSubscribedEvents
*
* @see EventSubscriberInterface
*
* @param EventSubscriberInterface $subscriber
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->addListener($eventName, array($subscriber, $params));
} elseif (is_string($params[0])) {
$this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
} else {
foreach ($params as $listener) {
$this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
}
}
}
}
/**
* Retrieves all listeners for a given event
*
* @param Event $event
* @return array All listeners: callables and scripts
*/
protected function getListeners(Event $event)
{
$scriptListeners = $this->getScriptListeners($event);
if (!isset($this->listeners[$event->getName()][0])) {
$this->listeners[$event->getName()][0] = array();
}
krsort($this->listeners[$event->getName()]);
$listeners = $this->listeners;
$listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
return call_user_func_array('array_merge', $listeners[$event->getName()]);
}
/**
* Checks if an event has listeners registered
*
* @param Event $event
* @return boolean
*/
public function hasEventListeners(Event $event)
{
$listeners = $this->getListeners($event);
return count($listeners) > 0;
}
/**
* Finds all listeners defined as scripts in the package
*
* @param Event $event Event object
* @return array Listeners
*/
protected function getScriptListeners(Event $event)
{
$package = $this->composer->getPackage();
$scripts = $package->getScripts();
if (empty($scripts[$event->getName()])) {
return array();
}
if ($this->loader) {
$this->loader->unregister();
}
$generator = $this->composer->getAutoloadGenerator();
$packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
$packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
$map = $generator->parseAutoloads($packageMap, $package);
$this->loader = $generator->createLoader($map);
$this->loader->register();
return $scripts[$event->getName()];
}
/**
* Checks if string given references a class path and method
*
* @param string $callable
* @return boolean
*/
protected function isPhpScript($callable)
{
return false === strpos($callable, ' ') && false !== strpos($callable, '::');
}
}

@ -0,0 +1,48 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\EventDispatcher;
/**
* An EventSubscriber knows which events it is interested in.
*
* If an EventSubscriber is added to an EventDispatcher, the manager invokes
* {@link getSubscribedEvents} and registers the subscriber as a listener for all
* returned events.
*
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Bernhard Schussek <bschussek@gmail.com>
*/
interface EventSubscriberInterface
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents();
}

@ -15,11 +15,16 @@ namespace Composer;
use Composer\Config\JsonConfigSource;
use Composer\Json\JsonFile;
use Composer\IO\IOInterface;
use Composer\Repository\ComposerRepository;
use Composer\Package\Archiver;
use Composer\Repository\RepositoryManager;
use Composer\Repository\RepositoryInterface;
use Composer\Util\ProcessExecutor;
use Composer\Util\RemoteFilesystem;
use Composer\Util\Filesystem;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
use Composer\Package\Version\VersionParser;
/**
* Creates a configured instance of composer.
@ -27,21 +32,29 @@ use Symfony\Component\Console\Formatter\OutputFormatterStyle;
* @author Ryan Weaver <ryan@knplabs.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Igor Wiedler <igor@wiedler.ch>
* @author Nils Adermann <naderman@naderman.de>
*/
class Factory
{
/**
* @return Config
* @return string
* @throws \RuntimeException
*/
public static function createConfig()
protected static function getHomeDir()
{
// determine home and cache dirs
$home = getenv('COMPOSER_HOME');
$cacheDir = getenv('COMPOSER_CACHE_DIR');
if (!getenv('HOME')) {
throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
$userDir = rtrim(getenv('HOME'), '/');
$followXDG = false;
if (!$home) {
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!getenv('APPDATA')) {
throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
$home = getenv('APPDATA') . '/Composer';
} elseif (getenv('XDG_CONFIG_DIRS')) {
// XDG Base Directory Specifications
@ -55,13 +68,27 @@ class Factory
$home = $userDir . '/.composer';
}
}
return $home;
}
/**
* @param string $home
*
* @return string
*/
protected static function getCacheDir($home)
{
$cacheDir = getenv('COMPOSER_CACHE_DIR');
if (!$cacheDir) {
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if ($cacheDir = getenv('LOCALAPPDATA')) {
$cacheDir .= '/Composer';
} else {
$cacheDir = getenv('APPDATA') . '/Composer/cache';
$cacheDir = $home . '/cache';
}
$cacheDir = strtr($cacheDir, '\\', '/');
} elseif (getenv('XDG_CONFIG_DIRS')) {
$followXDG = true;
$xdgCache = getenv('XDG_CACHE_HOME');
@ -69,13 +96,24 @@ class Factory
$xdgCache = $userDir . '/.cache';
}
$cacheDir = $xdgCache . '/composer';
} else {
$cacheDir = $home . '/.cache';
}
}
return $cacheDir;
}
/**
* @param IOInterface|null $io
* @return Config
*/
public static function createConfig(IOInterface $io = null)
{
// determine home and cache dirs
$home = self::getHomeDir();
$cacheDir = self::getCacheDir($home);
// Protect directory against web access. Since HOME could be
// the www-data's user home and be web-accessible it is a
// potential security risk
@ -106,48 +144,32 @@ class Factory
// add dirs to the config
$config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
// load global config
$file = new JsonFile($home.'/config.json');
if ($file->exists()) {
if ($io && $io->isDebug()) {
$io->write('Loading config file ' . $file->getPath());
}
$config->merge($file->read());
}
$config->setConfigSource(new JsonConfigSource($file));
// move old cache dirs to the new locations
$legacyPaths = array(
'cache-repo-dir' => array('/cache' => '/http*', '/cache.svn' => '/*', '/cache.github' => '/*'),
'cache-vcs-dir' => array('/cache.git' => '/*', '/cache.hg' => '/*'),
'cache-files-dir' => array('/cache.files' => '/*'),
);
foreach ($legacyPaths as $key => $oldPaths) {
foreach ($oldPaths as $oldPath => $match) {
$dir = $config->get($key);
if ('/cache.github' === $oldPath) {
$dir .= '/github.com';
}
$oldPath = $config->get('home').$oldPath;
$oldPathMatch = $oldPath . $match;
if (is_dir($oldPath) && $dir !== $oldPath) {
if (!is_dir($dir)) {
if (!@mkdir($dir, 0777, true)) {
continue;
}
}
if (is_array($children = glob($oldPathMatch))) {
foreach ($children as $child) {
@rename($child, $dir.'/'.basename($child));
}
}
@unlink($oldPath);
}
// load global auth file
$file = new JsonFile($config->get('home').'/auth.json');
if ($file->exists()) {
if ($io && $io->isDebug()) {
$io->write('Loading config file ' . $file->getPath());
}
$config->merge(array('config' => $file->read()));
}
$config->setAuthConfigSource(new JsonConfigSource($file, true));
return $config;
}
public static function getComposerFile()
{
return getenv('COMPOSER') ?: 'composer.json';
return trim(getenv('COMPOSER')) ?: './composer.json';
}
public static function createAdditionalStyles()
@ -163,7 +185,7 @@ class Factory
$repos = array();
if (!$config) {
$config = static::createConfig();
$config = static::createConfig($io);
}
if (!$rm) {
if (!$io) {
@ -193,13 +215,15 @@ class Factory
/**
* Creates a Composer instance
*
* @param IOInterface $io IO instance
* @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
* read from the default filename
* @param IOInterface $io IO instance
* @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
* read from the default filename
* @param bool $disablePlugins Whether plugins should not be loaded
* @throws \InvalidArgumentException
* @throws \UnexpectedValueException
* @return Composer
*/
public function createComposer(IOInterface $io, $localConfig = null)
public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false)
{
// load Composer configuration
if (null === $localConfig) {
@ -211,7 +235,7 @@ class Factory
$file = new JsonFile($localConfig, new RemoteFilesystem($io));
if (!$file->exists()) {
if ($localConfig === 'composer.json') {
if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
$message = 'Composer could not find a composer.json file in '.getcwd();
} else {
$message = 'Composer could not find the config file: '.$localConfig;
@ -224,53 +248,79 @@ class Factory
$localConfig = $file->read();
}
// Configuration defaults
$config = static::createConfig();
// Load config and override with local config/auth config
$config = static::createConfig($io);
$config->merge($localConfig);
// reload oauth token from config if available
if ($tokens = $config->get('github-oauth')) {
foreach ($tokens as $domain => $token) {
if (!preg_match('{^[a-z0-9]+$}', $token)) {
throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"');
if (isset($composerFile)) {
if ($io && $io->isDebug()) {
$io->write('Loading config file ' . $composerFile);
}
$localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
if ($localAuthFile->exists()) {
if ($io && $io->isDebug()) {
$io->write('Loading config file ' . $localAuthFile->getPath());
}
$io->setAuthentication($domain, $token, 'x-oauth-basic');
$config->merge(array('config' => $localAuthFile->read()));
$config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
}
}
// load auth configs into the IO instance
$io->loadConfiguration($config);
$vendorDir = $config->get('vendor-dir');
$binDir = $config->get('bin-dir');
// setup process timeout
ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
// initialize composer
$composer = new Composer();
$composer->setConfig($config);
// initialize event dispatcher
$dispatcher = new EventDispatcher($composer, $io);
// initialize repository manager
$rm = $this->createRepositoryManager($io, $config);
$rm = $this->createRepositoryManager($io, $config, $dispatcher);
// load local repository
$this->addLocalRepository($rm, $vendorDir);
// load package
$loader = new Package\Loader\RootPackageLoader($rm, $config);
$parser = new VersionParser;
$loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, new ProcessExecutor($io));
$package = $loader->load($localConfig);
// initialize download manager
$dm = $this->createDownloadManager($io, $config);
// initialize installation manager
$im = $this->createInstallationManager();
// initialize composer
$composer = new Composer();
$composer->setConfig($config);
// Composer composition
$composer->setPackage($package);
$composer->setRepositoryManager($rm);
$composer->setDownloadManager($dm);
$composer->setInstallationManager($im);
// initialize download manager
$dm = $this->createDownloadManager($io, $config, $dispatcher);
$composer->setDownloadManager($dm);
$composer->setEventDispatcher($dispatcher);
// initialize autoload generator
$generator = new AutoloadGenerator($dispatcher, $io);
$composer->setAutoloadGenerator($generator);
// add installers to the manager
$this->createDefaultInstallers($im, $composer, $io);
$globalRepository = $this->createGlobalRepository($config, $vendorDir);
$pm = $this->createPluginManager($composer, $io, $globalRepository);
$composer->setPluginManager($pm);
if (!$disablePlugins) {
$pm->loadInstalledPlugins();
}
// purge packages if they have been deleted on the filesystem
$this->purgePackages($rm, $im);
@ -279,7 +329,7 @@ class Factory
$lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
? substr($composerFile, 0, -4).'lock'
: $composerFile . '.lock';
$locker = new Package\Locker(new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, $im, md5_file($composerFile));
$locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io, $config)), $rm, $im, md5_file($composerFile));
$composer->setLocker($locker);
}
@ -289,18 +339,21 @@ class Factory
/**
* @param IOInterface $io
* @param Config $config
* @param EventDispatcher $eventDispatcher
* @return Repository\RepositoryManager
*/
protected function createRepositoryManager(IOInterface $io, Config $config)
protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
{
$rm = new RepositoryManager($io, $config);
$rm = new RepositoryManager($io, $config, $eventDispatcher);
$rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
$rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
$rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
$rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
return $rm;
}
@ -312,33 +365,99 @@ class Factory
protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
{
$rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
$rm->setLocalDevRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed_dev.json')));
}
/**
* @param Config $config
* @param string $vendorDir
* @return Repository\InstalledFilesystemRepository|null
*/
protected function createGlobalRepository(Config $config, $vendorDir)
{
if ($config->get('home') == $vendorDir) {
return null;
}
$path = $config->get('home').'/vendor/composer/installed.json';
if (!file_exists($path)) {
return null;
}
return new Repository\InstalledFilesystemRepository(new JsonFile($path));
}
/**
* @param IO\IOInterface $io
* @param Config $config
* @param IO\IOInterface $io
* @param Config $config
* @param EventDispatcher $eventDispatcher
* @return Downloader\DownloadManager
*/
public function createDownloadManager(IOInterface $io, Config $config)
public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
{
$cache = null;
if ($config->get('cache-files-ttl') > 0) {
$cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
}
$dm = new Downloader\DownloadManager();
$dm = new Downloader\DownloadManager($io);
switch ($config->get('preferred-install')) {
case 'dist':
$dm->setPreferDist(true);
break;
case 'source':
$dm->setPreferSource(true);
break;
case 'auto':
default:
// noop
break;
}
$dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
$dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
$dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
$dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $cache));
$dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $cache));
$dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $cache));
$dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $cache));
$dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
$dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
$dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
$dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
$dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
$dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
$dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
return $dm;
}
/**
* @param Config $config The configuration
* @param Downloader\DownloadManager $dm Manager use to download sources
*
* @return Archiver\ArchiveManager
*/
public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
{
if (null === $dm) {
$io = new IO\NullIO();
$io->loadConfiguration($config);
$dm = $this->createDownloadManager($io, $config);
}
$am = new Archiver\ArchiveManager($dm);
$am->addArchiver(new Archiver\PharArchiver);
return $am;
}
/**
* @param Composer $composer
* @param IOInterface $io
* @param RepositoryInterface $globalRepository
* @return Plugin\PluginManager
*/
protected function createPluginManager(Composer $composer, IOInterface $io, RepositoryInterface $globalRepository = null)
{
return new Plugin\PluginManager($composer, $io, $globalRepository);
}
/**
* @return Installer\InstallationManager
*/
@ -356,7 +475,7 @@ class Factory
{
$im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
$im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
$im->addInstaller(new Installer\InstallerInstaller($io, $composer));
$im->addInstaller(new Installer\PluginInstaller($io, $composer));
$im->addInstaller(new Installer\MetapackageInstaller($io));
}
@ -366,26 +485,25 @@ class Factory
*/
protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
{
foreach ($rm->getLocalRepositories() as $repo) {
/* @var $repo Repository\WritableRepositoryInterface */
foreach ($repo->getPackages() as $package) {
if (!$im->isPackageInstalled($repo, $package)) {
$repo->removePackage($package);
}
$repo = $rm->getLocalRepository();
foreach ($repo->getPackages() as $package) {
if (!$im->isPackageInstalled($repo, $package)) {
$repo->removePackage($package);
}
}
}
/**
* @param IOInterface $io IO instance
* @param mixed $config either a configuration array or a filename to read from, if null it will read from
* the default filename
* @param IOInterface $io IO instance
* @param mixed $config either a configuration array or a filename to read from, if null it will read from
* the default filename
* @param bool $disablePlugins Whether plugins should not be loaded
* @return Composer
*/
public static function create(IOInterface $io, $config = null)
public static function create(IOInterface $io, $config = null, $disablePlugins = false)
{
$factory = new static();
return $factory->createComposer($io, $config);
return $factory->createComposer($io, $config, $disablePlugins);
}
}

@ -0,0 +1,79 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\IO;
use Composer\Config;
abstract class BaseIO implements IOInterface
{
protected $authentications = array();
/**
* {@inheritDoc}
*/
public function getAuthentications()
{
return $this->authentications;
}
/**
* {@inheritDoc}
*/
public function hasAuthentication($repositoryName)
{
return isset($this->authentications[$repositoryName]);
}
/**
* {@inheritDoc}
*/
public function getAuthentication($repositoryName)
{
if (isset($this->authentications[$repositoryName])) {
return $this->authentications[$repositoryName];
}
return array('username' => null, 'password' => null);
}
/**
* {@inheritDoc}
*/
public function setAuthentication($repositoryName, $username, $password = null)
{
$this->authentications[$repositoryName] = array('username' => $username, 'password' => $password);
}
/**
* {@inheritDoc}
*/
public function loadConfiguration(Config $config)
{
// reload oauth token from config if available
if ($tokens = $config->get('github-oauth')) {
foreach ($tokens as $domain => $token) {
if (!preg_match('{^[a-z0-9]+$}', $token)) {
throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"');
}
$this->setAuthentication($domain, $token, 'x-oauth-basic');
}
}
// reload http basic credentials from config if available
if ($creds = $config->get('http-basic')) {
foreach ($creds as $domain => $cred) {
$this->setAuthentication($domain, $cred['username'], $cred['password']);
}
}
}
}

@ -23,8 +23,9 @@ use Symfony\Component\Console\Helper\HelperSet;
class BufferIO extends ConsoleIO
{
/**
* @param string $input
* @param int $verbosity
* @param string $input
* @param int $verbosity
* @param OutputFormatterInterface $formatter
*/
public function __construct($input = '', $verbosity = null, OutputFormatterInterface $formatter = null)
{

@ -15,6 +15,7 @@ namespace Composer\IO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Process\ExecutableFinder;
/**
* The Input/Output helper.
@ -22,13 +23,13 @@ use Symfony\Component\Console\Helper\HelperSet;
* @author François Pluchino <francois.pluchino@opendisplay.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ConsoleIO implements IOInterface
class ConsoleIO extends BaseIO
{
protected $input;
protected $output;
protected $helperSet;
protected $authentications = array();
protected $lastMessage;
private $startTime;
/**
* Constructor.
@ -44,6 +45,11 @@ class ConsoleIO implements IOInterface
$this->helperSet = $helperSet;
}
public function enableDebugging($startTime)
{
$this->startTime = $startTime;
}
/**
* {@inheritDoc}
*/
@ -65,7 +71,23 @@ class ConsoleIO implements IOInterface
*/
public function isVerbose()
{
return $this->output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE;
return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE;
}
/**
* {@inheritDoc}
*/
public function isVeryVerbose()
{
return $this->output->getVerbosity() >= 3; // OutputInterface::VERSOBITY_VERY_VERBOSE
}
/**
* {@inheritDoc}
*/
public function isDebug()
{
return $this->output->getVerbosity() >= 4; // OutputInterface::VERBOSITY_DEBUG
}
/**
@ -73,6 +95,15 @@ class ConsoleIO implements IOInterface
*/
public function write($messages, $newline = true)
{
if (null !== $this->startTime) {
$messages = (array) $messages;
$messages[0] = sprintf(
'[%.1fMB/%.2fs] %s',
memory_get_usage() / 1024 / 1024,
microtime(true) - $this->startTime,
$messages[0]
);
}
$this->output->write($messages, $newline);
$this->lastMessage = join($newline ? "\n" : '', (array) $messages);
}
@ -141,12 +172,33 @@ class ConsoleIO implements IOInterface
{
// handle windows
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$finder = new ExecutableFinder();
// use bash if it's present
if ($finder->find('bash') && $finder->find('stty')) {
$this->write($question, false);
$value = rtrim(shell_exec('bash -c "stty -echo; read -n0 discard; read -r mypassword; stty echo; echo $mypassword"'));
$this->write('');
return $value;
}
// fallback to hiddeninput executable
$exe = __DIR__.'\\hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
copy($exe, $tmpExe);
// use stream_copy_to_stream instead of copy
// to work around https://bugs.php.net/bug.php?id=64634
$source = fopen(__DIR__.'\\hiddeninput.exe', 'r');
$target = fopen($tmpExe, 'w+');
stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
unset($source, $target);
$exe = $tmpExe;
}
@ -185,40 +237,4 @@ class ConsoleIO implements IOInterface
// not able to hide the answer, proceed with normal question handling
return $this->ask($question);
}
/**
* {@inheritDoc}
*/
public function getAuthentications()
{
return $this->authentications;
}
/**
* {@inheritDoc}
*/
public function hasAuthentication($repositoryName)
{
$auths = $this->getAuthentications();
return isset($auths[$repositoryName]);
}
/**
* {@inheritDoc}
*/
public function getAuthentication($repositoryName)
{
$auths = $this->getAuthentications();
return isset($auths[$repositoryName]) ? $auths[$repositoryName] : array('username' => null, 'password' => null);
}
/**
* {@inheritDoc}
*/
public function setAuthentication($repositoryName, $username, $password = null)
{
$this->authentications[$repositoryName] = array('username' => $username, 'password' => $password);
}
}

@ -12,6 +12,8 @@
namespace Composer\IO;
use Composer\Config;
/**
* The Input/Output helper interface.
*
@ -27,12 +29,26 @@ interface IOInterface
public function isInteractive();
/**
* Is this input verbose?
* Is this output verbose?
*
* @return bool
*/
public function isVerbose();
/**
* Is the output very verbose?
*
* @return bool
*/
public function isVeryVerbose();
/**
* Is the output in debug verbosity?
*
* @return bool
*/
public function isDebug();
/**
* Is this output decorated?
*
@ -55,7 +71,7 @@ interface IOInterface
* @param bool $newline Whether to add a newline or not
* @param integer $size The size of line
*/
public function overwrite($messages, $newline = true, $size = 80);
public function overwrite($messages, $newline = true, $size = null);
/**
* Asks a question to the user.
@ -90,7 +106,7 @@ interface IOInterface
*
* @param string|array $question The question to ask
* @param callback $validator A PHP callback
* @param integer $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param bool|integer $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param string $default The default answer if none is given by the user
*
* @return mixed
@ -141,4 +157,11 @@ interface IOInterface
* @param string $password The password
*/
public function setAuthentication($repositoryName, $username, $password = null);
/**
* Loads authentications from a config instance
*
* @param Config $config
*/
public function loadConfiguration(Config $config);
}

@ -17,7 +17,7 @@ namespace Composer\IO;
*
* @author Christophe Coevoet <stof@notk.org>
*/
class NullIO implements IOInterface
class NullIO extends BaseIO
{
/**
* {@inheritDoc}
@ -38,7 +38,7 @@ class NullIO implements IOInterface
/**
* {@inheritDoc}
*/
public function isDecorated()
public function isVeryVerbose()
{
return false;
}
@ -46,37 +46,37 @@ class NullIO implements IOInterface
/**
* {@inheritDoc}
*/
public function write($messages, $newline = true)
public function isDebug()
{
return false;
}
/**
* {@inheritDoc}
*/
public function overwrite($messages, $newline = true, $size = 80)
public function isDecorated()
{
return false;
}
/**
* {@inheritDoc}
*/
public function ask($question, $default = null)
public function write($messages, $newline = true)
{
return $default;
}
/**
* {@inheritDoc}
*/
public function askConfirmation($question, $default = true)
public function overwrite($messages, $newline = true, $size = 80)
{
return $default;
}
/**
* {@inheritDoc}
*/
public function askAndValidate($question, $validator, $attempts = false, $default = null)
public function ask($question, $default = null)
{
return $default;
}
@ -84,39 +84,24 @@ class NullIO implements IOInterface
/**
* {@inheritDoc}
*/
public function askAndHideAnswer($question)
{
return null;
}
/**
* {@inheritDoc}
*/
public function getAuthentications()
{
return array();
}
/**
* {@inheritDoc}
*/
public function hasAuthentication($repositoryName)
public function askConfirmation($question, $default = true)
{
return false;
return $default;
}
/**
* {@inheritDoc}
*/
public function getAuthentication($repositoryName)
public function askAndValidate($question, $validator, $attempts = false, $default = null)
{
return array('username' => null, 'password' => null);
return $default;
}
/**
* {@inheritDoc}
*/
public function setAuthentication($repositoryName, $username, $password = null)
public function askAndHideAnswer($question)
{
return null;
}
}

@ -15,15 +15,21 @@ namespace Composer;
use Composer\Autoload\AutoloadGenerator;
use Composer\DependencyResolver\DefaultPolicy;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\DependencyResolver\Operation\OperationInterface;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\Request;
use Composer\DependencyResolver\Rule;
use Composer\DependencyResolver\Solver;
use Composer\DependencyResolver\SolverProblemsException;
use Composer\Downloader\DownloadManager;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Installer\InstallationManager;
use Composer\Config;
use Composer\Installer\InstallerEvents;
use Composer\Installer\NoopInstaller;
use Composer\IO\IOInterface;
use Composer\Json\JsonFile;
use Composer\Package\AliasPackage;
use Composer\Package\Link;
use Composer\Package\LinkConstraint\VersionConstraint;
@ -32,16 +38,17 @@ use Composer\Package\PackageInterface;
use Composer\Package\RootPackageInterface;
use Composer\Repository\CompositeRepository;
use Composer\Repository\InstalledArrayRepository;
use Composer\Repository\InstalledFilesystemRepository;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\RepositoryManager;
use Composer\Script\EventDispatcher;
use Composer\Script\ScriptEvents;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Beau Simensen <beau@dflydev.com>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class Installer
{
@ -98,7 +105,13 @@ class Installer
protected $verbose = false;
protected $update = false;
protected $runScripts = true;
/**
* Array of package names/globs flagged for update
*
* @var array|null
*/
protected $updateWhitelist = null;
protected $whitelistDependencies = false;
/**
* @var array
@ -138,6 +151,10 @@ class Installer
/**
* Run installation (or update)
*
* @return int 0 on success or a positive error code on failure
*
* @throws \Exception
*/
public function run()
{
@ -148,25 +165,44 @@ class Installer
$this->mockLocalRepositories($this->repositoryManager);
}
if ($this->preferSource) {
$this->downloadManager->setPreferSource(true);
// TODO remove this BC feature at some point
// purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
$devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
if ($devRepo->getPackages()) {
$this->io->write('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
foreach ($devRepo->getPackages() as $package) {
if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
$this->installationManager->uninstall($devRepo, new UninstallOperation($package));
}
}
unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
}
if ($this->preferDist) {
$this->downloadManager->setPreferDist(true);
unset($devRepo, $package);
// end BC
if ($this->runScripts) {
// dispatch pre event
$eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
$this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
}
// create installed repo, this contains all local packages + platform packages (php & extensions)
$this->downloadManager->setPreferSource($this->preferSource);
$this->downloadManager->setPreferDist($this->preferDist);
// clone root package to have one in the installed repo that does not require anything
// we don't want it to be uninstallable, but its requirements should not conflict
// with the lock file for example
$installedRootPackage = clone $this->package;
$installedRootPackage->setRequires(array());
$installedRootPackage->setDevRequires(array());
// create installed repo, this contains all local packages + platform packages (php & extensions)
$localRepo = $this->repositoryManager->getLocalRepository();
$platformRepo = new PlatformRepository();
$repos = array_merge(
$this->repositoryManager->getLocalRepositories(),
array(
new InstalledArrayRepository(array($installedRootPackage)),
$platformRepo,
)
$repos = array(
$localRepo,
new InstalledArrayRepository(array($installedRootPackage)),
$platformRepo,
);
$installedRepo = new CompositeRepository($repos);
if ($this->additionalInstalledRepository) {
@ -176,21 +212,11 @@ class Installer
$aliases = $this->getRootAliases();
$this->aliasPlatformPackages($platformRepo, $aliases);
if ($this->runScripts) {
// dispatch pre event
$eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
$this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
}
try {
$this->suggestedPackages = array();
if (!$this->doInstall($this->repositoryManager->getLocalRepository(), $installedRepo, $aliases)) {
return false;
}
if ($this->devMode) {
if (!$this->doInstall($this->repositoryManager->getLocalDevRepository(), $installedRepo, $aliases, true)) {
return false;
}
$res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
if ($res !== 0) {
return $res;
}
} catch (\Exception $e) {
$this->installationManager->notifyInstalls();
@ -199,14 +225,16 @@ class Installer
}
$this->installationManager->notifyInstalls();
// output suggestions
foreach ($this->suggestedPackages as $suggestion) {
$target = $suggestion['target'];
if ($installedRepo->filterPackages(function (PackageInterface $package) use ($target) {
if (in_array($target, $package->getNames())) {
return false;
// output suggestions if we're in dev mode
if ($this->devMode) {
foreach ($this->suggestedPackages as $suggestion) {
$target = $suggestion['target'];
foreach ($installedRepo->getPackages() as $package) {
if (in_array($target, $package->getNames())) {
continue 2;
}
}
})) {
$this->io->write($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
}
}
@ -214,12 +242,48 @@ class Installer
if (!$this->dryRun) {
// write lock
if ($this->update || !$this->locker->isLocked()) {
$localRepo->reload();
// if this is not run in dev mode and the root has dev requires, the lock must
// contain null to prevent dev installs from a non-dev lock
$devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
// split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
if ($this->devMode && $this->package->getDevRequires()) {
$policy = $this->createPolicy();
$pool = $this->createPool(true);
$pool->addRepository($installedRepo, $aliases);
// creating requirements request
$request = $this->createRequest($pool, $this->package, $platformRepo);
$request->updateAll();
foreach ($this->package->getRequires() as $link) {
$request->install($link->getTarget(), $link->getConstraint());
}
$this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request);
$solver = new Solver($policy, $pool, $installedRepo);
$ops = $solver->solve($request);
$this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request, $ops);
foreach ($ops as $op) {
if ($op->getJobType() === 'uninstall') {
$devPackages[] = $op->getPackage();
}
}
}
$platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
$platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
$updatedLock = $this->locker->setLockData(
$this->repositoryManager->getLocalRepository()->getPackages(),
$this->devMode ? $this->repositoryManager->getLocalDevRepository()->getPackages() : null,
array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
$devPackages,
$platformReqs,
$platformDevReqs,
$aliases,
$this->package->getMinimumStability(),
$this->package->getStabilityFlags()
$this->package->getStabilityFlags(),
$this->package->getPreferStable()
);
if ($updatedLock) {
$this->io->write('<info>Writing lock file</info>');
@ -227,41 +291,55 @@ class Installer
}
// write autoloader
$this->io->write('<info>Generating autoload files</info>');
$localRepos = new CompositeRepository($this->repositoryManager->getLocalRepositories());
$this->autoloadGenerator->dump($this->config, $localRepos, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
if ($this->optimizeAutoloader) {
$this->io->write('<info>Generating optimized autoload files</info>');
} else {
$this->io->write('<info>Generating autoload files</info>');
}
$this->autoloadGenerator->setDevMode($this->devMode);
$this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
if ($this->runScripts) {
// dispatch post event
$eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
$this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
}
$vendorDir = $this->config->get('vendor-dir');
if (is_dir($vendorDir)) {
touch($vendorDir);
}
}
return true;
return 0;
}
protected function doInstall($localRepo, $installedRepo, $aliases, $devMode = false)
protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
{
$minimumStability = $this->package->getMinimumStability();
$stabilityFlags = $this->package->getStabilityFlags();
// init vars
$lockedRepository = null;
$repositories = null;
// initialize locker to create aliased packages
$installFromLock = false;
if (!$this->update && $this->locker->isLocked($devMode)) {
if (!$this->update && $this->locker->isLocked()) {
$installFromLock = true;
$lockedRepository = $this->locker->getLockedRepository($devMode);
$minimumStability = $this->locker->getMinimumStability();
$stabilityFlags = $this->locker->getStabilityFlags();
try {
$lockedRepository = $this->locker->getLockedRepository($withDevReqs);
} catch (\RuntimeException $e) {
// if there are dev requires, then we really can not install
if ($this->package->getDevRequires()) {
throw $e;
}
// no require-dev in composer.json and the lock file was created with no dev info, so skip them
$lockedRepository = $this->locker->getLockedRepository();
}
}
$this->whitelistUpdateDependencies(
$localRepo,
$devMode,
$withDevReqs,
$this->package->getRequires(),
$this->package->getDevRequires()
);
@ -269,14 +347,14 @@ class Installer
$this->io->write('<info>Loading composer repositories with package information</info>');
// creating repository pool
$policy = new DefaultPolicy();
$pool = new Pool($minimumStability, $stabilityFlags);
$policy = $this->createPolicy();
$pool = $this->createPool($withDevReqs);
$pool->addRepository($installedRepo, $aliases);
if ($installFromLock) {
$pool->addRepository($lockedRepository, $aliases);
}
if (!$installFromLock || !$this->locker->isCompleteFormat($devMode)) {
if (!$installFromLock) {
$repositories = $this->repositoryManager->getRepositories();
foreach ($repositories as $repository) {
$pool->addRepository($repository, $aliases);
@ -284,31 +362,78 @@ class Installer
}
// creating requirements request
$request = new Request($pool);
$request = $this->createRequest($pool, $this->package, $platformRepo);
$constraint = new VersionConstraint('=', $this->package->getVersion());
$constraint->setPrettyString($this->package->getPrettyVersion());
$request->install($this->package->getName(), $constraint);
if (!$installFromLock) {
// remove unstable packages from the localRepo if they don't match the current stability settings
$removedUnstablePackages = array();
foreach ($localRepo->getPackages() as $package) {
if (
!$pool->isPackageAcceptable($package->getNames(), $package->getStability())
&& $this->installationManager->isPackageInstalled($localRepo, $package)
) {
$removedUnstablePackages[$package->getName()] = true;
$request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
}
}
}
if ($this->update) {
$this->io->write('<info>Updating '.($devMode ? 'dev ': '').'dependencies</info>');
$this->io->write('<info>Updating dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
$request->updateAll();
$links = $devMode ? $this->package->getDevRequires() : $this->package->getRequires();
if ($withDevReqs) {
$links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
} else {
$links = $this->package->getRequires();
}
foreach ($links as $link) {
$request->install($link->getTarget(), $link->getConstraint());
}
} elseif ($installFromLock) {
$this->io->write('<info>Installing '.($devMode ? 'dev ': '').'dependencies from lock file</info>');
if (!$this->locker->isCompleteFormat($devMode)) {
$this->io->write('<warning>Warning: Your lock file is in a deprecated format. It will most likely take a *long* time for composer to install dependencies, and may cause dependency solving issues.</warning>');
// if the updateWhitelist is enabled, packages not in it are also fixed
// to the version specified in the lock, or their currently installed version
if ($this->updateWhitelist) {
if ($this->locker->isLocked()) {
try {
$currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
} catch (\RuntimeException $e) {
// fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
$currentPackages = $this->locker->getLockedRepository()->getPackages();
}
} else {
$currentPackages = $installedRepo->getPackages();
}
// collect packages to fixate from root requirements as well as installed packages
$candidates = array();
foreach ($links as $link) {
$candidates[$link->getTarget()] = true;
}
foreach ($localRepo->getPackages() as $package) {
$candidates[$package->getName()] = true;
}
// fix them to the version in lock (or currently installed) if they are not updateable
foreach ($candidates as $candidate => $dummy) {
foreach ($currentPackages as $curPackage) {
if ($curPackage->getName() === $candidate) {
if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
$constraint = new VersionConstraint('=', $curPackage->getVersion());
$request->install($curPackage->getName(), $constraint);
}
break;
}
}
}
}
} elseif ($installFromLock) {
$this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').' from lock file</info>');
if (!$this->locker->isFresh() && !$devMode) {
$this->io->write('<warning>Warning: The lock file is not up to date with the latest changes in composer.json, you may be getting outdated dependencies, run update to update them.</warning>');
if (!$this->locker->isFresh()) {
$this->io->write('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.</warning>');
}
foreach ($lockedRepository->getPackages() as $package) {
@ -320,66 +445,21 @@ class Installer
$constraint->setPrettyString($package->getPrettyVersion());
$request->install($package->getName(), $constraint);
}
} else {
$this->io->write('<info>Installing '.($devMode ? 'dev ': '').'dependencies</info>');
$links = $devMode ? $this->package->getDevRequires() : $this->package->getRequires();
foreach ($links as $link) {
foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
$request->install($link->getTarget(), $link->getConstraint());
}
}
// fix the version of all installed packages (+ platform) that are not
// in the current local repo to prevent rogue updates (e.g. non-dev
// updating when in dev)
foreach ($installedRepo->getPackages() as $package) {
if ($package->getRepository() === $localRepo) {
continue;
}
$constraint = new VersionConstraint('=', $package->getVersion());
$constraint->setPrettyString($package->getPrettyVersion());
if (!($package->getRepository() instanceof PlatformRepository)
|| !($provided = $this->package->getProvides())
|| !isset($provided[$package->getName()])
|| !$provided[$package->getName()]->getConstraint()->matches($constraint)
) {
$request->install($package->getName(), $constraint);
}
}
} else {
$this->io->write('<info>Installing dependencies'.($withDevReqs?' (including require-dev)':'').'</info>');
// if the updateWhitelist is enabled, packages not in it are also fixed
// to the version specified in the lock, or their currently installed version
if ($this->update && $this->updateWhitelist) {
if ($this->locker->isLocked($devMode)) {
$currentPackages = $this->locker->getLockedRepository($devMode)->getPackages();
if ($withDevReqs) {
$links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
} else {
$currentPackages = $installedRepo->getPackages();
$links = $this->package->getRequires();
}
// collect links from composer as well as installed packages
$candidates = array();
foreach ($links as $link) {
$candidates[$link->getTarget()] = true;
}
foreach ($localRepo->getPackages() as $package) {
$candidates[$package->getName()] = true;
}
// fix them to the version in lock (or currently installed) if they are not updateable
foreach ($candidates as $candidate => $dummy) {
foreach ($currentPackages as $curPackage) {
if ($curPackage->getName() === $candidate) {
if ($this->isUpdateable($curPackage)) {
break;
}
$constraint = new VersionConstraint('=', $curPackage->getVersion());
$request->install($curPackage->getName(), $constraint);
}
}
$request->install($link->getTarget(), $link->getConstraint());
}
}
@ -387,27 +467,16 @@ class Installer
$this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
// solve dependencies
$this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request);
$solver = new Solver($policy, $pool, $installedRepo);
try {
$operations = $solver->solve($request);
$this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $policy, $pool, $installedRepo, $request, $operations);
} catch (SolverProblemsException $e) {
$this->io->write('<error>Your requirements could not be resolved to an installable set of packages.</error>');
$this->io->write($e->getMessage());
return false;
}
if ($devMode) {
// remove bogus operations that the solver creates for stuff that was force-updated in the non-dev pass
// TODO this should not be necessary ideally, but it seems to work around the problem quite well
foreach ($operations as $index => $op) {
if ('update' === $op->getJobType() && $op->getInitialPackage()->getUniqueName() === $op->getTargetPackage()->getUniqueName()
&& $op->getInitialPackage()->getSourceReference() === $op->getTargetPackage()->getSourceReference()
&& $op->getInitialPackage()->getDistReference() === $op->getTargetPackage()->getDistReference()
) {
unset($operations[$index]);
}
}
return max(1, $e->getCode());
}
// force dev packages to be updated if we update or install from a (potentially new) lock
@ -418,6 +487,9 @@ class Installer
$this->io->write('Nothing to install or update');
}
$operations = $this->movePluginsToFront($operations);
$operations = $this->moveUninstallsToFront($operations);
foreach ($operations as $operation) {
// collect suggestions
if ('install' === $operation->getJobType()) {
@ -430,11 +502,6 @@ class Installer
}
}
$event = 'Composer\Script\ScriptEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
if (defined($event) && $this->runScripts) {
$this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
}
// not installing from lock, force dev packages' references if they're in root package refs
if (!$installFromLock) {
$package = null;
@ -450,15 +517,53 @@ class Installer
$package->setDistReference($references[$package->getName()]);
}
}
if ('update' === $operation->getJobType()
&& $operation->getTargetPackage()->isDev()
&& $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion()
&& $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference()
) {
if ($this->io->isDebug()) {
$this->io->write(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version');
$this->io->write('');
}
continue;
}
}
// output alias operations in verbose mode, or all ops in dry run
if ($this->dryRun || ($this->verbose && false !== strpos($operation->getJobType(), 'Alias'))) {
$event = 'Composer\Script\ScriptEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
if (defined($event) && $this->runScripts) {
$this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
}
// output non-alias ops in dry run, output alias ops in debug verbosity
if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
$this->io->write(' - ' . $operation);
$this->io->write('');
} elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
$this->io->write(' - ' . $operation);
$this->io->write('');
}
$this->installationManager->execute($localRepo, $operation);
// output reasons why the operation was ran, only for install/update operations
if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
$reason = $operation->getReason();
if ($reason instanceof Rule) {
switch ($reason->getReason()) {
case Rule::RULE_JOB_INSTALL:
$this->io->write(' REASON: Required by root: '.$reason->getPrettyString());
$this->io->write('');
break;
case Rule::RULE_PACKAGE_REQUIRES:
$this->io->write(' REASON: '.$reason->getPrettyString());
$this->io->write('');
break;
}
}
}
$event = 'Composer\Script\ScriptEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
if (defined($event) && $this->runScripts) {
$this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $operation);
@ -469,7 +574,141 @@ class Installer
}
}
return true;
return 0;
}
/**
* Workaround: if your packages depend on plugins, we must be sure
* that those are installed / updated first; else it would lead to packages
* being installed multiple times in different folders, when running Composer
* twice.
*
* While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
* it at least fixes the symptoms and makes usage of composer possible (again)
* in such scenarios.
*
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function movePluginsToFront(array $operations)
{
$installerOps = array();
foreach ($operations as $idx => $op) {
if ($op instanceof InstallOperation) {
$package = $op->getPackage();
} elseif ($op instanceof UpdateOperation) {
$package = $op->getTargetPackage();
} else {
continue;
}
if ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer') {
// ignore requirements to platform or composer-plugin-api
$requires = array_keys($package->getRequires());
foreach ($requires as $index => $req) {
if ($req === 'composer-plugin-api' || preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
unset($requires[$index]);
}
}
// if there are no other requirements, move the plugin to the top of the op list
if (!count($requires)) {
$installerOps[] = $op;
unset($operations[$idx]);
}
}
}
return array_merge($installerOps, $operations);
}
/**
* Removals of packages should be executed before installations in
* case two packages resolve to the same path (due to custom installers)
*
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function moveUninstallsToFront(array $operations)
{
$uninstOps = array();
foreach ($operations as $idx => $op) {
if ($op instanceof UninstallOperation) {
$uninstOps[] = $op;
unset($operations[$idx]);
}
}
return array_merge($uninstOps, $operations);
}
private function createPool($withDevReqs)
{
$minimumStability = $this->package->getMinimumStability();
$stabilityFlags = $this->package->getStabilityFlags();
if (!$this->update && $this->locker->isLocked()) {
$minimumStability = $this->locker->getMinimumStability();
$stabilityFlags = $this->locker->getStabilityFlags();
}
$requires = $this->package->getRequires();
if ($withDevReqs) {
$requires = array_merge($requires, $this->package->getDevRequires());
}
$rootConstraints = array();
foreach ($requires as $req => $constraint) {
$rootConstraints[$req] = $constraint->getConstraint();
}
return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
}
private function createPolicy()
{
$preferStable = null;
if (!$this->update && $this->locker->isLocked()) {
$preferStable = $this->locker->getPreferStable();
}
// old lock file without prefer stable will return null
// so in this case we use the composer.json info
if (null === $preferStable) {
$preferStable = $this->package->getPreferStable();
}
return new DefaultPolicy($preferStable);
}
private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
{
$request = new Request($pool);
$constraint = new VersionConstraint('=', $rootPackage->getVersion());
$constraint->setPrettyString($rootPackage->getPrettyVersion());
$request->install($rootPackage->getName(), $constraint);
$fixedPackages = $platformRepo->getPackages();
if ($this->additionalInstalledRepository) {
$additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
$fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
}
// fix the version of all platform packages + additionally installed packages
// to prevent the solver trying to remove or update those
$provided = $rootPackage->getProvides();
foreach ($fixedPackages as $package) {
$constraint = new VersionConstraint('=', $package->getVersion());
$constraint->setPrettyString($package->getPrettyVersion());
// skip platform packages that are provided by the root package
if ($package->getRepository() !== $platformRepo
|| !isset($provided[$package->getName()])
|| !$provided[$package->getName()]->getConstraint()->matches($constraint)
) {
$request->install($package->getName(), $constraint);
}
}
return $request;
}
private function processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, $task, array $operations = null)
@ -481,16 +720,12 @@ class Installer
$operations = array();
}
foreach ($localRepo->getPackages() as $package) {
foreach ($localRepo->getCanonicalPackages() as $package) {
// skip non-dev packages
if (!$package->isDev()) {
continue;
}
if ($package instanceof AliasPackage) {
continue;
}
// skip packages that will be updated/uninstalled
foreach ($operations as $operation) {
if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
@ -608,8 +843,6 @@ class Installer
foreach ($versions as $version => $alias) {
$packages = $platformRepo->findPackages($package, $version);
foreach ($packages as $package) {
$package->setAlias($alias['alias_normalized']);
$package->setPrettyAlias($alias['alias']);
$aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
$aliasPackage->setRootPackageAlias(true);
$platformRepo->addPackage($aliasPackage);
@ -625,9 +858,8 @@ class Installer
}
foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
$cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
if (preg_match("{^".$cleanedWhiteListedPattern."$}i", $package->getName())) {
$patternRegexp = $this->packageNameToRegexp($whiteListedPattern);
if (preg_match($patternRegexp, $package->getName())) {
return true;
}
}
@ -635,6 +867,31 @@ class Installer
return false;
}
/**
* Build a regexp from a package name, expanding * globs as required
*
* @param string $whiteListedPattern
* @return string
*/
private function packageNameToRegexp($whiteListedPattern)
{
$cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
return "{^" . $cleanedWhiteListedPattern . "$}i";
}
private function extractPlatformRequirements($links)
{
$platformReqs = array();
foreach ($links as $link) {
if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
$platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
}
}
return $platformReqs;
}
/**
* Adds all dependencies of the update whitelist to the whitelist, too.
*
@ -653,6 +910,11 @@ class Installer
return;
}
$requiredPackageNames = array();
foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
$requiredPackageNames[] = $require->getTarget();
}
if ($devMode) {
$rootRequires = array_merge($rootRequires, $rootDevRequires);
}
@ -667,10 +929,31 @@ class Installer
$seen = array();
$rootRequiredPackageNames = array_keys($rootRequires);
foreach ($this->updateWhitelist as $packageName => $void) {
$packageQueue = new \SplQueue;
foreach ($pool->whatProvides($packageName) as $depPackage) {
$depPackages = $pool->whatProvides($packageName);
$nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true);
// check if the name is a glob pattern that did not match directly
if (!$nameMatchesRequiredPackage) {
$whitelistPatternRegexp = $this->packageNameToRegexp($packageName);
foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
$nameMatchesRequiredPackage = true;
break;
}
}
}
if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock'))) {
$this->io->write('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
}
foreach ($depPackages as $depPackage) {
$packageQueue->enqueue($depPackage);
}
@ -683,11 +966,12 @@ class Installer
$seen[$package->getId()] = true;
$this->updateWhitelist[$package->getName()] = true;
$requires = $package->getRequires();
if ($devMode) {
$requires = array_merge($requires, $package->getDevRequires());
if (!$this->whitelistDependencies) {
continue;
}
$requires = $package->getRequires();
foreach ($requires as $require) {
$requirePackages = $pool->whatProvides($require->getTarget());
@ -711,27 +995,17 @@ class Installer
*/
private function mockLocalRepositories(RepositoryManager $rm)
{
$packages = array_map(function ($p) {
return clone $p;
}, $rm->getLocalRepository()->getPackages());
foreach ($packages as $key => $package) {
if ($package instanceof AliasPackage) {
unset($packages[$key]);
}
$packages = array();
foreach ($rm->getLocalRepository()->getPackages() as $package) {
$packages[(string) $package] = clone $package;
}
$rm->setLocalRepository(
new InstalledArrayRepository($packages)
);
$packages = array_map(function ($p) {
return clone $p;
}, $rm->getLocalDevRepository()->getPackages());
foreach ($packages as $key => $package) {
if ($package instanceof AliasPackage) {
unset($packages[$key]);
$alias = (string) $package->getAliasOf();
$packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
}
}
$rm->setLocalDevRepository(
$rm->setLocalRepository(
new InstalledArrayRepository($packages)
);
}
@ -739,17 +1013,12 @@ class Installer
/**
* Create Installer
*
* @param IOInterface $io
* @param Composer $composer
* @param EventDispatcher $eventDispatcher
* @param AutoloadGenerator $autoloadGenerator
* @param IOInterface $io
* @param Composer $composer
* @return Installer
*/
public static function create(IOInterface $io, Composer $composer, EventDispatcher $eventDispatcher = null, AutoloadGenerator $autoloadGenerator = null)
public static function create(IOInterface $io, Composer $composer)
{
$eventDispatcher = $eventDispatcher ?: new EventDispatcher($composer, $io);
$autoloadGenerator = $autoloadGenerator ?: new AutoloadGenerator;
return new static(
$io,
$composer->getConfig(),
@ -758,8 +1027,8 @@ class Installer
$composer->getRepositoryManager(),
$composer->getLocker(),
$composer->getInstallationManager(),
$eventDispatcher,
$autoloadGenerator
$composer->getEventDispatcher(),
$composer->getAutoloadGenerator()
);
}
@ -812,7 +1081,7 @@ class Installer
/**
* Whether or not generated autoloader are optimized
*
* @param bool $optimizeAutoloader
* @param bool $optimizeAutoloader
* @return Installer
*/
public function setOptimizeAutoloader($optimizeAutoloader = false)
@ -902,7 +1171,20 @@ class Installer
}
/**
* Disables custom installers.
* Should dependencies of whitelisted packages be updated recursively?
*
* @param boolean $updateDependencies
* @return Installer
*/
public function setWhitelistDependencies($updateDependencies = true)
{
$this->whitelistDependencies = (boolean) $updateDependencies;
return $this;
}
/**
* Disables plugins.
*
* Call this if you want to ensure that third-party code never gets
* executed. The default is to automatically install, and execute
@ -910,9 +1192,9 @@ class Installer
*
* @return Installer
*/
public function disableCustomInstallers()
public function disablePlugins()
{
$this->installationManager->disableCustomInstallers();
$this->installationManager->disablePlugins();
return $this;
}

@ -29,6 +29,7 @@ use Composer\Util\StreamContextFactory;
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Nils Adermann <naderman@naderman.de>
*/
class InstallationManager
{
@ -66,16 +67,16 @@ class InstallationManager
}
/**
* Disables custom installers.
* Disables plugins.
*
* We prevent any custom installers from being instantiated by simply
* We prevent any plugins from being instantiated by simply
* deactivating the installer for them. This ensure that no third-party
* code is ever executed.
*/
public function disableCustomInstallers()
public function disablePlugins()
{
foreach ($this->installers as $i => $installer) {
if (!$installer instanceof InstallerInstaller) {
if (!$installer instanceof PluginInstaller) {
continue;
}
@ -90,7 +91,7 @@ class InstallationManager
*
* @return InstallerInterface
*
* @throws InvalidArgumentException if installer for provided type is not registered
* @throws \InvalidArgumentException if installer for provided type is not registered
*/
public function getInstaller($type)
{
@ -251,7 +252,7 @@ class InstallationManager
)
);
$context = StreamContextFactory::getContext($opts);
$context = StreamContextFactory::getContext($url, $opts);
@file_get_contents($url, false, $context);
}
@ -275,7 +276,7 @@ class InstallationManager
)
);
$context = StreamContextFactory::getContext($opts);
$context = StreamContextFactory::getContext($repoUrl, $opts);
@file_get_contents($repoUrl, false, $context);
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save