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