How do I apply a patch created with git diff?
table of contents
Hello.
I'm Mandai, in charge of Wild on the development team.
Git has a system called "patches".
Even though I sometimes use it when I can't get by with git stash, I can't remember this super simple command.
So I decided to leave it on my blog so I don't have to forget about it.
When creating a patch
If you want to create a patch, use the git diff command.
git diff test.txt > test.patch
Once you have created as many patches as you want, you can do a git reset and things will be back to normal.
As long as you have a patch file, you can change the contents to the current state.
By default, the diff will show the current file and its index.
You can also take diffs from several generations ago by specifying the commit ID.
I've never used it, but it seems that if you specify two commit IDs, you can do a diff between the commit IDs.
When applying the patch
Next, let's reflect the contents of the patch.
git apply test.patch
That's all.
However, if the file contents at the time of git apply are different from those at the time of git diff, it will not be applied.
In this case, you can use the method of specifying the commit ID and taking a diff, as briefly introduced with git diff.
I suddenly wondered what I should do to do the same thing as patch --dry-run, and when I looked into it, I found that the --check option was the answer.
summary
We have summarized the steps for creating and applying patches using git.
This is the first time I've learned that you can use git diff to create patches using commit IDs, but it's a feature unique to git, and I'd like to try it out someday and look proud.
Another great benefit of this trip was that I had the opportunity to do a little research on the --check option of git apply.
It can also be used as a preliminary check when reviewing code.
That's it.