Making a Drupal patch with Git

Thu, 01/26/2012 - 17:55

 

This page documents a high-level overview of the current best practice recommendations for contributing change requests, in the form of a patch file, to projects (e.g., modules, themes, Drupal core, etc) hosted on Drupal.org using Git. For a more advanced workflow with Git, please refer to the Advanced patch contributor guide.

Note 1: If you're unfamiliar with patching Drupal, please read the Getting Involved section on Patches.

Note 2: If you choose to create patches with a tool other than Git, be sure to produce a -p1 patch; the old -p0 format was phased out in 2011

General patch guidelines

Keeping things organized

To help reviewers understand the scope of changes, separate each change type into its own patch. For example, bug fixes, performance enhancements, code style fixes, and whitespace fixes all should be in different patches. Each separate change type (and patch) should be associated with a different issue in the queue on Drupal.org.

Line endings and directory separators

Note for Windows users: Use Unix line endings (LF) and directory separators (/). Many text editors can convert line endings, or you can pipe diff output through dos2unix.

The basic approach

This basic patch workflow is appropriate for many situations, but if you're doing more than a quick fix, adding or deleting files, or collaborating with others, see the advanced patch contributor guide.

Creating a patch

Be sure you have checked out the branch you wish to patch with the following command.

git branch

Ensure it is up-to-date with the following:

git pull origin [branchname]

Make your changes. Then if, for example, the issue appears on Drupal.org at http://drupal.org/node/707484, using issue-number 707484:

git diff > [project_name]-[short-description]-[issue-number]-[comment-number].patch

[project_name] refer's to the project's name as it appears in the URL, i.e. http://drupal.org/project/[project_name], or from the git remote repository location, i.e. http://git.drupal.org/project/[project_name].git

If you added new files with your patch, then:

git add [path.to.new.file]
git diff --staged > [project_name]-[short-description]-[issue-number]-[comment-number].patch

Applying a patch

Download the patch to the root of your working directory. Apply the patch with the following command. The -v flag makes the output verbose so you can see the patch apply successfully.

git apply -v [patch-name.patch]

To avoid accidentally including the patch file in future commits, remove it:

rm  [patch-name.patch]

When you're done: Reverting uncommited changes

Revert changes to a specific file:

git checkout [filename]

Revert changes to the whole working tree:

git reset --hard
Tags: