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 # Import media files on pull
67 my $import_media = run_git("config --get --bool remote.${remotename}.mediaimport");
69 $import_media = ($import_media eq 'true');
71 # Export media files on push
72 my $export_media = run_git("config --get --bool remote.${remotename}.mediaexport");
74 $export_media = !($export_media eq 'false');
76 my $wiki_login = run_git("config --get remote.${remotename}.mwLogin");
77 # Note: mwPassword is discourraged. Use the credential system instead.
78 my $wiki_passwd = run_git("config --get remote.${remotename}.mwPassword");
79 my $wiki_domain = run_git("config --get remote.${remotename}.mwDomain");
84 # Import only last revisions (both for clone and fetch)
85 my $shallow_import = run_git("config --get --bool remote.${remotename}.shallow");
86 chomp($shallow_import);
87 $shallow_import = ($shallow_import eq 'true');
89 # Fetch (clone and pull) by revisions instead of by pages. This behavior
90 # is more efficient when we have a wiki with lots of pages and we fetch
91 # the revisions quite often so that they concern only few pages.
93 # - by_rev: perform one query per new revision on the remote wiki
94 # - by_page: query each tracked page for new revision
95 my $fetch_strategy = run_git("config --get remote.${remotename}.fetchStrategy");
96 if (!$fetch_strategy) {
97 $fetch_strategy = run_git('config --get mediawiki.fetchStrategy');
99 chomp($fetch_strategy);
100 if (!$fetch_strategy) {
101 $fetch_strategy = 'by_page';
104 # Remember the timestamp corresponding to a revision id.
107 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
109 # Configurable with mediawiki.dumbPush, or per-remote with
110 # remote.<remotename>.dumbPush.
112 # This means the user will have to re-import the just-pushed
113 # revisions. On the other hand, this means that the Git revisions
114 # corresponding to MediaWiki revisions are all imported from the wiki,
115 # regardless of whether they were initially created in Git or from the
116 # web interface, hence all users will get the same history (i.e. if
117 # the push from Git to MediaWiki loses some information, everybody
118 # will get the history with information lost). If the import is
119 # deterministic, this means everybody gets the same sha1 for each
120 # MediaWiki revision.
121 my $dumb_push = run_git("config --get --bool remote.${remotename}.dumbPush");
123 $dumb_push = run_git('config --get --bool mediawiki.dumbPush');
126 $dumb_push = ($dumb_push eq 'true');
128 my $wiki_name = $url;
129 $wiki_name =~ s{[^/]*://}{};
130 # If URL is like http://user:password@example.com/, we clearly don't
131 # want the password in $wiki_name. While we're there, also remove user
132 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
133 $wiki_name =~ s/^.*@//;
139 if (!parse_command($_)) {
143 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
144 # command is fully processed.
147 ########################## Functions ##############################
150 sub exit_error_usage {
151 die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
153 "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
154 "module directly.\n" .
155 "This module can be used the following way:\n" .
156 "\tgit clone mediawiki://<address of a mediawiki>\n" .
157 "Then, use git commit, push and pull as with every normal git repository.\n";
162 my @cmd = split(/ /, $line);
163 if (!defined $cmd[0]) {
166 if ($cmd[0] eq 'capabilities') {
167 die("Too many arguments for capabilities\n")
168 if (defined($cmd[1]));
170 } elsif ($cmd[0] eq 'list') {
171 die("Too many arguments for list\n") if (defined($cmd[2]));
173 } elsif ($cmd[0] eq 'import') {
174 die("Invalid argument for import\n")
175 if ($cmd[1] eq EMPTY);
176 die("Too many arguments for import\n")
177 if (defined($cmd[2]));
179 } elsif ($cmd[0] eq 'option') {
180 die("Invalid arguments for option\n")
181 if ($cmd[1] eq EMPTY || $cmd[2] eq EMPTY);
182 die("Too many arguments for option\n")
183 if (defined($cmd[3]));
184 mw_option($cmd[1],$cmd[2]);
185 } elsif ($cmd[0] eq 'push') {
188 print {*STDERR} "Unknown command. Aborting...\n";
194 # MediaWiki API instance, created lazily.
199 print STDERR "fatal: could not $action.\n";
200 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
201 if ($url =~ /^https/) {
202 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
203 print STDERR "fatal: and the SSL certificate is correct.\n";
205 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
207 print STDERR "fatal: (error " .
208 $mediawiki->{error}->{code} . ': ' .
209 $mediawiki->{error}->{details} . ")\n";
213 ## Functions for listing pages on the remote wiki
214 sub get_mw_tracked_pages {
216 get_mw_page_list(\@tracked_pages, $pages);
220 sub get_mw_page_list {
221 my $page_list = shift;
223 my @some_pages = @{$page_list};
224 while (@some_pages) {
225 my $last_page = SLICE_SIZE;
226 if ($#some_pages < $last_page) {
227 $last_page = $#some_pages;
229 my @slice = @some_pages[0..$last_page];
230 get_mw_first_pages(\@slice, $pages);
231 @some_pages = @some_pages[(SLICE_SIZE + 1)..$#some_pages];
236 sub get_mw_tracked_categories {
238 foreach my $category (@tracked_categories) {
239 if (index($category, ':') < 0) {
240 # Mediawiki requires the Category
241 # prefix, but let's not force the user
243 $category = "Category:${category}";
245 my $mw_pages = $mediawiki->list( {
247 list => 'categorymembers',
248 cmtitle => $category,
250 || die $mediawiki->{error}->{code} . ': '
251 . $mediawiki->{error}->{details} . "\n";
252 foreach my $page (@{$mw_pages}) {
253 $pages->{$page->{title}} = $page;
259 sub get_mw_all_pages {
261 # No user-provided list, get the list of pages from the API.
262 my $mw_pages = $mediawiki->list({
267 if (!defined($mw_pages)) {
268 fatal_mw_error("get the list of wiki pages");
270 foreach my $page (@{$mw_pages}) {
271 $pages->{$page->{title}} = $page;
276 # queries the wiki for a set of pages. Meant to be used within a loop
277 # querying the wiki for slices of page list.
278 sub get_mw_first_pages {
279 my $some_pages = shift;
280 my @some_pages = @{$some_pages};
284 # pattern 'page1|page2|...' required by the API
285 my $titles = join('|', @some_pages);
287 my $mw_pages = $mediawiki->api({
291 if (!defined($mw_pages)) {
292 fatal_mw_error("query the list of wiki pages");
294 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
296 print {*STDERR} "Warning: page $page->{title} not found on wiki\n";
298 $pages->{$page->{title}} = $page;
304 # Get the list of pages to be fetched according to configuration.
306 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
308 print {*STDERR} "Listing pages on remote wiki...\n";
310 my %pages; # hash on page titles to avoid duplicates
312 if (@tracked_pages) {
314 # The user provided a list of pages titles, but we
315 # still need to query the API to get the page IDs.
316 get_mw_tracked_pages(\%pages);
318 if (@tracked_categories) {
320 get_mw_tracked_categories(\%pages);
322 if (!$user_defined) {
323 get_mw_all_pages(\%pages);
326 print {*STDERR} "Getting media files for selected pages...\n";
328 get_linked_mediafiles(\%pages);
330 get_all_mediafiles(\%pages);
333 print {*STDERR} (scalar keys %pages) . " pages found.\n";
337 # usage: $out = run_git("command args");
338 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
341 my $encoding = (shift || 'encoding(UTF-8)');
342 open(my $git, "-|:${encoding}", "git ${args}")
343 or die "Unable to fork: $!\n";
354 sub get_all_mediafiles {
356 # Attach list of all pages for media files from the API,
357 # they are in a different namespace, only one namespace
358 # can be queried at the same moment
359 my $mw_pages = $mediawiki->list({
362 apnamespace => get_mw_namespace_id('File'),
365 if (!defined($mw_pages)) {
366 print {*STDERR} "fatal: could not get the list of pages for media files.\n";
367 print {*STDERR} "fatal: '$url' does not appear to be a mediawiki\n";
368 print {*STDERR} "fatal: make sure '$url/api.php' is a valid page.\n";
371 foreach my $page (@{$mw_pages}) {
372 $pages->{$page->{title}} = $page;
377 sub get_linked_mediafiles {
379 my @titles = map { $_->{title} } values(%{$pages});
381 my $batch = BATCH_SIZE;
383 if ($#titles < $batch) {
386 my @slice = @titles[0..$batch];
388 # pattern 'page1|page2|...' required by the API
389 my $mw_titles = join('|', @slice);
391 # Media files could be included or linked from
392 # a page, get all related
395 prop => 'links|images',
396 titles => $mw_titles,
397 plnamespace => get_mw_namespace_id('File'),
400 my $result = $mediawiki->api($query);
402 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
404 if (defined($page->{links})) {
406 = map { $_->{title} } @{$page->{links}};
407 push(@media_titles, @link_titles);
409 if (defined($page->{images})) {
411 = map { $_->{title} } @{$page->{images}};
412 push(@media_titles, @image_titles);
415 get_mw_page_list(\@media_titles, $pages);
419 @titles = @titles[($batch+1)..$#titles];
424 sub get_mw_mediafile_for_page_revision {
425 # Name of the file on Wiki, with the prefix.
426 my $filename = shift;
427 my $timestamp = shift;
430 # Search if on a media file with given timestamp exists on
431 # MediaWiki. In that case download the file.
435 titles => "File:${filename}",
436 iistart => $timestamp,
438 iiprop => 'timestamp|archivename|url',
441 my $result = $mediawiki->api($query);
443 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
444 # If not defined it means there is no revision of the file for
446 if (defined($file->{imageinfo})) {
447 $mediafile{title} = $filename;
449 my $fileinfo = pop(@{$file->{imageinfo}});
450 $mediafile{timestamp} = $fileinfo->{timestamp};
451 # Mediawiki::API's download function doesn't support https URLs
452 # and can't download old versions of files.
453 print {*STDERR} "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
454 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
459 sub download_mw_mediafile {
460 my $download_url = shift;
462 my $response = $mediawiki->{ua}->get($download_url);
463 if ($response->code == HTTP_CODE_OK) {
464 return $response->decoded_content;
466 print {*STDERR} "Error downloading mediafile from :\n";
467 print {*STDERR} "URL: ${download_url}\n";
468 print {*STDERR} 'Server response: ' . $response->code . q{ } . $response->message . "\n";
473 sub get_last_local_revision {
474 # Get note regarding last mediawiki revision
475 my $note = run_git("notes --ref=${remotename}/mediawiki show refs/mediawiki/${remotename}/master 2>/dev/null");
476 my @note_info = split(/ /, $note);
478 my $lastrevision_number;
479 if (!(defined($note_info[0]) && $note_info[0] eq 'mediawiki_revision:')) {
480 print {*STDERR} 'No previous mediawiki revision found';
481 $lastrevision_number = 0;
483 # Notes are formatted : mediawiki_revision: #number
484 $lastrevision_number = $note_info[1];
485 chomp($lastrevision_number);
486 print {*STDERR} "Last local mediawiki revision found is ${lastrevision_number}";
488 return $lastrevision_number;
491 # Get the last remote revision without taking in account which pages are
492 # tracked or not. This function makes a single request to the wiki thus
493 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
495 sub get_last_global_remote_rev {
496 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
500 list => 'recentchanges',
505 my $result = $mediawiki->api($query);
506 return $result->{query}->{recentchanges}[0]->{revid};
509 # Get the last remote revision concerning the tracked pages and the tracked
511 sub get_last_remote_revision {
512 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
514 my %pages_hash = get_mw_pages();
515 my @pages = values(%pages_hash);
519 print {*STDERR} "Getting last revision id on tracked pages...\n";
521 foreach my $page (@pages) {
522 my $id = $page->{pageid};
527 rvprop => 'ids|timestamp',
531 my $result = $mediawiki->api($query);
533 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
535 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
537 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
540 print {*STDERR} "Last remote revision found is $max_rev_num.\n";
544 # Clean content before sending it to MediaWiki
545 sub mediawiki_clean {
547 my $page_created = shift;
548 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
549 # This function right trims a string and adds a \n at the end to follow this rule
551 if ($string eq EMPTY && $page_created) {
552 # Creating empty pages is forbidden.
553 $string = EMPTY_CONTENT;
558 # Filter applied on MediaWiki data before adding them to Git
559 sub mediawiki_smudge {
561 if ($string eq EMPTY_CONTENT) {
564 # This \n is important. This is due to mediawiki's way to handle end of files.
565 return "${string}\n";
570 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
574 sub literal_data_raw {
575 # Output possibly binary content.
577 # Avoid confusion between size in bytes and in characters
578 utf8::downgrade($content);
579 binmode STDOUT, ':raw';
580 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
581 binmode STDOUT, ':encoding(UTF-8)';
585 sub mw_capabilities {
586 # Revisions are imported to the private namespace
587 # refs/mediawiki/$remotename/ by the helper and fetched into
588 # refs/remotes/$remotename later by fetch.
589 print {*STDOUT} "refspec refs/heads/*:refs/mediawiki/${remotename}/*\n";
590 print {*STDOUT} "import\n";
591 print {*STDOUT} "list\n";
592 print {*STDOUT} "push\n";
593 print {*STDOUT} "\n";
598 # MediaWiki do not have branches, we consider one branch arbitrarily
599 # called master, and HEAD pointing to it.
600 print {*STDOUT} "? refs/heads/master\n";
601 print {*STDOUT} "\@refs/heads/master HEAD\n";
602 print {*STDOUT} "\n";
607 print {*STDERR} "remote-helper command 'option $_[0]' not yet implemented\n";
608 print {*STDOUT} "unsupported\n";
612 sub fetch_mw_revisions_for_page {
615 my $fetch_from = shift;
622 rvstartid => $fetch_from,
626 # Let MediaWiki know that we support the latest API.
631 # Get 500 revisions at a time due to the mediawiki api limit
633 my $result = $mediawiki->api($query);
635 # Parse each of those 500 revisions
636 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
638 $page_rev_ids->{pageid} = $page->{pageid};
639 $page_rev_ids->{revid} = $revision->{revid};
640 push(@page_revs, $page_rev_ids);
644 if ($result->{'query-continue'}) { # For legacy APIs
645 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
646 } elsif ($result->{continue}) { # For newer APIs
647 $query->{rvstartid} = $result->{continue}->{rvcontinue};
648 $query->{continue} = $result->{continue}->{continue};
653 if ($shallow_import && @page_revs) {
654 print {*STDERR} " Found 1 revision (shallow import).\n";
655 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
656 return $page_revs[0];
658 print {*STDERR} " Found ${revnum} revision(s).\n";
662 sub fetch_mw_revisions {
663 my $pages = shift; my @pages = @{$pages};
664 my $fetch_from = shift;
668 foreach my $page (@pages) {
669 my $id = $page->{pageid};
670 print {*STDERR} "page ${n}/", scalar(@pages), ': ', $page->{title}, "\n";
672 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
673 @revisions = (@page_revs, @revisions);
676 return ($n, @revisions);
681 $path =~ s/\\/\\\\/g;
684 return qq("${path}");
687 sub import_file_revision {
689 my %commit = %{$commit};
690 my $full_import = shift;
692 my $mediafile = shift;
695 %mediafile = %{$mediafile};
698 my $title = $commit{title};
699 my $comment = $commit{comment};
700 my $content = $commit{content};
701 my $author = $commit{author};
702 my $date = $commit{date};
704 print {*STDOUT} "commit refs/mediawiki/${remotename}/master\n";
705 print {*STDOUT} "mark :${n}\n";
706 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
707 literal_data($comment);
709 # If it's not a clone, we need to know where to start from
710 if (!$full_import && $n == 1) {
711 print {*STDOUT} "from refs/mediawiki/${remotename}/master^0\n";
713 if ($content ne DELETED_CONTENT) {
714 print {*STDOUT} 'M 644 inline ' .
715 fe_escape_path("${title}.mw") . "\n";
716 literal_data($content);
718 print {*STDOUT} 'M 644 inline '
719 . fe_escape_path($mediafile{title}) . "\n";
720 literal_data_raw($mediafile{content});
722 print {*STDOUT} "\n\n";
724 print {*STDOUT} 'D ' . fe_escape_path("${title}.mw") . "\n";
727 # mediawiki revision number in the git note
728 if ($full_import && $n == 1) {
729 print {*STDOUT} "reset refs/notes/${remotename}/mediawiki\n";
731 print {*STDOUT} "commit refs/notes/${remotename}/mediawiki\n";
732 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
733 literal_data('Note added by git-mediawiki during import');
734 if (!$full_import && $n == 1) {
735 print {*STDOUT} "from refs/notes/${remotename}/mediawiki^0\n";
737 print {*STDOUT} "N inline :${n}\n";
738 literal_data("mediawiki_revision: $commit{mw_revision}");
739 print {*STDOUT} "\n\n";
743 # parse a sequence of
747 # (like batch sequence of import and sequence of push statements)
753 if ($line =~ /^$cmd (.*)$/) {
755 } elsif ($line eq "\n") {
758 die("Invalid command in a '$cmd' batch: $_\n");
765 # multiple import commands can follow each other.
766 my @refs = (shift, get_more_refs('import'));
767 foreach my $ref (@refs) {
770 print {*STDOUT} "done\n";
776 # The remote helper will call "import HEAD" and
777 # "import refs/heads/master".
778 # Since HEAD is a symbolic ref to master (by convention,
779 # followed by the output of the command "list" that we gave),
780 # we don't need to do anything in this case.
781 if ($ref eq 'HEAD') {
785 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
787 print {*STDERR} "Searching revisions...\n";
788 my $last_local = get_last_local_revision();
789 my $fetch_from = $last_local + 1;
790 if ($fetch_from == 1) {
791 print {*STDERR} ", fetching from beginning.\n";
793 print {*STDERR} ", fetching from here.\n";
797 if ($fetch_strategy eq 'by_rev') {
798 print {*STDERR} "Fetching & writing export data by revs...\n";
799 $n = mw_import_ref_by_revs($fetch_from);
800 } elsif ($fetch_strategy eq 'by_page') {
801 print {*STDERR} "Fetching & writing export data by pages...\n";
802 $n = mw_import_ref_by_pages($fetch_from);
804 print {*STDERR} qq(fatal: invalid fetch strategy "${fetch_strategy}".\n);
805 print {*STDERR} "Check your configuration variables remote.${remotename}.fetchStrategy and mediawiki.fetchStrategy\n";
809 if ($fetch_from == 1 && $n == 0) {
810 print {*STDERR} "You appear to have cloned an empty MediaWiki.\n";
811 # Something has to be done remote-helper side. If nothing is done, an error is
812 # thrown saying that HEAD is referring to unknown object 0000000000000000000
813 # and the clone fails.
818 sub mw_import_ref_by_pages {
820 my $fetch_from = shift;
821 my %pages_hash = get_mw_pages();
822 my @pages = values(%pages_hash);
824 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
826 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
827 my @revision_ids = map { $_->{revid} } @revisions;
829 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
832 sub mw_import_ref_by_revs {
834 my $fetch_from = shift;
835 my %pages_hash = get_mw_pages();
837 my $last_remote = get_last_global_remote_rev();
838 my @revision_ids = $fetch_from..$last_remote;
839 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
842 # Import revisions given in second argument (array of integers).
843 # Only pages appearing in the third argument (hash indexed by page titles)
845 sub mw_import_revids {
846 my $fetch_from = shift;
847 my $revision_ids = shift;
852 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
854 foreach my $pagerevid (@{$revision_ids}) {
855 # Count page even if we skip it, since we display
856 # $n/$total and $total includes skipped pages.
859 # fetch the content of the pages
863 rvprop => 'content|timestamp|comment|user|ids',
864 revids => $pagerevid,
867 my $result = $mediawiki->api($query);
870 die "Failed to retrieve modified page for revision $pagerevid\n";
873 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
874 # The revision id does not exist on the remote wiki.
878 if (!defined($result->{query}->{pages})) {
879 die "Invalid revision ${pagerevid}.\n";
882 my @result_pages = values(%{$result->{query}->{pages}});
883 my $result_page = $result_pages[0];
884 my $rev = $result_pages[0]->{revisions}->[0];
886 my $page_title = $result_page->{title};
888 if (!exists($pages->{$page_title})) {
889 print {*STDERR} "${n}/", scalar(@{$revision_ids}),
890 ": Skipping revision #$rev->{revid} of ${page_title}\n";
897 $commit{author} = $rev->{user} || 'Anonymous';
898 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
899 $commit{title} = smudge_filename($page_title);
900 $commit{mw_revision} = $rev->{revid};
901 $commit{content} = mediawiki_smudge($rev->{'*'});
903 if (!defined($rev->{timestamp})) {
906 $last_timestamp = $rev->{timestamp};
908 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
910 # Differentiates classic pages and media files.
911 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
914 my $id = get_mw_namespace_id($namespace);
915 if ($id && $id == get_mw_namespace_id('File')) {
916 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
919 # If this is a revision of the media page for new version
920 # of a file do one common commit for both file and media page.
921 # Else do commit only for that page.
922 print {*STDERR} "${n}/", scalar(@{$revision_ids}), ": Revision #$rev->{revid} of $commit{title}\n";
923 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
929 sub error_non_fast_forward {
930 my $advice = run_git('config --bool advice.pushNonFastForward');
932 if ($advice ne 'false') {
933 # Native git-push would show this after the summary.
934 # We can't ask it to display it cleanly, so print it
936 print {*STDERR} "To prevent you from losing history, non-fast-forward updates were rejected\n";
937 print {*STDERR} "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
938 print {*STDERR} "'Note about fast-forwards' section of 'git push --help' for details.\n";
940 print {*STDOUT} qq(error $_[0] "non-fast-forward"\n);
945 my $complete_file_name = shift;
946 my $new_sha1 = shift;
947 my $extension = shift;
948 my $file_deleted = shift;
951 my $path = "File:${complete_file_name}";
952 my %hashFiles = get_allowed_file_extensions();
953 if (!exists($hashFiles{$extension})) {
954 print {*STDERR} "${complete_file_name} is not a permitted file on this wiki.\n";
955 print {*STDERR} "Check the configuration of file uploads in your mediawiki.\n";
958 # Deleting and uploading a file requires a priviledged user
960 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
966 if (!$mediawiki->edit($query)) {
967 print {*STDERR} "Failed to delete file on remote wiki\n";
968 print {*STDERR} "Check your permissions on the remote site. Error code:\n";
969 print {*STDERR} $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
973 # Don't let perl try to interpret file content as UTF-8 => use "raw"
974 my $content = run_git("cat-file blob ${new_sha1}", 'raw');
975 if ($content ne EMPTY) {
976 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
977 $mediawiki->{config}->{upload_url} =
978 "${url}/index.php/Special:Upload";
981 filename => $complete_file_name,
985 Content => $content],
989 } ) || die $mediawiki->{error}->{code} . ':'
990 . $mediawiki->{error}->{details} . "\n";
991 my $last_file_page = $mediawiki->get_page({title => $path});
992 $newrevid = $last_file_page->{revid};
993 print {*STDERR} "Pushed file: ${new_sha1} - ${complete_file_name}.\n";
995 print {*STDERR} "Empty file ${complete_file_name} not pushed.\n";
1002 my $diff_info = shift;
1003 # $diff_info contains a string in this format:
1004 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1005 my @diff_info_split = split(/[ \t]/, $diff_info);
1007 # Filename, including .mw extension
1008 my $complete_file_name = shift;
1010 my $summary = shift;
1011 # MediaWiki revision number. Keep the previous one by default,
1012 # in case there's no edit to perform.
1013 my $oldrevid = shift;
1016 if ($summary eq EMPTY_MESSAGE) {
1020 my $new_sha1 = $diff_info_split[3];
1021 my $old_sha1 = $diff_info_split[2];
1022 my $page_created = ($old_sha1 eq NULL_SHA1);
1023 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1024 $complete_file_name = clean_filename($complete_file_name);
1026 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1027 if (!defined($extension)) {
1030 if ($extension eq 'mw') {
1031 my $ns = get_mw_namespace_id_for_page($complete_file_name);
1032 if ($ns && $ns == get_mw_namespace_id('File') && (!$export_media)) {
1033 print {*STDERR} "Ignoring media file related page: ${complete_file_name}\n";
1034 return ($oldrevid, 'ok');
1037 if ($page_deleted) {
1038 # Deleting a page usually requires
1039 # special privileges. A common
1040 # convention is to replace the page
1041 # with this content instead:
1042 $file_content = DELETED_CONTENT;
1044 $file_content = run_git("cat-file blob ${new_sha1}");
1047 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1049 my $result = $mediawiki->edit( {
1051 summary => $summary,
1053 basetimestamp => $basetimestamps{$oldrevid},
1054 text => mediawiki_clean($file_content, $page_created),
1056 skip_encoding => 1 # Helps with names with accentuated characters
1059 if ($mediawiki->{error}->{code} == 3) {
1060 # edit conflicts, considered as non-fast-forward
1061 print {*STDERR} 'Warning: Error ' .
1062 $mediawiki->{error}->{code} .
1063 ' from mediawiki: ' . $mediawiki->{error}->{details} .
1065 return ($oldrevid, 'non-fast-forward');
1067 # Other errors. Shouldn't happen => just die()
1068 die 'Fatal: Error ' .
1069 $mediawiki->{error}->{code} .
1070 ' from mediawiki: ' . $mediawiki->{error}->{details} . "\n";
1073 $newrevid = $result->{edit}->{newrevid};
1074 print {*STDERR} "Pushed file: ${new_sha1} - ${title}\n";
1075 } elsif ($export_media) {
1076 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1077 $extension, $page_deleted,
1080 print {*STDERR} "Ignoring media file ${title}\n";
1082 $newrevid = ($newrevid or $oldrevid);
1083 return ($newrevid, 'ok');
1087 # multiple push statements can follow each other
1088 my @refsspecs = (shift, get_more_refs('push'));
1090 for my $refspec (@refsspecs) {
1091 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1092 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
1094 print {*STDERR} "Warning: forced push not allowed on a MediaWiki.\n";
1096 if ($local eq EMPTY) {
1097 print {*STDERR} "Cannot delete remote branch on a MediaWiki\n";
1098 print {*STDOUT} "error ${remote} cannot delete\n";
1101 if ($remote ne 'refs/heads/master') {
1102 print {*STDERR} "Only push to the branch 'master' is supported on a MediaWiki\n";
1103 print {*STDOUT} "error ${remote} only master allowed\n";
1106 if (mw_push_revision($local, $remote)) {
1111 # Notify Git that the push is done
1112 print {*STDOUT} "\n";
1114 if ($pushed && $dumb_push) {
1115 print {*STDERR} "Just pushed some revisions to MediaWiki.\n";
1116 print {*STDERR} "The pushed revisions now have to be re-imported, and your current branch\n";
1117 print {*STDERR} "needs to be updated with these re-imported commits. You can do this with\n";
1118 print {*STDERR} "\n";
1119 print {*STDERR} " git pull --rebase\n";
1120 print {*STDERR} "\n";
1125 sub mw_push_revision {
1127 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1128 my $last_local_revid = get_last_local_revision();
1129 print {*STDERR} ".\n"; # Finish sentence started by get_last_local_revision()
1130 my $last_remote_revid = get_last_remote_revision();
1131 my $mw_revision = $last_remote_revid;
1133 # Get sha1 of commit pointed by local HEAD
1134 my $HEAD_sha1 = run_git("rev-parse ${local} 2>/dev/null");
1136 # Get sha1 of commit pointed by remotes/$remotename/master
1137 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/${remotename}/master 2>/dev/null");
1138 chomp($remoteorigin_sha1);
1140 if ($last_local_revid > 0 &&
1141 $last_local_revid < $last_remote_revid) {
1142 return error_non_fast_forward($remote);
1145 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1150 # Get every commit in between HEAD and refs/remotes/origin/master,
1151 # including HEAD and refs/remotes/origin/master
1152 my @commit_pairs = ();
1153 if ($last_local_revid > 0) {
1154 my $parsed_sha1 = $remoteorigin_sha1;
1155 # Find a path from last MediaWiki commit to pushed commit
1156 print {*STDERR} "Computing path from local to remote ...\n";
1157 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents ${local} ^${parsed_sha1}"));
1159 foreach my $line (@local_ancestry) {
1160 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1161 foreach my $parent (split(/ /, $parents)) {
1162 $local_ancestry{$parent} = $child;
1164 } elsif (!$line =~ /^([a-f0-9]+)/) {
1165 die "Unexpected output from git rev-list: ${line}\n";
1168 while ($parsed_sha1 ne $HEAD_sha1) {
1169 my $child = $local_ancestry{$parsed_sha1};
1171 print {*STDERR} "Cannot find a path in history from remote commit to last commit\n";
1172 return error_non_fast_forward($remote);
1174 push(@commit_pairs, [$parsed_sha1, $child]);
1175 $parsed_sha1 = $child;
1178 # No remote mediawiki revision. Export the whole
1179 # history (linearized with --first-parent)
1180 print {*STDERR} "Warning: no common ancestor, pushing complete history\n";
1181 my $history = run_git("rev-list --first-parent --children ${local}");
1182 my @history = split(/\n/, $history);
1183 @history = @history[1..$#history];
1184 foreach my $line (reverse @history) {
1185 my @commit_info_split = split(/[ \n]/, $line);
1186 push(@commit_pairs, \@commit_info_split);
1190 foreach my $commit_info_split (@commit_pairs) {
1191 my $sha1_child = @{$commit_info_split}[0];
1192 my $sha1_commit = @{$commit_info_split}[1];
1193 my $diff_infos = run_git("diff-tree -r --raw -z ${sha1_child} ${sha1_commit}");
1194 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1195 # TODO: for now, it's just a delete+add
1196 my @diff_info_list = split(/\0/, $diff_infos);
1197 # Keep the subject line of the commit message as mediawiki comment for the revision
1198 my $commit_msg = run_git(qq(log --no-walk --format="%s" ${sha1_commit}));
1201 while (@diff_info_list) {
1203 # git diff-tree -z gives an output like
1204 # <metadata>\0<filename1>\0
1205 # <metadata>\0<filename2>\0
1206 # and we've split on \0.
1207 my $info = shift(@diff_info_list);
1208 my $file = shift(@diff_info_list);
1209 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1210 if ($status eq 'non-fast-forward') {
1211 # we may already have sent part of the
1212 # commit to MediaWiki, but it's too
1213 # late to cancel it. Stop the push in
1214 # the middle, but still give an
1215 # accurate error message.
1216 return error_non_fast_forward($remote);
1218 if ($status ne 'ok') {
1219 die("Unknown error from mw_push_file()\n");
1223 run_git(qq(notes --ref=${remotename}/mediawiki add -f -m "mediawiki_revision: ${mw_revision}" ${sha1_commit}));
1224 run_git(qq(update-ref -m "Git-MediaWiki push" refs/mediawiki/${remotename}/master ${sha1_commit} ${sha1_child}));
1228 print {*STDOUT} "ok ${remote}\n";
1232 sub get_allowed_file_extensions {
1233 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1238 siprop => 'fileextensions'
1240 my $result = $mediawiki->api($query);
1241 my @file_extensions = map { $_->{ext}} @{$result->{query}->{fileextensions}};
1242 my %hashFile = map { $_ => 1 } @file_extensions;
1247 # In memory cache for MediaWiki namespace ids.
1250 # Namespaces whose id is cached in the configuration file
1251 # (to avoid duplicates)
1252 my %cached_mw_namespace_id;
1254 # Return MediaWiki id for a canonical namespace name.
1255 # Ex.: "File", "Project".
1256 sub get_mw_namespace_id {
1257 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
1260 if (!exists $namespace_id{$name}) {
1261 # Look at configuration file, if the record for that namespace is
1262 # already cached. Namespaces are stored in form:
1263 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1264 my @temp = split(/\n/,
1265 run_git("config --get-all remote.${remotename}.namespaceCache"));
1267 foreach my $ns (@temp) {
1268 my ($n, $id) = split(/:/, $ns);
1269 if ($id eq 'notANameSpace') {
1270 $namespace_id{$n} = {is_namespace => 0};
1272 $namespace_id{$n} = {is_namespace => 1, id => $id};
1274 $cached_mw_namespace_id{$n} = 1;
1278 if (!exists $namespace_id{$name}) {
1279 print {*STDERR} "Namespace ${name} not found in cache, querying the wiki ...\n";
1280 # NS not found => get namespace id from MW and store it in
1281 # configuration file.
1285 siprop => 'namespaces'
1287 my $result = $mediawiki->api($query);
1289 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1290 if (defined($ns->{id}) && defined($ns->{canonical})) {
1291 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1293 # alias (e.g. french Fichier: as alias for canonical File:)
1294 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1300 my $ns = $namespace_id{$name};
1304 print {*STDERR} "No such namespace ${name} on MediaWiki.\n";
1305 $ns = {is_namespace => 0};
1306 $namespace_id{$name} = $ns;
1309 if ($ns->{is_namespace}) {
1313 # Store "notANameSpace" as special value for inexisting namespaces
1314 my $store_id = ($id || 'notANameSpace');
1316 # Store explicitely requested namespaces on disk
1317 if (!exists $cached_mw_namespace_id{$name}) {
1318 run_git(qq(config --add remote.${remotename}.namespaceCache "${name}:${store_id}"));
1319 $cached_mw_namespace_id{$name} = 1;
1324 sub get_mw_namespace_id_for_page {
1325 my $namespace = shift;
1326 if ($namespace =~ /^([^:]*):/) {
1327 return get_mw_namespace_id($namespace);