API: rcs_commit and rcs_commit_staged are passed a new parameter
[ikiwiki] / IkiWiki / Plugin / svn.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::svn;
3
4 use warnings;
5 use strict;
6 use IkiWiki;
7 use POSIX qw(setlocale LC_CTYPE);
8
9 sub import {
10         hook(type => "checkconfig", id => "svn", call => \&checkconfig);
11         hook(type => "getsetup", id => "svn", call => \&getsetup);
12         hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
13         hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
14         hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
15         hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
16         hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
17         hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
18         hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
19         hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
20         hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
21         hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
22         hook(type => "rcs", id => "rcs_getmtime", call => \&rcs_getmtime);
23 }
24
25 sub checkconfig () {
26         if (! defined $config{svnpath}) {
27                 $config{svnpath}="trunk";
28         }
29         if (exists $config{svnpath}) {
30                 # code depends on the path not having extraneous slashes
31                 $config{svnpath}=~tr#/#/#s;
32                 $config{svnpath}=~s/\/$//;
33                 $config{svnpath}=~s/^\///;
34         }
35         if (defined $config{svn_wrapper} && length $config{svn_wrapper}) {
36                 push @{$config{wrappers}}, {
37                         wrapper => $config{svn_wrapper},
38                         wrappermode => (defined $config{svn_wrappermode} ? $config{svn_wrappermode} : "04755"),
39                 };
40         }
41 }
42
43 sub getsetup () {
44         return
45                 plugin => {
46                         safe => 0, # rcs plugin
47                         rebuild => undef,
48                         section => "rcs",
49                 },
50                 svnrepo => {
51                         type => "string",
52                         example => "/svn/wiki",
53                         description => "subversion repository location",
54                         safe => 0, # path
55                         rebuild => 0,
56                 },
57                 svnpath => {
58                         type => "string",
59                         example => "trunk",
60                         description => "path inside repository where the wiki is located",
61                         safe => 0, # paranoia
62                         rebuild => 0,
63                 },
64                 svn_wrapper => {
65                         type => "string",
66                         example => "/svn/wikirepo/hooks/post-commit",
67                         description => "svn post-commit hook to generate",
68                         safe => 0, # file
69                         rebuild => 0,
70                 },
71                 svn_wrappermode => {
72                         type => "string",
73                         example => '04755',
74                         description => "mode for svn_wrapper (can safely be made suid)",
75                         safe => 0,
76                         rebuild => 0,
77                 },
78                 historyurl => {
79                         type => "string",
80                         example => "http://svn.example.org/trunk/[[file]]",
81                         description => "viewvc url to show file history ([[file]] substituted)",
82                         safe => 1,
83                         rebuild => 1,
84                 },
85                 diffurl => {
86                         type => "string",
87                         example => "http://svn.example.org/trunk/[[file]]?root=wiki&r1=[[r1]]&r2=[[r2]]",
88                         description => "viewvc url to show a diff ([[file]], [[r1]], and [[r2]] substituted)",
89                         safe => 1,
90                         rebuild => 1,
91                 },
92 }
93
94 # svn needs LC_CTYPE set to a UTF-8 locale, so try to find one. Any will do.
95 sub find_lc_ctype() {
96         my $current = setlocale(LC_CTYPE());
97         return $current if $current =~ m/UTF-?8$/i;
98
99         # Make some obvious attempts to avoid calling `locale -a`
100         foreach my $locale ("$current.UTF-8", "en_US.UTF-8", "en_GB.UTF-8") {
101                 return $locale if setlocale(LC_CTYPE(), $locale);
102         }
103
104         # Try to get all available locales and pick the first UTF-8 one found.
105         if (my @locale = grep(/UTF-?8$/i, `locale -a`)) {
106                 chomp @locale;
107                 return $locale[0] if setlocale(LC_CTYPE(), $locale[0]);
108         }
109
110         # fallback to the current locale
111         return $current;
112 }
113 $ENV{LC_CTYPE} = $ENV{LC_CTYPE} || find_lc_ctype();
114
115 sub svn_info ($$) {
116         my $field=shift;
117         my $file=shift;
118
119         my $info=`LANG=C svn info $file`;
120         my ($ret)=$info=~/^$field: (.*)$/m;
121         return $ret;
122 }
123
124 sub rcs_update () {
125         if (-d "$config{srcdir}/.svn") {
126                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
127                         warn("svn update failed\n");
128                 }
129         }
130 }
131
132 sub rcs_prepedit ($) {
133         # Prepares to edit a file under revision control. Returns a token
134         # that must be passed into rcs_commit when the file is ready
135         # for committing.
136         # The file is relative to the srcdir.
137         my $file=shift;
138         
139         if (-d "$config{srcdir}/.svn") {
140                 # For subversion, return the revision of the file when
141                 # editing begins.
142                 my $rev=svn_info("Revision", "$config{srcdir}/$file");
143                 return defined $rev ? $rev : "";
144         }
145 }
146
147 sub rcs_commit ($$$;$$$) {
148         # Tries to commit the page; returns undef on _success_ and
149         # a version of the page with the rcs's conflict markers on failure.
150         # The file is relative to the srcdir.
151         my $file=shift;
152         my $message=shift;
153         my $rcstoken=shift;
154         my $user=shift;
155         my $ipaddr=shift;
156         my $emailuser=shift;
157
158         if (defined $user) {
159                 $message="web commit by $user".(length $message ? ": $message" : "");
160         }
161         elsif (defined $ipaddr) {
162                 $message="web commit from $ipaddr".(length $message ? ": $message" : "");
163         }
164
165         if (-d "$config{srcdir}/.svn") {
166                 # Check to see if the page has been changed by someone
167                 # else since rcs_prepedit was called.
168                 my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
169                 my $rev=svn_info("Revision", "$config{srcdir}/$file");
170                 if (defined $rev && defined $oldrev && $rev != $oldrev) {
171                         # Merge their changes into the file that we've
172                         # changed.
173                         if (system("svn", "merge", "--quiet", "-r$oldrev:$rev",
174                                    "$config{srcdir}/$file", "$config{srcdir}/$file") != 0) {
175                                 warn("svn merge -r$oldrev:$rev failed\n");
176                         }
177                 }
178
179                 if (system("svn", "commit", "--quiet", 
180                            "--encoding", "UTF-8", "-m",
181                            IkiWiki::possibly_foolish_untaint($message),
182                            $config{srcdir}) != 0) {
183                         my $conflict=readfile("$config{srcdir}/$file");
184                         if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
185                                 warn("svn revert failed\n");
186                         }
187                         return $conflict;
188                 }
189         }
190         return undef # success
191 }
192
193 sub rcs_commit_staged ($$$;$) {
194         # Commits all staged changes. Changes can be staged using rcs_add,
195         # rcs_remove, and rcs_rename.
196         my ($message, $user, $ipaddr, $emailuser)=@_;
197         
198         if (defined $user) {
199                 $message="web commit by $user".(length $message ? ": $message" : "");
200         }
201         elsif (defined $ipaddr) {
202                 $message="web commit from $ipaddr".(length $message ? ": $message" : "");
203         }
204         
205         if (system("svn", "commit", "--quiet",
206                    "--encoding", "UTF-8", "-m",
207                    IkiWiki::possibly_foolish_untaint($message),
208                    $config{srcdir}) != 0) {
209                 warn("svn commit failed\n");
210                 return 1; # failure     
211         }
212         return undef # success
213 }
214
215 sub rcs_add ($) {
216         # filename is relative to the root of the srcdir
217         my $file=shift;
218
219         if (-d "$config{srcdir}/.svn") {
220                 my $parent=IkiWiki::dirname($file);
221                 while (! -d "$config{srcdir}/$parent/.svn") {
222                         $file=$parent;
223                         $parent=IkiWiki::dirname($file);
224                 }
225                 
226                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
227                         warn("svn add failed\n");
228                 }
229         }
230 }
231
232 sub rcs_remove ($) {
233         # filename is relative to the root of the srcdir
234         my $file=shift;
235
236         if (-d "$config{srcdir}/.svn") {
237                 if (system("svn", "rm", "--force", "--quiet", "$config{srcdir}/$file") != 0) {
238                         warn("svn rm failed\n");
239                 }
240         }
241 }
242
243 sub rcs_rename ($$) {
244         # filenames relative to the root of the srcdir
245         my ($src, $dest)=@_;
246         
247         if (-d "$config{srcdir}/.svn") {
248                 # Add parent directory for $dest
249                 my $parent=IkiWiki::dirname($dest);
250                 if (! -d "$config{srcdir}/$parent/.svn") {
251                         while (! -d "$config{srcdir}/$parent/.svn") {
252                                 $parent=IkiWiki::dirname($dest);
253                         }
254                         if (system("svn", "add", "--quiet", "$config{srcdir}/$parent") != 0) {
255                                 warn("svn add $parent failed\n");
256                         }
257                 }
258
259                 if (system("svn", "mv", "--force", "--quiet", 
260                     "$config{srcdir}/$src", "$config{srcdir}/$dest") != 0) {
261                         warn("svn rename failed\n");
262                 }
263         }
264 }
265
266 sub rcs_recentchanges ($) {
267         my $num=shift;
268         my @ret;
269         
270         return unless -d "$config{srcdir}/.svn";
271
272         eval q{
273                 use Date::Parse;
274                 use XML::SAX;
275                 use XML::Simple;
276         };
277         error($@) if $@;
278
279         # avoid using XML::SAX::PurePerl, it's buggy with UTF-8 data
280         my @parsers = map { ${$_}{Name} } @{XML::SAX->parsers()};
281         do {
282                 $XML::Simple::PREFERRED_PARSER = pop @parsers;
283         } until $XML::Simple::PREFERRED_PARSER ne 'XML::SAX::PurePerl';
284
285         # --limit is only supported on Subversion 1.2.0+
286         my $svn_version=`svn --version -q`;
287         my $svn_limit='';
288         $svn_limit="--limit $num"
289                 if $svn_version =~ /\d\.(\d)\.\d/ && $1 >= 2;
290
291         my $svn_url=svn_info("URL", $config{srcdir});
292         my $xml = XMLin(scalar `svn $svn_limit --xml -v log '$svn_url'`,
293                 ForceArray => [ 'logentry', 'path' ],
294                 GroupTags => { paths => 'path' },
295                 KeyAttr => { path => 'content' },
296         );
297         foreach my $logentry (@{$xml->{logentry}}) {
298                 my (@pages, @message);
299
300                 my $rev = $logentry->{revision};
301                 my $user = $logentry->{author};
302
303                 my $when=str2time($logentry->{date}, 'UTC');
304
305                 foreach my $msgline (split(/\n/, $logentry->{msg})) {
306                         push @message, { line => $msgline };
307                 }
308
309                 my $committype="web";
310                 if (defined $message[0] &&
311                     $message[0]->{line}=~/$config{web_commit_regexp}/) {
312                         $user=defined $2 ? "$2" : "$3";
313                         $message[0]->{line}=$4;
314                 }
315                 else {
316                         $committype="svn";
317                 }
318
319                 foreach my $file (keys %{$logentry->{paths}}) {
320                         if (length $config{svnpath}) {
321                                 next unless $file=~/^\/\Q$config{svnpath}\E\/([^ ]+)(?:$|\s)/;
322                                 $file=$1;
323                         }
324
325                         my $diffurl=defined $config{diffurl} ? $config{diffurl} : "";
326                         $diffurl=~s/\[\[file\]\]/$file/g;
327                         $diffurl=~s/\[\[r1\]\]/$rev - 1/eg;
328                         $diffurl=~s/\[\[r2\]\]/$rev/g;
329
330                         push @pages, {
331                                 page => pagename($file),
332                                 diffurl => $diffurl,
333                         } if length $file;
334                 }
335                 push @ret, {
336                         rev => $rev,
337                         user => $user,
338                         committype => $committype,
339                         when => $when,
340                         message => [@message],
341                         pages => [@pages],
342                 } if @pages;
343                 return @ret if @ret >= $num;
344         }
345
346         return @ret;
347 }
348
349 sub rcs_diff ($) {
350         my $rev=IkiWiki::possibly_foolish_untaint(int(shift));
351         return `svnlook diff $config{svnrepo} -r$rev --no-diff-deleted`;
352 }
353
354 {
355
356 my ($lastfile, $lastmtime, $lastctime);
357
358 sub findtimes ($) {
359         my $file=shift;
360
361         if (defined $lastfile && $lastfile eq $file) {
362                 return $lastmtime, $lastctime;
363         }
364         $lastfile=$file;
365
366         my $svn_log_infoline=qr/^r\d+\s+\|\s+[^\s]+\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
367                 
368         my $child = open(SVNLOG, "-|");
369         if (! $child) {
370                 exec("svn", "log", $file) || error("svn log $file failed to run");
371         }
372
373         my ($cdate, $mdate);
374         while (<SVNLOG>) {
375                 if (/$svn_log_infoline/) {
376                         $cdate=$1;
377                         $mdate=$1 unless defined $mdate;
378                 }
379         }
380         close SVNLOG || error "svn log $file exited $?";
381
382         if (! defined $cdate) {
383                 error "failed to parse svn log for $file\n";
384         }
385                 
386         eval q{use Date::Parse};
387         error($@) if $@;
388         
389         $lastctime=str2time($cdate);
390         $lastmtime=str2time($mdate);
391         return $lastmtime, $lastctime;
392 }
393
394 }
395
396 sub rcs_getctime ($) {
397         my $file=shift;
398
399         return (findtimes($file))[1];
400 }
401
402 sub rcs_getmtime ($) {
403         my $file=shift;
404
405         return (findtimes($file))[0];
406 }
407
408 1