Fix diffurl links (cvsweb expects unescaped '/').
[ikiwiki] / IkiWiki / Plugin / cvs.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::cvs;
3
4 # Copyright (c) 2009 Amitai Schlair
5 # All rights reserved.
6 #
7 # This code is derived from software contributed to ikiwiki
8 # by Amitai Schlair.
9 #
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
12 # are met:
13 # 1. Redistributions of source code must retain the above copyright
14 #    notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 #    notice, this list of conditions and the following disclaimer in the
17 #    documentation and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY IKIWIKI AND CONTRIBUTORS ``AS IS''
20 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
23 # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29 # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 # SUCH DAMAGE.
31
32 use warnings;
33 use strict;
34 use IkiWiki;
35
36 use URI::Escape q{uri_escape_utf8};
37 use File::chdir;
38
39
40 # GENERAL PLUGIN API CALLS
41
42 sub import {
43         hook(type => "checkconfig", id => "cvs", call => \&checkconfig);
44         hook(type => "getsetup", id => "cvs", call => \&getsetup);
45         hook(type => "genwrapper", id => "cvs", call => \&genwrapper);
46
47         hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
48         hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
49         hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
50         hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
51         hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
52         hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
53         hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
54         hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
55         hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
56         hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
57         hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
58 }
59
60 sub checkconfig () {
61         if (! defined $config{cvspath}) {
62                 $config{cvspath}="ikiwiki";
63         }
64         if (exists $config{cvspath}) {
65                 # code depends on the path not having extraneous slashes
66                 $config{cvspath}=~tr#/#/#s;
67                 $config{cvspath}=~s/\/$//;
68                 $config{cvspath}=~s/^\///;
69         }
70         if (defined $config{cvs_wrapper} && length $config{cvs_wrapper}) {
71                 push @{$config{wrappers}}, {
72                         wrapper => $config{cvs_wrapper},
73                         wrappermode => (defined $config{cvs_wrappermode} ? $config{cvs_wrappermode} : "04755"),
74                 };
75         }
76 }
77
78 sub getsetup () {
79         return
80                 plugin => {
81                         safe => 0, # rcs plugin
82                         rebuild => undef,
83                         section => "rcs",
84                 },
85                 cvsrepo => {
86                         type => "string",
87                         example => "/cvs/wikirepo",
88                         description => "cvs repository location",
89                         safe => 0, # path
90                         rebuild => 0,
91                 },
92                 cvspath => {
93                         type => "string",
94                         example => "ikiwiki",
95                         description => "path inside repository where the wiki is located",
96                         safe => 0, # paranoia
97                         rebuild => 0,
98                 },
99                 cvs_wrapper => {
100                         type => "string",
101                         example => "/cvs/wikirepo/CVSROOT/post-commit",
102                         description => "cvs post-commit hook to generate (triggered by CVSROOT/loginfo entry)",
103                         safe => 0, # file
104                         rebuild => 0,
105                 },
106                 cvs_wrappermode => {
107                         type => "string",
108                         example => '04755',
109                         description => "mode for cvs_wrapper (can safely be made suid)",
110                         safe => 0,
111                         rebuild => 0,
112                 },
113                 historyurl => {
114                         type => "string",
115                         example => "http://cvs.example.org/cvsweb.cgi/ikiwiki/[[file]]",
116                         description => "cvsweb url to show file history ([[file]] substituted)",
117                         safe => 1,
118                         rebuild => 1,
119                 },
120                 diffurl => {
121                         type => "string",
122                         example => "http://cvs.example.org/cvsweb.cgi/ikiwiki/[[file]].diff?r1=text&tr1=[[r1]]&r2=text&tr2=[[r2]]",
123                         description => "cvsweb url to show a diff ([[file]], [[r1]], and [[r2]] substituted)",
124                         safe => 1,
125                         rebuild => 1,
126                 },
127 }
128
129 sub genwrapper () {
130         return <<EOF;
131         {
132                 int j;
133                 for (j = 1; j < argc; j++)
134                         if (strstr(argv[j], "New directory") != NULL)
135                                 exit(0);
136         }
137 EOF
138 }
139
140
141 # VCS PLUGIN API CALLS
142
143 sub rcs_update () {
144         return unless cvs_is_controlling();
145         cvs_runcvs('update', '-dP');
146 }
147
148 sub rcs_prepedit ($) {
149         # Prepares to edit a file under revision control. Returns a token
150         # that must be passed into rcs_commit when the file is ready
151         # for committing.
152         # The file is relative to the srcdir.
153         my $file=shift;
154
155         return unless cvs_is_controlling();
156
157         # For cvs, return the revision of the file when
158         # editing begins.
159         my $rev=cvs_info("Repository revision", "$file");
160         return defined $rev ? $rev : "";
161 }
162
163 sub rcs_commit (@) {
164         # Tries to commit the page; returns undef on _success_ and
165         # a version of the page with the rcs's conflict markers on failure.
166         # The file is relative to the srcdir.
167         my %params=@_;
168
169         return unless cvs_is_controlling();
170
171         # Check to see if the page has been changed by someone
172         # else since rcs_prepedit was called.
173         my ($oldrev)=$params{token}=~/^([0-9]+)$/; # untaint
174         my $rev=cvs_info("Repository revision", "$config{srcdir}/$params{file}");
175         if (defined $rev && defined $oldrev && $rev != $oldrev) {
176                 # Merge their changes into the file that we've
177                 # changed.
178                 cvs_runcvs('update', $params{file}) ||
179                         warn("cvs merge from $oldrev to $rev failed\n");
180         }
181
182         if (! cvs_runcvs('commit', '-m',
183                          IkiWiki::possibly_foolish_untaint(commitmessage(%params)))) {
184                 my $conflict=readfile("$config{srcdir}/$params{file}");
185                 cvs_runcvs('update', '-C', $params{file}) ||
186                         warn("cvs revert failed\n");
187                 return $conflict;
188         }
189
190         return undef # success
191 }
192
193 sub rcs_commit_staged (@) {
194         # Commits all staged changes. Changes can be staged using rcs_add,
195         # rcs_remove, and rcs_rename.
196         my %params=@_;
197
198         if (! cvs_runcvs('commit', '-m',
199                          IkiWiki::possibly_foolish_untaint(commitmessage(%params)))) {
200                 warn "cvs staged commit failed\n";
201                 return 1; # failure
202         }
203         return undef # success
204 }
205
206 sub rcs_add ($) {
207         # filename is relative to the root of the srcdir
208         my $file=shift;
209         my $parent=IkiWiki::dirname($file);
210         my @files_to_add = ($file);
211
212         until ((length($parent) == 0) || cvs_is_controlling("$config{srcdir}/$parent")){
213                 push @files_to_add, $parent;
214                 $parent = IkiWiki::dirname($parent);
215         }
216
217         while ($file = pop @files_to_add) {
218                 if (@files_to_add == 0) {
219                         cvs_runcvs('add', cvs_keyword_subst_args($file)) ||
220                                 warn("cvs add file $file failed\n");
221                 }
222                 else {
223                         cvs_runcvs('add', $file) ||
224                                 warn("cvs add dir $file failed\n");
225                 }
226         }
227 }
228
229 sub rcs_remove ($) {
230         # filename is relative to the root of the srcdir
231         my $file=shift;
232
233         return unless cvs_is_controlling();
234
235         cvs_runcvs('rm', '-f', $file) ||
236                 warn("cvs rm $file failed\n");
237 }
238
239 sub rcs_rename ($$) {
240         # filenames relative to the root of the srcdir
241         my ($src, $dest)=@_;
242
243         return unless cvs_is_controlling();
244
245         local $CWD = $config{srcdir};
246
247         if (system("mv", "$src", "$dest") != 0) {
248                 warn("filesystem rename failed\n");
249         }
250
251         rcs_add($dest);
252         rcs_remove($src);
253 }
254
255 sub rcs_recentchanges ($) {
256         my $num = shift;
257         my @ret;
258
259         return unless cvs_is_controlling();
260
261         eval q{use Date::Parse};
262         error($@) if $@;
263
264         local $CWD = $config{srcdir};
265
266         # There's no cvsps option to get the last N changesets.
267         # Write full output to a temp file and read backwards.
268
269         eval q{use File::Temp qw/tempfile/};
270         error($@) if $@;
271         eval q{use File::ReadBackwards};
272         error($@) if $@;
273
274         my ($tmphandle, $tmpfile) = tempfile();
275         system("env TZ=UTC cvsps -q --cvs-direct -z 30 -x >$tmpfile");
276         if ($? == -1) {
277                 error "couldn't run cvsps: $!\n";
278         }
279         elsif (($? >> 8) != 0) {
280                 error "cvsps exited " . ($? >> 8) . ": $!\n";
281         }
282
283         tie(*SPSVC, 'File::ReadBackwards', $tmpfile)
284                 || error "couldn't open $tmpfile for read: $!\n";
285
286         while (my $line = <SPSVC>) {
287                 $line =~ /^$/ || error "expected blank line, got $line";
288
289                 my ($rev, $user, $committype, $when);
290                 my (@message, @pages);
291
292                 # We're reading backwards.
293                 # Forwards, an entry looks like so:
294                 # ---------------------
295                 # PatchSet $rev
296                 # Date: $when
297                 # Author: $user (or user CGI runs as, for web commits)
298                 # Branch: branch
299                 # Tag: tag
300                 # Log:
301                 # @message_lines
302                 # Members:
303                 #       @pages (and revisions)
304                 #
305
306                 while ($line = <SPSVC>) {
307                         last if ($line =~ /^Members:/);
308                         for ($line) {
309                                 s/^\s+//;
310                                 s/\s+$//;
311                         }
312                         my ($page, $revs) = split(/:/, $line);
313                         my ($oldrev, $newrev) = split(/->/, $revs);
314                         $oldrev =~ s/INITIAL/0/;
315                         $newrev =~ s/\(DEAD\)//;
316                         my $diffurl = defined $config{diffurl} ? $config{diffurl} : "";
317                         my $epage = join('/',
318                                 map { uri_escape_utf8($_) } split('/', $page)
319                         );
320                         $diffurl=~s/\[\[file\]\]/$epage/g;
321                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
322                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
323                         unshift @pages, {
324                                 page => pagename($page),
325                                 diffurl => $diffurl,
326                         } if length $page;
327                 }
328
329                 while ($line = <SPSVC>) {
330                         last if ($line =~ /^Log:$/);
331                         chomp $line;
332                         unshift @message, { line => $line };
333                 }
334                 $committype = "web";
335                 if (defined $message[0] &&
336                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
337                         $user=defined $2 ? "$2" : "$3";
338                         $message[0]->{line}=$4;
339                 }
340                 else {
341                         $committype="cvs";
342                 }
343
344                 $line = <SPSVC>;        # Tag
345                 $line = <SPSVC>;        # Branch
346
347                 $line = <SPSVC>;
348                 if ($line =~ /^Author: (.*)$/) {
349                         $user = $1 unless defined $user && length $user;
350                 }
351                 else {
352                         error "expected Author, got $line";
353                 }
354
355                 $line = <SPSVC>;
356                 if ($line =~ /^Date: (.*)$/) {
357                         $when = str2time($1, 'UTC');
358                 }
359                 else {
360                         error "expected Date, got $line";
361                 }
362
363                 $line = <SPSVC>;
364                 if ($line =~ /^PatchSet (.*)$/) {
365                         $rev = $1;
366                 }
367                 else {
368                         error "expected PatchSet, got $line";
369                 }
370
371                 $line = <SPSVC>;        # ---------------------
372
373                 push @ret, {
374                         rev => $rev,
375                         user => $user,
376                         committype => $committype,
377                         when => $when,
378                         message => [@message],
379                         pages => [@pages],
380                 } if @pages;
381                 last if @ret >= $num;
382         }
383
384         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
385
386         return @ret;
387 }
388
389 sub rcs_diff ($;$) {
390         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
391         my $maxlines=shift;
392
393         local $CWD = $config{srcdir};
394
395         # diff output is unavoidably preceded by the cvsps PatchSet entry
396         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
397         my $blank_lines_seen = 0;
398
399         # skip log, get to the diff
400         while (my $line = shift @cvsps) {
401                 $blank_lines_seen++ if ($line =~ /^$/);
402                 last if $blank_lines_seen == 2;
403         }
404
405         @cvsps = @cvsps[0..$maxlines-1]
406                 if defined $maxlines && @cvsps > $maxlines;
407
408         if (wantarray) {
409                 return @cvsps;
410         }
411         else {
412                 return join("", @cvsps);
413         }
414 }
415
416 sub rcs_getctime ($) {
417         my $file=shift;
418
419         local $CWD = $config{srcdir};
420
421         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
422
423         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
424                 || error "couldn't get cvs log output: $!\n";
425
426         my $date;
427         while (<CVSLOG>) {
428                 if (/$cvs_log_infoline/) {
429                         $date=$1;
430                 }
431         }
432         close CVSLOG || warn "cvs log $file exited $?";
433
434         if (! defined $date) {
435                 warn "failed to parse cvs log for $file\n";
436                 return 0;
437         }
438
439         eval q{use Date::Parse};
440         error($@) if $@;
441         $date=str2time($date, 'UTC');
442         debug("found ctime ".localtime($date)." for $file");
443         return $date;
444 }
445
446 sub rcs_getmtime ($) {
447         error "rcs_getmtime is not implemented for cvs\n"; # TODO
448 }
449
450
451 # INTERNAL SUPPORT ROUTINES
452
453 sub commitmessage (@) {
454         my %params=@_;
455
456         if (defined $params{session}) {
457                 if (defined $params{session}->param("name")) {
458                         return "web commit by ".
459                                 $params{session}->param("name").
460                                 (length $params{message} ? ": $params{message}" : "");
461                 }
462                 elsif (defined $params{session}->remote_addr()) {
463                         return "web commit from ".
464                                 $params{session}->remote_addr().
465                                 (length $params{message} ? ": $params{message}" : "");
466                 }
467         }
468         return $params{message};
469 }
470
471 sub cvs_info ($$) {
472         my $field=shift;
473         my $file=shift;
474
475         local $CWD = $config{srcdir};
476
477         my $info=`cvs status $file`;
478         my ($ret)=$info=~/^\s*$field:\s*(\S+)/m;
479         return $ret;
480 }
481
482 sub cvs_is_controlling {
483         my $dir=shift;
484         $dir=$config{srcdir} unless defined($dir);
485         return (-d "$dir/CVS") ? 1 : 0;
486 }
487
488 sub cvs_keyword_subst_args ($) {
489         my $file = shift;
490
491         local $CWD = $config{srcdir};
492
493         eval q{use File::MimeInfo};
494         error($@) if $@;
495         my $filemime = File::MimeInfo::default($file);
496         # if (-T $file) {
497
498         defined($filemime) && $filemime eq 'text/plain'
499                 ? return ('-kkv', $file)
500                 : return ('-kb', $file);
501 }
502
503 sub cvs_runcvs(@) {
504         my @cmd = @_;
505         unshift @cmd, 'cvs', '-Q';
506
507         # CVS can't operate outside a srcdir, so we're always setting $CWD.
508         # "local $CWD" restores the previous value when we go out of scope.
509         # Usually that's correct. But if we're removing the last file from
510         # a directory, the post-commit hook will exec in a working directory
511         # that's about to not exist (CVS will prune it).
512         #
513         # chdir() manually here, so we can selectively not chdir() back.
514
515         my $oldcwd = $CWD;
516         chdir($config{srcdir});
517
518         eval q{
519                 use IPC::Open3;
520                 use Symbol qw(gensym);
521                 use IO::File;
522         };
523         error($@) if $@;
524
525         my $cvsout = '';
526         my $cvserr = '';
527         local *CATCHERR = IO::File->new_tmpfile;
528         my $pid = open3(gensym(), \*CATCHOUT, ">&CATCHERR", @cmd);
529         while (my $l = <CATCHOUT>) {
530                 $cvsout .= $l
531                         unless 1;
532         }
533         waitpid($pid, 0);
534         my $ret = $? >> 8;
535         seek CATCHERR, 0, 0;
536         while (my $l = <CATCHERR>) {
537                 $cvserr .= $l
538                         unless $l =~ /^cvs commit: changing keyword expansion /;
539         }
540
541         print STDOUT $cvsout;
542         print STDERR $cvserr;
543
544         chdir($oldcwd) if -d $oldcwd;
545
546         return ($ret == 0) ? 1 : 0;
547 }
548
549 1