/
svnPostCommitHook.util.php
693 lines (590 loc) · 17.1 KB
/
svnPostCommitHook.util.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
<?php
/**
* A really simple logging class
*/
class LogUtil
{
/**
* file pointer to log file
*/
private static $fp = null;
/**
* Loglevels enabled
*
* @var array
*/
private static $arrLogLevel = array('info', 'error');
/**
* warn
* @param string message
* @param string module
*/
public static function warn($msg, $module = null)
{
LogUtil::out($msg, "warn", $module);
}
/**
* error
* @param string message
* @param string module
* */
public static function error($msg, $module = null)
{
LogUtil::out($msg, "error", $module);
}
/**
* info
* @param string message
* @param string module
* */
public static function info($msg, $module = null)
{
LogUtil::out($msg, "info", $module);
}
/**
* debug
* @param string message
* @param string module
*/
public static function debug($msg, $module = null)
{
LogUtil::out($msg, "debug", $module);
}
/**
* opens the given log file
* @param string path to log file
*/
public static function open($aLogFile)
{
self::$fp = fopen($aLogFile, "a+");
LogUtil::info("-------------------------------------------");
LogUtil::info("Log file " . $aLogFile . " opened for write");
}
/**
* Set used log level
*
* @param array $aArrLogLevel
*/
public static function setLogLevel($aArrLogLevel)
{
self::$arrLogLevel = $aArrLogLevel;
}
/**
* closes opened log file
*/
public static function close()
{
self::info("Closing log file");
if (self::$fp != null)
{
fclose(self::$fp);
}
}
/**
* print the given message to log file
* @param string message
* @param string level
* @param string module
*/
private static function out($msg, $level, $module = null)
{
if (self::$fp != null)
{
if (in_array($level, self::$arrLogLevel))
{
if (null == $module)
{
$module = "core";
}
fwrite(self::$fp, date("Y-m-d H:i:s") . " [" . $level . "] " . " [" . $module . "] " .$msg . "\r\n");
}
}
}
}
/**
* transfer object class. Every entry of "svn log" will result in exactly one SvnCommitTO
*
* @author ckl <christopher[dot]klein[at]ecw[dot]de>
* @url http://wap.ecw.de / http://www.ecw.de
* @since 2008-07-13
* */
class SvnCommitTO
{
/**
* message of commit. German umlauts are converted to htmlentities
*
* @var string
*/
public $message;
/**
* Revision
*
* @var int
*/
public $revision;
/**
* Date of commit.
* Format is 2008-07-14 16:33:57 +0200 (Mo, 14 Jul 2008)
*
* @var string
*/
public $date;
/**
* Timestamp
*
* @var int
*/
public $timestamp;
/**
* username
*
* @var string
*/
public $user;
/**
* zero, one or more SvnFileInCommitTOs
* @type SvnFileInCommitTO
*/
public $svnFileInCommitTO;
/**
* Name of repository
*
* @var string
*/
public $repository;
/**
* URL to repository
*
* @var string
*/
public $repositoryUrl;
}
/**
* transfer object class. Every commited file results in exactly one SvnFileInCommitTO
*
* @author ckl <christopher[dot]klein[at]ecw[dot]de>
* @url http://wap.ecw.de / http://www.ecw.de
* @since 2008-07-13
*/
class SvnFileInCommitTO
{
/**
* Filename, german umlauts are converted to hmtlentities
*
* @var unknown_type
*/
public $filename;
/**
* type of file (modified, changed, deleted) as single char in upper cases (M,C,D)
*
* @var char
*/
public $type;
}
/**
* Helper class for accessing "svn log"
*
* @author ckl <christopher[dot]klein[at]ecw[dot]de>
* @url http://wap.ecw.de / http://www.ecw.de
* @since 2008-07-13
*/
class SvnLogUtil
{
/**
* path to "svn log"
* @type string
*/
private $_cmdSvnLog;
/**
* full URL of repository
*
* @var string
*/
private $_repositoryPath;
/**
* name of repository
*
* @var string
*/
private $_repositoryName;
/**
* constructor
* @param string path to "svn log"
*/
public function __construct($aCmdSvnLog, $aRepositoryPath, $aRepositoryName)
{
$this->_cmdSvnLog = $aCmdSvnLog;
$this->_repositoryName = $aRepositoryName;
$this->_repositoryPath = $aRepositoryPath;
if (!file_exists($this->_cmdSvnLog))
{
$msg = "Could not find svn executable: '" . $this->_cmdSvnLog ."'";
LogUtil::error($msg);
throw new Exception($msg);
}
LogUtil::debug("New SvnToUtil created:");
LogUtil::debug(" * path to svn is '" . $this->_cmdSvnLog."'");
LogUtil::debug(" * repository url is '" . $this->_repositoryPath . "'");
LogUtil::debug(" * repository name is '" . $this->_repositoryName . "'");
}
/**
* retrieves all commits
* @return array of SvnCommitTo. The first item (idx 0) is the oldest revision (e.g. 1). The latest item (idx > 0) is the newest revision (e.g. 2)
*/
public function retrieveAllCommits()
{
LogUtil::info("Retrieving all commits from repository '" . $this->_repositoryPath ."'...");
$subCommand = "log -v " .$this->_repositoryPath;
$buffer = $this->getSvnLogResult($subCommand);
$svnCommitEntry = '';
$bForceParsingOnNextMatch = false;
$rSvn = array();
$arrBuffer = array();
for ($i = 0, $m = sizeof($buffer); $i < $m; $i++)
{
$line = $buffer[$i];
if ((strstr($line, "------") !== FALSE) )
{
if ($bForceParsingOnNextMatch == true)
{
array_push($arrBuffer, $line);
array_push($rSvn, $this->svnCommitEntryToTO($arrBuffer));
$arrBuffer = array();
}
else
{
$bForceParsingOnNextMatch = true;
}
}
array_push($arrBuffer, $line);
}
return array_reverse($rSvn, false);
}
/**
* retrieves a single revision
*
* @param int revision
* @return array of SvnCommitTO
*/
public function retrieveCommitByRevision($aRevision)
{
$subCommand = "log -r $aRevision -v " . $this->_repositoryPath;
$buffer = $this->getSvnLogResult($subCommand);
return $this->svnCommitEntryToTO($buffer);
}
/**
* executes the "svn log" command with given parameters and returns the output as array
*
* @param string Subcommand of "svn log"
* @return array each entry contains one line of output
*/
private function getSvnLogResult($aSubCommand)
{
$cmdSvnLog = $this->_cmdSvnLog ." " . $aSubCommand;
LogUtil::info("Executing '" . $cmdSvnLog ."' ...");
$fp = popen($cmdSvnLog, "r");
$rBuffer = '';
if ($fp != null)
{
$buffer = '';
while(!feof($fp))
{
$buffer .= fgets($fp, 4096);
}
pclose($fp);
$rBuffer = explode("\n", trim($buffer));
}
else
{
LogUtil::error("Could not open pipe to svn");
}
LogUtil::info("Buffer has '" . sizeof($rBuffer) . "' lines");
return $rBuffer;
}
/**
* Converts exactly one log entry into a transfer object.
* Field 'message' and 'files' are converted to htmlentities.
*
* @param array each item must contain exactly one line of result. The first and last line must be "--------"!
* @return SvnCommitTO or null if commit entry is invalid
*/
public function svnCommitEntryToTO($aLogEntry)
{
$rTO = new SvnCommitTO();
$totalLines = sizeof($aLogEntry);
if ($totalLines == 1)
{
LogUtil::error("Log entry seems to be invalid. Did you specify a valid revision and repository url? Return a NULL SvnCommitTO");
return null;
}
LogUtil::info("Log entry has '" . $totalLines . "' lines");
$revisionInfo = explode("|", $aLogEntry[1]);
$rTO->revision = str_replace("r", "", trim($revisionInfo[0]));
$rTO->user = trim($revisionInfo[1]);
$rTO->date = trim($revisionInfo[2]);
$rTO->repository = $this->_repositoryName;
$rTO->repositoryUrl = $this->_repositoryPath;
$rTO->timestamp = self::svnDateToTimestamp($rTO->date);
preg_match("/(\d*)(\w*)/", trim($revisionInfo[3]), $arrLinesAdded);
$totalMessageLines = $arrLinesAdded[1];
$message = '';
// parse messages
for ($i = ($totalLines - $totalMessageLines), $m = $totalLines; $i < $m; $i++) {
$wantedLineNumber = $i;
$currentLine = $aLogEntry[$wantedLineNumber - 1];
if (strlen(trim($currentLine)) > 0)
{
$message .= $currentLine . "\n";
}
}
$rTO->message = self::cp850toGermanHtmlEntities(trim($message));
$arrFiles = array();
for ($i = 3, $m = (sizeof($aLogEntry) - 2 - $totalMessageLines); $i < $m; $i++) {
$logFileLine = trim($aLogEntry[$i]);
if (strlen($logFileLine) > 0)
{
$file = new SvnFileInCommitTO();
$file->type = $logFileLine{0};
$file->filename = self::cp850toGermanHtmlEntities(substr($logFileLine, 2));
array_push($arrFiles, $file);
}
}
$rTO->svnFileInCommitTO = $arrFiles;
return $rTO;
}
/**
* Converts codepage 850 items to HTML entities
*
* @param string $aText
* @return string
*/
public static function cp850toGermanHtmlEntities($aText)
{
$arrBads = array("\x84", "\x81", "\x94", "\x8e", "\x9a", "\x99", "\xe1");
$arrGoods = array('ä', 'ü', 'ö', 'Ä', 'Ü', 'Ö', 'ß');
return str_replace($arrBads, $arrGoods, $aText);
}
/**
* Converts a SVN date to timestamp
*
* @param string $aSvnDate
* @return int
*/
public static function svnDateToTimestamp($aSvnDate)
{
$data = self::svnDateToArray($aSvnDate);
return mktime($data['hour'], $data['minute'], $data['second'], $data['month'], $data['day'], $data['year']);
}
/**
* Converts a svn date to an array
*
* @param hash $aSvnDate
*/
public static function svnDateToArray($aSvnDate)
{
if (preg_match("/^(\d\d\d\d)\-(\d\d)\-(\d\d)\s(\d\d):(\d\d):(\d\d)\s([\+|\-])(\d\d\d\d)\s\((\w*)\,\s(\d*)\s(\w*)\s(\d*)\)/", $aSvnDate, $arrRet))
{
$r['year'] = $arrRet[1];
$r['month'] = $arrRet[2];
$r['day'] = $arrRet[3];
$r['hour'] = $arrRet[4];
$r['minute'] = $arrRet[5];
$r['second'] = $arrRet[6];
$r['addition'] = $arrRet[7];
$r['gmt'] = $arrRet[8];
$r['dayName'] = $arrRet[9];
$r['monthName'] = $arrRet[11];
return $r;
}
}
}
/**
* Executes all hooks.
*
* @author ckl <christopher[dot]klein[at]ecw[dot]de>
* @url http://wap.ecw.de / http://www.ecw.de
* @since 2008-07-13
*/
class SvnHookRunner
{
/**
* @var string
*/
private $_repositoryName;
/**
* @var int
*/
private $_revision;
/**
* @var hash
*/
private $_confEnvironment;
/**
* @var hash
*/
private $_confRepositories;
/**
* @var hash
*/
private $_confCurrentRepository;
/**
* @var array
*/
private $_executeHooks;
/**
* @var array
*/
private $_configHooks;
/**
* @var SvnLogUtil
*/
private $_svnLogUtil;
/**
* @var string
*/
private $_repositoryPath;
/**
* Constructor
*
* @param string name of repository
* @param string revision
* @param array $aConfEnvironment
* @param array $aConfRepositories
*/
public function __construct($aRepositoryName, $aRevision, $aConfEnvironment, $aConfRepositories)
{
$this->_repositoryName = $aRepositoryName;
$this->_revision = $aRevision;
$this->_confEnvironment = $aConfEnvironment;
$this->_confRepositories = $aConfRepositories;
$this->_configHooks = array();
$this->setUp();
}
/**
* delegate method to sub routines
* @throws Exception if setup failed
*/
private function setUp()
{
if ($this->_confEnvironment['logging']['enable'] == true)
{
LogUtil::open($this->_confEnvironment['logging']['file']);
LogUtil::setLogLevel($this->_confEnvironment['logging']['level']);
}
$this->loadCurrentRepositoryConfiguration();
$this->loadHooks();
$this->_svnLogUtil = new SvnLogUtil($this->_confEnvironment['svn']['executable'], $this->_repositoryPath, $this->_repositoryName);
}
/**
* Loads the configuration. If no own configuration is assigned for repository, the configuration __DEFAULT__ is used.
* @throws Exception If configuration could not be set.
*/
private function loadCurrentRepositoryConfiguration()
{
if (isset($this->_confRepositories[strtolower($this->_repositoryName)]))
{
$this->_confCurrentRepository = $this->_confRepositories[strtolower($this->_repositoryName)];
LogUtil::info("Own configuration loaded for repository " . $this->_repositoryName);
}
else
{
$this->_confCurrentRepository = $this->_confRepositories['__DEFAULT__'];
LogUtil::info("Default configuration loaded for repository " . $this->_repositoryName);
}
if (!$this->_confCurrentRepository)
{
throw new Exception("No configuration loaded for repository '" . $this->_repositoryName ."'");
}
$this->_repositoryPath = $this->_confCurrentRepository['repositoryUrl'] . '/' . $this->_repositoryName;
LogUtil::debug("Configuration values: " . print_r($this->_confCurrentRepository, true));
}
/**
* Loads all desired hooks - our own class loader.
* This method does ***not*** throw any error if loading failed.
*/
private function loadHooks()
{
$arrHooks = $this->_confCurrentRepository['arrHooks'];
LogUtil::debug("'" . sizeof($arrHooks) ."' hooks assigned for this repository");
$thisDir = dirname(__FILE__);
while(list($hook, $arrHookConfig) = each($arrHooks))
{
if ($hook == '' && !is_array($arrHookConfig)) {
$hook = $arrHookConfig;
$arrHookConfig = array();
}
$path = $thisDir . "/hooks/" . $hook . "/" . $hook . ".php";
if (file_exists($path))
{
include_once($path);
LogUtil::debug("Hook file '$hook'' loaded");
if (class_exists($hook))
{
$clazz = new $hook();
if ($clazz instanceof ISvnPostCommitHook )
{
$this->_executeHooks[] = $clazz;
$this->_configHooks[] = $arrHookConfig;
LogUtil::info("Hook '$hook' ready for use");
}
else
{
LogUtil::error("Hook '$hook' does not implement ISvnPostCommitHook");
}
}
else
{
LogUtil::error("Clazz '$hook' does not exists in file '" . $path . "'");
}
}
else
{
LogUtil::error("Could not load hook '" . $hook . "': file '" . $path . "' not found");
}
}
}
/**
* run all available scripts for current repository
*/
public function run()
{
$commitTO = $this->_svnLogUtil->retrieveCommitByRevision($this->_revision);
if (null == $commitTO)
{
LogUtil::info("Will not execute any hooks. SvnCommitTO is NULL");
return;
}
for ($i = 0, $m = sizeof($this->_executeHooks); $i < $m; $i++)
{
$clazz = $this->_executeHooks[$i];
$clazz->runHook($this->_configHooks[$i], $this->_repositoryName, $this->_revision, $this->_repositoryPath, $this, $commitTO);
}
}
/**
* returns the configuration for current repository
*
* @return hash
*/
public function getCurrentRepositoryConfiguration()
{
return $this->_confCurrentRepository;
}
/**
* returns the svn log utility
*
* @return SvnLogUtil
*/
public function getSvnLogUtil()
{
return $this->_svnLogUtil;
}
/**
* destructor - only used for closing log file
*
*/
public function __destruct()
{
LogUtil::close();
}
}
?>