- Got blame.php to work
[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(&$controller)
274 {
275 $this->rawoutput = $controller->library->command('blame');
276 $this->process();
277 }
278
279 /**
280 * Returns blame for display
281 *
282 * @access public
283 *
284 * @return array Blame data
285 */
286 function fetch()
287 {
288 return $this->blame;
289 }
290
291 /**
292 * Parses the blame data
293 *
294 * @access private
295 */
296 function process()
297 {
298 $lineno = 1;
299
300 foreach ($this->rawoutput AS $line)
301 {
302 if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)\s(.*)$#', $line, $matches))
303 {
304 $this->blame[] = array(
305 'rev' => $matches[1],
306 'author' => $matches[2],
307 'line' => $matches[3],
308 'lineno' => $lineno++
309 );
310 }
311 // a blank line
312 else if (preg_match('#^\s+([0-9]+)\s+([\w\.\-_]+)$#', $line, $matches))
313 {
314 $this->blame[] = array(
315 'rev' => $matches[1],
316 'author' => $matches[2],
317 'line' => '',
318 'lineno' => $lineno++
319 );
320 }
321 }
322 }
323 }
324
325 /**
326 * Log management system; creates a complex list
327 * of SVN log information
328 *
329 * @package ViewSVN
330 * @version $Id$
331 */
332 class SVNLog
333 {
334 /**
335 * Array of logs
336 * @var array
337 */
338 var $logs = array();
339
340 /**
341 * Raw "svn log" output
342 * @var array
343 */
344 var $rawoutput;
345
346 /**
347 * Constructor: create log store for the given file
348 *
349 * @param string Repository
350 * @param string Path
351 * @param integer Lower revision
352 * @param integer Higher revision
353 */
354 function SVNLog($repos, $path, $lorev, $hirev)
355 {
356 global $viewsvn;
357
358 $this->rawoutput = $viewsvn->svn->log($repos, $path, $lorev, $hirev);
359 $this->process();
360 }
361
362 /**
363 * Returns logs for display
364 *
365 * @access public
366 *
367 * @return array Log data
368 */
369 function fetch()
370 {
371 return $this->logs;
372 }
373
374 /**
375 * Splits up the raw output into a usable log
376 *
377 * @access private
378 */
379 function process()
380 {
381 $lastrev = 0;
382
383 for ($i = 1; $i <= sizeof($this->rawoutput) - 1; $i++)
384 {
385 $line = $this->rawoutput["$i"];
386
387 if (preg_match('#^r([0-9]*) \| (.*?) \| (....-..-.. ..:..:..) ([0-9\-]*) \((.*?)\) \| ([0-9]*) lines?$#', $line, $matches))
388 {
389 if (isset($this->logs["$lastrev"]))
390 {
391 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
392 }
393
394 $this->logs["$matches[1]"] = array(
395 'rev' => $matches[1],
396 'author' => $matches[2],
397 'date' => $matches[3],
398 'timezone' => $matches[4],
399 'lines' => $matches[6],
400 'message' => ''
401 );
402
403 $lastrev = $matches[1];
404 }
405 else if (preg_match('#^\s+([ADMR])\s(.*)#', $line, $matches))
406 {
407 if (preg_match('#(.*) \(from (.*?)\)$#', $matches[2], $amatches))
408 {
409 $matches[2] = $amatches[1];
410 }
411
412 $this->logs["$lastrev"]['files'][] = array(
413 'action' => $matches[1],
414 'file' => trim($matches[2]),
415 'from' => (isset($amatches[2]) ? $amatches[2] : '')
416 );
417 }
418 else
419 {
420 if (trim($line) != 'Changed paths:')
421 {
422 $this->logs["$lastrev"]['message'] .= $line . "\n";
423 }
424 }
425 }
426
427 if (isset($this->logs["$lastrev"]))
428 {
429 $this->logs["$lastrev"]['message'] = $this->strip_last_line($this->logs["$lastrev"]['message']);
430 }
431 }
432
433 /**
434 * Trims the last dash line off a message
435 *
436 * @access private
437 *
438 * @param string Message with annoying-ass line
439 *
440 * @return string Clean string
441 */
442 function strip_last_line($string)
443 {
444 return trim(preg_replace("#\n(.*?)\n$#", '', $string));
445 }
446 }
447
448 /**
449 * Diff system; constructs a diff array that
450 * is ready for output
451 *
452 * @package ViewSVN
453 */
454 class SVNDiff
455 {
456 /**
457 * Array of diff information
458 * @var array
459 */
460 var $diff = array();
461
462 /**
463 * Raw "svn diff" output
464 * @var array
465 */
466 var $rawoutput;
467
468 /**
469 * Constructor: create and store diff data
470 *
471 * @param string Repository
472 * @param string Path
473 * @param integer Lower revision
474 * @param integer Higher revision
475 */
476 function SVNDiff($repos, $path, $lorev, $hirev)
477 {
478 global $viewsvn;
479
480 $this->rawoutput = $viewsvn->svn->diff($repos, $path, $lorev, $hirev);
481 $this->process();
482 }
483
484 /**
485 * Returns diffs for display
486 *
487 * @access public
488 *
489 * @return array Diff data
490 */
491 function fetch()
492 {
493 return $this->diff;
494 }
495
496 /**
497 * Processes and prepares diff data
498 *
499 * @access private
500 */
501 function process()
502 {
503 global $viewsvn;
504
505 $chunk = 0;
506 $indexcounter = null;
507 $curprop = '';
508
509 $delstack = array();
510
511 foreach ($this->rawoutput AS $line)
512 {
513 if (preg_match('#^@@ \-([0-9]*),([0-9]*) \+([0-9]*),([0-9]*) @@$#', $line, $bits))
514 {
515 $property = false;
516 $delstack = array();
517 $this->diff["$index"][ ++$chunk ]['hunk'] = array('old' => array('line' => $bits[1], 'count' => $bits[2]), 'new' => array('line' => $bits[3], 'count' => $bits[4]));
518 $lines['old'] = $this->diff["$index"]["$chunk"]['hunk']['old']['line'] - 1;
519 $lines['new'] = $this->diff["$index"]["$chunk"]['hunk']['new']['line'] - 1;
520 continue;
521 }
522 else if (preg_match('#^Property changes on: (.*?)$#', $line, $bits))
523 {
524 $property = true;
525 $index = $bits[1];
526 $this->diff["$index"]['props'] = array();
527 continue;
528 }
529
530 if ($indexcounter <= 3 AND $indexcounter !== null)
531 {
532 $indexcounter++;
533 continue;
534 }
535 else if ($indexcounter == 3)
536 {
537 $indexcounter = null;
538 continue;
539 }
540
541 if (preg_match('#^([\+\- ])(.*)#', $line, $matches) AND !$property)
542 {
543 $act = $matches[1];
544 $content = $matches[2];
545
546 if ($act == ' ')
547 {
548 $this->diff["$index"]["$chunk"][] = array(
549 'line' => $content,
550 'act' => '',
551 'oldlineno' => ++$lines['old'],
552 'newlineno' => ++$lines['new']
553 );
554
555 $delstack = array();
556 }
557 else if ($act == '+')
558 {
559 // potential line delta
560 if (sizeof($delstack) > 0)
561 {
562 $lastline = array_shift($delstack);
563
564 if ($delta = @$this->fetch_diff_extent($lastline['line'], $content))
565 {
566 if (strlen($lastline['line']) > ($delta['start'] - $delta['end']))
567 {
568 $end = strlen($lastline['line']) + $delta['end'];
569 $viewsvn->debug("RM delta- = " . $end);
570 $change = '{@-' . '-}' . substr($lastline['line'], $delta['start'], $end - $delta['start']) . '{/@-' . '-}';
571 $this->diff["$index"]["$chunk"]["$lastline[INDEX]"]['line'] = substr($lastline['line'], 0, $delta['start']) . $change . substr($lastline['line'], $end);
572 }
573
574 if (strlen($content) > $delta['start'] - $delta['end'])
575 {
576 $end = strlen($content) + $delta['end'];
577 $viewsvn->debug("MK delta+ = " . $end);
578 $change = '{@+' . '+}' . substr($content, $delta['start'], $end - $delta['start']) . '{/@+' . '+}';
579 $content = substr($content, 0, $delta['start']) . $change . substr($content, $end);
580 }
581 }
582 }
583
584 $this->diff["$index"]["$chunk"][] = array(
585 'line' => $content,
586 'act' => '+',
587 'oldlineno' => '',
588 'newlineno' => ++$lines['new']
589 );
590 }
591 else if ($act == '-')
592 {
593 $this->diff["$index"]["$chunk"][] = $thearray = array(
594 'line' => $content,
595 'act' => '-',
596 'oldlineno' => ++$lines['old'],
597 'newlineno' => ''
598 );
599
600 $key = sizeof($this->diff["$index"]["$chunk"]) - 2;
601 $thearray['INDEX'] = $key;
602
603 array_push($delstack, $thearray);
604 }
605 }
606 // whitespace lines
607 else
608 {
609 if (preg_match('#^Index: (.*?)$#', $line, $matches))
610 {
611 $index = $matches[1];
612 $indexcounter = 1;
613 $chunk = 0;
614 continue;
615 }
616
617 if ($property)
618 {
619 if (preg_match('#^__*_$#', trim($line)))
620 {
621 $viewsvn->debug("skipping: $line");
622 continue;
623 }
624
625 if (preg_match('#Name: (.*?)$#', $line, $matches))
626 {
627 $curprop = $matches[1];
628 $viewsvn->debug("prop: $curprop");
629 continue;
630 }
631 else
632 {
633 if (preg_match('#^\s+?\+(.*)#', $line, $matches))
634 {
635 $mode = 'add';
636 $this->diff["$index"]['props']["$curprop"]['add'] .= $matches[1];
637 }
638 else if (preg_match('#^\s+?\-(.*)#', $line, $matches))
639 {
640 $mode = 'del';
641 $this->diff["$index"]['props']["$curprop"]['del'] .= $matches[1];
642 }
643 else if (!preg_match('#^\s+[\+\- ](.*)#', $line) AND trim($line) != '')
644 {
645 $this->diff["$index"]['props']["$curprop"]["$mode"] .= "\n" . $line;
646 }
647 continue;
648 }
649 }
650
651 $this->diff["$index"]["$chunk"][] = array(
652 'line' => '',
653 'act' => '',
654 'oldlineno' => ++$lines['old'],
655 'newlineno' => ++$lines['new']
656 );
657
658 $delstack = array();
659 }
660 }
661 }
662
663 /**
664 * Returns the amount of change that occured
665 * between two lines
666 *
667 * @access private
668 *
669 * @param string Old line
670 * @param string New line
671 *
672 * @return array Difference of positions
673 */
674 function fetch_diff_extent($old, $new)
675 {
676 global $viewsvn;
677
678 $start = 0;
679 $min = min(strlen($old), strlen($new));
680
681 $viewsvn->debug("min1 = $min");
682
683 while ($start < $min AND $old["$start"] == $new["$start"])
684 {
685 $start++;
686 }
687
688 $end = -1;
689 $min = $min - $start;
690
691 $viewsvn->debug("min2 = $min");
692
693 $viewsvn->debug("checking: " . $old[ strlen($old) + $end ] . ' == ' . $new[ strlen($new) + $end ]);
694
695 while (-$end <= $min AND $old[ strlen($old) + $end ] == $new[ strlen($new) + $end ])
696 {
697 $end--;
698 }
699
700 return array('start' => $start, 'end' => $end + 1);
701 }
702 }
703
704 /*=====================================================================*\
705 || ###################################################################
706 || # $HeadURL$
707 || # $Id$
708 || ###################################################################
709 \*=====================================================================*/
710 ?>