We don’t like to write the same code multiple times. If you have to apply any changes to projects that share files (the files you are editing), you can use git to accomplish this boring task. This is the hypothetical directories structure where the 2 repositories of this example is located:
-- projects/ |---first_repo_path/ |---second_repo_path/
Create the patch
We can start looking for what commit we would like to start to create the patch with. Let’s enter into the first repo and show the last commits:
$ cd projects/first_repo_path/ $ git log --pretty=oneline --abbrev-commit -3 a5f83e3 fixes security bug #123 789f90c fixes security bug #98 48c120e fixes problems with rails_admin
The second command print some important details on our commits. We can now detect our commit target (“789f90c” in our example) and create the patch with the command:
git format-patch -M 789f90c --stdout > fixes_security_bugs.patch
This will create the file fixes_security_bugs.patch the incapsulate the changes of the last two commits.
Apply the patch to other repository
To apply the patch to the other repository, we can move to his root and launch this command:
$ cd ../second_repo_path/ $ git am --signoff < ../first_repo_path/fixes_security_bugs.patch
Resolve possible conflicts
If there are any problems and the patch application fails no changes will be applied to the second repository. We can solve conflict using:
git apply --reject --whitespace=fix fixes_security_bugs.patch
that allows to apply only changes that don’t create conflicts. Refused code will be placed in .rej files that we can manually apply to our original code.