git-remote-mediawiki: move "use warnings;" before any instruction
[git/mingw.git] / contrib / mw-to-git / git-remote-mediawiki.perl
blob895e081b6ecde0cd4e0998002badc8fe4249cd33
1 #! /usr/bin/perl
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
11 # Gateway between Git and MediaWiki.
12 # Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
14 use strict;
15 use MediaWiki::API;
16 use Git;
17 use DateTime::Format::ISO8601;
18 use warnings;
20 # By default, use UTF-8 to communicate with Git and the user
21 binmode STDERR, ":utf8";
22 binmode STDOUT, ":utf8";
24 use URI::Escape;
25 use IPC::Open2;
27 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
28 use constant SLASH_REPLACEMENT => "%2F";
30 # It's not always possible to delete pages (may require some
31 # privileges). Deleted pages are replaced with this content.
32 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
34 # It's not possible to create empty pages. New empty files in Git are
35 # sent with this content instead.
36 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
38 # used to reflect file creation or deletion in diff.
39 use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
41 # Used on Git's side to reflect empty edit messages on the wiki
42 use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
44 my $remotename = $ARGV[0];
45 my $url = $ARGV[1];
47 # Accept both space-separated and multiple keys in config file.
48 # Spaces should be written as _ anyway because we'll use chomp.
49 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
50 chomp(@tracked_pages);
52 # Just like @tracked_pages, but for MediaWiki categories.
53 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
54 chomp(@tracked_categories);
56 # Import media files on pull
57 my $import_media = run_git("config --get --bool remote.". $remotename .".mediaimport");
58 chomp($import_media);
59 $import_media = ($import_media eq "true");
61 # Export media files on push
62 my $export_media = run_git("config --get --bool remote.". $remotename .".mediaexport");
63 chomp($export_media);
64 $export_media = !($export_media eq "false");
66 my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
67 # Note: mwPassword is discourraged. Use the credential system instead.
68 my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
69 my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
70 chomp($wiki_login);
71 chomp($wiki_passwd);
72 chomp($wiki_domain);
74 # Import only last revisions (both for clone and fetch)
75 my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
76 chomp($shallow_import);
77 $shallow_import = ($shallow_import eq "true");
79 # Fetch (clone and pull) by revisions instead of by pages. This behavior
80 # is more efficient when we have a wiki with lots of pages and we fetch
81 # the revisions quite often so that they concern only few pages.
82 # Possible values:
83 # - by_rev: perform one query per new revision on the remote wiki
84 # - by_page: query each tracked page for new revision
85 my $fetch_strategy = run_git("config --get remote.$remotename.fetchStrategy");
86 unless ($fetch_strategy) {
87 $fetch_strategy = run_git("config --get mediawiki.fetchStrategy");
89 chomp($fetch_strategy);
90 unless ($fetch_strategy) {
91 $fetch_strategy = "by_page";
94 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
96 # Configurable with mediawiki.dumbPush, or per-remote with
97 # remote.<remotename>.dumbPush.
99 # This means the user will have to re-import the just-pushed
100 # revisions. On the other hand, this means that the Git revisions
101 # corresponding to MediaWiki revisions are all imported from the wiki,
102 # regardless of whether they were initially created in Git or from the
103 # web interface, hence all users will get the same history (i.e. if
104 # the push from Git to MediaWiki loses some information, everybody
105 # will get the history with information lost). If the import is
106 # deterministic, this means everybody gets the same sha1 for each
107 # MediaWiki revision.
108 my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
109 unless ($dumb_push) {
110 $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
112 chomp($dumb_push);
113 $dumb_push = ($dumb_push eq "true");
115 my $wiki_name = $url;
116 $wiki_name =~ s/[^\/]*:\/\///;
117 # If URL is like http://user:password@example.com/, we clearly don't
118 # want the password in $wiki_name. While we're there, also remove user
119 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
120 $wiki_name =~ s/^.*@//;
122 # Commands parser
123 my $entry;
124 my @cmd;
125 while (<STDIN>) {
126 chomp;
127 @cmd = split(/ /);
128 if (defined($cmd[0])) {
129 # Line not blank
130 if ($cmd[0] eq "capabilities") {
131 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
132 mw_capabilities();
133 } elsif ($cmd[0] eq "list") {
134 die("Too many arguments for list") unless (!defined($cmd[2]));
135 mw_list($cmd[1]);
136 } elsif ($cmd[0] eq "import") {
137 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
138 mw_import($cmd[1]);
139 } elsif ($cmd[0] eq "option") {
140 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
141 mw_option($cmd[1],$cmd[2]);
142 } elsif ($cmd[0] eq "push") {
143 mw_push($cmd[1]);
144 } else {
145 print STDERR "Unknown command. Aborting...\n";
146 last;
148 } else {
149 # blank line: we should terminate
150 last;
153 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
154 # command is fully processed.
157 ########################## Functions ##############################
159 # MediaWiki API instance, created lazily.
160 my $mediawiki;
162 sub mw_connect_maybe {
163 if ($mediawiki) {
164 return;
166 $mediawiki = MediaWiki::API->new;
167 $mediawiki->{config}->{api_url} = "$url/api.php";
168 if ($wiki_login) {
169 my %credential = (
170 'url' => $url,
171 'username' => $wiki_login,
172 'password' => $wiki_passwd
174 Git::credential(\%credential);
175 my $request = {lgname => $credential{username},
176 lgpassword => $credential{password},
177 lgdomain => $wiki_domain};
178 if ($mediawiki->login($request)) {
179 Git::credential(\%credential, 'approve');
180 print STDERR "Logged in mediawiki user \"$credential{username}\".\n";
181 } else {
182 print STDERR "Failed to log in mediawiki user \"$credential{username}\" on $url\n";
183 print STDERR " (error " .
184 $mediawiki->{error}->{code} . ': ' .
185 $mediawiki->{error}->{details} . ")\n";
186 Git::credential(\%credential, 'reject');
187 exit 1;
192 sub fatal_mw_error {
193 my $action = shift;
194 print STDERR "fatal: could not $action.\n";
195 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
196 if ($url =~ /^https/) {
197 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
198 print STDERR "fatal: and the SSL certificate is correct.\n";
199 } else {
200 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
202 print STDERR "fatal: (error " .
203 $mediawiki->{error}->{code} . ': ' .
204 $mediawiki->{error}->{details} . ")\n";
205 exit 1;
208 ## Functions for listing pages on the remote wiki
209 sub get_mw_tracked_pages {
210 my $pages = shift;
211 get_mw_page_list(\@tracked_pages, $pages);
214 sub get_mw_page_list {
215 my $page_list = shift;
216 my $pages = shift;
217 my @some_pages = @$page_list;
218 while (@some_pages) {
219 my $last = 50;
220 if ($#some_pages < $last) {
221 $last = $#some_pages;
223 my @slice = @some_pages[0..$last];
224 get_mw_first_pages(\@slice, $pages);
225 @some_pages = @some_pages[51..$#some_pages];
229 sub get_mw_tracked_categories {
230 my $pages = shift;
231 foreach my $category (@tracked_categories) {
232 if (index($category, ':') < 0) {
233 # Mediawiki requires the Category
234 # prefix, but let's not force the user
235 # to specify it.
236 $category = "Category:" . $category;
238 my $mw_pages = $mediawiki->list( {
239 action => 'query',
240 list => 'categorymembers',
241 cmtitle => $category,
242 cmlimit => 'max' } )
243 || die $mediawiki->{error}->{code} . ': '
244 . $mediawiki->{error}->{details};
245 foreach my $page (@{$mw_pages}) {
246 $pages->{$page->{title}} = $page;
251 sub get_mw_all_pages {
252 my $pages = shift;
253 # No user-provided list, get the list of pages from the API.
254 my $mw_pages = $mediawiki->list({
255 action => 'query',
256 list => 'allpages',
257 aplimit => 'max'
259 if (!defined($mw_pages)) {
260 fatal_mw_error("get the list of wiki pages");
262 foreach my $page (@{$mw_pages}) {
263 $pages->{$page->{title}} = $page;
267 # queries the wiki for a set of pages. Meant to be used within a loop
268 # querying the wiki for slices of page list.
269 sub get_mw_first_pages {
270 my $some_pages = shift;
271 my @some_pages = @{$some_pages};
273 my $pages = shift;
275 # pattern 'page1|page2|...' required by the API
276 my $titles = join('|', @some_pages);
278 my $mw_pages = $mediawiki->api({
279 action => 'query',
280 titles => $titles,
282 if (!defined($mw_pages)) {
283 fatal_mw_error("query the list of wiki pages");
285 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
286 if ($id < 0) {
287 print STDERR "Warning: page $page->{title} not found on wiki\n";
288 } else {
289 $pages->{$page->{title}} = $page;
294 # Get the list of pages to be fetched according to configuration.
295 sub get_mw_pages {
296 mw_connect_maybe();
298 print STDERR "Listing pages on remote wiki...\n";
300 my %pages; # hash on page titles to avoid duplicates
301 my $user_defined;
302 if (@tracked_pages) {
303 $user_defined = 1;
304 # The user provided a list of pages titles, but we
305 # still need to query the API to get the page IDs.
306 get_mw_tracked_pages(\%pages);
308 if (@tracked_categories) {
309 $user_defined = 1;
310 get_mw_tracked_categories(\%pages);
312 if (!$user_defined) {
313 get_mw_all_pages(\%pages);
315 if ($import_media) {
316 print STDERR "Getting media files for selected pages...\n";
317 if ($user_defined) {
318 get_linked_mediafiles(\%pages);
319 } else {
320 get_all_mediafiles(\%pages);
323 print STDERR (scalar keys %pages) . " pages found.\n";
324 return %pages;
327 # usage: $out = run_git("command args");
328 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
329 sub run_git {
330 my $args = shift;
331 my $encoding = (shift || "encoding(UTF-8)");
332 open(my $git, "-|:$encoding", "git " . $args);
333 my $res = do { local $/; <$git> };
334 close($git);
336 return $res;
340 sub get_all_mediafiles {
341 my $pages = shift;
342 # Attach list of all pages for media files from the API,
343 # they are in a different namespace, only one namespace
344 # can be queried at the same moment
345 my $mw_pages = $mediawiki->list({
346 action => 'query',
347 list => 'allpages',
348 apnamespace => get_mw_namespace_id("File"),
349 aplimit => 'max'
351 if (!defined($mw_pages)) {
352 print STDERR "fatal: could not get the list of pages for media files.\n";
353 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
354 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
355 exit 1;
357 foreach my $page (@{$mw_pages}) {
358 $pages->{$page->{title}} = $page;
362 sub get_linked_mediafiles {
363 my $pages = shift;
364 my @titles = map $_->{title}, values(%{$pages});
366 # The query is split in small batches because of the MW API limit of
367 # the number of links to be returned (500 links max).
368 my $batch = 10;
369 while (@titles) {
370 if ($#titles < $batch) {
371 $batch = $#titles;
373 my @slice = @titles[0..$batch];
375 # pattern 'page1|page2|...' required by the API
376 my $mw_titles = join('|', @slice);
378 # Media files could be included or linked from
379 # a page, get all related
380 my $query = {
381 action => 'query',
382 prop => 'links|images',
383 titles => $mw_titles,
384 plnamespace => get_mw_namespace_id("File"),
385 pllimit => 'max'
387 my $result = $mediawiki->api($query);
389 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
390 my @media_titles;
391 if (defined($page->{links})) {
392 my @link_titles = map $_->{title}, @{$page->{links}};
393 push(@media_titles, @link_titles);
395 if (defined($page->{images})) {
396 my @image_titles = map $_->{title}, @{$page->{images}};
397 push(@media_titles, @image_titles);
399 if (@media_titles) {
400 get_mw_page_list(\@media_titles, $pages);
404 @titles = @titles[($batch+1)..$#titles];
408 sub get_mw_mediafile_for_page_revision {
409 # Name of the file on Wiki, with the prefix.
410 my $filename = shift;
411 my $timestamp = shift;
412 my %mediafile;
414 # Search if on a media file with given timestamp exists on
415 # MediaWiki. In that case download the file.
416 my $query = {
417 action => 'query',
418 prop => 'imageinfo',
419 titles => "File:" . $filename,
420 iistart => $timestamp,
421 iiend => $timestamp,
422 iiprop => 'timestamp|archivename|url',
423 iilimit => 1
425 my $result = $mediawiki->api($query);
427 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
428 # If not defined it means there is no revision of the file for
429 # given timestamp.
430 if (defined($file->{imageinfo})) {
431 $mediafile{title} = $filename;
433 my $fileinfo = pop(@{$file->{imageinfo}});
434 $mediafile{timestamp} = $fileinfo->{timestamp};
435 # Mediawiki::API's download function doesn't support https URLs
436 # and can't download old versions of files.
437 print STDERR "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
438 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
440 return %mediafile;
443 sub download_mw_mediafile {
444 my $url = shift;
446 my $response = $mediawiki->{ua}->get($url);
447 if ($response->code == 200) {
448 return $response->decoded_content;
449 } else {
450 print STDERR "Error downloading mediafile from :\n";
451 print STDERR "URL: $url\n";
452 print STDERR "Server response: " . $response->code . " " . $response->message . "\n";
453 exit 1;
457 sub get_last_local_revision {
458 # Get note regarding last mediawiki revision
459 my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
460 my @note_info = split(/ /, $note);
462 my $lastrevision_number;
463 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
464 print STDERR "No previous mediawiki revision found";
465 $lastrevision_number = 0;
466 } else {
467 # Notes are formatted : mediawiki_revision: #number
468 $lastrevision_number = $note_info[1];
469 chomp($lastrevision_number);
470 print STDERR "Last local mediawiki revision found is $lastrevision_number";
472 return $lastrevision_number;
475 # Remember the timestamp corresponding to a revision id.
476 my %basetimestamps;
478 # Get the last remote revision without taking in account which pages are
479 # tracked or not. This function makes a single request to the wiki thus
480 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
481 # option.
482 sub get_last_global_remote_rev {
483 mw_connect_maybe();
485 my $query = {
486 action => 'query',
487 list => 'recentchanges',
488 prop => 'revisions',
489 rclimit => '1',
490 rcdir => 'older',
492 my $result = $mediawiki->api($query);
493 return $result->{query}->{recentchanges}[0]->{revid};
496 # Get the last remote revision concerning the tracked pages and the tracked
497 # categories.
498 sub get_last_remote_revision {
499 mw_connect_maybe();
501 my %pages_hash = get_mw_pages();
502 my @pages = values(%pages_hash);
504 my $max_rev_num = 0;
506 print STDERR "Getting last revision id on tracked pages...\n";
508 foreach my $page (@pages) {
509 my $id = $page->{pageid};
511 my $query = {
512 action => 'query',
513 prop => 'revisions',
514 rvprop => 'ids|timestamp',
515 pageids => $id,
518 my $result = $mediawiki->api($query);
520 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
522 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
524 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
527 print STDERR "Last remote revision found is $max_rev_num.\n";
528 return $max_rev_num;
531 # Clean content before sending it to MediaWiki
532 sub mediawiki_clean {
533 my $string = shift;
534 my $page_created = shift;
535 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
536 # This function right trims a string and adds a \n at the end to follow this rule
537 $string =~ s/\s+$//;
538 if ($string eq "" && $page_created) {
539 # Creating empty pages is forbidden.
540 $string = EMPTY_CONTENT;
542 return $string."\n";
545 # Filter applied on MediaWiki data before adding them to Git
546 sub mediawiki_smudge {
547 my $string = shift;
548 if ($string eq EMPTY_CONTENT) {
549 $string = "";
551 # This \n is important. This is due to mediawiki's way to handle end of files.
552 return $string."\n";
555 sub mediawiki_clean_filename {
556 my $filename = shift;
557 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
558 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
559 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
560 # but with _ added to prevent MediaWiki from thinking this is
561 # an actual special character.
562 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
563 # If we use the uri escape before
564 # we should unescape here, before anything
566 return $filename;
569 sub mediawiki_smudge_filename {
570 my $filename = shift;
571 $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
572 $filename =~ s/ /_/g;
573 # Decode forbidden characters encoded in mediawiki_clean_filename
574 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
575 return $filename;
578 sub literal_data {
579 my ($content) = @_;
580 print STDOUT "data ", bytes::length($content), "\n", $content;
583 sub literal_data_raw {
584 # Output possibly binary content.
585 my ($content) = @_;
586 # Avoid confusion between size in bytes and in characters
587 utf8::downgrade($content);
588 binmode STDOUT, ":raw";
589 print STDOUT "data ", bytes::length($content), "\n", $content;
590 binmode STDOUT, ":utf8";
593 sub mw_capabilities {
594 # Revisions are imported to the private namespace
595 # refs/mediawiki/$remotename/ by the helper and fetched into
596 # refs/remotes/$remotename later by fetch.
597 print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
598 print STDOUT "import\n";
599 print STDOUT "list\n";
600 print STDOUT "push\n";
601 print STDOUT "\n";
604 sub mw_list {
605 # MediaWiki do not have branches, we consider one branch arbitrarily
606 # called master, and HEAD pointing to it.
607 print STDOUT "? refs/heads/master\n";
608 print STDOUT "\@refs/heads/master HEAD\n";
609 print STDOUT "\n";
612 sub mw_option {
613 print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
614 print STDOUT "unsupported\n";
617 sub fetch_mw_revisions_for_page {
618 my $page = shift;
619 my $id = shift;
620 my $fetch_from = shift;
621 my @page_revs = ();
622 my $query = {
623 action => 'query',
624 prop => 'revisions',
625 rvprop => 'ids',
626 rvdir => 'newer',
627 rvstartid => $fetch_from,
628 rvlimit => 500,
629 pageids => $id,
632 my $revnum = 0;
633 # Get 500 revisions at a time due to the mediawiki api limit
634 while (1) {
635 my $result = $mediawiki->api($query);
637 # Parse each of those 500 revisions
638 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
639 my $page_rev_ids;
640 $page_rev_ids->{pageid} = $page->{pageid};
641 $page_rev_ids->{revid} = $revision->{revid};
642 push(@page_revs, $page_rev_ids);
643 $revnum++;
645 last unless $result->{'query-continue'};
646 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
648 if ($shallow_import && @page_revs) {
649 print STDERR " Found 1 revision (shallow import).\n";
650 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
651 return $page_revs[0];
653 print STDERR " Found ", $revnum, " revision(s).\n";
654 return @page_revs;
657 sub fetch_mw_revisions {
658 my $pages = shift; my @pages = @{$pages};
659 my $fetch_from = shift;
661 my @revisions = ();
662 my $n = 1;
663 foreach my $page (@pages) {
664 my $id = $page->{pageid};
666 print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
667 $n++;
668 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
669 @revisions = (@page_revs, @revisions);
672 return ($n, @revisions);
675 sub fe_escape_path {
676 my $path = shift;
677 $path =~ s/\\/\\\\/g;
678 $path =~ s/"/\\"/g;
679 $path =~ s/\n/\\n/g;
680 return '"' . $path . '"';
683 sub import_file_revision {
684 my $commit = shift;
685 my %commit = %{$commit};
686 my $full_import = shift;
687 my $n = shift;
688 my $mediafile = shift;
689 my %mediafile;
690 if ($mediafile) {
691 %mediafile = %{$mediafile};
694 my $title = $commit{title};
695 my $comment = $commit{comment};
696 my $content = $commit{content};
697 my $author = $commit{author};
698 my $date = $commit{date};
700 print STDOUT "commit refs/mediawiki/$remotename/master\n";
701 print STDOUT "mark :$n\n";
702 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
703 literal_data($comment);
705 # If it's not a clone, we need to know where to start from
706 if (!$full_import && $n == 1) {
707 print STDOUT "from refs/mediawiki/$remotename/master^0\n";
709 if ($content ne DELETED_CONTENT) {
710 print STDOUT "M 644 inline " .
711 fe_escape_path($title . ".mw") . "\n";
712 literal_data($content);
713 if (%mediafile) {
714 print STDOUT "M 644 inline "
715 . fe_escape_path($mediafile{title}) . "\n";
716 literal_data_raw($mediafile{content});
718 print STDOUT "\n\n";
719 } else {
720 print STDOUT "D " . fe_escape_path($title . ".mw") . "\n";
723 # mediawiki revision number in the git note
724 if ($full_import && $n == 1) {
725 print STDOUT "reset refs/notes/$remotename/mediawiki\n";
727 print STDOUT "commit refs/notes/$remotename/mediawiki\n";
728 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
729 literal_data("Note added by git-mediawiki during import");
730 if (!$full_import && $n == 1) {
731 print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
733 print STDOUT "N inline :$n\n";
734 literal_data("mediawiki_revision: " . $commit{mw_revision});
735 print STDOUT "\n\n";
738 # parse a sequence of
739 # <cmd> <arg1>
740 # <cmd> <arg2>
741 # \n
742 # (like batch sequence of import and sequence of push statements)
743 sub get_more_refs {
744 my $cmd = shift;
745 my @refs;
746 while (1) {
747 my $line = <STDIN>;
748 if ($line =~ m/^$cmd (.*)$/) {
749 push(@refs, $1);
750 } elsif ($line eq "\n") {
751 return @refs;
752 } else {
753 die("Invalid command in a '$cmd' batch: ". $_);
758 sub mw_import {
759 # multiple import commands can follow each other.
760 my @refs = (shift, get_more_refs("import"));
761 foreach my $ref (@refs) {
762 mw_import_ref($ref);
764 print STDOUT "done\n";
767 sub mw_import_ref {
768 my $ref = shift;
769 # The remote helper will call "import HEAD" and
770 # "import refs/heads/master".
771 # Since HEAD is a symbolic ref to master (by convention,
772 # followed by the output of the command "list" that we gave),
773 # we don't need to do anything in this case.
774 if ($ref eq "HEAD") {
775 return;
778 mw_connect_maybe();
780 print STDERR "Searching revisions...\n";
781 my $last_local = get_last_local_revision();
782 my $fetch_from = $last_local + 1;
783 if ($fetch_from == 1) {
784 print STDERR ", fetching from beginning.\n";
785 } else {
786 print STDERR ", fetching from here.\n";
789 my $n = 0;
790 if ($fetch_strategy eq "by_rev") {
791 print STDERR "Fetching & writing export data by revs...\n";
792 $n = mw_import_ref_by_revs($fetch_from);
793 } elsif ($fetch_strategy eq "by_page") {
794 print STDERR "Fetching & writing export data by pages...\n";
795 $n = mw_import_ref_by_pages($fetch_from);
796 } else {
797 print STDERR "fatal: invalid fetch strategy \"$fetch_strategy\".\n";
798 print STDERR "Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
799 exit 1;
802 if ($fetch_from == 1 && $n == 0) {
803 print STDERR "You appear to have cloned an empty MediaWiki.\n";
804 # Something has to be done remote-helper side. If nothing is done, an error is
805 # thrown saying that HEAD is referring to unknown object 0000000000000000000
806 # and the clone fails.
810 sub mw_import_ref_by_pages {
812 my $fetch_from = shift;
813 my %pages_hash = get_mw_pages();
814 my @pages = values(%pages_hash);
816 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
818 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
819 my @revision_ids = map $_->{revid}, @revisions;
821 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
824 sub mw_import_ref_by_revs {
826 my $fetch_from = shift;
827 my %pages_hash = get_mw_pages();
829 my $last_remote = get_last_global_remote_rev();
830 my @revision_ids = $fetch_from..$last_remote;
831 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
834 # Import revisions given in second argument (array of integers).
835 # Only pages appearing in the third argument (hash indexed by page titles)
836 # will be imported.
837 sub mw_import_revids {
838 my $fetch_from = shift;
839 my $revision_ids = shift;
840 my $pages = shift;
842 my $n = 0;
843 my $n_actual = 0;
844 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
846 foreach my $pagerevid (@$revision_ids) {
847 # Count page even if we skip it, since we display
848 # $n/$total and $total includes skipped pages.
849 $n++;
851 # fetch the content of the pages
852 my $query = {
853 action => 'query',
854 prop => 'revisions',
855 rvprop => 'content|timestamp|comment|user|ids',
856 revids => $pagerevid,
859 my $result = $mediawiki->api($query);
861 if (!$result) {
862 die "Failed to retrieve modified page for revision $pagerevid";
865 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
866 # The revision id does not exist on the remote wiki.
867 next;
870 if (!defined($result->{query}->{pages})) {
871 die "Invalid revision $pagerevid.";
874 my @result_pages = values(%{$result->{query}->{pages}});
875 my $result_page = $result_pages[0];
876 my $rev = $result_pages[0]->{revisions}->[0];
878 my $page_title = $result_page->{title};
880 if (!exists($pages->{$page_title})) {
881 print STDERR "$n/", scalar(@$revision_ids),
882 ": Skipping revision #$rev->{revid} of $page_title\n";
883 next;
886 $n_actual++;
888 my %commit;
889 $commit{author} = $rev->{user} || 'Anonymous';
890 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
891 $commit{title} = mediawiki_smudge_filename($page_title);
892 $commit{mw_revision} = $rev->{revid};
893 $commit{content} = mediawiki_smudge($rev->{'*'});
895 if (!defined($rev->{timestamp})) {
896 $last_timestamp++;
897 } else {
898 $last_timestamp = $rev->{timestamp};
900 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
902 # Differentiates classic pages and media files.
903 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
904 my %mediafile;
905 if ($namespace) {
906 my $id = get_mw_namespace_id($namespace);
907 if ($id && $id == get_mw_namespace_id("File")) {
908 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
911 # If this is a revision of the media page for new version
912 # of a file do one common commit for both file and media page.
913 # Else do commit only for that page.
914 print STDERR "$n/", scalar(@$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
915 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
918 return $n_actual;
921 sub error_non_fast_forward {
922 my $advice = run_git("config --bool advice.pushNonFastForward");
923 chomp($advice);
924 if ($advice ne "false") {
925 # Native git-push would show this after the summary.
926 # We can't ask it to display it cleanly, so print it
927 # ourselves before.
928 print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
929 print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
930 print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
932 print STDOUT "error $_[0] \"non-fast-forward\"\n";
933 return 0;
936 sub mw_upload_file {
937 my $complete_file_name = shift;
938 my $new_sha1 = shift;
939 my $extension = shift;
940 my $file_deleted = shift;
941 my $summary = shift;
942 my $newrevid;
943 my $path = "File:" . $complete_file_name;
944 my %hashFiles = get_allowed_file_extensions();
945 if (!exists($hashFiles{$extension})) {
946 print STDERR "$complete_file_name is not a permitted file on this wiki.\n";
947 print STDERR "Check the configuration of file uploads in your mediawiki.\n";
948 return $newrevid;
950 # Deleting and uploading a file requires a priviledged user
951 if ($file_deleted) {
952 mw_connect_maybe();
953 my $query = {
954 action => 'delete',
955 title => $path,
956 reason => $summary
958 if (!$mediawiki->edit($query)) {
959 print STDERR "Failed to delete file on remote wiki\n";
960 print STDERR "Check your permissions on the remote site. Error code:\n";
961 print STDERR $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
962 exit 1;
964 } else {
965 # Don't let perl try to interpret file content as UTF-8 => use "raw"
966 my $content = run_git("cat-file blob $new_sha1", "raw");
967 if ($content ne "") {
968 mw_connect_maybe();
969 $mediawiki->{config}->{upload_url} =
970 "$url/index.php/Special:Upload";
971 $mediawiki->edit({
972 action => 'upload',
973 filename => $complete_file_name,
974 comment => $summary,
975 file => [undef,
976 $complete_file_name,
977 Content => $content],
978 ignorewarnings => 1,
979 }, {
980 skip_encoding => 1
981 } ) || die $mediawiki->{error}->{code} . ':'
982 . $mediawiki->{error}->{details};
983 my $last_file_page = $mediawiki->get_page({title => $path});
984 $newrevid = $last_file_page->{revid};
985 print STDERR "Pushed file: $new_sha1 - $complete_file_name.\n";
986 } else {
987 print STDERR "Empty file $complete_file_name not pushed.\n";
990 return $newrevid;
993 sub mw_push_file {
994 my $diff_info = shift;
995 # $diff_info contains a string in this format:
996 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
997 my @diff_info_split = split(/[ \t]/, $diff_info);
999 # Filename, including .mw extension
1000 my $complete_file_name = shift;
1001 # Commit message
1002 my $summary = shift;
1003 # MediaWiki revision number. Keep the previous one by default,
1004 # in case there's no edit to perform.
1005 my $oldrevid = shift;
1006 my $newrevid;
1008 if ($summary eq EMPTY_MESSAGE) {
1009 $summary = '';
1012 my $new_sha1 = $diff_info_split[3];
1013 my $old_sha1 = $diff_info_split[2];
1014 my $page_created = ($old_sha1 eq NULL_SHA1);
1015 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1016 $complete_file_name = mediawiki_clean_filename($complete_file_name);
1018 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1019 if (!defined($extension)) {
1020 $extension = "";
1022 if ($extension eq "mw") {
1023 my $ns = get_mw_namespace_id_for_page($complete_file_name);
1024 if ($ns && $ns == get_mw_namespace_id("File") && (!$export_media)) {
1025 print STDERR "Ignoring media file related page: $complete_file_name\n";
1026 return ($oldrevid, "ok");
1028 my $file_content;
1029 if ($page_deleted) {
1030 # Deleting a page usually requires
1031 # special privileges. A common
1032 # convention is to replace the page
1033 # with this content instead:
1034 $file_content = DELETED_CONTENT;
1035 } else {
1036 $file_content = run_git("cat-file blob $new_sha1");
1039 mw_connect_maybe();
1041 my $result = $mediawiki->edit( {
1042 action => 'edit',
1043 summary => $summary,
1044 title => $title,
1045 basetimestamp => $basetimestamps{$oldrevid},
1046 text => mediawiki_clean($file_content, $page_created),
1047 }, {
1048 skip_encoding => 1 # Helps with names with accentuated characters
1050 if (!$result) {
1051 if ($mediawiki->{error}->{code} == 3) {
1052 # edit conflicts, considered as non-fast-forward
1053 print STDERR 'Warning: Error ' .
1054 $mediawiki->{error}->{code} .
1055 ' from mediwiki: ' . $mediawiki->{error}->{details} .
1056 ".\n";
1057 return ($oldrevid, "non-fast-forward");
1058 } else {
1059 # Other errors. Shouldn't happen => just die()
1060 die 'Fatal: Error ' .
1061 $mediawiki->{error}->{code} .
1062 ' from mediwiki: ' . $mediawiki->{error}->{details};
1065 $newrevid = $result->{edit}->{newrevid};
1066 print STDERR "Pushed file: $new_sha1 - $title\n";
1067 } elsif ($export_media) {
1068 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1069 $extension, $page_deleted,
1070 $summary);
1071 } else {
1072 print STDERR "Ignoring media file $title\n";
1074 $newrevid = ($newrevid or $oldrevid);
1075 return ($newrevid, "ok");
1078 sub mw_push {
1079 # multiple push statements can follow each other
1080 my @refsspecs = (shift, get_more_refs("push"));
1081 my $pushed;
1082 for my $refspec (@refsspecs) {
1083 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1084 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1085 if ($force) {
1086 print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
1088 if ($local eq "") {
1089 print STDERR "Cannot delete remote branch on a MediaWiki\n";
1090 print STDOUT "error $remote cannot delete\n";
1091 next;
1093 if ($remote ne "refs/heads/master") {
1094 print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
1095 print STDOUT "error $remote only master allowed\n";
1096 next;
1098 if (mw_push_revision($local, $remote)) {
1099 $pushed = 1;
1103 # Notify Git that the push is done
1104 print STDOUT "\n";
1106 if ($pushed && $dumb_push) {
1107 print STDERR "Just pushed some revisions to MediaWiki.\n";
1108 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
1109 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
1110 print STDERR "\n";
1111 print STDERR " git pull --rebase\n";
1112 print STDERR "\n";
1116 sub mw_push_revision {
1117 my $local = shift;
1118 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1119 my $last_local_revid = get_last_local_revision();
1120 print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
1121 my $last_remote_revid = get_last_remote_revision();
1122 my $mw_revision = $last_remote_revid;
1124 # Get sha1 of commit pointed by local HEAD
1125 my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1126 # Get sha1 of commit pointed by remotes/$remotename/master
1127 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1128 chomp($remoteorigin_sha1);
1130 if ($last_local_revid > 0 &&
1131 $last_local_revid < $last_remote_revid) {
1132 return error_non_fast_forward($remote);
1135 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1136 # nothing to push
1137 return 0;
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
1146 print STDERR "Computing path from local to remote ...\n";
1147 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents $local ^$parsed_sha1"));
1148 my %local_ancestry;
1149 foreach my $line (@local_ancestry) {
1150 if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1151 foreach my $parent (split(' ', $parents)) {
1152 $local_ancestry{$parent} = $child;
1154 } elsif (!$line =~ m/^([a-f0-9]+)/) {
1155 die "Unexpected output from git rev-list: $line";
1158 while ($parsed_sha1 ne $HEAD_sha1) {
1159 my $child = $local_ancestry{$parsed_sha1};
1160 if (!$child) {
1161 printf STDERR "Cannot find a path in history from remote commit to last commit\n";
1162 return error_non_fast_forward($remote);
1164 push(@commit_pairs, [$parsed_sha1, $child]);
1165 $parsed_sha1 = $child;
1167 } else {
1168 # No remote mediawiki revision. Export the whole
1169 # history (linearized with --first-parent)
1170 print STDERR "Warning: no common ancestor, pushing complete history\n";
1171 my $history = run_git("rev-list --first-parent --children $local");
1172 my @history = split(/\n/, $history);
1173 @history = @history[1..$#history];
1174 foreach my $line (reverse @history) {
1175 my @commit_info_split = split(/ |\n/, $line);
1176 push(@commit_pairs, \@commit_info_split);
1180 foreach my $commit_info_split (@commit_pairs) {
1181 my $sha1_child = @{$commit_info_split}[0];
1182 my $sha1_commit = @{$commit_info_split}[1];
1183 my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
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);
1187 # Keep the subject line of the commit message as mediawiki comment for the revision
1188 my $commit_msg = run_git("log --no-walk --format=\"%s\" $sha1_commit");
1189 chomp($commit_msg);
1190 # Push every blob
1191 while (@diff_info_list) {
1192 my $status;
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);
1199 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1200 if ($status eq "non-fast-forward") {
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);
1208 if ($status ne "ok") {
1209 die("Unknown error from mw_push_file()");
1212 unless ($dumb_push) {
1213 run_git("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1214 run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1218 print STDOUT "ok $remote\n";
1219 return 1;
1222 sub get_allowed_file_extensions {
1223 mw_connect_maybe();
1225 my $query = {
1226 action => 'query',
1227 meta => 'siteinfo',
1228 siprop => 'fileextensions'
1230 my $result = $mediawiki->api($query);
1231 my @file_extensions= map $_->{ext},@{$result->{query}->{fileextensions}};
1232 my %hashFile = map {$_ => 1}@file_extensions;
1234 return %hashFile;
1237 # In memory cache for MediaWiki namespace ids.
1238 my %namespace_id;
1240 # Namespaces whose id is cached in the configuration file
1241 # (to avoid duplicates)
1242 my %cached_mw_namespace_id;
1244 # Return MediaWiki id for a canonical namespace name.
1245 # Ex.: "File", "Project".
1246 sub get_mw_namespace_id {
1247 mw_connect_maybe();
1248 my $name = shift;
1250 if (!exists $namespace_id{$name}) {
1251 # Look at configuration file, if the record for that namespace is
1252 # already cached. Namespaces are stored in form:
1253 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1254 my @temp = split(/[\n]/, run_git("config --get-all remote."
1255 . $remotename .".namespaceCache"));
1256 chomp(@temp);
1257 foreach my $ns (@temp) {
1258 my ($n, $id) = split(/:/, $ns);
1259 if ($id eq 'notANameSpace') {
1260 $namespace_id{$n} = {is_namespace => 0};
1261 } else {
1262 $namespace_id{$n} = {is_namespace => 1, id => $id};
1264 $cached_mw_namespace_id{$n} = 1;
1268 if (!exists $namespace_id{$name}) {
1269 print STDERR "Namespace $name not found in cache, querying the wiki ...\n";
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'
1277 my $result = $mediawiki->api($query);
1279 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1280 if (defined($ns->{id}) && defined($ns->{canonical})) {
1281 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1282 if ($ns->{'*'}) {
1283 # alias (e.g. french Fichier: as alias for canonical File:)
1284 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1290 my $ns = $namespace_id{$name};
1291 my $id;
1293 unless (defined $ns) {
1294 print STDERR "No such namespace $name on MediaWiki.\n";
1295 $ns = {is_namespace => 0};
1296 $namespace_id{$name} = $ns;
1299 if ($ns->{is_namespace}) {
1300 $id = $ns->{id};
1303 # Store "notANameSpace" as special value for inexisting namespaces
1304 my $store_id = ($id || 'notANameSpace');
1306 # Store explicitely requested namespaces on disk
1307 if (!exists $cached_mw_namespace_id{$name}) {
1308 run_git("config --add remote.". $remotename
1309 .".namespaceCache \"". $name .":". $store_id ."\"");
1310 $cached_mw_namespace_id{$name} = 1;
1312 return $id;
1315 sub get_mw_namespace_id_for_page {
1316 if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1317 return get_mw_namespace_id($namespace);
1318 } else {
1319 return;