7

I'm writing a package for Packagist and I'm facing a problem with Composer. I need to copy a file from my package to the project root after install, but nothing is happening after the package installation.

After reading Composer documentation, I found that I should put a script inside the event post-install-cmd, inside the script section into composer.json file.

So, I added this to my package composer.json file

    "scripts": {
        "post-install-cmd": [
            "php -r \"copy('vendor/myvendor/mypackage/myfile', 'myfile');\""
        ]
    }

To install the package I'm doing

$ composer require myvendor/mypackage --dev

After the package installation everything seems fine, but the file is not being copied and no error is shown.

Dharman
  • 30,962
  • 25
  • 85
  • 135
felipe_bool
  • 93
  • 1
  • 7

2 Answers2

10

See https://getcomposer.org/doc/articles/scripts.md for the documentation of scripts. The most relevant part is:

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.

So, you cannot define any scripts in your module. There is a bug report about that, but the maintainer of composer is not a friend of executing the scripts of dependencies

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
  • 1
    Ok, but, what is the purpose of this `"post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ],` in the laravel composer.json file? https://github.com/laravel/laravel/blob/master/composer.json – felipe_bool Feb 14 '18 at 11:49
  • 2
    Have a look at the linked documentation ;) It's run when using `create-project` – Nico Haase Feb 14 '18 at 12:23
-2

You can install this composer plugin to achieve your purpose: https://packagist.org/packages/markocupic/composer-file-copier-plugin

If configured, the plugin listens to Composers post-install-cmd and post-update-cmd events and copies files or entire folders from your package to the filesystem.

Configuration is made under the extra key inside the composer.json of your package.