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