- added diff.php
[viewsvn.git] / includes / svnlib.php
1 <?php
2 /*=====================================================================*\
3 || ################################################################### ||
4 || # ViewSVN [#]version[#]
5 || # --------------------------------------------------------------- # ||
6 || # Copyright ©2002-[#]year[#] by Iris Studios, Inc. All Rights Reserved. # ||
7 || # This file may not be reproduced in any way without permission. # ||
8 || # --------------------------------------------------------------- # ||
9 || # User License Agreement at http://www.iris-studios.com/license/ # ||
10 || ################################################################### ||
11 \*=====================================================================*/
12
13 /**
14 * Command line interface with the SVN commands
15 *
16 * @package ViewSVN
17 */
18
19 /**
20 * Interacts with the command line subsystem to
21 * access SVN information
22 *
23 * @package ViewSVN
24 * @version $Id$
25 */
26 class SVNLib
27 {
28 /**
29 * Path to the SVN binary
30 * @var string
31 */
32 var $svnpath;
33
34 /**
35 * Common command system
36 * @var object
37 */
38 var $common;
39
40 /**
41 * Constructor: validate SVN path
42 *
43 * @param string Path to SVN binary
44 */
45 function SVNLib($svnpath)
46 {
47 global $viewsvn;
48
49 $this->svnpath = $viewsvn->shell->cmd($svnpath);
50
51 $this->common =& new SVNCommon();
52
53 $access = $viewsvn->shell->exec($this->svnpath . ' --version');
54
55 if (!$access)
56 {
57 $viewsvn->trigger->error('svn binary could not be found');
58 }
59
60 if (!preg_match('#^svn, version (.*?)\)$#i', trim($access[0])))
61 {
62 $viewsvn->trigger->error('svn binary does not pass test');
63 }
64 }
65
66 /**
67 * Prepares data for output
68 *
69 * @access public
70 *
71 * @param string Standard data
72 *
73 * @return string Output-ready data
74 */
75 function format($string)
76 {
77 // convert entities
78 $string = htmlspecialchars($string);
79
80 // tabs to 5 spaces
81 $string = str_replace("\t", ' ', $string);
82
83 // spaces to nbsp
84 $string = str_replace(' ', '&nbsp;', $string);
85
86 // convert advanced diff
87 $string = str_replace(array('{@++}', '{@--}'), array('<span class="diff_add">', '<span class="diff_del">'), $string);
88 $string = str_replace(array('{/@++}', '{/@--}'), '</span>', $string);
89
90 // nl2br
91 $string = nl2br($string);
92
93 return $string;
94 }
95
96 /**
97 * Executes the SVN binary
98 *
99 * @access private
100 *
101 * @param string Command
102 *
103 * @return array Output
104 */
105 function svn($command)
106 {
107 global $viewsvn;
108
109 $output = $viewsvn->shell->exec($this->svnpath . ' ' . $command . ' 2>&1');
110 $temp = implode("\n", $output);
111 if (strpos($temp, 'apr_error=') !== false OR strpos($temp, 'svn:') !== false)
112 {
113 $viewsvn->trigger->error(nl2br($temp));
114 }
115 return $output;
116 }
117
118 /**
119 * SVN Wrapper: standard command system
120 *
121 * @access private
122 *
123 * @param string SVN command
124 * @param string Repository
125 * @param string Path
126 * @param integer Revision
127 *
128 * @return array Lines of output
129 */
130 function std($command, $repos, $path, $revision)
131 {
132 global $viewsvn;
133
134 $revision = $this->rev($revision);
135 $repospath = $viewsvn->repos->fetch_path($repos, false);
136
137 return $this->svn($command . ' -r' . $revision . ' ' . $repospath . $path);
138 }
139
140 /**
141 * SVN Wrapper: blame
142 *
143 * @access protected
144 *
145 * @param string Repository
146 * @param string Path
147 * @param integer Revision
148 *
149 * @return array Lines of blame output
150 */
151 function blame($repos, $path, $revision)
152 {
153 return $this->std('blame', $repos, $path, $revision);
154 }
155
156 /**
157 * SVN Wrapper: cat
158 *
159 * @access protected
160 *
161 * @param string Repository
162 * @param string Path
163 * @param integer Revision
164 *
165 * @return array Lines of cat output
166 */
167 function cat($repos, $path, $revision)
168 {
169 return $this->std('cat', $repos, $path, $revision);
170 }
171
172 /**
173 * SVN Wrapper: diff
174 *
175 * @access protected
176 *
177 * @param string Repository
178 * @param string Path
179 * @param integer Lower revision
180 * @param integer Higher revision
181 *
182 * @return array Lines of diff output
183 */
184 function diff($repos, $path, $lorev, $hirev)
185 {
186 global $viewsvn;
187
188 $hirev = $this->rev($hirev);
189 $lorev = $this->rev($lorev);
190 if ($lorev == 'HEAD')
191 {
192 $lorev = 1;
193 }
194
195 if (is_integer($hirev) AND is_integer($lorev))
196 {
197 if ($lorev > $hirev)
198 {
199 $lorev = $hirev - 1;
200 }
201 if ($lorev == $hirev)
202 {
203 $lorev = 0;
204 }
205 }
206
207 $repospath = $viewsvn->repos->fetch_path($repos, false);
208
209 return $this->svn('diff -r' . $lorev . ':' . $hirev . ' ' . $repospath . $path);
210 }
211
212 /**
213 * SVN Wrapper: log
214 *
215 * @access protected
216 *
217 * @param string Repository
218 * @param string Path
219 * @param integer Lower revision
220 * @param integer Higher revision
221 *
222 * @return array Lines of log output
223 */
224 function log($repos, $path, $lorev, $hirev)
225 {
226 global $viewsvn;
227
228 $hirev = $this->rev($hirev);
229 $lorev = $this->rev($hirev);
230 if ($lorev == 'HEAD')
231 {
232 $lorev = 0;
233 }
234
235 if (is_integer($hirev) AND is_integer($lorev))
236 {
237 if ($lorev > $hirev)
238 {
239 $lorev = $hirev - 1;
240 }
241 if ($lorev == $hirev)
242 {
243 $lorev = 0;
244 }
245 }
246
247 $repospath = $viewsvn->repos->fetch_path($repos, false);
248
249 return $this->svn('log -r' . $hirev . ':' . $lorev . ' ' . $repospath . $path);
250 }
251
252 /**
253 * SVN Wrapper: ls (list)
254 *
255 * @access protected
256 *
257 * @param string Repository
258 * @param string Path
259 * @param integer Revision
260 *
261 * @return array Lines of list output
262 */
263 function ls($repos, $path, $revision)
264 {
265 return $this->std('list', $repos, $path, $revision);
266 }
267
268 /**
269 * Generates a clean revision number
270 *
271 * @access public
272 *
273 * @param integer Revision number
274 *
275 * @return mixed Cleaned revision or HEAD
276 */
277 function rev($revision)
278 {
279 if (($revision = intval($revision)) < 1)
280 {
281 $revision = 'HEAD';
282 }
283 return $revision;
284 }
285 }
286
287 /**
288 * Commonly executed SVN commands that return data
289 * used in many parts of the system
290 *
291 * @package ViewSVN
292 * @version $Id$
293 */
294 class SVNCommon
295 {
296 /**
297 * Registry object
298 * @var object
299 */
300 var $registry;
301
302 /**
303 * List of revisions
304 * @var array
305 */
306 var $revisions;
307
308 /**
309 * List of logs
310 * @var array
311 */
312 var $logs;
313
314 /**
315 * Constructor: bind with registry
316 */
317 function SVNCommon()
318 {
319 global $viewsvn;
320
321 $this->registry =& $viewsvn;
322 }
323
324 /**
325 * Checks to see if the given universal path is
326 * a directory
327 *
328 * @access public
329 *
330 * @param string Universal path
331 *
332 * @return bool Directory or not
333 */
334 function isdir($path)
335 {
336 $output = $this->registry->svn->cat($this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 'HEAD');
337 $output = implode("\n", $output);
338 if (strpos($output, 'svn:') === false)
339 {
340 return false;
341 }
342 else
343 {
344 return true;
345 }
346 }
347
348 /**
349 * Get a list of revisions for a path
350 *
351 * @access public
352 *
353 * @param string Universal path
354 *
355 * @return array Key revisions
356 */
357 function fetch_revs($path)
358 {
359 if (!isset($this->revisions["$path"]))
360 {
361 $log = new SVNLog($this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 0, 0);
362
363 $revs = array_keys($log->fetch());
364
365 $this->revisions["$path"] = array(
366 'HEAD' => $revs[0],
367 'START' => $revs[ count($revs) - 1 ],
368 'revs' => $revs
369 );
370 }
371
372 return $this->revisions["$path"];
373 }
374
375 /**
376 * Gets the revision that is marked as HEAD
377 *
378 * @access public
379 *
380 * @param string Universal path
381 *
382 * @return integer Revision
383 */
384 function fetch_head_rev($path)
385 {
386 $revs = $this->fetch_revs($path);
387 return $revs['HEAD'];
388 }
389
390 /**
391 * Returns the previous revision to the one given
392 *
393 * @access public
394 *
395 * @param string Universal path
396 * @param integer Arbitrary revision
397 *
398 * @return integer Previous revision (-1 if none)
399 */
400 function fetch_prev_rev($path, $current)
401 {
402 $revs = $this->fetch_revs($path);
403
404 $index = array_search($current, $revs['revs']);
405 if ($current === false)
406 {
407 $message->trigger->error('revision ' . $current . ' is not in ' . $path);
408 }
409
410 if (isset($revs['revs'][ $index + 1 ]))
411 {
412 return $revs['revs'][ $index + 1 ];
413 }
414 else
415 {
416 return -1;
417 }
418 }
419
420 /**
421 * Get a list of logs
422 *
423 * @access public
424 *
425 * @param string Universal path
426 *
427 * @return array Log data
428 */
429 function fetch_logs($path)
430 {
431 if (!isset($this->logs["$path"]))
432 {
433 $log = new SVNLog($this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 0, 0);
434
435 $this->logs["$path"] = $log->fetch();
436 }
437
438 return $this->logs["$path"];
439 }
440
441 /**
442 * Returns a given log entry for a path
443 * and revision
444 *
445 * @access public
446 *
447 * @param string Universal path
448 * @param integer Arbitrary revision
449 *
450 * @return array Log entry
451 */
452 function fetch_log($path, $rev)
453 {
454 $logs = $this->fetch_logs($path);
455
456 $rev = $this->registry->svn->rev($rev);
457 if ($rev == 'HEAD')
458 {
459 $rev = $this->fetch_head_rev($path);
460 }
461
462 if (isset($logs["$rev"]))
463 {
464 return $logs["$rev"];
465 }
466 else
467 {
468 return null;
469 }
470 }
471 }
472
473 /**
474 * Annotation/blame system; constructs an array
475 * that is ready for output
476 *
477 * @package ViewSVN
478 * @version $Id$
479 */
480 class SVNBlame
481 {
482 /**
483 * Array of blame information
484 * @var array
485 */
486 var $blame = array();
487
488 /**
489 * Raw "svn blame" output
490 * @var array
491 */
492 var $rawoutput;
493
494 /**
495 * Constructor: create blame and store data
496 *
497 * @param string Repository
498 * @param string Path
499 * @param integer Revision
500 */
501 function SVNBlame($repos, $path, $revision)
502 {
503 global $viewsvn;
504
505 $this->rawoutput = $viewsvn->svn->blame($repos, $path, $revision);
506 $this->process();
507 }
508
509 /**
510 * Returns blame for display
511 *
512 * @access public
513 *
514 * @return array Blame data
515 */
516 function fetch()
517 {
518 return $this->blame;
519 }
520
521 /**
522 * Parses the blame data
523 *
524 * @access private
525 */
526 function process()
527 {
528 $lineno = 1;
529
530 foreach ($this->rawoutput AS $line)
531 {
532 if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)\s(.*)$#', $line, $matches))
533 {
534 $this->blame[] = array(
535 'rev' => $matches[1],
536 'author' => $matches[2],
537 'line' => $matches[3],
538 'lineno' => $lineno++
539 );
540 }
541 // a blank line
542 else if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)$#', $line, $matches))
543 {
544 $this->blame[] = array(
545 'rev' => $matches[1],
546 'author' => $matches[2],
547 'line' => '',
548 'lineno' => $lineno++
549 );
550 }
551 }
552 }
553 }
554
555 /**
556 * Log management system; creates a complex list
557 * of SVN log information
558 *
559 * @package ViewSVN
560 * @version $Id$
561 */
562 class SVNLog
563 {
564 /**
565 * Array of logs
566 * @var array
567 */
568 var $logs = array();
569
570 /**
571 * Raw "svn log" output
572 * @var array
573 */
574 var $rawoutput;
575
576 /**
577 * Constructor: create log store for the given file
578 *
579 * @param string Repository
580 * @param string Path
581 * @param integer Lower revision
582 * @param integer Higher revision
583 */
584 function SVNLog($repos, $path, $lorev, $hirev)
585 {
586 global $viewsvn;
587
588 $this->rawoutput = $viewsvn->svn->log($repos, $path, $lorev, $hirev);
589 $this->process();
590 }
591
592 /**
593 * Returns logs for display
594 *
595 * @access public
596 *
597 * @return array Log data
598 */
599 function fetch()
600 {
601 return $this->logs;
602 }
603
604 /**
605 * Splits up the raw output into a usable log
606 *
607 * @access private
608 */
609 function process()
610 {
611 $lastrev = 0;
612
613 for ($i = 1; $i <= count($this->rawoutput) - 1; $i++)
614 {
615 $line = $this->rawoutput["$i"];
616
617 if (preg_match('#^r([0-9]*) \| (.*?) \| (....-..-.. ..:..:..) ([0-9\-]*) \((.*?)\) \| ([0-9]*) lines?$#', $line, $matches))
618 {
619 if (isset($this->logs["$lastrev"]))
620 {
621 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
622 }
623
624 $this->logs["$matches[1]"] = array(
625 'rev' => $matches[1],
626 'author' => $matches[2],
627 'date' => $matches[3],
628 'timezone' => $matches[4],
629 'lines' => $matches[6],
630 'message' => ''
631 );
632
633 $lastrev = $matches[1];
634 }
635 else
636 {
637 $this->logs["$lastrev"]['message'] .= $line . "\n";
638 }
639 }
640
641 if (isset($this->logs["$lastrev"]))
642 {
643 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
644 }
645 }
646
647 /**
648 * Trims the last dash line off a message
649 *
650 * @access private
651 *
652 * @param string Message with annoying-ass line
653 *
654 * @return string Clean string
655 */
656 function strip_last_line($string)
657 {
658 return trim(preg_replace("#\n(.*?)\n$#", '', $string));
659 }
660 }
661
662 /**
663 * Diff system; constructs a diff array that
664 * is ready for output
665 *
666 * @package ViewSVN
667 */
668 class SVNDiff
669 {
670 /**
671 * Array of diff information
672 * @var array
673 */
674 var $diff = array();
675
676 /**
677 * Raw "svn diff" output
678 * @var array
679 */
680 var $rawoutput;
681
682 /**
683 * Constructor: create and store diff data
684 *
685 * @param string Repository
686 * @param string Path
687 * @param integer Lower revision
688 * @param integer Higher revision
689 */
690 function SVNDiff($repos, $path, $lorev, $hirev)
691 {
692 global $viewsvn;
693
694 $this->rawoutput = $viewsvn->svn->diff($repos, $path, $lorev, $hirev);
695 $this->process();
696 }
697
698 /**
699 * Returns diffs for display
700 *
701 * @access public
702 *
703 * @return array Diff data
704 */
705 function fetch()
706 {
707 return $this->diff;
708 }
709
710 /**
711 * Processes and prepares diff data
712 *
713 * @access private
714 */
715 function process()
716 {
717 $chunk = 0;
718 $indexcounter = null;
719
720 $lastact = '';
721 $lastcontent = '';
722
723 foreach ($this->rawoutput AS $line)
724 {
725 if (preg_match('#^@@ \-([0-9]*),([0-9]*) \+([0-9]*),([0-9]*) @@$#', $line, $bits))
726 {
727 $lastact = '';
728 $lastcontent = '';
729
730 $this->diff["$index"][ ++$chunk ]['hunk'] = array('old' => array('line' => $bits[1], 'count' => $bits[2]), 'new' => array('line' => $bits[3], 'count' => $bits[4]));
731 $lines['old'] = $this->diff["$index"]["$chunk"]['hunk']['old']['line'] - 1;
732 $lines['new'] = $this->diff["$index"]["$chunk"]['hunk']['new']['line'] - 1;
733 continue;
734 }
735
736 if ($indexcounter <= 5 AND $indexcounter !== null)
737 {
738 $indexcounter++;
739 continue;
740 }
741 else if ($indexcounter == 5)
742 {
743 $indexcounter = null;
744 continue;
745 }
746
747 if (preg_match('#^([\+\- ])(.*)#', $line, $matches))
748 {
749 $act = $matches[1];
750 $content = $matches[2];
751
752 if ($act == ' ')
753 {
754 $this->diff["$index"]["$chunk"][] = array(
755 'line' => $content,
756 'act' => '',
757 'oldlineno' => ++$lines['old'],
758 'newlineno' => ++$lines['new']
759 );
760 }
761 else if ($act == '+')
762 {
763 // potential line delta
764 if ($lastact == '-')
765 {
766 if ($delta = @$this->fetch_diff_extent($lastcontent, $content))
767 {
768 // create two sets of ends for the two contents
769 $delta['endo'] = strlen($lastcontent) - $delta['end'];
770 $delta['endn'] = strlen($content) - $delta['end'];
771
772 $diffo = $delta['endo'] - $delta['start'];
773 $diffn = $delta['endn'] - $delta['start'];
774
775 if (strlen($lastcontent) > $delta['endo'] - $diffo)
776 {
777 $removed = substr($lastcontent, $delta['start'], $diffo);
778 $this->diff["$index"]["$chunk"][ count($this->diff["$index"]["$chunk"]) - 2 ]['line'] = substr_replace($lastcontent, '{@--}' . $removed . '{/@--}', $delta['start'], $diffo);
779 }
780
781 if (strlen($content) > $delta['endn'] - $diffn)
782 {
783 $added = substr($content, $delta['start'], $diffn);
784 $content = substr_replace($content, '{@++}' . $added . '{/@++}', $delta['start'], $diffn);
785 }
786 }
787 }
788
789 $this->diff["$index"]["$chunk"][] = array(
790 'line' => $content,
791 'act' => '+',
792 'oldlineno' => '',
793 'newlineno' => ++$lines['new']
794 );
795 }
796 else if ($act == '-')
797 {
798 $lastcontent = $content;
799
800 $this->diff["$index"]["$chunk"][] = array(
801 'line' => $content,
802 'act' => '-',
803 'oldlineno' => ++$lines['old'],
804 'newlineno' => ''
805 );
806 }
807
808 $lastact = $act;
809 }
810 // whitespace lines
811 else
812 {
813 if (preg_match('#^Index: (.*?)$#', $line, $matches))
814 {
815 $index = $matches[1];
816 $indexcounter = 1;
817 $chunk = 0;
818 continue;
819 }
820
821 $lastact = '';
822
823 $this->diff["$index"]["$chunk"][] = array(
824 'line' => '',
825 'act' => '',
826 'oldlineno' => ++$lines['old'],
827 'newlineno' => ++$lines['new']
828 );
829 }
830 }
831 }
832
833 /**
834 * Returns the amount of change that occured
835 * between two lines
836 *
837 * @access private
838 *
839 * @param string Old line
840 * @param string New line
841 *
842 * @return array Difference of positions
843 */
844 function fetch_diff_extent($old, $new)
845 {
846 $start = 0;
847 $min = min(strlen($old), strlen($new));
848
849 for ($start = 0; $start < $min; $start++)
850 {
851 if ($old{"$start"} != $new{"$start"})
852 {
853 break;
854 }
855 }
856
857 $max = max(strlen($old), strlen($new));
858
859 for ($end = 0; $end < $min; $end++)
860 {
861 $oldpos = strlen($old) - $end;
862 $newpos = strlen($new) - $end;
863
864 if ($old{"$oldpos"} != $new{"$newpos"})
865 {
866 break;
867 }
868 }
869
870 $end--;
871
872 if ($start == 0 AND $end == $max)
873 {
874 return false;
875 }
876
877 return array('start' => $start, 'end' => $end);
878 }
879 }
880
881 /*=====================================================================*\
882 || ###################################################################
883 || # $HeadURL$
884 || # $Id$
885 || ###################################################################
886 \*=====================================================================*/
887 ?>