git-remote-mediawiki: modify strings for a better coding-style
[git/git.git] / contrib / mw-to-git / git-remote-mediawiki.perl
CommitLineData
428c995c
JN
1#! /usr/bin/perl
2
3# Copyright (C) 2011
4# Jérémie Nikaes <jeremie.nikaes@ensimag.imag.fr>
5# Arnaud Lacurie <arnaud.lacurie@ensimag.imag.fr>
6# Claire Fousse <claire.fousse@ensimag.imag.fr>
7# David Amouyal <david.amouyal@ensimag.imag.fr>
8# Matthieu Moy <matthieu.moy@grenoble-inp.fr>
9# License: GPL v2 or later
10
11# Gateway between Git and MediaWiki.
9a7365cf 12# Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
428c995c
JN
13
14use strict;
15use MediaWiki::API;
da608b12 16use Git;
428c995c 17use DateTime::Format::ISO8601;
668eec6f 18use warnings;
428c995c 19
721a533f 20# By default, use UTF-8 to communicate with Git and the user
86e95ef2
CM
21binmode STDERR, ':encoding(UTF-8)';
22binmode STDOUT, ':encoding(UTF-8)';
428c995c
JN
23
24use URI::Escape;
a7271ad1 25
428c995c 26# Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
86e95ef2 27use constant SLASH_REPLACEMENT => '%2F';
428c995c
JN
28
29# It's not always possible to delete pages (may require some
2582ab18 30# privileges). Deleted pages are replaced with this content.
428c995c
JN
31use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
32
33# It's not possible to create empty pages. New empty files in Git are
34# sent with this content instead.
35use constant EMPTY_CONTENT => "<!-- empty page -->\n";
36
37# used to reflect file creation or deletion in diff.
86e95ef2 38use constant NULL_SHA1 => '0000000000000000000000000000000000000000';
428c995c 39
dcb1ea62
MM
40# Used on Git's side to reflect empty edit messages on the wiki
41use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
42
428c995c
JN
43my $remotename = $ARGV[0];
44my $url = $ARGV[1];
45
46# Accept both space-separated and multiple keys in config file.
47# Spaces should be written as _ anyway because we'll use chomp.
86e95ef2 48my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.${remotename}.pages"));
428c995c
JN
49chomp(@tracked_pages);
50
51# Just like @tracked_pages, but for MediaWiki categories.
86e95ef2 52my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.${remotename}.categories"));
428c995c
JN
53chomp(@tracked_categories);
54
2045e293 55# Import media files on pull
86e95ef2 56my $import_media = run_git("config --get --bool remote.${remotename}.mediaimport");
6a9e55b0 57chomp($import_media);
86e95ef2 58$import_media = ($import_media eq 'true');
6a9e55b0 59
2045e293 60# Export media files on push
86e95ef2 61my $export_media = run_git("config --get --bool remote.${remotename}.mediaexport");
2045e293 62chomp($export_media);
86e95ef2 63$export_media = !($export_media eq 'false');
2045e293 64
86e95ef2 65my $wiki_login = run_git("config --get remote.${remotename}.mwLogin");
2da7830d 66# Note: mwPassword is discourraged. Use the credential system instead.
86e95ef2
CM
67my $wiki_passwd = run_git("config --get remote.${remotename}.mwPassword");
68my $wiki_domain = run_git("config --get remote.${remotename}.mwDomain");
428c995c
JN
69chomp($wiki_login);
70chomp($wiki_passwd);
1d6abac9 71chomp($wiki_domain);
428c995c
JN
72
73# Import only last revisions (both for clone and fetch)
86e95ef2 74my $shallow_import = run_git("config --get --bool remote.${remotename}.shallow");
428c995c 75chomp($shallow_import);
86e95ef2 76$shallow_import = ($shallow_import eq 'true');
428c995c 77
5a29217d
MM
78# Fetch (clone and pull) by revisions instead of by pages. This behavior
79# is more efficient when we have a wiki with lots of pages and we fetch
80# the revisions quite often so that they concern only few pages.
81# Possible values:
82# - by_rev: perform one query per new revision on the remote wiki
83# - by_page: query each tracked page for new revision
86e95ef2 84my $fetch_strategy = run_git("config --get remote.${remotename}.fetchStrategy");
5a29217d 85unless ($fetch_strategy) {
86e95ef2 86 $fetch_strategy = run_git('config --get mediawiki.fetchStrategy');
5a29217d
MM
87}
88chomp($fetch_strategy);
89unless ($fetch_strategy) {
86e95ef2 90 $fetch_strategy = 'by_page';
5a29217d
MM
91}
92
0afd29e2
CM
93# Remember the timestamp corresponding to a revision id.
94my %basetimestamps;
95
93f0d338
MM
96# Dumb push: don't update notes and mediawiki ref to reflect the last push.
97#
98# Configurable with mediawiki.dumbPush, or per-remote with
99# remote.<remotename>.dumbPush.
100#
101# This means the user will have to re-import the just-pushed
102# revisions. On the other hand, this means that the Git revisions
103# corresponding to MediaWiki revisions are all imported from the wiki,
104# regardless of whether they were initially created in Git or from the
105# web interface, hence all users will get the same history (i.e. if
106# the push from Git to MediaWiki loses some information, everybody
107# will get the history with information lost). If the import is
108# deterministic, this means everybody gets the same sha1 for each
109# MediaWiki revision.
86e95ef2 110my $dumb_push = run_git("config --get --bool remote.${remotename}.dumbPush");
93f0d338 111unless ($dumb_push) {
86e95ef2 112 $dumb_push = run_git('config --get --bool mediawiki.dumbPush');
93f0d338
MM
113}
114chomp($dumb_push);
86e95ef2 115$dumb_push = ($dumb_push eq 'true');
93f0d338 116
428c995c 117my $wiki_name = $url;
857f21a3 118$wiki_name =~ s{[^/]*://}{};
9fb79503
MM
119# If URL is like http://user:password@example.com/, we clearly don't
120# want the password in $wiki_name. While we're there, also remove user
121# and '@' sign, to avoid author like MWUser@HTTPUser@host.com
122$wiki_name =~ s/^.*@//;
428c995c
JN
123
124# Commands parser
428c995c
JN
125while (<STDIN>) {
126 chomp;
6a316bee
CM
127
128 if (!parse_command($_)) {
428c995c
JN
129 last;
130 }
131
132 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
133 # command is fully processed.
134}
135
136########################## Functions ##############################
137
6a316bee
CM
138sub parse_command {
139 my ($line) = @_;
140 my @cmd = split(/ /, $line);
141 if (!defined $cmd[0]) {
142 return 0;
143 }
86e95ef2 144 if ($cmd[0] eq 'capabilities') {
6a316bee
CM
145 die("Too many arguments for capabilities\n")
146 if (defined($cmd[1]));
147 mw_capabilities();
86e95ef2 148 } elsif ($cmd[0] eq 'list') {
6a316bee
CM
149 die("Too many arguments for list\n") if (defined($cmd[2]));
150 mw_list($cmd[1]);
86e95ef2 151 } elsif ($cmd[0] eq 'import') {
6a316bee
CM
152 die("Invalid arguments for import\n")
153 if ($cmd[1] eq "" || defined($cmd[2]));
154 mw_import($cmd[1]);
86e95ef2 155 } elsif ($cmd[0] eq 'option') {
6a316bee
CM
156 die("Too many arguments for option\n")
157 if ($cmd[1] eq "" || $cmd[2] eq "" || defined($cmd[3]));
158 mw_option($cmd[1],$cmd[2]);
86e95ef2 159 } elsif ($cmd[0] eq 'push') {
6a316bee
CM
160 mw_push($cmd[1]);
161 } else {
162 print STDERR "Unknown command. Aborting...\n";
163 return 0;
164 }
165 return 1;
166}
167
428c995c
JN
168# MediaWiki API instance, created lazily.
169my $mediawiki;
170
171sub mw_connect_maybe {
172 if ($mediawiki) {
a7271ad1 173 return;
428c995c
JN
174 }
175 $mediawiki = MediaWiki::API->new;
86e95ef2 176 $mediawiki->{config}->{api_url} = "${url}/api.php";
428c995c 177 if ($wiki_login) {
da608b12
BP
178 my %credential = (
179 'url' => $url,
180 'username' => $wiki_login,
181 'password' => $wiki_passwd
182 );
183 Git::credential(\%credential);
a7271ad1
MM
184 my $request = {lgname => $credential{username},
185 lgpassword => $credential{password},
186 lgdomain => $wiki_domain};
187 if ($mediawiki->login($request)) {
da608b12 188 Git::credential(\%credential, 'approve');
86e95ef2 189 print STDERR qq(Logged in mediawiki user "$credential{username}".\n);
428c995c 190 } else {
86e95ef2
CM
191 print STDERR qq(Failed to log in mediawiki user "$credential{username}" on ${url}\n);
192 print STDERR ' (error ' .
a7271ad1
MM
193 $mediawiki->{error}->{code} . ': ' .
194 $mediawiki->{error}->{details} . ")\n";
da608b12 195 Git::credential(\%credential, 'reject');
a7271ad1 196 exit 1;
428c995c
JN
197 }
198 }
1aff8c62 199 return;
428c995c
JN
200}
201
0aa03212
MM
202sub fatal_mw_error {
203 my $action = shift;
204 print STDERR "fatal: could not $action.\n";
205 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
206 if ($url =~ /^https/) {
207 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
208 print STDERR "fatal: and the SSL certificate is correct.\n";
209 } else {
210 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
211 }
212 print STDERR "fatal: (error " .
213 $mediawiki->{error}->{code} . ': ' .
214 $mediawiki->{error}->{details} . ")\n";
215 exit 1;
216}
217
9cb74f36
MM
218## Functions for listing pages on the remote wiki
219sub get_mw_tracked_pages {
220 my $pages = shift;
6df7e0df 221 get_mw_page_list(\@tracked_pages, $pages);
1aff8c62 222 return;
6df7e0df
MM
223}
224
225sub get_mw_page_list {
226 my $page_list = shift;
227 my $pages = shift;
228 my @some_pages = @$page_list;
9cb74f36 229 while (@some_pages) {
b835baf6
CM
230 my $last_page = 50;
231 if ($#some_pages < $last_page) {
232 $last_page = $#some_pages;
9cb74f36 233 }
b835baf6 234 my @slice = @some_pages[0..$last_page];
9cb74f36
MM
235 get_mw_first_pages(\@slice, $pages);
236 @some_pages = @some_pages[51..$#some_pages];
237 }
1aff8c62 238 return;
9cb74f36
MM
239}
240
241sub get_mw_tracked_categories {
242 my $pages = shift;
243 foreach my $category (@tracked_categories) {
244 if (index($category, ':') < 0) {
245 # Mediawiki requires the Category
246 # prefix, but let's not force the user
247 # to specify it.
86e95ef2 248 $category = "Category:${category}";
9cb74f36
MM
249 }
250 my $mw_pages = $mediawiki->list( {
251 action => 'query',
252 list => 'categorymembers',
253 cmtitle => $category,
254 cmlimit => 'max' } )
255 || die $mediawiki->{error}->{code} . ': '
8a43b36a 256 . $mediawiki->{error}->{details} . "\n";
9cb74f36
MM
257 foreach my $page (@{$mw_pages}) {
258 $pages->{$page->{title}} = $page;
259 }
260 }
1aff8c62 261 return;
9cb74f36
MM
262}
263
264sub get_mw_all_pages {
265 my $pages = shift;
266 # No user-provided list, get the list of pages from the API.
267 my $mw_pages = $mediawiki->list({
268 action => 'query',
269 list => 'allpages',
270 aplimit => 'max'
271 });
272 if (!defined($mw_pages)) {
0aa03212 273 fatal_mw_error("get the list of wiki pages");
9cb74f36
MM
274 }
275 foreach my $page (@{$mw_pages}) {
276 $pages->{$page->{title}} = $page;
277 }
1aff8c62 278 return;
9cb74f36
MM
279}
280
281# queries the wiki for a set of pages. Meant to be used within a loop
282# querying the wiki for slices of page list.
428c995c
JN
283sub get_mw_first_pages {
284 my $some_pages = shift;
285 my @some_pages = @{$some_pages};
286
287 my $pages = shift;
288
289 # pattern 'page1|page2|...' required by the API
290 my $titles = join('|', @some_pages);
291
292 my $mw_pages = $mediawiki->api({
293 action => 'query',
294 titles => $titles,
295 });
296 if (!defined($mw_pages)) {
0aa03212 297 fatal_mw_error("query the list of wiki pages");
428c995c
JN
298 }
299 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
300 if ($id < 0) {
301 print STDERR "Warning: page $page->{title} not found on wiki\n";
302 } else {
303 $pages->{$page->{title}} = $page;
304 }
305 }
1aff8c62 306 return;
428c995c
JN
307}
308
9cb74f36 309# Get the list of pages to be fetched according to configuration.
428c995c
JN
310sub get_mw_pages {
311 mw_connect_maybe();
312
f690ddfd
MM
313 print STDERR "Listing pages on remote wiki...\n";
314
428c995c
JN
315 my %pages; # hash on page titles to avoid duplicates
316 my $user_defined;
317 if (@tracked_pages) {
318 $user_defined = 1;
319 # The user provided a list of pages titles, but we
320 # still need to query the API to get the page IDs.
9cb74f36 321 get_mw_tracked_pages(\%pages);
428c995c
JN
322 }
323 if (@tracked_categories) {
324 $user_defined = 1;
9cb74f36 325 get_mw_tracked_categories(\%pages);
428c995c
JN
326 }
327 if (!$user_defined) {
9cb74f36 328 get_mw_all_pages(\%pages);
428c995c 329 }
6a9e55b0
PV
330 if ($import_media) {
331 print STDERR "Getting media files for selected pages...\n";
332 if ($user_defined) {
333 get_linked_mediafiles(\%pages);
334 } else {
335 get_all_mediafiles(\%pages);
428c995c
JN
336 }
337 }
f690ddfd 338 print STDERR (scalar keys %pages) . " pages found.\n";
b1ede9a9 339 return %pages;
428c995c
JN
340}
341
b3d98595
NKT
342# usage: $out = run_git("command args");
343# $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
428c995c 344sub run_git {
b3d98595 345 my $args = shift;
86e95ef2
CM
346 my $encoding = (shift || 'encoding(UTF-8)');
347 open(my $git, "-|:${encoding}", "git ${args}")
348 or die "Unable to fork: $!\n";
4f1b7883
CM
349 my $res = do {
350 local $/ = undef;
351 <$git>
352 };
428c995c
JN
353 close($git);
354
355 return $res;
356}
357
358
6a9e55b0
PV
359sub get_all_mediafiles {
360 my $pages = shift;
361 # Attach list of all pages for media files from the API,
362 # they are in a different namespace, only one namespace
363 # can be queried at the same moment
364 my $mw_pages = $mediawiki->list({
365 action => 'query',
366 list => 'allpages',
86e95ef2 367 apnamespace => get_mw_namespace_id('File'),
6a9e55b0
PV
368 aplimit => 'max'
369 });
370 if (!defined($mw_pages)) {
371 print STDERR "fatal: could not get the list of pages for media files.\n";
372 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
373 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
374 exit 1;
375 }
376 foreach my $page (@{$mw_pages}) {
377 $pages->{$page->{title}} = $page;
378 }
1aff8c62 379 return;
6a9e55b0
PV
380}
381
382sub get_linked_mediafiles {
383 my $pages = shift;
81f6a7a4 384 my @titles = map { $_->{title} } values(%{$pages});
6a9e55b0
PV
385
386 # The query is split in small batches because of the MW API limit of
387 # the number of links to be returned (500 links max).
388 my $batch = 10;
389 while (@titles) {
390 if ($#titles < $batch) {
391 $batch = $#titles;
392 }
393 my @slice = @titles[0..$batch];
394
395 # pattern 'page1|page2|...' required by the API
396 my $mw_titles = join('|', @slice);
397
398 # Media files could be included or linked from
399 # a page, get all related
400 my $query = {
401 action => 'query',
402 prop => 'links|images',
403 titles => $mw_titles,
86e95ef2 404 plnamespace => get_mw_namespace_id('File'),
6a9e55b0
PV
405 pllimit => 'max'
406 };
407 my $result = $mediawiki->api($query);
408
409 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
6df7e0df 410 my @media_titles;
6a9e55b0 411 if (defined($page->{links})) {
81f6a7a4
CM
412 my @link_titles
413 = map { $_->{title} } @{$page->{links}};
6df7e0df 414 push(@media_titles, @link_titles);
6a9e55b0
PV
415 }
416 if (defined($page->{images})) {
81f6a7a4
CM
417 my @image_titles
418 = map { $_->{title} } @{$page->{images}};
6df7e0df 419 push(@media_titles, @image_titles);
6a9e55b0 420 }
6df7e0df
MM
421 if (@media_titles) {
422 get_mw_page_list(\@media_titles, $pages);
6a9e55b0
PV
423 }
424 }
425
426 @titles = @titles[($batch+1)..$#titles];
427 }
1aff8c62 428 return;
6a9e55b0
PV
429}
430
431sub get_mw_mediafile_for_page_revision {
432 # Name of the file on Wiki, with the prefix.
6df7e0df 433 my $filename = shift;
6a9e55b0
PV
434 my $timestamp = shift;
435 my %mediafile;
436
6df7e0df
MM
437 # Search if on a media file with given timestamp exists on
438 # MediaWiki. In that case download the file.
6a9e55b0
PV
439 my $query = {
440 action => 'query',
441 prop => 'imageinfo',
86e95ef2 442 titles => "File:${filename}",
6a9e55b0
PV
443 iistart => $timestamp,
444 iiend => $timestamp,
445 iiprop => 'timestamp|archivename|url',
446 iilimit => 1
447 };
448 my $result = $mediawiki->api($query);
449
6df7e0df 450 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
6a9e55b0
PV
451 # If not defined it means there is no revision of the file for
452 # given timestamp.
453 if (defined($file->{imageinfo})) {
6a9e55b0
PV
454 $mediafile{title} = $filename;
455
456 my $fileinfo = pop(@{$file->{imageinfo}});
457 $mediafile{timestamp} = $fileinfo->{timestamp};
6df7e0df
MM
458 # Mediawiki::API's download function doesn't support https URLs
459 # and can't download old versions of files.
460 print STDERR "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
461 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
6a9e55b0
PV
462 }
463 return %mediafile;
464}
465
6df7e0df 466sub download_mw_mediafile {
8f04f7dd 467 my $download_url = shift;
6a9e55b0 468
8f04f7dd 469 my $response = $mediawiki->{ua}->get($download_url);
6df7e0df
MM
470 if ($response->code == 200) {
471 return $response->decoded_content;
6a9e55b0 472 } else {
6df7e0df 473 print STDERR "Error downloading mediafile from :\n";
86e95ef2
CM
474 print STDERR "URL: ${download_url}\n";
475 print STDERR 'Server response: ' . $response->code . q{ } . $response->message . "\n";
6a9e55b0 476 exit 1;
6a9e55b0
PV
477 }
478}
479
428c995c
JN
480sub get_last_local_revision {
481 # Get note regarding last mediawiki revision
86e95ef2 482 my $note = run_git("notes --ref=${remotename}/mediawiki show refs/mediawiki/${remotename}/master 2>/dev/null");
428c995c
JN
483 my @note_info = split(/ /, $note);
484
485 my $lastrevision_number;
86e95ef2
CM
486 if (!(defined($note_info[0]) && $note_info[0] eq 'mediawiki_revision:')) {
487 print STDERR 'No previous mediawiki revision found';
428c995c
JN
488 $lastrevision_number = 0;
489 } else {
490 # Notes are formatted : mediawiki_revision: #number
491 $lastrevision_number = $note_info[1];
492 chomp($lastrevision_number);
86e95ef2 493 print STDERR "Last local mediawiki revision found is ${lastrevision_number}";
428c995c
JN
494 }
495 return $lastrevision_number;
496}
497
5a29217d
MM
498# Get the last remote revision without taking in account which pages are
499# tracked or not. This function makes a single request to the wiki thus
500# avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
501# option.
502sub get_last_global_remote_rev {
503 mw_connect_maybe();
504
505 my $query = {
506 action => 'query',
507 list => 'recentchanges',
508 prop => 'revisions',
509 rclimit => '1',
510 rcdir => 'older',
511 };
512 my $result = $mediawiki->api($query);
513 return $result->{query}->{recentchanges}[0]->{revid};
514}
515
516# Get the last remote revision concerning the tracked pages and the tracked
517# categories.
428c995c
JN
518sub get_last_remote_revision {
519 mw_connect_maybe();
520
b1ede9a9
MM
521 my %pages_hash = get_mw_pages();
522 my @pages = values(%pages_hash);
428c995c
JN
523
524 my $max_rev_num = 0;
525
a393f488
MM
526 print STDERR "Getting last revision id on tracked pages...\n";
527
428c995c
JN
528 foreach my $page (@pages) {
529 my $id = $page->{pageid};
530
531 my $query = {
532 action => 'query',
533 prop => 'revisions',
3c1ed90e 534 rvprop => 'ids|timestamp',
428c995c
JN
535 pageids => $id,
536 };
537
538 my $result = $mediawiki->api($query);
539
540 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
541
3c1ed90e
MM
542 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
543
428c995c
JN
544 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
545 }
546
547 print STDERR "Last remote revision found is $max_rev_num.\n";
548 return $max_rev_num;
549}
550
551# Clean content before sending it to MediaWiki
552sub mediawiki_clean {
553 my $string = shift;
554 my $page_created = shift;
555 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
556 # This function right trims a string and adds a \n at the end to follow this rule
557 $string =~ s/\s+$//;
558 if ($string eq "" && $page_created) {
559 # Creating empty pages is forbidden.
560 $string = EMPTY_CONTENT;
561 }
562 return $string."\n";
563}
564
565# Filter applied on MediaWiki data before adding them to Git
566sub mediawiki_smudge {
567 my $string = shift;
568 if ($string eq EMPTY_CONTENT) {
569 $string = "";
570 }
571 # This \n is important. This is due to mediawiki's way to handle end of files.
86e95ef2 572 return "${string}\n";
428c995c
JN
573}
574
575sub mediawiki_clean_filename {
576 my $filename = shift;
857f21a3 577 $filename =~ s{@{[SLASH_REPLACEMENT]}}{/}g;
428c995c
JN
578 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
579 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
580 # but with _ added to prevent MediaWiki from thinking this is
581 # an actual special character.
582 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
583 # If we use the uri escape before
584 # we should unescape here, before anything
585
586 return $filename;
587}
588
589sub mediawiki_smudge_filename {
590 my $filename = shift;
857f21a3 591 $filename =~ s{/}{@{[SLASH_REPLACEMENT]}}g;
428c995c
JN
592 $filename =~ s/ /_/g;
593 # Decode forbidden characters encoded in mediawiki_clean_filename
86e95ef2 594 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf('%c', hex($1))/ge;
428c995c
JN
595 return $filename;
596}
597
598sub literal_data {
599 my ($content) = @_;
86e95ef2 600 print STDOUT 'data ', bytes::length($content), "\n", $content;
1aff8c62 601 return;
428c995c
JN
602}
603
6a9e55b0
PV
604sub literal_data_raw {
605 # Output possibly binary content.
606 my ($content) = @_;
607 # Avoid confusion between size in bytes and in characters
608 utf8::downgrade($content);
86e95ef2
CM
609 binmode STDOUT, ':raw';
610 print STDOUT 'data ', bytes::length($content), "\n", $content;
611 binmode STDOUT, ':encoding(UTF-8)';
1aff8c62 612 return;
6a9e55b0
PV
613}
614
428c995c
JN
615sub mw_capabilities {
616 # Revisions are imported to the private namespace
617 # refs/mediawiki/$remotename/ by the helper and fetched into
618 # refs/remotes/$remotename later by fetch.
86e95ef2 619 print STDOUT "refspec refs/heads/*:refs/mediawiki/${remotename}/*\n";
428c995c
JN
620 print STDOUT "import\n";
621 print STDOUT "list\n";
622 print STDOUT "push\n";
623 print STDOUT "\n";
1aff8c62 624 return;
428c995c
JN
625}
626
627sub mw_list {
628 # MediaWiki do not have branches, we consider one branch arbitrarily
629 # called master, and HEAD pointing to it.
630 print STDOUT "? refs/heads/master\n";
631 print STDOUT "\@refs/heads/master HEAD\n";
632 print STDOUT "\n";
1aff8c62 633 return;
428c995c
JN
634}
635
636sub mw_option {
637 print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
638 print STDOUT "unsupported\n";
1aff8c62 639 return;
428c995c
JN
640}
641
642sub fetch_mw_revisions_for_page {
643 my $page = shift;
644 my $id = shift;
645 my $fetch_from = shift;
646 my @page_revs = ();
647 my $query = {
648 action => 'query',
649 prop => 'revisions',
650 rvprop => 'ids',
651 rvdir => 'newer',
652 rvstartid => $fetch_from,
653 rvlimit => 500,
654 pageids => $id,
655 };
656
657 my $revnum = 0;
658 # Get 500 revisions at a time due to the mediawiki api limit
659 while (1) {
660 my $result = $mediawiki->api($query);
661
662 # Parse each of those 500 revisions
663 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
664 my $page_rev_ids;
665 $page_rev_ids->{pageid} = $page->{pageid};
666 $page_rev_ids->{revid} = $revision->{revid};
667 push(@page_revs, $page_rev_ids);
668 $revnum++;
669 }
670 last unless $result->{'query-continue'};
671 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
672 }
673 if ($shallow_import && @page_revs) {
674 print STDERR " Found 1 revision (shallow import).\n";
675 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
676 return $page_revs[0];
677 }
86e95ef2 678 print STDERR " Found ${revnum} revision(s).\n";
428c995c
JN
679 return @page_revs;
680}
681
682sub fetch_mw_revisions {
683 my $pages = shift; my @pages = @{$pages};
684 my $fetch_from = shift;
685
686 my @revisions = ();
687 my $n = 1;
688 foreach my $page (@pages) {
689 my $id = $page->{pageid};
86e95ef2 690 print STDERR "page ${n}/", scalar(@pages), ': ', $page->{title}, "\n";
428c995c
JN
691 $n++;
692 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
693 @revisions = (@page_revs, @revisions);
694 }
695
696 return ($n, @revisions);
697}
698
462d97da
MM
699sub fe_escape_path {
700 my $path = shift;
701 $path =~ s/\\/\\\\/g;
702 $path =~ s/"/\\"/g;
703 $path =~ s/\n/\\n/g;
86e95ef2 704 return qq("${path}");
462d97da
MM
705}
706
428c995c
JN
707sub import_file_revision {
708 my $commit = shift;
709 my %commit = %{$commit};
710 my $full_import = shift;
711 my $n = shift;
6a9e55b0
PV
712 my $mediafile = shift;
713 my %mediafile;
714 if ($mediafile) {
715 %mediafile = %{$mediafile};
716 }
428c995c
JN
717
718 my $title = $commit{title};
719 my $comment = $commit{comment};
720 my $content = $commit{content};
721 my $author = $commit{author};
722 my $date = $commit{date};
723
86e95ef2
CM
724 print STDOUT "commit refs/mediawiki/${remotename}/master\n";
725 print STDOUT "mark :${n}\n";
726 print STDOUT "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
428c995c
JN
727 literal_data($comment);
728
729 # If it's not a clone, we need to know where to start from
730 if (!$full_import && $n == 1) {
86e95ef2 731 print STDOUT "from refs/mediawiki/${remotename}/master^0\n";
428c995c
JN
732 }
733 if ($content ne DELETED_CONTENT) {
86e95ef2
CM
734 print STDOUT 'M 644 inline ' .
735 fe_escape_path("${title}.mw") . "\n";
428c995c 736 literal_data($content);
6a9e55b0 737 if (%mediafile) {
86e95ef2 738 print STDOUT 'M 644 inline '
462d97da 739 . fe_escape_path($mediafile{title}) . "\n";
6a9e55b0
PV
740 literal_data_raw($mediafile{content});
741 }
428c995c
JN
742 print STDOUT "\n\n";
743 } else {
86e95ef2 744 print STDOUT 'D ' . fe_escape_path("${title}.mw") . "\n";
428c995c
JN
745 }
746
747 # mediawiki revision number in the git note
748 if ($full_import && $n == 1) {
86e95ef2 749 print STDOUT "reset refs/notes/${remotename}/mediawiki\n";
428c995c 750 }
86e95ef2
CM
751 print STDOUT "commit refs/notes/${remotename}/mediawiki\n";
752 print STDOUT "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
753 literal_data('Note added by git-mediawiki during import');
428c995c 754 if (!$full_import && $n == 1) {
86e95ef2 755 print STDOUT "from refs/notes/${remotename}/mediawiki^0\n";
428c995c 756 }
86e95ef2
CM
757 print STDOUT "N inline :${n}\n";
758 literal_data("mediawiki_revision: $commit{mw_revision}");
428c995c 759 print STDOUT "\n\n";
1aff8c62 760 return;
428c995c
JN
761}
762
763# parse a sequence of
764# <cmd> <arg1>
765# <cmd> <arg2>
766# \n
767# (like batch sequence of import and sequence of push statements)
768sub get_more_refs {
769 my $cmd = shift;
770 my @refs;
771 while (1) {
772 my $line = <STDIN>;
eb96b750 773 if ($line =~ /^$cmd (.*)$/) {
428c995c
JN
774 push(@refs, $1);
775 } elsif ($line eq "\n") {
776 return @refs;
777 } else {
8a43b36a 778 die("Invalid command in a '$cmd' batch: $_\n");
428c995c
JN
779 }
780 }
1aff8c62 781 return;
428c995c
JN
782}
783
784sub mw_import {
785 # multiple import commands can follow each other.
86e95ef2 786 my @refs = (shift, get_more_refs('import'));
428c995c
JN
787 foreach my $ref (@refs) {
788 mw_import_ref($ref);
789 }
790 print STDOUT "done\n";
1aff8c62 791 return;
428c995c
JN
792}
793
794sub mw_import_ref {
795 my $ref = shift;
796 # The remote helper will call "import HEAD" and
797 # "import refs/heads/master".
798 # Since HEAD is a symbolic ref to master (by convention,
799 # followed by the output of the command "list" that we gave),
800 # we don't need to do anything in this case.
86e95ef2 801 if ($ref eq 'HEAD') {
428c995c
JN
802 return;
803 }
804
805 mw_connect_maybe();
806
428c995c
JN
807 print STDERR "Searching revisions...\n";
808 my $last_local = get_last_local_revision();
809 my $fetch_from = $last_local + 1;
810 if ($fetch_from == 1) {
811 print STDERR ", fetching from beginning.\n";
812 } else {
813 print STDERR ", fetching from here.\n";
814 }
428c995c 815
5a29217d 816 my $n = 0;
86e95ef2 817 if ($fetch_strategy eq 'by_rev') {
5a29217d
MM
818 print STDERR "Fetching & writing export data by revs...\n";
819 $n = mw_import_ref_by_revs($fetch_from);
86e95ef2 820 } elsif ($fetch_strategy eq 'by_page') {
5a29217d
MM
821 print STDERR "Fetching & writing export data by pages...\n";
822 $n = mw_import_ref_by_pages($fetch_from);
823 } else {
86e95ef2
CM
824 print STDERR qq(fatal: invalid fetch strategy "${fetch_strategy}".\n);
825 print STDERR "Check your configuration variables remote.${remotename}.fetchStrategy and mediawiki.fetchStrategy\n";
5a29217d
MM
826 exit 1;
827 }
828
829 if ($fetch_from == 1 && $n == 0) {
830 print STDERR "You appear to have cloned an empty MediaWiki.\n";
831 # Something has to be done remote-helper side. If nothing is done, an error is
2582ab18 832 # thrown saying that HEAD is referring to unknown object 0000000000000000000
5a29217d
MM
833 # and the clone fails.
834 }
1aff8c62 835 return;
5a29217d
MM
836}
837
838sub mw_import_ref_by_pages {
839
840 my $fetch_from = shift;
841 my %pages_hash = get_mw_pages();
842 my @pages = values(%pages_hash);
843
428c995c
JN
844 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
845
4465b6d6 846 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
81f6a7a4 847 my @revision_ids = map { $_->{revid} } @revisions;
4465b6d6 848
312fa9aa
MM
849 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
850}
851
5a29217d
MM
852sub mw_import_ref_by_revs {
853
854 my $fetch_from = shift;
855 my %pages_hash = get_mw_pages();
428c995c 856
5a29217d
MM
857 my $last_remote = get_last_global_remote_rev();
858 my @revision_ids = $fetch_from..$last_remote;
859 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
860}
861
862# Import revisions given in second argument (array of integers).
863# Only pages appearing in the third argument (hash indexed by page titles)
864# will be imported.
312fa9aa
MM
865sub mw_import_revids {
866 my $fetch_from = shift;
867 my $revision_ids = shift;
868 my $pages = shift;
869
870 my $n = 0;
5a29217d 871 my $n_actual = 0;
428c995c
JN
872 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
873
312fa9aa 874 foreach my $pagerevid (@$revision_ids) {
ebd5fe1c
MM
875 # Count page even if we skip it, since we display
876 # $n/$total and $total includes skipped pages.
877 $n++;
878
428c995c
JN
879 # fetch the content of the pages
880 my $query = {
881 action => 'query',
882 prop => 'revisions',
883 rvprop => 'content|timestamp|comment|user|ids',
4465b6d6 884 revids => $pagerevid,
428c995c
JN
885 };
886
887 my $result = $mediawiki->api($query);
888
ff0bfd75 889 if (!$result) {
8a43b36a 890 die "Failed to retrieve modified page for revision $pagerevid\n";
ff0bfd75
MM
891 }
892
ebd5fe1c
MM
893 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
894 # The revision id does not exist on the remote wiki.
895 next;
896 }
897
ff0bfd75 898 if (!defined($result->{query}->{pages})) {
86e95ef2 899 die "Invalid revision ${pagerevid}.\n";
ff0bfd75
MM
900 }
901
4465b6d6
MM
902 my @result_pages = values(%{$result->{query}->{pages}});
903 my $result_page = $result_pages[0];
904 my $rev = $result_pages[0]->{revisions}->[0];
428c995c 905
4465b6d6 906 my $page_title = $result_page->{title};
5a29217d
MM
907
908 if (!exists($pages->{$page_title})) {
86e95ef2
CM
909 print STDERR "${n}/", scalar(@$revision_ids),
910 ": Skipping revision #$rev->{revid} of ${page_title}\n";
5a29217d
MM
911 next;
912 }
913
914 $n_actual++;
915
428c995c
JN
916 my %commit;
917 $commit{author} = $rev->{user} || 'Anonymous';
dcb1ea62 918 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
6a9e55b0 919 $commit{title} = mediawiki_smudge_filename($page_title);
4465b6d6 920 $commit{mw_revision} = $rev->{revid};
428c995c
JN
921 $commit{content} = mediawiki_smudge($rev->{'*'});
922
923 if (!defined($rev->{timestamp})) {
924 $last_timestamp++;
925 } else {
926 $last_timestamp = $rev->{timestamp};
927 }
928 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
929
6a9e55b0 930 # Differentiates classic pages and media files.
6df7e0df 931 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
6a9e55b0 932 my %mediafile;
2272400c
MM
933 if ($namespace) {
934 my $id = get_mw_namespace_id($namespace);
86e95ef2 935 if ($id && $id == get_mw_namespace_id('File')) {
2272400c
MM
936 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
937 }
6a9e55b0
PV
938 }
939 # If this is a revision of the media page for new version
940 # of a file do one common commit for both file and media page.
941 # Else do commit only for that page.
86e95ef2 942 print STDERR "${n}/", scalar(@$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
5a29217d 943 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
428c995c
JN
944 }
945
5a29217d 946 return $n_actual;
428c995c
JN
947}
948
949sub error_non_fast_forward {
86e95ef2 950 my $advice = run_git('config --bool advice.pushNonFastForward');
fd47d7b9 951 chomp($advice);
86e95ef2 952 if ($advice ne 'false') {
fd47d7b9
MM
953 # Native git-push would show this after the summary.
954 # We can't ask it to display it cleanly, so print it
955 # ourselves before.
956 print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
957 print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
958 print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
959 }
86e95ef2 960 print STDOUT qq(error $_[0] "non-fast-forward"\n);
428c995c
JN
961 return 0;
962}
963
b3d98595
NKT
964sub mw_upload_file {
965 my $complete_file_name = shift;
966 my $new_sha1 = shift;
967 my $extension = shift;
968 my $file_deleted = shift;
969 my $summary = shift;
970 my $newrevid;
86e95ef2 971 my $path = "File:${complete_file_name}";
b3d98595
NKT
972 my %hashFiles = get_allowed_file_extensions();
973 if (!exists($hashFiles{$extension})) {
86e95ef2 974 print STDERR "${complete_file_name} is not a permitted file on this wiki.\n";
b3d98595
NKT
975 print STDERR "Check the configuration of file uploads in your mediawiki.\n";
976 return $newrevid;
977 }
978 # Deleting and uploading a file requires a priviledged user
979 if ($file_deleted) {
980 mw_connect_maybe();
981 my $query = {
982 action => 'delete',
983 title => $path,
984 reason => $summary
985 };
986 if (!$mediawiki->edit($query)) {
987 print STDERR "Failed to delete file on remote wiki\n";
988 print STDERR "Check your permissions on the remote site. Error code:\n";
989 print STDERR $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
990 exit 1;
991 }
992 } else {
993 # Don't let perl try to interpret file content as UTF-8 => use "raw"
86e95ef2 994 my $content = run_git("cat-file blob ${new_sha1}", 'raw');
b3d98595
NKT
995 if ($content ne "") {
996 mw_connect_maybe();
997 $mediawiki->{config}->{upload_url} =
86e95ef2 998 "${url}/index.php/Special:Upload";
b3d98595
NKT
999 $mediawiki->edit({
1000 action => 'upload',
1001 filename => $complete_file_name,
1002 comment => $summary,
1003 file => [undef,
1004 $complete_file_name,
1005 Content => $content],
1006 ignorewarnings => 1,
1007 }, {
1008 skip_encoding => 1
1009 } ) || die $mediawiki->{error}->{code} . ':'
8a43b36a 1010 . $mediawiki->{error}->{details} . "\n";
b3d98595
NKT
1011 my $last_file_page = $mediawiki->get_page({title => $path});
1012 $newrevid = $last_file_page->{revid};
86e95ef2 1013 print STDERR "Pushed file: ${new_sha1} - ${complete_file_name}.\n";
b3d98595 1014 } else {
86e95ef2 1015 print STDERR "Empty file ${complete_file_name} not pushed.\n";
b3d98595
NKT
1016 }
1017 }
1018 return $newrevid;
1019}
1020
428c995c
JN
1021sub mw_push_file {
1022 my $diff_info = shift;
1023 # $diff_info contains a string in this format:
1024 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1025 my @diff_info_split = split(/[ \t]/, $diff_info);
1026
1027 # Filename, including .mw extension
1028 my $complete_file_name = shift;
1029 # Commit message
1030 my $summary = shift;
93f0d338
MM
1031 # MediaWiki revision number. Keep the previous one by default,
1032 # in case there's no edit to perform.
b3d98595
NKT
1033 my $oldrevid = shift;
1034 my $newrevid;
428c995c 1035
dcb1ea62
MM
1036 if ($summary eq EMPTY_MESSAGE) {
1037 $summary = '';
1038 }
1039
428c995c
JN
1040 my $new_sha1 = $diff_info_split[3];
1041 my $old_sha1 = $diff_info_split[2];
1042 my $page_created = ($old_sha1 eq NULL_SHA1);
1043 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1044 $complete_file_name = mediawiki_clean_filename($complete_file_name);
1045
b3d98595
NKT
1046 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1047 if (!defined($extension)) {
1048 $extension = "";
1049 }
86e95ef2 1050 if ($extension eq 'mw') {
2045e293 1051 my $ns = get_mw_namespace_id_for_page($complete_file_name);
86e95ef2
CM
1052 if ($ns && $ns == get_mw_namespace_id('File') && (!$export_media)) {
1053 print STDERR "Ignoring media file related page: ${complete_file_name}\n";
1054 return ($oldrevid, 'ok');
2045e293 1055 }
428c995c
JN
1056 my $file_content;
1057 if ($page_deleted) {
1058 # Deleting a page usually requires
2582ab18 1059 # special privileges. A common
428c995c
JN
1060 # convention is to replace the page
1061 # with this content instead:
1062 $file_content = DELETED_CONTENT;
1063 } else {
86e95ef2 1064 $file_content = run_git("cat-file blob ${new_sha1}");
428c995c
JN
1065 }
1066
1067 mw_connect_maybe();
1068
1069 my $result = $mediawiki->edit( {
1070 action => 'edit',
1071 summary => $summary,
1072 title => $title,
b3d98595 1073 basetimestamp => $basetimestamps{$oldrevid},
428c995c
JN
1074 text => mediawiki_clean($file_content, $page_created),
1075 }, {
1076 skip_encoding => 1 # Helps with names with accentuated characters
3c1ed90e
MM
1077 });
1078 if (!$result) {
1079 if ($mediawiki->{error}->{code} == 3) {
1080 # edit conflicts, considered as non-fast-forward
1081 print STDERR 'Warning: Error ' .
1082 $mediawiki->{error}->{code} .
1083 ' from mediwiki: ' . $mediawiki->{error}->{details} .
1084 ".\n";
86e95ef2 1085 return ($oldrevid, 'non-fast-forward');
3c1ed90e
MM
1086 } else {
1087 # Other errors. Shouldn't happen => just die()
1088 die 'Fatal: Error ' .
1089 $mediawiki->{error}->{code} .
8a43b36a 1090 ' from mediwiki: ' . $mediawiki->{error}->{details} . "\n";
3c1ed90e
MM
1091 }
1092 }
93f0d338 1093 $newrevid = $result->{edit}->{newrevid};
86e95ef2 1094 print STDERR "Pushed file: ${new_sha1} - ${title}\n";
2045e293 1095 } elsif ($export_media) {
b3d98595
NKT
1096 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1097 $extension, $page_deleted,
1098 $summary);
2045e293 1099 } else {
86e95ef2 1100 print STDERR "Ignoring media file ${title}\n";
428c995c 1101 }
b3d98595 1102 $newrevid = ($newrevid or $oldrevid);
86e95ef2 1103 return ($newrevid, 'ok');
428c995c
JN
1104}
1105
1106sub mw_push {
1107 # multiple push statements can follow each other
86e95ef2 1108 my @refsspecs = (shift, get_more_refs('push'));
428c995c
JN
1109 my $pushed;
1110 for my $refspec (@refsspecs) {
1111 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
8a43b36a 1112 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
428c995c
JN
1113 if ($force) {
1114 print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
1115 }
1116 if ($local eq "") {
1117 print STDERR "Cannot delete remote branch on a MediaWiki\n";
86e95ef2 1118 print STDOUT "error ${remote} cannot delete\n";
428c995c
JN
1119 next;
1120 }
86e95ef2 1121 if ($remote ne 'refs/heads/master') {
428c995c 1122 print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
86e95ef2 1123 print STDOUT "error ${remote} only master allowed\n";
428c995c
JN
1124 next;
1125 }
1126 if (mw_push_revision($local, $remote)) {
1127 $pushed = 1;
1128 }
1129 }
1130
1131 # Notify Git that the push is done
1132 print STDOUT "\n";
1133
93f0d338 1134 if ($pushed && $dumb_push) {
428c995c
JN
1135 print STDERR "Just pushed some revisions to MediaWiki.\n";
1136 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
1137 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
1138 print STDERR "\n";
1139 print STDERR " git pull --rebase\n";
1140 print STDERR "\n";
1141 }
1aff8c62 1142 return;
428c995c
JN
1143}
1144
1145sub mw_push_revision {
1146 my $local = shift;
1147 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1148 my $last_local_revid = get_last_local_revision();
1149 print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
1150 my $last_remote_revid = get_last_remote_revision();
93f0d338 1151 my $mw_revision = $last_remote_revid;
428c995c
JN
1152
1153 # Get sha1 of commit pointed by local HEAD
86e95ef2
CM
1154 my $HEAD_sha1 = run_git("rev-parse ${local} 2>/dev/null");
1155 chomp($HEAD_sha1);
428c995c 1156 # Get sha1 of commit pointed by remotes/$remotename/master
86e95ef2 1157 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/${remotename}/master 2>/dev/null");
428c995c
JN
1158 chomp($remoteorigin_sha1);
1159
1160 if ($last_local_revid > 0 &&
1161 $last_local_revid < $last_remote_revid) {
1162 return error_non_fast_forward($remote);
1163 }
1164
1165 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1166 # nothing to push
1167 return 0;
1168 }
1169
1170 # Get every commit in between HEAD and refs/remotes/origin/master,
1171 # including HEAD and refs/remotes/origin/master
1172 my @commit_pairs = ();
1173 if ($last_local_revid > 0) {
1174 my $parsed_sha1 = $remoteorigin_sha1;
1175 # Find a path from last MediaWiki commit to pushed commit
93e92d4d 1176 print STDERR "Computing path from local to remote ...\n";
86e95ef2 1177 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents ${local} ^${parsed_sha1}"));
93e92d4d
MM
1178 my %local_ancestry;
1179 foreach my $line (@local_ancestry) {
eb96b750 1180 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
11499573 1181 foreach my $parent (split(/ /, $parents)) {
93e92d4d
MM
1182 $local_ancestry{$parent} = $child;
1183 }
eb96b750 1184 } elsif (!$line =~ /^([a-f0-9]+)/) {
86e95ef2 1185 die "Unexpected output from git rev-list: ${line}\n";
93e92d4d
MM
1186 }
1187 }
428c995c 1188 while ($parsed_sha1 ne $HEAD_sha1) {
93e92d4d
MM
1189 my $child = $local_ancestry{$parsed_sha1};
1190 if (!$child) {
1191 printf STDERR "Cannot find a path in history from remote commit to last commit\n";
428c995c
JN
1192 return error_non_fast_forward($remote);
1193 }
93e92d4d
MM
1194 push(@commit_pairs, [$parsed_sha1, $child]);
1195 $parsed_sha1 = $child;
428c995c
JN
1196 }
1197 } else {
1198 # No remote mediawiki revision. Export the whole
1199 # history (linearized with --first-parent)
1200 print STDERR "Warning: no common ancestor, pushing complete history\n";
86e95ef2 1201 my $history = run_git("rev-list --first-parent --children ${local}");
05d4c7b1 1202 my @history = split(/\n/, $history);
428c995c
JN
1203 @history = @history[1..$#history];
1204 foreach my $line (reverse @history) {
6b825a46 1205 my @commit_info_split = split(/[ \n]/, $line);
428c995c
JN
1206 push(@commit_pairs, \@commit_info_split);
1207 }
1208 }
1209
1210 foreach my $commit_info_split (@commit_pairs) {
1211 my $sha1_child = @{$commit_info_split}[0];
1212 my $sha1_commit = @{$commit_info_split}[1];
86e95ef2 1213 my $diff_infos = run_git("diff-tree -r --raw -z ${sha1_child} ${sha1_commit}");
428c995c
JN
1214 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1215 # TODO: for now, it's just a delete+add
1216 my @diff_info_list = split(/\0/, $diff_infos);
28c24bd7 1217 # Keep the subject line of the commit message as mediawiki comment for the revision
86e95ef2 1218 my $commit_msg = run_git(qq(log --no-walk --format="%s" ${sha1_commit}));
428c995c
JN
1219 chomp($commit_msg);
1220 # Push every blob
1221 while (@diff_info_list) {
3c1ed90e 1222 my $status;
428c995c
JN
1223 # git diff-tree -z gives an output like
1224 # <metadata>\0<filename1>\0
1225 # <metadata>\0<filename2>\0
1226 # and we've split on \0.
1227 my $info = shift(@diff_info_list);
1228 my $file = shift(@diff_info_list);
3c1ed90e 1229 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
86e95ef2 1230 if ($status eq 'non-fast-forward') {
3c1ed90e
MM
1231 # we may already have sent part of the
1232 # commit to MediaWiki, but it's too
1233 # late to cancel it. Stop the push in
1234 # the middle, but still give an
1235 # accurate error message.
1236 return error_non_fast_forward($remote);
1237 }
86e95ef2 1238 if ($status ne 'ok') {
8a43b36a 1239 die("Unknown error from mw_push_file()\n");
3c1ed90e 1240 }
93f0d338
MM
1241 }
1242 unless ($dumb_push) {
86e95ef2
CM
1243 run_git(qq(notes --ref=${remotename}/mediawiki add -f -m "mediawiki_revision: ${mw_revision}" ${sha1_commit}));
1244 run_git(qq(update-ref -m "Git-MediaWiki push" refs/mediawiki/${remotename}/master ${sha1_commit} ${sha1_child}));
428c995c
JN
1245 }
1246 }
1247
86e95ef2 1248 print STDOUT "ok ${remote}\n";
428c995c
JN
1249 return 1;
1250}
b3d98595
NKT
1251
1252sub get_allowed_file_extensions {
1253 mw_connect_maybe();
1254
1255 my $query = {
1256 action => 'query',
1257 meta => 'siteinfo',
1258 siprop => 'fileextensions'
1259 };
1260 my $result = $mediawiki->api($query);
81f6a7a4
CM
1261 my @file_extensions = map { $_->{ext}} @{$result->{query}->{fileextensions}};
1262 my %hashFile = map { $_ => 1 } @file_extensions;
b3d98595
NKT
1263
1264 return %hashFile;
1265}
6a9e55b0 1266
6df7e0df
MM
1267# In memory cache for MediaWiki namespace ids.
1268my %namespace_id;
1269
1270# Namespaces whose id is cached in the configuration file
1271# (to avoid duplicates)
1272my %cached_mw_namespace_id;
1273
6a9e55b0
PV
1274# Return MediaWiki id for a canonical namespace name.
1275# Ex.: "File", "Project".
6a9e55b0
PV
1276sub get_mw_namespace_id {
1277 mw_connect_maybe();
1278 my $name = shift;
1279
1280 if (!exists $namespace_id{$name}) {
1281 # Look at configuration file, if the record for that namespace is
6df7e0df 1282 # already cached. Namespaces are stored in form:
6a9e55b0 1283 # "Name_of_namespace:Id_namespace", ex.: "File:6".
86e95ef2
CM
1284 my @temp = split(/\n/,
1285 run_git("config --get-all remote.${remotename}.namespaceCache"));
6a9e55b0
PV
1286 chomp(@temp);
1287 foreach my $ns (@temp) {
6df7e0df 1288 my ($n, $id) = split(/:/, $ns);
2272400c
MM
1289 if ($id eq 'notANameSpace') {
1290 $namespace_id{$n} = {is_namespace => 0};
1291 } else {
1292 $namespace_id{$n} = {is_namespace => 1, id => $id};
1293 }
6df7e0df 1294 $cached_mw_namespace_id{$n} = 1;
6a9e55b0
PV
1295 }
1296 }
1297
1298 if (!exists $namespace_id{$name}) {
86e95ef2 1299 print STDERR "Namespace ${name} not found in cache, querying the wiki ...\n";
6a9e55b0
PV
1300 # NS not found => get namespace id from MW and store it in
1301 # configuration file.
1302 my $query = {
1303 action => 'query',
1304 meta => 'siteinfo',
1305 siprop => 'namespaces'
1306 };
1307 my $result = $mediawiki->api($query);
1308
1309 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
6df7e0df 1310 if (defined($ns->{id}) && defined($ns->{canonical})) {
2272400c 1311 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
6df7e0df
MM
1312 if ($ns->{'*'}) {
1313 # alias (e.g. french Fichier: as alias for canonical File:)
2272400c 1314 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
6df7e0df
MM
1315 }
1316 }
6a9e55b0
PV
1317 }
1318 }
1319
2272400c
MM
1320 my $ns = $namespace_id{$name};
1321 my $id;
6df7e0df 1322
2272400c 1323 unless (defined $ns) {
86e95ef2 1324 print STDERR "No such namespace ${name} on MediaWiki.\n";
2272400c
MM
1325 $ns = {is_namespace => 0};
1326 $namespace_id{$name} = $ns;
1327 }
1328
1329 if ($ns->{is_namespace}) {
1330 $id = $ns->{id};
1331 }
1332
1333 # Store "notANameSpace" as special value for inexisting namespaces
1334 my $store_id = ($id || 'notANameSpace');
1335
1336 # Store explicitely requested namespaces on disk
1337 if (!exists $cached_mw_namespace_id{$name}) {
86e95ef2 1338 run_git(qq(config --add remote.${remotename}.namespaceCache "${name}:${store_id}"));
2272400c 1339 $cached_mw_namespace_id{$name} = 1;
6a9e55b0 1340 }
2272400c 1341 return $id;
6a9e55b0 1342}
2045e293
MM
1343
1344sub get_mw_namespace_id_for_page {
6c2fbe25
CM
1345 my $namespace = shift;
1346 if ($namespace =~ /^([^:]*):/) {
2045e293
MM
1347 return get_mw_namespace_id($namespace);
1348 } else {
1349 return;
1350 }
1351}