How PatchSet, PatchedFile, and Hunks work together
mainThe library follows a hierarchical model for representing unified diff data:
PatchSet: The top-level container representing the entire diff. It acts like a list ofPatchedFileobjects. You can instantiate it with a file-like object, an iterable of strings, or bytes.PatchedFile: Represents a single file modified in the patch. It contains metadata (likepath,is_added_file,is_modified_file,addedcount,removedcount) and a list ofHunkobjects.Hunk: Represents a specific block of changes within aPatchedFile. It contains line range information (source_start,target_start) and a list ofLineobjects.Line: Represents an individual line within a hunk. You can check if a line is part of the addition (is_added) or removal (is_removed) and access its content (value) and line number (source_line_noortarget_line_no).
At any level, calling print() or getting the string representation of these objects returns the unified diff data for that specific scope.
from unidiff import PatchSet
# Example of the hierarchy
patch = PatchSet.from_string('--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n hola\n-mundo\n+world\n')
file = patch[0]
hunk = file[0]
line = hunk[0]