Knock off another to-do item: "Don't slurp the entire cvsps output
[ikiwiki.git] / 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         debug("runcvs: " . join(" ", @$cmd));
112
113         my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf) =
114                 IPC::Cmd::run(command => $cmd, verbose => 0);
115         if (! $success) {
116                 warn(join(" ", @$cmd) . " exited with code $error_code\n");
117                 warn(join "", @$stderr_buf);
118         }
119         return $success;
120 }
121
122 sub cvs_shquote_commit ($) {
123         my $message = shift;
124
125         eval q{use String::ShellQuote};
126         error($@) if $@;
127
128         return shell_quote(IkiWiki::possibly_foolish_untaint($message));
129 }
130
131 sub cvs_is_controlling {
132         my $dir=shift;
133         $dir=$config{srcdir} unless defined($dir);
134         return (-d "$dir/CVS") ? 1 : 0;
135 }
136
137 sub rcs_update () {
138         return unless cvs_is_controlling;
139         cvs_runcvs(['update', '-dP']);
140 }
141
142 sub rcs_prepedit ($) {
143         # Prepares to edit a file under revision control. Returns a token
144         # that must be passed into rcs_commit when the file is ready
145         # for committing.
146         # The file is relative to the srcdir.
147         my $file=shift;
148
149         return unless cvs_is_controlling;
150
151         # For cvs, return the revision of the file when
152         # editing begins.
153         my $rev=cvs_info("Repository revision", "$file");
154         return defined $rev ? $rev : "";
155 }
156
157 sub rcs_commit ($$$;$$) {
158         # Tries to commit the page; returns undef on _success_ and
159         # a version of the page with the rcs's conflict markers on failure.
160         # The file is relative to the srcdir.
161         my $file=shift;
162         my $message=shift;
163         my $rcstoken=shift;
164         my $user=shift;
165         my $ipaddr=shift;
166
167         return unless cvs_is_controlling;
168
169         if (defined $user) {
170                 $message="web commit by $user".(length $message ? ": $message" : "");
171         }
172         elsif (defined $ipaddr) {
173                 $message="web commit from $ipaddr".(length $message ? ": $message" : "");
174         }
175
176         # Check to see if the page has been changed by someone
177         # else since rcs_prepedit was called.
178         my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
179         my $rev=cvs_info("Repository revision", "$config{srcdir}/$file");
180         if (defined $rev && defined $oldrev && $rev != $oldrev) {
181                 # Merge their changes into the file that we've
182                 # changed.
183                 cvs_runcvs(['update', $file]) ||
184                         warn("cvs merge from $oldrev to $rev failed\n");
185         }
186
187         if (! cvs_runcvs(['commit', '-m', cvs_shquote_commit $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', cvs_shquote_commit $message])) {
210                 warn "cvs staged commit failed\n";
211                 return 1; # failure
212         }
213         return undef # success
214 }
215
216 sub rcs_add ($) {
217         # filename is relative to the root of the srcdir
218         my $file=shift;
219         my $parent=IkiWiki::dirname($file);
220         my @files_to_add = ($file);
221
222         eval q{use File::MimeInfo};
223         error($@) if $@;
224
225         until ((length($parent) == 0) || cvs_is_controlling("$config{srcdir}/$parent")){
226                 push @files_to_add, $parent;
227                 $parent = IkiWiki::dirname($parent);
228         }
229
230         while ($file = pop @files_to_add) {
231                 if ((@files_to_add == 0) &&
232                         (File::MimeInfo::default $file ne 'text/plain')) {
233                         # it's a binary file, add specially
234                         cvs_runcvs(['add', '-kb', $file]) ||
235                                 warn("cvs add $file failed\n");
236                 } else {
237                         # directory or regular file
238                         cvs_runcvs(['add', $file]) ||
239                                 warn("cvs add $file failed\n");
240                 }
241         }
242 }
243
244 sub rcs_remove ($) {
245         # filename is relative to the root of the srcdir
246         my $file=shift;
247
248         return unless cvs_is_controlling;
249
250         cvs_runcvs(['rm', '-f', $file]) ||
251                 warn("cvs rm $file failed\n");
252 }
253
254 sub rcs_rename ($$) {
255         # filenames relative to the root of the srcdir
256         my ($src, $dest)=@_;
257
258         return unless cvs_is_controlling;
259
260         chdir $config{srcdir} || error("Cannot chdir to $config{srcdir}: $!");
261
262         if (system("mv", "$src", "$dest") != 0) {
263                 warn("filesystem rename failed\n");
264         }
265
266         rcs_add($dest);
267         rcs_remove($src);
268 }
269
270 sub rcs_recentchanges($) {
271         my $num = shift;
272         my @ret;
273
274         return unless cvs_is_controlling;
275
276         eval q{use Date::Parse};
277         error($@) if $@;
278
279         chdir $config{srcdir} || error("Cannot chdir to $config{srcdir}: $!");
280
281         # There's no cvsps option to get the last N changesets.
282         # Write full output to a temp file and read backwards.
283
284         eval q{use File::Temp qw/tempfile/};
285         error($@) if $@;
286         eval q{use File::ReadBackwards};
287         error($@) if $@;
288
289         my (undef, $tmpfile) = tempfile(OPEN=>0);
290         system("env TZ=UTC cvsps -q --cvs-direct -z 30 -x >$tmpfile");
291         if ($? == -1) {
292                 error "couldn't run cvsps: $!\n";
293         } elsif (($? >>8) != 0) {
294                 error "cvsps exited " . ($? >> 8) . ": $!\n";
295         }
296
297         tie(*SPSVC, 'File::ReadBackwards', $tmpfile)
298                 || error "couldn't open $tmpfile for read: $!\n";
299
300         while (my $line = <SPSVC>) {
301                 $line =~ /^$/ || error "expected blank line, got $line";
302
303                 my ($rev, $user, $committype, $when);
304                 my (@message, @pages);
305
306                 # We're reading backwards.
307                 # Forwards, an entry looks like so:
308                 # ---------------------
309                 # PatchSet $rev
310                 # Date: $when
311                 # Author: $user (or user CGI runs as, for web commits)
312                 # Branch: branch
313                 # Tag: tag
314                 # Log:
315                 # @message_lines
316                 # Members:
317                 #       @pages (and revisions)
318                 #
319
320                 while ($line = <SPSVC>) {
321                         last if ($line =~ /^Members:/);
322                         for ($line) {
323                                 s/^\s+//;
324                                 s/\s+$//;
325                         }
326                         my ($page, $revs) = split(/:/, $line);
327                         my ($oldrev, $newrev) = split(/->/, $revs);
328                         $oldrev =~ s/INITIAL/0/;
329                         $newrev =~ s/\(DEAD\)//;
330                         my $diffurl = defined $config{diffurl} ? $config{diffurl} : "";
331                         $diffurl=~s/\[\[file\]\]/$page/g;
332                         $diffurl=~s/\[\[r1\]\]/$oldrev/g;
333                         $diffurl=~s/\[\[r2\]\]/$newrev/g;
334                         unshift @pages, {
335                                 page => pagename($page),
336                                 diffurl => $diffurl,
337                         } if length $page;
338                 }
339
340                 while ($line = <SPSVC>) {
341                         last if ($line =~ /^Log:$/);
342                         chomp $line;
343                         unshift @message, { line => $line };
344                 }
345                 $committype = "web";
346                 if (defined $message[0] &&
347                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
348                         $user=defined $2 ? "$2" : "$3";
349                         $message[0]->{line}=$4;
350                 } else {
351                         $committype="cvs";
352                 }
353
354                 $line = <SPSVC>;        # Tag
355                 $line = <SPSVC>;        # Branch
356
357                 $line = <SPSVC>;
358                 if ($line =~ /^Author: (.*)$/) {
359                         $user = $1 unless defined $user && length $user;
360                 } else {
361                         error "expected Author, got $line";
362                 }
363
364                 $line = <SPSVC>;
365                 if ($line =~ /^Date: (.*)$/) {
366                         $when = str2time($1, 'UTC');
367                 } else {
368                         error "expected Date, got $line";
369                 }
370
371                 $line = <SPSVC>;
372                 if ($line =~ /^PatchSet (.*)$/) {
373                         $rev = $1;
374                 } else {
375                         error "expected PatchSet, got $line";
376                 }
377
378                 $line = <SPSVC>;        # ---------------------
379
380                 push @ret, {
381                         rev => $rev,
382                         user => $user,
383                         committype => $committype,
384                         when => $when,
385                         message => [@message],
386                         pages => [@pages],
387                 } if @pages;
388                 last if @ret >= $num;
389         }
390
391         unlink($tmpfile) || error "couldn't unlink $tmpfile: $!\n";
392
393         return @ret;
394 }
395
396 sub rcs_diff ($) {
397         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
398
399         chdir $config{srcdir} || error("Cannot chdir to $config{srcdir}: $!");
400
401         # diff output is unavoidably preceded by the cvsps PatchSet entry
402         my @cvsps = `env TZ=UTC cvsps -q --cvs-direct -z 30 -g -s $rev`;
403         my $blank_lines_seen = 0;
404
405         while (my $line = shift @cvsps) {
406                 $blank_lines_seen++ if ($line =~ /^$/);
407                 last if $blank_lines_seen == 2;
408         }
409
410         if (wantarray) {
411                 return @cvsps;
412         } else {
413                 return join("", @cvsps);
414         }
415 }
416
417 sub rcs_getctime ($) {
418         my $file=shift;
419
420         my $cvs_log_infoline=qr/^date: (.+);\s+author/;
421
422         open CVSLOG, "cvs -Q log -r1.1 '$file' |"
423                 || error "couldn't get cvs log output: $!\n";
424
425         my $date;
426         while (<CVSLOG>) {
427                 if (/$cvs_log_infoline/) {
428                         $date=$1;
429                 }
430         }
431         close CVSLOG || warn "cvs log $file exited $?";
432
433         if (! defined $date) {
434                 warn "failed to parse cvs log for $file\n";
435                 return 0;
436         }
437
438         eval q{use Date::Parse};
439         error($@) if $@;
440         $date=str2time($date, 'UTC');
441         debug("found ctime ".localtime($date)." for $file");
442         return $date;
443 }
444
445 1