Cherry-Picking Commits in Git

Tutorial 2 of 5

1. Introduction

In this tutorial, we will learn how to cherry-pick commits in Git, a powerful tool that allows developers to selectively apply changes from one branch to another. This can be particularly useful when you want to apply some but not all changes, that have been made in a different branch.

By the end of this tutorial, you will:
- Understand what cherry-pick is and why it can be useful.
- Be able to use cherry-pick to apply changes from one branch to another.
- Learn how to revert commits when necessary.

Prerequisites:
You should have Git installed and have a basic understanding of how to commit changes.

2. Step-by-Step Guide

Understanding cherry-pick

Cherry-pick is a git command that allows you to apply changes from specific commits. This is in contrast to merging or rebasing, where all changes from one branch are applied to another.

Using cherry-pick

To use cherry-pick, you first need the commit hash of the commit you want to apply. This can be found by using git log.

  1. First, check out the branch where you want to apply the commit.
    git checkout <branch-name>
  2. Then, use the cherry-pick command with the commit hash:
    git cherry-pick <commit-hash>

3. Code Examples

Example 1: Basic cherry-pick

  1. Check out the branch where you want to apply the commit.
    git checkout master
  2. Use git log to find the commit hash.
    git log
    This will show you a list of all commits, with the most recent at the top. Each commit will have a hash next to it. Copy the hash of the commit you want to cherry-pick.

  3. Use git cherry-pick with the commit hash.
    git cherry-pick 9fceb02
    This will apply the changes from commit 9fceb02 to the master branch.

Example 2: Reverting a cherry-pick

If you make a mistake or change your mind, you can always undo a cherry-pick with the --abort option:
git cherry-pick --abort
This will stop the current cherry-pick process and return you to the state before you started the cherry-pick.

4. Summary

In this tutorial, we've covered how to use Git's cherry-pick feature to selectively apply changes from one branch to another, and how to revert commits when necessary.

From here, you can further your understanding by learning about other powerful features of Git, such as rebase and merge.

5. Practice Exercises

To solidify your understanding, try these exercises on your own.

Exercise 1: Cherry-pick a commit from one branch to another in a new project.

Exercise 2: Create a situation where cherry-picking would be useful, then use it to solve the problem.

Exercise 3: Cherry-pick multiple commits at once.

Note: Remember to use git log to view your commit history and git cherry-pick --abort if you need to undo a cherry-pick.