Skip to content

Instantly share code, notes, and snippets.

@dkorpar
Created March 19, 2018 21:24
Show Gist options
  • Save dkorpar/2c973bbb60c85bca341f5edd6344bb3a to your computer and use it in GitHub Desktop.
Save dkorpar/2c973bbb60c85bca341f5edd6344bb3a to your computer and use it in GitHub Desktop.
Creating and appying Git patches

Creating and appying Git patches

Creating patch files in the examples below are primarely meant for usage in cweagans/composer-patches, although can be used with plain Git. Instructions of including generated patches are explained in the repo itself.

Another package with a similar (if not the same) functionality is available at jamescowie/composer-patcher, but not tested though.

git format-patch

Creates new files with all changes from the current (feature branch) against another (source) branch. The idea behind this is to have a new branch, made of and ahead of a branch that diff will be run against. Patch will include only commits that are ahead of a source branch.

Place yourself in a feature branch and run a command below against a source branch (e.g. master):

$ git format-patch <branch>

It results in creating a new patch file for each commit:

  • 0001-commit1.patch
  • 0002-commit2.patch
  • 0003-commit3.patch

Packing a diff of all commits against the source branch into a single file:

$ git format-patch <branch> --stdout > patchname.patch

Creating a diff of only one specific commit:

$ git format-patch -1 <commit>

Using relative paths to exclude changes outside the directory and show pathnames relative to it with this option:

$ git format-patch <branch> --relative=<path>

git apply & git am

Applying patches is automated with the composer-patches package, although they can be applied manually when needed.

Checking changes inside the patch. It does not apply the patch, but only show stats of what it will do:

$ git apply --stat patchname.patch

Checking the patch before applying. No errors means the patch can be applied cleanly:

$ git apply --check patchname.patch

Applying the patch with a singoff parameter that provides useful info about how the commit ended up in the code:

$ git am --signoff < patchname.patch

Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment