Create a patch file from git diff

Sometimes you want to share changes you made in the code to a friend, maybe for learning purpose or help fix a broken line.

In such cases, a patch file (diff file) can help you. Let’s walk through step by step.

We shall begin with git status on a terminal. A working copy is clean.
Open the source code in a text editor called VS Code. Send commandcode .

Edit any files, I’ll change some content in app.component.html

Changed, the right picture shows how it looks.

You can review changes in VS Code. The red lines with minus signs are lines removed.
The green ones with plus signs are lines added.

Let’s see how it looks differently in terminal.
Do git status.

Below you can see one modified file marked red.

Do git diff. You will see the same changes in a different format. It is just a different presentation.

Next, creating a patch file. Do the following command.

Put any filenames you prefer, I’ll use edit_content.diff.
The extension (which is .diff here) can be diff or patch. Both will do.

An option -u is to tell that you’re making a diff file, which is actually a default setting. :p
About --no-prefix, let’s get it explained in the last section.

You can see the result in edit_content.diff in VS Code. It looks like what you get from git diff and what you’ve seen in VS Code earlier. The only difference is that things are presented in different colors.

Next, we’ll take all the changes back. You can revert unstaged changes by doing git checkout.

Check the code, it is as new.

Now it’s time to create a patch. Let’s do the following command.

The option -i is to tell the program to use a patch file called edit_content.diff.
The option -p will be explained with git diff's --no-prefix option in the last section.

Now, let’s just check if the patch’s been applied correctly.

It seems like so!

Let’s talk about the git diff’s — no-prefix option.

The pictures below show the differences between the results of with and without--no-prefixoption.

On the left, test.diff is without — no-prefix.
On the right, edit_content.diffis the one with --no-prefix option.

You can see that without --no-prefix option, you will get leading folder structure, annotated with a and b. So when you apply the patch, you have to provide -p1 to tell the program the reference point to apply the patch.

If the patch is made to compare things in the same folder, you can provide -p0 options. This is when we use with the — no-prefix’s patch files.

This section, we’ll see the diff results (Not a git diff)

Compare things in different folders. In this case patch2 and patch and then save the difference to a file called diff-u.diff.
You must provide -u option, to tell the the diff command to save the output as unified format

Open up the diff-u.diff file, you can see the folders underlined.

,

These changes are the results of 2 folders comparations. But git diff is to compare things in the same folder, so we can use --no-prefix.

--

--