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 Git::Mediawiki qw(clean_filename smudge_filename connect_maybe
19 use DateTime::Format::ISO8601;
22 # By default, use UTF-8 to communicate with Git and the user
23 binmode STDERR, ':encoding(UTF-8)';
24 binmode STDOUT, ':encoding(UTF-8)';
28 # It's not always possible to delete pages (may require some
29 # privileges). Deleted pages are replaced with this content.
30 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
32 # It's not possible to create empty pages. New empty files in Git are
33 # sent with this content instead.
34 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
36 # used to reflect file creation or deletion in diff.
37 use constant NULL_SHA1 => '0000000000000000000000000000000000000000';
39 # Used on Git's side to reflect empty edit messages on the wiki
40 use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
42 # Number of pages taken into account at once in submodule get_mw_page_list
43 use constant SLICE_SIZE => 50;
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).
48 use constant BATCH_SIZE => 10;
54 my $remotename = $ARGV[0];
57 # Accept both space-separated and multiple keys in config file.
58 # Spaces should be written as _ anyway because we'll use chomp.
59 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.${remotename}.pages"));
60 chomp(@tracked_pages);
62 # Just like @tracked_pages, but for MediaWiki categories.
63 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.${remotename}.categories"));
64 chomp(@tracked_categories);
66 # Just like @tracked_categories, but for MediaWiki namespaces.
67 my @tracked_namespaces = split(/[ \n]/, run_git("config --get-all remote.${remotename}.namespaces"));
68 for (@tracked_namespaces) { s/_/ /g; }
69 chomp(@tracked_namespaces);
71 # Import media files on pull
72 my $import_media = run_git("config --get --bool remote.${remotename}.mediaimport");
74 $import_media = ($import_media eq 'true');
76 # Export media files on push
77 my $export_media = run_git("config --get --bool remote.${remotename}.mediaexport");
79 $export_media = !($export_media eq 'false');
81 my $wiki_login = run_git("config --get remote.${remotename}.mwLogin");
82 # Note: mwPassword is discourraged. Use the credential system instead.
83 my $wiki_passwd = run_git("config --get remote.${remotename}.mwPassword");
84 my $wiki_domain = run_git("config --get remote.${remotename}.mwDomain");
89 # Import only last revisions (both for clone and fetch)
90 my $shallow_import = run_git("config --get --bool remote.${remotename}.shallow");
91 chomp($shallow_import);
92 $shallow_import = ($shallow_import eq 'true');
94 # Fetch (clone and pull) by revisions instead of by pages. This behavior
95 # is more efficient when we have a wiki with lots of pages and we fetch
96 # the revisions quite often so that they concern only few pages.
98 # - by_rev: perform one query per new revision on the remote wiki
99 # - by_page: query each tracked page for new revision
100 my $fetch_strategy = run_git("config --get remote.${remotename}.fetchStrategy");
101 if (!$fetch_strategy) {
102 $fetch_strategy = run_git('config --get mediawiki.fetchStrategy');
104 chomp($fetch_strategy);
105 if (!$fetch_strategy) {
106 $fetch_strategy = 'by_page';
109 # Remember the timestamp corresponding to a revision id.
112 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
114 # Configurable with mediawiki.dumbPush, or per-remote with
115 # remote.<remotename>.dumbPush.
117 # This means the user will have to re-import the just-pushed
118 # revisions. On the other hand, this means that the Git revisions
119 # corresponding to MediaWiki revisions are all imported from the wiki,
120 # regardless of whether they were initially created in Git or from the
121 # web interface, hence all users will get the same history (i.e. if
122 # the push from Git to MediaWiki loses some information, everybody
123 # will get the history with information lost). If the import is
124 # deterministic, this means everybody gets the same sha1 for each
125 # MediaWiki revision.
126 my $dumb_push = run_git("config --get --bool remote.${remotename}.dumbPush");
128 $dumb_push = run_git('config --get --bool mediawiki.dumbPush');
131 $dumb_push = ($dumb_push eq 'true');
133 my $wiki_name = $url;
134 $wiki_name =~ s{[^/]*://}{};
135 # If URL is like http://user:password@example.com/, we clearly don't
136 # want the password in $wiki_name. While we're there, also remove user
137 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
138 $wiki_name =~ s/^.*@//;
144 if (!parse_command($_)) {
148 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
149 # command is fully processed.
152 ########################## Functions ##############################
155 sub exit_error_usage {
156 die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
158 "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
159 "module directly.\n" .
160 "This module can be used the following way:\n" .
161 "\tgit clone mediawiki://<address of a mediawiki>\n" .
162 "Then, use git commit, push and pull as with every normal git repository.\n";
167 my @cmd = split(/ /, $line);
168 if (!defined $cmd[0]) {
171 if ($cmd[0] eq 'capabilities') {
172 die("Too many arguments for capabilities\n")
173 if (defined($cmd[1]));
175 } elsif ($cmd[0] eq 'list') {
176 die("Too many arguments for list\n") if (defined($cmd[2]));
178 } elsif ($cmd[0] eq 'import') {
179 die("Invalid argument for import\n")
180 if ($cmd[1] eq EMPTY);
181 die("Too many arguments for import\n")
182 if (defined($cmd[2]));
184 } elsif ($cmd[0] eq 'option') {
185 die("Invalid arguments for option\n")
186 if ($cmd[1] eq EMPTY || $cmd[2] eq EMPTY);
187 die("Too many arguments for option\n")
188 if (defined($cmd[3]));
189 mw_option($cmd[1],$cmd[2]);
190 } elsif ($cmd[0] eq 'push') {
193 print {*STDERR} "Unknown command. Aborting...\n";
199 # MediaWiki API instance, created lazily.
204 print STDERR "fatal: could not $action.\n";
205 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
206 if ($url =~ /^https/) {
207 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
208 print STDERR "fatal: and the SSL certificate is correct.\n";
210 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
212 print STDERR "fatal: (error " .
213 $mediawiki->{error}->{code} . ': ' .
214 $mediawiki->{error}->{details} . ")\n";
218 ## Functions for listing pages on the remote wiki
219 sub get_mw_tracked_pages {
221 get_mw_page_list(\@tracked_pages, $pages);
225 sub get_mw_page_list {
226 my $page_list = shift;
228 my @some_pages = @{$page_list};
229 while (@some_pages) {
230 my $last_page = SLICE_SIZE;
231 if ($#some_pages < $last_page) {
232 $last_page = $#some_pages;
234 my @slice = @some_pages[0..$last_page];
235 get_mw_first_pages(\@slice, $pages);
236 @some_pages = @some_pages[(SLICE_SIZE + 1)..$#some_pages];
241 sub get_mw_tracked_categories {
243 foreach my $category (@tracked_categories) {
244 if (index($category, ':') < 0) {
245 # Mediawiki requires the Category
246 # prefix, but let's not force the user
248 $category = "Category:${category}";
250 my $mw_pages = $mediawiki->list( {
252 list => 'categorymembers',
253 cmtitle => $category,
255 || die $mediawiki->{error}->{code} . ': '
256 . $mediawiki->{error}->{details} . "\n";
257 foreach my $page (@{$mw_pages}) {
258 $pages->{$page->{title}} = $page;
264 sub get_mw_tracked_namespaces {
266 foreach my $local_namespace (@tracked_namespaces) {
267 my $namespace_id = get_mw_namespace_id($local_namespace);
268 # virtual namespaces don't support allpages
269 next if !defined($namespace_id) || $namespace_id < 0;
270 my $mw_pages = $mediawiki->list( {
273 apnamespace => $namespace_id,
275 || die $mediawiki->{error}->{code} . ': '
276 . $mediawiki->{error}->{details} . "\n";
277 foreach my $page (@{$mw_pages}) {
278 $pages->{$page->{title}} = $page;
284 sub get_mw_all_pages {
286 # No user-provided list, get the list of pages from the API.
287 my $mw_pages = $mediawiki->list({
292 if (!defined($mw_pages)) {
293 fatal_mw_error("get the list of wiki pages");
295 foreach my $page (@{$mw_pages}) {
296 $pages->{$page->{title}} = $page;
301 # queries the wiki for a set of pages. Meant to be used within a loop
302 # querying the wiki for slices of page list.
303 sub get_mw_first_pages {
304 my $some_pages = shift;
305 my @some_pages = @{$some_pages};
309 # pattern 'page1|page2|...' required by the API
310 my $titles = join('|', @some_pages);
312 my $mw_pages = $mediawiki->api({
316 if (!defined($mw_pages)) {
317 fatal_mw_error("query the list of wiki pages");
319 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
321 print {*STDERR} "Warning: page $page->{title} not found on wiki\n";
323 $pages->{$page->{title}} = $page;
329 # Get the list of pages to be fetched according to configuration.
331 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
333 print {*STDERR} "Listing pages on remote wiki...\n";
335 my %pages; # hash on page titles to avoid duplicates
337 if (@tracked_pages) {
339 # The user provided a list of pages titles, but we
340 # still need to query the API to get the page IDs.
341 get_mw_tracked_pages(\%pages);
343 if (@tracked_categories) {
345 get_mw_tracked_categories(\%pages);
347 if (@tracked_namespaces) {
349 get_mw_tracked_namespaces(\%pages);
351 if (!$user_defined) {
352 get_mw_all_pages(\%pages);
355 print {*STDERR} "Getting media files for selected pages...\n";
357 get_linked_mediafiles(\%pages);
359 get_all_mediafiles(\%pages);
362 print {*STDERR} (scalar keys %pages) . " pages found.\n";
366 # usage: $out = run_git("command args");
367 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
370 my $encoding = (shift || 'encoding(UTF-8)');
371 open(my $git, "-|:${encoding}", "git ${args}")
372 or die "Unable to fork: $!\n";
383 sub get_all_mediafiles {
385 # Attach list of all pages for media files from the API,
386 # they are in a different namespace, only one namespace
387 # can be queried at the same moment
388 my $mw_pages = $mediawiki->list({
391 apnamespace => get_mw_namespace_id('File'),
394 if (!defined($mw_pages)) {
395 print {*STDERR} "fatal: could not get the list of pages for media files.\n";
396 print {*STDERR} "fatal: '$url' does not appear to be a mediawiki\n";
397 print {*STDERR} "fatal: make sure '$url/api.php' is a valid page.\n";
400 foreach my $page (@{$mw_pages}) {
401 $pages->{$page->{title}} = $page;
406 sub get_linked_mediafiles {
408 my @titles = map { $_->{title} } values(%{$pages});
410 my $batch = BATCH_SIZE;
412 if ($#titles < $batch) {
415 my @slice = @titles[0..$batch];
417 # pattern 'page1|page2|...' required by the API
418 my $mw_titles = join('|', @slice);
420 # Media files could be included or linked from
421 # a page, get all related
424 prop => 'links|images',
425 titles => $mw_titles,
426 plnamespace => get_mw_namespace_id('File'),
429 my $result = $mediawiki->api($query);
431 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
433 if (defined($page->{links})) {
435 = map { $_->{title} } @{$page->{links}};
436 push(@media_titles, @link_titles);
438 if (defined($page->{images})) {
440 = map { $_->{title} } @{$page->{images}};
441 push(@media_titles, @image_titles);
444 get_mw_page_list(\@media_titles, $pages);
448 @titles = @titles[($batch+1)..$#titles];
453 sub get_mw_mediafile_for_page_revision {
454 # Name of the file on Wiki, with the prefix.
455 my $filename = shift;
456 my $timestamp = shift;
459 # Search if on a media file with given timestamp exists on
460 # MediaWiki. In that case download the file.
464 titles => "File:${filename}",
465 iistart => $timestamp,
467 iiprop => 'timestamp|archivename|url',
470 my $result = $mediawiki->api($query);
472 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
473 # If not defined it means there is no revision of the file for
475 if (defined($file->{imageinfo})) {
476 $mediafile{title} = $filename;
478 my $fileinfo = pop(@{$file->{imageinfo}});
479 $mediafile{timestamp} = $fileinfo->{timestamp};
480 # Mediawiki::API's download function doesn't support https URLs
481 # and can't download old versions of files.
482 print {*STDERR} "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
483 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
488 sub download_mw_mediafile {
489 my $download_url = shift;
491 my $response = $mediawiki->{ua}->get($download_url);
492 if ($response->code == HTTP_CODE_OK) {
493 # It is tempting to return
494 # $response->decoded_content({charset => "none"}), but
495 # when doing so, utf8::downgrade($content) fails with
496 # "Wide character in subroutine entry".
498 return $response->content();
500 print {*STDERR} "Error downloading mediafile from :\n";
501 print {*STDERR} "URL: ${download_url}\n";
502 print {*STDERR} 'Server response: ' . $response->code . q{ } . $response->message . "\n";
507 sub get_last_local_revision {
508 # Get note regarding last mediawiki revision
509 my $note = run_git("notes --ref=${remotename}/mediawiki show refs/mediawiki/${remotename}/master 2>/dev/null");
510 my @note_info = split(/ /, $note);
512 my $lastrevision_number;
513 if (!(defined($note_info[0]) && $note_info[0] eq 'mediawiki_revision:')) {
514 print {*STDERR} 'No previous mediawiki revision found';
515 $lastrevision_number = 0;
517 # Notes are formatted : mediawiki_revision: #number
518 $lastrevision_number = $note_info[1];
519 chomp($lastrevision_number);
520 print {*STDERR} "Last local mediawiki revision found is ${lastrevision_number}";
522 return $lastrevision_number;
525 # Get the last remote revision without taking in account which pages are
526 # tracked or not. This function makes a single request to the wiki thus
527 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
529 sub get_last_global_remote_rev {
530 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
534 list => 'recentchanges',
539 my $result = $mediawiki->api($query);
540 return $result->{query}->{recentchanges}[0]->{revid};
543 # Get the last remote revision concerning the tracked pages and the tracked
545 sub get_last_remote_revision {
546 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
548 my %pages_hash = get_mw_pages();
549 my @pages = values(%pages_hash);
553 print {*STDERR} "Getting last revision id on tracked pages...\n";
555 foreach my $page (@pages) {
556 my $id = $page->{pageid};
561 rvprop => 'ids|timestamp',
565 my $result = $mediawiki->api($query);
567 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
569 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
571 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
574 print {*STDERR} "Last remote revision found is $max_rev_num.\n";
578 # Clean content before sending it to MediaWiki
579 sub mediawiki_clean {
581 my $page_created = shift;
582 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
583 # This function right trims a string and adds a \n at the end to follow this rule
585 if ($string eq EMPTY && $page_created) {
586 # Creating empty pages is forbidden.
587 $string = EMPTY_CONTENT;
592 # Filter applied on MediaWiki data before adding them to Git
593 sub mediawiki_smudge {
595 if ($string eq EMPTY_CONTENT) {
598 # This \n is important. This is due to mediawiki's way to handle end of files.
599 return "${string}\n";
604 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
608 sub literal_data_raw {
609 # Output possibly binary content.
611 # Avoid confusion between size in bytes and in characters
612 utf8::downgrade($content);
613 binmode STDOUT, ':raw';
614 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
615 binmode STDOUT, ':encoding(UTF-8)';
619 sub mw_capabilities {
620 # Revisions are imported to the private namespace
621 # refs/mediawiki/$remotename/ by the helper and fetched into
622 # refs/remotes/$remotename later by fetch.
623 print {*STDOUT} "refspec refs/heads/*:refs/mediawiki/${remotename}/*\n";
624 print {*STDOUT} "import\n";
625 print {*STDOUT} "list\n";
626 print {*STDOUT} "push\n";
628 print {*STDOUT} "no-private-update\n";
630 print {*STDOUT} "\n";
635 # MediaWiki do not have branches, we consider one branch arbitrarily
636 # called master, and HEAD pointing to it.
637 print {*STDOUT} "? refs/heads/master\n";
638 print {*STDOUT} "\@refs/heads/master HEAD\n";
639 print {*STDOUT} "\n";
644 print {*STDERR} "remote-helper command 'option $_[0]' not yet implemented\n";
645 print {*STDOUT} "unsupported\n";
649 sub fetch_mw_revisions_for_page {
652 my $fetch_from = shift;
659 rvstartid => $fetch_from,
663 # Let MediaWiki know that we support the latest API.
668 # Get 500 revisions at a time due to the mediawiki api limit
670 my $result = $mediawiki->api($query);
672 # Parse each of those 500 revisions
673 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
675 $page_rev_ids->{pageid} = $page->{pageid};
676 $page_rev_ids->{revid} = $revision->{revid};
677 push(@page_revs, $page_rev_ids);
681 if ($result->{'query-continue'}) { # For legacy APIs
682 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
683 } elsif ($result->{continue}) { # For newer APIs
684 $query->{rvstartid} = $result->{continue}->{rvcontinue};
685 $query->{continue} = $result->{continue}->{continue};
690 if ($shallow_import && @page_revs) {
691 print {*STDERR} " Found 1 revision (shallow import).\n";
692 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
693 return $page_revs[0];
695 print {*STDERR} " Found ${revnum} revision(s).\n";
699 sub fetch_mw_revisions {
700 my $pages = shift; my @pages = @{$pages};
701 my $fetch_from = shift;
705 foreach my $page (@pages) {
706 my $id = $page->{pageid};
707 print {*STDERR} "page ${n}/", scalar(@pages), ': ', $page->{title}, "\n";
709 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
710 @revisions = (@page_revs, @revisions);
713 return ($n, @revisions);
718 $path =~ s/\\/\\\\/g;
721 return qq("${path}");
724 sub import_file_revision {
726 my %commit = %{$commit};
727 my $full_import = shift;
729 my $mediafile = shift;
732 %mediafile = %{$mediafile};
735 my $title = $commit{title};
736 my $comment = $commit{comment};
737 my $content = $commit{content};
738 my $author = $commit{author};
739 my $date = $commit{date};
741 print {*STDOUT} "commit refs/mediawiki/${remotename}/master\n";
742 print {*STDOUT} "mark :${n}\n";
743 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
744 literal_data($comment);
746 # If it's not a clone, we need to know where to start from
747 if (!$full_import && $n == 1) {
748 print {*STDOUT} "from refs/mediawiki/${remotename}/master^0\n";
750 if ($content ne DELETED_CONTENT) {
751 print {*STDOUT} 'M 644 inline ' .
752 fe_escape_path("${title}.mw") . "\n";
753 literal_data($content);
755 print {*STDOUT} 'M 644 inline '
756 . fe_escape_path($mediafile{title}) . "\n";
757 literal_data_raw($mediafile{content});
759 print {*STDOUT} "\n\n";
761 print {*STDOUT} 'D ' . fe_escape_path("${title}.mw") . "\n";
764 # mediawiki revision number in the git note
765 if ($full_import && $n == 1) {
766 print {*STDOUT} "reset refs/notes/${remotename}/mediawiki\n";
768 print {*STDOUT} "commit refs/notes/${remotename}/mediawiki\n";
769 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
770 literal_data('Note added by git-mediawiki during import');
771 if (!$full_import && $n == 1) {
772 print {*STDOUT} "from refs/notes/${remotename}/mediawiki^0\n";
774 print {*STDOUT} "N inline :${n}\n";
775 literal_data("mediawiki_revision: $commit{mw_revision}");
776 print {*STDOUT} "\n\n";
780 # parse a sequence of
784 # (like batch sequence of import and sequence of push statements)
790 if ($line =~ /^$cmd (.*)$/) {
792 } elsif ($line eq "\n") {
795 die("Invalid command in a '$cmd' batch: $_\n");
802 # multiple import commands can follow each other.
803 my @refs = (shift, get_more_refs('import'));
804 foreach my $ref (@refs) {
807 print {*STDOUT} "done\n";
813 # The remote helper will call "import HEAD" and
814 # "import refs/heads/master".
815 # Since HEAD is a symbolic ref to master (by convention,
816 # followed by the output of the command "list" that we gave),
817 # we don't need to do anything in this case.
818 if ($ref eq 'HEAD') {
822 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
824 print {*STDERR} "Searching revisions...\n";
825 my $last_local = get_last_local_revision();
826 my $fetch_from = $last_local + 1;
827 if ($fetch_from == 1) {
828 print {*STDERR} ", fetching from beginning.\n";
830 print {*STDERR} ", fetching from here.\n";
834 if ($fetch_strategy eq 'by_rev') {
835 print {*STDERR} "Fetching & writing export data by revs...\n";
836 $n = mw_import_ref_by_revs($fetch_from);
837 } elsif ($fetch_strategy eq 'by_page') {
838 print {*STDERR} "Fetching & writing export data by pages...\n";
839 $n = mw_import_ref_by_pages($fetch_from);
841 print {*STDERR} qq(fatal: invalid fetch strategy "${fetch_strategy}".\n);
842 print {*STDERR} "Check your configuration variables remote.${remotename}.fetchStrategy and mediawiki.fetchStrategy\n";
846 if ($fetch_from == 1 && $n == 0) {
847 print {*STDERR} "You appear to have cloned an empty MediaWiki.\n";
848 # Something has to be done remote-helper side. If nothing is done, an error is
849 # thrown saying that HEAD is referring to unknown object 0000000000000000000
850 # and the clone fails.
855 sub mw_import_ref_by_pages {
857 my $fetch_from = shift;
858 my %pages_hash = get_mw_pages();
859 my @pages = values(%pages_hash);
861 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
863 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
864 my @revision_ids = map { $_->{revid} } @revisions;
866 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
869 sub mw_import_ref_by_revs {
871 my $fetch_from = shift;
872 my %pages_hash = get_mw_pages();
874 my $last_remote = get_last_global_remote_rev();
875 my @revision_ids = $fetch_from..$last_remote;
876 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
879 # Import revisions given in second argument (array of integers).
880 # Only pages appearing in the third argument (hash indexed by page titles)
882 sub mw_import_revids {
883 my $fetch_from = shift;
884 my $revision_ids = shift;
889 my $last_timestamp = 0; # Placeholder in case $rev->timestamp is undefined
891 foreach my $pagerevid (@{$revision_ids}) {
892 # Count page even if we skip it, since we display
893 # $n/$total and $total includes skipped pages.
896 # fetch the content of the pages
900 rvprop => 'content|timestamp|comment|user|ids',
901 revids => $pagerevid,
904 my $result = $mediawiki->api($query);
907 die "Failed to retrieve modified page for revision $pagerevid\n";
910 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
911 # The revision id does not exist on the remote wiki.
915 if (!defined($result->{query}->{pages})) {
916 die "Invalid revision ${pagerevid}.\n";
919 my @result_pages = values(%{$result->{query}->{pages}});
920 my $result_page = $result_pages[0];
921 my $rev = $result_pages[0]->{revisions}->[0];
923 my $page_title = $result_page->{title};
925 if (!exists($pages->{$page_title})) {
926 print {*STDERR} "${n}/", scalar(@{$revision_ids}),
927 ": Skipping revision #$rev->{revid} of ${page_title}\n";
934 $commit{author} = $rev->{user} || 'Anonymous';
935 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
936 $commit{title} = smudge_filename($page_title);
937 $commit{mw_revision} = $rev->{revid};
938 $commit{content} = mediawiki_smudge($rev->{'*'});
940 if (!defined($rev->{timestamp})) {
943 $last_timestamp = $rev->{timestamp};
945 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
947 # Differentiates classic pages and media files.
948 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
951 my $id = get_mw_namespace_id($namespace);
952 if ($id && $id == get_mw_namespace_id('File')) {
953 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
956 # If this is a revision of the media page for new version
957 # of a file do one common commit for both file and media page.
958 # Else do commit only for that page.
959 print {*STDERR} "${n}/", scalar(@{$revision_ids}), ": Revision #$rev->{revid} of $commit{title}\n";
960 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
966 sub error_non_fast_forward {
967 my $advice = run_git('config --bool advice.pushNonFastForward');
969 if ($advice ne 'false') {
970 # Native git-push would show this after the summary.
971 # We can't ask it to display it cleanly, so print it
973 print {*STDERR} "To prevent you from losing history, non-fast-forward updates were rejected\n";
974 print {*STDERR} "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
975 print {*STDERR} "'Note about fast-forwards' section of 'git push --help' for details.\n";
977 print {*STDOUT} qq(error $_[0] "non-fast-forward"\n);
982 my $complete_file_name = shift;
983 my $new_sha1 = shift;
984 my $extension = shift;
985 my $file_deleted = shift;
988 my $path = "File:${complete_file_name}";
989 my %hashFiles = get_allowed_file_extensions();
990 if (!exists($hashFiles{$extension})) {
991 print {*STDERR} "${complete_file_name} is not a permitted file on this wiki.\n";
992 print {*STDERR} "Check the configuration of file uploads in your mediawiki.\n";
995 # Deleting and uploading a file requires a privileged user
997 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1003 if (!$mediawiki->edit($query)) {
1004 print {*STDERR} "Failed to delete file on remote wiki\n";
1005 print {*STDERR} "Check your permissions on the remote site. Error code:\n";
1006 print {*STDERR} $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
1010 # Don't let perl try to interpret file content as UTF-8 => use "raw"
1011 my $content = run_git("cat-file blob ${new_sha1}", 'raw');
1012 if ($content ne EMPTY) {
1013 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1014 $mediawiki->{config}->{upload_url} =
1015 "${url}/index.php/Special:Upload";
1018 filename => $complete_file_name,
1019 comment => $summary,
1021 $complete_file_name,
1022 Content => $content],
1023 ignorewarnings => 1,
1026 } ) || die $mediawiki->{error}->{code} . ':'
1027 . $mediawiki->{error}->{details} . "\n";
1028 my $last_file_page = $mediawiki->get_page({title => $path});
1029 $newrevid = $last_file_page->{revid};
1030 print {*STDERR} "Pushed file: ${new_sha1} - ${complete_file_name}.\n";
1032 print {*STDERR} "Empty file ${complete_file_name} not pushed.\n";
1039 my $diff_info = shift;
1040 # $diff_info contains a string in this format:
1041 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1042 my @diff_info_split = split(/[ \t]/, $diff_info);
1044 # Filename, including .mw extension
1045 my $complete_file_name = shift;
1047 my $summary = shift;
1048 # MediaWiki revision number. Keep the previous one by default,
1049 # in case there's no edit to perform.
1050 my $oldrevid = shift;
1053 if ($summary eq EMPTY_MESSAGE) {
1057 my $new_sha1 = $diff_info_split[3];
1058 my $old_sha1 = $diff_info_split[2];
1059 my $page_created = ($old_sha1 eq NULL_SHA1);
1060 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1061 $complete_file_name = clean_filename($complete_file_name);
1063 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1064 if (!defined($extension)) {
1067 if ($extension eq 'mw') {
1068 my $ns = get_mw_namespace_id_for_page($complete_file_name);
1069 if ($ns && $ns == get_mw_namespace_id('File') && (!$export_media)) {
1070 print {*STDERR} "Ignoring media file related page: ${complete_file_name}\n";
1071 return ($oldrevid, 'ok');
1074 if ($page_deleted) {
1075 # Deleting a page usually requires
1076 # special privileges. A common
1077 # convention is to replace the page
1078 # with this content instead:
1079 $file_content = DELETED_CONTENT;
1081 $file_content = run_git("cat-file blob ${new_sha1}");
1084 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1086 my $result = $mediawiki->edit( {
1088 summary => $summary,
1090 basetimestamp => $basetimestamps{$oldrevid},
1091 text => mediawiki_clean($file_content, $page_created),
1093 skip_encoding => 1 # Helps with names with accentuated characters
1096 if ($mediawiki->{error}->{code} == 3) {
1097 # edit conflicts, considered as non-fast-forward
1098 print {*STDERR} 'Warning: Error ' .
1099 $mediawiki->{error}->{code} .
1100 ' from mediawiki: ' . $mediawiki->{error}->{details} .
1102 return ($oldrevid, 'non-fast-forward');
1104 # Other errors. Shouldn't happen => just die()
1105 die 'Fatal: Error ' .
1106 $mediawiki->{error}->{code} .
1107 ' from mediawiki: ' . $mediawiki->{error}->{details} . "\n";
1110 $newrevid = $result->{edit}->{newrevid};
1111 print {*STDERR} "Pushed file: ${new_sha1} - ${title}\n";
1112 } elsif ($export_media) {
1113 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1114 $extension, $page_deleted,
1117 print {*STDERR} "Ignoring media file ${title}\n";
1119 $newrevid = ($newrevid or $oldrevid);
1120 return ($newrevid, 'ok');
1124 # multiple push statements can follow each other
1125 my @refsspecs = (shift, get_more_refs('push'));
1127 for my $refspec (@refsspecs) {
1128 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1129 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
1131 print {*STDERR} "Warning: forced push not allowed on a MediaWiki.\n";
1133 if ($local eq EMPTY) {
1134 print {*STDERR} "Cannot delete remote branch on a MediaWiki\n";
1135 print {*STDOUT} "error ${remote} cannot delete\n";
1138 if ($remote ne 'refs/heads/master') {
1139 print {*STDERR} "Only push to the branch 'master' is supported on a MediaWiki\n";
1140 print {*STDOUT} "error ${remote} only master allowed\n";
1143 if (mw_push_revision($local, $remote)) {
1148 # Notify Git that the push is done
1149 print {*STDOUT} "\n";
1151 if ($pushed && $dumb_push) {
1152 print {*STDERR} "Just pushed some revisions to MediaWiki.\n";
1153 print {*STDERR} "The pushed revisions now have to be re-imported, and your current branch\n";
1154 print {*STDERR} "needs to be updated with these re-imported commits. You can do this with\n";
1155 print {*STDERR} "\n";
1156 print {*STDERR} " git pull --rebase\n";
1157 print {*STDERR} "\n";
1162 sub mw_push_revision {
1164 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1165 my $last_local_revid = get_last_local_revision();
1166 print {*STDERR} ".\n"; # Finish sentence started by get_last_local_revision()
1167 my $last_remote_revid = get_last_remote_revision();
1168 my $mw_revision = $last_remote_revid;
1170 # Get sha1 of commit pointed by local HEAD
1171 my $HEAD_sha1 = run_git("rev-parse ${local} 2>/dev/null");
1173 # Get sha1 of commit pointed by remotes/$remotename/master
1174 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/${remotename}/master 2>/dev/null");
1175 chomp($remoteorigin_sha1);
1177 if ($last_local_revid > 0 &&
1178 $last_local_revid < $last_remote_revid) {
1179 return error_non_fast_forward($remote);
1182 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1187 # Get every commit in between HEAD and refs/remotes/origin/master,
1188 # including HEAD and refs/remotes/origin/master
1189 my @commit_pairs = ();
1190 if ($last_local_revid > 0) {
1191 my $parsed_sha1 = $remoteorigin_sha1;
1192 # Find a path from last MediaWiki commit to pushed commit
1193 print {*STDERR} "Computing path from local to remote ...\n";
1194 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents ${local} ^${parsed_sha1}"));
1196 foreach my $line (@local_ancestry) {
1197 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1198 foreach my $parent (split(/ /, $parents)) {
1199 $local_ancestry{$parent} = $child;
1201 } elsif (!$line =~ /^([a-f0-9]+)/) {
1202 die "Unexpected output from git rev-list: ${line}\n";
1205 while ($parsed_sha1 ne $HEAD_sha1) {
1206 my $child = $local_ancestry{$parsed_sha1};
1208 print {*STDERR} "Cannot find a path in history from remote commit to last commit\n";
1209 return error_non_fast_forward($remote);
1211 push(@commit_pairs, [$parsed_sha1, $child]);
1212 $parsed_sha1 = $child;
1215 # No remote mediawiki revision. Export the whole
1216 # history (linearized with --first-parent)
1217 print {*STDERR} "Warning: no common ancestor, pushing complete history\n";
1218 my $history = run_git("rev-list --first-parent --children ${local}");
1219 my @history = split(/\n/, $history);
1220 @history = @history[1..$#history];
1221 foreach my $line (reverse @history) {
1222 my @commit_info_split = split(/[ \n]/, $line);
1223 push(@commit_pairs, \@commit_info_split);
1227 foreach my $commit_info_split (@commit_pairs) {
1228 my $sha1_child = @{$commit_info_split}[0];
1229 my $sha1_commit = @{$commit_info_split}[1];
1230 my $diff_infos = run_git("diff-tree -r --raw -z ${sha1_child} ${sha1_commit}");
1231 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1232 # TODO: for now, it's just a delete+add
1233 my @diff_info_list = split(/\0/, $diff_infos);
1234 # Keep the subject line of the commit message as mediawiki comment for the revision
1235 my $commit_msg = run_git(qq(log --no-walk --format="%s" ${sha1_commit}));
1238 while (@diff_info_list) {
1240 # git diff-tree -z gives an output like
1241 # <metadata>\0<filename1>\0
1242 # <metadata>\0<filename2>\0
1243 # and we've split on \0.
1244 my $info = shift(@diff_info_list);
1245 my $file = shift(@diff_info_list);
1246 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1247 if ($status eq 'non-fast-forward') {
1248 # we may already have sent part of the
1249 # commit to MediaWiki, but it's too
1250 # late to cancel it. Stop the push in
1251 # the middle, but still give an
1252 # accurate error message.
1253 return error_non_fast_forward($remote);
1255 if ($status ne 'ok') {
1256 die("Unknown error from mw_push_file()\n");
1260 run_git(qq(notes --ref=${remotename}/mediawiki add -f -m "mediawiki_revision: ${mw_revision}" ${sha1_commit}));
1264 print {*STDOUT} "ok ${remote}\n";
1268 sub get_allowed_file_extensions {
1269 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1274 siprop => 'fileextensions'
1276 my $result = $mediawiki->api($query);
1277 my @file_extensions = map { $_->{ext}} @{$result->{query}->{fileextensions}};
1278 my %hashFile = map { $_ => 1 } @file_extensions;
1283 # In memory cache for MediaWiki namespace ids.
1286 # Namespaces whose id is cached in the configuration file
1287 # (to avoid duplicates)
1288 my %cached_mw_namespace_id;
1290 # Return MediaWiki id for a canonical namespace name.
1291 # Ex.: "File", "Project".
1292 sub get_mw_namespace_id {
1293 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1296 if (!exists $namespace_id{$name}) {
1297 # Look at configuration file, if the record for that namespace is
1298 # already cached. Namespaces are stored in form:
1299 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1300 my @temp = split(/\n/,
1301 run_git("config --get-all remote.${remotename}.namespaceCache"));
1303 foreach my $ns (@temp) {
1304 my ($n, $id) = split(/:/, $ns);
1305 if ($id eq 'notANameSpace') {
1306 $namespace_id{$n} = {is_namespace => 0};
1308 $namespace_id{$n} = {is_namespace => 1, id => $id};
1310 $cached_mw_namespace_id{$n} = 1;
1314 if (!exists $namespace_id{$name}) {
1315 print {*STDERR} "Namespace ${name} not found in cache, querying the wiki ...\n";
1316 # NS not found => get namespace id from MW and store it in
1317 # configuration file.
1321 siprop => 'namespaces'
1323 my $result = $mediawiki->api($query);
1325 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1326 if (defined($ns->{id}) && defined($ns->{canonical})) {
1327 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1329 # alias (e.g. french Fichier: as alias for canonical File:)
1330 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1336 my $ns = $namespace_id{$name};
1340 my @namespaces = map { s/ /_/g; $_; } sort keys %namespace_id;
1341 print {*STDERR} "No such namespace ${name} on MediaWiki, known namespaces: @namespaces\n";
1342 $ns = {is_namespace => 0};
1343 $namespace_id{$name} = $ns;
1346 if ($ns->{is_namespace}) {
1350 # Store "notANameSpace" as special value for inexisting namespaces
1351 my $store_id = ($id || 'notANameSpace');
1353 # Store explicitly requested namespaces on disk
1354 if (!exists $cached_mw_namespace_id{$name}) {
1355 run_git(qq(config --add remote.${remotename}.namespaceCache "${name}:${store_id}"));
1356 $cached_mw_namespace_id{$name} = 1;
1361 sub get_mw_namespace_id_for_page {
1362 my $namespace = shift;
1363 if ($namespace =~ /^([^:]*):/) {
1364 return get_mw_namespace_id($namespace);