svnlib::common::isdir() speed up
[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_err=') !== 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 -v -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->std('info', $this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 'HEAD');
337
338 foreach ($output AS $line)
339 {
340 if (preg_match('#^Node Kind: (.*)#', $line, $matches))
341 {
342 if (trim(strtolower($matches[1])) == 'directory')
343 {
344 return true;
345 }
346 }
347 }
348
349 return false;
350 }
351
352 /**
353 * Get a list of revisions for a path
354 *
355 * @access public
356 *
357 * @param string Universal path
358 *
359 * @return array Key revisions
360 */
361 function fetch_revs($path)
362 {
363 if (!isset($this->revisions["$path"]))
364 {
365 $log = $this->fetch_logs($path);
366
367 $revs = array_keys($log);
368
369 $this->revisions["$path"] = array(
370 'HEAD' => $revs[0],
371 'START' => $revs[ count($revs) - 1 ],
372 'revs' => $revs
373 );
374 }
375
376 return $this->revisions["$path"];
377 }
378
379 /**
380 * Gets the revision that is marked as HEAD
381 *
382 * @access public
383 *
384 * @param string Universal path
385 *
386 * @return integer Revision
387 */
388 function fetch_head_rev($path)
389 {
390 $revs = $this->fetch_revs($path);
391 return $revs['HEAD'];
392 }
393
394 /**
395 * Returns the previous revision to the one given
396 *
397 * @access public
398 *
399 * @param string Universal path
400 * @param integer Arbitrary revision
401 *
402 * @return integer Previous revision (-1 if none)
403 */
404 function fetch_prev_rev($path, $current)
405 {
406 $revs = $this->fetch_revs($path);
407
408 $index = array_search($current, $revs['revs']);
409 if ($current === false)
410 {
411 $message->trigger->error('revision ' . $current . ' is not in ' . $path);
412 }
413
414 if (isset($revs['revs'][ $index + 1 ]))
415 {
416 return $revs['revs'][ $index + 1 ];
417 }
418 else
419 {
420 return -1;
421 }
422 }
423
424 /**
425 * Get a list of logs
426 *
427 * @access public
428 *
429 * @param string Universal path
430 *
431 * @return array Log data
432 */
433 function fetch_logs($path)
434 {
435 if (!isset($this->logs["$path"]))
436 {
437 $log = new SVNLog($this->registry->paths->fetch_repos($path), $this->registry->paths->fetch_path($path), 0, 0);
438
439 $this->logs["$path"] = $log->fetch();
440 }
441
442 return $this->logs["$path"];
443 }
444
445 /**
446 * Returns a given log entry for a path
447 * and revision
448 *
449 * @access public
450 *
451 * @param string Universal path
452 * @param integer Arbitrary revision
453 *
454 * @return array Log entry
455 */
456 function fetch_log($path, $rev)
457 {
458 $logs = $this->fetch_logs($path);
459
460 $rev = $this->registry->svn->rev($rev);
461 if ($rev == 'HEAD')
462 {
463 $rev = $this->fetch_head_rev($path);
464 }
465
466 if (isset($logs["$rev"]))
467 {
468 return $logs["$rev"];
469 }
470 else
471 {
472 return null;
473 }
474 }
475 }
476
477 /**
478 * Annotation/blame system; constructs an array
479 * that is ready for output
480 *
481 * @package ViewSVN
482 * @version $Id$
483 */
484 class SVNBlame
485 {
486 /**
487 * Array of blame information
488 * @var array
489 */
490 var $blame = array();
491
492 /**
493 * Raw "svn blame" output
494 * @var array
495 */
496 var $rawoutput;
497
498 /**
499 * Constructor: create blame and store data
500 *
501 * @param string Repository
502 * @param string Path
503 * @param integer Revision
504 */
505 function SVNBlame($repos, $path, $revision)
506 {
507 global $viewsvn;
508
509 $this->rawoutput = $viewsvn->svn->blame($repos, $path, $revision);
510 $this->process();
511 }
512
513 /**
514 * Returns blame for display
515 *
516 * @access public
517 *
518 * @return array Blame data
519 */
520 function fetch()
521 {
522 return $this->blame;
523 }
524
525 /**
526 * Parses the blame data
527 *
528 * @access private
529 */
530 function process()
531 {
532 $lineno = 1;
533
534 foreach ($this->rawoutput AS $line)
535 {
536 if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)\s(.*)$#', $line, $matches))
537 {
538 $this->blame[] = array(
539 'rev' => $matches[1],
540 'author' => $matches[2],
541 'line' => $matches[3],
542 'lineno' => $lineno++
543 );
544 }
545 // a blank line
546 else if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)$#', $line, $matches))
547 {
548 $this->blame[] = array(
549 'rev' => $matches[1],
550 'author' => $matches[2],
551 'line' => '',
552 'lineno' => $lineno++
553 );
554 }
555 }
556 }
557 }
558
559 /**
560 * Log management system; creates a complex list
561 * of SVN log information
562 *
563 * @package ViewSVN
564 * @version $Id$
565 */
566 class SVNLog
567 {
568 /**
569 * Array of logs
570 * @var array
571 */
572 var $logs = array();
573
574 /**
575 * Raw "svn log" output
576 * @var array
577 */
578 var $rawoutput;
579
580 /**
581 * Constructor: create log store for the given file
582 *
583 * @param string Repository
584 * @param string Path
585 * @param integer Lower revision
586 * @param integer Higher revision
587 */
588 function SVNLog($repos, $path, $lorev, $hirev)
589 {
590 global $viewsvn;
591
592 $this->rawoutput = $viewsvn->svn->log($repos, $path, $lorev, $hirev);
593 $this->process();
594 }
595
596 /**
597 * Returns logs for display
598 *
599 * @access public
600 *
601 * @return array Log data
602 */
603 function fetch()
604 {
605 return $this->logs;
606 }
607
608 /**
609 * Splits up the raw output into a usable log
610 *
611 * @access private
612 */
613 function process()
614 {
615 $lastrev = 0;
616
617 for ($i = 1; $i <= count($this->rawoutput) - 1; $i++)
618 {
619 $line = $this->rawoutput["$i"];
620
621 if (preg_match('#^r([0-9]*) \| (.*?) \| (....-..-.. ..:..:..) ([0-9\-]*) \((.*?)\) \| ([0-9]*) lines?$#', $line, $matches))
622 {
623 if (isset($this->logs["$lastrev"]))
624 {
625 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
626 }
627
628 $this->logs["$matches[1]"] = array(
629 'rev' => $matches[1],
630 'author' => $matches[2],
631 'date' => $matches[3],
632 'timezone' => $matches[4],
633 'lines' => $matches[6],
634 'message' => ''
635 );
636
637 $lastrev = $matches[1];
638 }
639 else if (preg_match('#^\s+([ADM])\s(.*)#', $line, $matches))
640 {
641 $this->logs["$lastrev"]['files'][] = array(
642 'action' => $matches[1],
643 'file' => $matches[2]
644 );
645 }
646 else
647 {
648 if (trim($line) != 'Changed paths:')
649 {
650 $this->logs["$lastrev"]['message'] .= $line . "\n";
651 }
652 }
653 }
654
655 if (isset($this->logs["$lastrev"]))
656 {
657 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
658 }
659 }
660
661 /**
662 * Trims the last dash line off a message
663 *
664 * @access private
665 *
666 * @param string Message with annoying-ass line
667 *
668 * @return string Clean string
669 */
670 function strip_last_line($string)
671 {
672 return trim(preg_replace("#\n(.*?)\n$#", '', $string));
673 }
674 }
675
676 /**
677 * Diff system; constructs a diff array that
678 * is ready for output
679 *
680 * @package ViewSVN
681 */
682 class SVNDiff
683 {
684 /**
685 * Array of diff information
686 * @var array
687 */
688 var $diff = array();
689
690 /**
691 * Raw "svn diff" output
692 * @var array
693 */
694 var $rawoutput;
695
696 /**
697 * Constructor: create and store diff data
698 *
699 * @param string Repository
700 * @param string Path
701 * @param integer Lower revision
702 * @param integer Higher revision
703 */
704 function SVNDiff($repos, $path, $lorev, $hirev)
705 {
706 global $viewsvn;
707
708 $this->rawoutput = $viewsvn->svn->diff($repos, $path, $lorev, $hirev);
709 $this->process();
710 }
711
712 /**
713 * Returns diffs for display
714 *
715 * @access public
716 *
717 * @return array Diff data
718 */
719 function fetch()
720 {
721 return $this->diff;
722 }
723
724 /**
725 * Processes and prepares diff data
726 *
727 * @access private
728 */
729 function process()
730 {
731 $chunk = 0;
732 $indexcounter = null;
733
734 $lastact = '';
735 $lastcontent = '';
736
737 foreach ($this->rawoutput AS $line)
738 {
739 if (preg_match('#^@@ \-([0-9]*),([0-9]*) \+([0-9]*),([0-9]*) @@$#', $line, $bits))
740 {
741 $lastact = '';
742 $lastcontent = '';
743
744 $this->diff["$index"][ ++$chunk ]['hunk'] = array('old' => array('line' => $bits[1], 'count' => $bits[2]), 'new' => array('line' => $bits[3], 'count' => $bits[4]));
745 $lines['old'] = $this->diff["$index"]["$chunk"]['hunk']['old']['line'] - 1;
746 $lines['new'] = $this->diff["$index"]["$chunk"]['hunk']['new']['line'] - 1;
747 continue;
748 }
749
750 if ($indexcounter <= 5 AND $indexcounter !== null)
751 {
752 $indexcounter++;
753 continue;
754 }
755 else if ($indexcounter == 5)
756 {
757 $indexcounter = null;
758 continue;
759 }
760
761 if (preg_match('#^([\+\- ])(.*)#', $line, $matches))
762 {
763 $act = $matches[1];
764 $content = $matches[2];
765
766 if ($act == ' ')
767 {
768 $this->diff["$index"]["$chunk"][] = array(
769 'line' => $content,
770 'act' => '',
771 'oldlineno' => ++$lines['old'],
772 'newlineno' => ++$lines['new']
773 );
774 }
775 else if ($act == '+')
776 {
777 // potential line delta
778 if ($lastact == '-')
779 {
780 if ($delta = @$this->fetch_diff_extent($lastcontent, $content))
781 {
782 // create two sets of ends for the two contents
783 $delta['endo'] = strlen($lastcontent) - $delta['end'];
784 $delta['endn'] = strlen($content) - $delta['end'];
785
786 $diffo = $delta['endo'] - $delta['start'];
787 $diffn = $delta['endn'] - $delta['start'];
788
789 if (strlen($lastcontent) > $delta['endo'] - $diffo)
790 {
791 $removed = substr($lastcontent, $delta['start'], $diffo);
792 $this->diff["$index"]["$chunk"][ count($this->diff["$index"]["$chunk"]) - 2 ]['line'] = substr_replace($lastcontent, '{@--}' . $removed . '{/@--}', $delta['start'], $diffo);
793 }
794
795 if (strlen($content) > $delta['endn'] - $diffn)
796 {
797 $added = substr($content, $delta['start'], $diffn);
798 $content = substr_replace($content, '{@++}' . $added . '{/@++}', $delta['start'], $diffn);
799 }
800 }
801 }
802
803 $this->diff["$index"]["$chunk"][] = array(
804 'line' => $content,
805 'act' => '+',
806 'oldlineno' => '',
807 'newlineno' => ++$lines['new']
808 );
809 }
810 else if ($act == '-')
811 {
812 $lastcontent = $content;
813
814 $this->diff["$index"]["$chunk"][] = array(
815 'line' => $content,
816 'act' => '-',
817 'oldlineno' => ++$lines['old'],
818 'newlineno' => ''
819 );
820 }
821
822 $lastact = $act;
823 }
824 // whitespace lines
825 else
826 {
827 if (preg_match('#^Index: (.*?)$#', $line, $matches))
828 {
829 $index = $matches[1];
830 $indexcounter = 1;
831 $chunk = 0;
832 continue;
833 }
834
835 $lastact = '';
836
837 $this->diff["$index"]["$chunk"][] = array(
838 'line' => '',
839 'act' => '',
840 'oldlineno' => ++$lines['old'],
841 'newlineno' => ++$lines['new']
842 );
843 }
844 }
845 }
846
847 /**
848 * Returns the amount of change that occured
849 * between two lines
850 *
851 * @access private
852 *
853 * @param string Old line
854 * @param string New line
855 *
856 * @return array Difference of positions
857 */
858 function fetch_diff_extent($old, $new)
859 {
860 $start = 0;
861 $min = min(strlen($old), strlen($new));
862
863 for ($start = 0; $start < $min; $start++)
864 {
865 if ($old{"$start"} != $new{"$start"})
866 {
867 break;
868 }
869 }
870
871 $max = max(strlen($old), strlen($new));
872
873 for ($end = 0; $end < $min; $end++)
874 {
875 $oldpos = strlen($old) - $end;
876 $newpos = strlen($new) - $end;
877
878 if ($old{"$oldpos"} != $new{"$newpos"})
879 {
880 break;
881 }
882 }
883
884 $end--;
885
886 if ($start == 0 AND $end == $max)
887 {
888 return false;
889 }
890
891 return array('start' => $start, 'end' => $end);
892 }
893 }
894
895 /*=====================================================================*\
896 || ###################################################################
897 || # $HeadURL$
898 || # $Id$
899 || ###################################################################
900 \*=====================================================================*/
901 ?>