Git export a commit and apply to another branch

Spread the love

Git difference between cherry pick and patch.

There are some cases where you have committed a code on one branch and later you have apply the same changes to different branch, but not other commits before or after that are not on other branch.

For that you have to export the patch using format-patch command in cmd or may be your GUI git tool provide that. Then you need to apply that patch to other branch. But if your patch have some conflicts then it will show errors, so you may need to remove some of the patch code from patch file that you have exported.

Command to export a commit as patch:

git format-patch -1 <SHA>

Then you need to save that to ‘.patch’ file and check and apply to another branch using following commands:

git apply --check file.patch

If there are no errors in check then apply using the following command:

git am < file.patch

Error example of check command:

error: patch failed: .env.production:4
error: .env.production: patch does not apply

Example of a patch file

From 365fcccd775947d19f3db17296f1c4efadf90272 Mon Sep 17 00:00:00 2001
From: Faltutech Author <[email protected]>
Date: Tue, 23 Aug 2022 14:41:10 +0000
Subject: [PATCH] Android | Update version code.

---
 android/app/build.gradle | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/android/app/build.gradle b/android/app/build.gradle
index a7c274e..dde0673 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -148,7 +148,7 @@ android {
         applicationId "com.faltutech.app"
         minSdkVersion rootProject.ext.minSdkVersion
         targetSdkVersion rootProject.ext.targetSdkVersion
-        versionCode 3
+        versionCode 4
         versionName "1.0.0"
     }
     splits {
-- 
2.30.1

To solve this you need to remove the error file patches. In the above given error .env.production file have an issue, so the patch could not applied. So, remove the diff of that file from ‘.patch’ file.

The cherry pick thing that you may have read creates a new branch, which also contains all the code prior to that commit. But patch thing only exports that commit.

Cheers and Peace out!!!