64

Let's say that I am 7 commits ahead of the origin/master repo. I would like to create a patch that includes in the patch specific files that were changed, not all the files. Or equivalent exclude specific files from the patch that were changed. How can I achieve that?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
vasilakisfil
  • 2,279
  • 4
  • 24
  • 31

2 Answers2

99

You can create a patch file by restricting the output of git diff by listing paths at the end of the command (after a -- to avoid any potential clashes between path names and branch names).

For example, you could do the following:

git diff origin/master HEAD -- app/models/region.rb doc/ > changes.patch

Above commands generate a patch that shows only the differences for a particular file: region.rb and a particular directory : doc when compared to origin/master

Then you can apply the patch using

patch -p1 < changes.patch

The -p1 tells patch to strip the a/ and b/ in the paths in the patch

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Mark Longair
  • 446,582
  • 72
  • 411
  • 327
  • 8
    If you're like me and you got here but didn't know how to use the `patch` command (I don't know why you would, but I didn't, so...), you can apply the patch using `patch -p1 < changes.patch` (the `-p1` tells patch to strip the `a/` and `b/` in the paths in the patch) – Daisy Sophia Hollman Feb 05 '19 at 16:57
  • @DaisySophiaHollman thanks to your very usefull comment, I have include it in the answer – Mauricio Gracia Gutierrez Jan 22 '21 at 19:38
37

You can include files in the patches with:

git format-patch <rev> <files...>

Example

git format-patch HEAD^^^ Makefile

Will give you three files 0001-[commit] ... 0003-[commit] only containing the Makefile.

lars
  • 2,015
  • 1
  • 14
  • 8
  • 3
    Does this really work? format-patch documentation doesn't say that you can give specific files as parameters. – Vladimir Gritsenko Feb 25 '14 at 14:43
  • 3
    It worked for me, even though I haven't found any reference of that feature in the docs. – Willington Vega Sep 03 '14 at 15:52
  • I also haven't been able to find documentation of this feature. Was hoping to better understand the options for use in a script! – Charlie Gorichanaz Apr 20 '17 at 05:13
  • 2
    In the synopsis of the git-format-patch command, it does show `[]` as an argument. So I think most options for git-diff work for git-format-patch. – Sam Sieber Aug 10 '17 at 22:12
  • 1
    What does the `HEAD^^^` syntax mean? I am not familiar with that. – jocull Jun 25 '18 at 19:28
  • 1
    https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection The carets mean "ancestor of" -- so this would point at the revision that is the parent of the parent of the parent of HEAD. – jocull Jun 25 '18 at 19:36