s/count/sizeof/g
[viewsvn.git] / includes / svnlib.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # ViewSVN [#]version[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version [#]gpl[#] of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Command line interface with the SVN commands
24 *
25 * @package ViewSVN
26 */
27
28 /**
29 * Interacts with the command line subsystem to
30 * access SVN information
31 *
32 * @package ViewSVN
33 * @version $Id$
34 */
35 class SVNLib
36 {
37 /**
38 * Path to the SVN binary
39 * @var string
40 */
41 var $svnpath;
42
43 /**
44 * Controller
45 * @var object
46 * @access private
47 */
48 var $controller;
49
50 /**
51 * Constructor: validate SVN path
52 *
53 * @param object Controller
54 */
55 function SVNLib(&$controller)
56 {
57 $this->controller =& $controller;
58
59 $this->svnpath =& $this->controller->xquery->cmd($this->controller->registry->svnpath);
60
61 $access = $this->controller->xquery->exec($this->svnpath . ' --version');
62
63 if (!$access)
64 {
65 $this->controller->registry->trigger->error($this->controller->registry->lang->string('The SVN binary could not be located'));
66 }
67
68 if (!preg_match('#^svn, version (.*?)\)$#i', trim($access[0])))
69 {
70 $this->controller->registry->trigger->error($this->controller->registry->lang->string('The SVN binary does not appear to be valid (it failed our tests)'));
71 }
72 }
73
74 /**
75 * Executes the SVN binary
76 *
77 * @access private
78 *
79 * @param string Command
80 *
81 * @return array Output
82 */
83 function svn($command)
84 {
85 $output = $this->controller->xquery->exec($this->svnpath . ' ' . $command . ' 2>&1');
86
87 // make sure that we keep escaped chars
88 //$output = str_replace(array('\t', '\n', '\r'), array('\\\t', '\\\n', '\\\r'), $output);
89 //$output = preg_replace('#\\\(.)#', '\\\\\\\\' . '\1', $output);
90 //$output = str_replace('\\', '\\\\', $output);
91
92 $temp = implode("\n", $output);
93 if (strpos($temp, '(apr' . '_err=') !== false)
94 {
95 $this->controller->registry->trigger->error(nl2br($temp));
96 }
97 return $output;
98 }
99
100 /**
101 * SVN Wrapper: standard command system
102 *
103 * @access public
104 *
105 * @param string SVN command
106 *
107 * @return array Lines of output
108 */
109 function command($command)
110 {
111 global $viewsvn;
112
113 $revision = SVNCommon::rev($this->controller->revnum);
114
115 return $this->svn($command . ' ' . $this->controller->repospath . $this->controller->path . '@' . $revision);
116 }
117
118 /**
119 * SVN Wrapper: blame
120 *
121 * @access protected
122 *
123 * @param string Repository
124 * @param string Path
125 * @param integer Revision
126 *
127 * @return array Lines of blame output
128 */
129 function blame($repos, $path, $revision)
130 {
131 return $this->std('blame', $repos, $path, $revision);
132 }
133
134 /**
135 * SVN Wrapper: cat
136 *
137 * @access protected
138 *
139 * @param string Repository
140 * @param string Path
141 * @param integer Revision
142 *
143 * @return array Lines of cat output
144 */
145 function cat($repos, $path, $revision)
146 {
147 return $this->std('cat', $repos, $path, $revision);
148 }
149
150 /**
151 * SVN Wrapper: diff
152 *
153 * @access protected
154 *
155 * @param string Repository
156 * @param string Path
157 * @param integer Lower revision
158 * @param integer Higher revision
159 *
160 * @return array Lines of diff output
161 */
162 function diff($repos, $path, $lorev, $hirev)
163 {
164 global $viewsvn;
165
166 $hirev = $this->rev($hirev);
167 $lorev = $this->rev($lorev);
168 if ($lorev == 'HEAD')
169 {
170 $lorev = 1;
171 }
172
173 if (is_integer($hirev) AND is_integer($lorev))
174 {
175 if ($lorev > $hirev)
176 {
177 $lorev = $hirev - 1;
178 }
179 if ($lorev == $hirev)
180 {
181 $lorev = 0;
182 }
183 }
184
185 $repospath = $viewsvn->repos->fetch_path($repos, false);
186
187 return $this->svn('diff -r' . $lorev . ':' . $hirev . ' ' . $repospath . $path);
188 }
189
190 /**
191 * SVN Wrapper: log
192 *
193 * @access protected
194 *
195 * @param string Repository
196 * @param string Path
197 * @param integer Lower revision
198 * @param integer Higher revision
199 *
200 * @return array Lines of log output
201 */
202 function log($repos, $path, $lorev, $hirev)
203 {
204 global $viewsvn;
205
206 $hirev = $this->rev($hirev);
207 $lorev = $this->rev($hirev);
208 if ($lorev == 'HEAD')
209 {
210 $lorev = 0;
211 }
212
213 if (is_integer($hirev) AND is_integer($lorev))
214 {
215 if ($lorev > $hirev)
216 {
217 $lorev = $hirev - 1;
218 }
219 if ($lorev == $hirev)
220 {
221 $lorev = 0;
222 }
223 }
224
225 $repospath = $viewsvn->repos->fetch_path($repos, false);
226
227 return $this->svn('log -v -r' . $hirev . ':' . $lorev . ' ' . $repospath . $path);
228 }
229
230 /**
231 * SVN Wrapper: ls (list)
232 *
233 * @access public
234 *
235 * @param object Controller object
236 *
237 * @return array Lines of list output
238 */
239 function ls(&$controller)
240 {
241 return $this->std('list');
242 }
243 }
244
245 /**
246 * Annotation/blame system; constructs an array
247 * that is ready for output
248 *
249 * @package ViewSVN
250 * @version $Id$
251 */
252 class SVNBlame
253 {
254 /**
255 * Array of blame information
256 * @var array
257 */
258 var $blame = array();
259
260 /**
261 * Raw "svn blame" output
262 * @var array
263 */
264 var $rawoutput;
265
266 /**
267 * Constructor: create blame and store data
268 *
269 * @param string Repository
270 * @param string Path
271 * @param integer Revision
272 */
273 function SVNBlame($repos, $path, $revision)
274 {
275 global $viewsvn;
276
277 $this->rawoutput = $viewsvn->svn->blame($repos, $path, $revision);
278 $this->process();
279 }
280
281 /**
282 * Returns blame for display
283 *
284 * @access public
285 *
286 * @return array Blame data
287 */
288 function fetch()
289 {
290 return $this->blame;
291 }
292
293 /**
294 * Parses the blame data
295 *
296 * @access private
297 */
298 function process()
299 {
300 $lineno = 1;
301
302 foreach ($this->rawoutput AS $line)
303 {
304 if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)\s(.*)$#', $line, $matches))
305 {
306 $this->blame[] = array(
307 'rev' => $matches[1],
308 'author' => $matches[2],
309 'line' => $matches[3],
310 'lineno' => $lineno++
311 );
312 }
313 // a blank line
314 else if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)$#', $line, $matches))
315 {
316 $this->blame[] = array(
317 'rev' => $matches[1],
318 'author' => $matches[2],
319 'line' => '',
320 'lineno' => $lineno++
321 );
322 }
323 }
324 }
325 }
326
327 /**
328 * Log management system; creates a complex list
329 * of SVN log information
330 *
331 * @package ViewSVN
332 * @version $Id$
333 */
334 class SVNLog
335 {
336 /**
337 * Array of logs
338 * @var array
339 */
340 var $logs = array();
341
342 /**
343 * Raw "svn log" output
344 * @var array
345 */
346 var $rawoutput;
347
348 /**
349 * Constructor: create log store for the given file
350 *
351 * @param string Repository
352 * @param string Path
353 * @param integer Lower revision
354 * @param integer Higher revision
355 */
356 function SVNLog($repos, $path, $lorev, $hirev)
357 {
358 global $viewsvn;
359
360 $this->rawoutput = $viewsvn->svn->log($repos, $path, $lorev, $hirev);
361 $this->process();
362 }
363
364 /**
365 * Returns logs for display
366 *
367 * @access public
368 *
369 * @return array Log data
370 */
371 function fetch()
372 {
373 return $this->logs;
374 }
375
376 /**
377 * Splits up the raw output into a usable log
378 *
379 * @access private
380 */
381 function process()
382 {
383 $lastrev = 0;
384
385 for ($i = 1; $i <= sizeof($this->rawoutput) - 1; $i++)
386 {
387 $line = $this->rawoutput["$i"];
388
389 if (preg_match('#^r([0-9]*) \| (.*?) \| (....-..-.. ..:..:..) ([0-9\-]*) \((.*?)\) \| ([0-9]*) lines?$#', $line, $matches))
390 {
391 if (isset($this->logs["$lastrev"]))
392 {
393 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
394 }
395
396 $this->logs["$matches[1]"] = array(
397 'rev' => $matches[1],
398 'author' => $matches[2],
399 'date' => $matches[3],
400 'timezone' => $matches[4],
401 'lines' => $matches[6],
402 'message' => ''
403 );
404
405 $lastrev = $matches[1];
406 }
407 else if (preg_match('#^\s+([ADMR])\s(.*)#', $line, $matches))
408 {
409 if (preg_match('#(.*) \(from (.*?)\)$#', $matches[2], $amatches))
410 {
411 $matches[2] = $amatches[1];
412 }
413
414 $this->logs["$lastrev"]['files'][] = array(
415 'action' => $matches[1],
416 'file' => trim($matches[2]),
417 'from' => (isset($amatches[2]) ? $amatches[2] : '')
418 );
419 }
420 else
421 {
422 if (trim($line) != 'Changed paths:')
423 {
424 $this->logs["$lastrev"]['message'] .= $line . "\n";
425 }
426 }
427 }
428
429 if (isset($this->logs["$lastrev"]))
430 {
431 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
432 }
433 }
434
435 /**
436 * Trims the last dash line off a message
437 *
438 * @access private
439 *
440 * @param string Message with annoying-ass line
441 *
442 * @return string Clean string
443 */
444 function strip_last_line($string)
445 {
446 return trim(preg_replace("#\n(.*?)\n$#", '', $string));
447 }
448 }
449
450 /**
451 * Diff system; constructs a diff array that
452 * is ready for output
453 *
454 * @package ViewSVN
455 */
456 class SVNDiff
457 {
458 /**
459 * Array of diff information
460 * @var array
461 */
462 var $diff = array();
463
464 /**
465 * Raw "svn diff" output
466 * @var array
467 */
468 var $rawoutput;
469
470 /**
471 * Constructor: create and store diff data
472 *
473 * @param string Repository
474 * @param string Path
475 * @param integer Lower revision
476 * @param integer Higher revision
477 */
478 function SVNDiff($repos, $path, $lorev, $hirev)
479 {
480 global $viewsvn;
481
482 $this->rawoutput = $viewsvn->svn->diff($repos, $path, $lorev, $hirev);
483 $this->process();
484 }
485
486 /**
487 * Returns diffs for display
488 *
489 * @access public
490 *
491 * @return array Diff data
492 */
493 function fetch()
494 {
495 return $this->diff;
496 }
497
498 /**
499 * Processes and prepares diff data
500 *
501 * @access private
502 */
503 function process()
504 {
505 global $viewsvn;
506
507 $chunk = 0;
508 $indexcounter = null;
509 $curprop = '';
510
511 $delstack = array();
512
513 foreach ($this->rawoutput AS $line)
514 {
515 if (preg_match('#^@@ \-([0-9]*),([0-9]*) \+([0-9]*),([0-9]*) @@$#', $line, $bits))
516 {
517 $property = false;
518 $delstack = array();
519 $this->diff["$index"][ ++$chunk ]['hunk'] = array('old' => array('line' => $bits[1], 'count' => $bits[2]), 'new' => array('line' => $bits[3], 'count' => $bits[4]));
520 $lines['old'] = $this->diff["$index"]["$chunk"]['hunk']['old']['line'] - 1;
521 $lines['new'] = $this->diff["$index"]["$chunk"]['hunk']['new']['line'] - 1;
522 continue;
523 }
524 else if (preg_match('#^Property changes on: (.*?)$#', $line, $bits))
525 {
526 $property = true;
527 $index = $bits[1];
528 $this->diff["$index"]['props'] = array();
529 continue;
530 }
531
532 if ($indexcounter <= 3 AND $indexcounter !== null)
533 {
534 $indexcounter++;
535 continue;
536 }
537 else if ($indexcounter == 3)
538 {
539 $indexcounter = null;
540 continue;
541 }
542
543 if (preg_match('#^([\+\- ])(.*)#', $line, $matches) AND !$property)
544 {
545 $act = $matches[1];
546 $content = $matches[2];
547
548 if ($act == ' ')
549 {
550 $this->diff["$index"]["$chunk"][] = array(
551 'line' => $content,
552 'act' => '',
553 'oldlineno' => ++$lines['old'],
554 'newlineno' => ++$lines['new']
555 );
556
557 $delstack = array();
558 }
559 else if ($act == '+')
560 {
561 // potential line delta
562 if (sizeof($delstack) > 0)
563 {
564 $lastline = array_shift($delstack);
565
566 if ($delta = @$this->fetch_diff_extent($lastline['line'], $content))
567 {
568 if (strlen($lastline['line']) > ($delta['start'] - $delta['end']))
569 {
570 $end = strlen($lastline['line']) + $delta['end'];
571 $viewsvn->debug("RM delta- = " . $end);
572 $change = '{@-' . '-}' . substr($lastline['line'], $delta['start'], $end - $delta['start']) . '{/@-' . '-}';
573 $this->diff["$index"]["$chunk"]["$lastline[INDEX]"]['line'] = substr($lastline['line'], 0, $delta['start']) . $change . substr($lastline['line'], $end);
574 }
575
576 if (strlen($content) > $delta['start'] - $delta['end'])
577 {
578 $end = strlen($content) + $delta['end'];
579 $viewsvn->debug("MK delta+ = " . $end);
580 $change = '{@+' . '+}' . substr($content, $delta['start'], $end - $delta['start']) . '{/@+' . '+}';
581 $content = substr($content, 0, $delta['start']) . $change . substr($content, $end);
582 }
583 }
584 }
585
586 $this->diff["$index"]["$chunk"][] = array(
587 'line' => $content,
588 'act' => '+',
589 'oldlineno' => '',
590 'newlineno' => ++$lines['new']
591 );
592 }
593 else if ($act == '-')
594 {
595 $this->diff["$index"]["$chunk"][] = $thearray = array(
596 'line' => $content,
597 'act' => '-',
598 'oldlineno' => ++$lines['old'],
599 'newlineno' => ''
600 );
601
602 $key = sizeof($this->diff["$index"]["$chunk"]) - 2;
603 $thearray['INDEX'] = $key;
604
605 array_push($delstack, $thearray);
606 }
607 }
608 // whitespace lines
609 else
610 {
611 if (preg_match('#^Index: (.*?)$#', $line, $matches))
612 {
613 $index = $matches[1];
614 $indexcounter = 1;
615 $chunk = 0;
616 continue;
617 }
618
619 if ($property)
620 {
621 if (preg_match('#^__*_$#', trim($line)))
622 {
623 $viewsvn->debug("skipping: $line");
624 continue;
625 }
626
627 if (preg_match('#Name: (.*?)$#', $line, $matches))
628 {
629 $curprop = $matches[1];
630 $viewsvn->debug("prop: $curprop");
631 continue;
632 }
633 else
634 {
635 if (preg_match('#^\s+?\+(.*)#', $line, $matches))
636 {
637 $mode = 'add';
638 $this->diff["$index"]['props']["$curprop"]['add'] .= $matches[1];
639 }
640 else if (preg_match('#^\s+?\-(.*)#', $line, $matches))
641 {
642 $mode = 'del';
643 $this->diff["$index"]['props']["$curprop"]['del'] .= $matches[1];
644 }
645 else if (!preg_match('#^\s+[\+\- ](.*)#', $line) AND trim($line) != '')
646 {
647 $this->diff["$index"]['props']["$curprop"]["$mode"] .= "\n" . $line;
648 }
649 continue;
650 }
651 }
652
653 $this->diff["$index"]["$chunk"][] = array(
654 'line' => '',
655 'act' => '',
656 'oldlineno' => ++$lines['old'],
657 'newlineno' => ++$lines['new']
658 );
659
660 $delstack = array();
661 }
662 }
663 }
664
665 /**
666 * Returns the amount of change that occured
667 * between two lines
668 *
669 * @access private
670 *
671 * @param string Old line
672 * @param string New line
673 *
674 * @return array Difference of positions
675 */
676 function fetch_diff_extent($old, $new)
677 {
678 global $viewsvn;
679
680 $start = 0;
681 $min = min(strlen($old), strlen($new));
682
683 $viewsvn->debug("min1 = $min");
684
685 while ($start < $min AND $old["$start"] == $new["$start"])
686 {
687 $start++;
688 }
689
690 $end = -1;
691 $min = $min - $start;
692
693 $viewsvn->debug("min2 = $min");
694
695 $viewsvn->debug("checking: " . $old[ strlen($old) + $end ] . ' == ' . $new[ strlen($new) + $end ]);
696
697 while (-$end <= $min AND $old[ strlen($old) + $end ] == $new[ strlen($new) + $end ])
698 {
699 $end--;
700 }
701
702 return array('start' => $start, 'end' => $end + 1);
703 }
704 }
705
706 /*=====================================================================*\
707 || ###################################################################
708 || # $HeadURL$
709 || # $Id$
710 || ###################################################################
711 \*=====================================================================*/
712 ?>