]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/cvs.pm
Merge branch 'master' into cvs
[git.ikiwiki.info.git] / IkiWiki / Plugin / cvs.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::cvs;
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.
32 use warnings;
33 use strict;
34 use IkiWiki;
36 use File::chdir;
39 # GENERAL PLUGIN API CALLS
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);
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 }
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 }
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                 },
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
140 # VCS PLUGIN API CALLS
142 sub rcs_update () {
143         return unless cvs_is_controlling();
144         cvs_runcvs('update', '-dP');
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;
154         return unless cvs_is_controlling();
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 : "";
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=@_;
168         return unless cvs_is_controlling();
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         }
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         }
189         return undef # success
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=@_;
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
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);
211         until ((length($parent) == 0) || cvs_is_controlling("$config{srcdir}/$parent")){
212                 push @files_to_add, $parent;
213                 $parent = IkiWiki::dirname($parent);
214         }
216         while ($file = pop @files_to_add) {
217                 if (@files_to_add == 0) {
218                         cvs_runcvs('add', cvs_keyword_subst_args($file)) ||
219                                 warn("cvs add file $file failed\n");
220                 }
221                 else {
222                         cvs_runcvs('add', $file) ||
223                                 warn("cvs add dir $file failed\n");
224                 }
225         }
228 sub rcs_remove ($) {
229         # filename is relative to the root of the srcdir
230         my $file=shift;
232         return unless cvs_is_controlling();
234         cvs_runcvs('rm', '-f', $file) ||
235                 warn("cvs rm $file failed\n");
238 sub rcs_rename ($$) {
239         # filenames relative to the root of the srcdir
240         my ($src, $dest)=@_;
242         return unless cvs_is_controlling();
244         local $CWD = $config{srcdir};
246         if (system("mv", "$src", "$dest") != 0) {
247                 warn("filesystem rename failed\n");
248         }
250         rcs_add($dest);
251         rcs_remove($src);
254 sub rcs_recentchanges ($) {
255         my $num = shift;
256         my @ret;
258         return unless cvs_is_controlling();
260         eval q{use Date::Parse};
261         error($@) if $@;
263         local $CWD = $config{srcdir};
265         # There's no cvsps option to get the last N changesets.
266         # Write full output to a temp file and read backwards.
268         eval q{use File::Temp qw/tempfile/};
269         error($@) if $@;
270         eval q{use File::ReadBackwards};
271         error($@) if $@;
273         my ($tmphandle, $tmpfile) = tempfile();
274         system("env TZ=UTC cvsps -q --cvs-direct -z 30 -x >$tmpfile");
275         if ($? == -1) {
276                 error "couldn't run cvsps: $!\n";
277         }
278         elsif (($? >> 8) != 0) {
279                 error "cvsps exited " . ($? >> 8) . ": $!\n";
280         }
282         tie(*SPSVC, 'File::ReadBackwards', $tmpfile)
283                 || error "couldn't open $tmpfile for read: $!\n";
285         while (my $line = <SPSVC>) {
286                 $line =~ /^$/ || error "expected blank line, got $line";
288                 my ($rev, $user, $committype, $when);
289                 my (@message, @pages);
291                 # We're reading backwards.
292                 # Forwards, an entry looks like so:
293                 # ---------------------
294                 # PatchSet $rev
295                 # Date: $when
296                 # Author: $user (or user CGI runs as, for web commits)
297                 # Branch: branch
298                 # Tag: tag
299                 # Log:
300                 # @message_lines
301                 # Members:
302                 #       @pages (and revisions)
303                 #
305                 while ($line = <SPSVC>) {
306                         last if ($line =~ /^Members:/);
307                         for ($line) {
308                                 s/^\s+//;
309                                 s/\s+$//;
310                         }
311                         my ($page, $revs) = split(/:/, $line);
312                         my ($oldrev, $newrev) = split(/->/, $revs);
313                         $oldrev =~ s/INITIAL/0/;
314                         $newrev =~ s/\(DEAD\)//;
315                         my $diffurl = defined $config{diffurl} ? $config{diffurl} : "";
316                         $diffurl=~s/\[\[file\]\]/$page/g;
317                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
318                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
319                         unshift @pages, {
320                                 page => pagename($page),
321                                 diffurl => $diffurl,
322                         } if length $page;
323                 }
325                 while ($line = <SPSVC>) {
326                         last if ($line =~ /^Log:$/);
327                         chomp $line;
328                         unshift @message, { line => $line };
329                 }
330                 $committype = "web";
331                 if (defined $message[0] &&
332                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
333                         $user=defined $2 ? "$2" : "$3";
334                         $message[0]->{line}=$4;
335                 }
336                 else {
337                         $committype="cvs";
338                 }
340                 $line = <SPSVC>;        # Tag
341                 $line = <SPSVC>;        # Branch
343                 $line = <SPSVC>;
344                 if ($line =~ /^Author: (.*)$/) {
345                         $user = $1 unless defined $user && length $user;
346                 }
347                 else {
348                         error "expected Author, got $line";
349                 }
351                 $line = <SPSVC>;
352                 if ($line =~ /^Date: (.*)$/) {
353                         $when = str2time($1, 'UTC');
354                 }
355                 else {
356                         error "expected Date, got $line";
357                 }
359                 $line = <SPSVC>;
360                 if ($line =~ /^PatchSet (.*)$/) {
361                         $rev = $1;
362                 }
363                 else {
364                         error "expected PatchSet, got $line";
365                 }
367                 $line = <SPSVC>;        # ---------------------
369                 push @ret, {
370                         rev => $rev,
371                         user => $user,
372                         committype => $committype,
373                         when => $when,
374                         message => [@message],
375                         pages => [@pages],
376                 } if @pages;
377                 last if @ret >= $num;
378         }
380         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
382         return @ret;
385 sub rcs_diff ($;$) {
386         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
387         my $maxlines=shift;
389         local $CWD = $config{srcdir};
391         # diff output is unavoidably preceded by the cvsps PatchSet entry
392         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
393         my $blank_lines_seen = 0;
395         # skip log, get to the diff
396         while (my $line = shift @cvsps) {
397                 $blank_lines_seen++ if ($line =~ /^$/);
398                 last if $blank_lines_seen == 2;
399         }
401         @cvsps = @cvsps[0..$maxlines-1]
402                 if defined $maxlines && @cvsps > $maxlines;
404         if (wantarray) {
405                 return @cvsps;
406         }
407         else {
408                 return join("", @cvsps);
409         }
412 sub rcs_getctime ($) {
413         my $file=shift;
415         local $CWD = $config{srcdir};
417         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
419         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
420                 || error "couldn't get cvs log output: $!\n";
422         my $date;
423         while (<CVSLOG>) {
424                 if (/$cvs_log_infoline/) {
425                         $date=$1;
426                 }
427         }
428         close CVSLOG || warn "cvs log $file exited $?";
430         if (! defined $date) {
431                 warn "failed to parse cvs log for $file\n";
432                 return 0;
433         }
435         eval q{use Date::Parse};
436         error($@) if $@;
437         $date=str2time($date, 'UTC');
438         debug("found ctime ".localtime($date)." for $file");
439         return $date;
442 sub rcs_getmtime ($) {
443         error "rcs_getmtime is not implemented for cvs\n"; # TODO
447 # INTERNAL SUPPORT ROUTINES
449 sub commitmessage (@) {
450         my %params=@_;
452         if (defined $params{session}) {
453                 if (defined $params{session}->param("name")) {
454                         return "web commit by ".
455                                 $params{session}->param("name").
456                                 (length $params{message} ? ": $params{message}" : "");
457                 }
458                 elsif (defined $params{session}->remote_addr()) {
459                         return "web commit from ".
460                                 $params{session}->remote_addr().
461                                 (length $params{message} ? ": $params{message}" : "");
462                 }
463         }
464         return $params{message};
467 sub cvs_info ($$) {
468         my $field=shift;
469         my $file=shift;
471         local $CWD = $config{srcdir};
473         my $info=`cvs status $file`;
474         my ($ret)=$info=~/^\s*$field:\s*(\S+)/m;
475         return $ret;
478 sub cvs_is_controlling {
479         my $dir=shift;
480         $dir=$config{srcdir} unless defined($dir);
481         return (-d "$dir/CVS") ? 1 : 0;
484 sub cvs_keyword_subst_args ($) {
485         my $file = shift;
487         local $CWD = $config{srcdir};
489         eval q{use File::MimeInfo};
490         error($@) if $@;
491         my $filemime = File::MimeInfo::default($file);
492         # if (-T $file) {
494         defined($filemime) && $filemime eq 'text/plain'
495                 ? return ('-kkv', $file)
496                 : return ('-kb', $file);
499 sub cvs_runcvs(@) {
500         my @cmd = @_;
501         unshift @cmd, 'cvs', '-Q';
503         local $CWD = $config{srcdir};
505         eval q{
506                 use IPC::Open3;
507                 use Symbol qw(gensym);
508                 use IO::File;
509         };
510         error($@) if $@;
512         my $cvsout = '';
513         my $cvserr = '';
514         local *CATCHERR = IO::File->new_tmpfile;
515         my $pid = open3(gensym(), \*CATCHOUT, ">&CATCHERR", @cmd);
516         while (my $l = <CATCHOUT>) {
517                 $cvsout .= $l
518                         unless 1;
519         }
520         waitpid($pid, 0);
521         my $ret = $? >> 8;
522         seek CATCHERR, 0, 0;
523         while (my $l = <CATCHERR>) {
524                 $cvserr .= $l
525                         unless $l =~ /^cvs commit: changing keyword expansion /;
526         }
528         print STDOUT $cvsout;
529         print STDERR $cvserr;
531         return ($ret == 0) ? 1 : 0;