Using --patch and manual hunk mode on Git

status
Published
date
Jul 13, 2021
featured_image
slug
git-patch-and-manual-hunk-mode
tags
summary
When adding changes before committing with Git, we can use the --patch parameter to take only a part of the changes in a file, not all of them: git add -p or git add --patch
type
Post
When adding changes before committing with Git, we can use the --patch parameter to take only a part of the changes in a file, not all of them: git add -p or git add --patch
After the command is sent, we can process the changes step by step and interactively with the following shortcuts.
Changes will be displayed on the screen in chunks (hunks). A change in a file can be considered as a chunk, and there can be multiple chunks of changes within a file. Outside of standard uses, we can send the current change chunk to the end for control with the j and k shortcuts.
If a change in a file includes changes that should be in different commits, the change chunk can be split into smaller chunks with s. However, in some cases, splitting into smaller chunks cannot be done automatically, in which case we need to use manual hunk mode to manually correct the current change chunk with e. A vi-based editor is needed for the correction process.
As stated in the description; if we do not want to save certain changes, if they are deleted lines, we need to change the - character at the beginning to a space, and if they are added lines, we need to delete the lines entirely. We can change the character with r<Space>, and delete the line where the cursor is with dd.
For example, if we only want to consider the change made for ENDPOINT in the above code example, the final version of the file should be as follows.
After this change, the addition is made by saving the change with the :wq! command. If a wrong operation is done, an error indicating that the patch failed is shown and the process is requested to be done again.
Using manual hunk mode can help us make multiple different changes on a project at the same time and send more specific and accurate commits when sending changes.

© Samet 2017 - 2024