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