Patching with Git

About patching

Generally a patch – is a file containing source code differences. In a patch you can specify which line in which file should be added, updated or deleted. The structure of such file is standardized – that means if you create a patch file in Windows you can easily implement it on Linux.

Let’s imagine you have a project you work on. You have a production server and a development workstation. Before starting your work you copied the production source code to the workstation and initiated a Git repo there. After you finish updating you need to apply updates on the production server.

How can you do that? The easiest way is to create a patch.

Creating patches with Git

  1. Check out initial commit and create a version tag by command
    git tag -a Initial_state
  2. Check out the commit with updated code. Create another version tag
    git tag -a Problem_solved
  3. Verify tags are created 
    git tag
  4. Create a patch file 
    git diff Initial_state Problem_solved -- > the-patch.diff
  5. Move the-patch.diff file to the production server in the project root directory.
  6. Login to the production server via SSH and change directory to the project root directory.
  7. Open the-patch.diff file in text editor. You will see many instructions. The most important information for you is file names, e.g. 
    diff --git a/app/Console/Commands/someCommand.php b/app/Console/Commands/someCommand.php
  8. Create a backup of the current project state!
  9. Pay attention to the file path. Since you are in the project root directory, you need to cut off first parts of files paths: a/ and b/ while patch applying. To do that, use -p1 parameter of the patch command (-p1 stands for “cut 1 part of path”):
    patch -p1 < ../the-patch.diff
  10. Carefully review the command’s output to avoid errors.