What is Cherry-Picking?
Cherry-pick is a method to select specific commits from one branch and apply them to another. For instance, when two developers are working independently on branches A and B, and an important bug fix is committed to branch A, branch B can apply this bug fix through cherry-picking.
Unlike rebasing branch B onto branch A, cherry-picking aims to apply individual commits without merging or reorganizing the entire branch.
Cherry-Picking Existing Commits
Using VS Code
Cherry-picking is relatively simple in Git. Right-click on the desired commit in the current branch and select Cherry Pick...
.
Using Command Line
Check the current branch status and note the commit IDs:
If the current branch’s latest commit is 52a310a7
, and you only want to cherry-pick 2f01e37
, enter the command git cherry-pick 2f01e37
:
|
|
Similarly, to cherry-pick a range of commits, remember the start and end commit IDs, and enter:
|
|
For example, to cherry-pick commits between 5d59 and b03a (inclusive):
|
|
After executing the above, the final branch status is:
If conflicts arise, you must resolve them manually or abort the cherry-pick process using git cherry-pick --abort
.
Cherry-Picking a Specific File
In Git, the cherry-pick command can only apply entire commits, not specific file changes. However, if you want to apply changes from a specific file in a commit or branch
, you can use the checkout command to achieve this.
|
|
As shown in the image below, the current branch CP is at commit ID 52a310a7
. We can use the checkout command to retrieve the file.txt from the commit ID d616aa83
(WITH_ANOTHER_FIX_ALL):
|
|
The file will be in the staging area, and you can commit it using VS Code:
The final branch status is shown in the image below, where the commit ID 223cf241
with the message File.txt_fixed
includes both the “Fix file.txt” and “WITH_ANOTHER_FIX_ALL” changes. This is a common technique in simplifying and merging commits, allowing for more effective management and integration of changes within the codebase by consolidating changes from different commits into one file.
Conclusion
Using the cherry-pick command, we can copy commits from one branch to another. However, frequent cherry-picking can complicate the branch structure, making it harder to maintain.
Using rebase or merge operations can simplify branch complexity. Particularly, in cases with multiple file changes, merges are more likely to encounter conflicts, which can be challenging for newcomers to resolve.