Search code examples
phpcomposer-phppackagist

Ignore tests folder when send to packagist


I have a project with the following structure:

- src
----/ /* Relevant files */
- tests
----/ /* Irrelevant files */
- composer.json
- phpunit.xml

The project is sent to packagist on every commit already. But, it is sending the test files.

I'd like to ignore tests folder, so composer wont download unecessary files when someone calls composer require my/package

Here is whats the content of my composer.json looks like:

{
    "name": "my/package",
    "description": "...",
    "type": "library",
    "license": "MIT",
    "require": {
        "php": ">=7"
    },
    "require-dev": {
        "phpunit/phpunit": ">=5.4"
    },
    "autoload": {
        "psr-4": {
            "MyProject\\": "./src"
        }
    }
}

Solution

  • Ignore tests folder when send to packagist

    Let's first clear up some confusion.

    When you enable Packagist for your repository, Packagist will load the composer.json to get metadata about your project and fetch the version informations from the tags/branches.

    But you are not sending your PHP code or any tests to Packagist.


    I'd like to ignore tests folder, so composer wont download unecessary files when someone calls composer require my/package

    This question pops up quite often. I'm referencing a detailed answer, which i've written some time ago, which explains a lot of the background: https://stackoverflow.com/a/32476500/1163786

    Usage of a .gitattributes file with export-ignore directive

    • Technically, you could add a .gitattributes file to your repository, which declares a export-ignore rule for the test folder.
    • This means that any git export will no longer have the tests folder, including the Github zip file.

    Ok, exclude done..

    But, when someone composer require's your project, it will now depend on the --prefer-dist setting to install the package from the dist (zip). (You would get the tests with --prefer-source).


    • If it is a small library, stop to worry. Be happy.. :)

    • If it is a bigger application, then a better solution is to package your application properly, instead of relying on the git exported zip distribution. Most developers don't use a build.xml or any build script anymore, but that's the correct way to do it in my opinion.

      That means once you are ready to tag a new release. You trigger your build script, which fetches all the dependencies, runs the tests once more and when everything is ok, drop all the tests and packages the files for deployment.


    Small hint: don't forget to add a autoload-dev section for your tests to composer.json.