Page 1 of 1

Git - Working with Patches

#1 yothsoggoth   User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 61
  • Joined: 19-June 12

Posted 13 July 2012 - 02:45 PM

(Tutorial copied from my website )

Often when you work on other people’s code, or work with code in groups, it’s not a good idea to commit to the main repository. If not for any other reason, just so you don’t piss off the person who’s running the project.

That definitely doesn’t mean that you shouldn’t work on their code, though. The sensible thing to do is to create a patch that the person in charge of the repository can plug in and commit themselves.
Here’s how to do that using Git.

Not only have I written this little tutorial, but I’ve created a git repository to example this with, in which we will modify a very simple function to use a constant.
I have included generalised commands and instructions, and also ones specific to working on this repository.
Feel free to send me your patches for the repo and I’ll let you know if you did it all right!

Get the Main Code

The first thing you need to do to work on their code is to get the code. This should be pretty easy to anyone that’s ever used git.

git clone [address of the repo]

This will download a copy of the entire repo.

So, for my demo repo…

git clone git:// PatchDemo

This will download everything in the repo to a folder called PatchDemo.

Work on the Code

Now you have to make your changes. It is very, very, very important that you work on your code on a separate branch.

git checkout -b new_branch_name

So, if you’re working on PatchDemo

git checkout -b const_patch

Now make your changes and commit as you would normally.
If you’re working on PatchDemo, change OutputMessage.cpp to have the following.

const char* MESSAGE = "Hello, from a constant!";

Now commit it.

Do not forget to test that it works!
If you’re using PatchDemo, you just have to build the program and check to see if it outputs correctly.

Create the Patch

Now we need to create the actual patch that will make the changes we’ve made.

git format-patch [original branch] --stdout > name_of_patch_file.patch

For PatchDemo…

git format-patch master --stdout > const_message.patch

That’s it, done.

Applying the Patch

If you’re interested, the patch can be applied using the following commands.

First check the patch will work as you need it to. The first of these commands will show you what will be changed. The second shows you if any problems will arise from applying the patch (e.g. conflicts)

git apply --stat [patch_file]
git apply --check [patch_file]

Now, apply the patch.

git apply [patch_file]

So, for PatchDemo run the following.

git apply --stat const_message.patch
git apply --check const_message.patch
git apply const_message.patch

If everything went well, submit your patch to whoever’s in charge.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1