How to apply a patch created with git diff (how to apply a patch with git in the first place)

git

Hello.
I'm Mandai, the Wild team member in charge of development.

Git has a mechanism called "patching."
Even though I occasionally use it when `git stash` doesn't work, I can't seem to remember this incredibly simple command.

So I decided to leave it on my blog so I can forget about it

 

When creating a patch

To create a patch, use the git diff command

git diff test.txt > test.patch

 

Once you've created all the patches you need, you can just use `git reset` to revert to the previous state.
As long as you have the patch files, you can restore the system to its state at that point in time.

By default, the diff will show the current state of the file and its index.
You can also specify a commit ID to take a diff from several generations ago.

I've never used it, but it seems that if you specify two commit IDs, you can also get a diff between the commit IDs

 

When to apply a patch

Now let's apply the patch contents

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`, the changes will not be applied.
In such cases, you can use the method of specifying the commit ID to take a diff, which I briefly introduced in the `git diff` section.

I suddenly wondered what I should do to do the same thing as patch --dry-run, and after looking into it, I found that the --check option seems to be the answer

 

summary

We have summarized the steps for creating and applying patches using git

This was the first time I learned that you can create patches between commit IDs using git diff, but it's a feature unique to git, and I'd like to try using it casually someday and be proud of myself for it

One of the biggest takeaways from this experience was having the opportunity to look into the `--check` option of `git apply`.
It seems like it could be useful for pre-checking during code reviews.

 
That's all

If you found this article helpful,please give it a "Like"!
2
Loading...
2 votes, average: 1.00 / 12
78,378
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Yoichi Bandai

My main job is developing web APIs for social games, but thankfully I'm also given the opportunity to work on various other tasks, including marketing.
My image rights within Beyond are treated as CC0.