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