4 # Jérémie Nikaes <jeremie.nikaes@ensimag.imag.fr>
5 # Arnaud Lacurie <arnaud.lacurie@ensimag.imag.fr>
6 # Claire Fousse <claire.fousse@ensimag.imag.fr>
7 # David Amouyal <david.amouyal@ensimag.imag.fr>
8 # Matthieu Moy <matthieu.moy@grenoble-inp.fr>
9 # License: GPL v2 or later
11 # Gateway between Git and MediaWiki.
12 # Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
17 use DateTime::Format::ISO8601;
19 # By default, use UTF-8 to communicate with Git and the user
20 binmode STDERR, ":utf8";
21 binmode STDOUT, ":utf8";
28 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
29 use constant SLASH_REPLACEMENT => "%2F";
31 # It's not always possible to delete pages (may require some
32 # privileges). Deleted pages are replaced with this content.
33 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
35 # It's not possible to create empty pages. New empty files in Git are
36 # sent with this content instead.
37 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
39 # used to reflect file creation or deletion in diff.
40 use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
42 # Used on Git's side to reflect empty edit messages on the wiki
43 use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
45 my $remotename = $ARGV[0];
48 # Accept both space-separated and multiple keys in config file.
49 # Spaces should be written as _ anyway because we'll use chomp.
50 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
51 chomp(@tracked_pages);
53 # Just like @tracked_pages, but for MediaWiki categories.
54 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
55 chomp(@tracked_categories);
57 # Import media files on pull
58 my $import_media = run_git("config --get --bool remote.". $remotename .".mediaimport");
60 $import_media = ($import_media eq "true");
62 # Export media files on push
63 my $export_media = run_git("config --get --bool remote.". $remotename .".mediaexport");
65 $export_media = !($export_media eq "false");
67 my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
68 # Note: mwPassword is discourraged. Use the credential system instead.
69 my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
70 my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
75 # Import only last revisions (both for clone and fetch)
76 my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
77 chomp($shallow_import);
78 $shallow_import = ($shallow_import eq "true");
80 # Fetch (clone and pull) by revisions instead of by pages. This behavior
81 # is more efficient when we have a wiki with lots of pages and we fetch
82 # the revisions quite often so that they concern only few pages.
84 # - by_rev: perform one query per new revision on the remote wiki
85 # - by_page: query each tracked page for new revision
86 my $fetch_strategy = run_git("config --get remote.$remotename.fetchStrategy");
87 unless ($fetch_strategy) {
88 $fetch_strategy = run_git("config --get mediawiki.fetchStrategy");
90 chomp($fetch_strategy);
91 unless ($fetch_strategy) {
92 $fetch_strategy = "by_page";
95 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
97 # Configurable with mediawiki.dumbPush, or per-remote with
98 # remote.<remotename>.dumbPush.
100 # This means the user will have to re-import the just-pushed
101 # revisions. On the other hand, this means that the Git revisions
102 # corresponding to MediaWiki revisions are all imported from the wiki,
103 # regardless of whether they were initially created in Git or from the
104 # web interface, hence all users will get the same history (i.e. if
105 # the push from Git to MediaWiki loses some information, everybody
106 # will get the history with information lost). If the import is
107 # deterministic, this means everybody gets the same sha1 for each
108 # MediaWiki revision.
109 my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
110 unless ($dumb_push) {
111 $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
114 $dumb_push = ($dumb_push eq "true");
116 my $wiki_name = $url;
117 $wiki_name =~ s/[^\/]*:\/\///;
118 # If URL is like http://user:password@example.com/, we clearly don't
119 # want the password in $wiki_name. While we're there, also remove user
120 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
121 $wiki_name =~ s/^.*@//;
129 if (defined($cmd[0])) {
131 if ($cmd[0] eq "capabilities") {
132 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
134 } elsif ($cmd[0] eq "list") {
135 die("Too many arguments for list") unless (!defined($cmd[2]));
137 } elsif ($cmd[0] eq "import") {
138 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
140 } elsif ($cmd[0] eq "option") {
141 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
142 mw_option($cmd[1],$cmd[2]);
143 } elsif ($cmd[0] eq "push") {
146 print STDERR "Unknown command. Aborting...\n";
150 # blank line: we should terminate
154 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
155 # command is fully processed.
158 ########################## Functions ##############################
160 # MediaWiki API instance, created lazily.
163 sub mw_connect_maybe {
167 $mediawiki = MediaWiki::API->new;
168 $mediawiki->{config}->{api_url} = "$url/api.php";
172 'username' => $wiki_login,
173 'password' => $wiki_passwd
175 Git::credential(\%credential);
176 my $request = {lgname => $credential{username},
177 lgpassword => $credential{password},
178 lgdomain => $wiki_domain};
179 if ($mediawiki->login($request)) {
180 Git::credential(\%credential, 'approve');
181 print STDERR "Logged in mediawiki user \"$credential{username}\".\n";
183 print STDERR "Failed to log in mediawiki user \"$credential{username}\" on $url\n";
184 print STDERR " (error " .
185 $mediawiki->{error}->{code} . ': ' .
186 $mediawiki->{error}->{details} . ")\n";
187 Git::credential(\%credential, 'reject');
193 ## Functions for listing pages on the remote wiki
194 sub get_mw_tracked_pages {
196 get_mw_page_list(\@tracked_pages, $pages);
199 sub get_mw_page_list {
200 my $page_list = shift;
202 my @some_pages = @$page_list;
203 while (@some_pages) {
205 if ($#some_pages < $last) {
206 $last = $#some_pages;
208 my @slice = @some_pages[0..$last];
209 get_mw_first_pages(\@slice, $pages);
210 @some_pages = @some_pages[51..$#some_pages];
214 sub get_mw_tracked_categories {
216 foreach my $category (@tracked_categories) {
217 if (index($category, ':') < 0) {
218 # Mediawiki requires the Category
219 # prefix, but let's not force the user
221 $category = "Category:" . $category;
223 my $mw_pages = $mediawiki->list( {
225 list => 'categorymembers',
226 cmtitle => $category,
228 || die $mediawiki->{error}->{code} . ': '
229 . $mediawiki->{error}->{details};
230 foreach my $page (@{$mw_pages}) {
231 $pages->{$page->{title}} = $page;
236 sub get_mw_all_pages {
238 # No user-provided list, get the list of pages from the API.
239 my $mw_pages = $mediawiki->list({
244 if (!defined($mw_pages)) {
245 print STDERR "fatal: could not get the list of wiki pages.\n";
246 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
247 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
250 foreach my $page (@{$mw_pages}) {
251 $pages->{$page->{title}} = $page;
255 # queries the wiki for a set of pages. Meant to be used within a loop
256 # querying the wiki for slices of page list.
257 sub get_mw_first_pages {
258 my $some_pages = shift;
259 my @some_pages = @{$some_pages};
263 # pattern 'page1|page2|...' required by the API
264 my $titles = join('|', @some_pages);
266 my $mw_pages = $mediawiki->api({
270 if (!defined($mw_pages)) {
271 print STDERR "fatal: could not query the list of wiki pages.\n";
272 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
273 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
276 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
278 print STDERR "Warning: page $page->{title} not found on wiki\n";
280 $pages->{$page->{title}} = $page;
285 # Get the list of pages to be fetched according to configuration.
289 print STDERR "Listing pages on remote wiki...\n";
291 my %pages; # hash on page titles to avoid duplicates
293 if (@tracked_pages) {
295 # The user provided a list of pages titles, but we
296 # still need to query the API to get the page IDs.
297 get_mw_tracked_pages(\%pages);
299 if (@tracked_categories) {
301 get_mw_tracked_categories(\%pages);
303 if (!$user_defined) {
304 get_mw_all_pages(\%pages);
307 print STDERR "Getting media files for selected pages...\n";
309 get_linked_mediafiles(\%pages);
311 get_all_mediafiles(\%pages);
314 print STDERR (scalar keys %pages) . " pages found.\n";
318 # usage: $out = run_git("command args");
319 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
322 my $encoding = (shift || "encoding(UTF-8)");
323 open(my $git, "-|:$encoding", "git " . $args);
324 my $res = do { local $/; <$git> };
331 sub get_all_mediafiles {
333 # Attach list of all pages for media files from the API,
334 # they are in a different namespace, only one namespace
335 # can be queried at the same moment
336 my $mw_pages = $mediawiki->list({
339 apnamespace => get_mw_namespace_id("File"),
342 if (!defined($mw_pages)) {
343 print STDERR "fatal: could not get the list of pages for media files.\n";
344 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
345 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
348 foreach my $page (@{$mw_pages}) {
349 $pages->{$page->{title}} = $page;
353 sub get_linked_mediafiles {
355 my @titles = map $_->{title}, values(%{$pages});
357 # The query is split in small batches because of the MW API limit of
358 # the number of links to be returned (500 links max).
361 if ($#titles < $batch) {
364 my @slice = @titles[0..$batch];
366 # pattern 'page1|page2|...' required by the API
367 my $mw_titles = join('|', @slice);
369 # Media files could be included or linked from
370 # a page, get all related
373 prop => 'links|images',
374 titles => $mw_titles,
375 plnamespace => get_mw_namespace_id("File"),
378 my $result = $mediawiki->api($query);
380 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
382 if (defined($page->{links})) {
383 my @link_titles = map $_->{title}, @{$page->{links}};
384 push(@media_titles, @link_titles);
386 if (defined($page->{images})) {
387 my @image_titles = map $_->{title}, @{$page->{images}};
388 push(@media_titles, @image_titles);
391 get_mw_page_list(\@media_titles, $pages);
395 @titles = @titles[($batch+1)..$#titles];
399 sub get_mw_mediafile_for_page_revision {
400 # Name of the file on Wiki, with the prefix.
401 my $filename = shift;
402 my $timestamp = shift;
405 # Search if on a media file with given timestamp exists on
406 # MediaWiki. In that case download the file.
410 titles => "File:" . $filename,
411 iistart => $timestamp,
413 iiprop => 'timestamp|archivename|url',
416 my $result = $mediawiki->api($query);
418 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
419 # If not defined it means there is no revision of the file for
421 if (defined($file->{imageinfo})) {
422 $mediafile{title} = $filename;
424 my $fileinfo = pop(@{$file->{imageinfo}});
425 $mediafile{timestamp} = $fileinfo->{timestamp};
426 # Mediawiki::API's download function doesn't support https URLs
427 # and can't download old versions of files.
428 print STDERR "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
429 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
434 sub download_mw_mediafile {
437 my $response = $mediawiki->{ua}->get($url);
438 if ($response->code == 200) {
439 return $response->decoded_content;
441 print STDERR "Error downloading mediafile from :\n";
442 print STDERR "URL: $url\n";
443 print STDERR "Server response: " . $response->code . " " . $response->message . "\n";
448 sub get_last_local_revision {
449 # Get note regarding last mediawiki revision
450 my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
451 my @note_info = split(/ /, $note);
453 my $lastrevision_number;
454 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
455 print STDERR "No previous mediawiki revision found";
456 $lastrevision_number = 0;
458 # Notes are formatted : mediawiki_revision: #number
459 $lastrevision_number = $note_info[1];
460 chomp($lastrevision_number);
461 print STDERR "Last local mediawiki revision found is $lastrevision_number";
463 return $lastrevision_number;
466 # Remember the timestamp corresponding to a revision id.
469 # Get the last remote revision without taking in account which pages are
470 # tracked or not. This function makes a single request to the wiki thus
471 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
473 sub get_last_global_remote_rev {
478 list => 'recentchanges',
483 my $result = $mediawiki->api($query);
484 return $result->{query}->{recentchanges}[0]->{revid};
487 # Get the last remote revision concerning the tracked pages and the tracked
489 sub get_last_remote_revision {
492 my %pages_hash = get_mw_pages();
493 my @pages = values(%pages_hash);
497 print STDERR "Getting last revision id on tracked pages...\n";
499 foreach my $page (@pages) {
500 my $id = $page->{pageid};
505 rvprop => 'ids|timestamp',
509 my $result = $mediawiki->api($query);
511 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
513 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
515 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
518 print STDERR "Last remote revision found is $max_rev_num.\n";
522 # Clean content before sending it to MediaWiki
523 sub mediawiki_clean {
525 my $page_created = shift;
526 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
527 # This function right trims a string and adds a \n at the end to follow this rule
529 if ($string eq "" && $page_created) {
530 # Creating empty pages is forbidden.
531 $string = EMPTY_CONTENT;
536 # Filter applied on MediaWiki data before adding them to Git
537 sub mediawiki_smudge {
539 if ($string eq EMPTY_CONTENT) {
542 # This \n is important. This is due to mediawiki's way to handle end of files.
546 sub mediawiki_clean_filename {
547 my $filename = shift;
548 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
549 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
550 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
551 # but with _ added to prevent MediaWiki from thinking this is
552 # an actual special character.
553 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
554 # If we use the uri escape before
555 # we should unescape here, before anything
560 sub mediawiki_smudge_filename {
561 my $filename = shift;
562 $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
563 $filename =~ s/ /_/g;
564 # Decode forbidden characters encoded in mediawiki_clean_filename
565 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
571 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, ":utf8";
584 sub mw_capabilities {
585 # Revisions are imported to the private namespace
586 # refs/mediawiki/$remotename/ by the helper and fetched into
587 # refs/remotes/$remotename later by fetch.
588 print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
589 print STDOUT "import\n";
590 print STDOUT "list\n";
591 print STDOUT "push\n";
596 # MediaWiki do not have branches, we consider one branch arbitrarily
597 # called master, and HEAD pointing to it.
598 print STDOUT "? refs/heads/master\n";
599 print STDOUT "\@refs/heads/master HEAD\n";
604 print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
605 print STDOUT "unsupported\n";
608 sub fetch_mw_revisions_for_page {
611 my $fetch_from = shift;
618 rvstartid => $fetch_from,
624 # Get 500 revisions at a time due to the mediawiki api limit
626 my $result = $mediawiki->api($query);
628 # Parse each of those 500 revisions
629 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
631 $page_rev_ids->{pageid} = $page->{pageid};
632 $page_rev_ids->{revid} = $revision->{revid};
633 push(@page_revs, $page_rev_ids);
636 last unless $result->{'query-continue'};
637 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
639 if ($shallow_import && @page_revs) {
640 print STDERR " Found 1 revision (shallow import).\n";
641 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
642 return $page_revs[0];
644 print STDERR " Found ", $revnum, " revision(s).\n";
648 sub fetch_mw_revisions {
649 my $pages = shift; my @pages = @{$pages};
650 my $fetch_from = shift;
654 foreach my $page (@pages) {
655 my $id = $page->{pageid};
657 print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
659 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
660 @revisions = (@page_revs, @revisions);
663 return ($n, @revisions);
668 $path =~ s/\\/\\\\/g;
671 return '"' . $path . '"';
674 sub import_file_revision {
676 my %commit = %{$commit};
677 my $full_import = shift;
679 my $mediafile = shift;
682 %mediafile = %{$mediafile};
685 my $title = $commit{title};
686 my $comment = $commit{comment};
687 my $content = $commit{content};
688 my $author = $commit{author};
689 my $date = $commit{date};
691 print STDOUT "commit refs/mediawiki/$remotename/master\n";
692 print STDOUT "mark :$n\n";
693 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
694 literal_data($comment);
696 # If it's not a clone, we need to know where to start from
697 if (!$full_import && $n == 1) {
698 print STDOUT "from refs/mediawiki/$remotename/master^0\n";
700 if ($content ne DELETED_CONTENT) {
701 print STDOUT "M 644 inline " .
702 fe_escape_path($title . ".mw") . "\n";
703 literal_data($content);
705 print STDOUT "M 644 inline "
706 . fe_escape_path($mediafile{title}) . "\n";
707 literal_data_raw($mediafile{content});
711 print STDOUT "D " . fe_escape_path($title . ".mw") . "\n";
714 # mediawiki revision number in the git note
715 if ($full_import && $n == 1) {
716 print STDOUT "reset refs/notes/$remotename/mediawiki\n";
718 print STDOUT "commit refs/notes/$remotename/mediawiki\n";
719 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
720 literal_data("Note added by git-mediawiki during import");
721 if (!$full_import && $n == 1) {
722 print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
724 print STDOUT "N inline :$n\n";
725 literal_data("mediawiki_revision: " . $commit{mw_revision});
729 # parse a sequence of
733 # (like batch sequence of import and sequence of push statements)
739 if ($line =~ m/^$cmd (.*)$/) {
741 } elsif ($line eq "\n") {
744 die("Invalid command in a '$cmd' batch: ". $_);
750 # multiple import commands can follow each other.
751 my @refs = (shift, get_more_refs("import"));
752 foreach my $ref (@refs) {
755 print STDOUT "done\n";
760 # The remote helper will call "import HEAD" and
761 # "import refs/heads/master".
762 # Since HEAD is a symbolic ref to master (by convention,
763 # followed by the output of the command "list" that we gave),
764 # we don't need to do anything in this case.
765 if ($ref eq "HEAD") {
771 print STDERR "Searching revisions...\n";
772 my $last_local = get_last_local_revision();
773 my $fetch_from = $last_local + 1;
774 if ($fetch_from == 1) {
775 print STDERR ", fetching from beginning.\n";
777 print STDERR ", fetching from here.\n";
781 if ($fetch_strategy eq "by_rev") {
782 print STDERR "Fetching & writing export data by revs...\n";
783 $n = mw_import_ref_by_revs($fetch_from);
784 } elsif ($fetch_strategy eq "by_page") {
785 print STDERR "Fetching & writing export data by pages...\n";
786 $n = mw_import_ref_by_pages($fetch_from);
788 print STDERR "fatal: invalid fetch strategy \"$fetch_strategy\".\n";
789 print STDERR "Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
793 if ($fetch_from == 1 && $n == 0) {
794 print STDERR "You appear to have cloned an empty MediaWiki.\n";
795 # Something has to be done remote-helper side. If nothing is done, an error is
796 # thrown saying that HEAD is referring to unknown object 0000000000000000000
797 # and the clone fails.
801 sub mw_import_ref_by_pages {
803 my $fetch_from = shift;
804 my %pages_hash = get_mw_pages();
805 my @pages = values(%pages_hash);
807 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
809 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
810 my @revision_ids = map $_->{revid}, @revisions;
812 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
815 sub mw_import_ref_by_revs {
817 my $fetch_from = shift;
818 my %pages_hash = get_mw_pages();
820 my $last_remote = get_last_global_remote_rev();
821 my @revision_ids = $fetch_from..$last_remote;
822 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
825 # Import revisions given in second argument (array of integers).
826 # Only pages appearing in the third argument (hash indexed by page titles)
828 sub mw_import_revids {
829 my $fetch_from = shift;
830 my $revision_ids = shift;
835 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
837 foreach my $pagerevid (@$revision_ids) {
838 # Count page even if we skip it, since we display
839 # $n/$total and $total includes skipped pages.
842 # fetch the content of the pages
846 rvprop => 'content|timestamp|comment|user|ids',
847 revids => $pagerevid,
850 my $result = $mediawiki->api($query);
853 die "Failed to retrieve modified page for revision $pagerevid";
856 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
857 # The revision id does not exist on the remote wiki.
861 if (!defined($result->{query}->{pages})) {
862 die "Invalid revision $pagerevid.";
865 my @result_pages = values(%{$result->{query}->{pages}});
866 my $result_page = $result_pages[0];
867 my $rev = $result_pages[0]->{revisions}->[0];
869 my $page_title = $result_page->{title};
871 if (!exists($pages->{$page_title})) {
872 print STDERR "$n/", scalar(@$revision_ids),
873 ": Skipping revision #$rev->{revid} of $page_title\n";
880 $commit{author} = $rev->{user} || 'Anonymous';
881 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
882 $commit{title} = mediawiki_smudge_filename($page_title);
883 $commit{mw_revision} = $rev->{revid};
884 $commit{content} = mediawiki_smudge($rev->{'*'});
886 if (!defined($rev->{timestamp})) {
889 $last_timestamp = $rev->{timestamp};
891 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
893 # Differentiates classic pages and media files.
894 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
897 my $id = get_mw_namespace_id($namespace);
898 if ($id && $id == get_mw_namespace_id("File")) {
899 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
902 # If this is a revision of the media page for new version
903 # of a file do one common commit for both file and media page.
904 # Else do commit only for that page.
905 print STDERR "$n/", scalar(@$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
906 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
912 sub error_non_fast_forward {
913 my $advice = run_git("config --bool advice.pushNonFastForward");
915 if ($advice ne "false") {
916 # Native git-push would show this after the summary.
917 # We can't ask it to display it cleanly, so print it
919 print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
920 print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
921 print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
923 print STDOUT "error $_[0] \"non-fast-forward\"\n";
928 my $complete_file_name = shift;
929 my $new_sha1 = shift;
930 my $extension = shift;
931 my $file_deleted = shift;
934 my $path = "File:" . $complete_file_name;
935 my %hashFiles = get_allowed_file_extensions();
936 if (!exists($hashFiles{$extension})) {
937 print STDERR "$complete_file_name is not a permitted file on this wiki.\n";
938 print STDERR "Check the configuration of file uploads in your mediawiki.\n";
941 # Deleting and uploading a file requires a priviledged user
949 if (!$mediawiki->edit($query)) {
950 print STDERR "Failed to delete file on remote wiki\n";
951 print STDERR "Check your permissions on the remote site. Error code:\n";
952 print STDERR $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
956 # Don't let perl try to interpret file content as UTF-8 => use "raw"
957 my $content = run_git("cat-file blob $new_sha1", "raw");
958 if ($content ne "") {
960 $mediawiki->{config}->{upload_url} =
961 "$url/index.php/Special:Upload";
964 filename => $complete_file_name,
968 Content => $content],
972 } ) || die $mediawiki->{error}->{code} . ':'
973 . $mediawiki->{error}->{details};
974 my $last_file_page = $mediawiki->get_page({title => $path});
975 $newrevid = $last_file_page->{revid};
976 print STDERR "Pushed file: $new_sha1 - $complete_file_name.\n";
978 print STDERR "Empty file $complete_file_name not pushed.\n";
985 my $diff_info = shift;
986 # $diff_info contains a string in this format:
987 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
988 my @diff_info_split = split(/[ \t]/, $diff_info);
990 # Filename, including .mw extension
991 my $complete_file_name = shift;
994 # MediaWiki revision number. Keep the previous one by default,
995 # in case there's no edit to perform.
996 my $oldrevid = shift;
999 if ($summary eq EMPTY_MESSAGE) {
1003 my $new_sha1 = $diff_info_split[3];
1004 my $old_sha1 = $diff_info_split[2];
1005 my $page_created = ($old_sha1 eq NULL_SHA1);
1006 my $page_deleted = ($new_sha1 eq NULL_SHA1);
1007 $complete_file_name = mediawiki_clean_filename($complete_file_name);
1009 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1010 if (!defined($extension)) {
1013 if ($extension eq "mw") {
1014 my $ns = get_mw_namespace_id_for_page($complete_file_name);
1015 if ($ns && $ns == get_mw_namespace_id("File") && (!$export_media)) {
1016 print STDERR "Ignoring media file related page: $complete_file_name\n";
1017 return ($oldrevid, "ok");
1020 if ($page_deleted) {
1021 # Deleting a page usually requires
1022 # special privileges. A common
1023 # convention is to replace the page
1024 # with this content instead:
1025 $file_content = DELETED_CONTENT;
1027 $file_content = run_git("cat-file blob $new_sha1");
1032 my $result = $mediawiki->edit( {
1034 summary => $summary,
1036 basetimestamp => $basetimestamps{$oldrevid},
1037 text => mediawiki_clean($file_content, $page_created),
1039 skip_encoding => 1 # Helps with names with accentuated characters
1042 if ($mediawiki->{error}->{code} == 3) {
1043 # edit conflicts, considered as non-fast-forward
1044 print STDERR 'Warning: Error ' .
1045 $mediawiki->{error}->{code} .
1046 ' from mediwiki: ' . $mediawiki->{error}->{details} .
1048 return ($oldrevid, "non-fast-forward");
1050 # Other errors. Shouldn't happen => just die()
1051 die 'Fatal: Error ' .
1052 $mediawiki->{error}->{code} .
1053 ' from mediwiki: ' . $mediawiki->{error}->{details};
1056 $newrevid = $result->{edit}->{newrevid};
1057 print STDERR "Pushed file: $new_sha1 - $title\n";
1058 } elsif ($export_media) {
1059 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1060 $extension, $page_deleted,
1063 print STDERR "Ignoring media file $title\n";
1065 $newrevid = ($newrevid or $oldrevid);
1066 return ($newrevid, "ok");
1070 # multiple push statements can follow each other
1071 my @refsspecs = (shift, get_more_refs("push"));
1073 for my $refspec (@refsspecs) {
1074 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1075 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1077 print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
1080 print STDERR "Cannot delete remote branch on a MediaWiki\n";
1081 print STDOUT "error $remote cannot delete\n";
1084 if ($remote ne "refs/heads/master") {
1085 print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
1086 print STDOUT "error $remote only master allowed\n";
1089 if (mw_push_revision($local, $remote)) {
1094 # Notify Git that the push is done
1097 if ($pushed && $dumb_push) {
1098 print STDERR "Just pushed some revisions to MediaWiki.\n";
1099 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
1100 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
1102 print STDERR " git pull --rebase\n";
1107 sub mw_push_revision {
1109 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1110 my $last_local_revid = get_last_local_revision();
1111 print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
1112 my $last_remote_revid = get_last_remote_revision();
1113 my $mw_revision = $last_remote_revid;
1115 # Get sha1 of commit pointed by local HEAD
1116 my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1117 # Get sha1 of commit pointed by remotes/$remotename/master
1118 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1119 chomp($remoteorigin_sha1);
1121 if ($last_local_revid > 0 &&
1122 $last_local_revid < $last_remote_revid) {
1123 return error_non_fast_forward($remote);
1126 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1131 # Get every commit in between HEAD and refs/remotes/origin/master,
1132 # including HEAD and refs/remotes/origin/master
1133 my @commit_pairs = ();
1134 if ($last_local_revid > 0) {
1135 my $parsed_sha1 = $remoteorigin_sha1;
1136 # Find a path from last MediaWiki commit to pushed commit
1137 print STDERR "Computing path from local to remote ...\n";
1138 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents $local ^$parsed_sha1"));
1140 foreach my $line (@local_ancestry) {
1141 if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1142 foreach my $parent (split(' ', $parents)) {
1143 $local_ancestry{$parent} = $child;
1145 } elsif (!$line =~ m/^([a-f0-9]+)/) {
1146 die "Unexpected output from git rev-list: $line";
1149 while ($parsed_sha1 ne $HEAD_sha1) {
1150 my $child = $local_ancestry{$parsed_sha1};
1152 printf STDERR "Cannot find a path in history from remote commit to last commit\n";
1153 return error_non_fast_forward($remote);
1155 push(@commit_pairs, [$parsed_sha1, $child]);
1156 $parsed_sha1 = $child;
1159 # No remote mediawiki revision. Export the whole
1160 # history (linearized with --first-parent)
1161 print STDERR "Warning: no common ancestor, pushing complete history\n";
1162 my $history = run_git("rev-list --first-parent --children $local");
1163 my @history = split('\n', $history);
1164 @history = @history[1..$#history];
1165 foreach my $line (reverse @history) {
1166 my @commit_info_split = split(/ |\n/, $line);
1167 push(@commit_pairs, \@commit_info_split);
1171 foreach my $commit_info_split (@commit_pairs) {
1172 my $sha1_child = @{$commit_info_split}[0];
1173 my $sha1_commit = @{$commit_info_split}[1];
1174 my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
1175 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1176 # TODO: for now, it's just a delete+add
1177 my @diff_info_list = split(/\0/, $diff_infos);
1178 # Keep the subject line of the commit message as mediawiki comment for the revision
1179 my $commit_msg = run_git("log --no-walk --format=\"%s\" $sha1_commit");
1182 while (@diff_info_list) {
1184 # git diff-tree -z gives an output like
1185 # <metadata>\0<filename1>\0
1186 # <metadata>\0<filename2>\0
1187 # and we've split on \0.
1188 my $info = shift(@diff_info_list);
1189 my $file = shift(@diff_info_list);
1190 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1191 if ($status eq "non-fast-forward") {
1192 # we may already have sent part of the
1193 # commit to MediaWiki, but it's too
1194 # late to cancel it. Stop the push in
1195 # the middle, but still give an
1196 # accurate error message.
1197 return error_non_fast_forward($remote);
1199 if ($status ne "ok") {
1200 die("Unknown error from mw_push_file()");
1203 unless ($dumb_push) {
1204 run_git("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1205 run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1209 print STDOUT "ok $remote\n";
1213 sub get_allowed_file_extensions {
1219 siprop => 'fileextensions'
1221 my $result = $mediawiki->api($query);
1222 my @file_extensions= map $_->{ext},@{$result->{query}->{fileextensions}};
1223 my %hashFile = map {$_ => 1}@file_extensions;
1228 # In memory cache for MediaWiki namespace ids.
1231 # Namespaces whose id is cached in the configuration file
1232 # (to avoid duplicates)
1233 my %cached_mw_namespace_id;
1235 # Return MediaWiki id for a canonical namespace name.
1236 # Ex.: "File", "Project".
1237 sub get_mw_namespace_id {
1241 if (!exists $namespace_id{$name}) {
1242 # Look at configuration file, if the record for that namespace is
1243 # already cached. Namespaces are stored in form:
1244 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1245 my @temp = split(/[\n]/, run_git("config --get-all remote."
1246 . $remotename .".namespaceCache"));
1248 foreach my $ns (@temp) {
1249 my ($n, $id) = split(/:/, $ns);
1250 if ($id eq 'notANameSpace') {
1251 $namespace_id{$n} = {is_namespace => 0};
1253 $namespace_id{$n} = {is_namespace => 1, id => $id};
1255 $cached_mw_namespace_id{$n} = 1;
1259 if (!exists $namespace_id{$name}) {
1260 print STDERR "Namespace $name not found in cache, querying the wiki ...\n";
1261 # NS not found => get namespace id from MW and store it in
1262 # configuration file.
1266 siprop => 'namespaces'
1268 my $result = $mediawiki->api($query);
1270 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1271 if (defined($ns->{id}) && defined($ns->{canonical})) {
1272 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1274 # alias (e.g. french Fichier: as alias for canonical File:)
1275 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1281 my $ns = $namespace_id{$name};
1284 unless (defined $ns) {
1285 print STDERR "No such namespace $name on MediaWiki.\n";
1286 $ns = {is_namespace => 0};
1287 $namespace_id{$name} = $ns;
1290 if ($ns->{is_namespace}) {
1294 # Store "notANameSpace" as special value for inexisting namespaces
1295 my $store_id = ($id || 'notANameSpace');
1297 # Store explicitely requested namespaces on disk
1298 if (!exists $cached_mw_namespace_id{$name}) {
1299 run_git("config --add remote.". $remotename
1300 .".namespaceCache \"". $name .":". $store_id ."\"");
1301 $cached_mw_namespace_id{$name} = 1;
1306 sub get_mw_namespace_id_for_page {
1307 if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1308 return get_mw_namespace_id($namespace);