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