API: rcs_commit and rcs_commit_staged are passed a new parameter
[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 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 rcs_commit ($$$;$$$) {
187         # Tries to commit the page; returns undef on _success_ and
188         # a version of the page with the rcs's conflict markers on failure.
189         # The file is relative to the srcdir.
190         my $file=shift;
191         my $message=shift;
192         my $rcstoken=shift;
193         my $user=shift;
194         my $ipaddr=shift;
195         my $emailuser=shift;
196
197         return unless cvs_is_controlling;
198
199         if (defined $user) {
200                 $message="web commit by $user".(length $message ? ": $message" : "");
201         }
202         elsif (defined $ipaddr) {
203                 $message="web commit from $ipaddr".(length $message ? ": $message" : "");
204         }
205
206         # Check to see if the page has been changed by someone
207         # else since rcs_prepedit was called.
208         my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
209         my $rev=cvs_info("Repository revision", "$config{srcdir}/$file");
210         if (defined $rev && defined $oldrev && $rev != $oldrev) {
211                 # Merge their changes into the file that we've
212                 # changed.
213                 cvs_runcvs('update', $file) ||
214                         warn("cvs merge from $oldrev to $rev failed\n");
215         }
216
217         if (! cvs_runcvs('commit', '-m',
218                          IkiWiki::possibly_foolish_untaint $message)) {
219                 my $conflict=readfile("$config{srcdir}/$file");
220                 cvs_runcvs('update', '-C', $file) ||
221                         warn("cvs revert failed\n");
222                 return $conflict;
223         }
224
225         return undef # success
226 }
227
228 sub rcs_commit_staged ($$$;$) {
229         # Commits all staged changes. Changes can be staged using rcs_add,
230         # rcs_remove, and rcs_rename.
231         my ($message, $user, $ipaddr, $emailuser)=@_;
232
233         if (defined $user) {
234                 $message="web commit by $user".(length $message ? ": $message" : "");
235         }
236         elsif (defined $ipaddr) {
237                 $message="web commit from $ipaddr".(length $message ? ": $message" : "");
238         }
239
240         if (! cvs_runcvs('commit', '-m',
241                          IkiWiki::possibly_foolish_untaint $message)) {
242                 warn "cvs staged commit failed\n";
243                 return 1; # failure
244         }
245         return undef # success
246 }
247
248 sub rcs_add ($) {
249         # filename is relative to the root of the srcdir
250         my $file=shift;
251         my $parent=IkiWiki::dirname($file);
252         my @files_to_add = ($file);
253
254         eval q{use File::MimeInfo};
255         error($@) if $@;
256
257         until ((length($parent) == 0) || cvs_is_controlling("$config{srcdir}/$parent")){
258                 push @files_to_add, $parent;
259                 $parent = IkiWiki::dirname($parent);
260         }
261
262         while ($file = pop @files_to_add) {
263                 if (@files_to_add == 0) {
264                         # file
265                         my $filemime = File::MimeInfo::default($file);
266                         if (defined($filemime) && $filemime eq 'text/plain') {
267                                 cvs_runcvs('add', $file) ||
268                                         warn("cvs add $file failed\n");
269                         }
270                         else {
271                                 cvs_runcvs('add', '-kb', $file) ||
272                                         warn("cvs add binary $file failed\n");
273                         }
274                 }
275                 else {
276                         # directory
277                         cvs_runcvs('add', $file) ||
278                                 warn("cvs add $file failed\n");
279                 }
280         }
281 }
282
283 sub rcs_remove ($) {
284         # filename is relative to the root of the srcdir
285         my $file=shift;
286
287         return unless cvs_is_controlling;
288
289         cvs_runcvs('rm', '-f', $file) ||
290                 warn("cvs rm $file failed\n");
291 }
292
293 sub rcs_rename ($$) {
294         # filenames relative to the root of the srcdir
295         my ($src, $dest)=@_;
296
297         return unless cvs_is_controlling;
298
299         local $CWD = $config{srcdir};
300
301         if (system("mv", "$src", "$dest") != 0) {
302                 warn("filesystem rename failed\n");
303         }
304
305         rcs_add($dest);
306         rcs_remove($src);
307 }
308
309 sub rcs_recentchanges ($) {
310         my $num = shift;
311         my @ret;
312
313         return unless cvs_is_controlling;
314
315         eval q{use Date::Parse};
316         error($@) if $@;
317
318         local $CWD = $config{srcdir};
319
320         # There's no cvsps option to get the last N changesets.
321         # Write full output to a temp file and read backwards.
322
323         eval q{use File::Temp qw/tempfile/};
324         error($@) if $@;
325         eval q{use File::ReadBackwards};
326         error($@) if $@;
327
328         my ($tmphandle, $tmpfile) = tempfile();
329         system("env TZ=UTC cvsps -q --cvs-direct -z 30 -x >$tmpfile");
330         if ($? == -1) {
331                 error "couldn't run cvsps: $!\n";
332         }
333         elsif (($? >> 8) != 0) {
334                 error "cvsps exited " . ($? >> 8) . ": $!\n";
335         }
336
337         tie(*SPSVC, 'File::ReadBackwards', $tmpfile)
338                 || error "couldn't open $tmpfile for read: $!\n";
339
340         while (my $line = <SPSVC>) {
341                 $line =~ /^$/ || error "expected blank line, got $line";
342
343                 my ($rev, $user, $committype, $when);
344                 my (@message, @pages);
345
346                 # We're reading backwards.
347                 # Forwards, an entry looks like so:
348                 # ---------------------
349                 # PatchSet $rev
350                 # Date: $when
351                 # Author: $user (or user CGI runs as, for web commits)
352                 # Branch: branch
353                 # Tag: tag
354                 # Log:
355                 # @message_lines
356                 # Members:
357                 #       @pages (and revisions)
358                 #
359
360                 while ($line = <SPSVC>) {
361                         last if ($line =~ /^Members:/);
362                         for ($line) {
363                                 s/^\s+//;
364                                 s/\s+$//;
365                         }
366                         my ($page, $revs) = split(/:/, $line);
367                         my ($oldrev, $newrev) = split(/->/, $revs);
368                         $oldrev =~ s/INITIAL/0/;
369                         $newrev =~ s/\(DEAD\)//;
370                         my $diffurl = defined $config{diffurl} ? $config{diffurl} : "";
371                         $diffurl=~s/\[\[file\]\]/$page/g;
372                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
373                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
374                         unshift @pages, {
375                                 page => pagename($page),
376                                 diffurl => $diffurl,
377                         } if length $page;
378                 }
379
380                 while ($line = <SPSVC>) {
381                         last if ($line =~ /^Log:$/);
382                         chomp $line;
383                         unshift @message, { line => $line };
384                 }
385                 $committype = "web";
386                 if (defined $message[0] &&
387                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
388                         $user=defined $2 ? "$2" : "$3";
389                         $message[0]->{line}=$4;
390                 }
391                 else {
392                         $committype="cvs";
393                 }
394
395                 $line = <SPSVC>;        # Tag
396                 $line = <SPSVC>;        # Branch
397
398                 $line = <SPSVC>;
399                 if ($line =~ /^Author: (.*)$/) {
400                         $user = $1 unless defined $user && length $user;
401                 }
402                 else {
403                         error "expected Author, got $line";
404                 }
405
406                 $line = <SPSVC>;
407                 if ($line =~ /^Date: (.*)$/) {
408                         $when = str2time($1, 'UTC');
409                 }
410                 else {
411                         error "expected Date, got $line";
412                 }
413
414                 $line = <SPSVC>;
415                 if ($line =~ /^PatchSet (.*)$/) {
416                         $rev = $1;
417                 }
418                 else {
419                         error "expected PatchSet, got $line";
420                 }
421
422                 $line = <SPSVC>;        # ---------------------
423
424                 push @ret, {
425                         rev => $rev,
426                         user => $user,
427                         committype => $committype,
428                         when => $when,
429                         message => [@message],
430                         pages => [@pages],
431                 } if @pages;
432                 last if @ret >= $num;
433         }
434
435         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
436
437         return @ret;
438 }
439
440 sub rcs_diff ($) {
441         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
442
443         local $CWD = $config{srcdir};
444
445         # diff output is unavoidably preceded by the cvsps PatchSet entry
446         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
447         my $blank_lines_seen = 0;
448
449         while (my $line = shift @cvsps) {
450                 $blank_lines_seen++ if ($line =~ /^$/);
451                 last if $blank_lines_seen == 2;
452         }
453
454         if (wantarray) {
455                 return @cvsps;
456         }
457         else {
458                 return join("", @cvsps);
459         }
460 }
461
462 sub rcs_getctime ($) {
463         my $file=shift;
464
465         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
466
467         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
468                 || error "couldn't get cvs log output: $!\n";
469
470         my $date;
471         while (<CVSLOG>) {
472                 if (/$cvs_log_infoline/) {
473                         $date=$1;
474                 }
475         }
476         close CVSLOG || warn "cvs log $file exited $?";
477
478         if (! defined $date) {
479                 warn "failed to parse cvs log for $file\n";
480                 return 0;
481         }
482
483         eval q{use Date::Parse};
484         error($@) if $@;
485         $date=str2time($date, 'UTC');
486         debug("found ctime ".localtime($date)." for $file");
487         return $date;
488 }
489
490 sub rcs_getmtime ($) {
491         error "rcs_getmtime is not implemented for cvs\n"; # TODO
492 }
493
494 1