Tip 10: diff and patch

From Vlsiwiki
Jump to: navigation, search

Suppose you have two scenarios:

1) Someone patched a bug and you want to apply their changes to your code (which may already be modified).

2) You fix a bug in someones code but you don't have access to commit to their repository.

The solution for both of these is to use diff and patch.

diff

The unix "diff" command shows the incremental differences in a text file or in a subdirectory of files. This is handy because you can only transfer what changed (and a little more for context) rather than redistribute everything. To get the differences between your code and a directory of the original code, you can simply do:

diff -rupN original/ new/ > original.patch

The -r specifies recursive, the -u specifies to output context lines, and the -p tells it to give specific C function names for context too. -N says to treat absent files as empty.

patch

Once you have this difference file, you can apply these differences using the "patch" program. To update the original in our example, simply do a:

patch < original.patch

Sometimes there will be issues with path names in the patch. For example, if your original directory was in /user/bob/research and the new one was not, you can chop off these paths using the -p option to patch. For example,

patch -p4 < original.patch

would use the directories under research. More in the man page.

SVN and CVS

Subversion comes with a handy way to generate a diff with another SVN revision. At any time, if you type:

svn diff

it will show the diff between your copy and the current one in the repository. You can simply send this to someone else as a patch file using:

svn diff  > original.patch

You can do a similar patch in CVS with:

cvs diff -upN > original.patch

Note, that you could use this to "undo" local changes and apply them back again later by using the "reverse patch" option:

patch -p0 -R < original.patch

then later:

patch -p0 < original.patch

git

First, stage all of your commits. This should be something like:

git commit -a -m "Log message describing what you did"

You can undo this later by doing:

git reset HEAD^

In git, you can generate a patch with:

git format-patch origin/master --stdout > fix_code.patch

Then you can check the statistics about the patch with:

git apply --stat fix_code.patch

To finally apply the patch, you do:

git apply --check fix_code.patch

If you don't have any errors, you can commit the code and use the patch!