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