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 # https://github.com/Bibzball/Git-Mediawiki/wiki
16 # - Several strategies are provided to fetch modifications from the
17 # wiki, but no automatic heuristics is provided, the user has
18 # to understand and chose which strategy is appropriate for him.
20 # - Git renames could be turned into MediaWiki renames (see TODO
23 # - No way to import "one page, and all pages included in it"
25 # - Multiple remote MediaWikis have not been very well tested.
29 use DateTime::Format::ISO8601;
31 # By default, use UTF-8 to communicate with Git and the user
32 binmode STDERR, ":utf8";
33 binmode STDOUT, ":utf8";
40 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
41 use constant SLASH_REPLACEMENT => "%2F";
43 # It's not always possible to delete pages (may require some
44 # priviledges). Deleted pages are replaced with this content.
45 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
47 # It's not possible to create empty pages. New empty files in Git are
48 # sent with this content instead.
49 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
51 # used to reflect file creation or deletion in diff.
52 use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
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 too.
67 my $import_media = run_git("config --get --bool remote.". $remotename .".mediaimport");
69 $import_media = ($import_media eq "true");
71 my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
72 # Note: mwPassword is discourraged. Use the credential system instead.
73 my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
74 my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
79 # Import only last revisions (both for clone and fetch)
80 my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
81 chomp($shallow_import);
82 $shallow_import = ($shallow_import eq "true");
84 # Fetch (clone and pull) by revisions instead of by pages. This behavior
85 # is more efficient when we have a wiki with lots of pages and we fetch
86 # the revisions quite often so that they concern only few pages.
88 # - by_rev: perform one query per new revision on the remote wiki
89 # - by_page: query each tracked page for new revision
90 my $fetch_strategy = run_git("config --get remote.$remotename.fetchStrategy");
91 unless ($fetch_strategy) {
92 $fetch_strategy = run_git("config --get mediawiki.fetchStrategy");
94 chomp($fetch_strategy);
95 unless ($fetch_strategy) {
96 $fetch_strategy = "by_page";
99 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
101 # Configurable with mediawiki.dumbPush, or per-remote with
102 # remote.<remotename>.dumbPush.
104 # This means the user will have to re-import the just-pushed
105 # revisions. On the other hand, this means that the Git revisions
106 # corresponding to MediaWiki revisions are all imported from the wiki,
107 # regardless of whether they were initially created in Git or from the
108 # web interface, hence all users will get the same history (i.e. if
109 # the push from Git to MediaWiki loses some information, everybody
110 # will get the history with information lost). If the import is
111 # deterministic, this means everybody gets the same sha1 for each
112 # MediaWiki revision.
113 my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
114 unless ($dumb_push) {
115 $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
118 $dumb_push = ($dumb_push eq "true");
120 my $wiki_name = $url;
121 $wiki_name =~ s/[^\/]*:\/\///;
122 # If URL is like http://user:password@example.com/, we clearly don't
123 # want the password in $wiki_name. While we're there, also remove user
124 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
125 $wiki_name =~ s/^.*@//;
133 if (defined($cmd[0])) {
135 if ($cmd[0] eq "capabilities") {
136 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
138 } elsif ($cmd[0] eq "list") {
139 die("Too many arguments for list") unless (!defined($cmd[2]));
141 } elsif ($cmd[0] eq "import") {
142 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
144 } elsif ($cmd[0] eq "option") {
145 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
146 mw_option($cmd[1],$cmd[2]);
147 } elsif ($cmd[0] eq "push") {
150 print STDERR "Unknown command. Aborting...\n";
154 # blank line: we should terminate
158 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
159 # command is fully processed.
162 ########################## Functions ##############################
164 ## credential API management (generic functions)
166 sub credential_from_url {
168 my $parsed = URI->new($url);
171 if ($parsed->scheme) {
172 $credential{protocol} = $parsed->scheme;
175 $credential{host} = $parsed->host;
178 $credential{path} = $parsed->path;
180 if ($parsed->userinfo) {
181 if ($parsed->userinfo =~ /([^:]*):(.*)/) {
182 $credential{username} = $1;
183 $credential{password} = $2;
185 $credential{username} = $parsed->userinfo;
192 sub credential_read {
197 my ($key, $value) = /([^=]*)=(.*)/;
198 if (not defined $key) {
199 die "ERROR receiving response from git credential $op:\n$_\n";
201 $credential{$key} = $value;
206 sub credential_write {
207 my $credential = shift;
209 while (my ($key, $value) = each(%$credential) ) {
211 print $writer "$key=$value\n";
218 my $credential = shift;
219 my $pid = open2(my $reader, my $writer, "git credential $op");
220 credential_write($credential, $writer);
225 %$credential = credential_read($reader, $op);
228 die "ERROR while running git credential $op:\n$_";
233 my $child_exit_status = $? >> 8;
234 if ($child_exit_status != 0) {
235 die "'git credential $op' failed with code $child_exit_status.";
239 # MediaWiki API instance, created lazily.
242 sub mw_connect_maybe {
246 $mediawiki = MediaWiki::API->new;
247 $mediawiki->{config}->{api_url} = "$url/api.php";
249 my %credential = credential_from_url($url);
250 $credential{username} = $wiki_login;
251 $credential{password} = $wiki_passwd;
252 credential_run("fill", \%credential);
253 my $request = {lgname => $credential{username},
254 lgpassword => $credential{password},
255 lgdomain => $wiki_domain};
256 if ($mediawiki->login($request)) {
257 credential_run("approve", \%credential);
258 print STDERR "Logged in mediawiki user \"$credential{username}\".\n";
260 print STDERR "Failed to log in mediawiki user \"$credential{username}\" on $url\n";
261 print STDERR " (error " .
262 $mediawiki->{error}->{code} . ': ' .
263 $mediawiki->{error}->{details} . ")\n";
264 credential_run("reject", \%credential);
270 ## Functions for listing pages on the remote wiki
271 sub get_mw_tracked_pages {
273 get_mw_page_list(\@tracked_pages, $pages);
276 sub get_mw_page_list {
277 my $page_list = shift;
279 my @some_pages = @$page_list;
280 while (@some_pages) {
282 if ($#some_pages < $last) {
283 $last = $#some_pages;
285 my @slice = @some_pages[0..$last];
286 get_mw_first_pages(\@slice, $pages);
287 @some_pages = @some_pages[51..$#some_pages];
291 sub get_mw_tracked_categories {
293 foreach my $category (@tracked_categories) {
294 if (index($category, ':') < 0) {
295 # Mediawiki requires the Category
296 # prefix, but let's not force the user
298 $category = "Category:" . $category;
300 my $mw_pages = $mediawiki->list( {
302 list => 'categorymembers',
303 cmtitle => $category,
305 || die $mediawiki->{error}->{code} . ': '
306 . $mediawiki->{error}->{details};
307 foreach my $page (@{$mw_pages}) {
308 $pages->{$page->{title}} = $page;
313 sub get_mw_all_pages {
315 # No user-provided list, get the list of pages from the API.
316 my $mw_pages = $mediawiki->list({
321 if (!defined($mw_pages)) {
322 print STDERR "fatal: could not get the list of wiki pages.\n";
323 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
324 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
327 foreach my $page (@{$mw_pages}) {
328 $pages->{$page->{title}} = $page;
332 # queries the wiki for a set of pages. Meant to be used within a loop
333 # querying the wiki for slices of page list.
334 sub get_mw_first_pages {
335 my $some_pages = shift;
336 my @some_pages = @{$some_pages};
340 # pattern 'page1|page2|...' required by the API
341 my $titles = join('|', @some_pages);
343 my $mw_pages = $mediawiki->api({
347 if (!defined($mw_pages)) {
348 print STDERR "fatal: could not query the list of wiki pages.\n";
349 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
350 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
353 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
355 print STDERR "Warning: page $page->{title} not found on wiki\n";
357 $pages->{$page->{title}} = $page;
362 # Get the list of pages to be fetched according to configuration.
366 my %pages; # hash on page titles to avoid duplicates
368 if (@tracked_pages) {
370 # The user provided a list of pages titles, but we
371 # still need to query the API to get the page IDs.
372 get_mw_tracked_pages(\%pages);
374 if (@tracked_categories) {
376 get_mw_tracked_categories(\%pages);
378 if (!$user_defined) {
379 get_mw_all_pages(\%pages);
382 print STDERR "Getting media files for selected pages...\n";
384 get_linked_mediafiles(\%pages);
386 get_all_mediafiles(\%pages);
392 # usage: $out = run_git("command args");
393 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
396 my $encoding = (shift || "encoding(UTF-8)");
397 open(my $git, "-|:$encoding", "git " . $args);
398 my $res = do { local $/; <$git> };
405 sub get_all_mediafiles {
407 # Attach list of all pages for media files from the API,
408 # they are in a different namespace, only one namespace
409 # can be queried at the same moment
410 my $mw_pages = $mediawiki->list({
413 apnamespace => get_mw_namespace_id("File"),
416 if (!defined($mw_pages)) {
417 print STDERR "fatal: could not get the list of pages for media files.\n";
418 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
419 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
422 foreach my $page (@{$mw_pages}) {
423 $pages->{$page->{title}} = $page;
427 sub get_linked_mediafiles {
429 my @titles = map $_->{title}, values(%{$pages});
431 # The query is split in small batches because of the MW API limit of
432 # the number of links to be returned (500 links max).
435 if ($#titles < $batch) {
438 my @slice = @titles[0..$batch];
440 # pattern 'page1|page2|...' required by the API
441 my $mw_titles = join('|', @slice);
443 # Media files could be included or linked from
444 # a page, get all related
447 prop => 'links|images',
448 titles => $mw_titles,
449 plnamespace => get_mw_namespace_id("File"),
452 my $result = $mediawiki->api($query);
454 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
456 if (defined($page->{links})) {
457 my @link_titles = map $_->{title}, @{$page->{links}};
458 push(@media_titles, @link_titles);
460 if (defined($page->{images})) {
461 my @image_titles = map $_->{title}, @{$page->{images}};
462 push(@media_titles, @image_titles);
465 get_mw_page_list(\@media_titles, $pages);
469 @titles = @titles[($batch+1)..$#titles];
473 sub get_mw_mediafile_for_page_revision {
474 # Name of the file on Wiki, with the prefix.
475 my $filename = shift;
476 my $timestamp = shift;
479 # Search if on a media file with given timestamp exists on
480 # MediaWiki. In that case download the file.
484 titles => "File:" . $filename,
485 iistart => $timestamp,
487 iiprop => 'timestamp|archivename|url',
490 my $result = $mediawiki->api($query);
492 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
493 # If not defined it means there is no revision of the file for
495 if (defined($file->{imageinfo})) {
496 $mediafile{title} = $filename;
498 my $fileinfo = pop(@{$file->{imageinfo}});
499 $mediafile{timestamp} = $fileinfo->{timestamp};
500 # Mediawiki::API's download function doesn't support https URLs
501 # and can't download old versions of files.
502 print STDERR "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
503 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
508 sub download_mw_mediafile {
511 my $response = $mediawiki->{ua}->get($url);
512 if ($response->code == 200) {
513 return $response->decoded_content;
515 print STDERR "Error downloading mediafile from :\n";
516 print STDERR "URL: $url\n";
517 print STDERR "Server response: " . $response->code . " " . $response->message . "\n";
522 sub get_last_local_revision {
523 # Get note regarding last mediawiki revision
524 my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
525 my @note_info = split(/ /, $note);
527 my $lastrevision_number;
528 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
529 print STDERR "No previous mediawiki revision found";
530 $lastrevision_number = 0;
532 # Notes are formatted : mediawiki_revision: #number
533 $lastrevision_number = $note_info[1];
534 chomp($lastrevision_number);
535 print STDERR "Last local mediawiki revision found is $lastrevision_number";
537 return $lastrevision_number;
540 # Remember the timestamp corresponding to a revision id.
543 # Get the last remote revision without taking in account which pages are
544 # tracked or not. This function makes a single request to the wiki thus
545 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
547 sub get_last_global_remote_rev {
552 list => 'recentchanges',
557 my $result = $mediawiki->api($query);
558 return $result->{query}->{recentchanges}[0]->{revid};
561 # Get the last remote revision concerning the tracked pages and the tracked
563 sub get_last_remote_revision {
566 my %pages_hash = get_mw_pages();
567 my @pages = values(%pages_hash);
571 foreach my $page (@pages) {
572 my $id = $page->{pageid};
577 rvprop => 'ids|timestamp',
581 my $result = $mediawiki->api($query);
583 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
585 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
587 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
590 print STDERR "Last remote revision found is $max_rev_num.\n";
594 # Clean content before sending it to MediaWiki
595 sub mediawiki_clean {
597 my $page_created = shift;
598 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
599 # This function right trims a string and adds a \n at the end to follow this rule
601 if ($string eq "" && $page_created) {
602 # Creating empty pages is forbidden.
603 $string = EMPTY_CONTENT;
608 # Filter applied on MediaWiki data before adding them to Git
609 sub mediawiki_smudge {
611 if ($string eq EMPTY_CONTENT) {
614 # This \n is important. This is due to mediawiki's way to handle end of files.
618 sub mediawiki_clean_filename {
619 my $filename = shift;
620 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
621 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
622 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
623 # but with _ added to prevent MediaWiki from thinking this is
624 # an actual special character.
625 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
626 # If we use the uri escape before
627 # we should unescape here, before anything
632 sub mediawiki_smudge_filename {
633 my $filename = shift;
634 $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
635 $filename =~ s/ /_/g;
636 # Decode forbidden characters encoded in mediawiki_clean_filename
637 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
643 print STDOUT "data ", bytes::length($content), "\n", $content;
646 sub literal_data_raw {
647 # Output possibly binary content.
649 # Avoid confusion between size in bytes and in characters
650 utf8::downgrade($content);
651 binmode STDOUT, ":raw";
652 print STDOUT "data ", bytes::length($content), "\n", $content;
653 binmode STDOUT, ":utf8";
656 sub mw_capabilities {
657 # Revisions are imported to the private namespace
658 # refs/mediawiki/$remotename/ by the helper and fetched into
659 # refs/remotes/$remotename later by fetch.
660 print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
661 print STDOUT "import\n";
662 print STDOUT "list\n";
663 print STDOUT "push\n";
668 # MediaWiki do not have branches, we consider one branch arbitrarily
669 # called master, and HEAD pointing to it.
670 print STDOUT "? refs/heads/master\n";
671 print STDOUT "\@refs/heads/master HEAD\n";
676 print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
677 print STDOUT "unsupported\n";
680 sub fetch_mw_revisions_for_page {
683 my $fetch_from = shift;
690 rvstartid => $fetch_from,
696 # Get 500 revisions at a time due to the mediawiki api limit
698 my $result = $mediawiki->api($query);
700 # Parse each of those 500 revisions
701 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
703 $page_rev_ids->{pageid} = $page->{pageid};
704 $page_rev_ids->{revid} = $revision->{revid};
705 push(@page_revs, $page_rev_ids);
708 last unless $result->{'query-continue'};
709 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
711 if ($shallow_import && @page_revs) {
712 print STDERR " Found 1 revision (shallow import).\n";
713 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
714 return $page_revs[0];
716 print STDERR " Found ", $revnum, " revision(s).\n";
720 sub fetch_mw_revisions {
721 my $pages = shift; my @pages = @{$pages};
722 my $fetch_from = shift;
726 foreach my $page (@pages) {
727 my $id = $page->{pageid};
729 print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
731 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
732 @revisions = (@page_revs, @revisions);
735 return ($n, @revisions);
738 sub import_file_revision {
740 my %commit = %{$commit};
741 my $full_import = shift;
743 my $mediafile = shift;
746 %mediafile = %{$mediafile};
749 my $title = $commit{title};
750 my $comment = $commit{comment};
751 my $content = $commit{content};
752 my $author = $commit{author};
753 my $date = $commit{date};
755 print STDOUT "commit refs/mediawiki/$remotename/master\n";
756 print STDOUT "mark :$n\n";
757 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
758 literal_data($comment);
760 # If it's not a clone, we need to know where to start from
761 if (!$full_import && $n == 1) {
762 print STDOUT "from refs/mediawiki/$remotename/master^0\n";
764 if ($content ne DELETED_CONTENT) {
765 print STDOUT "M 644 inline $title.mw\n";
766 literal_data($content);
768 print STDOUT "M 644 inline $mediafile{title}\n";
769 literal_data_raw($mediafile{content});
773 print STDOUT "D $title.mw\n";
776 # mediawiki revision number in the git note
777 if ($full_import && $n == 1) {
778 print STDOUT "reset refs/notes/$remotename/mediawiki\n";
780 print STDOUT "commit refs/notes/$remotename/mediawiki\n";
781 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
782 literal_data("Note added by git-mediawiki during import");
783 if (!$full_import && $n == 1) {
784 print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
786 print STDOUT "N inline :$n\n";
787 literal_data("mediawiki_revision: " . $commit{mw_revision});
791 # parse a sequence of
795 # (like batch sequence of import and sequence of push statements)
801 if ($line =~ m/^$cmd (.*)$/) {
803 } elsif ($line eq "\n") {
806 die("Invalid command in a '$cmd' batch: ". $_);
812 # multiple import commands can follow each other.
813 my @refs = (shift, get_more_refs("import"));
814 foreach my $ref (@refs) {
817 print STDOUT "done\n";
822 # The remote helper will call "import HEAD" and
823 # "import refs/heads/master".
824 # Since HEAD is a symbolic ref to master (by convention,
825 # followed by the output of the command "list" that we gave),
826 # we don't need to do anything in this case.
827 if ($ref eq "HEAD") {
833 print STDERR "Searching revisions...\n";
834 my $last_local = get_last_local_revision();
835 my $fetch_from = $last_local + 1;
836 if ($fetch_from == 1) {
837 print STDERR ", fetching from beginning.\n";
839 print STDERR ", fetching from here.\n";
843 if ($fetch_strategy eq "by_rev") {
844 print STDERR "Fetching & writing export data by revs...\n";
845 $n = mw_import_ref_by_revs($fetch_from);
846 } elsif ($fetch_strategy eq "by_page") {
847 print STDERR "Fetching & writing export data by pages...\n";
848 $n = mw_import_ref_by_pages($fetch_from);
850 print STDERR "fatal: invalid fetch strategy \"$fetch_strategy\".\n";
851 print STDERR "Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
855 if ($fetch_from == 1 && $n == 0) {
856 print STDERR "You appear to have cloned an empty MediaWiki.\n";
857 # Something has to be done remote-helper side. If nothing is done, an error is
858 # thrown saying that HEAD is refering to unknown object 0000000000000000000
859 # and the clone fails.
863 sub mw_import_ref_by_pages {
865 my $fetch_from = shift;
866 my %pages_hash = get_mw_pages();
867 my @pages = values(%pages_hash);
869 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
871 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
872 my @revision_ids = map $_->{revid}, @revisions;
874 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
877 sub mw_import_ref_by_revs {
879 my $fetch_from = shift;
880 my %pages_hash = get_mw_pages();
882 my $last_remote = get_last_global_remote_rev();
883 my @revision_ids = $fetch_from..$last_remote;
884 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
887 # Import revisions given in second argument (array of integers).
888 # Only pages appearing in the third argument (hash indexed by page titles)
890 sub mw_import_revids {
891 my $fetch_from = shift;
892 my $revision_ids = shift;
897 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
899 foreach my $pagerevid (@$revision_ids) {
900 # fetch the content of the pages
904 rvprop => 'content|timestamp|comment|user|ids',
905 revids => $pagerevid,
908 my $result = $mediawiki->api($query);
911 die "Failed to retrieve modified page for revision $pagerevid";
914 if (!defined($result->{query}->{pages})) {
915 die "Invalid revision $pagerevid.";
918 my @result_pages = values(%{$result->{query}->{pages}});
919 my $result_page = $result_pages[0];
920 my $rev = $result_pages[0]->{revisions}->[0];
922 # Count page even if we skip it, since we display
923 # $n/$total and $total includes skipped pages.
926 my $page_title = $result_page->{title};
928 if (!exists($pages->{$page_title})) {
929 print STDERR "$n/", scalar(@$revision_ids),
930 ": Skipping revision #$rev->{revid} of $page_title\n";
937 $commit{author} = $rev->{user} || 'Anonymous';
938 $commit{comment} = $rev->{comment} || '*Empty MediaWiki Message*';
939 $commit{title} = mediawiki_smudge_filename($page_title);
940 $commit{mw_revision} = $rev->{revid};
941 $commit{content} = mediawiki_smudge($rev->{'*'});
943 if (!defined($rev->{timestamp})) {
946 $last_timestamp = $rev->{timestamp};
948 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
950 # Differentiates classic pages and media files.
951 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
953 if ($namespace && get_mw_namespace_id($namespace) == get_mw_namespace_id("File")) {
954 %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 "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 priviledged user
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 "") {
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};
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 my $new_sha1 = $diff_info_split[3];
1054 my $old_sha1 = $diff_info_split[2];
1055 my $page_created = ($old_sha1 eq NULL_SHA1);
1056 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1057 $complete_file_name = mediawiki_clean_filename($complete_file_name);
1059 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1060 if (!defined($extension)) {
1063 if ($extension eq "mw") {
1065 if ($page_deleted) {
1066 # Deleting a page usually requires
1067 # special priviledges. A common
1068 # convention is to replace the page
1069 # with this content instead:
1070 $file_content = DELETED_CONTENT;
1072 $file_content = run_git("cat-file blob $new_sha1");
1077 my $result = $mediawiki->edit( {
1079 summary => $summary,
1081 basetimestamp => $basetimestamps{$oldrevid},
1082 text => mediawiki_clean($file_content, $page_created),
1084 skip_encoding => 1 # Helps with names with accentuated characters
1087 if ($mediawiki->{error}->{code} == 3) {
1088 # edit conflicts, considered as non-fast-forward
1089 print STDERR 'Warning: Error ' .
1090 $mediawiki->{error}->{code} .
1091 ' from mediwiki: ' . $mediawiki->{error}->{details} .
1093 return ($oldrevid, "non-fast-forward");
1095 # Other errors. Shouldn't happen => just die()
1096 die 'Fatal: Error ' .
1097 $mediawiki->{error}->{code} .
1098 ' from mediwiki: ' . $mediawiki->{error}->{details};
1101 $newrevid = $result->{edit}->{newrevid};
1102 print STDERR "Pushed file: $new_sha1 - $title\n";
1104 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1105 $extension, $page_deleted,
1108 $newrevid = ($newrevid or $oldrevid);
1109 return ($newrevid, "ok");
1113 # multiple push statements can follow each other
1114 my @refsspecs = (shift, get_more_refs("push"));
1116 for my $refspec (@refsspecs) {
1117 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1118 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1120 print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
1123 print STDERR "Cannot delete remote branch on a MediaWiki\n";
1124 print STDOUT "error $remote cannot delete\n";
1127 if ($remote ne "refs/heads/master") {
1128 print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
1129 print STDOUT "error $remote only master allowed\n";
1132 if (mw_push_revision($local, $remote)) {
1137 # Notify Git that the push is done
1140 if ($pushed && $dumb_push) {
1141 print STDERR "Just pushed some revisions to MediaWiki.\n";
1142 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
1143 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
1145 print STDERR " git pull --rebase\n";
1150 sub mw_push_revision {
1152 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1153 my $last_local_revid = get_last_local_revision();
1154 print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
1155 my $last_remote_revid = get_last_remote_revision();
1156 my $mw_revision = $last_remote_revid;
1158 # Get sha1 of commit pointed by local HEAD
1159 my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1160 # Get sha1 of commit pointed by remotes/$remotename/master
1161 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1162 chomp($remoteorigin_sha1);
1164 if ($last_local_revid > 0 &&
1165 $last_local_revid < $last_remote_revid) {
1166 return error_non_fast_forward($remote);
1169 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1174 # Get every commit in between HEAD and refs/remotes/origin/master,
1175 # including HEAD and refs/remotes/origin/master
1176 my @commit_pairs = ();
1177 if ($last_local_revid > 0) {
1178 my $parsed_sha1 = $remoteorigin_sha1;
1179 # Find a path from last MediaWiki commit to pushed commit
1180 while ($parsed_sha1 ne $HEAD_sha1) {
1181 my @commit_info = grep(/^$parsed_sha1/, split(/\n/, run_git("rev-list --children $local")));
1182 if (!@commit_info) {
1183 return error_non_fast_forward($remote);
1185 my @commit_info_split = split(/ |\n/, $commit_info[0]);
1186 # $commit_info_split[1] is the sha1 of the commit to export
1187 # $commit_info_split[0] is the sha1 of its direct child
1188 push(@commit_pairs, \@commit_info_split);
1189 $parsed_sha1 = $commit_info_split[1];
1192 # No remote mediawiki revision. Export the whole
1193 # history (linearized with --first-parent)
1194 print STDERR "Warning: no common ancestor, pushing complete history\n";
1195 my $history = run_git("rev-list --first-parent --children $local");
1196 my @history = split('\n', $history);
1197 @history = @history[1..$#history];
1198 foreach my $line (reverse @history) {
1199 my @commit_info_split = split(/ |\n/, $line);
1200 push(@commit_pairs, \@commit_info_split);
1204 foreach my $commit_info_split (@commit_pairs) {
1205 my $sha1_child = @{$commit_info_split}[0];
1206 my $sha1_commit = @{$commit_info_split}[1];
1207 my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
1208 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1209 # TODO: for now, it's just a delete+add
1210 my @diff_info_list = split(/\0/, $diff_infos);
1211 # Keep the subject line of the commit message as mediawiki comment for the revision
1212 my $commit_msg = run_git("log --no-walk --format=\"%s\" $sha1_commit");
1215 while (@diff_info_list) {
1217 # git diff-tree -z gives an output like
1218 # <metadata>\0<filename1>\0
1219 # <metadata>\0<filename2>\0
1220 # and we've split on \0.
1221 my $info = shift(@diff_info_list);
1222 my $file = shift(@diff_info_list);
1223 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1224 if ($status eq "non-fast-forward") {
1225 # we may already have sent part of the
1226 # commit to MediaWiki, but it's too
1227 # late to cancel it. Stop the push in
1228 # the middle, but still give an
1229 # accurate error message.
1230 return error_non_fast_forward($remote);
1232 if ($status ne "ok") {
1233 die("Unknown error from mw_push_file()");
1236 unless ($dumb_push) {
1237 run_git("notes --ref=$remotename/mediawiki add -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1238 run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1242 print STDOUT "ok $remote\n";
1246 sub get_allowed_file_extensions {
1252 siprop => 'fileextensions'
1254 my $result = $mediawiki->api($query);
1255 my @file_extensions= map $_->{ext},@{$result->{query}->{fileextensions}};
1256 my %hashFile = map {$_ => 1}@file_extensions;
1261 # In memory cache for MediaWiki namespace ids.
1264 # Namespaces whose id is cached in the configuration file
1265 # (to avoid duplicates)
1266 my %cached_mw_namespace_id;
1268 # Return MediaWiki id for a canonical namespace name.
1269 # Ex.: "File", "Project".
1270 sub get_mw_namespace_id {
1274 if (!exists $namespace_id{$name}) {
1275 # Look at configuration file, if the record for that namespace is
1276 # already cached. Namespaces are stored in form:
1277 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1278 my @temp = split(/[ \n]/, run_git("config --get-all remote."
1279 . $remotename .".namespaceCache"));
1281 foreach my $ns (@temp) {
1282 my ($n, $id) = split(/:/, $ns);
1283 $namespace_id{$n} = $id;
1284 $cached_mw_namespace_id{$n} = 1;
1288 if (!exists $namespace_id{$name}) {
1289 print STDERR "Namespace $name not found in cache, querying the wiki ...\n";
1290 # NS not found => get namespace id from MW and store it in
1291 # configuration file.
1295 siprop => 'namespaces'
1297 my $result = $mediawiki->api($query);
1299 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1300 if (defined($ns->{id}) && defined($ns->{canonical})) {
1301 $namespace_id{$ns->{canonical}} = $ns->{id};
1303 # alias (e.g. french Fichier: as alias for canonical File:)
1304 $namespace_id{$ns->{'*'}} = $ns->{id};
1310 my $id = $namespace_id{$name};
1313 # Store explicitely requested namespaces on disk
1314 if (!exists $cached_mw_namespace_id{$name}) {
1315 run_git("config --add remote.". $remotename
1316 .".namespaceCache \"". $name .":". $id ."\"");
1317 $cached_mw_namespace_id{$name} = 1;
1321 die "No such namespace $name on MediaWiki.";