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