blob: 8dd74a9a406e9cfd685ea1af3947e4bea4c82f90 [file] [log] [blame]
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001#! /usr/bin/perl
2
3# Copyright (C) 2011
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
10
11# Gateway between Git and MediaWiki.
Matthieu Moy9a7365c2012-08-03 10:40:23 +020012# Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
Jeremie Nikaes428c9952011-09-01 18:54:55 +020013
14use strict;
15use MediaWiki::API;
Benoit Personda608b12013-06-05 12:58:00 +020016use Git;
Benoit Person192f7a02013-07-04 22:38:58 +020017use Git::Mediawiki qw(clean_filename smudge_filename connect_maybe
18 EMPTY HTTP_CODE_OK);
Jeremie Nikaes428c9952011-09-01 18:54:55 +020019use DateTime::Format::ISO8601;
Jeremie Nikaes428c9952011-09-01 18:54:55 +020020use warnings;
21
Jeremie Nikaes428c9952011-09-01 18:54:55 +020022# By default, use UTF-8 to communicate with Git and the user
Célestin Matte86e95ef2013-06-14 15:50:30 +020023binmode STDERR, ':encoding(UTF-8)';
24binmode STDOUT, ':encoding(UTF-8)';
Jeremie Nikaes428c9952011-09-01 18:54:55 +020025
26use URI::Escape;
Jeremie Nikaes428c9952011-09-01 18:54:55 +020027
Jeremie Nikaes428c9952011-09-01 18:54:55 +020028# It's not always possible to delete pages (may require some
Stefano Lattarini2582ab12013-04-12 00:36:10 +020029# privileges). Deleted pages are replaced with this content.
Jeremie Nikaes428c9952011-09-01 18:54:55 +020030use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
31
32# It's not possible to create empty pages. New empty files in Git are
33# sent with this content instead.
34use constant EMPTY_CONTENT => "<!-- empty page -->\n";
35
36# used to reflect file creation or deletion in diff.
Célestin Matte86e95ef2013-06-14 15:50:30 +020037use constant NULL_SHA1 => '0000000000000000000000000000000000000000';
Jeremie Nikaes428c9952011-09-01 18:54:55 +020038
Matthieu Moydcb1ea62012-07-16 14:00:47 +020039# Used on Git's side to reflect empty edit messages on the wiki
40use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
41
Célestin Mattefed56c02013-06-14 15:50:34 +020042# Number of pages taken into account at once in submodule get_mw_page_list
43use constant SLICE_SIZE => 50;
44
45# Number of linked mediafile to get at once in get_linked_mediafiles
46# The query is split in small batches because of the MW API limit of
47# the number of links to be returned (500 links max).
48use constant BATCH_SIZE => 10;
49
Célestin Matte5ada8682013-06-11 15:38:48 +020050if (@ARGV != 2) {
51 exit_error_usage();
52}
53
Jeremie Nikaes428c9952011-09-01 18:54:55 +020054my $remotename = $ARGV[0];
55my $url = $ARGV[1];
56
57# Accept both space-separated and multiple keys in config file.
58# Spaces should be written as _ anyway because we'll use chomp.
Célestin Matte86e95ef2013-06-14 15:50:30 +020059my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.${remotename}.pages"));
Jeremie Nikaes428c9952011-09-01 18:54:55 +020060chomp(@tracked_pages);
61
62# Just like @tracked_pages, but for MediaWiki categories.
Célestin Matte86e95ef2013-06-14 15:50:30 +020063my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.${remotename}.categories"));
Jeremie Nikaes428c9952011-09-01 18:54:55 +020064chomp(@tracked_categories);
65
Matthieu Moy2045e292012-07-16 21:46:37 +020066# Import media files on pull
Célestin Matte86e95ef2013-06-14 15:50:30 +020067my $import_media = run_git("config --get --bool remote.${remotename}.mediaimport");
Pavel Volek6a9e55b2012-06-27 16:21:29 +020068chomp($import_media);
Célestin Matte86e95ef2013-06-14 15:50:30 +020069$import_media = ($import_media eq 'true');
Pavel Volek6a9e55b2012-06-27 16:21:29 +020070
Matthieu Moy2045e292012-07-16 21:46:37 +020071# Export media files on push
Célestin Matte86e95ef2013-06-14 15:50:30 +020072my $export_media = run_git("config --get --bool remote.${remotename}.mediaexport");
Matthieu Moy2045e292012-07-16 21:46:37 +020073chomp($export_media);
Célestin Matte86e95ef2013-06-14 15:50:30 +020074$export_media = !($export_media eq 'false');
Matthieu Moy2045e292012-07-16 21:46:37 +020075
Célestin Matte86e95ef2013-06-14 15:50:30 +020076my $wiki_login = run_git("config --get remote.${remotename}.mwLogin");
Matthieu Moy2da78302012-07-08 18:18:28 +020077# Note: mwPassword is discourraged. Use the credential system instead.
Célestin Matte86e95ef2013-06-14 15:50:30 +020078my $wiki_passwd = run_git("config --get remote.${remotename}.mwPassword");
79my $wiki_domain = run_git("config --get remote.${remotename}.mwDomain");
Jeremie Nikaes428c9952011-09-01 18:54:55 +020080chomp($wiki_login);
81chomp($wiki_passwd);
Matthieu Moy1d6abac2011-09-28 15:48:01 +020082chomp($wiki_domain);
Jeremie Nikaes428c9952011-09-01 18:54:55 +020083
84# Import only last revisions (both for clone and fetch)
Célestin Matte86e95ef2013-06-14 15:50:30 +020085my $shallow_import = run_git("config --get --bool remote.${remotename}.shallow");
Jeremie Nikaes428c9952011-09-01 18:54:55 +020086chomp($shallow_import);
Célestin Matte86e95ef2013-06-14 15:50:30 +020087$shallow_import = ($shallow_import eq 'true');
Jeremie Nikaes428c9952011-09-01 18:54:55 +020088
Matthieu Moy5a292172012-07-06 12:03:14 +020089# Fetch (clone and pull) by revisions instead of by pages. This behavior
90# is more efficient when we have a wiki with lots of pages and we fetch
91# the revisions quite often so that they concern only few pages.
92# Possible values:
93# - by_rev: perform one query per new revision on the remote wiki
94# - by_page: query each tracked page for new revision
Célestin Matte86e95ef2013-06-14 15:50:30 +020095my $fetch_strategy = run_git("config --get remote.${remotename}.fetchStrategy");
Célestin Matteb8b4e1b2013-06-14 15:50:32 +020096if (!$fetch_strategy) {
Célestin Matte86e95ef2013-06-14 15:50:30 +020097 $fetch_strategy = run_git('config --get mediawiki.fetchStrategy');
Matthieu Moy5a292172012-07-06 12:03:14 +020098}
99chomp($fetch_strategy);
Célestin Matteb8b4e1b2013-06-14 15:50:32 +0200100if (!$fetch_strategy) {
Célestin Matte86e95ef2013-06-14 15:50:30 +0200101 $fetch_strategy = 'by_page';
Matthieu Moy5a292172012-07-06 12:03:14 +0200102}
103
Célestin Matte0afd29e2013-06-14 15:50:13 +0200104# Remember the timestamp corresponding to a revision id.
105my %basetimestamps;
106
Matthieu Moy93f0d332011-09-01 18:54:56 +0200107# Dumb push: don't update notes and mediawiki ref to reflect the last push.
108#
109# Configurable with mediawiki.dumbPush, or per-remote with
110# remote.<remotename>.dumbPush.
111#
112# This means the user will have to re-import the just-pushed
113# revisions. On the other hand, this means that the Git revisions
114# corresponding to MediaWiki revisions are all imported from the wiki,
115# regardless of whether they were initially created in Git or from the
116# web interface, hence all users will get the same history (i.e. if
117# the push from Git to MediaWiki loses some information, everybody
118# will get the history with information lost). If the import is
119# deterministic, this means everybody gets the same sha1 for each
120# MediaWiki revision.
Célestin Matte86e95ef2013-06-14 15:50:30 +0200121my $dumb_push = run_git("config --get --bool remote.${remotename}.dumbPush");
Célestin Matteb8b4e1b2013-06-14 15:50:32 +0200122if (!$dumb_push) {
Célestin Matte86e95ef2013-06-14 15:50:30 +0200123 $dumb_push = run_git('config --get --bool mediawiki.dumbPush');
Matthieu Moy93f0d332011-09-01 18:54:56 +0200124}
125chomp($dumb_push);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200126$dumb_push = ($dumb_push eq 'true');
Matthieu Moy93f0d332011-09-01 18:54:56 +0200127
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200128my $wiki_name = $url;
Célestin Matte857f21a2013-06-14 15:50:18 +0200129$wiki_name =~ s{[^/]*://}{};
Matthieu Moy9fb79502011-10-20 19:04:59 +0200130# If URL is like http://user:password@example.com/, we clearly don't
131# want the password in $wiki_name. While we're there, also remove user
132# and '@' sign, to avoid author like MWUser@HTTPUser@host.com
133$wiki_name =~ s/^.*@//;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200134
135# Commands parser
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200136while (<STDIN>) {
137 chomp;
Célestin Matte6a316be2013-06-14 15:50:29 +0200138
139 if (!parse_command($_)) {
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200140 last;
141 }
142
143 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
144 # command is fully processed.
145}
146
147########################## Functions ##############################
148
Célestin Matte5ada8682013-06-11 15:38:48 +0200149## error handling
150sub exit_error_usage {
151 die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
152 "parameters\n" .
153 "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
154 "module directly.\n" .
155 "This module can be used the following way:\n" .
156 "\tgit clone mediawiki://<address of a mediawiki>\n" .
157 "Then, use git commit, push and pull as with every normal git repository.\n";
158}
159
Célestin Matte6a316be2013-06-14 15:50:29 +0200160sub parse_command {
161 my ($line) = @_;
162 my @cmd = split(/ /, $line);
163 if (!defined $cmd[0]) {
164 return 0;
165 }
Célestin Matte86e95ef2013-06-14 15:50:30 +0200166 if ($cmd[0] eq 'capabilities') {
Célestin Matte6a316be2013-06-14 15:50:29 +0200167 die("Too many arguments for capabilities\n")
168 if (defined($cmd[1]));
169 mw_capabilities();
Célestin Matte86e95ef2013-06-14 15:50:30 +0200170 } elsif ($cmd[0] eq 'list') {
Célestin Matte6a316be2013-06-14 15:50:29 +0200171 die("Too many arguments for list\n") if (defined($cmd[2]));
172 mw_list($cmd[1]);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200173 } elsif ($cmd[0] eq 'import') {
Célestin Matted8e7c672013-06-14 15:50:39 +0200174 die("Invalid argument for import\n")
175 if ($cmd[1] eq EMPTY);
176 die("Too many arguments for import\n")
177 if (defined($cmd[2]));
Célestin Matte6a316be2013-06-14 15:50:29 +0200178 mw_import($cmd[1]);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200179 } elsif ($cmd[0] eq 'option') {
Célestin Matted8e7c672013-06-14 15:50:39 +0200180 die("Invalid arguments for option\n")
181 if ($cmd[1] eq EMPTY || $cmd[2] eq EMPTY);
Célestin Matte6a316be2013-06-14 15:50:29 +0200182 die("Too many arguments for option\n")
Célestin Matted8e7c672013-06-14 15:50:39 +0200183 if (defined($cmd[3]));
Célestin Matte6a316be2013-06-14 15:50:29 +0200184 mw_option($cmd[1],$cmd[2]);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200185 } elsif ($cmd[0] eq 'push') {
Célestin Matte6a316be2013-06-14 15:50:29 +0200186 mw_push($cmd[1]);
187 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200188 print {*STDERR} "Unknown command. Aborting...\n";
Célestin Matte6a316be2013-06-14 15:50:29 +0200189 return 0;
190 }
191 return 1;
192}
193
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200194# MediaWiki API instance, created lazily.
195my $mediawiki;
196
Matthieu Moy0aa03212013-05-29 14:06:29 +0200197sub fatal_mw_error {
198 my $action = shift;
199 print STDERR "fatal: could not $action.\n";
200 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
201 if ($url =~ /^https/) {
202 print STDERR "fatal: make sure '$url/api.php' is a valid page\n";
203 print STDERR "fatal: and the SSL certificate is correct.\n";
204 } else {
205 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
206 }
207 print STDERR "fatal: (error " .
208 $mediawiki->{error}->{code} . ': ' .
209 $mediawiki->{error}->{details} . ")\n";
210 exit 1;
211}
212
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200213## Functions for listing pages on the remote wiki
214sub get_mw_tracked_pages {
215 my $pages = shift;
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200216 get_mw_page_list(\@tracked_pages, $pages);
Célestin Matte1aff8c62013-06-14 15:50:12 +0200217 return;
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200218}
219
220sub get_mw_page_list {
221 my $page_list = shift;
222 my $pages = shift;
Célestin Matted49a0382013-06-14 15:50:36 +0200223 my @some_pages = @{$page_list};
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200224 while (@some_pages) {
Célestin Mattefed56c02013-06-14 15:50:34 +0200225 my $last_page = SLICE_SIZE;
Célestin Matteb835baf2013-06-14 15:50:25 +0200226 if ($#some_pages < $last_page) {
227 $last_page = $#some_pages;
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200228 }
Célestin Matteb835baf2013-06-14 15:50:25 +0200229 my @slice = @some_pages[0..$last_page];
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200230 get_mw_first_pages(\@slice, $pages);
Célestin Mattefed56c02013-06-14 15:50:34 +0200231 @some_pages = @some_pages[(SLICE_SIZE + 1)..$#some_pages];
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200232 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200233 return;
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200234}
235
236sub get_mw_tracked_categories {
237 my $pages = shift;
238 foreach my $category (@tracked_categories) {
239 if (index($category, ':') < 0) {
240 # Mediawiki requires the Category
241 # prefix, but let's not force the user
242 # to specify it.
Célestin Matte86e95ef2013-06-14 15:50:30 +0200243 $category = "Category:${category}";
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200244 }
245 my $mw_pages = $mediawiki->list( {
246 action => 'query',
247 list => 'categorymembers',
248 cmtitle => $category,
249 cmlimit => 'max' } )
250 || die $mediawiki->{error}->{code} . ': '
Célestin Matte8a43b362013-06-14 15:50:21 +0200251 . $mediawiki->{error}->{details} . "\n";
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200252 foreach my $page (@{$mw_pages}) {
253 $pages->{$page->{title}} = $page;
254 }
255 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200256 return;
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200257}
258
259sub get_mw_all_pages {
260 my $pages = shift;
261 # No user-provided list, get the list of pages from the API.
262 my $mw_pages = $mediawiki->list({
263 action => 'query',
264 list => 'allpages',
265 aplimit => 'max'
266 });
267 if (!defined($mw_pages)) {
Matthieu Moy0aa03212013-05-29 14:06:29 +0200268 fatal_mw_error("get the list of wiki pages");
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200269 }
270 foreach my $page (@{$mw_pages}) {
271 $pages->{$page->{title}} = $page;
272 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200273 return;
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200274}
275
276# queries the wiki for a set of pages. Meant to be used within a loop
277# querying the wiki for slices of page list.
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200278sub get_mw_first_pages {
279 my $some_pages = shift;
280 my @some_pages = @{$some_pages};
281
282 my $pages = shift;
283
284 # pattern 'page1|page2|...' required by the API
285 my $titles = join('|', @some_pages);
286
287 my $mw_pages = $mediawiki->api({
288 action => 'query',
289 titles => $titles,
290 });
291 if (!defined($mw_pages)) {
Matthieu Moy0aa03212013-05-29 14:06:29 +0200292 fatal_mw_error("query the list of wiki pages");
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200293 }
294 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
295 if ($id < 0) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200296 print {*STDERR} "Warning: page $page->{title} not found on wiki\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200297 } else {
298 $pages->{$page->{title}} = $page;
299 }
300 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200301 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200302}
303
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200304# Get the list of pages to be fetched according to configuration.
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200305sub get_mw_pages {
Benoit Person192f7a02013-07-04 22:38:58 +0200306 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200307
Célestin Mattee83d36b2013-06-14 15:50:31 +0200308 print {*STDERR} "Listing pages on remote wiki...\n";
Matthieu Moyf690ddf2012-07-16 21:46:40 +0200309
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200310 my %pages; # hash on page titles to avoid duplicates
311 my $user_defined;
312 if (@tracked_pages) {
313 $user_defined = 1;
314 # The user provided a list of pages titles, but we
315 # still need to query the API to get the page IDs.
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200316 get_mw_tracked_pages(\%pages);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200317 }
318 if (@tracked_categories) {
319 $user_defined = 1;
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200320 get_mw_tracked_categories(\%pages);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200321 }
322 if (!$user_defined) {
Matthieu Moy9cb74f32012-06-27 11:10:19 +0200323 get_mw_all_pages(\%pages);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200324 }
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200325 if ($import_media) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200326 print {*STDERR} "Getting media files for selected pages...\n";
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200327 if ($user_defined) {
328 get_linked_mediafiles(\%pages);
329 } else {
330 get_all_mediafiles(\%pages);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200331 }
332 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200333 print {*STDERR} (scalar keys %pages) . " pages found.\n";
Matthieu Moyb1ede9a2012-07-06 12:03:11 +0200334 return %pages;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200335}
336
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200337# usage: $out = run_git("command args");
338# $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200339sub run_git {
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200340 my $args = shift;
Célestin Matte86e95ef2013-06-14 15:50:30 +0200341 my $encoding = (shift || 'encoding(UTF-8)');
342 open(my $git, "-|:${encoding}", "git ${args}")
343 or die "Unable to fork: $!\n";
Célestin Matte4f1b7882013-06-14 15:50:26 +0200344 my $res = do {
345 local $/ = undef;
346 <$git>
347 };
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200348 close($git);
349
350 return $res;
351}
352
353
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200354sub get_all_mediafiles {
355 my $pages = shift;
356 # Attach list of all pages for media files from the API,
357 # they are in a different namespace, only one namespace
358 # can be queried at the same moment
359 my $mw_pages = $mediawiki->list({
360 action => 'query',
361 list => 'allpages',
Célestin Matte86e95ef2013-06-14 15:50:30 +0200362 apnamespace => get_mw_namespace_id('File'),
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200363 aplimit => 'max'
364 });
365 if (!defined($mw_pages)) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200366 print {*STDERR} "fatal: could not get the list of pages for media files.\n";
367 print {*STDERR} "fatal: '$url' does not appear to be a mediawiki\n";
368 print {*STDERR} "fatal: make sure '$url/api.php' is a valid page.\n";
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200369 exit 1;
370 }
371 foreach my $page (@{$mw_pages}) {
372 $pages->{$page->{title}} = $page;
373 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200374 return;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200375}
376
377sub get_linked_mediafiles {
378 my $pages = shift;
Célestin Matte81f6a7a2013-06-14 15:50:14 +0200379 my @titles = map { $_->{title} } values(%{$pages});
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200380
Célestin Mattefed56c02013-06-14 15:50:34 +0200381 my $batch = BATCH_SIZE;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200382 while (@titles) {
383 if ($#titles < $batch) {
384 $batch = $#titles;
385 }
386 my @slice = @titles[0..$batch];
387
388 # pattern 'page1|page2|...' required by the API
389 my $mw_titles = join('|', @slice);
390
391 # Media files could be included or linked from
392 # a page, get all related
393 my $query = {
394 action => 'query',
395 prop => 'links|images',
396 titles => $mw_titles,
Célestin Matte86e95ef2013-06-14 15:50:30 +0200397 plnamespace => get_mw_namespace_id('File'),
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200398 pllimit => 'max'
399 };
400 my $result = $mediawiki->api($query);
401
402 while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200403 my @media_titles;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200404 if (defined($page->{links})) {
Célestin Matte81f6a7a2013-06-14 15:50:14 +0200405 my @link_titles
406 = map { $_->{title} } @{$page->{links}};
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200407 push(@media_titles, @link_titles);
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200408 }
409 if (defined($page->{images})) {
Célestin Matte81f6a7a2013-06-14 15:50:14 +0200410 my @image_titles
411 = map { $_->{title} } @{$page->{images}};
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200412 push(@media_titles, @image_titles);
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200413 }
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200414 if (@media_titles) {
415 get_mw_page_list(\@media_titles, $pages);
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200416 }
417 }
418
419 @titles = @titles[($batch+1)..$#titles];
420 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200421 return;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200422}
423
424sub get_mw_mediafile_for_page_revision {
425 # Name of the file on Wiki, with the prefix.
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200426 my $filename = shift;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200427 my $timestamp = shift;
428 my %mediafile;
429
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200430 # Search if on a media file with given timestamp exists on
431 # MediaWiki. In that case download the file.
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200432 my $query = {
433 action => 'query',
434 prop => 'imageinfo',
Célestin Matte86e95ef2013-06-14 15:50:30 +0200435 titles => "File:${filename}",
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200436 iistart => $timestamp,
437 iiend => $timestamp,
438 iiprop => 'timestamp|archivename|url',
439 iilimit => 1
440 };
441 my $result = $mediawiki->api($query);
442
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200443 my ($fileid, $file) = each( %{$result->{query}->{pages}} );
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200444 # If not defined it means there is no revision of the file for
445 # given timestamp.
446 if (defined($file->{imageinfo})) {
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200447 $mediafile{title} = $filename;
448
449 my $fileinfo = pop(@{$file->{imageinfo}});
450 $mediafile{timestamp} = $fileinfo->{timestamp};
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200451 # Mediawiki::API's download function doesn't support https URLs
452 # and can't download old versions of files.
Célestin Mattee83d36b2013-06-14 15:50:31 +0200453 print {*STDERR} "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200454 $mediafile{content} = download_mw_mediafile($fileinfo->{url});
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200455 }
456 return %mediafile;
457}
458
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200459sub download_mw_mediafile {
Célestin Matte8f04f7d2013-06-14 15:50:22 +0200460 my $download_url = shift;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200461
Célestin Matte8f04f7d2013-06-14 15:50:22 +0200462 my $response = $mediawiki->{ua}->get($download_url);
Célestin Mattefed56c02013-06-14 15:50:34 +0200463 if ($response->code == HTTP_CODE_OK) {
Matthieu Moy9742fb72014-04-23 16:34:29 +0200464 # It is tempting to return
465 # $response->decoded_content({charset => "none"}), but
466 # when doing so, utf8::downgrade($content) fails with
467 # "Wide character in subroutine entry".
468 $response->decode();
469 return $response->content();
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200470 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200471 print {*STDERR} "Error downloading mediafile from :\n";
472 print {*STDERR} "URL: ${download_url}\n";
473 print {*STDERR} 'Server response: ' . $response->code . q{ } . $response->message . "\n";
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200474 exit 1;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200475 }
476}
477
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200478sub get_last_local_revision {
479 # Get note regarding last mediawiki revision
Célestin Matte86e95ef2013-06-14 15:50:30 +0200480 my $note = run_git("notes --ref=${remotename}/mediawiki show refs/mediawiki/${remotename}/master 2>/dev/null");
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200481 my @note_info = split(/ /, $note);
482
483 my $lastrevision_number;
Célestin Matte86e95ef2013-06-14 15:50:30 +0200484 if (!(defined($note_info[0]) && $note_info[0] eq 'mediawiki_revision:')) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200485 print {*STDERR} 'No previous mediawiki revision found';
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200486 $lastrevision_number = 0;
487 } else {
488 # Notes are formatted : mediawiki_revision: #number
489 $lastrevision_number = $note_info[1];
490 chomp($lastrevision_number);
Célestin Mattee83d36b2013-06-14 15:50:31 +0200491 print {*STDERR} "Last local mediawiki revision found is ${lastrevision_number}";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200492 }
493 return $lastrevision_number;
494}
495
Matthieu Moy5a292172012-07-06 12:03:14 +0200496# Get the last remote revision without taking in account which pages are
497# tracked or not. This function makes a single request to the wiki thus
498# avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
499# option.
500sub get_last_global_remote_rev {
Benoit Person192f7a02013-07-04 22:38:58 +0200501 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Matthieu Moy5a292172012-07-06 12:03:14 +0200502
503 my $query = {
504 action => 'query',
505 list => 'recentchanges',
506 prop => 'revisions',
507 rclimit => '1',
508 rcdir => 'older',
509 };
510 my $result = $mediawiki->api($query);
511 return $result->{query}->{recentchanges}[0]->{revid};
512}
513
514# Get the last remote revision concerning the tracked pages and the tracked
515# categories.
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200516sub get_last_remote_revision {
Benoit Person192f7a02013-07-04 22:38:58 +0200517 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200518
Matthieu Moyb1ede9a2012-07-06 12:03:11 +0200519 my %pages_hash = get_mw_pages();
520 my @pages = values(%pages_hash);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200521
522 my $max_rev_num = 0;
523
Célestin Mattee83d36b2013-06-14 15:50:31 +0200524 print {*STDERR} "Getting last revision id on tracked pages...\n";
Matthieu Moya393f482012-07-16 21:46:41 +0200525
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200526 foreach my $page (@pages) {
527 my $id = $page->{pageid};
528
529 my $query = {
530 action => 'query',
531 prop => 'revisions',
Matthieu Moy3c1ed902011-09-27 19:54:59 +0200532 rvprop => 'ids|timestamp',
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200533 pageids => $id,
534 };
535
536 my $result = $mediawiki->api($query);
537
538 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
539
Matthieu Moy3c1ed902011-09-27 19:54:59 +0200540 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
541
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200542 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
543 }
544
Célestin Mattee83d36b2013-06-14 15:50:31 +0200545 print {*STDERR} "Last remote revision found is $max_rev_num.\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200546 return $max_rev_num;
547}
548
549# Clean content before sending it to MediaWiki
550sub mediawiki_clean {
551 my $string = shift;
552 my $page_created = shift;
553 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
554 # This function right trims a string and adds a \n at the end to follow this rule
555 $string =~ s/\s+$//;
Célestin Matteaeb95ee2013-06-14 15:50:33 +0200556 if ($string eq EMPTY && $page_created) {
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200557 # Creating empty pages is forbidden.
558 $string = EMPTY_CONTENT;
559 }
560 return $string."\n";
561}
562
563# Filter applied on MediaWiki data before adding them to Git
564sub mediawiki_smudge {
565 my $string = shift;
566 if ($string eq EMPTY_CONTENT) {
Célestin Matteaeb95ee2013-06-14 15:50:33 +0200567 $string = EMPTY;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200568 }
569 # This \n is important. This is due to mediawiki's way to handle end of files.
Célestin Matte86e95ef2013-06-14 15:50:30 +0200570 return "${string}\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200571}
572
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200573sub literal_data {
574 my ($content) = @_;
Célestin Mattee83d36b2013-06-14 15:50:31 +0200575 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
Célestin Matte1aff8c62013-06-14 15:50:12 +0200576 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200577}
578
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200579sub literal_data_raw {
580 # Output possibly binary content.
581 my ($content) = @_;
582 # Avoid confusion between size in bytes and in characters
583 utf8::downgrade($content);
Matthieu Moy0e7c41c2013-07-03 11:14:19 +0200584 binmode STDOUT, ':raw';
Célestin Mattee83d36b2013-06-14 15:50:31 +0200585 print {*STDOUT} 'data ', bytes::length($content), "\n", $content;
Matthieu Moy0e7c41c2013-07-03 11:14:19 +0200586 binmode STDOUT, ':encoding(UTF-8)';
Célestin Matte1aff8c62013-06-14 15:50:12 +0200587 return;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200588}
589
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200590sub mw_capabilities {
591 # Revisions are imported to the private namespace
592 # refs/mediawiki/$remotename/ by the helper and fetched into
593 # refs/remotes/$remotename later by fetch.
Célestin Mattee83d36b2013-06-14 15:50:31 +0200594 print {*STDOUT} "refspec refs/heads/*:refs/mediawiki/${remotename}/*\n";
595 print {*STDOUT} "import\n";
596 print {*STDOUT} "list\n";
597 print {*STDOUT} "push\n";
Matthieu Moyaa38dc62013-09-02 09:19:47 +0200598 if ($dumb_push) {
599 print {*STDOUT} "no-private-update\n";
600 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200601 print {*STDOUT} "\n";
Célestin Matte1aff8c62013-06-14 15:50:12 +0200602 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200603}
604
605sub mw_list {
606 # MediaWiki do not have branches, we consider one branch arbitrarily
607 # called master, and HEAD pointing to it.
Célestin Mattee83d36b2013-06-14 15:50:31 +0200608 print {*STDOUT} "? refs/heads/master\n";
609 print {*STDOUT} "\@refs/heads/master HEAD\n";
610 print {*STDOUT} "\n";
Célestin Matte1aff8c62013-06-14 15:50:12 +0200611 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200612}
613
614sub mw_option {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200615 print {*STDERR} "remote-helper command 'option $_[0]' not yet implemented\n";
616 print {*STDOUT} "unsupported\n";
Célestin Matte1aff8c62013-06-14 15:50:12 +0200617 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200618}
619
620sub fetch_mw_revisions_for_page {
621 my $page = shift;
622 my $id = shift;
623 my $fetch_from = shift;
624 my @page_revs = ();
625 my $query = {
626 action => 'query',
627 prop => 'revisions',
628 rvprop => 'ids',
629 rvdir => 'newer',
630 rvstartid => $fetch_from,
631 rvlimit => 500,
632 pageids => $id,
Benoit Person1d905f72013-09-24 21:32:30 +0200633
634 # Let MediaWiki know that we support the latest API.
635 continue => '',
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200636 };
637
638 my $revnum = 0;
639 # Get 500 revisions at a time due to the mediawiki api limit
640 while (1) {
641 my $result = $mediawiki->api($query);
642
643 # Parse each of those 500 revisions
644 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
645 my $page_rev_ids;
646 $page_rev_ids->{pageid} = $page->{pageid};
647 $page_rev_ids->{revid} = $revision->{revid};
648 push(@page_revs, $page_rev_ids);
649 $revnum++;
650 }
Benoit Person1d905f72013-09-24 21:32:30 +0200651
652 if ($result->{'query-continue'}) { # For legacy APIs
653 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
654 } elsif ($result->{continue}) { # For newer APIs
655 $query->{rvstartid} = $result->{continue}->{rvcontinue};
656 $query->{continue} = $result->{continue}->{continue};
657 } else {
658 last;
659 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200660 }
661 if ($shallow_import && @page_revs) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200662 print {*STDERR} " Found 1 revision (shallow import).\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200663 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
664 return $page_revs[0];
665 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200666 print {*STDERR} " Found ${revnum} revision(s).\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200667 return @page_revs;
668}
669
670sub fetch_mw_revisions {
671 my $pages = shift; my @pages = @{$pages};
672 my $fetch_from = shift;
673
674 my @revisions = ();
675 my $n = 1;
676 foreach my $page (@pages) {
677 my $id = $page->{pageid};
Célestin Mattee83d36b2013-06-14 15:50:31 +0200678 print {*STDERR} "page ${n}/", scalar(@pages), ': ', $page->{title}, "\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200679 $n++;
680 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
681 @revisions = (@page_revs, @revisions);
682 }
683
684 return ($n, @revisions);
685}
686
Matthieu Moy462d97d2012-11-29 18:00:55 +0100687sub fe_escape_path {
688 my $path = shift;
689 $path =~ s/\\/\\\\/g;
690 $path =~ s/"/\\"/g;
691 $path =~ s/\n/\\n/g;
Célestin Matte86e95ef2013-06-14 15:50:30 +0200692 return qq("${path}");
Matthieu Moy462d97d2012-11-29 18:00:55 +0100693}
694
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200695sub import_file_revision {
696 my $commit = shift;
697 my %commit = %{$commit};
698 my $full_import = shift;
699 my $n = shift;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200700 my $mediafile = shift;
701 my %mediafile;
702 if ($mediafile) {
703 %mediafile = %{$mediafile};
704 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200705
706 my $title = $commit{title};
707 my $comment = $commit{comment};
708 my $content = $commit{content};
709 my $author = $commit{author};
710 my $date = $commit{date};
711
Célestin Mattee83d36b2013-06-14 15:50:31 +0200712 print {*STDOUT} "commit refs/mediawiki/${remotename}/master\n";
713 print {*STDOUT} "mark :${n}\n";
714 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200715 literal_data($comment);
716
717 # If it's not a clone, we need to know where to start from
718 if (!$full_import && $n == 1) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200719 print {*STDOUT} "from refs/mediawiki/${remotename}/master^0\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200720 }
721 if ($content ne DELETED_CONTENT) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200722 print {*STDOUT} 'M 644 inline ' .
Célestin Matte86e95ef2013-06-14 15:50:30 +0200723 fe_escape_path("${title}.mw") . "\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200724 literal_data($content);
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200725 if (%mediafile) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200726 print {*STDOUT} 'M 644 inline '
Matthieu Moy462d97d2012-11-29 18:00:55 +0100727 . fe_escape_path($mediafile{title}) . "\n";
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200728 literal_data_raw($mediafile{content});
729 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200730 print {*STDOUT} "\n\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200731 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200732 print {*STDOUT} 'D ' . fe_escape_path("${title}.mw") . "\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200733 }
734
735 # mediawiki revision number in the git note
736 if ($full_import && $n == 1) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200737 print {*STDOUT} "reset refs/notes/${remotename}/mediawiki\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200738 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200739 print {*STDOUT} "commit refs/notes/${remotename}/mediawiki\n";
740 print {*STDOUT} "committer ${author} <${author}\@${wiki_name}> " . $date->epoch . " +0000\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +0200741 literal_data('Note added by git-mediawiki during import');
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200742 if (!$full_import && $n == 1) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200743 print {*STDOUT} "from refs/notes/${remotename}/mediawiki^0\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200744 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200745 print {*STDOUT} "N inline :${n}\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +0200746 literal_data("mediawiki_revision: $commit{mw_revision}");
Célestin Mattee83d36b2013-06-14 15:50:31 +0200747 print {*STDOUT} "\n\n";
Célestin Matte1aff8c62013-06-14 15:50:12 +0200748 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200749}
750
751# parse a sequence of
752# <cmd> <arg1>
753# <cmd> <arg2>
754# \n
755# (like batch sequence of import and sequence of push statements)
756sub get_more_refs {
757 my $cmd = shift;
758 my @refs;
759 while (1) {
760 my $line = <STDIN>;
Célestin Matteeb96b752013-06-14 15:50:16 +0200761 if ($line =~ /^$cmd (.*)$/) {
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200762 push(@refs, $1);
763 } elsif ($line eq "\n") {
764 return @refs;
765 } else {
Célestin Matte8a43b362013-06-14 15:50:21 +0200766 die("Invalid command in a '$cmd' batch: $_\n");
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200767 }
768 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200769 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200770}
771
772sub mw_import {
773 # multiple import commands can follow each other.
Célestin Matte86e95ef2013-06-14 15:50:30 +0200774 my @refs = (shift, get_more_refs('import'));
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200775 foreach my $ref (@refs) {
776 mw_import_ref($ref);
777 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200778 print {*STDOUT} "done\n";
Célestin Matte1aff8c62013-06-14 15:50:12 +0200779 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200780}
781
782sub mw_import_ref {
783 my $ref = shift;
784 # The remote helper will call "import HEAD" and
785 # "import refs/heads/master".
786 # Since HEAD is a symbolic ref to master (by convention,
787 # followed by the output of the command "list" that we gave),
788 # we don't need to do anything in this case.
Célestin Matte86e95ef2013-06-14 15:50:30 +0200789 if ($ref eq 'HEAD') {
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200790 return;
791 }
792
Benoit Person192f7a02013-07-04 22:38:58 +0200793 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200794
Célestin Mattee83d36b2013-06-14 15:50:31 +0200795 print {*STDERR} "Searching revisions...\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200796 my $last_local = get_last_local_revision();
797 my $fetch_from = $last_local + 1;
798 if ($fetch_from == 1) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200799 print {*STDERR} ", fetching from beginning.\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200800 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200801 print {*STDERR} ", fetching from here.\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200802 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200803
Matthieu Moy5a292172012-07-06 12:03:14 +0200804 my $n = 0;
Célestin Matte86e95ef2013-06-14 15:50:30 +0200805 if ($fetch_strategy eq 'by_rev') {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200806 print {*STDERR} "Fetching & writing export data by revs...\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200807 $n = mw_import_ref_by_revs($fetch_from);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200808 } elsif ($fetch_strategy eq 'by_page') {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200809 print {*STDERR} "Fetching & writing export data by pages...\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200810 $n = mw_import_ref_by_pages($fetch_from);
811 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200812 print {*STDERR} qq(fatal: invalid fetch strategy "${fetch_strategy}".\n);
813 print {*STDERR} "Check your configuration variables remote.${remotename}.fetchStrategy and mediawiki.fetchStrategy\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200814 exit 1;
815 }
816
817 if ($fetch_from == 1 && $n == 0) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200818 print {*STDERR} "You appear to have cloned an empty MediaWiki.\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200819 # Something has to be done remote-helper side. If nothing is done, an error is
Stefano Lattarini2582ab12013-04-12 00:36:10 +0200820 # thrown saying that HEAD is referring to unknown object 0000000000000000000
Matthieu Moy5a292172012-07-06 12:03:14 +0200821 # and the clone fails.
822 }
Célestin Matte1aff8c62013-06-14 15:50:12 +0200823 return;
Matthieu Moy5a292172012-07-06 12:03:14 +0200824}
825
826sub mw_import_ref_by_pages {
827
828 my $fetch_from = shift;
829 my %pages_hash = get_mw_pages();
830 my @pages = values(%pages_hash);
831
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200832 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
833
Matthieu Moy4465b6d2012-07-06 12:03:12 +0200834 @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
Célestin Matte81f6a7a2013-06-14 15:50:14 +0200835 my @revision_ids = map { $_->{revid} } @revisions;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200836
Matthieu Moy312fa9a2012-07-06 12:03:13 +0200837 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
838}
839
Matthieu Moy5a292172012-07-06 12:03:14 +0200840sub mw_import_ref_by_revs {
841
842 my $fetch_from = shift;
843 my %pages_hash = get_mw_pages();
844
845 my $last_remote = get_last_global_remote_rev();
846 my @revision_ids = $fetch_from..$last_remote;
847 return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
848}
849
850# Import revisions given in second argument (array of integers).
851# Only pages appearing in the third argument (hash indexed by page titles)
852# will be imported.
Matthieu Moy312fa9a2012-07-06 12:03:13 +0200853sub mw_import_revids {
854 my $fetch_from = shift;
855 my $revision_ids = shift;
856 my $pages = shift;
857
858 my $n = 0;
Matthieu Moy5a292172012-07-06 12:03:14 +0200859 my $n_actual = 0;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200860 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
861
Célestin Matted49a0382013-06-14 15:50:36 +0200862 foreach my $pagerevid (@{$revision_ids}) {
Matthieu Moyebd5fe12012-07-16 21:46:42 +0200863 # Count page even if we skip it, since we display
864 # $n/$total and $total includes skipped pages.
865 $n++;
866
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200867 # fetch the content of the pages
868 my $query = {
869 action => 'query',
870 prop => 'revisions',
871 rvprop => 'content|timestamp|comment|user|ids',
Matthieu Moy4465b6d2012-07-06 12:03:12 +0200872 revids => $pagerevid,
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200873 };
874
875 my $result = $mediawiki->api($query);
876
Matthieu Moyff0bfd72012-07-06 12:03:15 +0200877 if (!$result) {
Célestin Matte8a43b362013-06-14 15:50:21 +0200878 die "Failed to retrieve modified page for revision $pagerevid\n";
Matthieu Moyff0bfd72012-07-06 12:03:15 +0200879 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200880
Matthieu Moyebd5fe12012-07-16 21:46:42 +0200881 if (defined($result->{query}->{badrevids}->{$pagerevid})) {
882 # The revision id does not exist on the remote wiki.
883 next;
884 }
885
Matthieu Moyff0bfd72012-07-06 12:03:15 +0200886 if (!defined($result->{query}->{pages})) {
Célestin Matte86e95ef2013-06-14 15:50:30 +0200887 die "Invalid revision ${pagerevid}.\n";
Matthieu Moyff0bfd72012-07-06 12:03:15 +0200888 }
889
Matthieu Moy4465b6d2012-07-06 12:03:12 +0200890 my @result_pages = values(%{$result->{query}->{pages}});
891 my $result_page = $result_pages[0];
892 my $rev = $result_pages[0]->{revisions}->[0];
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200893
Matthieu Moy4465b6d2012-07-06 12:03:12 +0200894 my $page_title = $result_page->{title};
Matthieu Moy5a292172012-07-06 12:03:14 +0200895
896 if (!exists($pages->{$page_title})) {
Célestin Matted49a0382013-06-14 15:50:36 +0200897 print {*STDERR} "${n}/", scalar(@{$revision_ids}),
Célestin Matte86e95ef2013-06-14 15:50:30 +0200898 ": Skipping revision #$rev->{revid} of ${page_title}\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200899 next;
900 }
901
902 $n_actual++;
903
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200904 my %commit;
905 $commit{author} = $rev->{user} || 'Anonymous';
Matthieu Moydcb1ea62012-07-16 14:00:47 +0200906 $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
Benoit Person192f7a02013-07-04 22:38:58 +0200907 $commit{title} = smudge_filename($page_title);
Matthieu Moy4465b6d2012-07-06 12:03:12 +0200908 $commit{mw_revision} = $rev->{revid};
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200909 $commit{content} = mediawiki_smudge($rev->{'*'});
910
911 if (!defined($rev->{timestamp})) {
912 $last_timestamp++;
913 } else {
914 $last_timestamp = $rev->{timestamp};
915 }
916 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
917
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200918 # Differentiates classic pages and media files.
Matthieu Moy6df7e0d2012-07-04 14:53:36 +0200919 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200920 my %mediafile;
Matthieu Moy22724002012-07-17 16:06:00 +0200921 if ($namespace) {
922 my $id = get_mw_namespace_id($namespace);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200923 if ($id && $id == get_mw_namespace_id('File')) {
Matthieu Moy22724002012-07-17 16:06:00 +0200924 %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
925 }
Pavel Volek6a9e55b2012-06-27 16:21:29 +0200926 }
927 # If this is a revision of the media page for new version
928 # of a file do one common commit for both file and media page.
929 # Else do commit only for that page.
Célestin Matted49a0382013-06-14 15:50:36 +0200930 print {*STDERR} "${n}/", scalar(@{$revision_ids}), ": Revision #$rev->{revid} of $commit{title}\n";
Matthieu Moy5a292172012-07-06 12:03:14 +0200931 import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200932 }
933
Matthieu Moy5a292172012-07-06 12:03:14 +0200934 return $n_actual;
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200935}
936
937sub error_non_fast_forward {
Célestin Matte86e95ef2013-06-14 15:50:30 +0200938 my $advice = run_git('config --bool advice.pushNonFastForward');
Matthieu Moyfd47d7b2011-09-27 19:55:00 +0200939 chomp($advice);
Célestin Matte86e95ef2013-06-14 15:50:30 +0200940 if ($advice ne 'false') {
Matthieu Moyfd47d7b2011-09-27 19:55:00 +0200941 # Native git-push would show this after the summary.
942 # We can't ask it to display it cleanly, so print it
943 # ourselves before.
Célestin Mattee83d36b2013-06-14 15:50:31 +0200944 print {*STDERR} "To prevent you from losing history, non-fast-forward updates were rejected\n";
945 print {*STDERR} "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
946 print {*STDERR} "'Note about fast-forwards' section of 'git push --help' for details.\n";
Matthieu Moyfd47d7b2011-09-27 19:55:00 +0200947 }
Célestin Mattee83d36b2013-06-14 15:50:31 +0200948 print {*STDOUT} qq(error $_[0] "non-fast-forward"\n);
Jeremie Nikaes428c9952011-09-01 18:54:55 +0200949 return 0;
950}
951
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200952sub mw_upload_file {
953 my $complete_file_name = shift;
954 my $new_sha1 = shift;
955 my $extension = shift;
956 my $file_deleted = shift;
957 my $summary = shift;
958 my $newrevid;
Célestin Matte86e95ef2013-06-14 15:50:30 +0200959 my $path = "File:${complete_file_name}";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200960 my %hashFiles = get_allowed_file_extensions();
961 if (!exists($hashFiles{$extension})) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200962 print {*STDERR} "${complete_file_name} is not a permitted file on this wiki.\n";
963 print {*STDERR} "Check the configuration of file uploads in your mediawiki.\n";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200964 return $newrevid;
965 }
966 # Deleting and uploading a file requires a priviledged user
967 if ($file_deleted) {
Benoit Person192f7a02013-07-04 22:38:58 +0200968 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200969 my $query = {
970 action => 'delete',
971 title => $path,
972 reason => $summary
973 };
974 if (!$mediawiki->edit($query)) {
Célestin Mattee83d36b2013-06-14 15:50:31 +0200975 print {*STDERR} "Failed to delete file on remote wiki\n";
976 print {*STDERR} "Check your permissions on the remote site. Error code:\n";
977 print {*STDERR} $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200978 exit 1;
979 }
980 } else {
981 # Don't let perl try to interpret file content as UTF-8 => use "raw"
Célestin Matte86e95ef2013-06-14 15:50:30 +0200982 my $content = run_git("cat-file blob ${new_sha1}", 'raw');
Célestin Matteaeb95ee2013-06-14 15:50:33 +0200983 if ($content ne EMPTY) {
Benoit Person192f7a02013-07-04 22:38:58 +0200984 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200985 $mediawiki->{config}->{upload_url} =
Célestin Matte86e95ef2013-06-14 15:50:30 +0200986 "${url}/index.php/Special:Upload";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200987 $mediawiki->edit({
988 action => 'upload',
989 filename => $complete_file_name,
990 comment => $summary,
991 file => [undef,
992 $complete_file_name,
993 Content => $content],
994 ignorewarnings => 1,
995 }, {
996 skip_encoding => 1
997 } ) || die $mediawiki->{error}->{code} . ':'
Célestin Matte8a43b362013-06-14 15:50:21 +0200998 . $mediawiki->{error}->{details} . "\n";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +0200999 my $last_file_page = $mediawiki->get_page({title => $path});
1000 $newrevid = $last_file_page->{revid};
Célestin Mattee83d36b2013-06-14 15:50:31 +02001001 print {*STDERR} "Pushed file: ${new_sha1} - ${complete_file_name}.\n";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001002 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001003 print {*STDERR} "Empty file ${complete_file_name} not pushed.\n";
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001004 }
1005 }
1006 return $newrevid;
1007}
1008
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001009sub mw_push_file {
1010 my $diff_info = shift;
1011 # $diff_info contains a string in this format:
1012 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1013 my @diff_info_split = split(/[ \t]/, $diff_info);
1014
1015 # Filename, including .mw extension
1016 my $complete_file_name = shift;
1017 # Commit message
1018 my $summary = shift;
Matthieu Moy93f0d332011-09-01 18:54:56 +02001019 # MediaWiki revision number. Keep the previous one by default,
1020 # in case there's no edit to perform.
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001021 my $oldrevid = shift;
1022 my $newrevid;
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001023
Matthieu Moydcb1ea62012-07-16 14:00:47 +02001024 if ($summary eq EMPTY_MESSAGE) {
Célestin Matteaeb95ee2013-06-14 15:50:33 +02001025 $summary = EMPTY;
Matthieu Moydcb1ea62012-07-16 14:00:47 +02001026 }
1027
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001028 my $new_sha1 = $diff_info_split[3];
1029 my $old_sha1 = $diff_info_split[2];
1030 my $page_created = ($old_sha1 eq NULL_SHA1);
1031 my $page_deleted = ($new_sha1 eq NULL_SHA1);
Benoit Person192f7a02013-07-04 22:38:58 +02001032 $complete_file_name = clean_filename($complete_file_name);
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001033
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001034 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1035 if (!defined($extension)) {
Célestin Matteaeb95ee2013-06-14 15:50:33 +02001036 $extension = EMPTY;
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001037 }
Célestin Matte86e95ef2013-06-14 15:50:30 +02001038 if ($extension eq 'mw') {
Matthieu Moy2045e292012-07-16 21:46:37 +02001039 my $ns = get_mw_namespace_id_for_page($complete_file_name);
Célestin Matte86e95ef2013-06-14 15:50:30 +02001040 if ($ns && $ns == get_mw_namespace_id('File') && (!$export_media)) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001041 print {*STDERR} "Ignoring media file related page: ${complete_file_name}\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +02001042 return ($oldrevid, 'ok');
Matthieu Moy2045e292012-07-16 21:46:37 +02001043 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001044 my $file_content;
1045 if ($page_deleted) {
1046 # Deleting a page usually requires
Stefano Lattarini2582ab12013-04-12 00:36:10 +02001047 # special privileges. A common
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001048 # convention is to replace the page
1049 # with this content instead:
1050 $file_content = DELETED_CONTENT;
1051 } else {
Célestin Matte86e95ef2013-06-14 15:50:30 +02001052 $file_content = run_git("cat-file blob ${new_sha1}");
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001053 }
1054
Benoit Person192f7a02013-07-04 22:38:58 +02001055 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001056
1057 my $result = $mediawiki->edit( {
1058 action => 'edit',
1059 summary => $summary,
1060 title => $title,
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001061 basetimestamp => $basetimestamps{$oldrevid},
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001062 text => mediawiki_clean($file_content, $page_created),
1063 }, {
1064 skip_encoding => 1 # Helps with names with accentuated characters
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001065 });
1066 if (!$result) {
1067 if ($mediawiki->{error}->{code} == 3) {
1068 # edit conflicts, considered as non-fast-forward
Célestin Mattee83d36b2013-06-14 15:50:31 +02001069 print {*STDERR} 'Warning: Error ' .
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001070 $mediawiki->{error}->{code} .
Célestin Matte7c475832013-06-14 15:50:35 +02001071 ' from mediawiki: ' . $mediawiki->{error}->{details} .
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001072 ".\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +02001073 return ($oldrevid, 'non-fast-forward');
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001074 } else {
1075 # Other errors. Shouldn't happen => just die()
1076 die 'Fatal: Error ' .
1077 $mediawiki->{error}->{code} .
Célestin Matte7c475832013-06-14 15:50:35 +02001078 ' from mediawiki: ' . $mediawiki->{error}->{details} . "\n";
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001079 }
1080 }
Matthieu Moy93f0d332011-09-01 18:54:56 +02001081 $newrevid = $result->{edit}->{newrevid};
Célestin Mattee83d36b2013-06-14 15:50:31 +02001082 print {*STDERR} "Pushed file: ${new_sha1} - ${title}\n";
Matthieu Moy2045e292012-07-16 21:46:37 +02001083 } elsif ($export_media) {
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001084 $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1085 $extension, $page_deleted,
1086 $summary);
Matthieu Moy2045e292012-07-16 21:46:37 +02001087 } else {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001088 print {*STDERR} "Ignoring media file ${title}\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001089 }
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001090 $newrevid = ($newrevid or $oldrevid);
Célestin Matte86e95ef2013-06-14 15:50:30 +02001091 return ($newrevid, 'ok');
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001092}
1093
1094sub mw_push {
1095 # multiple push statements can follow each other
Célestin Matte86e95ef2013-06-14 15:50:30 +02001096 my @refsspecs = (shift, get_more_refs('push'));
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001097 my $pushed;
1098 for my $refspec (@refsspecs) {
1099 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
Célestin Matte8a43b362013-06-14 15:50:21 +02001100 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001101 if ($force) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001102 print {*STDERR} "Warning: forced push not allowed on a MediaWiki.\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001103 }
Célestin Matteaeb95ee2013-06-14 15:50:33 +02001104 if ($local eq EMPTY) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001105 print {*STDERR} "Cannot delete remote branch on a MediaWiki\n";
1106 print {*STDOUT} "error ${remote} cannot delete\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001107 next;
1108 }
Célestin Matte86e95ef2013-06-14 15:50:30 +02001109 if ($remote ne 'refs/heads/master') {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001110 print {*STDERR} "Only push to the branch 'master' is supported on a MediaWiki\n";
1111 print {*STDOUT} "error ${remote} only master allowed\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001112 next;
1113 }
1114 if (mw_push_revision($local, $remote)) {
1115 $pushed = 1;
1116 }
1117 }
1118
1119 # Notify Git that the push is done
Célestin Mattee83d36b2013-06-14 15:50:31 +02001120 print {*STDOUT} "\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001121
Matthieu Moy93f0d332011-09-01 18:54:56 +02001122 if ($pushed && $dumb_push) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001123 print {*STDERR} "Just pushed some revisions to MediaWiki.\n";
1124 print {*STDERR} "The pushed revisions now have to be re-imported, and your current branch\n";
1125 print {*STDERR} "needs to be updated with these re-imported commits. You can do this with\n";
1126 print {*STDERR} "\n";
1127 print {*STDERR} " git pull --rebase\n";
1128 print {*STDERR} "\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001129 }
Célestin Matte1aff8c62013-06-14 15:50:12 +02001130 return;
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001131}
1132
1133sub mw_push_revision {
1134 my $local = shift;
1135 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1136 my $last_local_revid = get_last_local_revision();
Célestin Mattee83d36b2013-06-14 15:50:31 +02001137 print {*STDERR} ".\n"; # Finish sentence started by get_last_local_revision()
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001138 my $last_remote_revid = get_last_remote_revision();
Matthieu Moy93f0d332011-09-01 18:54:56 +02001139 my $mw_revision = $last_remote_revid;
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001140
1141 # Get sha1 of commit pointed by local HEAD
Célestin Matte86e95ef2013-06-14 15:50:30 +02001142 my $HEAD_sha1 = run_git("rev-parse ${local} 2>/dev/null");
1143 chomp($HEAD_sha1);
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001144 # Get sha1 of commit pointed by remotes/$remotename/master
Célestin Matte86e95ef2013-06-14 15:50:30 +02001145 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/${remotename}/master 2>/dev/null");
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001146 chomp($remoteorigin_sha1);
1147
1148 if ($last_local_revid > 0 &&
1149 $last_local_revid < $last_remote_revid) {
1150 return error_non_fast_forward($remote);
1151 }
1152
1153 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1154 # nothing to push
1155 return 0;
1156 }
1157
1158 # Get every commit in between HEAD and refs/remotes/origin/master,
1159 # including HEAD and refs/remotes/origin/master
1160 my @commit_pairs = ();
1161 if ($last_local_revid > 0) {
1162 my $parsed_sha1 = $remoteorigin_sha1;
1163 # Find a path from last MediaWiki commit to pushed commit
Célestin Mattee83d36b2013-06-14 15:50:31 +02001164 print {*STDERR} "Computing path from local to remote ...\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +02001165 my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents ${local} ^${parsed_sha1}"));
Matthieu Moy93e92d42012-07-16 21:46:38 +02001166 my %local_ancestry;
1167 foreach my $line (@local_ancestry) {
Célestin Matteeb96b752013-06-14 15:50:16 +02001168 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
Célestin Matte11499572013-06-14 15:50:17 +02001169 foreach my $parent (split(/ /, $parents)) {
Matthieu Moy93e92d42012-07-16 21:46:38 +02001170 $local_ancestry{$parent} = $child;
1171 }
Célestin Matteeb96b752013-06-14 15:50:16 +02001172 } elsif (!$line =~ /^([a-f0-9]+)/) {
Célestin Matte86e95ef2013-06-14 15:50:30 +02001173 die "Unexpected output from git rev-list: ${line}\n";
Matthieu Moy93e92d42012-07-16 21:46:38 +02001174 }
1175 }
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001176 while ($parsed_sha1 ne $HEAD_sha1) {
Matthieu Moy93e92d42012-07-16 21:46:38 +02001177 my $child = $local_ancestry{$parsed_sha1};
1178 if (!$child) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001179 print {*STDERR} "Cannot find a path in history from remote commit to last commit\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001180 return error_non_fast_forward($remote);
1181 }
Matthieu Moy93e92d42012-07-16 21:46:38 +02001182 push(@commit_pairs, [$parsed_sha1, $child]);
1183 $parsed_sha1 = $child;
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001184 }
1185 } else {
1186 # No remote mediawiki revision. Export the whole
1187 # history (linearized with --first-parent)
Célestin Mattee83d36b2013-06-14 15:50:31 +02001188 print {*STDERR} "Warning: no common ancestor, pushing complete history\n";
Célestin Matte86e95ef2013-06-14 15:50:30 +02001189 my $history = run_git("rev-list --first-parent --children ${local}");
Célestin Matte05d4c7b2013-06-14 15:50:09 +02001190 my @history = split(/\n/, $history);
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001191 @history = @history[1..$#history];
1192 foreach my $line (reverse @history) {
Célestin Matte6b825a42013-06-14 15:50:19 +02001193 my @commit_info_split = split(/[ \n]/, $line);
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001194 push(@commit_pairs, \@commit_info_split);
1195 }
1196 }
1197
1198 foreach my $commit_info_split (@commit_pairs) {
1199 my $sha1_child = @{$commit_info_split}[0];
1200 my $sha1_commit = @{$commit_info_split}[1];
Célestin Matte86e95ef2013-06-14 15:50:30 +02001201 my $diff_infos = run_git("diff-tree -r --raw -z ${sha1_child} ${sha1_commit}");
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001202 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1203 # TODO: for now, it's just a delete+add
1204 my @diff_info_list = split(/\0/, $diff_infos);
Matthieu Moy28c24bd2012-06-27 11:10:16 +02001205 # Keep the subject line of the commit message as mediawiki comment for the revision
Célestin Matte86e95ef2013-06-14 15:50:30 +02001206 my $commit_msg = run_git(qq(log --no-walk --format="%s" ${sha1_commit}));
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001207 chomp($commit_msg);
1208 # Push every blob
1209 while (@diff_info_list) {
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001210 my $status;
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001211 # git diff-tree -z gives an output like
1212 # <metadata>\0<filename1>\0
1213 # <metadata>\0<filename2>\0
1214 # and we've split on \0.
1215 my $info = shift(@diff_info_list);
1216 my $file = shift(@diff_info_list);
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001217 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
Célestin Matte86e95ef2013-06-14 15:50:30 +02001218 if ($status eq 'non-fast-forward') {
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001219 # we may already have sent part of the
1220 # commit to MediaWiki, but it's too
1221 # late to cancel it. Stop the push in
1222 # the middle, but still give an
1223 # accurate error message.
1224 return error_non_fast_forward($remote);
1225 }
Célestin Matte86e95ef2013-06-14 15:50:30 +02001226 if ($status ne 'ok') {
Célestin Matte8a43b362013-06-14 15:50:21 +02001227 die("Unknown error from mw_push_file()\n");
Matthieu Moy3c1ed902011-09-27 19:54:59 +02001228 }
Matthieu Moy93f0d332011-09-01 18:54:56 +02001229 }
Célestin Matteb8b4e1b2013-06-14 15:50:32 +02001230 if (!$dumb_push) {
Célestin Matte86e95ef2013-06-14 15:50:30 +02001231 run_git(qq(notes --ref=${remotename}/mediawiki add -f -m "mediawiki_revision: ${mw_revision}" ${sha1_commit}));
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001232 }
1233 }
1234
Célestin Mattee83d36b2013-06-14 15:50:31 +02001235 print {*STDOUT} "ok ${remote}\n";
Jeremie Nikaes428c9952011-09-01 18:54:55 +02001236 return 1;
1237}
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001238
1239sub get_allowed_file_extensions {
Benoit Person192f7a02013-07-04 22:38:58 +02001240 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001241
1242 my $query = {
1243 action => 'query',
1244 meta => 'siteinfo',
1245 siprop => 'fileextensions'
1246 };
1247 my $result = $mediawiki->api($query);
Célestin Matte81f6a7a2013-06-14 15:50:14 +02001248 my @file_extensions = map { $_->{ext}} @{$result->{query}->{fileextensions}};
1249 my %hashFile = map { $_ => 1 } @file_extensions;
NGUYEN Kim Thuatb3d98592012-06-27 11:10:18 +02001250
1251 return %hashFile;
1252}
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001253
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001254# In memory cache for MediaWiki namespace ids.
1255my %namespace_id;
1256
1257# Namespaces whose id is cached in the configuration file
1258# (to avoid duplicates)
1259my %cached_mw_namespace_id;
1260
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001261# Return MediaWiki id for a canonical namespace name.
1262# Ex.: "File", "Project".
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001263sub get_mw_namespace_id {
Benoit Person192f7a02013-07-04 22:38:58 +02001264 $mediawiki = connect_maybe($mediawiki, $remotename, $url);
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001265 my $name = shift;
1266
1267 if (!exists $namespace_id{$name}) {
1268 # Look at configuration file, if the record for that namespace is
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001269 # already cached. Namespaces are stored in form:
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001270 # "Name_of_namespace:Id_namespace", ex.: "File:6".
Célestin Matte86e95ef2013-06-14 15:50:30 +02001271 my @temp = split(/\n/,
1272 run_git("config --get-all remote.${remotename}.namespaceCache"));
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001273 chomp(@temp);
1274 foreach my $ns (@temp) {
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001275 my ($n, $id) = split(/:/, $ns);
Matthieu Moy22724002012-07-17 16:06:00 +02001276 if ($id eq 'notANameSpace') {
1277 $namespace_id{$n} = {is_namespace => 0};
1278 } else {
1279 $namespace_id{$n} = {is_namespace => 1, id => $id};
1280 }
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001281 $cached_mw_namespace_id{$n} = 1;
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001282 }
1283 }
1284
1285 if (!exists $namespace_id{$name}) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001286 print {*STDERR} "Namespace ${name} not found in cache, querying the wiki ...\n";
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001287 # NS not found => get namespace id from MW and store it in
1288 # configuration file.
1289 my $query = {
1290 action => 'query',
1291 meta => 'siteinfo',
1292 siprop => 'namespaces'
1293 };
1294 my $result = $mediawiki->api($query);
1295
1296 while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001297 if (defined($ns->{id}) && defined($ns->{canonical})) {
Matthieu Moy22724002012-07-17 16:06:00 +02001298 $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001299 if ($ns->{'*'}) {
1300 # alias (e.g. french Fichier: as alias for canonical File:)
Matthieu Moy22724002012-07-17 16:06:00 +02001301 $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001302 }
1303 }
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001304 }
1305 }
1306
Matthieu Moy22724002012-07-17 16:06:00 +02001307 my $ns = $namespace_id{$name};
1308 my $id;
Matthieu Moy6df7e0d2012-07-04 14:53:36 +02001309
Célestin Matteb8b4e1b2013-06-14 15:50:32 +02001310 if (!defined $ns) {
Célestin Mattee83d36b2013-06-14 15:50:31 +02001311 print {*STDERR} "No such namespace ${name} on MediaWiki.\n";
Matthieu Moy22724002012-07-17 16:06:00 +02001312 $ns = {is_namespace => 0};
1313 $namespace_id{$name} = $ns;
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001314 }
Matthieu Moy22724002012-07-17 16:06:00 +02001315
1316 if ($ns->{is_namespace}) {
1317 $id = $ns->{id};
1318 }
1319
1320 # Store "notANameSpace" as special value for inexisting namespaces
1321 my $store_id = ($id || 'notANameSpace');
1322
Masanari Iida68840cb2013-11-13 00:17:45 +09001323 # Store explicitly requested namespaces on disk
Matthieu Moy22724002012-07-17 16:06:00 +02001324 if (!exists $cached_mw_namespace_id{$name}) {
Célestin Matte86e95ef2013-06-14 15:50:30 +02001325 run_git(qq(config --add remote.${remotename}.namespaceCache "${name}:${store_id}"));
Matthieu Moy22724002012-07-17 16:06:00 +02001326 $cached_mw_namespace_id{$name} = 1;
1327 }
1328 return $id;
Pavel Volek6a9e55b2012-06-27 16:21:29 +02001329}
Matthieu Moy2045e292012-07-16 21:46:37 +02001330
1331sub get_mw_namespace_id_for_page {
Célestin Matte6c2fbe22013-06-14 15:50:15 +02001332 my $namespace = shift;
1333 if ($namespace =~ /^([^:]*):/) {
Matthieu Moy2045e292012-07-16 21:46:37 +02001334 return get_mw_namespace_id($namespace);
1335 } else {
1336 return;
1337 }
1338}