How do I apply a patch with Composer workflow? I need to include a patch in my project. I have included cweagans/composer-patches in composer.json and added the following lines in the extra section (example is from when trying to enable distribution in the Configuration installer).

"patches": {
        "drupal/config_installer": {
            "Enable distribution for Configuration installer profile": "patches/config_installer_enable_distribution.patch"
        }
    }


Afterwards, I run composer update.

- Installing drupal/config_installer (1.5.0): Loading from cache
- Applying patches for drupal/config_installer
    patches/config_installer_enable_distribution.patch (Enable distribution for Configuration installer profile)


So I get no errors and the patch seems to have been applied successfully. Also the file PATCHES.txt is successfully created in the package's root directory. Still, the patch hasn't been applied.

I've tried this method with other packages which come from Github and it works, however every time I try this with a module or a profile from drupal.org then the patch isn't being applied.

Am I missing anything?

When I ran composer update -vvv, I saw the command which is running for the patch is indeed with Git.

git -C 'web/profiles/contrib/config_installer' apply '-p1' '/path/to/project/patches/config_installer_enable_distribu‌​‌​tion.patch'


I've tried running the command by itself; again, it didn't change the file.
The issue is that composer is applying patches using git apply which is not working for packages that are not installed from source.

Therefore the solution is to install the packages from source. This way the package will fetch the package along with its repository (when available) thus enabling it to be patched.

So...

How to install/update a package from source

For new packages:

Use

composer require vendor/package --prefer-source


For existing packages

If your package is already installed then you need to delete it so that you can re-fetch it with composer install (there is no composer reinstall command). Do so and then use

composer install vendor/package --prefer-source


Set it as the default behavior

You can also set it up as the default behavior for the project in the config section of composer.json:

"config": {
      "preferred-install": "source"
    },


Update:

Set it as the default behavior for a specific package

In case you don't want to set your entire project to install from source, you can do so for a specific package only. To do so you need to specify the VCS Branch in the Version constrain of the package.

"require": {
        "vendor/package": "dev-branch#branch-hash"
}