]> 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 File::chdir;
37
38
39 # GENERAL PLUGIN API CALLS
40
41 sub import {
42         hook(type => "checkconfig", id => "cvs", call => \&checkconfig);
43         hook(type => "getsetup", id => "cvs", call => \&getsetup);
44         hook(type => "genwrapper", id => "cvs", call => \&genwrapper);
45
46         hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
47         hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
48         hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
49         hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
50         hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
51         hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
52         hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
53         hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
54         hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
55         hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
56         hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
57 }
58
59 sub checkconfig () {
60         if (! defined $config{cvspath}) {
61                 $config{cvspath}="ikiwiki";
62         }
63         if (exists $config{cvspath}) {
64                 # code depends on the path not having extraneous slashes
65                 $config{cvspath}=~tr#/#/#s;
66                 $config{cvspath}=~s/\/$//;
67                 $config{cvspath}=~s/^\///;
68         }
69         if (defined $config{cvs_wrapper} && length $config{cvs_wrapper}) {
70                 push @{$config{wrappers}}, {
71                         wrapper => $config{cvs_wrapper},
72                         wrappermode => (defined $config{cvs_wrappermode} ? $config{cvs_wrappermode} : "04755"),
73                 };
74         }
75 }
76
77 sub getsetup () {
78         return
79                 plugin => {
80                         safe => 0, # rcs plugin
81                         rebuild => undef,
82                         section => "rcs",
83                 },
84                 cvsrepo => {
85                         type => "string",
86                         example => "/cvs/wikirepo",
87                         description => "cvs repository location",
88                         safe => 0, # path
89                         rebuild => 0,
90                 },
91                 cvspath => {
92                         type => "string",
93                         example => "ikiwiki",
94                         description => "path inside repository where the wiki is located",
95                         safe => 0, # paranoia
96                         rebuild => 0,
97                 },
98                 cvs_wrapper => {
99                         type => "string",
100                         example => "/cvs/wikirepo/CVSROOT/post-commit",
101                         description => "cvs post-commit hook to generate (triggered by CVSROOT/loginfo entry)",
102                         safe => 0, # file
103                         rebuild => 0,
104                 },
105                 cvs_wrappermode => {
106                         type => "string",
107                         example => '04755',
108                         description => "mode for cvs_wrapper (can safely be made suid)",
109                         safe => 0,
110                         rebuild => 0,
111                 },
112                 historyurl => {
113                         type => "string",
114                         example => "http://cvs.example.org/cvsweb.cgi/ikiwiki/[[file]]",
115                         description => "cvsweb url to show file history ([[file]] substituted)",
116                         safe => 1,
117                         rebuild => 1,
118                 },
119                 diffurl => {
120                         type => "string",
121                         example => "http://cvs.example.org/cvsweb.cgi/ikiwiki/[[file]].diff?r1=text&tr1=[[r1]]&r2=text&tr2=[[r2]]",
122                         description => "cvsweb url to show a diff ([[file]], [[r1]], and [[r2]] substituted)",
123                         safe => 1,
124                         rebuild => 1,
125                 },
126 }
127
128 sub genwrapper () {
129         return <<EOF;
130         {
131                 int j;
132                 for (j = 1; j < argc; j++)
133                         if (strstr(argv[j], "New directory") != NULL)
134                                 exit(0);
135         }
136 EOF
137 }
138
139
140 # VCS PLUGIN API CALLS
141
142 sub rcs_update () {
143         return unless cvs_is_controlling;
144         cvs_runcvs('update', '-dP');
145 }
146
147 sub rcs_prepedit ($) {
148         # Prepares to edit a file under revision control. Returns a token
149         # that must be passed into rcs_commit when the file is ready
150         # for committing.
151         # The file is relative to the srcdir.
152         my $file=shift;
153
154         return unless cvs_is_controlling;
155
156         # For cvs, return the revision of the file when
157         # editing begins.
158         my $rev=cvs_info("Repository revision", "$file");
159         return defined $rev ? $rev : "";
160 }
161
162 sub rcs_commit (@) {
163         # Tries to commit the page; returns undef on _success_ and
164         # a version of the page with the rcs's conflict markers on failure.
165         # The file is relative to the srcdir.
166         my %params=@_;
167
168         return unless cvs_is_controlling;
169
170         # Check to see if the page has been changed by someone
171         # else since rcs_prepedit was called.
172         my ($oldrev)=$params{token}=~/^([0-9]+)$/; # untaint
173         my $rev=cvs_info("Repository revision", "$config{srcdir}/$params{file}");
174         if (defined $rev && defined $oldrev && $rev != $oldrev) {
175                 # Merge their changes into the file that we've
176                 # changed.
177                 cvs_runcvs('update', $params{file}) ||
178                         warn("cvs merge from $oldrev to $rev failed\n");
179         }
180
181         if (! cvs_runcvs('commit', '-m',
182                          IkiWiki::possibly_foolish_untaint(commitmessage(%params)))) {
183                 my $conflict=readfile("$config{srcdir}/$params{file}");
184                 cvs_runcvs('update', '-C', $params{file}) ||
185                         warn("cvs revert failed\n");
186                 return $conflict;
187         }
188
189         return undef # success
190 }
191
192 sub rcs_commit_staged (@) {
193         # Commits all staged changes. Changes can be staged using rcs_add,
194         # rcs_remove, and rcs_rename.
195         my %params=@_;
196
197         if (! cvs_runcvs('commit', '-m',
198                          IkiWiki::possibly_foolish_untaint(commitmessage(%params)))) {
199                 warn "cvs staged commit failed\n";
200                 return 1; # failure
201         }
202         return undef # success
203 }
204
205 sub rcs_add ($) {
206         # filename is relative to the root of the srcdir
207         my $file=shift;
208         my $parent=IkiWiki::dirname($file);
209         my @files_to_add = ($file);
210
211         eval q{use File::MimeInfo};
212         error($@) if $@;
213
214         until ((length($parent) == 0) || cvs_is_controlling("$config{srcdir}/$parent")){
215                 push @files_to_add, $parent;
216                 $parent = IkiWiki::dirname($parent);
217         }
218
219         while ($file = pop @files_to_add) {
220                 if (@files_to_add == 0) {
221                         # file
222                         my $filemime = File::MimeInfo::default($file);
223                         if (defined($filemime) && $filemime eq 'text/plain') {
224                                 cvs_runcvs('add', $file) ||
225                                         warn("cvs add $file failed\n");
226                         }
227                         else {
228                                 cvs_runcvs('add', '-kb', $file) ||
229                                         warn("cvs add binary $file failed\n");
230                         }
231                 }
232                 else {
233                         # directory
234                         cvs_runcvs('add', $file) ||
235                                 warn("cvs add $file failed\n");
236                 }
237         }
238 }
239
240 sub rcs_remove ($) {
241         # filename is relative to the root of the srcdir
242         my $file=shift;
243
244         return unless cvs_is_controlling;
245
246         cvs_runcvs('rm', '-f', $file) ||
247                 warn("cvs rm $file failed\n");
248 }
249
250 sub rcs_rename ($$) {
251         # filenames relative to the root of the srcdir
252         my ($src, $dest)=@_;
253
254         return unless cvs_is_controlling;
255
256         local $CWD = $config{srcdir};
257
258         if (system("mv", "$src", "$dest") != 0) {
259                 warn("filesystem rename failed\n");
260         }
261
262         rcs_add($dest);
263         rcs_remove($src);
264 }
265
266 sub rcs_recentchanges ($) {
267         my $num = shift;
268         my @ret;
269
270         return unless cvs_is_controlling;
271
272         eval q{use Date::Parse};
273         error($@) if $@;
274
275         local $CWD = $config{srcdir};
276
277         # There's no cvsps option to get the last N changesets.
278         # Write full output to a temp file and read backwards.
279
280         eval q{use File::Temp qw/tempfile/};
281         error($@) if $@;
282         eval q{use File::ReadBackwards};
283         error($@) if $@;
284
285         my ($tmphandle, $tmpfile) = tempfile();
286         system("env TZ=UTC cvsps -q --cvs-direct -z 30 -x >$tmpfile");
287         if ($? == -1) {
288                 error "couldn't run cvsps: $!\n";
289         }
290         elsif (($? >> 8) != 0) {
291                 error "cvsps exited " . ($? >> 8) . ": $!\n";
292         }
293
294         tie(*SPSVC, 'File::ReadBackwards', $tmpfile)
295                 || error "couldn't open $tmpfile for read: $!\n";
296
297         while (my $line = <SPSVC>) {
298                 $line =~ /^$/ || error "expected blank line, got $line";
299
300                 my ($rev, $user, $committype, $when);
301                 my (@message, @pages);
302
303                 # We're reading backwards.
304                 # Forwards, an entry looks like so:
305                 # ---------------------
306                 # PatchSet $rev
307                 # Date: $when
308                 # Author: $user (or user CGI runs as, for web commits)
309                 # Branch: branch
310                 # Tag: tag
311                 # Log:
312                 # @message_lines
313                 # Members:
314                 #       @pages (and revisions)
315                 #
316
317                 while ($line = <SPSVC>) {
318                         last if ($line =~ /^Members:/);
319                         for ($line) {
320                                 s/^\s+//;
321                                 s/\s+$//;
322                         }
323                         my ($page, $revs) = split(/:/, $line);
324                         my ($oldrev, $newrev) = split(/->/, $revs);
325                         $oldrev =~ s/INITIAL/0/;
326                         $newrev =~ s/\(DEAD\)//;
327                         my $diffurl = defined $config{diffurl} ? $config{diffurl} : "";
328                         $diffurl=~s/\[\[file\]\]/$page/g;
329                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
330                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
331                         unshift @pages, {
332                                 page => pagename($page),
333                                 diffurl => $diffurl,
334                         } if length $page;
335                 }
336
337                 while ($line = <SPSVC>) {
338                         last if ($line =~ /^Log:$/);
339                         chomp $line;
340                         unshift @message, { line => $line };
341                 }
342                 $committype = "web";
343                 if (defined $message[0] &&
344                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
345                         $user=defined $2 ? "$2" : "$3";
346                         $message[0]->{line}=$4;
347                 }
348                 else {
349                         $committype="cvs";
350                 }
351
352                 $line = <SPSVC>;        # Tag
353                 $line = <SPSVC>;        # Branch
354
355                 $line = <SPSVC>;
356                 if ($line =~ /^Author: (.*)$/) {
357                         $user = $1 unless defined $user && length $user;
358                 }
359                 else {
360                         error "expected Author, got $line";
361                 }
362
363                 $line = <SPSVC>;
364                 if ($line =~ /^Date: (.*)$/) {
365                         $when = str2time($1, 'UTC');
366                 }
367                 else {
368                         error "expected Date, got $line";
369                 }
370
371                 $line = <SPSVC>;
372                 if ($line =~ /^PatchSet (.*)$/) {
373                         $rev = $1;
374                 }
375                 else {
376                         error "expected PatchSet, got $line";
377                 }
378
379                 $line = <SPSVC>;        # ---------------------
380
381                 push @ret, {
382                         rev => $rev,
383                         user => $user,
384                         committype => $committype,
385                         when => $when,
386                         message => [@message],
387                         pages => [@pages],
388                 } if @pages;
389                 last if @ret >= $num;
390         }
391
392         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
393
394         return @ret;
395 }
396
397 sub rcs_diff ($;$) {
398         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
399         my $maxlines=shift;
400
401         local $CWD = $config{srcdir};
402
403         # diff output is unavoidably preceded by the cvsps PatchSet entry
404         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
405         my $blank_lines_seen = 0;
406
407         while (my $line = shift @cvsps) {
408                 $blank_lines_seen++ if ($line =~ /^$/);
409                 last if $blank_lines_seen == 2;
410         }
411
412         if (wantarray) {
413                 return @cvsps;
414         }
415         else {
416                 return join("", @cvsps);
417         }
418 }
419
420 sub rcs_getctime ($) {
421         my $file=shift;
422
423         local $CWD = $config{srcdir};
424
425         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
426
427         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
428                 || error "couldn't get cvs log output: $!\n";
429
430         my $date;
431         while (<CVSLOG>) {
432                 if (/$cvs_log_infoline/) {
433                         $date=$1;
434                 }
435         }
436         close CVSLOG || warn "cvs log $file exited $?";
437
438         if (! defined $date) {
439                 warn "failed to parse cvs log for $file\n";
440                 return 0;
441         }
442
443         eval q{use Date::Parse};
444         error($@) if $@;
445         $date=str2time($date, 'UTC');
446         debug("found ctime ".localtime($date)." for $file");
447         return $date;
448 }
449
450 sub rcs_getmtime ($) {
451         error "rcs_getmtime is not implemented for cvs\n"; # TODO
452 }
453
454
455 # INTERNAL SUPPORT ROUTINES
456
457 sub commitmessage (@) {
458         my %params=@_;
459
460         if (defined $params{session}) {
461                 if (defined $params{session}->param("name")) {
462                         return "web commit by ".
463                                 $params{session}->param("name").
464                                 (length $params{message} ? ": $params{message}" : "");
465                 }
466                 elsif (defined $params{session}->remote_addr()) {
467                         return "web commit from ".
468                                 $params{session}->remote_addr().
469                                 (length $params{message} ? ": $params{message}" : "");
470                 }
471         }
472         return $params{message};
473 }
474
475 sub cvs_info ($$) {
476         my $field=shift;
477         my $file=shift;
478
479         local $CWD = $config{srcdir};
480
481         my $info=`cvs status $file`;
482         my ($ret)=$info=~/^\s*$field:\s*(\S+)/m;
483         return $ret;
484 }
485
486 sub cvs_is_controlling {
487         my $dir=shift;
488         $dir=$config{srcdir} unless defined($dir);
489         return (-d "$dir/CVS") ? 1 : 0;
490 }
491
492 sub cvs_runcvs(@) {
493         my @cmd = @_;
494         unshift @cmd, 'cvs', '-Q';
495
496         local $CWD = $config{srcdir};
497
498         open(my $savedout, ">&STDOUT");
499         open(STDOUT, ">", "/dev/null");
500         my $ret = system(@cmd);
501         open(STDOUT, ">&", $savedout);
502
503         return ($ret == 0) ? 1 : 0;
504 }
505
506 1