Thursday, 27 December 2018

GIT: Using the Git cherry-pick command

38.1. Applying a single commit with cherry-pick

The git cherry-pick command allows you to select the patch which was introduced with an individual commit and apply this patch on another branch. The patch is captured as a new commit on the other branch.
This way you can select individual changes from one branch and transfer them to another branch.
The new commit does not point back to its original commit so do not use 
cherry-pick blindly since you may end up with several copies of the same
 change. Most often cherry-pick is either used locally (to emulate an interactive 
rebase) or to port individual bug fixes done on a development branch into
 maintenance branches.

38.2. Example: Using cherry-pick

In the following example you create a new branch and commit two changes.
# create new branch
git checkout -b picktest

# create some data and commit
touch pickfile.txt
git add pickfile.txt
git commit -m "adds new file"

# create second commit
echo "changes to file" > pickfile.txt
git commit -a -m "changes in file"
You can check the commit history, for example, with the git log --oneline command.
# see change commit history

git log --oneline

# results in the following output

2fc2e55 changes in file
ebb46b7 adds new file
[MORE COMMITS]
330b6a3 initial commit
The following command selects the first commit based on the commit ID and applies its changes to the master branch. This creates a new commit on the master branch.
git checkout master
git cherry-pick ebb46b7
The cherry-pick command can be used to change the order of commits. git cherry-pick also accepts commit ranges for example in the following command.
git checkout master
# pick the last two commits
git cherry-pick picktest~1..picktest~2
If things go wrong or you change your mind, you can always reset to the previous state using the following command.
git cherry-pick --abort

0 comments:

Post a Comment