A development team is working on a network automation script using Git. A junior developer cloned the `main` repository and started working on a new feature. Before pushing their changes, they realize that the `main` branch has been updated with several critical bug fixes. They want to incorporate these latest changes from `main` into their local feature branch without creating an additional merge commit on their feature branch, and then continue working on their feature. Which Git command sequence would achieve this?
- Agit checkout main && git merge feature-branch
- Bgit pull origin main && git merge main
- Cgit checkout feature-branch && git rebase main
- Dgit fetch origin && git reset --hard origin/main
Show answer & explanationAnswer & explanation
Correct answer: C. git checkout feature-branch && git rebase main
The `git rebase main` command, executed while on `feature-branch`, will replay the commits from `feature-branch` on top of the latest `main` branch. This effectively moves the base of the `feature-branch` to the new tip of `main`, incorporating the bug fixes linearly without creating a merge commit on `feature-branch` itself. This maintains a clean and linear history for the feature branch.
Why the other options are wrong
- A. This would merge the `feature-branch` into `main`, which is the opposite of the desired action (incorporating `main` into `feature-branch`) and would create a merge commit on `main`.
- B. `git pull origin main` would fetch and merge `main` into the current branch, creating a merge commit if there are divergent histories.
- D. `git reset --hard origin/main` would discard all local changes on the current branch and reset it to match `origin/main`, which is destructive and not for integrating changes.
Git Rebase Workflow
The Git rebase command is used to integrate changes from one branch onto another by moving or combining a sequence of commits to a new base commit. A common workflow is to rebase a feature branch onto an updated `main` (or `develop`) branch to incorporate the latest changes while maintaining a linear project history.
- Always rebase your feature branch ONTO the target branch (e.g., `git rebase main`).
- Rewrites the commit history of the feature branch.
- Avoid rebasing branches that have already been pushed to a shared remote repository.
- Helps maintain a clean, linear, and easy-to-read project history.
Memory trick: Rebase: Re-aligns Base for a Smooth, Straight path.