-
Notifications
You must be signed in to change notification settings - Fork 1
/
UnifiedDiffPatcher.php
380 lines (305 loc) · 11.2 KB
/
UnifiedDiffPatcher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
/**
* Implementation of the a patch mecanism for unified diff file.
* This method allow the validation of the whole patch before modifying any file.
*
* @author Francois Mazerolle <[email protected]>
*/
class UnifiedDiffPatcher {
private $debug = false;
private $arrError = array();
private $patch = false;
//Patch file
protected $patchHandle = null;
protected $patchLine = 0;
//Destination file ( resulting patched file )
protected $dstHandle = null;
protected $dstPath = null;
protected $dstLine = 0;
//Source file (unmodified file)
protected $srcHandle = null;
protected $srcPath = null;
protected $srcLine = 0;
public function __construct() {
}
/**
* Display debug messages.
*
* @param string $txt Debug message
*/
protected function debug($txt) {
if ($this->debug) {
echo $txt . "\n";
}
}
/**
* Log an error.
*
* @param string $txt Error message
*/
protected function addError($txt) {
$this->arrError[] = $txt;
}
/**
* Get the error that occured.
*
* @return array List of error
*/
public function getError(){
return $this->arrError;
}
/**
* Check if error occured.
*
* @return bool true is error occured.
*/
public function hasError() {
return !empty($this->arrError);
}
/**
* Validate a patch file.
*
* @param string $patchFile File path
* @param integer $patch_level -p param of the patch command
*
* @return bool true if no error.
*/
public function processPatch($patchFile, $patchLevel = '-1', $debug = false) {
$this->patch = true;
$this->debug = (bool)$debug;
$this->openPatch($patchFile);
$this->processFiles($patchLevel);
return !$this->hasError();
}
/**
* Validate a patch file.
*
* @param string $patchFile File path
* @param integer $patch_level -p param of the patch command
*
* @return bool true if no error.
*/
public function validatePatch($patchFile, $patchLevel = '-1', $debug = false) {
$this->patch = false;
$this->debug = (bool)$debug;
$this->debug("Validating patch ( read-only mode )");
$this->openPatch($patchFile);
$this->processFiles($patchLevel);
return !$this->hasError();
}
/**
* Loop in the patch file to find files to be patched.
* This method take care of initiating the resources handles
* to the files required further in the process.
*
* @param int $patchLevel -p parameter of the unix patch command.
*/
protected function processFiles($patchLevel) {
$line = fgets($this->patchHandle);
$this->patchLine++;
$this->srcHandle = null;
//Loop in all the line of the patch file.
do {
//loop until a file is found
if ($this->srcHandle) {
$this->processHunks($line);
//Preserving the unmodified lines after the last hunk.
$this->copyOriginalLines($this->srcLine+1, false);
if ($this->patch) {
unlink($this->srcPath);
}
$this->srcHandle = null; //Make the loop skip all the file hunks.
}
//Look if a file is specified at this line
if (0 == strncmp($line, '+++ ', 4)) {
$this->srcPath = $this->extractFileName($line, $patchLevel);
$this->debug(sprintf("Patching %s...", $this->srcPath));
if ($this->patch) {
//Make a copy for the source file.
$this->dstPath = $this->srcPath;
$this->srcPath .= '.orig';
rename($this->dstPath, $this->srcPath);
}
//Open source file
$this->srcHandle = fopen($this->srcPath, "r");
$this->srcLine = 0;
if (!$this->srcHandle) {
$this->addError(sprintf("File %s not found.", $this->srcHandle));
$this->srcHandle = null; //Make the loop skip all the file hunks.
}
if ($this->patch) {
//Open destination file
$this->dstHandle = fopen($this->dstPath, "w");
if (!$this->dstHandle) {
$this->addError(sprintf("File %s not found.", $this->dstHandle));
$this->srcHandle = null; //Make the loop skip all the file hunks.
}
}
}
$line = fgets($this->patchHandle);
$this->patchLine++;
} while (false !== $line);
}
protected function processHunks($line) {
$arrHunk = array(
'no' => 0,
'srcBegLine' => null,
'dstBegLine' => null,
'srcLastLine' => 1, //Hunk line length
'dstLastLine' => 1, //Hunk line length
);
$hunkSkip = false;
do {
$cmd = $line[0]; //Get the first character of the line
//Check if a Hunk just completed
if(('O' == $cmd || 'd' == $cmd || '@' == $cmd)
&& 0 != $arrHunk['no'] //This condition should not be executed before the first hunk is processed.
&& !$hunkSkip //If a hunk have failed, do not consider the line as modified : it failed.
) {
$from = $arrHunk['srcBegLine'];
$to = $arrHunk['srcBegLine']+$arrHunk['srcLastLine']-1;
$this->debug(sprintf("\t\tModified lines %u to %u.", $from, $to));
}
if ($cmd == 'O' || $cmd == 'd') { //Only or diff mean all hunk of this dst file have been processed.
return;
} else if ($cmd == '@') { //We're entering a new hunk
$hunkSkip = false; //New hunk, new attempt.
$h1 = sscanf(
$line, "@@ -%d,%d +%d,%d",
$arrHunk['srcBegLine'], $arrHunk['srcLastLine'], $arrHunk['dstBegLine'], $arrHunk['dstLastLine']
);
$h2 = sscanf(
$line, "@@ -%d +%d,%d",
$arrHunk['srcBegLine'], $arrHunk['dstBegLine'], $arrHunk['dstLastLine']
);
$arrHunk['no']++;
$this->debug(sprintf("\tChecking hunk #%u", $arrHunk['no']));
//Preserving the unmodified lines before the hunk.
$this->copyOriginalLines($this->srcLine+1, $arrHunk['srcBegLine']-1);
} else if ($cmd == '+' || $cmd == '-' || $cmd == ' ') {
if (!$hunkSkip) { //If the hunk previously failed, skip remaining instruction of that hunk.
$ret = $this->processInstruction($arrHunk, $line);
if (!$ret) {
$this->debug(sprintf("\t\tHunk FAILED."));
$hunkSkip = true; //A line of the hunk failed to compare, skip the whole hunk: it failed.
}
}
} else {
$this->addError(sprintf("Line #%u of the patch file seems invalid.", $this->patchLine));
}
$line = fgets($this->patchHandle);
$this->patchLine++;
} while (false !== $line);
}
protected function processInstruction($arrHunk, $line) {
$cmd = $line[0];
$code = substr($line, 1);
if($cmd != '+') { // ' ' or '-' : compare to validate
$srcLine = fgets($this->srcHandle);
$diff = strcmp($code, $srcLine);
if ($diff !== 0) {
$this->addError(sprintf("Line #%u of the patch file could not be matched with line #%u of %s.", $this->patchLine, $this->srcLine, $this->srcPath));
return false;
}
$this->srcLine++; //Only calculate the line if it passed.
}
if ($cmd != '-') { // ' ' or '+' : apply.
if ($this->patch) {
//Write/copy lines to dst.
if (!fwrite($this->dstHandle, $code)) {
throw new Exception("error writing to new file");
}
$this->dstLine++;
}
}
return true;
}
/**
* Open patch file.
*
* @param string $filePath Patch file path.
* @return Resource File handle to patch file.
*/
protected function openPatch($filePath) {
$this->debug(sprintf("Openning %s", $filePath));
$this->patchHandle = fopen($filePath, "r");
$this->patchLine = 0;
if (!$this->patchHandle) {
throw new Exception(sprintf("Could not open file %s.", $filePath));
}
return true;
}
/**
* Extract the file path from the +++ line.
*
* @param string $line Raw line from the patch file ( '+++ ...' )
* @param int $patchLevel Number of folder to remove from the file name.
* @return string File path.
*/
protected function extractFileName($line, $patchLevel) {
/* Terminate string at end of source filename */
$line = strstr($line, "\t", true);
//Remove the first 4 chr. ( '--- ' or '+++ ' )
$line = substr($line, 4);
/* Skip over (patch_level) number of leading directories */
while ($patchLevel--) {
$cut = strstr($line, '/');
if (!$cut) {
break;
}
$line = ltrim($cut, '/');
}
return $line;
}
/**
* Copy unmodified lines from the srcHandle to the dstHandle.
*
* @param int $from
* @param int $to
*/
protected function copyOriginalLines($from, $to) {
if($to === false) {
$to = PHP_INT_MAX;
}
if(0 > $from || 0 >= $to) {
return false; //No line to copy
}
for($i=$from;$i<=$to;$i++) {
$line = fgets($this->srcHandle);
if(!$line) {
break;
}
//Write/copy lines to dst.
if ($this->patch) {
if (!fwrite($this->dstHandle, $line)) {
throw new Exception("error writing to new file");
}
$this->dstLine++;
}
}
if($from != $i) {
$this->debug(sprintf("\t\tCopied unmodified lines %u to %u.", $from, $i-1));
}
$this->srcLine += $to - $from +1;
return true;
}
}
// Run the Patching process
try{
$diff = new UnifiedDiffPatcher();
$patchPath = getcwd() . '/patch.txt'; //Absolute path of the patch file.
$p = 0; // -p parameter of the unix patch command
chdir('common/framework/lib/module/');//The folder from where the patch path are relative to.
$ret = $diff->validatePatch($patchPath, $p, true); //Validate the patch, and display debug informations
if ($ret) {
$diff->processPatch($patchPath, $p); //Apply the patch without displaying debug informations.
} else {
echo 'Error repport:' . "\n";
echo implode("\n", $diff->getError());
}
}
catch(Exception $e) { //This will catch critical error witch can't be recovered.
//Like file access errors.
echo "\n" . $e->getMessage();
}
exit("\n");