Applying Drupal Patches in Composer

I recently had a Drupal core patch that I needed to use on a site I’m building. This can be done manually using the patch command, but when managing a Drupal project with Composer, any manual patches could get wiped out on the next run of the composer update or composer install commands. In order to make sure patches stick, they need to be added to Composer, like a requirement.

For future reference: I was able to manually apply my patch by downloading the patch file to the directory containing the Drupal core directory (in my case, the web directory, if you follow a similar setup to this one), then running the patch -p1 < path/file.patch command. For some reason I was never able to get the git apply command to work for me.

Adding a Patch to Composer

In order to apply patches with Composer, the cweagans/composer-patches plugin needs to be added to the Composer requirements. From the project root directory containing the composer.json file, run this command:

composer require cweagans/composer-patches

After that, the require section of the composer.json file should look something like this:

{
  "require": {
    "cweagans/composer-patches": "~1.0",
    "drupal/core": "~8.5.0"
  }
}

Now the patch can be added to the extra section of the composer.json file:

"extra": {
  "patches": {
    "drupal/core": {
      "Views integration for datetime range fields": "https://www.drupal.org/files/issues/2786577-270_0.patch"
    }
  }
}

Once the composer update command is run, the patch should be applied to the project.

Example

Here is a full example composer.json file:

{
  "name": "natedillon/project",
  "type": "project",
  "description": "My Drupal Website",
  "homepage": "https://example.com",
  "authors": [
    {
      "name": "D. Nathan Dillon",
      "role": "Developer",
      "homepage": "https://natedillon.com"
    }
  ],
  "repositories": [
    {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    }
  ],
  "require": {
    "composer/installers": "^1.2",
    "drupal-composer/drupal-scaffold": "^2.2",
    "cweagans/composer-patches": "^1.6",
    "drupal/console": "~1.0",
    "drupal/core": "~8.5.0",
    "drush/drush": "~8.0",
    "drupal/pathauto": "^1.0"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "extra": {
    "installer-paths": {
      "web/core": ["type:drupal-core"],
      "web/libraries/{$name}": ["type:drupal-library"],
      "web/modules/contrib/{$name}": ["type:drupal-module"],
      "web/modules/custom/{$name}": ["type:drupal-custom-module"],
      "web/profiles/contrib/{$name}": ["type:drupal-profile"],
      "web/themes/contrib/{$name}": ["type:drupal-theme"],
      "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
    },
    "patches": {
      "drupal/core": {
        "Views integration for datetime range fields": "https://www.drupal.org/files/issues/2786577-270_0.patch"
      }
    }
  }
}

Resources