]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/cvs.pm
Merge branch 'master' into cvs
[ikiwiki.git] / 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 = uri_escape_utf8($page);
318                         $diffurl=~s/\[\[file\]\]/$epage/g;
319                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
320                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
321                         unshift @pages, {
322                                 page => pagename($page),
323                                 diffurl => $diffurl,
324                         } if length $page;
325                 }
326
327                 while ($line = <SPSVC>) {
328                         last if ($line =~ /^Log:$/);
329                         chomp $line;
330                         unshift @message, { line => $line };
331                 }
332                 $committype = "web";
333                 if (defined $message[0] &&
334                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
335                         $user=defined $2 ? "$2" : "$3";
336                         $message[0]->{line}=$4;
337                 }
338                 else {
339                         $committype="cvs";
340                 }
341
342                 $line = <SPSVC>;        # Tag
343                 $line = <SPSVC>;        # Branch
344
345                 $line = <SPSVC>;
346                 if ($line =~ /^Author: (.*)$/) {
347                         $user = $1 unless defined $user && length $user;
348                 }
349                 else {
350                         error "expected Author, got $line";
351                 }
352
353                 $line = <SPSVC>;
354                 if ($line =~ /^Date: (.*)$/) {
355                         $when = str2time($1, 'UTC');
356                 }
357                 else {
358                         error "expected Date, got $line";
359                 }
360
361                 $line = <SPSVC>;
362                 if ($line =~ /^PatchSet (.*)$/) {
363                         $rev = $1;
364                 }
365                 else {
366                         error "expected PatchSet, got $line";
367                 }
368
369                 $line = <SPSVC>;        # ---------------------
370
371                 push @ret, {
372                         rev => $rev,
373                         user => $user,
374                         committype => $committype,
375                         when => $when,
376                         message => [@message],
377                         pages => [@pages],
378                 } if @pages;
379                 last if @ret >= $num;
380         }
381
382         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
383
384         return @ret;
385 }
386
387 sub rcs_diff ($;$) {
388         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
389         my $maxlines=shift;
390
391         local $CWD = $config{srcdir};
392
393         # diff output is unavoidably preceded by the cvsps PatchSet entry
394         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
395         my $blank_lines_seen = 0;
396
397         # skip log, get to the diff
398         while (my $line = shift @cvsps) {
399                 $blank_lines_seen++ if ($line =~ /^$/);
400                 last if $blank_lines_seen == 2;
401         }
402
403         @cvsps = @cvsps[0..$maxlines-1]
404                 if defined $maxlines && @cvsps > $maxlines;
405
406         if (wantarray) {
407                 return @cvsps;
408         }
409         else {
410                 return join("", @cvsps);
411         }
412 }
413
414 sub rcs_getctime ($) {
415         my $file=shift;
416
417         local $CWD = $config{srcdir};
418
419         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
420
421         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
422                 || error "couldn't get cvs log output: $!\n";
423
424         my $date;
425         while (<CVSLOG>) {
426                 if (/$cvs_log_infoline/) {
427                         $date=$1;
428                 }
429         }
430         close CVSLOG || warn "cvs log $file exited $?";
431
432         if (! defined $date) {
433                 warn "failed to parse cvs log for $file\n";
434                 return 0;
435         }
436
437         eval q{use Date::Parse};
438         error($@) if $@;
439         $date=str2time($date, 'UTC');
440         debug("found ctime ".localtime($date)." for $file");
441         return $date;
442 }
443
444 sub rcs_getmtime ($) {
445         error "rcs_getmtime is not implemented for cvs\n"; # TODO
446 }
447
448
449 # INTERNAL SUPPORT ROUTINES
450
451 sub commitmessage (@) {
452         my %params=@_;
453
454         if (defined $params{session}) {
455                 if (defined $params{session}->param("name")) {
456                         return "web commit by ".
457                                 $params{session}->param("name").
458                                 (length $params{message} ? ": $params{message}" : "");
459                 }
460                 elsif (defined $params{session}->remote_addr()) {
461                         return "web commit from ".
462                                 $params{session}->remote_addr().
463                                 (length $params{message} ? ": $params{message}" : "");
464                 }
465         }
466         return $params{message};
467 }
468
469 sub cvs_info ($$) {
470         my $field=shift;
471         my $file=shift;
472
473         local $CWD = $config{srcdir};
474
475         my $info=`cvs status $file`;
476         my ($ret)=$info=~/^\s*$field:\s*(\S+)/m;
477         return $ret;
478 }
479
480 sub cvs_is_controlling {
481         my $dir=shift;
482         $dir=$config{srcdir} unless defined($dir);
483         return (-d "$dir/CVS") ? 1 : 0;
484 }
485
486 sub cvs_keyword_subst_args ($) {
487         my $file = shift;
488
489         local $CWD = $config{srcdir};
490
491         eval q{use File::MimeInfo};
492         error($@) if $@;
493         my $filemime = File::MimeInfo::default($file);
494         # if (-T $file) {
495
496         defined($filemime) && $filemime eq 'text/plain'
497                 ? return ('-kkv', $file)
498                 : return ('-kb', $file);
499 }
500
501 sub cvs_runcvs(@) {
502         my @cmd = @_;
503         unshift @cmd, 'cvs', '-Q';
504
505         local $CWD = $config{srcdir};
506
507         eval q{
508                 use IPC::Open3;
509                 use Symbol qw(gensym);
510                 use IO::File;
511         };
512         error($@) if $@;
513
514         my $cvsout = '';
515         my $cvserr = '';
516         local *CATCHERR = IO::File->new_tmpfile;
517         my $pid = open3(gensym(), \*CATCHOUT, ">&CATCHERR", @cmd);
518         while (my $l = <CATCHOUT>) {
519                 $cvsout .= $l
520                         unless 1;
521         }
522         waitpid($pid, 0);
523         my $ret = $? >> 8;
524         seek CATCHERR, 0, 0;
525         while (my $l = <CATCHERR>) {
526                 $cvserr .= $l
527                         unless $l =~ /^cvs commit: changing keyword expansion /;
528         }
529
530         print STDOUT $cvsout;
531         print STDERR $cvserr;
532
533         return ($ret == 0) ? 1 : 0;
534 }
535
536 1