Friday, May 4, 2012

Git: generate patches, after or before commit happens.

Occasionally, if not often, I need to generate patches to be applied to another git copy. This can happen either before I commit or after. It turns out, the ways to do it for the two scenarios are different.

If the change set is already committed, then below command line can generate the patch:



git format-patch -1

This will create a patch in the current folder with file name like 0001-comments-in-the-commit.patch.

-1 in the command line means generating patch for last one commit. If you want to patch in more commits, specify the number here. If you don't like the default file name and want to specify your own output file name, then you can direct output to stdout and the redirect stdout to a file, like below:


  git format-patch -1 --stdout > your_file_name.patch

So how do you do it when you don't want to commit the changes? A simple way is to generate the diff output and redirect it to a file. The problems is, like most people, I'm not satisfied with git's diff output and I use a graphical tool, BeyandCompare, to do the diff viewing. If I execute

git diff > pathfile.txt


the BC is invoked and there is nothing redirected to the patch file, unsurprisingly. So how to force the diff command to skip the GUI tool? As in most of the cases, a command line switch comes to help: --no-ext-diff. Below command line will happily output the result to console and skip BC:

 git diff --no-ext-diff Applying patches generated with git diff is simple:
patch -p1 < patch-file.txt

No comments:

Post a Comment