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