Patch Loader
Overview
The PatchLoader class loads and processes patch files in unified diff format,
extracts added/removed lines, builds n-gram hash lists, and tracks patches by
file type. It is a core component of the PatchTrack pipeline responsible for
normalizing and preparing patch data for classification.
This page explains the workflow, key methods, data structures, and tuning parameters. For the complete API reference and docstrings, see the mkdocstrings section below.
Purpose
- Load patch files from the filesystem (single files or directory trees)
- Extract added lines (from patch files) and removed lines (from buggy files)
- Normalize content by removing comments and collapsing whitespace
- Build n-gram hash lists using three independent hash functions
- Track file type information for language-aware processing
Key Concepts
Patch Types
- Buggy patches: Files with removed lines (prefixed with
-in diff format) represent the original buggy code - Patch files: Files with added lines (prefixed with
+in diff format) represent the fix/patch applied to address the bug
N-gram hashing
Sequences of NGRAM_SIZE tokens are hashed using three hash functions:
- FNV-1a: Fast, non-cryptographic hash
- DJB2: Daniel J. Bernstein's hash
- SDBM: SDBM hash function
All three hashes are stored for each n-gram to improve matching robustness (three independent hash functions reduce collision risk).
Normalization
Raw patch lines are normalized by:
- Converting to lowercase
- Removing language-specific comments (using
helpers.remove_comment()) - Collapsing whitespace and splitting into tokens
File Type Index
The file_ext parameter is an integer index (2–39 range) that identifies
the file type/language. This is used to apply language-specific comment removal
and tokenization rules. The index maps to extensions defined in
analyzer.constant.EXTENSIONS.
Workflow
PatchLoader.traverse(patch_path, patch_type, file_ext)
│
├─── For each patch file:
│
├─── _process_patch_file() routes to:
│ ├─ _process_buggy() [removed lines]
│ └─ _process_patch() [added lines]
│
├─── For each diff hunk (@@):
│ ├─ Extract lines (- or +)
│ ├─ Format for display (HTML color tags)
│ └─ Call _add_patch_from_diff()
│
├─── _add_patch_from_diff():
│ ├─ Normalize lines
│ ├─ Call _build_hash_list()
│ ├─ Create PatchInfo object
│ └─ Append to _patch_list
│
└─── Return count of patches loaded
Key Methods
| Method | Returns | Purpose |
|---|---|---|
traverse(patch_path, patch_type, file_ext) |
int |
Load and process all patches from path; return count. Routes to _process_buggy() or _process_patch(). |
_process_buggy(patch_path, file_ext) |
None |
Extract removed lines (prefix -), accumulate diff hunks, and call _add_patch_from_diff(). |
_process_patch(patch_path, file_ext) |
None |
Extract added lines (prefix +), accumulate diff hunks, and call _add_patch_from_diff(). |
_add_patch_from_diff(...) |
None |
Normalize diff lines, build hash list, create PatchInfo, append to internal list. |
_normalize(patch, file_ext) |
str |
Remove comments, collapse whitespace, lowercase. |
_build_hash_list(diff_norm_lines) |
Tuple |
Compute FNV-1a, DJB2, SDBM hashes for each n-gram. Return (hash_list, patch_hashes). |
items() |
List[PatchInfo] |
Get all loaded PatchInfo objects. |
length() |
int |
Get count of loaded patches. |
hashes() |
Dict[int, str] |
Get hash-to-ngram lookup table. |
added() |
List[List[str]] |
Get all added (patch) lines as token lists. |
removed() |
List[List[str]] |
Get all removed (buggy) lines as token lists. |
Data Structures
PatchInfo (from common.py)
Each patch record contains:
PatchInfo(
path: str, # "[filename] file.py #2" (patch id)
file_type: int, # File extension type index (2-39)
diff_orig_lines: str, # Raw diff lines (HTML-formatted)
diff_norm_lines: List[str], # Normalized tokens
hash_list: List[int], # All hashes (fnv1a, djb2, sdbm per n-gram)
patch_hashes: List[Tuple[...]], # (ngram_str, [hash1, hash2, hash3])
ngram_size: int # Size of n-grams used
)
Hash Storage
Internal _hashes: Dict[int, str] maps hash values to n-gram strings for
reverse lookup. Built and populated during _build_hash_list().
Usage Example
Basic usage (CLI-like)
from analyzer.patchLoader import PatchLoader
loader = PatchLoader()
# Process buggy patches (removed lines)
buggy_count = loader.traverse(
patch_path='data/buggy/',
patch_type='buggy',
file_ext=2 # Language type index for Python
)
print(f"Loaded {buggy_count} buggy patches")
# Process fixes (added lines)
patch_count = loader.traverse(
patch_path='data/patches/',
patch_type='patch',
file_ext=2
)
print(f"Loaded {patch_count} patch files")
# Inspect results
for patch_info in loader.items():
print(f"Patch: {patch_info.path}")
print(f" File type: {patch_info.file_type}")
print(f" Hashes: {len(patch_info.hash_list)}")
print(f" N-gram size: {patch_info.ngram_size}")
# Retrieve specific data
hash_map = loader.hashes() # Dict[hash_value] -> ngram string
removed_lines = loader.removed() # List of removed token lists
added_lines = loader.added() # List of added token lists
Processing a single file
loader = PatchLoader()
loader.traverse(
patch_path='data/buggy/file.patch',
patch_type='buggy',
file_ext=2
)
N-gram Size and Performance
- Default
NGRAM_SIZEfromanalyzer.constantis1. - Larger n-grams (e.g., 3–7) reduce false positives but increase hashing overhead and may decrease recall.
- If a diff is shorter than
ngram_size, thengram_sizeis reduced dynamically in_add_patch_from_diff()to match the diff length. - The
ngram_sizeused is stored in eachPatchInfofor later reference.
Best Practices
- Use consistent
file_extindices across buggy and patch processing to ensure language-aware normalization is applied uniformly. - Pre-validate patch file format (unified diff) before passing to
traverse(). - Monitor
_npatchor calllength()to confirm patches were loaded successfully. - Store
loader.hashes()for reverse-lookup if you need to map hash values back to n-gram strings during classification.
Notes on Comments Removal
The _normalize() method calls helpers.remove_comment(source, file_ext) to
strip language-specific comments before tokenization. The file_ext parameter
tells the helper which language syntax to use (e.g., # for Python, // for
Java, etc.). See docs/reference/helpers.md for details.
API Reference
Patch loader for analyzing patch files.
The PatchLoader class loads and processes patch files (unified diff format), builds hash lists using n-grams, and tracks added/removed lines.
analyzer.patchLoader.PatchLoader
Loads and processes patch files using diff format and n-gram hashing.
Source code in analyzer/patchLoader.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
analyzer.patchLoader.PatchLoader.__init__()
Initialize the PatchLoader with empty data structures.
Source code in analyzer/patchLoader.py
analyzer.patchLoader.PatchLoader.traverse(patch_path, patch_type, file_ext)
Traverse patch files and process them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patch_path
|
str
|
Path to a patch file or directory. |
required |
patch_type
|
str
|
Type of patch ('buggy' or 'patch'). |
required |
file_ext
|
int
|
File extension type index. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of patches processed. |
Source code in analyzer/patchLoader.py
analyzer.patchLoader.PatchLoader.items()
analyzer.patchLoader.PatchLoader.length()
analyzer.patchLoader.PatchLoader.hashes()
analyzer.patchLoader.PatchLoader.added()
See Also
- Main Module — How patches are loaded in the pipeline
- Classifier — How hash lists are used for matching
- Constant — File type indices and
NGRAM_SIZE - Helpers — Comment removal for different languages