Interactively review and apply changes using git -p
When working on projects that involve multiple configuration files, it's common to encounter situations where only specific changes need to be committed while excluding unwanted modifications. Manually editing each file can be time-consuming and error-prone. This is where Git's git add -p option comes to the rescue.
git add --patch file-name
git add -p .
What is git add -p?
The git add -p command is a powerful tool that allows you to interactively review and selectively stage changes within a file. It provides a granular approach to commit preparation by presenting a patch-like interface that lets you choose which modifications to include in your commit.
How git add -p Works?!
When you run git add -p, Git presents you with a series of change chunks within the file. Each chunk represents a hunk of code that has been modified. For each chunk, Git offers a set of options:
- y: Stage the current hunk and include it in the commit.
- n: Do not stage the current hunk and exclude it from the commit.
- q: Quit the interactive mode and exit git add -p.
- a: Stage this hunk and all remaining hunks in the file.
- d: Do not stage this hunk or any of the remaining hunks in the file.
- j: Leave this hunk undecided, move to the next undecided hunk.
- J: Leave this hunk undecided, but do not move to the next undecided hunk.
- g: Select a specific hunk to go to.
- /: Search for a hunk that matches a given regex pattern.
- e: Manually edit the current hunk.
- ?: Open the help prompt to see these options.
By selecting the appropriate options, you can precisely curate the changes that belong to your commit, leaving out any unwanted modifications. Git walks you through each chunk until you've processed all the changes.
In conclusion, the git add -p option is a valuable feature that enables you to review and selectively stage changes within a file. Its interactive mode empowers you to curate commits with precision, excluding undesired modifications and promoting cleaner commit histories. By leveraging this capability, you can streamline your workflow and enhance collaboration in projects involving complex configuration files. Give it a try and experience the benefits of selective commits with Git!
Note: The git add -p option is available in Git versions 2.6.0 and above.