Many git commands have a interesting option --patch or -p for short, it allows a user to go through every change and asks what to do instead of adding all changes in the file to a new index.

git add -p

Developer often edits the same file multiple times and generates too many changes in the file for a single function improvement, it’s not suitable to add the whole file to new index because other developers can’t review your code in a clear logic. The command git add -p will help us to add partial changes for current commit. We can type ? to read the introduction for every sub-options for staging.



The most powerful option is e, it supports to edit hunk and stage the new change. We can type y if we want to stage the hunk or n if the current hunk is not suitable for the next commit.

git stash -p

The command git stash saves local modifications away and make the working directory clean to match the HEAD commit. If we want to stash a few modifications rather than all changes in the current working path, just pass -p to the command.
The workflow is similar to git add -p, the only difference is the effect of two git commands. This one removes local hunk and the last command add hunk for a new commit. But relax, git stash doesn’t delete the change forever, it can be recovered by git stash apply.



git reset -p

We have the commit history for the project like the following image.



Now we want to reset the last commit content but retain a few changes. It’s time for git reset -p to work for us, it can remove partial hunks on the commit, the last commit will be in history because we retained some hunks, it’s different from git reset.



Then we compare the current working status and HEAD commit, the applied hunk is regarded as a new line. But the commit a41f76 has both lines, it’s not changed by reset command.



Other Commands

There are some similar commands such as git checkout -p. The option patch gives these edit commands more flexible operations. git log -p is a popular reading command, we can read changing details in every commit by it.

Categories: Tool

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] git stash all: it can remove everything from our working directory even if the files are not tracked. git stash -p: –patch/-p can help us to include a part content in stash stack. Relevant article: Interesting Option -P For Git Command […]

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
1
0
Would love your thoughts, please comment.x
()
x