tremby
tremby

Reputation: 10069

Composer -- can a package get its own version

I'm distributing a PHP package with Composer. Composer versions packages via their git tags.

I'd like my package to send its version number in the user agent string used when it makes HTTP requests.

Is it possible for my package, once installed as a dependency of another package, to get its own currently installed version number, presuming that this version number is not hard coded anywhere in the source code?

When the package in question is the root package, I can get the version number at install/update time, via a post-package-install/post-package-update script. An event is passed to that from which I can get the currently installed version:

public static function write(\Composer\Script\CommandEvent $event)
{
    $composer = $event->getComposer();
    $localRepository = $composer->getRepositoryManager()->getLocalRepository();
    $package = $composer->getPackage($localRepository, 'my/package-name', null);

    file_put_contents(__DIR__ . '/../version', $package->getVersion());
}

However, for security reasons, scripts of dependencies aren't run when installing/updating a parent package, and so this won't fly.

One possible line would be to run composer show -i my/package-name and parse out the version number, but this is not very portable. (Where is the PHP executable? Where is the composer.phar file? etc)

Another might be to have Composer itself as a dependency, and use some of its own logic as in the code example above. But it is a lot of bloat to include Composer itself as a dependency.

I saw in Composer's own source code that it specifies its own version as '@package_version@', but as far as I can tell this is only for Composer itself, and is replaced with its version number when Composer compiles itself into a phar file.

I could parse the version number out of the composer.lock file in the root package. This seems messy, but I think this is what I'll do for now.

Are there any other solutions? I get the feeling there's something very simple I'm missing.

Upvotes: 2

Views: 735

Answers (1)

mcuelenaere
mcuelenaere

Reputation: 2099

You could do something like https://github.com/mcuelenaere/composer-revision-plugin: this generates a PHP class containing the git revision of all composer dependencies at build-time.

Upvotes: 1

Related Questions