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 of the development team.

Git has a mechanism called "patch",
which I sometimes use when I can't get around it with git stash, but I can't 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 have created as many patches as you want, you can use git reset to restore the original.
As long as you have the patch file, you can restore the contents to the current state.

By default, the diff is taken between the current file and the index state of that file.
You can also take a diff from several generations ago by specifying a commit ID.

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 it.
However, if the contents of the file 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 briefly introduced in git diff, which specifies the commit ID to take the diff.

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

Another great benefit of this session was the opportunity to learn a bit about the --check option of git apply.
It seems like it could be useful for pre-checking code before a code review.

 
That's all

If you found this article useful, please click [Like]!
1
Loading...
1 vote, average: 1.00 / 11
77,658
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 I'm also grateful to be able to do a variety of other work, including marketing.
My portrait rights within Beyond are CC0.