Creating and Applying Code Patches with diff and patch
The diff and patch utilities are used to create and apply textual changes to source code. To generate a patch, you must have an original copy of the source and a modified copy. The modified files should retain their original names. For instance, if you modify main.c, keep it named main.c. It is advisalbe to back up the original file first, e.g., cp main.c main.c.orig.
Generating a Patch for a Single File
Use the diff command to compare the original and modified versions of a single file.
diff -u original_file.c modified_file.c > changes.patch
Key options:
-u: Produces a unified diff format, showing lines of context (typically 3 lines) around changes.-p: Adds function name information to the output, making patches easier to read.
The command output is redirected to a file (changes.patch), which becomes the patch file.
Generating a Patch for Multiple Files or Directories
To capture changes across multiple files or entire directory trees, use diff recursively.
diff -urN original_directory/ modified_directory/ > full_changes.patch
Key options:
-r: Enables recursive comparison of subdirectories.-N: Treats absent files as empty. This ensures newly added files in the modified directory are included in the patch as addisions. Without this flag,diffmerely reports missing files.
Applying a Patch
Use the patch command to apply changes from a patch file to the original source tree. Navigate to the root directory of the source code you want to patch.
cd /path/to/source_root
patch -p1 < /path/to/full_changes.patch
The -p1 option instructs patch to strip the first component from each file path found in the patch header. This is necesssary because the paths in the patch file (e.g., original_directory/src/file.c) likely contain a top-level directory name that differs from your local source directory's name.
Workflow Example
Consider a scenario where Developer A modifies a kernel source tree and needs to share the changes with Developer B.
Developer A's original source is in linux-kernel-orig/. The modified copy is in linux-kernel-mod/. To create a comprehensive patch:
diff -uprN linux-kernel-orig/ linux-kernel-mod/ > kernel_modifications.patch
Developer B receives kernel_modifications.patch. To apply it to their own clean copy of linux-kernel-orig/:
cd linux-kernel-orig
patch -p1 < ../kernel_modifications.patch
This process updates Developer B's source tree to match the modifications made by Developer A.