Yet another web developer blog

Quick way to create an own patch for composer package of Drupal module and other projects

Very often we need to quickly change something in source files of composer package (for example some Drupal module), and generate a patch with those changes.

This can be done via those steps, using drupal/search_api_solr composer package as example :

  1. Reinstall version of module with vcs (git) sources:
    composer reinstall drupal/search_api_solr --prefer-source
    In older versions of composer the `--reinstall` command is not available, so we must replace that command to something like this:
    composer install drupal/search_api_solr:^4.2 --prefer-source
  2. Make changes in module source files and save files.
  3. Create the patch file:
    cd web/modules/contrib/search_api_solr
    git diff > ../../../../patches/search_api_solr-better_logging.patch
    
  4. Ensure that "cweagans/composer-patches" package is installed and enabled, and test the patch:
    composer require cweagans/composer-patches
    composer config --merge --json extra.enable-patching true
    composer config --merge --json extra.patches '{"drupal/search_api_solr": {"Better logging local patch": "./patches/search_api_solr-better_logging.patch"}}'
    composer install

If you already make changes to files, before reinstalling the package from git

There are tree ways:

  1. Copy your modified files (or all files of the package) to other folder, reinstall module with git repo, and copy them back, and continue from step 3 of first instruction.
  2. Revert back your changes, initialize new fresh git repo with current files via:
    git init && git add . && git commit -m init
    Copy back your changed files, and continue from step 3 of first instruction.
  3. Download the module to separate folder (it can be even without git), and generate patch via diff command:
    cd web/modules/contrib/search_api_solr
    mkdir web/modules/contrib/search_api_solr
    git diff > ../../../../patches/search_api_solr-better_logging.patch
    git diff --no-index . ../search_api_solr-orig > ../../../../patches/search_api_solr-better_logging.patch
    # you probably will need to remove all changes matched to .git folder in generated patch and other changes by package scripts
    rm -rf ../search_api_solr-orig