git am: Patch format detection failed. git apply also fails

2.7k Views Asked by At

I'm trying to learn git patching, so I set up a test repo and made a few commits.

I then created a patch: git format-patch -1 HEAD --stdout > changes.patch

Next, I checked out a new branch and tried to use changes.patch: git am .\changes.patch. It gives me the error Patch format detection failed.

I searched here, and found this related question.

So I tried git apply .\changes.patch. It gives me error: unrecognized input.

The patch file seems fine to my untrained eye:

From 1c054c05bc528afbd929a1744fcacf9d70069246 Mon Sep 17 00:00:00 2001
From: MyUsername <[email protected]>
Date: Sat, 4 May 2019 22:43:32 -0400
Subject: [PATCH] Commit 4

---
test.txt | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/test.txt b/test.txt
index 58ef11d..763fe4e 100644
--- a/test.txt
+++ b/test.txt
@@ -1,3 +1,4 @@
 Initial commit
 Commit 2
-Commit 3
\ No newline at end of file
+Commit 3
+Commit 4
\ No newline at end of file
-- 
2.21.0.windows.1

I thought it might be that the patch is in the same directory as the repo, so I moved it to another directory. The results are the same.

I also noticed that many people had a < in the command, so I tried it: git am < ..\changes.patch. Apparently that's not valid syntax.

This is using 64 bit git on Windows with PowerShell.

Any ideas?

2

There are 2 best solutions below

7
ElpieKay On BEST ANSWER

Try cat .\changes.patch | git am.

But I have no idea why git am .\changes.patch can't work.

Update:

changes.patch is in USC-2 Little Endian by default. After changing it to UTF-8, git am .\changes.patch works.

4
Manuel Schmidt On

Do you want to create a patch from HEAD? Then you can simply do as follows:

To save the patch:

git show HEAD > /some/location/patch.txt

To apply the patch:

git apply /some/location/patch.txt

If you want to create a patch from a bunch of commits you can do:

git diff OLDEST_COMMIT..NEWEST_COMMIT > /some/location/patch.txt

This way you can, for instance, create a patch containing the changes from a feature branch:

git diff origin/master...origin/new_feature > /some/location/feature.patch

Notice the three dots, they mean you want the changes contained in origin/new_feature with respect to the common ancestor of the two branches.