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/
17 use DateTime::Format::ISO8601;
20 # By default, use UTF-8 to communicate with Git and the user
21 binmode STDERR, ':encoding(UTF-8)';
22 binmode STDOUT, ':encoding(UTF-8)';
26 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
27 use constant SLASH_REPLACEMENT => '%2F';
29 # It's not always possible to delete pages (may require some
30 # privileges). Deleted pages are replaced with this content.
31 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
33 # It's not possible to create empty pages. New empty files in Git are
34 # sent with this content instead.
35 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
37 # used to reflect file creation or deletion in diff.
38 use constant NULL_SHA1 => '0000000000000000000000000000000000000000';
40 # Used on Git's side to reflect empty edit messages on the wiki
41 use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
43 use constant EMPTY => q{};
45 my $remotename = $ARGV[0];
48 # Accept both space-separated and multiple keys in config file.
49 # Spaces should be written as _ anyway because we'll use chomp.
50 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.${remotename}.pages"));
51 chomp(@tracked_pages);
53 # Just like @tracked_pages, but for MediaWiki categories.
54 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.${remotename}.categories"));
55 chomp(@tracked_categories);
57 # Import media files on pull
58 my $import_media = run_git("config --get --bool remote.${remotename}.mediaimport");
60 $import_media = ($import_media eq 'true');
62 # Export media files on push
63 my $export_media = run_git("config --get --bool remote.${remotename}.mediaexport");
65 $export_media = !($export_media eq 'false');
67 my $wiki_login = run_git("config --get remote.${remotename}.mwLogin");
68 # Note: mwPassword is discourraged. Use the credential system instead.
69 my $wiki_passwd = run_git("config --get remote.${remotename}.mwPassword");
70 my $wiki_domain = run_git("config --get remote.${remotename}.mwDomain");
75 # Import only last revisions (both for clone and fetch)
76 my $shallow_import = run_git("config --get --bool remote.${remotename}.shallow");
77 chomp($shallow_import);
78 $shallow_import = ($shallow_import eq 'true');
80 # Fetch (clone and pull) by revisions instead of by pages. This behavior
81 # is more efficient when we have a wiki with lots of pages and we fetch
82 # the revisions quite often so that they concern only few pages.
84 # - by_rev: perform one query per new revision on the remote wiki
85 # - by_page: query each tracked page for new revision
86 my $fetch_strategy = run_git("config --get remote.${remotename}.fetchStrategy");
87 if (!$fetch_strategy) {
88 $fetch_strategy = run_git('config --get mediawiki.fetchStrategy');
90 chomp($fetch_strategy);
91 if (!$fetch_strategy) {
92 $fetch_strategy = 'by_page';
95 # Remember the timestamp corresponding to a revision id.
98 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
100 # Configurable with mediawiki.dumbPush, or per-remote with
101 # remote.<remotename>.dumbPush.
103 # This means the user will have to re-import the just-pushed
104 # revisions. On the other hand, this means that the Git revisions
105 # corresponding to MediaWiki revisions are all imported from the wiki,
106 # regardless of whether they were initially created in Git or from the
107 # web interface, hence all users will get the same history (i.e. if
108 # the push from Git to MediaWiki loses some information, everybody
109 # will get the history with information lost). If the import is
110 # deterministic, this means everybody gets the same sha1 for each
111 # MediaWiki revision.
112 my $dumb_push = run_git("config --get --bool remote.${remotename}.dumbPush");
114 $dumb_push = run_git('config --get --bool mediawiki.dumbPush');
117 $dumb_push = ($dumb_push eq 'true');
119 my $wiki_name = $url;
120 $wiki_name =~ s{[^/]*://}{};
121 # If URL is like http://user:password@example.com/, we clearly don't
122 # want the password in $wiki_name. While we're there, also remove user
123 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
124 $wiki_name =~ s/^.*@//;
130 if (!parse_command($_)) {
134 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
135 # command is fully processed.
138 ########################## Functions ##############################
142 my @cmd = split(/ /, $line);
143 if (!defined $cmd[0]) {
146 if ($cmd[0] eq 'capabilities') {
147 die("Too many arguments for capabilities\n")
148 if (defined($cmd[1]));
150 } elsif ($cmd[0] eq 'list') {
151 die("Too many arguments for list\n") if (defined($cmd[2]));
153 } elsif ($cmd[0] eq 'import') {
154 die("Invalid arguments for import\n")
155 if ($cmd[1] eq EMPTY || defined($cmd[2]));
157 } elsif ($cmd[0] eq 'option') {
158 die("Too many arguments for option\n")
159 if ($cmd[1] eq EMPTY || $cmd[2] eq EMPTY || defined($cmd[3]));
160 mw_option($cmd[1],$cmd[2]);
161 } elsif ($cmd[0] eq 'push') {
164 print {*STDERR} "Unknown command. Aborting...\n";
170 # MediaWiki API instance, created lazily.
173 sub mw_connect_maybe {
177 $mediawiki = MediaWiki::API->new;
178 $mediawiki->{config}->{api_url} = "${url}/api.php";
182 'username' => $wiki_login,
183 'password' => $wiki_passwd
185 Git::credential(\%credential);
186 my $request = {lgname => $credential{username},
187 lgpassword => $credential{password},
188 lgdomain => $wiki_domain};
189 if ($mediawiki->login($request)) {
190 Git::credential(\%credential, 'approve');
191 print {*STDERR} qq(Logged in mediawiki user "$credential{username}".\n);
193 print {*STDERR} qq(Failed to log in mediawiki user "$credential{username}" on ${url}\n);
194 print {*STDERR} ' (error ' .
195 $mediawiki->{error}->{code} . ': ' .
196 $mediawiki->{error}->{details} . ")\n";
197 Git::credential(\%credential, 'reject');
206 print STDERR "fatal: could not $action.\n";
207 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
208 if ($url =~ /^https/) {
209 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
210 print STDERR "fatal: and the SSL certificate is correct.\n";
212 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
214 print STDERR "fatal: (error " .
215 $mediawiki->{error}->{code} . ': ' .
216 $mediawiki->{error}->{details} . ")\n";
220 ## Functions for listing pages on the remote wiki
221 sub get_mw_tracked_pages {
223 get_mw_page_list(\@tracked_pages, $pages);
227 sub get_mw_page_list {
228 my $page_list = shift;
230 my @some_pages = @$page_list;
231 while (@some_pages) {
233 if ($#some_pages < $last_page) {
234 $last_page = $#some_pages;
236 my @slice = @some_pages[0..$last_page];
237 get_mw_first_pages(\@slice, $pages);
238 @some_pages = @some_pages[51..$#some_pages];
243 sub get_mw_tracked_categories {
245 foreach my $category (@tracked_categories) {
246 if (index($category, ':') < 0) {
247 # Mediawiki requires the Category
248 # prefix, but let's not force the user
250 $category = "Category:${category}";
252 my $mw_pages = $mediawiki->list( {
254 list => 'categorymembers',
255 cmtitle => $category,
257 || die $mediawiki->{error}->{code} . ': '
258 . $mediawiki->{error}->{details} . "\n";
259 foreach my $page (@{$mw_pages}) {
260 $pages->{$page->{title}} = $page;
266 sub get_mw_all_pages {
268 # No user-provided list, get the list of pages from the API.
269 my $mw_pages = $mediawiki->list({
274 if (!defined($mw_pages)) {
275 fatal_mw_error("get the list of wiki pages");
277 foreach my $page (@{$mw_pages}) {
278 $pages->{$page->{title}} = $page;
283 # queries the wiki for a set of pages. Meant to be used within a loop
284 # querying the wiki for slices of page list.
285 sub get_mw_first_pages {
286 my $some_pages = shift;
287 my @some_pages = @{$some_pages};
291 # pattern 'page1|page2|...' required by the API
292 my $titles = join('|', @some_pages);
294 my $mw_pages = $mediawiki->api({
298 if (!defined($mw_pages)) {
299 fatal_mw_error("query the list of wiki pages");
301 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
303 print {*STDERR} "Warning: page $page->{title} not found on wiki\n";
305 $pages->{$page->{title}} = $page;
311 # Get the list of pages to be fetched according to configuration.
315 print {*STDERR} "Listing pages on remote wiki...\n";
317 my %pages; # hash on page titles to avoid duplicates
319 if (@tracked_pages) {
321 # The user provided a list of pages titles, but we
322 # still need to query the API to get the page IDs.
323 get_mw_tracked_pages(\%pages);
325 if (@tracked_categories) {
327 get_mw_tracked_categories(\%pages);
329 if (!$user_defined) {
330 get_mw_all_pages(\%pages);
333 print {*STDERR} "Getting media files for selected pages...\n";
335 get_linked_mediafiles(\%pages);
337 get_all_mediafiles(\%pages);
340 print {*STDERR} (scalar keys %pages) . " pages found.\n";
344 # usage: $out = run_git("command args");
345 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
348 my $encoding = (shift || 'encoding(UTF-8)');
349 open(my $git, "-|:${encoding}", "git ${args}")
350 or die "Unable to fork: $!\n";
361 sub get_all_mediafiles {
363 # Attach list of all pages for media files from the API,
364 # they are in a different namespace, only one namespace
365 # can be queried at the same moment
366 my $mw_pages = $mediawiki->list({
369 apnamespace => get_mw_namespace_id('File'),
372 if (!defined($mw_pages)) {
373 print {*STDERR} "fatal: could not get the list of pages for media files.\n";
374 print {*STDERR} "fatal: '$url' does not appear to be a mediawiki\n";
375 print {*STDERR} "fatal: make sure '$url/api.php' is a valid page.\n";
378 foreach my $page (@{$mw_pages}) {
379 $pages->{$page->{title}} = $page;
384 sub get_linked_mediafiles {
386 my @titles = map { $_->{title} } values(%{$pages});
388 # The query is split in small batches because of the MW API limit of
389 # the number of links to be returned (500 links max).
392 if ($#titles < $batch) {
395 my @slice = @titles[0..$batch];
397 # pattern 'page1|page2|...' required by the API
398 my $mw_titles = join('|', @slice);
400 # Media files could be included or linked from
401 # a page, get all related
404 prop => 'links|images',
405 titles => $mw_titles,
406 plnamespace => get_mw_namespace_id('File'),
409 my $result = $mediawiki->api($query);
411 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
413 if (defined($page->{links})) {
415 = map { $_->{title} } @{$page->{links}};
416 push(@media_titles, @link_titles);
418 if (defined($page->{images})) {
420 = map { $_->{title} } @{$page->{images}};
421 push(@media_titles, @image_titles);
424 get_mw_page_list(\@media_titles, $pages);
428 @titles = @titles[($batch+1)..$#titles];
433 sub get_mw_mediafile_for_page_revision {
434 # Name of the file on Wiki, with the prefix.
435 my $filename = shift;
436 my $timestamp = shift;
439 # Search if on a media file with given timestamp exists on
440 # MediaWiki. In that case download the file.
444 titles => "File:${filename}",
445 iistart => $timestamp,
447 iiprop => 'timestamp|archivename|url',
450 my $result = $mediawiki->api($query);
452 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
453 # If not defined it means there is no revision of the file for
455 if (defined($file->{imageinfo})) {
456 $mediafile{title} = $filename;
458 my $fileinfo = pop(@{$file->{imageinfo}});
459 $mediafile{timestamp} = $fileinfo->{timestamp};
460 # Mediawiki::API's download function doesn't support https URLs
461 # and can't download old versions of files.
462 print {*STDERR} "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
463 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
468 sub download_mw_mediafile {
469 my $download_url = shift;
471 my $response = $mediawiki->{ua}->get($download_url);
472 if ($response->code == 200) {
473 return $response->decoded_content;
475 print {*STDERR} "Error downloading mediafile from :\n";
476 print {*STDERR} "URL: ${download_url}\n";
477 print {*STDERR} 'Server response: ' . $response->code . q{ } . $response->message . "\n";
482 sub get_last_local_revision {
483 # Get note regarding last mediawiki revision
484 my $note = run_git("notes --ref=${remotename}/mediawiki show refs/mediawiki/${remotename}/master 2>/dev/null");
485 my @note_info = split(/ /, $note);
487 my $lastrevision_number;
488 if (!(defined($note_info[0]) && $note_info[0] eq 'mediawiki_revision:')) {
489 print {*STDERR} 'No previous mediawiki revision found';
490 $lastrevision_number = 0;
492 # Notes are formatted : mediawiki_revision: #number
493 $lastrevision_number = $note_info[1];
494 chomp($lastrevision_number);
495 print {*STDERR} "Last local mediawiki revision found is ${lastrevision_number}";
497 return $lastrevision_number;
500 # Get the last remote revision without taking in account which pages are
501 # tracked or not. This function makes a single request to the wiki thus
502 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
504 sub get_last_global_remote_rev {
509 list => 'recentchanges',
514 my $result = $mediawiki->api($query);
515 return $result->{query}->{recentchanges}[0]->{revid};
518 # Get the last remote revision concerning the tracked pages and the tracked
520 sub get_last_remote_revision {
523 my %pages_hash = get_mw_pages();
524 my @pages = values(%pages_hash);
528 print {*STDERR} "Getting last revision id on tracked pages...\n";
530 foreach my $page (@pages) {
531 my $id = $page->{pageid};
536 rvprop => 'ids|timestamp',
540 my $result = $mediawiki->api($query);
542 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
544 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
546 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
549 print {*STDERR} "Last remote revision found is $max_rev_num.\n";
553 # Clean content before sending it to MediaWiki
554 sub mediawiki_clean {
556 my $page_created = shift;
557 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
558 # This function right trims a string and adds a \n at the end to follow this rule
560 if ($string eq EMPTY && $page_created) {
561 # Creating empty pages is forbidden.
562 $string = EMPTY_CONTENT;
567 # Filter applied on MediaWiki data before adding them to Git
568 sub mediawiki_smudge {
570 if ($string eq EMPTY_CONTENT) {
573 # This \n is important. This is due to mediawiki's way to handle end of files.
574 return "${string}\n";
577 sub mediawiki_clean_filename {
578 my $filename = shift;
579 $filename =~ s{@{[SLASH_REPLACEMENT]}}{/}g;
580 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
581 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
582 # but with _ added to prevent MediaWiki from thinking this is
583 # an actual special character.
584 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
585 # If we use the uri escape before
586 # we should unescape here, before anything
591 sub mediawiki_smudge_filename {
592 my $filename = shift;
593 $filename =~ s{/}{@{[SLASH_REPLACEMENT]}}g;
594 $filename =~ s/ /_/g;
595 # Decode forbidden characters encoded in mediawiki_clean_filename
596 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf('%c', hex($1))/ge;
602 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
606 sub literal_data_raw {
607 # Output possibly binary content.
609 # Avoid confusion between size in bytes and in characters
610 utf8::downgrade($content);
611 binmode {*STDOUT}, ':raw';
612 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
613 binmode {*STDOUT}, ':encoding(UTF-8)';
617 sub mw_capabilities {
618 # Revisions are imported to the private namespace
619 # refs/mediawiki/$remotename/ by the helper and fetched into
620 # refs/remotes/$remotename later by fetch.
621 print {*STDOUT} "refspec refs/heads/*:refs/mediawiki/${remotename}/*\n";
622 print {*STDOUT} "import\n";
623 print {*STDOUT} "list\n";
624 print {*STDOUT} "push\n";
625 print {*STDOUT} "\n";
630 # MediaWiki do not have branches, we consider one branch arbitrarily
631 # called master, and HEAD pointing to it.
632 print {*STDOUT} "? refs/heads/master\n";
633 print {*STDOUT} "\@refs/heads/master HEAD\n";
634 print {*STDOUT} "\n";
639 print {*STDERR} "remote-helper command 'option $_[0]' not yet implemented\n";
640 print {*STDOUT} "unsupported\n";
644 sub fetch_mw_revisions_for_page {
647 my $fetch_from = shift;
654 rvstartid => $fetch_from,
660 # Get 500 revisions at a time due to the mediawiki api limit
662 my $result = $mediawiki->api($query);
664 # Parse each of those 500 revisions
665 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
667 $page_rev_ids->{pageid} = $page->{pageid};
668 $page_rev_ids->{revid} = $revision->{revid};
669 push(@page_revs, $page_rev_ids);
672 last if (!$result->{'query-continue'});
673 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
675 if ($shallow_import && @page_revs) {
676 print {*STDERR} " Found 1 revision (shallow import).\n";
677 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
678 return $page_revs[0];
680 print {*STDERR} " Found ${revnum} revision(s).\n";
684 sub fetch_mw_revisions {
685 my $pages = shift; my @pages = @{$pages};
686 my $fetch_from = shift;
690 foreach my $page (@pages) {
691 my $id = $page->{pageid};
692 print {*STDERR} "page ${n}/", scalar(@pages), ': ', $page->{title}, "\n";
694 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
695 @revisions = (@page_revs, @revisions);
698 return ($n, @revisions);
703 $path =~ s/\\/\\\\/g;
706 return qq("${path}");
709 sub import_file_revision {
711 my %commit = %{$commit};
712 my $full_import = shift;
714 my $mediafile = shift;
717 %mediafile = %{$mediafile};
720 my $title = $commit{title};
721 my $comment = $commit{comment};
722 my $content = $commit{content};
723 my $author = $commit{author};
724 my $date = $commit{date};
726 print {*STDOUT} "commit refs/mediawiki/${remotename}/master\n";
727 print {*STDOUT} "mark :${n}\n";
728 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
729 literal_data($comment);
731 # If it's not a clone, we need to know where to start from
732 if (!$full_import && $n == 1) {
733 print {*STDOUT} "from refs/mediawiki/${remotename}/master^0\n";
735 if ($content ne DELETED_CONTENT) {
736 print {*STDOUT} 'M 644 inline ' .
737 fe_escape_path("${title}.mw") . "\n";
738 literal_data($content);
740 print {*STDOUT} 'M 644 inline '
741 . fe_escape_path($mediafile{title}) . "\n";
742 literal_data_raw($mediafile{content});
744 print {*STDOUT} "\n\n";
746 print {*STDOUT} 'D ' . fe_escape_path("${title}.mw") . "\n";
749 # mediawiki revision number in the git note
750 if ($full_import && $n == 1) {
751 print {*STDOUT} "reset refs/notes/${remotename}/mediawiki\n";
753 print {*STDOUT} "commit refs/notes/${remotename}/mediawiki\n";
754 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
755 literal_data('Note added by git-mediawiki during import');
756 if (!$full_import && $n == 1) {
757 print {*STDOUT} "from refs/notes/${remotename}/mediawiki^0\n";
759 print {*STDOUT} "N inline :${n}\n";
760 literal_data("mediawiki_revision: $commit{mw_revision}");
761 print {*STDOUT} "\n\n";
765 # parse a sequence of
769 # (like batch sequence of import and sequence of push statements)
775 if ($line =~ /^$cmd (.*)$/) {
777 } elsif ($line eq "\n") {
780 die("Invalid command in a '$cmd' batch: $_\n");
787 # multiple import commands can follow each other.
788 my @refs = (shift, get_more_refs('import'));
789 foreach my $ref (@refs) {
792 print {*STDOUT} "done\n";
798 # The remote helper will call "import HEAD" and
799 # "import refs/heads/master".
800 # Since HEAD is a symbolic ref to master (by convention,
801 # followed by the output of the command "list" that we gave),
802 # we don't need to do anything in this case.
803 if ($ref eq 'HEAD') {
809 print {*STDERR} "Searching revisions...\n";
810 my $last_local = get_last_local_revision();
811 my $fetch_from = $last_local + 1;
812 if ($fetch_from == 1) {
813 print {*STDERR} ", fetching from beginning.\n";
815 print {*STDERR} ", fetching from here.\n";
819 if ($fetch_strategy eq 'by_rev') {
820 print {*STDERR} "Fetching & writing export data by revs...\n";
821 $n = mw_import_ref_by_revs($fetch_from);
822 } elsif ($fetch_strategy eq 'by_page') {
823 print {*STDERR} "Fetching & writing export data by pages...\n";
824 $n = mw_import_ref_by_pages($fetch_from);
826 print {*STDERR} qq(fatal: invalid fetch strategy "${fetch_strategy}".\n);
827 print {*STDERR} "Check your configuration variables remote.${remotename}.fetchStrategy and mediawiki.fetchStrategy\n";
831 if ($fetch_from == 1 && $n == 0) {
832 print {*STDERR} "You appear to have cloned an empty MediaWiki.\n";
833 # Something has to be done remote-helper side. If nothing is done, an error is
834 # thrown saying that HEAD is referring to unknown object 0000000000000000000
835 # and the clone fails.
840 sub mw_import_ref_by_pages {
842 my $fetch_from = shift;
843 my %pages_hash = get_mw_pages();
844 my @pages = values(%pages_hash);
846 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
848 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
849 my @revision_ids = map { $_->{revid} } @revisions;
851 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
854 sub mw_import_ref_by_revs {
856 my $fetch_from = shift;
857 my %pages_hash = get_mw_pages();
859 my $last_remote = get_last_global_remote_rev();
860 my @revision_ids = $fetch_from..$last_remote;
861 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
864 # Import revisions given in second argument (array of integers).
865 # Only pages appearing in the third argument (hash indexed by page titles)
867 sub mw_import_revids {
868 my $fetch_from = shift;
869 my $revision_ids = shift;
874 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
876 foreach my $pagerevid (@$revision_ids) {
877 # Count page even if we skip it, since we display
878 # $n/$total and $total includes skipped pages.
881 # fetch the content of the pages
885 rvprop => 'content|timestamp|comment|user|ids',
886 revids => $pagerevid,
889 my $result = $mediawiki->api($query);
892 die "Failed to retrieve modified page for revision $pagerevid\n";
895 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
896 # The revision id does not exist on the remote wiki.
900 if (!defined($result->{query}->{pages})) {
901 die "Invalid revision ${pagerevid}.\n";
904 my @result_pages = values(%{$result->{query}->{pages}});
905 my $result_page = $result_pages[0];
906 my $rev = $result_pages[0]->{revisions}->[0];
908 my $page_title = $result_page->{title};
910 if (!exists($pages->{$page_title})) {
911 print {*STDERR} "${n}/", scalar(@$revision_ids),
912 ": Skipping revision #$rev->{revid} of ${page_title}\n";
919 $commit{author} = $rev->{user} || 'Anonymous';
920 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
921 $commit{title} = mediawiki_smudge_filename($page_title);
922 $commit{mw_revision} = $rev->{revid};
923 $commit{content} = mediawiki_smudge($rev->{'*'});
925 if (!defined($rev->{timestamp})) {
928 $last_timestamp = $rev->{timestamp};
930 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
932 # Differentiates classic pages and media files.
933 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
936 my $id = get_mw_namespace_id($namespace);
937 if ($id && $id == get_mw_namespace_id('File')) {
938 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
941 # If this is a revision of the media page for new version
942 # of a file do one common commit for both file and media page.
943 # Else do commit only for that page.
944 print {*STDERR} "${n}/", scalar(@$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
945 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
951 sub error_non_fast_forward {
952 my $advice = run_git('config --bool advice.pushNonFastForward');
954 if ($advice ne 'false') {
955 # Native git-push would show this after the summary.
956 # We can't ask it to display it cleanly, so print it
958 print {*STDERR} "To prevent you from losing history, non-fast-forward updates were rejected\n";
959 print {*STDERR} "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
960 print {*STDERR} "'Note about fast-forwards' section of 'git push --help' for details.\n";
962 print {*STDOUT} qq(error $_[0] "non-fast-forward"\n);
967 my $complete_file_name = shift;
968 my $new_sha1 = shift;
969 my $extension = shift;
970 my $file_deleted = shift;
973 my $path = "File:${complete_file_name}";
974 my %hashFiles = get_allowed_file_extensions();
975 if (!exists($hashFiles{$extension})) {
976 print {*STDERR} "${complete_file_name} is not a permitted file on this wiki.\n";
977 print {*STDERR} "Check the configuration of file uploads in your mediawiki.\n";
980 # Deleting and uploading a file requires a priviledged user
988 if (!$mediawiki->edit($query)) {
989 print {*STDERR} "Failed to delete file on remote wiki\n";
990 print {*STDERR} "Check your permissions on the remote site. Error code:\n";
991 print {*STDERR} $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
995 # Don't let perl try to interpret file content as UTF-8 => use "raw"
996 my $content = run_git("cat-file blob ${new_sha1}", 'raw');
997 if ($content ne EMPTY) {
999 $mediawiki->{config}->{upload_url} =
1000 "${url}/index.php/Special:Upload";
1003 filename => $complete_file_name,
1004 comment => $summary,
1006 $complete_file_name,
1007 Content => $content],
1008 ignorewarnings => 1,
1011 } ) || die $mediawiki->{error}->{code} . ':'
1012 . $mediawiki->{error}->{details} . "\n";
1013 my $last_file_page = $mediawiki->get_page({title => $path});
1014 $newrevid = $last_file_page->{revid};
1015 print {*STDERR} "Pushed file: ${new_sha1} - ${complete_file_name}.\n";
1017 print {*STDERR} "Empty file ${complete_file_name} not pushed.\n";
1024 my $diff_info = shift;
1025 # $diff_info contains a string in this format:
1026 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1027 my @diff_info_split = split(/[ \t]/, $diff_info);
1029 # Filename, including .mw extension
1030 my $complete_file_name = shift;
1032 my $summary = shift;
1033 # MediaWiki revision number. Keep the previous one by default,
1034 # in case there's no edit to perform.
1035 my $oldrevid = shift;
1038 if ($summary eq EMPTY_MESSAGE) {
1042 my $new_sha1 = $diff_info_split[3];
1043 my $old_sha1 = $diff_info_split[2];
1044 my $page_created = ($old_sha1 eq NULL_SHA1);
1045 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1046 $complete_file_name = mediawiki_clean_filename($complete_file_name);
1048 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1049 if (!defined($extension)) {
1052 if ($extension eq 'mw') {
1053 my $ns = get_mw_namespace_id_for_page($complete_file_name);
1054 if ($ns && $ns == get_mw_namespace_id('File') && (!$export_media)) {
1055 print {*STDERR} "Ignoring media file related page: ${complete_file_name}\n";
1056 return ($oldrevid, 'ok');
1059 if ($page_deleted) {
1060 # Deleting a page usually requires
1061 # special privileges. A common
1062 # convention is to replace the page
1063 # with this content instead:
1064 $file_content = DELETED_CONTENT;
1066 $file_content = run_git("cat-file blob ${new_sha1}");
1071 my $result = $mediawiki->edit( {
1073 summary => $summary,
1075 basetimestamp => $basetimestamps{$oldrevid},
1076 text => mediawiki_clean($file_content, $page_created),
1078 skip_encoding => 1 # Helps with names with accentuated characters
1081 if ($mediawiki->{error}->{code} == 3) {
1082 # edit conflicts, considered as non-fast-forward
1083 print {*STDERR} 'Warning: Error ' .
1084 $mediawiki->{error}->{code} .
1085 ' from mediwiki: ' . $mediawiki->{error}->{details} .
1087 return ($oldrevid, 'non-fast-forward');
1089 # Other errors. Shouldn't happen => just die()
1090 die 'Fatal: Error ' .
1091 $mediawiki->{error}->{code} .
1092 ' from mediwiki: ' . $mediawiki->{error}->{details} . "\n";
1095 $newrevid = $result->{edit}->{newrevid};
1096 print {*STDERR} "Pushed file: ${new_sha1} - ${title}\n";
1097 } elsif ($export_media) {
1098 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1099 $extension, $page_deleted,
1102 print {*STDERR} "Ignoring media file ${title}\n";
1104 $newrevid = ($newrevid or $oldrevid);
1105 return ($newrevid, 'ok');
1109 # multiple push statements can follow each other
1110 my @refsspecs = (shift, get_more_refs('push'));
1112 for my $refspec (@refsspecs) {
1113 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1114 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
1116 print {*STDERR} "Warning: forced push not allowed on a MediaWiki.\n";
1118 if ($local eq EMPTY) {
1119 print {*STDERR} "Cannot delete remote branch on a MediaWiki\n";
1120 print {*STDOUT} "error ${remote} cannot delete\n";
1123 if ($remote ne 'refs/heads/master') {
1124 print {*STDERR} "Only push to the branch 'master' is supported on a MediaWiki\n";
1125 print {*STDOUT} "error ${remote} only master allowed\n";
1128 if (mw_push_revision($local, $remote)) {
1133 # Notify Git that the push is done
1134 print {*STDOUT} "\n";
1136 if ($pushed && $dumb_push) {
1137 print {*STDERR} "Just pushed some revisions to MediaWiki.\n";
1138 print {*STDERR} "The pushed revisions now have to be re-imported, and your current branch\n";
1139 print {*STDERR} "needs to be updated with these re-imported commits. You can do this with\n";
1140 print {*STDERR} "\n";
1141 print {*STDERR} " git pull --rebase\n";
1142 print {*STDERR} "\n";
1147 sub mw_push_revision {
1149 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1150 my $last_local_revid = get_last_local_revision();
1151 print {*STDERR} ".\n"; # Finish sentence started by get_last_local_revision()
1152 my $last_remote_revid = get_last_remote_revision();
1153 my $mw_revision = $last_remote_revid;
1155 # Get sha1 of commit pointed by local HEAD
1156 my $HEAD_sha1 = run_git("rev-parse ${local} 2>/dev/null");
1158 # Get sha1 of commit pointed by remotes/$remotename/master
1159 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/${remotename}/master 2>/dev/null");
1160 chomp($remoteorigin_sha1);
1162 if ($last_local_revid > 0 &&
1163 $last_local_revid < $last_remote_revid) {
1164 return error_non_fast_forward($remote);
1167 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1172 # Get every commit in between HEAD and refs/remotes/origin/master,
1173 # including HEAD and refs/remotes/origin/master
1174 my @commit_pairs = ();
1175 if ($last_local_revid > 0) {
1176 my $parsed_sha1 = $remoteorigin_sha1;
1177 # Find a path from last MediaWiki commit to pushed commit
1178 print {*STDERR} "Computing path from local to remote ...\n";
1179 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents ${local} ^${parsed_sha1}"));
1181 foreach my $line (@local_ancestry) {
1182 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1183 foreach my $parent (split(/ /, $parents)) {
1184 $local_ancestry{$parent} = $child;
1186 } elsif (!$line =~ /^([a-f0-9]+)/) {
1187 die "Unexpected output from git rev-list: ${line}\n";
1190 while ($parsed_sha1 ne $HEAD_sha1) {
1191 my $child = $local_ancestry{$parsed_sha1};
1193 print {*STDERR} "Cannot find a path in history from remote commit to last commit\n";
1194 return error_non_fast_forward($remote);
1196 push(@commit_pairs, [$parsed_sha1, $child]);
1197 $parsed_sha1 = $child;
1200 # No remote mediawiki revision. Export the whole
1201 # history (linearized with --first-parent)
1202 print {*STDERR} "Warning: no common ancestor, pushing complete history\n";
1203 my $history = run_git("rev-list --first-parent --children ${local}");
1204 my @history = split(/\n/, $history);
1205 @history = @history[1..$#history];
1206 foreach my $line (reverse @history) {
1207 my @commit_info_split = split(/[ \n]/, $line);
1208 push(@commit_pairs, \@commit_info_split);
1212 foreach my $commit_info_split (@commit_pairs) {
1213 my $sha1_child = @{$commit_info_split}[0];
1214 my $sha1_commit = @{$commit_info_split}[1];
1215 my $diff_infos = run_git("diff-tree -r --raw -z ${sha1_child} ${sha1_commit}");
1216 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1217 # TODO: for now, it's just a delete+add
1218 my @diff_info_list = split(/\0/, $diff_infos);
1219 # Keep the subject line of the commit message as mediawiki comment for the revision
1220 my $commit_msg = run_git(qq(log --no-walk --format="%s" ${sha1_commit}));
1223 while (@diff_info_list) {
1225 # git diff-tree -z gives an output like
1226 # <metadata>\0<filename1>\0
1227 # <metadata>\0<filename2>\0
1228 # and we've split on \0.
1229 my $info = shift(@diff_info_list);
1230 my $file = shift(@diff_info_list);
1231 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1232 if ($status eq 'non-fast-forward') {
1233 # we may already have sent part of the
1234 # commit to MediaWiki, but it's too
1235 # late to cancel it. Stop the push in
1236 # the middle, but still give an
1237 # accurate error message.
1238 return error_non_fast_forward($remote);
1240 if ($status ne 'ok') {
1241 die("Unknown error from mw_push_file()\n");
1245 run_git(qq(notes --ref=${remotename}/mediawiki add -f -m "mediawiki_revision: ${mw_revision}" ${sha1_commit}));
1246 run_git(qq(update-ref -m "Git-MediaWiki push" refs/mediawiki/${remotename}/master ${sha1_commit} ${sha1_child}));
1250 print {*STDOUT} "ok ${remote}\n";
1254 sub get_allowed_file_extensions {
1260 siprop => 'fileextensions'
1262 my $result = $mediawiki->api($query);
1263 my @file_extensions = map { $_->{ext}} @{$result->{query}->{fileextensions}};
1264 my %hashFile = map { $_ => 1 } @file_extensions;
1269 # In memory cache for MediaWiki namespace ids.
1272 # Namespaces whose id is cached in the configuration file
1273 # (to avoid duplicates)
1274 my %cached_mw_namespace_id;
1276 # Return MediaWiki id for a canonical namespace name.
1277 # Ex.: "File", "Project".
1278 sub get_mw_namespace_id {
1282 if (!exists $namespace_id{$name}) {
1283 # Look at configuration file, if the record for that namespace is
1284 # already cached. Namespaces are stored in form:
1285 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1286 my @temp = split(/\n/,
1287 run_git("config --get-all remote.${remotename}.namespaceCache"));
1289 foreach my $ns (@temp) {
1290 my ($n, $id) = split(/:/, $ns);
1291 if ($id eq 'notANameSpace') {
1292 $namespace_id{$n} = {is_namespace => 0};
1294 $namespace_id{$n} = {is_namespace => 1, id => $id};
1296 $cached_mw_namespace_id{$n} = 1;
1300 if (!exists $namespace_id{$name}) {
1301 print {*STDERR} "Namespace ${name} not found in cache, querying the wiki ...\n";
1302 # NS not found => get namespace id from MW and store it in
1303 # configuration file.
1307 siprop => 'namespaces'
1309 my $result = $mediawiki->api($query);
1311 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1312 if (defined($ns->{id}) && defined($ns->{canonical})) {
1313 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1315 # alias (e.g. french Fichier: as alias for canonical File:)
1316 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1322 my $ns = $namespace_id{$name};
1326 print {*STDERR} "No such namespace ${name} on MediaWiki.\n";
1327 $ns = {is_namespace => 0};
1328 $namespace_id{$name} = $ns;
1331 if ($ns->{is_namespace}) {
1335 # Store "notANameSpace" as special value for inexisting namespaces
1336 my $store_id = ($id || 'notANameSpace');
1338 # Store explicitely requested namespaces on disk
1339 if (!exists $cached_mw_namespace_id{$name}) {
1340 run_git(qq(config --add remote.${remotename}.namespaceCache "${name}:${store_id}"));
1341 $cached_mw_namespace_id{$name} = 1;
1346 sub get_mw_namespace_id_for_page {
1347 my $namespace = shift;
1348 if ($namespace =~ /^([^:]*):/) {
1349 return get_mw_namespace_id($namespace);