Introduction
Protected branches, such as develop
and main
, are critical for maintaining the integrity of your repository. These branches cannot be reset or force-pushed due to restrictions, making it essential to create new commits to undo changes.
This post explores a simple method to revert changes, using the git restore command, especially when dealing with large or complex modifications.
Why Reverting Matters
Reverting changes is a common task in software development, especially when debugging or rolling back unintended modifications. For protected branches, reverting must be done carefully to preserve the branch’s history and avoid conflicts.
The Common Solution
A typical approach involves using git revert
to create a commit that reverses changes from a range of commits:
|
|
However, this method requires analyzing the log to identify commits to revert, which is error-prone. It becomes even more challenging when merge commits are involved, as they have two parents, and git revert
requires specifying one parent. Since protected branches often include merge commits, this adds complexity.
The Naive Solution
A simpler but less efficient solution involves manually checking out the desired branch or commit in a separate folder:
|
|
Manually delete all files except the .git
directory (to remove files added in the commits being reverted) and copy the contents from the target branch, ensuring the .git
directory is not copied. Then commit the changes:
|
|
⚠️ DO NOT copy the
.git
directory to prevent altering the Git index.
The Simpler Solution
The git restore
command simplifies this process by copying files from the source
branch into the current branch without modifying the Git index (unlike git checkout
or git reset
).
Example: Restore Entire Branch
|
|
Example: Restore Specific Files
You can also restore specific files or use a GLOB pattern to filter files:
|
|
This approach is efficient, minimizes errors, and works seamlessly with protected branches.