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/
16 use DateTime
::Format
::ISO8601
;
18 # By default, use UTF-8 to communicate with Git and the user
19 binmode STDERR
, ":utf8";
20 binmode STDOUT
, ":utf8";
27 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
28 use constant SLASH_REPLACEMENT
=> "%2F";
30 # It's not always possible to delete pages (may require some
31 # privileges). Deleted pages are replaced with this content.
32 use constant DELETED_CONTENT
=> "[[Category:Deleted]]\n";
34 # It's not possible to create empty pages. New empty files in Git are
35 # sent with this content instead.
36 use constant EMPTY_CONTENT
=> "<!-- empty page -->\n";
38 # used to reflect file creation or deletion in diff.
39 use constant NULL_SHA1
=> "0000000000000000000000000000000000000000";
41 # Used on Git's side to reflect empty edit messages on the wiki
42 use constant EMPTY_MESSAGE
=> '*Empty MediaWiki Message*';
48 my $remotename = $ARGV[0];
51 # Accept both space-separated and multiple keys in config file.
52 # Spaces should be written as _ anyway because we'll use chomp.
53 my @tracked_pages = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".pages"));
54 chomp(@tracked_pages);
56 # Just like @tracked_pages, but for MediaWiki categories.
57 my @tracked_categories = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".categories"));
58 chomp(@tracked_categories);
60 # Import media files on pull
61 my $import_media = run_git
("config --get --bool remote.". $remotename .".mediaimport");
63 $import_media = ($import_media eq "true");
65 # Export media files on push
66 my $export_media = run_git
("config --get --bool remote.". $remotename .".mediaexport");
68 $export_media = !($export_media eq "false");
70 my $wiki_login = run_git
("config --get remote.". $remotename .".mwLogin");
71 # Note: mwPassword is discourraged. Use the credential system instead.
72 my $wiki_passwd = run_git
("config --get remote.". $remotename .".mwPassword");
73 my $wiki_domain = run_git
("config --get remote.". $remotename .".mwDomain");
78 # Import only last revisions (both for clone and fetch)
79 my $shallow_import = run_git
("config --get --bool remote.". $remotename .".shallow");
80 chomp($shallow_import);
81 $shallow_import = ($shallow_import eq "true");
83 # Fetch (clone and pull) by revisions instead of by pages. This behavior
84 # is more efficient when we have a wiki with lots of pages and we fetch
85 # the revisions quite often so that they concern only few pages.
87 # - by_rev: perform one query per new revision on the remote wiki
88 # - by_page: query each tracked page for new revision
89 my $fetch_strategy = run_git
("config --get remote.$remotename.fetchStrategy");
90 unless ($fetch_strategy) {
91 $fetch_strategy = run_git
("config --get mediawiki.fetchStrategy");
93 chomp($fetch_strategy);
94 unless ($fetch_strategy) {
95 $fetch_strategy = "by_page";
98 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
100 # Configurable with mediawiki.dumbPush, or per-remote with
101 # remote.<remotename>.dumbPush.
103 # This means the user will have to re-import the just-pushed
104 # revisions. On the other hand, this means that the Git revisions
105 # corresponding to MediaWiki revisions are all imported from the wiki,
106 # regardless of whether they were initially created in Git or from the
107 # web interface, hence all users will get the same history (i.e. if
108 # the push from Git to MediaWiki loses some information, everybody
109 # will get the history with information lost). If the import is
110 # deterministic, this means everybody gets the same sha1 for each
111 # MediaWiki revision.
112 my $dumb_push = run_git
("config --get --bool remote.$remotename.dumbPush");
113 unless ($dumb_push) {
114 $dumb_push = run_git
("config --get --bool mediawiki.dumbPush");
117 $dumb_push = ($dumb_push eq "true");
119 my $wiki_name = $url;
120 $wiki_name =~ s/[^\/]*:\/\
///;
121 # If URL is like http://user:password@example.com/, we clearly don't
122 # want the password in $wiki_name. While we're there, also remove user
123 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
124 $wiki_name =~ s/^.*@//;
132 if (defined($cmd[0])) {
134 if ($cmd[0] eq "capabilities") {
135 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
137 } elsif ($cmd[0] eq "list") {
138 die("Too many arguments for list") unless (!defined($cmd[2]));
140 } elsif ($cmd[0] eq "import") {
141 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
143 } elsif ($cmd[0] eq "option") {
144 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
145 mw_option
($cmd[1],$cmd[2]);
146 } elsif ($cmd[0] eq "push") {
149 print STDERR
"Unknown command. Aborting...\n";
153 # blank line: we should terminate
157 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
158 # command is fully processed.
161 ########################## Functions ##############################
164 sub exit_error_usage
{
165 die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
167 "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
168 "module directly.\n" .
169 "This module can be used the following way:\n" .
170 "\tgit clone mediawiki://<address of a mediawiki>\n" .
171 "Then, use git commit, push and pull as with every normal git repository.\n";
174 ## credential API management (generic functions)
176 sub credential_read
{
181 my ($key, $value) = /([^=]*)=(.*)/;
182 if (not defined $key) {
183 die "ERROR receiving response from git credential $op:\n$_\n";
185 $credential{$key} = $value;
190 sub credential_write
{
191 my $credential = shift;
193 # url overwrites other fields, so it must come first
194 print $writer "url=$credential->{url}\n" if exists $credential->{url
};
195 while (my ($key, $value) = each(%$credential) ) {
196 if (length $value && $key ne 'url') {
197 print $writer "$key=$value\n";
204 my $credential = shift;
205 my $pid = open2
(my $reader, my $writer, "git credential $op");
206 credential_write
($credential, $writer);
211 %$credential = credential_read
($reader, $op);
214 die "ERROR while running git credential $op:\n$_";
219 my $child_exit_status = $?
>> 8;
220 if ($child_exit_status != 0) {
221 die "'git credential $op' failed with code $child_exit_status.";
225 # MediaWiki API instance, created lazily.
228 sub mw_connect_maybe
{
232 $mediawiki = MediaWiki
::API
->new;
233 $mediawiki->{config
}->{api_url
} = "$url/api.php";
235 my %credential = (url
=> $url);
236 $credential{username
} = $wiki_login;
237 $credential{password
} = $wiki_passwd;
238 credential_run
("fill", \
%credential);
239 my $request = {lgname
=> $credential{username
},
240 lgpassword
=> $credential{password
},
241 lgdomain
=> $wiki_domain};
242 if ($mediawiki->login($request)) {
243 credential_run
("approve", \
%credential);
244 print STDERR
"Logged in mediawiki user \"$credential{username}\".\n";
246 print STDERR
"Failed to log in mediawiki user \"$credential{username}\" on $url\n";
247 print STDERR
" (error " .
248 $mediawiki->{error
}->{code
} . ': ' .
249 $mediawiki->{error
}->{details
} . ")\n";
250 credential_run
("reject", \
%credential);
256 ## Functions for listing pages on the remote wiki
257 sub get_mw_tracked_pages
{
259 get_mw_page_list
(\
@tracked_pages, $pages);
262 sub get_mw_page_list
{
263 my $page_list = shift;
265 my @some_pages = @
$page_list;
266 while (@some_pages) {
268 if ($#some_pages < $last) {
269 $last = $#some_pages;
271 my @slice = @some_pages[0..$last];
272 get_mw_first_pages
(\
@slice, $pages);
273 @some_pages = @some_pages[51..$#some_pages];
277 sub get_mw_tracked_categories
{
279 foreach my $category (@tracked_categories) {
280 if (index($category, ':') < 0) {
281 # Mediawiki requires the Category
282 # prefix, but let's not force the user
284 $category = "Category:" . $category;
286 my $mw_pages = $mediawiki->list( {
288 list
=> 'categorymembers',
289 cmtitle
=> $category,
291 || die $mediawiki->{error
}->{code
} . ': '
292 . $mediawiki->{error
}->{details
};
293 foreach my $page (@
{$mw_pages}) {
294 $pages->{$page->{title
}} = $page;
299 sub get_mw_all_pages
{
301 # No user-provided list, get the list of pages from the API.
302 my $mw_pages = $mediawiki->list({
307 if (!defined($mw_pages)) {
308 print STDERR
"fatal: could not get the list of wiki pages.\n";
309 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
310 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
313 foreach my $page (@
{$mw_pages}) {
314 $pages->{$page->{title
}} = $page;
318 # queries the wiki for a set of pages. Meant to be used within a loop
319 # querying the wiki for slices of page list.
320 sub get_mw_first_pages
{
321 my $some_pages = shift;
322 my @some_pages = @
{$some_pages};
326 # pattern 'page1|page2|...' required by the API
327 my $titles = join('|', @some_pages);
329 my $mw_pages = $mediawiki->api({
333 if (!defined($mw_pages)) {
334 print STDERR
"fatal: could not query the list of wiki pages.\n";
335 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
336 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
339 while (my ($id, $page) = each(%{$mw_pages->{query
}->{pages
}})) {
341 print STDERR
"Warning: page $page->{title} not found on wiki\n";
343 $pages->{$page->{title
}} = $page;
348 # Get the list of pages to be fetched according to configuration.
352 print STDERR
"Listing pages on remote wiki...\n";
354 my %pages; # hash on page titles to avoid duplicates
356 if (@tracked_pages) {
358 # The user provided a list of pages titles, but we
359 # still need to query the API to get the page IDs.
360 get_mw_tracked_pages
(\
%pages);
362 if (@tracked_categories) {
364 get_mw_tracked_categories
(\
%pages);
366 if (!$user_defined) {
367 get_mw_all_pages
(\
%pages);
370 print STDERR
"Getting media files for selected pages...\n";
372 get_linked_mediafiles
(\
%pages);
374 get_all_mediafiles
(\
%pages);
377 print STDERR
(scalar keys %pages) . " pages found.\n";
381 # usage: $out = run_git("command args");
382 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
385 my $encoding = (shift || "encoding(UTF-8)");
386 open(my $git, "-|:$encoding", "git " . $args);
387 my $res = do { local $/; <$git> };
394 sub get_all_mediafiles
{
396 # Attach list of all pages for media files from the API,
397 # they are in a different namespace, only one namespace
398 # can be queried at the same moment
399 my $mw_pages = $mediawiki->list({
402 apnamespace
=> get_mw_namespace_id
("File"),
405 if (!defined($mw_pages)) {
406 print STDERR
"fatal: could not get the list of pages for media files.\n";
407 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
408 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
411 foreach my $page (@
{$mw_pages}) {
412 $pages->{$page->{title
}} = $page;
416 sub get_linked_mediafiles
{
418 my @titles = map $_->{title
}, values(%{$pages});
420 # The query is split in small batches because of the MW API limit of
421 # the number of links to be returned (500 links max).
424 if ($#titles < $batch) {
427 my @slice = @titles[0..$batch];
429 # pattern 'page1|page2|...' required by the API
430 my $mw_titles = join('|', @slice);
432 # Media files could be included or linked from
433 # a page, get all related
436 prop
=> 'links|images',
437 titles
=> $mw_titles,
438 plnamespace
=> get_mw_namespace_id
("File"),
441 my $result = $mediawiki->api($query);
443 while (my ($id, $page) = each(%{$result->{query
}->{pages
}})) {
445 if (defined($page->{links
})) {
446 my @link_titles = map $_->{title
}, @
{$page->{links
}};
447 push(@media_titles, @link_titles);
449 if (defined($page->{images
})) {
450 my @image_titles = map $_->{title
}, @
{$page->{images
}};
451 push(@media_titles, @image_titles);
454 get_mw_page_list
(\
@media_titles, $pages);
458 @titles = @titles[($batch+1)..$#titles];
462 sub get_mw_mediafile_for_page_revision
{
463 # Name of the file on Wiki, with the prefix.
464 my $filename = shift;
465 my $timestamp = shift;
468 # Search if on a media file with given timestamp exists on
469 # MediaWiki. In that case download the file.
473 titles
=> "File:" . $filename,
474 iistart
=> $timestamp,
476 iiprop
=> 'timestamp|archivename|url',
479 my $result = $mediawiki->api($query);
481 my ($fileid, $file) = each( %{$result->{query
}->{pages
}} );
482 # If not defined it means there is no revision of the file for
484 if (defined($file->{imageinfo
})) {
485 $mediafile{title
} = $filename;
487 my $fileinfo = pop(@
{$file->{imageinfo
}});
488 $mediafile{timestamp
} = $fileinfo->{timestamp
};
489 # Mediawiki::API's download function doesn't support https URLs
490 # and can't download old versions of files.
491 print STDERR
"\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
492 $mediafile{content
} = download_mw_mediafile
($fileinfo->{url
});
497 sub download_mw_mediafile
{
500 my $response = $mediawiki->{ua
}->get($url);
501 if ($response->code == 200) {
502 return $response->decoded_content;
504 print STDERR
"Error downloading mediafile from :\n";
505 print STDERR
"URL: $url\n";
506 print STDERR
"Server response: " . $response->code . " " . $response->message . "\n";
511 sub get_last_local_revision
{
512 # Get note regarding last mediawiki revision
513 my $note = run_git
("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
514 my @note_info = split(/ /, $note);
516 my $lastrevision_number;
517 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
518 print STDERR
"No previous mediawiki revision found";
519 $lastrevision_number = 0;
521 # Notes are formatted : mediawiki_revision: #number
522 $lastrevision_number = $note_info[1];
523 chomp($lastrevision_number);
524 print STDERR
"Last local mediawiki revision found is $lastrevision_number";
526 return $lastrevision_number;
529 # Remember the timestamp corresponding to a revision id.
532 # Get the last remote revision without taking in account which pages are
533 # tracked or not. This function makes a single request to the wiki thus
534 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
536 sub get_last_global_remote_rev
{
541 list
=> 'recentchanges',
546 my $result = $mediawiki->api($query);
547 return $result->{query
}->{recentchanges
}[0]->{revid
};
550 # Get the last remote revision concerning the tracked pages and the tracked
552 sub get_last_remote_revision
{
555 my %pages_hash = get_mw_pages
();
556 my @pages = values(%pages_hash);
560 print STDERR
"Getting last revision id on tracked pages...\n";
562 foreach my $page (@pages) {
563 my $id = $page->{pageid
};
568 rvprop
=> 'ids|timestamp',
572 my $result = $mediawiki->api($query);
574 my $lastrev = pop(@
{$result->{query
}->{pages
}->{$id}->{revisions
}});
576 $basetimestamps{$lastrev->{revid
}} = $lastrev->{timestamp
};
578 $max_rev_num = ($lastrev->{revid
} > $max_rev_num ?
$lastrev->{revid
} : $max_rev_num);
581 print STDERR
"Last remote revision found is $max_rev_num.\n";
585 # Clean content before sending it to MediaWiki
586 sub mediawiki_clean
{
588 my $page_created = shift;
589 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
590 # This function right trims a string and adds a \n at the end to follow this rule
592 if ($string eq "" && $page_created) {
593 # Creating empty pages is forbidden.
594 $string = EMPTY_CONTENT
;
599 # Filter applied on MediaWiki data before adding them to Git
600 sub mediawiki_smudge
{
602 if ($string eq EMPTY_CONTENT
) {
605 # This \n is important. This is due to mediawiki's way to handle end of files.
609 sub mediawiki_clean_filename
{
610 my $filename = shift;
611 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g
;
612 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
613 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
614 # but with _ added to prevent MediaWiki from thinking this is
615 # an actual special character.
616 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
617 # If we use the uri escape before
618 # we should unescape here, before anything
623 sub mediawiki_smudge_filename
{
624 my $filename = shift;
625 $filename =~ s/\//@
{[SLASH_REPLACEMENT
]}/g
;
626 $filename =~ s/ /_/g;
627 # Decode forbidden characters encoded in mediawiki_clean_filename
628 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
634 print STDOUT
"data ", bytes
::length($content), "\n", $content;
637 sub literal_data_raw
{
638 # Output possibly binary content.
640 # Avoid confusion between size in bytes and in characters
641 utf8
::downgrade
($content);
642 binmode STDOUT
, ":raw";
643 print STDOUT
"data ", bytes
::length($content), "\n", $content;
644 binmode STDOUT
, ":utf8";
647 sub mw_capabilities
{
648 # Revisions are imported to the private namespace
649 # refs/mediawiki/$remotename/ by the helper and fetched into
650 # refs/remotes/$remotename later by fetch.
651 print STDOUT
"refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
652 print STDOUT
"import\n";
653 print STDOUT
"list\n";
654 print STDOUT
"push\n";
659 # MediaWiki do not have branches, we consider one branch arbitrarily
660 # called master, and HEAD pointing to it.
661 print STDOUT
"? refs/heads/master\n";
662 print STDOUT
"\@refs/heads/master HEAD\n";
667 print STDERR
"remote-helper command 'option $_[0]' not yet implemented\n";
668 print STDOUT
"unsupported\n";
671 sub fetch_mw_revisions_for_page
{
674 my $fetch_from = shift;
681 rvstartid
=> $fetch_from,
687 # Get 500 revisions at a time due to the mediawiki api limit
689 my $result = $mediawiki->api($query);
691 # Parse each of those 500 revisions
692 foreach my $revision (@
{$result->{query
}->{pages
}->{$id}->{revisions
}}) {
694 $page_rev_ids->{pageid
} = $page->{pageid
};
695 $page_rev_ids->{revid
} = $revision->{revid
};
696 push(@page_revs, $page_rev_ids);
699 last unless $result->{'query-continue'};
700 $query->{rvstartid
} = $result->{'query-continue'}->{revisions
}->{rvstartid
};
702 if ($shallow_import && @page_revs) {
703 print STDERR
" Found 1 revision (shallow import).\n";
704 @page_revs = sort {$b->{revid
} <=> $a->{revid
}} (@page_revs);
705 return $page_revs[0];
707 print STDERR
" Found ", $revnum, " revision(s).\n";
711 sub fetch_mw_revisions
{
712 my $pages = shift; my @pages = @
{$pages};
713 my $fetch_from = shift;
717 foreach my $page (@pages) {
718 my $id = $page->{pageid
};
720 print STDERR
"page $n/", scalar(@pages), ": ". $page->{title
} ."\n";
722 my @page_revs = fetch_mw_revisions_for_page
($page, $id, $fetch_from);
723 @revisions = (@page_revs, @revisions);
726 return ($n, @revisions);
731 $path =~ s/\\/\\\\/g;
734 return '"' . $path . '"';
737 sub import_file_revision
{
739 my %commit = %{$commit};
740 my $full_import = shift;
742 my $mediafile = shift;
745 %mediafile = %{$mediafile};
748 my $title = $commit{title
};
749 my $comment = $commit{comment
};
750 my $content = $commit{content
};
751 my $author = $commit{author
};
752 my $date = $commit{date
};
754 print STDOUT
"commit refs/mediawiki/$remotename/master\n";
755 print STDOUT
"mark :$n\n";
756 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
757 literal_data
($comment);
759 # If it's not a clone, we need to know where to start from
760 if (!$full_import && $n == 1) {
761 print STDOUT
"from refs/mediawiki/$remotename/master^0\n";
763 if ($content ne DELETED_CONTENT
) {
764 print STDOUT
"M 644 inline " .
765 fe_escape_path
($title . ".mw") . "\n";
766 literal_data
($content);
768 print STDOUT
"M 644 inline "
769 . fe_escape_path
($mediafile{title
}) . "\n";
770 literal_data_raw
($mediafile{content
});
774 print STDOUT
"D " . fe_escape_path
($title . ".mw") . "\n";
777 # mediawiki revision number in the git note
778 if ($full_import && $n == 1) {
779 print STDOUT
"reset refs/notes/$remotename/mediawiki\n";
781 print STDOUT
"commit refs/notes/$remotename/mediawiki\n";
782 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
783 literal_data
("Note added by git-mediawiki during import");
784 if (!$full_import && $n == 1) {
785 print STDOUT
"from refs/notes/$remotename/mediawiki^0\n";
787 print STDOUT
"N inline :$n\n";
788 literal_data
("mediawiki_revision: " . $commit{mw_revision
});
792 # parse a sequence of
796 # (like batch sequence of import and sequence of push statements)
802 if ($line =~ m/^$cmd (.*)$/) {
804 } elsif ($line eq "\n") {
807 die("Invalid command in a '$cmd' batch: ". $_);
813 # multiple import commands can follow each other.
814 my @refs = (shift, get_more_refs
("import"));
815 foreach my $ref (@refs) {
818 print STDOUT
"done\n";
823 # The remote helper will call "import HEAD" and
824 # "import refs/heads/master".
825 # Since HEAD is a symbolic ref to master (by convention,
826 # followed by the output of the command "list" that we gave),
827 # we don't need to do anything in this case.
828 if ($ref eq "HEAD") {
834 print STDERR
"Searching revisions...\n";
835 my $last_local = get_last_local_revision
();
836 my $fetch_from = $last_local + 1;
837 if ($fetch_from == 1) {
838 print STDERR
", fetching from beginning.\n";
840 print STDERR
", fetching from here.\n";
844 if ($fetch_strategy eq "by_rev") {
845 print STDERR
"Fetching & writing export data by revs...\n";
846 $n = mw_import_ref_by_revs
($fetch_from);
847 } elsif ($fetch_strategy eq "by_page") {
848 print STDERR
"Fetching & writing export data by pages...\n";
849 $n = mw_import_ref_by_pages
($fetch_from);
851 print STDERR
"fatal: invalid fetch strategy \"$fetch_strategy\".\n";
852 print STDERR
"Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
856 if ($fetch_from == 1 && $n == 0) {
857 print STDERR
"You appear to have cloned an empty MediaWiki.\n";
858 # Something has to be done remote-helper side. If nothing is done, an error is
859 # thrown saying that HEAD is referring to unknown object 0000000000000000000
860 # and the clone fails.
864 sub mw_import_ref_by_pages
{
866 my $fetch_from = shift;
867 my %pages_hash = get_mw_pages
();
868 my @pages = values(%pages_hash);
870 my ($n, @revisions) = fetch_mw_revisions
(\
@pages, $fetch_from);
872 @revisions = sort {$a->{revid
} <=> $b->{revid
}} @revisions;
873 my @revision_ids = map $_->{revid
}, @revisions;
875 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
878 sub mw_import_ref_by_revs
{
880 my $fetch_from = shift;
881 my %pages_hash = get_mw_pages
();
883 my $last_remote = get_last_global_remote_rev
();
884 my @revision_ids = $fetch_from..$last_remote;
885 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
888 # Import revisions given in second argument (array of integers).
889 # Only pages appearing in the third argument (hash indexed by page titles)
891 sub mw_import_revids
{
892 my $fetch_from = shift;
893 my $revision_ids = shift;
898 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
900 foreach my $pagerevid (@
$revision_ids) {
901 # Count page even if we skip it, since we display
902 # $n/$total and $total includes skipped pages.
905 # fetch the content of the pages
909 rvprop
=> 'content|timestamp|comment|user|ids',
910 revids
=> $pagerevid,
913 my $result = $mediawiki->api($query);
916 die "Failed to retrieve modified page for revision $pagerevid";
919 if (defined($result->{query
}->{badrevids
}->{$pagerevid})) {
920 # The revision id does not exist on the remote wiki.
924 if (!defined($result->{query
}->{pages
})) {
925 die "Invalid revision $pagerevid.";
928 my @result_pages = values(%{$result->{query
}->{pages
}});
929 my $result_page = $result_pages[0];
930 my $rev = $result_pages[0]->{revisions
}->[0];
932 my $page_title = $result_page->{title
};
934 if (!exists($pages->{$page_title})) {
935 print STDERR
"$n/", scalar(@
$revision_ids),
936 ": Skipping revision #$rev->{revid} of $page_title\n";
943 $commit{author
} = $rev->{user
} || 'Anonymous';
944 $commit{comment
} = $rev->{comment
} || EMPTY_MESSAGE
;
945 $commit{title
} = mediawiki_smudge_filename
($page_title);
946 $commit{mw_revision
} = $rev->{revid
};
947 $commit{content
} = mediawiki_smudge
($rev->{'*'});
949 if (!defined($rev->{timestamp
})) {
952 $last_timestamp = $rev->{timestamp
};
954 $commit{date
} = DateTime
::Format
::ISO8601
->parse_datetime($last_timestamp);
956 # Differentiates classic pages and media files.
957 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
960 my $id = get_mw_namespace_id
($namespace);
961 if ($id && $id == get_mw_namespace_id
("File")) {
962 %mediafile = get_mw_mediafile_for_page_revision
($filename, $rev->{timestamp
});
965 # If this is a revision of the media page for new version
966 # of a file do one common commit for both file and media page.
967 # Else do commit only for that page.
968 print STDERR
"$n/", scalar(@
$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
969 import_file_revision
(\
%commit, ($fetch_from == 1), $n_actual, \
%mediafile);
975 sub error_non_fast_forward
{
976 my $advice = run_git
("config --bool advice.pushNonFastForward");
978 if ($advice ne "false") {
979 # Native git-push would show this after the summary.
980 # We can't ask it to display it cleanly, so print it
982 print STDERR
"To prevent you from losing history, non-fast-forward updates were rejected\n";
983 print STDERR
"Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
984 print STDERR
"'Note about fast-forwards' section of 'git push --help' for details.\n";
986 print STDOUT
"error $_[0] \"non-fast-forward\"\n";
991 my $complete_file_name = shift;
992 my $new_sha1 = shift;
993 my $extension = shift;
994 my $file_deleted = shift;
997 my $path = "File:" . $complete_file_name;
998 my %hashFiles = get_allowed_file_extensions
();
999 if (!exists($hashFiles{$extension})) {
1000 print STDERR
"$complete_file_name is not a permitted file on this wiki.\n";
1001 print STDERR
"Check the configuration of file uploads in your mediawiki.\n";
1004 # Deleting and uploading a file requires a priviledged user
1005 if ($file_deleted) {
1012 if (!$mediawiki->edit($query)) {
1013 print STDERR
"Failed to delete file on remote wiki\n";
1014 print STDERR
"Check your permissions on the remote site. Error code:\n";
1015 print STDERR
$mediawiki->{error
}->{code
} . ':' . $mediawiki->{error
}->{details
};
1019 # Don't let perl try to interpret file content as UTF-8 => use "raw"
1020 my $content = run_git
("cat-file blob $new_sha1", "raw");
1021 if ($content ne "") {
1023 $mediawiki->{config
}->{upload_url
} =
1024 "$url/index.php/Special:Upload";
1027 filename
=> $complete_file_name,
1028 comment
=> $summary,
1030 $complete_file_name,
1031 Content
=> $content],
1032 ignorewarnings
=> 1,
1035 } ) || die $mediawiki->{error
}->{code
} . ':'
1036 . $mediawiki->{error
}->{details
};
1037 my $last_file_page = $mediawiki->get_page({title
=> $path});
1038 $newrevid = $last_file_page->{revid
};
1039 print STDERR
"Pushed file: $new_sha1 - $complete_file_name.\n";
1041 print STDERR
"Empty file $complete_file_name not pushed.\n";
1048 my $diff_info = shift;
1049 # $diff_info contains a string in this format:
1050 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1051 my @diff_info_split = split(/[ \t]/, $diff_info);
1053 # Filename, including .mw extension
1054 my $complete_file_name = shift;
1056 my $summary = shift;
1057 # MediaWiki revision number. Keep the previous one by default,
1058 # in case there's no edit to perform.
1059 my $oldrevid = shift;
1062 if ($summary eq EMPTY_MESSAGE
) {
1066 my $new_sha1 = $diff_info_split[3];
1067 my $old_sha1 = $diff_info_split[2];
1068 my $page_created = ($old_sha1 eq NULL_SHA1
);
1069 my $page_deleted = ($new_sha1 eq NULL_SHA1
);
1070 $complete_file_name = mediawiki_clean_filename
($complete_file_name);
1072 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1073 if (!defined($extension)) {
1076 if ($extension eq "mw") {
1077 my $ns = get_mw_namespace_id_for_page
($complete_file_name);
1078 if ($ns && $ns == get_mw_namespace_id
("File") && (!$export_media)) {
1079 print STDERR
"Ignoring media file related page: $complete_file_name\n";
1080 return ($oldrevid, "ok");
1083 if ($page_deleted) {
1084 # Deleting a page usually requires
1085 # special privileges. A common
1086 # convention is to replace the page
1087 # with this content instead:
1088 $file_content = DELETED_CONTENT
;
1090 $file_content = run_git
("cat-file blob $new_sha1");
1095 my $result = $mediawiki->edit( {
1097 summary
=> $summary,
1099 basetimestamp
=> $basetimestamps{$oldrevid},
1100 text
=> mediawiki_clean
($file_content, $page_created),
1102 skip_encoding
=> 1 # Helps with names with accentuated characters
1105 if ($mediawiki->{error
}->{code
} == 3) {
1106 # edit conflicts, considered as non-fast-forward
1107 print STDERR
'Warning: Error ' .
1108 $mediawiki->{error
}->{code
} .
1109 ' from mediwiki: ' . $mediawiki->{error
}->{details
} .
1111 return ($oldrevid, "non-fast-forward");
1113 # Other errors. Shouldn't happen => just die()
1114 die 'Fatal: Error ' .
1115 $mediawiki->{error
}->{code
} .
1116 ' from mediwiki: ' . $mediawiki->{error
}->{details
};
1119 $newrevid = $result->{edit
}->{newrevid
};
1120 print STDERR
"Pushed file: $new_sha1 - $title\n";
1121 } elsif ($export_media) {
1122 $newrevid = mw_upload_file
($complete_file_name, $new_sha1,
1123 $extension, $page_deleted,
1126 print STDERR
"Ignoring media file $title\n";
1128 $newrevid = ($newrevid or $oldrevid);
1129 return ($newrevid, "ok");
1133 # multiple push statements can follow each other
1134 my @refsspecs = (shift, get_more_refs
("push"));
1136 for my $refspec (@refsspecs) {
1137 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1138 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1140 print STDERR
"Warning: forced push not allowed on a MediaWiki.\n";
1143 print STDERR
"Cannot delete remote branch on a MediaWiki\n";
1144 print STDOUT
"error $remote cannot delete\n";
1147 if ($remote ne "refs/heads/master") {
1148 print STDERR
"Only push to the branch 'master' is supported on a MediaWiki\n";
1149 print STDOUT
"error $remote only master allowed\n";
1152 if (mw_push_revision
($local, $remote)) {
1157 # Notify Git that the push is done
1160 if ($pushed && $dumb_push) {
1161 print STDERR
"Just pushed some revisions to MediaWiki.\n";
1162 print STDERR
"The pushed revisions now have to be re-imported, and your current branch\n";
1163 print STDERR
"needs to be updated with these re-imported commits. You can do this with\n";
1165 print STDERR
" git pull --rebase\n";
1170 sub mw_push_revision
{
1172 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1173 my $last_local_revid = get_last_local_revision
();
1174 print STDERR
".\n"; # Finish sentence started by get_last_local_revision()
1175 my $last_remote_revid = get_last_remote_revision
();
1176 my $mw_revision = $last_remote_revid;
1178 # Get sha1 of commit pointed by local HEAD
1179 my $HEAD_sha1 = run_git
("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1180 # Get sha1 of commit pointed by remotes/$remotename/master
1181 my $remoteorigin_sha1 = run_git
("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1182 chomp($remoteorigin_sha1);
1184 if ($last_local_revid > 0 &&
1185 $last_local_revid < $last_remote_revid) {
1186 return error_non_fast_forward
($remote);
1189 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1194 # Get every commit in between HEAD and refs/remotes/origin/master,
1195 # including HEAD and refs/remotes/origin/master
1196 my @commit_pairs = ();
1197 if ($last_local_revid > 0) {
1198 my $parsed_sha1 = $remoteorigin_sha1;
1199 # Find a path from last MediaWiki commit to pushed commit
1200 print STDERR
"Computing path from local to remote ...\n";
1201 my @local_ancestry = split(/\n/, run_git
("rev-list --boundary --parents $local ^$parsed_sha1"));
1203 foreach my $line (@local_ancestry) {
1204 if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1205 foreach my $parent (split(' ', $parents)) {
1206 $local_ancestry{$parent} = $child;
1208 } elsif (!$line =~ m/^([a-f0-9]+)/) {
1209 die "Unexpected output from git rev-list: $line";
1212 while ($parsed_sha1 ne $HEAD_sha1) {
1213 my $child = $local_ancestry{$parsed_sha1};
1215 printf STDERR
"Cannot find a path in history from remote commit to last commit\n";
1216 return error_non_fast_forward
($remote);
1218 push(@commit_pairs, [$parsed_sha1, $child]);
1219 $parsed_sha1 = $child;
1222 # No remote mediawiki revision. Export the whole
1223 # history (linearized with --first-parent)
1224 print STDERR
"Warning: no common ancestor, pushing complete history\n";
1225 my $history = run_git
("rev-list --first-parent --children $local");
1226 my @history = split('\n', $history);
1227 @history = @history[1..$#history];
1228 foreach my $line (reverse @history) {
1229 my @commit_info_split = split(/ |\n/, $line);
1230 push(@commit_pairs, \
@commit_info_split);
1234 foreach my $commit_info_split (@commit_pairs) {
1235 my $sha1_child = @
{$commit_info_split}[0];
1236 my $sha1_commit = @
{$commit_info_split}[1];
1237 my $diff_infos = run_git
("diff-tree -r --raw -z $sha1_child $sha1_commit");
1238 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1239 # TODO: for now, it's just a delete+add
1240 my @diff_info_list = split(/\0/, $diff_infos);
1241 # Keep the subject line of the commit message as mediawiki comment for the revision
1242 my $commit_msg = run_git
("log --no-walk --format=\"%s\" $sha1_commit");
1245 while (@diff_info_list) {
1247 # git diff-tree -z gives an output like
1248 # <metadata>\0<filename1>\0
1249 # <metadata>\0<filename2>\0
1250 # and we've split on \0.
1251 my $info = shift(@diff_info_list);
1252 my $file = shift(@diff_info_list);
1253 ($mw_revision, $status) = mw_push_file
($info, $file, $commit_msg, $mw_revision);
1254 if ($status eq "non-fast-forward") {
1255 # we may already have sent part of the
1256 # commit to MediaWiki, but it's too
1257 # late to cancel it. Stop the push in
1258 # the middle, but still give an
1259 # accurate error message.
1260 return error_non_fast_forward
($remote);
1262 if ($status ne "ok") {
1263 die("Unknown error from mw_push_file()");
1266 unless ($dumb_push) {
1267 run_git
("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1268 run_git
("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1272 print STDOUT
"ok $remote\n";
1276 sub get_allowed_file_extensions
{
1282 siprop
=> 'fileextensions'
1284 my $result = $mediawiki->api($query);
1285 my @file_extensions= map $_->{ext
},@
{$result->{query
}->{fileextensions
}};
1286 my %hashFile = map {$_ => 1}@file_extensions;
1291 # In memory cache for MediaWiki namespace ids.
1294 # Namespaces whose id is cached in the configuration file
1295 # (to avoid duplicates)
1296 my %cached_mw_namespace_id;
1298 # Return MediaWiki id for a canonical namespace name.
1299 # Ex.: "File", "Project".
1300 sub get_mw_namespace_id
{
1304 if (!exists $namespace_id{$name}) {
1305 # Look at configuration file, if the record for that namespace is
1306 # already cached. Namespaces are stored in form:
1307 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1308 my @temp = split(/[\n]/, run_git
("config --get-all remote."
1309 . $remotename .".namespaceCache"));
1311 foreach my $ns (@temp) {
1312 my ($n, $id) = split(/:/, $ns);
1313 if ($id eq 'notANameSpace') {
1314 $namespace_id{$n} = {is_namespace
=> 0};
1316 $namespace_id{$n} = {is_namespace
=> 1, id
=> $id};
1318 $cached_mw_namespace_id{$n} = 1;
1322 if (!exists $namespace_id{$name}) {
1323 print STDERR
"Namespace $name not found in cache, querying the wiki ...\n";
1324 # NS not found => get namespace id from MW and store it in
1325 # configuration file.
1329 siprop
=> 'namespaces'
1331 my $result = $mediawiki->api($query);
1333 while (my ($id, $ns) = each(%{$result->{query
}->{namespaces
}})) {
1334 if (defined($ns->{id
}) && defined($ns->{canonical
})) {
1335 $namespace_id{$ns->{canonical
}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1337 # alias (e.g. french Fichier: as alias for canonical File:)
1338 $namespace_id{$ns->{'*'}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1344 my $ns = $namespace_id{$name};
1347 unless (defined $ns) {
1348 print STDERR
"No such namespace $name on MediaWiki.\n";
1349 $ns = {is_namespace
=> 0};
1350 $namespace_id{$name} = $ns;
1353 if ($ns->{is_namespace
}) {
1357 # Store "notANameSpace" as special value for inexisting namespaces
1358 my $store_id = ($id || 'notANameSpace');
1360 # Store explicitely requested namespaces on disk
1361 if (!exists $cached_mw_namespace_id{$name}) {
1362 run_git
("config --add remote.". $remotename
1363 .".namespaceCache \"". $name .":". $store_id ."\"");
1364 $cached_mw_namespace_id{$name} = 1;
1369 sub get_mw_namespace_id_for_page
{
1370 if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1371 return get_mw_namespace_id
($namespace);