git create patch with diff

I tried doing

git diff 13.1_dev sale_edit > patch.diff

Then I tried doing git apply patch.diff in another branch, but I got patch does not apply. How do I create patch files from diffs that I can use with git apply?

Errors received:

$ git apply --ignore-space-change --ignore-whitespace diff.diff 
diff.diff:9: trailing whitespace.

diff.diff:10: trailing whitespace.
    function set_change_sale_date() 
diff.diff:12: space before tab in indent.
      $this->sale_lib->set_change_sale_date($this->input->post('change_sale_date'));
diff.diff:14: trailing whitespace.

diff.diff:15: trailing whitespace.
    function set_change_sale_date_enable() 
warning: application/controllers/sales.php has type 100755, expected 100644
error: patch failed: application/controllers/sales.php:520
error: application/controllers/sales.php: patch does not apply
warning: application/language/english/sales_lang.php has type 100755, expected 100644
error: patch failed: application/language/english/sales_lang.php:134
error: application/language/english/sales_lang.php: patch does not apply
warning: application/libraries/Sale_lib.php has type 100755, expected 100644
error: patch failed: application/models/sale.php:170
error: application/models/sale.php: patch does not apply
warning: application/views/sales/register.php has type 100755, expected 100644
error: patch failed: application/views/sales/register.php:361
error: application/views/sales/register.php: patch does not apply

I'm trying this on Mac


Try a:

git apply --ignore-space-change --ignore-whitespace patch.diff

As mentioned in "git: patch does not apply", this can be caused by:

  • the line endings differing between the local file system and the remote repo.
    User core.eol in .gitattributes file is a good approach (see "git force file encoding on commit")
  • the execution bit ('x').
    That can lead you to set git config core.filemode false, followed by a git reset --hard HEAD (make sure you don't have uncommitted changes, or they would be lost).

You can apply the patch as a 3-way merge:

git diff 13.1_dev sale_edit > patch.diff
git apply -3 patch.diff

It should bring up the conflict so that you can resolve manually. Or you could go with a one-liner, piping the patch to git-apply directly:

git diff 13.1_dev sale_edit | git apply -3

To reverse the patch:

git diff 13.1_dev sale_edit | git apply -3 -R

(note: this is same as the commands above, without the two-stage process of creating the patch file)

git help apply

-3, --3way           
When the patch does not apply cleanly, fall back on 3-way merge if 
the patch records the identity of blobs it is supposed to apply to, 
and we have those blobs available locally, possibly leaving 
the conflict markers in the files in the working tree for the user 
to resolve...