Cherry-picking Commits
Cherry-picking allows you to apply specific commits from one branch to another. This can be useful when porting a bug fix or a feature without merging an entire branch.
Example:
# Assume you are on the master branch and want to cherry-pick a commit from feature-branch
git checkout master
git cherry-pick <commit-hash>
Interactive Rebase
Interactive rebase is a powerful feature that lets you rewrite commit history. Before merging, you can reorder, squash, or edit commits to clean up your project history.
Example:
# Start an interactive rebase for the last 5 commits
git rebase -i HEAD~5
This command opens an editor where you can reorder, squash, or edit commits.
Bisecting to Find Bugs
Git bisect helps you find the commit that introduced a bug by performing a binary search through your commit history.
Example:
# Start bisecting
git bisect start
# Mark the current commit as bad
git bisect bad
# Mark a known good commit
git bisect good <commit-hash>
Git will checkout commits between the good and bad points, helping you to identify the exact commit that introduced the bug.
Working with Submodules
Submodules allow you to include and manage repositories within other repositories, making it easier to work with dependencies.
Example:
# Add a submodule
git submodule add <https://github.com/example/repo.git> path/to/submodule
# Initialize and update submodules
git submodule update --init --recursive
Sparse Checkout
Sparse checkout allows you to check out only a subset of files in a repository, which can be useful when working with large repositories.
Example:
# Enable sparse checkout
git config core.sparseCheckout true
# Specify files or directories to check out
echo "path/to/dir/" >> .git/info/sparse-checkout
# Update the working directory
git read-tree -mu HEAD
By mastering these advanced Git techniques, you can significantly enhance your workflow, making it more efficient and tailored to your project's needs. These techniques are invaluable for tackling complex tasks and maintaining a clean project history.